/* global React */
const { useState, useEffect, useRef, useMemo } = React;

// ───────────────────────────────────────────────
// Logo mark — simple geometric hourglass with crosshair pip
// ───────────────────────────────────────────────
function LogoMark({ size = 22, accent = 'var(--accent)' }) {
  return (
    <svg className="mark" width={size} height={size} viewBox="0 0 64 64" fill="none"
         stroke="currentColor" strokeWidth="2" strokeLinecap="square">
      <line x1="14" y1="12" x2="50" y2="12"/>
      <path d="M16 12 L32 32 L48 12"/>
      <path d="M16 52 L32 32 L48 52"/>
      <line x1="14" y1="52" x2="50" y2="52"/>
      <line x1="22" y1="32" x2="42" y2="32" strokeWidth="1" opacity="0.5"/>
      <circle cx="32" cy="32" r="2.4" fill={accent} stroke="none"/>
    </svg>
  );
}

// ───────────────────────────────────────────────
// Live ticking clock — UTC HH:MM:SS, urgency cue
// ───────────────────────────────────────────────
function LiveClock() {
  const [now, setNow] = useState(() => new Date());
  useEffect(() => {
    const id = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(id);
  }, []);
  const pad = (n) => String(n).padStart(2,'0');
  const hh = pad(now.getUTCHours()), mm = pad(now.getUTCMinutes()), ss = pad(now.getUTCSeconds());
  return (
    <span className="clock" aria-label={`Current UTC time ${hh}:${mm}:${ss}`}>
      <span className="t">{hh}</span><span className="sep">:</span>
      <span className="t">{mm}</span><span className="sep">:</span>
      <span className="t blink">{ss}</span>
      <span className="tz">UTC</span>
    </span>
  );
}

// ───────────────────────────────────────────────
// Top chrome — shared across all pages
// ───────────────────────────────────────────────
function Chrome({ projectId, current = 'home', onReset }) {
  const home = (e) => {
    if (current === 'diagnostic' && onReset) {
      e.preventDefault(); onReset();
    }
  };
  return (
    <header className="chrome" role="banner">
      <a href="index.html" className="brand" onClick={home} aria-label="Time+Tokens home">
        <LogoMark/>
        <span className="name">Time<span className="plus">+</span>Tokens</span>
      </a>
      <nav className="chrome-nav" aria-label="Primary">
        <a href="index.html" className={current==='home'?'active':''}>Home</a>
        <a href="about.html" className={current==='about'?'active':''}>About</a>
        <a href="diagnostic.html" className={current==='diagnostic'?'active':''}>Diagnostic</a>
      </nav>
      <div className="chrome-meta" aria-live="off">
        <span className="hide-sm"><span className="dot"></span>Studio Open</span>
        {projectId && <span className="hide-md">Session {projectId}</span>}
        <LiveClock/>
      </div>
    </header>
  );
}

// ───────────────────────────────────────────────
// Step indicator
// ───────────────────────────────────────────────
function Steps({ current }) {
  const steps = [
    { n: '01', label: 'Intake' },
    { n: '02', label: 'Stress Test' },
    { n: '03', label: 'Compute' },
    { n: '04', label: 'Diagnostic' },
    { n: '05', label: 'Handover' },
  ];
  return (
    <nav className="steps" aria-label="Progress">
      {steps.map((s, i) => (
        <React.Fragment key={s.n}>
          <span className={`step ${i === current ? 'active' : i < current ? 'done' : ''}`}>
            <span className="num">{i < current ? '✓' : s.n}</span>
            <span className="label">{s.label}</span>
          </span>
          {i < steps.length - 1 && <span className="sep" aria-hidden="true"></span>}
        </React.Fragment>
      ))}
    </nav>
  );
}

