// ─── Design System page ─────────────────────────────────────────────────
// Single-page reference for tokens, type, components, density, XIFty
// primitives, and motion. Lives at #/system inside the app shell.

// ─── Section primitive ────────────────────────────────────────────────
function DSSection({ id, title, sub, children }) {
  return (
    <section id={id} style={{ marginBottom: 56 }}>
      <div style={{ marginBottom: 16, paddingBottom: 8, borderBottom: '1px solid var(--color-border)' }}>
        <div className="film-edge" style={{ marginBottom: 4 }}>/// {id?.toUpperCase()}</div>
        <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>{title}</h2>
        {sub && (
          <div style={{ fontSize: 12, color: 'var(--color-text-secondary)', marginTop: 4 }}>{sub}</div>
        )}
      </div>
      {children}
    </section>
  );
}

function DSGrid({ cols = 'repeat(auto-fit, minmax(220px, 1fr))', gap = 12, children }) {
  return <div style={{ display: 'grid', gridTemplateColumns: cols, gap }}>{children}</div>;
}

function Swatch({ name, varName, hex, note }) {
  return (
    <div style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)', borderRadius: 3, overflow: 'hidden' }}>
      <div style={{ height: 56, background: `var(${varName})`, borderBottom: '1px solid var(--color-border)' }}/>
      <div style={{ padding: 10, display: 'flex', flexDirection: 'column', gap: 2 }}>
        <div style={{ fontFamily: 'var(--font-pixel)', fontSize: 11, letterSpacing: '0.12em', color: '#fbbf24' }}>{name}</div>
        <code style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--color-text-secondary)' }}>{varName}</code>
        <code style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--color-text-tertiary)' }}>{hex}</code>
        {note && <div style={{ fontSize: 10, color: 'var(--color-text-tertiary)', marginTop: 2 }}>{note}</div>}
      </div>
    </div>
  );
}

