/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Interface Admin - Onglet : Gestion des Panneaux (Modération)
 * =========================================================================
 */

window.pano_AdminPanelsTab = ({ data, refreshData, setManagingPanneau, setValidationErrors, openLocalModal, openLocalDialog, closeCurrentLayer, activeModal, activeDialog, targetId, showToast, setActiveTab }) => {
    const { useState, useEffect } = React;
    
    const routerActiveModal = activeModal || new URLSearchParams(window.location.search).get('modal');
    const routerActiveDialog = activeDialog || new URLSearchParams(window.location.search).get('dialog');
    const routerCloseLayer = closeCurrentLayer || (() => window.history.back());
    const routerOpenModal = openLocalModal || ((type, id = null) => {
        const u = new URL(window.location);
        u.searchParams.set('modal', type);
        if(id) u.searchParams.set('targetId', id);
        window.history.pushState({ modal: type }, '', u);
        window.dispatchEvent(new Event('popstate'));
    });
    const routerOpenDialog = openLocalDialog || ((type) => {
        const u = new URL(window.location);
        u.searchParams.set('dialog', type);
        window.history.pushState({ dialog: type }, '', u);
        window.dispatchEvent(new Event('popstate'));
    });

    const [forceRender, setForceRender] = useState(0);
    useEffect(() => {
        if (!activeDialog && !activeModal) {
            const onPop = () => setForceRender(prev => prev + 1);
            window.addEventListener('popstate', onPop);
            return () => window.removeEventListener('popstate', onPop);
        }
    }, [activeDialog, activeModal]);

    const [moderationTarget, setModerationTarget] = useState(null);
    const [isSaving, setIsSaving] = useState(false);
    const [suspendTarget, setSuspendTarget] = useState(null);
    const [suspendReason, setSuspendReason] = useState("");
    const [confirmConfig, setConfirmConfig] = useState(null);

    const Button = window.pano_Button || (() => null);
    const Modal = window.pano_Modal || (() => null);
    const ConfirmModal = window.pano_ConfirmModal || (() => null);
    const StatusBadge = window.pano_StatusBadge || (() => null);
    const PreviewModal = window.pano_PreviewModal || (() => null);
    const IconBadge = window.pano_IconBadge || (() => null);

    const BuildingIcon = window.pano_BuildingIcon || (() => null);
    const EyeIcon = window.pano_EyeIcon || (() => null);
    const EditIcon = window.pano_EditIcon || (() => null);
    const PowerIcon = window.pano_PowerIcon || (() => null);
    const Trash2Icon = window.pano_Trash2Icon || (() => null);
    const AlertTriangleIcon = window.pano_AlertTriangleIcon || (() => null);
    const CheckCircleIcon = window.pano_CheckCircleIcon || (() => null);
    const MessageSquareIcon = window.pano_MessageSquareIcon || (() => null);

    const checkPanelViolations = (p) => {
        const blacklist = (data.settings?.blacklist || '').split(',').map(s => s.trim().toLowerCase()).filter(Boolean);
        const greylist = (data.settings?.greylist || '').split(',').map(s => s.trim().toLowerCase()).filter(Boolean);
        let blackCount = 0; let greyCount = 0;
        const textToSearch = [p.name, p.location, p.description, p.maitreOuvrage].filter(Boolean).join(' ').toLowerCase();
        const detected = { black: [], grey: [] };
        
        blacklist.forEach(word => { if(textToSearch.includes(word)) { blackCount++; detected.black.push(word); } });
        greylist.forEach(word => { if(textToSearch.includes(word)) { greyCount++; detected.grey.push(word); } });
        
        return { isViolation: blackCount > 0 || greyCount > 2, detected };
    };

    const handleContactClient = (clientId) => {
        const u = new URL(window.location);
        u.searchParams.set('chat_id', 'SUPPORT_' + clientId);
        window.history.replaceState({}, '', u);
        setActiveTab('messages');
    };

    const handleSuspendSubmit = async (e) => {
        e.preventDefault();
        if (!suspendReason.trim()) return;

        setIsSaving(true);
        const p = suspendTarget;
        
        const d1 = await window.pano_apiFetch('panneaux/status', { body: { id: p.id, status: 'Suspendu' }});
        
        if (d1) {
            const message = `Le panneau "${p.name}" a été suspendu jusqu'à correction car il ne respecte pas les Conditions Générales de Vente du site.\n\nMotif du support :\n${suspendReason}\n\nVeuillez apporter les corrections nécessaires pour pouvoir le réactiver.`;
            await window.pano_apiFetch('interactions', {
                body: {
                    panneauId: `SUPPORT_${p.clientName}`,
                    detail: message,
                    author: 'Admin',
                    targetEmail: 'Client',
                    type: 'message'
                }
            });
            refreshData();
            routerCloseLayer();
            setTimeout(() => {
                setSuspendTarget(null);
                setSuspendReason("");
            }, 300);
        }
        setIsSaving(false);
    };

    const handleValidatePanel = async (id) => {
        const d = await window.pano_apiFetch('panneaux/mark_seen', {
            body: { id },
            setLoading: setIsSaving,
            successMessage: "Panneau validé et marqué comme contrôlé."
        });
        if (d) {
            refreshData();
            routerCloseLayer();
        }
    };

    const toggleStatus = (id, currentStatus) => {
        const newStatus = currentStatus === 'Actif' ? 'Suspendu' : 'Actif';
        setConfirmConfig({
            title: `Passer en ${newStatus}`,
            message: `Voulez-vous vraiment passer ce panneau en statut "${newStatus}" ?`,
            confirmText: "Confirmer",
            type: newStatus === 'Suspendu' ? 'warning' : 'success',
            onConfirm: async () => {
                routerCloseLayer();
                const d = await window.pano_apiFetch('panneaux/status', { body: { id, status: newStatus }, setLoading: setIsSaving });
                if (d) refreshData();
            }
        });
        routerOpenDialog('confirm');
    };

    const handleDelete = (id) => {
        setConfirmConfig({
            title: "Suppression forcée",
            message: "Attention : Cette action détruira immédiatement ce panneau et toutes ses données.",
            confirmText: "Détruire",
            isDestructive: true,
            onConfirm: async () => {
                routerCloseLayer();
                const d = await window.pano_apiFetch('panneaux/delete', { body: { id, force_immediate: true }, setLoading: setIsSaving });
                if (d) refreshData();
            }
        });
        routerOpenDialog('confirm');
    };

    const panneaux = data.panneaux || [];
    const clients = data.clients || [];

    const demoPanneau = 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 regularPanneaux = panneaux.filter(p => p.id !== 'demo-panneau' && p.status !== 'Brouillon');
    
    const publishedPanels = regularPanneaux.filter(p => p.status === 'Actif');
    const unseenPanels = publishedPanels.filter(p => !p.admin_seen);
    const seenPanels = publishedPanels.filter(p => p.admin_seen);
    const otherPanels = regularPanneaux.filter(p => p.status !== 'Actif');

    const adminPreviewCible = routerActiveModal === 'preview_admin' ? panneaux.find(p => p.id === targetId) : null;

    return (
        <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4">
            <div>
                <h1 className="text-3xl font-black text-slate-800">Panneaux (Admin)</h1>
                <p className="text-slate-500 font-medium">Modération et gestion de la base de données (version publiée uniquement).</p>
            </div>

            <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">
                <div className="flex gap-4 items-center">
                    <IconBadge icon={BuildingIcon} variant="purple" size="lg" />
                    <div>
                        <h3 className="font-black text-purple-900 text-lg">Panneau de démonstration</h3>
                        <p className="text-xs text-purple-700 font-medium">Modifiez ce panneau pour mettre à jour la page d'accueil.</p>
                    </div>
                </div>
                <Button variant="purple" icon={EditIcon} onClick={() => { setManagingPanneau({...demoPanneau}); setValidationErrors([]); routerOpenModal('editor', 'demo-panneau'); }} className="w-full sm:w-auto px-6 py-3">
                    Éditer le panneau démo
                </Button>
            </div>

            {unseenPanels.length > 0 && (
                <div className="space-y-4 mb-8">
                    <h2 className="text-xl font-black text-slate-800 flex items-center gap-2 border-b border-slate-200 pb-2"><AlertTriangleIcon size={20} className="text-amber-500"/> Nouveaux panneaux (À contrôler)</h2>
                    <div className="grid grid-cols-[repeat(auto-fit,minmax(320px,1fr))] gap-4">
                        {unseenPanels.map(p => {
                            const { isViolation, detected } = checkPanelViolations(p);
                            const owner = clients.find(c => c.id === p.clientName);
                            return (
                                <div key={p.id} className={`bg-white rounded-3xl p-5 shadow-sm border flex flex-col gap-4 transition hover:shadow-md ${isViolation ? 'border-red-400 bg-red-50/30' : 'border-slate-200 hover:border-emerald-200'}`}>
                                    <div className="flex justify-between items-start">
                                        <div className="min-w-0 pr-2">
                                            <p className="font-black text-base text-slate-800 truncate" title={p.name}>{p.name || 'Brouillon'}</p>
                                            <p className="text-xs text-slate-500 truncate mt-0.5">{owner ? (owner.name || owner.email) : 'Client inconnu'}</p>
                                        </div>
                                        {isViolation && <Button variant="danger" shape="round" icon={AlertTriangleIcon} onClick={() => { setModerationTarget({ panneau: p, detected }); routerOpenDialog('moderation'); }} className="p-2 shrink-0 shadow-none border-none" title="Alerte modération" />}
                                    </div>
                                    <div className="flex gap-2 flex-wrap pt-4 border-t border-slate-100 mt-auto">
                                        <Button variant="info" icon={EyeIcon} onClick={() => routerOpenModal('preview_admin', p.id)} className="flex-1 text-[10px] justify-center py-2">Contrôler</Button>
                                        <Button variant="secondary" shape="square" icon={MessageSquareIcon} onClick={() => handleContactClient(p.clientName)} className="p-2 shadow-none border-none" title="Contacter le client" />
                                        <Button variant="warning" shape="round" icon={PowerIcon} onClick={() => { setSuspendTarget(p); setSuspendReason(""); routerOpenDialog('suspend'); }} className="p-2 shadow-none border-none" title="Désactiver le panneau" />
                                        <Button variant="danger" shape="round" icon={Trash2Icon} onClick={() => handleDelete(p.id)} className="p-2 shadow-none border-none" title="Supprimer" />
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </div>
            )}

            {seenPanels.length > 0 && (
                <div className="space-y-4 mb-8">
                    <h2 className="text-xl font-black text-slate-800 flex items-center gap-2 border-b border-slate-200 pb-2"><CheckCircleIcon size={20} className="text-emerald-500"/> Panneaux actifs (Contrôlés)</h2>
                    <div className="grid grid-cols-[repeat(auto-fit,minmax(320px,1fr))] gap-4">
                        {seenPanels.map(p => {
                            const owner = clients.find(c => c.id === p.clientName);
                            return (
                                <div key={p.id} className="bg-white rounded-3xl p-5 shadow-sm border border-slate-200 flex flex-col gap-4 transition hover:shadow-md hover:border-blue-200">
                                    <div className="flex justify-between items-start">
                                        <div className="min-w-0 pr-2">
                                            <p className="font-black text-base text-slate-800 truncate" title={p.name}>{p.name || 'Brouillon'}</p>
                                            <p className="text-xs text-slate-500 truncate mt-0.5">{owner ? (owner.name || owner.email) : 'Client inconnu'}</p>
                                        </div>
                                    </div>
                                    <div className="flex gap-2 flex-wrap pt-4 border-t border-slate-100 mt-auto">
                                        <Button variant="secondary" icon={EyeIcon} onClick={() => routerOpenModal('preview_admin', p.id)} className="flex-1 text-[10px] justify-center py-2">Aperçu</Button>
                                        <Button variant="info" shape="square" icon={MessageSquareIcon} onClick={() => handleContactClient(p.clientName)} className="p-2 shadow-none border-none" title="Contacter le client" />
                                        <Button variant="warning" shape="round" icon={PowerIcon} onClick={() => { setSuspendTarget(p); setSuspendReason(""); routerOpenDialog('suspend'); }} className="p-2 shadow-none border-none" title="Désactiver le panneau" />
                                        <Button variant="danger" shape="round" icon={Trash2Icon} onClick={() => handleDelete(p.id)} className="p-2 shadow-none border-none" title="Supprimer" />
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </div>
            )}

            {otherPanels.length > 0 && (
                <div className="space-y-4">
                    <h2 className="text-xl font-black text-slate-800 flex items-center gap-2 border-b border-slate-200 pb-2"><BuildingIcon size={20} className="text-slate-400"/> Autres (Suspendus, Suppression...)</h2>
                    <div className="grid grid-cols-[repeat(auto-fit,minmax(320px,1fr))] gap-4 opacity-80">
                        {otherPanels.map(p => {
                            const owner = clients.find(c => c.id === p.clientName);
                            return (
                                <div key={p.id} className="bg-slate-50 rounded-3xl p-5 shadow-sm border border-slate-200 flex flex-col gap-4">
                                    <div className="flex justify-between items-start mb-2">
                                        <div className="min-w-0 pr-2">
                                            <p className="font-black text-base text-slate-700 truncate" title={p.name}>{p.name || 'Sans nom'}</p>
                                            <p className="text-xs text-slate-500 truncate mt-0.5">{owner ? (owner.name || owner.email) : 'Client inconnu'}</p>
                                        </div>
                                        <StatusBadge status={p.status} />
                                    </div>
                                    <div className="flex gap-2 flex-wrap pt-4 border-t border-slate-200 mt-auto">
                                        <Button variant="secondary" icon={EyeIcon} onClick={() => routerOpenModal('preview_admin', p.id)} className="flex-1 text-[10px] justify-center py-2">Aperçu</Button>
                                        <Button variant="info" shape="square" icon={MessageSquareIcon} onClick={() => handleContactClient(p.clientName)} className="p-2 shadow-none border-none" title="Contacter le client" />
                                        {p.status === 'Suspendu' && <Button variant="success" shape="square" icon={PowerIcon} onClick={() => toggleStatus(p.id, p.status)} className="p-2 shadow-none border-none" title="Réactiver" />}
                                        <Button variant="danger" shape="round" icon={Trash2Icon} onClick={() => handleDelete(p.id)} className="p-2 shadow-none border-none" title="Supprimer" />
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </div>
            )}

            {routerActiveDialog === 'suspend' && suspendTarget && Modal && (
                <Modal title="Désactiver le panneau" type="warning" onClose={routerCloseLayer} preventClose={isSaving} zIndex="z-[250]">
                    <form onSubmit={handleSuspendSubmit} className="space-y-4">
                        <p className="text-sm text-slate-600">
                            Veuillez saisir le motif de la désactivation. Ce message sera envoyé au client par e-mail et dans sa messagerie support pour l'informer que son panneau ne respecte pas les CGV et nécessite une correction.
                        </p>
                        <textarea 
                            value={suspendReason} 
                            onChange={e => setSuspendReason(e.target.value)} 
                            required 
                            rows={5}
                            placeholder="Motif détaillé de la suspension..."
                            className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm focus:border-amber-500 outline-none transition resize-none custom-scrollbar"
                        />
                        <div className="flex gap-3 pt-2 border-t border-slate-100">
                            <Button variant="secondary" type="button" onClick={routerCloseLayer} disabled={isSaving} className="flex-1 py-3 justify-center">Annuler</Button>
                            <Button variant="warningSolid" type="submit" disabled={isSaving || !suspendReason.trim()} className="flex-1 py-3 uppercase tracking-widest justify-center">Désactiver le panneau</Button>
                        </div>
                    </form>
                </Modal>
            )}

            {routerActiveDialog === 'moderation' && moderationTarget && Modal && (
                <Modal title="Alerte modération" type="error" onClose={routerCloseLayer} zIndex="z-[250]">
                    <div className="space-y-4">
                        <div className="bg-red-50 p-4 rounded-xl border border-red-200">
                            <p className="text-sm text-red-800 font-bold mb-2">Mots sensibles détectés dans le panneau : {moderationTarget.panneau.name}</p>
                            {moderationTarget.detected.black.length > 0 && (
                                <p className="text-xs text-red-600 font-black">Liste noire : {moderationTarget.detected.black.join(', ')}</p>
                            )}
                            {moderationTarget.detected.grey.length > 0 && (
                                <p className="text-xs text-orange-600 font-bold mt-1">Liste grise : {moderationTarget.detected.grey.join(', ')}</p>
                            )}
                        </div>
                        <p className="text-sm text-slate-600">Actions de modération rapides :</p>
                        <div className="flex flex-col gap-3 pt-4 border-t border-slate-100">
                            <Button variant="info" icon={MessageSquareIcon} onClick={() => { 
                                handleContactClient(moderationTarget.panneau.clientName);
                                routerCloseLayer(); 
                            }} className="w-full py-3 justify-center">
                                Contacter le client
                            </Button>
                            <Button variant="dangerSolid" icon={PowerIcon} onClick={() => { 
                                setSuspendTarget(moderationTarget.panneau); 
                                setSuspendReason(""); 
                                routerCloseLayer(); 
                                setTimeout(() => routerOpenDialog('suspend'), 100);
                            }} className="w-full py-3 justify-center">
                                Désactiver ce panneau
                            </Button>
                            <div className="flex gap-3">
                                <Button variant="secondary" onClick={routerCloseLayer} className="flex-1 py-3 justify-center">
                                    Ignorer (Fermer)
                                </Button>
                                <Button variant="primary" icon={EyeIcon} onClick={() => { 
                                    routerCloseLayer(); 
                                    setTimeout(() => routerOpenModal('preview_admin', moderationTarget.panneau.id), 100); 
                                }} className="flex-1 py-3 justify-center">
                                    Contrôler le panneau
                                </Button>
                            </div>
                        </div>
                    </div>
                </Modal>
            )}

            {adminPreviewCible && PreviewModal && (
                <PreviewModal 
                    panneau={adminPreviewCible} 
                    interactions={data.interactions || []} 
                    onClose={routerCloseLayer} 
                    showToast={showToast} 
                    refreshData={refreshData}
                    isAdmin={true}
                    onValidate={() => handleValidatePanel(adminPreviewCible.id)}
                    onContactClient={() => { handleContactClient(adminPreviewCible.clientName); routerCloseLayer(); }}
                    onSuspend={() => { setSuspendTarget(adminPreviewCible); setSuspendReason(""); routerCloseLayer(); setTimeout(()=>routerOpenDialog('suspend'), 100); }}
                />
            )}

            {routerActiveDialog === 'confirm' && confirmConfig && ConfirmModal && <ConfirmModal {...confirmConfig} onCancel={routerCloseLayer} zIndex="z-[350]" />}
        </div>
    );
};

/* EOF ========== [_react/_admin_panneaux.jsx] */