// ───────────────────────────────────────────────
// Step 1 — Intake
// ───────────────────────────────────────────────
function StepIntake({ value, setValue, onNext }) {
  const ref = useRef(null);
  useEffect(() => { ref.current?.focus(); }, []);

  const wordCount = value.trim() ? value.trim().split(/\s+/).length : 0;
  const valid = wordCount >= 8;

  return (
    <section aria-labelledby="step1-h" className="fade">
      <div className="eyebrow left">File 01 · The Spark</div>
      <h1 className="headline" id="step1-h">
        Elite talent <em>at the speed of AI.</em>
      </h1>
      <p className="lede">
        Time<span style={{color:'var(--accent)'}}>+</span>Tokens is a tool-agnostic architectural studio for founders scaling concepts.
        We open with a diagnostic. Describe what you're building &mdash; we map the path.
      </p>

      <label htmlFor="spark" className="eyebrow left fade fade-d1">
        Prompt 01 / 02 — The Brief
      </label>
      <div className="intake fade fade-d2">
        <textarea
          id="spark"
          ref={ref}
          value={value}
          onChange={(e)=>setValue(e.target.value)}
          placeholder="What are you building? Describe the core problem you're solving…"
          rows={3}
          aria-describedby="spark-help"
        />
      </div>
      <div className="intake-foot fade fade-d3">
        <span id="spark-help">{wordCount} {wordCount === 1 ? 'word' : 'words'} · min. 8</span>
        <button className="btn accent" disabled={!valid} onClick={onNext}>
          Continue <span className="arrow">→</span>
        </button>
      </div>
    </section>
  );
}

// ───────────────────────────────────────────────
// Step 2 — Stress test
// ───────────────────────────────────────────────
function StepStress({ value, setValue, onNext, onBack }) {
  const ref = useRef(null);
  useEffect(() => { ref.current?.focus(); }, []);
  const wordCount = value.trim() ? value.trim().split(/\s+/).length : 0;
  const valid = wordCount >= 6;

  return (
    <section aria-labelledby="step2-h" className="fade">
      <div className="eyebrow left">File 02 · The Forcing Function</div>
      <h2 className="headline" id="step2-h">
        At <span className="scale" style={{
          fontFamily:'var(--mono)', fontWeight:500, fontSize:'0.62em',
          background:'var(--accent)', color:'var(--ink)', padding:'0 0.3em', whiteSpace:'nowrap'
        }}>1M users</span>, what breaks first?
      </h2>
      <p className="lede">
        The single biggest technical or operational bottleneck you anticipate at scale.
        Be specific — this calibrates the diagnostic.
      </p>

      <label htmlFor="bottleneck" className="eyebrow left fade fade-d1">
        Prompt 02 / 02 — Stress Vector
      </label>
      <div className="intake fade fade-d2">
        <textarea
          id="bottleneck"
          ref={ref}
          value={value}
          onChange={(e)=>setValue(e.target.value)}
          placeholder="e.g. Inference cost per request balloons, or Postgres write throughput on the events table…"
          rows={3}
          aria-describedby="stress-help"
        />
      </div>
      <div className="intake-foot fade fade-d3">
        <span id="stress-help">{wordCount} {wordCount === 1 ? 'word' : 'words'} · min. 6</span>
        <button className="btn ghost" onClick={onBack}>← Back</button>
        <button className="btn accent" disabled={!valid} onClick={onNext}>
          Run Diagnostic <span className="arrow">→</span>
        </button>
      </div>
    </section>
  );
}

// ───────────────────────────────────────────────
// Step 3 — Processing
// ───────────────────────────────────────────────
function StepProcessing({ onDone }) {
  const lines = useMemo(() => ([
    { label: 'Parsing concept vector',           dur: 700 },
    { label: 'Indexing architectural primitives',dur: 900 },
    { label: 'Modeling load at 10⁶ scale',       dur: 1100 },
    { label: 'Estimating token-to-time ratio',   dur: 1000 },
    { label: 'Compiling resource envelope',      dur: 800 },
  ]), []);

  const [progress, setProgress] = useState(lines.map(()=>0));
  const [active, setActive] = useState(0);

  useEffect(() => {
    let cancelled = false;
    let i = 0;
    const tick = () => {
      if (cancelled) return;
      if (i >= lines.length) {
        setTimeout(() => !cancelled && onDone(), 500);
        return;
      }
      setActive(i);
      const start = performance.now();
      const dur = lines[i].dur;
      const step = () => {
        if (cancelled) return;
        const t = Math.min(1, (performance.now() - start) / dur);
        setProgress(p => { const c = [...p]; c[i] = t; return c; });
        if (t < 1) requestAnimationFrame(step);
        else { i++; tick(); }
      };
      requestAnimationFrame(step);
    };
    tick();
    return () => { cancelled = true; };
  }, [lines, onDone]);

  return (
    <section aria-labelledby="step3-h" aria-live="polite" className="fade">
      <div className="eyebrow left">File 03 · Initialization</div>
      <h2 className="headline" id="step3-h" style={{fontSize:'clamp(28px,4vw,44px)'}}>
        Calculating resource load<span className="cursor"></span>
      </h2>
      <p className="lede">Analyzing architectural requirements and token-to-time ratios…</p>

      <div className="proc-frame fade fade-d2">
        {lines.map((l, i) => {
          const p = progress[i];
          const status = p >= 1 ? 'OK' : i === active ? 'RUN' : '—';
          const cls = p >= 1 ? 'done' : '';
          return (
            <div key={i} className={`proc-line ${cls}`}>
              <span className="label" style={{minWidth: 30, color: 'var(--graphite)'}}>0{i+1}</span>
              <div>
                <div style={{marginBottom: 6, fontSize: 12}}>{l.label}</div>
                <div className="bar" style={{'--p': `${Math.round(p*100)}%`}}></div>
              </div>
              <span className={`status ${p>=1?'ok':''}`}>{status}</span>
            </div>
          );
        })}
      </div>
    </section>
  );
}

