// Direction A · LAB — refined terminal aesthetic
// off-black + bone + single muted-green accent
// dense, indexed, commit-log details, mono everywhere
const { useState, useEffect } = React;

const labTheme = {
  bg: '#0a0a0a',
  panel: '#111111',
  panelAlt: '#0d0d0d',
  line: 'rgba(232,230,223,0.10)',
  lineSoft: 'rgba(232,230,223,0.06)',
  fg: '#e8e6df',
  fgDim: '#9a978e',
  muted: '#6e6b62',
  mutedDim: '#4a4842',
  accent: 'oklch(0.82 0.16 142)',  // muted phosphor green
  accentDim: 'oklch(0.55 0.12 142)',
  warn: 'oklch(0.78 0.14 65)',     // muted amber
  mono: "'JetBrains Mono', ui-monospace, monospace",
};

function useIsMobile(bp = 768) {
  const [v, setV] = useState(() => (typeof window !== 'undefined' ? window.innerWidth <= bp : false));
  useEffect(() => {
    let raf = 0;
    const onResize = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => setV(window.innerWidth <= bp));
    };
    window.addEventListener('resize', onResize);
    return () => { cancelAnimationFrame(raf); window.removeEventListener('resize', onResize); };
  }, [bp]);
  return v;
}

function scrollToIdLab(id) {
  const el = document.getElementById(id);
  if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
}

function LabRow({ children, style }) {
  return <div style={{ display:'flex', alignItems:'center', gap:8, ...style }}>{children}</div>;
}

function LabDot({ color='oklch(0.82 0.16 142)', pulse=false }) {
  return (
    <span style={{
      display:'inline-block', width:8, height:8, borderRadius:'50%',
      background:color, boxShadow:`0 0 12px ${color}`,
      animation: pulse ? 'labpulse 1.6s ease-in-out infinite' : 'none',
    }} />
  );
}

function LabNav() {
  const t = labTheme;
  const isMobile = useIsMobile();
  return (
    <div style={{
      borderBottom:`1px solid ${t.line}`,
      padding: isMobile ? '14px 18px' : '18px 56px',
      display:'flex', alignItems:'center', justifyContent:'space-between',
      gap: isMobile ? 12 : 0, flexWrap: isMobile ? 'wrap' : 'nowrap',
      fontFamily:t.mono, fontSize:13, color:t.fgDim,
      background:'rgba(10,10,10,0.85)', backdropFilter:'blur(8px)',
      position: 'sticky', top: 0, zIndex: 50,
    }}>
      <LabRow style={{gap:isMobile?10:24, flex: isMobile ? '0 0 auto' : 'initial'}}>
        <span style={{color:t.fg, fontWeight:700, letterSpacing:-0.3, fontSize: isMobile ? 15 : 13}}>
          stGVs<span style={{color:t.accent}}>_</span>
        </span>
        {!isMobile && (
          <span style={{color:t.muted, fontSize:11}}>↳ engineering studio · est. 2024</span>
        )}
      </LabRow>
      {!isMobile && (
        <LabRow style={{gap:28, fontSize:12}}>
          {['index','work','approach','writing','contact'].map((n,i) => {
            const targets = { index:'lab-sec-top', work:'lab-sec-1', approach:'lab-sec-4', writing:'lab-sec-5', contact:'lab-sec-5' };
            return (
              <span key={n} className="lab-nav-item" onClick={()=>scrollToIdLab(targets[n])} style={{color: i===0 ? t.fg : t.fgDim, cursor:'pointer'}}>
                <span style={{color:t.muted}}>{String(i).padStart(2,'0')}/</span>{n}
              </span>
            );
          })}
        </LabRow>
      )}
      <LabRow style={{gap:10, fontSize:11, flex: isMobile ? '0 0 auto' : 'initial'}}>
        <LabDot pulse />
        <span style={{color:t.fgDim}}>shipping</span>
        {!isMobile && (
          <>
            <span style={{color:t.muted}}>·</span>
            <span style={{color:t.muted}}>2 / 3 slots booked · Q3</span>
          </>
        )}
      </LabRow>
    </div>
  );
}

function LabSectionHead({ idx, label, right }) {
  const t = labTheme;
  const isMobile = useIsMobile();
  return (
    <div id={`lab-sec-${idx}`} style={{
      display:'flex',
      flexDirection: isMobile ? 'column' : 'row',
      alignItems: isMobile ? 'flex-start' : 'baseline',
      justifyContent:'space-between',
      padding: isMobile ? '0 20px' : '0 56px',
      marginTop: isMobile ? 64 : 96,
      marginBottom: isMobile ? 24 : 36,
      gap: isMobile ? 6 : 0,
      fontFamily:t.mono, fontSize:12, color:t.muted,
      borderBottom:`1px solid ${t.line}`, paddingBottom:14, scrollMarginTop:80,
    }}>
      <LabRow style={{gap:isMobile?12:18}}>
        <span style={{color:t.accent}}>//{String(idx).padStart(2,'0')}</span>
        <span style={{color:t.fg, fontSize:13, letterSpacing:0.5, textTransform:'uppercase'}}>{label}</span>
      </LabRow>
      <span style={{fontSize: isMobile ? 10 : 12}}>{right}</span>
    </div>
  );
}

