// ECO-PANNEAU.FR - _react/riverains/_riverains.jsx

const { useState, useEffect, useRef } = React;

window.pano_RiverainView = ({ panneau, showToast, interactions = [], settings = {}, refreshData, isPreview = false, initialTab = 'home' }) => {
    const [activeTab, setActiveTab] = useState(initialTab);
    
    const [mountTime] = useState(Math.floor(Date.now() / 1000));
    const scrollRef = useRef(null);

    // 1. - Gestion isolée des modales Zéro-Dette (SPA)
    const urlModal = window.pano_useUrlModal ? window.pano_useUrlModal() : {};
    
    const [localModal, setLocalModal] = useState({ modal: null, targetId: null });
    const [localDialog, setLocalDialog] = useState({ dialog: null, dialogId: null });

    const activeModal = isPreview ? localModal.modal : urlModal.activeModal;
    const targetId = isPreview ? localModal.targetId : urlModal.targetId;
    const activeDialog = isPreview ? localDialog.dialog : urlModal.activeDialog;
    const dialogId = isPreview ? localDialog.dialogId : urlModal.dialogId;

    const openModal = (modal, target = null) => {
        if (isPreview) { setLocalModal({ modal, targetId: target }); } 
        else if (urlModal.openModal) { urlModal.openModal(modal, target, false); }
    };

    const openDialog = (dialog, target = null) => {
        if (isPreview) { setLocalDialog({ dialog, dialogId: target }); } 
        else if (urlModal.openDialog) { urlModal.openDialog(dialog, target, false); }
    };

    const closeCurrentLayer = () => {
        if (isPreview) {
            if (localDialog.dialog) setLocalDialog({ dialog: null, dialogId: null });
            else if (localModal.modal) setLocalModal({ modal: null, targetId: null });
        } else if (urlModal.closeCurrentLayer) {
            urlModal.closeCurrentLayer();
        }
    };

    // 2. - Récupération des icônes et composants
    const {
        AlertTriangleIcon, InfoIcon, UsersIcon, MessageSquareIcon, EyeIcon, MailIcon
    } = window.pano_getIcons();

    const {
        RiverainAccueilTab, RiverainEquipeTab, RiverainContactTab, RiverainNewsletterTab,
        Button, ConfirmModal, NotificationBadge, LogoSVG, TextLogo,
        RiverainPdfModal, RiverainImageModal, RiverainArretesModal, RiverainDemoWarningModal
    } = window.pano_getComponents();

    // 3. - Effets et télémétrie
    useEffect(() => {
        setActiveTab(initialTab);
    }, [initialTab]);

    useEffect(() => {
        if (isPreview && scrollRef.current) {
            scrollRef.current.scrollTo({ top: 0, behavior: 'smooth' });
        } else if (!isPreview) {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }
    }, [activeTab, isPreview]);

    useEffect(() => {
        if (!isPreview && panneau && panneau.id && panneau.id !== 'CONTACT_PUBLIC' && panneau.id !== 'demo-panneau' && panneau.status === 'Actif') {
            const trackKey = 'pano_view_' + panneau.id;
            if (!sessionStorage.getItem(trackKey)) {
                sessionStorage.setItem(trackKey, '1');
                fetch((window.pano_CONFIG?.apiBaseUrl || '?api=') + 'panneaux/view&silent=1', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ id: panneau.id })
                }).catch(() => {});
            }
        }
    }, [panneau, isPreview]);

    // 4. - Écrans d'erreur responsives
    if (!isPreview) {
        if (!panneau || panneau.status === 'Supprimé') {
            return (
                <div className="flex flex-col items-center justify-center p-6 bg-slate-50 text-center min-h-screen w-full">
                    <div className="max-w-md mx-auto">
                        {AlertTriangleIcon && <AlertTriangleIcon size={64} className="text-slate-300 mb-6 mx-auto" />}
                        <h2 className="text-2xl font-black text-slate-700 break-words">Panneau introuvable</h2>
                        <p className="text-base text-slate-500 mt-3 mb-8 break-words">Ce panneau n'existe pas ou a été supprimé par son propriétaire.</p>
                        <a href="https://eco-panneau.fr" className="flex items-center justify-center gap-2 opacity-50 hover:opacity-100 transition" title="Retour à l'accueil">
                            {LogoSVG && <LogoSVG size={20} className="text-slate-800" />}
                            {TextLogo && <TextLogo className="text-sm text-slate-800" />}
                        </a>
                    </div>
                </div>
            );
        }

        if (panneau.status === 'Brouillon') {
            return (
                <div className="flex flex-col items-center justify-center p-6 bg-slate-50 text-center min-h-screen w-full">
                    <div className="max-w-md mx-auto">
                        {AlertTriangleIcon && <AlertTriangleIcon size={64} className="text-slate-300 mb-6 mx-auto" />}
                        <h2 className="text-2xl font-black text-slate-700 break-words">En attente de publication</h2>
                        <p className="text-base text-slate-500 mt-3 mb-8 break-words">Ce panneau n'a pas encore été publié.</p>
                        <a href="https://eco-panneau.fr" className="flex items-center justify-center gap-2 opacity-50 hover:opacity-100 transition" title="Retour à l'accueil">
                            {LogoSVG && <LogoSVG size={20} className="text-slate-800" />}
                            {TextLogo && <TextLogo className="text-sm text-slate-800" />}
                        </a>
                    </div>
                </div>
            );
        }

        if (panneau.status === 'Hors ligne' || panneau.status === 'Désactivé' || panneau.status === 'Suspendu') {
            return (
                <div className="flex flex-col items-center justify-center p-6 bg-slate-50 text-center min-h-screen w-full">
                    <div className="max-w-md mx-auto">
                        {AlertTriangleIcon && <AlertTriangleIcon size={64} className="text-slate-300 mb-6 mx-auto" />}
                        <h2 className="text-2xl font-black text-slate-700 break-words">Panneau inactif</h2>
                        <p className="text-base text-slate-500 mt-3 mb-8 break-words leading-relaxed">
                            Ce panneau a été désactivé par son propriétaire sur la plateforme <a href="https://eco-panneau.fr" className="hover:opacity-80 transition ml-1 inline-block"><TextLogo className="text-sm" /></a>.
                        </p>
                        <a href="https://eco-panneau.fr" className="flex items-center justify-center gap-2 opacity-50 hover:opacity-100 transition" title="Retour à l'accueil">
                            {LogoSVG && <LogoSVG size={20} className="text-slate-800" />}
                            {TextLogo && <TextLogo className="text-sm text-slate-800" />}
                        </a>
                    </div>
                </div>
            );
        }
    } else if (!panneau) {
        return <div className="flex flex-col items-center justify-center bg-slate-50 text-slate-400 h-full w-full font-bold uppercase tracking-widest break-words p-4 text-center">Chargement de l'aperçu...</div>;
    }

    // 5. - Variables de configuration
    const isPublicContact = panneau.id === 'CONTACT_PUBLIC';
    const isDemo = panneau.id === 'demo-panneau';
    const isSimulated = isPreview || isDemo;
    
    const themeColor = panneau.themeColor || '#059669';
    const hasNoAds = panneau.hasNoAds;
    
    const displayOpts = panneau.displayOptions || {};
    const hideLegal = displayOpts.hideLegal === true;

    const hasIntervenants = panneau.intervenants && panneau.intervenants.length > 0;
    const hasLots = panneau.lots && panneau.lots.length > 0;
    const hideTeamTab = !hasIntervenants && !hasLots;

    const showNewsletterTab = settings?.opt_newsletter !== 'disabled' && !isPublicContact;
    const showMessagingTab = settings?.opt_messaging !== 'disabled';

    const panelInteractions = (interactions || []).filter(i => i.panneauId === panneau.id);
    
    const unreadCount = isSimulated ? 0 : panelInteractions.filter(m => !m.resolved && (m.authorType === 'Admin' || m.authorType === 'Client')).length;

    // L'image de fond (Header) reste en taille originale
    const displayImageUrl = (isPublicContact && settings?.contact_header_image)
        ? `${window.pano_CONFIG.apiBaseUrl}file/download&type=image&id=${settings.contact_header_image}` 
        : (panneau.imageId ? `${window.pano_CONFIG.apiBaseUrl}file/download&type=image&id=${panneau.imageId}` : panneau.imageUrl);
        
    // CORRECTION OOM : Le logo du MOA passe en miniature (&preview=1)
    const displayMoaLogoUrl = panneau.maitreOuvrageLogoId 
        ? `${window.pano_CONFIG.apiBaseUrl}file/download&type=image&id=${panneau.maitreOuvrageLogoId}&preview=1` 
        : panneau.maitreOuvrageLogoUrl;

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

    const handleExternalLink = (e, url) => {
        if (isSimulated) {
            if (e) { e.preventDefault(); e.stopPropagation(); }
            openDialog('demo_warning', 'link');
            return true;
        }
        return false;
    };

    useEffect(() => {
        if (activeTab === 'team' && hideTeamTab) setActiveTab('home');
        if (activeTab === 'newsletter' && !showNewsletterTab) setActiveTab('home');
        if (activeTab === 'contact' && !showMessagingTab) setActiveTab('home');
    }, [activeTab, hideTeamTab, showNewsletterTab, showMessagingTab]);

    const rootClasses = isPreview 
        ? "flex flex-col bg-slate-50 relative text-slate-800 font-sans selection:bg-emerald-200 h-full w-full"
        : "flex flex-col bg-slate-50 relative text-slate-800 font-sans selection:bg-emerald-200 min-h-screen w-full";

    const contentClasses = isPreview
        ? "flex-1 flex flex-col overflow-y-auto custom-scrollbar relative w-full"
        : "flex-1 flex flex-col relative w-full max-w-4xl mx-auto sm:px-6 md:px-8";

    const navPosition = isPreview ? 'absolute' : 'fixed';
    const basePb = isPublicContact ? 40 : (!hasNoAds ? 100 : 60);

    // 6. - Rendu UI
    return (
        <div className={rootClasses}>
            
            {showPanelBanner && (
                <div className="bg-blue-600 text-white text-center py-2.5 px-4 font-bold text-sm z-[60] relative shadow-md shrink-0">
                    <div 
                        dangerouslySetInnerHTML={{ 
                            __html: window.DOMPurify 
                                ? window.DOMPurify.sanitize(settings.panel_banner_msg, { USE_PROFILES: { html: true } }) 
                                : settings.panel_banner_msg.replace(/<[^>]*>?/gm, '') 
                        }} 
                        className="admin-html break-words leading-relaxed" 
                    />
                </div>
            )}

            <div className={`relative shrink-0 bg-slate-900 w-full ${displayImageUrl ? (isPreview ? 'h-[160px]' : 'h-[160px] sm:h-[220px] md:h-[280px]') : (isPreview ? 'h-[100px]' : 'h-[100px] sm:h-[120px]')}`}>
                {displayImageUrl && (
                    <>
                        <img 
                            src={displayImageUrl} 
                            alt="Panneau" 
                            className="absolute inset-0 w-full h-full object-cover" 
                            style={{ filter: 'grayscale(100%)' }}
                        />
                        <div className="absolute inset-0" style={{ 
                            backgroundColor: themeColor,
                            WebkitMaskImage: 'linear-gradient(to bottom, transparent 0px, transparent 1px, black 100%)',
                            maskImage: 'linear-gradient(to bottom, transparent 0px, transparent 1px, black 100%)',
                            mixBlendMode: 'multiply'
                        }}></div>
                        <div className="absolute inset-0 bg-gradient-to-t from-slate-900/90 via-slate-900/40 to-transparent pointer-events-none"></div>
                    </>
                )}
                
                {!displayImageUrl && <div className="absolute inset-0" style={{ backgroundColor: themeColor }}></div>}
                
                {displayImageUrl && !isPublicContact && Button && EyeIcon && (
                    <Button 
                        variant="secondary"
                        shape="square"
                        onClick={() => openModal('image')} 
                        icon={EyeIcon}
                        className="absolute top-4 right-4 z-20 bg-white/90 backdrop-blur-md hover:bg-white border-none shadow-xl"
                        style={{ color: themeColor }}
                        title="Aperçu du projet"
                    />
                )}

                <div className="absolute bottom-0 inset-x-0">
                    <div className="w-full max-w-4xl mx-auto p-4 sm:px-6 md:px-8 pr-16 flex flex-col justify-end h-full">
                        <h1 className={`font-black text-white leading-tight drop-shadow-md break-words ${isPreview ? 'text-xl' : 'text-xl sm:text-3xl md:text-4xl'}`}>
                            {panneau.name}
                        </h1>
                    </div>
                </div>
            </div>

            <div ref={scrollRef} className={contentClasses} style={{ paddingBottom: `calc(${basePb}px + env(safe-area-inset-bottom))` }}>
                {activeTab === 'home' && RiverainAccueilTab && (
                    <RiverainAccueilTab panneau={panneau} themeColor={themeColor} displayMoaLogoUrl={displayMoaLogoUrl} hideLegal={hideLegal} handleExternalLink={handleExternalLink} openModal={openModal} />
                )}

                {activeTab === 'team' && !hideTeamTab && RiverainEquipeTab && (
                    <RiverainEquipeTab panneau={panneau} themeColor={themeColor} handleExternalLink={handleExternalLink} isPreview={isPreview} />
                )}

                {activeTab === 'newsletter' && showNewsletterTab && RiverainNewsletterTab && (
                    <RiverainNewsletterTab panneau={panneau} themeColor={themeColor} showToast={showToast} isPreview={isPreview} />
                )}

                {activeTab === 'contact' && showMessagingTab && RiverainContactTab && (
                    <RiverainContactTab panneau={panneau} themeColor={themeColor} interactions={interactions} settings={settings} refreshData={refreshData} showToast={showToast} isPreview={isPreview} handleExternalLink={handleExternalLink} />
                )}
            </div>

            <div className={`${navPosition} bottom-0 inset-x-0 z-[100] flex flex-col w-full`}>
                
                {(!isPublicContact) && (
                    <div 
                        className="w-full bg-white border-t border-slate-200 flex items-center justify-center shadow-[0_-4px_10px_rgba(0,0,0,0.03)]"
                        style={{ 
                            height: (hasNoAds && !isPublicContact) ? 'calc(60px + env(safe-area-inset-bottom))' : '60px',
                            paddingBottom: (hasNoAds && !isPublicContact) ? 'env(safe-area-inset-bottom)' : '0'
                        }}
                    >
                        <div className={`flex items-center w-full max-w-4xl mx-auto px-2 h-[60px] ${isPreview ? 'justify-around' : 'justify-around sm:justify-center sm:gap-12'}`}>
                            <div role="button" tabIndex={0} onClick={() => setActiveTab('home')} className={`cursor-pointer flex flex-col items-center justify-center h-full space-y-1 transition-colors ${activeTab === 'home' ? 'text-slate-900' : 'text-slate-400 hover:text-slate-600'} ${isPreview ? 'w-full' : 'w-full sm:w-32'}`}>
                                {InfoIcon && <InfoIcon size={20} style={{ color: activeTab === 'home' ? themeColor : 'currentColor' }} />}
                                <span className={`font-bold text-center leading-none mt-1 break-words ${isPreview ? 'text-[9px]' : 'text-[9px] sm:text-xs'}`}>Le panneau</span>
                            </div>
                            
                            {!hideTeamTab && (
                                <div role="button" tabIndex={0} onClick={() => setActiveTab('team')} className={`cursor-pointer flex flex-col items-center justify-center h-full space-y-1 transition-colors ${activeTab === 'team' ? 'text-slate-900' : 'text-slate-400 hover:text-slate-600'} ${isPreview ? 'w-full' : 'w-full sm:w-32'}`}>
                                    {UsersIcon && <UsersIcon size={20} style={{ color: activeTab === 'team' ? themeColor : 'currentColor' }} />}
                                    <span className={`font-bold text-center leading-none mt-1 break-words ${isPreview ? 'text-[9px]' : 'text-[9px] sm:text-xs'}`}>L'équipe</span>
                                </div>
                            )}
                            
                            {showNewsletterTab && (
                                <div role="button" tabIndex={0} onClick={() => setActiveTab('newsletter')} className={`cursor-pointer flex flex-col items-center justify-center h-full space-y-1 transition-colors ${activeTab === 'newsletter' ? 'text-slate-900' : 'text-slate-400 hover:text-slate-600'} ${isPreview ? 'w-full' : 'w-full sm:w-32'}`}>
                                    {MailIcon && <MailIcon size={20} style={{ color: activeTab === 'newsletter' ? themeColor : 'currentColor' }} />}
                                    <span className={`font-bold text-center leading-none mt-1 break-words ${isPreview ? 'text-[9px]' : 'text-[9px] sm:text-xs'}`}>Info riverains</span>
                                </div>
                            )}
                            
                            {showMessagingTab && (
                                <div role="button" tabIndex={0} onClick={() => setActiveTab('contact')} className={`cursor-pointer flex flex-col items-center justify-center h-full space-y-1 relative transition-colors ${activeTab === 'contact' ? 'text-slate-900' : 'text-slate-400 hover:text-slate-600'} ${isPreview ? 'w-full' : 'w-full sm:w-32'}`}>
                                    <div className="relative">
                                        {MessageSquareIcon && <MessageSquareIcon size={20} style={{ color: activeTab === 'contact' ? themeColor : 'currentColor' }} />}
                                        {NotificationBadge && <NotificationBadge count={unreadCount} className="absolute -top-2 -right-2 scale-75" />}
                                    </div>
                                    <span className={`font-bold text-center leading-none mt-1 break-words ${isPreview ? 'text-[9px]' : 'text-[9px] sm:text-xs'}`}>Contact</span>
                                </div>
                            )}
                        </div>
                    </div>
                )}

                {(!hasNoAds || isPublicContact) && LogoSVG && TextLogo && (
                    <a 
                        href="https://eco-panneau.fr"
                        onClickCapture={(e) => {
                            if (isSimulated) { e.preventDefault(); e.stopPropagation(); openDialog('demo_warning', 'link'); }
                        }}
                        className={`w-full bg-slate-900 text-white flex items-center justify-center gap-1.5 opacity-95 hover:opacity-100 transition-colors shrink-0 ${isSimulated ? 'cursor-pointer' : ''}`}
                        title="Créer mon panneau de chantier"
                        style={{ 
                            height: 'calc(40px + env(safe-area-inset-bottom))',
                            paddingBottom: 'env(safe-area-inset-bottom)'
                        }}
                    >
                        <LogoSVG size={16} className="shrink-0 text-white pointer-events-none" />
                        <TextLogo colorEco="text-white" className="text-xs text-white pointer-events-none" />
                    </a>
                )}

            </div>

            {/* Ouverture isolée des modales Zéro-Dette */}
            {activeModal === 'pdf' && targetId && RiverainPdfModal && (
                <RiverainPdfModal targetId={targetId} panneau={panneau} onClose={closeCurrentLayer} onOpenArretes={() => openModal('arretes')} isPreview={isPreview} />
            )}

            {activeModal === 'image' && displayImageUrl && RiverainImageModal && (
                <RiverainImageModal displayImageUrl={displayImageUrl} onClose={closeCurrentLayer} isPreview={isPreview} />
            )}

            {activeModal === 'arretes' && RiverainArretesModal && (
                <RiverainArretesModal panneau={panneau} onClose={closeCurrentLayer} onOpenPdf={(id) => openModal('pdf', id)} isPreview={isPreview} />
            )}

            {activeDialog === 'demo_warning' && dialogId && RiverainDemoWarningModal && (
                <RiverainDemoWarningModal targetId={dialogId} onClose={closeCurrentLayer} isPreview={isPreview} />
            )}
        </div>
    );
};

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