import { Component, OnInit, OnDestroy, signal, computed, effect, inject, ElementRef, AfterViewInit } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } 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 { AudioEngineService } from '../../services/audio-engine.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';

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

  /** true = show chords (accordi mode), false = text only */
  public showChords = signal<boolean>(false);
  public showSensitivitySlider = 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('[');
    
    if ((this.showChords() && c.accordi) || (this.showChords() && 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 (this.showChords()) {
      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;

  private initialPinchDistance: number | null = null;
  private initialFontSize: 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 wordsSpokenInCurrentPage: number = 0;
  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 audioEngine = inject(AudioEngineService);
  private 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);

  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 });

    // Avanzamento guidato dai picchi acustici con conteggio parole della riga in corso
    effect(() => {
      const count = this.audioEngine.linesDetected();
      if (count > 0 && this.audioEngine.isListening()) {
        this.handleAcousticPeak();
      }
    });

    // Avanzamento in tempo reale tramite riconoscimento vocale di prossimità (driver primario veloce)
    effect(() => {
      const transcript = this.audioEngine.backgroundTranscript();
      const isSpeechActive = this.audioEngine.speechRecognitionActive();
      if (transcript && this.audioEngine.isListening() && isSpeechActive) {
        this.checkWordAdvancement();
      }
    });

    // 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 = comunitaCantiPers.find(c => c.id === id);
        }

        if (found) {
          const current = this.canto();
          // Avoid duplicate triggers for the same song
          if (!current || current.id !== found.id) {
            this.logPreviousSongTime();
            this.canto.set(found);
            this.songStartTime = Date.now();
            this.cantiService.getStorage()?.set('last_song_id', id);
            this.channel.postMessage({ type: 'SYNC_CANTO', id: found.id });
          }
        }
      }
    }, { 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) {
        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);
      } 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);
        }
      } else {
        this.transposeAmount.set(0);
        this.autoscrollSpeed.set(2);
      }
    }, { allowSignalWrites: true });
  }

  ngAfterViewInit() {
    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();

    const gestureY = this.gestureCtrl.create({
      el: this.el.nativeElement,
      direction: 'y',
      gestureName: 'swipe-song-y',
      canStart: (ev) => {
        const target = ev.event.target as HTMLElement;
        return !target.closest('ion-footer') && !target.closest('ion-header');
      },
      onEnd: (ev) => {
        if (Math.abs(ev.deltaY) > 50) {
          if (ev.deltaY > 0) {
            this.prev();
          } else {
            this.next();
          }
        }
      }
    });
    gestureY.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;
      newSize = Math.max(this.MIN_FONT, Math.min(this.MAX_FONT, newSize));
      if (Math.abs(newSize - this.fontSize()) > 0.01) {
        this.fontSize.set(newSize);
        this.channel.postMessage({ type: 'SYNC_FONT', fontSize: this.fontSize() });
      }
    }
  }

  onTouchEnd() {
    this.initialPinchDistance = null;
  }

  private lastWheelTime = 0;
  private readonly WHEEL_COOLDOWN = 400; // ms to avoid too rapid advancement

  onWheel(event: WheelEvent) {
    event.preventDefault();
    const now = Date.now();
    if (now - this.lastWheelTime < this.WHEEL_COOLDOWN) {
      return;
    }
    if (Math.abs(event.deltaY) > 5) {
      if (event.deltaY > 0) {
        this.next();
      } else {
        this.prev();
      }
      this.lastWheelTime = now;
    }
  }

  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);
  }

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

    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) {
        this.playlistService.updatePlaylistSongSettings(activePlaylistId, c.id, this.transposeAmount(), this.autoscrollSpeed());
      }
    }
  }

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

    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) {
        this.playlistService.updatePlaylistSongSettings(activePlaylistId, c.id, this.transposeAmount(), this.autoscrollSpeed());
      }
    }
  }

  zoomIn() {
    if (this.fontSize() < this.MAX_FONT) {
      this.fontSize.update(v => Math.min(v + this.FONT_STEP, this.MAX_FONT));
      this.channel.postMessage({ type: 'SYNC_FONT', fontSize: this.fontSize() });
    }
  }

  zoomOut() {
    if (this.fontSize() > this.MIN_FONT) {
      this.fontSize.update(v => Math.max(v - this.FONT_STEP, this.MIN_FONT));
      this.channel.postMessage({ type: 'SYNC_FONT', fontSize: this.fontSize() });
    }
  }

  toggleListening() {
    if (this.audioEngine.isListening()) {
      this.audioEngine.stopListening();
      this.showSensitivitySlider.set(false);
    } else {
      this.audioEngine.startListening();
      this.showSensitivitySlider.set(true);
    }
  }

  toggleSensitivitySlider(event: Event) {
    event.stopPropagation();
    this.showSensitivitySlider.update(v => !v);
  }

  onSensitivityChange(event: any) {
    this.audioEngine.sensitivity.set(event.detail.value);
  }

  handleSensitivityTouch(event: TouchEvent) {
    event.preventDefault();
    const touch = event.touches[0];
    const target = event.currentTarget as HTMLElement;
    const rect = target.getBoundingClientRect();
    
    // Calculate percentage based on Y position (bottom is 50%, top is 100%)
    const rawPercentage = 100 - ((touch.clientY - rect.top) / rect.height * 100);
    // Map 0-100 raw to 50-100 range
    let percentage = 50 + (rawPercentage * 0.5);
    percentage = Math.max(50, Math.min(100, Math.round(percentage)));
    
    this.audioEngine.sensitivity.set(percentage);
  }

  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.audioEngine.resetWordCount();
    this.youtubePlayerService.seekTo(0);
    this.channel.postMessage({ type: 'SYNC_INDEX', index: 0 });
    this.wordsSpokenInCurrentPage = 0;
    this.lastScrollBlock.set('center');
  }

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

      const containerHeight = container.clientHeight;
      
      // Calcoliamo la reale altezza visibile sottraendo l'eventuale footer in sovraimpressione
      let visibleHeight = containerHeight;
      const footer = document.querySelector('ion-footer') as HTMLElement;
      if (footer && footer.offsetHeight > 0) {
        const computedStyle = window.getComputedStyle(footer);
        if (computedStyle.display !== 'none') {
          visibleHeight -= footer.offsetHeight;
        }
      }

      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):', {
        containerHeight,
        visibleHeight,
        avgLineHeight,
        linesPerPage,
        pageStep
      });

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

  private getLineWords(lineIndex: number): string[] {
    const allLines = this.getAllLines();
    const lineText = allLines[lineIndex]?.text || '';
    return lineText
      .toLowerCase()
      .split(/\s+/)
      .map((w: string) => w.replace(/[^a-zA-Z0-9àèìòùáéíóú]/g, ''))
      .filter((w: string) => w.length >= 3);
  }

  public getPageWords(startIndex: number, pageSize: number): string[] {
    const allWords: string[] = [];
    const totalLines = this.getTotalLines();
    const end = Math.min(totalLines, startIndex + pageSize);
    for (let i = startIndex; i < end; i++) {
      allWords.push(...this.getLineWords(i));
    }
    return allWords;
  }

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

      const containerRect = container.getBoundingClientRect();
      const visibleTop = containerRect.top;
      let visibleBottom = containerRect.bottom;

      // Sottrai l'altezza dell'eventuale footer sovrapposto 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 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 [];
    }
  }

  public getPageTargetWordCount(): number {
    const visibleIndices = this.getVisibleLineIndices();
    let totalRawWords = 0;
    const currentIdx = this.currentLineIndex();

    if (visibleIndices.length > 0) {
      if (currentIdx === 0) {
        // Sulla prima pagina, contiamo solo la prima metà delle righe visibili
        // per far avanzare l'applicazione non appena si arriva a metà della prima schermata
        const halfLength = Math.max(1, Math.ceil(visibleIndices.length / 2));
        for (let i = 0; i < halfLength; i++) {
          const idx = visibleIndices[i];
          totalRawWords += this.getLineRawWordCount(idx);
        }
      } else {
        // Dalla seconda pagina in poi, contiamo solo le righe attive e future (escludendo il testo già cantato in alto)
        for (const idx of visibleIndices) {
          if (idx >= currentIdx) {
            totalRawWords += this.getLineRawWordCount(idx);
          }
        }
      }
    } else {
      // Fallback: calcolo teorico basato sulla pagina corrente
      const pageSize = this.calculatePageStepSize();
      const totalLines = this.getTotalLines();
      
      let end: number;
      if (currentIdx === 0) {
        // Fallback prima pagina: metà delle righe della pagina teorica
        const halfPageSize = Math.max(1, Math.ceil(pageSize / 2));
        end = Math.min(totalLines, currentIdx + halfPageSize);
      } else {
        end = Math.min(totalLines, currentIdx + pageSize);
      }

      for (let i = currentIdx; i < end; i++) {
        totalRawWords += this.getLineRawWordCount(i);
      }
    }

    // Soglia al 70% delle parole contate nella schermata visibile
    return Math.max(1, Math.ceil(totalRawWords * 0.70));
  }

  private checkWordAdvancement() {
    const now = Date.now();
    
    // Cooldown per prevenire avanzamenti multipli troppo veloci
    if (now - this.lastAdvanceTimestamp < this.ADVANCE_COOLDOWN) {
      return;
    }

    const currentIdx = this.currentLineIndex();
    let nextPageIdx: number;
    const totalLines = this.getTotalLines();

    if (currentIdx === 0) {
      // Sulla prima pagina, la "pagina successiva" è in realtà la seconda metà della prima schermata
      const visibleIndices = this.getVisibleLineIndices();
      if (visibleIndices.length > 0) {
        const halfLength = Math.max(1, Math.ceil(visibleIndices.length / 2));
        nextPageIdx = visibleIndices[halfLength] !== undefined ? visibleIndices[halfLength] : halfLength;
      } else {
        const pageSize = this.calculatePageStepSize();
        const halfPageSize = Math.max(1, Math.ceil(pageSize / 2));
        nextPageIdx = currentIdx + halfPageSize;
      }
    } else {
      nextPageIdx = this.calculateNextPageStartIndex();
    }

    if (nextPageIdx >= totalLines) return;

    const pageSize = this.calculatePageStepSize();

    // Raccoglie le parole del blocco successivo (metà pagina se siamo all'inizio, altrimenti intera pagina)
    const nextPageWords = this.getPageWords(nextPageIdx, currentIdx === 0 ? Math.max(1, Math.ceil(pageSize / 2)) : pageSize);
    if (nextPageWords.length === 0) return;

    // Parole rilevate di recente (con tolleranza di ritardo della Speech API)
    const recentWords = this.audioEngine.getRecentWordsSince(this.lastAdvanceTimestamp);

    // Controlla se l'utente ha cantato parole della pagina successiva -> Avanzamento istantaneo immediato
    const matchNext = nextPageWords.some(word => recentWords.includes(word));
    if (matchNext) {
      console.log(`[SmartKaraoke] Parola chiave del blocco successivo rilevata! Avanzamento immediato a: ${nextPageIdx}`);
      this.lastScrollBlock.set('center');
      this.currentLineIndex.set(nextPageIdx);
      this.channel.postMessage({ type: 'SYNC_INDEX', index: nextPageIdx });
      this.lastAdvanceTimestamp = now;
      this.audioEngine.resetWordCount();
      this.wordsSpokenInCurrentPage = 0;
    }
  }

  public getLineRawWordCount(lineIndex: number): number {
    const allLines = this.getAllLines();
    const lineText = allLines[lineIndex]?.text || '';
    const words = lineText.trim().split(/\s+/).filter((w: string) => w.length > 0);
    return words.length;
  }

  public getLineTargetWordCount(lineIndex: number): number {
    const rawCount = this.getLineRawWordCount(lineIndex);
    // Soglia proporzionale tollerante (65% del conteggio parole effettivo) per compensare legature melodiche
    return Math.max(1, Math.ceil(rawCount * 0.65));
  }

  private handleAcousticPeak() {
    const targetWordCount = this.getPageTargetWordCount();
    
    this.wordsSpokenInCurrentPage++;
    console.log(`[PeakAdvance] Peak detected. Spoken words on page: ${this.wordsSpokenInCurrentPage}/${targetWordCount}`);

    if (this.wordsSpokenInCurrentPage >= targetWordCount) {
      console.log(`[PeakAdvance] Target page word count reached (${targetWordCount}). Advancing page.`);
      this.next(true);
    }
  }

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

      const containerRect = container.getBoundingClientRect();
      let visibleBottom = containerRect.bottom;

      // 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);
        }
      }

      // Sottrai un piccolo margine di tolleranza di 8px
      const visibleLimitY = visibleBottom - 8;
      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) {
        console.log('[PageScroll] Riga coperta/tagliata in fondo rilevata. Diventerà la prima riga della nuova pagina:', foundNextIdx);
        return foundNextIdx;
      }

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

  next(isAutomatic: boolean = false) {
    this.lastAdvanceTimestamp = Date.now();
    this.audioEngine.resetWordCount();
    this.wordsSpokenInCurrentPage = 0;

    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()) {
        // Modalità manuale a pagine: 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() {
    this.lastAdvanceTimestamp = Date.now();
    this.audioEngine.resetWordCount();
    this.wordsSpokenInCurrentPage = 0;
    
    const prevIdx = this.currentLineIndex();
    if (prevIdx > 0) {
      const isPageMode = this.settingsService.karaokePageScrollMode();
      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];
      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];
      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');
    }
  }

  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;
  }

  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));
    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) {
        this.playlistService.updatePlaylistSongSettings(activePlaylistId, c.id, this.transposeAmount(), this.autoscrollSpeed());
      }
    }
  }

  decreaseAutoscrollSpeed() {
    this.autoscrollSpeed.update(s => Math.max(1, s - 1));
    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) {
        this.playlistService.updatePlaylistSongSettings(activePlaylistId, c.id, this.transposeAmount(), this.autoscrollSpeed());
      }
    }
  }

  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;
    }
  }

  ngOnDestroy() {
    this.stopAutoscroll();
    this.logPreviousSongTime();
    this.audioEngine.stopListening();
    this.channel.close();
  }
}
