// js/demande-document.js
const API_BASE_URL = '../../../../../model/api/demande-document.php';
const API_PROFESSEURS_URL = '../../../../../model/api/demande-document.php?action=professeurs';
const API_TYPE_DOCUMENT_URL = '../../../../../model/api/demande-document.php?action=type_documents';
const API_ETATS_URL = '../../../../../model/api/demande-document.php?action=etats';

let currentPage = 1;
const perPage = 10;
let totalPages = 1;
let editMode = false;
let currentDetailId = null;

// Maps pour les relations
let professeursMap = {};
let typeDocumentsMap = {};
let etatsMap = {};

// Load data on page load
document.addEventListener('DOMContentLoaded', function() {
    loadSelects();
    loadDemandes();
    loadStats();
    setupSearchForm();
});

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

function resetSearch() {
    document.getElementById('searchForm').reset();
    document.getElementById('searchProfesseur').value = '';
    document.getElementById('searchTypeDocument').value = '';
    document.getElementById('searchEtat').value = '';
    currentPage = 1;
    loadDemandes();
}

function loadSelects() {
    // Charger les professeurs
    fetch(API_PROFESSEURS_URL)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                const professeurs = result.data;
                professeursMap = {};
                professeurs.forEach(p => {
                    professeursMap[p.id] = p;
                });

                // Select de recherche
                const searchSelect = document.getElementById('searchProfesseur');
                searchSelect.innerHTML = '<option value="">Tous les professeurs</option>';
                professeurs.forEach(p => {
                    const option = document.createElement('option');
                    option.value = p.id;
                    option.textContent = `${p.nom} ${p.prenom} (${p.code})`;
                    searchSelect.appendChild(option);
                });

                // Select du formulaire
                const formSelect = document.getElementById('professeur_id');
                formSelect.innerHTML = '<option value="">Sélectionner un professeur</option>';
                professeurs.forEach(p => {
                    const option = document.createElement('option');
                    option.value = p.id;
                    option.textContent = `${p.nom} ${p.prenom} (${p.code})`;
                    formSelect.appendChild(option);
                });
            }
        })
        .catch(error => console.error('Error loading professeurs:', error));

    // Charger les types de documents
    fetch(API_TYPE_DOCUMENT_URL)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                const types = result.data;
                typeDocumentsMap = {};
                types.forEach(t => {
                    typeDocumentsMap[t.id] = t;
                });

                // Select de recherche
                const searchSelect = document.getElementById('searchTypeDocument');
                searchSelect.innerHTML = '<option value="">Tous les types</option>';
                types.forEach(t => {
                    const option = document.createElement('option');
                    option.value = t.id;
                    option.textContent = `${t.libelle} (${t.code})`;
                    searchSelect.appendChild(option);
                });

                // Select du formulaire
                const formSelect = document.getElementById('type_document_id');
                formSelect.innerHTML = '<option value="">Sélectionner un type de document</option>';
                types.forEach(t => {
                    const option = document.createElement('option');
                    option.value = t.id;
                    option.textContent = `${t.libelle} (${t.code})`;
                    formSelect.appendChild(option);
                });
            }
        })
        .catch(error => console.error('Error loading type documents:', error));

    // Charger les états
    fetch(API_ETATS_URL)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                const etats = result.data;
                etatsMap = {};
                etats.forEach(e => {
                    etatsMap[e.id] = e;
                });

                // Select de recherche
                const searchSelect = document.getElementById('searchEtat');
                searchSelect.innerHTML = '<option value="">Tous les états</option>';
                etats.forEach(e => {
                    const option = document.createElement('option');
                    option.value = e.id;
                    option.textContent = `${e.libelle} (${e.code})`;
                    searchSelect.appendChild(option);
                });

                // Select du formulaire
                const formSelect = document.getElementById('etat_demande_document_id');
                formSelect.innerHTML = '<option value="">Sélectionner un état</option>';
                etats.forEach(e => {
                    const option = document.createElement('option');
                    option.value = e.id;
                    option.textContent = `${e.libelle} (${e.code})`;
                    formSelect.appendChild(option);
                });
            }
        })
        .catch(error => console.error('Error loading etats:', error));
}

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;

                // Par état
                if (stats.by_etat) {
                    stats.by_etat.forEach(item => {
                        const code = item.libelle?.toLowerCase() || '';
                        if (code.includes('attente')) {
                            document.getElementById('statEnAttente').textContent = item.count;
                        } else if (code.includes('approuv')) {
                            document.getElementById('statApprouvees').textContent = item.count;
                        } else if (code.includes('rejet')) {
                            document.getElementById('statRejetees').textContent = item.count;
                        }
                    });
                }
            }
        })
        .catch(error => console.error('Error loading stats:', error));
}

