/* Command — the operator cockpit. Opens on the North Star and answers
   "is the engine converting content into growth?". */
const Screen_Command = ({ product, go }) => {
  const { kpi, fmt, series, queues, campaigns, insights } = MITA;
  const nsRef = React.useRef(null);
  React.useEffect(() => {
    if (nsRef.current && window.adCountUp) {
      return window.adCountUp(nsRef.current, { to: kpi.northStar, duration: 1100, format: (v) => Math.round(v).toLocaleString('en-US') });
    }
  }, []);

  const tree = [
    { label: 'Creators', value: kpi.creators, stage: 'Supply' },
    { label: 'Assets QA-passed', value: kpi.assets, stage: 'Produce' },
    { label: 'Posts', value: kpi.posts, stage: 'Distribute' },
    { label: 'Views', value: fmt.k(kpi.views), stage: 'Reach' },
    { label: 'Installs', value: fmt.n(kpi.installs), stage: 'Acquire' },
    { label: 'Subscriptions', value: fmt.n(kpi.subs), stage: 'North Star' },
  ];

  const fly = ['More campaigns', 'More performance data', 'Better creator scoring', 'Better hooks & QA', 'Better outcomes'];

  const queueDefs = [
    { key: 'outreach', n: queues.outreach, l: 'Outreach approvals', to: 'outreach' },
    { key: 'onboarding', n: queues.onboarding, l: 'Onboarding queue', to: 'outreach' },
    { key: 'qa', n: queues.qa, l: 'QA review', to: 'qa' },
    { key: 'recs', n: queues.recs, l: 'Recommendations', to: 'learning' },
  ];

  return (
    <div className="mt-page">
      <ScreenHead
        eyebrow="Command · The Growth Engine OS"
        question="Is the engine converting content into growth?"
        sub="One operator, the whole lifecycle — from sourced creator to attributed subscription, across every active product."
        actions={<Button variant="secondary" size="sm" trailingIcon={I.arrow} onClick={() => go('performance')}>Open performance</Button>}
      />

      {/* North Star + supporting */}
      <div className="mt-grid mt-grid--2 mt-fade" style={{ gridTemplateColumns: '1.15fr 1fr', alignItems: 'stretch' }}>
        <div className="mt-northstar">
          <div className="mt-northstar__pixel" />
          <p className="mt-northstar__label">{I.bolt} North Star · attributed paid conversions
            <HelpTip>Installs + subscriptions the engine can trace to a specific asset, creator and account. It captures the whole promise: content that turns into growth.</HelpTip>
          </p>
          <p className="mt-northstar__value" ref={nsRef}>0</p>
          <div className="mt-northstar__row">
            <div><p className="mono">{fmt.n(kpi.installs)}</p><p>Installs</p></div>
            <div><p className="mono">{fmt.n(kpi.subs)}</p><p>Subscriptions</p></div>
            <div><p className="mono">${kpi.cac}</p><p>Blended CAC</p></div>
            <div><p className="mono">{kpi.convPerDollar}</p><p>Conversions / $</p></div>
          </div>
        </div>

        <ChartFrame title="Are conversions trending up?" description="Installs and subscriptions, last 8 weeks" meta={<span className="mt-tag">best-effort attribution</span>}>
          <LineChart height={196} x={{ key: 'x' }} y={{ format: fmt.compact }} data={series}
            series={[{ key: 'installs', label: 'Installs', color: 's1' }, { key: 'subs', label: 'Subscriptions', color: 's2' }]} />
        </ChartFrame>
      </div>

      {/* KPI tree */}
      <div className="mt-section">
        <SectionH title="The production-to-conversion funnel" sub="every metric traces to source" />
        <Card>
          <CardBody>
            <div className="mt-tree">
              {tree.map((t, i) => (
                <div className="mt-tree__node" key={t.label}>
                  <p className="mt-tree__label">{t.label}</p>
                  <p className="mt-tree__val">{t.value}</p>
                  <p className="mt-tree__stage">{t.stage}</p>
                </div>
              ))}
            </div>
          </CardBody>
        </Card>
      </div>

      {/* KPI strip */}
      <div className="mt-section">
        <SectionH title="Efficiency & leverage" />
        <div className="mt-grid mt-grid--kpi">
          <Kpi label="QA pass rate" value={fmt.pct(kpi.qaPass)} delta="+3 pts" help="Share of submitted assets that clear technical, brand and brief checks first time." />
          <Kpi label="On-time publish" value={fmt.pct(kpi.onTime)} delta="+1.2 pts" />
          <Kpi label="Cost / video" value={`$${kpi.costPerVideo}`} delta="−$6" />
          <Kpi label="Asset reuse rate" value={fmt.pct(kpi.reuseRate)} delta="+5 pts" help="Winning assets re-cut for new accounts or repurposed as paid ads." />
          <Kpi label="Accounts / operator" value={kpi.accountsPerOp} delta="+2" help="The leverage health metric — it should rise every quarter. It tells you whether the company is becoming a product or staying a service." />
        </div>
      </div>

      {/* Queues + flywheel */}
      <div className="mt-section">
        <div className="mt-grid mt-grid--2" style={{ gridTemplateColumns: '1.2fr 1fr' }}>
          <div>
            <SectionH title="What needs a human?" sub="the engine runs on queues" />
            <div className="mt-queues">
              {queueDefs.map((q) => (
                <div key={q.key} className={`mt-queue ${q.n === 0 ? 'is-zero' : ''}`} onClick={() => go(q.to)}>
                  <span className="mt-queue__n">{q.n}</span>
                  <span className="mt-queue__l">{q.l}</span>
                </div>
              ))}
            </div>
          </div>
          <div>
            <SectionH title="Why it compounds" />
            <Card><CardBody>
              <div className="mt-flywheel">
                {fly.map((f, i) => (
                  <React.Fragment key={f}>
                    <span className="mt-fly__node">{f}</span>
                    <span className="mt-fly__arrow">{i === fly.length - 1 ? '↺' : '→'}</span>
                  </React.Fragment>
                ))}
              </div>
              <p className="mt-sub" style={{ marginTop: 'var(--space-sm)' }}>Every campaign feeds the Creative Learning Loop, which sharpens discovery, briefing and publishing — the moat competitors can't buy.</p>
            </CardBody></Card>
          </div>
        </div>
      </div>

      {/* Active campaigns */}
      <div className="mt-section">
        <SectionH title="Campaigns in flight" action={<Button variant="ghost" size="sm" onClick={() => go('performance')}>See all</Button>} />
        <Card><CardBody className="mt-rows">
          {campaigns.map((c) => (
            <div className="mt-row" key={c.id}>
              <span className="mt-tag">{c.id}</span>
              <div className="mt-row__main">
                <p className="mt-row__title">{c.name}</p>
                <p className="mt-row__meta">Objective: {c.objective} · Hook: “{c.hook}” · started {c.started}</p>
              </div>
              <span className="mono mt-muted" style={{ fontSize: 13 }}>{c.posts} posts</span>
              <Badge status={STATUS_TONE[c.status] || 'info'} tone="soft">{c.status}</Badge>
            </div>
          ))}
        </CardBody></Card>
      </div>
    </div>
  );
};
window.Screen_Command = Screen_Command;