// ───────────────────────────────────────────────
// Step 4 — Diagnostic
// ───────────────────────────────────────────────
function StepDiagnostic({ projectId, intake, stress, onNext, onBack }) {
  const data = useMemo(() => {
    const seed = (intake + stress).length;
    const r = (mod, off=0) => ((seed * 9301 + 49297 + off*7) % 233280) % mod;
    const hours = 240 + r(180);
    const phaseHours = Math.round(hours * 0.35);
    const tokens = (8 + r(22));
    const tokensSpike = (tokens * (1.4 + r(40)/100)).toFixed(1);
    const fitScore = 78 + r(18);
    const date = new Date();
    const m = String(date.getMonth()+1).padStart(2,'0');
    const d = String(date.getDate()).padStart(2,'0');
    return {
      hours, phaseHours,
      tokensM: tokens, tokensSpikeM: tokensSpike,
      fitScore,
      stamp: `${date.getFullYear()}-${m}-${d}`,
      severity: fitScore >= 88 ? 'TIER A' : fitScore >= 82 ? 'TIER B' : 'TIER C',
    };
  }, [intake, stress]);

  const assess = useMemo(() => {
    const trim = (s, n=80) => s.trim().length > n ? s.trim().slice(0, n).replace(/\s+\S*$/,'') + '…' : s.trim();
    const stressShort = trim(stress, 90);
    return {
      bottleneck: stressShort,
      fix: 'a stateless inference fabric with a write-buffered event spine, decoupling product surface from compute',
    };
  }, [stress]);

  return (
    <section aria-labelledby="step4-h" className="fade">
      <div className="eyebrow left">File 04 · Diagnostic Readout</div>
      <h2 className="headline" id="step4-h" style={{fontSize:'clamp(28px,4vw,44px)', marginBottom: 32}}>
        Architectural assessment <em>complete.</em>
      </h2>

      <article className="report" aria-label="Diagnostic readout">
        <header className="report-head">
          <div className="title-block">
            <div className="doc-type">T+T Architectural Brief / Algorithmic Baseline</div>
            <h2>Resource Estimate &amp; Bottleneck Map</h2>
          </div>
          <div className="meta">
            <div>PROJECT ID&nbsp;&nbsp;<span className="v">{projectId}</span></div>
            <div>ISSUED&nbsp;&nbsp;<span className="v">{data.stamp}</span></div>
            <div>FIT SCORE&nbsp;&nbsp;<span className="v">{data.fitScore}/100 · {data.severity}</span></div>
          </div>
        </header>

        <div className="report-section">
          <div className="sec-label"><span>§ 01 — Estimated Resource Load</span><span className="num">EST. ENVELOPE / 90-DAY</span></div>
          <table className="kvtable">
            <tbody>
              <tr>
                <th>Time<br/><span style={{fontWeight:400, fontSize:11, opacity:0.7}}>Senior Strategy + Design</span></th>
                <td><span className="v">{data.hours} hrs</span> &nbsp; architectural<br/>
                    <span className="sub">Phase 1 (foundation): {data.phaseHours} hrs · senior architect + design lead</span></td>
              </tr>
              <tr>
                <th>Tokens<br/><span style={{fontWeight:400, fontSize:11, opacity:0.7}}>Automated AI Throughput</span></th>
                <td><span className="v">{data.tokensM}M</span> tokens / month, baseline<br/>
                    <span className="sub">Burst projection at peak: {data.tokensSpikeM}M · multi-provider routing</span></td>
              </tr>
              <tr>
                <th>Strike Team<br/><span style={{fontWeight:400, fontSize:11, opacity:0.7}}>Bespoke Composition</span></th>
                <td><span className="v">3–4 operators</span> · tool-agnostic<br/>
                    <span className="sub">Lead architect + product engineer + AI eng. + (optional) design</span></td>
              </tr>
              <tr>
                <th>Cycle<br/><span style={{fontWeight:400, fontSize:11, opacity:0.7}}>Time-to-Production</span></th>
                <td><span className="v">8–12 weeks</span> to a load-bearing v1<br/>
                    <span className="sub">Deployable surface, observable, scale-ready</span></td>
              </tr>
            </tbody>
          </table>
        </div>

        <div className="report-section">
          <div className="sec-label"><span>§ 02 — Architectural Assessment</span><span className="num">PRIMARY VECTOR</span></div>
          <p className="assess">
            Identified bottleneck: <span style={{color:'var(--graphite)'}}>"{assess.bottleneck}"</span>.
            The tool-agnostic fix is <span className="lift">{assess.fix}</span> — restoring linear scale where the current path goes superlinear.
          </p>
        </div>

        <div className="report-section">
          <div className="sec-label"><span>§ 03 — Bespoke Execution Map</span><span className="num">RESTRICTED</span></div>
          <div className="locked">
            <div className="blur-list mono" aria-hidden="true">
              <div>Week 01 — Foundational schema, event spine, contract auth surfaces</div>
              <div>Week 02 — Inference router, multi-provider failover, cost telemetry</div>
              <div>Week 03 — Write-buffered ingestion, replay log, observability</div>
              <div>Week 04 — Product surface v0, internal alpha, load harness</div>
              <div>Week 05 — External beta, cohort metering, eval suites</div>
              <div>Week 06 — Production cutover, runbook, on-call rotation</div>
            </div>
            <div className="lock-overlay">
              <div className="icon" aria-hidden="true">
                <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4">
                  <rect x="3" y="7" width="10" height="7"/>
                  <path d="M5 7 V5 a3 3 0 0 1 6 0 V7"/>
                </svg>
              </div>
              <div>Locked — Bespoke Execution Map</div>
              <div style={{opacity:0.6, fontSize:10}}>Unlocked after senior architect mission-fit review</div>
            </div>
          </div>
        </div>
      </article>

      <div className="row" style={{marginTop: 32, justifyContent:'space-between'}}>
        <button className="btn ghost" onClick={onBack}>← Revise Inputs</button>
        <button className="btn accent" onClick={onNext}>
          Unlock Elite Review <span className="arrow">→</span>
        </button>
      </div>
    </section>
  );
}

