// screens-setup.jsx — Post-signup subscription redirect.
// The old ApiSetup and ExtInstall flows lived here — superseded by the
// Telegram bot (/buyapi, /addkey, /install), so the web flow now exists
// only as the post-signup landing before Billing takes over.

// ── SUBSCRIPTION ──────────────────────────────────────────────
const MAX_SLOTS = 4;

const Subscription = ({ goto, path, plan, setPlan }) => {
  const [billing, setBilling]   = React.useState("monthly");
  const [chosen, setChosen]     = React.useState(plan || "house_cut");
  const [slotCount, setSlots]   = React.useState(1);
  const [promoCode, setPromoCode]         = React.useState("");
  const [promoInfo, setPromoInfo]         = React.useState(null);
  const [promoErr, setPromoErr]           = React.useState("");
  const [checking, setChecking]           = React.useState(false);
  const [checkingOut, setCheckingOut]     = React.useState(false);
  const [payError, setPayError]           = React.useState("");

  // Three paid tiers — every plan covers both Stake.com and Stake.us, ships
  // with reloads + daily dollar, and grants the (forthcoming) Shuffle/Thrill
  // extension. What separates them is which code tiers BoostMonitor will route
  // to the user: regular only / + highroller / + Saturday stream.
  const PLANS = [
    {
      id: "house_cut", name: "The House Cut", tag: "Regular codes",
      price: { monthly: 10, yearly: 96 },
      blurb: "Regular bonus drops on both Stake.com and Stake.us — daily dollar and reloads on us.",
      features: [
        "Regular bonus codes (both platforms)",
        "Reloads + Stake.us daily dollar — bundled",
        "Pre-solved captchas, residential proxy",
        "Extension access (Shuffle + Thrill — coming soon)",
      ],
    },
    {
      id: "prime_cut", name: "The Prime Cut", tag: "+ Highroller",
      price: { monthly: 15, yearly: 144 },
      blurb: "Regular + highroller codes, both platforms. The pour-over of bonus claiming.",
      features: [
        "Everything in House Cut",
        "Highroller codes (both platforms)",
        "Same bundled reloads + daily dollar",
        "Telegram alerts on every claim",
      ],
      featured: true,
    },
    {
      id: "grand_feast", name: "The Grand Feast", tag: "Every code",
      price: { monthly: 30, yearly: 288 },
      blurb: "The whole spread — regular, highroller, and Saturday stream codes for both platforms.",
      features: [
        "Everything in Prime Cut",
        "Saturday stream codes (both platforms)",
        "First in line on every drop tier",
        "Priority support",
      ],
    },
  ];

  const chosenPlan = PLANS.find(p => p.id === chosen);
  const basePrice = billing === "monthly"
    ? (chosenPlan?.price.monthly ?? 0)
    : (chosenPlan?.price.yearly ?? 0);

  // Price scales linearly with slot count. 1 slot = 1 API key bound to one
  // platform; buying a 2nd slot lets the user run both Stake.com and Stake.us
  // in parallel under the same tier.
  const total = basePrice * slotCount;

  const checkPromo = async () => {
    if (!promoCode.trim()) return;
    setPromoErr(""); setChecking(true); setPromoInfo(null);
    const token = localStorage.getItem("cc_token");
    try {
      const r = await fetch("/api/promo/check", {
        method: "POST",
        headers: { "content-type": "application/json", "Authorization": `Bearer ${token}` },
        body: JSON.stringify({ code: promoCode.trim() }),
      });
      const d = await r.json();
      if (d.error) { setPromoErr(d.error); } else { setPromoInfo(d); }
    } catch (_) { setPromoErr("Network error"); }
    setChecking(false);
  };

  const checkout = async () => {
    setPayError("");
    const token = localStorage.getItem("cc_token");
    if (!token) { goto("signup"); return; }
    setCheckingOut(true);
    try {
      const r = await fetch("/api/payments/create", {
        method: "POST",
        headers: { "content-type": "application/json", "Authorization": `Bearer ${token}` },
        body: JSON.stringify({
          plan: chosen,
          addons: { reload: addonReload, extra_seat: addonSeat },
          promo_code: promoCode.trim() || undefined,
        }),
      });
      const d = await r.json();
      if (d.error) { setPayError(d.error); setCheckingOut(false); return; }
      if (d.dev_mode || !d.invoice_url) {
        setPlan(chosen);
        goto("api-setup");
      } else {
        window.location.href = d.invoice_url;
      }
    } catch {
      setPayError("Network error — try again");
      setCheckingOut(false);
    }
  };

  const pill = (label) => (
    <span style={{
      fontSize: 10, fontFamily: "var(--font-display)", letterSpacing: ".08em",
      textTransform: "uppercase", fontWeight: 700,
      padding: "2px 7px", borderRadius: 3,
      background: "var(--accent)", color: "#07090c",
    }}>{label}</span>
  );

  return (
    <div className="container fade-in" style={{ maxWidth: 1100, padding: "44px 28px" }}>
      <div className="row" style={{ gap: 12, marginBottom: 24 }}>
        <Steps items={["Account", "Path", "Plan", "Setup"]} current={2} />
        <span className="muted" style={{ marginLeft: "auto", fontSize: 12 }}>cancel anytime</span>
      </div>
      <span className="eyebrow">step 3 · pick your cut</span>
      <h2 style={{ fontSize: 36, marginTop: 8, marginBottom: 6 }}>What'll it be?</h2>
      <p className="muted" style={{ marginBottom: 20 }}>Choose your platform. Add extras below. Yearly saves ~20%.</p>

      {/* Billing toggle */}
      <div className="row" style={{ gap: 8, marginBottom: 24 }}>
        <div style={{ display: "inline-flex", border: "1px solid var(--border-2)", borderRadius: 999, padding: 3, background: "var(--surf-2)" }}>
          {["monthly", "yearly"].map(b => (
            <button key={b} onClick={() => setBilling(b)} style={{
              border: 0, padding: "6px 14px", borderRadius: 999, cursor: "pointer",
              background: billing === b ? "var(--accent)" : "transparent",
              color: billing === b ? "#07090c" : "var(--text-2)",
              fontFamily: "var(--font-display)", fontSize: 12, letterSpacing: ".06em", textTransform: "uppercase", fontWeight: 600,
            }}>{b}{b === "yearly" && " · −20%"}</button>
          ))}
        </div>
      </div>

      {/* Plan cards */}
      <div className="grid-4" style={{ gap: 14, marginBottom: 28 }}>
        {PLANS.map(p => (
          <div key={p.id}
            className={"path-card " + (chosen === p.id ? "selected " : "") + (p.featured ? "featured" : "")}
            onClick={() => setChosen(p.id)}
            style={{ minHeight: 300, position: "relative", cursor: "pointer" }}>
            {p.featured && <span className="ribbon">best value</span>}
            <div className="row" style={{ gap: 8, alignItems: "center", marginBottom: 4 }}>
              <strong style={{ fontSize: 16 }}>{p.name}</strong>
              {pill(p.tag)}
            </div>
            <p className="muted" style={{ fontSize: 12, marginTop: 2, minHeight: 32 }}>{p.blurb}</p>
            <div style={{ display: "flex", alignItems: "baseline", gap: 3, marginTop: 10 }}>
              <span style={{ fontFamily: "var(--font-num)", fontSize: 38, fontWeight: 700, color: "var(--text)", letterSpacing: "-.02em" }}>
                ${billing === "monthly" ? p.price.monthly : p.price.yearly}
              </span>
              <span className="muted" style={{ fontSize: 12 }}>/{billing === "monthly" ? "mo" : "yr"}</span>
            </div>
            <div className="divider" style={{ margin: "10px 0" }} />
            <ul style={{ listStyle: "none", padding: 0, margin: 0 }}>
              {p.features.map((f, i) => (
                <li key={i} className="row" style={{ gap: 7, fontSize: 12, padding: "3px 0" }}>
                  <Icon name="check" style={{ color: "var(--accent)", flexShrink: 0 }} />
                  <span>{f}</span>
                </li>
              ))}
            </ul>
            <div className="row" style={{ marginTop: 12, gap: 7 }}>
              <span style={{
                width: 16, height: 16, borderRadius: 999, flexShrink: 0,
                border: "2px solid var(--border-2)", display: "grid", placeItems: "center",
                background: chosen === p.id ? "var(--accent)" : "transparent",
              }}>
                {chosen === p.id && <Icon name="check" size={10} style={{ color: "#07090c" }} />}
              </span>
              <span className="muted" style={{ fontSize: 12 }}>{chosen === p.id ? "selected" : "tap to select"}</span>
            </div>
          </div>
        ))}
      </div>

      {/* Add-ons */}
      <div style={{ marginBottom: 28 }}>
        <div className="row" style={{ gap: 8, marginBottom: 12, alignItems: "center" }}>
          <span className="eyebrow" style={{ margin: 0 }}>secret seasonings</span>
          {!hasApi && <span className="muted" style={{ fontSize: 12 }}>— requires a Stake.com or Stake.us plan</span>}
        </div>
        <div style={{ display: "flex", gap: 14, flexWrap: "wrap" }}>
          {ADDONS.map(a => {
            const active = addonStates[a.id];
            const disabled = a.requiresApi && !hasApi;
            return (
              <div key={a.id}
                onClick={() => !disabled && addonSetters[a.id](!active)}
                style={{
                  border: `2px solid ${active ? "var(--accent)" : "var(--border-2)"}`,
                  borderRadius: "var(--radius-sm)",
                  padding: "14px 18px",
                  minWidth: 200, flex: 1, maxWidth: 320,
                  cursor: disabled ? "not-allowed" : "pointer",
                  opacity: disabled ? 0.4 : 1,
                  background: active ? "rgba(0,230,77,.07)" : "var(--surf)",
                  transition: "border-color .15s, background .15s",
                }}>
                <div className="row" style={{ gap: 10, alignItems: "center", marginBottom: 6 }}>
                  <span style={{ fontSize: 20 }}>{a.icon}</span>
                  <strong style={{ fontSize: 14 }}>{a.name}</strong>
                  <span style={{ marginLeft: "auto", fontFamily: "var(--font-num)", fontSize: 15, fontWeight: 700 }}>
                    +${billing === "monthly" ? a.price.monthly : a.price.yearly}
                    <span className="muted" style={{ fontSize: 11, fontWeight: 400 }}>/{billing === "monthly" ? "mo" : "yr"}</span>
                  </span>
                </div>
                <p className="muted" style={{ fontSize: 12, margin: 0 }}>{a.blurb}</p>
                <div className="row" style={{ marginTop: 10, gap: 7 }}>
                  <span style={{
                    width: 16, height: 16, borderRadius: 3, flexShrink: 0,
                    border: `2px solid ${active ? "var(--accent)" : "var(--border-2)"}`,
                    display: "grid", placeItems: "center",
                    background: active ? "var(--accent)" : "transparent",
                  }}>
                    {active && <Icon name="check" size={10} style={{ color: "#07090c" }} />}
                  </span>
                  <span className="muted" style={{ fontSize: 12 }}>{active ? "added" : "tap to add"}</span>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Order summary */}
      <div style={{
        border: "1px solid var(--border-2)", borderRadius: "var(--radius-sm)",
        padding: "16px 20px", marginBottom: 20, background: "var(--surf-2)", maxWidth: 420,
      }}>
        <div className="row between" style={{ fontSize: 13, marginBottom: 6 }}>
          <span className="muted">{chosenPlan?.name}</span>
          <span>${basePrice}/{billing === "monthly" ? "mo" : "yr"}</span>
        </div>
        {addonReload && (
          <div className="row between" style={{ fontSize: 13, marginBottom: 6 }}>
            <span className="muted">+ Reload Claimer</span>
            <span>+${ADDONS[0].price[billing]}/{billing === "monthly" ? "mo" : "yr"}</span>
          </div>
        )}
        {addonSeat && (
          <div className="row between" style={{ fontSize: 13, marginBottom: 6 }}>
            <span className="muted">+ Extra API Slot</span>
            <span>+${ADDONS[1].price[billing]}/{billing === "monthly" ? "mo" : "yr"}</span>
          </div>
        )}
        {promoInfo && (
          <div className="row between" style={{ fontSize: 13, marginBottom: 6, color: "var(--ok)" }}>
            <span>✓ {promoInfo.code}</span>
            <span>−{promoInfo.description}</span>
          </div>
        )}
        <div className="divider" style={{ margin: "10px 0" }} />
        <div className="row between" style={{ fontWeight: 700, fontSize: 15 }}>
          <span>Total</span>
          <span style={{ fontFamily: "var(--font-num)" }}>${total}/{billing === "monthly" ? "mo" : "yr"}</span>
        </div>
      </div>

      {/* Promo code */}
      <div className="row" style={{ gap: 8, marginBottom: 8, maxWidth: 380 }}>
        <input value={promoCode} onChange={e => { setPromoCode(e.target.value.toUpperCase()); setPromoInfo(null); setPromoErr(""); }}
          placeholder="Promo code (optional)"
          style={{ flex: 1, padding: "8px 12px", fontSize: 13, background: "var(--surf-2)", color: "var(--text)", border: "1px solid var(--border-2)", borderRadius: "var(--radius-sm)", textTransform: "uppercase", letterSpacing: ".06em", outline: "none" }} />
        <Btn sm kind="ghost" onClick={checkPromo} disabled={checking || !promoCode.trim()}>
          {checking ? "…" : "Apply"}
        </Btn>
      </div>
      {promoErr  && <p style={{ color: "var(--err)", fontSize: 13, marginTop: 4 }}>{promoErr}</p>}
      {payError  && <p style={{ color: "var(--err)", fontSize: 13, marginTop: 4 }}>{payError}</p>}

      <div className="row between" style={{ marginTop: 20 }}>
        <Btn onClick={() => goto("onboarding")}><Icon name="left" /> Back</Btn>
        <Btn kind="primary" lg onClick={checkout} disabled={checkingOut}>
          {checkingOut
            ? <><span className="spin" style={{ display: "inline-block" }}>◐</span> Starting…</>
            : <>Subscribe · ${total}/{billing === "monthly" ? "mo" : "yr"} <Icon name="arrow" /></>}
        </Btn>
      </div>
    </div>
  );
};

Object.assign(window, { Subscription });
