// ECO-PANNEAU.FR - _react/clients/_clients_settings.jsx

// 1. - MODALE : GESTIONNAIRE DE FICHIERS (QUOTA)
const FileManagerModal = ({ onClose, showToast, refreshData }) => {
    const { useState, useEffect } = React;
    const { isMounted, safeFetch } = window.pano_useSafeFetch();
    const [files, setFiles] = useState([]);
    const [isLoading, setIsLoading] = useState(true);
    const [isDeleting, setIsDeleting] = useState(false);

    const { Trash2Icon, FileTextIcon, ShieldIcon, LoaderIcon, AlertTriangleIcon } = window.pano_getIcons();
    const { Button, Modal } = window.pano_getComponents();

    const fetchFiles = async () => {
        setIsLoading(true);
        const d = await safeFetch('clients/files/list', { method: 'GET', silent: true });
        if (!isMounted.current) return;
        if (d && d.status === 'success') {
            setFiles(d.data || []);
        }
        setIsLoading(false);
    };

    useEffect(() => { fetchFiles(); }, []);

    const handleDelete = async (fileId) => {
        const d = await safeFetch('clients/files/delete', {
            body: { file_id: fileId },
            setLoading: setIsDeleting,
            successMessage: "Fichier supprimé avec succès. Espace libéré."
        });
        if (!isMounted.current) return;
        if (d) {
            await fetchFiles();
            if (refreshData) refreshData();
        }
    };

    return (
        <Modal 
            title="Gestionnaire de fichiers" 
            onClose={onClose} 
            maxWidth="max-w-4xl"
            preventClose={isDeleting}
            actions={(close) => (
                <Button variant="primary" onClick={close} disabled={isDeleting} className="w-full py-3 uppercase tracking-widest justify-center shadow-md text-xs">
                    Fermer le gestionnaire
                </Button>
            )}
        >
            <div className="space-y-4 pb-2 min-h-[50vh] flex flex-col min-w-0">
                <p className="text-sm text-slate-500 leading-relaxed break-words">
                    Retrouvez ici l'ensemble des fichiers stockés sur votre compte. Les documents légaux (ex: Arrêtés, D.O.E) ne peuvent pas être supprimés manuellement pour des raisons de conformité.
                </p>

                {isLoading ? (
                    <div className="flex-1 flex flex-col items-center justify-center text-slate-400 py-10">
                        <LoaderIcon className="animate-spin w-8 h-8 mb-4" />
                        <span className="text-sm font-bold uppercase tracking-widest">Analyse de l'espace...</span>
                    </div>
                ) : files.length === 0 ? (
                    <div className="flex-1 flex flex-col items-center justify-center text-slate-400 py-10 bg-slate-50 rounded-xl border border-slate-200 border-dashed">
                        <FileTextIcon className="w-12 h-12 mb-4 opacity-50" />
                        <span className="text-sm font-medium">Aucun fichier volumineux trouvé sur votre compte.</span>
                    </div>
                ) : (
                    <div className="bg-white border border-slate-200 rounded-xl overflow-hidden shadow-sm flex-1 min-h-0 overflow-y-auto custom-scrollbar">
                        <table className="w-full text-left border-collapse min-w-0">
                            <thead className="bg-slate-50 sticky top-0 z-10 shadow-sm">
                                <tr>
                                    <th className="p-3 text-xs font-bold text-slate-500 uppercase tracking-widest border-b border-slate-200">Fichier</th>
                                    <th className="p-3 text-xs font-bold text-slate-500 uppercase tracking-widest border-b border-slate-200">Emplacement</th>
                                    <th className="p-3 text-xs font-bold text-slate-500 uppercase tracking-widest border-b border-slate-200 text-right">Taille</th>
                                    <th className="p-3 text-xs font-bold text-slate-500 uppercase tracking-widest border-b border-slate-200 text-center">Action</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-slate-100">
                                {files.map(f => (
                                    <tr key={f.id} className="hover:bg-slate-50/50 transition group">
                                        <td className="p-3 min-w-0">
                                            <div className="flex items-center gap-3 min-w-0">
                                                <div className="w-8 h-8 rounded bg-blue-50 text-blue-600 flex items-center justify-center shrink-0">
                                                    <FileTextIcon size={16} />
                                                </div>
                                                <div className="min-w-0">
                                                    <p className="text-sm font-bold text-slate-800 truncate" title={f.name}>{f.name}</p>
                                                    <p className="text-[10px] text-slate-400 truncate">{new Date(f.created_at).toLocaleDateString('fr-FR')}</p>
                                                </div>
                                            </div>
                                        </td>
                                        <td className="p-3 text-sm text-slate-600 font-medium truncate min-w-0 max-w-[150px]" title={f.context_label}>
                                            {f.context_label}
                                        </td>
                                        <td className="p-3 text-sm font-mono text-slate-700 text-right whitespace-nowrap">
                                            {parseFloat(f.size_mb).toFixed(2)} Mo
                                        </td>
                                        <td className="p-3 text-center w-24">
                                            {f.is_legal ? (
                                                <div className="inline-flex items-center justify-center w-8 h-8 rounded-full bg-slate-100 text-slate-400 cursor-not-allowed" title="Fichier légal obligatoire">
                                                    <ShieldIcon size={14} />
                                                </div>
                                            ) : (
                                                <Button 
                                                    variant="danger" 
                                                    shape="square" 
                                                    icon={Trash2Icon} 
                                                    onClick={() => handleDelete(f.id)} 
                                                    disabled={isDeleting}
                                                    title="Supprimer pour libérer de l'espace"
                                                    className="opacity-0 group-hover:opacity-100 transition-opacity w-8 h-8 p-0"
                                                />
                                            )}
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
            </div>
        </Modal>
    );
};

// 2. - MODALE : UPSELL DE FORFAIT (STORAGE PLAN)
const StoragePlanModal = ({ onClose, showToast, refreshData, clientData, adminData }) => {
    const { useState } = React;
    const { isMounted, safeFetch } = window.pano_useSafeFetch();
    const [isSaving, setIsSaving] = useState(false);

    const { HardDriveIcon, MinusIcon, PlusIcon, LoaderIcon, AlertTriangleIcon } = window.pano_getIcons();
    const { Button, Modal } = window.pano_getComponents();

    // Récupération des constantes d'admin
    const baseQuota = parseInt(adminData.settings?.quota_global_mb || 5000, 10);
    const stepGb = parseInt(adminData.settings?.quota_step_gb || 10, 10);
    const stepPrice = parseFloat(adminData.prices?.storage || 5);

    // Données client
    const usedMb = parseFloat(clientData.storage_used_mb || 0);
    const currentSteps = parseInt(clientData.storage_extra_gb || 0, 10) / stepGb;
    
    const [selectedSteps, setSelectedSteps] = useState(isNaN(currentSteps) ? 0 : Math.floor(currentSteps));

    // Calculs dynamiques
    const newTotalMb = baseQuota + (selectedSteps * stepGb * 1024);
    const newPrice = selectedSteps * stepPrice;
    const canDowngrade = newTotalMb >= usedMb;

    const handleSave = async () => {
        if (!canDowngrade) return;
        
        const extraGb = selectedSteps * stepGb;
        const d = await safeFetch('clients/profile/update_storage_plan', {
            body: { extra_gb: extraGb, price_mo: newPrice },
            setLoading: setIsSaving,
            successMessage: "Votre forfait de stockage a été mis à jour avec succès."
        });

        if (!isMounted.current) return;
        if (d) {
            if (refreshData) refreshData();
            onClose();
        }
    };

    return (
        <Modal 
            title="Modifier mon forfait de stockage" 
            onClose={onClose} 
            maxWidth="max-w-md"
            preventClose={isSaving}
            actions={(close) => (
                <>
                    <Button variant="secondary" onClick={close} disabled={isSaving} className="flex-1 py-3 justify-center text-xs">Annuler</Button>
                    <Button variant="primary" onClick={handleSave} disabled={isSaving || !canDowngrade || selectedSteps === (currentSteps || 0)} icon={isSaving ? LoaderIcon : null} className="flex-[2] py-3 uppercase tracking-widest justify-center shadow-md text-xs">
                        {isSaving ? 'Validation...' : 'Valider le forfait'}
                    </Button>
                </>
            )}
        >
            <div className="space-y-6 pb-2 min-w-0">
                <div className="text-center min-w-0">
                    <div className="w-16 h-16 bg-indigo-50 text-indigo-600 rounded-full flex items-center justify-center mx-auto mb-4 shrink-0">
                        <HardDriveIcon size={32} />
                    </div>
                    <p className="text-sm text-slate-600 font-medium leading-relaxed break-words">
                        Augmentez votre capacité de stockage pour conserver plus de photos, de D.O.E et d'historiques de messagerie. Sans engagement de durée.
                    </p>
                </div>

                <div className="bg-slate-50 border border-slate-200 rounded-xl p-4 space-y-4 min-w-0">
                    <div className="flex items-center justify-between min-w-0">
                        <span className="text-sm font-bold text-slate-700 break-words">Forfait de base (Inclus)</span>
                        <span className="text-sm font-mono text-slate-500">{(baseQuota / 1024).toFixed(2)} Go</span>
                    </div>

                    <div className="flex items-center justify-between border-t border-slate-200 pt-4 min-w-0">
                        <div className="min-w-0">
                            <span className="text-sm font-bold text-slate-800 break-words block mb-1">Paliers supplémentaires</span>
                            <span className="text-xs text-slate-500 block">+{stepGb} Go / {stepPrice} € HT mois</span>
                        </div>
                        <div className="flex items-center gap-3 bg-white border border-slate-200 rounded-lg p-1 shrink-0">
                            <Button variant="ghost" shape="square" icon={MinusIcon} onClick={() => setSelectedSteps(Math.max(0, selectedSteps - 1))} disabled={selectedSteps === 0 || isSaving} className="w-8 h-8 p-0 border-none shadow-none text-slate-600 hover:bg-slate-100" />
                            <span className="font-black text-slate-800 w-6 text-center">{selectedSteps}</span>
                            <Button variant="ghost" shape="square" icon={PlusIcon} onClick={() => setSelectedSteps(selectedSteps + 1)} disabled={isSaving} className="w-8 h-8 p-0 border-none shadow-none text-slate-600 hover:bg-slate-100" />
                        </div>
                    </div>
                </div>

                <div className="bg-indigo-600 text-white rounded-xl p-4 flex justify-between items-center shadow-md min-w-0">
                    <div className="min-w-0">
                        <p className="text-xs font-bold text-indigo-200 uppercase tracking-widest break-words mb-1">Nouveau Total</p>
                        <p className="text-2xl font-black break-words truncate">{(newTotalMb / 1024).toFixed(2)} Go</p>
                    </div>
                    <div className="text-right min-w-0">
                        <p className="text-xs font-bold text-indigo-200 uppercase tracking-widest break-words mb-1">Facturation</p>
                        <p className="text-2xl font-black break-words truncate">+{newPrice.toFixed(2)} € <span className="text-sm font-medium opacity-80">HT/mo</span></p>
                    </div>
                </div>

                {!canDowngrade && (
                    <div className="bg-red-50 border border-red-200 p-3 rounded-lg flex gap-3 animate-in fade-in zoom-in-95 min-w-0">
                        <AlertTriangleIcon className="text-red-600 shrink-0 w-5 h-5" />
                        <p className="text-xs text-red-700 font-bold leading-relaxed break-words min-w-0">
                            Vous consommez actuellement {(usedMb / 1024).toFixed(2)} Go. Vous devez d'abord supprimer des fichiers via le gestionnaire pour pouvoir revenir à ce forfait inférieur.
                        </p>
                    </div>
                )}
            </div>
        </Modal>
    );
};

// 3. - CONTENEUR PRINCIPAL (WRAPPER)
window.pano_ClientSettingsView = ({ data, refreshData, initialTab }) => {
    const { useState, useEffect } = React;
    const [activeDialog, setActiveDialog] = useState(null);
    const { SettingsIcon, UserIcon } = window.pano_getIcons();
    const { ClientSettingsProfile } = window.pano_getComponents(); // Le fichier précédent
    
    const myClientData = data.clients?.[0] || {};
    const adminData = { settings: data.settings, prices: data.prices };

    const openLocalDialog = (id) => setActiveDialog(id);
    const closeCurrentLayer = () => setActiveDialog(null);

    // Fonction simulée de Toast pour l'exemple
    const showToast = (msg, type) => { if (window.pano_showToast) window.pano_showToast(msg, type); };

    return (
        <div className="flex-1 flex flex-col min-h-0 bg-slate-50 w-full min-w-0">
            <div className="p-4 sm:p-6 lg:p-8 flex-1 min-h-0 overflow-y-auto custom-scrollbar w-full min-w-0 pb-32">
                <div className="flex items-center gap-3 mb-8 min-w-0">
                    <div className="w-12 h-12 rounded-2xl bg-indigo-100 text-indigo-600 flex items-center justify-center shrink-0 shadow-inner">
                        <SettingsIcon size={24} />
                    </div>
                    <div className="min-w-0">
                        <h1 className="text-2xl sm:text-3xl font-black text-slate-800 tracking-tight truncate break-words">Mon Compte</h1>
                        <p className="text-slate-500 font-medium text-sm sm:text-base truncate break-words">Paramètres, facturation et stockage</p>
                    </div>
                </div>

                {/* Inclusion du profil client (Le fichier précédent) */}
                {ClientSettingsProfile && (
                    <ClientSettingsProfile 
                        myClientData={myClientData} 
                        data={data} 
                        showToast={showToast} 
                        refreshData={refreshData} 
                        openLocalDialog={openLocalDialog} 
                        closeCurrentLayer={closeCurrentLayer} 
                        activeDialog={activeDialog} 
                    />
                )}
            </div>

            {/* MODALES EXTERNES APPELLÉES PAR LE PROFIL */}
            {activeDialog === 'file_manager' && (
                <FileManagerModal 
                    onClose={closeCurrentLayer} 
                    showToast={showToast} 
                    refreshData={refreshData} 
                />
            )}

            {activeDialog === 'storage_plan' && (
                <StoragePlanModal 
                    onClose={closeCurrentLayer} 
                    showToast={showToast} 
                    refreshData={refreshData} 
                    clientData={myClientData} 
                    adminData={adminData} 
                />
            )}
        </div>
    );
};

/* EOF ========== [_react/clients/_clients_settings.jsx] */