import { Component, OnInit, OnDestroy, signal, computed, effect, inject, ElementRef, AfterViewInit, untracked, HostListener } from '@angular/core';
import { DomSanitizer, SafeResourceUrl, Meta } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { AlertController, ToastController, GestureController } from '@ionic/angular';
import { CantiService, Canto } from '../../services/canti.service';
import { LyricsParserService, ParsedSection } from '../../services/lyrics-parser.service';
import { ThemeService } from '../../services/theme.service';
import { SettingsService } from '../../services/settings.service';
import { ConnectivityService } from '../../services/connectivity.service';
import { PlaylistService } from '../../services/playlist.service';
import { YoutubePlayerService } from '../../services/youtube-player.service';
import { MyCantiService } from '../../services/my-canti.service';
import { ComunitaService } from '../../services/comunita.service';
import { StatsService } from '../../services/stats.service';
import { FaceDetectorService } from '../../services/face-detector.service';

@Component({
  selector: 'app-player',
  templateUrl: './player.page.html',
  styleUrls: ['./player.page.scss'],
  host: {
    '[class.landscape-active]': 'isLandscapeActive()'
  },
  standalone: false
})
export class PlayerPage implements OnInit, AfterViewInit, OnDestroy {
  public canto = signal<Canto | null>(null);
  public activeSongId = signal<string | null>(null);

