/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Composant : Modale de paiement et tunnel Stripe (Checkout)
 * =========================================================================
 */

const { useState } = React;

window.ClientCheckoutModal = ({ managingPanneau, setManagingPanneau, data, myClientData, profileData, onClose, onBackToEditor, refreshData, showToast }) => {
    const XIcon = window.XIcon || (() => null);
    const AlertTriangleIcon = window.AlertTriangleIcon || (() => null);
    const PackageIcon = window.PackageIcon || (() => null);
    const LoaderIcon = window.LoaderIcon || (() => null);
    const CreditCardIcon = window.CreditCardIcon || (() => null);
    
    const StripeElements = window.StripeElements || (() => null);
    const ModalOverlay = window.ModalOverlay || (({ children }) => <div>{children}</div>);
    
    // COMPOSANTS GLOBAUX NETTOYÉS
    const AlertBox = window.AlertBox;
    const Button = window.Button;
    
    const [step, setStep] = useState('select');
    const [paymentData, setPaymentData] = useState(null);
    const [waiverAccepted, setWaiverAccepted] = useState(false);
    const [isSaving, setIsSaving] = useState(false);

    const isSuspended = myClientData.paymentStatus === 'suspended';
    const purchasesAllowed = data.settings?.allow_new_purchases !== '0';

    const pRental = data.prices?.rentalMo ?? 180;
    const pPurchase = data.prices?.purchase ?? 850;
    const pHosting = data.prices?.hostingYr ?? 1;
    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 === managingPanneau?.id);
    const isActif = originalPanneau?.status === 'Actif';
    const originalOfferType = originalPanneau?.offerType || 'rental';
    const originalPanels = originalPanneau?.physicalPanels || 0;
    const originalHasNoAds = originalPanneau?.hasNoAds || false;

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

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

    let upfrontHT = 0;
    if (!isActif) {
        upfrontHT = (currentPanels > 0 ? pBoardFirst + (currentPanels - 1) * pBoardAdd : 0) + (currentHasNoAds ? pNoAds : 0) + (currentOfferType === 'rental' ? pRental : pPurchase);
    } else {
        if (originalOfferType === 'rental' && currentOfferType === 'purchase') upfrontHT += pPurchase;
        if (currentHasNoAds && !originalHasNoAds) upfrontHT += pNoAds;
        upfrontHT += addedPanelsCost;
    }

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

    const handleActivationRequest = async () => {
        if(isSuspended) return showToast("Votre compte est suspendu. Veuillez régulariser vos factures.", "error");
        if(!purchasesAllowed) return showToast("Les nouvelles commandes sont suspendues.", "error");
        if(!waiverAccepted) return showToast("Veuillez accepter la renonciation au délai de rétractation de 14 jours.", "error");
        
        const payload = { panneau_id: managingPanneau.id, offer_type: managingPanneau.offerType, physical_panels: managingPanneau.physicalPanels, hasNoAds: managingPanneau.hasNoAds };
        
        const d = await window.apiFetch('stripe/intent', { body: payload, setLoading: setIsSaving });
        
        if (d) {
            if (d.data.free_activation_required) {
                const freeRes = await window.apiFetch('panneaux/activate_free', { 
                    body: { ...payload, id: managingPanneau.id, offerType: managingPanneau.offerType, physicalPanels: managingPanneau.physicalPanels, details: managingPanneau, name: managingPanneau.name },
                    successMessage: "Mise à jour et activation réussie !"
                });
                
                if (freeRes) { 
                    onClose(); 
                    refreshData(); 
                }
            } else {
                setPaymentData({ secret: d.data.clientSecret, subId: d.data.subscription_id, amountCents: d.data.amountCents });
                setStep('payment');
            }
        }
    };

    const handlePaymentSuccess = async (pi_id) => {
        const payload = { payment_intent_id: pi_id, subscription_id: paymentData?.subId, id: managingPanneau.id, offerType: managingPanneau.offerType, currentRate: managingPanneau.currentRate, physicalPanels: managingPanneau.physicalPanels, details: managingPanneau, name: managingPanneau.name };
        
        const d = await window.apiFetch('panneaux/activate_paid', { 
            body: payload, 
            setLoading: setIsSaving,
            successMessage: "Paiement validé ! Panneau activé."
        });
        
        if (d) { 
            onClose(); 
            refreshData(); 
        }
    };

    if (step === 'payment' && paymentData && window.StripeElements) {
        return (
            <ModalOverlay zIndex="z-[300]" onClose={() => { setStep('select'); setPaymentData(null); }} preventClose={isSaving}>
                <div className="bg-white rounded-3xl w-full max-w-md shadow-2xl overflow-hidden 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">
                        <h3 className="font-black text-white text-lg">Paiement sécurisé</h3>
                        <div role="button" tabIndex={0} onClick={() => { setStep('select'); setPaymentData(null); }} className="text-slate-400 hover:text-white hover:bg-slate-800 p-2 rounded-xl transition cursor-pointer" title="Fermer"><XIcon size={20}/></div>
                    </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>
        );
    }

    return (
        <ModalOverlay zIndex="z-[200]" onClose={onClose} preventClose={isSaving}>
            <div className="bg-white rounded-[2rem] w-full max-w-4xl shadow-2xl overflow-hidden 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">
                    <div>
                        <h2 className="text-xl font-black text-white">Détails de facturation</h2>
                        <p className="text-xs text-slate-300 font-medium">Configurez votre abonnement et commandez vos supports physiques.</p>
                    </div>
                    <div role="button" tabIndex={0} onClick={() => { if(!isSaving) onClose(); }} className={`p-2 rounded-xl transition ${isSaving ? 'text-slate-300 cursor-not-allowed' : 'text-slate-400 hover:text-white hover:bg-slate-800 cursor-pointer'}`} title="Fermer">
                        <XIcon size={24}/>
                    </div>
                </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>
                    
                    {(!purchasesAllowed) && (
                        <AlertBox type="warning" icon={AlertTriangleIcon}>
                            La création de nouvelles commandes est temporairement suspendue par l'administrateur.
                        </AlertBox>
                    )}

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <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({...managingPanneau, 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({...managingPanneau, 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. (Frais d'hébergement offerts la 1ère année).</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({...managingPanneau, 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">
                                    <div role="button" tabIndex={0} onClick={() => { if(currentPanels > originalPanels) setManagingPanneau(p => ({...p, physicalPanels: Math.max(originalPanels, p.physicalPanels - 1)})) }} className={`w-10 h-10 flex items-center justify-center rounded-lg font-black transition ${currentPanels <= originalPanels ? 'bg-slate-100 text-slate-400 opacity-30 cursor-not-allowed' : 'bg-slate-100 hover:bg-slate-200 text-slate-600 cursor-pointer'}`}>-</div>
                                    <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">Panneau(x)</span>
                                    </div>
                                    <div role="button" tabIndex={0} onClick={() => setManagingPanneau(p => ({...p, physicalPanels: p.physicalPanels + 1}))} className="w-10 h-10 flex items-center justify-center bg-slate-100 hover:bg-slate-200 rounded-lg text-slate-600 font-black transition cursor-pointer">+</div>
                                </div>
                                
                                {originalPanels > 0 && <p className="text-xs text-blue-600 mt-3 font-bold text-center">Vous avez déjà commandé {originalPanels} panneau(x) physique(s).</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={managingPanneau.shippingAddress || profileData.address || ''} onChange={e => setManagingPanneau({...managingPanneau, 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>
                    </div>

                    <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>
                                    <div className="flex justify-between items-center"><span className="text-slate-300">Frais d'hébergement (1ère année)</span><span className="font-bold text-emerald-400 uppercase text-xs tracking-wider">Offert</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>
                                    <div className="flex justify-between items-center"><span className="text-slate-300">Frais d'hébergement (1ère année)</span><span className="font-bold text-emerald-400 uppercase text-xs tracking-wider">Offert</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} panneau(x) A1</span><span className="font-bold">{addedPanelsCost.toFixed(2)} €</span></div>
                            )}
                        </div>

                        {discountPct > 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</p><p className="text-xs text-emerald-500/70">Appliquée sur l'ensemble de la commande HT</p></div>
                                <span className="text-xl font-black text-emerald-400">-{discountPct}%</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 : {(upfrontHT * priceMultiplier).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. <span className="text-red-500 font-black">*</span>
                        </span>
                    </label>

                    <div className="flex gap-3 pt-2 mt-4 border-t border-slate-100">
                        <Button variant="secondary" onClick={onBackToEditor} disabled={isSaving} className="px-6 py-3">
                            Retour
                        </Button>
                        <Button variant="primary" onClick={handleActivationRequest} disabled={isSaving || !waiverAccepted} icon={isSaving ? LoaderIcon : CreditCardIcon} className="flex-1 py-3 uppercase tracking-widest justify-center">
                            Confirmer et valider
                        </Button>
                    </div>
                </div>
            </div>
        </ModalOverlay>
    );
};

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