<ng-container *transloco="let t; prefix: 'book.seriesPage'">
@if (filteredBooks$ | async; as books) {
  <div class="series-wrapper">
    <p-tabs [value]="tab" lazy="true" scrollable>
      <p-tablist>
        <p-tab value="view">
          <i [class]="'pi pi-crown'"></i>
          {{ t('seriesDetailsTab') }}
        </p-tab>
        <p-tab value="list">
          <i [class]="'pi pi-list'"></i>
          {{ t('bookListTab') }}
        </p-tab>
      </p-tablist>
      <p-tabpanels class="tabpanels-responsive">
        <p-tabpanel value="view">

          @if (books[0]; as firstBook) {
            <div class="series-main">
              <div class="series-details">

                <!-- HERO: Cover + Identity info -->
                <div class="series-hero">
                  @if (coverBook$ | async; as coverBook) {
                    <div class="hero-cover-section">
                      <img
                        [src]="getBookThumbnailUrl(coverBook)"
                        class="hero-cover-img"
                        [alt]="coverBook.metadata?.title || ''"
                        loading="lazy"
                        decoding="async"/>
                    </div>
                  }

                  <div class="hero-info">
                    <h2 class="series-title">{{ seriesTitle$ | async }}</h2>

                    @if (allAuthors$ | async; as authors) {
                      <p class="series-authors">
                        @for (author of authors; track $index; let isLast = $last) {
                          <a class="author-link" (click)="goToAuthorBooks(author)">{{ author }}</a>
                          @if (!isLast) {<span>, </span>}
                        }
                      </p>
                    }

                    @if (allCategories$ | async; as categories) {
                      @if (categories.length) {
                        <div class="categories-scroll">
                          <div class="categories-list">
                            @for (category of categories; track category) {
                              <a (click)="goToCategory(category)" class="category-link">
                                <app-tag color="red" size="xs">{{ category }}</app-tag>
                              </a>
                            }
                          </div>
                        </div>
                      }
                    }

                    <div class="metadata-cards">
                      @if (allPublishers$ | async; as publishers) {
                        @if (publishers.length) {
                          <span class="meta-card meta-card--publisher" (click)="goToPublisher(publishers[0])">
                            <i class="pi pi-building"></i>
                            @for (pub of publishers; track pub; let isLast = $last) {
                              {{ pub }}{{ isLast ? '' : ', ' }}
                            }
                          </span>
                        }
                      }
                      <span class="meta-card meta-card--books">
                        <i class="pi pi-book"></i>
                        {{ books.length }} {{ books.length === 1 ? t('book') : t('books') }}
                      </span>
                      @if (yearsRange$ | async; as years) {
                        <span class="meta-card meta-card--years">
                          <i class="pi pi-calendar"></i>
                          {{ years }}
                        </span>
                      }
                      @if (seriesStats$ | async; as stats) {
                        @if (stats.totalPages > 0) {
                          <span class="meta-card meta-card--pages">
                            <i class="pi pi-file"></i>
                            {{ stats.totalPages | number }} {{ t('stats.totalPages') }}
                          </span>
                        }
                        @if (stats.formatCounts.size > 0) {
                          <span class="meta-card meta-card--format">
                            <i class="pi pi-tag"></i>
                            @for (entry of stats.formatCounts | keyvalue; track entry.key) {
                              {{ entry.key }}{{ $last ? '' : ', ' }}
                            }
                          </span>
                        }
                        @if (stats.totalAudioDurationSeconds > 0) {
                          <span class="meta-card meta-card--audio">
                            <i class="pi pi-headphones"></i>
                            {{ formatDuration(stats.totalAudioDurationSeconds) }}
                          </span>
                        }
                      }
                      @if (allLanguages$ | async; as languages) {
                        @if (languages.length) {
                          <span class="meta-card meta-card--language">
                            <i class="pi pi-globe"></i>
                            {{ languages.join(', ') }}
                          </span>
                        }
                      }
                      @if (seriesCompletion$ | async; as completion) {
                        <span class="meta-card meta-card--owned">
                          <i class="pi pi-check-circle"></i>
                          {{ completion.owned }}/{{ completion.total }} {{ t('stats.owned') }}
                        </span>
                      }
                    </div>

                    <!-- Ratings -->
                    @if (seriesStats$ | async; as stats) {
                      @if (stats.avgPersonalRating != null || stats.avgGoodreads != null || stats.avgAmazon != null || stats.avgHardcover != null) {
                        <div class="ratings-row">
                          @if (stats.avgPersonalRating != null) {
                            <div class="rating-chip">
                              <i class="pi pi-star-fill rating-icon personal"></i>
                              <span class="rating-value">{{ stats.avgPersonalRating | number:'1.1-1' }}/10</span>
                              <span class="rating-label">{{ t('stats.avgPersonalRating') }}</span>
                            </div>
                          }
                          @if (stats.avgGoodreads != null) {
                            <div class="rating-chip">
                              <i class="pi pi-star-fill rating-icon goodreads"></i>
                              <span class="rating-value">{{ getRatingPercent(stats.avgGoodreads) }}%</span>
                              <span class="rating-label">{{ t('stats.avgGoodreads') }}</span>
                            </div>
                          }
                          @if (stats.avgAmazon != null) {
                            <div class="rating-chip">
                              <i class="pi pi-star-fill rating-icon amazon"></i>
                              <span class="rating-value">{{ getRatingPercent(stats.avgAmazon) }}%</span>
                              <span class="rating-label">{{ t('stats.avgAmazon') }}</span>
                            </div>
                          }
                          @if (stats.avgHardcover != null) {
                            <div class="rating-chip">
                              <i class="pi pi-star-fill rating-icon hardcover"></i>
                              <span class="rating-value">{{ getRatingPercent(stats.avgHardcover) }}%</span>
                              <span class="rating-label">{{ t('stats.avgHardcover') }}</span>
                            </div>
                          }
                        </div>
                      }
                    }

                    <!-- Next Up + Progress (pushed to bottom, aligned with cover) -->
                    <div class="hero-status">
                      @if (nextUp$ | async; as nextUp) {
                        <div class="next-up-card" (click)="readBook(nextUp.book.id)">
                          <img [src]="nextUp.thumbnailUrl"
                            [alt]="nextUp.book.metadata?.title || ''"
                            class="next-up-thumb"
                            loading="lazy"/>
                          <div class="next-up-info">
                            <span class="next-up-label">
                              <i class="pi pi-bookmark-fill"></i>
                              {{ nextUp.isReading ? t('continueReading') : t('nextUp') }}
                            </span>
                            <span class="next-up-title">{{ nextUp.book.metadata?.title || '' }}</span>
                            @if (nextUp.isReading && nextUp.progressPercent != null) {
                              <div class="next-up-progress-row">
                                <p-progressBar
                                  [value]="nextUp.progressPercent"
                                  [showValue]="false"
                                  class="next-up-progress">
                                </p-progressBar>
                                <span class="next-up-percent">{{ nextUp.progressPercent }}%</span>
                              </div>
                            }
                          </div>
                        </div>
                      }

                      @if (readStatusBreakdown$ | async; as segments) {
                        @if (segments.length) {
                          <div class="read-progress-card">
                            <div class="read-progress-section">
                              <div class="read-progress-bar">
                                @for (seg of segments; track seg.status) {
                                  <div class="read-progress-segment"
                                    [ngStyle]="{'width': seg.percent + '%', 'background-color': getStatusColor(seg.status)}"
                                    [pTooltip]="getStatusLabel(seg.status) + ': ' + seg.count">
                                  </div>
                                }
                              </div>
                              <div class="read-progress-legend">
                                @for (seg of segments; track seg.status) {
                                  <span class="legend-item"
                                    [ngStyle]="{'border-color': getStatusColor(seg.status)}">
                                    <span class="legend-dot"
                                      [ngStyle]="{'background-color': getStatusColor(seg.status)}"></span>
                                    {{ getStatusLabel(seg.status) }} ({{ seg.count }})
                                  </span>
                                }
                                @let readProg = seriesReadProgress$ | async;
                                @if (readProg) {
                                  <span class="read-percent-label">
                                    {{ t('readPercent', { progress: readProg }) }}
                                  </span>
                                }
                              </div>
                            </div>
                          </div>
                        }
                      }
                    </div>

                  </div>
                </div>

                <div class="description-section">
                  <div class="description-header">
                    <i class="pi pi-align-left"></i>
                    <span>{{ t('synopsis') }}</span>
                  </div>
                  <div class="description-body">
                    <div #descriptionContent [ngClass]="{ 'line-clamp-7': !isExpanded }"
                      class="description-content">
                      <div class="description-html"
                        [innerHTML]="(firstDescription$ | async) || t('noDescription')"></div>
                    </div>
                    @if (isExpanded || isOverflowing) {
                      <button class="expand-toggle" (click)="toggleExpand()">
                        {{ isExpanded ? t('showLess') : t('showMore') }}
                        <i class="pi" [ngClass]="isExpanded ? 'pi-chevron-up' : 'pi-chevron-down'"></i>
                      </button>
                    }
                  </div>
                </div>

                <h3 class="section-title">
                  <i class="pi pi-objects-column"></i>
                  {{ t('booksInSeries') }}
                </h3>
                <div class="series-items-grid" #Container
                  [ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth + ', 1fr))'}">
                  @for (book of books; track book; let i = $index) {
                    <div class="grid-item"
                      [ngStyle]="{width: currentCardSize.width + 'px', height: currentCardSize.height + 'px'}">
                      <app-book-card
                          [index]="i"
                          [book]="book"
                          [isCheckboxEnabled]="true"
                          [isSelected]="selectedBooks.has(book.id)"
                          (checkboxClick)="onCheckboxClicked($event)"
                          [onBookSelect]="handleBookSelect.bind(this)"
                          [isSeriesCollapsed]="false"
                          [overlayPreferenceService]="bookCardOverlayPreferenceService">
                      </app-book-card>
                    </div>
                  }
                  @if (books.length === 0) {
                    <div class="empty-state">{{ t('noBooksFound') }}</div>
                  }
                </div>

              </div>

            </div>
        }

      </p-tabpanel>

      <!-- BOOK LIST TAB -->
      <p-tabpanel value="list">
        <div class="book-list-container">
          @for (book of books; track book.id; let i = $index) {
            <div class="book-list-card">
              <div class="list-number-col">
                <span class="list-series-number">
                  {{ book.metadata?.seriesNumber != null ? '#' + book.metadata?.seriesNumber : '-' }}
                </span>
              </div>
              <img [src]="getBookThumbnailUrl(book)"
                [alt]="book.metadata?.title || ''"
                class="list-thumb"
                loading="lazy"/>
              <div class="list-book-info">
                <span class="list-book-title">{{ book.metadata?.title || '' }}</span>
                <div class="list-book-meta">
                  @if (book.metadata?.authors?.length) {
                    <span class="list-book-authors">{{ book.metadata!.authors!.join(', ') }}</span>
                  }
                  @if (book.metadata?.publishedDate; as date) {
                    <span class="list-meta-dot">·</span>
                    <span class="list-book-year">{{ date }}</span>
                  }
                  @if (book.metadata?.pageCount; as pages) {
                    <span class="list-meta-dot">·</span>
                    <span class="list-book-pages">{{ pages }} {{ t('listPages') }}</span>
                  }
                </div>
                @if (getBookProgress(book); as progress) {
                  <div class="list-progress-row">
                    <div class="list-progress-bar">
                      <div class="list-progress-fill" [ngStyle]="{'width': progress + '%'}"></div>
                    </div>
                    <span class="list-progress-text">{{ progress }}%</span>
                  </div>
                }
                @if (book.personalRating) {
                  <div class="list-rating-row">
                    @for (star of [1,2,3,4,5]; track star) {
                      <i class="pi list-star"
                        [ngClass]="book.personalRating! >= star * 2 ? 'pi-star-fill' : (book.personalRating! >= star * 2 - 1 ? 'pi-star-half-fill' : 'pi-star')">
                      </i>
                    }
                    <span class="list-rating-value">{{ book.personalRating }}/10</span>
                  </div>
                }
              </div>
              <div class="list-right-col">
                <div class="list-badges">
                  <span class="list-status-badge"
                    [ngStyle]="{'background-color': getStatusColor(book.readStatus)}">
                    {{ getStatusLabel(book.readStatus) }}
                  </span>
                  @if (book.primaryFile?.bookType; as bookType) {
                    <span class="list-format-badge"
                      [style.background-color]="'color-mix(in srgb, var(--book-type-' + bookType.toLowerCase() + '-color) 20%, transparent)'"
                      [style.border-color]="'var(--book-type-' + bookType.toLowerCase() + '-color)'"
                      [style.color]="'var(--book-type-' + bookType.toLowerCase() + '-color)'">
                      {{ bookType }}
                    </span>
                  }
                </div>
                <div class="list-actions">
                  <button class="list-action-btn btn-read" (click)="readBook(book.id); $event.stopPropagation()"
                    [pTooltip]="t('readButton')" tooltipPosition="top">
                    <i class="pi pi-book"></i>
                  </button>
                  <button class="list-action-btn btn-details" (click)="viewBookDetails(book.id); $event.stopPropagation()"
                    [pTooltip]="t('viewDetails')" tooltipPosition="top">
                    <i class="pi pi-info-circle"></i>
                  </button>
                </div>
              </div>
            </div>
          }
          @if (books.length === 0) {
            <div class="empty-state">{{ t('noBooksFound') }}</div>
          }
        </div>
      </p-tabpanel>

    </p-tabpanels>
  </p-tabs>
  @if (selectedBooks.size > 0) {
    @if (userService.userState$ | async; as userState) {
      <div class="book-browser-footer" [@slideInOut]>
        <div class="footer-content">
          <div class="footer-left">
            <div class="selected-count-badge">
              <i class="pi pi-check-circle badge-icon"></i>
              <span class="badge-count" style="color: var(--primary-color)">{{ selectedBooks.size }}</span>
              <span class="badge-label">{{ t('selected') }}</span>
            </div>
          </div>
          <div class="footer-center">
              <div class="footer-action-group">
                @if (hasMetadataMenuItems) {
                  <p-tieredMenu #menu [model]="metadataMenuItems" [popup]="true" appendTo="body"/>
                  <p-button
                    (click)="menu.toggle($event)"
                    [pTooltip]="t('tooltip.metadataActions')"
                    tooltipPosition="top"
                    outlined="true"
                    severity="info"
                    icon="pi pi-database">
                  </p-button>
                }
                <p-button
                  icon="pi pi-bookmark-fill"
                  outlined="true"
                  severity="info"
                  (onClick)="openShelfAssigner()"
                  [pTooltip]="t('tooltip.assignToShelf')"
                  tooltipPosition="top">
                </p-button>
                @if (userState.user!.permissions.canBulkLockUnlockMetadata) {
                  <p-button
                    outlined="true"
                    icon="pi pi-lock"
                    severity="info"
                    (click)="lockUnlockMetadata()"
                    [pTooltip]="t('tooltip.lockUnlockMetadata')"
                    tooltipPosition="top">
                  </p-button>
                }
                @if (userState.user!.permissions.canMoveOrganizeFiles && (appSettingsService.appSettings$ | async)?.diskType === 'LOCAL') {
                  <p-button
                    outlined="true"
                    icon="pi pi-arrows-h"
                    severity="info"
                    (click)="moveFiles()"
                    [pTooltip]="t('tooltip.organizeFiles')"
                    tooltipPosition="top">
                  </p-button>
                }
                @if (hasMoreActionsItems) {
                  <div class="more-actions-wrapper">
                    <p-button
                      (click)="menu.toggle($event)"
                      [pTooltip]="t('tooltip.moreActions')"
                      tooltipPosition="top"
                      outlined="true"
                      severity="info"
                      icon="pi pi-ellipsis-v">
                    </p-button>
                    <p-tieredMenu #menu [model]="moreActionsMenuItems" [popup]="true" appendTo="body"/>
                  </div>
                }
              </div>
            <p-divider layout="vertical"></p-divider>
            <div class="footer-action-group">
              <p-button
                outlined="true"
                icon="pi pi-check-square"
                severity="success"
                (click)="selectAllBooks()"
                [pTooltip]="t('tooltip.selectAll')"
                tooltipPosition="top">
              </p-button>
              <p-button
                outlined="true"
                icon="pi pi-times"
                severity="warn"
                (click)="deselectAllBooks()"
                [pTooltip]="t('tooltip.deselectAll')"
                tooltipPosition="top">
              </p-button>
            </div>
            @if (userState.user!.permissions.admin || userState.user!.permissions.canDeleteBook) {
              <p-divider layout="vertical"></p-divider>
              <p-button
                outlined="true"
                icon="pi pi-trash"
                severity="danger"
                (click)="confirmDeleteBooks()"
                [pTooltip]="t('tooltip.deleteSelected')"
                tooltipPosition="top">
              </p-button>
            }
          </div>
          <div class="footer-right"></div>
        </div>
      </div>
    }
  }
</div>

} @else {
  <div class="loading-state">
    <p-progressSpinner strokeWidth="4" fill="transparent" animationDuration=".8s">
    </p-progressSpinner>
    <p style="color: var(--primary-color);">
      {{ t('loadingSeriesDetails') }}
    </p>
  </div>
}
</ng-container>
