// ECO-PANNEAU.FR - _react/clients/_clients_panneaux.jsx

window.pano_ClientPanelsTab = ({ data, myClientData, refreshData, setManagingPanneau, setValidationErrors, setPreviewPanneau, clientOpts, toggleDashboardPin, handleCreateNewPanel, setPanelTeamModal, setArchiveConfig }) => {
    
    // 1. - HOOKS ET ROUTAGE Zéro-Dette
    const { useState } = React;
    
    // SÉCURITÉ ANTI-FUITE DE MÉMOIRE (Memory Leak)
    const { isMounted, safeFetch } = window.pano_useSafeFetch();

    // CORRECTION ZÉRO-DETTE : Distribution centralisée des props du routeur pour éviter les Render Loops
    const urlModal = window.pano_useUrlModal ? window.pano_useUrlModal() : {};
    const { openModal, openDialog, closeCurrentLayer, openChat, activeModal, activeDialog, targetId, dialogId } = urlModal;

    // 2. - COMPOSANTS ET ICÔNES
    const {
        BuildingIcon, PlusIcon, AlertTriangleIcon, PinIcon, QrCodeIcon, EditIcon
    } = window.pano_getIcons();

    const {
        Modal, Button, AlertBox,
        CardGrid, SearchBar, EmptySearch, PaginationFooter, ClientPanelCard, ClientInviteCard
    } = window.pano_getComponents();

    // 3. - RECHERCHE ET PAGINATION
    const { pendingInvites, visiblePanels } = window.pano_getPanelAccessRights ? window.pano_getPanelAccessRights(data.panneaux || [], myClientData.id, myClientData.email_hash) : { pendingInvites:[], visiblePanels:[] };
    const isSuspended = myClientData.paymentStatus === 'suspended';
    const purchasesAllowed = data.settings?.allow_new_purchases !== '0';

    const hasAnyPanelOrInvite = visiblePanels.length > 0 || pendingInvites.length > 0;

    const { 
        searchQuery, setSearchQuery, 
        visibleCount, setVisibleCount, 
        filteredData: filteredPanels 
    } = window.pano_useSearchAndPagination(visiblePanels, (p, q) => {
        const n = window.pano_normalizeString;
        return n(p.name).includes(q) ||
               n(p.location).includes(q) ||
               n(p.id).includes(q) ||
               n(p.status).includes(q); 
    });

    const activePendingInvites = pendingInvites.filter(p => {
        if (!searchQuery) return true;
        const q = window.pano_normalizeString(searchQuery);
        const n = window.pano_normalizeString;
        const inviter = p.owner_company || p.owner_name || '';
        return n(p.name).includes(q) || n(inviter).includes(q);
    });

    const isFeatureEnabled = (adminOpt, clientVal) => {
        if (adminOpt === 'disabled') return false;
        if (adminOpt === 'active') return true;
        if (adminOpt === 'optional_on') return clientVal !== false; 
        if (adminOpt === 'optional_off' || adminOpt === 'optional') return clientVal === true;
        return true; 
    };

    const hasNewsletterFeature = isFeatureEnabled(data.settings?.opt_newsletter, clientOpts?.newsletter);
    const hasCollabFeature = isFeatureEnabled(data.settings?.opt_collab, clientOpts?.collab);
    const hasMessagingFeature = isFeatureEnabled(data.settings?.opt_messaging, clientOpts?.messaging);

    const threads = window.pano_buildClientChatThreads ? window.pano_buildClientChatThreads(data.interactions || [], myClientData, visiblePanels, pendingInvites) : [];
    
    const unreadMap = {};
    threads.forEach(t => {
        if (t.unread > 0 && t.panneauId) {
            if (!unreadMap[t.panneauId]) {
                unreadMap[t.panneauId] = { total: 0, riverain: 0, group: 0 };
            }
            unreadMap[t.panneauId].total += t.unread;
            if (t.type === 'riverain') unreadMap[t.panneauId].riverain += t.unread;
            if (t.type === 'group') unreadMap[t.panneauId].group += t.unread;
        }
    });

    const pinnedIds = clientOpts?.pinned_panels || [];
    
    const attentionPanels = [];
    const pinnedPanels = [];
    const draftChangesPanels = [];
    const draftPanelsList = [];
    const otherPanels = [];

    // 4.1 - Classification Urgence > Favoris > Reste
    filteredPanels.forEach(c => {
        if (c.status === 'Réservé') return;

        const isPinned = pinnedIds.includes(c.id);
        const unreadCount = unreadMap[c.id]?.total || 0;
        const hasDraft = c.draft_data && Object.keys(c.draft_data).length > 0;
        
        const isUnreadDOE = c.status === 'DOE' && !c.doe_downloaded;
        
        const needsAttention = c.status === 'Suspendu' || c.status === 'Attente validation' || c.inactivity_alert_level > 0 || unreadCount > 0 || isUnreadDOE || (c.physicalPanels > 0 && (c.shipping_status === 'Expédié' || c.shipping_status === 'Attente validation client'));

        if (needsAttention) {
            attentionPanels.push(c);
        } else if (isPinned) {
            pinnedPanels.push(c);
        } else if (c.status === 'Actif' && hasDraft) {
            draftChangesPanels.push(c); 
        } else if (c.status === 'Brouillon') {
            draftPanelsList.push(c);
        } else {
            otherPanels.push(c);
        }
    });

    const displayedOtherPanels = otherPanels.slice(0, visibleCount);
    
    const demoPanneau = (data.panneaux || []).find(p => p.id === 'demo-panneau') || { id: 'demo-panneau', status: 'Actif', offerType: 'demo', name: 'Panneau de démonstration', location: 'Paris', themeColor: '#059669', hasNoAds: false };
    const demoHasDraft = demoPanneau.draft_data && Object.keys(demoPanneau.draft_data).length > 0;

    // 5. - RENDU UI
    return (
        <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 min-w-0 w-full">
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 w-full min-w-0">
                <div className="min-w-0">
                    <h1 className="text-3xl font-black text-slate-800 break-words">Mes panneaux</h1>
                    <p className="text-slate-500 font-medium break-words leading-relaxed">Gestion de vos affichages et de vos collaborations.</p>
                </div>
                
                {hasAnyPanelOrInvite && SearchBar && (
                    <div className="w-full sm:w-auto flex-1 flex justify-end gap-2 shrink-0">
                        <SearchBar searchQuery={searchQuery} setSearchQuery={setSearchQuery} placeholder="Rechercher (Nom, Lieu, Statut)..." />
                        {!isSuspended && (
                            <Button variant="primary" icon={PlusIcon} onClick={handleCreateNewPanel} className="px-4 py-3 shrink-0 shadow-md">
                                <span className="hidden sm:inline">Nouveau panneau</span>
                            </Button>
                        )}
                    </div>
                )}
                {!hasAnyPanelOrInvite && !isSuspended && (
                    <div className="flex gap-2 shrink-0">
                        <Button variant="primary" icon={PlusIcon} onClick={handleCreateNewPanel} className="shadow-md">Nouveau panneau</Button>
                    </div>
                )}
            </div>

            {(!purchasesAllowed) && <AlertBox type="warning" icon={AlertTriangleIcon}>Les commandes sont temporairement suspendues, mais la création de brouillons reste autorisée.</AlertBox>}

            {/* SECTION DÉMO (SI PRÉSENT DANS VISIBLE PANELS) */}
            {visiblePanels.some(p => p.id === 'demo-panneau') && (
                <div className="bg-purple-50 border border-purple-200 rounded-3xl p-5 flex flex-col sm:flex-row justify-between items-center gap-4 shadow-sm mb-6 min-w-0 w-full">
                    <div className="flex gap-4 items-center min-w-0 flex-1">
                        <IconBadge icon={BuildingIcon} variant="purple" size="lg" className="shrink-0" />
                        <div className="min-w-0">
                            <h3 className="font-black text-purple-900 text-lg flex flex-wrap items-center gap-2 break-words leading-tight">
                                Panneau de démonstration
                                {demoHasDraft && <span className="text-[10px] font-black uppercase tracking-widest bg-purple-200 text-purple-800 px-2 py-0.5 rounded shadow-sm">Modifié</span>}
                            </h3>
                            <p className="text-xs text-purple-700 font-medium break-words mt-1 leading-tight">Modifiez ce panneau pour mettre à jour la page d'accueil.</p>
                        </div>
                    </div>
                    
                    <div className="flex flex-wrap items-center gap-2 w-full sm:w-auto shrink-0">
                        <Button variant="success" shape="square" icon={QrCodeIcon} onClick={() => { const livePanel = { ...demoPanneau }; delete livePanel.draft_data; if (setPreviewPanneau) setPreviewPanneau(livePanel); openModal('preview', livePanel.id, false); }} className="bg-white shadow-sm flex-1 sm:flex-none" title="Voir le panneau en ligne" />
                        <Button variant="purple" icon={EditIcon} onClick={() => {
                            const panelToEdit = JSON.parse(JSON.stringify(demoPanneau));
                            if (panelToEdit.draft_data && Object.keys(panelToEdit.draft_data).length > 0) {
                                const draft = panelToEdit.draft_data;
                                delete panelToEdit.draft_data;
                                Object.assign(panelToEdit, draft);
                            }
                            setManagingPanneau(panelToEdit);
                            setValidationErrors([]);
                            openModal('editor', 'demo-panneau', false);
                        }} className="w-full sm:w-auto px-8 py-3.5 uppercase tracking-widest font-black shadow-md justify-center">
                            Édition
                        </Button>
                    </div>
                </div>
            )}

            {/* 5.2 - Affichage des grilles conditionnelles */}
            {!hasAnyPanelOrInvite ? (
                <div className="text-center p-12 bg-white rounded-3xl border border-slate-200 border-dashed min-w-0 w-full">
                    <BuildingIcon size={48} className="mx-auto text-slate-300 mb-4" />
                    <h3 className="text-lg font-black text-slate-700 break-words">Aucun panneau</h3>
                    <p className="text-sm text-slate-500 mt-2 break-words">Vous n'avez pas encore de projet en cours.</p>
                </div>
            ) : filteredPanels.length === 0 && activePendingInvites.length === 0 ? (
                EmptySearch && <EmptySearch searchQuery={searchQuery} />
            ) : (
                <>
                    {/* 5.2.1 - Priorité */}
                    {(attentionPanels.length > 0 || activePendingInvites.length > 0) && (
                        <div className="mb-10 space-y-4 min-w-0 w-full">
                            <h2 className="text-lg font-black text-slate-800 flex items-center gap-2 border-b border-slate-200 pb-2">
                                <AlertTriangleIcon size={20} className="text-amber-500" /> Action requise
                            </h2>
                            <CardGrid minWidth="320px">

                                {activePendingInvites.map(p => (
                                    <ClientInviteCard 
                                        key={`inv_${p.id}`} 
                                        invite={p} 
                                        setPreviewPanneau={setPreviewPanneau} 
                                        refreshData={refreshData} 
                                        hasCollabFeature={hasCollabFeature}
                                        openModal={openModal}
                                        openChat={openChat}
                                    />
                                ))}

                                {attentionPanels.map(c => {
                                    return (
                                        <ClientPanelCard 
                                            key={c.id} panel={c} data={data} myClientData={myClientData} localPinned={pinnedIds} togglePin={(id, e) => toggleDashboardPin('pinned_panels', id, e)} 
                                            unreadMap={unreadMap} setPreviewPanneau={setPreviewPanneau} 
                                            setManagingPanneau={setManagingPanneau} setValidationErrors={setValidationErrors} 
                                            isSuspended={isSuspended} hasNewsletterFeature={hasNewsletterFeature} 
                                            hasCollabFeature={hasCollabFeature} hasMessagingFeature={hasMessagingFeature} refreshData={refreshData}
                                            setPanelTeamModal={setPanelTeamModal} setArchiveConfig={setArchiveConfig}
                                            openModal={openModal} openDialog={openDialog} closeCurrentLayer={closeCurrentLayer} openChat={openChat}
                                            activeDialog={activeDialog} dialogId={dialogId}
                                        />
                                    );
                                })}
                            </CardGrid>
                        </div>
                    )}

                    {/* 5.2.2 - Favoris */}
                    {pinnedPanels.length > 0 && (
                        <div className="mb-10 space-y-4 min-w-0 w-full">
                            <h2 className="text-lg font-black text-slate-800 flex items-center gap-2 border-b border-slate-200 pb-2">
                                <PinIcon size={20} className="text-emerald-600" filled /> Favoris (Épinglés)
                            </h2>
                            <CardGrid minWidth="320px">
                                {pinnedPanels.map(c => {
                                    return (
                                        <ClientPanelCard 
                                            key={c.id} panel={c} data={data} myClientData={myClientData} localPinned={pinnedIds} togglePin={(id, e) => toggleDashboardPin('pinned_panels', id, e)} 
                                            unreadMap={unreadMap} setPreviewPanneau={setPreviewPanneau} 
                                            setManagingPanneau={setManagingPanneau} setValidationErrors={setValidationErrors} 
                                            isSuspended={isSuspended} hasNewsletterFeature={hasNewsletterFeature} 
                                            hasCollabFeature={hasCollabFeature} hasMessagingFeature={hasMessagingFeature} refreshData={refreshData}
                                            setPanelTeamModal={setPanelTeamModal} setArchiveConfig={setArchiveConfig}
                                            openModal={openModal} openDialog={openDialog} closeCurrentLayer={closeCurrentLayer} openChat={openChat}
                                            activeDialog={activeDialog} dialogId={dialogId}
                                        />
                                    );
                                })}
                            </CardGrid>
                        </div>
                    )}

                    {/* 5.2.3 - Modifications à publier */}
                    {draftChangesPanels.length > 0 && (
                        <div className="mb-10 space-y-4 min-w-0 w-full">
                            <h2 className="text-lg font-black text-slate-800 flex items-center gap-2 border-b border-slate-200 pb-2">
                                <BuildingIcon size={20} className="text-purple-600" /> Modifications à publier
                            </h2>
                            <CardGrid minWidth="320px">
                                {draftChangesPanels.map(c => {
                                    return (
                                        <ClientPanelCard 
                                            key={c.id} panel={c} data={data} myClientData={myClientData} localPinned={pinnedIds} togglePin={(id, e) => toggleDashboardPin('pinned_panels', id, e)} 
                                            unreadMap={unreadMap} setPreviewPanneau={setPreviewPanneau} 
                                            setManagingPanneau={setManagingPanneau} setValidationErrors={setValidationErrors} 
                                            isSuspended={isSuspended} hasNewsletterFeature={hasNewsletterFeature} 
                                            hasCollabFeature={hasCollabFeature} hasMessagingFeature={hasMessagingFeature} refreshData={refreshData}
                                            setPanelTeamModal={setPanelTeamModal} setArchiveConfig={setArchiveConfig}
                                            openModal={openModal} openDialog={openDialog} closeCurrentLayer={closeCurrentLayer} openChat={openChat}
                                            activeDialog={activeDialog} dialogId={dialogId}
                                        />
                                    );
                                })}
                            </CardGrid>
                        </div>
                    )}

                    {/* 5.2.4 - Brouillons */}
                    {draftPanelsList.length > 0 && (
                        <div className="mb-10 space-y-4 min-w-0 w-full">
                            <h2 className="text-lg font-black text-slate-800 flex items-center gap-2 border-b border-slate-200 pb-2">
                                <BuildingIcon size={20} className="text-slate-600" /> Mes brouillons
                            </h2>
                            <CardGrid minWidth="320px">
                                {draftPanelsList.map(c => {
                                    return (
                                        <ClientPanelCard 
                                            key={c.id} panel={c} data={data} myClientData={myClientData} localPinned={pinnedIds} togglePin={(id, e) => toggleDashboardPin('pinned_panels', id, e)} 
                                            unreadMap={unreadMap} setPreviewPanneau={setPreviewPanneau} 
                                            setManagingPanneau={setManagingPanneau} setValidationErrors={setValidationErrors} 
                                            isSuspended={isSuspended} hasNewsletterFeature={hasNewsletterFeature} 
                                            hasCollabFeature={hasCollabFeature} hasMessagingFeature={hasMessagingFeature} refreshData={refreshData}
                                            setPanelTeamModal={setPanelTeamModal} setArchiveConfig={setArchiveConfig}
                                            openModal={openModal} openDialog={openDialog} closeCurrentLayer={closeCurrentLayer} openChat={openChat}
                                            activeDialog={activeDialog} dialogId={dialogId}
                                        />
                                    );
                                })}
                            </CardGrid>
                        </div>
                    )}

                    {/* 5.2.5 - Autres panneaux */}
                    {otherPanels.length > 0 && (
                        <div className="space-y-4 min-w-0 w-full">
                            <h2 className="text-lg font-black text-slate-800 flex items-center gap-2 border-b border-slate-200 pb-2">
                                <BuildingIcon size={20} className="text-blue-600" /> Autres panneaux
                                <span className="ml-auto text-sm font-bold text-slate-400 bg-slate-100 px-3 py-1 rounded-lg">{otherPanels.length}</span>
                            </h2>
                            <CardGrid minWidth="320px">
                                {displayedOtherPanels.map(c => {
                                    return (
                                        <ClientPanelCard 
                                            key={c.id} panel={c} data={data} myClientData={myClientData} localPinned={pinnedIds} togglePin={(id, e) => toggleDashboardPin('pinned_panels', id, e)} 
                                            unreadMap={unreadMap} setPreviewPanneau={setPreviewPanneau} 
                                            setManagingPanneau={setManagingPanneau} setValidationErrors={setValidationErrors} 
                                            isSuspended={isSuspended} hasNewsletterFeature={hasNewsletterFeature} 
                                            hasCollabFeature={hasCollabFeature} hasMessagingFeature={hasMessagingFeature} refreshData={refreshData}
                                            setPanelTeamModal={setPanelTeamModal} setArchiveConfig={setArchiveConfig}
                                            openModal={openModal} openDialog={openDialog} closeCurrentLayer={closeCurrentLayer} openChat={openChat}
                                            activeDialog={activeDialog} dialogId={dialogId}
                                        />
                                    );
                                })}
                            </CardGrid>
                            
                            {PaginationFooter && (
                                <PaginationFooter 
                                    visibleCount={visibleCount} 
                                    setVisibleCount={setVisibleCount} 
                                    totalCount={otherPanels.length} 
                                    itemName="panneaux" 
                                />
                            )}
                        </div>
                    )}
                </>
            )}
        </div>
    );
};

/* EOF ========== [_react/clients/_clients_panneaux.jsx] */