/**
 * =========================================================================
 * 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 
} = 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 = ({ chantier, showToast, interactions = [], refreshData, isPreview = false, initialTab = 'home' }) => {
    const [activeTab, setActiveTab] = useState(initialTab);
    
    // Synchronisation si la prop initialTab change à la volée (ex: clic sur lien magique)
    useEffect(() => {
        setActiveTab(initialTab);
    }, [initialTab]);

    // Défilement automatique vers le haut au changement d'onglet
    const contentRef = useRef(null);
    useEffect(() => {
        if (contentRef.current) contentRef.current.scrollTo({ top: 0, behavior: 'smooth' });
    }, [activeTab]);

    if (!chantier) {
        return (
            <div className="min-h-full 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">Ce panneau n'est plus actif ou l'URL est invalide.</p>
            </div>
        );
    }

    const isPublicContact = chantier.id === 'CONTACT_PUBLIC';
    const isDemo = chantier.id === 'demo-chantier';
    const themeColor = chantier.themeColor || '#059669';
    const displayImageUrl = chantier.imageUrl || (chantier.imageId ? `?api=file/download&type=image&id=${chantier.imageId}` : null);
    const displayMoaLogoUrl = chantier.maitreOuvrageLogoUrl || (chantier.maitreOuvrageLogoId ? `?api=file/download&type=image&id=${chantier.maitreOuvrageLogoId}` : null);

    // Fonction d'envoi de réponse au sein du fil de discussion existant
    const handleChatSend = async (text) => {
        // On récupère l'email du riverain depuis l'historique ou le cache
        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 = { chantierId: chantier.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");
        }
    };

    // On formate les messages pour que le ChatBox (qui se base sur le rôle "public") identifie bien le riverain
    const chatMessages = interactions.map(m => ({
        ...m,
        author: (m.author !== 'Admin' && m.author !== 'Client') ? 'Riverain' : m.author
    }));

    // Compteur de messages non lus destinés au riverain (venant du client ou de l'admin)
    const unreadCount = interactions.filter(m => !m.resolved && (m.author === 'Admin' || m.author === 'Client')).length;

    return (
        <div className="flex flex-col h-full bg-slate-50 relative text-slate-800 font-sans selection:bg-emerald-200 overflow-hidden">
            
            {/* --- EN-TÊTE DYNAMIQUE (HERO) --- */}
            <div className="relative shrink-0 bg-slate-900 overflow-hidden" style={{ height: displayImageUrl ? '220px' : '140px' }}>
                {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-5">
                    {(!isPublicContact && !isDemo) && (
                        <span className="inline-block px-3 py-1 bg-white/20 backdrop-blur-md text-white text-[10px] font-black uppercase tracking-widest rounded-lg mb-3">
                            Panneau en cours
                        </span>
                    )}
                    <h1 className="text-2xl font-black text-white leading-tight drop-shadow-md line-clamp-2">
                        {chantier.name}
                    </h1>
                </div>
            </div>

            {/* --- CONTENU PRINCIPAL --- */}
            <div ref={contentRef} className="flex-1 overflow-y-auto custom-scrollbar">
                
                {/* ONGLET 1 : INFORMATIONS (HOME) */}
                {activeTab === 'home' && (
                    <div className="p-4 space-y-4 animate-in fade-in slide-in-from-bottom-2 duration-300">
                        
                        {/* Localisation */}
                        <div className="bg-white p-4 rounded-2xl shadow-sm border border-slate-100 flex items-start gap-3">
                            <div className="w-10 h-10 rounded-full flex items-center justify-center shrink-0 bg-slate-50" style={{ color: themeColor }}>
                                <MapPin size={20} />
                            </div>
                            <div>
                                <p className="text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-0.5">Localisation</p>
                                <p className="text-sm font-bold text-slate-700 leading-snug">{chantier.location}</p>
                            </div>
                        </div>

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

                        {/* Arrêté Légal PDF */}
                        {chantier.pdfId && (
                            <div className="bg-white p-4 rounded-2xl shadow-sm border-2" style={{ borderColor: `${themeColor}20` }}>
                                <div className="flex items-start gap-3">
                                    <div className="w-10 h-10 rounded-full flex items-center justify-center shrink-0" style={{ backgroundColor: `${themeColor}15`, color: themeColor }}>
                                        <Shield size={20} />
                                    </div>
                                    <div className="flex-1">
                                        <p className="text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-0.5">Autorisation d'urbanisme</p>
                                        <p className="text-sm font-black text-slate-800 uppercase">{chantier.permitNumber || 'Arrêté officiel'}</p>
                                    </div>
                                </div>
                                <a href={`?api=file/download&type=pdf&id=${chantier.pdfId}`} target="_blank" rel="noopener noreferrer" className="mt-4 w-full py-3 rounded-xl font-bold text-white text-sm shadow-md flex items-center justify-center gap-2 transition hover:opacity-90" style={{ backgroundColor: themeColor }}>
                                    <FileDigit size={16} /> Consulter l'arrêté (PDF)
                                </a>
                            </div>
                        )}

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

                        {(chantier.noiseSchedule || chantier.promoterLink) && (
                            <div className="grid grid-cols-2 gap-3">
                                {chantier.noiseSchedule && (
                                    <div className="bg-white p-4 rounded-2xl shadow-sm border border-slate-100 flex flex-col justify-center">
                                        <Clock size={16} className="text-slate-400 mb-2" />
                                        <p className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Horaires autorisés</p>
                                        <p className="text-sm font-bold text-slate-800 mt-0.5">{chantier.noiseSchedule}</p>
                                    </div>
                                )}
                                {chantier.promoterLink && (
                                    <a href={chantier.promoterLink.startsWith('http') ? chantier.promoterLink : `https://${chantier.promoterLink}`} target="_blank" rel="noopener noreferrer" className="bg-white p-4 rounded-2xl shadow-sm border border-slate-100 flex flex-col justify-center hover:bg-slate-50 transition group">
                                        <ExternalLink size={16} className="text-slate-400 mb-2 group-hover:text-slate-800 transition" />
                                        <p className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Site web</p>
                                        <p className="text-sm font-bold text-slate-800 mt-0.5 truncate">Visiter le site</p>
                                    </a>
                                )}
                            </div>
                        )}
                    </div>
                )}

                {/* ONGLET 2 : L'ÉQUIPE (TEAM) */}
                {activeTab === 'team' && (
                    <div className="p-4 space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300">
                        {(!chantier.intervenants?.length && !chantier.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 */}
                                {chantier.intervenants?.length > 0 && (
                                    <div className="space-y-3">
                                        <h3 className="text-[10px] font-black text-slate-400 uppercase tracking-widest pl-1">Intervenants principaux</h3>
                                        {chantier.intervenants.map((inter, idx) => (
                                            <div key={idx} className="bg-white p-4 rounded-2xl shadow-sm border border-slate-100 flex gap-4">
                                                {inter.logoId ? (
                                                    <img src={`?api=file/download&type=image&id=${inter.logoId}`} alt="logo" className="w-12 h-12 object-contain rounded-xl shrink-0" />
                                                ) : (
                                                    <div className="w-12 h-12 rounded-xl bg-slate-50 flex items-center justify-center shrink-0 text-slate-300"><Users size={20}/></div>
                                                )}
                                                <div className="min-w-0">
                                                    <p className="font-black text-sm text-slate-800 truncate">{inter.name}</p>
                                                    <p className="text-xs text-slate-500 truncate">{inter.role}</p>
                                                    {(inter.phone || inter.email) && (
                                                        <div className="flex gap-3 mt-2">
                                                            {inter.phone && <a href={`tel:${inter.phone}`} className="text-xs font-bold flex items-center gap-1 hover:opacity-80 transition" style={{color: themeColor}}><Phone size={12}/> Appeler</a>}
                                                            {inter.email && <a href={`mailto:${inter.email}`} className="text-xs font-bold flex items-center gap-1 hover:opacity-80 transition" style={{color: themeColor}}><MessageSquare size={12}/> Email</a>}
                                                        </div>
                                                    )}
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                )}

                                {/* Sous-traitants par Lots */}
                                {chantier.lots?.length > 0 && (
                                    <div className="space-y-4">
                                        <h3 className="text-[10px] font-black text-slate-400 uppercase tracking-widest pl-1">Entreprises sous-traitantes</h3>
                                        {chantier.lots.map((lot, idx) => (
                                            <div key={idx} className="bg-white rounded-2xl shadow-sm border border-slate-100 overflow-hidden">
                                                <div className="bg-slate-50 px-4 py-3 border-b border-slate-100">
                                                    <p className="font-black text-xs 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-4 flex gap-3">
                                                            {ent.logoId && <img src={`?api=file/download&type=image&id=${ent.logoId}`} alt="logo" className="w-8 h-8 object-contain rounded-lg shrink-0" />}
                                                            <div className="min-w-0">
                                                                <p className="font-bold text-sm text-slate-800 truncate">{ent.name}</p>
                                                                {ent.role && <p className="text-[10px] text-slate-500 uppercase tracking-wide truncate">{ent.role}</p>}
                                                            </div>
                                                        </div>
                                                    ))}
                                                    {(!lot.entreprises || lot.entreprises.length === 0) && (
                                                        <p className="p-4 text-xs text-slate-400 italic">En cours d'attribution</p>
                                                    )}
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                )}
                            </>
                        )}
                    </div>
                )}

                {/* ONGLET 3 : CONTACT & MESSAGERIE */}
                {activeTab === 'contact' && (
                    <div className="p-3 sm:p-4 space-y-3 animate-in fade-in slide-in-from-bottom-2 duration-300 flex flex-col min-h-full">
                        
                        {chantier.emergencyPhone && (
                            <div className="bg-red-50 p-4 rounded-2xl border border-red-100 flex items-center justify-between shrink-0">
                                <div>
                                    <p className="text-[10px] font-black text-red-400 uppercase tracking-widest mb-0.5">Numéro d'urgence</p>
                                    <p className="text-lg font-black text-red-600">{chantier.emergencyPhone}</p>
                                </div>
                                <a href={`tel:${chantier.emergencyPhone}`} className="w-12 h-12 bg-red-600 text-white rounded-full flex items-center justify-center shadow-lg hover:bg-red-700 transition">
                                    <Phone size={20} />
                                </a>
                            </div>
                        )}

                        <div className="bg-white rounded-2xl shadow-sm border border-slate-100 overflow-hidden flex-1 flex flex-col">
                            <div className="p-3 sm:p-4 border-b border-slate-100 bg-slate-50 shrink-0">
                                <h3 className="font-black text-slate-800 flex items-center gap-2">
                                    <MessageSquare size={16} style={{color: themeColor}}/> Échanger avec le responsable
                                </h3>
                                <p className="text-xs text-slate-500 mt-1">
                                    {interactions.length > 0 ? "Historique de vos échanges confidentiels :" : "Posez une question ou signalez une nuisance. Le responsable vous répondra en toute confidentialité."}
                                </p>
                            </div>
                            
                            <div className="flex-1 relative bg-slate-50/50">
                                {interactions.length === 0 ? (
                                    <div className="p-4">
                                        <PublicContactForm 
                                            chantierId={chantier.id} 
                                            showToast={showToast} 
                                            isPreview={isPreview}
                                            onSuccess={() => {
                                                const emailInput = document.querySelector('input[name="email"]');
                                                if(emailInput) localStorage.setItem('eco_riverain_email', emailInput.value);
                                                if(refreshData) refreshData();
                                            }} 
                                        />
                                    </div>
                                ) : (
                                    <div className="absolute inset-0">
                                        <ChatBox 
                                            messages={chatMessages} 
                                            currentUserRole="public" 
                                            chantierId={chantier.id} 
                                            refreshData={refreshData} 
                                            onSend={handleChatSend} 
                                        />
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                )}
            </div>

            {/* --- NAVIGATION INFERIEURE (FIXED BOTTOM) --- */}
            <div className="shrink-0 h-16 bg-white border-t border-slate-200 flex items-center justify-around px-2 pb-safe shadow-[0_-10px_20px_-10px_rgba(0,0,0,0.05)] z-50">
                <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={20} style={{ color: activeTab === 'home' ? themeColor : 'currentColor' }} />
                    <span className="text-[10px] 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={20} style={{ color: activeTab === 'team' ? themeColor : 'currentColor' }} />
                    <span className="text-[10px] 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 transition relative ${activeTab === 'contact' ? 'text-slate-900' : 'text-slate-400 hover:text-slate-600'}`}>
                    <div className="relative">
                        <MessageSquare size={20} 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-[10px] font-bold">Contact</span>
                </button>
            </div>
        </div>
    );
};

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