/* global React, ReactDOM, useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakToggle, Chrome, LiveClock, LogoMark, Foot */
const { useState, useEffect, useRef, useMemo } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "dark",
  "accentHue": 200,
  "showSocials": true,
  "particleSpeed": "regular"
}/*EDITMODE-END*/;

// ───────────────────────────────────────────────
// Animated Hourglass — canvas, sand particles falling continuously
// ───────────────────────────────────────────────
function HourglassCanvas({ speed = 1 }) {
  const canvasRef = useRef(null);
  const wrapRef = useRef(null);
  const stateRef = useRef({ particles: [], dpr: 1, w: 0, h: 0, t: 0 });

  useEffect(() => {
    const canvas = canvasRef.current;
    const wrap = wrapRef.current;
    if (!canvas || !wrap) return;
    const ctx = canvas.getContext('2d');
    let raf = 0;

    const setSize = () => {
      const r = wrap.getBoundingClientRect();
      const dpr = Math.min(2, window.devicePixelRatio || 1);
      stateRef.current.dpr = dpr;
      stateRef.current.w = r.width;
      stateRef.current.h = r.height;
      canvas.width = r.width * dpr;
      canvas.height = r.height * dpr;
      ctx.setTransform(dpr,0,0,dpr,0,0);
    };
    setSize();
    const ro = new ResizeObserver(setSize);
    ro.observe(wrap);

    const particles = stateRef.current.particles;
    const SPAWN_RATE = 2.4 * speed;

    const spawn = (W, H) => {
      const cx = W * 0.5;
      const yTop = H * 0.10;
      const x = cx + (Math.random() - 0.5) * (W * 0.30);
      particles.push({
        x, y: yTop + Math.random() * 4,
        vx: 0, vy: 0.4 + Math.random() * 0.4,
        phase: 'top',
        size: 0.8 + Math.random() * 1.4,
        life: 0,
        max: 600 + Math.random() * 200,
      });
    };

    const draw = () => {
      const W = stateRef.current.w, H = stateRef.current.h;
      ctx.clearRect(0,0,W,H);

      const cx = W / 2;
      const top = H * 0.08;
      const bot = H * 0.92;
      const mid = (top + bot) / 2;
      const halfW = Math.min(W * 0.36, 230);
      const neck = 6;
      const accent = getComputedStyle(document.documentElement).getPropertyValue('--accent').trim() || '#7BD9D6';

      ctx.lineWidth = 1.2;
      ctx.strokeStyle = `rgba(232,228,218,0.55)`;
      if (document.body.dataset.theme === 'light') ctx.strokeStyle = 'rgba(14,15,14,0.6)';
      ctx.beginPath();
      ctx.moveTo(cx - halfW, top); ctx.lineTo(cx + halfW, top);
      ctx.moveTo(cx - halfW, top); ctx.lineTo(cx - neck, mid);
      ctx.moveTo(cx + halfW, top); ctx.lineTo(cx + neck, mid);
      ctx.moveTo(cx - neck, mid); ctx.lineTo(cx - halfW, bot);
      ctx.moveTo(cx + neck, mid); ctx.lineTo(cx + halfW, bot);
      ctx.moveTo(cx - halfW, bot); ctx.lineTo(cx + halfW, bot);
      ctx.stroke();

      ctx.strokeStyle = `rgba(232,228,218,0.25)`;
      if (document.body.dataset.theme === 'light') ctx.strokeStyle = 'rgba(14,15,14,0.3)';
      ctx.beginPath();
      ctx.moveTo(cx - 14, mid); ctx.lineTo(cx + 14, mid);
      ctx.moveTo(cx, mid - 14); ctx.lineTo(cx, mid + 14);
      ctx.stroke();

      ctx.fillStyle = accent;
      ctx.beginPath(); ctx.arc(cx, mid, 2.4, 0, Math.PI*2); ctx.fill();
      ctx.strokeStyle = accent; ctx.lineWidth = 0.6; ctx.globalAlpha = 0.4;
      ctx.beginPath(); ctx.arc(cx, mid, 8, 0, Math.PI*2); ctx.stroke();
      ctx.globalAlpha = 1;

      for (let i = 0; i < SPAWN_RATE; i++) {
        if (Math.random() < SPAWN_RATE - i) spawn(W, H);
      }

      for (let i = particles.length - 1; i >= 0; i--) {
        const p = particles[i];
        p.life++;

        if (p.phase === 'top') {
          const dx = cx - p.x;
          const dy = mid - p.y;
          const d = Math.hypot(dx, dy) + 0.001;
          p.vx += (dx / d) * 0.04 * speed;
          p.vy += 0.05 * speed;
          p.vx *= 0.96; p.vy *= 0.99;
          p.x += p.vx; p.y += p.vy;
          const t = (p.y - top) / (mid - top);
          const wAtY = halfW * (1 - t) + neck * t;
          if (p.x < cx - wAtY) { p.x = cx - wAtY; p.vx *= -0.3; }
          if (p.x > cx + wAtY) { p.x = cx + wAtY; p.vx *= -0.3; }
          if (p.y > mid - 2) { p.phase = 'neck'; p.x = cx + (Math.random()-0.5)*3; p.vx = (Math.random()-0.5)*0.4; p.vy = 1.2 * speed; }
        } else {
          p.vy += 0.08 * speed;
          p.x += p.vx;
          p.y += p.vy;
          const t = (p.y - mid) / (bot - mid);
          const wAtY = neck * (1 - t) + halfW * t;
          if (p.x < cx - wAtY) { p.x = cx - wAtY; p.vx *= -0.4; }
          if (p.x > cx + wAtY) { p.x = cx + wAtY; p.vx *= -0.4; }
          if (p.y > bot - 1) { particles.splice(i, 1); continue; }
        }

        const isLight = document.body.dataset.theme === 'light';
        ctx.fillStyle = p.phase === 'neck' ? accent : (isLight ? 'rgba(14,15,14,0.85)' : 'rgba(232,228,218,0.9)');
        ctx.globalAlpha = p.phase === 'neck' ? 0.95 : 0.7;
        ctx.fillRect(p.x - p.size/2, p.y - p.size/2, p.size, p.size);
        ctx.globalAlpha = 1;
      }

      if (particles.length > 800) particles.splice(0, particles.length - 800);

      stateRef.current.t++;
      raf = requestAnimationFrame(draw);
    };

    raf = requestAnimationFrame(draw);

    return () => { cancelAnimationFrame(raf); ro.disconnect(); };
  }, [speed]);

  return (
    <div className="hourglass-stage" ref={wrapRef} aria-hidden="true">
      <canvas ref={canvasRef}/>
      <div className="hg-meta tl">VESSEL_01<br/><span className="v">TIME · TOKENS</span></div>
      <div className="hg-meta tr">FLOW RATE<br/><span className="v">{(speed * 142).toFixed(0)} tok/s</span></div>
      <div className="hg-meta bl">PROCESS<br/><span className="v">CONTINUOUS</span></div>
      <div className="hg-meta br">STATUS<br/><span className="v" style={{color:'var(--accent)'}}>● LIVE</span></div>
    </div>
  );
}

