// ===================================================================
// controller2.events.js — CORRIGIDO E SINCRONIZADO
// ===================================================================

(function(){

    function qs(sel){ return document.querySelector(sel); }

    function norm(s){
        if (!s) return "";
        return s.toLowerCase()
            .normalize("NFD").replace(/[\u0300-\u036f]/g,"")
            .replace(/[^\p{L}\p{N}\s]/gu,"")
            .replace(/\s+/g," ")
            .trim();
    }

    // ===============================================================
    // FALAR CARD
    // ===============================================================
    window.speakCardText = async function(card, skipAutoAdvance){

        if (window.dialogState && window.dialogState.started && typeof window.getCardOwner === 'function' && window.CARDS_DATA) {
            const idx = parseInt(card.id.replace('card-', ''));
            const validCards = window.CARDS_DATA
                .map((_, i) => document.getElementById('card-' + i))
                .filter(c => c && !c.classList.contains('ignored'));

            const lastValid = validCards.length ? validCards[validCards.length - 1] : null;

            if (lastValid && card === lastValid && window.getCardOwner(idx) === 'system') {
                const modal = document.getElementById('dialogoModal');
                if (modal) {
                    let beepCount = 0;
                    function beepAndShow(){
                        if (beepCount < 5){
                            window.playBeep?.();
                            beepCount++;
                            setTimeout(beepAndShow, 350);
                        } else {
                            modal.style.display = 'flex';
                            setTimeout(()=>modal.style.display='none', 5000);
                        }
                    }
                    beepAndShow();
                }
            }
        }

        card?.scrollIntoView?.({ behavior:"smooth", block:"center" });

        async function afterSpeak(){
            if (!skipAutoAdvance && window.dialogState?.started){
                const idx = parseInt(card.id.replace("card-",""));
                const nextOwner = window.getCardOwner(idx+1);
                if (nextOwner === 'human'){
                    const nextCard = document.getElementById('card-'+(idx+1));
                    if (nextCard){
                        window.SttEngine?.stop?.();
                        window.handleCardMic(nextCard);
                    }
                }
            }
        }

        if (window.dialogState && window.dialogState.started === false && window.chkNodoDialogo?.checked){
            const idx = parseInt(card.id.replace("card-",""));
            if (idx === 0){
                window.startDialog('system');
                if (window.getCardOwner(0) === 'system'){
                    incrementCardCounter(card);
                }
            }
        }

        window.UI?.setManualCurrent?.(card);

        const fromText = card.dataset.from;
        const toText   = card.dataset.to;

        const rate     = parseFloat(qs("#selTtsRate")?.value || "1");
        const interval = parseInt(qs("#selAutoInterval")?.value || "2000");

        const langFrom = LANGS_BCP[window.FROM];
        const langTo   = LANGS_BCP[window.TO];

        async function speakWithHighlight(text, opts){
            card.classList.add('card-speaking');
            card.classList.remove('card-spoken');
            try {
                await TtsEngine.speak(text, opts);
            } finally {
                card.classList.remove('card-speaking');
                card.classList.add('card-spoken');
            }
        }

        if (window._speakFromFirst && fromText){
            await speakWithHighlight(fromText,{ langTag:langFrom, rate });
            await new Promise(r=>setTimeout(r, interval));
        }
        if (toText){
            await speakWithHighlight(toText,{ langTag:langTo, rate });
        }

        if (window.dialogState?.started){
            const idx = parseInt(card.id.replace("card-",""));
            if (window.getCardOwner(idx) === 'system'){
                incrementCardCounter(card);
            }
        }

        await afterSpeak();
    };

    // ===============================================================
    // MIC DO CARD
    // ===============================================================
    window.handleCardMic = function(card){

        document.querySelectorAll('.card-mic-active')
            .forEach(c=>c.classList.remove('card-mic-active'));

        card?.classList.add('card-mic-active');

        if (window.dialogState?.started){
            const idx = parseInt(card.id.replace("card-",""));
            if (window.getCardOwner(idx) === 'human'){
                card.classList.add('card-mic-persist');
            }
        }

        card?.scrollIntoView?.({ behavior:"smooth", block:"center" });

        if (window.dialogState && window.dialogState.started === false && window.chkNodoDialogo?.checked){
            const idx = parseInt(card.id.replace("card-",""));
            if (idx === 0){
                window.startDialog('human');
            }
        }

        if (window.AutoPlayer?.running) window.AutoPlayer.stop();

        const rec = card.querySelector(".card-recognized");
        if (rec) rec.textContent = "";

        SttEngine.start(LANGS_BCP[window.TO]);
        UI.toast("🎤 Fale agora…");

        let micBuffer = "";
        let micTimer  = null;

        SttEngine.onFinal = (txt)=>{
            card.classList.remove('card-mic-active');
            const idx = parseInt(card.id.replace("card-",""));
            micBuffer = (micBuffer + " " + txt).trim();
            if (micTimer) clearTimeout(micTimer);
            const waitTime = window.chkNodoDialogo?.checked ? 2000 : 1000;
            micTimer = setTimeout(()=>{
                const finalText = micBuffer;
                micBuffer = "";
                micTimer = null;
                SttEngine.stop();
                UI.updateHeardFooter(LANGS[window.TO], finalText);
                const globalMicEnabled = window.chkMicGlobal?.checked;
                if (window.fuzzyMatch(finalText, card.dataset.to)){
                    card.classList.add("hit");
                    card.classList.remove("blue");
                    incrementCardCounter(card);
                    window.playSuccessBeep?.();
                    if (rec) rec.textContent = finalText;
                    UI.toast("✅ Acertou!!!");
                    const nextCard = document.getElementById('card-'+(idx+1));
                    const nextOwner = window.getCardOwner ? window.getCardOwner(idx+1) : null;
                    if (nextCard && nextOwner){
                        if (nextOwner === 'system'){
                            setTimeout(()=>window.speakCardText(nextCard),600);
                        } else {
                            setTimeout(()=>window.handleCardMic(nextCard),600);
                        }
                    }
                    if (globalMicEnabled){
                        setTimeout(()=>window.handleCardMic(card),600);
                    }
                } else {
                    card.classList.add("blue");
                    card.classList.remove("hit");
                    if (rec) rec.textContent = finalText;
                    window.playErrorBeep?.();
                    UI.toast("❌ Não corresponde.",1500);
                    if (globalMicEnabled){
                        setTimeout(()=>window.handleCardMic(card),600);
                    }
                }
                UI.updateStats();
            }, waitTime);
        };
    };

    // ===============================================================
    // CONTADOR FINAL
    // ===============================================================
    window.incrementCardCounter = function(card){
        if (!window.HIT_TARGET) return;
        const index = parseInt(card.id.replace("card-",""));
        const obj = window.CARDS_DATA[index];
        if (!obj) return;
        obj._count = (obj._count || 0) + 1;
        UI.refreshCounters?.();
    };

    // ===============================================================
    // REDESENHAR
    // ===============================================================
    window.redrawCards = function(){
        const cards = CardsRepo.getAll();
        UI.renderCards(cards,{ fromKey:window.FROM, toKey:window.TO });
        UI.updateShowPT(qs("#chkShowPT")?.checked);
        UI.updateShowLang(qs("#chkShowLang")?.checked);
        UI.updateStats();
    };

    // ===============================================================
    // BEEPS
    // ===============================================================
    window.playBeep = function(){
        const a = document.getElementById("beep1");
        if (!a) return;
        a.pause(); a.currentTime = 0; a.volume = 0.45;
        a.play().catch(()=>{});
    };

    window.playSuccessBeep = function(){
        let a = document.getElementById("beep-success");
        if (!a){
            a = document.createElement("audio");
            a.id="beep-success"; a.src="ui/beep-success.mp3";
            document.body.appendChild(a);
        }
        a.pause(); a.currentTime=0; a.volume=0.55;
        a.play().catch(()=>window.playBeep());
    };

    window.playErrorBeep = function(){
        let a = document.getElementById("beep-error");
        if (!a){
            a = document.createElement("audio");
            a.id="beep-error"; a.src="ui/beep-error.mp3";
            document.body.appendChild(a);
        }
        a.pause(); a.currentTime=0; a.volume=0.55;
        a.play().catch(()=>window.playBeep());
    };

    // ===============================================================
    // AUTOPLAY / CONTROLES
    // ===============================================================
    window.speakNextCard = function(){
        const cards = UI.getVisibleCards();
        if (!cards.length) return UI.toast("Nenhum CARD disponível.");
        const current = document.querySelector(".autoplay-current");
        const next = current ? cards[cards.indexOf(current)+1] : cards[0];
        if (!next) return UI.toast("🙌 Chegou ao último CARD.");
        UI.setAutoplayCurrent(next);
        speakCardText(next);
    };

    window.nextAndSpeak = function(){
        window.speakNextCard();
    };

    window.speakNextFrom = function(card){
        const cards = UI.getVisibleCards();
        const idx = cards.indexOf(card);
        if (!cards[idx+1]) return UI.toast("🙌 Último CARD alcançado.");
        UI.setAutoplayCurrent(cards[idx+1]);
        speakCardText(cards[idx+1]);
    };

    window.repeatCurrentCard = function(){
        let card = document.querySelector(".autoplay-current")
            || document.querySelector(".card.spoken, .card.hit, .card.blue")
            || UI.getVisibleCards()[0];
        if (!card) return UI.toast("Nenhum CARD para repetir.");
        speakCardText(card);
    };

})();
