class LyricsSystem {
    constructor() {
        this.lyrics = [];
        this.currentLyricIndex = -1;
        this.showLyrics = true; // Mostrar letras por defecto
        this.font = null;
        this.songDuration = 189; // 3:09 en segundos
        this.isGameOver = false;
        this.gameOverScreen = false;
        this.fadeOpacity = 1.0;
        this.fadeDirection = 1; // 1 para aparecer, -1 para desaparecer
        
        // Offset de tiempo para ajustar sincronización (en segundos)
        // Valor positivo = letras aparecen ANTES
        // Valor negativo = letras aparecen DESPUÉS
        this.timeOffset = 0.2;
        
        // Configuración de texto
        this.maxLineWidth = 280; // Ancho máximo de línea en píxeles (original)
        this.lineHeight = 18; // Altura entre líneas (original)
        
        // Cargar la fuente personalizada
        this.loadCustomFont();
        
        // Parsear las letras desde el archivo
        this.parseLyrics();
    }
    
    loadCustomFont() {
        this.font = new FontFace('CustomFont', 'url(assets/font.ttf)');
        this.font.load().then(() => {
            document.fonts.add(this.font);
        }).catch(err => {
            console.warn('No se pudo cargar la fuente personalizada:', err);
        });
    }
    
    parseLyrics() {
        // Letras en romaji usando los tiempos exactos del archivo
        const lyricsData = [
            { time: 2.8, text: "mogumogu" },
            { time: 6.4, text: "shinra banshou no akusenkutou mo mayoneizpu kaketara daitai oishiku naru?" },
            { time: 13.3, text: "kimi ga naite mo onaka wa suku yo shouka dekinakatta \"gomen gomen\"" },
            { time: 19.8, text: "sui mo amai mo katte ni tabete gomeiwaku okakeshite imasu" },
            { time: 26.7, text: "pakuchii na okite hen na aji no juusu kokoro wo mu ni shite nomikomimasu" },
            { time: 33.3, text: "aa konton jouhou kata no resutoran de usoppachi no menyuu ni ocha koboshite" },
            { time: 39.8, text: "kimi to mogumogu (mogumogu) mogumogu (mogumogu)" },
            { time: 43, text: "juugeki-sen no mannaka de mogumogu (ugya～)" },
            { time: 46, text: "chimi mouryou harapeko no mure manpuku ni naru mirai wo negatteiru yo" },
            { time: 53, text: "mogumogu (mogumogu) mogumogu (mogumogu) sekai ga owaru mae ni" },
            { time: 59, text: "mogumogu yamii maji kami yamuyamu ari no manma" },
            { time: 66, text: "mogumogu yamii Magic Coming konoyo wo ajiwaun da umauma" },
            { time: 77, text: "" },
            { time: 80, text: "riron busou no mirufiiyu sando (sando)" },
            { time: 83, text: "tokumei kibou no ourora sousu (sousu)" },
            { time: 87, text: "oozappa na ajitsuke oome ni mite yo oishiku nattara \"ok ok.\"" },
            { time: 93, text: "ii mon warui mon ippai tabete yogoreta kuchimoto nuguimasu" },
            { time: 100, text: "onigiri piza keiki gouka na furu kousu wana wo utagai ki wo tsukemasu" },
            { time: 106, text: "aa mousou ryuugen higo no baikingu de dokuiri to zeppin ryouri yoriwakete" },
            { time: 113, text: "kimi to mogumogu (mogumogu) mogumogu (mogumogu)" },
            { time: 117, text: "desugeimu no kyoushitsu de mogumogu (ugya～)" },
            { time: 120, text: "chimi mouryou harapeko no mure naka no ii kimi to ikinokoretara ii na" },
            { time: 127, text: "mogumogu (mogumogu) mogumogu (mogumogu) suu nen-go mo kono basho de" },
            { time: 133, text: "mogumogu yamii maji kami kon'ya no bangohan wa" },
            { time: 139, text: "mogumogu yamii Magic Coming tsugi wa omae no ban da" },
            { time: 146, text: "mogumogu yamii maji kami yamuyamu ari no manma" },
            { time: 152, text: "mogumogu yamii Magic Coming konoyo wo ajiwaun da umauma" },
            { time: 160, text: "" },
            { time: 162, text: "mogumogu mogumogu mogumogu mogumogu mogumogu mogumogu mogumogu yamii" },
            { time: 168, text: "mogumogu mogumogu mogumogu mogumogu mogumogu mogumogu mogumogu yamii" },
            { time: 175, text: "mogumogu mogumogu mogumogu mogumogu mogumogu mogumogu mogumogu yamii" },
            { time: 181, text: "mogumogu mogumogu mogumogu mogumogu"},
            { time: 187, text: "yamii yamii" }
        ];
        
        this.lyrics = lyricsData;
    }
    