function LabHero() {
  const t = labTheme;
  const isMobile = useIsMobile();
  return (
    <div style={{padding: isMobile ? '52px 20px 44px' : '120px 56px 80px', position:'relative'}}>
      {!isMobile && (
        <div style={{
          position:'absolute', inset:'0 56px', top:96, height:1,
          background:`linear-gradient(90deg, ${t.line}, transparent)`,
        }} />
      )}
      <div style={{
        display:'flex',
        flexDirection: isMobile ? 'column' : 'row',
        gap: isMobile ? 36 : 64,
        alignItems: isMobile ? 'stretch' : 'flex-start',
      }}>
        <div style={{flex:1, minWidth: 0}}>
          <div style={{
            fontFamily:t.mono, fontSize: isMobile ? 10 : 12, color:t.muted, letterSpacing:1.5,
            marginBottom: isMobile ? 22 : 32,
            display:'flex', alignItems:'center', gap: isMobile ? 8 : 14,
            flexWrap: isMobile ? 'wrap' : 'nowrap',
          }}>
            <span style={{color:t.accent}}>▸</span>
            <span>SOFTWARE · EVM · SOLANA · ML</span>
            {!isMobile && <span style={{flex:1, height:1, background:t.line}}/>}
            {!isMobile && <span>ENGINEERING STUDIO · LONDON</span>}
            {isMobile && <span style={{color:t.muted}}>· LONDON</span>}
          </div>
          <h1 style={{
            fontFamily:t.mono,
            fontSize: isMobile ? 38 : 88,
            lineHeight: isMobile ? 1.02 : 0.95,
            fontWeight:500,
            color:t.fg, margin:0,
            letterSpacing: isMobile ? -1.2 : -2.5,
          }}>
            We build software<br/>
            for <span style={{color:t.accent, fontStyle:'italic', fontWeight:400}}>hard</span> problems<br/>
            <span style={{color:t.fgDim}}>in adversarial</span><br/>
            <span style={{color:t.fgDim}}>environments<span style={{color:t.accent}}>.</span></span>
          </h1>
          <div style={{
            marginTop: isMobile ? 32 : 48,
            display:'flex', gap:12, fontFamily:t.mono, fontSize:13,
            flexWrap: 'wrap',
          }}>
            <button className="lab-cta-primary" onClick={()=>scrollToIdLab('lab-sec-5')} style={{
              background:t.accent, color:'#0a0a0a', border:'none',
              padding:'14px 22px', fontFamily:t.mono, fontSize:13, fontWeight:600,
              cursor:'pointer', display:'flex', alignItems:'center', gap:10,
              minHeight: 48,
              flex: isMobile ? '1 1 auto' : '0 0 auto',
              justifyContent: 'center',
            }}>
              <span>$ start a project</span>
              <span>→</span>
            </button>
            <button className="lab-cta-secondary" onClick={()=>scrollToIdLab('lab-sec-1')} style={{
              background:'transparent', color:t.fg, border:`1px solid ${t.line}`,
              padding:'14px 22px', fontFamily:t.mono, fontSize:13,
              cursor:'pointer', display:'flex', alignItems:'center', gap:10,
              minHeight: 48,
              flex: isMobile ? '1 1 auto' : '0 0 auto',
              justifyContent: 'center',
            }}>
              <span style={{color:t.muted}}>↳</span>
              <span>see recent work</span>
            </button>
          </div>
        </div>
        <div style={{
          width: isMobile ? '100%' : 340,
          fontFamily:t.mono, fontSize:11, color:t.fgDim,
        }}>
          <div style={{color:t.muted, fontSize:10, letterSpacing:1.5, marginBottom:14}}>// NOW</div>
          <div style={{lineHeight:1.7}}>
            <div style={{color:t.fg, marginBottom:10, fontSize:12}}>Currently building:</div>
            {[
              ['HFT arb · perps × options', 'live'],
              ['Prediction-mkt mm engine', 'live'],
              ['Solidity audit · ~22k LOC', 'wk 02/06'],
              ['ML pipeline · agentic ops', 'design'],
            ].map(([k,v],i)=>(
              <div key={i} style={{display:'flex', justifyContent:'space-between', borderBottom:`1px dashed ${t.lineSoft}`, padding:'7px 0', gap: 12}}>
                <span>{k}</span>
                <span style={{color: v==='live'?t.accent:t.muted, display:'inline-flex', alignItems:'center', gap:6, whiteSpace:'nowrap'}}>
                  {v==='live' && <LabDot pulse />}{v}
                </span>
              </div>
            ))}
          </div>
          <div style={{marginTop:28, paddingTop:20, borderTop:`1px solid ${t.line}`, fontSize:11, color:t.muted, lineHeight:1.7}}>
            <div style={{color:t.fgDim, marginBottom:6}}>CRN16078224 // London</div>
            <div>2 partners · 4 engineers · 1 designer</div>
          </div>
        </div>
      </div>

      <div style={{
        marginTop: isMobile ? 44 : 72,
        display:'grid',
        gridTemplateColumns: isMobile ? '1fr 1fr' : 'repeat(4, 1fr)',
        gap:0, border:`1px solid ${t.line}`,
      }}>
        {[
          ['LANGUAGES', 'rust · solidity · ts · python · cuda'],
          ['DOMAINS', 'defi · hft · ml · cyber · marketplaces'],
          ['ENGAGEMENT', '8 wk minimum · retainer or scope'],
          ['LATENCY', 'eu/uk · london · async-first'],
        ].map(([k,v],i)=>{
          const isRightEdge = isMobile ? (i % 2 === 1) : (i === 3);
          const isBottomRow = isMobile ? (i >= 2) : false;
          return (
            <div key={i} style={{
              padding: isMobile ? '18px 16px' : '24px 22px',
              borderRight: isRightEdge ? 'none' : `1px solid ${t.line}`,
              borderTop: isBottomRow ? `1px solid ${t.line}` : 'none',
              fontFamily:t.mono,
            }}>
              <div style={{fontSize:10, color:t.muted, letterSpacing:1.5, marginBottom:10}}>{k}</div>
              <div style={{fontSize: isMobile ? 12 : 13, color:t.fg, lineHeight:1.5}}>{v}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function LabCapabilities() {
  const t = labTheme;
  const isMobile = useIsMobile();
  const caps = [
    { id:'01', title:'Software engineering', sub:'product · platforms · infra', body:'Type-safe systems from idea to ship. React/Next/Vite on the frontend; Rust, Python, Node on the back. We sweat the build, CI, and observability so the rest stays cheap to change.', tags:['ts','rust','postgres','k8s'] },
    { id:'02', title:'Onchain · EVM / Solana', sub:'solidity · anchor · audits', body:'Smart-contract design, implementation, and adversarial review across EVM chains and Solana. Gas-optimal patterns, formal-verification-ready specs, and the audit-trail to back it up.', tags:['solidity','foundry','anchor','rust'] },
    { id:'03', title:'Trading systems', sub:'hft · arb · market-making', body:'Latency-sensitive trading on perps, options, and prediction markets. Depth-spike detection, cross-venue arb, exchange-grade order routers. We profile in nanoseconds, not p95.', tags:['hyperliquid','polymarket','deribit','cme'] },
    { id:'04', title:'Cybersecurity', sub:'audit · pentest · threat-model', body:'Adversarial review of smart contracts, web apps, and infra. Engagement formats from a 1-week sweep to a multi-month embedded review with the build team.', tags:['solidity','web','infra','wallets'] },
    { id:'05', title:'ML & agents', sub:'training · inference · ops', body:'Production ML — from data plumbing to inference cost. Lately, agentic systems with eval harnesses, tool-use orchestration, and the observability to keep them honest.', tags:['pytorch','vllm','dspy','langgraph'] },
    { id:'06', title:'Design & UX', sub:'product · brand · interaction', body:'Interfaces that earn their density. We work with design systems if you have one, and write one with you if you don\'t. Special weakness for trading UIs and high-information dashboards.', tags:['figma','tokens','motion','prototype'] },
  ];
  return (
    <div style={{padding: isMobile ? '0 20px' : '0 56px'}}>
      <div style={{
        display:'grid',
        gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr',
        gap:0, border:`1px solid ${t.line}`,
      }}>
        {caps.map((c,i)=>{
          const isRightCol = !isMobile && i%2===1;
          const isLastInDesktop = i>=4;
          const isLastInMobile = i === caps.length - 1;
          return (
            <div key={c.id} className="lab-card" style={{
              padding: isMobile ? '24px 20px' : '36px 32px',
              borderRight: isMobile || isRightCol ? 'none' : `1px solid ${t.line}`,
              borderBottom: isMobile ? (isLastInMobile ? 'none' : `1px solid ${t.line}`) : (isLastInDesktop ? 'none' : `1px solid ${t.line}`),
              position:'relative', minHeight: isMobile ? 'auto' : 230, overflow:'hidden',
            }}>
              <div style={{
                display:'flex',
                alignItems: isMobile ? 'center' : 'baseline',
                flexWrap: 'wrap',
                gap: isMobile ? 8 : 14,
                marginBottom: isMobile ? 14 : 18,
              }}>
                <span style={{fontFamily:t.mono, fontSize:11, color:t.accent}}>[{c.id}]</span>
                <span style={{fontFamily:t.mono, fontSize: isMobile ? 17 : 20, color:t.fg, letterSpacing:-0.4}}>{c.title}</span>
                {!isMobile && <span style={{flex:1, height:1, background:t.lineSoft}}/>}
                <span style={{fontFamily:t.mono, fontSize:10, color:t.muted, letterSpacing:1, flexBasis: isMobile ? '100%' : 'auto'}}>{c.sub.toUpperCase()}</span>
              </div>
              <div style={{fontFamily:t.mono, fontSize: isMobile ? 12 : 13, lineHeight:1.65, color:t.fgDim, marginBottom: isMobile ? 16 : 22}}>{c.body}</div>
              <div style={{display:'flex', gap:6, flexWrap:'wrap'}}>
                {c.tags.map(tag=>(
                  <span key={tag} className="lab-tag" style={{
                    fontFamily:t.mono, fontSize:10, color:t.muted, letterSpacing:0.5,
                    border:`1px solid ${t.line}`, padding:'3px 8px', borderRadius:2,
                  }}>{tag}</span>
                ))}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function LabWork() {
  const t = labTheme;
  const isMobile = useIsMobile();
  const rows = [
    { hash:'a1f3c9', name:'Hyperliquid options arb', client:'undisclosed prop desk', tag:'hft', period:'2025.11 — present', status:'live', metric:'+9.4 sharpe' },
    { hash:'b7e221', name:'Polymarket depth-spike mm', client:'undisclosed', tag:'mm', period:'2025.08 — 2026.02', status:'shipped', metric:'$2.1m volume / wk' },
    { hash:'c0d4ee', name:'L2 bridge · solidity audit', client:'eco-grant', tag:'audit', period:'2026.01 — 2026.03', status:'shipped', metric:'4 highs · 12 mediums' },
    { hash:'d8a905', name:'Multi-vendor marketplace', client:'consumer brand', tag:'product', period:'2025.05 — 2025.12', status:'shipped', metric:'12k merchants' },
    { hash:'e3b67c', name:'AI fund-manager dashboard', client:'family office', tag:'ml/product', period:'2026.02 — present', status:'live', metric:'$140m aum' },
    { hash:'f5912a', name:'Casino game engine', client:'gaming co.', tag:'product/sec', period:'2025.03 — 2025.09', status:'shipped', metric:'140k DAU' },
  ];

  if (isMobile) {
    return (
      <div style={{padding:'0 20px', display:'flex', flexDirection:'column', gap:10}}>
        {rows.map(r=>(
          <div key={r.hash} className="lab-card" style={{
            border:`1px solid ${t.line}`, padding:'16px 16px', background:t.panelAlt,
            fontFamily:t.mono,
          }}>
            <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:10}}>
              <span style={{color:t.muted, fontSize:11}}>#{r.hash}</span>
              <span style={{
                display:'flex', alignItems:'center', gap:6, fontSize:10, letterSpacing:1,
                textTransform:'uppercase', color: r.status==='live'?t.accent:t.fgDim,
              }}>
                <LabDot color={r.status==='live'?t.accent:t.muted} pulse={r.status==='live'} />
                {r.status}
              </span>
            </div>
            <div style={{fontSize:15, color:t.fg, marginBottom:6, lineHeight:1.3}}>{r.name}</div>
            <div style={{fontSize:11, color:t.fgDim, marginBottom:14}}>{r.client}</div>
            <div style={{display:'flex', justifyContent:'space-between', gap:8, fontSize:10, paddingTop:10, borderTop:`1px dashed ${t.lineSoft}`}}>
              <span style={{color:t.muted, letterSpacing:1, textTransform:'uppercase'}}>{r.tag}</span>
              <span style={{color:t.fgDim}}>{r.period}</span>
            </div>
            <div style={{marginTop:10, color:t.accent, fontSize:13, textAlign:'right'}}>{r.metric}</div>
          </div>
        ))}
      </div>
    );
  }

  return (
    <div style={{padding:'0 56px'}}>
      <div style={{
        fontFamily:t.mono, fontSize:11, color:t.muted, display:'grid',
        gridTemplateColumns:'80px 1fr 220px 80px 140px 90px 170px',
        padding:'12px 18px', borderBottom:`1px solid ${t.line}`, letterSpacing:1,
      }}>
        <span>HASH</span><span>ENGAGEMENT</span><span>CLIENT</span>
        <span>TAG</span><span>PERIOD</span><span>STATUS</span><span style={{textAlign:'right'}}>METRIC</span>
      </div>
      {rows.map((r,i)=>(
        <div key={r.hash} className="lab-row" style={{
          fontFamily:t.mono, fontSize:13, color:t.fg, display:'grid',
          gridTemplateColumns:'80px 1fr 220px 80px 140px 90px 170px',
          padding:'18px 18px', borderBottom:`1px solid ${t.lineSoft}`, alignItems:'center',
        }}>
          <span style={{color:t.muted}}>#{r.hash}</span>
          <span>{r.name}</span>
          <span style={{color:t.fgDim}}>{r.client}</span>
          <span style={{color:t.muted, fontSize:10, letterSpacing:1, textTransform:'uppercase'}}>{r.tag}</span>
          <span style={{color:t.fgDim, fontSize:12}}>{r.period}</span>
          <span style={{display:'flex', alignItems:'center', gap:6, fontSize:11, color: r.status==='live'?t.accent:t.fgDim}}>
            <LabDot color={r.status==='live'?t.accent:t.muted} pulse={r.status==='live'} />
            {r.status}
          </span>
          <span style={{textAlign:'right', color:t.accent, whiteSpace:'nowrap'}}>{r.metric}</span>
        </div>
      ))}
    </div>
  );
}

function LabCaseStudies() {
  const t = labTheme;
  const isMobile = useIsMobile();
  const studies = [
    {
      idx:'A',
      title:'Cross-venue perp/options arb',
      kicker:'hft · 18 mo · with prop desk (undisclosed)',
      body:'Built a low-latency arb engine straddling Hyperliquid perps and Deribit options. Custom orderbook reconstruction, in-process risk, and a co-located router. From research notebook to production in 14 weeks.',
      stats:[['+9.4', 'sharpe (lifetime)'], ['<150μs','tick→order'], ['~$2.1B','notional (TTM)']],
      schematic:[
        '[ HYPERLIQUID ] ──┐',
        '                  ├─▶ [ ROUTER ] ─▶ [ HEDGE ]',
        '[ DERIBIT     ] ──┘        │',
        '         ▲                 ▼',
        '         └── risk ◀── [ STATE ]',
      ],
    },
    {
      idx:'B',
      title:'Prediction-market depth-spike mm',
      kicker:'mm · 6 mo · self-funded',
      body:'A market-making system for Polymarket that quotes around detected depth anomalies. Designed to extract a measurable edge from large-event order-flow without leaning on insider information.',
      stats:[['$2.1m','weekly volume'], ['62 bps','realised edge'], ['98.4%','uptime']],
      schematic:[
        'event ─▶ orderbook ─▶ depth Δ',
        '             │            │',
        '             ▼            ▼',
        '         fills ◀── [ QUOTE ENGINE ]',
        '                          │',
        '                          ▼',
        '                        risk',
      ],
    },
    {
      idx:'C',
      title:'AI fund-manager dashboard',
      kicker:'product/ml · ongoing · single-family office, $140m AUM',
      body:'A single-pane-of-glass dashboard for a discretionary multi-strategy book. Real-time PnL, risk decomposition, and an agentic assistant that drafts the daily commentary. Built on top of their existing risk pipe.',
      stats:[['$140m','aum tracked'], ['~340','positions'], ['<2s','agent latency']],
      schematic:[
        'risk pipe ─┐',
        'positions ─┼─▶ [ AGG ] ─▶ [ LLM AGENT ]',
        'prices    ─┘                    │',
        '                                ├─▶ dashboard',
        '                                └─▶ daily memo',
      ],
    },
  ];
  return (
    <div style={{
      padding: isMobile ? '0 20px' : '0 56px',
      display:'grid',
      gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr 1fr',
      gap: isMobile ? 12 : 16,
    }}>
      {studies.map(s=>(
        <div key={s.idx} className="lab-card" style={{
          border:`1px solid ${t.line}`, background:t.panel,
          padding: isMobile ? '20px 18px' : '28px 26px',
          display:'flex', flexDirection:'column', gap:0, position:'relative', overflow:'hidden',
        }}>
          <div style={{
            height: isMobile ? 140 : 160, marginBottom: isMobile ? 18 : 24,
            border:`1px solid ${t.line}`,
            background:`repeating-linear-gradient(135deg, transparent 0 6px, ${t.lineSoft} 6px 7px)`,
            padding:'24px 16px 14px', position:'relative', overflow:'auto',
          }}>
            <div style={{position:'absolute', top:10, left:14, fontFamily:t.mono, fontSize:10, color:t.muted, letterSpacing:1}}>FIG · {s.idx}</div>
            <pre style={{
              margin:0, fontFamily:t.mono, fontSize: isMobile ? 10 : 11, lineHeight:1.5,
              color:t.fgDim, whiteSpace:'pre',
            }}>{s.schematic.join('\n')}</pre>
          </div>
          <div style={{fontFamily:t.mono, fontSize:11, color:t.accent, letterSpacing:1, marginBottom:10}}>CASE · {s.idx}</div>
          <div style={{fontFamily:t.mono, fontSize: isMobile ? 19 : 22, color:t.fg, lineHeight:1.2, letterSpacing:-0.4, marginBottom:8}}>{s.title}</div>
          <div style={{fontFamily:t.mono, fontSize:11, color:t.muted, marginBottom:18}}>{s.kicker}</div>
          <div style={{fontFamily:t.mono, fontSize:12, color:t.fgDim, lineHeight:1.65, marginBottom:22}}>{s.body}</div>
          <div style={{borderTop:`1px solid ${t.line}`, paddingTop:18, display:'flex', gap: isMobile ? 12 : 16}}>
            {s.stats.map(([n,l])=>(
              <div key={l} style={{flex:1, minWidth: 0}}>
                <div style={{fontFamily:t.mono, fontSize: isMobile ? 16 : 18, color:t.fg, letterSpacing:-0.4}}>{n}</div>
                <div style={{fontFamily:t.mono, fontSize:10, color:t.muted, letterSpacing:0.5, marginTop:4, lineHeight: 1.3}}>{l}</div>
              </div>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

function LabStack() {
  const t = labTheme;
  const isMobile = useIsMobile();
  const groups = [
    ['LANG', ['rust','typescript','python','solidity','huff','cuda','go']],
    ['FRAMEWORK', ['next.js','vite','foundry','pytorch','vllm','tokio','tonic']],
    ['DATA', ['postgres','clickhouse','redis','kafka','duckdb','parquet']],
    ['INFRA', ['k8s','nix','terraform','cloudflare','aws','tailscale']],
    ['ONCHAIN', ['evm','solana','op-stack','anchor','hyperliquid','permit2']],
    ['DESIGN', ['figma','tokens','motion','tldraw','rive']],
  ];
  return (
    <div style={{padding: isMobile ? '0 20px' : '0 56px'}}>
      <div style={{
        display:'grid',
        gridTemplateColumns: isMobile ? '1fr' : 'repeat(3, 1fr)',
        gap:0, border:`1px solid ${t.line}`,
      }}>
        {groups.map((g,i)=>{
          const isRightEdge = !isMobile && i%3===2;
          const isLastRow = !isMobile && i>=3;
          const isLastMobile = isMobile && i === groups.length - 1;
          return (
            <div key={g[0]} style={{
              padding: isMobile ? '20px 20px' : '26px 26px',
              borderRight: isMobile || isRightEdge ? 'none' : `1px solid ${t.line}`,
              borderBottom: isMobile ? (isLastMobile ? 'none' : `1px solid ${t.line}`) : (isLastRow ? 'none' : `1px solid ${t.line}`),
            }}>
              <div style={{fontFamily:t.mono, fontSize:11, color:t.accent, letterSpacing:1.5, marginBottom:18}}>// {g[0]}</div>
              <div style={{display:'flex', flexWrap:'wrap', gap:'10px 14px'}}>
                {g[1].map(tag=>(
                  <span key={tag} style={{fontFamily:t.mono, fontSize:13, color:t.fg}}>
                    <span style={{color:t.muted}}>·</span> {tag}
                  </span>
                ))}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function LabApproach() {
  const t = labTheme;
  const isMobile = useIsMobile();
  const steps = [
    { n:'00', when:'wk 0', title:'Discovery call', body:'Free 45 min. We figure out if you have a real problem and if we are the right shape of team for it. Most engagements start here.' },
    { n:'01', when:'wk 1', title:'Scoping memo', body:'A 3–5 page memo with the problem stated back to you, the proposed shape of the solution, the risks, and the cost envelope. You keep the memo whether or not we proceed.' },
    { n:'02', when:'wk 2', title:'Build kickoff', body:'Repo, CI, observability and a working spike in your hands inside the first sprint. We optimise for the first deploy, not the first architecture diagram.' },
    { n:'03', when:'wk N', title:'Ship · review · ship', body:'Weekly demos. Public commit log. Async by default, synchronous when it matters. No status reports — just the build.' },
    { n:'04', when:'eos',  title:'Handover', body:'Working software, runbooks, a 30-day warranty, and a recommendation on whether to keep us, hire, or both. We are happy to write ourselves out of the picture.' },
  ];
  return (
    <div style={{padding: isMobile ? '0 20px' : '0 56px'}}>
      <div style={{border:`1px solid ${t.line}`}}>
        {steps.map((s,i)=>(
          <div key={s.n} className="lab-step" style={{
            display: isMobile ? 'flex' : 'grid',
            flexDirection: isMobile ? 'column' : undefined,
            gridTemplateColumns: isMobile ? undefined : '90px 100px 1fr 1fr',
            gap: isMobile ? 8 : 32,
            padding: isMobile ? '22px 20px' : '30px 32px',
            borderBottom: i<steps.length-1 ? `1px solid ${t.line}` : 'none',
            alignItems: isMobile ? 'flex-start' : 'baseline',
          }}>
            {isMobile ? (
              <>
                <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 4}}>
                  <span style={{fontFamily:t.mono, fontSize:12, color:t.accent}}>commit/{s.n}</span>
                  <span style={{fontFamily:t.mono, fontSize:10, color:t.muted, letterSpacing:1}}>{s.when.toUpperCase()}</span>
                </div>
                <span style={{fontFamily:t.mono, fontSize:18, color:t.fg, letterSpacing:-0.4, marginBottom: 6}}>{s.title}</span>
                <span style={{fontFamily:t.mono, fontSize:12, color:t.fgDim, lineHeight:1.6}}>{s.body}</span>
              </>
            ) : (
              <>
                <span style={{fontFamily:t.mono, fontSize:13, color:t.accent}}>commit/{s.n}</span>
                <span style={{fontFamily:t.mono, fontSize:11, color:t.muted, letterSpacing:1}}>{s.when.toUpperCase()}</span>
                <span style={{fontFamily:t.mono, fontSize:22, color:t.fg, letterSpacing:-0.4}}>{s.title}</span>
                <span style={{fontFamily:t.mono, fontSize:13, color:t.fgDim, lineHeight:1.65}}>{s.body}</span>
              </>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

function LabContact() {
  const t = labTheme;
  const isMobile = useIsMobile();
  return (
    <div style={{padding: isMobile ? '0 20px' : '0 56px'}}>
      <div style={{
        display:'grid',
        gridTemplateColumns: isMobile ? '1fr' : '1.1fr 1fr',
        gap: isMobile ? 36 : 48,
        alignItems:'start',
      }}>
        <div>
          <div style={{fontFamily:t.mono, fontSize:13, color:t.muted, marginBottom:8}}>
            <span style={{color:t.accent}}>$</span><span className="lab-caret" style={{color:t.accent}}>_</span> ssh stgvs.com — initiate engagement
          </div>
          <h2 style={{
            fontFamily:t.mono,
            fontSize: isMobile ? 34 : 56,
            lineHeight:1, color:t.fg,
            margin:'0 0 24px',
            letterSpacing: isMobile ? -1 : -1.5, fontWeight:500,
          }}>
            Tell us what<br/>you're <span style={{color:t.accent, fontStyle:'italic'}}>actually</span> building.
          </h2>
          <div style={{fontFamily:t.mono, fontSize:14, color:t.fgDim, lineHeight:1.65, maxWidth:480}}>
            Write a paragraph, not a brief. Code, repos, prior memos — drop them all in. We read everything before we reply.
          </div>
          <div style={{marginTop:36, fontFamily:t.mono, fontSize:12, color:t.muted, lineHeight:2}}>
            <div>→ <a href="mailto:work@stgvs.com" style={{color:t.fg, textDecoration:'none'}}>work@stgvs.com</a></div>
          </div>
        </div>
        <div style={{
          border:`1px solid ${t.line}`, background:t.panel,
          padding: isMobile ? 22 : 28,
          fontFamily:t.mono, fontSize:12,
        }}>
          <div style={{color:t.muted, marginBottom:18, fontSize:10, letterSpacing:1.5}}>STGVS@INTAKE:~$ new_engagement</div>
          {[
            ['name', '_'],
            ['org', 'your fund / co.'],
            ['budget', '> $50k · > $200k · > $500k · open'],
            ['timeline', 'when does this need to ship'],
            ['describe', 'paragraph + links · 60s of your voice memo also fine'],
          ].map(([k,v],i)=>(
            <div key={k} style={{
              marginBottom:18, borderBottom:`1px solid ${t.lineSoft}`, paddingBottom:14,
            }}>
              <div style={{color:t.accent, marginBottom:8}}>:: {k}</div>
              <div style={{color:t.fgDim, minHeight: i===4?80:16, lineHeight:1.6}}>{v}</div>
            </div>
          ))}
          <button className="lab-cta-primary" onClick={()=>{window.location.href='mailto:work@stgvs.com?subject=Project%20inquiry'}} style={{
            background:t.accent, color:'#0a0a0a', border:'none',
            padding:'14px 18px', fontFamily:t.mono, fontSize:12, fontWeight:600,
            cursor:'pointer', width:'100%', textAlign:'left', minHeight: 48,
          }}>
            ▸ submit · we reply within 48h
          </button>
        </div>
      </div>
    </div>
  );
}

function LabFooter() {
  const t = labTheme;
  const isMobile = useIsMobile();
  return (
    <div style={{
      marginTop: isMobile ? 80 : 120,
      padding: isMobile ? '32px 20px 24px' : '40px 56px 32px',
      borderTop:`1px solid ${t.line}`,
      fontFamily:t.mono, fontSize:11, color:t.muted,
      display:'flex',
      flexDirection: isMobile ? 'column' : 'row',
      justifyContent:'space-between',
      alignItems: isMobile ? 'flex-start' : 'flex-end',
      gap: isMobile ? 18 : 0,
    }}>
      <div>
        <div style={{color:t.fg, fontSize:13, marginBottom:6}}>stGVs<span style={{color:t.accent}}>_</span> — engineering studio</div>
        <div>CRN16078224 // London</div>
        <div style={{marginTop:4}}>© 2026 · all rights reserved</div>
      </div>
      <div style={{textAlign: isMobile ? 'left' : 'right', lineHeight:1.8}}>
        <div>CRN16078224 // London</div>
        <div><a href="mailto:work@stgvs.com" style={{color:t.accent, textDecoration:'none'}}>work@stgvs.com</a></div>
      </div>
    </div>
  );
}

function LabDirection() {
  const t = labTheme;
  return (
    <div id="lab-sec-top" style={{
      width:'100%', minHeight:'100%', background:t.bg, color:t.fg,
      fontFamily:t.mono, position:'relative', overflowX: 'hidden',
    }}>
      <style>{`
        @keyframes labpulse {
          0%, 100% { opacity: 1; transform: scale(1); }
          50% { opacity: 0.5; transform: scale(0.85); }
        }
        @keyframes labfadeup {
          0% { opacity: 0; transform: translateY(18px); }
          100% { opacity: 1; transform: translateY(0); }
        }
        @keyframes labblink { 0%,100% { opacity: 1; } 50% { opacity: 0.35; } }
        @keyframes labscan {
          0% { transform: translateX(-100%); }
          100% { transform: translateX(100%); }
        }

        /* entrance: stagger hero + sections */
        #lab-sec-top > *:not(style):not([aria-hidden]) {
          animation: labfadeup 0.7s cubic-bezier(0.2, 0.7, 0.2, 1) both;
        }
        #lab-sec-top > *:nth-child(2) { animation-delay: 0.05s; }
        #lab-sec-top > *:nth-child(3) { animation-delay: 0.10s; }
        #lab-sec-top > *:nth-child(4) { animation-delay: 0.15s; }

        /* nav items: underline-grow on hover */
        .lab-nav-item { position: relative; transition: color 0.2s ease; }
        .lab-nav-item::after {
          content: ''; position: absolute; left: 0; right: 100%; bottom: -6px; height: 1px;
          background: oklch(0.82 0.16 142); transition: right 0.25s cubic-bezier(0.2, 0.7, 0.2, 1);
        }
        .lab-nav-item:hover { color: #e8e6df; }
        .lab-nav-item:hover::after { right: 0; }

        /* primary CTA: shimmer + lift */
        .lab-cta-primary {
          position: relative; overflow: hidden;
          transition: transform 0.2s ease, box-shadow 0.2s ease, filter 0.2s ease;
        }
        .lab-cta-primary:hover {
          transform: translateY(-1px);
          box-shadow: 0 8px 28px -8px oklch(0.82 0.16 142 / 0.55);
          filter: brightness(1.05);
        }
        .lab-cta-primary::before {
          content: ''; position: absolute; inset: 0;
          background: linear-gradient(90deg, transparent, rgba(255,255,255,0.35), transparent);
          transform: translateX(-100%);
        }
        .lab-cta-primary:hover::before { animation: labscan 0.8s ease; }

        .lab-cta-secondary {
          transition: border-color 0.2s ease, color 0.2s ease, background 0.2s ease, transform 0.2s ease;
        }
        .lab-cta-secondary:hover {
          border-color: rgba(232,230,223,0.35);
          background: rgba(232,230,223,0.03);
          transform: translateY(-1px);
        }

        /* work-log rows */
        .lab-row { transition: background 0.2s ease, padding-left 0.2s ease; }
        .lab-row:hover { background: rgba(232,230,223,0.025); padding-left: 26px; }

        /* capability + case-study + stack cards */
        .lab-card { transition: background 0.25s ease, transform 0.25s ease, border-color 0.25s ease; position: relative; }
        .lab-card:hover { background: rgba(232,230,223,0.02); }
        .lab-card::before {
          content: ''; position: absolute; left: 0; top: 0; bottom: 0; width: 2px;
          background: oklch(0.82 0.16 142); transform: scaleY(0); transform-origin: top;
          transition: transform 0.35s cubic-bezier(0.2, 0.7, 0.2, 1);
        }
        .lab-card:hover::before { transform: scaleY(1); }

        .lab-tag { transition: color 0.2s ease, border-color 0.2s ease, background 0.2s ease; }
        .lab-tag:hover {
          color: #e8e6df; border-color: rgba(232,230,223,0.25);
          background: rgba(232,230,223,0.04);
        }

        /* approach commit rows */
        .lab-step { transition: background 0.25s ease; }
        .lab-step:hover { background: rgba(232,230,223,0.02); }

        /* caret blink for the "$" prompts */
        .lab-caret { animation: labblink 1.1s steps(2, end) infinite; }

        /* Touch devices: kill all hover-stuck states and add big tap targets */
        @media (hover: none) {
          .lab-nav-item:hover { color: inherit; }
          .lab-nav-item:hover::after { right: 100%; }
          .lab-cta-primary:hover { transform: none; box-shadow: none; filter: none; }
          .lab-cta-primary:hover::before { animation: none; }
          .lab-cta-secondary:hover { transform: none; background: transparent; border-color: rgba(232,230,223,0.10); }
          .lab-row:hover { background: transparent; padding-left: 18px; }
          .lab-card:hover { background: transparent; }
          .lab-card:hover::before { transform: scaleY(0); }
          .lab-tag:hover { color: #6e6b62; background: transparent; border-color: rgba(232,230,223,0.10); }
          .lab-step:hover { background: transparent; }
          button, .lab-nav-item, .lab-cta-primary, .lab-cta-secondary, .lab-tag, .lab-row, .lab-card { touch-action: manipulation; }
        }

        @media (prefers-reduced-motion: reduce) {
          *, *::before, *::after { animation: none !important; transition: none !important; }
        }
      `}</style>
      {/* background grain */}
      <div aria-hidden="true" style={{
        position:'absolute', inset:0, pointerEvents:'none',
        backgroundImage:`radial-gradient(circle at 1px 1px, rgba(232,230,223,0.025) 1px, transparent 0)`,
        backgroundSize:'24px 24px',
      }}/>
      <LabNav />
      <LabHero />
      <LabSectionHead idx={0} label="Capabilities · what we do" right="06 · disciplines" />
      <LabCapabilities />
      <LabSectionHead idx={1} label="Current work · engagement log" right="last 12 mo · 6 of ~14" />
      <LabWork />
      <LabSectionHead idx={2} label="Case studies · selected" right="↳ longer write-ups on request" />
      <LabCaseStudies />
      <LabSectionHead idx={3} label="Stack · tools we reach for first" right="opinionated · evolving" />
      <LabStack />
      <LabSectionHead idx={4} label="Approach · how engagements run" right="5 phases · weekly demos" />
      <LabApproach />
      <LabSectionHead idx={5} label="Contact · initiate a session" right="↳ work@stgvs.com" />
      <LabContact />
      <LabFooter />
    </div>
  );
}

window.LabDirection = LabDirection;
