/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Point d'entrée de l'Application React (_main.jsx)
 * Gère le routage, l'authentification, les toasts et le flux de données
 * =========================================================================
 */

const { useState, useEffect, useRef } = React;
const { ShieldAlert, CheckCircle, AlertTriangle, Loader, LogIn, Mail, KeyRound, X, ArrowLeft } = window;

// =========================================================================
// 1. COMPOSANT DÉLÉGUÉ (ACCÈS ARCHITECTE / SOUS-TRAITANT)
// =========================================================================

const DelegateView = ({ token, showToast }) => {
    const [chantier, setChantier] = useState(null);
    const [loading, setLoading] = useState(true);
    const [isSaving, setIsSaving] = useState(false);
    const [editingEntity, setEditingEntity] = useState(null);
    const [draggedItem, setDraggedItem] = useState(null);

    useEffect(() => {
        window.CURRENT_DELEGATE_TOKEN = token;
        
        fetch(window.ECO_CONFIG.apiBaseUrl + 'chantiers/delegated_access&token=' + encodeURIComponent(token))
            .then(res => res.json())
            .then(d => {
                if (d.status === 'success') setChantier(d.data);
                else showToast(d.message || "Lien invalide ou expiré.", "error");
            })
            .catch(() => showToast("Erreur de connexion", "error"))
            .finally(() => setLoading(false));

        return () => { window.CURRENT_DELEGATE_TOKEN = null; };
    }, [token]);

    const handleSave = () => {
        setIsSaving(true);
        fetch(window.ECO_CONFIG.apiBaseUrl + 'chantiers/delegated_update', {
            method: 'POST',
            body: JSON.stringify({
                token,
                name: chantier.name,
                location: chantier.location,
                themeColor: chantier.themeColor,
                intervenants: chantier.intervenants,
                lots: chantier.lots,
                pdfId: chantier.pdfId
            })
        }).then(res => res.json()).then(d => {
            if (d.status === 'success') {
                showToast("Modifications enregistrées avec succès.", "success");
                setTimeout(() => window.location.href = '?', 2000);
            } else {
                showToast(d.message || "Erreur de sauvegarde", "error");
            }
        }).finally(() => setIsSaving(false));
    };

    const saveEditedEntity = () => {
        let newInter = [...(chantier.intervenants || [])];
        let newLots = JSON.parse(JSON.stringify(chantier.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()});
        }
        setChantier({ ...chantier, intervenants: newInter, lots: newLots });
        setEditingEntity(null);
    };

    const deleteEntity = (loc) => {
        if (!confirm("Supprimer cet élément ?")) return;
        let newInter = [...(chantier.intervenants || [])];
        let newLots = JSON.parse(JSON.stringify(chantier.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);
        setChantier({ ...chantier, 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 = [...(chantier.intervenants || [])];
        let newLots = JSON.parse(JSON.stringify(chantier.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);
        }
        setChantier({ ...chantier, intervenants: newInter, lots: newLots });
        setDraggedItem(null);
    };

    if (loading) return <div className="h-screen flex items-center justify-center bg-slate-50"><Loader className="animate-spin text-emerald-600" size={32} /></div>;
    if (!chantier) return <div className="h-screen flex items-center justify-center bg-slate-50 text-slate-500 font-bold">Accès non autorisé ou expiré.</div>;

    return (
        <div className="h-screen bg-slate-100 flex flex-col">
            <div className="bg-slate-900 text-white p-4 sm:p-6 shrink-0 shadow-md z-10 flex justify-between items-center">
                <div>
                    <h1 className="text-xl font-black">Accès délégué</h1>
                    <p className="text-xs text-slate-400">Édition restreinte du panneau légal</p>
                </div>
            </div>
            <div className="flex-1 relative overflow-hidden">
                <window.ChantierEditorForm 
                    chantier={chantier} 
                    setChantier={setChantier} 
                    managingChantier={{status: 'Brouillon'}} 
                    onCancel={() => window.location.href = '?'} 
                    onSaveDraft={handleSave} 
                    onEditEntity={(loc, data) => setEditingEntity({location: loc, data})} 
                    draggedItem={draggedItem} 
                    handleDragStart={handleDragStart} 
                    handleDragOver={handleDragOver} 
                    handleDrop={handleDrop} 
                    deleteEntity={deleteEntity} 
                    isSaving={isSaving} 
                    uiMode="delege" 
                />
            </div>
            {editingEntity && <window.EntityEditorModal editingEntity={editingEntity} setEditingEntity={setEditingEntity} saveEditedEntity={saveEditedEntity} />}
        </div>
    );
};

// =========================================================================
// 2. ÉCRAN D'AUTHENTIFICATION UNIFIÉ
// =========================================================================

const AuthScreen = ({ onLoginSuccess, showToast, urlParams, initialView = 'login', onBack }) => {
    const [view, setView] = useState(initialView); 
    const [loading, setLoading] = useState(false);
    const [loginData, setLoginData] = useState({ email: '', password: '', code2fa: '' });
    const [regData, setRegData] = useState({ email: '', company: '' });

    useEffect(() => {
        const processUrlParams = async () => {
            const grantToken = urlParams.get('grant_access');
            if (grantToken) {
                try {
                    const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'clients/grant_access', { method: 'POST', body: JSON.stringify({ token: grantToken }) });
                    if ((await res.json()).status === 'success') showToast("Accès temporaire accordé au support.", "success");
                    else showToast("Lien d'autorisation invalide.", "error");
                } catch(e) { showToast("Erreur réseau.", "error"); }
                window.history.replaceState({}, '', '?');
            }
            
            const regToken = urlParams.get('reg_token');
            if (regToken) setView('register_confirm');
            
            const resetToken = urlParams.get('reset_token');
            if (resetToken) setView('reset_password');
        };
        processUrlParams();
    }, []);

    const handleLogin = async (e) => {
        e.preventDefault();
        setLoading(true);
        try {
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'auth/login', { method: 'POST', body: JSON.stringify({ login: loginData.email, password: loginData.password }) });
            const data = await res.json();
            if (data.status === 'success') {
                if (data.data['2fa_required']) {
                    setView('2fa');
                    showToast(data.data.method === 'email' ? "Un code a été envoyé à votre adresse e-mail." : "Ouvrez votre application d'authentification.", "info");
                } else {
                    onLoginSuccess(data.data.role);
                }
            } else {
                showToast(data.message || "Identifiants incorrects", "error");
            }
        } catch (err) { showToast("Erreur de connexion", "error"); }
        setLoading(false);
    };

    const handle2FA = async (e) => {
        e.preventDefault();
        setLoading(true);
        try {
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'auth/verify_2fa', { method: 'POST', body: JSON.stringify({ code: loginData.code2fa }) });
            const data = await res.json();
            if (data.status === 'success') onLoginSuccess(data.data.role);
            else showToast(data.message || "Code invalide", "error");
        } catch (err) { showToast("Erreur de validation", "error"); }
        setLoading(false);
    };

    const handleRegisterRequest = async (e) => {
        e.preventDefault(); setLoading(true);
        try {
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'auth/register_request', { method: 'POST', body: JSON.stringify(regData) });
            const data = await res.json();
            if (data.status === 'success') { setView('register_pending'); showToast("Veuillez vérifier vos e-mails.", "success"); }
            else if (data.status === 'exists') { setView('login'); showToast("Ce compte existe déjà. Veuillez vous connecter.", "info"); }
            else showToast(data.message || "Erreur d'inscription", "error");
        } catch (err) { showToast("Erreur réseau", "error"); }
        setLoading(false);
    };

    const handleRegisterConfirm = async (e) => {
        e.preventDefault(); setLoading(true);
        try {
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'auth/register_confirm', { method: 'POST', body: JSON.stringify({ token: urlParams.get('reg_token'), password: loginData.password }) });
            const data = await res.json();
            if (data.status === 'success') { showToast("Compte créé avec succès !", "success"); window.history.replaceState({}, '', '?'); onLoginSuccess('client'); }
            else showToast(data.message || "Lien invalide", "error");
        } catch (err) { showToast("Erreur", "error"); }
        setLoading(false);
    };

    const handleResetPassword = async (e) => {
        e.preventDefault(); setLoading(true);
        try {
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'auth/reset_password', { method: 'POST', body: JSON.stringify({ token: urlParams.get('reset_token'), password: loginData.password }) });
            const data = await res.json();
            if (data.status === 'success') { showToast("Mot de passe modifié !", "success"); window.history.replaceState({}, '', '?'); setView('login'); }
            else showToast(data.message || "Lien expiré", "error");
        } catch (err) { showToast("Erreur", "error"); }
        setLoading(false);
    };

    const handleForgotPasswordRequest = async (e) => {
        e.preventDefault(); setLoading(true);
        try {
            await fetch(window.ECO_CONFIG.apiBaseUrl + 'auth/forgot_password', { method: 'POST', body: JSON.stringify({ email: loginData.email }) });
            showToast("Si ce compte existe, un e-mail a été envoyé.", "info");
            setView('login');
        } catch (err) { showToast("Erreur", "error"); }
        setLoading(false);
    };

    return (
        <div className="min-h-screen bg-slate-50 flex items-center justify-center p-4 relative overflow-hidden">
            <div className="absolute -top-40 -left-40 w-96 h-96 bg-emerald-400 rounded-full mix-blend-multiply filter blur-[100px] opacity-30 animate-pulse"></div>
            <div className="absolute -bottom-40 -right-40 w-96 h-96 bg-blue-400 rounded-full mix-blend-multiply filter blur-[100px] opacity-30 animate-pulse" style={{ animationDelay: '2s' }}></div>

            <div className="bg-white rounded-3xl shadow-2xl w-full max-w-md p-8 relative z-10 border border-slate-100">
                
                <button onClick={onBack} title="Fermer" className="absolute top-4 right-4 p-2 text-slate-400 hover:text-slate-800 hover:bg-slate-100 rounded-full transition">
                    <X size={20} />
                </button>

                <div className="flex justify-center mb-8">
                    <window.SiteLogo className="text-2xl cursor-pointer hover:opacity-80 transition" qrSize={32} onClick={onBack} title="Retour à l'accueil" />
                </div>

                {view === 'login' && (
                    <div className="animate-in fade-in slide-in-from-bottom-4">
                        <h2 className="text-2xl font-black text-slate-800 text-center mb-6">Connexion</h2>
                        <form onSubmit={handleLogin} className="space-y-4">
                            <div><label className="text-xs font-bold text-slate-500 uppercase tracking-wider block mb-1">E-mail ou identifiant</label><input type="text" required value={loginData.email} onChange={e=>setLoginData({...loginData, email: e.target.value})} className="w-full border-2 border-slate-200 rounded-xl p-3 focus:border-emerald-500 outline-none transition" /></div>
                            <div>
                                <div className="flex justify-between items-center mb-1">
                                    <label className="text-xs font-bold text-slate-500 uppercase tracking-wider block">Mot de passe</label>
                                    <button type="button" onClick={()=>setView('forgot')} className="text-xs text-emerald-600 font-bold hover:underline">Oublié ?</button>
                                </div>
                                <input type="password" required value={loginData.password} onChange={e=>setLoginData({...loginData, password: e.target.value})} className="w-full border-2 border-slate-200 rounded-xl p-3 focus:border-emerald-500 outline-none transition" />
                            </div>
                            <button type="submit" disabled={loading} className="w-full bg-slate-900 text-white py-4 rounded-xl font-black uppercase tracking-widest hover:bg-slate-800 transition shadow-lg flex items-center justify-center gap-2 mt-4 disabled:opacity-50">
                                {loading ? <Loader className="animate-spin"/> : <LogIn size={18}/>} Se connecter
                            </button>
                        </form>
                        <div className="mt-8 text-center border-t border-slate-100 pt-6">
                            <p className="text-sm text-slate-500">Vous n'avez pas de compte ?</p>
                            <button onClick={()=>setView('register')} className="text-emerald-600 font-bold mt-1 hover:underline">Créer un compte professionnel</button>
                            <div className="mt-6">
                                <button onClick={onBack} className="text-xs font-bold text-slate-400 hover:text-slate-600 flex items-center justify-center gap-1 mx-auto transition">
                                    <ArrowLeft size={14}/> Retour à l'accueil
                                </button>
                            </div>
                        </div>
                    </div>
                )}

                {view === '2fa' && (
                    <div className="animate-in fade-in slide-in-from-right-4">
                        <div className="flex justify-center mb-4 text-emerald-600"><ShieldAlert size={48} /></div>
                        <h2 className="text-2xl font-black text-slate-800 text-center mb-2">Sécurité requise</h2>
                        <p className="text-center text-sm text-slate-500 mb-6">Veuillez saisir le code de vérification à 6 chiffres pour valider votre identité.</p>
                        <form onSubmit={handle2FA} className="space-y-4">
                            <input type="text" required maxLength="6" placeholder="000000" value={loginData.code2fa} onChange={e=>setLoginData({...loginData, code2fa: e.target.value})} className="w-full border-2 border-slate-200 rounded-xl p-4 text-center text-2xl font-mono tracking-widest focus:border-emerald-500 outline-none transition" />
                            <button type="submit" disabled={loading} className="w-full bg-emerald-600 text-white py-4 rounded-xl font-black uppercase tracking-widest hover:bg-emerald-700 transition shadow-lg disabled:opacity-50">Valider</button>
                        </form>
                        <button onClick={()=>setView('login')} className="w-full text-center text-sm font-bold text-slate-400 hover:text-slate-600 mt-6">Annuler</button>
                    </div>
                )}

                {view === 'register' && (
                    <div className="animate-in fade-in slide-in-from-right-4">
                        <h2 className="text-2xl font-black text-slate-800 text-center mb-6">Nouveau compte</h2>
                        <form onSubmit={handleRegisterRequest} className="space-y-4">
                            <div><label className="text-xs font-bold text-slate-500 uppercase block mb-1">Nom de la société</label><input type="text" required value={regData.company} onChange={e=>setRegData({...regData, company: e.target.value})} className="w-full border-2 border-slate-200 rounded-xl p-3 focus:border-emerald-500 outline-none transition" /></div>
                            <div><label className="text-xs font-bold text-slate-500 uppercase block mb-1">E-mail professionnel</label><input type="email" required value={regData.email} onChange={e=>setRegData({...regData, email: e.target.value})} className="w-full border-2 border-slate-200 rounded-xl p-3 focus:border-emerald-500 outline-none transition" /></div>
                            <button type="submit" disabled={loading} className="w-full bg-emerald-600 text-white py-4 rounded-xl font-black uppercase tracking-widest hover:bg-emerald-700 transition shadow-lg mt-4 disabled:opacity-50">Inscription gratuite</button>
                        </form>
                        <button onClick={()=>setView('login')} className="w-full text-center text-sm font-bold text-slate-400 hover:text-slate-600 mt-6">Retour à la connexion</button>
                    </div>
                )}

                {view === 'register_pending' && (
                    <div className="text-center animate-in fade-in zoom-in-95">
                        <div className="w-20 h-20 bg-emerald-100 text-emerald-600 rounded-full flex items-center justify-center mx-auto mb-6"><Mail size={32} /></div>
                        <h2 className="text-2xl font-black text-slate-800 mb-2">Vérifiez vos e-mails</h2>
                        <p className="text-slate-500 text-sm">Un lien d'activation a été envoyé à l'adresse indiquée. Cliquez dessus pour configurer votre mot de passe.</p>
                    </div>
                )}

                {view === 'register_confirm' && (
                    <div className="animate-in fade-in slide-in-from-bottom-4">
                        <div className="flex justify-center mb-4 text-emerald-600"><KeyRound size={40} /></div>
                        <h2 className="text-2xl font-black text-slate-800 text-center mb-2">Sécurisez votre compte</h2>
                        <p className="text-center text-sm text-slate-500 mb-6">Créez un mot de passe robuste (Min 8 caractères, Maj, Min, Chiffre).</p>
                        <form onSubmit={handleRegisterConfirm} className="space-y-4">
                            <input type="password" required value={loginData.password} onChange={e=>setLoginData({...loginData, password: e.target.value})} placeholder="Votre mot de passe..." className="w-full border-2 border-slate-200 rounded-xl p-3 focus:border-emerald-500 outline-none transition" />
                            <button type="submit" disabled={loading} className="w-full bg-emerald-600 text-white py-4 rounded-xl font-black uppercase tracking-widest hover:bg-emerald-700 transition shadow-lg disabled:opacity-50">Activer mon compte</button>
                        </form>
                    </div>
                )}

                {view === 'forgot' && (
                    <div className="animate-in fade-in slide-in-from-left-4">
                        <h2 className="text-2xl font-black text-slate-800 text-center mb-2">Mot de passe oublié</h2>
                        <p className="text-center text-sm text-slate-500 mb-6">Entrez votre e-mail pour recevoir un lien de réinitialisation.</p>
                        <form onSubmit={handleForgotPasswordRequest} className="space-y-4">
                            <input type="email" required value={loginData.email} onChange={e=>setLoginData({...loginData, email: e.target.value})} placeholder="E-mail du compte" className="w-full border-2 border-slate-200 rounded-xl p-3 focus:border-emerald-500 outline-none transition" />
                            <button type="submit" disabled={loading} className="w-full bg-slate-900 text-white py-4 rounded-xl font-black uppercase tracking-widest hover:bg-slate-800 transition shadow-lg disabled:opacity-50">Envoyer le lien</button>
                        </form>
                        <button onClick={()=>setView('login')} className="w-full text-center text-sm font-bold text-slate-400 hover:text-slate-600 mt-6">Annuler</button>
                    </div>
                )}

                {view === 'reset_password' && (
                    <div className="animate-in fade-in slide-in-from-bottom-4">
                        <h2 className="text-2xl font-black text-slate-800 text-center mb-6">Nouveau mot de passe</h2>
                        <form onSubmit={handleResetPassword} className="space-y-4">
                            <input type="password" required value={loginData.password} onChange={e=>setLoginData({...loginData, password: e.target.value})} placeholder="Nouveau mot de passe fort" className="w-full border-2 border-slate-200 rounded-xl p-3 focus:border-emerald-500 outline-none transition" />
                            <button type="submit" disabled={loading} className="w-full bg-emerald-600 text-white py-4 rounded-xl font-black uppercase tracking-widest hover:bg-emerald-700 transition shadow-lg disabled:opacity-50">Mettre à jour</button>
                        </form>
                    </div>
                )}
            </div>
            
            <div className="absolute bottom-4 inset-x-0 text-center text-[10px] font-bold text-slate-400 uppercase tracking-widest">
                Plateforme sécurisée © {new Date().getFullYear()} eco-panneau.fr
            </div>
        </div>
    );
};