function Marquee() {
  const items = [
    'Tool-Agnostic by Design',
    'Bespoke Strike Teams',
    'Senior Architects · No Juniors',
    '90-Second Diagnostic',
    'Time + Tokens',
    'Built for 10⁶ Scale',
    'Fixed-Scope Phase 01',
    '24-Hour Senior Review',
  ];
  const row = (
    <span>
      {items.map((s, i) => (
        <React.Fragment key={i}>
          {s}<span className="pip"></span>
        </React.Fragment>
      ))}
    </span>
  );
  return (
    <div className="marquee-strip" aria-hidden="true">
      <div className="marquee-track">
        {row}{row}
      </div>
    </div>
  );
}

function ValueGrid() {
  const cells = [
    { n: '01 · Diagnose', t: 'Architectural Resource Estimate', d: 'In 90 seconds, get a quantified read on Time (architectural hours) and Tokens (monthly compute load) your concept will require to scale.' },
    { n: '02 · Compose', t: 'Bespoke Strike Team', d: 'No agency bench. We compose a 3–4 operator team for your specific vector — senior architect, product engineer, AI engineer, optional design.' },
    { n: '03 · Deploy', t: 'Load-Bearing v1 in 8–12 Weeks', d: 'A deployable, observable, scale-ready surface — not a prototype, not a deck. Production cutover with runbook and on-call.' },
  ];
  return (
    <section className="section">
      <div className="section-head">
        <div className="file-tag"><span className="accent">§ 01</span> · The Offer</div>
        <h2>Elite talent at <em>the speed of AI.</em><br/>Without the agency tax.</h2>
      </div>
      <div className="value-grid">
        {cells.map((c,i) => (
          <div className="value-cell" key={i}>
            <div className="num">{c.n}</div>
            <h3>{c.t}</h3>
            <p>{c.d}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

function Process() {
  const steps = [
    { n: '01', t: 'Intake', d: 'Describe what you\'re building.' },
    { n: '02', t: 'Stress Test', d: 'Identify your bottleneck at scale.' },
    { n: '03', t: 'Compute', d: 'Algorithmic baseline runs in seconds.' },
    { n: '04', t: 'Diagnostic', d: 'Resource Estimate and assessment.' },
    { n: '05', t: 'Handover', d: 'Senior architect review within 24 hrs.' },
  ];
  return (
    <section className="section" style={{paddingTop: 0}}>
      <div className="section-head">
        <div className="file-tag"><span className="accent">§ 02</span> · The Front Door</div>
        <h2>Five files. <em>Ninety seconds.</em></h2>
      </div>
      <div className="process">
        {steps.map(s => (
          <div className="proc-step" key={s.n}>
            <div className="n">FILE {s.n}</div>
            <h4>{s.t}</h4>
            <p>{s.d}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

function FinalCTA() {
  return (
    <section className="cta-final">
      <h2>The clock is the <em>only</em> renewable resource.</h2>
      <p>Open the Front Door. Get a free architectural baseline. No deck, no discovery call, no bench email.</p>
      <div style={{display:'flex', gap:16, justifyContent:'center', flexWrap:'wrap'}}>
        <a href="diagnostic.html" className="btn accent">
          Run the Diagnostic <span className="arrow">→</span>
        </a>
        <a href="about.html" className="btn">
          What you'll get
        </a>
      </div>
    </section>
  );
}

function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const speed = tweaks.particleSpeed === 'fast' ? 1.7 : tweaks.particleSpeed === 'slow' ? 0.55 : 0.65;

  useEffect(() => {
    document.body.dataset.theme = tweaks.theme;
    document.documentElement.style.setProperty('--accent', `oklch(0.82 0.08 ${tweaks.accentHue})`);
    document.documentElement.style.setProperty('--accent-dim', `oklch(0.55 0.06 ${tweaks.accentHue})`);
  }, [tweaks.theme, tweaks.accentHue]);

  return (
    <div className="app">
      <a className="skip-link" href="#main">Skip to content</a>
      <Chrome current="home"/>

      <main id="main">
        <section className="hero">
          <div className="hero-copy">
            <div className="hero-eyebrow">
              <span className="pulse-dot"></span>
              FRONT DOOR · OPEN FOR Q2/2026
            </div>
            <h1 className="mega">
              <span className="word">Elite</span>{' '}
              <span className="word">talent</span>{' '}
              <span className="word">at the</span>{' '}
              <span className="word"><em>speed</em></span>{' '}
              <span className="word"><em>of AI.</em></span>
            </h1>
            <p className="hero-lede">
              Time<span style={{color:'var(--accent)'}}>+</span>Tokens is a tool-agnostic architectural studio for founders scaling concepts.
              Open the Front Door — get a free Resource Estimate in 90 seconds.
            </p>
            <div className="cta-row">
              <a href="diagnostic.html" className="btn accent">
                Begin Diagnostic <span className="arrow">→</span>
              </a>
              <a href="about.html" className="btn">
                Tell me more
              </a>
            </div>
            <div className="hero-stats">
              <div className="stat"><div className="v">90s</div><div className="l">to baseline</div></div>
              <div className="stat"><div className="v">24h</div><div className="l">senior review</div></div>
              <div className="stat"><div className="v">8–12w</div><div className="l">to v1</div></div>
            </div>
          </div>
          <HourglassCanvas speed={speed}/>
        </section>

        <Marquee/>
        <ValueGrid/>
        <Process/>
        <FinalCTA/>
      </main>

      {tweaks.showSocials && <Foot/>}

      <TweaksPanel title="Tweaks">
        <TweakSection title="Theme">
          <TweakRadio label="Mode" value={tweaks.theme}
            options={[{value:'dark',label:'Charcoal'},{value:'light',label:'Vellum'}]}
            onChange={(v)=>setTweak('theme', v)}/>
        </TweakSection>
        <TweakSection title="Accent">
          <div style={{display:'flex', gap:8, flexWrap:'wrap'}}>
            {[{h:200,name:'Cyan'},{h:160,name:'Mint'},{h:60,name:'Amber'},{h:30,name:'Rust'},{h:340,name:'Coral'},{h:280,name:'Iris'}].map(c => (
              <button key={c.h} onClick={()=>setTweak('accentHue', c.h)} title={c.name} aria-label={`Accent ${c.name}`}
                style={{width:28, height:28, background:`oklch(0.82 0.08 ${c.h})`,
                  border: tweaks.accentHue===c.h ? '2px solid #fff' : '1px solid rgba(255,255,255,0.2)', cursor:'pointer'}}/>
            ))}
          </div>
        </TweakSection>
        <TweakSection title="Sand Flow">
          <TweakRadio label="Speed" value={tweaks.particleSpeed}
            options={[{value:'slow',label:'Slow'},{value:'regular',label:'Regular'},{value:'fast',label:'Fast'}]}
            onChange={(v)=>setTweak('particleSpeed', v)}/>
        </TweakSection>
        <TweakSection title="Layout">
          <TweakToggle label="Show footer + socials" value={tweaks.showSocials}
            onChange={(v)=>setTweak('showSocials', v)}/>
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

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