// js/concours.js
const API_BASE_URL = '../../../../model/api/concours.php';
let currentPage = 1;
const perPage = 10;
let totalPages = 1;
let editMode = false;
let membersList = [];
let professorsList = [];
let detailsList = [];
let typesDiplomeList = [];

// ========================================
// CHARGEMENT INITIAL
// ========================================
document.addEventListener('DOMContentLoaded', function() {
    loadConcours();
    loadStats();
    loadProfessors();
    loadTypesDiplome();
    setupSearchForm();
});

// ========================================
// RECHERCHE
// ========================================
function setupSearchForm() {
    document.getElementById('searchForm').addEventListener('submit', function(e) {
        e.preventDefault();
        currentPage = 1;
        loadConcours();
    });
}

function resetSearch() {
    document.getElementById('searchForm').reset();
    currentPage = 1;
    loadConcours();
}

// ========================================
// STATISTIQUES
// ========================================
function loadStats() {
    fetch(`${API_BASE_URL}?action=stats`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                const stats = result.data;
                document.getElementById('statTotal').textContent = stats.total || 0;
                document.getElementById('statOuvert').textContent = stats.ouvert || 0;
                document.getElementById('statEnCours').textContent = stats.en_cours || 0;
                document.getElementById('statTermine').textContent = stats.termine || 0;
            }
        })
        .catch(error => console.error('Error loading stats:', error));
}

// ========================================
// PROFESSEURS
// ========================================
function loadProfessors() {
    fetch(`${API_BASE_URL}?action=professors`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                professorsList = result.data;
                populateProfessorDropdowns();
            }
        })
        .catch(error => console.error('Error loading professors:', error));
}

function populateProfessorDropdowns() {
    const selects = ['committee_chef', 'memberSelect'];
    selects.forEach(id => {
        const select = document.getElementById(id);
        if (select) {
            const firstOption = select.options[0];
            select.innerHTML = '';
            select.appendChild(firstOption);

            professorsList.forEach(prof => {
                const option = document.createElement('option');
                option.value = prof.id;
                option.textContent = prof.code + ' - ' + prof.nom + ' ' + (prof.prenom || '');
                select.appendChild(option);
            });
        }
    });
}

// ========================================
// TYPES DE DIPLÔMES
// ========================================
function loadTypesDiplome() {
    const loading = document.getElementById('loadingTypes');
    if (loading) loading.style.display = 'block';

    fetch(`${API_BASE_URL}?action=types_diplome`)
        .then(response => response.json())
        .then(result => {
            if (loading) loading.style.display = 'none';
            if (result.success) {
                typesDiplomeList = result.data;
                populateTypeDiplomeDropdown();
            } else {
                showToast('Erreur lors du chargement des types de diplômes', 'error');
            }
        })
        .catch(error => {
            if (loading) loading.style.display = 'none';
            showToast('Erreur de connexion au serveur', 'error');
            console.error('Error loading types diplome:', error);
        });
}

function populateTypeDiplomeDropdown() {
    const select = document.getElementById('detail_type_diplome');
    if (select) {
        const defaultOption = select.options[0];
        select.innerHTML = '';
        select.appendChild(defaultOption);

        typesDiplomeList.forEach(type => {
            const option = document.createElement('option');
            option.value = type.id;
            option.textContent = type.libelle + ' (' + type.annee_apres_bac + ' ans) - ' + type.code;
            option.dataset.code = type.code;
            option.dataset.annee = type.annee_apres_bac;
            select.appendChild(option);
        });
    }
}

