// Direction B — BUREAU (v2)
// Pushed further into "public filing" territory.
//
// New in v2:
//   · Sticky left rail — fascicle TOC w/ progress, active-section glow
//   · Hero revenue stamp + examiner signature line
//   · Ticker bar — rotating recent attestations
//   · Click any row → expanded FORM card inline (mini schematic, full url,
//     attestation timestamp, related entries from same fascicle)
//   · ⌘K command palette (search + jump)
//   · "Examined ✓" mark on every row, hand-stamp on hover
//   · Page numbers in section headers · ledger feel
//
// Mounted as <SuedeBureau dark={bool} onToggleDark={fn} />

const Bureau = (() => {
  const { useState, useEffect, useMemo, useRef, useCallback } = React;

  // ─── Module-level tweak state ─────────────────────────────
  // SuedeBureau syncs its useTweaks() result here on every render so all the
  // inner components (which call tokens(dark) freshly) pick up the live values
  // without needing every helper to take an `accent` prop.
  let _tweaks = { accent: 'amber', density: 'standard', showTicker: true, displaySerif: true, audience: 'all' };
  const ACCENT_MAP = {
    amber:    { dark: '#e8d56b', light: '#a7551b', seal: { dark: '#e8d56b', light: '#a83617' } },
    oxide:    { dark: '#7fb5d8', light: '#1d5b8a', seal: { dark: '#7fb5d8', light: '#1d5b8a' } },
    bordeaux: { dark: '#d28b8b', light: '#7a1f25', seal: { dark: '#d28b8b', light: '#7a1f25' } },
    ink:      { dark: '#ece6d3', light: '#161410', seal: { dark: '#ece6d3', light: '#161410' } },
  };
  const DENSITY = {
    compact:  { rowPadY: 7,  rowFs: 11.5, titleFs: 16 },
    standard: { rowPadY: 10, rowFs: 12,   titleFs: 17 },
    comfy:    { rowPadY: 14, rowFs: 13,   titleFs: 19 },
  };

  const tokens = (dark) => {
    const a = ACCENT_MAP[_tweaks.accent] || ACCENT_MAP.amber;
    const accent = a[dark ? 'dark' : 'light'];
    const seal   = a.seal[dark ? 'dark' : 'light'];
    return ({
      bg:         dark ? '#0a0a08' : '#f6f3ea',
      bgDeep:     dark ? '#050505' : '#ede8d8',
      bgPaper:    dark ? '#0e0d0b' : '#fbf7ec',
      fg:         dark ? '#ece6d3' : '#161410',
      fgSoft:     dark ? 'rgba(236,230,211,0.62)' : 'rgba(22,20,16,0.58)',
      fgMute:     dark ? 'rgba(236,230,211,0.38)' : 'rgba(22,20,16,0.38)',
      rule:       dark ? 'rgba(236,230,211,0.22)' : 'rgba(22,20,16,0.22)',
      ruleSoft:   dark ? 'rgba(236,230,211,0.09)' : 'rgba(22,20,16,0.10)',
      row:        dark ? 'rgba(236,230,211,0.03)' : 'rgba(22,20,16,0.025)',
      hi:         dark ? 'rgba(236,230,211,0.07)' : 'rgba(22,20,16,0.06)',
      accent,
      accentDim:  dark ? 'rgba(232,213,107,0.18)' : 'rgba(167,85,27,0.16)',
      seal,
      sealSoft:   dark ? 'rgba(232,213,107,0.22)' : 'rgba(168,54,23,0.22)',
      density:    DENSITY[_tweaks.density] || DENSITY.standard,
      displaySerif: _tweaks.displaySerif !== false,
    });
  };

  const FONTS = {
    mono: '"JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, monospace',
    serif: '"Cormorant Garamond", "EB Garamond", Georgia, serif',
    sans: '"Inter Tight", "Helvetica Neue", Arial, sans-serif',
  };

  // ─── Helpers ──────────────────────────────────────────────
  const STATUSES = ['LIVE','LIVE','LIVE','LIVE','LIVE','LIVE','LIVE','BETA','BETA','SCHED'];
  function statusFor(url) {
    let h = 0; for (let i = 0; i < url.length; i++) h = (h * 31 + url.charCodeAt(i)) >>> 0;
    return STATUSES[h % STATUSES.length];
  }
  function classFor(host) {
    if (/coinbase|stargate|virtuals/.test(host)) return 'EXT';
    if (/\.org/.test(host)) return 'PAPER';
    if (/app\./.test(host)) return 'CONSOLE';
    if (/^[a-z]+\.suedeai/.test(host)) return 'NODE';
    return 'PUBLIC';
  }
  function hostOf(u) { try { return new URL(u).host; } catch (e) { return u; } }

  // Deterministic "examined" date so things don't reshuffle on rerender
  function examDate(url) {
    let h = 0; for (let i = 0; i < url.length; i++) h = (h * 17 + url.charCodeAt(i)) >>> 0;
    const d = new Date(Date.UTC(2026, 0, 1));
    d.setUTCDate(d.getUTCDate() + (h % 138));
    return d.toISOString().slice(0,10).replace(/-/g, '.');
  }
  function formNo(secIdx, itemIdx) {
    return `SLBO-${String(secIdx+1).padStart(2,'0')}.${String(itemIdx+1).padStart(2,'0')}`;
  }

  // ─── Screenshot loader (thum.io w/ schematic fallback) ────
  // Renders a real screenshot for any public URL. On failure (timeout, blocked
  // site, network error) the <img> hides and the schematic block underneath
  // remains visible — so previews always have something legible.
  const _shotCache = new Set();
  function Screenshot({ url, dark }) {
    const t = tokens(dark);
    const [state, setState] = useState(_shotCache.has(url) ? 'ok' : 'load');
    const src = `https://image.thum.io/get/width/600/crop/420/maxAge/72/noanimate/${url}`;
    if (state === 'fail') return null;
    return (
      <img src={src} alt="" loading="lazy"
        onLoad={() => { _shotCache.add(url); setState('ok'); }}
        onError={() => setState('fail')}
        style={{
          position:'absolute', inset: 0, width:'100%', height:'100%',
          objectFit:'cover', objectPosition:'top left',
          opacity: state === 'ok' ? (dark ? 0.78 : 0.92) : 0,
          transition:'opacity .4s', pointerEvents:'none',
          filter: dark ? 'brightness(0.85) contrast(0.95)' : 'none',
        }}
      />
    );
  }

  // ─── Inject keyframes once ────────────────────────────────
  function useBureauStyles() {
    useEffect(() => {
      if (document.getElementById('bureau-kf')) return;
      const s = document.createElement('style');
      s.id = 'bureau-kf';
      s.textContent = `
        @keyframes bur-blink { 50% { opacity: 0; } }
        @keyframes bur-stamp { 0% { transform: rotate(-12deg) scale(.5); opacity: 0; }
                               60%{ transform: rotate(-8deg) scale(1.05); opacity: 1; }
                               100%{ transform: rotate(-7deg) scale(1); opacity: 1; } }
        @keyframes bur-ticker { from { transform: translateX(0); } to { transform: translateX(-50%); } }
        @keyframes bur-glow { 0%,100% { opacity: 0.4 } 50% { opacity: 1 } }
        @keyframes bur-slide { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: none; } }
      `;
      document.head.appendChild(s);
    }, []);
  }

  // ─── Boot terminal ────────────────────────────────────────
  function Boot({ done, dark }) {
    const t = tokens(dark);
    const lines = [
      'SLBO·BUREAU OF OPERATIONS — REGISTRY CONSOLE',
      'CONNECTING ······································ OK',
      'AUTH ············································· ANONYMOUS · PUBLIC',
      'LOADING FASCICLE INDEX ···························· OK',
      'VERIFYING CHAIN HEADS · base solana avax ··········· OK',
      'INDEXING ENTRIES ·································· 60/60',
      'ATTESTING FILING ·································· EXAMINER #047',
      'OPENING PUBLIC REGISTRY ···························',
    ];
    const [n, setN] = useState(0);
    useEffect(() => {
      if (n >= lines.length) { const id = setTimeout(done, 460); return () => clearTimeout(id); }
      const id = setTimeout(() => setN(n + 1), n === 0 ? 280 : 110 + Math.random() * 70);
      return () => clearTimeout(id);
    }, [n]);
    return (
      <div style={{
        position:'absolute', inset:0, background: t.bg, zIndex: 80,
        display:'flex', flexDirection:'column', justifyContent:'center', padding: '0 60px',
        opacity: n >= lines.length ? 0 : 1, transition:'opacity .42s', pointerEvents: n >= lines.length ? 'none' : 'auto',
        fontFamily: FONTS.mono,
      }}>
        <div style={{ maxWidth: 760, color: t.fg, fontSize: 13, lineHeight: 1.8, letterSpacing:'0.02em' }}>
          <div style={{ color: t.fgSoft, fontSize: 9, letterSpacing:'0.28em', marginBottom: 18 }}>FORM SLBO-00 · BOOT</div>
          {lines.slice(0, n).map((l, i) => (
            <div key={i} style={{ display:'flex', gap: 16 }}>
              <span style={{ color: t.fgSoft, width: 22, textAlign:'right' }}>{String(i+1).padStart(2,'0')}</span>
              <span>{l}</span>
            </div>
          ))}
          {n < lines.length && (
            <div style={{ display:'flex', gap: 16, color: t.accent }}>
              <span style={{ color: t.fgSoft, width: 22, textAlign:'right' }}>{String(n+1).padStart(2,'0')}</span>
              <span style={{ animation: 'bur-blink 1s steps(1) infinite' }}>▌</span>
            </div>
          )}
        </div>
      </div>
    );
  }

  // ─── Revenue Stamp (CSS art only — no figurative SVG) ─────
  function RevenueStamp({ dark, formNum }) {
    const t = tokens(dark);
    return (
      <div style={{
        position:'relative', width: 178, height: 178, animation: 'bur-stamp 1.4s cubic-bezier(.4,1.6,.5,1) .8s both',
        color: t.seal,
      }}>
        {/* double border */}
        <div style={{ position:'absolute', inset:0, border: `3px solid ${t.seal}`, borderRadius: 4 }} />
        <div style={{ position:'absolute', inset:8, border: `1px solid ${t.seal}`, borderRadius: 2 }} />
        {/* corner notches */}
        {[[2,2],[2,'auto'],['auto',2],['auto','auto']].map((p, i) => (
          <div key={i} style={{
            position:'absolute',
            top: typeof p[0] === 'number' ? p[0] : 'auto',
            bottom: p[0] === 'auto' ? 2 : 'auto',
            left: typeof p[1] === 'number' ? p[1] : 'auto',
            right: p[1] === 'auto' ? 2 : 'auto',
            width: 14, height: 14, borderTop: i < 2 ? `2px solid ${t.seal}` : 'none', borderBottom: i >= 2 ? `2px solid ${t.seal}` : 'none',
            borderLeft: (i === 0 || i === 2) ? `2px solid ${t.seal}` : 'none', borderRight: (i === 1 || i === 3) ? `2px solid ${t.seal}` : 'none',
          }} />
        ))}
        <div style={{
          position:'absolute', inset:14, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center',
          textAlign:'center', fontFamily: FONTS.mono,
        }}>
          <div style={{ fontSize: 9, letterSpacing:'0.32em', opacity: 0.88, marginBottom: 6 }}>SUEDE LABS</div>
          <div style={{ fontFamily: FONTS.serif, fontSize: 38, lineHeight: 1, fontStyle:'italic', letterSpacing:'-0.02em' }}>{formNum}</div>
          <div style={{ fontSize: 8, letterSpacing:'0.26em', opacity: 0.7, marginTop: 6 }}>BUREAU OF OPERATIONS</div>
          <div style={{ fontSize: 8, letterSpacing:'0.26em', opacity: 0.7, marginTop: 4 }}>FILED · UNRESTRICTED</div>
        </div>
        {/* dashed perforation ring */}
        <div style={{ position:'absolute', inset:-6, border: `2px dashed ${t.sealSoft}`, borderRadius: 6 }} />
      </div>
    );
  }

  // ─── Hover popover preview ────────────────────────────────
  function Preview({ item, position, dark }) {
    const t = tokens(dark);
    if (!item) return null;
    return (
      <div style={{
        position:'fixed',
        left: Math.min(position.x + 18, window.innerWidth - 360),
        top: Math.min(position.y + 12, window.innerHeight - 280),
        width: 320, background: t.bgPaper, border: `1px solid ${t.rule}`, padding: '14px 16px 16px', zIndex: 30,
        fontFamily: FONTS.mono, color: t.fg, pointerEvents:'none',
        boxShadow: dark ? '0 12px 40px rgba(0,0,0,0.6)' : '0 12px 40px rgba(0,0,0,0.18)',
      }}>
        <div style={{ display:'flex', justifyContent:'space-between', fontSize: 9, letterSpacing:'0.22em', color: t.fgSoft, borderBottom: `1px solid ${t.ruleSoft}`, paddingBottom: 8, marginBottom: 10 }}>
          <span>FORM {formNo(item.secIdx, item.itemIdx)}</span>
          <span style={{ color: statusFor(item.url) === 'LIVE' ? t.accent : t.fgSoft }}>● {statusFor(item.url)}</span>
        </div>
        <div style={{ fontFamily: FONTS.serif, fontSize: 22, fontStyle:'italic', lineHeight: 1.1, marginBottom: 6, color: t.fg }}>
          {item.label}
        </div>
        <div style={{ fontFamily: FONTS.serif, fontSize: 13, color: t.fgSoft, fontStyle:'italic', lineHeight: 1.45, marginBottom: 12 }}>
          {item.desc}
        </div>
        <div style={{
          height: 84, position:'relative', overflow:'hidden',
          background: dark ? '#100f0d' : '#fbf8ef', border: `1px solid ${t.ruleSoft}`, marginBottom: 10,
          backgroundImage: `linear-gradient(${t.ruleSoft} 1px, transparent 1px), linear-gradient(90deg, ${t.ruleSoft} 1px, transparent 1px)`,
          backgroundSize: '16px 16px',
        }}>
          <Screenshot url={item.url} dark={dark} />
          <div style={{ position:'absolute', top: 8, left: 10, fontSize: 8, letterSpacing:'0.2em', color: t.fgSoft, mixBlendMode: dark ? 'normal' : 'difference' }}>{hostOf(item.url)}</div>
          <div style={{ position:'absolute', top: 28, left: 10, right: 10, height: 4, background: t.rule, opacity: .55 }} />
          <div style={{ position:'absolute', top: 38, left: 10, right: 60, height: 4, background: t.rule, opacity: .4 }} />
          <div style={{ position:'absolute', top: 48, left: 10, right: 100, height: 4, background: t.rule, opacity: .3 }} />
          <div style={{ position:'absolute', bottom: 8, left: 10, fontSize: 8, color: t.accent, letterSpacing:'0.2em' }}>{classFor(hostOf(item.url))}</div>
        </div>
        <div style={{ display:'flex', justifyContent:'space-between', fontSize: 9, letterSpacing:'0.16em', color: t.fgSoft }}>
          <span>EXAMINED {examDate(item.url)}</span>
          <span>↳ click to open form</span>
        </div>
      </div>
    );
  }

  // ─── Expanded inline FORM card (click row) ────────────────
  function FormDetail({ item, secIdx, itemIdx, section, dark, onClose }) {
    const t = tokens(dark);
    const host = hostOf(item.url);
    const related = section.items.filter((x) => x.url !== item.url).slice(0, 4);
    return (
      <div style={{
        background: t.bgPaper, borderTop: `1px solid ${t.accentDim}`, borderBottom: `1px solid ${t.accentDim}`,
        padding: '22px 24px 26px', position:'relative', fontFamily: FONTS.mono,
        animation: 'bur-slide .22s ease',
      }}>
        {/* paper guides */}
        <div style={{ position:'absolute', top: 0, bottom: 0, left: 60, width: 1, background: t.ruleSoft }} />
        <div style={{ position:'absolute', top: 0, bottom: 0, left: 152, width: 1, background: t.ruleSoft }} />

        <div data-bureau-form style={{ display:'grid', gridTemplateColumns:'60px 92px 1fr 220px', gap: 14, alignItems:'flex-start' }}>
          <div style={{ fontSize: 9, letterSpacing:'0.22em', color: t.fgSoft, paddingTop: 6 }}>↳ FORM</div>
          <div style={{ fontSize: 11, letterSpacing:'0.18em', color: t.accent, paddingTop: 6 }}>{formNo(secIdx, itemIdx)}</div>
          <div>
            <div style={{ fontFamily: FONTS.serif, fontSize: 36, fontStyle:'italic', lineHeight: 1.02, letterSpacing:'-0.015em', color: t.fg }}>
              {item.label}
            </div>
            <div style={{ fontFamily: FONTS.serif, fontStyle:'italic', fontSize: 16, color: t.fgSoft, marginTop: 6, lineHeight: 1.45, maxWidth: 720 }}>
              {item.desc}
            </div>
            {/* attestation row */}
            <div style={{
              marginTop: 18, display:'grid', gridTemplateColumns:'repeat(4, auto)', gap: 26,
              fontSize: 10, letterSpacing:'0.16em', color: t.fgSoft,
            }}>
              <div>
                <div style={{ fontSize: 9, color: t.fgMute, marginBottom: 4 }}>CLASS</div>
                <div style={{ color: t.fg }}>{classFor(host)}</div>
              </div>
              <div>
                <div style={{ fontSize: 9, color: t.fgMute, marginBottom: 4 }}>STATE</div>
                <div style={{ color: statusFor(item.url) === 'LIVE' ? t.accent : t.fg }}>● {statusFor(item.url)}</div>
              </div>
              <div>
                <div style={{ fontSize: 9, color: t.fgMute, marginBottom: 4 }}>EXAMINED</div>
                <div style={{ color: t.fg }}>{examDate(item.url)}</div>
              </div>
              <div>
                <div style={{ fontSize: 9, color: t.fgMute, marginBottom: 4 }}>EXAMINER</div>
                <div style={{ color: t.fg }}>#047 · BUREAU</div>
              </div>
            </div>
            {/* endpoint */}
            <a href={item.url} target="_blank" rel="noreferrer" style={{
              display:'inline-flex', alignItems:'center', gap: 12, marginTop: 22,
              padding: '11px 16px', background: t.accent, color: dark ? '#1a1610' : '#fbf8f0',
              fontFamily: FONTS.mono, fontSize: 11, letterSpacing:'0.18em', textDecoration:'none', borderRadius: 2,
            }}>
              OPEN ENDPOINT ↗ <span style={{ opacity: 0.8 }}>{item.url.replace(/^https?:\/\//,'')}</span>
            </a>
            {/* related */}
            <div style={{ marginTop: 22, paddingTop: 14, borderTop: `1px solid ${t.ruleSoft}` }}>
              <div style={{ fontSize: 9, letterSpacing:'0.24em', color: t.fgSoft, marginBottom: 10 }}>RELATED · {section.title.toUpperCase()}</div>
              <div style={{ display:'flex', flexWrap:'wrap', gap: 8 }}>
                {related.map((r) => (
                  <a key={r.url} href={r.url} target="_blank" rel="noreferrer" style={{
                    fontFamily: FONTS.serif, fontSize: 14, fontStyle:'italic', color: t.fg,
                    border: `1px solid ${t.ruleSoft}`, padding:'5px 12px', textDecoration:'none', borderRadius: 2,
                  }}>{r.label}</a>
                ))}
              </div>
            </div>
          </div>
          {/* right rail — schematic */}
          <div data-bureau-form-rail style={{ position:'relative' }}>
            <div style={{
              position:'relative', height: 200, border: `1px solid ${t.rule}`, background: t.bg,
              backgroundImage: `linear-gradient(${t.ruleSoft} 1px, transparent 1px), linear-gradient(90deg, ${t.ruleSoft} 1px, transparent 1px)`,
              backgroundSize: '20px 20px', overflow:'hidden',
            }}>
              <Screenshot url={item.url} dark={dark} />
              <div style={{ position:'absolute', top: 10, left: 12, right: 12, display:'flex', justifyContent:'space-between', fontSize: 8, letterSpacing:'0.22em', color: t.fgSoft, mixBlendMode: dark ? 'normal' : 'difference' }}>
                <span>{host}</span><span>SLBO</span>
              </div>
              <div style={{ position:'absolute', left: 12, right: 12, top: 36, fontFamily: FONTS.serif, fontSize: 22, fontStyle:'italic', color: t.fg, lineHeight: 1.05, textShadow: dark ? '0 1px 2px rgba(0,0,0,0.4)' : 'none' }}>{item.label}</div>
              <div style={{ position:'absolute', left: 12, right: 12, top: 86, height: 4, background: t.rule, opacity: .55 }} />
              <div style={{ position:'absolute', left: 12, right: 60, top: 96, height: 4, background: t.rule, opacity: .4 }} />
              <div style={{ position:'absolute', left: 12, right: 100, top: 106, height: 4, background: t.rule, opacity: .3 }} />
              <div style={{ position:'absolute', left: 12, right: 130, top: 116, height: 4, background: t.rule, opacity: .25 }} />
              <div style={{ position:'absolute', bottom: 10, left: 12, right: 12, display:'flex', justifyContent:'space-between', fontSize: 8, letterSpacing:'0.22em', color: t.accent }}>
                <span>{classFor(host)}</span><span>{statusFor(item.url)}</span>
              </div>
            </div>
            <button onClick={onClose} style={{
              position:'absolute', top: -6, right: -6, width: 26, height: 26, background: t.bg,
              border: `1px solid ${t.rule}`, color: t.fg, cursor:'pointer', fontFamily: FONTS.mono, fontSize: 13,
            }}>×</button>
          </div>
        </div>

        {/* signature strip */}
        <div style={{
          marginTop: 24, paddingTop: 16, borderTop: `1px dashed ${t.ruleSoft}`,
          display:'grid', gridTemplateColumns:'1fr auto auto', gap: 24, alignItems:'flex-end',
          fontSize: 9, letterSpacing:'0.2em', color: t.fgSoft,
        }}>
          <div>
            <div style={{ borderTop: `1px solid ${t.rule}`, paddingTop: 6, fontFamily: FONTS.serif, fontStyle:'italic', fontSize: 14, color: t.fg }}>
              ⌒ Johnny Suede
            </div>
            <div style={{ marginTop: 2 }}>SIGNATURE · BUREAU OF OPERATIONS</div>
          </div>
          <div>
            <div style={{ borderTop: `1px solid ${t.rule}`, paddingTop: 6, fontFamily: FONTS.serif, fontStyle:'italic', fontSize: 14, color: t.fg }}>
              {examDate(item.url)}
            </div>
            <div style={{ marginTop: 2 }}>DATE OF ATTESTATION</div>
          </div>
          <div style={{ position:'relative' }}>
            <div style={{
              fontFamily: FONTS.mono, fontSize: 11, letterSpacing:'0.18em', color: t.seal,
              border: `2px solid ${t.seal}`, padding:'8px 14px', transform:'rotate(-7deg)',
              borderRadius: 2, animation: 'bur-stamp .8s cubic-bezier(.4,1.6,.5,1) .1s both',
            }}>EXAMINED ✓</div>
          </div>
        </div>
      </div>
    );
  }

  // ─── Row ──────────────────────────────────────────────────
  function Row({ item, n, secIdx, itemIdx, sectionTitle, section, dark, onHover, expanded, onToggle }) {
    const t = tokens(dark);
    const host = hostOf(item.url);
    const status = statusFor(item.url);
    const cls = classFor(host);
    const [stamped, setStamped] = useState(false);
    return (
      <div style={{ position:'relative' }}>
        <a href={item.url}
          onClick={(e) => { if (!e.metaKey && !e.ctrlKey) { e.preventDefault(); onToggle(); } }}
          onMouseEnter={(e) => { onHover({ ...item, secIdx, itemIdx, sectionTitle }, { x: e.clientX, y: e.clientY }); setStamped(true); }}
          onMouseMove={(e) => onHover({ ...item, secIdx, itemIdx, sectionTitle }, { x: e.clientX, y: e.clientY })}
          onMouseLeave={() => { onHover(null, null); }}
          target="_blank" rel="noreferrer"
          data-bureau-row
          style={{
            display:'grid',
            gridTemplateColumns: '56px 90px 1.5fr 1.2fr 76px 82px 1fr 24px',
            alignItems:'center', gap: 14,
            padding: `${t.density.rowPadY}px 24px`, borderBottom: `1px solid ${t.ruleSoft}`,
            fontFamily: FONTS.mono, fontSize: t.density.rowFs, color: t.fg, textDecoration:'none',
            background: expanded ? t.hi : ((n % 2 === 0) ? 'transparent' : t.row),
            transition:'background .12s',
            position:'relative', cursor:'pointer',
          }}
          onMouseOver={(e) => { e.currentTarget.style.background = t.hi; }}
          onMouseOut={(e) => { e.currentTarget.style.background = expanded ? t.hi : ((n % 2 === 0) ? 'transparent' : t.row); }}
        >
          <span style={{ color: t.fgSoft, letterSpacing:'0.06em' }}>{String(n).padStart(4,'0')}</span>
          <span data-hide-narrow style={{ color: t.fgSoft }}>{formNo(secIdx, itemIdx)}</span>
          <span style={{ color: t.fg, letterSpacing:'0.02em', display:'flex', alignItems:'center', gap: 8 }}>
            <span style={{ fontSize: 10, color: t.fgMute, width: 9 }}>{expanded ? '▾' : '▸'}</span>
            <span style={{ fontFamily: FONTS.serif, fontSize: t.density.titleFs, fontStyle:'italic' }}>{item.label}</span>
          </span>
          <span data-bureau-row-sub style={{ color: t.fgSoft, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap', fontSize: 11 }}>{item.desc}</span>
          <span data-hide-narrow style={{ color: t.fgSoft, fontSize: 10, letterSpacing:'0.16em' }}>{cls}</span>
          <span style={{ fontSize: 10, letterSpacing:'0.16em', color: status === 'LIVE' ? t.accent : t.fgSoft }}>
            <span style={{
              display:'inline-block', width: 6, height: 6, borderRadius: '50%',
              background: status === 'LIVE' ? t.accent : t.fgSoft, marginRight: 6, verticalAlign:'middle',
              animation: status === 'LIVE' ? 'bur-glow 2.4s ease-in-out infinite' : 'none',
            }} />
            {status}
          </span>
          <span data-hide-narrow style={{ color: t.fgSoft, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap', fontSize: 10, letterSpacing:'0.08em' }}>
            {host}
          </span>
          <span data-hide-narrow style={{ color: t.fgSoft, textAlign:'right' }}>↗</span>

          {/* Hand-stamp on hover, fades in once per session per row */}
          {stamped && (
            <div style={{
              position:'absolute', right: 60, top: -6, pointerEvents:'none',
              fontFamily: FONTS.mono, fontSize: 9, letterSpacing:'0.22em', color: t.seal,
              border: `1.5px solid ${t.seal}`, padding: '3px 7px', transform:'rotate(-9deg)',
              opacity: 0, animation: 'bur-stamp .7s cubic-bezier(.4,1.6,.5,1) .05s both',
            }}>
              EXAMINED ✓
            </div>
          )}
        </a>
        {expanded && <FormDetail item={item} secIdx={secIdx} itemIdx={itemIdx} section={section} dark={dark} onClose={onToggle} />}
      </div>
    );
  }

  function SectionBlock({ section, secIdx, query, classFilter, statusFilter, audience, onHover, dark, startIdx, expandedKey, setExpandedKey, registerRef }) {
    const t = tokens(dark);
    const ref = useRef(null);
    useEffect(() => { registerRef(section.id, ref.current); }, []);
    const visible = useMemo(() => {
      return section.items.map((it, i) => ({ it, i })).filter(({ it }) => {
        if (audience && audience !== 'all' && !(it.aud || []).includes(audience)) return false;
        if (query) {
          const q = query.toLowerCase();
          const hit = it.label.toLowerCase().includes(q) ||
            (it.desc||'').toLowerCase().includes(q) ||
            it.url.toLowerCase().includes(q) ||
            section.title.toLowerCase().includes(q);
          if (!hit) return false;
        }
        if (classFilter && classFor(hostOf(it.url)) !== classFilter) return false;
        if (statusFilter && statusFor(it.url) !== statusFilter) return false;
        return true;
      });
    }, [query, classFilter, statusFilter, audience, section]);
    if (visible.length === 0) return null;
    return (
      <div id={`bureau-sec-${section.id}`} ref={ref}>
        <div data-bureau-section-head style={{
          padding: '24px 24px 12px', borderTop: `1px solid ${t.rule}`,
          display:'grid', gridTemplateColumns: '56px 90px 1fr auto', gap: 14, alignItems:'baseline',
          background: t.bgDeep, position:'relative',
        }}>
          <span style={{ fontFamily: FONTS.mono, fontSize: 10, letterSpacing:'0.22em', color: t.fgSoft }}>{section.latin.toUpperCase().replace('.','')}</span>
          <span data-hide-narrow style={{ fontFamily: FONTS.mono, fontSize: 10, letterSpacing:'0.22em', color: t.fgSoft }}>{String(secIdx+1).padStart(2,'0')}.00</span>
          <span>
            <span style={{ fontFamily: FONTS.serif, fontSize: 28, fontStyle:'italic', color: t.fg, letterSpacing:'-0.005em' }}>{section.title}</span>
            <span data-hide-narrow style={{ fontFamily: FONTS.mono, fontSize: 11, letterSpacing:'0.14em', color: t.fgSoft, marginLeft: 16 }}>· {section.sub.toUpperCase()}</span>
          </span>
          <span data-hide-narrow style={{ fontFamily: FONTS.mono, fontSize: 10, letterSpacing:'0.16em', color: t.fgSoft }}>
            {visible.length} / {section.items.length} ENTRIES · p. {String(startIdx+1).padStart(2,'0')}
          </span>
        </div>
        {visible.map(({ it, i }, k) => {
          const key = section.id + '/' + i;
          return (
            <Row key={key} item={it} n={startIdx + k + 1} secIdx={secIdx} itemIdx={i}
              sectionTitle={section.title} section={section} dark={dark} onHover={onHover}
              expanded={expandedKey === key} onToggle={() => setExpandedKey(expandedKey === key ? null : key)} />
          );
        })}
      </div>
    );
  }

  // ─── Sticky left rail (fascicle TOC) ──────────────────────
  function LeftRail({ data, dark, sectionRefs, query, classFilter, statusFilter }) {
    const t = tokens(dark);
    const [active, setActive] = useState(data.sections[0].id);
    useEffect(() => {
      const onScroll = () => {
        const scrollEl = document.querySelector('[data-bureau-scroll]');
        const baseTop = scrollEl ? scrollEl.getBoundingClientRect().top : 0;
        let cur = data.sections[0].id;
        for (const s of data.sections) {
          const el = sectionRefs.current[s.id];
          if (!el) continue;
          const top = el.getBoundingClientRect().top - baseTop;
          if (top < 160) cur = s.id;
        }
        setActive(cur);
      };
      const scrollEl = document.querySelector('[data-bureau-scroll]');
      (scrollEl || window).addEventListener('scroll', onScroll, { passive: true });
      onScroll();
      return () => (scrollEl || window).removeEventListener('scroll', onScroll);
    }, []);

    return (
      <aside style={{
        position:'sticky', top: 122, alignSelf:'flex-start', width: 220,
        padding: '20px 16px 20px 24px', borderRight: `1px solid ${t.rule}`,
        fontFamily: FONTS.mono, fontSize: 10.5, color: t.fgSoft, height:'fit-content',
      }}>
        <div style={{ fontSize: 9, letterSpacing:'0.28em', color: t.fgMute, marginBottom: 14 }}>
          TABLE OF FASCICLES
        </div>
        <ol style={{ listStyle:'none', padding:0, margin:0, display:'flex', flexDirection:'column', gap: 2 }}>
          {data.sections.map((s, i) => {
            const isActive = active === s.id;
            return (
              <li key={s.id}>
                <a href={`#bureau-sec-${s.id}`}
                  onClick={(e) => {
                    e.preventDefault();
                    const el = sectionRefs.current[s.id];
                    const scrollEl = document.querySelector('[data-bureau-scroll]');
                    if (el && scrollEl) {
                      scrollEl.scrollTo({ top: el.offsetTop - 110, behavior: 'smooth' });
                    }
                  }}
                  style={{
                    display:'grid', gridTemplateColumns: '32px 1fr auto', alignItems:'baseline', gap: 8,
                    padding: '7px 8px', textDecoration:'none', color: isActive ? t.fg : t.fgSoft,
                    background: isActive ? t.hi : 'transparent', borderLeft: `2px solid ${isActive ? t.accent : 'transparent'}`,
                    letterSpacing:'0.04em', transition:'all .14s',
                  }}>
                  <span style={{ color: isActive ? t.accent : t.fgMute }}>{String(i+1).padStart(2,'0')}.</span>
                  <span style={{ fontFamily: FONTS.serif, fontSize: 14, fontStyle: isActive ? 'italic' : 'normal' }}>{s.title}</span>
                  <span style={{ color: t.fgMute, fontSize: 9 }}>{s.items.length}</span>
                </a>
              </li>
            );
          })}
        </ol>
        <div style={{ marginTop: 22, paddingTop: 16, borderTop: `1px solid ${t.ruleSoft}`, fontSize: 9, letterSpacing:'0.2em', color: t.fgMute, lineHeight: 1.7 }}>
          <div>SET IN</div>
          <div style={{ fontFamily: FONTS.serif, fontStyle:'italic', fontSize: 13, color: t.fg, letterSpacing:'normal' }}>Cormorant Garamond</div>
          <div style={{ marginTop: 10 }}>EXAMINER</div>
          <div style={{ fontFamily: FONTS.serif, fontStyle:'italic', fontSize: 13, color: t.fg, letterSpacing:'normal' }}>#047, Bureau of Operations</div>
          <div style={{ marginTop: 10 }}>CHAINS</div>
          <div style={{ color: t.fg, letterSpacing:'0.15em' }}>BASE · SOL · AVAX</div>
        </div>
      </aside>
    );
  }

  // ─── Ticker ───────────────────────────────────────────────
  function Ticker({ data, dark }) {
    const t = tokens(dark);
    const items = useMemo(() => {
      const list = [];
      data.sections.forEach((s, si) => s.items.forEach((it, ii) => {
        list.push(`ATTESTED · ${formNo(si, ii)} · ${it.label} · ${examDate(it.url)}`);
      }));
      // Light shuffle by hash so first items aren't always identical
      return list.slice(0, 24);
    }, [data]);
    const line = items.join('   ·   ');
    return (
      <div style={{
        borderBottom: `1px solid ${t.rule}`, background: t.bgDeep, overflow:'hidden',
        fontFamily: FONTS.mono, fontSize: 10, letterSpacing:'0.18em', color: t.fgSoft, padding: '6px 0',
        display:'flex', alignItems:'center',
      }}>
        <span style={{ flex:'0 0 auto', padding:'0 14px', color: t.accent, borderRight: `1px solid ${t.rule}`, marginRight: 12 }}>NEWS WIRE</span>
        <div style={{ flex:1, overflow:'hidden', position:'relative' }}>
          <div style={{
            display:'inline-block', whiteSpace:'nowrap', animation: 'bur-ticker 90s linear infinite',
          }}>
            <span>{line}</span><span style={{ marginLeft: 28 }}>{line}</span>
          </div>
        </div>
      </div>
    );
  }

  // ─── Command palette (⌘K) ─────────────────────────────────
  function Palette({ open, onClose, data, dark, onJump }) {
    const t = tokens(dark);
    const [q, setQ] = useState('');
    const [idx, setIdx] = useState(0);
    const inputRef = useRef(null);
    useEffect(() => { if (open) { setQ(''); setIdx(0); setTimeout(() => inputRef.current?.focus(), 0); } }, [open]);
    const results = useMemo(() => {
      const all = [];
      data.sections.forEach((s, si) => s.items.forEach((it, ii) => all.push({ ...it, secIdx: si, itemIdx: ii, sectionTitle: s.title, sectionId: s.id })));
      if (!q) return all.slice(0, 14);
      const ql = q.toLowerCase();
      return all.filter(x =>
        x.label.toLowerCase().includes(ql) ||
        (x.desc||'').toLowerCase().includes(ql) ||
        x.sectionTitle.toLowerCase().includes(ql) ||
        x.url.toLowerCase().includes(ql)
      ).slice(0, 14);
    }, [q, data]);
    if (!open) return null;
    return (
      <div onClick={onClose} style={{
        position:'fixed', inset:0, background:'rgba(0,0,0,0.45)', zIndex: 100,
        display:'flex', alignItems:'flex-start', justifyContent:'center', paddingTop: 110,
      }}>
        <div onClick={(e) => e.stopPropagation()} style={{
          width: 560, background: t.bgPaper, border: `1px solid ${t.rule}`,
          fontFamily: FONTS.mono, color: t.fg, boxShadow: '0 20px 60px rgba(0,0,0,0.5)',
        }}>
          <div style={{ display:'flex', alignItems:'center', padding:'12px 16px', borderBottom: `1px solid ${t.ruleSoft}` }}>
            <span style={{ fontSize: 10, letterSpacing:'0.22em', color: t.accent, marginRight: 12 }}>⌘K</span>
            <input ref={inputRef} value={q} onChange={(e) => { setQ(e.target.value); setIdx(0); }}
              onKeyDown={(e) => {
                if (e.key === 'ArrowDown') { e.preventDefault(); setIdx((idx + 1) % Math.max(1, results.length)); }
                if (e.key === 'ArrowUp') { e.preventDefault(); setIdx((idx - 1 + results.length) % Math.max(1, results.length)); }
                if (e.key === 'Enter' && results[idx]) {
                  if (e.shiftKey) onJump(results[idx]);
                  else window.open(results[idx].url, '_blank');
                  onClose();
                }
                if (e.key === 'Escape') onClose();
              }}
              placeholder="Search registry · ↵ open  ⇧↵ jump  esc close"
              style={{ flex:1, background:'transparent', border:0, outline:'none', color: t.fg, fontSize: 14, fontFamily: FONTS.serif, fontStyle:'italic' }} />
            <span style={{ fontSize: 10, color: t.fgSoft, letterSpacing:'0.14em' }}>{results.length}</span>
          </div>
          <div style={{ maxHeight: 380, overflow:'auto' }}>
            {results.map((r, i) => (
              <div key={r.url}
                onMouseEnter={() => setIdx(i)}
                onClick={() => { window.open(r.url, '_blank'); onClose(); }}
                style={{
                  display:'grid', gridTemplateColumns:'80px 1fr auto', gap: 12, alignItems:'baseline',
                  padding:'10px 16px', cursor:'pointer',
                  background: i === idx ? t.hi : 'transparent', borderBottom: `1px solid ${t.ruleSoft}`,
                }}>
                <span style={{ fontSize: 10, letterSpacing:'0.16em', color: t.fgSoft }}>{formNo(r.secIdx, r.itemIdx)}</span>
                <span>
                  <span style={{ fontFamily: FONTS.serif, fontSize: 16, fontStyle:'italic', color: t.fg }}>{r.label}</span>
                  <span style={{ fontSize: 10, letterSpacing:'0.16em', color: t.fgSoft, marginLeft: 10 }}>· {r.sectionTitle.toUpperCase()}</span>
                </span>
                <span style={{ fontSize: 10, color: t.fgMute, letterSpacing:'0.1em' }}>↗</span>
              </div>
            ))}
            {results.length === 0 && (
              <div style={{ padding: 24, color: t.fgSoft, fontStyle:'italic', fontFamily: FONTS.serif }}>No entries match “{q}”.</div>
            )}
          </div>
          <div style={{ display:'flex', justifyContent:'space-between', padding:'8px 16px', borderTop: `1px solid ${t.ruleSoft}`, fontSize: 9, letterSpacing:'0.18em', color: t.fgSoft }}>
            <span>BUREAU OF OPERATIONS · COMMAND PALETTE</span>
            <span>↑↓ NAVIGATE</span>
          </div>
        </div>
      </div>
    );
  }

  function SuedeBureau({ dark = true, onToggleDark, tweaks, setTweak }) {
    useBureauStyles();
    // Sync tweak state into module so tokens() picks it up on this render.
    if (tweaks) _tweaks = { ..._tweaks, ...tweaks };

    const [query, setQuery] = useState('');
    const [classFilter, setClassFilter] = useState('');
    const [statusFilter, setStatusFilter] = useState('');
    const [audience, setAudience] = useState((tweaks && tweaks.audience) || 'all');
    const [booted, setBooted] = useState(false);
    const [preview, setPreview] = useState({ item: null, pos: { x: 0, y: 0 } });
    const [expandedKey, setExpandedKey] = useState(null);
    const [paletteOpen, setPaletteOpen] = useState(false);
    const sectionRefs = useRef({});
    const registerRef = (id, el) => { sectionRefs.current[id] = el; };
    const onHover = (item, pos) => setPreview({ item, pos: pos || preview.pos });
    const t = tokens(dark);
    const data = window.SUEDE_DATA;

    // Sync audience tweak -> local audience filter state (so tweaks panel changes apply)
    useEffect(() => { if (tweaks && tweaks.audience && tweaks.audience !== audience) setAudience(tweaks.audience); }, [tweaks && tweaks.audience]);

    // Inject mobile CSS once. Hides the left rail, stacks hero columns, drops
    // CLASS / STATE / ENDPOINT columns on the narrow registry table.
    useEffect(() => {
      if (document.getElementById('bureau-mobile')) return;
      const s = document.createElement('style');
      s.id = 'bureau-mobile';
      s.textContent = `
        @media (max-width: 960px) {
          [data-bureau-scroll] [data-bureau-rail] { display: none !important; }
          [data-bureau-scroll] [data-bureau-body] { grid-template-columns: 1fr !important; }
          [data-bureau-scroll] [data-bureau-hero] { grid-template-columns: 1fr !important; }
          [data-bureau-scroll] [data-bureau-hero-stamp] { display: none !important; }
          [data-bureau-scroll] [data-bureau-topbar] { grid-template-columns: 1fr !important; gap: 10px !important; }
          [data-bureau-scroll] [data-bureau-topbar] > * { justify-content: flex-start !important; }
          [data-bureau-scroll] h1 { font-size: 54px !important; }
          [data-bureau-scroll] [data-bureau-headline-h2] { font-size: 36px !important; }
        }
        @media (max-width: 720px) {
          [data-bureau-scroll] [data-bureau-row] { grid-template-columns: 44px 1.5fr 70px !important; }
          [data-bureau-scroll] [data-bureau-row-sub] { display: none !important; }
          [data-bureau-scroll] [data-bureau-table-head] { grid-template-columns: 44px 1.5fr 70px !important; }
          [data-bureau-scroll] [data-bureau-table-head] > [data-hide-narrow] { display: none !important; }
          [data-bureau-scroll] [data-bureau-section-head] { grid-template-columns: 44px 1fr !important; }
          [data-bureau-scroll] [data-bureau-section-head] > [data-hide-narrow] { display: none !important; }
          [data-bureau-scroll] [data-bureau-metrics] { grid-template-columns: repeat(3, 1fr) !important; }
          [data-bureau-scroll] [data-bureau-form] { grid-template-columns: 1fr !important; }
          [data-bureau-scroll] [data-bureau-form-rail] { display: none !important; }
          [data-bureau-scroll] [data-bureau-founder] { grid-template-columns: 1fr !important; }
          [data-bureau-scroll] [data-bureau-manifesto] { grid-template-columns: 1fr !important; }
          [data-bureau-scroll] [data-bureau-manifesto-body] { grid-template-columns: 1fr !important; }
        }
      `;
      document.head.appendChild(s);
    }, []);

    // ⌘K
    useEffect(() => {
      const handler = (e) => {
        if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
          e.preventDefault(); setPaletteOpen(o => !o);
        }
        if (e.key === 'Escape') { setPaletteOpen(false); setExpandedKey(null); }
      };
      window.addEventListener('keydown', handler);
      return () => window.removeEventListener('keydown', handler);
    }, []);

    const totalCount = data.sections.reduce((a, s) => a + s.items.length, 0);
    const CLASSES = ['', 'CONSOLE','NODE','PUBLIC','PAPER','EXT'];
    const STATS = ['', 'LIVE','BETA','SCHED'];

    let runningIdx = 0;

    const jumpTo = (r) => {
      const el = sectionRefs.current[r.sectionId];
      const scrollEl = document.querySelector('[data-bureau-scroll]');
      if (el && scrollEl) scrollEl.scrollTo({ top: el.offsetTop - 110, behavior:'smooth' });
      setExpandedKey(r.sectionId + '/' + r.itemIdx);
    };

    return (
      <div data-bureau-scroll style={{
        position:'relative', width:'100%', height:'100%', overflow:'auto',
        background: t.bg, color: t.fg, fontFamily: FONTS.mono,
      }}>
        {!booted && <Boot dark={dark} done={() => setBooted(true)} />}

        {/* Ticker */}
        {_tweaks.showTicker !== false && <Ticker data={data} dark={dark} />}

        {/* Topbar */}
        <div style={{ position:'sticky', top: 0, zIndex: 20, background: t.bg, borderBottom: `1px solid ${t.rule}` }}>
          <div data-bureau-topbar style={{ display:'grid', gridTemplateColumns: 'auto 1fr auto', alignItems:'center', gap: 24, padding: '12px 24px' }}>
            <a href="https://suedeai.ai" target="_blank" rel="noreferrer" style={{ display:'flex', alignItems:'center', gap: 14, textDecoration:'none', color:'inherit' }}>
              <img src="assets/suede-mark.jpeg" alt="Suede Labs" style={{ width: 28, height: 28, objectFit:'cover', borderRadius: 2, filter: dark ? 'none' : 'invert(1) hue-rotate(180deg) contrast(1.05)' }} />
              <div>
                <div style={{ fontSize: 10, letterSpacing:'0.24em', color: t.fgSoft }}>SLBO · BUREAU OF OPERATIONS</div>
                <div style={{ fontFamily: FONTS.serif, fontSize: 17, fontStyle:'italic', color: t.fg, lineHeight: 1.1 }}>
                  Suede Labs <span style={{ color: t.fgSoft }}>—</span> Public Registry of Surfaces
                </div>
              </div>
            </a>
            <div style={{ display:'flex', gap: 10, alignItems:'center', justifyContent:'center' }}>
              <div style={{ display:'flex', alignItems:'center', border: `1px solid ${t.rule}`, padding:'6px 10px', minWidth: 360 }}>
                <span style={{ fontSize: 10, letterSpacing:'0.2em', color: t.fgSoft, marginRight: 10 }}>QUERY ▸</span>
                <input value={query} onChange={(e)=>setQuery(e.target.value)} placeholder="label / description / url"
                  style={{ flex:1, background:'transparent', border:0, outline:'none', color: t.fg, fontFamily: FONTS.mono, fontSize: 12 }} />
                <button onClick={() => setPaletteOpen(true)} style={{
                  background:'transparent', border:`1px solid ${t.ruleSoft}`, color: t.fgSoft, fontSize: 9,
                  padding:'3px 6px', letterSpacing:'0.18em', cursor:'pointer', fontFamily: FONTS.mono,
                }}>⌘K</button>
              </div>
            </div>
            <div style={{ display:'flex', gap: 8 }}>
              <select value={classFilter} onChange={(e) => setClassFilter(e.target.value)} style={{
                background: t.bgDeep, color: t.fg, border:`1px solid ${t.rule}`, padding:'7px 10px', fontFamily: FONTS.mono, fontSize: 10, letterSpacing:'0.16em',
              }}>
                {CLASSES.map(c => <option key={c} value={c}>{c ? 'CLASS · ' + c : 'CLASS · ALL'}</option>)}
              </select>
              <select value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)} style={{
                background: t.bgDeep, color: t.fg, border:`1px solid ${t.rule}`, padding:'7px 10px', fontFamily: FONTS.mono, fontSize: 10, letterSpacing:'0.16em',
              }}>
                {STATS.map(s => <option key={s} value={s}>{s ? 'STATE · ' + s : 'STATE · ALL'}</option>)}
              </select>
              <button onClick={onToggleDark} style={{
                background: t.bgDeep, color: t.fg, border:`1px solid ${t.rule}`, padding:'7px 12px',
                fontFamily: FONTS.mono, fontSize: 10, letterSpacing:'0.18em', cursor:'pointer',
              }}>
                {dark ? '☼ DAY' : '☾ NIGHT'}
              </button>
            </div>
          </div>
          {/* table header row */}
          <div data-bureau-table-head style={{
            display:'grid', gridTemplateColumns: '56px 90px 1.5fr 1.2fr 76px 82px 1fr 24px', gap: 14,
            padding: '8px 24px', borderTop: `1px solid ${t.rule}`, background: t.bgDeep,
            fontSize: 9, letterSpacing:'0.22em', color: t.fgSoft,
          }}>
            <span>NO.</span><span data-hide-narrow>FORM</span><span>ENTRY</span><span data-hide-narrow>SYNOPSIS</span><span data-hide-narrow>CLASS</span><span>STATE</span><span data-hide-narrow>ENDPOINT</span><span></span>
          </div>
        </div>

        {/* Audience filter pills */}
        <window.BureauContent.AudiencePills t={t} value={audience}
          onChange={(v) => { setAudience(v); setTweak && setTweak({ audience: v }); }} />

        {/* Hero / front matter */}
        <header data-bureau-front style={{ padding: '48px 24px 40px', borderBottom: `1px solid ${t.rule}`, position:'relative' }}>
          <div data-bureau-hero style={{ display:'grid', gridTemplateColumns: '1.4fr 220px', gap: 48, alignItems:'flex-start' }}>
            <div>
              <div style={{ fontSize: 10, letterSpacing:'0.26em', color: t.fgSoft, marginBottom: 22 }}>
                FORM SLBO-00 · PUBLIC FILING · UNRESTRICTED · ISSUE I · MMXXVI
              </div>
              <h1 style={{ fontFamily: FONTS.serif, fontSize: 86, lineHeight: 0.95, margin: 0, letterSpacing:'-0.02em', color: t.fg, fontWeight: 400 }}>
                <span style={{ fontStyle:'italic' }}>Registry</span>
                <span style={{ color: t.fgSoft }}> of </span>
                Operating
                <br />
                Surfaces.
              </h1>
              <div style={{ fontFamily: FONTS.serif, fontSize: 17, fontStyle:'italic', color: t.fgSoft, marginTop: 22, maxWidth: 620, lineHeight: 1.5 }}>
                A canonical, machine-readable index of every console, registry, agent, and editorial
                surface operated under the auspices of Suede Labs. Each entry is filed by form number,
                examined, and bears a current state attestation.
              </div>

              {/* Metrics row */}
              <div data-bureau-metrics style={{ display:'grid', gridTemplateColumns:'repeat(6, 1fr)', gap: 0, border: `1px solid ${t.rule}`, fontSize: 11, marginTop: 28, maxWidth: 720 }}>
                {[
                  ['FASCICLES', data.sections.length],
                  ['ENTRIES', totalCount],
                  ['CHAINS', '3'],
                  ['ATTESTED', new Date().toISOString().slice(0,10)],
                  ['EXAMINER', '#047'],
                  ['LICENSE', 'PUBLIC'],
                ].map(([k,v], i) => (
                  <div key={k} style={{
                    padding: '12px 14px',
                    borderRight: i < 5 ? `1px solid ${t.ruleSoft}` : 'none',
                  }}>
                    <div style={{ fontSize: 8, letterSpacing:'0.22em', color: t.fgSoft }}>{k}</div>
                    <div style={{ fontFamily: FONTS.serif, fontSize: 18, fontStyle:'italic', color: t.fg, marginTop: 2, letterSpacing:'-0.005em' }}>{v}</div>
                  </div>
                ))}
              </div>

              {/* Examiner signature line */}
              <div style={{ display:'flex', gap: 36, marginTop: 30, alignItems:'flex-end' }}>
                <div style={{ minWidth: 220 }}>
                  <div style={{ borderTop: `1px solid ${t.rule}`, paddingTop: 6, fontFamily: FONTS.serif, fontStyle:'italic', fontSize: 17, color: t.fg }}>
                    ⌒ Johnny Suede
                  </div>
                  <div style={{ fontSize: 9, letterSpacing:'0.2em', color: t.fgSoft, marginTop: 2 }}>FILING SIGNATURE · BUREAU CHAIR</div>
                </div>
                <div style={{ minWidth: 160 }}>
                  <div style={{ borderTop: `1px solid ${t.rule}`, paddingTop: 6, fontFamily: FONTS.serif, fontStyle:'italic', fontSize: 17, color: t.fg }}>
                    Examiner #047
                  </div>
                  <div style={{ fontSize: 9, letterSpacing:'0.2em', color: t.fgSoft, marginTop: 2 }}>ATTESTING EXAMINER</div>
                </div>
                <div style={{ minWidth: 130 }}>
                  <div style={{ borderTop: `1px solid ${t.rule}`, paddingTop: 6, fontFamily: FONTS.serif, fontStyle:'italic', fontSize: 17, color: t.fg }}>
                    {new Date().toISOString().slice(0,10)}
                  </div>
                  <div style={{ fontSize: 9, letterSpacing:'0.2em', color: t.fgSoft, marginTop: 2 }}>DATE OF FILING</div>
                </div>
              </div>
            </div>

            <div data-bureau-hero-stamp style={{ display:'flex', justifyContent:'center', paddingTop: 12 }}>
              <RevenueStamp dark={dark} formNum="SLBO-00" />
            </div>
          </div>
        </header>

        {/* Sister content — manifesto excerpt + founder rail + dispatches */}
        <window.BureauContent.Manifesto t={t} useSerif={_tweaks.displaySerif !== false} />
        <window.BureauContent.Founder t={t} />
        <window.BureauContent.Dispatches t={t} />

        {/* Body: rail + table */}
        <div data-bureau-body style={{ display:'grid', gridTemplateColumns:'220px 1fr', alignItems:'flex-start' }}>
          <div data-bureau-rail>
            <LeftRail data={data} dark={dark} sectionRefs={sectionRefs} query={query} classFilter={classFilter} statusFilter={statusFilter} />
          </div>
          <div>
            {data.sections.map((s, i) => {
              const start = runningIdx;
              runningIdx += s.items.length;
              return <SectionBlock key={s.id} section={s} secIdx={i} query={query}
                classFilter={classFilter} statusFilter={statusFilter} audience={audience} onHover={onHover} dark={dark}
                startIdx={start} expandedKey={expandedKey} setExpandedKey={setExpandedKey} registerRef={registerRef} />;
            })}

            <footer style={{
              padding: '24px 24px 36px', borderTop: `1px solid ${t.rule}`, marginTop: 24,
              fontFamily: FONTS.mono, color: t.fgSoft,
            }}>
              <div style={{ display:'flex', justifyContent:'space-between', fontSize: 10, letterSpacing:'0.2em', marginBottom: 18 }}>
                <span>END OF FILING · SLBO-00 · {totalCount} ENTRIES ATTESTED</span>
                <span>{new Date().toISOString().slice(0,10).replace(/-/g,'.')}</span>
              </div>
              <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap: 28, paddingTop: 18, borderTop: `1px dashed ${t.ruleSoft}` }}>
                <div>
                  <div style={{ fontSize: 9, letterSpacing:'0.24em', color: t.fgMute, marginBottom: 6 }}>BUREAU</div>
                  <div style={{ fontFamily: FONTS.serif, fontStyle:'italic', fontSize: 15, color: t.fg, lineHeight: 1.5 }}>
                    Suede Labs maintains a single public index of every operating surface. Records are filed by examiners and made
                    available, free of fee, under unrestricted license.
                  </div>
                </div>
                <div>
                  <div style={{ fontSize: 9, letterSpacing:'0.24em', color: t.fgMute, marginBottom: 6 }}>SHORTCUTS</div>
                  <div style={{ fontFamily: FONTS.mono, fontSize: 11, color: t.fg, lineHeight: 1.85, letterSpacing:'0.04em' }}>
                    ⌘K · COMMAND PALETTE<br />↵   · OPEN FORM<br />⇧↵ · JUMP IN PAGE<br />ESC · CLOSE
                  </div>
                </div>
                <div>
                  <div style={{ fontSize: 9, letterSpacing:'0.24em', color: t.fgMute, marginBottom: 6 }}>COLOPHON</div>
                  <div style={{ fontFamily: FONTS.serif, fontStyle:'italic', fontSize: 15, color: t.fg, lineHeight: 1.5 }}>
                    Set in Cormorant Garamond and JetBrains Mono.<br />
                    Filed by Bureau of Operations, MMXXVI.
                  </div>
                  <div style={{ marginTop: 12 }}>
                    <a href="explorations.html" style={{
                      fontFamily: FONTS.mono, fontSize: 10, letterSpacing:'0.2em', color: t.accent,
                      textDecoration:'none', borderBottom: `1px solid ${t.accent}`, paddingBottom: 2,
                    }}>SEE DESIGN EXPLORATIONS ↗</a>
                  </div>
                </div>
              </div>

              {/* Center credit line — the final, smallest mark on the page. */}
              <div style={{
                marginTop: 28, paddingTop: 20, borderTop: `1px solid ${t.ruleSoft}`,
                textAlign:'center', fontFamily: FONTS.serif, fontStyle:'italic',
                fontSize: 12, color: t.fgSoft, letterSpacing:'0.02em',
              }}>
                A <a href="https://suedeai.ai" target="_blank" rel="noreferrer" style={{ color: t.fg, textDecoration:'none', borderBottom:`1px solid ${t.ruleSoft}` }}>Suede Labs</a>
                {' / '}
                <a href="https://suedeai.ai/jason-colapietro-images" target="_blank" rel="noreferrer" style={{ color: t.fg, textDecoration:'none', borderBottom:`1px solid ${t.ruleSoft}` }}>Jason Colapietro</a>
                {' creation.'}
              </div>
            </footer>
          </div>
        </div>

        <Preview item={preview.item} position={preview.pos} dark={dark} />
        <Palette open={paletteOpen} onClose={() => setPaletteOpen(false)} data={data} dark={dark} onJump={jumpTo} />
      </div>
    );
  }

  return SuedeBureau;
})();

window.SuedeBureau = Bureau;
