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

window.pano_ClientInvoicesTab = ({ data, openLocalDialog, closeCurrentLayer, activeDialog, dialogId, clientOpts, toggleDashboardPin, setArchiveConfig, refreshData }) => {
    const { useState, useEffect, useMemo } = React;
    
    // SÉCURITÉ ANTI-FUITE DE MÉMOIRE : Utilisation du Hook Global Zéro-Dette
    const { isMounted, safeFetch } = window.pano_useSafeFetch();
    
    // 1. - Routage Zéro-Dette et Modales
    const urlModal = window.pano_useUrlModal ? window.pano_useUrlModal() : {};
    
    const routerActiveDialog = activeDialog || urlModal.activeDialog;
    const routerDialogId = dialogId || urlModal.dialogId;
    const routerOpenDialog = openLocalDialog || urlModal.openDialog;
    const routerCloseLayer = closeCurrentLayer || urlModal.closeCurrentLayer;

    // 2. - États de téléchargement local
    const [downloadedInvoices, setDownloadedInvoices] = useState(() => {
        try { return JSON.parse(localStorage.getItem('pano_downloaded_invoices') || '[]'); } catch(e) { return []; }
    });
    const [previewInvoice, setPreviewInvoice] = useState(null);
    const [isSaving, setIsSaving] = useState(false);

    // Synchronisation multi-onglets pour la pastille "Non lu"
    useEffect(() => {
        const handleUpdate = () => {
            try { setDownloadedInvoices(JSON.parse(localStorage.getItem('pano_downloaded_invoices') || '[]')); } catch(e) {}
        };
        window.addEventListener('invoice_downloaded', handleUpdate);
        return () => window.removeEventListener('invoice_downloaded', handleUpdate);
    }, []);

    // 3. - Icônes et Composants
    const { FileTextIcon, DownloadIcon, InfoIcon, PinIcon, AlertTriangleIcon, EyeIcon, ArchiveIcon } = window.pano_getIcons();
    const { 
        Button, Modal, CardGrid, DataCard, 
        SearchBar, EmptySearch, PaginationFooter, UniversalViewer, ArchiveGeneratorModal
    } = window.pano_getComponents();

    // 4. - Données et Filtrage (Limité à 500 pour les performances)
    const invoices = data.invoices || [];

    const { 
        searchQuery, setSearchQuery, 
        visibleCount, setVisibleCount, 
        filteredData: filteredInvoices 
    } = window.pano_useSearchAndPagination(invoices, (inv, q) => {
        const n = window.pano_normalizeString;
        const dateStr = window.pano_formatDate ? window.pano_formatDate(inv.created_at) : new Date(String(inv.created_at || '').replace(' ', 'T')).toLocaleDateString('fr-FR');
        
        return n(inv.invoice_ref || inv.invoiceNumber).includes(q) || 
               n(inv.type).includes(q) || 
               n(inv.amount).includes(q) || 
               n(dateStr).includes(q) || 
               n(inv.panneauName).includes(q);
    });

    const MAX_DISPLAY = 500;
    const isLimited = filteredInvoices.length > MAX_DISPLAY;
    const effectiveInvoices = isLimited ? filteredInvoices.slice(0, MAX_DISPLAY) : filteredInvoices;

    const pinnedIds = clientOpts?.pinned_invoices || [];
    
    const attentionInvoices = [];
    const pinnedInvoices = [];
    const otherInvoices = [];

    // CLASSIFICATION : URGENCE > FAVORIS > RESTE
    effectiveInvoices.forEach(inv => {
        const invRef = inv.invoice_ref || inv.invoiceNumber;
        const isUnread = !downloadedInvoices.includes(invRef);
        const isPinned = pinnedIds.includes(invRef);

        if (isUnread) {
            attentionInvoices.push(inv);
        } else if (isPinned) {
            pinnedInvoices.push(inv);
        } else {
            otherInvoices.push(inv);
        }
    });

    const displayedOtherInvoices = otherInvoices.slice(0, visibleCount);

    // 5. - Actions métier
    const handleDownload = (invRef) => {
        if (!downloadedInvoices.includes(invRef)) {
            const newArr = [...downloadedInvoices, invRef];
            setDownloadedInvoices(newArr);
            localStorage.setItem('pano_downloaded_invoices', JSON.stringify(newArr));
            window.dispatchEvent(new CustomEvent('invoice_downloaded'));
        }
        // Sécurité SPA : Protection contre le kill de l'App par le navigateur
        window.open(`${window.pano_CONFIG.apiBaseUrl}invoices/download&ref=${invRef}`, '_blank');
    };

    const targetInvoice = routerActiveDialog === 'invoice_details' && routerDialogId ? invoices.find(i => (i.invoice_ref || i.invoiceNumber) === routerDialogId) : null;

    // 6. - Rendu des cartes (Factures)
    const renderInvoiceCard = (inv, keyPrefix) => {
        const invRef = inv.invoice_ref || inv.invoiceNumber;
        const isUnread = !downloadedInvoices.includes(invRef);
        const isPinned = pinnedIds.includes(invRef);
        const isAvoir = inv.type.includes('Avoir') || parseFloat(inv.amount) < 0;

        return (
            <DataCard key={`${keyPrefix}_${invRef}`} className={`relative group transition flex flex-col h-full p-4 min-w-0 ${isUnread ? 'border-emerald-300 shadow-md ring-2 ring-emerald-500/20' : 'hover:border-slate-300'}`}>
                {/* ÉPINGLE VOLANTE ET INCLINÉE */}
                <div 
                    role="button" 
                    tabIndex={0} 
                    onClick={(e) => { e.stopPropagation(); toggleDashboardPin && toggleDashboardPin('pinned_invoices', invRef, e); }} 
                    className={`absolute top-2 right-2 z-20 p-1 cursor-pointer transition-all duration-200 ${isPinned ? 'text-amber-500 opacity-100 hover:scale-110' : 'text-slate-300 opacity-0 group-hover:opacity-100 hover:text-slate-500 hover:scale-110'}`}
                    style={{ transform: 'rotate(30deg)' }}
                    title={isPinned ? "Désépingler" : "Épingler au tableau de bord"}
                >
                    <PinIcon size={18} filled={isPinned} />
                </div>

                {isUnread && <span className="absolute -top-2 -left-2 bg-emerald-500 text-white text-[10px] font-black uppercase tracking-widest px-2 py-1 rounded-full shadow-sm animate-pulse z-10">Nouvelle</span>}
                
                <div className="flex justify-between items-start gap-2 min-w-0">
                    <div className="min-w-0">
                        <span className="text-[10px] uppercase tracking-widest text-slate-400 font-bold block mb-1">Date</span>
                        <span className="text-sm font-bold text-slate-700">{window.pano_formatDate ? window.pano_formatDate(inv.created_at) : new Date(String(inv.created_at || '').replace(' ', 'T')).toLocaleDateString('fr-FR')}</span>
                    </div>
                    <div className="flex flex-col items-end gap-1 shrink-0 relative z-10 mr-6">
                        <div className="text-right min-w-0">
                            <span className="text-[10px] uppercase tracking-widest text-slate-400 font-bold block mb-1">Montant</span>
                            <span className={`text-sm font-black break-words ${isAvoir ? 'text-amber-600' : 'text-slate-800'}`}>{inv.amount} €</span>
                        </div>
                    </div>
                </div>
                
                {/* BLOC CENTRAL : Information par Exception (Silence si pas de projet) */}
                <div className="pt-2 border-t border-slate-100 flex-1 flex flex-col mt-2 min-w-0">
                    {inv.panneauName && (
                        <>
                            <span className="text-[10px] uppercase tracking-widest text-slate-400 font-bold block mb-1 break-words">Projet concerné</span>
                            <span className="text-sm font-black text-emerald-700 break-words leading-tight block mb-2">{inv.panneauName}</span>
                        </>
                    )}
                    <span className="text-[10px] font-medium text-slate-500 break-words leading-tight mt-auto pt-2 block">
                        {inv.type.replace(/\s*\(PI:[^)]+\)/, '')} (Réf. {invRef})
                    </span>
                </div>
                
                {/* ACTIONS : Masquées tant que la facture n'est pas téléchargée */}
                <div className="flex justify-end gap-2 pt-3 mt-auto border-t border-slate-100 min-w-0">
                    {!isUnread && (
                        <>
                            <Button variant="secondary" shape="square" icon={InfoIcon} onClick={() => routerOpenDialog('invoice_details', invRef, false)} title="Détails" className="p-2 bg-white shadow-sm border-slate-200 shrink-0" />
                            <Button variant="secondary" shape="square" icon={EyeIcon} onClick={() => setPreviewInvoice(invRef)} title="Aperçu de la facture" className="p-2 bg-white shadow-sm border-slate-200 shrink-0" />
                        </>
                    )}
                    <Button variant="primary" icon={DownloadIcon} onClick={() => handleDownload(invRef)} className="flex-1 py-2 text-xs uppercase tracking-widest justify-center shadow-md text-center">
                        Télécharger
                    </Button>
                </div>
            </DataCard>
        );
    };

    // 7. - Rendu UI
    return (
        <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 min-w-0 w-full overflow-x-hidden">
            <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">Factures et avoirs</h1>
                    <p className="text-slate-500 font-medium break-words">Retrouvez l'historique de vos paiements et abonnements.</p>
                </div>
                
                {invoices.length > 0 && SearchBar && (
                    <div className="relative w-full lg:w-96 flex-1 max-w-md shrink-0">
                        <SearchBar 
                            searchQuery={searchQuery} 
                            setSearchQuery={setSearchQuery} 
                            placeholder="Rechercher (Réf, Projet, Montant)..." 
                        />
                    </div>
                )}

                {/* CORRECTION SÉCURITÉ UI : Masquage conditionnel des boutons d'export */}
                {invoices.length > 0 && (
                    <div className="flex gap-2 shrink-0 w-full lg:w-auto">
                        <Button variant="outline" icon={ArchiveIcon} onClick={() => { setArchiveConfig({ type: 'factures' }); routerOpenDialog('archive_config', null, false); }} className="py-2.5 flex-1 lg:flex-none justify-center" title="Exporter toutes vos factures en ZIP sécurisé">
                            <span className="hidden sm:inline">Export ZIP sécurisé</span>
                            <span className="sm:hidden">ZIP</span>
                        </Button>
                        <Button variant="outline" icon={DownloadIcon} onClick={() => window.open(window.pano_CONFIG.apiBaseUrl + "invoices/export_csv", '_blank')} className="py-2.5 flex-1 lg:flex-none justify-center" title="Exporter le listing tableur (CSV)">
                            Export CSV
                        </Button>
                    </div>
                )}
            </div>
            
            {invoices.length === 0 ? (
                <div className="p-12 text-center text-slate-500 bg-white rounded-3xl border border-slate-200 border-dashed min-w-0">
                    {FileTextIcon && <FileTextIcon size={48} className="mx-auto text-slate-300 mb-4" />}
                    <p className="font-medium break-words">Aucune facture n'a encore été générée pour votre compte.</p>
                </div>
            ) : filteredInvoices.length === 0 ? (
                EmptySearch && <EmptySearch searchQuery={searchQuery} />
            ) : (
                <>
                    {/* A. PRIORITÉ (FACTURES NON TÉLÉCHARGÉES) */}
                    {attentionInvoices.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 break-words">
                                <AlertTriangleIcon size={20} className="text-amber-500 shrink-0" /> Factures non téléchargées
                            </h2>
                            <CardGrid minWidth="300px">
                                {attentionInvoices.map((inv, i) => renderInvoiceCard(inv, `att_${i}`))}
                            </CardGrid>
                        </div>
                    )}

                    {/* B. FAVORIS */}
                    {pinnedInvoices.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 break-words">
                                <PinIcon size={20} className="text-emerald-600 shrink-0" filled /> Favoris (Épinglés)
                            </h2>
                            <CardGrid minWidth="300px">
                                {pinnedInvoices.map((inv, i) => renderInvoiceCard(inv, `pin_${i}`))}
                            </CardGrid>
                        </div>
                    )}

                    {/* C. LE RESTE */}
                    {otherInvoices.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 break-words">
                                <FileTextIcon size={20} className="text-blue-600 shrink-0" /> Historique complet
                            </h2>
                            <CardGrid minWidth="300px">
                                {displayedOtherInvoices.slice(0, visibleCount).map((inv, i) => renderInvoiceCard(inv, `oth_${i}`))}
                            </CardGrid>

                            {PaginationFooter && (
                                <PaginationFooter 
                                    visibleCount={visibleCount} 
                                    setVisibleCount={setVisibleCount} 
                                    totalCount={otherInvoices.length} 
                                    itemName="factures" 
                                />
                            )}
                        </div>
                    )}

                    {isLimited && (
                        <div className="p-5 mt-4 bg-blue-50 border border-blue-200 rounded-xl text-center shadow-inner min-w-0">
                            <p className="text-sm text-blue-900 font-black mb-1 break-words">L'affichage est limité aux {MAX_DISPLAY} résultats les plus récents pour garantir les performances.</p>
                            <p className="text-xs text-blue-700 font-medium break-words leading-relaxed">Pour consulter l'intégralité de votre facturation, veuillez télécharger un export (ZIP ou CSV) via les boutons ci-dessus.</p>
                        </div>
                    )}
                </>
            )}

            {/* Modales contextuelles */}
            {routerActiveDialog === 'archive_config' && archiveConfig && ArchiveGeneratorModal && (
                <ArchiveGeneratorModal 
                    type={archiveConfig.type}
                    panelId={archiveConfig.panelId}
                    onClose={routerCloseLayer} 
                    refreshData={refreshData} 
                />
            )}

            {routerActiveDialog === 'invoice_details' && targetInvoice && Modal && (
                <Modal 
                    title={`Détails facture - ${targetInvoice.invoice_ref || targetInvoice.invoiceNumber}`} 
                    onClose={routerCloseLayer} 
                    actions={(close) => (
                        <Button variant="primary" icon={DownloadIcon} onClick={() => { handleDownload(targetInvoice.invoice_ref || targetInvoice.invoiceNumber); close(); }} className="w-full py-3 uppercase tracking-widest justify-center shadow-md text-xs">
                            Télécharger le PDF
                        </Button>
                    )}
                >
                    <div className="space-y-4 min-w-0 overflow-x-hidden">
                        <div className="bg-slate-50 p-4 rounded-xl border border-slate-200 min-w-0">
                            <div className="grid grid-cols-2 gap-4 min-w-0">
                                <div className="min-w-0">
                                    <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest break-words">Date d'émission</p>
                                    <p className="text-sm font-black text-slate-700 mt-1 break-words leading-tight">{window.pano_formatDate ? window.pano_formatDate(targetInvoice.created_at) : targetInvoice.created_at}</p>
                                </div>
                                <div className="min-w-0">
                                    <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest break-words">Montant TTC</p>
                                    <p className={`text-sm font-black mt-1 break-words leading-tight ${targetInvoice.type.includes('Avoir') || parseFloat(targetInvoice.amount) < 0 ? 'text-amber-600' : 'text-slate-800'}`}>{targetInvoice.amount} €</p>
                                </div>
                                
                                {targetInvoice.panneauName && (
                                    <div className="col-span-2 min-w-0">
                                        <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest break-words">Projet concerné</p>
                                        <p className="text-sm font-bold text-emerald-700 mt-1 break-words leading-tight">{targetInvoice.panneauName}</p>
                                    </div>
                                )}

                                <div className="col-span-2 min-w-0">
                                    <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest break-words">Objet / Description</p>
                                    <p className="text-xs text-slate-600 mt-1 break-words leading-relaxed">{targetInvoice.type.replace(/\s*\(PI:[^)]+\)/, '')}</p>
                                </div>
                            </div>
                        </div>
                        
                        <div className="bg-blue-50 p-4 rounded-xl border border-blue-200 text-sm text-blue-800 font-medium min-w-0">
                            <p className="break-words leading-relaxed">
                                En cas de question sur cette facturation, vous pouvez contacter le support depuis l'onglet <strong>Mon compte</strong>.
                            </p>
                        </div>
                    </div>
                </Modal>
            )}

            {previewInvoice && UniversalViewer && (
                <UniversalViewer 
                    fileUrl={`${window.pano_CONFIG.apiBaseUrl}invoices/download&ref=${previewInvoice}`}
                    fileType="pdf"
                    fileName={`Facture ${previewInvoice}`}
                    positionClass="fixed"
                    useSafePdfMode={false}
                    onClose={() => setPreviewInvoice(null)}
                />
            )}
        </div>
    );
};

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