// Plan picker that hands off to Stripe Checkout. We deliberately don't render
// any card form here — Stripe collects payment details on their domain (cards,
// PIX, etc.) and bounces back to /billing/success or /billing/cancel.

const PLANS = [
  {
    key: "pack_5",
    name: "Pay per use",
    price: 15,
    unit: "5 thumbnails · pagamento único",
    recurring: false,
    perks: [
      "5 gerações de thumbnails",
      "Sem renovação automática",
      "Download em PNG 1280×720",
    ],
  },
  {
    key: "plan_40",
    name: "Creator",
    price: 39,
    unit: "40 thumbnails / mês",
    recurring: true,
    badge: "popular",
    perks: [
      "40 gerações por mês",
      "Avatar com até 9 fotos de referência",
      "Editor de texto + recorte automático",
      "Histórico ilimitado",
    ],
  },
  {
    key: "plan_120",
    name: "Pro",
    price: 79,
    unit: "120 thumbnails / mês",
    recurring: true,
    perks: [
      "120 gerações por mês",
      "Tudo do Creator",
      "A/B test (3 variações por geração)",
      "Templates premium",
    ],
  },
];

const Checkout = ({ onComplete, onBack }) => {
  const [plan, setPlan] = React.useState("plan_40");
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState(null);
  const current = PLANS.find((p) => p.key === plan) || PLANS[0];

  const submit = async () => {
    if (busy) return;
    setBusy(true);
    setError(null);
    try {
      const res = await window.gtAPI.fetch("/billing/checkout", {
        method: "POST",
        body: JSON.stringify({ plan }),
      });
      if (!res?.url) throw new Error("Stripe não devolveu URL");
      // Hand off to Stripe Checkout. They collect payment, then redirect back
      // to APP_URL/billing/success?session_id=… (handled by App.jsx).
      window.location.href = res.url;
    } catch (e) {
      setError(e.message || "falha ao iniciar checkout");
      setBusy(false);
    }
  };

  return (
    <div className="fade-in">
      <div className="row-gap" style={{marginBottom: 22}}>
        <button className="btn btn-sm btn-ghost" onClick={onBack}>← Voltar</button>
        <div>
          <div className="eyebrow"><span className="dot" />Checkout</div>
          <h1 className="display" style={{fontSize: 36, margin: "4px 0 0"}}>Liberar geração</h1>
          <div className="muted-2" style={{marginTop: 6}}>
            Escolha um plano. Pagamento processado pela Stripe — cartão, PIX ou boleto.
          </div>
        </div>
      </div>

      <div className="checkout-grid">
        <div className="col-gap" style={{gap: 16}}>
          <div className="checkout-form">
            <h3>Escolha o plano</h3>
            <div className="col-gap" style={{gap: 10}}>
              {PLANS.map((p) => (
                <label key={p.key} className="row-gap" style={{
                  padding: "16px 18px",
                  border: "1px solid",
                  borderColor: plan === p.key ? "var(--brand)" : "var(--border)",
                  borderRadius: 12,
                  cursor: "pointer",
                  background: plan === p.key ? "var(--brand-soft)" : "var(--bg-2)",
                  gap: 14,
                }}>
                  <div style={{
                    width: 18, height: 18, borderRadius: "50%",
                    border: "2px solid", borderColor: plan === p.key ? "var(--brand)" : "var(--text-3)",
                    background: plan === p.key ? "var(--brand)" : "transparent",
                    boxShadow: plan === p.key ? "inset 0 0 0 3px var(--surface)" : "none",
                  }} />
                  <div style={{flex: 1}}>
                    <div className="row-gap" style={{gap: 8}}>
                      <span style={{fontWeight: 600, fontSize: 15}}>{p.name}</span>
                      {p.badge && <span className="chip brand">{p.badge}</span>}
                    </div>
                    <div className="muted-2" style={{fontSize: 13, marginTop: 2}}>{p.unit}</div>
                  </div>
                  <div className="display" style={{fontSize: 22}}>
                    R${p.price}
                    <span style={{fontSize: 12, fontWeight: 500, color: "var(--text-3)"}}>
                      {p.recurring ? "/mês" : ""}
                    </span>
                  </div>
                  <input type="radio" checked={plan === p.key}
                         onChange={() => setPlan(p.key)} style={{display: "none"}} />
                </label>
              ))}
            </div>
          </div>

          <div className="checkout-form">
            <div className="row-gap" style={{gap: 10}}>
              <Icon name="lock" size={18} />
              <div>
                <div style={{fontWeight: 600, fontSize: 14}}>Pagamento seguro pela Stripe</div>
                <div className="muted" style={{fontSize: 12, marginTop: 2}}>
                  Seus dados de cartão nunca passam pelo nosso servidor. Aceita Visa, Mastercard, Elo e PIX.
                </div>
              </div>
            </div>
          </div>
        </div>

        <div className="summary-card">
          <h3>Resumo</h3>
          <div className="line"><span className="muted-2">Plano</span><span>{current.name}</span></div>
          <div className="line">
            <span className="muted-2">Cobrança</span>
            <span>{current.recurring ? "Mensal recorrente" : "Pagamento único"}</span>
          </div>
          <div style={{padding: "10px 0", borderTop: "1px solid var(--border)", borderBottom: "1px solid var(--border)", margin: "6px 0"}}>
            <div className="muted-2" style={{fontSize: 12, marginBottom: 8, fontFamily: "var(--font-mono)", letterSpacing: "0.06em", textTransform: "uppercase"}}>
              Inclui
            </div>
            <ul style={{listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 6}}>
              {current.perks.map((p) => (
                <li key={p} className="row-gap" style={{gap: 8, fontSize: 13}}>
                  <span style={{color: "var(--brand)"}}><Icon name="check" size={13} /></span>{p}
                </li>
              ))}
            </ul>
          </div>
          <div className="line total">
            <span>Total {current.recurring ? "hoje" : ""}</span>
            <span className="display">R$ {current.price.toFixed(2).replace(".", ",")}</span>
          </div>

          {error && (
            <div style={{marginTop: 14, padding: 12, borderRadius: 8, background: "var(--brand-soft, rgba(225,29,72,0.12))", color: "var(--brand)", fontSize: 13}}>
              {error}
            </div>
          )}

          <button className="btn btn-primary btn-lg" style={{width: "100%", marginTop: 14}}
                  onClick={submit} disabled={busy}>
            {busy
              ? <><span className="ring" /> Abrindo Stripe…</>
              : <><Icon name="lock" size={14} /> Continuar pra pagamento</>}
          </button>
          <div className="muted" style={{textAlign: "center", fontSize: 12, marginTop: 12, lineHeight: 1.5}}>
            Você será redirecionado pra Stripe pra finalizar.
            {current.recurring && " Cancele a qualquer momento na conta."}
          </div>
        </div>
      </div>
    </div>
  );
};

window.Checkout = Checkout;
