repositories

daemon-sec-cheatsheet

The cheatsheet vault for operators: AD, enumeration, exploitation, priv-esc, web, DFIR

clonegit clone https://git.daemon-sec.xyz/daemon-sec-cheatsheet.git
HeroLoop.astroAstro465 lines30.7 KiBraw download
---
import ContourField from './ContourField.astro';
import HeroBrand from './HeroBrand.astro';

interface Shelf { n: string; label: string; path: string; accent: string; desc: string }
interface Props {
  shelves: Shelf[];
  name?: string;
  tagline?: string;
}
const { shelves, name = 'DΛΣMӨП-RΣF', tagline = 'DÆMON-REF · Cheatsheet vault' } = Astro.props;
const data = JSON.stringify({ shelves, name, tagline });
---
<section class="hero-loop bleed signal-hero" data-hero-loop data-hero={data} aria-label="Shelves">
  <ContourField />
  <HeroBrand />
  <noscript>
    <div style="padding:56px 44px;max-width:1560px;margin:0 auto;">
      <h1 style="margin:0;font-family:var(--font-wordmark);font-weight:800;font-size:clamp(40px,9vw,120px);font-stretch:88%;letter-spacing:-0.02em;line-height:1;color:var(--text);text-transform:uppercase;">{name}</h1>
      <p style="margin-top:14px;font-family:var(--font-plex);font-size:13px;letter-spacing:0.1em;text-transform:uppercase;color:var(--muted);">Six shelves. One vault.</p>
      <ul style="margin-top:28px;list-style:none;padding:0;border-top:1px solid var(--line);">
        {shelves.map((s) => (
          <li><a href={s.path} style={`display:flex;justify-content:space-between;gap:16px;padding:16px 0;border-bottom:1px solid var(--line);font-family:var(--font-archivo);font-weight:600;font-size:24px;text-transform:uppercase;color:var(--${s.accent});`}>{s.label}<span style="font-family:var(--font-plex);font-size:13px;color:var(--subtle);">{s.path}</span></a></li>
        ))}
      </ul>
    </div>
  </noscript>
</section>

