// =================================================================
// pw-screens-op-publishers.jsx — Operator · Publishers (tenant list)
//
// The tenant list, and the way in to creating one. It lived on Platform Overview until 2026-08-05,
// which made provisioning something you had to already know was there: Overview reads as a summary,
// so an actionable table on it is easy to scroll past. Overview keeps the Publishers count as a KPI
// and that number now links here.
//
// The create button sits on the list rather than opening a dialog because creating a publisher ends
// in an API key shown exactly once — see pw-screens-op-publisher-create.jsx for why that must not
// live somewhere a stray click can dismiss.
// =================================================================

const PublishersScreen = ({ data, setData }) => {
  const publishers = data.publishers || [];
  const plans = data.platformPlans || [];

  // Refresh on arrival so a tenant created in another tab, or by API, shows up without a reload.
  // Best-effort and silent: the list already on screen is not wrong, just possibly stale, and an
  // error toast on a background refresh is noise the operator cannot act on.
  React.useEffect(() => {
    window.__api.read("listPublishers")
      .then((rows) => setData((d) => ({ ...d, publishers: rows })))
      .catch(() => {});
  }, [setData]);

  const totalSubs = publishers.reduce((a, p) => a + (p.subscribers || 0), 0);
  const active = publishers.filter((p) => p.status === "active").length;
  const mrr = publishers.reduce((a, p) => {
    const plan = plans.find((pl) => pl.plan_code === p.plan_code);
    return a + ((plan && plan.price_fiat) || 0);
  }, 0);

  return (
    <Screen>
      <PageHead
        icon={IconBuilding}
        title="Publishers"
        subtitle="Every tenant on the platform, and the way in to adding one."
        actions={<Btn kind="primary" size="sm" onClick={() => window.__nav("publisher-create")}>Create publisher</Btn>}
      />

      <KpiGrid>
        <StatCard label="Publishers" value={publishers.length} sub="tenants" icon={<IconBuilding size={16}/>}/>
        <StatCard label="Active" value={active} sub="live tenants" icon={<IconActivity size={16}/>}/>
        <StatCard label="Total subscribers" value={fmt.compact(totalSubs)} sub="across tenants" icon={<IconUsers size={16}/>}/>
        <StatCard label="Platform MRR" value={fmt.currency(mrr)} sub="recurring" icon={<IconReceipt size={16}/>}/>
      </KpiGrid>

      <Card title="Tenants" subtitle="Plan, status and scale. Select a row to configure it." padded={false}>
        <DataTable
          rows={publishers}
          keyField="publisher_id"
          defaultSort={{ key: "subscribers", dir: "desc" }}
          rowsPerPage={25}
          stickyHeader
          // Publisher Config is the per-tenant editor and it has its own picker, so this is a
          // shortcut rather than a new screen. It selects nothing itself — the row click is the
          // selection — which is why the config screen still opens on its own default tenant.
          onRowClick={() => window.__nav("publisher-config")}
          empty="No publishers yet. Create the first one."
          columns={[
            { key: "name", label: "Publisher", render: (r) => <strong style={{ color: "var(--ink)" }}>{r.name}</strong> },
            { key: "plan_code", label: "SaaS plan", render: (r) => <Pill tone="accent" style={{ textTransform: "capitalize" }}>{r.plan_code}</Pill> },
            { key: "subscribers", label: "Subscribers", align: "right", render: (r) => <span style={{ fontFamily: "var(--mono)", fontSize: 12.5 }}>{fmt.number(r.subscribers)}</span> },
            { key: "status", label: "Status", render: (r) => <StatusPill status={r.status}/> },
            {
              key: "publisher_id", label: "Publisher ID",
              render: (r) => <span style={{ fontFamily: "var(--mono)", fontSize: 11.5, color: "var(--muted-2)" }}>{r.publisher_id}</span>,
            },
          ]}
        />
      </Card>
    </Screen>
  );
};

Object.assign(window, { PublishersScreen });