// ========================================
// LISTE DES CONCOURS
// ========================================
function loadConcours() {
    showLoading(true);

    const searchData = {
        code: document.getElementById('searchCode').value,
        label: document.getElementById('searchLabel').value,
        filliere: document.getElementById('searchFilliere').value,
        etat_concours: document.getElementById('searchEtat').value,
        active: document.getElementById('searchActive').value,
        page: currentPage,
        per_page: perPage
    };

    const params = new URLSearchParams(searchData);

    fetch(`${API_BASE_URL}?action=search&${params.toString()}`)
        .then(response => response.json())
        .then(result => {
            showLoading(false);
            if (result.success) {
                renderTable(result.data.data);
                renderPagination(result.data);
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            showLoading(false);
            showToast('Erreur de connexion au serveur', 'error');
            console.error('Error:', error);
        });
}

function renderTable(concours) {
    const tbody = document.getElementById('tableBody');

    if (concours.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="9" style="text-align: center; padding: 40px; color: #666;">
                    <p style="font-size: 18px;">📭 Aucun concours trouvé</p>
                    <p style="font-size: 14px; margin-top: 5px;">Essayez de modifier vos critères de recherche</p>
                </td>
            </tr>
        `;
        return;
    }

    tbody.innerHTML = concours.map(item => `
        <tr>
            <td>${item.id}</td>
            <td><strong>${escapeHtml(item.code)}</strong></td>
            <td>${escapeHtml(item.label)}</td>
            <td>${escapeHtml(item.filliere || '-')}</td>
            <td>${formatDate(item.date_lancement)}</td>
            <td>${formatDate(item.date_fin)}</td>
            <td><span class="badge badge-${item.etat_concours ? item.etat_concours.toLowerCase().replace('_', '-') : ''}">${escapeHtml(item.etat_concours)}</span></td>
            <td><span class="badge ${item.active ? 'badge-success' : 'badge-danger'}">${item.active ? 'Actif' : 'Inactif'}</span></td>
            <td>
                <button class="btn btn-info btn-sm" onclick="viewDetail(${item.id})">
                    <i class="fas fa-eye"></i>
                </button>
                <button class="btn btn-warning btn-sm" onclick="openEditModal(${item.id})">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="btn btn-danger btn-sm" onclick="deleteConcours(${item.id})">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        </tr>
    `).join('');
}

function renderPagination(data) {
    const { total, page, totalPages: pages } = data;
    totalPages = pages;

    const start = (page - 1) * perPage + 1;
    const end = Math.min(page * perPage, total);
    document.getElementById('paginationInfo').textContent =
        `Affichage de ${start} à ${end} sur ${total} concours`;

    const pageNumbers = document.getElementById('pageNumbers');
    let html = '';
    for (let i = 1; i <= pages; i++) {
        html += `<button onclick="goToPage(${i})" ${i === page ? 'class="active"' : ''}>${i}</button>`;
    }
    pageNumbers.innerHTML = html;

    document.getElementById('prevBtn').disabled = page <= 1;
    document.getElementById('nextBtn').disabled = page >= pages;
}

function changePage(direction) {
    if (direction === 'prev' && currentPage > 1) {
        currentPage--;
    } else if (direction === 'next' && currentPage < totalPages) {
        currentPage++;
    }
    loadConcours();
}

function goToPage(page) {
    currentPage = page;
    loadConcours();
}

// ========================================
// MODAL - CRÉATION / MODIFICATION
// ========================================
function openCreateModal() {
    editMode = false;
    document.getElementById('modalTitle').textContent = 'Nouveau Concours';
    document.getElementById('concoursForm').reset();
    document.getElementById('committeeForm').reset();
    document.getElementById('concoursId').value = '';
    document.getElementById('committeeId').value = '';
    membersList = [];
    detailsList = [];
    renderMembers();
    renderDetails();
    switchTab('info');
    document.querySelector('.modal-overlay').classList.add('active');
}

function openEditModal(id) {
    editMode = true;
    document.getElementById('modalTitle').textContent = 'Modifier Concours';
    document.getElementById('concoursId').value = id;
    membersList = [];
    detailsList = [];

    showLoading(true);

    fetch(`${API_BASE_URL}?action=get&id=${id}`)
        .then(response => response.json())
        .then(result => {
            showLoading(false);
            if (result.success) {
                const data = result.data;

                // Remplir les infos du concours
                document.getElementById('code').value = data.code;
                document.getElementById('label').value = data.label;
                document.getElementById('filliere').value = data.filliere || '';
                document.getElementById('etat_concours').value = data.etat_concours || 'OUVERT';
                document.getElementById('date_lancement').value = data.date_lancement ? data.date_lancement.slice(0, 16) : '';
                document.getElementById('date_fin').value = data.date_fin ? data.date_fin.slice(0, 16) : '';
                document.getElementById('active').value = data.active;
                document.getElementById('description').value = data.description || '';

                // Remplir les infos du comité
                if (data.commite_organisation) {
                    const committee = data.commite_organisation;
                    document.getElementById('committeeId').value = committee.id;
                    document.getElementById('committee_code').value = committee.code;
                    document.getElementById('committee_label').value = committee.label;
                    document.getElementById('committee_description').value = committee.description || '';
                    document.getElementById('committee_chef').value = committee.chef_id || '';

                    membersList = data.members ? data.members.map(m => m.professeur_id) : [];
                    renderMembers();
                }

                // Remplir les détails
                if (data.details && data.details.length > 0) {
                    detailsList = data.details.map(d => ({
                        type_diplome_id: d.type_diplome_id,
                        type_libelle: d.type_libelle || '',
                        type_code: d.type_code || '',
                        annee_apres_bac: d.annee_apres_bac || '',
                        pourcentage: parseFloat(d.pourcentage) || 0,
                        description: d.description || ''
                    }));
                    renderDetails();
                }

                document.querySelector('.modal-overlay').classList.add('active');
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            showLoading(false);
            showToast('Erreur de connexion au serveur', 'error');
            console.error('Error:', error);
        });
}

// ========================================
// GESTION DES MEMBRES
// ========================================
function addMember() {
    const select = document.getElementById('memberSelect');
    const memberId = parseInt(select.value);

    if (!memberId) {
        showToast('Veuillez sélectionner un membre', 'warning');
        return;
    }

    if (membersList.includes(memberId)) {
        showToast('Ce membre est déjà ajouté', 'warning');
        return;
    }

    membersList.push(memberId);
    renderMembers();
    select.value = '';
}

function removeMember(index) {
    membersList.splice(index, 1);
    renderMembers();
}

function renderMembers() {
    const container = document.getElementById('membersList');

    if (membersList.length === 0) {
        container.innerHTML = '<p style="color: #999; font-size: 14px;">Aucun membre sélectionné</p>';
        return;
    }

    let html = '';
    membersList.forEach((memberId, index) => {
        const prof = professorsList.find(p => p.id === memberId);
        const name = prof ? prof.code + ' - ' + prof.nom + ' ' + (prof.prenom || '') : 'Membre #' + memberId;
        html += `
            <div class="member-item">
                <span class="member-info">👤 ${escapeHtml(name)}</span>
                <button class="member-remove" onclick="removeMember(${index})">&times;</button>
            </div>
        `;
    });
    container.innerHTML = html;
}

// ========================================
// GESTION DES DÉTAILS (TYPES DE DIPLÔMES)
// ========================================
function addDetail() {
    const typeSelect = document.getElementById('detail_type_diplome');
    const pourcentage = document.getElementById('detail_pourcentage');
    const description = document.getElementById('detail_description');

    const typeId = parseInt(typeSelect.value);
    const pourcentageValue = parseFloat(pourcentage.value);

    if (!typeId) {
        showToast('Veuillez sélectionner un type de diplôme', 'warning');
        typeSelect.focus();
        return;
    }

    if (isNaN(pourcentageValue) || pourcentageValue <= 0 || pourcentageValue > 100) {
        showToast('Veuillez entrer un pourcentage valide (1-100)', 'warning');
        pourcentage.focus();
        return;
    }

    if (detailsList.some(d => d.type_diplome_id === typeId)) {
        showToast('Ce type de diplôme est déjà ajouté', 'warning');
        return;
    }

    const selectedOption = typeSelect.options[typeSelect.selectedIndex];
    const typeLibelle = selectedOption.textContent;
    const typeCode = selectedOption.dataset.code || '';
    const typeAnnee = selectedOption.dataset.annee || '';

    detailsList.push({
        type_diplome_id: typeId,
        type_libelle: typeLibelle,
        type_code: typeCode,
        annee_apres_bac: typeAnnee,
        pourcentage: pourcentageValue,
        description: description.value || ''
    });

    renderDetails();
    typeSelect.value = '';
    pourcentage.value = '';
    description.value = '';
}

function removeDetail(index) {
    detailsList.splice(index, 1);
    renderDetails();
}

function renderDetails() {
    const container = document.getElementById('detailsList');

    if (detailsList.length === 0) {
        container.innerHTML = '<p style="color: #999; font-size: 14px;">Aucun type de diplôme sélectionné</p>';
        return;
    }

    let totalPourcentage = 0;
    let html = '<div class="details-table-wrapper"><table class="details-table"><thead><tr>' +
        '<th>Type de Diplôme</th>' +
        '<th>Code</th>' +
        '<th>Années</th>' +
        '<th>Pourcentage</th>' +
        '<th>Description</th>' +
        '<th>Action</th>' +
        '</tr></thead><tbody>';

    detailsList.forEach((detail, index) => {
        totalPourcentage += detail.pourcentage;
        html += `
            <tr>
                <td><strong>${escapeHtml(detail.type_libelle)}</strong></td>
                <td>${escapeHtml(detail.type_code)}</td>
                <td>${detail.annee_apres_bac} ans</td>
                <td><span class="badge badge-primary">${detail.pourcentage}%</span></td>
                <td>${escapeHtml(detail.description || '-')}</td>
                <td>
                    <button type="button" class="btn btn-danger btn-sm" onclick="removeDetail(${index})">
                        <i class="fas fa-trash"></i>
                    </button>
                </td>
            </tr>
        `;
    });

    const totalColor = totalPourcentage === 100 ? 'var(--success-color)' : 'var(--danger-color)';
    const totalMessage = totalPourcentage !== 100 ? '⚠️ Le total doit être de 100%' : '✅ Total correct';

    html += `</tbody>
            <tfoot>
                <tr>
                    <td colspan="3" style="text-align: right; font-weight: 600;">Total</td>
                    <td colspan="3" style="font-weight: 700; color: ${totalColor};">
                        ${totalPourcentage}% ${totalMessage}
                    </td>
                </tr>
            </tfoot>
            </table></div>`;

    container.innerHTML = html;
}

// ========================================
// SAUVEGARDE DU CONCOURS
// ========================================
function saveConcours() {
    // Valider les infos du concours
    const code = document.getElementById('code').value;
    const label = document.getElementById('label').value;
    const filliere = document.getElementById('filliere').value;
    const etat_concours = document.getElementById('etat_concours').value;
    const date_lancement = document.getElementById('date_lancement').value;
    const date_fin = document.getElementById('date_fin').value;

    if (!code || !label || !filliere || !date_lancement || !date_fin) {
        showToast('Veuillez remplir tous les champs obligatoires du concours', 'warning');
        switchTab('info');
        return;
    }

    // Valider les infos du comité
    const committee_code = document.getElementById('committee_code').value;
    const committee_label = document.getElementById('committee_label').value;

    if (!committee_code || !committee_label) {
        showToast('Veuillez remplir tous les champs obligatoires du comité', 'warning');
        switchTab('committee');
        return;
    }

    // Valider les détails
    if (detailsList.length === 0) {
        showToast('Veuillez ajouter au moins un type de diplôme', 'warning');
        switchTab('details');
        return;
    }

    const totalPercentage = detailsList.reduce((sum, d) => sum + d.pourcentage, 0);
    if (totalPercentage !== 100) {
        showToast('Le total des pourcentages doit être égal à 100% (actuel: ' + totalPercentage + '%)', 'warning');
        switchTab('details');
        return;
    }

    const id = document.getElementById('concoursId').value;
    const committeeId = document.getElementById('committeeId').value;

    const data = {
        code: code,
        label: label,
        filliere: filliere,
        etat_concours: etat_concours,
        date_lancement: date_lancement,
        date_fin: date_fin,
        active: parseInt(document.getElementById('active').value),
        description: document.getElementById('description').value,
        commite_organisation: {
            id: committeeId || null,
            code: committee_code,
            label: committee_label,
            description: document.getElementById('committee_description').value,
            chef_id: parseInt(document.getElementById('committee_chef').value) || null,
            members: membersList
        },
        details: detailsList.map(d => ({
            type_diplome_id: d.type_diplome_id,
            pourcentage: d.pourcentage,
            description: d.description || null
        }))
    };

    const url = id ? `${API_BASE_URL}?action=update&id=${id}` : API_BASE_URL;
    const method = id ? 'PUT' : 'POST';

    const btn = document.querySelector('.modal-footer .btn-primary');
    const originalText = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Enregistrement...';

    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
        .then(response => response.json())
        .then(result => {
            btn.disabled = false;
            btn.innerHTML = originalText;

            if (result.success) {
                showToast(result.message, 'success');
                closeModal();
                loadConcours();
                loadStats();
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            btn.disabled = false;
            btn.innerHTML = originalText;
            showToast('Erreur de connexion au serveur', 'error');
            console.error('Error:', error);
        });
}

// ========================================
// SUPPRESSION
// ========================================
function deleteConcours(id) {
    if (!confirm('Êtes-vous sûr de vouloir supprimer ce concours ?')) return;

    fetch(`${API_BASE_URL}?action=delete&id=${id}`, {
        method: 'DELETE'
    })
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                showToast(result.message, 'success');
                loadConcours();
                loadStats();
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            showToast('Erreur de connexion au serveur', 'error');
            console.error('Error:', error);
        });
}

// ========================================
// DÉTAILS
// ========================================
function viewDetail(id) {
    document.getElementById('detailModal').classList.add('active');
    document.getElementById('detailContent').innerHTML = `
        <div class="loading active">
            <div class="spinner"></div>
            <p style="margin-top: 10px;">Chargement des détails...</p>
        </div>
    `;

    fetch(`${API_BASE_URL}?action=get&id=${id}`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                renderDetail(result.data);
            } else {
                document.getElementById('detailContent').innerHTML = `
                    <p style="color: var(--danger-color);">Erreur: ${result.message}</p>
                `;
            }
        })
        .catch(error => {
            document.getElementById('detailContent').innerHTML = `
                <p style="color: var(--danger-color);">Erreur de connexion au serveur</p>
            `;
            console.error('Error:', error);
        });
}

function renderDetail(data) {
    const committee = data.commite_organisation || {};
    const members = data.members || [];
    const details = data.details || [];

    let membersHtml = '';
    if (members.length > 0) {
        membersHtml = members.map(m => `
            <span class="member-badge ${m.professeur_id === committee.chef_id ? 'chef' : ''}">
                ${m.code || 'Membre'} ${m.professeur_id === committee.chef_id ? '⭐' : ''}
            </span>
        `).join('');
    } else {
        membersHtml = '<span style="color: #999;">Aucun membre</span>';
    }

    let detailsHtml = '';
    if (details.length > 0) {
        const total = details.reduce((sum, d) => sum + (d.pourcentage || 0), 0);
        detailsHtml = `
            <div class="details-table-wrapper">
                <table class="details-table">
                    <thead>
                        <tr>
                            <th>Type de Diplôme</th>
                            <th>Code</th>
                            <th>Années</th>
                            <th>Pourcentage</th>
                            <th>Description</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${details.map(d => `
                            <tr>
                                <td><strong>${escapeHtml(d.type_libelle || '')}</strong></td>
                                <td>${escapeHtml(d.type_code || '')}</td>
                                <td>${d.annee_apres_bac || '-'} ans</td>
                                <td><span class="badge badge-primary">${d.pourcentage || 0}%</span></td>
                                <td>${escapeHtml(d.description || '-')}</td>
                            </tr>
                        `).join('')}
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="3" style="text-align: right; font-weight: 600;">Total</td>
                            <td colspan="2" style="font-weight: 700; color: var(--success-color);">
                                ${total}%
                            </td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        `;
    } else {
        detailsHtml = '<p style="color: #999;">Aucun type de diplôme défini</p>';
    }

    document.getElementById('detailContent').innerHTML = `
        <div class="detail-section">
            <h3>📋 Informations du Concours</h3>
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="label">Code</span>
                    <span class="value">${escapeHtml(data.code)}</span>
                </div>
                <div class="detail-item">
                    <span class="label">Libellé</span>
                    <span class="value">${escapeHtml(data.label)}</span>
                </div>
                <div class="detail-item">
                    <span class="label">Filière</span>
                    <span class="value">${escapeHtml(data.filliere || '-')}</span>
                </div>
                <div class="detail-item">
                    <span class="label">État</span>
                    <span class="value"><span class="badge badge-${data.etat_concours ? data.etat_concours.toLowerCase().replace('_', '-') : ''}">${escapeHtml(data.etat_concours)}</span></span>
                </div>
                <div class="detail-item">
                    <span class="label">Date de Lancement</span>
                    <span class="value">${formatDate(data.date_lancement)}</span>
                </div>
                <div class="detail-item">
                    <span class="label">Date de Fin</span>
                    <span class="value">${formatDate(data.date_fin)}</span>
                </div>
              
                <div class="detail-item">
                    <span class="label">Statut</span>
                    <span class="value"><span class="badge ${data.active ? 'badge-success' : 'badge-danger'}">${data.active ? 'Actif' : 'Inactif'}</span></span>
                </div>
            </div>
            ${data.description ? `
                <div class="detail-item" style="margin-top: 10px;">
                    <span class="label">Description</span>
                    <span class="value">${escapeHtml(data.description)}</span>
                </div>
            ` : ''}
        </div>
        
        <div class="detail-section">
            <h3>👥 Comité d'Organisation</h3>
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="label">Code</span>
                    <span class="value">${escapeHtml(committee.code || '-')}</span>
                </div>
                <div class="detail-item">
                    <span class="label">Libellé</span>
                    <span class="value">${escapeHtml(committee.label || '-')}</span>
                </div>
                <div class="detail-item" style="grid-column: 1 / -1;">
                    <span class="label">Description</span>
                    <span class="value">${escapeHtml(committee.description || '-')}</span>
                </div>
                <div class="detail-item" style="grid-column: 1 / -1;">
                    <span class="label">Membres</span>
                    <div class="members-list-detail">${membersHtml}</div>
                </div>
            </div>
        </div>
        
        <div class="detail-section">
            <h3>🎓 Types de Diplômes</h3>
            <div class="detail-item" style="padding: 0; background: none;">
                ${detailsHtml}
            </div>
        </div>
    `;
}

function closeDetailModal() {
    document.getElementById('detailModal').classList.remove('active');
}

// ========================================
// UTILITAIRES
// ========================================
function switchTab(tab) {
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    document.querySelector(`.tab-btn[data-tab="${tab}"]`).classList.add('active');

    document.querySelectorAll('.tab-content').forEach(content => {
        content.classList.remove('active');
    });
    document.getElementById(`tab-${tab}`).classList.add('active');
}

function closeModal() {
    document.querySelector('.modal-overlay').classList.remove('active');
}

function showLoading(show) {
    const loading = document.querySelector('.loading');
    if (loading) {
        if (show) {
            loading.classList.add('active');
        } else {
            loading.classList.remove('active');
        }
    }
}

function showToast(message, type = 'info') {
    const container = document.getElementById('toastContainer');
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.innerHTML = `
        <span class="toast-icon">${getToastIcon(type)}</span>
        <span class="toast-message">${message}</span>
        <button class="toast-close" onclick="this.parentElement.remove()">&times;</button>
    `;
    container.appendChild(toast);

    setTimeout(() => {
        if (toast.parentElement) {
            toast.style.opacity = '0';
            toast.style.transform = 'translateX(100%)';
            toast.style.transition = 'all 0.3s ease';
            setTimeout(() => {
                if (toast.parentElement) {
                    toast.remove();
                }
            }, 300);
        }
    }, 4000);
}

function getToastIcon(type) {
    const icons = {
        success: '✅',
        error: '❌',
        warning: '⚠️',
        info: 'ℹ️'
    };
    return icons[type] || 'ℹ️';
}

function formatDate(dateStr) {
    if (!dateStr) return '-';
    const date = new Date(dateStr);
    return date.toLocaleString('fr-FR', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    });
}

function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// ========================================
// ÉVÉNEMENTS
// ========================================
// Fermer les modals en cliquant sur l'overlay
document.querySelectorAll('.modal-overlay').forEach(modal => {
    modal.addEventListener('click', function(e) {
        if (e.target === this) {
            if (this.id === 'detailModal') {
                closeDetailModal();
            } else {
                closeModal();
            }
        }
    });
});

// Fermer avec la touche Escape
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        if (document.getElementById('detailModal').classList.contains('active')) {
            closeDetailModal();
        } else {
            closeModal();
        }
    }
});
