// Billing & Plan — trust-first billing wedge.
// Flat per-business pricing, free collaborator seats, no-surprises guarantee,
// two-click cancel, and a competitor cost calculator. Local/mock (no Stripe yet).

// Rough public monthly pricing for comparison only (per the competitor research).
const COMPETITOR_PRICING = {
  Hootsuite: { perSeat: 99, note: "per seat/mo (Professional+), channels capped" },
  "Sprout Social": { perSeat: 249, note: "per seat/mo (Standard)" },
  Buffer: { perChannel: 6, note: "per channel/mo (billed per channel)" },
  Later: { perBusiness: 45, note: "per social set/mo (Growth)" },
  Agorapulse: { perSeat: 49, note: "per user/mo (Standard)" }
};

function money(n) {
  return "$" + Math.round(n).toLocaleString();
}

function BillingPage() {
  const hub = window.useClearCast();
  const data = hub.data || {};
  const billing = data.billing || { plan: "free", status: "active" };
  const plans = data.billingPlans || [];
  const currentPlan = plans.find((p) => p.id === billing.plan) || plans[0] || { id: "free", name: "Free", price: 0 };
  const businessCount = (data.workspaces || []).length || 1;

  const [busy, setBusy] = React.useState("");
  const [calc, setCalc] = React.useState({ businesses: businessCount, channels: 5, seats: 4 });
  const [stripe, setStripe] = React.useState({ connected: !!data.stripeConnected, payablePlans: [] });
  React.useEffect(() => { ClearCastAPI.stripeStatus().then((s) => s && setStripe(s)).catch(() => {}); }, []);

  const checkout = async (planId) => { setBusy(planId); try { await hub.actions.startCheckout(planId); } finally { setBusy(""); } };
  const openPortal = async () => { setBusy("portal"); try { await hub.actions.openBillingPortal(); } finally { setBusy(""); } };

  const changePlan = async (planId) => {
    if (planId === billing.plan) return;
    setBusy(planId);
    try { await hub.actions.changePlan(planId); } finally { setBusy(""); }
  };
  const cancel = async () => { setBusy("cancel"); try { await hub.actions.cancelBilling(); } finally { setBusy(""); } };
  const reactivate = async () => { setBusy("reactivate"); try { await hub.actions.reactivateBilling(); } finally { setBusy(""); } };

  // ClearCast cost = businesses x plan price (paid plan), all seats free.
  const ccPlanPrice = currentPlan.price > 0 ? currentPlan.price : 39;
  const ccMonthly = calc.businesses * ccPlanPrice;
  const competitors = Object.entries(COMPETITOR_PRICING).map(([name, model]) => {
    let monthly = 0;
    if (model.perSeat) monthly = model.perSeat * calc.seats;
    else if (model.perChannel) monthly = model.perChannel * calc.channels * calc.businesses;
    else if (model.perBusiness) monthly = model.perBusiness * calc.businesses;
    return { name, monthly, note: model.note };
  });
  const maxMonthly = Math.max(ccMonthly, ...competitors.map((c) => c.monthly), 1);
  const avgCompetitor = competitors.reduce((s, c) => s + c.monthly, 0) / competitors.length;
  const savingsYr = Math.max(0, (avgCompetitor - ccMonthly) * 12);

  const guarantees = [
    ["Two-click cancel, anytime", "Cancel from web or mobile in two taps — no phone calls, no retention maze."],
    ["No silent renewals", "We email you 7, 3, and 1 days before any renewal. Trials never auto-charge."],
    ["Automatic prorated refunds", "Downgrade or cancel and unused time is refunded automatically — no support ticket."],
    ["Free collaborator seats", "Approvers, viewers, and external clients are always free and unlimited."],
    ["Price-stability pledge", "We never raise your price or shrink your plan's included channels after you buy."]
  ];

  return (
    <div className="page billing-page">
      {/* Current plan */}
      <div className="card" style={{ padding: 20, marginBottom: 16 }}>
        <div style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 12, alignItems: "center" }}>
          <div>
            <div className="muted" style={{ fontSize: 12 }}>Current plan · {data.workspace?.name || "this business"}</div>
            <div style={{ fontSize: 22, fontWeight: 750, marginTop: 2 }}>
              {currentPlan.name} {currentPlan.price > 0 ? <span style={{ fontSize: 15, color: "var(--text-2)", fontWeight: 600 }}>· {money(currentPlan.price)}/mo</span> : null}
            </div>
            <div className="muted" style={{ fontSize: 12.5, marginTop: 4 }}>
              {billing.status === "canceled"
                ? `Canceled — access continues${billing.renewsAt ? ` until ${billing.renewsAt}` : ""}. No further charges.`
                : billing.renewsAt ? `Renews ${billing.renewsAt}. We'll remind you first.` : "Free plan — no charges."}
            </div>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            {billing.status === "canceled"
              ? <button className="btn btn-primary" disabled={busy === "reactivate"} onClick={reactivate}>{busy === "reactivate" ? "Working…" : "Reactivate"}</button>
              : currentPlan.price > 0 && <button className="btn" disabled={busy === "cancel"} onClick={cancel}>{busy === "cancel" ? "Working…" : "Cancel plan"}</button>}
          </div>
        </div>
      </div>

      {/* Card payments (Stripe) — fully built; inert until Stripe keys are added */}
      <div className="card" style={{ padding: 16, marginBottom: 16, display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
        <span className={`pill ${stripe.connected ? "green" : "warn"}`}><span className="pill-dot" />{stripe.connected ? "Card payments connected" : "Card payments not connected"}</span>
        <div className="muted" style={{ fontSize: 12.5, flex: 1, minWidth: 220 }}>
          {stripe.connected
            ? "Paid plans check out securely through Stripe. Manage your card, invoices, or cancel from the billing portal."
            : "Plans are managed manually for now. Stripe Checkout, the customer portal, and webhooks are fully built in — add your Stripe keys to start charging cards automatically (no code changes)."}
        </div>
        {stripe.connected && <button className="btn btn-sm" disabled={busy === "portal"} onClick={openPortal}>{busy === "portal" ? "Opening…" : "Manage billing"}</button>}
      </div>

      {/* No-surprises guarantee */}
      <div className="card" style={{ padding: 20, marginBottom: 16 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>
          <Icon.Check width="18" height="18" style={{ color: "var(--accent-2)" }} />
          <h3 style={{ margin: 0, fontSize: 15 }}>No billing surprises — guaranteed</h3>
          <button className="btn btn-sm" style={{ marginLeft: "auto" }} onClick={() => hub.setPage && hub.setPage("status")}>System status & SLA</button>
        </div>
        <div className="billing-guarantees">
          {guarantees.map(([title, desc]) => (
            <div key={title} className="billing-guarantee">
              <Icon.Check width="15" height="15" style={{ color: "var(--accent-2)", flexShrink: 0, marginTop: 2 }} />
              <div><b style={{ fontSize: 13 }}>{title}</b><div className="muted" style={{ fontSize: 12 }}>{desc}</div></div>
            </div>
          ))}
        </div>
      </div>

      {/* Plans */}
      <div style={{ fontSize: 13.5, color: "var(--text-2)", fontWeight: 600, margin: "0 0 10px 2px" }}>Choose a plan — flat per business, every seat included free</div>
      <div className="billing-plans">
        {plans.map((plan) => {
          const isCurrent = plan.id === billing.plan;
          return (
            <div key={plan.id} className={`billing-plan ${isCurrent ? "current" : ""} ${plan.popular ? "popular" : ""}`}>
              {plan.popular && <span className="billing-plan-tag">Most popular</span>}
              <div style={{ fontWeight: 700, fontSize: 15 }}>{plan.name}</div>
              <div style={{ fontSize: 24, fontWeight: 800, margin: "6px 0" }}>{plan.price === 0 ? "Free" : <>{money(plan.price)}<span style={{ fontSize: 13, fontWeight: 600, color: "var(--text-3)" }}>/mo</span></>}</div>
              <div className="muted" style={{ fontSize: 12, minHeight: 48, lineHeight: 1.5 }}>{plan.blurb}</div>
              {(() => {
                const viaStripe = stripe.connected && plan.price > 0 && (stripe.payablePlans || []).includes(plan.id);
                return (
                  <button
                    className={`btn btn-sm ${isCurrent ? "" : "btn-primary"}`}
                    disabled={isCurrent || !!busy}
                    onClick={() => (viaStripe ? checkout(plan.id) : changePlan(plan.id))}
                    style={{ width: "100%", marginTop: 8, justifyContent: "center" }}
                  >
                    {isCurrent ? "Current plan" : busy === plan.id ? "Working…" : viaStripe ? `Upgrade · ${money(plan.price)}/mo` : `Switch to ${plan.name}`}
                  </button>
                );
              })()}
            </div>
          );
        })}
      </div>

      {/* Competitor cost calculator */}
      <div className="card" style={{ padding: 20, marginTop: 18 }}>
        <h3 style={{ margin: "0 0 4px", fontSize: 15 }}>What you'd pay elsewhere</h3>
        <div className="muted" style={{ fontSize: 12, marginBottom: 16 }}>Estimated monthly cost based on public pricing — for comparison only.</div>
        <div className="billing-calc-inputs">
          {[
            ["businesses", "Businesses / brands", 1, 10],
            ["channels", "Channels per business", 1, 12],
            ["seats", "Team members", 1, 20]
          ].map(([key, label, min, max]) => (
            <label key={key} className="billing-calc-input">
              <span>{label}</span>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <input type="range" min={min} max={max} value={calc[key]} onChange={(e) => setCalc({ ...calc, [key]: Number(e.target.value) })} style={{ flex: 1, accentColor: "var(--accent)" }} />
                <b style={{ width: 24, textAlign: "right" }}>{calc[key]}</b>
              </div>
            </label>
          ))}
        </div>
        <div className="billing-calc-rows" style={{ marginTop: 16 }}>
          {[{ name: "ClearCast", monthly: ccMonthly, note: `${money(ccPlanPrice)}/business · seats free`, us: true }, ...competitors]
            .sort((a, b) => a.monthly - b.monthly)
            .map((row) => (
              <div key={row.name} className={`billing-calc-row ${row.us ? "us" : ""}`}>
                <div className="billing-calc-name"><b>{row.name}</b><small className="muted">{row.note}</small></div>
                <div className="billing-calc-bar"><span style={{ width: `${(row.monthly / maxMonthly) * 100}%` }} /></div>
                <div className="billing-calc-cost">{money(row.monthly)}<small className="muted">/mo</small></div>
              </div>
            ))}
        </div>
        {savingsYr > 0 && (
          <div style={{ marginTop: 14, padding: 12, borderRadius: 12, background: "var(--accent-softer)", border: "1px solid rgba(20,184,138,0.25)", fontSize: 13 }}>
            Estimated savings of <b style={{ color: "var(--accent-2)" }}>{money(savingsYr)}/year</b> vs. the average of these tools — with free collaborator seats and no per-channel fees.
          </div>
        )}
      </div>
    </div>
  );
}

window.BillingPage = BillingPage;
