/* Guide — the "why" behind every metric: definition, formula, when it's
   used, and the benchmark numbers that define success. Plus a concept
   glossary. This is the reference Mike can point anyone to. */

const GUIDE_METRICS = [
  { cat: 'North Star', name: 'Attributed paid conversions',
    formula: 'Σ (installs + subscriptions) traceable to a specific asset / creator / account',
    what: 'The single number that captures the whole promise: content that turns into growth.',
    why: 'It balances volume with quality — a viral clip that drives no installs does not move it. It is the metric the whole KPI tree rolls up to.',
    when: 'The headline on Command; the number every campaign is ultimately judged on.',
    bench: [['good', '↑ every month'], ['watch', 'flat 30d'], ['bad', 'declining']] },

  { cat: 'Supply', name: 'Active roster size',
    formula: 'count(creators where status = active)',
    what: 'Creators who have cleared the trial gate and are producing.',
    why: 'Output is supply-constrained early — no roster, no volume. Grows the top of the funnel.',
    when: 'Discovery + Command supply metrics.',
    bench: [['good', '+3–5 / month'], ['watch', 'flat'], ['bad', 'shrinking']] },
  { cat: 'Supply', name: 'Creator retention',
    formula: 'creators retained this month ÷ creators eligible for renewal',
    what: 'Share of trialled creators kept on for the next monthly cycle.',
    why: 'Retention is the quality signal for sourcing — high churn means Discovery scoring needs calibration.',
    when: 'Monthly roster review.',
    bench: [['good', '≥ 70%'], ['watch', '50–70%'], ['bad', '< 50%']] },

  { cat: 'Production', name: 'QA pass rate',
    formula: 'assets passing QA first time ÷ assets submitted',
    what: 'Share of submitted assets that clear technical, brand and brief checks on the first pass.',
    why: 'Rework is the silent cost of content ops. A rising pass rate means briefs + creators are dialled in.',
    when: 'Content QA + Command efficiency.',
    bench: [['good', '≥ 75%'], ['watch', '55–75%'], ['bad', '< 55%']] },
  { cat: 'Production', name: 'Brief-to-passing-asset rate',
    formula: 'assets passing QA ÷ briefs sent',
    what: 'How reliably a brief becomes a usable asset.',
    why: 'Ties brief quality to output — low rate means briefs are ambiguous or mis-matched to the creator.',
    when: 'Briefs + production reviews.',
    bench: [['good', '≥ 60%'], ['watch', '40–60%'], ['bad', '< 40%']] },

  { cat: 'Distribution', name: 'On-time publish rate',
    formula: 'posts published within target window ÷ scheduled posts',
    what: 'Reliability of the publishing orchestrator against its schedule.',
    why: 'Cadence and timing drive first-hour reach; missed slots waste warmed accounts.',
    when: 'Publishing + Command.',
    bench: [['good', '≥ 95%'], ['watch', '85–95%'], ['bad', '< 85%']] },
  { cat: 'Distribution', name: 'Posts per active account',
    formula: 'posts published ÷ active accounts',
    what: 'How hard each account is working, at a healthy cadence.',
    why: 'Too low wastes account inventory; too high risks rate-limits and bans.',
    when: 'Publishing account health.',
    bench: [['good', '3–7 / wk'], ['watch', '1–3 / wk'], ['bad', '> 10 / wk (ban risk)']] },

  { cat: 'Reach', name: 'Engagement rate',
    formula: '(likes + comments + shares + saves) ÷ views',
    what: 'How strongly viewers respond to a post.',
    why: 'A leading indicator the platform algorithm uses to expand reach — the cheapest early signal of a winning hook.',
    when: 'Performance; hook analysis.',
    bench: [['good', '≥ 6%'], ['watch', '3–6%'], ['bad', '< 3%']] },

  { cat: 'Acquisition & Monetisation', name: 'Install-rate (view→install)',
    formula: 'attributed installs ÷ views',
    what: 'How efficiently reach converts into installs.',
    why: 'Turns vanity reach into acquisition — the bridge from views to the North Star.',
    when: 'Performance funnel; hook attribution.',
    bench: [['good', '≥ 1.0%'], ['watch', '0.3–1.0%'], ['bad', '< 0.3%']] },
  { cat: 'Acquisition & Monetisation', name: 'Install→subscription rate',
    formula: 'attributed subscriptions ÷ attributed installs',
    what: 'Share of acquired installs that convert to paying subscribers.',
    why: 'Guards against low-intent installs — high views + installs but low subs means the audience is wrong.',
    when: 'Performance; North-Star quality check.',
    bench: [['good', '≥ 12%'], ['watch', '6–12%'], ['bad', '< 6%']] },

  { cat: 'Efficiency', name: 'Blended CAC',
    formula: '(creator + compute + media spend) ÷ attributed installs',
    what: 'All-in cost to acquire one install through the engine.',
    why: 'The organic-UGC thesis lives or dies here — near-zero marginal cost per clip is the whole edge over paid ads.',
    when: 'Performance; unit economics.',
    bench: [['good', '≤ $1.00'], ['watch', '$1–3'], ['bad', '> $3']] },
  { cat: 'Efficiency', name: 'Cost per video',
    formula: '(creator trials + production/compute) ÷ assets produced',
    what: 'Fully-loaded cost to produce one QA-passed asset.',
    why: 'The denominator of scale — automation should push this down every quarter.',
    when: 'Command efficiency.',
    bench: [['good', '≤ $30'], ['watch', '$30–60'], ['bad', '> $60']] },
  { cat: 'Efficiency', name: 'Conversions per dollar',
    formula: 'attributed conversions ÷ total spend',
    what: 'North-Star output per dollar in.',
    why: 'The single efficiency ratio that says whether spend is compounding or leaking.',
    when: 'Performance; board-level view.',
    bench: [['good', '≥ 3.0'], ['watch', '1–3'], ['bad', '< 1']] },

  { cat: 'Learning', name: 'Hook win-rate trend',
    formula: 'Δ install-rate of top-quartile hooks vs roster baseline, over time',
    what: 'Whether the hooks the loop recommends keep beating the average.',
    why: 'Proof the flywheel is turning — the moat is measurable lift that accrues, not a one-off hit.',
    when: 'Learning Loop.',
    bench: [['good', '↑ each cycle'], ['watch', 'flat'], ['bad', 'reverting']] },
  { cat: 'Learning', name: 'Asset reuse rate',
    formula: 'assets reused or repurposed as ads ÷ QA-passed assets',
    what: 'Share of winning assets given a second life (new accounts, paid ads).',
    why: 'Reuse is free growth — the highest-margin output of the library and the paid-repurposing upsell.',
    when: 'Learning Loop; Command efficiency.',
    bench: [['good', '≥ 20%'], ['watch', '10–20%'], ['bad', '< 10%']] },
  { cat: 'Learning', name: 'Recommendation acceptance',
    formula: 'recommendations accepted by an operator ÷ recommendations surfaced',
    what: 'How often a human agrees with the loop.',
    why: 'A proxy for model trust and calibration — too low means the loop is noisy; too high (≈100%) means no one is checking.',
    when: 'Learning Loop.',
    bench: [['good', '65–85%'], ['watch', '40–65%'], ['bad', '< 40%']] },

  { cat: 'Leverage', name: 'Managed accounts per operator',
    formula: 'active accounts ÷ human operators on the critical path',
    what: 'The core health ratio — how much one person can run.',
    why: 'It is the whole thesis in one number: rising = becoming a product; flat = still a service. It should climb every quarter.',
    when: 'Command; the metric Mike watches most.',
    bench: [['good', '↑ every quarter'], ['watch', 'flat'], ['bad', 'falling']] },
  { cat: 'Leverage', name: 'Human-touch rate',
    formula: 'conversations needing a human ÷ total conversations',
    what: 'Share of outreach the agent could not handle alone.',
    why: 'Lower is better over time — it is the automation dividend made visible.',
    when: 'Outreach.',
    bench: [['good', '≤ 15%'], ['watch', '15–30%'], ['bad', '> 30%']] },
];

