// --- SISTEMA DE LOGROS ---
const logros = {};

function initLogros() {
    for (let key in logrosData) {
        logros[key] = { ...logrosData[key], unlocked: false };
    }
}

function checkLogros() {
    for (let key in logros) {
        const logro = logros[key];
        if (!logro.unlocked && logro.condition()) {
            logro.unlocked = true;
            // Dar premio (Eliminado por balanceo)
            showAchievementNotification(logro);
            renderLogros();
            calculateVPS();
        }
    }
}

// Array to track active notifications
let activeNotifications = [];
const NOTIFICATION_HEIGHT = 80; // Approximate height including margin (accounts for text wrap)
const NOTIFICATION_START_TOP = 100;

function showAchievementNotification(logro) {
    audioSystem.playUnlock();
    // Anunciar para screen readers
    if (typeof announceAchievement === 'function') {
        announceAchievement(`${logro.icon} ${logro.name}`);
    }
    
    const notif = document.createElement('div');
    notif.className = 'achievement-notification';
    notif.innerHTML = `${logro.icon} ¡Logro desbloqueado: ${logro.name}!`;

    // Calculate position based on active notifications
    const topPosition = NOTIFICATION_START_TOP + (activeNotifications.length * NOTIFICATION_HEIGHT);
    notif.style.top = topPosition + 'px';

    document.body.appendChild(notif);
    activeNotifications.push(notif);

    setTimeout(() => {
        const index = activeNotifications.indexOf(notif);
        if (index > -1) {
            activeNotifications.splice(index, 1);
        }
        notif.remove();

        // Reposition remaining notifications
        activeNotifications.forEach((n, i) => {
            n.style.top = (NOTIFICATION_START_TOP + (i * NOTIFICATION_HEIGHT)) + 'px';
        });
    }, 3000);
}

function renderLogros() {
    const list = document.getElementById('achievements-list');
    list.innerHTML = '';
    for (let key in logros) {
        const logro = logros[key];
        const div = document.createElement('div');
        div.className = `achievement-item ${logro.unlocked ? 'unlocked' : 'locked'}`;
        div.innerHTML = `
            <div class="achievement-icon">${logro.icon}</div>
            <div class="achievement-info">
                <div class="achievement-name">${logro.name}</div>
                <div class="achievement-desc">${logro.desc}</div>
            </div>
        `;
        list.appendChild(div);
    }
}

function toggleAchievements() {
    audioSystem.playClick();
    const panel = document.getElementById('achievements-panel');
    const isOpening = !panel.classList.contains('visible');
    panel.classList.toggle('visible');
    updatePanelPositions();
    
    if (isOpening) {
        setupFocusTrap(panel, toggleAchievements);
    } else {
        removeFocusTrap(panel);
    }
}
