/* BasedMTA — Checkout modal.

   Real flow: the backend creates a CryptoCloud invoice and returns a
   hosted payment URL. We never touch wallet addresses or on-chain
   detection in the browser — CryptoCloud's hosted page does that, then
   posts back to /v1/postback/cryptocloud (JWT-verified server-side),
   which mints the key and emails it.

   Steps:
     1. Review order + email + accept terms
     2. Creating invoice -> redirect to CryptoCloud hosted checkout

   API: POST /v1/checkout  { email, tier_id, duration_days }
        -> { invoice_id, pay_url, price_usd_cents, expires_at }
   Served same-origin via Caddy reverse-proxy to the auth backend, so no
   CORS and no cross-origin secrets in the page.
*/

const { useState: cuState, useEffect: cuEffect } = React;

// Frontend tier slug -> backend numeric tier_id. Verified against the
// live /v1/pricing snapshot (Basic=1, Pro=2, VIP=3). The price the
// customer is actually charged is recomputed server-side from this
// tier_id + duration_days, so the displayed total can never diverge
// from the invoice amount.
const TIER_ID_BY_SLUG = { basic: 1, pro: 2, vip: 3 };

// Optional override for local dev; empty string == same-origin.
const API_BASE = (typeof window !== "undefined" && window.BMTA_API_BASE) || "";

