/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Interface Client B2B (Tableau de bord, Facturation, Gestion des panneaux)
 * =========================================================================
 */

const { useState, useEffect } = React;
const { 
    Home, Building, MessageSquare, FileText, UserCircle, Plus, Search, 
    CheckCircle, AlertTriangle, Shield, Copy, Archive, Trash2, Edit, Eye,
    CreditCard, Download, Loader, LogOut, ArrowLeft, KeyRound,
    Lock, ShieldCheck, Mail, Users, Bell, Power, Settings, FileCheck, Image, X, Zap, Package, Share2, RefreshCw, MapPin, ExternalLink
} = window;

// =========================================================================
// 1. COMPOSANT STRIPE : FORMULAIRE DE PAIEMENT
// =========================================================================

const StripePaymentForm = ({ clientSecret, onSuccess, onCancel, amountCents }) => {
    const stripe = window.Stripe(window.ECO_CONFIG.stripePubKey);
    const options = { clientSecret, appearance: { theme: 'stripe', variables: { colorPrimary: '#10b981', borderRadius: '12px' } } };

    const CheckoutForm = () => {
        const stripeInstance = window.ReactStripe.useStripe();
        const elements = window.ReactStripe.useElements();
        const [isProcessing, setIsProcessing] = useState(false);
        const [error, setError] = useState(null);

        const handleSubmit = async (e) => {
            e.preventDefault();
            if (!stripeInstance || !elements) return;
            setIsProcessing(true); setError(null);
            
            const { error: submitError } = await elements.submit();
            if (submitError) { setError(submitError.message); setIsProcessing(false); return; }

            const { error: confirmError, paymentIntent } = await stripeInstance.confirmPayment({
                elements, confirmParams: { return_url: window.location.href }, redirect: "if_required"
            });

            if (confirmError) { setError(confirmError.message); setIsProcessing(false); } 
            else if (paymentIntent && paymentIntent.status === "succeeded") { onSuccess(paymentIntent.id); }
            else { setError("Statut de paiement inattendu."); setIsProcessing(false); }
        };

        return (
            <form onSubmit={handleSubmit} className="space-y-6">
                <div className="bg-slate-50 p-4 rounded-xl mb-4 border border-slate-200 relative overflow-hidden">
                    <p className="text-sm font-bold text-slate-700 text-center mt-2">
                        Montant à régler : <span className="text-lg text-emerald-600 font-black">{amountCents ? (amountCents / 100).toFixed(2) : "0.00"} € TTC</span>
                    </p>
                </div>
                <window.ReactStripe.PaymentElement />
                {error && <div className="p-3 bg-red-50 text-red-600 text-sm font-bold rounded-xl border border-red-200 flex items-center gap-2"><AlertTriangle size={16}/> {error}</div>}
                <div className="flex gap-3 pt-4">
                    <button type="button" onClick={onCancel} disabled={isProcessing} title="Annuler le paiement" className="px-6 py-3 rounded-xl font-bold text-slate-500 hover:bg-slate-100 transition disabled:opacity-50">Annuler</button>
                    <button type="submit" disabled={isProcessing || !stripeInstance || !elements} title="Confirmer le paiement" className="flex-1 bg-emerald-600 text-white py-3 rounded-xl font-black uppercase tracking-widest hover:bg-emerald-700 transition shadow-lg flex items-center justify-center gap-2 disabled:opacity-50">
                        {isProcessing ? <Loader className="animate-spin w-5 h-5"/> : <CreditCard size={18}/>} Payer et activer
                    </button>
                </div>
            </form>
        );
    };

    return (
        <window.ReactStripe.Elements stripe={stripe} options={options}>
            <CheckoutForm />
        </window.ReactStripe.Elements>
    );
};

// =========================================================================
// 2. VUE PRINCIPALE DU CLIENT B2B
// =========================================================================

