// mandate.jsx — Capability Matrix
//
// Proves the platform's mandate — "manage, organize, monetize music catalogs" —
// by enumerating every supporting surface across the three verbs and deep-linking
// into them.
//
// Triple split:
//   MANAGE   — rights, agreements, registrations, compliance (control of the catalog)
//   ORGANIZE — ingest, normalize, dedupe, structure (state of the catalog)
//   MONETIZE — distribution, royalties, licensing, optimization (revenue from the catalog)

(function () {
  const { useState, useMemo } = React;

  // ── Capability matrix ────────────────────────────────────────────────
  // Each capability: { label, route, payload?, evidence }
  // Each verb has Pillars (groups of capabilities)

  const VERBS = {
    manage: {
      key: 'manage',
      label: 'Manage',
      tag: '01',
      blurb: 'Control of the catalog — who owns what, on what terms, registered where, and accountable to whom.',
      pillars: [
        {
          name: 'Rights & ownership',
          caps: [
            { label: 'Works (553)', route: 'catalog', evidence: 'Full ISWC-keyed catalog, owned vs administered, share hierarchy.' },
            { label: 'Recordings & releases', route: 'catalog', payload: { tab: 'recordings' }, evidence: 'ISRC + release graph, edition merging, P-line.' },
            { label: 'Directory of parties', route: 'directory', evidence: 'Profiles, publishers, labels, societies — single canonical record per party.' },
            { label: 'Sub-publisher map', route: 'subpubs', evidence: 'Per-territory sub-pub appointments, retention windows.' },
            { label: 'Copyright register', route: 'copyright', evidence: 'PA / SR filings + renewal calendar.' },
          ],
        },
        {
          name: 'Agreements',
          caps: [
            { label: 'Agreement library', route: 'agreement-templates', evidence: 'Co-pub, admin, sync-rep, sub-pub, label-services templates.' },
            { label: 'Live agreement detail', route: 'agreement', evidence: 'Waterfall, recoupment ledger, reversion timeline, e-sign block.' },
            { label: 'Party indicators', route: 'directory', evidence: 'Owned (★) / Administered (◆) cascade derived from agreements.' },
          ],
        },
        {
          name: 'Registrations & society compliance',
          caps: [
            { label: 'CWR submissions', route: 'cwr', evidence: 'v2.1 / 2.2 / 3.0 / 3.1 generator, 250+ byte assertions, society rules.' },
            { label: 'CAF agreements', route: 'caf', evidence: 'CAF v1.2 + v3.0 builder, validation, ack pipeline.' },
            { label: 'MLC sync', route: 'mlc', evidence: 'Match status, claim rate, conflict resolution.' },
            { label: 'Black-box claims', route: 'blackbox', evidence: 'Unmatched income capture + claim ranking.' },
            { label: 'Conformance report', route: 'conformance', evidence: 'Model-locked import audit + ongoing health.' },
          ],
        },
        {
          name: 'Operations & control',
          caps: [
            { label: 'Issues queue', route: 'issues', evidence: 'Live data-quality, ownership, registration backlog.' },
            { label: 'Inbox', route: 'inbox', evidence: 'CWR acks, statement errors, agreement signatures, society messages.' },
            { label: 'Audit log', route: 'audit', evidence: 'Every change, who, when, with what input.' },
            { label: 'Automations', route: 'automations', evidence: 'Trigger → condition → action rules, schedules, run history.' },
            { label: 'Reports', route: 'reports', evidence: 'Statement-out, royalty-in, registration coverage, audit pack.' },
          ],
        },
      ],
    },

    organize: {
      key: 'organize',
      label: 'Organize',
      tag: '02',
      blurb: 'State of the catalog — clean ingestion, identifiers, metadata, structure, lineage.',
      pillars: [
        {
          name: 'Ingest',
          caps: [
            { label: 'Bulk catalog import', route: 'bulk-import', evidence: 'Sniff/parse/map/validate/dedupe/apply for CSV/XLSX/DDEX/CWR/JSON.' },
            { label: 'DSP analytics import', route: 'dsp-import', evidence: '18 vendor adapters across 12 DSPs (S4A/AMfA/YouTube/Tidal/etc.).' },
            { label: 'Statement parser', route: 'stmt-parser', evidence: '14+ statement-format adapters with learning matcher.' },
            { label: 'API integrations', route: 'integrations', evidence: 'Live API pulls — Spotify, Apple, YouTube, MLC, Soundscan.' },
          ],
        },
        {
          name: 'Identifiers & metadata',
          caps: [
            { label: 'ISWC / ISRC validation', route: 'cwr', evidence: 'Check-digit verification, conflict surfacing.' },
            { label: 'IPI base & name codes', route: 'directory', evidence: 'IPI base-13 + name-11 mod-101 check-digits.' },
            { label: 'Audio fingerprinting', route: 'audio-fp', evidence: 'AcoustID + YouTube CID + Shazam + SoundExchange match status.' },
            { label: 'Audio intelligence', route: 'recording', evidence: 'BPM/key auto-detect, cover/sample/interp detection.' },
          ],
        },
        {
          name: 'Structure & lineage',
          caps: [
            { label: 'Work → recording graph', route: 'catalog', evidence: 'Work / recording / release / video tree, all directions.' },
            { label: 'Catalog clustering', route: 'insights', payload: { tab: 'cluster' }, evidence: 'ML grouping by writer / era / sound / territory.' },
            { label: 'Cover / sample / interp', route: 'insights', payload: { tab: 'cover' }, evidence: 'Lineage tree with confidence bands.' },
            { label: 'Saved views', route: 'catalog', evidence: 'Persistent named filter+sort+search states.' },
          ],
        },
        {
          name: 'Quality & localization',
          caps: [
            { label: 'Conformance', route: 'conformance', evidence: 'Pre-import audit + post-import health.' },
            { label: 'Localization shell', route: 'localization', evidence: 'i18n strings, NRA non-Roman names, territory aliases.' },
            { label: 'Reference data', route: 'settings', payload: { tab: 'ref-data' }, evidence: 'TIS territories, CISAC societies, role codes.' },
          ],
        },
      ],
    },

    monetize: {
      key: 'monetize',
      label: 'Monetize',
      tag: '03',
      blurb: 'Revenue from the catalog — collect, optimize, project, exploit, distribute.',
      pillars: [
        {
          name: 'Collect',
          caps: [
            { label: 'Royalties dashboard', route: 'royalties', evidence: 'In/out, by source, by period, statement timeline.' },
            { label: 'Reconciliation queue', route: 'reconciliation', evidence: 'Unmatched-line resolution + learning matcher.' },
            { label: 'Statement-out generator', route: 'statement-out', evidence: 'Counterparty-facing PDFs, recoupment-aware.' },
            { label: 'Inbox / errors', route: 'inbox', evidence: 'Outstanding statement errors, ack failures, FX flags.' },
          ],
        },
        {
          name: 'Optimize',
          caps: [
            { label: 'Royalty optimizer', route: 'royalties', evidence: 'Ranked strategies — claim BB, fix shares, register gaps, FX timing.' },
            { label: 'Leak detection', route: 'insights', payload: { tab: 'leak' }, evidence: 'ML-detected unclaimed/under-claimed income paths.' },
            { label: 'Black-box ranking', route: 'insights', payload: { tab: 'bbrank' }, evidence: 'Prioritized claims by recoverable $.' },
            { label: 'Royalty audit pack', route: 'reports', evidence: 'Society/distributor audit-ready evidence bundles.' },
          ],
        },
        {
          name: 'Project & value',
          caps: [
            { label: 'Per-work 12-mo forecast', route: 'insights', payload: { tab: 'forecast' }, evidence: 'Decay + seasonality + uplift modeling per work.' },
            { label: 'Predictions / scoring', route: 'insights', payload: { tab: 'predict' }, evidence: '5 algorithms — comp matching, attribution, sync fit, lifecycle.' },
            { label: 'Catalog valuation', route: 'analytics', payload: { tab: 'valuation' }, evidence: 'NPV bands, comp-multiples, discount sensitivity.' },
            { label: 'Future-proofing', route: 'future-proof', evidence: 'Standards / DSP / market-trend readiness scoring.' },
          ],
        },
        {
          name: 'Exploit',
          caps: [
            { label: 'Sync prediction', route: 'insights', payload: { tab: 'predict' }, evidence: 'Per-work sync-fit scoring with brand match.' },
            { label: 'Audience analytics', route: 'audience', evidence: 'Listener geo, cohorts, fan funnel, brand affinity.' },
            { label: 'Distribution analytics', route: 'analytics', evidence: '7 dimensional tabs (Market/Artist/Work/Recording/Release/Video/Platform).' },
            { label: 'DSP integrations', route: 'integrations', evidence: 'Live pulls + DSP analytics import for cross-platform reads.' },
          ],
        },
      ],
    },
  };

  // ── Visual ────────────────────────────────────────────────────────────

  const VERB_COLORS = {
    manage:   { ink: 'oklch(0.30 0.06 270)', accent: 'oklch(0.55 0.13 265)', wash: 'oklch(0.97 0.012 265)' },
    organize: { ink: 'oklch(0.30 0.06 145)', accent: 'oklch(0.50 0.12 145)', wash: 'oklch(0.97 0.012 145)' },
    monetize: { ink: 'oklch(0.30 0.06 60)',  accent: 'oklch(0.58 0.14 60)',  wash: 'oklch(0.97 0.014 60)'  },
  };

  function PillarCard({ pillar, verb, go }) {
    const c = VERB_COLORS[verb];
    return (
      <div style={{
        border: '1px solid var(--rule)', background: '#fff', padding: 18,
        display: 'flex', flexDirection: 'column', gap: 10, minHeight: 240,
      }}>
        <div className="ff-mono upper" style={{ fontSize: 9, letterSpacing: '.16em', color: c.accent }}>
          {pillar.name}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {pillar.caps.map((cap, i) => (
            <button
              key={i}
              onClick={() => go && go(cap.route, cap.payload)}
              style={{
                appearance: 'none', border: 0, background: 'transparent',
                textAlign: 'left', padding: '8px 10px', cursor: 'pointer',
                borderLeft: `2px solid ${c.accent}`,
                display: 'flex', flexDirection: 'column', gap: 3,
              }}
              onMouseEnter={e => e.currentTarget.style.background = c.wash}
              onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
            >
              <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink-1)' }}>
                {cap.label}
                <span style={{ fontSize: 10, color: 'var(--ink-3)', marginLeft: 6 }}>↗</span>
              </div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', lineHeight: 1.5 }}>
                {cap.evidence}
              </div>
            </button>
          ))}
        </div>
      </div>
    );
  }

  function VerbBlock({ verb, go }) {
    const v = VERBS[verb];
    const c = VERB_COLORS[verb];
    const totalCaps = v.pillars.reduce((s, p) => s + p.caps.length, 0);
    return (
      <section style={{ marginBottom: 64 }}>
        <header style={{ display: 'flex', alignItems: 'baseline', gap: 18, paddingBottom: 14, borderBottom: `2px solid ${c.ink}`, marginBottom: 22 }}>
          <span className="ff-mono" style={{ fontSize: 11, color: c.accent, letterSpacing: '.1em' }}>{v.tag}</span>
          <h2 style={{ margin: 0, fontSize: 44, letterSpacing: '-0.025em', color: c.ink, fontWeight: 500 }}>
            {v.label}
          </h2>
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 18, alignItems: 'baseline' }}>
            <span className="ff-mono num" style={{ fontSize: 22, color: c.ink, fontWeight: 500 }}>{totalCaps}</span>
            <span className="ff-mono upper" style={{ fontSize: 9, color: 'var(--ink-3)', letterSpacing: '.14em' }}>capabilities</span>
            <span className="ff-mono num" style={{ fontSize: 22, color: c.ink, fontWeight: 500, marginLeft: 12 }}>{v.pillars.length}</span>
            <span className="ff-mono upper" style={{ fontSize: 9, color: 'var(--ink-3)', letterSpacing: '.14em' }}>pillars</span>
          </div>
        </header>
        <p style={{ fontSize: 16, color: 'var(--ink-2)', maxWidth: 720, lineHeight: 1.55, marginTop: 0, marginBottom: 26 }}>
          {v.blurb}
        </p>
        <div style={{
          display: 'grid', gap: 14,
          gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))',
        }}>
          {v.pillars.map((p, i) => <PillarCard key={i} pillar={p} verb={verb} go={go} />)}
        </div>
      </section>
    );
  }

  function ScreenMandate({ go }) {
    const totals = useMemo(() => {
      const t = {};
      Object.values(VERBS).forEach(v => {
        t[v.key] = v.pillars.reduce((s, p) => s + p.caps.length, 0);
      });
      t.all = t.manage + t.organize + t.monetize;
      return t;
    }, []);

    return (
      <div style={{ paddingBottom: 80 }}>
        {/* Mandate header */}
        <div style={{ paddingBottom: 36, borderBottom: '1px solid var(--rule)', marginBottom: 40 }}>
          <div className="ff-mono upper" style={{ fontSize: 10, letterSpacing: '.18em', color: 'var(--ink-3)', marginBottom: 14 }}>
            Platform mandate · capability matrix
          </div>
          <h1 style={{
            margin: 0, fontSize: 64, letterSpacing: '-0.03em', fontWeight: 500, lineHeight: 1.05,
            maxWidth: 1100,
          }}>
            Manage, organize, and<br />monetize music catalogs.
          </h1>
          <div style={{
            marginTop: 28, display: 'flex', gap: 36, flexWrap: 'wrap',
            paddingTop: 18, borderTop: '1px solid var(--rule)',
          }}>
            {[
              ['Capabilities', totals.all],
              ['Manage', totals.manage, VERB_COLORS.manage.ink],
              ['Organize', totals.organize, VERB_COLORS.organize.ink],
              ['Monetize', totals.monetize, VERB_COLORS.monetize.ink],
            ].map(([label, n, ink], i) => (
              <div key={i} style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                <span className="ff-mono num" style={{ fontSize: 28, fontWeight: 500, color: ink || 'var(--ink-1)' }}>{n}</span>
                <span className="ff-mono upper" style={{ fontSize: 9, letterSpacing: '.16em', color: 'var(--ink-3)' }}>{label}</span>
              </div>
            ))}
          </div>
          <p style={{ marginTop: 26, fontSize: 14, color: 'var(--ink-2)', maxWidth: 760, lineHeight: 1.65 }}>
            Every claim in that sentence resolves to live surfaces in this app. Each card below is a deep-link to the
            screen that delivers the capability. If a verb shows fewer pillars or capabilities than the others, that
            is a coverage gap to close — the matrix is the contract.
          </p>
        </div>

        <VerbBlock verb="manage" go={go} />
        <VerbBlock verb="organize" go={go} />
        <VerbBlock verb="monetize" go={go} />

        {/* Footer note */}
        <div style={{
          marginTop: 40, padding: '20px 22px',
          background: 'var(--bg-2, #fafaf8)',
          border: '1px solid var(--rule)',
          fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.65, maxWidth: 920,
        }}>
          <span className="ff-mono upper" style={{ fontSize: 9, letterSpacing: '.16em', color: 'var(--ink-3)', display: 'block', marginBottom: 6 }}>
            Methodology
          </span>
          The matrix is generated from the live route table — not a marketing artifact. Every cap-card is a real
          screen reachable from this build. Pillars group capabilities into the smallest set that lets a non-expert
          confirm coverage at a glance. New surfaces appear here when they're routed, not when they're announced.
        </div>
      </div>
    );
  }

  window.ScreenMandate = ScreenMandate;
})();
