/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Interface Client - Onglet : Livraisons
 * =========================================================================
 */

window.pano_ClientLivraisonsTab = ({ data, myClientData, refreshData, showToast, activeModal, targetId, openLocalModal, closeCurrentLayer }) => {
    const { useState, useEffect, useMemo } = React;
    const [isSaving, setIsSaving] = useState(false);
    const [rejectReason, setRejectReason] = useState('');
    
    const {
        PackageIcon, MapPinIcon, CheckCircleIcon, ExternalLinkIcon, LoaderIcon, AlertTriangleIcon, EyeIcon, XIcon, PlusIcon
    } = window.pano_getIcons();

    const Modal = window.pano_Modal || (() => null);
    const StatusBadge = window.pano_StatusBadge || (({status}) => <span className="text-xs font-bold">{status}</span>);
    const IconBadge = window.pano_IconBadge || (() => null);
    const Button = window.pano_Button || (() => null);
    const ExternalLinkIconComp = window.pano_getIcons ? window.pano_getIcons().ExternalLinkIcon : (() => null);
    const CardGrid = window.pano_CardGrid || (({children, className}) => <div className={`grid gap-4 ${className}`}>{children}</div>);
    const DataCard = window.pano_DataCard || (({children, className, variant}) => <div className={`bg-white rounded-3xl p-5 shadow-sm border border-slate-200 flex flex-col gap-4 ${className} ${variant === 'warning' ? 'border-amber-300 bg-amber-50/50' : 'border-slate-200'}`}>{children}</div>);

    const SearchBar = window.pano_SearchBar || (() => null);
    const EmptySearch = window.pano_EmptySearch || (() => null);
    const PaginationFooter = window.pano_PaginationFooter || (() => null);

    const deliveryConfirmModal = activeModal === 'delivery_confirm' ? targetId : null;
    const rejectA1Target = activeModal === 'reject_a1' ? data.panneaux?.find(c => c.id === targetId) : null;
    
    const { visiblePanels } = window.pano_getPanelAccessRights ? window.pano_getPanelAccessRights(data.panneaux || [], myClientData.id) : { visiblePanels:[] };
    
    const deliveries = visiblePanels.filter(c => c.physicalPanels > 0 && c.status !== 'Brouillon');

    const { 
        searchQuery, setSearchQuery, 
        visibleCount, setVisibleCount, 
        filteredData: filteredDeliveries 
    } = window.pano_useSearchAndPagination(deliveries, (c, q) => {
        return (c.name && c.name.toLowerCase().includes(q)) ||
               (c.shippingAddress && c.shippingAddress.toLowerCase().includes(q)) ||
               (c.location && c.location.toLowerCase().includes(q)) ||
               (c.tracking_number && c.tracking_number.toLowerCase().includes(q)) ||
               (c.shipping_status && c.shipping_status.toLowerCase().includes(q)); 
    });

    const attentionDeliveries = [];
    const otherDeliveries = [];

    filteredDeliveries.forEach(c => {
        if (c.shipping_status === 'Expédié' || c.shipping_status === 'Attente validation client') {
            attentionDeliveries.push(c);
        } else {
            otherDeliveries.push(c);
        }
    });

    const displayedOtherDeliveries = otherDeliveries.slice(0, visibleCount);

    useEffect(() => {
        const url = new URL(window.location);
        const confirmDelivery = url.searchParams.get('confirm_delivery');
        if (confirmDelivery) {
            url.searchParams.delete('confirm_delivery');
            window.history.replaceState({}, '', url);
            openLocalModal('delivery_confirm', confirmDelivery);
        }
    }, []);

    const handleConfirmDelivery = async () => {
        if (!deliveryConfirmModal) return;
        const d = await window.pano_apiFetch('panneaux/shipping', { body: { id: deliveryConfirmModal, shipping_status: 'Réception confirmée' }, setLoading: setIsSaving, successMessage: "Réception confirmée !" });
        if (d) { refreshData(); closeCurrentLayer(); }
    };

    const renderDeliveryCard = (c) => {
        const variant = c.shipping_status === 'Attente validation client' ? 'warning' : 'default';

        return (
            <DataCard key={c.id} variant={variant}>
                <div className="flex gap-4 items-start">
                    <IconBadge icon={c.shipping_status === 'Réception confirmée' ? CheckCircleIcon : PackageIcon} variant={c.shipping_status === 'Réception confirmée' ? 'success' : (c.shipping_status === 'Attente validation client' ? 'warning' : 'info')} size="lg" />
                    <div className="min-w-0 flex-1"><p className="font-black text-base text-slate-800 break-words leading-tight">{c.name}</p></div>
                </div>
                
                <div className="p-3 rounded-xl bg-slate-50 border border-slate-100">
                    <div className="flex justify-between items-center mb-1">
                        <p className="text-[10px] font-bold uppercase tracking-widest text-slate-500">Statut</p>
                        <StatusBadge status={c.shipping_status} />
                    </div>
                </div>

                {c.shipping_status === 'Attente validation client' && (
                    <div className="mt-2 space-y-2">
                        <div className="bg-amber-50 text-amber-800 p-4 rounded-xl border border-amber-200 text-sm">
                            <p className="font-bold flex items-center gap-2"><AlertTriangleIcon size={16}/> Maquette modifiée à valider</p>
                            <p className="text-xs mt-2 leading-relaxed">Notre équipe a généré une nouvelle maquette pour votre projet. Veuillez la contrôler et la valider formellement pour lancer l'impression.</p>
                        </div>
                        {c.a1PdfId && (
                            <Button variant="secondary" icon={EyeIcon} onClick={() => window.open(`${window.pano_CONFIG.apiBaseUrl}file/download&type=pdf&id=${c.a1PdfId}`, '_blank')} className="w-full py-2.5 bg-white">Consulter le PDF de contrôle</Button>
                        )}
                        <div className="flex gap-2">
                            <Button variant="danger" icon={XIcon} onClick={() => { setRejectReason(''); openLocalModal('reject_a1', c.id); }} disabled={isSaving} className="flex-1 py-2.5 shadow-none bg-white border-none">Refuser</Button>
                            <Button variant="successSolid" icon={CheckCircleIcon} onClick={async () => {
                                const d = await window.pano_apiFetch('panneaux/client_validate_a1', { body: { id: c.id, action: 'accept' }, setLoading: setIsSaving, successMessage: "Maquette validée !" });
                                if (d) refreshData();
                            }} disabled={isSaving} className="flex-[2] py-2.5 text-xs">Valider l'impression</Button>
                        </div>
                    </div>
                )}

                {c.shipping_status === 'Expédié' && (
                    <div className="text-center bg-white p-3 rounded-xl border border-slate-200 mt-1 shadow-inner">
                        <p className="text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-2">En acheminement</p>
                        <div className="flex items-center justify-center gap-2">
                            {c.tracking_number ? (
                                <p className="text-sm font-mono text-blue-600 font-bold break-words select-all">{c.tracking_number}</p>
                            ) : (
                                <p className="text-sm font-bold text-slate-600">Votre commande est en route.</p>
                            )}
                            {c.tracking_link && (
                                <Button 
                                    variant="info" 
                                    shape="square" 
                                    icon={ExternalLinkIconComp} 
                                    onClick={() => window.open(c.tracking_link.startsWith('http') ? c.tracking_link : `https://${c.tracking_link}`, '_blank')} 
                                    className="p-1.5 shadow-none shrink-0" 
                                    title="Suivre mon colis en ligne" 
                                />
                            )}
                        </div>
                    </div>
                )}
                
                {c.shipping_status === 'Expédié' && (
                    <Button variant="primary" icon={CheckCircleIcon} onClick={() => openLocalModal('delivery_confirm', c.id)} disabled={isSaving} className="w-full py-3 text-sm mt-3">Confirmer la réception</Button>
                )}
            </DataCard>
        );
    };

    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 items-start md:items-center gap-4">
                <div><h1 className="text-3xl font-black text-slate-800">Livraisons</h1></div>
                
                {deliveries.length > 0 && SearchBar && (
                    <div className="w-full sm:w-auto flex-1 flex justify-end gap-2">
                        <SearchBar searchQuery={searchQuery} setSearchQuery={setSearchQuery} placeholder="Rechercher (Projet, Suivi, Statut)..." />
                    </div>
                )}
            </div>
            
            {deliveries.length === 0 ? (
                <div className="text-center p-12 bg-white rounded-3xl border border-slate-200 border-dashed">
                    <PackageIcon size={48} className="mx-auto text-slate-300 mb-4" />
                    <h3 className="text-lg font-black text-slate-700">Aucune livraison</h3>
                </div>
            ) : filteredDeliveries.length === 0 ? (
                EmptySearch && <EmptySearch searchQuery={searchQuery} />
            ) : (
                <>
                    {attentionDeliveries.length > 0 && (
                        <div className="mb-10 space-y-4">
                            <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="300px">
                                {attentionDeliveries.map(c => renderDeliveryCard(c))}
                            </CardGrid>
                        </div>
                    )}

                    {otherDeliveries.length > 0 && (
                        <div className="space-y-4">
                            <h2 className="text-lg font-black text-slate-800 flex items-center gap-2 border-b border-slate-200 pb-2">
                                <PackageIcon size={20} className="text-blue-600" /> Toutes les livraisons
                            </h2>
                            <CardGrid minWidth="300px">
                                {displayedOtherDeliveries.map(c => renderDeliveryCard(c))}
                            </CardGrid>
                            
                            {PaginationFooter && (
                                <PaginationFooter 
                                    visibleCount={visibleCount} 
                                    setVisibleCount={setVisibleCount} 
                                    totalCount={otherDeliveries.length} 
                                    itemName="livraisons" 
                                />
                            )}
                        </div>
                    )}
                </>
            )}

            {deliveryConfirmModal && Modal && (
                <Modal title="Confirmation de réception" type="success" onClose={closeCurrentLayer} preventClose={isSaving} zIndex="z-[250]">
                    <div className="space-y-4">
                        <div className="bg-emerald-50 text-emerald-800 p-5 rounded-2xl border border-emerald-200 text-sm"><p className="font-black">Colis livré ?</p></div>
                        <div className="flex gap-3 mt-6">
                            <Button variant="secondary" onClick={closeCurrentLayer} disabled={isSaving} className="flex-1 py-3">Annuler</Button>
                            <Button variant="primary" onClick={handleConfirmDelivery} disabled={isSaving} icon={isSaving ? LoaderIcon : CheckCircleIcon} className="flex-1 py-3">Oui, j'ai reçu mon colis</Button>
                        </div>
                    </div>
                </Modal>
            )}

            {rejectA1Target && Modal && (
                <Modal title="Refuser la maquette" onClose={closeCurrentLayer} preventClose={isSaving} zIndex="z-[250]">
                    <form onSubmit={async (e) => {
                        e.preventDefault();
                        const d = await window.pano_apiFetch('panneaux/client_validate_a1', { body: { id: rejectA1Target.id, action: 'reject', reason: rejectReason }, setLoading: setIsSaving, successMessage: "Refus transmis à l'équipe." });
                        if (d) { refreshData(); closeCurrentLayer(); }
                    }} className="space-y-4">
                        <div className="space-y-2">
                            <label className="text-xs font-bold text-slate-500 uppercase block">Motif du refus (Explications) <span className="text-red-500">*</span></label>
                            <textarea 
                                required 
                                rows={4}
                                value={rejectReason} 
                                onChange={e => setRejectReason(e.target.value)} 
                                className="w-full border-2 border-slate-200 rounded-xl p-3 focus:border-red-500 outline-none transition font-medium" 
                                placeholder="Ex: Le numéro de permis est incorrect, la couleur du fond ne correspond pas..." 
                                autoFocus
                            />
                        </div>
                        <div className="flex gap-3 pt-4 border-t border-slate-100">
                            <Button variant="secondary" type="button" onClick={closeCurrentLayer} disabled={isSaving} className="flex-1 py-3 justify-center">Annuler</Button>
                            <Button type="submit" variant="dangerSolid" disabled={isSaving || !rejectReason.trim()} className="flex-1 py-3 uppercase tracking-widest justify-center text-xs">Confirmer le refus</Button>
                        </div>
                    </form>
                </Modal>
            )}
        </div>
    );
};

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