<ion-header class="ion-no-border">
  <ion-toolbar class="bg-gradient">
    <ion-title class="outfit-font">
      <div class="header-logo-wrapper">
        <img src="assets/icon/favicon.png" class="header-logo">
        <div class="header-text-group">
          <span class="app-name">{{ appName }}</span>
          <span class="version-badge" (click)="checkForAppUpdate($event)" style="cursor: pointer; display: inline-flex; align-items: center; gap: 4px;">
            v{{ version }}<span *ngIf="settingsService.userName()"> - {{ settingsService.userName() }}</span>
            <span *ngIf="hasUpdateAvailable()" style="display: inline-flex; align-items: center; justify-content: center; padding: 4px; margin-left: 2px; background: rgba(var(--ion-color-secondary-rgb), 0.25); border-radius: 50%; border: 1px solid var(--ion-color-secondary); width: 24px; height: 24px; box-shadow: 0 0 8px rgba(var(--ion-color-secondary-rgb), 0.3);">
              <ion-icon name="refresh-outline" style="font-size: 1.15rem; color: var(--ion-color-secondary); font-weight: bold;"></ion-icon>
            </span>
          </span>
        </div>
      </div>
    </ion-title>
    <ion-buttons slot="end">

      <ion-button (click)="importPlaylist()" class="add-btn">
        <ion-icon slot="icon-only" name="qr-code-outline"></ion-icon>
      </ion-button>
      <ion-button routerLink="/settings" class="settings-btn">
        <ion-icon slot="icon-only" name="settings-outline"></ion-icon>
      </ion-button>
    </ion-buttons>
  </ion-toolbar>
  <ion-toolbar class="bg-gradient" *ngIf="!playlistService.selectionMode() || isAddingSongs()">
    <div class="search-wrapper-group">
      <div class="search-row">
        <div class="search-wrapper glass">
          <ion-searchbar 
            placeholder="Cerca un canto..." 
            [value]="searchQuery()"
            (ionInput)="onSearch($event)"
            class="custom-searchbar">
          </ion-searchbar>
          <ion-button fill="clear" (click)="toggleVoiceSearch()" class="voice-search-btn">
            <ion-icon slot="icon-only" [name]="audioEngine.isSearching() ? 'mic' : 'mic-outline'" [color]="audioEngine.isSearching() ? 'danger' : 'secondary'"></ion-icon>
          </ion-button>
        </div>
      </div>
      
      <div class="filter-actions-row">
        <div class="song-count-card outfit-font">
          {{ filteredCanti().length }}
        </div>
        <div class="filter-buttons">
          <ion-button 
            [fill]="activeFilterType() === 'playlist' || playlistService.activeListName() !== null ? 'solid' : 'outline'" 
            size="small" 
            (click)="toggleFilterType('playlist')"
            class="filter-chip">
            {{ playlistService.activeListName() !== null ? 'Playlist: ' + playlistService.activeListName() : 'Playlist' }}
            <ion-icon slot="end" name="chevron-down-outline" *ngIf="playlistService.activeListName() === null"></ion-icon>
            <span class="close-icon-wrapper" *ngIf="playlistService.activeListName() !== null" (click)="clearSpecialList($event)">
              <ion-icon slot="end" name="close-circle"></ion-icon>
            </span>
          </ion-button>

          <div class="comunita-filter-wrapper" style="position: relative; display: inline-flex; align-items: center; margin-right: 8px; z-index: 999;" *ngIf="settingsService.comunitaEnabled()">
            <ion-button 
              [fill]="comunitaService.isFilterActive() ? 'solid' : 'outline'" 
              size="small" 
              (click)="toggleComunitaFilter()"
              [color]="comunitaService.isFilterActive() ? 'secondary' : 'medium'"
              class="filter-chip"
              style="margin: 0;">
              <ion-icon slot="start" name="people-outline" style="font-size: 1.1rem; margin-right: 4px;"></ion-icon>
              {{ comunitaService.comunitaCode() ? comunitaService.comunitaNome() : 'Comunità' }}
            </ion-button>
          </div>

          <ion-button 
            [fill]="activeFilterType() === 'lista_completa' || showValidati() || showNonValidati() ? 'solid' : 'outline'" 
            size="small" 
            (click)="toggleFilterType('lista_completa')"
            class="filter-chip">
            {{ showValidati() ? 'Lista: Validati' : (showNonValidati() ? 'Lista: Non Validati' : 'Lista completa') }}
            <ion-icon slot="end" name="chevron-down-outline" *ngIf="!showValidati() && !showNonValidati()"></ion-icon>
            <span class="close-icon-wrapper" *ngIf="showValidati() || showNonValidati()" (click)="clearListaCompleta($event)">
              <ion-icon slot="end" name="close-circle"></ion-icon>
            </span>
          </ion-button>
          
          <ion-button 
            [fill]="activeFilterType() === 'liturgico' || selectedLiturgico() !== null ? 'solid' : 'outline'" 
            size="small" 
            (click)="toggleFilterType('liturgico')"
            class="filter-chip">
            {{ selectedLiturgico() !== null ? 'Liturgia: ' + getSelectedLiturgicoLabel() : 'Liturgia' }}
            <ion-icon slot="end" name="chevron-down-outline" *ngIf="selectedLiturgico() === null"></ion-icon>
            <span class="close-icon-wrapper" *ngIf="selectedLiturgico() !== null" (click)="clearLiturgico($event)">
              <ion-icon slot="end" name="close-circle"></ion-icon>
            </span>
          </ion-button>
          
          <ion-button 
            [fill]="activeFilterType() === 'tematico' || selectedTematico() !== null ? 'solid' : 'outline'" 
            size="small" 
            (click)="toggleFilterType('tematico')"
            class="filter-chip">
            {{ selectedTematico() !== null ? 'Periodo: ' + getSelectedTematicoLabel() : 'Periodo' }}
            <ion-icon slot="end" name="chevron-down-outline" *ngIf="selectedTematico() === null"></ion-icon>
            <span class="close-icon-wrapper" *ngIf="selectedTematico() !== null" (click)="clearTematico($event)">
              <ion-icon slot="end" name="close-circle"></ion-icon>
            </span>
          </ion-button>
          
          <ion-button 
            [fill]="showSuggeriti() ? 'solid' : 'outline'" 
            size="small" 
            (click)="toggleSuggeriti()"
            class="filter-chip">
            Suggeriti
            <span class="close-icon-wrapper" *ngIf="showSuggeriti()" (click)="clearSuggeriti($event)">
              <ion-icon slot="end" name="close-circle"></ion-icon>
            </span>
          </ion-button>

          <ion-button 
            [fill]="showTopTen() ? 'solid' : 'outline'" 
            size="small" 
            (click)="toggleTopTen()"
            class="filter-chip">
            Top Ten
            <span class="close-icon-wrapper" *ngIf="showTopTen()" (click)="clearTopTen($event)">
              <ion-icon slot="end" name="close-circle"></ion-icon>
            </span>
          </ion-button>
        </div>
      </div>
    </div>
  </ion-toolbar>


  <!-- Category Scroll (Dropdown style) -->
  <ion-toolbar class="bg-gradient momentos-toolbar" *ngIf="shouldShowSubSectionToolbar()">
    <div class="momento-scroll" *ngIf="activeFilterType() !== 'playlist' || playlistService.allPlaylists().length > 0 || playlistService.selectionMode()">
      <!-- Selection Mode Actions -->
      <div class="selection-pill glass" *ngIf="playlistService.selectionMode() && reorderList().length > 0">
        <span class="selection-count">{{ reorderList().length }}</span>
        <ion-button fill="clear" color="secondary" (click)="toggleAddingSongs()" class="mini-action-btn" *ngIf="reorderList().length > 0">
          <ion-icon slot="icon-only" [name]="isAddingSongs() ? 'list-outline' : 'add-circle-outline'"></ion-icon>
        </ion-button>
        <ion-button fill="clear" color="secondary" (click)="finishSelection()" [disabled]="reorderList().length === 0" class="mini-action-btn" *ngIf="reorderList().length > 0">
          <ion-icon slot="icon-only" name="save-outline"></ion-icon>
        </ion-button>
        <ion-button fill="clear" color="danger" (click)="cancelSelection()" class="mini-action-btn" *ngIf="reorderList().length > 0">
          <ion-icon slot="icon-only" name="close-circle-outline"></ion-icon>
        </ion-button>
      </div>

      <!-- Active Playlist Actions -->
      <div class="selection-pill glass" *ngIf="activeFilterType() === 'playlist' && playlistService.activePlaylistId() && !playlistService.selectionMode()">
        <ion-button fill="clear" color="secondary" (click)="editPlaylist()" class="mini-action-btn" *ngIf="!isComunitaPlaylist() && isActivePlaylistSaved()">
          <ion-icon slot="icon-only" name="create-outline"></ion-icon>
        </ion-button>
        <ion-button fill="clear" color="secondary" (click)="shareActivePlaylist()" class="mini-action-btn">
          <ion-icon slot="icon-only" name="share-social-outline"></ion-icon>
        </ion-button>
        <ion-button fill="clear" color="danger" (click)="deleteActivePlaylist()" class="mini-action-btn" *ngIf="playlistService.activePlaylistId() && !isComunitaPlaylist()">
          <ion-icon name="trash-outline" slot="icon-only"></ion-icon>
        </ion-button>
      </div>

      <!-- Filter chips -->
      <ng-container *ngIf="activeFilterType() === 'lista_completa'">
        <div 
          class="momento-chip glass"
          [class.active]="showValidati()"
          (click)="toggleValidati()">
          Validati
        </div>
        <div 
          class="momento-chip glass"
          [class.active]="showNonValidati()"
          (click)="toggleNonValidati()"
          style="display: inline-flex; align-items: center; gap: 6px;">
          <span>Non Validati</span>
          <ion-icon 
            *ngIf="showNonValidati() && !playlistService.selectionMode() && settingsService.showEditor()" 
            name="add-outline" 
            (click)="$event.stopPropagation()" 
            routerLink="/propose-canto" 
            class="non-validati-add-icon">
          </ion-icon>
        </div>
      </ng-container>

      <ng-container *ngIf="activeFilterType() !== 'lista_completa'">
        <div 
          *ngFor="let item of (activeFilterType() === 'playlist' ? playlistService.allPlaylists() : (activeFilterType() === 'liturgico' ? cantiService.indiceLiturgico() : (activeFilterType() === 'tematico' ? cantiService.indiceTematico() : [])))" 
          class="momento-chip glass"
          [class.active]="activeFilterType() === 'playlist' ? playlistService.activePlaylistId() === item.id : isIndexSelected(item.id)"
          [class.comunita-chip]="activeFilterType() === 'playlist' && item.isComunita"
          (click)="activeFilterType() === 'playlist' ? selectPlaylist(item) : toggleIndex(item.id, activeFilterType()!)">
          <ion-icon *ngIf="activeFilterType() === 'playlist' && item.isComunita" name="people-outline" style="font-size: 0.85rem; margin-right: 4px; vertical-align: middle;"></ion-icon>
          {{ activeFilterType() === 'playlist' ? item.name : item.tag_name }}
        </div>
      </ng-container>
    </div>

    <!-- Instructions when playlist is empty -->
    <div class="empty-playlist-container" *ngIf="activeFilterType() === 'playlist' && playlistService.allPlaylists().length === 0 && !playlistService.selectionMode()">
      <p class="empty-playlist-instruction outfit-font">
        Per creare una playlist, seleziona il nr del canto che vuoi inserire nella playlist, riordinali e salvala con nome
      </p>
    </div>
  </ion-toolbar>
