// ============ BILLING TAB ============
// Plan + this-month usage bar + per-agent breakdown. Reads usage from the
// live agents prop so it scales with whoever you've actually hired.

const BL_PLANS = [
  { id: "free",    name: "Free trial", price: 0,   agents: "1 agent, learning the ropes", support: "Self-serve" },
  { id: "starter", name: "Starter",    price: 49,  agents: "Up to 2 agents",              support: "Community"  },
  { id: "studio",  name: "Studio",     price: 199, agents: "Up to 8 agents",              support: "Email"      },
  { id: "scale",   name: "Scale",      price: 499, agents: "Up to 24 agents",             support: "Priority"   },
];

// Per-action usage charge kicks in on paid plans. Trial = no per-action.
const BL_PER_ACTION = 0.02;

function nextInvoiceDate() {
  const d = new Date();
  d.setMonth(d.getMonth() + 1, 1);
  return d.toLocaleString(undefined, { month: "short", day: "numeric" });
}

function BillingTab({ agents = [] }) {
  // Default to free trial — user upgrades manually when they're ready to pay.
  const [plan, setPlan]       = useState(() => {
    try { return localStorage.getItem("citrus_plan") || "free"; } catch { return "free"; }
  });
  const [picking, setPicking] = useState(false);
  const currentPlan = BL_PLANS.find((p) => p.id === plan) || BL_PLANS[0];

  // Free plan = no per-action charge; only paid plans accrue usage.
  const perAction = currentPlan.id === "free" ? 0 : BL_PER_ACTION;

  // Build usage rows from the live agents — total actions = each agent's runs
  const usage = agents.map((a) => ({
    agent:   a.name,
    id:      a.id,
    actions: a.runs || 0,
    cost:    `$${((a.runs || 0) * perAction).toFixed(2)}`,
    color:   a.palette ? a.palette.skin : "#888",
  }));
  const totalActions = usage.reduce((s, u) => s + u.actions, 0);
  const totalUsage   = totalActions * perAction;
  const nextInvoice  = currentPlan.price + totalUsage;

  const switchPlan = (id) => {
    setPlan(id);
    try { localStorage.setItem("citrus_plan", id); } catch {}
    setPicking(false);
    const next = BL_PLANS.find((p) => p.id === id);
    window.toast(`Switched to ${next.name}${next.price > 0 ? ` — $${next.price}/mo` : " — no charge"}`, "good");
  };

  return (
    <div className="bl-page">
      <div className="bl-grid">
        <div className="bl-card bl-card-plan">
          <div className="bl-tag">Plan</div>
          <div className="bl-plan-name">{currentPlan.name}</div>
          <div className="bl-plan-sub">{currentPlan.agents} · unlimited actions · {currentPlan.support} support</div>
          <div className="bl-plan-price">${currentPlan.price}<span>{currentPlan.price > 0 ? "/ mo" : " · trial"}</span></div>
          <button className="btn btn-ghost btn-sm" onClick={() => setPicking((v) => !v)}>
            {picking ? "Close" : "Change plan"}
          </button>
          {picking ? (
            <div className="bl-plan-picker">
              {BL_PLANS.map((p) => (
                <button
                  key={p.id}
                  className={`bl-plan-opt ${p.id === plan ? "is-on" : ""}`}
                  onClick={() => switchPlan(p.id)}
                  disabled={p.id === plan}
                >
                  <div className="bl-plan-opt-n">{p.name}</div>
                  <div className="bl-plan-opt-p">${p.price}/mo</div>
                  <div className="bl-plan-opt-s">{p.agents}</div>
                </button>
              ))}
            </div>
          ) : null}
        </div>

        <div className="bl-card bl-card-usage">
          <div className="bl-tag">This month · so far</div>
          <div className="bl-usage-n">{totalActions.toLocaleString()}</div>
          <div className="bl-usage-l">
            {agents.length === 0
              ? "No agents on shift yet"
              : `actions across ${agents.length} agent${agents.length === 1 ? "" : "s"}`}
          </div>
          {agents.length === 0 ? null : (
            <>
              <div className="bl-bar">
                {usage.map((u) => (
                  <div
                    key={u.agent}
                    className="bl-bar-seg"
                    style={{ flex: Math.max(u.actions, 0.01), background: u.color }}
                    title={`${u.agent}: ${u.actions}`}
                  />
                ))}
              </div>
              <div className="bl-bar-key">
                {usage.map((u) => (
                  <div key={u.agent} className="bl-key">
                    <span className="bl-key-d" style={{ background: u.color }} />
                    {u.agent} · {u.actions.toLocaleString()}
                  </div>
                ))}
              </div>
            </>
          )}
        </div>

        <div className="bl-card bl-card-next">
          <div className="bl-tag">Next invoice · {nextInvoiceDate()}</div>
          <div className="bl-next-n">${nextInvoice.toFixed(2)}</div>
          <div className="bl-next-l">
            {currentPlan.price === 0 && totalUsage === 0
              ? "Free trial · no charges yet"
              : `$${currentPlan.price} plan${totalUsage > 0 ? ` + $${totalUsage.toFixed(2)} usage` : " · no usage yet"}`}
          </div>
          <a className="btn btn-ghost btn-sm" href="invoice.html">View invoices</a>
        </div>
      </div>

      <div className="bl-table">
        <div className="bl-tag">Per-agent breakdown</div>
        {agents.length === 0 ? (
          <div className="kn-empty">No agents on shift yet — once you hire one, their usage will appear here.</div>
        ) : (
          <table className="bl-tbl">
            <thead>
              <tr><th>Agent</th><th>Actions</th><th>This month</th><th>Avg / action</th><th></th></tr>
            </thead>
            <tbody>
              {usage.map((u) => (
                <tr key={u.id}>
                  <td><span className="bl-tbl-mark" style={{ background: u.color }} />{u.agent}</td>
                  <td>{u.actions.toLocaleString()}</td>
                  <td>{u.cost}</td>
                  <td>{u.actions > 0 ? `$${(parseFloat(u.cost.slice(1)) / u.actions).toFixed(3)}` : "—"}</td>
                  <td><a href={`invoice.html?agent=${u.id}`} className="bl-tbl-link">View →</a></td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}

window.BillingTab = BillingTab;