function loadDemandes() {
    showLoading(true);

    const searchData = {
        id: document.getElementById('searchId')?.value || '',
        libelle: document.getElementById('searchLibelle')?.value || '',
        professeur_id: document.getElementById('searchProfesseur')?.value || '',
        type_document_id: document.getElementById('searchTypeDocument')?.value || '',
        etat_demande_document_id: document.getElementById('searchEtat')?.value || '',
        date_soumission_debut: document.getElementById('searchDateDebut')?.value || '',
        date_soumission_fin: document.getElementById('searchDateFin')?.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(demandes) {
    const tbody = document.getElementById('tableBody');

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

    tbody.innerHTML = demandes.map(d => `
        <tr>
            <td>${d.id}</td>
            <td><strong>${escapeHtml(d.libelle)}</strong></td>
            <td>${escapeHtml(d.professeur_nom || '')} ${escapeHtml(d.professeur_prenom || '')}</td>
            <td><span class="badge badge-info">${escapeHtml(d.type_document_libelle || '-')}</span></td>
            <td>${getEtatBadge(d.etat_demande_libelle)}</td>
            <td>${formatDate(d.date_soumission)}</td>
            <td>${d.date_reponse ? formatDate(d.date_reponse) : '-'}</td>
            <td>
                <button class="btn btn-info btn-sm" onclick="viewDetail(${d.id})" title="Voir les détails">
                    <i class="fas fa-eye"></i>
                </button>
                <button class="btn btn-warning btn-sm" onclick="openEditModal(${d.id})" title="Modifier">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="btn btn-danger btn-sm" onclick="deleteDemande(${d.id})" title="Supprimer">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        </tr>
    `).join('');
}

function getEtatBadge(libelle) {
    if (!libelle) return '-';
    const code = libelle.toLowerCase();
    let cssClass = 'badge-etat';
    if (code.includes('attente')) cssClass += ' badge-etat-att';
    else if (code.includes('cours')) cssClass += ' badge-etat-enc';
    else if (code.includes('approuv')) cssClass += ' badge-etat-app';
    else if (code.includes('rejet')) cssClass += ' badge-etat-rej';
    else if (code.includes('révision')) cssClass += ' badge-etat-rev';
    else cssClass += ' badge-etat-att';
    return `<span class="${cssClass}">${escapeHtml(libelle)}</span>`;
}

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} demandes`;

    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++;
    }
    loadDemandes();
}

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

function openCreateModal() {
    editMode = false;
    document.getElementById('modalTitle').textContent = 'Nouvelle Demande de Document';
    document.getElementById('demandeForm').reset();
    document.getElementById('demandeId').value = '';
    document.getElementById('date_soumission').value = new Date().toISOString().split('T')[0];
    document.getElementById('date_reponse').value = '';
    document.querySelector('#formModal').classList.add('active');
}

function openEditModal(id) {
    console.log('openEditModal id =', id);
    console.log('formModal =', document.getElementById('formModal'));
    console.log('libelle =', document.getElementById('libelle'));
    editMode = true;
    document.getElementById('modalTitle').textContent = 'Modifier Demande de Document';
    document.getElementById('demandeId').value = id;

    // Close detail modal if open
    if (document.getElementById('detailModal').classList.contains('active')) {
        closeDetailModal();
    }

    // Show loading state
    document.querySelector('#formModal').classList.add('active');
    document.getElementById('libelle').value = 'Chargement...';
    document.getElementById('libelle').disabled = true;
    document.getElementById('professeur_id').disabled = true;
    document.getElementById('type_document_id').disabled = true;
    document.getElementById('etat_demande_document_id').disabled = true;
    document.getElementById('date_soumission').disabled = true;
    document.getElementById('date_reponse').disabled = true;
    document.getElementById('description').value = 'Chargement...';
    document.getElementById('description').disabled = true;

    fetch(`${API_BASE_URL}?action=get&id=${id}`)
        .then(response => response.json())
        .then(result => {
            // Enable fields
            document.getElementById('libelle').disabled = false;
            document.getElementById('professeur_id').disabled = false;
            document.getElementById('type_document_id').disabled = false;
            document.getElementById('etat_demande_document_id').disabled = false;
            document.getElementById('date_soumission').disabled = false;
            document.getElementById('date_reponse').disabled = false;
            document.getElementById('description').disabled = false;

            if (result.success) {
                const d = result.data;
                document.getElementById('libelle').value = d.libelle;
                document.getElementById('professeur_id').value = d.professeur_id || '';
                document.getElementById('type_document_id').value = d.type_document_id || '';
                document.getElementById('etat_demande_document_id').value = d.etat_demande_document_id || '';
                document.getElementById('date_soumission').value = d.date_soumission || '';
                document.getElementById('date_reponse').value = d.date_reponse || '';
                document.getElementById('description').value = d.description || '';
            } else {
                showToast('Erreur: ' + result.message, 'error');
                closeModal();
            }
        })
        .catch(error => {
            document.getElementById('libelle').disabled = false;
            document.getElementById('professeur_id').disabled = false;
            document.getElementById('type_document_id').disabled = false;
            document.getElementById('etat_demande_document_id').disabled = false;
            document.getElementById('date_soumission').disabled = false;
            document.getElementById('date_reponse').disabled = false;
            document.getElementById('description').disabled = false;
            showToast('Erreur de connexion au serveur', 'error');
            closeModal();
            console.error('Error:', error);
        });
}

function viewDetail(id) {
    currentDetailId = id;

    // Show modal with loading state
    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>
    `;

    // Hide edit button initially
    document.getElementById('editFromDetailBtn').style.display = 'none';
    document.getElementById('detailEtatActions').innerHTML = '';

    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 = `
                    <div class="error-state">
                        <i class="fas fa-exclamation-circle"></i>
                        <p>Erreur: ${result.message}</p>
                    </div>
                `;
            }
        })
        .catch(error => {
            document.getElementById('detailContent').innerHTML = `
                <div class="error-state">
                    <i class="fas fa-exclamation-circle"></i>
                    <p>Erreur de connexion au serveur</p>
                </div>
            `;
            console.error('Error:', error);
        });
}

