/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Composant : Modale du coffre-fort légal et upload des preuves
 * =========================================================================
 */

const { useState } = React;

window.ClientLegalVaultModal = ({ managingPanneau, setManagingPanneau, onClose, refreshData, showToast }) => {
    const LockIcon = window.LockIcon || (() => null);
    const ArrowUpIcon = window.ArrowUpIcon || (() => null);
    const Trash2Icon = window.Trash2Icon || (() => null);
    const LoaderIcon = window.LoaderIcon || (() => null);
    
    // COMPOSANTS GLOBAUX NETTOYÉS ET FACTORISÉS
    const Modal = window.Modal;
    const AlertBox = window.AlertBox;
    const ConfirmModal = window.ConfirmModal;
    const Button = window.Button;
    const VaultDocumentThumbnail = window.VaultDocumentThumbnail || (() => null);
    const VaultDocumentViewer = window.VaultDocumentViewer || (() => null);
    const UploadErrorsModal = window.UploadErrorsModal || (() => null);
    
    const [isSaving, setIsSaving] = useState(false);
    const [uploadStats, setUploadStats] = useState({ current: 0, total: 0 });
    const [uploadDetail, setUploadDetail] = useState('');
    const [vaultDragging, setVaultDragging] = useState(false);
    const [viewingDoc, setViewingDoc] = useState(null);
    const [confirmDialog, setConfirmDialog] = useState(null);
    const [uploadErrors, setUploadErrors] = useState([]);

    const handleVaultUpload = async (fileList) => {
        if (!fileList || fileList.length === 0) return;
        const files = Array.from(fileList);
        let currentTotalSize = managingPanneau.privateDocs?.reduce((acc, doc) => acc + (doc.size || 0), 0) || 0;
        
        setIsSaving(true);
        setUploadStats({ current: 1, total: files.length });
        setUploadDetail('préparation');
        let currentDocs = [...(managingPanneau.privateDocs || [])];
        let hasChanges = false;
        let currentErrors = [];
        
        for (let i = 0; i < files.length; i++) {
            setUploadStats({ current: i + 1, total: files.length });
            setUploadDetail('préparation');
            const file = files[i];
            
            if (file.size > 10 * 1024 * 1024) { 
                currentErrors.push({ file: file.name, reason: "Taille > 10 Mo" }); 
                continue; 
            }
            if (currentTotalSize + file.size > 250 * 1024 * 1024) { 
                currentErrors.push({ file: file.name, reason: "Dépassement du quota (250 Mo)" }); 
                continue; 
            }
            
            try {
                const type = file.type.includes('pdf') ? 'pdf' : (file.type.startsWith('image/') ? 'image' : null);
                if (!type) {
                    currentErrors.push({ file: file.name, reason: "Format non supporté" });
                    continue;
                }

                // CORRECTION DE SIGNATURE : Suppression du 5ème argument redondant et passage propre des booléens publics/privés
                const fileId = await window.uploadFile(file, type, (msg) => setUploadDetail(msg), false, true, managingPanneau.client_uid, managingPanneau.id);
                
                const newDoc = { 
                    id: fileId.toString(), 
                    type, 
                    name: file.name, 
                    date: new Date().toLocaleDateString('fr-FR'), 
                    size: file.size, 
                    numPages: fileId.numPages || 1 
                };

                currentDocs = [...currentDocs, newDoc];
                currentTotalSize += file.size;
                hasChanges = true;
                
                // CORRECTION BDD : Mise à jour immédiate de la base de données et de l'UI
                const updatedPanneau = {...managingPanneau, privateDocs: currentDocs};
                setManagingPanneau(updatedPanneau);
                
                await window.apiFetch('panneaux', { 
                    body: { id: updatedPanneau.id, status: updatedPanneau.status, offerType: updatedPanneau.offerType, physicalPanels: updatedPanneau.physicalPanels, details: updatedPanneau }
                });
                
            } catch(err) { 
                currentErrors.push({ file: file.name, reason: err.message || err || "Fichier invalide ou corrompu" }); 
            }
        }
        
        if (hasChanges) refreshData();
         
        setIsSaving(false);
        setUploadStats({ current: 0, total: 0 });
        setUploadDetail('');

        if (currentErrors.length > 0) {
            setUploadErrors(currentErrors);
        }
    };

    return (
        <>
            <Modal title="Coffre-fort légal privé" type="info" onClose={onClose} preventClose={isSaving} zIndex="z-[200]">
                <div className="space-y-6">
                    
                    <AlertBox type="info" icon={LockIcon} title="Preuves et constats d'huissier">
                        Ces documents sont chiffrés et inaccessibles au public. Ils seront inclus dans l'archive D.O.E lors de la clôture du panneau.
                    </AlertBox>

                    <div 
                        onDragEnter={(e) => { e.preventDefault(); setVaultDragging(true); }}
                        onDragLeave={(e) => { e.preventDefault(); setVaultDragging(false); }}
                        onDragOver={(e) => e.preventDefault()}
                        onDrop={(e) => { e.preventDefault(); setVaultDragging(false); handleVaultUpload(e.dataTransfer.files); }}
                        className={`w-full min-h-[150px] border-2 border-dashed rounded-xl flex flex-col items-center justify-center p-6 transition relative ${vaultDragging ? 'border-emerald-500 bg-emerald-50/50' : 'border-slate-300 bg-slate-50 hover:bg-slate-100'}`}
                        title="Vous pouvez également coller vos fichiers (Ctrl+V) directement sur cette fenêtre."
                    >
                        {isSaving ? (
                            <div className="flex flex-col items-center text-slate-500 text-center">
                                <LoaderIcon size={32} className="animate-spin mb-2 mx-auto"/> 
                                <span className="text-sm font-bold">Traitement en cours...</span>
                                <span className="text-[10px] mt-1 font-bold">Fichier {uploadStats.current}/{uploadStats.total} {uploadDetail ? `(${uploadDetail})` : ''}</span>
                            </div>
                        ) : (
                            <>
                                <div className="w-12 h-12 bg-white rounded-full flex items-center justify-center shadow-sm mb-3 text-slate-400"><ArrowUpIcon size={24}/></div>
                                <span className="text-sm font-bold text-slate-700">Glissez-déposez vos preuves ici (ou Ctrl+V)</span>
                                <span className="text-xs text-slate-500 mt-1 text-center">Images ou PDF (Max 10 Mo/fichier, 250 Mo au total)</span>
                                <label className="mt-4 px-4 py-2 bg-white border border-slate-200 text-slate-700 rounded-lg text-xs font-bold shadow-sm hover:bg-slate-50 cursor-pointer transition">
                                    Parcourir les fichiers
                                    <input type="file" multiple accept="application/pdf,image/*" className="hidden" onChange={(e) => { if(e.target.files) handleVaultUpload(e.target.files); e.target.value = null; }} />
                                </label>
                            </>
                        )}
                    </div>

                    {managingPanneau.privateDocs && managingPanneau.privateDocs.length > 0 ? (
                        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4 mt-6">
                            {managingPanneau.privateDocs.map((doc, idx) => (
                                <div key={idx} className="relative group rounded-xl border border-slate-200 overflow-hidden bg-slate-50 shadow-sm flex flex-col cursor-pointer transition hover:border-emerald-300 hover:shadow-md" onClick={() => setViewingDoc(doc)}>
                                    <div className="h-24 w-full bg-white flex items-center justify-center p-2 shrink-0">
                                        <VaultDocumentThumbnail doc={doc} />
                                    </div>
                                    <div className="p-2 border-t border-slate-100 flex-1 flex flex-col justify-between">
                                        <p className="text-[10px] font-bold text-slate-700 truncate" title={doc.name}>{doc.name}</p>
                                        <div className="flex justify-between items-center mt-2">
                                            <span className="text-[9px] font-bold text-slate-400">{doc.date}</span>
                                            <Button variant="danger" icon={Trash2Icon} onClick={(e) => { 
                                                e.stopPropagation();
                                                setConfirmDialog({
                                                    title: "Supprimer le document",
                                                    message: "Voulez-vous vraiment supprimer ce document privé ?",
                                                    confirmText: "Supprimer",
                                                    isDestructive: true,
                                                    onConfirm: async () => {
                                                        setConfirmDialog(null);
                                                        const newDocs = [...managingPanneau.privateDocs]; newDocs.splice(idx, 1);
                                                        const updatedPanneau = {...managingPanneau, privateDocs: newDocs};
                                                        setManagingPanneau(updatedPanneau); 
                                                        
                                                        // Appel API pour suppression physique silencieuse
                                                        await window.apiFetch('file/delete', { body: { id: doc.id } });

                                                        const d = await window.apiFetch('panneaux', { 
                                                            body: { id: updatedPanneau.id, status: updatedPanneau.status, offerType: updatedPanneau.offerType, physicalPanels: updatedPanneau.physicalPanels, details: updatedPanneau }
                                                        });
                                                        
                                                        if (d) refreshData();
                                                    }
                                                });
                                            }} className="p-1.5" title="Supprimer" />
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    ) : (
                        <p className="text-center text-sm text-slate-400 py-4 italic">Aucun document privé stocké.</p>
                    )}
                    
                    <div className="text-right">
                        <span className="text-xs font-bold text-slate-400">Total utilisé : {((managingPanneau.privateDocs?.reduce((acc, doc) => acc + (doc.size || 0), 0) || 0) / (1024*1024)).toFixed(2)} Mo / 250 Mo</span>
                    </div>
                </div>

                {confirmDialog && ConfirmModal && (
                    <ConfirmModal 
                        {...confirmDialog} 
                        onCancel={() => setConfirmDialog(null)} 
                        zIndex="z-[350]" 
                    />
                )}
            </Modal>

            {viewingDoc && VaultDocumentViewer && (
                <VaultDocumentViewer viewingDoc={viewingDoc} setViewingDoc={setViewingDoc} />
            )}

            {uploadErrors.length > 0 && UploadErrorsModal && (
                <UploadErrorsModal errors={uploadErrors} onClose={() => setUploadErrors([])} zIndex="z-[300]" />
            )}
        </>
    );
};

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