/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Composant Vue Riverains (Interface publique scannée via QR Code)
 * Design Mobile-First, gère l'affichage légal et la messagerie publique.
 * =========================================================================
 */

const { useState, useEffect, useRef } = React;
const { 
    MapPin, Building, Phone, FileDigit, Users, MessageSquare, 
    AlertTriangle, ExternalLink, Clock, Info, Shield, Download, 
    PublicContactForm, ChatBox, Leaf, CheckCircle, Mail, SiteLogo, ArrowLeft, ArrowRight, X
} = window;

/**
 * Vue principale encapsulée pour le riverain.
 * S'affiche en plein écran sur mobile, ou confinée dans un mock-up iPhone sur l'espace client.
 */
window.RiverainView = ({ panneau, showToast, interactions = [], settings = {}, refreshData, isPreview = false, initialTab = 'home' }) => {
    const [activeTab, setActiveTab] = useState(initialTab);
    const [viewingPdf, setViewingPdf] = useState(null); // Gère l'affichage plein écran d'un document
    const [showArretesList, setShowArretesList] = useState(false); // Gère la liste multi-arrêtés
    const [demoLinkWarning, setDemoLinkWarning] = useState(null); // Gère la modale anti-spam du mode démo
    const scrollRef = useRef(null);
    
    useEffect(() => {
        setActiveTab(initialTab);
    }, [initialTab]);

    // Réinitialise le scroll à chaque changement d'onglet
    useEffect(() => {
        if (scrollRef.current) {
            scrollRef.current.scrollTo({ top: 0, behavior: 'smooth' });
        }
    }, [activeTab]);

    // =========================================================================
    // GESTION DES STATUTS DU PANNEAU (Bloqué pour le public, ignoré en Preview)
    // =========================================================================
    if (!isPreview) {
        if (!panneau || panneau.status === 'Supprimé') {
            return (
                <div className="min-h-screen flex flex-col items-center justify-center p-6 bg-slate-50 text-center">
                    <AlertTriangle size={48} className="text-slate-300 mb-4" />
                    <h2 className="text-xl font-black text-slate-700">Panneau introuvable</h2>
                    <p className="text-sm text-slate-500 mt-2 mb-8">Ce panneau n'existe pas ou a été supprimé par son propriétaire.</p>
                    <a href="https://eco-panneau.fr" className="opacity-50 hover:opacity-100 transition" title="Retour à l'accueil">
                        <SiteLogo theme="light" />
                    </a>
                </div>
            );
        }

        if (panneau.status === 'Brouillon') {
            return (
                <div className="min-h-screen flex flex-col items-center justify-center p-6 bg-slate-50 text-center">
                    <AlertTriangle size={48} className="text-slate-300 mb-4" />
                    <h2 className="text-xl font-black text-slate-700">En attente de publication</h2>
                    <p className="text-sm text-slate-500 mt-2 mb-8">Ce panneau n'a pas encore été publié.</p>
                    <a href="https://eco-panneau.fr" className="opacity-50 hover:opacity-100 transition" title="Retour à l'accueil">
                        <SiteLogo theme="light" />
                    </a>
                </div>
            );
        }

        if (panneau.status === 'Hors ligne' || panneau.status === 'Désactivé' || panneau.status === 'Suspendu') {
            return (
                <div className="min-h-screen flex flex-col items-center justify-center p-6 bg-slate-50 text-center">
                    <AlertTriangle size={48} className="text-slate-300 mb-4" />
                    <h2 className="text-xl font-black text-slate-700">Panneau inactif</h2>
                    <p className="text-sm text-slate-500 mt-2 mb-8">Ce panneau a été désactivé par son propriétaire.</p>
                    <a href="https://eco-panneau.fr" className="opacity-50 hover:opacity-100 transition" title="Retour à l'accueil">
                        <SiteLogo theme="light" />
                    </a>
                </div>
            );
        }
    } else if (!panneau) {
        // Sécurité si on tente une preview d'un panneau totalement vide
        return (
            <div className="h-full flex flex-col items-center justify-center bg-slate-50 text-slate-400">
                Chargement de l'aperçu...
            </div>
        );
    }

    const isPublicContact = panneau.id === 'CONTACT_PUBLIC';
    const isDemo = panneau.id === 'demo-panneau';
    const themeColor = panneau.themeColor || '#059669';
    const hasNoAds = panneau.hasNoAds;
    
    // Protection contre les fausses URL générées par l'éditeur (blob)
    const displayImageUrl = panneau.imageId 
        ? `?api=file/download&type=image&id=${panneau.imageId}` 
        : (panneau.imageUrl?.startsWith('blob:') ? null : panneau.imageUrl);
        
    const displayMoaLogoUrl = panneau.maitreOuvrageLogoId 
        ? `?api=file/download&type=image&id=${panneau.maitreOuvrageLogoId}` 
        : (panneau.maitreOuvrageLogoUrl?.startsWith('blob:') ? null : panneau.maitreOuvrageLogoUrl);
        
    const displayVue3dUrl = panneau.vue3dId 
        ? `?api=file/download&type=image&id=${panneau.vue3dId}` 
        : (panneau.vue3dUrl?.startsWith('blob:') ? null : panneau.vue3dUrl);

    // Fonction d'interception des liens sortants pour le mode démo
    const handleExternalLink = (e, url) => {
        if (isDemo) {
            e.preventDefault();
            setDemoLinkWarning(url);
        }
    };

    const handleChatSend = async (text) => {
        const threadEmail = interactions.find(m => m.author !== 'Admin' && m.author !== 'Client')?.author || localStorage.getItem('eco_riverain_email') || 'Visiteur anonyme';
        
        if (threadEmail !== 'Visiteur anonyme') {
            localStorage.setItem('eco_riverain_email', threadEmail);
        }

        const data = { 
            panneauId: panneau.id, 
            detail: text, 
            author: threadEmail, 
            isAlert: 0 
        };
        
        try {
            await fetch(window.ECO_CONFIG.apiBaseUrl + 'interactions', { 
                method: 'POST', 
                body: JSON.stringify(data) 
            });
            
            if (refreshData) {
                refreshData();
            }
        } catch (e) {
            if (showToast) {
                showToast("Erreur lors de l'envoi", "error");
            }
        }
    };

    const chatMessages = interactions.map(m => ({
        ...m,
        author: (m.author !== 'Admin' && m.author !== 'Client') ? 'Riverain' : m.author
    }));

    const unreadCount = interactions.filter(m => !m.resolved && (m.author === 'Admin' || m.author === 'Client')).length;

    const showPanelBanner = !isPublicContact && !isDemo && settings?.panel_banner_active === '1' && settings?.panel_banner_msg;

    const effectiveInteractions = (isPreview && !isDemo) ? [] : interactions;
    const isChatActive = activeTab === 'contact' && effectiveInteractions.length > 0;
    
    // Règle anti-scroll-imbriqué absolue
    const contentScrollClass = isChatActive ? 'min-h-0 overflow-hidden' : 'overflow-y-auto custom-scrollbar';

    return (
        <div className={`flex flex-col bg-slate-50 relative text-slate-800 font-sans selection:bg-emerald-200 ${isPreview ? 'h-full w-full overflow-hidden' : 'h-[100dvh] w-full overflow-hidden'}`}>
            
            {showPanelBanner && (
                <div className="bg-blue-600 text-white text-center py-2 px-3 font-bold text-[10px] sm:text-xs z-[60] relative shadow-md shrink-0">
                    <div 
                        dangerouslySetInnerHTML={{ 
                            __html: window.DOMPurify ? window.DOMPurify.sanitize(settings.panel_banner_msg) : settings.panel_banner_msg 
                        }} 
                        className="admin-html" 
                    />
                </div>
            )}

            {/* --- EN-TÊTE DYNAMIQUE (HERO RÉDUIT) --- */}
            <div className="relative shrink-0 bg-slate-900 overflow-hidden" style={{ height: displayImageUrl ? '160px' : '100px' }}>
                {displayImageUrl && (
                    <>
                        <img src={displayImageUrl} alt="Panneau" className="absolute inset-0 w-full h-full object-cover opacity-60 mix-blend-overlay" />
                        <div className="absolute inset-0 bg-gradient-to-t from-slate-900 via-slate-900/60 to-transparent"></div>
                    </>
                )}
                {!displayImageUrl && (
                    <div className="absolute inset-0 opacity-20" style={{ backgroundColor: themeColor }}></div>
                )}
                
                <div className="absolute bottom-0 inset-x-0 p-4">
                    <h1 className="text-xl sm:text-2xl font-black text-white leading-tight drop-shadow-md line-clamp-2">
                        {panneau.name}
                    </h1>
                </div>
            </div>

            {/* --- CONTENU PRINCIPAL --- */}
            <div ref={scrollRef} className={`flex-1 flex flex-col ${contentScrollClass} relative`} style={{ paddingBottom: !isPublicContact && !hasNoAds ? '86px' : (!isPublicContact ? '60px' : '0') }}>
                
                {/* ONGLET 1 : INFORMATIONS (HOME) */}
                {activeTab === 'home' && (
                    <div className="p-3 space-y-3 animate-in fade-in slide-in-from-bottom-2 duration-300">
                        
                        {displayVue3dUrl && (
                            <div className="bg-white p-2 rounded-xl shadow-sm border border-slate-100">
                                <p className="text-[9px] font-bold text-slate-400 uppercase tracking-wider mb-1.5 px-2 pt-1">Vue 3D du projet</p>
                                <img src={displayVue3dUrl} alt="Vue 3D du projet" className="w-full h-auto rounded-lg object-cover border border-slate-100" />
                            </div>
                        )}

                        {(panneau.maitreOuvrage || displayMoaLogoUrl) && (
                            <div className="bg-white p-3 rounded-xl shadow-sm border border-slate-100 flex items-center gap-3">
                                {displayMoaLogoUrl ? (
                                    <img src={displayMoaLogoUrl} alt="MOA" className="h-10 w-auto object-contain shrink-0" />
                                ) : (
                                    <div className="w-8 h-8 rounded-full flex items-center justify-center bg-slate-50 text-slate-400 shrink-0">
                                        <Building size={16} />
                                    </div>
                                )}
                                <div className="min-w-0 flex-1">
                                    <p className="text-[9px] font-bold text-slate-400 uppercase tracking-wider mb-0.5">Maître d'ouvrage</p>
                                    {panneau.maitreOuvrage && <p className="text-xs font-black text-slate-800 truncate">{panneau.maitreOuvrage}</p>}
                                </div>
                            </div>
                        )}

                        {panneau.description && (
                            <div className="bg-white p-3 rounded-xl shadow-sm border border-slate-100">
                                <p className="text-[9px] font-bold text-slate-400 uppercase tracking-wider mb-1.5">Description des travaux</p>
                                <p className="text-xs text-slate-600 leading-relaxed whitespace-pre-wrap">{panneau.description}</p>
                            </div>
                        )}

                        {panneau.promoterLink && (
                            <a 
                                href={panneau.promoterLink.startsWith('http') ? panneau.promoterLink : `https://${panneau.promoterLink}`} 
                                target="_blank" 
                                rel="noopener noreferrer" 
                                onClick={(e) => handleExternalLink(e, panneau.promoterLink)} 
                                className="bg-white p-3 rounded-xl shadow-sm border border-slate-100 flex items-center justify-between hover:bg-slate-50 transition group w-full"
                            >
                                <div className="flex items-center gap-3 w-full">
                                    <div className="w-8 h-8 rounded-full flex items-center justify-center shrink-0 bg-slate-50" style={{ color: themeColor }}>
                                        <ExternalLink size={16} />
                                    </div>
                                    <div className="flex-1">
                                        <p className="text-sm font-bold text-slate-800">Acheter ou s'informer</p>
                                    </div>
                                    <window.ArrowRight size={16} className="text-slate-300 group-hover:text-slate-600 group-hover:translate-x-1 transition-all shrink-0"/>
                                </div>
                            </a>
                        )}

                        {(panneau.pdfId || panneau.permitNumber || panneau.noiseSchedule) && (
                            <div className="bg-white p-3 rounded-xl shadow-sm border-2" style={{ borderColor: `${themeColor}20` }}>
                                <div className="flex items-start gap-2">
                                    <div className="w-8 h-8 rounded-full flex items-center justify-center shrink-0" style={{ backgroundColor: `${themeColor}15`, color: themeColor }}>
                                        <Shield size={16} />
                                    </div>
                                    <div className="flex-1">
                                        <p className="text-[9px] font-bold text-slate-400 uppercase tracking-wider mb-0.5">Autorisation d'urbanisme</p>
                                        <p className="text-xs font-black text-slate-800 uppercase">{panneau.permitNumber || 'Arrêté officiel'}</p>
                                    </div>
                                </div>
                                
                                {panneau.pdfId && (
                                    <button 
                                        onClick={() => { 
                                            // Si arrêtés modificatifs présents, ouvrir la liste, sinon ouvrir le PDF direct
                                            if (panneau.modificatifs?.length > 0) setShowArretesList(true); 
                                            else setViewingPdf(panneau.pdfId); 
                                        }} 
                                        className="mt-3 w-full py-2.5 rounded-lg font-bold text-white text-xs shadow-md flex items-center justify-center gap-2 transition hover:opacity-90" 
                                        style={{ backgroundColor: themeColor }}
                                    >
                                        <FileDigit size={14} /> Consulter {panneau.modificatifs?.length > 0 ? "les arrêtés" : "l'arrêté"}
                                        {panneau.modificatifs?.length > 0 && <span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] ml-1 font-black">{panneau.modificatifs.length + 1}</span>}
                                    </button>
                                )}

                                {panneau.noiseSchedule && (
                                    <div className="mt-3 pt-3">
                                        <p className="text-[10px] text-slate-500 font-medium flex items-start gap-1.5">
                                            <Clock size={12} className="shrink-0 mt-0.5" style={{ color: themeColor }} /> 
                                            <span>Horaires de nuisances autorisées :<br/> <strong className="text-slate-800 ml-1">{panneau.noiseSchedule}</strong></span>
                                        </p>
                                    </div>
                                )}
                            </div>
                        )}

                        {panneau.location && (
                            <div className="bg-white p-3 rounded-xl shadow-sm border border-slate-100 flex items-start gap-2">
                                <div className="w-8 h-8 rounded-full flex items-center justify-center shrink-0 bg-slate-50" style={{ color: themeColor }}>
                                    <MapPin size={16} />
                                </div>
                                <div>
                                    <p className="text-[9px] font-bold text-slate-400 uppercase tracking-wider mb-0.5">Localisation</p>
                                    <p className="text-xs font-bold text-slate-700 leading-snug">{panneau.location}</p>
                                </div>
                            </div>
                        )}
                    </div>
                )}

                {/* ONGLET 2 : L'ÉQUIPE (TEAM) - VERSION COMPLÈTE RESTAURÉE */}
                {activeTab === 'team' && (
                    <div className="p-3 space-y-4 animate-in fade-in slide-in-from-bottom-2 duration-300">
                        {(!panneau.intervenants?.length && !panneau.lots?.length) ? (
                            <div className="text-center p-8 text-slate-400 font-medium text-sm">
                                L'équipe du panneau n'a pas encore été renseignée.
                            </div>
                        ) : (
                            <>
                                {/* Intervenants principaux */}
                                {panneau.intervenants?.length > 0 && (
                                    <div className="space-y-2">
                                        <h3 className="text-[9px] font-black text-slate-400 uppercase tracking-widest pl-1">Intervenants principaux</h3>
                                        {panneau.intervenants.map((inter, idx) => (
                                            <div key={idx} className="bg-white p-3 rounded-xl shadow-sm border border-slate-100 flex flex-col sm:flex-row items-start gap-3">
                                                {inter.logoId ? (
                                                    <img src={`?api=file/download&type=image&id=${inter.logoId}`} alt="logo" className="w-10 h-10 object-contain rounded-lg shrink-0 border border-slate-100 bg-slate-50" />
                                                ) : (
                                                    <div className="w-10 h-10 rounded-lg bg-slate-50 flex items-center justify-center shrink-0 text-slate-300 hidden sm:flex">
                                                        <Users size={16}/>
                                                    </div>
                                                )}
                                                <div className="min-w-0 flex-1 w-full">
                                                    <p className="text-[9px] font-bold uppercase mb-0.5 truncate" style={{color: themeColor}}>{inter.role || 'Rôle non défini'}</p>
                                                    <p className="font-black text-xs text-slate-800 break-words leading-tight">{inter.name}</p>
                                                    {inter.description && <p className="text-[11px] text-slate-600 mt-1 mb-1.5 leading-relaxed">{inter.description}</p>}
                                                    {inter.address && (
                                                        <p className="text-[9px] text-slate-500 mt-1 flex items-start gap-1">
                                                            <MapPin size={10} className="mt-0.5 shrink-0"/> {inter.address}
                                                        </p>
                                                    )}
                                                    {(inter.phone || inter.email || inter.website) && (
                                                        <div className="flex flex-wrap gap-1.5 mt-2 pt-2 border-t border-slate-50">
                                                            {inter.phone && (
                                                                <a href={`tel:${inter.phone}`} onClick={(e) => handleExternalLink(e, `tel:${inter.phone}`)} className="text-[9px] font-bold text-slate-500 bg-slate-50 px-2 py-1 rounded border border-slate-100 hover:text-slate-800 transition flex items-center gap-1">
                                                                    <Phone size={10}/> {inter.phone}
                                                                </a>
                                                            )}
                                                            {inter.email && (
                                                                <a href={`mailto:${inter.email}`} onClick={(e) => handleExternalLink(e, `mailto:${inter.email}`)} className="text-[9px] font-bold text-slate-500 bg-slate-50 px-2 py-1 rounded border border-slate-100 hover:text-slate-800 transition flex items-center gap-1">
                                                                    <Mail size={10}/> Email
                                                                </a>
                                                            )}
                                                            {inter.website && (
                                                                <a href={inter.website.startsWith('http') ? inter.website : `https://${inter.website}`} target="_blank" rel="noopener noreferrer" onClick={(e) => handleExternalLink(e, inter.website)} className="text-[9px] font-bold text-slate-500 bg-slate-50 px-2 py-1 rounded border border-slate-100 hover:text-slate-800 transition flex items-center gap-1">
                                                                    <ExternalLink size={10}/> Web
                                                                </a>
                                                            )}
                                                        </div>
                                                    )}
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                )}

                                {/* Sous-traitants par lots */}
                                {panneau.lots?.length > 0 && (
                                    <div className="space-y-3 pt-3 border-t border-slate-200/60">
                                        <h3 className="text-[9px] font-black text-slate-400 uppercase tracking-widest pl-1">Entreprises sous-traitantes</h3>
                                        {panneau.lots.map((lot, idx) => (
                                            <div key={idx} className="bg-white rounded-xl shadow-sm border border-slate-100 overflow-hidden">
                                                <div className="bg-slate-50 px-3 py-2 border-b border-slate-100">
                                                    <p className="font-black text-[10px] text-slate-700 uppercase">{lot.name}</p>
                                                </div>
                                                <div className="divide-y divide-slate-50">
                                                    {lot.entreprises?.map((ent, eIdx) => (
                                                        <div key={eIdx} className="p-3 flex flex-col sm:flex-row gap-3 items-start">
                                                            {ent.logoId ? (
                                                                <img src={`?api=file/download&type=image&id=${ent.logoId}`} alt="logo" className="w-8 h-8 object-contain rounded-md shrink-0 border border-slate-100 bg-white" />
                                                            ) : (
                                                                <div className="w-8 h-8 rounded-md bg-slate-50 flex items-center justify-center shrink-0 text-slate-300 hidden sm:flex">
                                                                    <Building size={14}/>
                                                                </div>
                                                            )}
                                                            <div className="min-w-0 flex-1 w-full">
                                                                <p className="font-bold text-xs text-slate-800 break-words leading-tight">{ent.name}</p>
                                                                {ent.role && <p className="text-[9px] font-bold uppercase mt-0.5 truncate" style={{color: themeColor}}>{ent.role}</p>}
                                                                {ent.description && <p className="text-[10px] text-slate-600 mt-1 leading-relaxed">{ent.description}</p>}
                                                                {ent.address && (
                                                                    <p className="text-[9px] text-slate-500 mt-1 flex items-start gap-1">
                                                                        <MapPin size={10} className="mt-0.5 shrink-0"/> {ent.address}
                                                                    </p>
                                                                )}
                                                                {(ent.phone || ent.email || ent.website) && (
                                                                    <div className="flex flex-wrap gap-1.5 mt-2 pt-2 border-t border-slate-50">
                                                                        {ent.phone && (
                                                                            <a href={`tel:${ent.phone}`} onClick={(e) => handleExternalLink(e, `tel:${ent.phone}`)} className="text-[9px] font-bold text-slate-500 bg-white px-2 py-1 rounded border border-slate-100 hover:text-slate-800 transition flex items-center gap-1 shadow-sm">
                                                                                <Phone size={10}/> {ent.phone}
                                                                            </a>
                                                                        )}
                                                                        {ent.email && (
                                                                            <a href={`mailto:${ent.email}`} onClick={(e) => handleExternalLink(e, `mailto:${ent.email}`)} className="text-[9px] font-bold text-slate-500 bg-white px-2 py-1 rounded border border-slate-100 hover:text-slate-800 transition flex items-center gap-1 shadow-sm">
                                                                                <Mail size={10}/> Email
                                                                            </a>
                                                                        )}
                                                                        {ent.website && (
                                                                            <a href={ent.website.startsWith('http') ? ent.website : `https://${ent.website}`} target="_blank" rel="noopener noreferrer" onClick={(e) => handleExternalLink(e, ent.website)} className="text-[9px] font-bold text-slate-500 bg-white px-2 py-1 rounded border border-slate-100 hover:text-slate-800 transition flex items-center gap-1 shadow-sm">
                                                                                <ExternalLink size={10}/> Web
                                                                            </a>
                                                                        )}
                                                                    </div>
                                                                )}
                                                            </div>
                                                        </div>
                                                    ))}
                                                    {(!lot.entreprises || lot.entreprises.length === 0) && (
                                                        <p className="p-3 text-[10px] text-slate-400 italic">En cours d'attribution</p>
                                                    )}
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                )}
                            </>
                        )}
                    </div>
                )}

                {/* ONGLET 3 : CONTACT ET MESSAGERIE */}
                {activeTab === 'contact' && (
                    <div className={`p-3 space-y-3 flex flex-col animate-in fade-in slide-in-from-bottom-2 duration-300 ${isChatActive ? 'flex-1 min-h-0' : ''}`}>
                        {panneau.emergencyPhone && (
                            <div className="bg-slate-50 p-3 rounded-xl border border-slate-200 flex items-center justify-between shrink-0">
                                <div>
                                    <p className="text-[9px] font-black text-slate-500 uppercase tracking-widest mb-0.5">Numéro d'urgence</p>
                                    <p className="text-base font-black text-slate-800">{panneau.emergencyPhone}</p>
                                </div>
                                <a href={`tel:${panneau.emergencyPhone.replace(/\s+/g, '')}`} onClick={(e) => handleExternalLink(e, `tel:${panneau.emergencyPhone}`)} className="w-10 h-10 bg-slate-800 text-white rounded-full flex items-center justify-center shadow-md hover:bg-slate-900 transition">
                                    <Phone size={16} />
                                </a>
                            </div>
                        )}

                        <div className={`bg-white rounded-xl shadow-sm border border-slate-100 overflow-hidden flex flex-col relative ${isChatActive ? 'flex-1 min-h-0' : ''}`}>
                            <div className="p-3 border-b border-slate-100 bg-slate-50 shrink-0">
                                <h3 className="font-black text-slate-800 flex items-center gap-2 text-sm">
                                    <MessageSquare size={16} style={{color: themeColor}}/> Échanger avec le responsable
                                </h3>
                            </div>
                            
                            <div className={`relative bg-slate-50/50 ${isChatActive ? 'flex-1 min-h-0' : 'p-3'}`}>
                                {effectiveInteractions.length === 0 ? (
                                    <window.PublicContactForm 
                                        panneauId={panneau.id} 
                                        showToast={showToast} 
                                        isPreview={isPreview}
                                        settings={settings}
                                        onSuccess={() => { if (refreshData) refreshData(); }} 
                                    />
                                ) : (
                                    <div className="absolute inset-0">
                                        <window.ChatBox 
                                            messages={chatMessages} 
                                            currentUserRole="public" 
                                            panneauId={panneau.id} 
                                            refreshData={refreshData} 
                                            onSend={handleChatSend} 
                                            clientName={panneau.maitreOuvrage || 'Responsable'}
                                            settings={settings}
                                        />
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                )}
            </div>

            {/* --- NAVIGATION INFERIEURE --- */}
            {(!isPublicContact) && (
                <div className={`${isPreview ? 'absolute' : 'fixed'} ${!hasNoAds ? 'bottom-[40px]' : 'bottom-0'} inset-x-0 h-[60px] bg-white border-t border-slate-200 flex items-center justify-around px-2 z-[70] transition-all`}>
                    <button onClick={() => setActiveTab('home')} className={`flex flex-col items-center justify-center w-full h-full space-y-1 transition ${activeTab === 'home' ? 'text-slate-900' : 'text-slate-400 hover:text-slate-600'}`}>
                        <Info size={18} style={{ color: activeTab === 'home' ? themeColor : 'currentColor' }} />
                        <span className="text-[9px] font-bold">Le panneau</span>
                    </button>
                    <button onClick={() => setActiveTab('team')} className={`flex flex-col items-center justify-center w-full h-full space-y-1 transition ${activeTab === 'team' ? 'text-slate-900' : 'text-slate-400 hover:text-slate-600'}`}>
                        <Users size={18} style={{ color: activeTab === 'team' ? themeColor : 'currentColor' }} />
                        <span className="text-[9px] font-bold">L'équipe</span>
                    </button>
                    <button onClick={() => setActiveTab('contact')} className={`flex flex-col items-center justify-center w-full h-full space-y-1 relative ${activeTab === 'contact' ? 'text-slate-900' : 'text-slate-400 hover:text-slate-600'}`}>
                        <div className="relative">
                            <MessageSquare size={18} style={{ color: activeTab === 'contact' ? themeColor : 'currentColor' }} />
                            {unreadCount > 0 && (
                                <span className="absolute -top-1 -right-1 w-2.5 h-2.5 bg-red-500 rounded-full border-2 border-white"></span>
                            )}
                        </div>
                        <span className="text-[9px] font-bold">Contact</span>
                    </button>
                </div>
            )}

            {!hasNoAds && (
                <a href="https://eco-panneau.fr" target="_blank" rel="noopener noreferrer" className={`${isPreview ? 'absolute' : 'fixed'} bottom-0 inset-x-0 h-[40px] bg-slate-900 text-white z-[100] flex items-center justify-center opacity-95 hover:opacity-100 transition-colors cursor-pointer`}>
                    <SiteLogo className="text-xs" qrSize={16} theme="dark" />
                </a>
            )}

            {/* VISUALISATION PDF : Suppression de PDF.js au profit de l'image serveur WEBP ! */}
            {viewingPdf && (
                <div className="absolute inset-0 z-[999999] bg-slate-900/95 backdrop-blur-sm flex flex-col animate-in fade-in duration-200" onClick={() => setViewingPdf(null)}>
                    <div className="flex justify-between items-center p-4 bg-slate-900/50 text-white shrink-0 border-b border-white/10" onClick={e => e.stopPropagation()}>
                        <button 
                            onClick={() => { 
                                setViewingPdf(null); 
                                if (panneau.modificatifs?.length > 0) setShowArretesList(true); 
                            }} 
                            className="flex items-center gap-2 px-4 py-2 hover:bg-white/10 rounded-xl transition text-sm font-bold"
                        >
                            <ArrowLeft size={18}/> Retour
                        </button>
                        <a href={`?api=file/download&type=pdf&id=${viewingPdf}`} download className="flex items-center gap-2 px-4 py-2 bg-emerald-600 hover:bg-emerald-700 rounded-xl transition text-sm font-bold shadow-lg">
                            <Download size={18}/> <span className="hidden sm:inline">Télécharger</span>
                        </a>
                    </div>
                    <div className="flex-1 flex flex-col items-center justify-start p-2 sm:p-4 min-h-0 relative w-full overflow-y-auto custom-scrollbar">
                        <img src={`?api=file/preview&type=pdf&id=${viewingPdf}`} alt="Aperçu de l'arrêté" className="w-full max-w-3xl rounded-xl shadow-2xl" onClick={e => e.stopPropagation()} />
                    </div>
                </div>
            )}

            {/* MODALE LISTE DES ARRÊTÉS (MULTI-PERMIS) */}
            {showArretesList && (
                <div className="absolute inset-0 z-[999998] bg-slate-900/60 backdrop-blur-sm flex items-center justify-center p-4 animate-in fade-in duration-200" onClick={() => setShowArretesList(false)}>
                    <div className="bg-white rounded-[2rem] w-full max-w-[320px] shadow-2xl flex flex-col overflow-hidden animate-in slide-in-from-bottom-4" onClick={e => e.stopPropagation()}>
                        <div className="p-5 border-b border-slate-100 bg-slate-50 flex justify-between items-center">
                            <h3 className="font-black text-slate-800 text-sm uppercase tracking-wider">Documents d'urbanisme</h3>
                            <button onClick={() => setShowArretesList(false)} className="text-slate-400 p-1 hover:bg-slate-200 rounded-lg transition"><X size={18}/></button>
                        </div>
                        <div className="p-4 space-y-2 overflow-y-auto max-h-[60vh] custom-scrollbar">
                            {/* Arrêté Initial */}
                            <button onClick={() => { setViewingPdf(panneau.pdfId); setShowArretesList(false); }} className="w-full p-3 bg-slate-50 hover:bg-emerald-50 border border-slate-200 rounded-2xl flex items-center justify-between group transition text-left">
                                <div className="flex items-center gap-3 min-w-0">
                                    <div className="w-10 h-10 rounded-xl bg-emerald-100 text-emerald-600 flex items-center justify-center shrink-0"><FileDigit size={20}/></div>
                                    <div className="min-w-0"><p className="font-black text-slate-800 text-xs truncate">Arrêté initial</p><p className="text-[9px] text-slate-500 font-bold uppercase">Document principal</p></div>
                                </div>
                                <ArrowRight size={16} className="text-slate-300 group-hover:text-emerald-500 transition-transform group-hover:translate-x-1" />
                            </button>
                            {/* Arrêtés Modificatifs */}
                            {panneau.modificatifs?.map((mod, idx) => (
                                <button key={idx} onClick={() => { setViewingPdf(mod.id); setShowArretesList(false); }} className="w-full p-3 bg-slate-50 hover:bg-blue-50 border border-slate-200 rounded-2xl flex items-center justify-between group transition text-left">
                                    <div className="flex items-center gap-3 min-w-0">
                                        <div className="w-10 h-10 rounded-xl bg-blue-100 text-blue-600 flex items-center justify-center shrink-0"><FileDigit size={20}/></div>
                                        <div className="min-w-0"><p className="font-black text-slate-800 text-xs truncate">{mod.label}</p><p className="text-[9px] text-slate-500 font-bold uppercase">Ajouté le {new Date(mod.date).toLocaleDateString('fr-FR')}</p></div>
                                    </div>
                                    <ArrowRight size={16} className="text-slate-300 group-hover:text-blue-500 transition-transform group-hover:translate-x-1" />
                                </button>
                            ))}
                        </div>
                        <div className="p-4 bg-slate-50 border-t border-slate-100"><button onClick={() => setShowArretesList(false)} className="w-full bg-slate-800 text-white py-3 rounded-xl font-black uppercase text-[10px] tracking-widest">Fermer</button></div>
                    </div>
                </div>
            )}

            {/* MODALE D'AVERTISSEMENT ANTI-SPAM (MODE DÉMO) */}
            {demoLinkWarning && (
                <window.Modal title="Mode Démo" onClose={() => setDemoLinkWarning(null)} zIndex="z-[999999]">
                    <div className="space-y-4 text-center p-4">
                        <Info size={24} className="text-blue-600 mx-auto" />
                        <p className="text-xs text-slate-500 font-medium">Liens de contact désactivés sur cet exemple.</p>
                        <button onClick={() => setDemoLinkWarning(null)} className="w-full bg-slate-900 text-white py-3 rounded-xl font-bold hover:bg-slate-800 transition shadow-md text-sm">OK</button>
                    </div>
                </window.Modal>
            )}
        </div>
    );
};

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