<ng-container *transloco="let t; prefix:'import-cbl-modal'">
  <div class="modal-header">
    <h4 class="modal-title">
      {{t('title')}}
      @if (savedFiles().length > 1) {
        <span class="badge bg-secondary ms-2">
          {{t('file-counter', {current: currentFileIndex() + 1, total: savedFiles().length})}}
        </span>
      }
    </h4>
    <button type="button" class="btn-close" [attr.aria-label]="t('close')" (click)="dismiss()"></button>
  </div>

  <!--cdkScrollable is to ensure when we scroll the modal, the typeahead option keeps up-->
  <div class="modal-body" cdkScrollable>
    @if (isProcessing()) {
      <div class="text-center py-4">
        <app-loading [loading]="true" />
        <p class="mt-2 text-muted">{{t('processing')}}</p>
      </div>
    } @else if (currentSummary(); as summary) {
      <p>{{t('description')}} <a [href]="WikiLink.CblImportModal" rel="noopener noreferrer">{{t('wiki')}}</a></p>
      <!-- File name -->
      <h5 class="mb-3">
        {{summary.cblName || currentFile().name}}
        @if (summary.isUpdate) {
          <span class="badge bg-info ms-2">{{t('update-list')}}</span>
        } @else {
          <span class="badge bg-success ms-2">{{t('new-list')}}</span>
        }
      </h5>

      <!-- Summary bar -->
      <div class="d-flex gap-3 mb-3 align-items-center">
        <div class="btn-group" role="group">
          <input type="checkbox" class="btn-check" id="matched-btn" autocomplete="off" [checked]="showMatched()" (change)="toggleRowFilter('matched')">
          <label class="btn btn-outline-success" for="matched-btn">{{t('matched-count', {count: matchedCount()})}}</label>

          <input type="checkbox" class="btn-check" id="warnings-btn" autocomplete="off" [checked]="showIssues()" (change)="toggleRowFilter('issues')">
          <label class="btn btn-outline-warning" for="warnings-btn">{{t('issues-count', {count: issueCount()})}}</label>

          <input type="checkbox" class="btn-check" id="errors-btn" autocomplete="off" [checked]="showUnmatched()" (change)="toggleRowFilter('unmatched')">
          <label class="btn btn-outline-danger" for="errors-btn">{{t('unmatched-count', {count: unmatchedCount()})}}</label>
        </div>

        <button class="btn btn-sm btn-outline-secondary" (click)="validateCurrentFile()">
          <i class="fa fa-refresh me-1" aria-hidden="true"></i>
          {{t('refresh')}}
        </button>
      </div>

      <div class="table-wrapper">
        <ngx-datatable
          class="bootstrap"
          [rows]="visibleRows()"
          [columnMode]="'force'"
          rowHeight="auto"
          [footerHeight]="0"
          [scrollbarH]="false"
          [rowClass]="getRowClass">

          <!-- Order -->
          <ngx-datatable-column [width]="20" [sortable]="false" [draggable]="false" [resizeable]="false">
            <ng-template ngx-datatable-header-template>#</ng-template>
            <ng-template let-row="row" ngx-datatable-cell-template>
              @if (row.result.reason === CblImportReason.Success) {
                <i class="fa fa-check-circle text-success" aria-hidden="true"></i>
              } @else if (row.skipped) {
                <i class="fa fa-ban text-muted" aria-hidden="true"></i>
              } @else {
                <i class="fa fa-exclamation-circle text-warning" aria-hidden="true"></i>
              }
              <span class="ms-2">{{row.result.order + 1}}</span>
            </ng-template>
          </ngx-datatable-column>

          <!-- Requested Series -->
          <ngx-datatable-column [sortable]="false" [draggable]="false" [resizeable]="false">
            <ng-template ngx-datatable-header-template>{{t('col-series')}}</ng-template>
            <ng-template let-row="row" ngx-datatable-cell-template>
              {{row.result.series}}
            </ng-template>
          </ngx-datatable-column>

          <!-- Requested Vol / Issue -->
          <ngx-datatable-column [width]="100" [sortable]="false" [draggable]="false" [resizeable]="false">
            <ng-template ngx-datatable-header-template>{{t('col-vol-issue')}}</ng-template>
            <ng-template let-row="row" ngx-datatable-cell-template>
              @if (row.result.volume) {
                <span>{{t('volume-num', {num: row.result.volume})}}</span>
              }
              @if (row.result.number) {
                <span class="ms-1">{{t('issue-num', {num: row.result.number})}}</span>
              }
            </ng-template>
          </ngx-datatable-column>

          <!-- Status / Reason -->
          <ngx-datatable-column [width]="100" [sortable]="false" [draggable]="false" [resizeable]="false">
            <ng-template ngx-datatable-header-template>{{t('col-status')}}</ng-template>
            <ng-template let-row="row" ngx-datatable-cell-template>
              @if (row.result.reason === CblImportReason.Success && row.result.matchTier === CblMatchTier.RemapRule) {
                <span class="badge tier-badge text-bg-{{getMatchBadgeClass(row.result.matchTier)}}" [ngbTooltip]="getRemapRuleTooltip(row)" container="body">
                  {{row.result.matchTier | cblMatchTier}}
                </span>
              } @else if (row.result.reason === CblImportReason.Success) {
                <span class="badge tier-badge text-bg-{{getMatchBadgeClass(row.result.matchTier)}}" >
                  {{row.result.matchTier | cblMatchTier}}
                </span>
              } @else {
                <span class="badge bg-danger">{{row.result.reason | cblImportReason}}</span>
              }
            </ng-template>
          </ngx-datatable-column>

          <!-- Matched Series -->
          <ngx-datatable-column [width]="200" [sortable]="false" [draggable]="false" [resizeable]="false">
            <ng-template ngx-datatable-header-template>{{t('col-matched-series')}}</ng-template>
            <ng-template let-row="row" ngx-datatable-cell-template>

              <!-- Inline series typeahead when this is the active editing row -->
              @if (isEditingSeries(row)) {
                <div class="d-flex align-items-center gap-1">
                  <div class="flex-grow-1">
                    <app-typeahead [settings]="activeSeriesTypeahead()!"
                                   (selectedData)="onSeriesTypeaheadSelected(row, $event)">
                      <ng-template #badgeItem let-item>
                        {{item.name}} ({{libraryNames()[item.libraryId]}})
                      </ng-template>
                      <ng-template #optionItem let-item let-value="value">
                        <div class="d-flex align-items-center gap-2">
                          <app-image [imageUrl]="imageService.getSeriesCoverImage(item.seriesId)"
                                     height="40px" width="30px" />
                          <div>
                            <div>
                              @if (item.name.toLowerCase().trim().indexOf(value.toLowerCase().trim()) >= 0) {
                                {{item.name}}
                              } @else {
                                {{item.localizedName}}
                              }
                            </div>
                            <small class="text-muted">
                              {{item.libraryName}}
                              @if (item.releaseYear && item.releaseYear > 0) { &middot; {{item.releaseYear}} }
                              @if (item.chapterCount) { &middot; {{item.chapterCount}} issues }
                            </small>
                          </div>
                        </div>
                      </ng-template>
                    </app-typeahead>
                  </div>
                  <button class="btn btn-sm btn-outline-secondary" (click)="cancelResolve()"
                          [attr.aria-label]="t('cancel')">
                    <i class="fa fa-times" aria-hidden="true"></i>
                  </button>
                </div>
              } @else {
                <!-- Read-only display: series name as link + pencil edit -->
                @if (row.result.matchedSeriesName) {
                  <a [routerLink]="['/library', row.result.libraryId, 'series', row.result.seriesId]"
                     target="_blank">
                    {{row.result.matchedSeriesName}}
                  </a>
                  <button class="btn btn-sm btn-link p-0 ms-1" (click)="startResolveSeries(row)"
                          [attr.aria-label]="t('edit-match')">
                    <i class="fa fa-pencil" aria-hidden="true"></i>
                  </button>
                }

                <!-- Series collision with candidates (not actively editing) -->
                @if (isSeriesCollision(row) && row.result.candidates?.length > 0 && activeRow() !== row) {
                  <select class="form-select form-select-sm"
                          (change)="onCandidateSelected(row, row.result.candidates[$any($event.target).selectedIndex - 1])">
                    <option selected disabled>{{t('pick-candidate')}}</option>
                    @for (candidate of row.result.candidates; track candidate.seriesId) {
                      <option [value]="candidate.seriesId">{{candidate.seriesName}}</option>
                    }
                  </select>
                }
              }
            </ng-template>
          </ngx-datatable-column>

          <!-- Matched Issue -->
          <ngx-datatable-column [width]="100" [sortable]="false" [draggable]="false" [resizeable]="false">
            <ng-template ngx-datatable-header-template>{{t('col-matched-issue')}}</ng-template>
            <ng-template let-row="row" ngx-datatable-cell-template>

              <!-- Inline chapter typeahead when this is the active editing row -->
              @if (isEditingChapter(row)) {
                <div class="d-flex align-items-center gap-1">
                  <div class="flex-grow-1">
                    <app-typeahead [settings]="activeChapterTypeahead()!"
                                   (selectedData)="onChapterTypeaheadSelected(row, $event)">
                      <ng-template #badgeItem let-item let-position="idx">
                        {{item.title}}
                      </ng-template>
                      <ng-template #optionItem let-item let-position="idx">
                        <div class="d-flex align-items-center gap-2">
                          <app-image [imageUrl]="item.coverImage" height="40px" width="30px" />
                          <div>
                            <div>{{item.title}}</div>
                            @if (item.volumeTitle) {
                              <small class="text-muted">{{item.volumeTitle}}</small>
                            }
                          </div>
                        </div>
                      </ng-template>
                    </app-typeahead>
                  </div>
                  <button class="btn btn-sm btn-outline-secondary" (click)="cancelResolve()"
                          [attr.aria-label]="t('cancel')">
                    <i class="fa fa-times" aria-hidden="true"></i>
                  </button>
                </div>
              } @else if (row.result.chapterId > 0) {
                <a [routerLink]="['/library', row.result.libraryId, 'series', row.result.seriesId, 'chapter', row.result.chapterId]"
                   fragment="details-tab"
                   target="_blank">
                  <app-entity-title [libraryType]="row.result.libraryType"
                                    [prioritizeTitleName]="false"
                                    [includeChapter]="true"
                                    [includeVolume]="true"
                                    [entity]="buildChapterStub(row.result)" />
                </a>
                <button class="btn btn-sm btn-link p-0 ms-1" (click)="startResolveChapter(row)"
                        [attr.aria-label]="t('edit-match')">
                  <i class="fa fa-pencil" aria-hidden="true"></i>
                </button>
              }
            </ng-template>
          </ngx-datatable-column>

          <!-- Action Column -->
          <ngx-datatable-column [width]="60" [sortable]="false" [draggable]="false" [resizeable]="false">
            <ng-template ngx-datatable-header-template>{{t('col-action')}}</ng-template>
            <ng-template let-row="row" ngx-datatable-cell-template>
              @if (row.result.reason !== CblImportReason.Success) {
                <div class="d-flex align-items-center gap-1">
                  @if (!row.skipped && activeRow() !== row) {
                    <button class="btn btn-sm btn-outline-primary" (click)="startResolve(row)"
                            [attr.aria-label]="t('resolve')">
                      <i class="fa fa-pencil" aria-hidden="true"></i>
                    </button>
                  }
                  <button class="btn btn-sm btn-outline-secondary" (click)="toggleSkip(row)"
                          [attr.aria-label]="t('skip-item')" [ngbTooltip]="t('skip-item')">
                    @if (row.skipped) {
                      <i class="fa fa-undo" aria-hidden="true"></i>
                    } @else {
                      <i class="fa fa-ban" aria-hidden="true"></i>
                    }
                  </button>
                </div>
              }
            </ng-template>
          </ngx-datatable-column>
        </ngx-datatable>
      </div>
    }
  </div>

  <div class="modal-footer d-flex justify-content-between">
    <button class="btn btn-sm btn-outline-secondary" (click)="openRemapRulesModal()">
      <i class="fa fa-cog me-1" aria-hidden="true"></i>
      {{t('manage-rules')}} ({{remapRules().length}})
    </button>

    <div>
      @if (savedFiles().length > 1) {
        <button class="btn btn-secondary me-2" [disabled]="currentFileIndex() === 0 || isProcessing()"
                (click)="previousFile()">
          {{t('previous-file')}}
        </button>
        <button class="btn btn-secondary" [disabled]="currentFileIndex() >= savedFiles().length - 1 || isProcessing()"
                (click)="nextFile()">
          {{t('next-file')}}
        </button>
      }
    </div>
    <div class="d-flex align-items-center gap-2">
      @if (currentSummary()) {
        <span class="d-inline-flex align-items-center gap-1"
              [ngbTooltip]="t('promote-tooltip')" container="body">
          <input class="form-check-input mt-0" type="checkbox"
                 id="promote-checkbox"
                 [checked]="getPromoteForFile(currentFile().fileName)"
                 [disabled]="isCurrentFileUpdate()"
                 (change)="togglePromote(currentFile().fileName)">
          <label class="form-check-label" for="promote-checkbox">
            {{t('promote')}}
          </label>
        </span>
      }
      <button class="btn btn-secondary" (click)="dismiss()">{{t('close')}}</button>
      <button class="btn btn-primary" [disabled]="isProcessing()" (click)="finalizeAll()">
        @if (savedFiles().length > 1) {
          {{t('finalize')}}
        } @else {
          {{t('finalize-single')}}
        }
      </button>
    </div>
  </div>
</ng-container>
