// Atlas · Billing & plan management page

const { useState: useBillState, useEffect: useBillEffect } = React;

const TIER_META = {
  unverified:   { label: "Unverified (Restricted)", price: "Restricted", blurb: "1 report limit until your email address is verified." },
  researcher:   { label: "Researcher", price: "Free",     blurb: "2 reports per month, all report types, public research sources." },
  professional: { label: "Professional", price: "$10/mo", blurb: "4 reports per month plus your own Internal Knowledge Repository." },
  enterprise:   { label: "Enterprise", price: "Custom",   blurb: "Custom volume, shared team repository, unlimited users." },
};

function BillingPage({ user, setUser, onBack }) {
  const [me, setMe] = useBillState(user || null);
  const [busy, setBusy] = useBillState(false);
  const [error, setError] = useBillState(null);

  // Refresh on mount so a return from Stripe Checkout reflects the new tier.
  useBillEffect(() => {
    let live = true;
    (async () => {
      try {
        const res = await fetch("/api/me");
        if (!res.ok) return;
        const data = await res.json();
        if (!live) return;
        setMe(data);
        if (setUser) setUser((u) => (u ? { ...u, ...data } : u));
      } catch {}
    })();
    return () => { live = false; };
  }, []);

  const tier = me?.tier || "researcher";
  const meta = TIER_META[tier] || TIER_META.researcher;
  const used = me?.reports_used ?? 0;
  const limit = me?.reports_limit; // null = unlimited
  const status = me?.subscription_status;

  const go = async (path) => {
    setBusy(true); setError(null);
    try {
      const res = await fetch(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.detail || "Something went wrong.");
      if (data.url) { window.location.href = data.url; return; }
    } catch (e) {
      setError(e.message || "Something went wrong.");
    } finally {
      setBusy(false);
    }
  };

  const card = {
    background: "var(--bg-1)", border: "1px solid var(--line-2)", borderRadius: 12,
    padding: "24px 26px", maxWidth: 560,
  };

  return (
    <div style={{ padding: "8px 64px 64px" }}>
      <div style={{ ...card }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 16 }}>
          <div>
            <div style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.08em", color: "var(--ink-3)", textTransform: "uppercase" }}>Current plan</div>
            <div style={{ fontSize: 22, fontWeight: 600, color: "var(--ink)", marginTop: 4 }}>{meta.label}</div>
          </div>
          <div style={{ fontSize: 20, fontWeight: 600, color: "var(--ink)" }}>{meta.price}</div>
        </div>
        <div style={{ fontSize: 13.5, color: "var(--ink-2)", lineHeight: 1.55, marginTop: 10 }}>{meta.blurb}</div>

        <div style={{ height: 1, background: "var(--line-2)", margin: "20px 0" }} />

        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <div style={{ fontFamily: "var(--mono)", fontSize: 12, color: "var(--ink-2)" }}>Reports this month</div>
          <div style={{ fontFamily: "var(--mono)", fontSize: 13, color: "var(--ink)", fontWeight: 600 }}>
            {limit == null ? `${used} · unlimited` : `${used} / ${limit}`}
          </div>
        </div>
        {status && (
          <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 8 }}>
            Subscription status: {status}
          </div>
        )}

        <div style={{ height: 1, background: "var(--line-2)", margin: "20px 0" }} />

        {error && (
          <div style={{ color: "var(--rose)", fontSize: 13, marginBottom: 12 }}>{error}</div>
        )}

        {(tier === "unverified" || tier === "researcher") && (
          <div>
            {tier === "unverified" ? (
              <div style={{
                background: "var(--orange-tint, #fff7ed)",
                border: "1px solid var(--orange, #fed7aa)",
                borderRadius: "8px",
                padding: "12px 16px",
                fontSize: "13.5px",
                color: "var(--orange-ink, #c2410c)",
                fontWeight: 500,
                marginBottom: "16px",
                lineHeight: "1.55",
                display: "flex",
                alignItems: "center",
                gap: "8px"
              }}>
                <span style={{ fontSize: "16px" }}>⚠️</span>
                <span>
                  Please verify your email address via the banner at the top of the page to unlock the standard Researcher plan (2 free reports/mo) or to upgrade to Professional.
                </span>
              </div>
            ) : (
              <div style={{ fontSize: 13.5, color: "var(--ink-2)", marginBottom: 14, lineHeight: 1.55 }}>
                Upgrade to Professional for 4 reports a month and your own Internal Knowledge Repository.
              </div>
            )}
            <button className="btn accent" disabled={busy || tier === "unverified"} onClick={() => go("/api/billing/checkout")}>
              {busy ? "Redirecting…" : "Upgrade to Professional — $10/mo"}
            </button>
          </div>
        )}

        {tier === "professional" && (
          <div>
            <div style={{ fontSize: 13.5, color: "var(--ink-2)", marginBottom: 14, lineHeight: 1.55 }}>
              Update your card, view invoices, or cancel anytime through the billing portal.
            </div>
            <button className="btn" disabled={busy} onClick={() => go("/api/billing/portal")}>
              {busy ? "Redirecting…" : "Manage billing"}
            </button>
          </div>
        )}

        {tier === "enterprise" && (
          <div style={{ fontSize: 13.5, color: "var(--ink-2)", lineHeight: 1.55 }}>
            Your plan is managed by our team. For changes to volume, seats, or your shared
            repository, reach out at <a href="mailto:ramy@notedsource.com">ramy@notedsource.com</a> or{" "}
            <a href="/inquire">contact us</a>.
          </div>
        )}
      </div>

      <button
        onClick={onBack}
        style={{ marginTop: 22, background: "none", border: "none", color: "var(--ink-3)", cursor: "pointer", fontFamily: "var(--mono)", fontSize: 12 }}
      >← Back to reports</button>
    </div>
  );
}