function renderDetail(demande) {
    const typeDocLibelle = demande.type_document_libelle || (typeDocumentsMap[demande.type_document_id] ? typeDocumentsMap[demande.type_document_id].libelle : '-');
    const etatLibelle = demande.etat_demande_libelle || (etatsMap[demande.etat_demande_document_id] ? etatsMap[demande.etat_demande_document_id].libelle : '-');

    document.getElementById('detailContent').innerHTML = `
        <div class="detail-section">
            <!-- Header -->
            <div class="detail-header">
                <div class="detail-avatar">
                    <i class="fas fa-file-alt"></i>
                </div>
                <div class="detail-title">
                    <h2>${escapeHtml(demande.libelle)}</h2>
                    <div class="detail-meta">
                        <span class="badge badge-info">
                            <i class="fas fa-id-badge"></i> ID: ${demande.id}
                        </span>
                        <span class="badge badge-success">
                            <i class="fas fa-file"></i> ${escapeHtml(typeDocLibelle)}
                        </span>
                        ${getEtatBadge(etatLibelle)}
                    </div>
                </div>
            </div>
            
            <!-- Information Grid -->
            <h3><i class="fas fa-info-circle"></i> Informations de la Demande</h3>
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="label"><i class="fas fa-user"></i> Professeur</span>
                    <span class="value">
                        ${escapeHtml(demande.professeur_nom || '')} ${escapeHtml(demande.professeur_prenom || '')}
                        <br><small style="color: #666;">${escapeHtml(demande.professeur_code || '')} - ${escapeHtml(demande.professeur_email || '')}</small>
                    </span>
                </div>
                <div class="detail-item">
                    <span class="label"><i class="fas fa-file"></i> Type de Document</span>
                    <span class="value">
                        <span class="badge badge-info">${escapeHtml(typeDocLibelle)}</span>
                        <br><small style="color: #666;">Code: ${escapeHtml(demande.type_document_code || '-')}</small>
                    </span>
                </div>
                <div class="detail-item">
                    <span class="label"><i class="fas fa-tag"></i> État</span>
                    <span class="value">${getEtatBadge(etatLibelle)}</span>
                </div>
                <div class="detail-item">
                    <span class="label"><i class="fas fa-calendar-plus"></i> Date Soumission</span>
                    <span class="value">${formatDate(demande.date_soumission)}</span>
                </div>
                <div class="detail-item">
                    <span class="label"><i class="fas fa-calendar-check"></i> Date Réponse</span>
                    <span class="value">${demande.date_reponse ? formatDate(demande.date_reponse) : 'En attente'}</span>
                </div>
                <div class="detail-item full-width">
                    <span class="label"><i class="fas fa-align-left"></i> Libellé</span>
                    <span class="value">${escapeHtml(demande.libelle)}</span>
                </div>
                <div class="detail-item full-width">
                    <span class="label"><i class="fas fa-file-alt"></i> Description</span>
                    <span class="value ${!demande.description ? 'empty' : ''}">
                        ${demande.description ? escapeHtml(demande.description) : 'Aucune description'}
                    </span>
                </div>
            </div>
            
            <!-- Metadata -->
            <div class="detail-metadata">
                <h4><i class="fas fa-clock"></i> Métadonnées</h4>
                <div class="metadata-grid">
                    <div class="meta-item">
                        <span class="meta-label">Date de création:</span>
                        <span class="meta-value">${formatDate(demande.date_creation)}</span>
                    </div>
                    <div class="meta-item">
                        <span class="meta-label">Dernière mise à jour:</span>
                        <span class="meta-value">${demande.date_modification ? formatDate(demande.date_modification) : 'Jamais'}</span>
                    </div>
                </div>
            </div>
        </div>
    `;

    // Show the edit button
    document.getElementById('editFromDetailBtn').style.display = 'inline-flex';

    // Ajouter les boutons d'action sur l'état
    const etatActions = document.getElementById('detailEtatActions');
    const currentEtat = demande.etat_demande_document_id;

    // Définir les transitions possibles
    const transitions = {
        // Si l'état actuel est "En attente", proposer "Approuvé" et "Rejeté"
        '1': ['3', '4'], // ATT -> APP, REJ
        // Si "En cours", proposer "Approuvé", "Rejeté", "En révision"
        '2': ['3', '4', '5'], // ENC -> APP, REJ, REV
        // Si "Approuvé", proposer "En révision" (pour réouverture)
        '3': ['5'], // APP -> REV
        // Si "Rejeté", proposer "En attente" (pour nouvelle soumission)
        '4': ['1'], // REJ -> ATT
        // Si "En révision", proposer "Approuvé" ou "Rejeté"
        '5': ['3', '4'] // REV -> APP, REJ
    };

    const possibleTransitions = transitions[currentEtat] || [];
    if (possibleTransitions.length > 0) {
        let btns = '';
        possibleTransitions.forEach(etatId => {
            const etat = etatsMap[etatId];
            if (etat) {
                let btnClass = 'btn-primary';
                let icon = 'fa-check';
                if (etat.code === 'REJ' || etat.libelle?.toLowerCase().includes('rejet')) {
                    btnClass = 'btn-danger';
                    icon = 'fa-times';
                } else if (etat.code === 'REV' || etat.libelle?.toLowerCase().includes('révision')) {
                    btnClass = 'btn-warning';
                    icon = 'fa-edit';
                } else if (etat.code === 'ATT' || etat.libelle?.toLowerCase().includes('attente')) {
                    btnClass = 'btn-secondary';
                    icon = 'fa-clock';
                } else if (etat.code === 'APP' || etat.libelle?.toLowerCase().includes('approuv')) {
                    btnClass = 'btn-success';
                    icon = 'fa-check';
                }
                btns += `<button type="button" class="btn ${btnClass} btn-sm" onclick="updateEtat(${demande.id}, ${etatId})">
                    <i class="fas ${icon}"></i> ${escapeHtml(etat.libelle)}
                </button>`;
            }
        });
        etatActions.innerHTML = `<span style="font-size: 13px; color: #666; margin-right: 8px;">Changer l'état:</span> ${btns}`;
    }
}