    update(currentTime) {
        // Aplicar offset de tiempo
        const adjustedTime = currentTime + this.timeOffset;
        
        // Verificar si la canción ha terminado
        if (adjustedTime >= this.songDuration && !this.isGameOver) {
            this.isGameOver = true;
            this.gameOverScreen = true;
            this.showLyrics = false; // Ocultar letras cuando termine la canción
            return;
        }
        
        // Actualizar letra actual basada en el tiempo ajustado
        this.updateCurrentLyric(adjustedTime);
    }
    
    updateCurrentLyric(currentTime) {
        let newIndex = -1;
        
        for (let i = 0; i < this.lyrics.length; i++) {
            if (currentTime >= this.lyrics[i].time) {
                newIndex = i;
            } else {
                break;
            }
        }
        
        if (newIndex !== this.currentLyricIndex) {
            this.currentLyricIndex = newIndex;
        }
    }
    
    draw(ctx, canvas) {
        if (!this.showLyrics && this.fadeOpacity <= 0) return;
        
        // Actualizar opacidad para transición suave
        if (this.showLyrics && this.fadeOpacity < 1.0) {
            this.fadeOpacity += 0.05;
        } else if (!this.showLyrics && this.fadeOpacity > 0) {
            this.fadeOpacity -= 0.05;
        }
        
        // Dibujar letra actual
        if (this.currentLyricIndex >= 0 && this.currentLyricIndex < this.lyrics.length) {
            const currentLyric = this.lyrics[this.currentLyricIndex];
            
            // Configurar fuente (original)
            ctx.font = '14px CustomFont, Arial, sans-serif';
            ctx.fillStyle = `rgba(255, 255, 255, ${this.fadeOpacity})`;
            ctx.textAlign = 'center';
            
            // Dividir texto en líneas
            const lines = this.wrapText(currentLyric.text, ctx, this.maxLineWidth);
            
            // Calcular posición Y inicial (original for 320x240)
            const totalHeight = lines.length * this.lineHeight;
            const startY = canvas.height - 180 - (totalHeight - this.lineHeight);
            

            // Dibujar cada línea
            lines.forEach((line, index) => {
                const x = canvas.width / 2;
                const y = startY + (index * this.lineHeight);
                
                ctx.strokeText(line, x, y);
                ctx.fillText(line, x, y);
            });
            
            // Resetear sombra
            ctx.shadowColor = 'transparent';
            ctx.shadowBlur = 0;
            ctx.shadowOffsetX = 0;
            ctx.shadowOffsetY = 0;
        }
        

    }
    
    toggleLyrics() {
        this.showLyrics = !this.showLyrics;
        this.fadeDirection = this.showLyrics ? 1 : -1;
    }

    // Método para dividir texto en líneas
    wrapText(text, ctx, maxWidth) {
        const words = text.split(' ');
        const lines = [];
        let currentLine = words[0];
        
        for (let i = 1; i < words.length; i++) {
            const word = words[i];
            const width = ctx.measureText(currentLine + ' ' + word).width;
            
            if (width < maxWidth) {
                currentLine += ' ' + word;
            } else {
                lines.push(currentLine);
                currentLine = word;
            }
        }
        
        lines.push(currentLine);
        return lines;
    }
    
    // Método para desarrollo: simular fin de canción
    simulateGameOver() {
        this.isGameOver = true;
        this.gameOverScreen = true;
    }
    
    // Método para reiniciar el juego
    reset() {
        this.currentLyricIndex = -1;
        this.isGameOver = false;
        this.gameOverScreen = false;
        this.showLyrics = true;
        this.fadeOpacity = 1.0;
        this.timeOffset = 0; // Resetear offset
    }
}