/**
 * Scripts principaux - Nukunu Mofiala
 */

document.addEventListener('DOMContentLoaded', function() {
    // Animation des statistiques au chargement
    const statCards = document.querySelectorAll('.stat-card');
    statCards.forEach((card, index) => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(20px)';
        setTimeout(() => {
            card.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
            card.style.opacity = '1';
            card.style.transform = 'translateY(0)';
        }, index * 100);
    });

    // Confirmation pour la suppression
    const deleteButtons = document.querySelectorAll('.btn-delete');
    deleteButtons.forEach(btn => {
        btn.addEventListener('click', function(e) {
            if (!confirm('Êtes-vous sûr de vouloir supprimer cet élément ?')) {
                e.preventDefault();
            }
        });
    });

    // Menu mobile
    const menuToggle = document.querySelector('.menu-toggle');
    const sidebar = document.querySelector('.sidebar');
    if (menuToggle && sidebar) {
        menuToggle.addEventListener('click', (e) => {
            e.stopPropagation();
            sidebar.classList.toggle('active');
        });
        // Fermer en cliquant en dehors (overlay)
        document.addEventListener('click', (e) => {
            if (sidebar.classList.contains('active') &&
                !sidebar.contains(e.target) &&
                !menuToggle.contains(e.target)) {
                sidebar.classList.remove('active');
            }
        });
        // Fermer avec Escape
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && sidebar.classList.contains('active')) {
                sidebar.classList.remove('active');
            }
        });
    }

    // Masquer les messages flash après 5 secondes
    const flashMessages = document.querySelectorAll('.error-message, .success-message');
    flashMessages.forEach(msg => {
        setTimeout(() => {
            msg.style.transition = 'opacity 0.5s';
            msg.style.opacity = '0';
            setTimeout(() => msg.remove(), 500);
        }, 5000);
    });
});

// Fonction de recherche dans les tableaux
// Appelée via onkeyup="searchTable('inputId','tableId')"
function searchTable(inputId, tableId) {
    const input  = document.getElementById(inputId);
    const table  = document.getElementById(tableId);
    if (!input || !table) return;

    const filter = input.value.toLowerCase().trim();
    const rows   = table.querySelectorAll('tbody tr');

    rows.forEach(row => {
        // Garder visible les lignes "aucun résultat" (1 seule cellule colspan)
        if (row.cells.length === 1) { row.style.display = ''; return; }
        row.style.display = row.textContent.toLowerCase().includes(filter) ? '' : 'none';
    });
}
