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

const { useState, useEffect, useRef } = React;

window.pano_ClientCheckoutModal = ({ managingPanneau, setManagingPanneau, data, myClientData, onClose, onBackToEditor, refreshData, showToast, onGoToBilling }) => {
    
    // ZÉRO-DETTE : Utilisation de notre Hook abstrait !
    const { isMounted, safeFetch } = window.pano_useSafeFetch();

    // 1. - Composants et Icônes
    const {
        XIcon, AlertTriangleIcon, PackageIcon, LoaderIcon, CreditCardIcon, MinusIcon, PlusIcon, CheckCircleIcon, DownloadIcon, FileTextIcon, ShieldAlertIcon
    } = window.pano_getIcons();
    
    const { StripeElements, ModalOverlay, AlertBox, Button, CardGrid } = window.pano_getComponents();
    
    // 2. - États locaux
    const [step, setStep] = useState('select');
    const [paymentData, setPaymentData] = useState(null);
    const [waiverAccepted, setWaiverAccepted] = useState(false);
    const [isSaving, setIsSaving] = useState(false);
    
    // États pour le polling de la facture
    const [latestInvoiceRef, setLatestInvoiceRef] = useState(null);
    const [isPollingInvoice, setIsPollingInvoice] = useState(false);
    const pollCountRef = useRef(0);
    const pollIntervalRef = useRef(null);

    // 3. - Variables de tarification et d'état sécurisées
    const pCible = managingPanneau || {};
    
    const isSuspended = myClientData?.paymentStatus === 'suspended';
    
    // VÉRIFICATIONS DES RÈGLES DE BLOCAGE
    const rawAllow = data.settings?.allow_new_purchases ?? window.pano_CONFIG?.allow_new_purchases ?? window.pano_CONFIG?.settings?.allow_new_purchases;
    const purchasesAllowed = rawAllow === '1';
    
    const isAdminView = window.pano_CONFIG?.role === 'admin' || data.role === 'admin';

    const pRental = data.prices?.rentalMo ?? 180;
    const pPurchase = data.prices?.purchase ?? 850;
    const pBoardFirst = data.prices?.boardFirst ?? 250;
    const pBoardAdd = data.prices?.boardAdd ?? 150;
    const pNoAds = data.prices?.noAds ?? 150;

    const originalPanneau = data.panneaux?.find(p => p.id === pCible.id);
    const isActif = originalPanneau?.status === 'Actif';
    const originalOfferType = originalPanneau?.offerType || 'rental';
    const originalPanels = originalPanneau?.physicalPanels || 0;
    const originalHasNoAds = originalPanneau?.hasNoAds || false;

    const currentOfferType = pCible.offerType || 'rental';
    const currentPanels = pCible.physicalPanels || 0;
    const currentHasNoAds = pCible.hasNoAds || false;

    // SÉCURITÉ : Cristallisation du coût unitaire au moment de la commande
    const totalPhysicalPanelsCost = currentPanels > 0 ? pBoardFirst + (currentPanels - 1) * pBoardAdd : 0;

    let addedPanelsCost = 0;
    if (currentPanels > originalPanels) {
        const costNew = totalPhysicalPanelsCost;
        const costOld = originalPanels > 0 ? pBoardFirst + (originalPanels - 1) * pBoardAdd : 0;
        addedPanelsCost = Math.max(0, costNew - costOld);
    }

    let discountableHT = 0;
    let nonDiscountableHT = 0;

    if (!isActif) {
        nonDiscountableHT = totalPhysicalPanelsCost;
        discountableHT = (currentHasNoAds ? pNoAds : 0) + (currentOfferType === 'rental' ? pRental : pPurchase);
    } else {
        if (originalOfferType === 'rental' && currentOfferType === 'purchase') discountableHT += pPurchase;
        if (currentHasNoAds && !originalHasNoAds) discountableHT += pNoAds;
        nonDiscountableHT = addedPanelsCost;
    }

    const upfrontHT = discountableHT + nonDiscountableHT;

    const discountPct = myClientData?.discount || 0;
    const priceMultiplier = Math.max(0, (100 - discountPct) / 100);
    const discountAmount = discountableHT * (discountPct / 100);
    const discountedHT = upfrontHT - discountAmount;

    const platformHasTva = data.settings?.billing_has_tva !== '0';
    const tvaMult = platformHasTva ? 1.20 : 1.00;
    
    const finalUpfrontTTC = discountedHT * tvaMult;
    const finalMonthlyTTC = pRental * priceMultiplier * tvaMult;
    const remainingToPay = Math.max(0, finalUpfrontTTC - (myClientData?.wallet_balance || 0));

    // CORRECTION SÉCURITÉ 3D SECURE : Vérification au montage si l'on revient d'un paiement validé
    useEffect(() => {
        const successPiId = sessionStorage.getItem('pano_payment_success');
        if (successPiId) {
            sessionStorage.removeItem('pano_payment_success');
            setStep('success');
            startInvoicePolling(successPiId);
        }
        return () => {
            if (pollIntervalRef.current) clearInterval(pollIntervalRef.current);
        };
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    // Utilitaires de Garbage Collection
    const handleSafeClose = () => {
        sessionStorage.removeItem('pano_checkout_context');
        if (onClose) onClose();
    };

    const handleSafeBack = () => {
        sessionStorage.removeItem('pano_checkout_context');
        if (onBackToEditor) onBackToEditor();
    };

    // 4. - Actions métier
    const startInvoicePolling = (pi_id) => {
        if (!isMounted.current) return;
        setIsPollingInvoice(true);
        pollCountRef.current = 0;
        
        pollIntervalRef.current = setInterval(async () => {
            if (!isMounted.current) {
                clearInterval(pollIntervalRef.current);
                return;
            }

            pollCountRef.current += 1;
            
            const res = await safeFetch('invoices/check_by_pi', { 
                method: 'POST',
                body: { pi_id: pi_id },
                silent: true 
            });
            
            if (!isMounted.current) {
                clearInterval(pollIntervalRef.current);
                return;
            }
            
            if (res && res.status === 'success' && res.data?.invoice_ref) {
                setLatestInvoiceRef(res.data.invoice_ref);
                setIsPollingInvoice(false);
                clearInterval(pollIntervalRef.current);
                return;
            }
            
            if (pollCountRef.current >= 8) {
                setIsPollingInvoice(false);
                clearInterval(pollIntervalRef.current);
            }
        }, 2000);
    };

    const handleActivationRequest = async () => {
        if (isSuspended) return showToast("Votre compte est suspendu. Veuillez régulariser vos factures.", "error");
        if (!purchasesAllowed) return showToast("Les commandes sont temporairement suspendues.", "error");
        if (isAdminView) return showToast("En tant qu'administration, vous ne pouvez pas passer de commande.", "error");
        if (!waiverAccepted) return showToast("Veuillez accepter la renonciation au délai de rétractation.", "error");

        const detailsWithCost = { ...pCible, physicalPanelsCostHT: totalPhysicalPanelsCost };

        const payloadForIntent = { 
            panneau_id: pCible.id, 
            offer_type: currentOfferType, 
            price_type: currentOfferType === 'rental' ? 'rentalMo' : 'purchase',
            physicalPanels: currentPanels, 
            hasNoAds: currentHasNoAds 
        };

        const payloadForPaid = { 
            id: pCible.id, 
            offerType: currentOfferType, 
            currentRate: pCible.currentRate, 
            physicalPanels: currentPanels, 
            details: detailsWithCost, 
            name: pCible.name 
        };

        // CORRECTION SÉCURITÉ 3D SECURE : Sérialisation du contexte dans la session locale
        sessionStorage.setItem('pano_checkout_context', JSON.stringify(payloadForPaid));

        const d = await safeFetch('stripe/intent', { 
            body: payloadForIntent, 
            setLoading: setIsSaving
        });
        
        if (!isMounted.current) return;

        if (d) {
            if (d.data && d.data.free_activation_required) {
                const freeRes = await safeFetch('panneaux/activate_free', { 
                    body: { ...payloadForIntent, ...payloadForPaid },
                    setLoading: setIsSaving
                });
                
                if (!isMounted.current) return;

                if (freeRes) { 
                    // GARBAGE COLLECTION : Nettoyage immédiat après activation gratuite
                    sessionStorage.removeItem('pano_checkout_context');
                    setStep('success');
                    setIsPollingInvoice(false);
                    refreshData(); 
                }
            } else if (d.data && d.data.clientSecret) {
                const pi_id_extracted = d.data.clientSecret.split('_secret')[0];
                
                setPaymentData({ 
                    secret: d.data.clientSecret, 
                    pi_id: pi_id_extracted,
                    subId: d.data.subscription_id, 
                    amountCents: d.data.amountCents 
                });
                setStep('payment');
            } else {
                showToast("Erreur lors de l'initialisation du paiement.", "error");
            }
        }
    };

    const handlePaymentSuccess = async (pi_id) => {
        // GARBAGE COLLECTION : Nettoyage immédiat après paiement réussi direct
        sessionStorage.removeItem('pano_checkout_context');
        
        const active_pi = pi_id || paymentData?.pi_id;
        
        const detailsWithCost = { ...pCible, physicalPanelsCostHT: totalPhysicalPanelsCost };

        const payload = { 
            payment_intent_id: active_pi, 
            subscription_id: paymentData?.subId, 
            id: pCible.id, 
            offerType: currentOfferType, 
            currentRate: pCible.currentRate, 
            physicalPanels: currentPanels, 
            details: detailsWithCost, 
            name: pCible.name 
        };
        
        const d = await safeFetch('panneaux/activate_paid', { 
            body: payload, 
            setLoading: setIsSaving
        });
        
        if (!isMounted.current) return;

        if (d) { 
            setStep('success');
            if (active_pi) {
                startInvoicePolling(active_pi);
            }
            refreshData(); 
        } else {
            showToast("Erreur inattendue après validation du paiement.", "error");
        }
    };

    // 5. - ÉCRANS DE BLOCAGE STRICTS
    
    if (!purchasesAllowed) {
        return (
            <ModalOverlay onClose={handleSafeClose}>
                <div className="bg-white rounded-[2rem] w-full max-w-md shadow-2xl flex flex-col p-8 text-center animate-in zoom-in-95 duration-300" onMouseDown={e => e.stopPropagation()}>
                    <div className="w-20 h-20 bg-amber-100 text-amber-600 rounded-full flex items-center justify-center mx-auto mb-6">
                        {AlertTriangleIcon && <AlertTriangleIcon size={40} />}
                    </div>
                    <h2 className="text-2xl font-black text-slate-800 mb-2">Commandes suspendues</h2>
                    <p className="text-slate-500 font-medium mb-8 leading-relaxed">
                        Pour des raisons de maintenance ou de surcharge logistique, les commandes sont temporairement désactivées sur l'ensemble de la plateforme. Veuillez nous excuser pour ce désagrément et réessayer ultérieurement.
                    </p>
                    <div className="flex flex-col sm:flex-row gap-3">
                        <Button variant="secondary" onClick={handleSafeClose} className="flex-1 py-3 justify-center">Fermer</Button>
                        <Button variant="outline" onClick={handleSafeBack} className="flex-1 py-3 justify-center">Retour à l'éditeur</Button>
                    </div>
                </div>
            </ModalOverlay>
        );
    }

    if (isAdminView) {
        return (
            <ModalOverlay onClose={handleSafeClose}>
                <div className="bg-white rounded-[2rem] w-full max-w-md shadow-2xl flex flex-col p-8 text-center animate-in zoom-in-95 duration-300" onMouseDown={e => e.stopPropagation()}>
                    <div className="w-20 h-20 bg-blue-100 text-blue-600 rounded-full flex items-center justify-center mx-auto mb-6">
                        {ShieldAlertIcon ? <ShieldAlertIcon size={40} /> : <AlertTriangleIcon size={40} />}
                    </div>
                    <h2 className="text-2xl font-black text-slate-800 mb-2">Mode Administrateur</h2>
                    <p className="text-slate-500 font-medium mb-8 leading-relaxed">
                        En tant que membre de l'équipe, vous avez la possibilité de préparer et configurer des brouillons, mais <strong>seul le client final est autorisé à valider le paiement</strong> et passer la commande depuis son espace personnel.
                    </p>
                    <div className="flex flex-col sm:flex-row gap-3">
                        <Button variant="secondary" onClick={handleSafeClose} className="flex-1 py-3 justify-center">Fermer</Button>
                        <Button variant="primary" onClick={handleSafeBack} className="flex-[2] py-3 justify-center shadow-md">Continuer l'édition</Button>
                    </div>
                </div>
            </ModalOverlay>
        );
    }

    // 6. - Rendu UI : Tunnel de paiement (Étape 3) - MODALE DE SUCCÈS DÉDIÉE
    if (step === 'success') {
        return (
            <ModalOverlay onClose={handleSafeClose} preventClose={isSaving}>
                <div className="bg-white rounded-[2rem] w-full max-w-md shadow-2xl flex flex-col p-8 text-center animate-in zoom-in-95 duration-300" onMouseDown={e => e.stopPropagation()}>
                    <div className="w-20 h-20 bg-emerald-100 text-emerald-600 rounded-full flex items-center justify-center mx-auto mb-6">
                        {CheckCircleIcon && <CheckCircleIcon size={40} />}
                    </div>
                    <h2 className="text-2xl font-black text-slate-800 mb-2">Paiement validé !</h2>
                    <p className="text-slate-500 font-medium mb-6">
                        Votre panneau est désormais activé. 
                        {currentPanels > 0 ? (currentPanels > 1 ? " Les impressions ont été lancées." : " L'impression a été lancée.") : ""}
                    </p>
                    
                    <div className="bg-blue-50 border border-blue-200 rounded-xl p-4 mb-6">
                        <p className="text-sm font-bold text-blue-900">Votre facture a été générée.</p>
                        <p className="text-xs text-blue-700 mt-1">Vous pouvez la télécharger immédiatement pour votre comptabilité.</p>
                    </div>

                    <div className="flex flex-col sm:flex-row gap-3">
                        <Button variant="secondary" onClick={handleSafeClose} className="flex-1 py-3 justify-center">Fermer</Button>
                        
                        {isPollingInvoice ? (
                            <Button variant="primary" disabled={true} icon={LoaderIcon} className="flex-[2] py-3 justify-center shadow-md">
                                Préparation facture...
                            </Button>
                        ) : latestInvoiceRef ? (
                            <Button 
                                variant="primary" 
                                onClick={() => {
                                    window.open(`${window.pano_CONFIG.apiBaseUrl}invoices/download&ref=${latestInvoiceRef}`, '_blank');
                                    handleSafeClose();
                                }} 
                                icon={DownloadIcon} 
                                className="flex-[2] py-3 justify-center shadow-md"
                            >
                                Télécharger la facture
                            </Button>
                        ) : (
                            <Button variant="primary" onClick={() => { handleSafeClose(); if (onGoToBilling) onGoToBilling(); }} icon={FileTextIcon} className="flex-[2] py-3 justify-center shadow-md">
                                Voir mes factures
                            </Button>
                        )}
                    </div>
                </div>
            </ModalOverlay>
        );
    }

    // 7. - Rendu UI : Tunnel de paiement (Étape 2) - FORMULAIRE CB
    if (step === 'payment' && paymentData && StripeElements) {
        return (
            <ModalOverlay onClose={() => { setStep('select'); setPaymentData(null); }} preventClose={isSaving}>
                <div className="bg-white rounded-3xl w-full max-w-md shadow-2xl flex flex-col" onMouseDown={e => e.stopPropagation()}>
                    <div className="p-6 border-b border-slate-900 flex justify-between items-center bg-slate-900 shrink-0 rounded-t-3xl">
                        <h3 className="font-black text-white text-lg">Paiement sécurisé</h3>
                        <Button 
                            variant="ghost" 
                            icon={XIcon} 
                            onClick={() => { setStep('select'); setPaymentData(null); }} 
                            className="text-slate-400 hover:text-white hover:bg-slate-800 p-2 border-none shadow-none" 
                            title="Fermer" 
                        />
                    </div>
                    <div className="p-6">
                        <div className="bg-blue-50 text-blue-800 p-4 rounded-xl text-sm font-bold text-center mb-6 border border-blue-100">
                            Montant à régler : {(paymentData.amountCents / 100).toFixed(2)} €
                        </div>
                        <StripeElements clientSecret={paymentData.secret} onSuccess={handlePaymentSuccess} />
                    </div>
                </div>
            </ModalOverlay>
        );
    }

    // 8. - Rendu UI : Configuration de l'offre (Étape 1)
    return (
        <ModalOverlay onClose={handleSafeClose} preventClose={isSaving}>
            <div className="bg-white rounded-[2rem] w-full max-w-4xl shadow-2xl flex flex-col max-h-[95vh] animate-in zoom-in-95 duration-200" onMouseDown={e => e.stopPropagation()}>
                <div className="p-6 border-b border-slate-900 flex justify-between items-center bg-slate-900 shrink-0 rounded-t-[2rem]">
                    <div>
                        <h2 className="text-xl font-black text-white">{isActif ? "Commandes additionnelles" : "Détails de facturation"}</h2>
                        <p className="text-xs text-slate-300 font-medium">{isActif ? "Commandez de nouveaux panneaux physiques pour ce chantier." : "Configurez votre abonnement et commandez vos supports physiques."}</p>
                    </div>
                    <Button 
                        variant="ghost" 
                        icon={XIcon} 
                        onClick={() => { if(!isSaving) handleSafeClose(); }} 
                        disabled={isSaving} 
                        className="text-slate-400 hover:text-white hover:bg-slate-800 p-2 border-none shadow-none" 
                        title="Fermer" 
                    />
                </div>

                <div className="flex-1 overflow-y-auto p-6 space-y-8 custom-scrollbar">
                    
                    <div className="text-xs text-slate-500 mb-2"><span className="text-red-500 font-black">*</span> Champs obligatoires</div>

                    <CardGrid minWidth="320px">
                        <div className="space-y-4">
                            <h3 className="font-black text-slate-800 text-sm uppercase tracking-widest border-b pb-2">1. Formule d'abonnement</h3>
                            <div className="grid grid-cols-1 gap-3">
                                <label className={`relative p-4 rounded-2xl border-2 cursor-pointer transition flex flex-col gap-1 ${currentOfferType === 'rental' ? 'border-emerald-500 bg-emerald-50 shadow-sm' : 'border-slate-200 hover:border-emerald-200 hover:bg-slate-50'} ${originalOfferType === 'purchase' ? 'opacity-50 cursor-not-allowed pointer-events-none' : ''}`}>
                                    <div className="flex justify-between items-center">
                                        <div className="flex items-center gap-2">
                                            <input type="radio" name="offerType" value="rental" checked={currentOfferType === 'rental'} disabled={originalOfferType === 'purchase'} onChange={(e) => setManagingPanneau({...pCible, offerType: e.target.value, currentRate: pRental})} className="w-5 h-5 accent-emerald-600" />
                                            <span className="font-black text-slate-800 text-lg">Location mensuelle</span>
                                        </div>
                                        <span className="font-bold text-emerald-600">{pRental}€ <span className="text-xs text-emerald-600/70">/ mois</span></span>
                                    </div>
                                    <p className="text-xs text-slate-500 ml-7 leading-relaxed">Engagement flexible, résiliable à tout moment. Idéal pour chantiers courts.</p>
                                    {originalOfferType === 'purchase' && <div className="absolute inset-0 bg-slate-100/50 rounded-2xl backdrop-blur-[1px]"></div>}
                                </label>

                                <label className={`p-4 rounded-2xl border-2 cursor-pointer transition flex flex-col gap-1 ${currentOfferType === 'purchase' ? 'border-emerald-500 bg-emerald-50 shadow-sm' : 'border-slate-200 hover:border-emerald-200 hover:bg-slate-50'}`}>
                                    <div className="flex justify-between items-center">
                                        <div className="flex items-center gap-2">
                                            <input type="radio" name="offerType" value="purchase" checked={currentOfferType === 'purchase'} onChange={(e) => setManagingPanneau({...pCible, offerType: e.target.value, currentRate: 0})} className="w-5 h-5 accent-emerald-600" />
                                            <span className="font-black text-slate-800 text-lg">Achat unique</span>
                                        </div>
                                        <span className="font-bold text-emerald-600">{pPurchase}€</span>
                                    </div>
                                    <p className="text-xs text-slate-500 ml-7 leading-relaxed">Paiement unique, panneau acquis définitivement.</p>
                                    {originalOfferType === 'rental' && currentOfferType === 'purchase' && <div className="ml-7 mt-2 bg-blue-100 text-blue-800 px-3 py-1.5 rounded-lg text-[10px] font-bold uppercase tracking-wider inline-block">Upgrade : Changement définitif vers l'achat</div>}
                                </label>
                            </div>

                            <label className={`p-4 rounded-2xl border-2 cursor-pointer transition flex items-start gap-3 mt-4 ${currentHasNoAds ? 'border-purple-500 bg-purple-50 shadow-sm' : 'border-slate-200 hover:border-purple-200 hover:bg-slate-50'} ${originalHasNoAds ? 'opacity-50 cursor-not-allowed pointer-events-none' : ''}`}>
                                <input type="checkbox" checked={currentHasNoAds} disabled={originalHasNoAds} onChange={(e) => setManagingPanneau({...pCible, hasNoAds: e.target.checked})} className="mt-1 w-5 h-5 accent-purple-600 shrink-0" />
                                <div className="flex-1">
                                    <div className="flex justify-between items-center">
                                        <span className="font-black text-slate-800">Option marque blanche</span>
                                        <span className="font-bold text-purple-600">+{pNoAds}€</span>
                                    </div>
                                    <p className="text-xs text-slate-500 mt-1 leading-relaxed">Supprime la bannière publicitaire sur la page publique du panneau (Paiement unique).</p>
                                </div>
                            </label>
                        </div>

                        <div className="space-y-4">
                            <h3 className="font-black text-slate-800 text-sm uppercase tracking-widest border-b pb-2">2. Panneaux physiques A1</h3>
                            <div className="bg-slate-50 p-4 sm:p-5 rounded-2xl border border-slate-200">
                                <div className="flex justify-between items-center mb-2">
                                    <div className="flex items-center gap-2"><PackageIcon size={20} className="text-blue-600"/><h4 className="font-black text-slate-800">Impression A1 (Akilux)</h4></div>
                                    <div className="text-right">
                                        <p className="text-xs font-bold text-slate-500">{pBoardFirst}€ / 1er panneau</p>
                                        <p className="text-[10px] text-slate-400">Puis {pBoardAdd}€ l'unité supp.</p>
                                    </div>
                                </div>
                                <p className="text-xs text-slate-500 mb-4">Commandez vos panneaux physiques imprimés par nos soins et livrés sur votre chantier. (Tarif unique, impression et livraison incluses).</p>
                                
                                <div className="flex items-center justify-between bg-white border border-slate-200 rounded-xl p-2 shadow-sm">
                                    <Button 
                                        variant="secondary" 
                                        shape="square"
                                        icon={MinusIcon}
                                        onClick={() => { if (currentPanels > originalPanels) setManagingPanneau(p => ({...pCible, physicalPanels: Math.max(originalPanels, p.physicalPanels - 1)})) }} 
                                        disabled={currentPanels <= originalPanels} 
                                        className="w-10 h-10 bg-slate-100 hover:bg-slate-200 text-slate-600 border-none shadow-none"
                                        title="Réduire la quantité"
                                    />
                                    <div className="flex flex-col items-center">
                                        <span className="text-xl font-black text-slate-800">{currentPanels}</span>
                                        <span className="text-[9px] font-bold text-slate-400 uppercase tracking-widest">Panneaux</span>
                                    </div>
                                    <Button 
                                        variant="secondary" 
                                        shape="square"
                                        icon={PlusIcon}
                                        onClick={() => setManagingPanneau(p => ({...pCible, physicalPanels: p.physicalPanels + 1}))} 
                                        className="w-10 h-10 bg-slate-100 hover:bg-slate-200 text-slate-600 border-none shadow-none"
                                        title="Augmenter la quantité"
                                    />
                                </div>
                                
                                {originalPanels > 0 && <p className="text-xs text-blue-600 mt-3 font-bold text-center">Vous avez déjà commandé {originalPanels} panneaux physiques.</p>}
                            </div>

                            {currentPanels > originalPanels && (
                                <div className="space-y-2 animate-in fade-in">
                                    <label className="text-xs font-bold text-slate-500 uppercase block">Adresse de livraison pour l'impression A1 <span className="text-red-500 font-black">*</span></label>
                                    <textarea value={pCible.shippingAddress || myClientData?.address || ''} onChange={e => setManagingPanneau({...pCible, shippingAddress: e.target.value})} rows="2" className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm focus:border-blue-500 outline-none transition resize-none"></textarea>
                                    <p className="text-[10px] text-slate-400 font-medium">Modifiez cette adresse si le lieu de livraison diffère de l'adresse de votre entreprise.</p>
                                </div>
                            )}
                        </div>
                    </CardGrid>

                    <div className="bg-slate-900 text-white rounded-3xl p-6 sm:p-8 shadow-xl mt-8">
                        <h3 className="font-black text-lg mb-6 border-b border-slate-700 pb-4">Résumé de la commande (HT)</h3>
                        
                        <div className="space-y-3 mb-6 font-medium text-sm">
                            {!isActif && currentOfferType === 'rental' && (
                                <div className="flex justify-between items-center"><span className="text-slate-300">Abonnement (Location 1er mois)</span><span className="font-bold">{pRental.toFixed(2)} €</span></div>
                            )}
                            {!isActif && currentOfferType === 'purchase' && (
                                <>
                                    <div className="flex justify-between items-center"><span className="text-slate-300">Achat définitif du panneau</span><span className="font-bold">{pPurchase.toFixed(2)} €</span></div>
                                </>
                            )}
                            {isActif && originalOfferType === 'rental' && currentOfferType === 'purchase' && (
                                <>
                                    <div className="flex justify-between items-center"><span className="text-slate-300">Upgrade : Achat définitif</span><span className="font-bold">{pPurchase.toFixed(2)} €</span></div>
                                </>
                            )}
                            
                            {currentHasNoAds && !originalHasNoAds && (
                                <div className="flex justify-between items-center"><span className="text-slate-300">Option marque blanche</span><span className="font-bold">{pNoAds.toFixed(2)} €</span></div>
                            )}

                            {addedPanelsCost > 0 && (
                                <div className="flex justify-between items-center"><span className="text-slate-300">Impression et livraison de {currentPanels - originalPanels} panneaux A1</span><span className="font-bold">{addedPanelsCost.toFixed(2)} €</span></div>
                            )}
                        </div>

                        {discountPct > 0 && discountableHT > 0 && (
                            <div className="bg-emerald-900/50 border border-emerald-500/30 p-4 rounded-xl mb-6 flex justify-between items-center">
                                <div><p className="font-bold text-emerald-400">Remise client applicable ({discountPct}%)</p><p className="text-xs text-emerald-500/70">Sur les abonnements et options logicielles</p></div>
                                <span className="text-xl font-black text-emerald-400">-{discountAmount.toFixed(2)} €</span>
                            </div>
                        )}

                        {myClientData?.wallet_balance > 0 && (
                            <div className="bg-blue-900/30 border border-blue-500/30 p-4 rounded-xl mb-6 flex justify-between items-center">
                                <div><p className="font-bold text-blue-400">Solde disponible (Avoir)</p><p className="text-xs text-blue-500/70">Sera déduit automatiquement de ce paiement</p></div>
                                <span className="text-xl font-black text-blue-400">-{myClientData.wallet_balance.toFixed(2)} € TTC</span>
                            </div>
                        )}

                        <div className="pt-4 border-t border-slate-700 flex flex-col sm:flex-row sm:items-end justify-between gap-4">
                            <div>
                                <p className="text-slate-400 text-sm font-bold uppercase tracking-widest mb-1">Total à régler {platformHasTva ? 'TTC' : 'HT'}</p>
                                <div className="text-4xl font-black">{remainingToPay.toFixed(2)} €</div>
                                {platformHasTva && <p className="text-xs text-slate-500 mt-1">TVA (20%) incluse. Total initial HT : {discountedHT.toFixed(2)} €</p>}
                            </div>
                            
                            {currentOfferType === 'rental' && (
                                <div className="text-left sm:text-right bg-slate-800 p-3 rounded-xl border border-slate-700">
                                    <p className="text-[10px] text-slate-400 uppercase font-bold tracking-wider mb-1">Puis abonnement</p>
                                    <p className="text-lg font-black text-emerald-400">{finalMonthlyTTC.toFixed(2)} € <span className="text-xs font-medium text-slate-500">/ mois {platformHasTva ? 'TTC' : 'HT'}</span></p>
                                </div>
                            )}
                        </div>
                    </div>

                    <label className="flex items-start gap-3 p-4 bg-orange-50 border border-orange-200 rounded-xl cursor-pointer mt-6 shadow-sm">
                        <input type="checkbox" checked={waiverAccepted} onChange={(e) => setWaiverAccepted(e.target.checked)} className="mt-0.5 w-5 h-5 accent-orange-600 shrink-0 cursor-pointer" />
                        <span className="text-xs font-bold text-orange-900 leading-relaxed cursor-pointer select-none">
                            J'accepte que l'exécution du service et la fourniture du contenu numérique commencent immédiatement, et je renonce expressément à mon droit de rétractation de 14 jours si jamais j'y avais le droit. <span className="text-red-500 font-black">*</span>
                        </span>
                    </label>
                </div>

                {/* FIXED FOOTER */}
                <div className="p-4 sm:p-6 border-t border-slate-200 bg-white shrink-0 rounded-b-[2rem] flex gap-3">
                    <Button variant="secondary" onClick={handleSafeBack} disabled={isSaving} className="px-6 py-3">
                        Retour
                    </Button>
                    <Button 
                        variant="primary" 
                        onClick={handleActivationRequest} 
                        disabled={isSaving || !waiverAccepted} 
                        icon={isSaving ? LoaderIcon : (remainingToPay <= 0 ? CheckCircleIcon : CreditCardIcon)} 
                        className="flex-1 py-3 uppercase tracking-widest justify-center shadow-md text-xs"
                    >
                        {isSaving ? 'Traitement...' : (remainingToPay <= 0 ? (isActif ? 'Valider la commande' : 'Activer gratuitement') : 'Passer au paiement')}
                    </Button>
                </div>
            </div>
        </ModalOverlay>
    );
};

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