/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Interface Administrateur - Modales : Système (Code, Logs, Diagnostics)
 * =========================================================================
 */

window.pano_AdminModalsSystem = ({ activeModal, closeCurrentLayer, showToast }) => {
    const { useState, useEffect } = React;
    const [isSaving, setIsSaving] = useState(false);

    // 1. ÉTATS
    const [codeStats, setCodeStats] = useState(null);
    const [sortConfig, setSortConfig] = useState({ key: 'lines', direction: 'desc' });
    const [logs, setLogs] = useState('');
    const [diagnostics, setDiagnostics] = useState([]);

    // 2. COMPOSANTS ET ICÔNES
    const Modal = window.pano_Modal || (() => null);
    const Button = window.pano_Button || (() => null);
    const { ActivityIcon, TerminalIcon, FileDigitIcon, Trash2Icon, CopyIcon, CheckCircleIcon } = window.pano_getIcons();

    // 3. CHARGEMENT DYNAMIQUE
    useEffect(() => {
        if (activeModal === 'code_stats') loadCodeStats();
        if (activeModal === 'logs') loadLogs();
        if (activeModal === 'diagnostics') loadDiagnostics();
    }, [activeModal]);

    const loadCodeStats = async () => {
        // CORRECTION : Ajout de { method: 'GET' }
        const d = await window.pano_apiFetch('system/code_stats', { method: 'GET' });
        if (d && d.status === 'success') setCodeStats(d.data);
    };

    const loadLogs = async () => {
        // CORRECTION : Ajout de { method: 'GET' }
        const d = await window.pano_apiFetch('system/logs', { method: 'GET' });
        if (d && d.status === 'success') setLogs(d.data?.logs || '');
    };

    const loadDiagnostics = async () => {
        // CORRECTION : Ajout de { method: 'GET' }
        const d = await window.pano_apiFetch('system/diagnostics', { method: 'GET' });
        if (d && d.status === 'success') setDiagnostics(d.data || []);
    };

    // 4. HANDLERS JOURNAUX (LOGS)
    const handleClearLogs = async () => {
        const d = await window.pano_apiFetch('system/clear_logs', {
            method: 'POST', // Nettoyer les logs devrait être un POST
            setLoading: setIsSaving,
            successMessage: "Journaux purgés."
        });
        if (d) setLogs('');
    };

    const handleCopyLogs = () => {
        navigator.clipboard.writeText(logs);
        if (showToast) showToast("Journaux copiés dans le presse-papiers.", "success");
    };

    // 5. TRI DES FICHIERS (CODE STATS)
    const sortedFiles = React.useMemo(() => {
        if (!codeStats || !codeStats.files) return [];
        let sortableItems = [...codeStats.files];
        if (sortConfig !== null) {
            sortableItems.sort((a, b) => {
                if (a[sortConfig.key] < b[sortConfig.key]) return sortConfig.direction === 'asc' ? -1 : 1;
                if (a[sortConfig.key] > b[sortConfig.key]) return sortConfig.direction === 'asc' ? 1 : -1;
                return 0;
            });
        }
        return sortableItems;
    }, [codeStats, sortConfig]);

    const requestSort = (key) => {
        let direction = 'asc';
        if (sortConfig && sortConfig.key === key && sortConfig.direction === 'asc') direction = 'desc';
        setSortConfig({ key, direction });
    };

    // 6. RENDU
    return (
        <>
            {/* STATS DU CODE SOURCE */}
            {activeModal === 'code_stats' && (
                <Modal title="Statistiques du code" onClose={closeCurrentLayer} icon={FileDigitIcon} zIndex="z-[200]">
                    {!codeStats ? (
                        <div className="p-8 text-center text-slate-500 animate-pulse font-medium">Analyse des fichiers en cours...</div>
                    ) : (
                        <div className="space-y-6">
                            <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
                                <div className="bg-slate-50 p-4 rounded-2xl border border-slate-200 text-center">
                                    <p className="text-xl font-black text-slate-800">{codeStats.totalLines.toLocaleString('fr-FR')}</p>
                                    <p className="text-[10px] font-bold uppercase tracking-widest text-slate-500 mt-1">Lignes totales</p>
                                </div>
                                <div className="bg-slate-50 p-4 rounded-2xl border border-slate-200 text-center">
                                    <p className="text-xl font-black text-slate-800">{codeStats.totalChars.toLocaleString('fr-FR')}</p>
                                    <p className="text-[10px] font-bold uppercase tracking-widest text-slate-500 mt-1">Caractères</p>
                                </div>
                                <div className="bg-slate-50 p-4 rounded-2xl border border-slate-200 text-center">
                                    <p className="text-xl font-black text-slate-800">{codeStats.totalFiles.toLocaleString('fr-FR')}</p>
                                    <p className="text-[10px] font-bold uppercase tracking-widest text-slate-500 mt-1">Fichiers analysés</p>
                                </div>
                                <div className="bg-slate-50 p-4 rounded-2xl border border-slate-200 text-center">
                                    <p className="text-xl font-black text-slate-800">{codeStats.totalSizeMB.toFixed(2)} Mo</p>
                                    <p className="text-[10px] font-bold uppercase tracking-widest text-slate-500 mt-1">Poids (Code seul)</p>
                                </div>
                            </div>
                            <div className="bg-white rounded-2xl border border-slate-200 overflow-hidden shadow-sm">
                                <div className="overflow-x-auto">
                                    <table className="w-full text-left border-collapse">
                                        <thead>
                                            <tr className="bg-slate-50 border-b border-slate-200 text-xs text-slate-500">
                                                <th className="p-3 font-bold cursor-pointer hover:bg-slate-100 transition" onClick={() => requestSort('name')}>
                                                    Fichier {sortConfig?.key === 'name' ? (sortConfig.direction === 'asc' ? '↑' : '↓') : ''}
                                                </th>
                                                <th className="p-3 font-bold cursor-pointer hover:bg-slate-100 transition" onClick={() => requestSort('type')}>
                                                    Type {sortConfig?.key === 'type' ? (sortConfig.direction === 'asc' ? '↑' : '↓') : ''}
                                                </th>
                                                <th className="p-3 font-bold cursor-pointer hover:bg-slate-100 transition text-right" onClick={() => requestSort('lines')}>
                                                    Lignes {sortConfig?.key === 'lines' ? (sortConfig.direction === 'asc' ? '↑' : '↓') : ''}
                                                </th>
                                                <th className="p-3 font-bold cursor-pointer hover:bg-slate-100 transition text-right" onClick={() => requestSort('chars')}>
                                                    Caractères {sortConfig?.key === 'chars' ? (sortConfig.direction === 'asc' ? '↑' : '↓') : ''}
                                                </th>
                                            </tr>
                                        </thead>
                                        <tbody className="divide-y divide-slate-100 text-sm">
                                            {sortedFiles.map((f, i) => (
                                                <tr key={i} className="hover:bg-slate-50 transition">
                                                    <td className="p-3 font-bold text-slate-700 truncate max-w-[200px]" title={f.name}>{f.name}</td>
                                                    <td className="p-3 text-slate-500">{f.type}</td>
                                                    <td className="p-3 text-right font-mono text-slate-600">{f.lines.toLocaleString('fr-FR')}</td>
                                                    <td className="p-3 text-right font-mono text-slate-600">{f.chars.toLocaleString('fr-FR')}</td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    )}
                </Modal>
            )}

            {/* JOURNAUX D'ERREURS */}
            {activeModal === 'logs' && (
                <Modal title="Journaux système (PHP Error Log)" onClose={closeCurrentLayer} icon={TerminalIcon} zIndex="z-[200]">
                    <div className="space-y-4">
                        <div className="flex justify-between items-center">
                            <p className="text-sm text-slate-500">Trace technique des erreurs et alertes serveur.</p>
                            <div className="flex gap-2">
                                <Button variant="secondary" icon={CopyIcon} onClick={handleCopyLogs} disabled={!logs}>Copier</Button>
                                <Button variant="danger" icon={Trash2Icon} onClick={handleClearLogs} disabled={isSaving || !logs}>Purger</Button>
                            </div>
                        </div>
                        <div className="bg-slate-900 text-emerald-400 p-4 rounded-2xl font-mono text-xs overflow-auto h-[50vh] custom-scrollbar whitespace-pre shadow-inner leading-relaxed">
                            {logs || "Aucune erreur enregistrée dans le journal (Fichier error_log vide)."}
                        </div>
                    </div>
                </Modal>
            )}

            {/* DIAGNOSTICS */}
            {activeModal === 'diagnostics' && (
                <Modal title="Diagnostics système" onClose={closeCurrentLayer} icon={ActivityIcon} zIndex="z-[200]">
                    <div className="space-y-6">
                        <p className="text-sm text-slate-500">État de santé des services et de l'environnement d'hébergement.</p>
                        <div className="space-y-3">
                            {diagnostics.length > 0 ? diagnostics.map((d, i) => {
                                let statusColor = 'text-emerald-500';
                                if (d.status === 'warning') statusColor = 'text-amber-500';
                                if (d.status === 'error') statusColor = 'text-red-500';

                                return (
                                    <div key={i} className="flex flex-col sm:flex-row justify-between sm:items-center p-4 bg-slate-50 border border-slate-200 rounded-2xl gap-2 transition hover:border-emerald-200">
                                        <div>
                                            <p className="font-bold text-slate-800 text-sm flex items-center gap-2">
                                                {d.name}
                                                {d.status === 'success' && <CheckCircleIcon size={14} className={statusColor} />}
                                                {d.status !== 'success' && <ActivityIcon size={14} className={statusColor} />}
                                            </p>
                                        </div>
                                        <div className="text-right">
                                            <p className={`font-mono text-sm font-bold ${statusColor}`}>{d.detail}</p>
                                        </div>
                                    </div>
                                );
                            }) : (
                                <div className="p-8 text-center text-slate-500 animate-pulse font-medium">Récupération des diagnostics...</div>
                            )}
                        </div>
                    </div>
                </Modal>
            )}
        </>
    );
};

/* EOF ========== [_react/_admin_modals_system.jsx] */