<ng-container *transloco="let t; prefix: 'readerAudiobook'">
@if (isLoading) {
  <div class="loading-container">
    <p-progressSpinner strokeWidth="3" />
    <span class="loading-text">{{ t('loading') }}</span>
  </div>
} @else if (audiobookInfo) {
  <div class="audiobook-player">
    <!-- Hidden audio element -->
    <audio
      #audioElement
      (loadedmetadata)="onAudioLoaded()"
      (timeupdate)="onTimeUpdate()"
      (progress)="onProgress()"
      (ended)="onAudioEnded()"
      (error)="onAudioError()"
    ></audio>

    <!-- Header -->
    <header class="reader-header">
      <p-button
        icon="pi pi-arrow-left"
        [rounded]="true"
        [text]="true"
        severity="secondary"
        (onClick)="closeReader()"
        [pTooltip]="t('header.backTooltip')"
        tooltipPosition="bottom"
      />
      <div class="header-info">
        <h1 class="book-title">{{ audiobookInfo.title || t('untitled') }}</h1>
        <span class="book-author">{{ audiobookInfo.author || t('unknownAuthor') }}</span>
      </div>
      <div class="header-actions">
        <p-button
          icon="pi pi-bookmark"
          [rounded]="true"
          [text]="true"
          severity="secondary"
          (onClick)="toggleBookmarkList()"
          [pTooltip]="t('header.bookmarksTooltip')"
          tooltipPosition="bottom"
        />
        <p-button
          icon="pi pi-list"
          [rounded]="true"
          [text]="true"
          severity="secondary"
          (onClick)="toggleTrackList()"
          [pTooltip]="t('header.chaptersTracksTooltip')"
          tooltipPosition="bottom"
        />
      </div>
    </header>

    <!-- Main content -->
    <main class="reader-main">
      <!-- Cover art -->
      <div class="cover-container">
        <div class="cover-wrapper">
          @if (coverUrl) {
            <img
              [src]="coverUrl"
              (error)="onCoverError()"
              [alt]="t('coverAlt')"
              class="cover-image"
            />
          } @else {
            <div class="cover-placeholder">
              <i class="pi pi-headphones"></i>
            </div>
          }
          @if (audioLoading) {
            <div class="cover-loading">
              <p-progressSpinner strokeWidth="3" />
            </div>
          }
        </div>
      </div>

      <!-- Track/Chapter info -->
      <div class="track-info">
        @if (audiobookInfo.folderBased && currentTrack) {
          <span class="track-title">{{ currentTrack.title }}</span>
          <span class="track-number">{{ t('trackInfo.trackOf', { current: currentTrackIndex + 1, total: audiobookInfo.tracks?.length }) }}</span>
        } @else if (getCurrentChapter()) {
          <span class="track-title">{{ getCurrentChapter()?.title }}</span>
          @if (hasMultipleChapters()) {
            <span class="track-number">{{ t('trackInfo.chapterOf', { current: getCurrentChapterIndex() + 1, total: audiobookInfo.chapters?.length }) }}</span>
          }
        }
      </div>

      <!-- Progress bar -->
      <div class="progress-container">
        <div class="time-display">
          <span class="current-time">{{ formatTime(currentTime) }}</span>
          <span class="duration">{{ formatTime(duration) }}</span>
        </div>
        <div class="progress-bar-wrapper">
          <div class="buffered-bar" [style.width.%]="getBufferedPercent()"></div>
          <p-slider
            [(ngModel)]="currentTime"
            [min]="0"
            [max]="duration || 100"
            [step]="1"
            (onChange)="seek($event)"
            class="progress-slider"
          />
        </div>
      </div>

      <!-- Playback controls -->
      <div class="playback-controls">
        @if (audiobookInfo.folderBased) {
          <p-button
            icon="pi pi-step-backward"
            [rounded]="true"
            [text]="true"
            severity="secondary"
            (onClick)="previousTrack()"
            [disabled]="currentTrackIndex === 0"
            [pTooltip]="t('controls.previousTrackTooltip')"
            tooltipPosition="top"
            size="large"
          />
        } @else if (hasMultipleChapters()) {
          <p-button
            icon="pi pi-step-backward"
            [rounded]="true"
            [text]="true"
            severity="secondary"
            (onClick)="previousChapter()"
            [disabled]="!canGoPreviousChapter()"
            [pTooltip]="t('controls.previousChapterTooltip')"
            tooltipPosition="top"
            size="large"
          />
        }

        <p-button
          icon="pi pi-replay"
          [rounded]="true"
          [text]="true"
          severity="secondary"
          (onClick)="seekRelative(-30)"
          [pTooltip]="t('controls.rewindTooltip')"
          tooltipPosition="top"
          size="large"
        />

        <p-button
          [icon]="isPlaying ? 'pi pi-pause' : 'pi pi-play'"
          [rounded]="true"
          severity="contrast"
          (onClick)="togglePlay()"
          [disabled]="audioLoading"
          class="play-button"
          size="large"
        />

        <p-button
          icon="pi pi-forward"
          [rounded]="true"
          [text]="true"
          severity="secondary"
          (onClick)="seekRelative(30)"
          [pTooltip]="t('controls.forwardTooltip')"
          tooltipPosition="top"
          size="large"
        />

        @if (audiobookInfo.folderBased) {
          <p-button
            icon="pi pi-step-forward"
            [rounded]="true"
            [text]="true"
            severity="secondary"
            (onClick)="nextTrack()"
            [disabled]="!audiobookInfo.tracks || currentTrackIndex >= audiobookInfo.tracks.length - 1"
            [pTooltip]="t('controls.nextTrackTooltip')"
            tooltipPosition="top"
            size="large"
          />
        } @else if (hasMultipleChapters()) {
          <p-button
            icon="pi pi-step-forward"
            [rounded]="true"
            [text]="true"
            severity="secondary"
            (onClick)="nextChapter()"
            [disabled]="!canGoNextChapter()"
            [pTooltip]="t('controls.nextChapterTooltip')"
            tooltipPosition="top"
            size="large"
          />
        }
      </div>

      <!-- Secondary controls -->
      <div class="secondary-controls">
        <!-- Volume -->
        <div class="volume-control">
          <p-button
            [icon]="getVolumeIcon()"
            [rounded]="true"
            [text]="true"
            severity="secondary"
            (onClick)="toggleMute()"
            size="small"
          />
          <p-slider
            [(ngModel)]="volume"
            [min]="0"
            [max]="1"
            [step]="0.01"
            (onChange)="setVolume($event)"
            class="volume-slider"
          />
        </div>

        <!-- Playback speed -->
        <div class="speed-control">
          <p-selectButton
            [options]="playbackRates"
            [ngModel]="playbackRate"
            (ngModelChange)="setPlaybackRate($event)"
            optionLabel="label"
            optionValue="value"
            size="small"
          />
        </div>
      </div>

      <!-- Extra controls row -->
      <div class="extra-controls">
        <!-- Add bookmark button -->
        <p-button
          icon="pi pi-bookmark-fill"
          [label]="t('extra.addBookmark')"
          [rounded]="true"
          [text]="true"
          severity="secondary"
          (onClick)="addBookmark()"
          size="small"
        />

        <!-- Sleep timer -->
        <p-button
          #sleepTimerBtn
          icon="pi pi-moon"
          [label]="sleepTimerActive ? formatSleepTimerRemaining() : t('extra.sleepTimer')"
          [rounded]="true"
          [text]="true"
          severity="secondary"
          [class]="sleepTimerActive ? 'sleep-timer-active' : ''"
          (onClick)="sleepTimerMenu.toggle($event)"
          size="small"
        />
        <p-menu
          #sleepTimerMenu
          [model]="sleepTimerOptions"
          [popup]="true"
          appendTo="body"
        />
      </div>

      <!-- Audio details -->
      <div class="audio-details">
        @if (audiobookInfo.narrator) {
          <span class="detail-item">
            <i class="pi pi-user"></i>
            {{ t('details.narratedBy', { narrator: audiobookInfo.narrator }) }}
          </span>
        }
        @if (audiobookInfo.bitrate) {
          <span class="detail-item">
            <i class="pi pi-sliders-h"></i>
            {{ t('details.kbps', { bitrate: audiobookInfo.bitrate }) }}
          </span>
        }
        @if (audiobookInfo.durationMs) {
          <span class="detail-item">
            <i class="pi pi-clock"></i>
            {{ t('details.totalDuration', { duration: formatDuration(audiobookInfo.durationMs) }) }}
          </span>
        }
      </div>
    </main>

    <!-- Track/Chapter list sidebar -->
    @if (showTrackList) {
      <aside class="track-list-sidebar">
        <div class="sidebar-header">
          <h2>{{ audiobookInfo.folderBased ? t('sidebar.tracks') : t('sidebar.chapters') }}</h2>
          <p-button
            icon="pi pi-times"
            [rounded]="true"
            [text]="true"
            severity="secondary"
            (onClick)="toggleTrackList()"
          />
        </div>
        <div class="sidebar-content">
          @if (audiobookInfo.folderBased && audiobookInfo.tracks) {
            <ul class="track-list">
              @for (track of audiobookInfo.tracks; track track.index) {
                <li
                  class="track-item"
                  [class.active]="track.index === currentTrackIndex"
                  (click)="selectTrack(track)"
                >
                  <span class="track-index">{{ track.index + 1 }}</span>
                  <div class="track-details">
                    <span class="track-name">{{ track.title }}</span>
                    <span class="track-duration">{{ formatDuration(track.durationMs) }}</span>
                  </div>
                  @if (track.index === currentTrackIndex && isPlaying) {
                    <i class="pi pi-volume-up playing-indicator"></i>
                  }
                </li>
              }
            </ul>
          } @else if (audiobookInfo.chapters) {
            <ul class="track-list">
              @for (chapter of audiobookInfo.chapters; track chapter.index) {
                <li
                  class="track-item"
                  [class.active]="getCurrentChapter()?.index === chapter.index"
                  (click)="selectChapter(chapter)"
                >
                  <span class="track-index">{{ chapter.index + 1 }}</span>
                  <div class="track-details">
                    <span class="track-name">{{ chapter.title }}</span>
                    <span class="track-duration">{{ formatDuration(chapter.durationMs) }}</span>
                  </div>
                  @if (getCurrentChapter()?.index === chapter.index && isPlaying) {
                    <i class="pi pi-volume-up playing-indicator"></i>
                  }
                </li>
              }
            </ul>
          }
        </div>
      </aside>
    }

    <!-- Bookmark list sidebar -->
    @if (showBookmarkList) {
      <aside class="track-list-sidebar bookmark-sidebar">
        <div class="sidebar-header">
          <h2>{{ t('bookmarks.title') }}</h2>
          <p-button
            icon="pi pi-times"
            [rounded]="true"
            [text]="true"
            severity="secondary"
            (onClick)="toggleBookmarkList()"
          />
        </div>
        <div class="sidebar-content">
          @if (bookmarks.length === 0) {
            <div class="empty-bookmarks">
              <i class="pi pi-bookmark"></i>
              <p>{{ t('bookmarks.empty') }}</p>
              <span>{{ t('bookmarks.emptyHint') }}</span>
            </div>
          } @else {
            <ul class="track-list">
              @for (bookmark of bookmarks; track bookmark.id) {
                <li
                  class="track-item bookmark-item"
                  (click)="goToBookmark(bookmark)"
                >
                  <i class="pi pi-bookmark-fill bookmark-icon"></i>
                  <div class="track-details">
                    <span class="track-name">{{ bookmark.title }}</span>
                    <span class="track-duration">{{ formatBookmarkPosition(bookmark) }}</span>
                  </div>
                  <p-button
                    icon="pi pi-trash"
                    [rounded]="true"
                    [text]="true"
                    severity="danger"
                    size="small"
                    (onClick)="deleteBookmark($event, bookmark.id)"
                    [pTooltip]="t('bookmarks.deleteTooltip')"
                    tooltipPosition="left"
                  />
                </li>
              }
            </ul>
          }
        </div>
      </aside>
    }
  </div>
} @else {
  <div class="loading-container">
    <span class="loading-text">{{ t('toast.loadFailed') }}</span>
  </div>
}
</ng-container>
