// Extra tab views for screens 3/4/5/7. Adds realism & depth w/o reworking originals.

function Tabs({ tabs, active, onChange }) {
  return (
    <div className="mf-tabs">
      {tabs.map(t => (
        <div key={t.key}
          className={`tab ${active === t.key ? 'active' : ''}`}
          onClick={() => onChange(t.key)}>
          {t.label}
          {t.count !== undefined && <span className="ct">{t.count}</span>}
        </div>
      ))}
    </div>
  );
}

// ---- Profile extras ----
function ProfileExtras_Audit({ role }) {
  const rows = [
    ['2026-04-22 08:12:04', 'system',       'twin.sync',        'Nightly re-simulation completed · 342 deltas'],
    ['2026-04-22 07:40:11', 'r.kowalski',   'ks.apply',         'Applied KnowledgeSlot to "Surface finish" (high impact)'],
    ['2026-04-21 16:22:38', 'j.mendes',     'profile.update',   'Added 5-axis Mazak VC-500 to process list'],
    ['2026-04-21 09:01:55', 'system',       'cert.verify',      'AS9100D — revision D confirmed via IAQG OASIS'],
    ['2026-04-18 14:45:02', 'j.mendes',     'capacity.adjust',  'Q3 capacity revised 58% → 62% (rework absorbed)'],
    ['2026-04-15 11:30:17', 'system',       'match.propose',    'BU-2208 introduced to twin — tagged adjacent'],
    ['2026-04-14 17:02:09', 'system',       'itar.attest',      'ITAR registration DDTC-3481-02 valid thru 2027-03'],
    ['2026-04-10 08:17:44', 'r.kowalski',   'profile.create',   `Profile ${PROFILES[role].callsign} instantiated`],
  ];
  return (
    <table className="data-tbl">
      <thead>
        <tr><th style={{ width: 180 }}>Timestamp</th><th style={{ width: 120 }}>Actor</th><th style={{ width: 140 }}>Event</th><th>Detail</th></tr>
      </thead>
      <tbody>
        {rows.map((r, i) => (
          <tr key={i}>
            <td className="mono" style={{ color: 'var(--ink-3)' }}>{r[0]}</td>
            <td className="mono">{r[1]}</td>
            <td><span className="chip ghost">{r[2]}</span></td>
            <td>{r[3]}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

function ProfileExtras_Equipment({ role }) {
  const equip = {
    shop: [
      ['M-04', 'Mazak Integrex i-500 (5-axis)',  'Milling',  'Inconel, Ti, SS', '38%', 'operational'],
      ['M-02', 'Mazak VC-500A/5X',                'Milling',  'Aluminum, SS',    '71%', 'operational'],
      ['M-07', 'DMG Mori NLX 2500',               'Turning',  'SS, Ti',          '42%', 'operational'],
      ['M-11', 'Makino U6 (Wire EDM)',            'EDM',      'Inconel, Ti',     '28%', 'operational'],
      ['M-03', 'Mitsubishi MV1200R (Wire EDM)',   'EDM',      'SS, Al',          '12%', 'scheduled maint'],
      ['I-01', 'Zeiss Contura CMM',               'Inspect',  'All metallic',    '55%', 'operational'],
    ],
    buyer: [
      ['PL-A',  'Production line A (aerospace)',    'Assembly', 'Inconel, Ti',     '84%', 'running'],
      ['PL-B',  'Production line B (prototype)',     'Assembly', 'Al, SS',          '52%', 'running'],
      ['CMM-1', 'In-house Zeiss Prismo',             'Inspect',  'All metallic',    '41%', 'operational'],
    ],
    inspector: [
      ['CMM-1', 'Zeiss Prismo Ultra (800×1200)',  'CMM',       '±0.0001"',         '71%', 'operational'],
      ['CMM-2', 'Mitutoyo Crysta-Apex (500×700)', 'CMM',       '±0.0002"',         '45%', 'operational'],
      ['SCN-1', 'GOM ATOS Q (blue light)',         'Scan',      '±0.002 mm vol',    '23%', 'operational'],
      ['CT-1',  'Nikon XT H 225 ST',               'CT',        'Int. features',    '12%', 'operational'],
    ],
  }[role] || [];
  return (
    <table className="data-tbl">
      <thead>
        <tr><th>ID</th><th>Asset</th><th>Class</th><th>Materials</th><th>Util</th><th>Status</th></tr>
      </thead>
      <tbody>
        {equip.map((e, i) => (
          <tr key={i}>
            <td className="mono">{e[0]}</td>
            <td style={{ color: 'var(--ink)', fontWeight: 500 }}>{e[1]}</td>
            <td>{e[2]}</td>
            <td style={{ color: 'var(--ink-3)', fontSize: 11.5 }}>{e[3]}</td>
            <td>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <div style={{ width: 60, height: 4, background: 'var(--paper-3)', position: 'relative' }}>
                  <div style={{
                    position: 'absolute', inset: 0, width: e[4],
                    background: parseInt(e[4]) > 80 ? 'var(--miss)' : parseInt(e[4]) > 50 ? 'var(--warn)' : 'var(--ok)',
                  }} />
                </div>
                <span className="mono" style={{ fontSize: 11 }}>{e[4]}</span>
              </div>
            </td>
            <td>
              {e[5] === 'operational' && <span className="chip ok">{e[5]}</span>}
              {e[5] === 'running' && <span className="chip ok">{e[5]}</span>}
              {e[5] === 'scheduled maint' && <span className="chip warn">{e[5]}</span>}
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

function ProfileExtras_Certs({ role }) {
  const certs = [
    ['AS9100D',     'IAQG / Aerospace',           'Rev D',       '2027-03-18', 'DNV',         'active', 'Full aerospace QMS'],
    ['ISO 9001:2015','ISO',                        '2015',        '2027-03-18', 'DNV',         'active', 'Foundation QMS'],
    ['ITAR',        'US Dept. of State / DDTC',   'Reg. 3481-02','2027-03-01', 'Self-certified','active', 'Defense article jurisdiction'],
    ['NIST SP 800-171', 'NIST / DFARS 252.204-7012','Rev 2',     '2026-09-30', 'Coalfire',    'active', 'CUI handling'],
    ['Nadcap HT',   'PRI / Nadcap',               'Heat Treat',  '2026-11-22', 'PRI',         'active', 'Heat-treat scope'],
    ['RoHS 3',      'EU Directive 2015/863',      '—',           '—',          'Supplier-dec.','advisory', 'Material restrictions'],
  ];
  return (
    <table className="data-tbl">
      <thead>
        <tr><th>Standard</th><th>Body</th><th>Revision</th><th>Expires</th><th>Auditor</th><th>Status</th></tr>
      </thead>
      <tbody>
        {certs.map((c, i) => (
          <tr key={i}>
            <td className="mono" style={{ color: 'var(--ink)', fontWeight: 500 }}>{c[0]}</td>
            <td>{c[1]}</td>
            <td className="mono" style={{ fontSize: 11 }}>{c[2]}</td>
            <td className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{c[3]}</td>
            <td style={{ color: 'var(--ink-3)' }}>{c[4]}</td>
            <td>{c[5] === 'active' ? <span className="chip ok">active</span> : <span className="chip ghost">{c[5]}</span>}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

// ---- Dashboard extras ----
function DashboardExtras_Feed() {
  const events = [
    ['08:12:04.812', 'twin.sync',          'system',        'Δ 342 entities re-scored'],
    ['08:09:18.117', 'ks.field.apply',     'r.kowalski',    'Surface finish → Ra 32 μin'],
    ['08:04:55.004', 'match.clear',        'cosolvent.v7',  'MF-2026-04-0412 cleared threshold (83)'],
    ['08:02:11.441', 'match.propose',      'cosolvent.v7',  'Candidate BU-0117 evaluated'],
    ['07:58:40.908', 'match.reject',       'cosolvent.v7',  'BU-4409 below cert floor (mismatch)'],
    ['07:52:11.552', 'twin.simulate',      'system',        '12,478 synthetic entities loaded'],
    ['07:47:02.221', 'profile.sign',       'j.mendes',      'Signed capacity block Q3-2026'],
    ['07:40:33.018', 'ks.prompt.surface',  'knowledgeslot', '2 prompts surfaced (high, medium)'],
    ['07:34:12.117', 'cert.verify',        'IAQG OASIS',    'AS9100D rev D confirmed'],
    ['07:28:44.008', 'session.start',      'r.kowalski',    'SIM-4F82A · 185.11.xx.xx'],
  ];
  return (
    <div style={{
      background: '#1a1a17', color: 'var(--paper)', padding: 16,
      fontFamily: 'var(--mono)', fontSize: 11, lineHeight: 1.75,
      border: '1px solid var(--ink)',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 10, color: 'var(--ink-5)' }}>
        <span>$ tail -f /var/log/marketforge/twin.jsonl</span>
        <span style={{ color: 'var(--accent)' }}>● streaming</span>
      </div>
      {events.map((e, i) => (
        <div key={i} style={{ display: 'grid', gridTemplateColumns: '110px 140px 110px 1fr', gap: 14 }}>
          <span style={{ color: 'var(--ink-5)' }}>{e[0]}</span>
          <span style={{ color: 'var(--accent)' }}>{e[1]}</span>
          <span style={{ color: '#8ac8d6' }}>{e[2]}</span>
          <span style={{ color: 'var(--paper)' }}>{e[3]}</span>
        </div>
      ))}
      <div style={{ marginTop: 8, color: 'var(--ink-5)' }}>
        <span className="mf-pulse">▌</span>
      </div>
    </div>
  );
}

function DashboardExtras_Candidates({ role }) {
  const rows = [
    ['MF-2026-04-0412', 'BU-2208', 'Buyer',  12, 'Inconel 718', 'AS9102 FAI', 83, 'cleared',   '02m ago'],
    ['MF-2026-04-0388', 'BU-1002', 'Buyer',  6,  'Ti-6Al-4V',   'FAI optional', 68, 'queued',   '14m ago'],
    ['MF-2026-04-0361', 'BU-3390', 'Buyer',  24, '17-4 PH SS',  'CMM + PPAP',   62, 'queued',   '47m ago'],
    ['MF-2026-04-0340', 'BU-0055', 'Buyer',  4,  'A286',        'AS9102 FAI',   58, 'review',   '1h ago'],
    ['MF-2026-04-0321', 'BU-0117', 'Buyer',  18, 'Inconel 625', 'Ra 16',        54, 'reject · finish', '2h ago'],
    ['MF-2026-04-0308', 'BU-4409', 'Buyer',  2,  'SS 304',       '—',           41, 'reject · cert',   '3h ago'],
  ];
  return (
    <table className="data-tbl">
      <thead>
        <tr>
          <th>Match ID</th><th>CP</th><th>Type</th><th>Qty</th><th>Material</th><th>Inspection</th>
          <th>Confidence</th><th>Status</th><th>Since</th>
        </tr>
      </thead>
      <tbody>
        {rows.map((r, i) => (
          <tr key={i}>
            <td className="mono" style={{ color: 'var(--ink)' }}>{r[0]}</td>
            <td className="mono"><span className="redacted">{r[1]}</span></td>
            <td>{r[2]}</td>
            <td className="mono">{r[3]}</td>
            <td>{r[4]}</td>
            <td style={{ color: 'var(--ink-3)', fontSize: 11.5 }}>{r[5]}</td>
            <td>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <div style={{ width: 48, height: 4, background: 'var(--paper-3)', position: 'relative' }}>
                  <div style={{
                    position: 'absolute', inset: 0, width: `${r[6]}%`,
                    background: r[6] >= 80 ? 'var(--ok)' : r[6] >= 60 ? 'var(--warn)' : 'var(--miss)',
                  }} />
                </div>
                <span className="mono" style={{ fontSize: 11 }}>{r[6]}</span>
              </div>
            </td>
            <td>
              {r[7] === 'cleared' && <span className="chip ok">{r[7]}</span>}
              {r[7] === 'queued' && <span className="chip info">{r[7]}</span>}
              {r[7] === 'review' && <span className="chip warn">{r[7]}</span>}
              {r[7].startsWith('reject') && <span className="chip miss">{r[7]}</span>}
            </td>
            <td className="mono" style={{ fontSize: 10, color: 'var(--ink-3)' }}>{r[8]}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

// ---- Match extras ----
function MatchExtras_Provenance() {
  const nodes = [
    { step: '01', label: 'ClientSynth',  sub: 'v3.2 · synthetic twin population', detail: '12,478 entities · 342 Δ since 04:00' },
    { step: '02', label: 'KnowledgeSlot', sub: 'v2.1 · domain grounding',          detail: '47 ontology classes · 1,840 prompts' },
    { step: '03', label: 'Cosolvent',    sub: 'v7.4 · bidirectional matching',    detail: '2.4M pair evaluations · 8.2s walltime' },
    { step: '04', label: 'MarketForge',  sub: 'orchestrator',                     detail: 'Render · narrate · gate identity' },
  ];
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 0, border: '1px solid var(--line)' }}>
      {nodes.map((n, i) => (
        <div key={n.step} style={{
          padding: '14px 16px',
          borderRight: i < 3 ? '1px solid var(--line)' : 'none',
          background: 'var(--paper)',
          position: 'relative',
        }}>
          <div className="mono-lbl" style={{ color: 'var(--accent)' }}>step {n.step}</div>
          <div style={{ fontFamily: 'var(--serif)', fontSize: 17, marginTop: 4, letterSpacing: '-0.005em' }}>{n.label}</div>
          <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 4 }}>{n.sub}</div>
          <div style={{ fontSize: 11.5, color: 'var(--ink-2)', marginTop: 8, lineHeight: 1.55 }}>{n.detail}</div>
          {i < 3 && (
            <span style={{
              position: 'absolute', right: -8, top: '50%', transform: 'translateY(-50%)',
              background: 'var(--paper)', border: '1px solid var(--line)', width: 16, height: 16,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--ink-3)', zIndex: 1,
            }}>→</span>
          )}
        </div>
      ))}
    </div>
  );
}

function MatchExtras_Ledger() {
  const entries = [
    ['08:04:55.004', 'propose',  'cosolvent.v7', 'Candidate pair (MS-0417 ↔ BU-████) queued for eval'],
    ['08:04:55.128', 'gather',   'twin.read',    'Loaded 214 signals from both sides'],
    ['08:04:55.491', 'score',    'cosolvent.v7', 'Per-signal scoring · 14 signals weighted'],
    ['08:04:55.702', 'aggregate','cosolvent.v7', 'Mutual confidence: 83/100'],
    ['08:04:55.812', 'threshold','policy.v2',    'Above publish-threshold (70) — surfacing'],
    ['08:04:55.904', 'narrate',  'cosolvent.v7', 'Narrative generated, 3 paragraphs, 187 tokens'],
    ['08:04:56.001', 'gate',     'identity.v1',  'Identity withheld pending mutual opt-in'],
    ['08:04:56.078', 'surface',  'marketforge',  'Delivered to MS-0417 inbox'],
  ];
  return (
    <table className="data-tbl">
      <thead>
        <tr><th>Timestamp</th><th>Phase</th><th>Actor</th><th>Detail</th></tr>
      </thead>
      <tbody>
        {entries.map((e, i) => (
          <tr key={i}>
            <td className="mono" style={{ color: 'var(--ink-3)', width: 130 }}>{e[0]}</td>
            <td><span className="chip accent" style={{ fontSize: 9 }}>{e[1]}</span></td>
            <td className="mono" style={{ width: 140 }}>{e[2]}</td>
            <td>{e[3]}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

// ---- Deal extras ----
function DealExtras_Approvals() {
  const steps = [
    { who: 'Requestor',           name: 'Ardent · J. Mendes (Ops)',       when: '2026-04-22 08:14', status: 'signed' },
    { who: 'Quality approver',    name: 'Ardent · R. Kowalski (QA)',      when: '2026-04-22 09:02', status: 'signed' },
    { who: 'Buyer procurement',   name: 'Helios · L. Park (Procurement)', when: '2026-04-22 10:45', status: 'pending' },
    { who: 'Buyer quality',       name: 'Helios · A. Sato (Quality)',     when: '—',                 status: 'queued' },
    { who: 'Escrow (MarketForge)',name: 'Automated · escrow.v3',          when: '—',                 status: 'armed' },
  ];
  return (
    <div style={{ border: '1px solid var(--line)' }}>
      {steps.map((s, i) => (
        <div key={i} style={{
          display: 'grid', gridTemplateColumns: '36px 1fr 1fr 140px 120px',
          gap: 14, padding: '12px 14px', alignItems: 'center',
          borderTop: i > 0 ? '1px solid var(--line)' : 'none',
          background: 'var(--paper)',
        }}>
          <div style={{
            width: 28, height: 28, borderRadius: '50%',
            border: `1px solid ${s.status === 'signed' ? 'var(--ok)' : 'var(--line-2)'}`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            background: s.status === 'signed' ? 'var(--ok-soft)' : 'var(--paper-2)',
            color: s.status === 'signed' ? 'var(--ok)' : 'var(--ink-4)',
            fontFamily: 'var(--mono)', fontSize: 11,
          }}>
            {s.status === 'signed' ? '✓' : i + 1}
          </div>
          <div>
            <div className="mono-lbl">{s.who}</div>
            <div style={{ fontSize: 13, marginTop: 2 }}>{s.name}</div>
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>
            {s.status === 'signed' && 'Countersigned via verified wallet. Hash recorded.'}
            {s.status === 'pending' && 'Notified. SLA 4h remaining before escalation.'}
            {s.status === 'queued' && 'Awaiting upstream approval.'}
            {s.status === 'armed' && 'Escrow will fire when all signatures collected.'}
          </div>
          <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{s.when}</div>
          <div>
            {s.status === 'signed' && <span className="chip ok">signed</span>}
            {s.status === 'pending' && <span className="chip warn">pending · 4h SLA</span>}
            {s.status === 'queued' && <span className="chip ghost">queued</span>}
            {s.status === 'armed' && <span className="chip info">armed</span>}
          </div>
        </div>
      ))}
    </div>
  );
}

function DealExtras_Clauses() {
  const clauses = [
    ['01', 'Scope', 'Part numbers, drawing revs, quantity, material call-out', 'derived from buyer RFQ #RFQ-H-2201-44'],
    ['02', 'Quality', 'AS9102 FAI on first article; CMM dimensional + material cert', 'AS9100D aligned'],
    ['03', 'Delivery', '6-week lead time from PO; FOB Grand Rapids, MI', 'standard ground, insured'],
    ['04', 'Pricing', '$1,840/ea fixed for initial PO; volume tiers at 50/100/250', 'escalator tied to LME nickel'],
    ['05', 'Payment', 'Net 30 from acceptance; late fee 1.5% / month', 'ACH + wire both accepted'],
    ['06', 'Warranty', '12 months from delivery, workmanship + material', 'excludes consequential'],
    ['07', 'IP', 'Buyer retains all part-design IP; shop retains process IP', 'no joint IP'],
    ['08', 'Termination', 'For convenience w/ 30d notice; for cause w/ cure period', 'escrow returns unreleased funds'],
    ['09', 'Jurisdiction', 'Delaware law; AAA arbitration in New York', 'mutually agreed in twin'],
    ['10', 'Export', 'ITAR/EAR compliance; both parties US persons', 'verified pre-reveal'],
  ];
  return (
    <table className="data-tbl">
      <thead>
        <tr><th style={{ width: 30 }}>§</th><th style={{ width: 110 }}>Clause</th><th>Summary</th><th style={{ width: 220 }}>Source / note</th></tr>
      </thead>
      <tbody>
        {clauses.map((c, i) => (
          <tr key={i}>
            <td className="mono" style={{ color: 'var(--accent)' }}>{c[0]}</td>
            <td style={{ fontWeight: 500, color: 'var(--ink)' }}>{c[1]}</td>
            <td>{c[2]}</td>
            <td style={{ color: 'var(--ink-3)', fontSize: 11.5 }}>{c[3]}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

function DealExtras_Risk() {
  const risks = [
    { sev: 'low',  label: 'Capacity overlap',    desc: 'Q3 book at 62% with this deal — 28% headroom if pulled forward.', mit: 'Staging plan agreed; FAI slot pre-booked.' },
    { sev: 'low',  label: 'Material lead-time',   desc: 'Inconel 718 bar stock 3-week lead from MetalStock Inc.',          mit: 'Existing consignment covers first 8 of 12 parts.' },
    { sev: 'med',  label: 'Surface finish spec',  desc: 'Ra 32 μin preferred, Ra 16 on bearing surfaces.',                  mit: 'Finish pass validated on coupon; within capability.' },
    { sev: 'low',  label: 'Export compliance',    desc: 'ITAR article — both parties US persons, no foreign national access.', mit: 'Export control review on file.' },
    { sev: 'med',  label: 'Single-source',         desc: 'No back-up shop for this part number on buyer side.',              mit: 'Twin maintains shadow match (MS-2203) for continuity.' },
  ];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      {risks.map((r, i) => (
        <div key={i} style={{
          display: 'grid', gridTemplateColumns: '70px 180px 1fr 1fr',
          gap: 14, padding: '12px 14px', alignItems: 'flex-start',
          background: 'var(--paper)', border: '1px solid var(--line)',
        }}>
          {r.sev === 'low' && <span className="chip ok">low</span>}
          {r.sev === 'med' && <span className="chip warn">medium</span>}
          {r.sev === 'high' && <span className="chip miss">high</span>}
          <div style={{ fontWeight: 500 }}>{r.label}</div>
          <div style={{ fontSize: 12, color: 'var(--ink-2)' }}>{r.desc}</div>
          <div style={{ fontSize: 12, color: 'var(--ink-3)', fontStyle: 'italic' }}>{r.mit}</div>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, {
  Tabs,
  ProfileExtras_Audit, ProfileExtras_Equipment, ProfileExtras_Certs,
  DashboardExtras_Feed, DashboardExtras_Candidates,
  MatchExtras_Provenance, MatchExtras_Ledger,
  DealExtras_Approvals, DealExtras_Clauses, DealExtras_Risk,
});