<script>
  // Hero loop — a 1:1 vanilla port of the handoff's hero-loop.js (itself the
  // main site's hero-loop.tsx): one 21.4s rAF clock, an authored 1920×1080
  // canvas scaled to fit at >=1280px, a fluid flow shape below, pointer/focus
  // takeover with an eased `mix`, glyph decode until +0.55s, and the plate as
  // the inverse of the page (theme-aware P/Q). Pauses when hidden or scrolled
  // out; prefers-reduced-motion holds T=12.0 with no scramble.

  import { mountParticleField, type LitShelf, type ShelfSource } from '../scripts/dmn/particle-field';
  import { SHELF_ICONS } from '../scripts/dmn/shelf-icons';
  import { PALETTES } from '../lib/palettes';

  const W = 1920, H = 1080, PLATE_W = 784, PLATE_H = 780, MIN_HEIGHT = 560, MARQUEE = 92;
  const CANVAS_MIN = 1280, FLOW_PLATE_MIN = 860;
  const BOOT = 0, CLOSE = 18.8, AUTHORED = 21.4, HELD_FRAME = 12.0;
  const STARTS = [3.2, 5.8, 8.4, 11.0, 13.6, 16.2];
  const ENDS = STARTS.map((s, i) => (i < 5 ? STARTS[i + 1] : CLOSE));
  const GLYPH_POOL = 'ΛΣӨПΔΞΨΩ01#/\\_';

  const DAWN = { base: 'var(--color-dawn-base)', surface: 'var(--color-dawn-surface)', ink: 'var(--color-dawn-ink)', subtle: 'var(--color-dawn-subtle)', muted: 'var(--color-dawn-muted)', line: 'color-mix(in srgb, var(--color-dawn-ink) 16%, transparent)', pine: 'var(--color-dawn-pine)', foam: 'var(--color-dawn-foam)', gold: 'var(--color-dawn-gold)', love: 'var(--color-dawn-love)', iris: 'var(--color-dawn-iris)', rose: 'var(--color-dawn-rose)' };
  const NIGHT = { base: 'var(--color-night-base)', surface: 'var(--color-night-surface)', ink: 'var(--color-night-text)', subtle: 'var(--color-night-subtle)', muted: 'var(--color-night-muted)', line: 'color-mix(in srgb, var(--color-night-text) 16%, transparent)', pine: 'var(--color-night-pine)', foam: 'var(--color-night-foam)', gold: 'var(--color-night-gold)', love: 'var(--color-night-love)', iris: 'var(--color-night-iris)', rose: 'var(--color-night-rose)' };
  /* The caption names what the reader is looking at — "Gruvbox · Night" —
     and is rebuilt with the rest of the hero on `daemonmodechange`. */
  const modeName = () => {
    const root = document.documentElement;
    const name = PALETTES.find((p) => p.id === root.getAttribute('data-palette'))?.name ?? PALETTES[0].name;
    return `${name} · ${root.getAttribute('data-theme') === 'dark' ? 'Night' : 'Dawn'}`;
  };
  const MONO = 'var(--font-plex)', ARCHIVO = 'var(--font-archivo)', WORDMARK_FACE = 'var(--font-wordmark)';

  const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
  const easeOutCubic = (p: number) => 1 - Math.pow(1 - p, 3);
  const easeInOutCubic = (p: number) => (p < 0.5 ? 4 * p * p * p : 1 - Math.pow(-2 * p + 2, 3) / 2);
  const enter = (T: number, start: number, dur = 0.6) => { const o = easeOutCubic(clamp((T - start) / dur, 0, 1)); return { o, y: (1 - o) * 24 }; };
  const draw = (T: number, start: number, dur = 0.8) => easeInOutCubic(clamp((T - start) / dur, 0, 1));
  const hold = (T: number, a: number, b: number, ramp = 0.35) => Math.min(easeOutCubic(clamp((T - a) / ramp, 0, 1)), easeOutCubic(clamp((b - T) / ramp, 0, 1)));
  const hash = (i: number, k: number) => { const s = Math.sin(i * 12.9898 + k * 78.233) * 43758.5453; return s - Math.floor(s); };
  const activeAt = (T: number) => { for (let i = 0; i < 6; i++) if (T >= STARTS[i] && T < ENDS[i]) return i; return -1; };
  const timecode = (T: number) => `T+${String(Math.floor(T / 60)).padStart(2, '0')}:${String(Math.floor(T % 60)).padStart(2, '0')}.${String(Math.floor((T % 1) * 24)).padStart(2, '0')}`;

  type Shelf = { n: string; label: string; path: string; accent: string; desc: string };

  function shelfState(T: number, mix: number, held: number | null, shelves: Shelf[]) {
    const act: number[] = [], plateAct: number[] = [], plateY: number[] = [], plateLine: number[] = [];
    for (let i = 0; i < shelves.length; i++) {
      const hv = i === held ? 1 : 0;
      act.push(hold(T, STARTS[i], ENDS[i]) * (1 - mix) + hv * mix);
      plateAct.push(hold(T, STARTS[i], ENDS[i], 0.4) * (1 - mix) + hv * mix);
      plateY.push((1 - enter(T, STARTS[i], 0.5).o) * 40 * (1 - mix));
      const line = draw(T, STARTS[i] + 0.15, 0.7) * (1 - draw(T, ENDS[i] - 0.4, 0.4));
      plateLine.push(line * (1 - mix) + hv * mix);
    }
    const fromClock = activeAt(T);
    const active = mix > 0.5 ? (held ?? fromClock) : fromClock;
    const standing = Math.max(hold(T, BOOT + 1.6, STARTS[0]), hold(T, CLOSE + 0.35, AUTHORED + 1)) * (1 - mix);
    return { act, plateAct, plateY, plateLine, standing, active, accent: active >= 0 ? shelves[active].accent : 'love' };
  }

  // Tiny DOM helper. Numeric style values need no unit here — every length is
  // passed as an explicit px string.
  function el(tag: string, style?: Record<string, string>, kids?: any): HTMLElement {
    const n = document.createElement(tag);
    if (style) Object.assign(n.style, style);
    if (kids != null) (Array.isArray(kids) ? kids : [kids]).forEach((k) => { if (k == null || k === false) return; n.append(k.nodeType ? k : document.createTextNode(String(k))); });
    return n;
  }

  function build(hostW: number, mode: 'canvas' | 'flow', withPlate: boolean, shelves: Shelf[], name: string, tagline: string, P: any, Q: any, onHold: (i: number) => void, onRelease: () => void, brandTemplate: HTMLTemplateElement) {
    // Row metrics differ by shape.
    const M = mode === 'canvas'
      ? { height: '76px', columns: '64px 1fr auto', padLeft: '14px', chipSize: '14px', chipPad: '3px 7px', labelSize: '30px', pathSize: '15px', pathPad: '16px', shift: 10, arrow: true }
      : { height: '56px', columns: '44px 1fr auto', padLeft: '8px', chipSize: '11px', chipPad: '3px 6px', labelSize: 'clamp(17px, 2.2vw, 26px)', pathSize: 'clamp(10px, 1.1vw, 13px)', pathPad: '0px', shift: 8, arrow: false };

    // ── Shelf row ──
    const rows = shelves.map((s) => {
      const acc = P[s.accent];
      const wash = el('span', { position: 'absolute', inset: '0', background: P.surface, opacity: '0', borderLeft: `3px solid ${acc}`, transformOrigin: 'left', transform: 'scaleX(0)' });
      const chip = el('span', { fontFamily: MONO, fontSize: M.chipSize, letterSpacing: '0.06em', padding: M.chipPad, color: P.muted, background: 'transparent', boxShadow: `inset 0 0 0 1px ${P.line}` }, s.n);
      const chipWrap = el('span', { position: 'relative', display: 'flex', alignItems: 'center', paddingLeft: M.padLeft }, chip);
      const label = el('span', { position: 'relative', fontFamily: ARCHIVO, fontWeight: '600', fontSize: M.labelSize, letterSpacing: '0.04em', textTransform: 'uppercase', color: P.ink, opacity: '1', transform: 'translateX(0)' }, s.label);
      const arrow = M.arrow ? el('span', { display: 'inline-block', marginLeft: '12px', opacity: '0', transform: 'translateX(-8px)' }, '→') : null;
      const path = el('span', { position: 'relative', fontFamily: MONO, fontSize: M.pathSize, letterSpacing: '0.06em', color: P.ink, paddingRight: M.pathPad, opacity: '0.85' }, [s.path, arrow]);
      const a = el('a', { position: 'relative', display: 'grid', gridTemplateColumns: M.columns, alignItems: 'center', height: M.height, borderTop: `1px solid ${P.line}`, opacity: '1', transform: 'translateY(0)', textDecoration: 'none', color: P.ink }, [wash, chipWrap, label, path]) as HTMLAnchorElement;
      a.href = s.path;
      const idx = shelves.indexOf(s);
      a.addEventListener('mouseenter', () => onHold(idx));
      a.addEventListener('mouseleave', onRelease);
      a.addEventListener('focus', () => onHold(idx));
      a.addEventListener('blur', onRelease);
      return { a, wash, chip, label, path, arrow };
    });
    const nav = el('nav', mode === 'canvas'
      ? { position: 'absolute', left: '72px', top: '424px', width: '916px' }
      : { marginTop: '32px' }, [...rows.map((r) => r.a), el('div', { borderTop: `1px solid ${P.line}` })]);
    nav.setAttribute('aria-label', 'Shelves');
    // The contour field behind the hero reads this box and draws no line
    // inside it, so the rows sit on clean ground (and the plate's dot
    // field falls back to it as the icon's home).
    nav.setAttribute('data-index-zone', '');

    // ── Plate ──
    // The plate's dots: spread across it at rest and gathering into the
    // hovered shelf's icon (src/scripts/dmn). They replace the old random
    // grid, so the dots on the card are the ones that form the icon. The
    // anchor is the open upper half, between the chrome and the shelf block.
    const plateCanvas = el('canvas', { position: 'absolute', inset: '0', width: '100%', height: '100%', display: 'block' }) as HTMLCanvasElement;
    plateCanvas.className = 'dmn-plate-dots';
    const iconAnchor = el('div', { position: 'absolute', left: '40px', right: '40px', top: '92px', height: '300px' });
    iconAnchor.setAttribute('data-field-icon', '');
    const dotField = el('div', { position: 'absolute', left: '0', top: '0', width: PLATE_W + 'px', height: PLATE_H + 'px' }, [iconAnchor, plateCanvas]);
    const plateMeta = { fontFamily: MONO, fontSize: '14px', letterSpacing: '0.10em', textTransform: 'uppercase', color: Q.subtle };
    const chromeRight = el('span', { color: P.love }, '— / 06');
    const chrome = el('div', { position: 'absolute', left: '40px', right: '40px', top: '36px', display: 'flex', justifyContent: 'space-between', whiteSpace: 'nowrap', ...plateMeta }, [el('span', undefined, 'Plate · index'), chromeRight]);
    const standing = el('div', { position: 'absolute', left: '40px', right: '40px', bottom: '48px', opacity: '0', transform: 'translateY(16px)' }, [
      el('div', { ...plateMeta, marginBottom: '14px' }, 'Standing by'),
      el('div', { fontFamily: ARCHIVO, fontWeight: '700', fontSize: '64px', lineHeight: '0.98', letterSpacing: '-0.02em', color: Q.ink }, ['Security lives', el('br'), 'in the details.']),
      el('div', { marginTop: '22px', fontFamily: MONO, fontSize: '15px', letterSpacing: '0.04em', color: Q.muted }, '06 shelves · select an entry'),
    ]);
    const sections = shelves.map((s) => {
      const acc = Q[s.accent];
      const rule = el('div', { height: '2px', background: acc, marginTop: '26px', transformOrigin: 'left', transform: 'scaleX(0)' });
      const block = el('div', { position: 'absolute', left: '40px', right: '40px', bottom: '48px', opacity: '0', transform: 'translateY(40px)' }, [
        el('div', { display: 'flex', alignItems: 'center', gap: '14px', marginBottom: '20px' }, [
          el('span', { fontFamily: MONO, fontSize: '14px', letterSpacing: '0.08em', padding: '4px 8px', background: acc, color: Q.base }, s.n),
          el('span', { fontFamily: MONO, fontSize: '15px', letterSpacing: '0.08em', color: acc }, s.path),
        ]),
        el('div', { fontFamily: ARCHIVO, fontWeight: '800', fontSize: (s.label.length > 5 ? 118 : 148) + 'px', lineHeight: '0.92', letterSpacing: '-0.03em', textTransform: 'uppercase', color: Q.ink }, s.label),
        rule,
        el('div', { marginTop: '22px', fontFamily: ARCHIVO, fontSize: '27px', lineHeight: '1.3', color: Q.subtle, maxWidth: '620px' }, s.desc),
        el('div', { marginTop: '28px', fontFamily: MONO, fontSize: '15px', letterSpacing: '0.10em', textTransform: 'uppercase', color: Q.muted, display: 'flex', gap: '12px', alignItems: 'center' }, [el('span', { color: acc }, '▸'), ' Enter shelf']),
      ]);
      return { block, rule };
    });
    const plateSurface = el('div', { position: 'absolute', left: '0', top: '0', width: PLATE_W + 'px', height: PLATE_H + 'px', background: Q.base, color: Q.ink, overflow: 'hidden', clipPath: 'inset(0 100% 0 0)' }, [
      el('div', { position: 'absolute', inset: '0', background: `radial-gradient(120% 80% at 90% 100%, ${Q.surface} 0%, ${Q.base} 60%)` }),
      dotField, chrome,
      el('div', { position: 'absolute', left: '40px', right: '40px', top: '66px', height: '1px', background: Q.line }),
      standing, ...sections.map((s) => s.block),
    ]);
    plateSurface.setAttribute('aria-hidden', 'true');
    plateSurface.setAttribute('data-field-host', '');

    // Plate host — absolute box on canvas, aspect-ratio fitted box on flow.
    let plateHost: HTMLElement, plateScaleK = 1;
    if (mode === 'canvas') {
      plateHost = el('div', { position: 'absolute', left: '1064px', top: '150px', width: PLATE_W + 'px', height: PLATE_H + 'px' }, plateSurface);
    } else {
      const inner = el('div', { position: 'absolute', left: '0', top: '0', width: PLATE_W + 'px', height: PLATE_H + 'px', transformOrigin: '0 0' }, plateSurface);
      plateHost = el('div', { position: 'relative', width: '100%', aspectRatio: `${PLATE_W} / ${PLATE_H}`, overflow: 'hidden' }, inner);
      plateHost.setAttribute('aria-hidden', 'true');
      (plateHost as any)._inner = inner;
    }

    // ── Wordmark ──
    const wm = name.split('').map((g) => el('span', { display: 'inline-block', opacity: '0', transform: 'translateY(24px)', color: g === '-' ? P.love : P.muted, fontFamily: MONO, fontWeight: '500' }, g));
    // The page's one heading; the glyphs scramble on arrival, so the
    // accessible name is the settled spelling.
    const wordmark = el('h1', { margin: '0', fontFamily: WORDMARK_FACE, fontWeight: '700', lineHeight: '1', letterSpacing: '-0.02em', color: P.ink, display: 'flex', whiteSpace: 'pre' }, wm);
    wordmark.setAttribute('aria-label', name);
    const heroBrand = brandTemplate.content.firstElementChild!.cloneNode(true) as HTMLElement;
    heroBrand.classList.toggle('hero-brand--flow', mode === 'flow');
    heroBrand.querySelector('.hero-brand__type')!.insertBefore(wordmark, heroBrand.querySelector('.hero-brand__rail'));


    // ── Meta rows + subline ──
    const metaBase = (x?: Record<string, string>) => ({ fontFamily: MONO, fontSize: '15px', letterSpacing: '0.10em', textTransform: 'uppercase', color: P.subtle, whiteSpace: 'nowrap', ...(x || {}) });
    const recDot = el('div', { width: '8px', height: '8px', borderRadius: '4px', background: P.love, opacity: '1' });
    const timecodeEl = el('div', metaBase({ fontVariantNumeric: 'tabular-nums' }), timecode(0));
    const sublinePath = el('span', { color: P[shelves[0]?.accent] || P.love }, '/');
    let topMeta: HTMLElement, subline: HTMLElement, hairline: HTMLElement, bottomMeta: HTMLElement, root: HTMLElement;

    if (mode === 'canvas') {
      hairline = el('div', { position: 'absolute', left: '72px', right: '72px', top: '96px', height: '1px', background: P.ink, transformOrigin: 'left', transform: 'scaleX(0)', opacity: '0.9' });
      topMeta = el('div', { position: 'absolute', left: '72px', right: '72px', top: '56px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', opacity: '0' }, [
        el('div', metaBase(), tagline),
        el('div', { display: 'flex', alignItems: 'center', gap: '10px' }, [recDot, el('div', metaBase({ color: P.love }), 'REC')]),
        timecodeEl,
      ]);
      wordmark.style.fontSize = 'clamp(20px, 15cqw, 112px)';
      subline = el('div', metaBase({ marginTop: '18px', marginLeft: '4px', color: P.muted, opacity: '0', transform: 'translateY(24px)' }), ['Six shelves. One vault. ', sublinePath]);
      // Small type directly over the contour field: it shares the rows' clean ground.
      subline.setAttribute('data-contour-clear', '');
      const wmBlock = el('div', { position: 'absolute', left: '68px', top: '158px' }, [heroBrand, subline]);
      bottomMeta = el('div', { position: 'absolute', left: '72px', right: '72px', bottom: '56px', display: 'flex', justifyContent: 'space-between', opacity: '0' }, [
        el('div', metaBase({ color: P.muted }), `${modeName()} · plates inverted`),
        el('div', metaBase({ color: P.muted }), 'Scroll ↓'),
      ]);
      root = el('div', { position: 'absolute', inset: '0', color: P.ink, opacity: '0', overflow: 'hidden', fontFamily: ARCHIVO }, [hairline, topMeta, wmBlock, nav, plateHost, bottomMeta]);
    } else {
      wordmark.style.fontSize = 'clamp(28px, 15cqw, 100px)';
      hairline = el('div', { height: '1px', marginTop: '14px', background: P.ink, transformOrigin: 'left', transform: 'scaleX(0)', opacity: '0.9' });
      topMeta = el('div', { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '12px', opacity: '0' }, [
        el('div', metaBase({ fontSize: 'clamp(10px, 1.05vw, 13px)' }), tagline),
        el('div', { display: 'flex', alignItems: 'center', gap: '8px' }, [recDot, timecodeEl]),
      ]);
      subline = el('div', metaBase({ fontSize: 'clamp(10px, 1.05vw, 13px)', marginTop: '14px', color: P.muted, whiteSpace: 'normal', opacity: '0', transform: 'translateY(24px)' }), ['Six shelves. One vault. ', sublinePath]);
      // Small type directly over the contour field: it shares the rows' clean ground.
      subline.setAttribute('data-contour-clear', '');
      const left = el('div', { minWidth: '0' }, [heroBrand, subline, nav]);
      const center = el('div', { display: 'grid', gridTemplateColumns: withPlate ? 'minmax(0,1fr) clamp(300px, 44%, 560px)' : 'minmax(0,1fr)', gap: 'clamp(28px, 3.4vw, 56px)', alignItems: 'center' }, withPlate ? [left, plateHost] : [left]);
      const centerWrap = el('div', { flex: '1', display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: 'clamp(28px, 4vw, 56px) 0' }, center);
      bottomMeta = el('div', { paddingTop: '32px', display: 'flex', justifyContent: 'space-between', gap: '12px', opacity: '0' }, [
        el('div', metaBase({ fontSize: 'clamp(10px, 1.05vw, 13px)', color: P.muted }), modeName()),
        el('div', metaBase({ fontSize: 'clamp(10px, 1.05vw, 13px)', color: P.muted }), 'Scroll ↓'),
      ]);
      root = el('div', { display: 'flex', flexDirection: 'column', minHeight: `min(calc(100svh - ${MARQUEE}px), 620px)`, padding: 'clamp(28px, 4vw, 56px) clamp(20px, 3.8vw, 72px)', color: P.ink, opacity: '0', fontFamily: ARCHIVO }, [topMeta, hairline, centerWrap, bottomMeta]);
    }

    function paintPlate(T: number, st: any, reveal: number) {
      plateSurface.style.clipPath = `inset(0 ${(1 - reveal) * 100}% 0 0)`;
      const accentName = st.active >= 0 ? shelves[st.active].accent : 'love';
      const accentCol = Q[accentName];
      chromeRight.textContent = st.active >= 0 ? `${shelves[st.active].n} / 06` : '— / 06';
      chromeRight.style.color = accentCol;
      standing.style.opacity = String(st.standing);
      standing.style.transform = `translateY(${(1 - st.standing) * 16}px)`;
      for (let i = 0; i < sections.length; i++) {
        sections[i].block.style.opacity = String(st.plateAct[i]);
        sections[i].block.style.transform = `translateY(${st.plateY[i]}px)`;
        sections[i].rule.style.transform = `scaleX(${st.plateLine[i]})`;
      }
    }

    function paint(T: number, st: any) {
      const master = Math.min(enter(T, BOOT, 0.5).o, easeOutCubic(clamp((AUTHORED - T) / 0.5, 0, 1)));
      const reveal = draw(T, BOOT + 0.9, 1.0) * (1 - draw(T, CLOSE + 1.2, 0.8));
      const rule = draw(T, BOOT + 0.25, 0.9), pulse = 0.55 + 0.45 * Math.sin(T * 5), sub = enter(T, BOOT + 2.1);
      root.style.opacity = String(master);
      hairline.style.transform = `scaleX(${rule})`;
      topMeta.style.opacity = String(enter(T, BOOT + 0.2).o);
      recDot.style.opacity = String(pulse);
      timecodeEl.textContent = timecode(st.E ?? T);
      bottomMeta.style.opacity = String(enter(T, BOOT + 2.4).o);
      // Wordmark decode
      const roll = Math.floor(T * 18);
      for (let i = 0; i < wm.length; i++) {
        const g = name[i], at = BOOT + 0.35 + i * 0.16, revealed = T >= at + 0.55, e = enter(T, at, 0.5);
        const ch = revealed ? g : GLYPH_POOL[Math.floor(hash(i, roll) * GLYPH_POOL.length)];
        const node = wm[i];
        if (node.textContent !== ch) node.textContent = ch;
        node.style.opacity = String(e.o);
        node.style.transform = `translateY(${e.y}px)`;
        node.style.color = g === '-' ? P.love : revealed ? P.ink : P.muted;
        node.style.fontFamily = revealed ? WORDMARK_FACE : MONO;
        node.style.fontWeight = revealed ? '700' : '500';
      }
      // Subline
      subline.style.opacity = String(sub.o);
      subline.style.transform = `translateY(${sub.y}px)`;
      sublinePath.textContent = st.active >= 0 ? shelves[st.active].path : '/';
      sublinePath.style.color = P[st.accent];
      // Rows
      for (let i = 0; i < rows.length; i++) {
        const a = st.act[i], s = shelves[i], acc = P[s.accent], lit = a > 0.5;
        const en = enter(T, BOOT + 1.3 + i * 0.13, 0.55);
        const R = rows[i];
        R.a.style.opacity = String(en.o);
        R.a.style.transform = `translateY(${en.y}px)`;
        R.wash.style.opacity = String(a);
        R.wash.style.transform = `scaleX(${a})`;
        R.chip.style.color = lit ? P.base : P.muted;
        R.chip.style.background = lit ? acc : 'transparent';
        R.chip.style.boxShadow = `inset 0 0 0 1px ${lit ? acc : P.line}`;
        R.label.style.color = a > 0.01 ? acc : P.ink;
        // A row another shelf has taken the light from still has to read:
        // 85% of the ink is 4.66:1 on cream and 9.93:1 on night, so an
        // unlit label and its path both clear AA in either mode. The
        // lit row is told apart by its accent, wash and chip, not by
        // dimming the others.
        R.label.style.opacity = String(0.85 + 0.15 * Math.max(a, st.active >= 0 ? 0 : 1));
        R.label.style.transform = `translateX(${a * M.shift}px)`;
        R.path.style.opacity = String(0.85 + 0.15 * a);
        if (R.arrow) { R.arrow.style.opacity = String(a); R.arrow.style.transform = `translateX(${(1 - a) * -8}px)`; }
      }
      paintPlate(T, st, reveal);
      if (mode === 'flow' && withPlate) {
        const k = plateHost.clientWidth / PLATE_W;
        if (k > 0 && Math.abs(k - plateScaleK) > 0.001) { plateScaleK = k; (plateHost as any)._inner.style.transform = `scale(${k})`; }
      }
    }
    return { root, paint, plateCanvas };
  }

  function initHero() {
    const host = document.querySelector('[data-hero-loop]') as HTMLElement | null;
    if (!host || host.dataset.bound) return;
    const brandTemplate = host.querySelector<HTMLTemplateElement>('[data-hero-brand-template]');
    if (!brandTemplate) return;
    host.dataset.bound = '1';
    let cfg: { shelves: Shelf[]; name: string; tagline: string };
    try { cfg = JSON.parse(host.dataset.hero || '{}'); } catch { return; }
    const shelves = cfg.shelves || [];
    if (!shelves.length) return;

    const reduced = matchMedia('(prefers-reduced-motion: reduce)');
    let hover: { idx: number | null; last: number | null } = { idx: null, last: null };

    // Which shelf a hand is holding, for the plate's icon. Hover only: the
    // tour cycles the rows and the plate's copy, the icon answers a pointer.
    let lit: LitShelf = { index: null, accent: null, held: false };
    const litSubs = new Set<(s: LitShelf) => void>();
    const shelfSource: ShelfSource = {
      get: () => lit,
      subscribe(f) { litSubs.add(f); return () => { litSubs.delete(f); }; },
    };
    const setLit = (i: number | null) => {
      const next: LitShelf = i === null ? { index: null, accent: null, held: false } : { index: i, accent: shelves[i].accent, held: true };
      if (next.index === lit.index && next.held === lit.held) return;
      lit = next;
      litSubs.forEach((f) => f(lit));
    };
    const onHold = (i: number) => { hover = { idx: i, last: i }; setLit(i); };
    const onRelease = () => { hover = { idx: null, last: hover.last }; setLit(null); };
    let destroyPlate: (() => void) | null = null;
    const mountPlate = (cv: HTMLCanvasElement, qFam: 'dawn' | 'night') => {
      destroyPlate?.();
      destroyPlate = mountParticleField(cv, {
        icons: SHELF_ICONS,
        shelf: shelfSource,
        cloud: false,
        restFill: true,
        tone: 'plate',
        // The plate is the page's inverse, painted from the fixed poles.
        vars: {
          ink: qFam === 'night' ? '--color-night-text' : '--color-dawn-ink',
          base: `--color-${qFam}-base`,
          iris: `--color-${qFam}-iris`,
          love: `--color-${qFam}-love`,
        },
        accentVar: (a) => `--color-${qFam}-${a}`,
      });
    };

    let current: { root: HTMLElement; paint: (T: number, st: any) => void } | null = null;
    let mode: 'canvas' | 'flow' | null = null, withPlate = false, dark = document.documentElement.getAttribute('data-theme') === 'dark';
    let carriedT = 0, carriedE = 0, carriedMix = 0, raf = 0, prev = 0, visible = !document.hidden, inView = true;

    function rebuild() {
      const w = host.clientWidth || window.innerWidth;
      const canvas = window.innerWidth >= CANVAS_MIN;
      mode = canvas ? 'canvas' : 'flow';
      withPlate = !canvas && window.innerWidth >= FLOW_PLATE_MIN;
      dark = document.documentElement.getAttribute('data-theme') === 'dark';
      const P = dark ? NIGHT : DAWN, Q = dark ? DAWN : NIGHT;
      // Preserve the contour field when the hero rebuilds for theme or viewport changes.
      for (const child of Array.from(host.children)) {
        if (!child.hasAttribute('data-contour') && child !== brandTemplate) child.remove();
      }
      if (canvas) {
        // The artboard's fit is a measurement, not a movement. Under reduced
        // motion the global 0.01ms rule would still make each refit a
        // transition, and whatever measures the composition while one is
        // pending (the contour field's keep-clear box, the plate's icon
        // home) reads the old scale; `none` makes the fit land at once.
        const stage = el('div', { position: 'absolute', left: '0', top: '0', transformOrigin: '0 0', transition: 'none' });
        host.style.height = `max(${MIN_HEIGHT}px, min(calc(100vh - ${MARQUEE}px), ${(H / W) * 100}vw))`;
        const built = build(w, 'canvas', false, shelves, cfg.name, cfg.tagline, P, Q, onHold, onRelease, brandTemplate);
        stage.append(built.root);
        host.append(stage);
        mountPlate(built.plateCanvas, dark ? 'dawn' : 'night');
        const fit = () => {
          const bw = host.clientWidth, bh = host.clientHeight, scale = bw > 0 && bh > 0 ? Math.min(bw / W, bh / H) : 0;
          stage.style.width = W + 'px'; stage.style.height = H + 'px';
          stage.style.left = ((bw - W * scale) / 2) + 'px'; stage.style.top = ((bh - H * scale) / 2) + 'px';
          stage.style.transform = `scale(${scale})`;
        };
        fit();
        current = built;
        (host as any)._fit = fit;
      } else {
        host.style.height = '';
        const built = build(w, 'flow', withPlate, shelves, cfg.name, cfg.tagline, P, Q, onHold, onRelease, brandTemplate);
        host.append(built.root);
        if (withPlate) mountPlate(built.plateCanvas, dark ? 'dawn' : 'night');
        else { destroyPlate?.(); destroyPlate = null; }
        current = built;
        (host as any)._fit = null;
      }
      // Paint one frame immediately so a paused/first render is correct.
      paintFrame();
    }

    function paintFrame() {
      if (!current) return;
      const T = reduced.matches ? HELD_FRAME : carriedT;
      const st = { ...shelfState(T, carriedMix, hover.last, shelves), E: reduced.matches ? HELD_FRAME : carriedE };
      current.paint(T, st);
    }

    const running = () => !reduced.matches && visible && inView;
    function tick(now: number) {
      if (!running()) { raf = 0; return; }
      const dt = Math.min(0.05, (now - prev) / 1000); prev = now;
      // The boot plays once; the tour then wraps from the last shelf
      // straight back to the first instead of closing and booting again.
      // Every entrance has finished by STARTS[0], so the seam is invisible.
      carriedT += dt;
      carriedE += dt;
      if (carriedT >= CLOSE) carriedT = STARTS[0] + (carriedT - CLOSE);
      const target = hover.idx !== null ? 1 : 0;
      carriedMix += (target - carriedMix) * Math.min(1, dt * 14);
      paintFrame();
      raf = requestAnimationFrame(tick);
    }
    function start() { if (raf || !running()) { if (!running()) paintFrame(); return; } prev = performance.now(); raf = requestAnimationFrame(tick); }
    function stop() { if (raf) cancelAnimationFrame(raf); raf = 0; }

    rebuild();
    start();

    // Reactivity: breakpoint + theme rebuild, visibility + in-view pause.
    const canvasMq = matchMedia(`(min-width: ${CANVAS_MIN}px)`), plateMq = matchMedia(`(min-width: ${FLOW_PLATE_MIN}px)`);
    const onBp = () => { stop(); rebuild(); start(); };
    canvasMq.addEventListener('change', onBp);
    plateMq.addEventListener('change', onBp);
    reduced.addEventListener('change', () => { stop(); paintFrame(); start(); });
    window.addEventListener('daemonmodechange', () => { stop(); rebuild(); start(); });
    const ro = new ResizeObserver(() => { const f = (host as any)._fit; if (f) f(); });
    ro.observe(host);
    const onVis = () => { visible = !document.hidden; visible ? start() : stop(); };
    document.addEventListener('visibilitychange', onVis);
    const io = new IntersectionObserver(([e]) => { inView = e.isIntersecting; inView ? start() : stop(); });
    io.observe(host);

    document.addEventListener('astro:before-swap', () => {
      stop(); ro.disconnect(); io.disconnect();
      destroyPlate?.(); destroyPlate = null;
      document.removeEventListener('visibilitychange', onVis);
      canvasMq.removeEventListener('change', onBp); plateMq.removeEventListener('change', onBp);
    }, { once: true });
  }

  document.addEventListener('astro:page-load', initHero);
  if (document.readyState !== 'loading') initHero();
  else document.addEventListener('DOMContentLoaded', initHero);
</script>