  @HostListener('window:keydown', ['$event'])
  handleKeyDown(event: KeyboardEvent) {
    const target = event.target as HTMLElement;
    if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable)) {
      return;
    }
    if (event.key === 'ArrowUp') {
      this.prevSong();
      event.preventDefault();
    } else if (event.key === 'ArrowDown') {
      this.nextSong();
      event.preventDefault();
    }
  }


  private windowLandscape = signal<boolean>(window.innerWidth > window.innerHeight);

  public isLandscapeActive = computed(() => {
    return this.windowLandscape() && this.settingsService.landscapeProjectionEnabled();
  });

  /** true = show chords (accordi mode), false = text only */
  public showChords = signal<boolean>(false);

  /** Autoscroll standard */
  public isAutoscrolling = signal<boolean>(false);
  public autoscrollSpeed = signal<number>(2);
  private autoscrollTimer: any = null;

  /** Font size scale factor (1.0 = default) */
  public fontSize = signal<number>(1.0);

  /** Parsed sections for the current view mode */
  public parsedSections = computed<ParsedSection[]>(() => {
    const c = this.canto();
    if (!c) return [];

    let sections: ParsedSection[];
    // For local songs, if accordi is missing but testo has chords, use parseAccordi on testo
    const hasChordsInText = !c.accordi && c.testo?.includes('[');
    
    // Force text-only mode in landscape
    const activeShowChords = this.showChords() && !this.isLandscapeActive();
    
    if ((activeShowChords && c.accordi) || (activeShowChords && hasChordsInText)) {
      sections = this.lyricsParser.parseAccordi(c.accordi || c.testo);
    } else {
      sections = this.lyricsParser.parseText(c.testo);
    }

    // CRITICAL FIX: If sections are empty but we have text, force a manual section
    if (sections.length === 0 && c.testo) {
      const fallbackLines = c.testo.split('\n')
        .filter(l => l.trim().length > 0)
        .map(l => ({
          text: l.trim(),
          segments: [{ text: l.trim() }]
        }));
      
      if (fallbackLines.length > 0) {
        sections = [{
          type: 'verse',
          lines: fallbackLines
        }];
      }
    }

    // Apply transposition if in chords mode
    if (activeShowChords) {
      return this.lyricsParser.transposeSections(sections, this.transposeAmount());
    }

    return sections;
  });

  public transposeAmount = signal<number>(0);

  public currentLineIndex = signal<number>(0);
  public math = Math;
  public youtubePlayerService = inject(YoutubePlayerService);
  private channel = new BroadcastChannel('karaoke_sync');

  // Rimossi stati di freeze fragili per garantire fluidità e stabilità 100% dell'avanzamento

  private readonly MIN_FONT = 0.6;
  private readonly MAX_FONT = 5.0;
  private readonly FONT_STEP = 0.15;

  public minZoom = computed(() => this.isLandscapeActive() ? 2.0 : this.MIN_FONT);
  public maxZoom = computed(() => this.isLandscapeActive() ? 3.0 : this.MAX_FONT);

  private initialPinchDistance: number | null = null;
  private initialFontSize: number = 1.0;
  public portraitFontSize: number = 1.0;

  private lastMatchedTranscript: string = '';

  // --- Logic State ---
  private lastAdvanceTimestamp: number = 0;      // For safety cooldown
  private readonly ADVANCE_COOLDOWN = 1500;      // 1.5 seconds min
  
  public lastScrollBlock = signal<'start' | 'center'>('start');
  private lastProcessedTranscript: string = '';
  private initialStartTime: number = 0;

  private route = inject(ActivatedRoute);
  public router = inject(Router);
  public cantiService = inject(CantiService);
  public lyricsParser = inject(LyricsParserService);
  private alertCtrl = inject(AlertController);
  private toastCtrl = inject(ToastController);
  public themeService = inject(ThemeService);
  public settingsService = inject(SettingsService);
  public connectivityService = inject(ConnectivityService);
  public playlistService = inject(PlaylistService);
  public comunitaService = inject(ComunitaService);
  private myCantiService = inject(MyCantiService);
  private statsService = inject(StatsService);
  private gestureCtrl = inject(GestureController);
  private el = inject(ElementRef);
  private sanitizer = inject(DomSanitizer);
  public faceDetector = inject(FaceDetectorService);
  private meta = inject(Meta);

  public enableCameraNavigation = signal<boolean>(false);

  private songStartTime: number = 0;

  constructor() {
    // Sync transposition automatically to display/projection page
    effect(() => {
      const amount = this.transposeAmount();
      this.channel.postMessage({ type: 'SYNC_TRANSPOSE', amount });
    });

    // Sync mode from global settings
    effect(() => {
      this.showChords.set(this.settingsService.showChordsDefault());
    }, { allowSignalWrites: true });

    // Auto-scroll logic: keep active line in view
    effect(() => {
      const idx = this.currentLineIndex();
      // Wait for DOM update
      setTimeout(() => {
        const activeElem = document.querySelector('.lyric-line.active');
        if (activeElem) {
          // Usa l'allineamento calcolato dinamico (start per manuale a pagine, center per automatico e standard)
          // Usiamo behavior: 'auto' poiché il container CSS ha già 'scroll-behavior: smooth', evitando blocchi/conflitti nativi Chromium
          const scrollBlock = this.lastScrollBlock();
          activeElem.scrollIntoView({ behavior: 'auto', block: scrollBlock });
        }
      }, 100);
    });

    effect(() => {
      const c = this.canto();
      if (c) {
        if (this.playlistService.autoPlayPlaylist()) {
          setTimeout(() => this.initPlayer(c.id), 500);
        }
      }
    });

    // Reactive song loading based on activeSongId and available canti lists
    effect(() => {
      const id = this.activeSongId();
      const allCanti = this.cantiService.canti();
      const myCantiList = this.myCantiService.myCanti();
      const comunitaCantiPers = this.comunitaService.comunitaCantiPersonali();

      if (id) {
        let found: any = null;
        if (this.comunitaService.comunitaCode() && this.comunitaService.isFilterActive()) {
          found = comunitaCantiPers.find(c => c.id === id);
        }
        if (!found) {
          found = allCanti.find(c => c.id === id);
        }
        if (!found) {
          found = myCantiList.find(c => c.id === id);
        }
        if (!found) {
          found = this.playlistService.remoteCustomSongs().find(c => c.id === id || String(c.id_canti) === id);
        }
        if (!found) {
          found = this.playlistService.remoteShareCanti().find(c => c.id === id || String(c.id_canti) === id);
        }
        if (!found) {
          found = comunitaCantiPers.find(c => c.id === id);
        }

        if (found) {
          const current = untracked(() => this.canto());
          // Avoid duplicate triggers for the same song, but update if song content changed
          const contentChanged = !current || 
            current.id !== found.id || 
            current.titolo !== found.titolo || 
            current.autore !== found.autore ||
            current.link_youtube !== found.link_youtube ||
            current.testo !== found.testo || 
            current.accordi !== found.accordi || 
            JSON.stringify(current.id_momenti) !== JSON.stringify(found.id_momenti);

          if (contentChanged) {
            this.logPreviousSongTime();
            this.canto.set(found);
            this.currentLineIndex.set(0);
            this.lastScrollBlock.set('start');
            this.songStartTime = Date.now();
            this.cantiService.getStorage()?.set('last_song_id', id);
            this.channel.postMessage({ type: 'SYNC_CANTO', id: found.id });
            this.channel.postMessage({ type: 'SYNC_INDEX', index: 0 });

            // Update Open Graph Image tag dynamically
            const thumb = this.cantiService.getYoutubeThumb(found.link_youtube);
            if (thumb) {
              this.meta.updateTag({ property: 'og:image', content: thumb });
            } else {
              this.meta.updateTag({ property: 'og:image', content: window.location.origin + '/assets/icon/favicon.png' });
            }

            setTimeout(() => {
              const scrollEl = this.el.nativeElement.querySelector('.lyrics-container');
              if (scrollEl) {
                scrollEl.scrollTop = 0;
              }
              this.checkLandscapeZoom();
            }, 100);
          }
        }
      }
    }, { allowSignalWrites: true });

    // Reactive transposition and speed determination based on canto, playlists, and community settings
    effect(() => {
      const c = this.canto();
      if (!c) return;

      const activePlaylistId = this.playlistService.activePlaylistId();
      let playlistSongSetting: any = null;
      if (activePlaylistId) {
        if (activePlaylistId.startsWith('remote_')) {
          const pl = this.playlistService.remotePlaylist();
          if (pl && pl.songSettings && pl.songSettings[c.id]) {
            playlistSongSetting = pl.songSettings[c.id];
          }
        } else {
          const pl = this.playlistService.playlists().find(p => p.id === activePlaylistId);
          if (pl && pl.songSettings && pl.songSettings[c.id]) {
            playlistSongSetting = pl.songSettings[c.id];
          }
        }
      }

      if (playlistSongSetting) {
        this.transposeAmount.set(playlistSongSetting.tonalita !== undefined ? playlistSongSetting.tonalita : 0);
        this.autoscrollSpeed.set(playlistSongSetting.speed !== undefined ? playlistSongSetting.speed : 2);
        if (playlistSongSetting.zoom !== undefined) {
          this.fontSize.set(playlistSongSetting.zoom);
          this.portraitFontSize = playlistSongSetting.zoom;
        } else {
          this.fontSize.set(1.0);
          this.portraitFontSize = 1.0;
        }
      } else if (this.comunitaService.comunitaCode() && this.comunitaService.isFilterActive()) {
        const settings = this.comunitaService.comunitaCantiSettings();
        const songSetting = settings.find(s => s.id_canti === c.id_canti || s.id_canti === Number(c.id));
        if (songSetting) {
          if (songSetting.tonalita !== undefined) {
            this.transposeAmount.set(songSetting.tonalita);
          } else {
            this.transposeAmount.set(0);
          }
          if (songSetting.speed !== undefined && songSetting.speed > 0) {
            const mappedSpeed = Math.max(1, Math.min(10, Math.round(songSetting.speed / 100)));
            this.autoscrollSpeed.set(mappedSpeed);
          } else {
            this.autoscrollSpeed.set(2);
          }
        } else {
          this.transposeAmount.set(0);
          this.autoscrollSpeed.set(2);
        }
        this.fontSize.set(1.0);
        this.portraitFontSize = 1.0;
      } else {
        this.transposeAmount.set(0);
        this.autoscrollSpeed.set(2);
        this.fontSize.set(1.0);
        this.portraitFontSize = 1.0;
      }
    }, { allowSignalWrites: true });

    // Fullscreen control in landscape mode
    effect(() => {
      const isLandscape = this.isLandscapeActive();
      
      if (isLandscape) {
        this.enterFullscreen();
      } else {
        this.exitFullscreen();
      }
    });
  }

  public isBlackScreen = signal<boolean>(false);

  @HostListener('window:resize', ['$event'])
  onResize(event: any) {
    this.windowLandscape.set(window.innerWidth > window.innerHeight);
    this.checkLandscapeZoom();
  }

  private isLandscape(): boolean {
    return this.isLandscapeActive();
  }

  private checkAndLimitFontSize(targetFont: number): number {
    if (!this.isLandscape()) {
      return targetFont;
    }
    const titleMain = this.el.nativeElement.querySelector('.title-main');
    if (!titleMain) return targetFont;

    const originalStyle = titleMain.style.fontSize;
    let bestFont = targetFont;

    // We want to find the largest font <= targetFont where the title stays on one line.
    // Let's iterate down from targetFont to 0.6 in steps of 0.05.
    for (let f = targetFont; f >= 0.6; f -= 0.05) {
      titleMain.style.fontSize = `${f * 1.1}rem`;
      
      // Force layout calculation
      const height = titleMain.clientHeight;
      // Get computed line height
      const computedStyle = window.getComputedStyle(titleMain);
      const lineHeightVal = computedStyle.lineHeight;
      let lh = parseFloat(lineHeightVal);
      
      // If line-height is 'normal', fallback to a reasonable estimate based on font-size
      if (isNaN(lh) || lineHeightVal === 'normal') {
        const fs = parseFloat(computedStyle.fontSize) || (f * 1.1 * 16);
        lh = fs * 1.25;
      }

      // If the actual height is less than 1.5 * line-height, it fits on one line!
      if (height <= lh * 1.5) {
        bestFont = f;
        break;
      }
      bestFont = f; // Fallback
    }

    // Restore original style
    titleMain.style.fontSize = originalStyle;
    return Math.max(0.6, parseFloat(bestFont.toFixed(2)));
  }

  public checkLandscapeZoom() {
    if (this.isLandscape()) {
      setTimeout(() => {
        const container = this.el.nativeElement.querySelector('.lyrics-container');
        if (!container) return;
        const visibleHeight = container.clientHeight;
        const lineElems = this.el.nativeElement.querySelectorAll('.lyric-line');
        if (lineElems.length > 0 && visibleHeight > 0) {
          let totalHeight = 0;
          lineElems.forEach((el: any) => {
            totalHeight += el.getBoundingClientRect().height;
          });
          const avgLineHeight = totalHeight / lineElems.length;
          if (avgLineHeight > 0) {
            const currentFont = this.fontSize();
            const margin = 16; // 1rem in pixels
            const targetLineHeight = Math.max(10, (visibleHeight / 3.1) - margin);
            const avgLineHeightAtFont1 = avgLineHeight / currentFont;
            const newFont = targetLineHeight / avgLineHeightAtFont1;
            
            const targetFont = Math.max(2.0, Math.min(3.0, newFont));
            let limitedFont = this.checkAndLimitFontSize(targetFont);
            if (limitedFont < 2.0) {
              limitedFont = 2.0;
            }
            this.fontSize.set(limitedFont);
            this.channel.postMessage({ type: 'SYNC_FONT', fontSize: this.fontSize() });
          }
        }
      }, 150);
    } else {
      this.fontSize.set(this.portraitFontSize);
      this.channel.postMessage({ type: 'SYNC_FONT', fontSize: this.portraitFontSize });
    }
  }

  deactivateBlackScreen() {
    this.isBlackScreen.set(false);
  }

  private async enterFullscreen() {
    try {
      const docEl = document.documentElement;
      if (docEl.requestFullscreen) {
        await docEl.requestFullscreen();
      } else if ((docEl as any).webkitRequestFullscreen) {
        await (docEl as any).webkitRequestFullscreen();
      } else if ((docEl as any).msRequestFullscreen) {
        await (docEl as any).msRequestFullscreen();
      }
    } catch (e) {
      console.warn('[PlayerPage] Failed to enter fullscreen:', e);
    }
  }

  private async exitFullscreen() {
    try {
      if (document.exitFullscreen) {
        if (document.fullscreenElement) {
          await document.exitFullscreen();
        }
      } else if ((document as any).webkitExitFullscreen) {
        if ((document as any).webkitFullscreenElement) {
          await (document as any).webkitExitFullscreen();
        }
      } else if ((document as any).msExitFullscreen) {
        if ((document as any).msFullscreenElement) {
          await (document as any).msExitFullscreen();
        }
      }
    } catch (e) {
      console.warn('[PlayerPage] Failed to exit fullscreen:', e);
    }
  }

  ngAfterViewInit() {
    this.checkLandscapeZoom();
    const gestureX = this.gestureCtrl.create({
      el: this.el.nativeElement,
      direction: 'x',
      gestureName: 'swipe-song-x',
      canStart: (ev) => {
        const target = ev.event.target as HTMLElement;
        return !target.closest('ion-footer') && !target.closest('ion-header');
      },
      onEnd: (ev) => {
        if (Math.abs(ev.deltaX) > 60) {
          if (ev.deltaX > 0) {
            this.prev();
          } else {
            this.next();
          }
        }
      }
    });
    gestureX.enable();

  }


  private getAllLines(): any[] {
    const sections = this.parsedSections();
    const allLines: any[] = [];
    for (const s of sections) {
      for (const l of s.lines) {
        allLines.push(l);
      }
    }
    return allLines;
  }

  ngOnInit() {
    this.route.queryParams.subscribe(async params => {
      let id = params['id'];
      if (params['t']) {
        this.initialStartTime = parseInt(params['t'], 10);
      }
      if (!id) {
        const checkStorage = async () => {
          let storage = this.cantiService.getStorage();
          while (!storage) {
            await new Promise(resolve => setTimeout(resolve, 50));
            storage = this.cantiService.getStorage();
          }
          const storedId = await storage.get('last_song_id');
          if (storedId && !this.activeSongId()) {
            this.activeSongId.set(storedId);
          }
        };
        checkStorage();
      } else {
        this.activeSongId.set(id);
      }
    });
  }



  onTouchStart(event: TouchEvent) {
    if (event.touches.length === 2) {
      this.initialPinchDistance = this.getDistance(event.touches[0], event.touches[1]);
      this.initialFontSize = this.fontSize();
    }
  }

  onTouchMove(event: TouchEvent) {
    if (event.touches.length === 2 && this.initialPinchDistance !== null) {
      event.preventDefault();
      const currentDistance = this.getDistance(event.touches[0], event.touches[1]);
      const ratio = currentDistance / this.initialPinchDistance;
      let newSize = this.initialFontSize * ratio;
      const minZ = this.minZoom();
      const maxZ = this.maxZoom();
      newSize = Math.max(minZ, Math.min(maxZ, newSize));
      let limited = this.checkAndLimitFontSize(newSize);
      if (this.isLandscape() && limited < 2.0) {
        limited = 2.0;
      }
      if (Math.abs(limited - this.fontSize()) > 0.01) {
        this.fontSize.set(limited);
        if (!this.isLandscape()) {
          this.portraitFontSize = limited;
        }
        this.channel.postMessage({ type: 'SYNC_FONT', fontSize: this.fontSize() });
      }
    }
  }

  onTouchEnd() {
    this.initialPinchDistance = null;
    this.updatePlaylistSettings();
  }


  private getDistance(t1: Touch, t2: Touch): number {
    return Math.sqrt(Math.pow(t1.clientX - t2.clientX, 2) + Math.pow(t1.clientY - t2.clientY, 2));
  }

  toggleChords() {
    this.showChords.update(v => !v);
    this.channel.postMessage({ type: 'SYNC_CHORDS', showChords: this.showChords() });
    this.transposeAmount.set(0);
    this.checkLandscapeZoom();
  }

  private updatePlaylistSettings() {
    const c = this.canto();
    if (c) {
      const dbSpeed = this.autoscrollSpeed() * 100;
      this.statsService.updateSongSettings(c.id_canti, this.transposeAmount(), dbSpeed);
      
      const activePlaylistId = this.playlistService.activePlaylistId();
      if (activePlaylistId) {
        if (activePlaylistId.startsWith('remote_')) {
          return;
        }
        this.playlistService.updatePlaylistSongSettings(
          activePlaylistId, 
          c.id, 
          this.transposeAmount(), 
          this.autoscrollSpeed(),
          this.fontSize()
        );
      }
    }
  }

  transposeUp() {
    this.transposeAmount.update(v => v + 1);
    this.updatePlaylistSettings();
  }

  transposeDown() {
    this.transposeAmount.update(v => v - 1);
    this.updatePlaylistSettings();
  }

  zoomIn() {
    const maxZ = this.maxZoom();
    if (this.fontSize() < maxZ) {
      const target = Math.min(this.fontSize() + this.FONT_STEP, maxZ);
      let limited = this.checkAndLimitFontSize(target);
      if (this.isLandscape() && limited < 2.0) {
        limited = 2.0;
      }
      if (limited !== this.fontSize()) {
        this.fontSize.set(limited);
        if (!this.isLandscape()) {
          this.portraitFontSize = limited;
        }
        this.channel.postMessage({ type: 'SYNC_FONT', fontSize: this.fontSize() });
        this.updatePlaylistSettings();
      }
    }
  }

  zoomOut() {
    const minZ = this.minZoom();
    if (this.fontSize() > minZ) {
      const target = Math.max(this.fontSize() - this.FONT_STEP, minZ);
      this.fontSize.set(target);
      if (!this.isLandscape()) {
        this.portraitFontSize = target;
      }
      this.channel.postMessage({ type: 'SYNC_FONT', fontSize: this.fontSize() });
      this.updatePlaylistSettings();
    }
  }

  toggleAudio() {
    if (this.youtubePlayerService.currentCantoId() === this.canto()?.id) {
      this.youtubePlayerService.togglePlayPause();
    } else {
      const c = this.canto();
      if (c) {
        this.playlistService.autoPlayPlaylist.set(true);
        this.initPlayer(c.id);
      }
    }
  }

  stopVideo(event?: Event) {
    if (event) event.stopPropagation();
    this.youtubePlayerService.stop();
    this.playlistService.autoPlayPlaylist.set(false);
  }

  onSeek(event: any) {
    this.youtubePlayerService.seekTo(event.detail.value);
  }

  restart() {
    this.currentLineIndex.set(0);
    this.youtubePlayerService.seekTo(0);
    this.channel.postMessage({ type: 'SYNC_INDEX', index: 0 });
    this.lastScrollBlock.set('start');
    setTimeout(() => {
      const scrollEl = this.el.nativeElement.querySelector('.lyrics-container');
      if (scrollEl) {
        scrollEl.scrollTop = 0;
      }
    }, 100);
  }

  public calculatePageStepSize(): number {
    try {
      const container = document.querySelector('.lyrics-container') as HTMLElement;
      if (!container) return 3; // Ritorno generico se il contenitore non è pronto

      const containerRect = container.getBoundingClientRect();
      const visibleTop = Math.max(containerRect.top, 0);
      let visibleBottom = Math.min(containerRect.bottom, window.innerHeight || document.documentElement.clientHeight);

      const footer = document.querySelector('ion-footer') as HTMLElement;
      if (footer) {
        const footerRect = footer.getBoundingClientRect();
        if (footerRect.height > 0 && window.getComputedStyle(footer).display !== 'none') {
          visibleBottom = Math.min(visibleBottom, footerRect.top);
        }
      }

      const floatingBar = document.querySelector('.floating-autoscroll-bar') as HTMLElement;
      if (floatingBar) {
        const barRect = floatingBar.getBoundingClientRect();
        if (barRect.height > 0 && window.getComputedStyle(floatingBar).display !== 'none') {
          visibleBottom = Math.min(visibleBottom, barRect.top);
        }
      }

      // Calcoliamo la reale altezza visibile
      const visibleHeight = Math.max(0, visibleBottom - visibleTop);

      const lineElems = document.querySelectorAll('.lyric-line');
      
      if (lineElems.length === 0) return 3;

      let totalHeight = 0;
      lineElems.forEach((el: any) => {
        totalHeight += el.clientHeight;
      });
      const avgLineHeight = totalHeight / lineElems.length;

      if (avgLineHeight <= 0) return 3;

      // Quante righe entrano effettivamente nella vista REALE non oscurata dello schermo
      const linesPerPage = Math.floor(visibleHeight / avgLineHeight);

      // Passo di scorrimento: una pagina intera pulita (zero sovrapposizione) per far sparire il testo precedente
      const pageStep = Math.max(1, linesPerPage);
      
      console.log('[PageScroll] Calcolo dinamico dello scorrimento a pagina (Area visibile depurata):', {
        visibleHeight,
        avgLineHeight,
        linesPerPage,
        pageStep
      });

      return pageStep;
    } catch (e) {
      console.warn('[PageScroll] Impossibile calcolare dinamicamente lo step di pagina:', e);
      return 3; // Fallback di emergenza
    }
  }

  public getVisibleLineIndices(): number[] {
    try {
      const container = document.querySelector('.lyrics-container') as HTMLElement;
      if (!container) return [];

      const containerRect = container.getBoundingClientRect();
      const visibleTop = Math.max(containerRect.top, 0);
      let visibleBottom = Math.min(containerRect.bottom, window.innerHeight || document.documentElement.clientHeight);

      // Sottrai l'altezza dell'eventuale footer o barra sovrapposti ad alto z-index
      const footer = document.querySelector('ion-footer') as HTMLElement;
      if (footer) {
        const footerRect = footer.getBoundingClientRect();
        if (footerRect.height > 0 && window.getComputedStyle(footer).display !== 'none') {
          visibleBottom = Math.min(visibleBottom, footerRect.top);
        }
      }

      const floatingBar = document.querySelector('.floating-autoscroll-bar') as HTMLElement;
      if (floatingBar) {
        const barRect = floatingBar.getBoundingClientRect();
        if (barRect.height > 0 && window.getComputedStyle(floatingBar).display !== 'none') {
          visibleBottom = Math.min(visibleBottom, barRect.top);
        }
      }

      const lineElems = document.querySelectorAll('.lyric-line');
      const visibleIndices: number[] = [];

      for (let i = 0; i < lineElems.length; i++) {
        const el = lineElems[i] as HTMLElement;
        const rect = el.getBoundingClientRect();

        // Consideriamo la riga visibile se la sua metà verticale è all'interno dei limiti visibili reali
        const lineMiddle = (rect.top + rect.bottom) / 2;
        if (lineMiddle >= visibleTop && lineMiddle <= visibleBottom) {
          visibleIndices.push(i);
        }
      }
      return visibleIndices;
    } catch (e) {
      console.warn('[PageScroll] Errore nel recupero degli indici delle righe visibili:', e);
      return [];
    }
  }

  private calculateNextPageStartIndex(): number {
    try {
      const container = document.querySelector('.lyrics-container') as HTMLElement;
      if (!container) return this.currentLineIndex() + 1;

      const containerRect = container.getBoundingClientRect();
      // Assicuriamoci che il limite inferiore non superi l'altezza reale della finestra
      let visibleBottom = Math.min(containerRect.bottom, window.innerHeight || document.documentElement.clientHeight);

      // Trova la posizione del footer o di qualunque elemento sovrapposto in fondo
      const footer = document.querySelector('ion-footer') as HTMLElement;
      if (footer) {
        const footerRect = footer.getBoundingClientRect();
        if (footerRect.height > 0 && window.getComputedStyle(footer).display !== 'none') {
          visibleBottom = Math.min(visibleBottom, footerRect.top);
        }
      }

      const floatingBar = document.querySelector('.floating-autoscroll-bar') as HTMLElement;
      if (floatingBar) {
        const barRect = floatingBar.getBoundingClientRect();
        if (barRect.height > 0 && window.getComputedStyle(floatingBar).display !== 'none') {
          visibleBottom = Math.min(visibleBottom, barRect.top);
        }
      }

      // Aumentiamo il margine di tolleranza a 24px (o più) per essere sicuri 
      // di non perdere mai una riga parzialmente coperta. Meglio rileggere una riga 
      // in cima alla pagina successiva che perderla completamente a causa dello zoom.
      const visibleLimitY = visibleBottom - 24;
      const lineElems = document.querySelectorAll('.lyric-line');
      
      const totalLines = this.getTotalLines();
      const currentIdx = this.currentLineIndex();

      // Scansiona le righe successive a quella attiva e trova la prima riga che non era COMPLETAMENTE visibile
      let foundNextIdx = -1;
      for (let i = currentIdx + 1; i < lineElems.length; i++) {
        const el = lineElems[i] as HTMLElement;
        const rect = el.getBoundingClientRect();
        
        // Se la parte inferiore della riga ricade sotto l'area di visualizzazione utile (coperta da footer/log)
        if (rect.bottom > visibleLimitY) {
          foundNextIdx = i;
          break;
        }
      }

      if (foundNextIdx !== -1) {
        // Overlap by 1 line to ensure the last visible line is repeated at the top of the next page
        const targetIdx = Math.max(currentIdx + 1, foundNextIdx - 1);
        console.log('[PageScroll] Riga coperta/tagliata in fondo rilevata. Nuova pagina inizierà con overlap a:', targetIdx);
        return targetIdx;
      }

      // Se tutto era perfettamente visibile, avanza dello step di pagina calcolato standard con 1 riga di overlap
      const step = this.calculatePageStepSize();
      const targetIdx = Math.max(currentIdx + 1, currentIdx + step - 1);
      return Math.min(totalLines - 1, targetIdx);
    } catch (e) {
      console.warn('[PageScroll] Errore nel calcolo dinamico dell\'indice della pagina successiva:', e);
      return this.currentLineIndex() + 1;
    }
  }

  next(isAutomatic: boolean = false, isVisual: boolean = false) {
    if (this.isBlackScreen()) {
      this.deactivateBlackScreen();
      return;
    }
    this.lastAdvanceTimestamp = Date.now();

    const totalLines = this.getTotalLines();
    const prevIdx = this.currentLineIndex();

    if (prevIdx < totalLines - 1) {
      let nextIdx: number;
      if (isAutomatic) {
        if (prevIdx === 0) {
          // Sulla prima pagina, avanziamo alla metà della pagina (inizio della seconda metà)
          const visibleIndices = this.getVisibleLineIndices();
          if (visibleIndices.length > 0) {
            const halfLength = Math.max(1, Math.ceil(visibleIndices.length / 2));
            nextIdx = Math.min(totalLines - 1, visibleIndices[halfLength] !== undefined ? visibleIndices[halfLength] : halfLength);
          } else {
            const pageSize = this.calculatePageStepSize();
            const halfPageSize = Math.max(1, Math.ceil(pageSize / 2));
            nextIdx = Math.min(totalLines - 1, prevIdx + halfPageSize);
          }
        } else {
          // Avanzamento acustico automatico: avanza l'intera pagina lasciando centrale la riga di riferimento
          nextIdx = this.calculateNextPageStartIndex();
        }
        this.lastScrollBlock.set('center');
      } else if ((this.settingsService.karaokePageScrollMode() || isVisual) && !this.isLandscapeActive()) {
        // Modalità manuale a pagine (o trigger visuale): calcolo analitico preciso per non perdere righe coperte
        nextIdx = this.calculateNextPageStartIndex();
        this.lastScrollBlock.set('start');
      } else {
        // Avanzamento riga per riga standard manuale
        nextIdx = prevIdx + 1;
        this.lastScrollBlock.set('center');
      }
      
      this.currentLineIndex.set(nextIdx);
      this.channel.postMessage({ type: 'SYNC_INDEX', index: nextIdx });
    }
  }

  // Metodi di validazione e freeze rimossi per migliorare affidabilità e prevenire blocchi permanenti

  prev(isVisual: boolean = false) {
    if (this.isBlackScreen()) {
      this.deactivateBlackScreen();
      return;
    }
    this.lastAdvanceTimestamp = Date.now();
    
    const prevIdx = this.currentLineIndex();
    if (prevIdx > 0) {
      const isPageMode = (this.settingsService.karaokePageScrollMode() || isVisual) && !this.isLandscapeActive();
      const stepSize = isPageMode ? this.calculatePageStepSize() : 1;
      const nextIdx = Math.max(0, prevIdx - stepSize);
      
      if (nextIdx === 0) {
        // Se torniamo all'inizio, allineiamo in alto
        this.lastScrollBlock.set('start');
      } else if (isPageMode) {
        this.lastScrollBlock.set('start');
      } else {
        this.lastScrollBlock.set('center');
      }
      
      this.currentLineIndex.set(nextIdx);
      this.channel.postMessage({ type: 'SYNC_INDEX', index: nextIdx });
    }
  }

  nextSong() {
    let list = this.playlistService.activeListIds();
    if (list.length === 0) {
      list = this.cantiService.canti().map(c => c.id);
    }
    
    const currentId = this.canto()?.id;
    if (!currentId) return;

    const index = list.indexOf(currentId);
    if (index >= 0 && index < list.length - 1) {
      const nextId = list[index + 1];
      if (this.isLandscapeActive()) {
        this.isBlackScreen.set(true);
      }
      this.router.navigate(['/player'], { queryParams: { id: nextId } });
    } else {
      this.playlistService.autoPlayPlaylist.set(false);
    }
  }

  prevSong() {
    let list = this.playlistService.activeListIds();
    if (list.length === 0) {
      list = this.cantiService.canti().map(c => c.id);
    }

    const currentId = this.canto()?.id;
    if (!currentId) return;

    const index = list.indexOf(currentId);
    if (index > 0) {
      const prevId = list[index - 1];
      if (this.isLandscapeActive()) {
        this.isBlackScreen.set(true);
      }
      this.router.navigate(['/player'], { queryParams: { id: prevId } });
    }
  }

  private goToSong(id: string) {
    this.router.navigate([], {
      relativeTo: this.route,
      queryParams: { id },
      queryParamsHandling: 'merge'
    });
    this.restart();
  }

  getTotalLines(): number {
    return this.parsedSections().reduce((acc, s) => acc + s.lines.length, 0);
  }

  isActiveLine(sectionIdx: number, lineIdx: number): boolean {
    let flatIdx = 0;
    for (let s = 0; s < this.parsedSections().length; s++) {
      for (let l = 0; l < this.parsedSections()[s].lines.length; l++) {
        if (s === sectionIdx && l === lineIdx) {
          return flatIdx === this.currentLineIndex();
        }
        flatIdx++;
      }
    }
    return false;
  }

  async openDisplay() {
    const url = this.router.serializeUrl(
      this.router.createUrlTree(['/display'], { queryParams: { id: this.canto()?.id } })
    );
    const absoluteUrl = window.location.origin + window.location.pathname + url;
    const win = window.open(absoluteUrl, '_blank', 'width=1024,height=768');
    if (!win) {
      const alert = await this.alertCtrl.create({
        header: 'Proiezione TV',
        message: 'Il browser ha bloccato l\'apertura della finestra. Vuoi copiare il link da inviare alla TV?',
        buttons: [
          { text: 'Annulla', role: 'cancel' },
          { text: 'Copia Link', handler: () => { this.copyToClipboard(absoluteUrl); } }
        ]
      });
      await alert.present();
    }
  }

  async copyToClipboard(text: string) {
    try {
      await navigator.clipboard.writeText(text);
      const toast = await this.toastCtrl.create({
        message: 'Link copiato negli appunti!',
        duration: 2000,
        position: 'top',
        color: 'secondary'
      });
      await toast.present();
    } catch (err) {}
  }

  openYoutube() {
    const videoId = this.cantiService.getYoutubeId(this.canto()?.link_youtube);
    if (videoId) {
      window.open(`https://www.youtube.com/watch?v=${videoId}`, '_blank');
    }
  }

  async editOrCloneCanto() {
    const c = this.canto();
    if (!c) return;

    if (
      this.settingsService.comunitaEnabled() &&
      this.settingsService.showEditor() &&
      this.comunitaService.comunitaCode() &&
      !c.id.startsWith('my_')
    ) {
      // Clone the song: Title: <original title>
      const clonedTitle = c.titolo;

      const clonedCanto = await this.myCantiService.saveCanto({
        titolo: clonedTitle,
        autore: c.autore,
        link_youtube: c.link_youtube,
        testo: c.testo || c.accordi || '',
        accordi: c.accordi || c.testo || '',
        id_momenti: c.id_momenti || []
      });

      // Redirect to the edit page for the newly cloned song
      this.router.navigate(['/propose-canto'], { queryParams: { editId: clonedCanto.id } });
    } else {
      // Standard edit path
      this.router.navigate(['/propose-canto'], { queryParams: { editId: c.id } });
    }
  }

  async shareCanto() {
    const c = this.canto();
    if (!c) return;

    const isStandard = !c.id.startsWith('my_') && !c.id.startsWith('remote_share_') && !c.nonValidato;

    try {
      let shareLink = '';
      if (isStandard) {
        shareLink = `https://www.canticristiani.it/?id=${c.id}`;
      } else {
        await this.playlistService.syncLocalDataToServer();
        const uid = this.settingsService.userUuid();
        shareLink = `https://www.canticristiani.it/?song-uid=${uid}&song-id=${c.id_canti}`;
      }

      let fileToShare: File | null = null;
      const thumbUrl = this.cantiService.getYoutubeThumb(c.link_youtube);
      
      // Try to fetch YouTube thumbnail first if available
      if (thumbUrl) {
        try {
          const response = await Promise.race([
            fetch(thumbUrl),
            new Promise<Response>((_, reject) => setTimeout(() => reject(new Error('Timeout')), 3000))
          ]);
          if (response.ok) {
            const blob = await response.blob();
            fileToShare = new File([blob], 'song_thumbnail.jpg', { type: 'image/jpeg' });
          }
        } catch (e) {
          console.warn('[Share] Failed to fetch YouTube thumbnail due to CORS or timeout:', e);
        }
      }

      // If no YouTube thumb or fetch failed, fallback to local canticristiani logo (favicon)
      if (!fileToShare) {
        try {
          const response = await fetch('assets/icon/favicon.png');
          if (response.ok) {
            const blob = await response.blob();
            fileToShare = new File([blob], 'canticristiani_logo.png', { type: 'image/png' });
          }
        } catch (e) {
          console.warn('[Share] Failed to fetch local logo:', e);
        }
      }

      const shareDataObj: any = {
        title: `Condividi Canto: ${c.titolo}`,
        text: isStandard
          ? `Ecco il canto "${c.titolo}" dall'app Canti Cristiani. Clicca sul link per aprirlo:\n\n`
          : `Ecco il canto "${c.titolo}" per l'app Canti Cristiani. Clicca sul link per aggiungerlo:\n\n`,
        url: shareLink
      };

      if (fileToShare && navigator.canShare && navigator.canShare({ files: [fileToShare] })) {
        shareDataObj.files = [fileToShare];
      }

      if (navigator.share) {
        await navigator.share(shareDataObj);
      } else {
        if (navigator.clipboard) {
          await navigator.clipboard.writeText(shareLink);
          const toast = await this.toastCtrl.create({
            message: 'Link di condivisione copiato negli appunti!',
            duration: 2500,
            color: 'success'
          });
          await toast.present();
        }
      }
    } catch (err) {
      console.error('Failed to share song', err);
    }
  }

  private initPlayer(id: string) {
    if (!this.youtubePlayerService.isPlayerSupported()) {
      return;
    }
    const startT = this.initialStartTime;
    this.initialStartTime = 0; // Reset
    
    this.youtubePlayerService.setMediaSessionCallbacks(
      () => this.nextSong(),
      () => this.prevSong()
    );

    this.youtubePlayerService.initPlayer(
      id, 
      startT,
      () => {
        if (this.playlistService.autoPlayPlaylist() && this.settingsService.autoAdvance()) {
          this.nextSong();
        } else {
          this.playlistService.autoPlayPlaylist.set(false);
        }
      },
      () => {
        if (this.playlistService.autoPlayPlaylist() && this.settingsService.autoAdvance()) {
          setTimeout(() => this.nextSong(), 1000);
        } else {
          this.playlistService.autoPlayPlaylist.set(false);
        }
      }
    );
  }

  togglePlaylistSelection() {
    const c = this.canto();
    if (c) {
      this.playlistService.toggleSongSelection(c.id);
    }
  }

  getCommunitySongNumber(canto: any): string | null {
    if (!canto) return null;
    if (!this.comunitaService.comunitaCode() || !this.comunitaService.isFilterActive()) return null;
    const cantiInfo = this.comunitaService.comunitaCantiInfo();
    const info = cantiInfo.find(x => x.id_canti === canto.id_canti || x.id_canti === Number(canto.id));
    return info && info.num_canto ? info.num_canto.toString() : null;
  }

  getMySongNumber(canto: any): number {
    if (!canto || !canto.id) return 0;
    const index = this.myCantiService.myCanti().findIndex(c => c.id === canto.id);
    return index !== -1 ? index + 1 : 0;
  }

  toggleAutoscroll() {
    if (this.isAutoscrolling()) {
      this.stopAutoscroll();
    } else {
      this.startAutoscroll();
    }
  }

  startAutoscroll() {
    this.isAutoscrolling.set(true);
    if (this.autoscrollTimer) clearInterval(this.autoscrollTimer);
    
    const scrollEl = this.el.nativeElement.querySelector('.lyrics-container');
    if (!scrollEl) return;

    this.autoscrollTimer = setInterval(() => {
      if (!this.isAutoscrolling()) {
        clearInterval(this.autoscrollTimer);
        return;
      }
      const step = this.autoscrollSpeed() * 0.25;
      scrollEl.scrollTop += step;
    }, 40);
  }

  stopAutoscroll() {
    this.isAutoscrolling.set(false);
    if (this.autoscrollTimer) {
      clearInterval(this.autoscrollTimer);
      this.autoscrollTimer = null;
    }
  }

  increaseAutoscrollSpeed() {
    this.autoscrollSpeed.update(s => Math.min(10, s + 1));
    this.updatePlaylistSettings();
  }

  decreaseAutoscrollSpeed() {
    this.autoscrollSpeed.update(s => Math.max(1, s - 1));
    this.updatePlaylistSettings();
  }

  private logPreviousSongTime() {
    const c = this.canto();
    if (c && this.songStartTime > 0) {
      const timeSpent = (Date.now() - this.songStartTime) / 1000;
      this.statsService.logSongView(c.id_canti, timeSpent);
      this.songStartTime = 0;
    }
  }

  toggleCameraNavigation() {
    if (this.enableCameraNavigation()) {
      this.stopCameraNavigation();
    } else {
      this.startCameraNavigation();
    }
  }

  startCameraNavigation() {
    this.enableCameraNavigation.set(true);
    
    setTimeout(async () => {
      const videoEl = document.querySelector('#face-preview-video') as HTMLVideoElement;
      if (videoEl) {
        try {
          await this.faceDetector.start(videoEl, (direction) => {
            console.log(`[PlayerPage] Head tilt trigger received: ${direction}`);
            if (direction === 'next') {
              this.next(false, true);
            } else {
              this.prev(true);
            }
          });
        } catch (e) {
          this.enableCameraNavigation.set(false);
          alert('Impossibile accedere alla fotocamera. Assicurati di aver concesso i permessi e di usare HTTPS.');
        }
      }
    }, 300);
  }

  stopCameraNavigation() {
    this.enableCameraNavigation.set(false);
    this.faceDetector.stop();
  }

  ngOnDestroy() {
    this.exitFullscreen();
    this.stopAutoscroll();
    this.logPreviousSongTime();
    this.stopCameraNavigation();
    this.channel.close();
  }
}
