/* =========================================================
   ALLEGEDLY — Accountability DB
   Single-file React app. Hash routing. No build step.
   Routes:
     #/                      Directory (default)
     #/p/<sample-id>         Dossier for one product
     #/adaptogens            Adaptogen reference grid
     #/adaptogens/<slug>     Single adaptogen detail
     #/show/<sample-id>      Episode (Accountability Show) stub
   ========================================================= */
const { useState, useEffect, useMemo } = React;

/* ---------- helpers ---------- */
const slug = s => String(s||'').toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'');
const yes = v => v === 'Yes' || v === 'YES' || v === true;
const norm = v => (v == null || v === '' ? null : v);

function useRoute(){
  const get = () => (window.location.hash || '#/').replace(/^#/,'') || '/';
  const [r, setR] = useState(get);
  useEffect(()=>{
    const fn = () => setR(get());
    window.addEventListener('hashchange', fn);
    return () => window.removeEventListener('hashchange', fn);
  }, []);
  return r;
}

function matchRoute(path){
  if (path === '/' || path === '') return { name:'directory' };
  let m = path.match(/^\/p\/([\w-]+)$/);
  if (m) return { name:'dossier', sampleId: m[1] };
  m = path.match(/^\/adaptogens\/?$/);
  if (m) return { name:'adaptogens' };
  m = path.match(/^\/adaptogens\/([\w-]+)$/);
  if (m) return { name:'adaptogen', slug: m[1] };
  m = path.match(/^\/show\/([\w-]+)$/);
  if (m) return { name:'episode', sampleId: m[1] };
  return { name:'404' };
}

function feasibilityClass(f){
  if (!f) return '';
  const s = String(f).toUpperCase();
  if (s.startsWith('HIGH')) return 'feas-HIGH';
  if (s.startsWith('MODERATE')) return 'feas-MODERATE';
  if (s.startsWith('VERY LOW')) return 'feas-VERY';
  if (s.startsWith('LOW')) return 'feas-LOW';
  return '';
}

/* ---------- primitives ---------- */
function Grade({ g, size }){
  const v = (g && String(g).trim()) || 'NA';
  const cls = 'grade grade-'+(['A','B','C','D','F'].includes(v) ? v : 'NA') + (size==='lg' ? ' lg' : '');
  return <span className={cls}>{v === 'NA' ? '·' : v}</span>;
}
function Pill({ status }){
  const v = (status && String(status).trim()) || 'QUEUED';
  return <span className={'pill pill-'+v}>{v}</span>;
}
function PassFail({ v, label }){
  if (v === 'Yes' || v === 'YES') return <span className="pill pill-PASSED">{label || 'PASS'}</span>;
  if (v === 'No' || v === 'NO')  return <span className="pill pill-FAILED">{label || 'FAIL'}</span>;
  return <span className="pill">PENDING</span>;
}

/* ---------- header ---------- */
function Header({ count, dosed, blend, none }){
  return (
    <header className="header">
      <div className="wrap">
        <div className="eyebrow"><span className="e-n">01</span><span>CASE FILES // ADAPTOGENIC BEVERAGES</span></div>
        <h1 className="h-mega">The Accountability DB<span className="alg" style={{fontFamily:'var(--serif)',fontSize:'0.5em',verticalAlign:'0.45em'}}>*</span></h1>
        <p className="lede" style={{marginTop:'18px'}}>
          A searchable, lab-verified database of every adaptogenic beverage on the market — ingredients, doses, claims, and whether they hold up. We test one product per day on camera. Until a sample comes back from the lab, every claim is, by definition, alleged.
        </p>
        <p className="fn" style={{marginTop:'10px',maxWidth:'62ch'}}>
          Allegedly is the first adaptogen company to publicly verify its competitors&apos; claims. The footnote is the feature.
        </p>
        <div className="header-meta">
          <div className="meta-cell"><span className="ml">Products tracked</span><span className="mv">{count}</span></div>
          <div className="meta-cell"><span className="ml">Disclose mg/dose</span><span className="mv">{dosed}<span className="mv-mono" style={{display:'inline',marginLeft:8,color:'var(--light-3)'}}>/ {count}</span></span></div>
          <div className="meta-cell"><span className="ml">Use “blend” language</span><span className="mv">{blend}</span></div>
          <div className="meta-cell"><span className="ml">No dose info</span><span className="mv" style={{color:'var(--red)'}}>{none}</span></div>
          <div className="meta-cell"><span className="ml">COAs published</span><span className="mv">0</span></div>
        </div>
      </div>
    </header>
  );
}

/* ---------- filter bar ---------- */
const GRADES = ['A','D','F'];
const STATUSES = ['QUEUED','SAMPLED','LAB','PUBLISHED'];

function FilterBar({ q, setQ, grade, setGrade, status, setStatus, dosed, setDosed, total, shown }){
  return (
    <div className="filter-bar">
      <div className="filter-inner">
        <div className="filter-group">
          <span className="fl">QUERY</span>
          <input className="search-input" placeholder="brand, product, adaptogen…" value={q} onChange={e=>setQ(e.target.value)} />
        </div>
        <div className="filter-group">
          <span className="fl">GRADE</span>
          <button className={'chip '+(grade==='ALL'?'active':'')} onClick={()=>setGrade('ALL')}>ALL</button>
          {GRADES.map(g => (
            <button key={g} className={'chip '+(grade===g?'active':'')} onClick={()=>setGrade(g)}>{g}</button>
          ))}
        </div>
        <div className="filter-group">
          <span className="fl">STATUS</span>
          <button className={'chip '+(status==='ALL'?'active':'')} onClick={()=>setStatus('ALL')}>ALL</button>
          {STATUSES.map(s => (
            <button key={s} className={'chip '+(status===s?'active':'')} onClick={()=>setStatus(s)}>{s}</button>
          ))}
        </div>
        <div className="filter-group">
          <button className={'chip '+(dosed?'active':'')} onClick={()=>setDosed(!dosed)}>DOSE DISCLOSED</button>
        </div>
        <span className="result-count">{shown} / {total} CASE FILES</span>
      </div>
    </div>
  );
}

/* ---------- directory list ---------- */
function Directory({ products }){
  const [q, setQ] = useState('');
  const [grade, setGrade] = useState('ALL');
  const [status, setStatus] = useState('ALL');
  const [dosed, setDosed] = useState(false);

  const stats = useMemo(()=>{
    const dosedC = products.filter(p => p['Dose Disclosed?']==='YES').length;
    const noneC  = products.filter(p => !p['Dose Disclosed?'] || p['Dose Disclosed?']==='NO').length;
    const blendC = products.filter(p => String(p['Key Adaptogens']||'').toLowerCase().includes('blend')).length;
    return { dosedC, noneC, blendC };
  }, [products]);

  const filtered = useMemo(()=>{
    const qq = q.trim().toLowerCase();
    return products.filter(p=>{
      if (grade !== 'ALL' && p['Transparency Grade'] !== grade) return false;
      if (status !== 'ALL' && p['Test Status'] !== status) return false;
      if (dosed && p['Dose Disclosed?'] !== 'YES') return false;
      if (qq){
        const hay = [p['Brand'], p['Product Name'], p['Key Adaptogens'], p['Other Actives'], p['Category']].join(' ').toLowerCase();
        if (!hay.includes(qq)) return false;
      }
      return true;
    });
  }, [products, q, grade, status, dosed]);

  return (
    <div className="view">
      <Header count={products.length} dosed={stats.dosedC} blend={stats.blendC} none={stats.noneC} />
      <FilterBar
        q={q} setQ={setQ}
        grade={grade} setGrade={setGrade}
        status={status} setStatus={setStatus}
        dosed={dosed} setDosed={setDosed}
        total={products.length} shown={filtered.length} />
      <section className="directory">
        <div className="dir-row dir-head">
          <span>GRADE</span>
          <span>BRAND // PRODUCT</span>
          <span className="dc-adapt">CLAIMED ADAPTOGENS</span>
          <span className="dc-cat">CATEGORY</span>
          <span className="dc-status">DOSE</span>
          <span className="dc-status">STATUS</span>
          <span>ID</span>
        </div>
        {filtered.map(p => {
          const sid = p['Sample ID'];
          return (
            <a key={sid} href={'#/p/'+sid} className="dir-row">
              <Grade g={p['Transparency Grade']} />
              <div>
                <div className="dc-brand">{p['Brand']}</div>
                <div className="dc-name">{p['Product Name']}</div>
              </div>
              <div className="dc-adapt">{p['Key Adaptogens']}</div>
              <div className="dc-cat" style={{fontFamily:'var(--data)',fontSize:'10px',letterSpacing:'0.12em',textTransform:'uppercase',color:'var(--silver)'}}>{p['Category']}</div>
              <div className="dc-status">
                {p['Dose Disclosed?']==='YES'
                  ? <span className="pill pill-PASSED">YES</span>
                  : <span className="pill pill-FAILED">NO</span>}
              </div>
              <div className="dc-status"><Pill status={p['Test Status']} /></div>
              <div className="dc-id">{sid}</div>
            </a>
          );
        })}
        {filtered.length === 0 && (
          <div className="dir-row" style={{display:'block',padding:'48px var(--gutter)',color:'var(--silver)',fontStyle:'italic',fontFamily:'var(--serif)',fontSize:'22px'}}>
            No case files match. Adjust the filters.
          </div>
        )}
      </section>
    </div>
  );
}

/* ---------- dossier ---------- */
function Cell({ label, children, num, serif, muted, tbd }){
  return (
    <div className="dg-cell">
      <div className="dgl"><span>{label}</span></div>
      <div className={'dgv '+(serif?'dgv-serif ':'')+(num?'dgv-num ':'')+(muted?'dgv-muted ':'')+(tbd?'dgv-tbd':'')}>
        {tbd ? 'pending' : (children || <span className="dgv-muted">—</span>)}
      </div>
    </div>
  );
}

function Dossier({ sampleId, products }){
  const p = products.find(x => x['Sample ID'] === sampleId);
  if (!p) return <div className="wrap section view"><p className="lede">Sample {sampleId} not found. <a href="#/" className="bar-link">Back to the index.</a></p></div>;

  const status = p['Test Status'] || 'QUEUED';
  const tested = status === 'PUBLISHED' || norm(p['COA Reference']);

  return (
    <div className="dossier view">
      <div className="wrap">
        <div className="dossier-stamp">
          <a href="#/" className="dossier-back">← INDEX</a>
          <span>CASE FILE {p['Sample ID']}</span>
          <Pill status={status} />
          <Grade g={p['Transparency Grade']} />
          <a href={'#/show/'+p['Sample ID']} className="dossier-back" style={{marginLeft:'auto'}}>SHOW EPISODE →</a>
        </div>

        <div className="dossier-head">
          <div>
            <div className="dh-brand">{p['Brand']}</div>
            <h1 className="dh-name">{p['Product Name']}</h1>
            <div className="dh-cat">{p['Category']}</div>
          </div>
          <Grade g={p['Transparency Grade']} size="lg" />
        </div>

        <div className="dossier-grid">
          <Cell label="CLAIMED ADAPTOGENS" serif>{p['Key Adaptogens']}</Cell>
          <Cell label="OTHER ACTIVES">{p['Other Actives']}</Cell>
          <Cell label="FORMAT">{p['Format']} · {p['Pack Size']}</Cell>
          <Cell label="PRICE">{p['Price (USD)']}</Cell>
          <Cell label="SUGAR (g/serving)" num>{norm(p['Sugar (g/serving)']) ?? '—'}</Cell>
          <Cell label="CAFFEINE (mg)" num>{norm(p['Caffeine (mg)']) ?? '—'}</Cell>
          <Cell label="ALCOHOL-FREE">{p['Alcohol-Free']}</Cell>
          <Cell label="MARKET">{p['Country/Market']} · <a href={'https://'+p['Website/Source']} target="_blank" rel="noreferrer" style={{borderBottom:'1px solid currentColor',color:'var(--silver-bright)'}}>{p['Website/Source']}</a></Cell>
          <Cell label="DOSE DISCLOSED ON LABEL?">
            {p['Dose Disclosed?']==='YES'
              ? <span className="pill pill-PASSED">YES</span>
              : <span className="pill pill-FAILED">NO</span>}
          </Cell>
          <Cell label="TRANSPARENCY GRADE">
            <span style={{fontFamily:'var(--serif)',fontSize:'28px'}}>{p['Transparency Grade']}</span>
            <span className="dgv-muted" style={{marginLeft:'10px',fontFamily:'var(--mono)',fontSize:'12px'}}>
              {p['Transparency Grade']==='A' && 'discloses milligrams per ingredient'}
              {p['Transparency Grade']==='D' && 'lists adaptogens, no doses'}
              {p['Transparency Grade']==='F' && 'lists “blend” only or worse'}
            </span>
          </Cell>
        </div>

        <div className="dossier-coa">
          <div className="coa-head">
            <span className="coa-title">CERTIFICATE OF ANALYSIS</span>
            <span>SAMPLE {p['Sample ID']}</span>
            <span>LAB: {p['Lab Partner'] || 'TBD'}</span>
            <span>COA REF: {p['COA Reference'] || '—'}</span>
          </div>
          <div className="coa-body">
            {tested ? (
              <table className="coa-table">
                <thead>
                  <tr>
                    <th>ASSAY</th><th>METHOD</th><th className="num">CLAIMED</th><th className="num">ACTUAL</th><th>RESULT</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td>Potency · adaptogens</td><td>HPLC</td>
                    <td className="num">{p['Key Adaptogens']}</td>
                    <td className="num">{p['Actual Adaptogens (mg)'] || '—'}</td>
                    <td>{p['Actual vs Claimed'] || '—'}</td>
                  </tr>
                  <tr>
                    <td>Identity</td><td>HPTLC + DNA barcoding</td>
                    <td className="num">label</td>
                    <td className="num">{p['Identity Confirmed?']==='Yes' ? 'matched' : 'not yet'}</td>
                    <td><PassFail v={p['Identity Confirmed?']} /></td>
                  </tr>
                  <tr>
                    <td>Heavy metals</td><td>ICP-MS</td>
                    <td className="num">USP &lt; limits</td>
                    <td className="num">{p['Heavy Metals Pass?'] || '—'}</td>
                    <td><PassFail v={p['Heavy Metals Pass?']} /></td>
                  </tr>
                  <tr>
                    <td>Microbiology</td><td>USP &lt;61&gt;/&lt;62&gt;</td>
                    <td className="num">USP &lt; limits</td>
                    <td className="num">{p['Micro Pass?'] || '—'}</td>
                    <td><PassFail v={p['Micro Pass?']} /></td>
                  </tr>
                  <tr>
                    <td>Clinical dose match</td><td>vs systematic reviews</td>
                    <td className="num">clinical range</td>
                    <td className="num">{p['Clinical Dose Match?'] || '—'}</td>
                    <td>{p['Evidence Grade'] ? <span className="pill">{p['Evidence Grade']}</span> : <span className="pill">PENDING</span>}</td>
                  </tr>
                </tbody>
              </table>
            ) : (
              <p className="coa-empty">
                Awaiting lab. Until this sample comes back from an ISO-17025 facility with a Certificate of Analysis, every claim on this product is, <em>by definition</em>, <span className="alg">allegedly</span> true.
              </p>
            )}
          </div>
        </div>

        <div style={{marginTop:'40px'}} className="verdict">
          <Grade g={p['Transparency Grade']} size="lg" />
          <div>
            <div className="v-claim">
              {(p['Allegedly Verdict']) || (
                p['Transparency Grade']==='A'
                  ? <span>Discloses milligram doses on label. <em>Worth lab-verifying.</em></span>
                  : p['Transparency Grade']==='F'
                    ? <span>Calls its formula a “blend.” <em>The label doesn&apos;t commit to anything.</em></span>
                    : <span>Lists adaptogens without doses. <em>Plausibly clinical. Probably not.</em></span>
              )}
            </div>
            <div className="v-sub">VERDICT // ALLEGEDLY. *PENDING LAB</div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- adaptogen reference ---------- */
function AdaptogenList({ adaptogens }){
  return (
    <div className="view">
      <header className="header">
        <div className="wrap">
          <div className="eyebrow"><span className="e-n">02</span><span>CLINICAL REFERENCE // 26 ADAPTOGENS</span></div>
          <h1 className="h-mega">The Reference</h1>
          <p className="lede" style={{marginTop:'18px'}}>
            Every adaptogen on the market, indexed against systematic reviews and meta-analyses. Clinical dose, evidence grade, and whether a beverage serving can plausibly carry the dose at all.
          </p>
        </div>
      </header>
      <section className="section">
        <div className="wrap">
          <div className="adapt-grid">
            {adaptogens.map(a => (
              <a key={a['Adaptogen']} href={'#/adaptogens/'+slug(a['Adaptogen'])} className="adapt-card">
                <div>
                  <div className="ac-cat">{a['Category']} · {a['Traditional Use']}</div>
                  <div className="ac-name" style={{marginTop:6}}>{a['Adaptogen']}</div>
                </div>
                <div className="ac-dose">{a['Clinical Dose Range']}<br/><span style={{color:'var(--light-3)'}}>study window: {a['Study Duration']}</span></div>
                <div className={'ac-feas '+feasibilityClass(a['Beverage Dose Feasibility'])}>
                  Beverage feasibility: {a['Beverage Dose Feasibility'] || '—'}
                </div>
              </a>
            ))}
          </div>
        </div>
      </section>
    </div>
  );
}

function AdaptogenDetail({ slugId, adaptogens, products }){
  const a = adaptogens.find(x => slug(x['Adaptogen']) === slugId);
  if (!a) return <div className="wrap section view"><p className="lede">Adaptogen not found. <a href="#/adaptogens" className="bar-link">Back to the reference.</a></p></div>;
  const lower = (a['Adaptogen']||'').toLowerCase();
  const using = products.filter(p => String(p['Key Adaptogens']||'').toLowerCase().includes(lower.split(' ')[0]));

  return (
    <div className="adapt-detail view">
      <div className="wrap">
        <div className="dossier-stamp" style={{marginTop:24}}>
          <a href="#/adaptogens" className="dossier-back">← REFERENCE</a>
          <span>{a['Category']?.toUpperCase()} · {a['Traditional Use']?.toUpperCase()}</span>
          <span className="pill">EVIDENCE {a['Evidence Grade']}</span>
        </div>
        <h1 className="dh-name" style={{marginTop:32, marginBottom:12, fontFamily:'var(--serif)', fontSize:'clamp(48px,8vw,112px)', lineHeight:0.98}}>{a['Adaptogen']}</h1>
        <p className="lede">{a['Key Benefits']}</p>

        <div className="dossier-grid" style={{marginTop:40}}>
          <Cell label="CLINICAL DOSE">{a['Clinical Dose Range']}</Cell>
          <Cell label="STUDY DURATION">{a['Study Duration']}</Cell>
          <Cell label="META-ANALYSES" num>{a['Meta-Analyses']}</Cell>
          <Cell label="RCT COUNT">{a['RCT Count']}</Cell>
          <Cell label="TOTAL N (subjects)">{a['Total N']}</Cell>
          <Cell label="EVIDENCE GRADE">{a['Evidence Grade']}</Cell>
          <Cell label="KEY MARKER COMPOUND" serif>{a['Key Marker Compound']}</Cell>
          <Cell label="HPLC METHOD AVAILABLE">{a['HPLC Method Available?']}</Cell>
          <Cell label="BEVERAGE DOSE FEASIBILITY">
            <span className={feasibilityClass(a['Beverage Dose Feasibility'])} style={{fontFamily:'var(--data)',letterSpacing:'0.12em',textTransform:'uppercase'}}>
              {a['Beverage Dose Feasibility']}
            </span>
          </Cell>
          <Cell label="ACUTE EFFECT?">{a['Acute Effect?']}</Cell>
          <Cell label="COMMON FORMS">{a['Common Forms']}</Cell>
          <Cell label="TRADITIONAL USE">{a['Traditional Use']}</Cell>
        </div>

        <h2 className="disp" style={{marginTop:64, marginBottom:18}}>
          Products in the database using <em>{a['Adaptogen']}</em>
        </h2>
        <section className="directory" style={{borderTop:'1px solid var(--line)'}}>
          <div className="dir-row dir-head">
            <span>GRADE</span><span>BRAND // PRODUCT</span><span className="dc-adapt">CLAIMED ADAPTOGENS</span><span className="dc-cat">CATEGORY</span><span className="dc-status">DOSE</span><span className="dc-status">STATUS</span><span>ID</span>
          </div>
          {using.map(p => (
            <a key={p['Sample ID']} href={'#/p/'+p['Sample ID']} className="dir-row">
              <Grade g={p['Transparency Grade']} />
              <div><div className="dc-brand">{p['Brand']}</div><div className="dc-name">{p['Product Name']}</div></div>
              <div className="dc-adapt">{p['Key Adaptogens']}</div>
              <div className="dc-cat" style={{fontFamily:'var(--data)',fontSize:'10px',letterSpacing:'0.12em',textTransform:'uppercase',color:'var(--silver)'}}>{p['Category']}</div>
              <div className="dc-status">{p['Dose Disclosed?']==='YES' ? <span className="pill pill-PASSED">YES</span> : <span className="pill pill-FAILED">NO</span>}</div>
              <div className="dc-status"><Pill status={p['Test Status']} /></div>
              <div className="dc-id">{p['Sample ID']}</div>
            </a>
          ))}
          {using.length === 0 && (
            <div style={{padding:'32px var(--gutter)',color:'var(--silver)',fontStyle:'italic',fontFamily:'var(--serif)',fontSize:'18px'}}>No products in the database currently claim {a['Adaptogen']}.</div>
          )}
        </section>
      </div>
    </div>
  );
}

/* ---------- episode (show stub) ---------- */
const SHOW_STEPS = [
  { n:'01', t:'PURCHASE',     d:'Buy from retail shelf on camera. Full label photography. Timestamped receipt.' },
  { n:'02', t:'TASTE TEST',   d:'10 testers rate taste, texture, and perceived effects independently.' },
  { n:'03', t:'CLAIMS AUDIT', d:'Every label / website / social claim cross-referenced against clinical evidence.' },
  { n:'04', t:'SEAL + SHIP',  d:'Sealed in tamper-evident bag on camera. Shipped to ISO-17025 lab with chain-of-custody form.' },
  { n:'05', t:'LAB RESULTS',  d:'Certificate of Analysis returned. Actual mg vs claimed mg. Heavy metals pass/fail.' },
  { n:'06', t:'PUBLISH',      d:'Full video with COA overlay. Grade assigned. Database updated. Sticker applied.' },
];

function Episode({ sampleId, products }){
  const p = products.find(x => x['Sample ID'] === sampleId);
  if (!p) return <div className="wrap section view"><p className="lede">Sample {sampleId} not found. <a href="#/" className="bar-link">Back to the index.</a></p></div>;
  const status = p['Test Status'] || 'QUEUED';
  const completed = { QUEUED:0, SAMPLED:2, LAB:4, PUBLISHED:6 }[status] || 0;

  return (
    <div className="episode view">
      <div className="wrap">
        <div className="dossier-stamp" style={{marginTop:24}}>
          <a href={'#/p/'+sampleId} className="dossier-back">← DOSSIER</a>
          <span>EPISODE · {p['Sample ID']}</span>
          <Pill status={status} />
          {p['Video URL'] && <a href={p['Video URL']} target="_blank" rel="noreferrer" className="dossier-back" style={{marginLeft:'auto'}}>WATCH ↗</a>}
        </div>

        <h1 className="dh-name" style={{marginTop:24, fontFamily:'var(--serif)', fontSize:'clamp(36px,6vw,80px)', lineHeight:0.98}}>
          We tested <em>{p['Brand']} {p['Product Name']}</em>.
        </h1>
        <p className="lede" style={{marginTop:16}}>
          {status === 'PUBLISHED'
            ? 'Episode published. COA on file. Sticker dispatched.'
            : 'Episode in queue. The footage starts on the retail shelf and ends in a sealed bag on the lab counter.'}
        </p>

        <div className="episode-frame">
          {p['Video URL'] ? (
            <span className="ef-label"><span className="ef-big">▶</span><span>VIDEO PUBLISHED</span></span>
          ) : (
            <span className="ef-label"><span className="ef-big">PEND</span><span>SHOW SLOT RESERVED</span></span>
          )}
        </div>

        <div className="episode-steps">
          {SHOW_STEPS.map((s, i) => (
            <div key={s.n} className="episode-step">
              <span className="es-n">{s.n}</span>
              <div>
                <div className="es-title">{s.t}</div>
                <div className="es-desc">{s.d}</div>
              </div>
              <Pill status={
                i < completed ? 'PUBLISHED'
                : i === completed ? 'SAMPLED'
                : 'QUEUED'
              } />
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ---------- subnav: links between major surfaces ---------- */
function SubNav({ active }){
  const item = (href, label, isActive) => (
    <a href={href} className="chip" style={{
      borderColor: isActive ? 'var(--silver-bright)' : 'var(--line)',
      color: isActive ? 'var(--light)' : 'var(--light-2)',
      background: isActive ? 'oklch(72% 0.007 250 / 0.08)' : 'transparent',
    }}>{label}</a>
  );
  return (
    <div style={{
      position:'sticky', top:0, zIndex:60,
      background:'oklch(8% 0.006 252 / 0.92)', backdropFilter:'blur(10px)',
      borderBottom:'1px solid var(--line)',
      padding:'10px var(--gutter)',
      display:'flex', gap:10, alignItems:'center', justifyContent:'center',
    }}>
      {item('#/', 'CASE FILES', active==='directory')}
      {item('#/adaptogens', 'ADAPTOGEN REFERENCE', active==='adaptogens'||active==='adaptogen')}
      <span style={{fontFamily:'var(--data)',fontSize:'9px',letterSpacing:'0.2em',textTransform:'uppercase',color:'var(--silver)',marginLeft:'auto'}}>ALLEGEDLY · ACCOUNTABILITY DB</span>
    </div>
  );
}

/* ---------- app ---------- */
function App(){
  const [ready, setReady] = useState(window.ACC && window.ACC.ready);
  useEffect(()=>{
    if (!ready) window.ACC.onReady(()=>setReady(true));
  }, [ready]);
  const route = useRoute();

  if (!ready) return (
    <div className="wrap section">
      <p className="lede" style={{fontFamily:'var(--serif)',fontStyle:'italic',color:'var(--silver)'}}>Loading case files…</p>
    </div>
  );

  const r = matchRoute(route);
  const products = window.ACC.products;
  const adaptogens = window.ACC.adaptogens;

  return (
    <>
      <SubNav active={r.name} />
      {r.name === 'directory' && <Directory products={products} />}
      {r.name === 'dossier'   && <Dossier sampleId={r.sampleId} products={products} />}
      {r.name === 'episode'   && <Episode sampleId={r.sampleId} products={products} />}
      {r.name === 'adaptogens'&& <AdaptogenList adaptogens={adaptogens} />}
      {r.name === 'adaptogen' && <AdaptogenDetail slugId={r.slug} adaptogens={adaptogens} products={products} />}
      {r.name === '404'       && <div className="wrap section view"><p className="lede">404 · unknown route. <a href="#/" className="bar-link">Back to the index.</a></p></div>}
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