// ───────────────────────────────────────────────
// Step 5 — Handover
// ───────────────────────────────────────────────
function StepHandover({ projectId, onBack, onSubmit, submitted, submitting = false, submitError = null }) {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [company, setCompany] = useState('');
  const valid = name.trim() && /\S+@\S+\.\S+/.test(email);

  if (submitted) {
    return (
      <section aria-labelledby="step5-h" className="fade">
        <div className="eyebrow left">File 05 · Handover</div>
        <h2 className="headline" id="step5-h" style={{fontSize:'clamp(28px,4vw,44px)'}}>
          Submitted for <em>mission-fit review.</em>
        </h2>

        <div className="success fade fade-d1">
          <div className="check" aria-hidden="true">✓</div>
          <h3>Project {projectId} is in queue with a senior architect.</h3>
          <p>
            If accepted, you'll receive a full Execution Map within <strong style={{color:'var(--vellum)'}}>24 hours</strong>,
            including the Bespoke Strike Team composition and a fixed-scope Phase 01 proposal.
          </p>
          <div className="divider"></div>
          <div className="mono muted">
            CONFIRMATION SENT · {email || 'you@domain.com'}<br/>
            STATUS · ALGORITHMIC BASELINE → PENDING SENIOR REVIEW
          </div>
        </div>
      </section>
    );
  }

  return (
    <section aria-labelledby="step5-h" className="fade">
      <div className="eyebrow left">File 05 · The Handover</div>
      <h2 className="headline" id="step5-h" style={{fontSize:'clamp(28px,4vw,44px)'}}>
        Unlock <em>Elite Review.</em>
      </h2>
      <p className="lede">
        This is an algorithmic baseline. Our senior architects will review your project for mission-fit.
        If accepted, you will receive a full Execution Map within 24 hours.
      </p>

      <form className="handover fade fade-d1" onSubmit={(e)=>{ e.preventDefault(); if(valid) onSubmit({name,email,company}); }}>
        <div className="field">
          <label htmlFor="h-name">Name</label>
          <input id="h-name" required value={name} onChange={e=>setName(e.target.value)} placeholder="Your full name" autoComplete="name"/>
        </div>
        <div className="field">
          <label htmlFor="h-email">Email</label>
          <input id="h-email" type="email" required value={email} onChange={e=>setEmail(e.target.value)} placeholder="founder@company.com" autoComplete="email"/>
        </div>
        <div className="field">
          <label htmlFor="h-co">Company</label>
          <input id="h-co" value={company} onChange={e=>setCompany(e.target.value)} placeholder="Working name (optional)" autoComplete="organization"/>
        </div>

        {submitError && (
          <div style={{padding: 16, background: 'rgba(220,80,80,0.1)', border: '1px solid rgba(220,80,80,0.3)', borderRadius: 4, color: '#d84848', fontSize: 14, marginBottom: 16}}>
            {submitError}
          </div>
        )}

        <div className="row" style={{justifyContent:'space-between', marginTop: 16}}>
          <button type="button" className="btn ghost" onClick={onBack} disabled={submitting}>← Back to Diagnostic</button>
          <button type="submit" className="btn accent" disabled={!valid || submitting}>
            {submitting ? 'Submitting...' : 'Submit for Review'} {!submitting && <span className="arrow">→</span>}
          </button>
        </div>
      </form>
    </section>
  );
}

