/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Interface Client - Onglet : Tableau de bord (Vue d'ensemble)
 * =========================================================================
 */

window.pano_ClientDashboardTab = ({ 
    data, 
    myClientData, 
    refreshData, 
    showToast, 
    setActiveTab,
    setManagingPanneau,
    setValidationErrors,
    openLocalModal,
    openLocalDialog,
    setPreviewPanneau
}) => {
    const { useState } = React;
    const [isSaving, setIsSaving] = useState(false);

    // RÉCUPÉRATION DES ICÔNES
    const {
        PlusIcon, AlertTriangleIcon, UsersIcon, CheckCircleIcon, XIcon,
        MessageSquareIcon, EyeIcon, ShieldCheckIcon, EditIcon, UserCircleIcon,
        ActivityIcon
    } = window.pano_getIcons();
    
    // COMPOSANTS GLOBAUX
    const StatCard = window.pano_StatCard || (() => null);
    const SimpleBarChart = window.pano_SimpleBarChart || (() => null);
    const IconBadge = window.pano_IconBadge || (() => null);
    const Button = window.pano_Button || (() => null);

    // DROITS ET ACCÈS
    const { pendingInvites, visiblePanels } = window.pano_getPanelAccessRights 
        ? window.pano_getPanelAccessRights(data.panneaux || [], myClientData.id) 
        : { pendingInvites:[], visiblePanels:[] };
        
    const activePanneauxCount = visiblePanels.filter(c => c.status === 'Actif').length;
    const draftPanneauxCount = visiblePanels.filter(c => c.status === 'Brouillon').length;

    const isSuspended = myClientData.paymentStatus === 'suspended';
    const purchasesAllowed = data.settings?.allow_new_purchases !== '0';
    
    const totalUnread = window.pano_computeClientUnread 
        ? window.pano_computeClientUnread(data.interactions || [], myClientData, visiblePanels, pendingInvites) 
        : 0;

    // HANDLERS
    const respondToInvite = async (panneauId, action) => {
        const d = await window.pano_apiFetch('panneaux/collaborators/respond', {
            body: { panneau_id: panneauId, action },
            setLoading: setIsSaving,
            successMessage: "Invitation " + (action === 'accept' ? 'acceptée' : 'refusée') + " avec succès."
        });
        if (d) refreshData();
    };

    return (
        <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4">
            <div className="flex flex-col md:flex-row justify-between gap-4 items-start md:items-center">
                <div>
                    <h1 className="text-3xl font-black text-slate-800">Bienvenue, {myClientData.full_name || myClientData.name || 'Client'}</h1>
                    <p className="text-slate-500 font-medium">Gérez vos obligations légales BTP en toute simplicité sur <a href="https://eco-panneau.fr" target="_blank" rel="noopener noreferrer" className="text-emerald-600 hover:underline font-bold">eco-panneau.fr</a>.</p>
                </div>
                {!isSuspended && purchasesAllowed && (
                    <Button variant="primary" icon={PlusIcon} className="uppercase tracking-widest px-6 py-3 rounded-xl" onClick={() => { 
                        const newPanneauId = 'pan_' + (typeof crypto !== 'undefined' && crypto.randomUUID ? crypto.randomUUID().replace(/-/g, '').substring(0, 12) : Date.now().toString(36) + Math.random().toString(36).substring(2, 8));
                        setManagingPanneau({ id: newPanneauId, name: '', location: '', permitNumber: '', status: 'Brouillon', offerType: 'rental', currentRate: data.prices?.rentalMo ?? 180, physicalPanels: 0, hasNoAds: false, privateDocs: [], shippingAddress: '', client_uid: myClientData.id }); 
                        setValidationErrors([]); 
                        openLocalModal('editor', newPanneauId); 
                    }}>
                        Nouveau panneau
                    </Button>
                )}
            </div>

            {(!purchasesAllowed) && (
                <div className="bg-blue-50 text-blue-800 p-4 rounded-2xl border border-blue-200 shadow-sm flex items-center gap-3">
                    <AlertTriangleIcon size={24} className="shrink-0" />
                    <p className="text-sm font-bold">La validation de nouvelles commandes est temporairement suspendue. Vous pouvez toujours préparer vos brouillons.</p>
                </div>
            )}
            
            {isSuspended && (
                <div className="bg-red-50 border-2 border-red-200 p-6 rounded-2xl flex items-start gap-4">
                    <AlertTriangleIcon size={32} className="text-red-600 shrink-0"/>
                    <div>
                        <h3 className="font-black text-red-800 text-lg">Facture impayée - compte suspendu</h3>
                        <p className="text-red-700 text-sm mt-1">L'édition de vos panneaux est temporairement bloquée. Veuillez régulariser votre situation dans l'onglet Factures.</p>
                        <Button variant="dangerSolid" className="mt-3 px-4 py-2 rounded-xl" onClick={() => setActiveTab('billing')}>
                            Régulariser maintenant
                        </Button>
                    </div>
                </div>
            )}

            {pendingInvites.length > 0 && (
                <div className="mb-8 space-y-4 animate-in slide-in-from-top-4">
                    <h2 className="text-xl font-black text-slate-800 flex items-center gap-2">
                        <UsersIcon size={20} className="text-blue-600" />
                        Invitations en attente
                    </h2>
                    <div className="grid grid-cols-[repeat(auto-fit,minmax(300px,1fr))] gap-4">
                        {pendingInvites.map(p => {
                            const collab = p.collaborators?.find(c => c.uid === myClientData.id);
                            return (
                                <div key={p.id} className="bg-white p-5 rounded-2xl shadow-sm border border-blue-200 flex flex-col gap-3">
                                    <div className="flex items-start gap-3">
                                        {IconBadge && <IconBadge icon={UsersIcon} variant="info" size="md" className="shrink-0" />}
                                        <div className="flex-1">
                                            <h3 className="font-black text-blue-900 leading-tight truncate">{p.name}</h3>
                                            <p className="text-xs text-slate-600 mt-1">
                                                Invitation de <strong className="font-bold text-slate-800">{collab?.inviter_name || 'le propriétaire'}</strong> ({collab?.inviter_company || 'Société'})
                                            </p>
                                        </div>
                                    </div>
                                    <div className="flex flex-wrap gap-2 mt-2">
                                        <Button variant="secondary" icon={EyeIcon} onClick={() => { setPreviewPanneau(p); openLocalModal('preview', p.id); }} className="flex-1 py-2 rounded-xl">Aperçu</Button>
                                        <Button variant="info" icon={MessageSquareIcon} onClick={() => {
                                            const u = new URL(window.location);
                                            u.searchParams.set('chat_id', `GROUP_${p.id}`);
                                            window.history.pushState({ chat_id: `GROUP_${p.id}` }, '', u);
                                            window.dispatchEvent(new Event('popstate'));
                                        }} className="flex-1 py-2 rounded-xl text-xs justify-center">Messagerie</Button>
                                        <Button variant="primary" icon={CheckCircleIcon} onClick={() => respondToInvite(p.id, 'accept')} disabled={isSaving} className="flex-1 py-2 rounded-xl">Accepter</Button>
                                        <Button variant="danger" icon={XIcon} onClick={() => respondToInvite(p.id, 'reject')} disabled={isSaving} className="flex-1 py-2 rounded-xl">Refuser</Button>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </div>
            )}

            <div className="grid grid-cols-[repeat(auto-fit,minmax(240px,1fr))] gap-4">
                {StatCard && (
                    <>
                        <StatCard title="Panneaux actifs" value={activePanneauxCount} icon={<ShieldCheckIcon size={24}/>} variant="success" onClick={() => setActiveTab('panels')} />
                        <StatCard title="Brouillons" value={draftPanneauxCount} icon={<EditIcon size={24}/>} variant="secondary" onClick={() => setActiveTab('panels')} />
                        <StatCard title="Scans riverains" value={data.stats?.totalViews || 0} icon={<UserCircleIcon size={24}/>} variant="info" />
                        <StatCard title="Messages" value={totalUnread} icon={<MessageSquareIcon size={24}/>} variant="warning" onClick={() => setActiveTab('messages')} />
                    </>
                )}
            </div>

            {data.stats?.history && data.stats.history.length > 0 && SimpleBarChart && (
                <div className="bg-white p-6 rounded-3xl border border-slate-200 shadow-sm mt-6">
                    <h3 className="font-black text-slate-800 mb-6 flex items-center gap-2">
                        <ActivityIcon size={18} className="text-emerald-600"/> 
                        Activité des riverains (30 derniers jours)
                    </h3>
                    <SimpleBarChart data={data.stats.history} />
                </div>
            )}
        </div>
    );
};

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