function CheckoutModal({ open, order, onClose }) {
  const [step, setStep] = cuState(1);
  const [email, setEmail] = cuState("");
  const [emailErr, setEmailErr] = cuState("");
  const [accept, setAccept] = cuState(true);
  const [submitting, setSubmitting] = cuState(false);
  const [fatalErr, setFatalErr] = cuState("");

  cuEffect(() => {
    if (open) {
      setStep(1);
      setEmail("");
      setEmailErr("");
      setAccept(true);
      setSubmitting(false);
      setFatalErr("");
    }
  }, [open]);

  cuEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape" && !submitting) onClose(); };
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [open, onClose, submitting]);

  if (!open || !order) return null;

  const validEmail = (v) => /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(v.trim());

  // Base tier price for the selected duration. This is exactly what the
  // backend charges; add-ons (if any) are arranged separately via a
  // ticket and are NOT folded into the crypto invoice.
  const baseAmount = order.tier.durations[order.duration.id];
  const tierID = TIER_ID_BY_SLUG[order.tier.id];

  const goPay = async () => {
    if (!validEmail(email)) {
      setEmailErr("Enter a valid email so we can deliver your key.");
      return;
    }
    if (!accept) {
      setEmailErr("Please accept the terms of sale to continue.");
      return;
    }
    if (!tierID) {
      setFatalErr("This tier can't be purchased online yet — open a Discord ticket.");
      return;
    }
    setEmailErr("");
    setFatalErr("");
    setSubmitting(true);
    setStep(2);

    try {
      const resp = await fetch(API_BASE + "/v1/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json", "Accept": "application/json" },
        body: JSON.stringify({
          email: email.trim(),
          tier_id: tierID,
          duration_days: order.duration.days,
        }),
      });

      const data = await resp.json().catch(() => ({}));

      if (!resp.ok) {
        let msg = "We couldn't start your payment. Please try again.";
        if (resp.status === 503) {
          msg = "Crypto payments are briefly unavailable. Please try again in a minute, or open a Discord ticket.";
        } else if (resp.status === 429) {
          msg = "Too many attempts. Wait a moment and try again.";
        } else if (data && data.error === "invalid email") {
          msg = "That email looks invalid. Please double-check it.";
        } else if (data && data.detail) {
          msg = String(data.detail);
        }
        setFatalErr(msg);
        setSubmitting(false);
        setStep(1);
        return;
      }

      const payURL = data && data.pay_url;
      if (!payURL || typeof payURL !== "string" || !/^https:\/\//i.test(payURL)) {
        setFatalErr("The payment processor did not return a valid checkout link. Please try again.");
        setSubmitting(false);
        setStep(1);
        return;
      }

      // Stash for an optional post-payment status check (key checker can
      // surface "we emailed your key"). Best-effort; ignore failures.
      try {
        localStorage.setItem("bmta_last_invoice", JSON.stringify({
          invoice_id: data.invoice_id || null,
          email: email.trim(),
          tier: order.tier.name,
          duration: order.duration.label,
          ts: Date.now(),
        }));
      } catch (_) {}

      // Hand off to CryptoCloud's hosted, PCI-out-of-scope payment page.
      window.location.assign(payURL);
    } catch (err) {
      setFatalErr("Network error reaching the payment server. Check your connection and try again.");
      setSubmitting(false);
      setStep(1);
    }
  };

  const hasAddons = order.addons && order.addons.length > 0;

  return (
    <div className={"ck-overlay" + (open ? " open" : "")} onClick={() => { if (!submitting) onClose(); }}>
      <div className="ck-modal" onClick={(e) => e.stopPropagation()}>
        <header className="ck-head">
          <div className="ck-brand">
            <span className="brand brand-sm">
              <span className="brand-b">B</span>
              <span className="brand-rest">asedMTA</span>
            </span>
          </div>
          <div className="ck-steps">
            <CkStep n="1" label="Review"  active={step === 1} done={step > 1} />
            <CkStep n="2" label="Payment" active={step === 2} done={false} />
          </div>
          <button className="ck-close" onClick={() => { if (!submitting) onClose(); }} aria-label="Close" disabled={submitting}>
            <svg width="14" height="14" viewBox="0 0 14 14"><path d="M3 3 L11 11 M11 3 L3 11" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" /></svg>
          </button>
        </header>

        <div className="ck-body">
          <aside className="ck-summary">
            <div className="ck-sum-label">Order</div>
            <div className="ck-sum-pill" data-tier={order.tier.id}>
              {order.tier.name} tier &middot; {order.duration.label}
            </div>
            <ul className="ck-sum-lines">
              <li>
                <div className="ck-sum-line-meta">
                  <span className="ck-sum-line-label">{order.tier.name} tier</span>
                  <span className="ck-sum-line-sub">{order.duration.label}</span>
                </div>
                <span className="ck-sum-line-amt">${baseAmount}</span>
              </li>
            </ul>
            <div className="ck-sum-total">
              <span className="ck-sum-total-lbl">Total due</span>
              <span className="ck-sum-total-val"><span className="cur">$</span>{baseAmount}</span>
            </div>
            {hasAddons && (
              <div className="ck-sum-fine" style={{ marginTop: 10 }}>
                <p><span className="ck-fine-key">Add-ons</span><span>{order.addons.map((a) => a.name).join(", ")} — arranged on Discord after delivery, billed separately.</span></p>
              </div>
            )}
            <div className="ck-sum-fine">
              <p><span className="ck-fine-key">Payment</span><span>CryptoCloud (BTC, XMR, USDT, ETH, LTC)</span></p>
              <p><span className="ck-fine-key">Delivery</span><span>License key emailed within ~5 min of confirmation</span></p>
              <p><span className="ck-fine-key">HWID</span><span>Bound on first launch</span></p>
            </div>
          </aside>

          <div className="ck-main">
            {step === 1 && (
              <div className="ck-step ck-step-1">
                <h2 className="ck-step-title">Review your order</h2>
                <p className="ck-step-sub">Your license key is delivered by email. We never share it, sell it, or send marketing.</p>

                <label className="ck-field">
                  <span className="ck-field-label">Email address</span>
                  <input
                    type="email"
                    className={"ck-input" + (emailErr ? " err" : "")}
                    placeholder="you@example.com"
                    value={email}
                    onChange={(e) => { setEmail(e.target.value); if (emailErr) setEmailErr(""); }}
                    autoFocus
                    autoComplete="email"
                    spellCheck="false"
                    inputMode="email"
                  />
                  {emailErr && <span className="ck-field-err">{emailErr}</span>}
                </label>

                <label className="ck-check">
                  <input type="checkbox" checked={accept} onChange={(e) => setAccept(e.target.checked)} />
                  <span className="ck-check-box">
                    <svg width="10" height="10" viewBox="0 0 12 12"><path d="M2 6 L5 9 L10 3" stroke="currentColor" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round" /></svg>
                  </span>
                  <span>I accept the <a href="tos.html" target="_blank" rel="noopener">terms of sale</a>. All sales are final.</span>
                </label>

                {fatalErr && <span className="ck-field-err" style={{ display: "block", marginTop: 4 }}>{fatalErr}</span>}

                <div className="ck-actions">
                  <button className="ck-btn-ghost" onClick={onClose}>Cancel</button>
                  <button className="ck-btn-primary" onClick={goPay}>Continue to payment</button>
                </div>
              </div>
            )}

            {step === 2 && (
              <div className="ck-step ck-step-2">
                <div className="ck-redir">
                  <div className="ck-spinner">
                    <svg width="44" height="44" viewBox="0 0 44 44" aria-hidden="true">
                      <circle cx="22" cy="22" r="18" stroke="currentColor" strokeWidth="2" strokeOpacity="0.18" fill="none" />
                      <circle cx="22" cy="22" r="18" stroke="currentColor" strokeWidth="2" strokeDasharray="36 200" strokeLinecap="round" fill="none">
                        <animateTransform attributeName="transform" type="rotate" from="0 22 22" to="360 22 22" dur="1.2s" repeatCount="indefinite" />
                      </circle>
                    </svg>
                  </div>
                  <h2 className="ck-step-title ck-center">Opening secure checkout</h2>
                  <p className="ck-step-sub ck-center">
                    Creating your <strong>${baseAmount} USD</strong> invoice with CryptoCloud and redirecting you to their hosted payment page.
                    Once it clears on-chain, your key is emailed to <strong>{email}</strong>.
                  </p>
                  <div className="ck-redir-meta">
                    <div><span className="ck-fine-key">Processor</span><span>CryptoCloud</span></div>
                    <div><span className="ck-fine-key">Order</span><span>{order.tier.name} &middot; {order.duration.label}</span></div>
                    <div><span className="ck-fine-key">Amount</span><span className="mono">${baseAmount} USD</span></div>
                  </div>
                  <p className="ck-step-sub ck-center" style={{ opacity: 0.7, fontSize: "0.82rem" }}>
                    If you are not redirected automatically, please don't refresh — open a Discord ticket and we'll sort it out.
                  </p>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

function CkStep({ n, label, active, done }) {
  return (
    <div className={"ck-step-pill" + (active ? " active" : "") + (done ? " done" : "")}>
      <span className="ck-step-pill-n">
        {done ? <svg width="10" height="10" viewBox="0 0 12 12"><path d="M2 6 L5 9 L10 3" stroke="currentColor" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round" /></svg> : n}
      </span>
      <span className="ck-step-pill-l">{label}</span>
    </div>
  );
}

window.CheckoutModal = CheckoutModal;