window.ClientView = ({ data, refreshData, showToast }) => {
    const [activeTab, setActiveTab] = useState('dashboard');
    const [uiMode, setUiMode] = useState('simplifie');
    const [pushEnabled, setPushEnabled] = useState(localStorage.getItem('eco_push_enabled') === 'true' && window.Notification?.permission === 'granted');
    
    const [managingChantier, setManagingChantier] = useState(null);
    const [editingEntity, setEditingEntity] = useState(null);
    const [draggedItem, setDraggedItem] = useState(null);
    const [isSaving, setIsSaving] = useState(false);
    
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [modalStep, setModalStep] = useState('config_full');
    const [validationErrors, setValidationErrors] = useState([]);
    const [delegateLink, setDelegateLink] = useState('');
    const [paymentData, setPaymentData] = useState(null);
    const [previewChantier, setPreviewChantier] = useState(null);
    
    const [profileData, setProfileData] = useState({ name: '', address: '', siret: '', tva: '', monthlyReport: 0 });
    const [hasTva, setHasTva] = useState(true);
    const [showTvaWarning, setShowTvaWarning] = useState(false);
    
    const [passwordData, setPasswordData] = useState({ oldPassword: '', newPassword: '' });
    const [teamEmail, setTeamEmail] = useState('');

    const [meRes, setMeRes] = useState(null);
    useEffect(() => { 
        fetch(window.ECO_CONFIG.apiBaseUrl + 'auth/me').then(r=>r.json()).then(d=>setMeRes(d.data)); 
    }, []);

    const myClientData = data.clients?.find(c => c.id === meRes?.user_id) || data.clients?.[0] || {};
    const isSuspended = myClientData.paymentStatus === 'suspended';
    const isCollaborator = !data.team; 
    const isImpersonating = meRes?.is_impersonating;

    useEffect(() => {
        if (myClientData.uiMode) setUiMode(myClientData.uiMode);
        
        const isTvaExempt = myClientData.tva === 'NON_ASSUJETTI';
        setHasTva(!isTvaExempt);
        
        setProfileData({
            name: myClientData.name || '', address: myClientData.address || '',
            siret: myClientData.siret || '', tva: isTvaExempt ? '' : (myClientData.tva || ''),
            monthlyReport: myClientData.monthlyReport || 0
        });
    }, [myClientData]);

    // Interception du lien magique de validation de réception (depuis l'e-mail logistique)
    useEffect(() => {
        const url = new URL(window.location);
        const confirmDelivery = url.searchParams.get('confirm_delivery');
        if (confirmDelivery) {
            setActiveTab('livraisons');
            if (window.confirm("Avez-vous bien reçu vos panneaux pour ce chantier ?")) {
                setIsSaving(true);
                fetch(window.ECO_CONFIG.apiBaseUrl + 'chantiers/shipping', {
                    method: 'POST',
                    body: JSON.stringify({ id: confirmDelivery, shipping_status: 'Livré' })
                }).then(res => res.json()).then(d => {
                    if (d.status === 'success') {
                        showToast("Réception confirmée, merci !");
                        refreshData();
                    }
                }).finally(() => setIsSaving(false));
            }
            url.searchParams.delete('confirm_delivery');
            window.history.replaceState({}, '', url);
        }
    }, []);

    const activeChantiers = data.chantiers?.filter(c => c.status === 'Actif') || [];
    const draftChantiers = data.chantiers?.filter(c => c.status === 'Brouillon') || [];
    const interactions = data.interactions || [];
    const totalUnread = interactions.filter(m => !m.resolved && m.author !== 'Client').length;
    const activeDeliveries = data.chantiers?.filter(c => c.physicalPanels > 0 && c.shipping_status !== 'Livré') || [];

    const handleLogout = async () => {
        await fetch(window.ECO_CONFIG.apiBaseUrl + 'auth/logout');
        window.location.href = '?';
    };

    const handleUnimpersonate = async () => {
        const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'auth/unimpersonate', { method: 'POST' });
        const d = await res.json();
        if (d.status === 'success') { window.location.href = '?'; } else { showToast(d.message, 'error'); }
    };

    const customLogout = isImpersonating ? {
        label: "Retour Admin",
        icon: <ArrowLeft size={18}/>,
        action: () => handleUnimpersonate()
    } : null;

    const navItems = [
        { id: 'dashboard', icon: <Home size={18}/>, label: 'Tableau de bord', badge: 0 },
        { id: 'panels', icon: <Building size={18}/>, label: 'Mes chantiers', badge: 0 },
        { id: 'livraisons', icon: <Package size={18}/>, label: 'Livraisons', badge: activeDeliveries.length },
        { id: 'messages', icon: <MessageSquare size={18}/>, label: 'Messagerie', badge: totalUnread },
        ...(isCollaborator ? [] : [{ id: 'billing', icon: <FileText size={18}/>, label: 'Factures', badge: 0 }]),
        { id: 'account', icon: <UserCircle size={18}/>, label: 'Mon compte', badge: 0 },
    ];

    const saveEditedEntity = () => {
        let newInter = [...(managingChantier.intervenants || [])];
        let newLots = JSON.parse(JSON.stringify(managingChantier.lots || []));
        const loc = editingEntity.location;

        if (loc.type === 'intervenant') {
            if (loc.index !== undefined) newInter[loc.index] = editingEntity.data;
            else newInter.push({...editingEntity.data, id: crypto.randomUUID()});
        } else if (loc.type === 'lot') {
            if (loc.index !== undefined) newLots[loc.index] = {...newLots[loc.index], ...editingEntity.data};
            else newLots.push({...editingEntity.data, id: crypto.randomUUID(), entreprises: []});
        } else if (loc.type === 'entreprise') {
            if (loc.index !== undefined) newLots[loc.lotIndex].entreprises[loc.index] = editingEntity.data;
            else newLots[loc.lotIndex].entreprises.push({...editingEntity.data, id: crypto.randomUUID()});
        }
        setManagingChantier({ ...managingChantier, intervenants: newInter, lots: newLots });
        setEditingEntity(null);
    };

    const deleteEntity = (loc) => {
        if (!confirm("Supprimer cet élément ?")) return;
        let newInter = [...(managingChantier.intervenants || [])];
        let newLots = JSON.parse(JSON.stringify(managingChantier.lots || []));
        if (loc.type === 'intervenant') newInter.splice(loc.index, 1);
        else if (loc.type === 'lot') newLots.splice(loc.index, 1);
        else newLots[loc.lotIndex].entreprises.splice(loc.index, 1);
        setManagingChantier({ ...managingChantier, intervenants: newInter, lots: newLots });
    };

    const handleDragStart = (e, location) => { setDraggedItem(location); e.dataTransfer.effectAllowed = 'move'; };
    const handleDragOver = (e) => { e.preventDefault(); e.dataTransfer.dropEffect = 'move'; };
    const handleDrop = (e, dropLocation) => {
        e.preventDefault();
        if (!draggedItem || draggedItem.type !== dropLocation.type) return;
        if (draggedItem.type === 'entreprise' && draggedItem.lotIndex !== dropLocation.lotIndex) return;
        
        let newInter = [...(managingChantier.intervenants || [])];
        let newLots = JSON.parse(JSON.stringify(managingChantier.lots || []));
        
        if (draggedItem.type === 'intervenant') {
            const item = newInter.splice(draggedItem.index, 1)[0];
            newInter.splice(dropLocation.index, 0, item);
        } else if (draggedItem.type === 'lot') {
            const item = newLots.splice(draggedItem.index, 1)[0];
            newLots.splice(dropLocation.index, 0, item);
        } else if (draggedItem.type === 'entreprise') {
            const arr = newLots[dropLocation.lotIndex].entreprises;
            const item = arr.splice(draggedItem.index, 1)[0];
            arr.splice(dropLocation.index, 0, item);
        }
        setManagingChantier({ ...managingChantier, intervenants: newInter, lots: newLots });
        setDraggedItem(null);
    };

    const validatePanel = () => {
        const errors = [];
        if (!managingChantier.name?.trim()) errors.push("Le nom du chantier est manquant.");
        if (!managingChantier.location?.trim()) errors.push("L'adresse du chantier est manquante.");
        if (!managingChantier.pdfId) errors.push("L'arrêté légal (PDF) n'a pas été uploadé.");
        
        if (!isCollaborator) {
            if (!profileData.name?.trim()) errors.push("Facturation : raison sociale manquante (onglet Mon compte).");
            if (!profileData.address?.trim()) errors.push("Facturation : adresse postale manquante (onglet Mon compte).");
            if (!profileData.siret?.trim()) errors.push("Facturation : SIRET de l'entreprise manquant (onglet Mon compte).");
        }
        return errors;
    };

    const handleSaveChantier = async (forceDraft = false) => {
        if (!forceDraft && managingChantier.status === 'Actif') {
            const errs = validatePanel();
            if (errs.length > 0) { setValidationErrors(errs); return; }
        }

        setIsSaving(true);
        try {
            const payload = { 
                id: managingChantier.id, 
                status: managingChantier.status, 
                offerType: managingChantier.offerType, 
                currentRate: managingChantier.currentRate, 
                physicalPanels: managingChantier.physicalPanels, 
                details: { ...managingChantier, name: managingChantier.name?.trim() || 'Brouillon sans nom', location: managingChantier.location?.trim() || '' } 
            };
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'chantiers', { method: 'POST', body: JSON.stringify(payload) });
            const d = await res.json();
            if(d.status === 'success') { showToast(forceDraft ? "Brouillon sauvegardé !" : "Chantier mis à jour !"); setIsModalOpen(false); refreshData(); }
            else showToast(d.message, 'error');
        } catch(e) { showToast("Erreur de sauvegarde", "error"); }
        setIsSaving(false);
    };

    const handleActivationRequest = async () => {
        if(isSuspended) return showToast("Votre compte est suspendu. Veuillez régulariser vos factures.", "error");
        
        setIsSaving(true);
        try {
            const payload = { chantier_id: managingChantier.id, offer_type: managingChantier.offerType, physical_panels: managingChantier.physicalPanels, hasNoAds: managingChantier.hasNoAds };
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'stripe/intent', { method: 'POST', body: JSON.stringify(payload) });
            const d = await res.json();
            
            if(d.status === 'success') {
                if(d.data.free_activation_required) {
                    const freeRes = await fetch(window.ECO_CONFIG.apiBaseUrl + 'chantiers/activate_free', { method: 'POST', body: JSON.stringify({ ...payload, id: managingChantier.id, offerType: managingChantier.offerType, physicalPanels: managingChantier.physicalPanels, details: managingChantier, name: managingChantier.name }) });
                    if((await freeRes.json()).status === 'success') { showToast("Activation gratuite réussie !"); setIsModalOpen(false); refreshData(); }
                    else showToast("Erreur d'activation", "error");
                } else {
                    setPaymentData({ secret: d.data.clientSecret, subId: d.data.subscription_id, amountCents: d.data.amountCents });
                    setModalStep('payment');
                }
            } else showToast(d.message, 'error');
        } catch(e) { showToast("Erreur de communication Stripe", "error"); }
        setIsSaving(false);
    };

    const handlePaymentSuccess = async (pi_id) => {
        setIsSaving(true);
        try {
            const payload = { payment_intent_id: pi_id, subscription_id: paymentData?.subId, id: managingChantier.id, offerType: managingChantier.offerType, currentRate: managingChantier.currentRate, physicalPanels: managingChantier.physicalPanels, details: managingChantier, name: managingChantier.name };
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'chantiers/activate_paid', { method: 'POST', body: JSON.stringify(payload) });
            const d = await res.json();
            if(d.status === 'success') { showToast("Paiement validé ! Panneau activé."); setIsModalOpen(false); refreshData(); }
            else showToast(d.message, 'error');
        } catch(e) { showToast("Erreur", "error"); }
        setIsSaving(false);
    };

    const generateDelegateLink = async (id) => {
        try {
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'chantiers/delegate_link', { method: 'POST', body: JSON.stringify({ id }) });
            const d = await res.json();
            if(d.status === 'success') { setDelegateLink(d.data.link); setModalStep('share'); setIsModalOpen(true); }
            else showToast(d.message, 'error');
        } catch(e) { showToast("Erreur réseau", "error"); }
    };

    const handleDeleteTeamMember = async (uid) => {
        if (!confirm("Voulez-vous vraiment supprimer ce collaborateur ? Ses accès seront révoqués et ses panneaux vous seront réassignés.")) return;
        setIsSaving(true);
        try {
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'clients/team/delete', { method: 'POST', body: JSON.stringify({ uid }) });
            if ((await res.json()).status === 'success') { showToast("Collaborateur supprimé."); refreshData(); }
        } finally { setIsSaving(false); }
    };

    const handleAssignPanel = async (chantierId, assignedUid) => {
        setIsSaving(true);
        try {
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'chantiers/assign', { method: 'POST', body: JSON.stringify({ chantier_id: chantierId, assigned_uid: assignedUid }) });
            if ((await res.json()).status === 'success') { showToast("Assignation mise à jour."); refreshData(); }
        } finally { setIsSaving(false); }
    };

    const handleAutoFill = async () => {
        const num = prompt("Saisissez votre numéro SIRET (14 chiffres) ou SIREN (9 chiffres) :");
        if (!num) return;
        const cleanNum = num.replace(/\D/g, '');
        if (cleanNum.length !== 9 && cleanNum.length !== 14) {
            return showToast("Le numéro doit contenir exactement 9 ou 14 chiffres.", "error");
        }
        
        setIsSaving(true);
        try {
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'system/sirene', {
                method: 'POST',
                body: JSON.stringify({ q: cleanNum })
            });
            const responseData = await res.json();
            
            if (responseData.status !== 'success') throw new Error(responseData.message);

            const apiData = responseData.data;
            if (apiData.results && apiData.results.length > 0) {
                const company = apiData.results[0];
                const expectedSiren = cleanNum.substring(0, 9);
                
                if (company.siren !== expectedSiren) {
                    setIsSaving(false);
                    return showToast("Numéro invalide : Aucune entreprise correspondante.", "error");
                }

                const siege = company.siege || {};
                const siren = company.siren;
                let foundSiret = siege.siret || siren + "00010";
                
                if (cleanNum.length === 14) {
                    if (siege.siret === cleanNum) foundSiret = cleanNum;
                    else if (company.matching_etablissements) {
                        const exactEtab = company.matching_etablissements.find(e => e.siret === cleanNum);
                        if (exactEtab) foundSiret = cleanNum;
                    }
                }

                const addressParts = [siege.numero_voie, siege.indice_repetition, siege.type_voie, siege.libelle_voie, siege.code_postal, siege.libelle_commune];
                const address = addressParts.filter(Boolean).join(' ').replace(/\s+/g, ' ').trim() || "Adresse non renseignée";

                const tvaKey = (12 + 3 * (parseInt(siren, 10) % 97)) % 97;
                const calculatedTva = `FR${tvaKey.toString().padStart(2, '0')}${siren}`;

                setProfileData({ ...profileData, name: company.nom_complet, address: address, siret: foundSiret, tva: calculatedTva });
                setHasTva(true);
                showToast("Informations récupérées avec succès !", "success");
            } else {
                showToast("Aucune entreprise trouvée.", "error");
            }
        } catch (err) { 
            console.error("Détail de l'erreur SIRENE :", err);
            showToast("Le service gouvernemental est momentanément indisponible.", "error"); 
        }
        setIsSaving(false);
    };

    const handleToggleTva = () => {
        if (isCollaborator) return;
        if (hasTva) setShowTvaWarning(true); 
        else setHasTva(true); 
    };

    const confirmTvaExemption = () => {
        setHasTva(false);
        setProfileData({ ...profileData, tva: '' });
        setShowTvaWarning(false);
    };

    const handleSaveProfile = async () => {
        if(!profileData.name.trim() || !profileData.address.trim() || !profileData.siret.trim()) {
            return showToast("Veuillez remplir le nom, l'adresse et le SIRET.", "error");
        }

        let cleanTva = 'NON_ASSUJETTI';
        if (hasTva) {
            if (!profileData.tva || profileData.tva.trim() === '') return showToast("Veuillez renseigner votre numéro de TVA.", "error");
            cleanTva = profileData.tva.replace(/\s+/g, '').toUpperCase();
            if (!/^[A-Z]{2}[A-Z0-9]{2,12}$/.test(cleanTva)) return showToast("Format de TVA invalide.", "error");
            if (cleanTva.startsWith('FR')) {
                if (!/^FR[0-9A-Z]{2}[0-9]{9}$/.test(cleanTva)) return showToast("Format de TVA française invalide.", "error");
                if (profileData.siret && profileData.siret.length >= 9) {
                    const sirenBase = profileData.siret.replace(/\s+/g, '').substring(0, 9);
                    const tvaSiren = cleanTva.substring(4);
                    if (sirenBase !== tvaSiren) return showToast("La TVA ne correspond pas au SIRET.", "error");
                }
            }
        }

        setIsSaving(true);
        try {
            const payload = { ...profileData, tva: cleanTva, uiMode: uiMode };
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'clients/profile/update', { method: 'POST', body: JSON.stringify(payload) });
            if((await res.json()).status === 'success') { 
                setProfileData({ ...profileData, tva: hasTva ? cleanTva : '' });
                showToast("Profil mis à jour et validé !"); 
                refreshData(); 
            }
        } finally { setIsSaving(false); }
    };

    const handleUiModeChange = async (isAdvanced) => {
        const newMode = isAdvanced ? 'professionnel' : 'simplifie';
        setUiMode(newMode);
        setIsSaving(true);
        try {
            let cleanTva = 'NON_ASSUJETTI';
            if (hasTva && profileData.tva) cleanTva = profileData.tva.replace(/\s+/g, '').toUpperCase();
            
            const payload = { ...profileData, tva: cleanTva, uiMode: newMode };
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'clients/profile/update', { method: 'POST', body: JSON.stringify(payload) });
            if((await res.json()).status === 'success') { 
                showToast(isAdvanced ? "Interface avancée activée." : "Interface simplifiée activée."); 
                refreshData(); 
            }
        } catch(e) {
            showToast("Erreur lors de la sauvegarde du mode", "error");
        } finally { setIsSaving(false); }
    };

    const handleSavePassword = async () => {
        if(!passwordData.oldPassword || !passwordData.newPassword) return showToast("Champs manquants", "error");
        setIsSaving(true);
        try {
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'clients/password/update', { method: 'POST', body: JSON.stringify({ oldPassword: passwordData.oldPassword, password: passwordData.newPassword }) });
            const d = await res.json();
            if(d.status === 'success') { showToast("Mot de passe mis à jour"); setPasswordData({oldPassword:'', newPassword:''}); }
            else showToast(d.message, 'error');
        } finally { setIsSaving(false); }
    };

    const handleInviteTeam = async () => {
        if(!teamEmail) return;
        setIsSaving(true);
        try {
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'clients/invite_team', { method: 'POST', body: JSON.stringify({ email: teamEmail }) });
            const d = await res.json();
            if(d.status === 'success') { showToast("Invitation envoyée !"); setTeamEmail(''); refreshData(); }
            else showToast(d.message, 'error');
        } finally { setIsSaving(false); }
    };

    const requestAccountDeletion = async () => {
        const pwd = prompt("Pour confirmer la suppression de votre compte, veuillez saisir votre mot de passe :");
        if (!pwd) return;
        try {
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'clients/request_delete', { method: 'POST', body: JSON.stringify({ password: pwd }) });
            const d = await res.json();
            if (d.status === 'success') showToast("E-mail de confirmation envoyé.", "info");
            else showToast(d.message, 'error');
        } catch(e) { showToast("Erreur", "error"); }
    };

    const togglePush = () => {
        if (pushEnabled) {
            localStorage.setItem('eco_push_enabled', 'false'); setPushEnabled(false); showToast("Notifications web désactivées.", "info");
        } else {
            if (!window.Notification) return showToast("Votre navigateur ne supporte pas les notifications.", "error");
            Notification.requestPermission().then(perm => {
                if (perm === 'granted') { localStorage.setItem('eco_push_enabled', 'true'); setPushEnabled(true); showToast("Notifications activées !", "success"); } 
                else { showToast("Vous avez bloqué les notifications dans votre navigateur.", "error"); }
            });
        }
    };

    const sidebarFooter = !isCollaborator ? (
        <label className="flex items-center justify-between p-3 rounded-xl border border-slate-200 bg-white hover:bg-slate-50 transition cursor-pointer mb-2" title="Activer les fonctionnalités avancées (équipes, personnalisation)">
            <span className="text-xs font-bold text-slate-700">Mode avancé</span>
            <div className={`w-8 h-4 rounded-full transition-colors relative shrink-0 ${uiMode === 'professionnel' ? 'bg-emerald-500' : 'bg-slate-300'}`}>
                <div className={`absolute top-[2px] bg-white w-3 h-3 rounded-full transition-transform ${uiMode === 'professionnel' ? 'translate-x-4' : 'translate-x-1'}`}></div>
            </div>
            <input type="checkbox" className="hidden" checked={uiMode === 'professionnel'} onChange={(e) => handleUiModeChange(e.target.checked)} disabled={isSaving} />
        </label>
    ) : null;

    const renderDashboard = () => (
        <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4">
            <div className="flex flex-col md:flex-row justify-between gap-4 items-start md:items-center">
                <div><h1 className="text-3xl font-black text-slate-800">Bienvenue, {myClientData.name || 'Client'}</h1><p className="text-slate-500 font-medium">Gérez vos obligations légales BTP en toute simplicité.</p></div>
                {!isSuspended && !isCollaborator && (
                    <button onClick={() => { setManagingChantier({ name: '', location: '', permitNumber: '', status: 'Brouillon', offerType: 'rental', currentRate: data.prices?.rentalMo || 180, physicalPanels: 0, hasNoAds: false, privateDocs: [] }); setValidationErrors([]); setModalStep('config_full'); setIsModalOpen(true); }} className="bg-emerald-600 text-white px-6 py-3 rounded-xl font-black uppercase tracking-widest text-sm hover:bg-emerald-700 transition shadow-lg flex items-center gap-2">
                        <Plus size={18}/> Nouveau chantier
                    </button>
                )}
            </div>

            {isSuspended && (
                <div className="bg-red-50 border-2 border-red-200 p-6 rounded-2xl flex items-start gap-4">
                    <AlertTriangle size={32} className="text-red-600 shrink-0"/>
                    <div>
                        <h3 className="font-black text-red-800 text-lg">Facture impayée - compte suspendu</h3>
                        <p className="text-red-700 text-sm mt-1">L'accès à l'édition de vos panneaux est temporairement bloqué. Veuillez régulariser votre situation dans l'onglet Factures.</p>
                        {!isCollaborator && <button onClick={() => setActiveTab('billing')} className="mt-3 bg-red-600 text-white px-4 py-2 rounded-xl text-xs font-bold hover:bg-red-700 transition">Régulariser maintenant</button>}
                    </div>
                </div>
            )}

            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                <window.StatCard title="Panneaux actifs" value={activeChantiers.length} icon={<ShieldCheck size={24}/>} color="text-emerald-600" bg="bg-emerald-100" onClick={() => setActiveTab('panels')} />
                <window.StatCard title="Brouillons" value={draftChantiers.length} icon={<Edit size={24}/>} color="text-slate-600" bg="bg-slate-200" onClick={() => setActiveTab('panels')} />
                <window.StatCard title="Scans riverains" value={data.stats?.totalViews || 0} icon={<UserCircle size={24}/>} color="text-blue-600" bg="bg-blue-100" />
                <window.StatCard title="Messages" value={totalUnread} icon={<MessageSquare size={24}/>} color="text-amber-600" bg="bg-amber-100" onClick={() => setActiveTab('messages')} />
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                <div className="lg:col-span-2 bg-white rounded-3xl p-6 shadow-sm border border-slate-100">
                    <h3 className="font-black text-slate-800 mb-6 text-lg flex items-center gap-2"><window.Activity size={20} className="text-emerald-600"/> Fréquentation (30j)</h3>
                    <window.SimpleBarChart data={data.stats?.history || []} />
                </div>
                <div className="bg-white rounded-3xl p-6 shadow-sm border border-slate-100">
                    <h3 className="font-black text-slate-800 mb-6 text-lg">Activité récente</h3>
                    <div className="space-y-4">
                        {interactions.slice(0, 5).map((m, i) => (
                            <div key={i} onClick={() => setActiveTab('messages')} className="flex items-start gap-3 p-3 rounded-xl hover:bg-slate-50 cursor-pointer transition border border-transparent hover:border-slate-100">
                                <div className={`w-8 h-8 rounded-full flex items-center justify-center shrink-0 ${m.isAlert ? 'bg-red-100 text-red-600' : 'bg-blue-100 text-blue-600'}`}>{m.isAlert ? <AlertTriangle size={14}/> : <MessageSquare size={14}/>}</div>
                                <div className="min-w-0">
                                    <p className="text-sm font-bold text-slate-700 truncate">{m.author}</p>
                                    <p className="text-xs text-slate-500 truncate">{m.detail}</p>
                                </div>
                            </div>
                        ))}
                        {interactions.length === 0 && <p className="text-sm text-slate-400 italic text-center py-6">Aucune activité récente.</p>}
                    </div>
                </div>
            </div>
        </div>
    );

    const renderPanels = () => (
        <div className="space-y-6 animate-in fade-in slide-in-from-bottom-4">
            <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
                <div><h1 className="text-3xl font-black text-slate-800">Mes chantiers</h1><p className="text-slate-500 font-medium">Gestion de vos affichages légaux.</p></div>
                {!isSuspended && !isCollaborator && <button onClick={() => { setManagingChantier({ name: '', location: '', permitNumber: '', status: 'Brouillon', offerType: 'rental', currentRate: data.prices?.rentalMo || 180, physicalPanels: 0, hasNoAds: false, privateDocs: [] }); setValidationErrors([]); setModalStep('config_full'); setIsModalOpen(true); }} className="bg-emerald-600 text-white px-5 py-2.5 rounded-xl font-bold text-sm hover:bg-emerald-700 transition shadow-lg flex items-center gap-2"><Plus size={16}/> Nouveau chantier</button>}
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {data.chantiers?.map((c, i) => (
                    <div key={i} className={`bg-white rounded-3xl p-6 shadow-sm border ${c.status === 'Actif' ? 'border-emerald-200' : 'border-slate-200'} flex flex-col`}>
                        <div className="flex justify-between items-start mb-4">
                            <div className="flex items-center gap-3">
                                <div className={`w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 ${c.status === 'Actif' ? 'bg-emerald-100 text-emerald-600' : 'bg-slate-100 text-slate-400'}`}><Building size={24}/></div>
                                <div>
                                    <h3 className="font-black text-lg text-slate-800 leading-tight truncate max-w-[200px] sm:max-w-[250px]" title={c.name}>{c.name || 'Brouillon sans nom'}</h3>
                                    <p className="text-xs text-slate-500 font-medium mt-0.5 truncate max-w-[200px]" title={c.location}>{c.location || 'Localisation non définie'}</p>
                                </div>
                            </div>
                            <span className={`px-3 py-1 rounded-lg text-[10px] font-black uppercase tracking-widest shrink-0 ${c.status === 'Actif' ? 'bg-emerald-50 text-emerald-700 border border-emerald-200' : 'bg-slate-100 text-slate-600 border border-slate-200'}`}>{c.status}</span>
                        </div>
                        
                        <div className="flex-1"></div>

                        {c.status === 'Actif' && (
                            <div className="grid grid-cols-2 gap-2 mb-4 bg-slate-50 p-3 rounded-xl border border-slate-100">
                                <div className="text-center"><p className="text-[10px] font-bold text-slate-400 uppercase">Scans QR</p><p className="font-black text-slate-800">{c.views}</p></div>
                                <div className="text-center border-l border-slate-200"><p className="text-[10px] font-bold text-slate-400 uppercase">Abonnement</p><p className="font-black text-slate-800">{c.offerType === 'rental' ? 'Location' : 'Achat'}</p></div>
                            </div>
                        )}

                        <div className="flex flex-wrap gap-2 pt-4 border-t border-slate-100">
                            {c.status === 'Actif' && (
                                <>
                                    <button onClick={() => setPreviewChantier(c)} title="Aperçu du panneau" className="flex-1 sm:flex-none justify-center bg-emerald-50 text-emerald-700 px-4 py-2 rounded-xl text-xs font-bold hover:bg-emerald-100 flex items-center gap-2 transition"><window.QrCode size={16}/> Voir le panneau</button>
                                    <button onClick={() => generateDelegateLink(c.id)} title="Lien de saisie pour architecte" className="flex-1 sm:flex-none justify-center bg-blue-50 text-blue-700 px-4 py-2 rounded-xl text-xs font-bold hover:bg-blue-100 flex items-center gap-2 transition"><Share2 size={16}/> Délégué</button>
                                    <button onClick={() => { setManagingChantier(c); setModalStep('legal_vault'); setIsModalOpen(true); }} title="Documents d'huissier" className="flex-1 sm:flex-none justify-center bg-slate-900 text-white px-4 py-2 rounded-xl text-xs font-bold hover:bg-slate-800 flex items-center gap-2 transition"><Lock size={16}/> Coffre-fort</button>
                                    {!isSuspended && (
                                        <button onClick={() => { setManagingChantier({...c}); setValidationErrors([]); setModalStep('config_full'); setIsModalOpen(true); }} title="Éditer le panneau" className="flex-1 sm:flex-none justify-center bg-white border border-slate-200 text-slate-600 px-4 py-2 rounded-xl text-xs font-bold hover:bg-slate-50 flex items-center gap-2 transition"><Edit size={16}/> Modifier</button>
                                    )}
                                    {!isCollaborator && (
                                        <button onClick={() => {
                                            if (confirm("Clôturer ce panneau ? Cette action va archiver toutes les données et arrêter la facturation.")) {
                                                setIsSaving(true);
                                                fetch(window.ECO_CONFIG.apiBaseUrl + 'chantiers/archive', { method: 'POST', body: JSON.stringify({id: c.id}) })
                                                .then(res => res.json())
                                                .then(d => {
                                                    if(d.status === 'success') {
                                                        window.location.href = d.data.archive_url;
                                                        showToast("Archive générée et panneau clôturé !");
                                                        refreshData();
                                                    } else showToast(d.message, 'error');
                                                }).finally(() => setIsSaving(false));
                                            }
                                        }} disabled={isSaving} title="Clôturer et archiver le chantier" className="w-full justify-center bg-red-50 text-red-600 px-4 py-2 rounded-xl text-xs font-bold hover:bg-red-100 flex items-center gap-2 transition"><Archive size={16}/> Clôturer et archiver (D.O.E)</button>
                                    )}
                                </>
                            )}
                            {c.status === 'Brouillon' && !isSuspended && (
                                <>
                                    <button onClick={() => setPreviewChantier(c)} title="Aperçu du panneau" className="flex-1 sm:flex-none justify-center bg-blue-50 text-blue-700 px-4 py-2 rounded-xl text-xs font-bold hover:bg-blue-100 flex items-center gap-2 transition"><Eye size={16}/> Aperçu</button>
                                    <button onClick={() => { setManagingChantier({...c}); setValidationErrors([]); setModalStep('config_full'); setIsModalOpen(true); }} title="Éditer ce brouillon" className="flex-1 bg-emerald-600 text-white px-4 py-2 rounded-xl text-xs font-bold hover:bg-emerald-700 flex items-center justify-center gap-2 transition"><Edit size={16}/> Reprendre l'édition</button>
                                    {!isCollaborator && <button onClick={() => { if(confirm("Supprimer ce brouillon ?")) { fetch(window.ECO_CONFIG.apiBaseUrl + 'chantiers/delete', { method: 'POST', body: JSON.stringify({id: c.id}) }).then(() => refreshData()); } }} title="Supprimer ce brouillon" className="px-4 py-2 rounded-xl text-xs font-bold text-red-600 bg-red-50 hover:bg-red-100 transition"><Trash2 size={16}/></button>}
                                </>
                            )}
                            {!isCollaborator && (
                                <button onClick={() => { 
                                    const deepClone = JSON.parse(JSON.stringify(c));
                                    const cleanIntervenants = (deepClone.intervenants || []).map(i => ({...i, id: crypto.randomUUID(), logoId: '', logoUrl: ''}));
                                    const cleanLots = (deepClone.lots || []).map(l => ({...l, id: crypto.randomUUID(), entreprises: (l.entreprises || []).map(e => ({...e, id: crypto.randomUUID(), logoId: '', logoUrl: ''}))}));

                                    setManagingChantier(null); 
                                    setManagingChantier({ 
                                        ...c, 
                                        id: undefined, 
                                        name: c.name + ' (Copie)', 
                                        location: '', 
                                        permitNumber: '', 
                                        status: 'Brouillon', 
                                        offerType: 'rental', 
                                        physicalPanels: 0, 
                                        hasNoAds: false, 
                                        privateDocs: [], 
                                        imageId: '', 
                                        imageUrl: '', 
                                        pdfId: '',
                                        maitreOuvrageLogoId: '', 
                                        maitreOuvrageLogoUrl: '',
                                        intervenants: cleanIntervenants,
                                        lots: cleanLots
                                    }); 
                                    setValidationErrors([]);
                                    setModalStep('config_full'); 
                                    setIsModalOpen(true); 
                                }} title="Dupliquer le panneau" className="flex-1 sm:flex-none justify-center bg-white border border-slate-200 text-slate-600 px-4 py-2 rounded-xl text-xs font-bold hover:bg-slate-50 flex items-center gap-2 transition"><Copy size={16}/> Dupliquer</button>
                            )}
                        </div>

                        {(!isCollaborator && data.team?.length > 0 && uiMode === 'professionnel') && (
                            <div className="mt-4 pt-4 border-t border-slate-100 flex items-center justify-between gap-2">
                                <span className="text-[10px] font-bold text-slate-400 uppercase">Géré par :</span>
                                <select
                                    value={c.assigned_uid || ''}
                                    onChange={(e) => handleAssignPanel(c.id, e.target.value)}
                                    disabled={isSaving}
                                    className="text-xs font-bold text-slate-700 border border-slate-200 rounded-lg px-2 py-1 outline-none bg-slate-50 focus:border-emerald-500 transition"
                                >
                                    <option value="">Moi-même (principal)</option>
                                    {data.team.map(m => (
                                        <option key={m.id} value={m.id}>{m.email}</option>
                                    ))}
                                </select>
                            </div>
                        )}
                        {isCollaborator && (
                            <div className="mt-4 pt-4 border-t border-slate-100 text-right">
                                <span className="text-[10px] font-bold text-blue-700 bg-blue-50 px-3 py-1 rounded-md uppercase tracking-wider">Assigné à vous</span>
                            </div>
                        )}
                    </div>
                ))}
                {data.chantiers?.length === 0 && (
                    <div className="col-span-full text-center p-12 bg-white rounded-3xl border border-slate-200 border-dashed">
                        <Building size={48} className="mx-auto text-slate-300 mb-4" />
                        <h3 className="text-lg font-black text-slate-700">Aucun chantier</h3>
                        <p className="text-slate-500 text-sm mt-1">{isCollaborator ? "Aucun chantier ne vous est assigné." : "Créez votre premier chantier pour démarrer."}</p>
                        {!isSuspended && !isCollaborator && <button onClick={() => { setManagingChantier({ name: '', location: '', permitNumber: '', status: 'Brouillon', offerType: 'rental', currentRate: data.prices?.rentalMo || 180, physicalPanels: 0, hasNoAds: false, privateDocs: [] }); setValidationErrors([]); setModalStep('config_full'); setIsModalOpen(true); }} className="mt-6 bg-emerald-600 text-white px-6 py-3 rounded-xl font-bold shadow-lg hover:bg-emerald-700 transition">Créer un chantier</button>}
                    </div>
                )}
            </div>
        </div>
    );

    const renderLivraisons = () => {
        const deliveries = data.chantiers?.filter(c => c.physicalPanels > 0) || [];
        const activeDeliveries = deliveries.filter(c => c.shipping_status !== 'Livré');
        const historyDeliveries = deliveries.filter(c => c.shipping_status === 'Livré');

        const DeliveryCard = ({ c, isHistory }) => {
            const isShipped = c.shipping_status === 'Expédié';
            const isWaiting = c.shipping_status === 'Validation en cours' || c.shipping_status === "Attente d'impression";
            const displayStatus = c.shipping_status === "Attente d'impression" ? "Validée (en attente d'impression)" : c.shipping_status;
            
            return (
                <div className={`bg-white rounded-3xl p-5 shadow-sm border ${isShipped ? 'border-blue-200' : 'border-slate-200'} flex flex-col gap-4 transition hover:shadow-md`}>
                    <div className="flex gap-4 items-start">
                        <div className={`w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 ${isShipped ? 'bg-blue-50 text-blue-600' : (isHistory ? 'bg-emerald-50 text-emerald-600' : 'bg-slate-100 text-slate-500')}`}>
                            {isHistory ? <CheckCircle size={24} /> : <Package size={24} />}
                        </div>
                        <div className="min-w-0 flex-1">
                            <p className="font-black text-base text-slate-800 truncate" title={c.name}>{c.name}</p>
                            <p className="text-xs text-slate-500 flex items-center gap-1 mt-0.5"><MapPin size={12}/> {c.location}</p>
                        </div>
                        <div className="text-right shrink-0">
                            <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1">Quantité</p>
                            <p className="text-lg font-black text-slate-800 leading-none">{c.physicalPanels}</p>
                        </div>
                    </div>

                    <div className={`p-3 rounded-xl border ${isShipped ? 'bg-blue-50/50 border-blue-100' : 'bg-slate-50 border-slate-100'}`}>
                        <div className="flex justify-between items-center mb-1">
                            <p className="text-[10px] font-bold uppercase tracking-widest text-slate-500">Statut de la commande</p>
                            <span className={`px-2 py-0.5 rounded-md text-[10px] font-black uppercase text-center ${isShipped ? 'bg-blue-100 text-blue-700' : (isHistory ? 'bg-emerald-100 text-emerald-700' : 'bg-amber-100 text-amber-700')}`}>
                                {displayStatus}
                            </span>
                        </div>
                        {c.tracking_number && (
                            <div className="mt-3 pt-3 border-t border-slate-200/60">
                                <p className="text-xs font-bold text-slate-700">N° de suivi : <span className="font-mono text-blue-600 ml-1 select-all">{c.tracking_number}</span></p>
                                {c.tracking_link && (
                                    <a href={c.tracking_link} target="_blank" rel="noopener noreferrer" className="text-[11px] font-bold text-blue-600 hover:text-blue-800 flex items-center gap-1 mt-1.5 transition">
                                        <ExternalLink size={12}/> Suivre mon colis sur le site du transporteur
                                    </a>
                                )}
                            </div>
                        )}
                        {isWaiting && (
                            <p className="text-[11px] text-slate-500 mt-2 font-medium">Votre commande est en cours de traitement par nos équipes. Vous recevrez un lien de suivi dès l'expédition.</p>
                        )}
                    </div>

                    {isShipped && !isHistory && (
                        <button onClick={() => {
                            if(window.confirm("Confirmez-vous la bonne réception de ces panneaux ?")) {
                                setIsSaving(true);
                                fetch(window.ECO_CONFIG.apiBaseUrl + 'chantiers/shipping', { method: 'POST', body: JSON.stringify({ id: c.id, shipping_status: 'Livré' }) })
                                .then(res => res.json()).then(() => { showToast("Réception confirmée !"); refreshData(); }).finally(() => setIsSaving(false));
                            }
                        }} disabled={isSaving} className="w-full bg-emerald-600 text-white py-3 rounded-xl font-bold text-sm hover:bg-emerald-700 transition shadow-md flex justify-center items-center gap-2">
                            <CheckCircle size={16}/> Confirmer la réception
                        </button>
                    )}
                </div>
            );
        };

        return (
            <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4">
                <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
                    <div><h1 className="text-3xl font-black text-slate-800">Livraisons</h1><p className="text-slate-500 font-medium">Suivi de vos commandes de panneaux physiques.</p></div>
                    <button onClick={refreshData} title="Actualiser" className="shrink-0 bg-white border border-slate-200 text-slate-700 px-4 py-2.5 rounded-xl font-bold text-sm hover:bg-slate-50 transition shadow-sm flex items-center gap-2"><RefreshCw size={16}/> Actualiser</button>
                </div>
                
                {deliveries.length === 0 ? (
                    <div className="text-center p-12 bg-white rounded-3xl border border-slate-200 border-dashed">
                        <Package size={48} className="mx-auto text-slate-300 mb-4" />
                        <h3 className="text-lg font-black text-slate-700">Aucune livraison</h3>
                        <p className="text-slate-500 text-sm mt-1">Vous n'avez pas encore commandé de panneaux physiques.</p>
                    </div>
                ) : (
                    <>
                        {activeDeliveries.length > 0 && (
                            <div className="space-y-4">
                                <h3 className="font-black text-slate-800 text-lg flex items-center gap-2"><Package size={20} className="text-blue-600"/> En cours ({activeDeliveries.length})</h3>
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    {activeDeliveries.map(c => <DeliveryCard key={c.id} c={c} isHistory={false} />)}
                                </div>
                            </div>
                        )}
                        
                        {historyDeliveries.length > 0 && (
                            <div className="space-y-4">
                                <h3 className="font-black text-slate-800 text-lg flex items-center gap-2 pt-4 border-t border-slate-200"><CheckCircle size={20} className="text-emerald-600"/> Historique ({historyDeliveries.length})</h3>
                                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 opacity-80 hover:opacity-100 transition-opacity">
                                    {historyDeliveries.map(c => <DeliveryCard key={c.id} c={c} isHistory={true} />)}
                                </div>
                            </div>
                        )}
                    </>
                )}
            </div>
        );
    };

    const renderMessages = () => {
        const supportThreadId = `SUPPORT_${myClientData.id}`;
        const threadsMap = {
            [supportThreadId]: { id: supportThreadId, title: "Support technique eco-panneau", targetEmail: 'Admin', messages: [], unread: 0, isSupport: true }
        };

        if (isCollaborator) delete threadsMap[supportThreadId];

        interactions.forEach(m => {
            if (m.chantierId === supportThreadId && !isCollaborator) {
                threadsMap[supportThreadId].messages.push(m);
                if (m.author === 'Admin' && !m.resolved) threadsMap[supportThreadId].unread++;
            } else if (m.chantierId !== supportThreadId) {
                const riverainEmail = (m.author !== 'Client' && m.author !== 'Admin') ? m.author : m.target;
                if (!riverainEmail) return;
                
                const threadId = `${m.chantierId}_${riverainEmail}`;
                const panelName = activeChantiers.find(c => c.id === m.chantierId)?.name || draftChantiers.find(c => c.id === m.chantierId)?.name || 'Panneau inconnu';
                
                if (!threadsMap[threadId]) {
                    threadsMap[threadId] = { id: threadId, chantierId: m.chantierId, title: `${panelName} - ${riverainEmail}`, targetEmail: riverainEmail, messages: [], unread: 0, isSupport: false };
                }
                threadsMap[threadId].messages.push(m);
                if (m.author !== 'Client' && !m.resolved) threadsMap[threadId].unread++;
            }
        });

        const threads = Object.values(threadsMap)
            .filter(t => t.isSupport || t.messages.length > 0)
            .sort((a,b) => {
                const dateA = a.messages.length > 0 ? new Date(a.messages[0].created_at) : new Date(0);
                const dateB = b.messages.length > 0 ? new Date(b.messages[0].created_at) : new Date(0);
                return dateB - dateA;
            });

        const selectedThreadId = new URLSearchParams(window.location.search).get('chat_id') || threads[0]?.id;
        const setChatId = (id) => { const u = new URL(window.location); u.searchParams.set('chat_id', id); window.history.replaceState({}, '', u); refreshData(); };
        const selectedThread = threads.find(t => t.id === selectedThreadId);

        const handleSendClient = async (text) => {
            if (!selectedThread) return;
            const payload = {
                chantierId: selectedThread.isSupport ? selectedThread.id : selectedThread.chantierId,
                detail: text,
                author: 'Client',
                targetEmail: selectedThread.targetEmail
            };
            await fetch(window.ECO_CONFIG.apiBaseUrl + 'interactions', { method: 'POST', body: JSON.stringify(payload) });
            refreshData();
        };

        return (
            <div className="flex flex-col md:flex-row h-[80vh] bg-white rounded-3xl shadow-sm border border-slate-200 overflow-hidden animate-in fade-in slide-in-from-bottom-4">
                <div className="w-full md:w-1/3 border-r border-slate-200 flex flex-col bg-slate-50/50">
                    <div className="p-4 border-b border-slate-200 bg-white flex justify-between items-center"><h2 className="font-black text-slate-800 text-lg">Conversations</h2><button onClick={refreshData} title="Actualiser les messages" className="p-2 hover:bg-slate-100 rounded-lg transition text-slate-500"><RefreshCw size={16}/></button></div>
                    <div className="flex-1 overflow-y-auto p-2 space-y-1 custom-scrollbar">
                        {threads.map(t => (
                            <button key={t.id} onClick={() => setChatId(t.id)} className={`w-full text-left p-3 rounded-xl flex items-center justify-between transition ${selectedThreadId === t.id ? 'bg-emerald-50 border border-emerald-200' : 'hover:bg-white border border-transparent'}`}>
                                <div className="min-w-0 pr-2">
                                    <p className={`text-sm truncate ${t.isSupport ? 'font-black text-emerald-700' : 'font-bold text-slate-800'}`}>{t.title}</p>
                                    <p className="text-xs text-slate-500 truncate">{t.messages.length} messages</p>
                                </div>
                                {t.unread > 0 && <span className="bg-red-500 text-white text-[10px] px-2 py-0.5 rounded-full shrink-0">{t.unread}</span>}
                            </button>
                        ))}
                        {threads.length === 0 && <p className="text-center text-slate-400 text-sm mt-10 italic">Aucune conversation.</p>}
                    </div>
                </div>
                <div className="w-full md:w-2/3 flex flex-col relative bg-slate-50">
                    {selectedThread ? (
                        <>
                            <div className="p-4 border-b border-slate-200 bg-white shrink-0"><h3 className="font-black text-slate-800">{selectedThread.title}</h3></div>
                            <div className="flex-1 relative">
                                <div className="absolute inset-0">
                                    <window.ChatBox messages={selectedThread.messages} currentUserRole="client" chantierId={selectedThread.isSupport ? selectedThread.id : selectedThread.chantierId} refreshData={refreshData} onSend={handleSendClient}/>
                                </div>
                            </div>
                        </>
                    ) : (<div className="flex-1 flex flex-col items-center justify-center text-slate-400"><MessageSquare size={48} className="mb-4 opacity-50"/><p className="font-medium">Sélectionnez une conversation</p></div>)}
                </div>
            </div>
        );
    };

    const renderBilling = () => (
        <div className="space-y-6 animate-in fade-in slide-in-from-bottom-4">
            <div className="flex justify-between items-center">
                <div><h1 className="text-3xl font-black text-slate-800">Factures</h1><p className="text-slate-500 font-medium">Historique comptable et paiements.</p></div>
                <a href="?api=invoices/export_csv" className="bg-white border border-slate-200 text-slate-700 px-4 py-2.5 rounded-xl font-bold text-sm hover:bg-slate-50 transition shadow-sm flex items-center gap-2"><Download size={16}/> Export CSV</a>
            </div>
            
            <div className="bg-white rounded-3xl shadow-sm border border-slate-200 overflow-x-auto">
                <table className="w-full text-left border-collapse whitespace-nowrap">
                    <thead>
                        <tr className="bg-slate-50 text-[10px] uppercase tracking-widest text-slate-500 border-b border-slate-200">
                            <th className="p-4 font-bold">Date</th><th className="p-4 font-bold">Chantier</th><th className="p-4 font-bold">Détail</th><th className="p-4 font-bold">Montant</th><th className="p-4 font-bold text-right">PDF</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-100">
                        {data.invoices?.map((inv, i) => (
                            <tr key={i} className="hover:bg-slate-50 transition">
                                <td className="p-4 text-sm font-bold text-slate-700">{new Date(inv.created_at).toLocaleDateString('fr-FR')}</td>
                                <td className="p-4 text-sm text-slate-600 truncate max-w-[200px]">{inv.chantierName}</td>
                                <td className="p-4 text-sm text-slate-600">{inv.type}</td>
                                <td className="p-4 text-sm font-black text-slate-800">{inv.amount} €</td>
                                <td className="p-4 text-right"><a href={`?api=invoices/download&ref=${inv.invoiceNumber}`} title="Télécharger la facture" className="inline-flex p-2 bg-slate-100 text-slate-600 rounded-lg hover:bg-slate-200 transition"><Download size={16}/></a></td>
                            </tr>
                        ))}
                    </tbody>
                </table>
                {data.invoices?.length === 0 && <div className="p-12 text-center text-slate-500"><FileText size={48} className="mx-auto mb-4 opacity-50"/>Aucune facture pour le moment.</div>}
            </div>
        </div>
    );

    const renderAccount = () => (
        <div className="space-y-6 animate-in fade-in slide-in-from-bottom-4">
            <div><h1 className="text-3xl font-black text-slate-800">Mon compte</h1><p className="text-slate-500 font-medium">Paramètres de profil et sécurité.</p></div>

            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <div className="bg-white rounded-3xl p-6 sm:p-8 shadow-sm border border-slate-200">
                    <div className="flex justify-between items-center mb-6">
                        <h3 className="font-black text-slate-800 flex items-center gap-2"><Building size={18} className="text-emerald-600"/> Profil de la société</h3>
                        {!isCollaborator && (
                            <button onClick={handleAutoFill} className="text-xs font-bold text-blue-700 bg-blue-50 hover:bg-blue-100 px-3 py-1.5 rounded-lg flex items-center gap-1 transition border border-blue-200 shadow-sm">
                                <Zap size={14}/> Saisie automatique
                            </button>
                        )}
                    </div>
                    <div className="space-y-4">
                        <div className="space-y-1"><label className="text-xs font-bold text-slate-500 uppercase block">Nom / raison sociale *</label><input value={profileData.name} onChange={e=>setProfileData({...profileData, name: e.target.value})} disabled={isCollaborator} className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm focus:border-emerald-500 outline-none transition disabled:bg-slate-50" /></div>
                        <div className="space-y-1"><label className="text-xs font-bold text-slate-500 uppercase block">Adresse complète *</label><textarea value={profileData.address} onChange={e=>setProfileData({...profileData, address: e.target.value})} disabled={isCollaborator} rows="2" className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm focus:border-emerald-500 outline-none transition resize-none disabled:bg-slate-50"></textarea></div>
                        
                        <div className="space-y-1"><label className="text-xs font-bold text-slate-500 uppercase block">SIRET *</label><input value={profileData.siret} onChange={e=>setProfileData({...profileData, siret: e.target.value})} disabled={isCollaborator} className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm focus:border-emerald-500 outline-none transition disabled:bg-slate-50" /></div>
                        
                        {!isCollaborator && (
                            <div className="pt-2 border-t border-slate-100">
                                <label className="flex items-center justify-between cursor-pointer group py-2">
                                    <div>
                                        <p className="text-sm font-bold text-slate-800">Assujetti à la TVA</p>
                                        <p className="text-[10px] font-medium text-slate-500">Mon entreprise facture la TVA.</p>
                                    </div>
                                    <div className={`w-12 h-6 rounded-full transition-colors relative shrink-0 ${hasTva ? 'bg-emerald-500' : 'bg-slate-300'}`}>
                                        <div className={`absolute top-1 bg-white w-4 h-4 rounded-full transition-transform ${hasTva ? 'left-7' : 'left-1'}`}></div>
                                    </div>
                                    <input type="checkbox" className="hidden" checked={hasTva} onChange={handleToggleTva} />
                                </label>

                                {hasTva && (
                                    <div className="space-y-1 mt-2 animate-in fade-in slide-in-from-top-2">
                                        <label className="text-xs font-bold text-slate-500 uppercase block">TVA intracommunautaire *</label>
                                        <input value={profileData.tva} onChange={e=>setProfileData({...profileData, tva: e.target.value})} placeholder="FR..." className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm focus:border-emerald-500 outline-none transition uppercase" />
                                    </div>
                                )}
                            </div>
                        )}

                        {!isCollaborator && (
                            <label className="flex items-center gap-3 p-4 border border-slate-200 rounded-xl cursor-pointer hover:bg-slate-50 transition mt-4">
                                <input type="checkbox" checked={profileData.monthlyReport === 1} onChange={(e) => setProfileData({...profileData, monthlyReport: e.target.checked ? 1 : 0})} className="w-5 h-5 accent-emerald-600" />
                                <div><p className="text-sm font-bold text-slate-800">Rapports d'activité</p><p className="text-xs text-slate-500">Recevoir un e-mail mensuel sur l'usage des panneaux.</p></div>
                            </label>
                        )}
                        {!isCollaborator && <button onClick={handleSaveProfile} disabled={isSaving} className="w-full bg-slate-900 text-white py-3 rounded-xl font-bold shadow-md hover:bg-slate-800 transition disabled:opacity-50">Enregistrer les modifications</button>}
                    </div>
                </div>

                <div className="space-y-6">

                    <div className="bg-white rounded-3xl p-6 sm:p-8 shadow-sm border border-slate-200">
                        <h3 className="font-black text-slate-800 mb-6 flex items-center gap-2"><Lock size={18} className="text-emerald-600"/> Sécurité</h3>
                        <div className="space-y-4">
                            <div className="space-y-1"><label className="text-xs font-bold text-slate-500 uppercase block">Ancien mot de passe</label><input type="password" value={passwordData.oldPassword} onChange={e=>setPasswordData({...passwordData, oldPassword: e.target.value})} className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm focus:border-emerald-500 outline-none transition" /></div>
                            <div className="space-y-1"><label className="text-xs font-bold text-slate-500 uppercase block">Nouveau mot de passe</label><input type="password" value={passwordData.newPassword} onChange={e=>setPasswordData({...passwordData, newPassword: e.target.value})} className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm focus:border-emerald-500 outline-none transition" placeholder="Min 8 car., Maj, Min, Chiffre" /></div>
                            <button onClick={handleSavePassword} disabled={isSaving} className="w-full bg-slate-100 text-slate-700 py-3 rounded-xl font-bold hover:bg-slate-200 transition disabled:opacity-50">Modifier le mot de passe</button>
                        </div>
                    </div>

                    {!isCollaborator && uiMode === 'professionnel' && (
                        <div className="bg-white rounded-3xl p-6 sm:p-8 shadow-sm border border-slate-200">
                            <h3 className="font-black text-slate-800 mb-2 flex items-center gap-2"><Users size={18} className="text-emerald-600"/> Équipe de collaborateurs</h3>
                            <p className="text-xs text-slate-500 mb-4">Gérez les accès de votre équipe à vos chantiers.</p>
                            <button onClick={() => setModalStep('team_manage')} className="w-full bg-slate-100 text-slate-700 py-3 rounded-xl font-bold hover:bg-slate-200 transition flex justify-center items-center gap-2 shadow-sm"><Users size={16}/> Gérer l'équipe ({data.team?.length || 0})</button>
                        </div>
                    )}

                    <div className="bg-indigo-50 p-6 rounded-2xl border border-indigo-100 shadow-sm mt-6">
                        <h3 className="font-black text-indigo-900 mb-2 flex items-center gap-2"><Bell size={18}/> Alertes navigateur</h3>
                        <p className="text-xs text-indigo-700/80 mb-4 leading-relaxed font-medium">Recevez une alerte visuelle et sonore sur votre PC/Mobile dès qu'un riverain poste un message.</p>
                        <button onClick={togglePush} className={`w-full px-4 py-3 rounded-xl font-bold text-sm transition shadow-sm ${pushEnabled ? 'bg-indigo-200 text-indigo-800 hover:bg-indigo-300' : 'bg-indigo-600 text-white hover:bg-indigo-700'}`}>
                            {pushEnabled ? 'Désactiver les alertes' : 'Activer les alertes (Opt-in)'}
                        </button>
                    </div>

                    {!isCollaborator && (
                        <div className="bg-slate-50 p-6 rounded-2xl border border-slate-200 shadow-sm mt-6">
                            <h3 className="font-black text-slate-800 mb-2 flex items-center gap-2"><Download size={18} className="text-blue-600"/> Données personnelles (RGPD)</h3>
                            <p className="text-xs text-slate-500 mb-4 leading-relaxed font-medium">Téléchargez une archive complète de vos données personnelles (profil, factures, panneaux, D.O.E, pièces jointes) au format ZIP.</p>
                            <a href="?api=clients/export_data" target="_blank" className="w-full bg-white border border-slate-200 text-slate-700 px-4 py-3 rounded-xl font-bold text-sm shadow-sm hover:bg-slate-50 transition flex items-center justify-center gap-2">
                                <Download size={16}/> Exporter mes données
                            </a>
                        </div>
                    )}

                    {!isCollaborator && (
                        <div className="bg-red-50 p-6 rounded-2xl border border-red-100 shadow-sm">
                            <h3 className="font-black text-red-900 mb-2 flex items-center gap-2"><Power size={18}/> Zone de danger</h3>
                            <p className="text-xs text-red-700/80 mb-4 leading-relaxed font-medium">La suppression de votre compte effacera définitivement tous vos panneaux, factures et fichiers (D.O.E inclus).</p>
                            <button onClick={requestAccountDeletion} className="w-full bg-red-600 text-white px-4 py-3 rounded-xl font-bold text-sm shadow-md hover:bg-red-700 transition">Supprimer mon compte définitivement</button>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );

    // Initialisation des variables pour le résumé temps réel du prix
    const pRental = data.prices?.rentalMo || 180;
    const pPurchase = data.prices?.purchase || 850;
    const pBoardFirst = data.prices?.boardFirst || 250;
    const pBoardAdd = data.prices?.boardAdd || 150;
    const pNoAds = data.prices?.noAds || 150;

    const currentOfferType = managingChantier?.offerType || 'rental';
    const currentPanels = managingChantier?.physicalPanels || 0;
    const currentHasNoAds = managingChantier?.hasNoAds || false;

    let boardCostHT = 0;
    if (currentPanels > 0) {
        boardCostHT = pBoardFirst + (currentPanels - 1) * pBoardAdd;
    }

    let upfrontHT = boardCostHT + (currentHasNoAds ? pNoAds : 0);
    if (currentOfferType === 'rental') {
        upfrontHT += pRental;
    } else {
        upfrontHT += pPurchase;
    }

    const discountPct = myClientData.discount || 0;
    const priceMultiplier = Math.max(0, (100 - discountPct) / 100);
    
    const platformHasTva = data.settings?.billing_has_tva !== '0';
    const tvaMult = platformHasTva ? 1.20 : 1.00;

    const finalUpfrontTTC = upfrontHT * priceMultiplier * tvaMult;
    const finalMonthlyTTC = pRental * priceMultiplier * tvaMult;

    return (
        <window.DashboardLayout 
            role={isCollaborator ? "Collaborateur" : "Client titulaire"} 
            user={myClientData.name || 'Connecté'} 
            theme="emerald" 
            navItems={navItems} 
            activeTab={activeTab} 
            setActiveTab={setActiveTab} 
            onLogout={handleLogout} 
            customLogout={customLogout}
            sidebarFooter={!isCollaborator ? (
                <label className="flex items-center justify-between p-3 rounded-xl border border-slate-200 bg-white hover:bg-slate-50 transition cursor-pointer mb-2" title="Activer les fonctionnalités avancées (équipes, personnalisation)">
                    <span className="text-xs font-bold text-slate-700">Mode avancé</span>
                    <div className={`w-8 h-4 rounded-full transition-colors relative shrink-0 ${uiMode === 'professionnel' ? 'bg-emerald-500' : 'bg-slate-300'}`}>
                        <div className={`absolute top-[2px] bg-white w-3 h-3 rounded-full transition-transform ${uiMode === 'professionnel' ? 'translate-x-4' : 'translate-x-1'}`}></div>
                    </div>
                    <input type="checkbox" className="hidden" checked={uiMode === 'professionnel'} onChange={(e) => handleUiModeChange(e.target.checked)} disabled={isSaving} />
                </label>
            ) : null}
        >
            {activeTab === 'dashboard' && renderDashboard()}
            {activeTab === 'panels' && renderPanels()}
            {activeTab === 'livraisons' && renderLivraisons()}
            {activeTab === 'messages' && renderMessages()}
            {activeTab === 'billing' && renderBilling()}
            {activeTab === 'account' && renderAccount()}

            {/* Modale d'avertissement TVA */}
            {showTvaWarning && (
                <window.Modal title="Avertissement légal" onClose={() => setShowTvaWarning(false)}>
                    <div className="space-y-4">
                        <div className="bg-orange-50 text-orange-800 p-5 rounded-2xl border border-orange-200 text-sm leading-relaxed">
                            <p className="font-black mb-2 flex items-center gap-2"><AlertTriangle size={18}/> Déclaration sur l'honneur</p>
                            <p>En désactivant ce champ, vous attestez sur l'honneur relever d'un régime d'exonération de TVA (ex: franchise en base de TVA des micro-entreprises - art. 293 B du CGI).</p>
                            <p className="mt-2">Veuillez noter que la plateforme eco-panneau.fr est tenue de vous facturer la TVA française (20%) sur ses services. En tant que non-assujetti, vous ne pourrez pas la récupérer fiscalement.</p>
                            <p className="mt-2 font-bold text-orange-900">Toute fausse déclaration engage votre responsabilité exclusive vis-à-vis de l'administration fiscale.</p>
                        </div>
                        <div className="flex gap-3">
                            <button onClick={() => setShowTvaWarning(false)} className="flex-1 bg-slate-100 text-slate-700 py-3 rounded-xl font-bold hover:bg-slate-200 transition">Annuler</button>
                            <button onClick={confirmTvaExemption} className="flex-1 bg-emerald-600 text-white py-3 rounded-xl font-black uppercase tracking-widest hover:bg-emerald-700 transition shadow-lg">J'atteste et je désactive</button>
                        </div>
                    </div>
                </window.Modal>
            )}

            {/* Modale de gestion d'équipe */}
            {modalStep === 'team_manage' && (
                <window.Modal title="Équipe de collaborateurs" onClose={() => setModalStep('config_full')}>
                    <div className="space-y-6">
                        <div className="bg-slate-50 p-4 rounded-xl border border-slate-200">
                            <p className="text-sm font-bold text-slate-800 mb-2">Inviter un nouveau membre</p>
                            <div className="flex gap-2">
                                <input type="email" value={teamEmail} onChange={e=>setTeamEmail(e.target.value)} placeholder="E-mail du collaborateur" className="flex-1 border border-slate-200 rounded-lg p-2.5 text-sm outline-none focus:border-emerald-500 bg-white" />
                                <button onClick={handleInviteTeam} disabled={isSaving || !teamEmail} className="bg-slate-900 text-white px-4 rounded-lg font-bold hover:bg-slate-800 transition disabled:opacity-50 text-sm">Inviter</button>
                            </div>
                        </div>
                        <div className="space-y-3">
                            <p className="text-sm font-bold text-slate-800">Membres actuels</p>
                            {data.team?.map((member, i) => (
                                <div key={i} className="flex items-center justify-between p-3 bg-white shadow-sm rounded-xl border border-slate-100">
                                    <div className="flex items-center gap-3">
                                        <div className="w-8 h-8 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center shrink-0"><UserCircle size={16}/></div>
                                        <p className="font-bold text-sm text-slate-700">{member.email}</p>
                                    </div>
                                    <button onClick={() => handleDeleteTeamMember(member.id)} disabled={isSaving} className="p-2 text-red-500 hover:bg-red-100 rounded-lg transition" title="Supprimer ce collaborateur">
                                        <Trash2 size={16}/>
                                    </button>
                                </div>
                            ))}
                            {(!data.team || data.team.length === 0) && <p className="text-center text-sm text-slate-400 py-4 italic">Aucun collaborateur dans votre équipe.</p>}
                        </div>
                    </div>
                </window.Modal>
            )}

            {/* Modales d'actions */}
            {isModalOpen && modalStep.startsWith('config') && (
                <div className="fixed inset-0 bg-slate-900/80 backdrop-blur-md z-[200] animate-in fade-in duration-300 flex items-center justify-center p-0 sm:p-4" onMouseDown={(e) => { if(e.target === e.currentTarget) document.getElementById('editor-cancel-btn')?.click(); }}>
                    <div className="h-full sm:h-[95vh] w-full max-w-5xl mx-auto bg-white sm:rounded-3xl shadow-2xl flex flex-col relative overflow-hidden" onMouseDown={e => e.stopPropagation()}>
                        <div className="p-4 sm:p-6 border-b border-slate-100 flex justify-between items-center bg-slate-50 shrink-0">
                            <div><h2 className="text-xl font-black text-slate-800">{managingChantier.id ? 'Édition du chantier' : 'Nouveau chantier'}</h2><p className="text-xs text-slate-500 font-medium">Assurez-vous de l'exactitude des informations légales.</p></div>
                            <button onClick={() => document.getElementById('editor-cancel-btn')?.click()} className="text-slate-400 hover:bg-white hover:text-slate-700 p-2 rounded-xl border border-transparent hover:border-slate-200 transition" title="Fermer"><X size={24}/></button>
                        </div>
                        
                        {validationErrors.length > 0 && (
                            <div className="mx-4 sm:mx-6 mt-4 bg-red-50 border-2 border-red-200 p-4 rounded-xl">
                                <h4 className="font-black text-red-800 flex items-center gap-2 mb-2"><AlertTriangle size={18}/> Impossible de publier. Éléments bloquants :</h4>
                                <ul className="list-disc pl-5 text-sm text-red-700 space-y-1 font-medium">
                                    {validationErrors.map((err, idx) => <li key={idx}>{err}</li>)}
                                </ul>
                            </div>
                        )}

                        <div className="flex-1 relative overflow-hidden">
                            <window.ChantierEditorForm 
                                chantier={managingChantier} 
                                setChantier={setManagingChantier} 
                                managingChantier={managingChantier} 
                                onCancel={() => setIsModalOpen(false)} 
                                onSaveDraft={() => handleSaveChantier(true)} 
                                onPublish={
                                    isCollaborator 
                                    ? (managingChantier.status === 'Actif' ? () => {
                                        const errs = validatePanel();
                                        if (errs.length > 0) setValidationErrors(errs);
                                        else handleSaveChantier(false);
                                      } : undefined) 
                                    : () => {
                                        const errs = validatePanel();
                                        if (errs.length > 0) {
                                            setValidationErrors(errs);
                                        } else {
                                            setValidationErrors([]);
                                            if (managingChantier.status === 'Brouillon') {
                                                setModalStep('select_offer');
                                            } else {
                                                handleSaveChantier(false);
                                            }
                                        }
                                    }
                                }
                                onPreview={() => setPreviewChantier(managingChantier)}
                                onEditEntity={(loc, data) => setEditingEntity({location: loc, data})} 
                                draggedItem={draggedItem} 
                                handleDragStart={handleDragStart} 
                                handleDragOver={handleDragOver} 
                                handleDrop={handleDrop} 
                                deleteEntity={deleteEntity} 
                                isSaving={isSaving} 
                                uiMode={uiMode} 
                                settings={data.settings}
                                validationErrors={validationErrors}
                            />
                        </div>
                        {editingEntity && <window.EntityEditorModal editingEntity={editingEntity} setEditingEntity={setEditingEntity} saveEditedEntity={saveEditedEntity} />}
                    </div>
                </div>
            )}

            {isModalOpen && modalStep === 'select_offer' && (
                <div className="fixed inset-0 bg-slate-900/80 backdrop-blur-md z-[200] animate-in fade-in duration-300 flex items-center justify-center p-4">
                    <div className="w-full max-w-2xl bg-white rounded-3xl shadow-2xl flex flex-col relative overflow-hidden">
                        <div className="p-6 border-b border-slate-100 bg-slate-50 flex justify-between items-center">
                            <div><h2 className="text-xl font-black text-slate-800">Choix de l'offre</h2><p className="text-xs text-slate-500 font-medium">Sélectionnez le type d'abonnement et les options matérielles.</p></div>
                            <button onClick={() => setModalStep('config_full')} className="text-slate-400 hover:bg-white hover:text-slate-700 p-2 rounded-xl border border-transparent hover:border-slate-200 transition" title="Retour à l'édition"><X size={24}/></button>
                        </div>
                        <div className="p-6 space-y-8 overflow-y-auto custom-scrollbar max-h-[80vh]">
                            
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                {/* Option Abonnement Mensuel */}
                                <div 
                                    onClick={() => setManagingChantier({...managingChantier, offerType: 'rental'})}
                                    className={`p-6 rounded-2xl border-2 cursor-pointer transition flex flex-col justify-between ${currentOfferType === 'rental' ? 'border-emerald-500 bg-emerald-50 shadow-md' : 'border-slate-200 hover:border-emerald-200'}`}
                                >
                                    <div>
                                        <div className="flex items-center gap-2 mb-2"><div className={`w-4 h-4 rounded-full border-2 flex items-center justify-center ${currentOfferType === 'rental' ? 'border-emerald-600' : 'border-slate-300'}`}><div className={`w-2 h-2 rounded-full bg-emerald-600 transition-opacity ${currentOfferType === 'rental' ? 'opacity-100' : 'opacity-0'}`}></div></div><h4 className="font-black text-slate-800">Abonnement mensuel</h4></div>
                                        <p className="text-3xl font-black text-emerald-600 my-4">{pRental} € <span className="text-sm font-bold text-slate-500">HT / mois</span></p>
                                        <p className="text-sm text-slate-600 leading-relaxed font-medium">Paiement mensuel automatisé. Résiliable à tout moment, en un clic, à la fin de votre chantier.</p>
                                    </div>
                                </div>

                                {/* Option Achat Définitif */}
                                <div 
                                    onClick={() => setManagingChantier({...managingChantier, offerType: 'purchase'})}
                                    className={`p-6 rounded-2xl border-2 cursor-pointer transition flex flex-col justify-between ${currentOfferType === 'purchase' ? 'border-emerald-500 bg-emerald-50 shadow-md' : 'border-slate-200 hover:border-emerald-200'}`}
                                >
                                    <div>
                                        <div className="flex items-center gap-2 mb-2"><div className={`w-4 h-4 rounded-full border-2 flex items-center justify-center ${currentOfferType === 'purchase' ? 'border-emerald-600' : 'border-slate-300'}`}><div className={`w-2 h-2 rounded-full bg-emerald-600 transition-opacity ${currentOfferType === 'purchase' ? 'opacity-100' : 'opacity-0'}`}></div></div><h4 className="font-black text-slate-800">Achat définitif</h4></div>
                                        <p className="text-3xl font-black text-emerald-600 my-4">{pPurchase} € <span className="text-sm font-bold text-slate-500">HT</span></p>
                                        <p className="text-sm text-slate-600 leading-relaxed font-medium">Paiement unique sans abonnement. Le panneau numérique reste actif indéfiniment.</p>
                                    </div>
                                </div>
                            </div>

                            <div className="bg-slate-50 p-6 rounded-2xl border border-slate-200 shadow-sm">
                                <h4 className="font-black text-slate-800 mb-2 flex items-center gap-2"><Package size={18} className="text-blue-600"/> Commander des panneaux physiques</h4>
                                <p className="text-sm text-slate-600 mb-6">Recevez votre panneau pré-imprimé (Format A1) sur un support rigide Akilux résistant aux intempéries, livré directement au cabinet.</p>
                                
                                <div className="flex items-center justify-between bg-white p-4 rounded-xl border border-slate-200">
                                    <div>
                                        <p className="text-sm font-bold text-slate-800">Quantité souhaitée</p>
                                        <p className="text-xs text-slate-500 mt-1 font-medium">{pBoardFirst}€ HT le premier, {pBoardAdd}€ HT l'unité supplémentaire.</p>
                                    </div>
                                    <div className="flex items-center gap-4 bg-slate-50 border border-slate-200 rounded-xl p-1 shadow-inner">
                                        <button onClick={() => setManagingChantier({...managingChantier, physicalPanels: Math.max(0, currentPanels - 1)})} className="w-10 h-10 flex items-center justify-center rounded-lg bg-white text-slate-600 hover:text-emerald-600 shadow-sm transition font-black text-xl">-</button>
                                        <span className="font-black text-xl w-6 text-center text-slate-800">{currentPanels}</span>
                                        <button onClick={() => setManagingChantier({...managingChantier, physicalPanels: currentPanels + 1})} className="w-10 h-10 flex items-center justify-center rounded-lg bg-white text-slate-600 hover:text-emerald-600 shadow-sm transition font-black text-xl">+</button>
                                    </div>
                                </div>
                            </div>

                            {/* Résumé en temps réel */}
                            <div className="bg-slate-900 rounded-2xl p-5 text-white shadow-xl">
                                <h4 className="text-sm font-bold text-slate-300 uppercase tracking-widest mb-3 border-b border-slate-700 pb-2">Résumé de votre commande</h4>
                                <div className="space-y-2 text-sm font-medium">
                                    <div className="flex justify-between">
                                        <span className="text-slate-300">{currentOfferType === 'rental' ? 'Abonnement mensuel (1er mois inclus)' : 'Achat définitif'}</span>
                                        <span>{(currentOfferType === 'rental' ? pRental : pPurchase).toFixed(2)} € HT</span>
                                    </div>
                                    {currentPanels > 0 && (
                                        <div className="flex justify-between">
                                            <span className="text-slate-300">Panneaux physiques ({currentPanels}x)</span>
                                            <span>{boardCostHT.toFixed(2)} € HT</span>
                                        </div>
                                    )}
                                    {currentHasNoAds && (
                                        <div className="flex justify-between">
                                            <span className="text-slate-300">Option marque blanche</span>
                                            <span>{pNoAds.toFixed(2)} € HT</span>
                                        </div>
                                    )}
                                    {discountPct > 0 && (
                                        <div className="flex justify-between text-emerald-400">
                                            <span>Remise client ({discountPct}%)</span>
                                            <span>-{(upfrontHT * (discountPct / 100)).toFixed(2)} € HT</span>
                                        </div>
                                    )}
                                    <div className="border-t border-slate-700 mt-3 pt-3 flex justify-between items-end">
                                        <div>
                                            <p className="text-lg font-black">Total à payer aujourd'hui</p>
                                            <p className="text-[10px] text-slate-400 uppercase tracking-wider mt-1">{platformHasTva ? 'TVA 20% incluse' : 'TVA non applicable'}</p>
                                        </div>
                                        <div className="text-right">
                                            <p className="text-2xl font-black text-emerald-400">{finalUpfrontTTC.toFixed(2)} €</p>
                                            {currentOfferType === 'rental' && <p className="text-xs text-slate-400 mt-1">Puis {finalMonthlyTTC.toFixed(2)} € TTC / mois</p>}
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div className="flex gap-3 pt-2">
                                <button type="button" onClick={() => setModalStep('config_full')} disabled={isSaving} className="px-6 py-3 rounded-xl font-bold text-slate-500 hover:bg-slate-100 transition disabled:opacity-50">Retour</button>
                                <button onClick={handleActivationRequest} disabled={isSaving} className="flex-1 bg-emerald-600 text-white py-3 rounded-xl font-black uppercase tracking-widest hover:bg-emerald-700 transition shadow-lg flex items-center justify-center gap-2 disabled:opacity-50">
                                    {isSaving ? <Loader className="animate-spin w-5 h-5"/> : <CreditCard size={18}/>} Confirmer l'offre et payer
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {isModalOpen && modalStep === 'payment' && paymentData && (
                <window.Modal title="Activation du panneau légal" onClose={() => setIsModalOpen(false)} preventClose={isSaving}>
                    <StripePaymentForm clientSecret={paymentData.secret} amountCents={paymentData.amountCents} onSuccess={handlePaymentSuccess} onCancel={() => setIsModalOpen(false)} />
                </window.Modal>
            )}

            {isModalOpen && modalStep === 'share' && (
                <window.Modal title="Lien de saisie déléguée" onClose={() => setIsModalOpen(false)}>
                    <div className="text-center space-y-6">
                        <div className="w-16 h-16 bg-blue-100 text-blue-600 rounded-full flex items-center justify-center mx-auto"><Share2 size={32}/></div>
                        <div>
                            <p className="text-sm text-slate-600 mb-4">Envoyez ce lien sécurisé (valable 7 jours) à l'architecte ou au maître d'œuvre. Il pourra compléter l'équipe et déposer l'arrêté sans avoir accès à votre facturation.</p>
                            <div className="flex items-center gap-2 bg-slate-50 p-2 rounded-xl border border-slate-200">
                                <input type="text" readOnly value={delegateLink} className="flex-1 bg-transparent text-sm text-slate-500 font-mono outline-none px-2" />
                                <button onClick={() => { navigator.clipboard.writeText(delegateLink); showToast("Lien copié !"); }} title="Copier le lien" className="bg-white border border-slate-200 text-slate-700 px-4 py-2 rounded-lg text-xs font-bold hover:bg-slate-100 transition shadow-sm"><Copy size={14}/></button>
                            </div>
                        </div>
                    </div>
                </window.Modal>
            )}

            {isModalOpen && modalStep === 'legal_vault' && (
                <window.Modal title="Coffre-fort légal privé" onClose={() => setIsModalOpen(false)}>
                    <div className="space-y-6">
                        <div className="bg-slate-50 p-4 rounded-xl border border-slate-200 flex gap-4 items-start">
                            <Lock size={24} className="text-slate-400 shrink-0"/>
                            <div>
                                <p className="text-sm font-bold text-slate-800">Preuves et constats d'huissier</p>
                                <p className="text-xs text-slate-500 mt-1">Ces documents sont chiffrés et inaccessibles au public. Ils seront inclus dans l'archive D.O.E lors de la clôture du chantier.</p>
                            </div>
                        </div>
                        <div className="space-y-3">
                            {managingChantier.privateDocs?.map((doc, idx) => (
                                <div key={idx} className="flex items-center justify-between p-3 bg-white border border-slate-200 rounded-xl shadow-sm">
                                    <div className="flex items-center gap-3">
                                        <div className="w-10 h-10 bg-slate-100 text-slate-500 rounded-lg flex items-center justify-center"><FileCheck size={20}/></div>
                                        <div><p className="text-sm font-bold text-slate-700 truncate max-w-[200px]">{doc.name}</p><p className="text-[10px] text-slate-400 uppercase">{doc.date}</p></div>
                                    </div>
                                    <div className="flex gap-2">
                                        <button onClick={() => window.open(`?api=file/download_private&type=${doc.type}&id=${doc.id}`, '_blank')} title="Télécharger le document" className="p-2 text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 transition"><Download size={16}/></button>
                                        <button onClick={() => {
                                            const newDocs = [...managingChantier.privateDocs]; newDocs.splice(idx, 1);
                                            setManagingChantier({...managingChantier, privateDocs: newDocs}); handleSaveChantier(true);
                                        }} title="Supprimer ce document privé" className="p-2 text-red-600 bg-red-50 rounded-lg hover:bg-red-100 transition"><Trash2 size={16}/></button>
                                    </div>
                                </div>
                            ))}
                            {(!managingChantier.privateDocs || managingChantier.privateDocs.length === 0) && <p className="text-center text-sm text-slate-400 py-4 italic">Aucun document privé stocké.</p>}
                        </div>
                        <label className="w-full border-2 border-dashed border-slate-300 rounded-xl p-6 flex flex-col items-center justify-center gap-2 cursor-pointer hover:bg-slate-50 transition" title="Sélectionner un fichier (PDF ou image)">
                            <Plus size={24} className="text-slate-400"/>
                            <span className="text-sm font-bold text-slate-600">Ajouter une preuve (PDF/image)</span>
                            <input type="file" accept="application/pdf,image/*" className="hidden" disabled={isSaving} onChange={async (e) => {
                                const file = e.target.files[0]; if(!file) return;
                                if (file.size > 5 * 1024 * 1024) return showToast("Fichier trop lourd (max 5 Mo).", "error");
                                setIsSaving(true);
                                try {
                                    const type = file.type.includes('pdf') ? 'pdf' : 'image';
                                    const id = await window.uploadFile(file, type, null, true);
                                    const newDocs = [...(managingChantier.privateDocs || []), { id, type, name: file.name, date: new Date().toLocaleDateString('fr-FR') }];
                                    const updatedChantier = {...managingChantier, privateDocs: newDocs};
                                    setManagingChantier(updatedChantier);
                                    await fetch(window.ECO_CONFIG.apiBaseUrl + 'chantiers', { method: 'POST', body: JSON.stringify({ id: updatedChantier.id, status: updatedChantier.status, offerType: updatedChantier.offerType, currentRate: updatedChantier.currentRate, physicalPanels: updatedChantier.physicalPanels, details: updatedChantier }) });
                                    refreshData();
                                } catch(err) { showToast(err.message, "error"); }
                                setIsSaving(false); e.target.value = null;
                            }} />
                        </label>
                    </div>
                </window.Modal>
            )}

            {previewChantier && <window.PreviewModal chantier={previewChantier} interactions={interactions} onClose={() => setPreviewChantier(null)} showToast={showToast} refreshData={refreshData} />}
        </window.DashboardLayout>
    );
};

/* EOF ===== [_clients.jsx] =============== */