// TABC Seeding Admin — import pipeline visualization
// Exports: window.Seeding

function Seeding({ onNav }) {
  const [stage, setStage] = React.useState(0); // 0 idle, 1 ingest, 2 normalize, 3 enrich, 4 dedupe, 5 done
  const [progress, setProgress] = React.useState(0);
  const [selected, setSelected] = React.useState('new-1');
  const [view, setView] = React.useState('pipeline'); // pipeline | queue | settings

  const run = () => {
    setStage(1); setProgress(0);
    let s = 1, p = 0;
    const iv = setInterval(() => {
      p += 4;
      setProgress(p);
      if (p >= 100 && s < 5) {
        s++; p = 0; setStage(s); setProgress(0);
      } else if (p >= 100 && s === 5) {
        clearInterval(iv);
      }
    }, 90);
  };

  return (
    <main className="container" style={{ paddingTop: 40, paddingBottom: 64 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
        <div>
          <div className="section-label">Admin · Data Operations</div>
          <h1 className="h-display" style={{ fontSize: 'clamp(40px, 5vw, 72px)' }}>
            TABC Seeding Pipeline
          </h1>
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <span className="chip" style={{ background: stage === 5 ? '#1f5d3c' : stage === 0 ? 'var(--chip)' : '#b8881e', color: stage === 0 ? 'var(--ink-soft)' : 'var(--paper)' }}>
            {stage === 0 ? 'Idle' : stage === 5 ? 'Run complete' : 'Running'}
          </span>
          <button className="btn" onClick={run} disabled={stage > 0 && stage < 5}>
            {stage === 5 ? 'Run again' : stage === 0 ? 'Start import run' : 'Running…'}
          </button>
        </div>
      </div>
      <p className="lede" style={{ marginBottom: 28, maxWidth: '70ch' }}>
        Ingests the Texas Alcoholic Beverage Commission's public licensee export (permits
        G, WB, Q) and transforms it into draft winery profiles. Source is a PIA/AIMS CSV
        refreshed quarterly. Nothing goes live without a human approval.
      </p>

      {/* Tabs */}
      <div style={{ display: 'flex', gap: 0, borderBottom: '1px solid var(--rule)', marginBottom: 32 }}>
        {[
          { v: 'pipeline', l: 'Pipeline' },
          { v: 'queue', l: 'Review queue' },
          { v: 'settings', l: 'Source & schedule' },
        ].map(t => (
          <button key={t.v} onClick={() => setView(t.v)} style={{
            padding: '12px 22px', background: 'transparent', border: 0,
            borderBottom: view === t.v ? '2px solid var(--accent)' : '2px solid transparent',
            cursor: 'pointer',
            fontFamily: 'var(--font-ui)', fontSize: 13, fontWeight: 600,
            color: view === t.v ? 'var(--ink)' : 'var(--ink-mute)',
          }}>{t.l}</button>
        ))}
      </div>

      {view === 'pipeline' && <PipelineView stage={stage} progress={progress} />}
      {view === 'queue' && <QueueView selected={selected} setSelected={setSelected} />}
      {view === 'settings' && <SettingsView />}
    </main>
  );
}

/* ================= PIPELINE ================= */
function PipelineView({ stage, progress }) {
  const steps = [
    {
      n: 1, key: 'ingest', title: 'Ingest',
      desc: 'Parse TABC PIA export (CSV). Filter to permit types G, WB, Q. Active status only.',
      stats: [['Rows in CSV', '4,812'], ['Winery permits', '671'], ['Active', '534'], ['Columns mapped', '18/18']],
      output: 'txt',
    },
    {
      n: 2, key: 'normalize', title: 'Normalize',
      desc: 'Canonicalize names (drop Inc/LLC/Corp), collapse DBA variants, parse addresses (USPS), resolve entity → single row per winery.',
      stats: [['Raw records', '534'], ['After dedupe', '517'], ['DBA collisions merged', '17'], ['Address parse fail', '3']],
      output: 'table',
    },
    {
      n: 3, key: 'enrich', title: 'Enrich',
      desc: 'Geocode addresses. Reverse-lookup county → AVA boundary (TTB shapefile). Discover website via Google Places + fuzzy domain match. Extract phone.',
      stats: [['Geocoded', '514/517'], ['AVA assigned', '498'], ['Website found', '421'], ['Phone found', '489']],
      output: 'map',
    },
    {
      n: 4, key: 'dedupe', title: 'Dedupe vs. directory',
      desc: 'Fuzzy match (Levenshtein ≥ 0.88 on name + 500m geoproximity) against existing records. Flag as new, possible-duplicate, or auto-update.',
      stats: [['New drafts', '187'], ['Possible duplicates', '24'], ['Updates to existing', '142'], ['Unchanged', '164']],
      output: 'list',
    },
    {
      n: 5, key: 'queue', title: 'Write to review queue',
      desc: 'High-confidence rows go straight to draft status. Low-confidence (missing AVA, duplicate, permit expiring) route to manual review.',
      stats: [['Auto-drafted', '149'], ['Needs review', '62'], ['Rejected', '0'], ['Est. outreach emails', '211']],
      output: 'summary',
    },
  ];

  return (
    <div>
      {/* Stepper visual */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 8, marginBottom: 28 }}>
        {steps.map((s, i) => {
          const done = stage > s.n;
          const active = stage === s.n;
          return (
            <div key={s.key} style={{
              padding: 14, borderTop: '3px solid',
              borderTopColor: done ? 'var(--accent)' : active ? 'var(--accent)' : 'var(--rule)',
              background: active ? 'var(--paper)' : 'transparent',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
                <span style={{
                  width: 20, height: 20, borderRadius: '50%',
                  background: done ? 'var(--accent)' : active ? 'var(--ink)' : 'transparent',
                  border: active || done ? 'none' : '1px solid var(--rule)',
                  color: (done || active) ? 'var(--paper)' : 'var(--ink-mute)',
                  fontFamily: 'var(--font-mono)', fontSize: 10, fontWeight: 700,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>{done ? '✓' : s.n}</span>
                <span style={{ fontFamily: 'var(--font-ui)', fontSize: 12, fontWeight: 600, color: active || done ? 'var(--ink)' : 'var(--ink-mute)' }}>
                  {s.title}
                </span>
              </div>
              {active && (
                <div style={{
                  height: 3, background: 'var(--chip)', overflow: 'hidden',
                  marginTop: 4,
                }}>
                  <div style={{ width: `${progress}%`, height: '100%', background: 'var(--accent)', transition: 'width 0.1s' }} />
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* Step cards */}
      {steps.map(s => {
        const done = stage > s.n;
        const active = stage === s.n;
        const revealed = done || active;
        return (
          <article key={s.key} style={{
            padding: 28,
            border: '1px solid var(--rule)',
            background: active ? 'var(--paper)' : revealed ? 'var(--paper)' : 'transparent',
            marginBottom: 12,
            opacity: revealed ? 1 : 0.55,
          }}>
            <div style={{ display: 'grid', gridTemplateColumns: 'auto 1fr auto', gap: 20, alignItems: 'start' }}>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.14em', color: 'var(--ink-mute)', paddingTop: 4 }}>
                STEP {String(s.n).padStart(2,'0')}
              </div>
              <div>
                <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 26, margin: '0 0 6px', letterSpacing: '-0.015em' }}>{s.title}</h3>
                <p style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--ink-soft)', margin: '0 0 16px', lineHeight: 1.55, maxWidth: '75ch' }}>{s.desc}</p>
                {revealed && (
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginTop: 14 }}>
                    {s.stats.map(([k,v]) => (
                      <div key={k} style={{ borderLeft: '2px solid var(--accent)', paddingLeft: 12 }}>
                        <div style={{ fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 600, color: 'var(--ink)', lineHeight: 1 }}>{v}</div>
                        <div style={{ fontFamily: 'var(--font-ui)', fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-mute)', marginTop: 6, fontWeight: 600 }}>{k}</div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
              <span className="chip" style={{
                background: done ? '#1f5d3c' : active ? '#b8881e' : 'var(--chip)',
                color: done || active ? 'var(--paper)' : 'var(--ink-mute)',
              }}>
                {done ? 'Complete' : active ? 'Running' : 'Pending'}
              </span>
            </div>

            {/* Output previews — only when step has run */}
            {done && s.key === 'ingest' && <OutputIngest />}
            {done && s.key === 'normalize' && <OutputNormalize />}
            {done && s.key === 'enrich' && <OutputEnrich />}
            {done && s.key === 'dedupe' && <OutputDedupe />}
            {done && s.key === 'queue' && <OutputQueue />}
          </article>
        );
      })}
    </div>
  );
}

/* ---- Step output panels ---- */
function Panel({ title, children }) {
  return (
    <div style={{ marginTop: 20, borderTop: '1px dashed var(--rule)', paddingTop: 18 }}>
      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-mute)', letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 10 }}>
        ↳ {title}
      </div>
      {children}
    </div>
  );
}

function OutputIngest() {
  const rows = [
    ['PERMIT_NO', 'TRADE_NAME', 'LEGAL_NAME', 'PERMIT_TYPE', 'STATUS', 'CITY', 'ZIP'],
    ['G-1229874', 'Becker Vineyards', 'Becker Vineyards, Inc.', 'G', 'ACTIVE', 'Stonewall', '78671'],
    ['WB-442019', 'William Chris Vineyards', 'William Chris Vineyards LLC', 'WB', 'ACTIVE', 'Hye', '78635'],
    ['G-0994512', 'Llano Estacado Winery', 'Llano Estacado Winery Inc', 'G', 'ACTIVE', 'Lubbock', '79404'],
    ['WB-551890', 'Duchman Family Winery', 'Duchman Family Winery LLC', 'WB', 'ACTIVE', 'Driftwood', '78619'],
    ['G-1021337', 'Pedernales Cellars', 'Pedernales Cellars, LLC', 'G', 'ACTIVE', 'Stonewall', '78671'],
    ['Q-331402', 'Lost Draw Cellars', 'Lost Draw Cellars LLC', 'Q', 'ACTIVE', 'Fredericksburg', '78624'],
  ];
  return (
    <Panel title="Raw CSV sample · first 6 rows">
      <div style={{ overflow: 'auto', border: '1px solid var(--rule)', background: '#0e1a14', color: '#d4e2d9', fontFamily: 'var(--font-mono)', fontSize: 11 }}>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <tbody>
            {rows.map((r, i) => (
              <tr key={i} style={{ borderBottom: '1px solid rgba(255,255,255,0.08)' }}>
                {r.map((c, j) => (
                  <td key={j} style={{ padding: '8px 12px', color: i === 0 ? '#8aab97' : '#d4e2d9', fontWeight: i === 0 ? 700 : 400, whiteSpace: 'nowrap' }}>{c}</td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </Panel>
  );
}

function OutputNormalize() {
  const transforms = [
    { from: '"Becker Vineyards, Inc."', to: 'Becker Vineyards', rule: 'strip corporate suffix' },
    { from: '"WILLIAM CHRIS VINEYARDS LLC"', to: 'William Chris Vineyards', rule: 'title-case + strip suffix' },
    { from: '"PEDERNALES CELLARS LLC" + "Pedernales Cellars, LLC"', to: 'Pedernales Cellars', rule: 'merge DBA variants' },
    { from: '"Duchman Family Winery / Mandola Estate"', to: 'Duchman Family Winery', rule: 'take primary DBA' },
  ];
  return (
    <Panel title="Normalization transforms">
      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>
        {transforms.map((t, i) => (
          <div key={i} style={{ display: 'grid', gridTemplateColumns: '1.4fr auto 1fr auto 1fr', gap: 12, padding: '10px 14px', background: i % 2 ? 'var(--chip)' : 'transparent', alignItems: 'center' }}>
            <code style={{ color: 'var(--ink-mute)' }}>{t.from}</code>
            <span style={{ color: 'var(--accent)' }}>→</span>
            <code style={{ color: 'var(--ink)', fontWeight: 600 }}>{t.to}</code>
            <span style={{ color: 'var(--ink-mute)' }}>·</span>
            <span style={{ color: 'var(--ink-soft)' }}>{t.rule}</span>
          </div>
        ))}
      </div>
    </Panel>
  );
}

function OutputEnrich() {
  const rows = [
    { name: 'Becker Vineyards', geo: '30.2461, -98.8944', ava: 'Fredericksburg', site: 'beckervineyards.com', conf: 0.98 },
    { name: 'William Chris', geo: '30.2718, -98.5663', ava: 'Fredericksburg', site: 'williamchriswines.com', conf: 0.97 },
    { name: 'Llano Estacado', geo: '33.4725, -101.8472', ava: 'Texas High Plains', site: 'llanowine.com', conf: 0.99 },
    { name: 'Pedernales Cellars', geo: '30.2396, -98.8512', ava: 'Fredericksburg', site: 'pedernalescellars.com', conf: 0.95 },
    { name: 'Small Cellars TX', geo: 'FAILED', ava: '—', site: '—', conf: 0.41 },
  ];
  return (
    <Panel title="Enrichment results · sample">
      <div style={{ border: '1px solid var(--rule)' }}>
        <table style={{ width: '100%', fontFamily: 'var(--font-mono)', fontSize: 12, borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ background: 'var(--chip)', textAlign: 'left' }}>
              {['Winery', 'Geocode', 'AVA', 'Domain', 'Confidence'].map(h => (
                <th key={h} style={{ padding: '10px 14px', fontFamily: 'var(--font-ui)', fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-mute)', fontWeight: 600 }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map((r, i) => (
              <tr key={i} style={{ borderTop: '1px solid var(--rule)', background: r.conf < 0.7 ? 'rgba(200,40,40,0.06)' : 'transparent' }}>
                <td style={{ padding: '10px 14px', fontFamily: 'var(--font-display)', fontSize: 14, fontWeight: 600 }}>{r.name}</td>
                <td style={{ padding: '10px 14px', color: r.geo === 'FAILED' ? '#b32d2d' : 'var(--ink-soft)' }}>{r.geo}</td>
                <td style={{ padding: '10px 14px', color: 'var(--ink-soft)' }}>{r.ava}</td>
                <td style={{ padding: '10px 14px', color: 'var(--accent)' }}>{r.site}</td>
                <td style={{ padding: '10px 14px' }}>
                  <span style={{
                    display: 'inline-block', padding: '2px 8px', borderRadius: 99,
                    background: r.conf > 0.9 ? '#1f5d3c' : r.conf > 0.7 ? '#b8881e' : '#b32d2d',
                    color: '#fff', fontSize: 11, fontWeight: 600,
                  }}>{r.conf.toFixed(2)}</span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </Panel>
  );
}

function OutputDedupe() {
  const matches = [
    { a: 'Becker Vineyards', b: 'Becker Vineyards (existing)', score: 0.99, action: 'update' },
    { a: 'Bending Branch Winery', b: 'Bending Branch (existing)', score: 0.91, action: 'update' },
    { a: 'Brennen Family Vineyards', b: 'Brennan Vineyards (existing)', score: 0.83, action: 'flag' },
    { a: 'Blue Horizon Winery', b: '— (none found)', score: 0, action: 'new' },
    { a: 'Messina Hof Hill Country', b: 'Messina Hof (existing)', score: 0.86, action: 'flag' },
  ];
  const color = (a) => a === 'new' ? '#1f5d3c' : a === 'update' ? '#2a5a8a' : '#b8881e';
  return (
    <Panel title="Dedupe decisions">
      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>
        {matches.map((m, i) => (
          <div key={i} style={{ display: 'grid', gridTemplateColumns: '1.4fr auto 1.4fr auto auto', gap: 16, padding: '10px 14px', borderBottom: '1px dotted var(--rule)', alignItems: 'center' }}>
            <span style={{ color: 'var(--ink)', fontWeight: 600 }}>{m.a}</span>
            <span style={{ color: 'var(--ink-mute)' }}>≈</span>
            <span style={{ color: 'var(--ink-soft)' }}>{m.b}</span>
            <span style={{ color: 'var(--ink-mute)' }}>score {m.score.toFixed(2)}</span>
            <span className="chip" style={{ background: color(m.action), color: 'var(--paper)' }}>{m.action}</span>
          </div>
        ))}
      </div>
    </Panel>
  );
}

function OutputQueue() {
  return (
    <Panel title="Run summary · what to do next">
      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 24, alignItems: 'start' }}>
        <div style={{ padding: 20, background: '#0e1a14', color: '#d4e2d9', fontFamily: 'var(--font-mono)', fontSize: 12, lineHeight: 1.7 }}>
          <div style={{ color: '#6fa18a' }}>$ wot-seed run --source tabc-2026-q2.csv</div>
          <div>→ 534 active winery permits parsed</div>
          <div>→ 517 canonicalized entities</div>
          <div>→ 514 geocoded · 498 AVA-assigned</div>
          <div>→ 142 updates to existing directory records</div>
          <div>→ 149 new drafts auto-published (needs-claim)</div>
          <div>→ 62 flagged for manual review</div>
          <div style={{ color: '#9ccf9c', marginTop: 10 }}>✓ Writing to seed/outputs/2026-q2.json (823 KB)</div>
          <div style={{ color: '#9ccf9c' }}>✓ 211 outreach candidates queued</div>
          <div style={{ marginTop: 10, color: '#d4b56f' }}>Next: open "Review queue" tab to approve flagged items.</div>
        </div>
        <div style={{ padding: 20, background: 'var(--chip)' }}>
          <div className="kicker" style={{ marginBottom: 10 }}>Export</div>
          <button className="btn btn-ghost" style={{ width: '100%', justifyContent: 'center', marginBottom: 8, fontSize: 11 }}>Download seed JSON</button>
          <button className="btn btn-ghost" style={{ width: '100%', justifyContent: 'center', marginBottom: 8, fontSize: 11 }}>Outreach CSV (Mailchimp)</button>
          <button className="btn" style={{ width: '100%', justifyContent: 'center', fontSize: 11 }}>Publish 149 drafts</button>
        </div>
      </div>
    </Panel>
  );
}

/* ================= REVIEW QUEUE ================= */
function QueueView({ selected, setSelected }) {
  const items = [
    { id: 'new-1', name: 'Brennen Family Vineyards', status: 'duplicate', reason: 'Name ≈ "Brennan Vineyards" (0.83)', ava: 'Hill Country', permit: 'G-1402881', city: 'Comanche' },
    { id: 'new-2', name: 'Messina Hof Hill Country', status: 'duplicate', reason: 'Same owner group as Messina Hof (Bryan)', ava: 'Hill Country', permit: 'WB-441502', city: 'Fredericksburg' },
    { id: 'new-3', name: 'Blue Horizon Winery', status: 'new', reason: 'No matches. Website unresolved.', ava: '— unknown', permit: 'G-1512903', city: 'Marble Falls' },
    { id: 'new-4', name: 'Six Shooter Cellars', status: 'missing-ava', reason: 'Geocode OK; outside all 8 AVAs.', ava: '— outside AVA', permit: 'WB-662018', city: 'Navasota' },
    { id: 'new-5', name: 'Small Cellars TX', status: 'geocode-fail', reason: 'Address could not be resolved.', ava: '—', permit: 'Q-339401', city: '(unknown)' },
    { id: 'new-6', name: 'Kerrville Hills Winery', status: 'update-conflict', reason: 'Website changed since last run.', ava: 'Hill Country', permit: 'G-0982140', city: 'Kerrville' },
    { id: 'new-7', name: 'Longhorn Cellars', status: 'new', reason: 'New in Q2 · permit issued Feb 2026', ava: 'Fredericksburg', permit: 'WB-710221', city: 'Fredericksburg' },
  ];
  const statusColor = {
    'duplicate': '#b8881e',
    'new': '#1f5d3c',
    'missing-ava': '#b8881e',
    'geocode-fail': '#b32d2d',
    'update-conflict': '#2a5a8a',
  };
  const cur = items.find(i => i.id === selected) || items[0];

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 32, alignItems: 'start' }}>
      <div style={{ border: '1px solid var(--rule)' }}>
        <div style={{ padding: '14px 16px', background: 'var(--chip)', fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-mute)', display: 'flex', justifyContent: 'space-between' }}>
          <span>{items.length} items · needs review</span>
          <span>TABC 2026-Q2</span>
        </div>
        {items.map(it => (
          <div key={it.id} onClick={() => setSelected(it.id)} style={{
            padding: '14px 16px', borderTop: '1px solid var(--rule)',
            background: selected === it.id ? 'var(--paper)' : 'transparent',
            cursor: 'pointer',
            borderLeft: selected === it.id ? '3px solid var(--accent)' : '3px solid transparent',
          }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start' }}>
              <div>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 600, letterSpacing: '-0.01em' }}>{it.name}</div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ink-mute)', letterSpacing: '0.1em', marginTop: 2, textTransform: 'uppercase' }}>
                  {it.permit} · {it.city.toUpperCase()}
                </div>
              </div>
              <span className="chip" style={{ background: statusColor[it.status], color: 'var(--paper)' }}>{it.status}</span>
            </div>
            <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--ink-soft)', marginTop: 6 }}>{it.reason}</div>
          </div>
        ))}
      </div>

      <aside style={{ position: 'sticky', top: 80 }}>
        <div style={{ padding: 24, background: 'var(--paper)', border: '1px solid var(--ink)' }}>
          <div className="kicker">Record · {cur.permit}</div>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 26, margin: '8px 0 6px', letterSpacing: '-0.015em' }}>{cur.name}</h3>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-mute)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
            {cur.city} · {cur.ava}
          </div>

          <div style={{ marginTop: 18, padding: 14, background: 'rgba(200,160,40,0.08)', border: '1px solid rgba(200,160,40,0.3)', borderRadius: 'var(--radius)' }}>
            <div style={{ fontFamily: 'var(--font-ui)', fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: '#7a5a18', fontWeight: 700, marginBottom: 6 }}>Why flagged</div>
            <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--ink)', lineHeight: 1.5 }}>{cur.reason}</div>
          </div>

          <h4 className="kicker" style={{ marginTop: 20 }}>Decision</h4>
          <div style={{ display: 'grid', gap: 8, marginTop: 12 }}>
            <button className="btn" style={{ width: '100%', justifyContent: 'center' }}>Publish as new draft</button>
            <button className="btn btn-ghost" style={{ width: '100%', justifyContent: 'center' }}>Merge into existing</button>
            <button className="btn btn-ghost" style={{ width: '100%', justifyContent: 'center' }}>Request more info</button>
            <button className="btn btn-ghost" style={{ width: '100%', justifyContent: 'center', color: '#b32d2d', borderColor: '#b32d2d' }}>Reject · not a winery</button>
          </div>
        </div>

        <div style={{ padding: 20, background: 'var(--chip)', marginTop: 16, fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--ink-soft)', lineHeight: 1.6 }}>
          <strong style={{ color: 'var(--ink)' }}>Pro tip:</strong> Duplicates often come from permit transfers, ownership changes, or multi-location wineries. Merging preserves history.
        </div>
      </aside>
    </div>
  );
}

/* ================= SETTINGS ================= */
function SettingsView() {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 40 }}>
      <div>
        <h3 className="h2" style={{ marginBottom: 16 }}>Data sources</h3>

        <SourceCard
          kind="Primary"
          name="TABC · AIMS Public Licensee Export"
          desc="Texas Alcoholic Beverage Commission's system of record. Permits filtered to G (Winery), WB (Winery Bonded), Q (Wine Bottler's)."
          status="connected"
          cadence="Quarterly PIA request · csv"
          lastRun="Apr 12, 2026 · 534 rows"
        />
        <SourceCard
          kind="Enrichment"
          name="TTB AVA Boundaries · Shapefile"
          desc="Federal appellation boundaries from the Alcohol and Tobacco Tax and Trade Bureau. Used for county → AVA assignment."
          status="connected"
          cadence="Manual · annual"
          lastRun="Jan 3, 2026"
        />
        <SourceCard
          kind="Enrichment"
          name="Google Places API"
          desc="Used to confirm website, phone, and hours. Falls back to manual search for low-confidence matches."
          status="connected"
          cadence="On each run · API"
          lastRun="Apr 12, 2026"
        />
        <SourceCard
          kind="Secondary"
          name="Go Texan · Member Roster"
          desc="Texas Department of Agriculture's Go Texan program winery roster. Used as a cross-reference for trade names."
          status="manual"
          cadence="Manual · biannual"
          lastRun="Feb 2026"
        />
      </div>

      <aside>
        <div style={{ padding: 24, background: 'var(--paper)', border: '1px solid var(--rule)' }}>
          <div className="kicker" style={{ marginBottom: 10 }}>Schedule</div>
          <div style={{ display: 'flex', justifyContent: 'space-between', padding: '10px 0', borderBottom: '1px dotted var(--rule)', fontFamily: 'var(--font-body)', fontSize: 14 }}>
            <span style={{ color: 'var(--ink-mute)' }}>Next PIA request</span>
            <span>Jul 1, 2026</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', padding: '10px 0', borderBottom: '1px dotted var(--rule)', fontFamily: 'var(--font-body)', fontSize: 14 }}>
            <span style={{ color: 'var(--ink-mute)' }}>Est. PIA turnaround</span>
            <span>10 business days</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', padding: '10px 0', borderBottom: '1px dotted var(--rule)', fontFamily: 'var(--font-body)', fontSize: 14 }}>
            <span style={{ color: 'var(--ink-mute)' }}>Delta detection</span>
            <span>Weekly diff</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', padding: '10px 0', fontFamily: 'var(--font-body)', fontSize: 14 }}>
            <span style={{ color: 'var(--ink-mute)' }}>Auto-publish ≥</span>
            <span>confidence 0.90</span>
          </div>
        </div>

        <div style={{ padding: 24, background: 'var(--chip)', marginTop: 16 }}>
          <div className="kicker" style={{ marginBottom: 10 }}>Compliance</div>
          <p style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--ink-soft)', margin: 0, lineHeight: 1.6 }}>
            All TABC data used here is public under Texas Government Code §552. Contact details are used strictly for directory listing and one-time onboarding outreach. Unsubscribe rate: <strong style={{ color: 'var(--ink)' }}>0.4%</strong>.
          </p>
        </div>
      </aside>
    </div>
  );
}

function SourceCard({ kind, name, desc, status, cadence, lastRun }) {
  return (
    <article style={{ padding: 22, border: '1px solid var(--rule)', background: 'var(--paper)', marginBottom: 10 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start', marginBottom: 8 }}>
        <div className="kicker">{kind}</div>
        <span className="chip" style={{ background: status === 'connected' ? '#1f5d3c' : '#b8881e', color: 'var(--paper)' }}>{status}</span>
      </div>
      <h4 style={{ fontFamily: 'var(--font-display)', fontSize: 20, margin: '0 0 6px', letterSpacing: '-0.01em' }}>{name}</h4>
      <p style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--ink-soft)', margin: '0 0 14px', lineHeight: 1.55 }}>{desc}</p>
      <div style={{ display: 'flex', gap: 18, fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-mute)', letterSpacing: '0.06em' }}>
        <span>CADENCE · {cadence}</span>
        <span>LAST · {lastRun}</span>
      </div>
    </article>
  );
}

window.Seeding = Seeding;