// ─── Density demo: a tiny table that responds to the toggle ─────────
function DensityDemo() {
  const rows = [
    { id: 'ast_0001', tier: 'hot',  size: '124 MB',  src: 'midjourney' },
    { id: 'ast_0002', tier: 'warm', size: '2.1 GB',  src: 'upload' },
    { id: 'ast_0003', tier: 'cold', size: '480 MB',  src: 'runway' },
    { id: 'ast_0004', tier: 'hot',  size: '8 KB',    src: 'elevenlabs' },
  ];
  return (
    <div className="density-demo" style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)', borderRadius: 3, overflow: 'hidden' }}>
      <table>
        <thead>
          <tr><th>ID</th><th>Tier</th><th>Size</th><th>Source</th></tr>
        </thead>
        <tbody>
          {rows.map(r => (
            <tr key={r.id}>
              <td><code style={{ fontFamily: 'var(--font-mono)', fontSize: 11 }}>{r.id}</code></td>
              <td><span className={`badge badge-${r.tier}`}>{r.tier}</span></td>
              <td style={{ fontFamily: 'var(--font-mono)' }}>{r.size}</td>
              <td style={{ fontFamily: 'var(--font-mono)' }}>{r.src}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// ─── Page ──────────────────────────────────────────────────────────────
function SystemPage() {
  const { density } = useDensity();

  return (
    <div style={{ padding: 24, maxWidth: 1200, margin: '0 auto' }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 14, marginBottom: 28 }}>
        <div>
          <div className="film-edge" style={{ marginBottom: 4 }}>/// DESIGN SYSTEM</div>
          <h1 className="page-h1">Khaos Storage — design system</h1>
          <div style={{ fontSize: 12, color: 'var(--color-text-secondary)', marginTop: 4 }}>
            Tokens, components, and motion. Living reference — every primitive on this page is the same one used in production app routes.
          </div>
        </div>
        <div style={{ flex: 1 }}/>
        <a href="#/motion" className="btn btn-secondary btn-sm">
          <Sparkles size={12}/> Motion lab →
        </a>
      </div>

      {/* TOC */}
      <div style={{
        display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 28,
        padding: '10px 12px',
        background: 'var(--color-surface)',
        border: '1px solid var(--color-border)',
        borderRadius: 3,
      }}>
        {['tokens','type','density','buttons','badges','inputs','tables','xifty','motion'].map(id => (
          <a key={id} href={`#system-${id}`}
            onClick={(e) => { e.preventDefault(); document.getElementById(`system-${id}`)?.scrollIntoView({ behavior: 'smooth', block: 'start' }); }}
            style={{
              padding: '4px 10px',
              fontFamily: 'var(--font-pixel)', fontSize: 11, letterSpacing: '0.15em',
              color: 'var(--color-text-secondary)',
              border: '1px solid var(--color-border-strong)',
              borderRadius: 2,
              cursor:'pointer',
            }}
          >{id.toUpperCase()}</a>
        ))}
      </div>

      {/* TOKENS */}
      <DSSection id="system-tokens" title="Color tokens" sub="Surface + brand + tier palette. CSS custom properties on :root.">
        <div style={{ marginBottom: 14 }}>
          <div className="film-edge" style={{ marginBottom: 8 }}>/// BRAND</div>
          <DSGrid>
            <Swatch name="Primary"       varName="--color-primary"       hex="#F59E0B" note="Khaos amber"/>
            <Swatch name="Primary hover" varName="--color-primary-hover" hex="#FBBF24"/>
            <Swatch name="Primary dim"   varName="--color-primary-dim"   hex="#78510a"/>
          </DSGrid>
        </div>
        <div style={{ marginBottom: 14 }}>
          <div className="film-edge" style={{ marginBottom: 8 }}>/// SURFACES</div>
          <DSGrid>
            <Swatch name="Background"    varName="--color-bg"             hex="#0a0a0a" note="Page"/>
            <Swatch name="Surface"       varName="--color-surface"        hex="#111111" note="Cards / inputs"/>
            <Swatch name="Surface raised"varName="--color-surface-raised" hex="#1a1a1a" note="Hover, active nav"/>
            <Swatch name="Surface overlay" varName="--color-surface-overlay" hex="#222222" note="Tooltips, menus"/>
            <Swatch name="Sidebar"       varName="--color-sidebar"        hex="#0d0d0d"/>
          </DSGrid>
        </div>
        <div style={{ marginBottom: 14 }}>
          <div className="film-edge" style={{ marginBottom: 8 }}>/// TIER</div>
          <DSGrid>
            <Swatch name="Hot"  varName="--color-hot"  hex="#22c55e" note="Active / recent"/>
            <Swatch name="Warm" varName="--color-warm" hex="#38bdf8" note="Idle, cheap retrieval"/>
            <Swatch name="Cold" varName="--color-cold" hex="#71717a" note="Archived"/>
            <Swatch name="Deep" varName="--color-deep" hex="#3f3f46" note="Glacier-class"/>
          </DSGrid>
        </div>
        <div>
          <div className="film-edge" style={{ marginBottom: 8 }}>/// SEMANTIC</div>
          <DSGrid>
            <Swatch name="Success" varName="--color-success" hex="#22c55e"/>
            <Swatch name="Warning" varName="--color-warning" hex="#F59E0B"/>
            <Swatch name="Danger"  varName="--color-danger"  hex="#ef4444"/>
            <Swatch name="Info"    varName="--color-info"    hex="#38bdf8"/>
          </DSGrid>
        </div>
      </DSSection>

      {/* TYPE */}
      <DSSection id="system-type" title="Typography" sub="Three families: Inter (UI), JetBrains Mono (data), VT323 (film-edge labels).">
        <DSGrid cols="repeat(auto-fit, minmax(280px, 1fr))">
          <div style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)', padding: 14, borderRadius: 3 }}>
            <div className="film-edge" style={{ marginBottom: 8 }}>/// SANS · INTER</div>
            <div style={{ fontFamily: 'var(--font-sans)', fontSize: 28, fontWeight: 600, letterSpacing: '-0.01em' }}>Storage you can edit.</div>
            <div style={{ fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--color-text-secondary)', marginTop: 6 }}>The quick brown fox jumps over the lazy dog. 0123456789</div>
            <code style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--color-text-tertiary)', display: 'block', marginTop: 8 }}>--font-sans</code>
          </div>
          <div style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)', padding: 14, borderRadius: 3 }}>
            <div className="film-edge" style={{ marginBottom: 8 }}>/// MONO · JETBRAINS</div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 18, fontWeight: 500 }}>s3://khaos/projects/{'{slug}'}</div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--color-text-secondary)', marginTop: 6 }}>sha256:8f3c2a91b46d…  ·  2.1 GB  ·  1080×1920</div>
            <code style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--color-text-tertiary)', display: 'block', marginTop: 8 }}>--font-mono</code>
          </div>
          <div style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)', padding: 14, borderRadius: 3 }}>
            <div className="film-edge" style={{ marginBottom: 8 }}>/// PIXEL · VT323</div>
            <div style={{ fontFamily: 'var(--font-pixel)', fontSize: 32, letterSpacing: '0.1em', color: '#fbbf24' }}>KHAOS · 24fps</div>
            <div style={{ fontFamily: 'var(--font-pixel)', fontSize: 14, letterSpacing: '0.18em', color: 'var(--color-text-secondary)', marginTop: 6 }}>FILM-EDGE LABELS · STATUS · MARGINALIA</div>
            <code style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--color-text-tertiary)', display: 'block', marginTop: 8 }}>--font-pixel</code>
          </div>
        </DSGrid>
      </DSSection>

      {/* DENSITY */}
      <DSSection id="system-density" title="Density" sub="Comfortable (default) vs compact. Toggles row padding and font sizes for data-heavy views. Persisted in localStorage.">
        <div style={{ marginBottom: 12, display: 'flex', alignItems: 'center', gap: 12 }}>
          <DensityToggle/>
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--color-text-tertiary)' }}>
            current: <span style={{ color: '#fbbf24' }}>{density}</span> · the table below reflects the toggle
          </span>
        </div>
        <DensityDemo/>
      </DSSection>

      {/* BUTTONS */}
      <DSSection id="system-buttons" title="Buttons" sub="Primary, secondary, ghost, danger. Sizes: default + sm.">
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, padding: 16, background: 'var(--color-surface)', border: '1px solid var(--color-border)', borderRadius: 3 }}>
          <button className="btn btn-primary"><Upload size={13}/> Upload</button>
          <button className="btn btn-secondary"><Download size={13}/> Download</button>
          <button className="btn btn-ghost"><Eye size={13}/> Preview</button>
          <button className="btn btn-danger"><Trash size={13}/> Delete</button>
          <button className="btn btn-primary btn-sm">Save</button>
          <button className="btn btn-secondary btn-sm">Cancel</button>
          <button className="btn btn-ghost btn-sm"><Settings size={11}/></button>
          <button className="btn btn-ghost btn-icon"><Plus size={14}/></button>
        </div>
      </DSSection>

      {/* BADGES */}
      <DSSection id="system-badges" title="Badges" sub="Tier + status. VT323 caps lock the entire badge family.">
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, padding: 16, background: 'var(--color-surface)', border: '1px solid var(--color-border)', borderRadius: 3 }}>
          <span className="badge badge-hot">hot</span>
          <span className="badge badge-warm">warm</span>
          <span className="badge badge-cold">cold</span>
          <span className="badge badge-deep">deep</span>
          <span className="badge badge-active">active</span>
          <span className="badge badge-archived">archived</span>
          <span className="badge badge-pending">pending</span>
          <span className="badge badge-error">error</span>
        </div>
      </DSSection>

      {/* INPUTS */}
      <DSSection id="system-inputs" title="Inputs" sub="Dark surface, amber focus, JetBrains Mono for technical inputs.">
        <DSGrid cols="repeat(auto-fit, minmax(260px, 1fr))">
          <div style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)', padding: 14, borderRadius: 3 }}>
            <label className="form-label">Asset title</label>
            <input placeholder="opening-shot-take-3" defaultValue="opening-shot-take-3" style={{ width: '100%', fontFamily: 'var(--font-mono)' }}/>
          </div>
          <div style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)', padding: 14, borderRadius: 3 }}>
            <label className="form-label">Region</label>
            <select style={{ width: '100%' }} defaultValue="us-west-2">
              <option value="us-west-2">us-west-2</option>
              <option>us-east-1</option>
              <option>eu-central-1</option>
            </select>
          </div>
          <div style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)', padding: 14, borderRadius: 3 }}>
            <label className="form-label">Description</label>
            <textarea rows="2" placeholder="optional…" style={{ width: '100%', resize: 'vertical' }}/>
          </div>
        </DSGrid>
      </DSSection>

      {/* TABLES */}
      <DSSection id="system-tables" title="Table" sub="The shared shell used by Assets, Keys, Activity. Sticky header, hover row, selection.">
        <div style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)', borderRadius: 3, overflow: 'hidden' }}>
          <table>
            <thead>
              <tr>
                <th>Title</th><th>Project</th><th>Tier</th><th>Size</th><th>Last access</th>
              </tr>
            </thead>
            <tbody>
              <tr className="selected">
                <td><code style={{ fontFamily: 'var(--font-mono)' }}>opening-shot-take-3.mp4</code></td>
                <td>kahani-board</td>
                <td><span className="badge badge-hot">hot</span></td>
                <td style={{ fontFamily: 'var(--font-mono)' }}>1.4 GB</td>
                <td style={{ color: 'var(--color-text-secondary)' }}>2h ago</td>
              </tr>
              <tr>
                <td><code style={{ fontFamily: 'var(--font-mono)' }}>character-portrait-anya.jpg</code></td>
                <td>rendered-fates</td>
                <td><span className="badge badge-warm">warm</span></td>
                <td style={{ fontFamily: 'var(--font-mono)' }}>8.4 MB</td>
                <td style={{ color: 'var(--color-text-secondary)' }}>4d ago</td>
              </tr>
              <tr>
                <td><code style={{ fontFamily: 'var(--font-mono)' }}>storyboard-act2-pg14.pdf</code></td>
                <td>museum-of-future</td>
                <td><span className="badge badge-cold">cold</span></td>
                <td style={{ fontFamily: 'var(--font-mono)' }}>3.2 MB</td>
                <td style={{ color: 'var(--color-text-secondary)' }}>31d ago</td>
              </tr>
            </tbody>
          </table>
        </div>
      </DSSection>

      {/* XIFTY */}
      <DSSection id="system-xifty" title="XIFty metadata" sub="Khaos's extended EXIF for creative media. Drop into the asset detail right rail when source data is available.">
        <DSGrid cols="repeat(auto-fit, minmax(280px, 1fr))" gap={12}>
          <FourView asset={{ id: 'demo-fv', thumb: 'linear-gradient(135deg, oklch(0.4 0.1 30), oklch(0.2 0.06 80))' }}/>
          <CameraExif/>
          <DroneTelemetry/>
          <GpsLocation/>
        </DSGrid>
      </DSSection>

      {/* MOTION */}
      <DSSection id="system-motion" title="Motion" sub="Four motion primitives. Full lab with replay + scrub at /motion.">
        <DSGrid cols="repeat(auto-fit, minmax(300px, 1fr))" gap={12}>
          <MiniMotion title="PROJECTOR" code="<ProjectorLoader/>" route="motion">
            <ProjectorLoader runId={0}/>
          </MiniMotion>
          <MiniMotion title="TIER SHIFT" code="hot → cold" route="motion">
            <TierShift runId={0}/>
          </MiniMotion>
          <MiniMotion title="SHARE MINT" code="POST /shares/sign" route="motion">
            <ShareMint runId={0}/>
          </MiniMotion>
          <MiniMotion title="SCRUB" code="<Scrub/>" route="motion">
            <Scrub runId={0}/>
          </MiniMotion>
        </DSGrid>
      </DSSection>

      <div style={{
        marginTop: 16, padding: '12px 16px',
        background: 'var(--color-surface)', border: '1px solid var(--color-border)',
        borderRadius: 3,
        fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--color-text-tertiary)',
      }}>
        <span style={{ color: '#fbbf24' }}>note</span> · this page is the source of truth for tokens + primitives.
        Edits here ripple through every app screen.
      </div>
    </div>
  );
}

function MiniMotion({ title, code, route, children }) {
  return (
    <div style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)', borderRadius: 3, overflow: 'hidden' }}>
      <div style={{ padding: '8px 12px', borderBottom: '1px solid var(--color-border)', display: 'flex', alignItems: 'center', gap: 8 }}>
        <div style={{ fontFamily: 'var(--font-pixel)', fontSize: 11, letterSpacing: '0.15em', color: '#fbbf24' }}>{title}</div>
        <div style={{ flex: 1 }}/>
        <code style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: 'var(--color-text-tertiary)' }}>{code}</code>
      </div>
      <div style={{
        height: 180, padding: 12,
        background: 'radial-gradient(ellipse at center, #0d0d0d 0%, #050505 100%)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        overflow: 'hidden', position: 'relative',
      }}>{children}</div>
      <div style={{ padding: '6px 12px', borderTop: '1px solid var(--color-border)', textAlign: 'right' }}>
        <a href={`#/${route}`} style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--color-text-tertiary)' }}>open in lab →</a>
      </div>
    </div>
  );
}

Object.assign(window, { SystemPage });
