// Resistiré - UI Overlays (Focus trap, screen reader, fin de juego)

// --- FOCUS TRAP SYSTEM (WCAG) ---
let lastFocusedElement = null;
let activeModal = null;

function saveFocus() {
    lastFocusedElement = document.activeElement;
}

function restoreFocus() {
    if (lastFocusedElement) {
        lastFocusedElement.focus();
        lastFocusedElement = null;
    }
}

function getFocusableElements(container) {
    const focusableSelectors = [
        'button:not([disabled])',
        'a[href]:not([disabled])',
        'input:not([disabled])',
        'select:not([disabled])',
        'textarea:not([disabled])',
        '[tabindex]:not([tabindex="-1"]):not([disabled])',
        '[contenteditable]:not([disabled])'
    ];
    return Array.from(container.querySelectorAll(focusableSelectors.join(',')));
}

function focusFirstElement(container) {
    const focusable = getFocusableElements(container);
    if (focusable.length > 0) focusable[0].focus();
}

function handleTabKey(e, modal) {
    const focusable = getFocusableElements(modal);
    if (focusable.length === 0) return;

    const firstFocusable = focusable[0];
    const lastFocusable = focusable[focusable.length - 1];

    if (e.shiftKey) {
        if (document.activeElement === firstFocusable) {
            e.preventDefault();
            lastFocusable.focus();
        }
    } else {
        if (document.activeElement === lastFocusable) {
            e.preventDefault();
            firstFocusable.focus();
        }
    }
}

function setupFocusTrap(modal, closeCallback) {
    activeModal = modal;

    const keyHandler = (e) => {
        if (e.key === 'Escape') {
            e.preventDefault();
            closeCallback();
        } else if (e.key === 'Tab') {
            handleTabKey(e, modal);
        }
    };

    modal.addEventListener('keydown', keyHandler);
    modal._focusTrapHandler = keyHandler;

    saveFocus();
    focusFirstElement(modal);
}

function removeFocusTrap(modal) {
    if (modal._focusTrapHandler) {
        modal.removeEventListener('keydown', modal._focusTrapHandler);
        delete modal._focusTrapHandler;
    }
    activeModal = null;
    restoreFocus();
}

// --- SCREEN READER ANNOUNCEMENTS ---
let srAnnouncements, srEvents;

function initAriaLiveRefs() {
    srAnnouncements = document.getElementById('sr-announcements');
    srEvents = document.getElementById('sr-events');
}

function announceToSR(message, type = 'polite') {
    const region = type === 'assertive' ? srEvents : srAnnouncements;
    if (!region) return;

    setTimeout(() => {
        region.textContent = message;
        setTimeout(() => {
            if (region.textContent === message) region.textContent = '';
        }, 3000);
    }, 100);
}

function announceEvent(eventTitle, eventDescription) {
    if (!srEvents) return;
    setTimeout(() => {
        srEvents.textContent = `📢 Evento: ${eventTitle}. ${eventDescription || ''}`;
        setTimeout(() => { srEvents.textContent = ''; }, 6000);
    }, 100);
}

// --- FIN DE JUEGO ---
function mostrarFinJuego() {
    const modal = document.getElementById('endgame-modal');
    const statsEl = document.getElementById('endgame-stats');
    const scoreEl = document.getElementById('final-score');
    const ratingEl = document.getElementById('endgame-rating');

    if (!modal || !gameState) return;

    calcularPuntuacion();
    const rating = getRating(gameState.puntuacionTotal);

    const finalNarrativo = getFinalNarrativo();
    const muertesEstimadas = Math.round((100 - gameState.recursosGlobales.vidasSalvadas) * 800);

    let statsHTML = `
        <div class="endgame-section">
            <h4>📊 LO QUE TE LLEVAS A CASA</h4>
            <div class="stat-row"><span>📈 Popularidad:</span><span class="positive">${Math.round(gameState.playerResources.popularidad)}%</span></div>
            <div class="stat-row"><span>📺 Relato:</span><span class="positive">${Math.round(gameState.playerResources.relato)}%</span></div>
            <div class="stat-row"><span>💼 Enchufes:</span><span class="positive">${Math.round(gameState.playerResources.enchufes)} pts</span></div>
            <div class="stat-row"><span>🤝 Socios:</span><span class="positive">${Math.round(gameState.playerResources.socios)}%</span></div>
            <div class="stat-row"><span>🥇 Ego:</span><span class="positive">${Math.round(gameState.playerResources.ego)} pts</span></div>
        </div>
        <div class="endgame-section">
            <h4>🇪🇸 LO QUE DEJAS</h4>
            <div class="stat-row"><span>🏥 Sanidad disponible:</span><span class="${getClaseRecursoGlobal('sanidadDisponible')}">${Math.round(gameState.recursosGlobales.sanidadDisponible)}%</span></div>
            <div class="stat-row"><span>💶 Economía:</span><span class="${getClaseRecursoGlobal('economia')}">${Math.round(gameState.recursosGlobales.economia)}%</span></div>
            <div class="stat-row"><span>📜 Libertades:</span><span class="${getClaseRecursoGlobal('libertades')}">${Math.round(gameState.recursosGlobales.libertades)}%</span></div>
            <div class="stat-row"><span>🦠 Población contagiada:</span><span class="${getClaseRecursoGlobal('saludPoblacional')}">${100 - Math.round(gameState.recursosGlobales.saludPoblacional)}%</span></div>
            <div class="stat-row"><span>💀 Muertes estimadas:</span><span class="negative">${muertesEstimadas.toLocaleString('es-ES')}</span></div>
            <div class="stat-row"><span>Caos nacional:</span><span class="negative">${Math.round(gameState.puntuacionMiseria)}%</span></div>
        </div>
        <div class="endgame-section endgame-final">
            <h4>📰 EL DESENLACE</h4>
            <p class="final-narrative">${finalNarrativo}</p>
        </div>
    `;

    statsEl.innerHTML = statsHTML;
    scoreEl.textContent = gameState.puntuacionTotal.toLocaleString('es-ES');

    ratingEl.innerHTML = `
        <div class="rating-title">${rating.title}</div>
        <div class="rating-desc">${rating.description}</div>
        <div class="rating-quote">"${getFraseFinal(gameState.puntuacionTotal)}"</div>
    `;

    modal.classList.add('active');
    setupFocusTrap(modal, () => {
        modal.classList.remove('active');
        removeFocusTrap(modal);
    });

    deleteSave();

    if (typeof enviarPuntuacionAlRanking === 'function') {
        enviarPuntuacionAlRanking(gameState.puntuacionTotal);
    }
}