// ───────────────────────────────────────────────
// Footer / socials
// ───────────────────────────────────────────────
function Foot() {
  const Icon = ({ href, d, label }) => (
    <a href={href || '#'} aria-label={label} title={label}
       target={href && href.startsWith('http') ? '_blank' : undefined}
       rel={href && href.startsWith('http') ? 'noopener noreferrer' : undefined}
       onClick={!href || href === '#' ? (e)=>e.preventDefault() : undefined}>
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="square">{d}</svg>
    </a>
  );
  return (
    <footer className="foot" role="contentinfo">
      <div>
        <div>© 2026 Time+Tokens · Tool-agnostic by design · <a href="mailto:hello@timeplustokens.com">hello@timeplustokens.com</a></div>
        <div className="foot-sub">
          A <a href="https://humanleveragegroup.com" target="_blank" rel="noopener noreferrer">Human Leverage Group</a> studio.
        </div>
      </div>
      <div className="socials" aria-label="Social links">
        <Icon href="https://x.com/timeplustokens" label="X / Twitter" d={<>
          <path d="M3 3 L21 21 M21 3 L3 21"/>
        </>}/>
        <Icon href="https://www.linkedin.com/company/timeplustokens" label="LinkedIn" d={<>
          <rect x="3" y="3" width="18" height="18"/>
          <line x1="7" y1="10" x2="7" y2="17"/>
          <circle cx="7" cy="7" r="0.6" fill="currentColor"/>
          <path d="M11 17 V11 M11 13 a3 3 0 0 1 6 0 V17"/>
        </>}/>
        <Icon href="https://github.com/timeplustokens" label="GitHub" d={<>
          <path d="M9 19 v-2 c-3 1 -4 -2 -5 -3 M15 19 v-3 a3 3 0 0 0 -1 -3 c3 0 5 -1 5 -5 a4 4 0 0 0 -1 -3 c0 -1 0 -2 -1 -3 c0 0 -2 0 -3 1 a10 10 0 0 0 -5 0 c-1 -1 -3 -1 -3 -1 c-1 1 -1 2 -1 3 a4 4 0 0 0 -1 3 c0 4 2 5 5 5 a3 3 0 0 0 -1 3 v3"/>
        </>}/>
        <Icon href="mailto:hello@timeplustokens.com" label="Email" d={<>
          <rect x="3" y="5" width="18" height="14"/>
          <path d="M3 5 L12 13 L21 5"/>
        </>}/>
      </div>
    </footer>
  );
}

Object.assign(window, {
  LogoMark, LiveClock, Chrome, Steps,
  StepIntake, StepStress, StepProcessing, StepDiagnostic, StepHandover,
  Foot,
});