function updateEtat(id, etatId) {
    if (!confirm('Êtes-vous sûr de vouloir changer l\'état de cette demande ?')) return;

    fetch(`${API_BASE_URL}?action=update_etat&id=${id}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            etat_demande_document_id: etatId,
            date_reponse: new Date().toISOString().split('T')[0]
        })
    })
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                showToast(result.message, 'success');
                closeDetailModal();
                loadDemandes();
                loadStats();
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            showToast('Erreur de connexion au serveur', 'error');
            console.error('Error:', error);
        });
}

function editFromDetail() {
    if (currentDetailId) {
        const id = currentDetailId;
        closeDetailModal();
        setTimeout(() => {
            openEditModal(id);
        }, 300);
    }
}

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

function saveDemande() {
    // Validation
    const libelle = document.getElementById('libelle').value.trim();
    const professeur_id = document.getElementById('professeur_id').value;
    const type_document_id = document.getElementById('type_document_id').value;
    const etat_demande_document_id = document.getElementById('etat_demande_document_id').value;
    const date_soumission = document.getElementById('date_soumission').value;
    const date_reponse = document.getElementById('date_reponse').value;
    const description = document.getElementById('description').value.trim();

    if (!libelle) {
        showToast('Veuillez saisir le libellé de la demande', 'warning');
        document.getElementById('libelle').focus();
        return;
    }

    if (!professeur_id) {
        showToast('Veuillez sélectionner un professeur', 'warning');
        document.getElementById('professeur_id').focus();
        return;
    }

    if (!type_document_id) {
        showToast('Veuillez sélectionner un type de document', 'warning');
        document.getElementById('type_document_id').focus();
        return;
    }

    if (!etat_demande_document_id) {
        showToast('Veuillez sélectionner un état', 'warning');
        document.getElementById('etat_demande_document_id').focus();
        return;
    }

    const id = document.getElementById('demandeId').value;
    const data = {
        libelle: libelle,
        professeur_id: parseInt(professeur_id),
        type_document_id: parseInt(type_document_id),
        etat_demande_document_id: parseInt(etat_demande_document_id),
        description: description || null
    };

    if (date_soumission) {
        data.date_soumission = date_soumission;
    }
    if (date_reponse) {
        data.date_reponse = date_reponse;
    }

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

    // Show loading state on button
    const saveBtn = document.querySelector('#formModal .btn-primary');
    const originalText = saveBtn.innerHTML;
    saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Enregistrement...';
    saveBtn.disabled = true;

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

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

function deleteDemande(id) {
    if (!confirm('Êtes-vous sûr de vouloir supprimer cette demande de document ?\n\nCette action est irréversible.')) return;

    const btn = document.querySelector(`button[onclick="deleteDemande(${id})"]`);
    if (btn) {
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
        btn.disabled = true;
    }

    fetch(`${API_BASE_URL}?action=delete&id=${id}`, {
        method: 'DELETE'
    })
        .then(response => response.json())
        .then(result => {
            if (btn) {
                btn.innerHTML = '<i class="fas fa-trash"></i>';
                btn.disabled = false;
            }

            if (result.success) {
                showToast(result.message, 'success');
                loadDemandes();
                loadStats();
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            if (btn) {
                btn.innerHTML = '<i class="fas fa-trash"></i>';
                btn.disabled = false;
            }
            showToast('Erreur de connexion au serveur', 'error');
            console.error('Error:', error);
        });
}

function exportDemandes() {
    window.location.href = `${API_BASE_URL}?action=export`;
}

function closeModal() {
    document.querySelector('#formModal').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');
    if (!container) {
        // Create container if it doesn't exist
        const newContainer = document.createElement('div');
        newContainer.className = 'toast-container';
        newContainer.id = 'toastContainer';
        document.body.appendChild(newContainer);
        return showToast(message, type);
    }

    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;
}

// Close modal on overlay click
document.querySelectorAll('.modal-overlay').forEach(modal => {
    modal.addEventListener('click', function(e) {
        if (e.target === this) {
            if (this.id === 'detailModal') {
                closeDetailModal();
            } else if (this.id === 'formModal') {
                closeModal();
            }
        }
    });
});

// Close modal on Escape key
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        if (document.getElementById('detailModal').classList.contains('active')) {
            closeDetailModal();
        } else if (document.querySelector('#formModal.active')) {
            closeModal();
        }
    }
});
function closeDetailModal() {
    document.getElementById('detailModal').classList.remove('active');
}