const GUIDE_CONCEPTS = [
  { term: 'The Growth Engine OS', body: 'Seven modules (A–G) across four stages — Acquire, Produce, Distribute, Measure & Learn — that turn short-form content into installs and subscriptions, run by one operator instead of a content team.' },
  { term: 'Human-in-the-loop', body: 'A step where a person must act — for judgment, trust or exceptions. Agents handle volume and classification; humans hold strategy, creative direction and final approval. Every queue in the app is a human-in-the-loop checkpoint.' },
  { term: 'Attribution (best-effort)', body: 'Linking an outcome (install, subscription) back to the asset, creator, account and hook that drove it — via tracked links, promo codes and UTMs. Platform privacy limits make this best-effort, and the app is explicit about coverage.' },
  { term: 'The learning loop / flywheel', body: 'Every campaign produces data that improves the next: better creator scores, hook seeds and posting timing feed back into Discovery, Briefing and Publishing. Competitors can buy the same AI tools but not the accumulated, conversion-linked dataset.' },
  { term: 'Trial gate', body: 'A paid trial (~US$150 for 10 videos) every new creator clears before joining the roster. A cheap, fast quality filter that keeps roster standards high without long commitments.' },
  { term: 'Operational leverage', body: 'Managed accounts per operator — the ratio that says whether the company is becoming a software product or staying a headcount-bound service. The goal is to raise it every quarter.' },
  { term: 'Done-with-you', body: 'The Phase-2 commercial model: an external client gets portal access and approves their own briefs and sensitive assets, while campaigns run on the same engine with operator support.' },
  { term: 'The moat', body: 'Not AI video generation, which will commoditise — but the operating system around it: the creator dataset, workflow intelligence, performance benchmarks, the reusable asset library and the account network.' },
];