// 3 finales narrativos
function getFinalNarrativo() {
    const muertes = Math.round((100 - gameState.recursosGlobales.vidasSalvadas) * 800);
    const popularidad = gameState.playerResources.popularidad;

    if (muertes >= 60000) {
        return 'COMISIÓN DE INVESTIGACIÓN. Tras la pandemia te llaman a declarar al Senado. No pasa nada técnicamente, pero las hemerotecas no perdonan. Tu carrera política termina aquí, aunque siempre te quedará una columna en El País.';
    }
    if (popularidad < 30) {
        return 'MOCIÓN DE CENSURA. El líder de la oposición entra en Moncloa con apoyos cruzados. Tu legado: "el que no doblegó la curva". Te ofrecen una embajada lejana. Aceptas.';
    }
    if (popularidad >= 60 && muertes < 30000) {
        return 'RESISTENCIA. Convocas elecciones generales y ganas. La pandemia se convierte en tu medalla: "He resistido". TVE te dedica un especial. Tu biografía sale por Navidad.';
    }
    return 'EMPATE TÉCNICO. La legislatura se arrastra hasta el final. Ni triunfo ni catástrofe. La gente te recuerda con un encogimiento de hombros. "Bueno, podría haber sido peor."';
}

function getRating(score) {
    let rating = RATINGS[0];
    for (const r of RATINGS) {
        if (score >= r.minScore) rating = r;
    }
    return rating;
}

function restartGame() {
    stopAutoSave();
    deleteSave();
    cerrarTodosModales();
    initGameState();
    showStartScreen();
    renderizarSeleccionPersonaje();
}

function cerrarTodosModales() {
    const modals = document.querySelectorAll('.modal');
    modals.forEach(modal => modal.classList.remove('active'));
    const panels = document.querySelectorAll('.panel');
    panels.forEach(panel => panel.classList.remove('active'));
}

function showStartScreen() {
    const startScreen = document.getElementById('start-screen');
    const gameContainer = document.getElementById('game-container');
    if (startScreen) {
        startScreen.style.opacity = '1';
        startScreen.style.display = 'flex';
    }
    if (gameContainer) gameContainer.style.display = 'none';
}

function hideStartScreen() {
    const startScreen = document.getElementById('start-screen');
    const gameContainer = document.getElementById('game-container');
    if (startScreen) {
        startScreen.style.opacity = '0';
        setTimeout(() => { startScreen.style.display = 'none'; }, 500);
    }
    if (gameContainer) gameContainer.style.display = 'block';
}

function mostrarMenuPausa() {
    const modal = document.getElementById('pause-modal');
    if (modal) {
        modal.classList.add('active');
        setupFocusTrap(modal, cerrarPausa);
    }
}

function cerrarPausa() {
    const modal = document.getElementById('pause-modal');
    if (modal) {
        modal.classList.remove('active');
        removeFocusTrap(modal);
    }
}

function mostrarAyuda() {
    const modal = document.getElementById('help-modal');
    if (modal) {
        modal.classList.add('active');
        setupFocusTrap(modal, cerrarAyuda);
    }
}

function cerrarAyuda() {
    const modal = document.getElementById('help-modal');
    if (modal) {
        modal.classList.remove('active');
        removeFocusTrap(modal);
    }
}

function confirmarNuevaPartida() {
    mostrarModalConfirmacion(
        '¿Seguro que quieres empezar una nueva partida? Se perderá el progreso actual.',
        () => {
            cerrarModalConfirmacion();
            cerrarPausa();
            restartGame();
        }
    );
}

function mostrarModalConfirmacion(mensaje, onConfirm) {
    const modal = document.getElementById('confirm-modal');
    const messageEl = document.getElementById('confirm-message');
    const yesBtn = document.getElementById('confirm-yes');
    const noBtn = document.getElementById('confirm-no');

    if (!modal) return;
    messageEl.textContent = mensaje;

    const newYesBtn = yesBtn.cloneNode(true);
    const newNoBtn = noBtn.cloneNode(true);
    yesBtn.parentNode.replaceChild(newYesBtn, yesBtn);
    noBtn.parentNode.replaceChild(newNoBtn, noBtn);

    newYesBtn.addEventListener('click', onConfirm);
    newNoBtn.addEventListener('click', cerrarModalConfirmacion);

    modal.classList.add('active');
    setupFocusTrap(modal, cerrarModalConfirmacion);
}

function cerrarModalConfirmacion() {
    const modal = document.getElementById('confirm-modal');
    if (modal) {
        modal.classList.remove('active');
        removeFocusTrap(modal);
    }
}

if (typeof document !== 'undefined') {
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initAriaLiveRefs);
    } else {
        initAriaLiveRefs();
    }
}