// =========================================================================
// 3. RACINE DE L'APPLICATION (APP ROUTER)
// =========================================================================

const App = () => {
    const [globalData, setGlobalData] = useState({ chantiers: [], interactions: [], clients: [], invoices: [], settings: {}, prices: {}, stats: {} });
    const [loading, setLoading] = useState(true);
    const [userRole, setUserRole] = useState('public');
    const [toasts, setToasts] = useState([]);
    
    // Détection des URL spéciales
    const urlParams = new URLSearchParams(window.location.search);
    const scanId = urlParams.get('scan');
    const delegateToken = urlParams.get('delegate');
    const threadToken = urlParams.get('thread');
    const hasAuthParams = urlParams.has('reg_token') || urlParams.has('reset_token') || urlParams.has('grant_access');

    // État pour afficher la vitrine ou l'écran d'auth
    const [authMode, setAuthMode] = useState(hasAuthParams ? 'login' : null);

    const showToast = (msg, type = 'success') => {
        const id = Date.now();
        setToasts(prev => [...prev, { id, msg, type }]);
        setTimeout(() => setToasts(prev => prev.filter(t => t.id !== id)), 4000);
    };

    const hasFetched = useRef(false);
    
    const fetchData = async () => {
        try {
            const vid = window.getVisitorId ? window.getVisitorId() : '';
            // Anti-cache strict pour garantir que les données "Rafraîchir" sont bien nouvelles
            let url = window.ECO_CONFIG.apiBaseUrl + `sync&visitor_id=${vid}&_t=${Date.now()}`;
            if (scanId) url += `&scan=${scanId}`;
            if (threadToken) url += `&thread=${encodeURIComponent(threadToken)}`;

            const res = await fetch(url);
            if (res.status === 401) { setUserRole('public'); return; }
            if (res.status === 503) { showToast("Le site est en maintenance.", "error"); return; }
            
            const data = await res.json();
            if (data.status === 'success') {
                setGlobalData(data.data);
                if (data.data.clients && data.data.clients.length > 0) {
                    const roleRes = await fetch(window.ECO_CONFIG.apiBaseUrl + 'auth/me');
                    if (roleRes.ok) {
                        const roleData = await roleRes.json();
                        if (roleData.status === 'success') setUserRole(roleData.data.role);
                    }
                }
            }
        } catch (err) {
            console.error(err);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (hasFetched.current) return;
        hasFetched.current = true;
        
        fetchData();

        const handleSessionExpired = () => {
            showToast("Votre session a expiré.", "error");
            setUserRole('public');
            setAuthMode('login'); 
        };
        window.addEventListener('session_expired', handleSessionExpired);
        
        return () => window.removeEventListener('session_expired', handleSessionExpired);
    }, []);

    // ---------------------------------------------------------------------
    // ROUTAGE DES VUES
    // ---------------------------------------------------------------------

    if (loading) return (
        <div className="h-screen flex items-center justify-center bg-slate-50 flex-col gap-4">
            <Loader className="animate-spin text-emerald-600" size={32} />
            <p className="text-xs font-bold text-slate-500 uppercase tracking-widest animate-pulse">Chargement...</p>
        </div>
    );

    // 1. Vue Riverain standard (Scan physique)
    if (scanId) {
        const c = globalData.chantiers?.find(x => x.id === scanId);
        return (
            <React.Fragment>
                <window.RiverainView chantier={c} showToast={showToast} interactions={globalData.interactions} refreshData={fetchData} initialTab={threadToken ? "contact" : "home"} />
                <ToastContainer toasts={toasts} />
            </React.Fragment>
        );
    }

    // 2. Vue Riverain publique (Lien de réponse Support sans ID de panneau)
    if (threadToken && !scanId) {
        const publicChantier = { 
            id: 'CONTACT_PUBLIC', 
            name: 'Service client', 
            location: 'Plateforme eco-panneau.fr', 
            themeColor: '#0f172a', 
            hasNoAds: true 
        };
        return (
            <React.Fragment>
                <window.RiverainView chantier={publicChantier} showToast={showToast} interactions={globalData.interactions} refreshData={fetchData} initialTab="contact" />
                <ToastContainer toasts={toasts} />
            </React.Fragment>
        );
    }

    // 3. Délégation Architecte
    if (delegateToken) {
        return (
            <React.Fragment>
                <DelegateView token={delegateToken} showToast={showToast} />
                <ToastContainer toasts={toasts} />
            </React.Fragment>
        );
    }

    // 4. Espaces connectés
    if (userRole === 'admin') {
        return (
            <React.Fragment>
                <window.AdminView data={globalData} refreshData={fetchData} showToast={showToast} />
                <ToastContainer toasts={toasts} />
            </React.Fragment>
        );
    }

    if (userRole === 'client') {
        return (
            <React.Fragment>
                <window.ClientView data={globalData} refreshData={fetchData} showToast={showToast} />
                <ToastContainer toasts={toasts} />
            </React.Fragment>
        );
    }

    // Écran public : modale de connexion
    if (authMode) {
        return (
            <React.Fragment>
                <AuthScreen 
                    initialView={authMode}
                    onLoginSuccess={(role) => { setUserRole(role); setLoading(true); hasFetched.current = false; fetchData(); }} 
                    showToast={showToast} 
                    urlParams={urlParams} 
                    onBack={() => setAuthMode(null)}
                />
                <ToastContainer toasts={toasts} />
            </React.Fragment>
        );
    }

    // Écran public : Vitrine Web (Landing Page)
    return (
        <React.Fragment>
            <window.AccueilView onLoginClick={(mode) => setAuthMode(mode)} data={globalData} showToast={showToast} />
            <ToastContainer toasts={toasts} />
        </React.Fragment>
    );
};

// =========================================================================
// 4. SYSTÈME DE TOASTS GLOBAUX
// =========================================================================

const ToastContainer = ({ toasts }) => (
    <div className="fixed top-4 right-4 z-[9999] flex flex-col gap-2 pointer-events-none">
        {toasts.map(t => (
            <div key={t.id} className={`pointer-events-auto px-6 py-4 rounded-2xl shadow-2xl flex items-center gap-3 animate-in slide-in-from-right-8 fade-in text-white font-bold text-sm tracking-wide ${t.type === 'error' ? 'bg-red-600' : (t.type === 'info' ? 'bg-blue-600' : 'bg-slate-900')}`}>
                {t.type === 'error' ? <AlertTriangle size={18}/> : <CheckCircle size={18} className={t.type === 'success' ? 'text-emerald-400' : ''}/>}
                {t.msg}
            </div>
        ))}
    </div>
);

// =========================================================================
// 5. INJECTION REACT DANS LE DOM (React 18 API)
// =========================================================================

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <window.ErrorBoundary>
        <App />
    </window.ErrorBoundary>
);

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