const Screen_Guide = ({ product, go }) => {
  const cats = ['All', ...Array.from(new Set(GUIDE_METRICS.map((m) => m.cat)))];
  const [cat, setCat] = React.useState('All');
  const shown = GUIDE_METRICS.filter((m) => cat === 'All' || m.cat === cat);

  return (
    <div className="mt-page">
      <ScreenHead
        eyebrow="Reference · Glossary & Playbook"
        question="What does each number mean — and what does “good” look like?"
        sub="The why behind every feature: how each metric is calculated, when you use it, and the benchmark numbers that define success. Point anyone here."
        actions={<Button size="sm" leadingIcon={I.bolt} onClick={() => window.__mitaStartTour && window.__mitaStartTour()}>Replay tour</Button>}
      />

      <div className="mt-guide-toc mt-fade">
        {cats.map((c) => (
          <button key={c} className={c === cat ? 'is-active' : ''} onClick={() => setCat(c)}>{c}</button>
        ))}
      </div>

      <div className="mt-grid mt-grid--2 mt-fade">
        {shown.map((m) => (
          <div className="mt-metric" key={m.name}>
            <div className="mt-metric__head">
              <h3 className="mt-metric__name">{m.name}</h3>
              <span className="mt-tag">{m.cat}</span>
            </div>
            <code className="mt-metric__formula">{m.formula}</code>
            <div className="mt-metric__row"><b>What</b><span>{m.what}</span></div>
            <div className="mt-metric__row"><b>Why</b><span>{m.why}</span></div>
            <div className="mt-metric__row"><b>When</b><span>{m.when}</span></div>
            <div className="mt-metric__row"><b>Success</b>
              <span className="mt-bench">
                {m.bench.map(([tone, label], i) => <span key={i} className={tone}>{tone === 'good' ? 'Good ' : tone === 'watch' ? 'Watch ' : 'Risk '}{label}</span>)}
              </span>
            </div>
          </div>
        ))}
      </div>

      <div className="mt-section">
        <SectionH title="Concepts" sub="the vocabulary of the engine" />
        <Card className="mt-fade"><CardBody>
          <Accordion type="single" variant="bordered" items={GUIDE_CONCEPTS.map((c, i) => ({
            value: 'c' + i, trigger: c.term, content: <p className="mt-sub" style={{ fontSize: 13.5, margin: 0 }}>{c.body}</p>,
          }))} />
        </CardBody></Card>
      </div>
    </div>
  );
};
window.Screen_Guide = Screen_Guide;
