/* Publishing Orchestrator (Module E) — the right asset on the right
   account at the right time, at volume, with account health. */
const Screen_Publishing = ({ product, go }) => {
  const { fmt } = MITA;
  const accounts = MITA.accounts;
  const healthTone = { Healthy: 'success', Warming: 'warning', 'Rate-limited': 'error' };

  const columns = [
    { key: 'when', header: 'When', sortable: true, sticky: true, cell: (r) => <span className="mono">{r.when}</span> },
    { key: 'hook', header: 'Asset', cell: (r) => (
      <span><p style={{ margin: 0, fontSize: 13, fontWeight: 600 }}>“{r.hook}”</p><p style={{ margin: 0, fontSize: 12, color: 'var(--fg-muted)' }} className="mono">{r.asset}</p></span>) },
    { key: 'platform', header: 'Platform', sortable: true },
    { key: 'account', header: 'Account', cell: (r) => { const a = accounts.find((x) => x.id === r.account); return <span className="mono" style={{ fontSize: 12 }}>{a ? a.handle : '—'}</span>; } },
    { key: 'postId', header: 'Post ID', align: 'right', cell: (r) => <span className="mono" style={{ fontSize: 12, color: 'var(--fg-muted)' }}>{r.postId}</span> },
    { key: 'status', header: 'Status', sortable: true, cell: (r) => <Badge status={STATUS_TONE[r.status] || 'neutral'} tone="soft" dot>{r.status}</Badge> },
  ];

  const failing = accounts.find((a) => a.health === 'Rate-limited');

  return (
    <div className="mt-page">
      <ScreenHead
        eyebrow="Distribute · Module E · Publishing Orchestrator"
        question="What's going out, and is every account healthy?"
        sub="Scheduling and posting across many accounts and platforms, adapting format per platform, with retries and account-health alerts. Every post links back to its asset and campaign."
        actions={<Button size="sm" leadingIcon={I.plus}>Schedule post</Button>}
      />

      <div className="mt-grid mt-grid--kpi mt-fade" style={{ marginBottom: 'var(--space-lg)' }}>
        <Kpi label="Posts published" value={fmt.n(MITA.kpi.posts)} delta="+18 this week" />
        <Kpi label="On-time rate" value={`${MITA.kpi.onTime}%`} delta="+1.2 pts" help="Posts that published within the target window of their scheduled time." />
        <Kpi label="Active accounts" value={accounts.length} />
        <Kpi label="Posts / active account" value={(MITA.kpi.posts / accounts.length).toFixed(1)} />
      </div>

      {failing && (
        <div className="mt-fade" style={{ marginBottom: 'var(--space-lg)' }}>
          <Alert variant="error" title={`Account issue · ${failing.handle} is rate-limited`}
            action={<Button size="sm" variant="ghost" onClick={() => go('learning')}>See recommendation</Button>}>
            Cadence auto-throttled and posts re-routed. The Learning Loop suggests shifting this product's cadence to a warmed account.
          </Alert>
        </div>
      )}

      <div className="mt-section" style={{ marginTop: 0 }}>
        <SectionH title="Account inventory & health" />
        <div className="mt-grid mt-grid--4 mt-fade">
          {accounts.map((a) => (
            <Card key={a.id}><CardBody>
              <div className="mt-spread">
                <span className="mono" style={{ fontSize: 13, fontWeight: 600 }}>{a.handle}</span>
                <span className="mt-dot" style={{ background: `var(--${healthTone[a.health] === 'error' ? 'error' : healthTone[a.health] === 'warning' ? 'warning' : 'success'}-500)` }} />
              </div>
              <p className="mt-row__meta" style={{ marginTop: 4 }}>{a.platform}</p>
              <div className="mt-spread" style={{ marginTop: 'var(--space-sm)' }}>
                <Badge status={healthTone[a.health]} tone="soft" size="sm">{a.health}</Badge>
                <span className="mono mt-muted" style={{ fontSize: 12 }}>{a.posts} posts</span>
              </div>
            </CardBody></Card>
          ))}
        </div>
      </div>

      <div className="mt-section">
        <SectionH title="Schedule & queue" sub="next up across all accounts" />
        <Card className="mt-fade"><CardBody>
          <DataTable columns={columns} data={MITA.posts.slice(0, 18)} rowKey="id" columnVisibility
            summary={`Showing 18 of ${MITA.posts.length} scheduled + published posts`} />
        </CardBody></Card>
      </div>
    </div>
  );
};
window.Screen_Publishing = Screen_Publishing;