</ion-header>

<ion-content class="bg-gradient" 
             (touchstart)="onTouchStart($event); onInteraction()" 
             (touchmove)="onTouchMove($event)" 
             (touchend)="onTouchEnd()"
             (click)="onInteraction()">

  <div class="ion-padding no-padding-top">

    <div *ngIf="cantiService.loading() && filteredCanti().length === 0" class="ion-text-center ion-padding loading-container">
      <div class="loading-wrapper">
        <ion-spinner name="crescent" color="secondary"></ion-spinner>
        <div class="percentage-label outfit-font">{{ cantiService.progress() }}%</div>
        <p class="ion-margin-top" style="color: var(--ion-color-secondary)">Caricamento canti...</p>
      </div>
    </div>

    <!-- Wrap in DragDrop only in Reorder mode -->
    <div cdkDropList 
         [cdkDropListDisabled]="!playlistService.selectionMode() || isAddingSongs()"
         (cdkDropListDropped)="drop($event)"
         class="transparent-list">
      
      <!-- Premium Suggested Mass Card (Collapsible with Swipe support) -->
      <div class="suggeriti-header-card glass ion-margin-bottom" 
           *ngIf="showSuggeriti() && cantiLettureService.data()"
           (click)="isMassCardExpanded.set(!isMassCardExpanded())"
           (touchstart)="onMassCardTouchStart($event)"
           (touchend)="onMassCardTouchEnd($event)"
           [class.expanded]="isMassCardExpanded()">
        <div class="card-inner ion-padding">
          <div class="card-header-row">
            <div class="card-header-left">
              <span class="card-label">SINTESI MESSA</span>
              <span class="card-date-compact" *ngIf="!isMassCardExpanded()">{{ getSelectedMassFormattedDate() }}</span>
            </div>
            <div class="card-header-right" style="display: flex; align-items: center; gap: 8px;">
              <div class="mass-nav-buttons" style="display: flex; align-items: center; gap: 4px; z-index: 10;" (click)="$event.stopPropagation()">
                <ion-button fill="clear" size="small" color="secondary" (click)="navigateMassDate(-1)" style="margin: 0; --padding-start: 4px; --padding-end: 4px; height: 28px;">
                  <ion-icon slot="icon-only" name="chevron-back-outline" style="font-size: 1.1rem;"></ion-icon>
                </ion-button>
                <ion-button fill="clear" size="small" color="secondary" (click)="navigateMassDate(1)" style="margin: 0; --padding-start: 4px; --padding-end: 4px; height: 28px;">
                  <ion-icon slot="icon-only" name="chevron-forward-outline" style="font-size: 1.1rem;"></ion-icon>
                </ion-button>
              </div>
              <ion-icon [name]="isMassCardExpanded() ? 'chevron-up-outline' : 'chevron-down-outline'" class="expand-icon" style="margin-left: 4px;"></ion-icon>
            </div>
          </div>
          
          <div class="expandable-content" [class.show]="isMassCardExpanded()">
            <div class="card-date-row" *ngIf="isMassCardExpanded()">
              <span class="card-date">{{ getSelectedMassFormattedDate() }}</span>
            </div>
            <h1 class="card-title outfit-font">{{ getSelectedMassTitle() }}</h1>
            <p class="card-summary outfit-font" *ngIf="getSelectedMassSummary()">
              {{ getSelectedMassSummary() }}
            </p>
          </div>
        </div>
      </div>
      
      <ion-item *ngFor="let canto of visibleCanti()" 
                [id]="'canto-' + canto.id" 
                class="glass ion-margin-bottom custom-item"
                [class.is-playing]="youtubePlayerService.currentCantoId() === canto.id"
                cdkDrag 
                [cdkDragDisabled]="!playlistService.selectionMode() || isAddingSongs()">
        
        <!-- Drag Handle (visible only in reorder mode) -->
        <div class="drag-handle" cdkDragHandle *ngIf="playlistService.selectionMode() && !isAddingSongs()">
          <ion-icon name="reorder-two-outline"></ion-icon>
        </div>

        <div class="item-wrapper">
          <!-- Selection Area -->
          <div class="selection-column" (click)="toggleSongSelection(canto.id); $event.stopPropagation()">
            <span class="canto-number" [class.selected-number]="playlistService.selectedIds().has(canto.id)">
              {{ canto.id.startsWith('my_') ? getMySongNumber(canto) : canto.id_canti }}
            </span>
          </div>

          <!-- Content Area -->
          <div class="content-column" (click)="goToCanto(canto.id)">
            <div class="top-row">
              <ion-label class="info-section">
                <h2 class="outfit-font" style="font-weight: 500; color: var(--ion-color-secondary); display: flex; align-items: center; flex-wrap: wrap; gap: 4px;">
                  <span *ngIf="getCommunitySongNumber(canto)" style="color: var(--ion-color-secondary); font-weight: 600; margin-right: 8px; opacity: 0.9;">{{ getCommunitySongNumber(canto) }}</span>
                  <span>{{ canto.titolo }}</span>
                  <span *ngIf="canto.nonValidato && !canto.id.startsWith('my_')" class="non-validato-badge remote-badge">Remoto</span>
                  <span *ngIf="canto.id.startsWith('my_')" class="non-validato-badge mio-badge">Mio</span>
                </h2>
                <p style="color: rgba(255,255,255,0.6); margin-bottom: 2px; display: flex; align-items: center; flex-wrap: wrap; gap: 8px;">
                  <span>{{ canto.autore || 'Autore sconosciuto' }}</span>
                  <span *ngIf="settingsService.showUpdateDate() && canto.data_update" class="update-date-badge" style="font-size: 0.7rem; color: rgba(255, 255, 255, 0.45); font-weight: 400; display: inline-flex; align-items: center; gap: 3px;">
                    <ion-icon name="calendar-outline" style="font-size: 0.75rem; color: rgba(255,255,255,0.45);"></ion-icon>
                    agg. {{ cantiService.formatUpdateDate(canto.data_update) }}
                  </span>
                  <span *ngIf="showTopTen() && getEsecuzioniCount(canto.id) !== null" class="esecuzioni-badge" style="color: var(--ion-color-secondary); font-size: 0.75rem; background: rgba(var(--ion-color-secondary-rgb), 0.12); padding: 2px 6px; border-radius: 6px; display: inline-flex; align-items: center; gap: 4px; border: 1px solid rgba(var(--ion-color-secondary-rgb), 0.2);">
                    <ion-icon name="stats-chart-outline" style="font-size: 0.75rem; color: var(--ion-color-secondary);"></ion-icon>
                    {{ getEsecuzioniCount(canto.id) }} esecuzioni
                  </span>
                  <span *ngIf="showSuggeriti() && getMassSuggestionWeight(canto.id_canti) !== null" class="suggerito-badge" style="color: var(--ion-color-secondary); font-size: 0.75rem; background: rgba(var(--ion-color-secondary-rgb), 0.12); padding: 2px 6px; border-radius: 6px; display: inline-flex; align-items: center; gap: 4px; border: 1px solid rgba(var(--ion-color-secondary-rgb), 0.3);">
                    <ion-icon name="sparkles-outline" style="font-size: 0.75rem; color: var(--ion-color-secondary);"></ion-icon>
                    Attinenza {{ getMassSuggestionWeight(canto.id_canti) }}%
                  </span>
                </p>

                <!-- Visualizza tag sotto autore -->
                <div *ngIf="settingsService.showTagsInList() && cantiService.getSongTags(canto).length > 0" class="song-tags-list">
                  <span *ngFor="let tag of cantiService.getSongTags(canto)" class="song-tag-badge">
                    {{ tag }}
                  </span>
                </div>
              </ion-label>

              <!-- Video Thumbnail Section -->
              <div *ngIf="cantiService.getYoutubeId(canto.link_youtube)" class="thumb-section" (click)="$event.stopPropagation()">
                <div class="thumb-container compact">
                  <ng-container *ngIf="youtubePlayerService.isPlayerSupported(); else noPlayerThumb">
                    <div class="thumb-wrapper" (click)="playVideo($event, canto.id)">
                      <img [src]="cantiService.getYoutubeThumb(canto.link_youtube)" 
                           class="thumb-img loaded" 
                           loading="lazy">
                      <div class="play-overlay youtube-overlay">
                        <ion-icon name="play-sharp"></ion-icon>
                      </div>
                    </div>
                  </ng-container>
                  <ng-template #noPlayerThumb>
                    <div class="thumb-wrapper">
                      <img [src]="cantiService.getYoutubeThumb(canto.link_youtube)" 
                           class="thumb-img loaded" 
                           loading="lazy"
                           *ngIf="connectivityService.isOnline(); else offlineIcon">
                      <ng-template #offlineIcon>
                        <div class="offline-thumb">
                          <ion-icon name="cloud-offline-outline"></ion-icon>
                        </div>
                      </ng-template>
                    </div>
                  </ng-template>
                </div>
              </div>

              <!-- Delete Button (only for local songs) -->
              <div *ngIf="canto.id.startsWith('my_')" class="delete-section" (click)="$event.stopPropagation()">
                <ion-button fill="clear" color="danger" (click)="deleteMyCanto(canto.id, $event)">
                  <ion-icon slot="icon-only" name="trash-outline"></ion-icon>
                </ion-button>
              </div>
            </div>
          </div>

          <!-- Player bars removed from here -->
        </div>
      </ion-item>
    </div>

    <!-- Add songs / Toggle View Button -->
    <div class="ion-text-center ion-margin-top" *ngIf="playlistService.selectionMode()">
      <ion-button fill="solid" color="secondary" (click)="toggleAddingSongs()" class="action-mode-btn glass">
        <ion-icon slot="start" [name]="isAddingSongs() ? 'list-outline' : 'add-circle-outline'"></ion-icon>
        {{ isAddingSongs() ? 'Torna alla Playlist' : 'Aggiungi altri canti' }}
      </ion-button>
    </div>

    <div *ngIf="!cantiService.loading() && filteredCanti().length === 0" class="ion-text-center ion-padding">
      <p style="color: rgba(255,255,255,0.5)">Nessun canto trovato.</p>
    </div>
  </div>

  <ion-infinite-scroll (ionInfinite)="loadData($event)" threshold="150px" [disabled]="limit() >= filteredCanti().length || (playlistService.selectionMode() && !isAddingSongs())">
    <ion-infinite-scroll-content loadingSpinner="bubbles" loadingText="Caricamento altri canti...">
    </ion-infinite-scroll-content>
  </ion-infinite-scroll>

