/* YeYe Portal v20 — invoice checkout */
function CheckoutModal({ open, onClose, onSuccess, onNeedProfile }) {
  const { t, currency } = useT();
  const cart = useCartState();
  const [stage, setStage] = useState('idle');
  const [error, setError] = useState('');
  const [invoice, setInvoice] = useState(null);
  const [stripeSession, setStripeSession] = useState(null);
  const [stripeReady, setStripeReady] = useState(false);
  const [stripeStatus, setStripeStatus] = useState('');
  const [promoCode, setPromoCode] = useState('');
  const stripeHostRef = useRef(null);
  const stripeCheckoutRef = useRef(null);
  useEffect(() => {
    if (open) {
      setStage('idle');
      setError('');
      setInvoice(null);
      setStripeSession(null);
      setStripeReady(false);
      setStripeStatus('');
      setPromoCode('');
    }
  }, [open]);
  useEffect(() => {
    return () => {
      if (stripeCheckoutRef.current && stripeCheckoutRef.current.destroy) {
        try { stripeCheckoutRef.current.destroy(); } catch (_) {}
      }
      stripeCheckoutRef.current = null;
    };
  }, []);
  if (!open) return null;
  const authState = (window.YEYE_AUTH && window.YEYE_AUTH.getState && window.YEYE_AUTH.getState()) || {};
  const contact = authState.contact || {};
  const contactId = contact.contactId || '';
  const email = contact.email || (authState.user && authState.user.email) || '';
  const name = [contact.firstName, contact.lastName].filter(Boolean).join(' ') || (authState.user && authState.user.name) || '—';
  const phone = contact.phone || '—';
  const needsProfile = !contactId || !email;
  const invoiceCurrency = window.YEYE_CART_CURRENCY ? window.YEYE_CART_CURRENCY(currency) : (currency || 'EUR');
  const totals = window.YEYE_CART_TOTALS(cart.items, invoiceCurrency);
  const paymentProvider = String((window.YEYE_CONFIG && window.YEYE_CONFIG.PAYMENT_PROVIDER) || 'stripe').toLowerCase();
  const stripePublishableKey = String((window.YEYE_CONFIG && window.YEYE_CONFIG.STRIPE_PUBLISHABLE_KEY) || '').trim();
  const stripeAvailable = paymentProvider === 'stripe' && !!stripePublishableKey && !!window.Stripe;
  const delay = (ms) => new Promise((resolve) => window.setTimeout(resolve, ms));
  const retryOnRateLimit = async (fn) => {
    let lastError = null;
    for (let attempt = 0; attempt < 3; attempt += 1) {
      try { return await fn(); }
      catch (err) {
        lastError = err;
        if (!err || err.status !== 429 || attempt === 2) throw err;
        await delay(900 * (attempt + 1));
      }
    }
    throw lastError || new Error('rate-limit-retry-failed');
  };
  const itemsForPayment = () => cart.items.map((item) => {
    const unitAmount = window.YEYE_CART_CONVERT
      ? window.YEYE_CART_CONVERT(item.uiPrice, item.uiCurrency, invoiceCurrency)
      : (Number(item.uiPrice) || 0);
    return {
      name: item.name + (item.variantLabel ? ' — ' + item.variantLabel : ''),
      amount: Math.round(unitAmount * 100) / 100,
      currency: invoiceCurrency,
      qty: item.qty,
      productKey: item.productKey || '',
      variantKey: item.variantKey || '',
      productId: item.productId || '',
      priceId: item.priceId || '',
      description: [
        item.productKey ? 'Product: ' + item.productKey : '',
        item.variantKey ? 'Variant: ' + item.variantKey : '',
        item.productId ? 'GHL productId: ' + item.productId : '',
        item.priceId ? 'GHL priceId: ' + item.priceId : '',
      ].filter(Boolean).join(' · ') || undefined,
    };
  }).filter((row) => Number(row.amount) > 0);
  const legacyGhlInvoiceCheckout = async () => {
    if (needsProfile || !cart.items.length || stage === 'processing') return;
    let paymentWindow = null;
    try {
      paymentWindow = window.open('', '_blank');
      if (paymentWindow && paymentWindow.document) {
        paymentWindow.document.write('<!doctype html><title>YeYe Invoice</title><body style="font-family:-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;padding:24px;color:#23313a">Invoice is being prepared...</body>');
      }
    } catch (_) {}
    setStage('processing');
    setError('');
    try {
      const result = invoice && invoice.invoiceId ? invoice : await retryOnRateLimit(() => window.YEYE_BACKEND.createInvoice({
          contactId, currency: invoiceCurrency, liveMode: true,
          templateId: (window.YEYE_CONFIG && window.YEYE_CONFIG.INVOICE_TEMPLATE_ID) || undefined,
          items: itemsForPayment(),
        }));
      if (!result || !result.invoiceId) throw new Error('invoice-id-missing');
      let finalResult = result;
      try {
        const sendResult = await retryOnRateLimit(() => window.YEYE_BACKEND.sendInvoice(result.invoiceId));
        if (sendResult && sendResult.invoiceUrl) finalResult = Object.assign({}, result, { invoiceUrl: sendResult.invoiceUrl });
      } catch (sendErr) { console.warn('Invoice created but send failed', sendErr); }
      setInvoice(finalResult);
      if (finalResult.invoiceUrl) {
        try {
          const cache = JSON.parse(localStorage.getItem('yeye_invoice_urls_v1') || '{}');
          cache[finalResult.invoiceId] = finalResult.invoiceUrl;
          localStorage.setItem('yeye_invoice_urls_v1', JSON.stringify(cache));
        } catch (_) {}
      }
      window.YEYE_CART.clear();
      setStage('success');
      if (onSuccess) onSuccess(finalResult);
      if (finalResult.invoiceUrl) {
        if (paymentWindow && !paymentWindow.closed) paymentWindow.location.href = finalResult.invoiceUrl;
        else window.open(finalResult.invoiceUrl, '_blank', 'noopener,noreferrer');
      } else if (paymentWindow && !paymentWindow.closed) {
        paymentWindow.close();
      }
    } catch (err) {
      if (paymentWindow && !paymentWindow.closed) paymentWindow.close();
      setError((err && err.message) || t('checkout.error'));
      setStage('error');
    }
  };
  const createStripeCheckout = async () => {
    if (needsProfile || !cart.items.length || stage === 'processing') return;
    if (!stripeAvailable) {
      setError(t('checkout.stripeMissing'));
      setStage('error');
      return;
    }
    setStage('processing');
    setError('');
    setStripeStatus('');
    const _dbgPayload = {
      contactId,
      email,
      name,
      phone: phone === '—' ? '' : phone,
      currency: invoiceCurrency,
      items: itemsForPayment(),
      promoCode: promoCode.trim(),
      allowPromotionCodes: true,
      locale: (localStorage.getItem('yeye-lang') || 'en').toLowerCase(),
      origin: window.location.origin,
      returnUrl: window.location.origin + window.location.pathname + '?checkout_session_id={CHECKOUT_SESSION_ID}',
    };
    console.log('[YEYE_DEBUG] Stripe checkout payload:', JSON.stringify(_dbgPayload, null, 2));
    try {
      const result = await window.YEYE_BACKEND.createStripeCheckoutSession(_dbgPayload);
      if (!result || !result.clientSecret) throw new Error('stripe-client-secret-missing');
      setStripeSession(result);
      setStage('stripe');
      window.setTimeout(async () => {
        if (!stripeHostRef.current) return;
        const stripe = window.Stripe(stripePublishableKey);
        const checkout = await stripe.initEmbeddedCheckout({ clientSecret: result.clientSecret, onComplete: () => checkStripePayment(result.sessionId) });
        if (stripeCheckoutRef.current && stripeCheckoutRef.current.destroy) {
          try { stripeCheckoutRef.current.destroy(); } catch (_) {}
        }
        stripeCheckoutRef.current = checkout;
        checkout.mount(stripeHostRef.current);
        setStripeReady(true);
      }, 0);
    } catch (err) {
      console.log('[YEYE_DEBUG] Stripe checkout error:', err, err && err.body, _dbgPayload);
      setError((err && err.message) || t('checkout.stripeError'));
      setStage('error');
    }
  };
  const create = () => {
    if (paymentProvider === 'ghl' || paymentProvider === 'legacy-ghl') return legacyGhlInvoiceCheckout();
    return createStripeCheckout();
  };
  const checkStripePayment = async (sessionId) => {
    if (!sessionId) return;
    try {
      const statusResult = await window.YEYE_BACKEND.getStripeCheckoutSession(sessionId);
      setStripeStatus(statusResult && statusResult.paymentStatus ? statusResult.paymentStatus : '');
      if (statusResult && (statusResult.status === 'complete' || statusResult.paymentStatus === 'paid')) {
        const paidItems = cart.items.slice();
        if (onSuccess) onSuccess(Object.assign({}, statusResult, { paidItems }));
        window.YEYE_CART.clear();
        setStage('success');
      }
    } catch (err) {
      setError((err && err.message) || t('checkout.stripeStatusError'));
      setStage('error');
    }
  };
  const confirmStripePayment = () => checkStripePayment(stripeSession && stripeSession.sessionId);
  const gotoProfile = () => {
    onClose();
    if (onNeedProfile) onNeedProfile();
    else if (window.YEYE_GO) window.YEYE_GO('formSubmission');
  };
  const gotoPayments = () => { onClose(); if (window.YEYE_GO) window.YEYE_GO('invoices'); };
  return (
    <Modal wide icon={paymentProvider === 'stripe' ? 'credit-card' : 'receipt-text'} title={t('checkout.title')} onClose={stage === 'processing' ? () => {} : onClose}
      footer={stage === 'success' ? (
        <Btn variant="ghost" onClick={gotoPayments}>{t('checkout.goToPayments')}</Btn>
      ) : stage === 'stripe' ? (
        <>
          <Btn variant="ghost" onClick={onClose}>{t('c.cancel')}</Btn>
          <Btn variant="primary" icon="check" onClick={confirmStripePayment}>{t('checkout.iPaid')}</Btn>
        </>
      ) : (
        <>
          <Btn variant="ghost" onClick={onClose} disabled={stage === 'processing'}>{t('c.cancel')}</Btn>
          <Btn variant="primary" icon="receipt-text" onClick={create} disabled={needsProfile || !cart.items.length || stage === 'processing'}>
            {stage === 'processing' ? t('checkout.processing') : t('checkout.confirmAndPay')}
          </Btn>
        </>
      )}>
      {stage === 'success' ? (
        <div className="checkout-success">
          <div className="checkout-success-icon"><Icon name="check" size={27} stroke={2.5} /></div>
          <div className="h2">{t('checkout.redirecting')}</div>
          <div className="muted" style={{ fontSize: 13, marginTop: 8, textAlign: 'center' }}>{t('checkout.pleaseWait')}</div>
        </div>
      ) : stage === 'stripe' ? (
        <div className="checkout-body">
          <div className="embedded-checkout-head">
            <div className="h3">{t('checkout.secureCardPayment')}</div>
            <div className="muted">{stripeStatus ? t('checkout.paymentStatus').replace('{status}', stripeStatus) : t('checkout.embeddedReady')}</div>
          </div>
          {!stripeReady && <div className="checkout-stripe-loading"><div className="ring" /><span>{t('checkout.loadingStripe')}</span></div>}
          <div ref={stripeHostRef} className="stripe-embedded-host" />
        </div>
      ) : (
        <div className="checkout-body">
          <section>
            <div className="eyebrow mb-8">{t('checkout.summary')}</div>
            <div className="checkout-summary">
              {cart.items.map((item) => (
                <div className="checkout-line" key={item.id}>
                  <div><div className="strong">{item.name}</div><div className="muted">{item.variantLabel} · {item.qty}×</div></div>
                  <strong className="tnum">{window.YEYE_CART_MONEY((window.YEYE_CART_CONVERT ? window.YEYE_CART_CONVERT(item.uiPrice, item.uiCurrency, invoiceCurrency) : (Number(item.uiPrice) || 0)) * item.qty, invoiceCurrency)}</strong>
                </div>
              ))}
            </div>
          </section>
          <section>
            <div className="eyebrow mb-8">{t('checkout.contactInfo')}</div>
            <div className="checkout-contact">
              <div><Icon name="user" size={15} /><span>{name}</span></div>
              <div><Icon name="mail" size={15} /><span>{email || '—'}</span></div>
              <div><Icon name="phone" size={15} /><span>{phone}</span></div>
            </div>
          </section>
          <section>
            <div className="eyebrow mb-8">{t('checkout.promoCode')}</div>
            <input className="input" value={promoCode} onChange={(e) => setPromoCode(e.target.value)} placeholder={t('checkout.promoCodePlaceholder')} />
          </section>
          <section className="checkout-total">
            <div className="eyebrow">{t('checkout.total')}</div>
            {Object.keys(totals).map((code) => <div key={code}><span>{code}</span><strong>{window.YEYE_CART_MONEY(totals[code], code)}</strong></div>)}
          </section>
          {paymentProvider !== 'stripe' && <div className="cart-test-warning"><Icon name="triangle-alert" size={16} /><span>{t('cart.testAmountWarning')}</span></div>}
          {needsProfile && (
            <div className="checkout-profile-nudge">
              <div><strong>{t('checkout.needProfile')}</strong></div>
              <Btn variant="soft" size="sm" iconR="arrow-right" onClick={gotoProfile}>{t('welcome.completeProfile')}</Btn>
            </div>
          )}
          {stage === 'error' && (
            <div className="alert bad">
              <div className="a-ic"><Icon name="octagon-alert" size={16} /></div>
              <div className="grow"><div className="a-t">{t('checkout.error')}</div><div className="a-s">{error}</div></div>
              <Btn variant="ghost" size="sm" onClick={create}>{t('c.retry')}</Btn>
            </div>
          )}
        </div>
      )}
    </Modal>
  );
}
Object.assign(window, { CheckoutModal });
