// ============================================================================
// ScreenIdCodes — paste-and-validate + format reference + catalog audit
//
// Three tabs:
//   1. Validate — paste any value(s); auto-detect kind, show ✓/✕, fix offers
//   2. Reference — card per code with pattern, example, check-digit math
//   3. Audit — scan WORKS/RECORDINGS/RELEASES/PARTIES catalogs for invalid IDs
//
// Wired into rail under Tools (rail menu).
// EXPORT: window.ScreenIdCodes
// ============================================================================
(function () {
  const { useState, useMemo } = React;

  const KINDS = ['iswc','isrc','ipiName','ipiBase','isni','upc','ean13','grid','dpid','labelCode','society','tis','iscc','ismn','mbid','isan'];

  function ScreenIdCodes({ go }) {
    const [tab, setTab] = useState('validate');
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
        <header style={{ borderBottom: '1px solid var(--rule)', paddingBottom: 16, marginBottom: 20 }}>
          <div className="ff-mono" style={{ fontSize: 10, letterSpacing: 1.5, color: 'var(--ink-3)', textTransform: 'uppercase' }}>Tools</div>
          <h1 style={{ fontSize: 36, margin: '6px 0 4px', fontWeight: 400 }}>Identifier codes</h1>
          <div style={{ color: 'var(--ink-2)', fontSize: 13 }}>Validate, format, and audit every music-industry ID — ISWC, ISRC, IPI, ISNI, UPC, EAN, GRid, DPID, LC, Society, TIS, ISCC, ISMN, MBID, ISAN.</div>
        </header>
        <nav style={{ display: 'flex', gap: 0, borderBottom: '1px solid var(--rule)', marginBottom: 20 }}>
          {[['validate','Validate'],['reference','Reference'],['audit','Catalog audit']].map(([k,l]) =>
            <button key={k} onClick={() => setTab(k)} className="ff-mono"
              style={{ padding: '10px 16px', fontSize: 11, letterSpacing: 1, textTransform: 'uppercase',
                background: 'transparent', border: 'none',
                borderBottom: tab===k ? '2px solid var(--ink)' : '2px solid transparent',
                color: tab===k ? 'var(--ink)' : 'var(--ink-3)', cursor: 'pointer' }}>{l}</button>)}
        </nav>
        {tab === 'validate'  && <ValidateTab />}
        {tab === 'reference' && <ReferenceTab />}
        {tab === 'audit'     && <AuditTab go={go} />}
      </div>);
  }

  // ─── Tab 1: Validate ────────────────────────────────────────────────────
  function ValidateTab() {
    const [text, setText] = useState('T1010551172\n012345678905\n5b11f4ce-a62d-471e-81fc-a69a8278c7da\nUSRC11700001\nLC-12345\nPADPIDA2014011001I\nA1-2425G-ABC1234002-M');
    const [kindOverride, setKindOverride] = useState('auto');

    const lines = useMemo(() => text.split(/\r?\n/).map((l) => l.trim()).filter(Boolean), [text]);
    const results = useMemo(() => {
      if (!window.IdCodes) return [];
      return lines.map((line) => {
        if (kindOverride !== 'auto') {
          const r = window.IdCodes.validate(kindOverride, line);
          return { line, kind: kindOverride, result: r };
        }
        const guesses = window.IdCodes.detect(line);
        if (guesses.length) return { line, kind: guesses[0].kind, result: guesses[0].result, alternates: guesses.slice(1) };
        return { line, kind: '?', result: { valid: false, reason: 'no validator matched' } };
      });
    }, [lines, kindOverride]);

    const ok = results.filter((r) => r.result.valid === true).length;
    const warns = results.filter((r) => r.result.valid === 'warn').length;
    const bad = results.filter((r) => r.result.valid === false).length;

    return (
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 24 }}>
        <section>
          <div className="ff-mono" style={{ fontSize: 10, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 1, marginBottom: 6 }}>Paste values (one per line)</div>
          <textarea value={text} onChange={(e) => setText(e.target.value)} className="ff-mono"
            style={{ width: '100%', minHeight: 320, padding: 10, fontSize: 12, lineHeight: 1.5,
              background: 'var(--bg)', border: '1px solid var(--rule)', color: 'var(--ink)', outline: 'none' }} />
          <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginTop: 10, fontSize: 11 }}>
            <span className="ff-mono" style={{ color: 'var(--ink-3)' }}>kind:</span>
            <select value={kindOverride} onChange={(e) => setKindOverride(e.target.value)}
              style={{ padding: '4px 8px', fontSize: 11, background: 'var(--bg)', color: 'var(--ink)', border: '1px solid var(--rule)' }}>
              <option value="auto">auto-detect</option>
              {KINDS.map((k) => <option key={k} value={k}>{(window.IdCodes?.formats[k]||{}).label || k}</option>)}
            </select>
            <span style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
              <span style={{ color: '#0a7d3b' }} className="ff-mono">{ok} ok</span>
              <span style={{ color: '#b76f00' }} className="ff-mono">{warns} warn</span>
              <span style={{ color: '#a3261b' }} className="ff-mono">{bad} bad</span>
            </span>
          </div>
        </section>
        <section>
          <div className="ff-mono" style={{ fontSize: 10, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 1, marginBottom: 6 }}>Results</div>
          <div style={{ border: '1px solid var(--rule)', maxHeight: 480, overflow: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 11 }}>
              <thead>
                <tr style={{ background: 'var(--bg-2)', fontSize: 10, textTransform: 'uppercase', letterSpacing: 1, color: 'var(--ink-3)' }}>
                  <th style={{ padding: '6px 8px', textAlign: 'left', width: 30 }}></th>
                  <th style={{ padding: '6px 8px', textAlign: 'left', width: 100 }}>Kind</th>
                  <th style={{ padding: '6px 8px', textAlign: 'left' }}>Value</th>
                  <th style={{ padding: '6px 8px', textAlign: 'left' }}>Result</th>
                </tr>
              </thead>
              <tbody>
                {results.map((row, i) => {
                  const r = row.result;
                  const dotColor = r.valid === true ? '#0a7d3b' : r.valid === 'warn' ? '#b76f00' : '#a3261b';
                  const fmt = (window.IdCodes?.formats[row.kind]) || { label: row.kind };
                  return (
                    <tr key={i} style={{ borderTop: '1px solid var(--rule)' }}>
                      <td style={{ padding: '6px 8px', verticalAlign: 'top' }}>
                        <span style={{ display: 'inline-block', width: 8, height: 8, borderRadius: '50%', background: dotColor }} />
                      </td>
                      <td style={{ padding: '6px 8px', verticalAlign: 'top' }} className="ff-mono">{fmt.label}</td>
                      <td style={{ padding: '6px 8px', verticalAlign: 'top' }} className="ff-mono">{row.line}</td>
                      <td style={{ padding: '6px 8px', verticalAlign: 'top' }}>
                        {r.valid === true && <span style={{ color: '#0a7d3b' }}>✓ valid · <span className="ff-mono">{r.normalized || row.line}</span></span>}
                        {r.valid === 'warn' && <span style={{ color: '#b76f00' }}>△ {r.reason}</span>}
                        {r.valid === false && (
                          <div>
                            <div style={{ color: '#a3261b' }}>✕ {r.reason}</div>
                            {r.suggestion && <div className="ff-mono" style={{ fontSize: 10, color: 'var(--ink-2)', marginTop: 2 }}>suggested: {r.suggestion}</div>}
                          </div>)}
                        {row.alternates && row.alternates.length > 0 && (
                          <div style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 4 }}>
                            also matches: {row.alternates.map(a => (window.IdCodes?.formats[a.kind]||{}).label || a.kind).join(', ')}
                          </div>)}
                      </td>
                    </tr>);
                })}
                {results.length === 0 && (
                  <tr><td colSpan="4" style={{ padding: 30, textAlign: 'center', color: 'var(--ink-3)' }}>Paste one or more identifier values above</td></tr>)}
              </tbody>
            </table>
          </div>
        </section>
      </div>);
  }

  // ─── Tab 2: Reference ───────────────────────────────────────────────────
  function ReferenceTab() {
    if (!window.IdCodes) return <div>Library not loaded.</div>;
    const fmts = window.IdCodes.formats;
    return (
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))', gap: 14 }}>
        {KINDS.map((k) => {
          const f = fmts[k] || { label: k };
          return (
            <div key={k} style={{ border: '1px solid var(--rule)', padding: 14, background: 'var(--bg)' }}>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 8 }}>
                <strong style={{ fontSize: 14 }}>{f.label}</strong>
                <span className="ff-mono" style={{ fontSize: 10, color: 'var(--ink-3)' }}>{f.scope}</span>
              </div>
              <dl style={{ margin: 0, fontSize: 11, lineHeight: 1.6, color: 'var(--ink-2)' }}>
                <div style={{ display: 'flex', gap: 8 }}>
                  <dt style={{ width: 70, color: 'var(--ink-3)' }}>Pattern</dt>
                  <dd style={{ margin: 0, flex: 1 }} className="ff-mono">{f.pattern}</dd>
                </div>
                <div style={{ display: 'flex', gap: 8 }}>
                  <dt style={{ width: 70, color: 'var(--ink-3)' }}>Standard</dt>
                  <dd style={{ margin: 0, flex: 1 }}>{f.body}</dd>
                </div>
                <div style={{ display: 'flex', gap: 8 }}>
                  <dt style={{ width: 70, color: 'var(--ink-3)' }}>Example</dt>
                  <dd style={{ margin: 0, flex: 1 }} className="ff-mono">{f.example}</dd>
                </div>
              </dl>
            </div>);
        })}
      </div>);
  }

  // ─── Tab 3: Catalog audit ───────────────────────────────────────────────
  function AuditTab({ go }) {
    const audit = useMemo(() => runCatalogAudit(), []);
    const [filter, setFilter] = useState('all');

    const filtered = useMemo(() => {
      if (filter === 'all') return audit.rows;
      return audit.rows.filter((r) => r.entity === filter);
    }, [filter, audit]);

    return (
      <div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12, marginBottom: 20 }}>
          {[
            ['Total checked', audit.totalChecked, 'var(--ink)'],
            ['Valid', audit.totalValid, '#0a7d3b'],
            ['Invalid', audit.totalInvalid, '#a3261b'],
            ['Warnings', audit.totalWarn, '#b76f00'],
            ['Health', Math.round(100 * audit.totalValid / Math.max(1, audit.totalChecked)) + '%', 'var(--ink)'],
          ].map(([l, v, c], i) => (
            <div key={i} style={{ border: '1px solid var(--rule)', padding: 12 }}>
              <div className="ff-mono" style={{ fontSize: 10, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 1 }}>{l}</div>
              <div style={{ fontSize: 24, fontWeight: 300, color: c, marginTop: 4 }} className="ff-mono num">{v}</div>
            </div>))}
        </div>
        <div style={{ display: 'flex', gap: 6, marginBottom: 12 }}>
          {[['all','All'],['work','Works'],['recording','Recordings'],['release','Releases'],['party','Parties']].map(([k,l]) =>
            <button key={k} onClick={() => setFilter(k)} className="ff-mono"
              style={{ padding: '4px 10px', fontSize: 11,
                background: filter===k ? 'var(--ink)' : 'transparent',
                color: filter===k ? 'var(--bg)' : 'var(--ink-2)',
                border: '1px solid var(--rule)', cursor: 'pointer' }}>{l}</button>)}
        </div>
        <div style={{ border: '1px solid var(--rule)', maxHeight: 540, overflow: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 11 }}>
            <thead>
              <tr style={{ background: 'var(--bg-2)', fontSize: 10, textTransform: 'uppercase', letterSpacing: 1, color: 'var(--ink-3)', position: 'sticky', top: 0 }}>
                <th style={{ padding: '6px 8px', textAlign: 'left' }}>Type</th>
                <th style={{ padding: '6px 8px', textAlign: 'left' }}>Entity</th>
                <th style={{ padding: '6px 8px', textAlign: 'left' }}>Field</th>
                <th style={{ padding: '6px 8px', textAlign: 'left' }}>Value</th>
                <th style={{ padding: '6px 8px', textAlign: 'left' }}>Issue</th>
                <th style={{ padding: '6px 8px', textAlign: 'left' }}>Fix</th>
              </tr>
            </thead>
            <tbody>
              {filtered.flatMap((row) => row.issues.map((iss, i) => (
                <tr key={row.entity + '/' + row.id + '/' + iss.kind + '/' + i} style={{ borderTop: '1px solid var(--rule)' }}>
                  <td style={{ padding: '6px 8px' }} className="ff-mono">{row.entity}</td>
                  <td style={{ padding: '6px 8px' }}>
                    {row.label || row.id}
                    {go && row.routeName && <button onClick={() => go(row.routeName, row.routePayload)}
                      className="ff-mono" style={{ marginLeft: 6, fontSize: 10, padding: '0 4px',
                        background: 'transparent', border: '1px solid var(--rule)', color: 'var(--ink-2)', cursor: 'pointer' }}>open ↗</button>}
                  </td>
                  <td style={{ padding: '6px 8px' }} className="ff-mono">{(window.IdCodes?.formats[iss.kind]||{}).label || iss.kind}</td>
                  <td style={{ padding: '6px 8px' }} className="ff-mono">{iss.value}</td>
                  <td style={{ padding: '6px 8px', color: iss.severity === 'high' ? '#a3261b' : '#b76f00' }}>{iss.reason}</td>
                  <td style={{ padding: '6px 8px' }} className="ff-mono">{iss.suggestion ? <span style={{ color: '#0a7d3b' }}>→ {iss.suggestion}</span> : '—'}</td>
                </tr>)))}
              {filtered.every((r) => r.issues.length === 0) && (
                <tr><td colSpan="6" style={{ padding: 30, textAlign: 'center', color: 'var(--ink-3)' }}>No issues. Catalog IDs all check out.</td></tr>)}
            </tbody>
          </table>
        </div>
      </div>);
  }

  // ─── Catalog audit runner ──────────────────────────────────────────────
  function runCatalogAudit() {
    const rows = [];
    let totalChecked = 0, totalValid = 0, totalInvalid = 0, totalWarn = 0;

    const RS = window.RS || {};
    const works = RS.works || window.WORKS || [];
    const recordings = RS.recordings || window.RECORDINGS || [];
    const releases = RS.releases || window.RELEASES || [];
    const parties = RS.parties || window.PARTIES || [];

    const tally = (r) => {
      if (!r) return;
      totalChecked++;
      if (r.valid === true) totalValid++;
      else if (r.valid === 'warn') totalWarn++;
      else totalInvalid++;
    };

    for (const w of (works || []).slice(0, 200)) {
      const a = window.IdCodes?.auditEntity({ kind: 'work', data: { id: w.id, iswc: w.iswc } });
      tally(window.IdCodes?.validate('iswc', w.iswc));
      rows.push({ entity: 'work', id: w.id, label: w.title || w.id, routeName: 'work', routePayload: w, issues: a ? a.issues : [] });
    }
    for (const r of (recordings || []).slice(0, 200)) {
      tally(window.IdCodes?.validate('isrc', r.isrc));
      const a = window.IdCodes?.auditEntity({ kind: 'recording', data: { id: r.id, isrc: r.isrc } });
      rows.push({ entity: 'recording', id: r.id, label: r.title || r.id, routeName: 'recording', routePayload: r, issues: a ? a.issues : [] });
    }
    for (const rel of (releases || []).slice(0, 200)) {
      const a = window.IdCodes?.auditEntity({ kind: 'release', data: { id: rel.id, upc: rel.upc, ean13: rel.ean13, grid: rel.grid, lc: rel.lc } });
      ['upc','ean13','grid','labelCode'].forEach((k) => { const v = k === 'labelCode' ? rel.lc : rel[k]; if (v) tally(window.IdCodes?.validate(k, v)); });
      rows.push({ entity: 'release', id: rel.id, label: rel.title || rel.id, issues: a ? a.issues : [] });
    }
    for (const p of (parties || []).slice(0, 200)) {
      ['ipiName','ipiBase','isni','dpid'].forEach((k) => { const v = k === 'ipiName' ? p.ipi : p[k]; if (v) tally(window.IdCodes?.validate(k, v)); });
      const a = window.IdCodes?.auditEntity({ kind: 'party', data: { id: p.id, ipi: p.ipi, ipiBase: p.ipiBase, isni: p.isni, dpid: p.dpid } });
      rows.push({ entity: 'party', id: p.id, label: p.name || p.id, issues: a ? a.issues : [] });
    }

    return { rows, totalChecked, totalValid, totalInvalid, totalWarn };
  }

  window.ScreenIdCodes = ScreenIdCodes;
})();