</ion-content>

<ion-footer *ngIf="youtubePlayerService.isPlayerSupported() && youtubePlayerService.currentCantoId()" class="ion-no-border">
  <ion-toolbar class="global-player-toolbar glass">
    <div class="player-content">
      <div class="controls-row">
        <ion-button fill="clear" color="secondary" (click)="playPrevPreview($event)" class="skip-btn">
          <ion-icon slot="icon-only" name="play-skip-back-sharp"></ion-icon>
        </ion-button>
        
        <ion-button fill="clear" color="secondary" (click)="youtubePlayerService.isPlaying() ? stopVideo($event) : playVideo($event, youtubePlayerService.currentCantoId()!)" class="play-btn">
          <ion-icon slot="icon-only" [name]="youtubePlayerService.isPlaying() ? 'pause-sharp' : 'play-sharp'"></ion-icon>
        </ion-button>

        <ion-range 
          [min]="0" 
          [max]="youtubePlayerService.videoDuration()" 
          [value]="youtubePlayerService.videoProgress()"
          (ionChange)="onSeek($event)"
          (ionKnobMoveStart)="onSeekStart()"
          (ionKnobMoveEnd)="onSeekEnd()"
          color="secondary"
          class="global-range">
        </ion-range>

        <ion-button fill="clear" color="secondary" (click)="playNextPreview($event)" class="skip-btn">
          <ion-icon slot="icon-only" name="play-skip-forward-sharp"></ion-icon>
        </ion-button>

        <ion-button fill="clear" color="medium" (click)="stopVideo($event)" class="close-btn">
          <ion-icon slot="icon-only" name="close-circle-outline"></ion-icon>
        </ion-button>
      </div>
    </div>
  </ion-toolbar>
</ion-footer>


