/* global React, MotionCanvas, IsometricInfra */
const { useState, useEffect } = React;

/* ---------------- NAV ---------------- */
function Nav() {
  return (
    <nav className="vt-nav">
      <div className="vt-nav__inner">
        <div className="vt-nav__brand">
          <img src="assets/logo-mark-inverse.svg" height="32" alt="" style={{display:'block'}}/>
          <span className="wordmark">Vectory</span>
        </div>
        <div className="vt-nav__links">
          <a href="#why">Why Vectory</a>
          <a href="#services">Services</a>
          <a href="#framework">Framework</a>
          <a href="#platform">Platform</a>
          <a href="#about">About</a>
        </div>
        <div className="vt-nav__ticker">
          <span className="dot"/>
          <span>Q2 · 2 spots open</span>
        </div>
      </div>
    </nav>
  );
}

/* ---------------- HERO ---------------- */
function Hero({ motionType, speed, density, onCycle }) {
  const ORDER = ['harmonograph','lissajous','field','torus','lorenz','rose','fourier','dejong','phyllotaxis'];
  const [anim, setAnim] = useState({ phase: 'in', key: 0 });
  const cycle = () => {
    const next = ORDER[(ORDER.indexOf(motionType)+1) % ORDER.length];
    setAnim({ phase: 'out', key: anim.key });
    setTimeout(() => {
      onCycle(next);
      setAnim({ phase: 'enter', key: anim.key + 1 });
      requestAnimationFrame(() => requestAnimationFrame(() => setAnim({ phase: 'in', key: anim.key + 1 })));
    }, 450);
  };
  return (
    <header className="vt-hero">
      <div className="vt-hero__copy">
        <div className="vt-hero__eyebrow">Boutique AI Consulting · Outcome Pricing</div>
        <h1>Your AI energy<br/>needs a <em>direction.</em></h1>
        <p className="vt-hero__sub">
          Every business has AI excitement right now. The ones winning have direction.
          Vectory turns ambition into measurable outcomes in weeks, not quarters.
        </p>
        <div className="vt-hero__meta">
          <div className="line"><span className="k">Method</span><span className="v">Baseline → Define → Build → Deploy → Assess</span></div>
          <div className="line"><span className="k">Pricing</span><span className="v">No outcomes, no charge</span></div>
          <div className="line"><span className="k">Who</span><span className="v">$20M–$250M operators</span></div>
        </div>
        <div className="vt-hero__cta">
          <a className="vt-btn vt-btn--primary" href="Direction Score.html">Get your Direction Score <span className="ar">→</span></a>
          <a className="vt-btn vt-btn--on-dark" href="Apply.html">Apply to work with us</a>
        </div>
      </div>
      <div className="vt-hero__motion">
        <div key={anim.key} className={`vt-hero__motion-stage vt-hero__motion-stage--${anim.phase}`}>
          <MotionCanvas type={motionType} speed={speed} density={density} background="ink"/>
        </div>
        <div className="vt-hero__corner vt-hero__corner--tl"/>
        <button className="vt-hero__motion-label" onClick={cycle} title="Click to cycle equation">
          <span className="dot"/>
          <span>Signal · {labelFor(motionType)}</span>
          <span className="cycle-ar">→</span>
        </button>
        <Readout type={motionType}/>
      </div>
    </header>
  );
}
function labelFor(t) {
  return { harmonograph: 'Harmonograph', lissajous: 'Lissajous 5:3', field: 'Vector field', torus: 'Parametric torus',
           lorenz: 'Lorenz attractor', rose: 'Maurer rose', fourier: 'Fourier epicycles', dejong: 'De Jong attractor', phyllotaxis: 'Phyllotaxis φ' }[t] || '—';
}
function Readout({ type }) {
  const [tick, setTick] = useState(0);
  useEffect(() => { const i = setInterval(() => setTick(v => v+1), 800); return () => clearInterval(i); }, []);
  const lines = {
    harmonograph: [['A₁', '1.00'], ['ω', '2.01, 3.00'], ['decay', '0.002']],
    lissajous:    [['ratio', '5 : 3'], ['φ', (Math.sin(tick*0.08)*Math.PI).toFixed(2)], ['A', '0.38·min']],
    field:        [['N', '180'], ['∂x', 'cos(0.006y + 0.3t)'], ['σ', '0.08 signal']],
    torus:        [['R', '1.00'], ['r', '0.42'], ['ω', 'y=0.3, x=sin(0.25t)']],
    lorenz:       [['σ', '10'], ['ρ', '28'], ['β', '8/3']],
    rose:         [['r', 'cos(n·θ)'], ['n', '6'], ['d', '29']],
    fourier:      [['N', '11 harmonics'], ['f', 'Σ sin(kωt)/k'], ['shape', 'square']],
    dejong:       [['a,b', '1.40, −2.30'], ['c,d', '1.60, −0.30'], ['N', '12k']],
    phyllotaxis:  [['φ', '137.5°'], ['r', 'c√n'], ['N', '900']],
  };
  const L = lines[type] || [];
  return (
    <div className="vt-hero__motion-readout">
      {L.map((row, i) => <div key={i}><span style={{color:'#858B9A'}}>{row[0]}</span> <b>{row[1]}</b></div>)}
    </div>
  );
}

/* ---------------- MISSION BAND (ember) ---------------- */
function Mission() {
  return (
    <section className="vt-mission">
      <div className="vt-mission__inner">
        <p>Vectory turns AI curiosity into compounding outcomes. You bring the business. We bring the <em>method</em>, the measurement, and the promise not to bill until the dashboard moves.</p>
      </div>
    </section>
  );
}

/* ---------------- SERVICES ACCORDION ---------------- */
function Services({ motionType, speed, density }) {
  const svcs = [
    { name: 'Engineering team transformation', metric: 'Ship 3× faster', deliv: ['AI-augmented dev workflow','Automated review pipelines','Test-gen + coverage audit','Velocity baseline'], body: 'The engineering team is where AI ROI becomes legible. We rebuild the workflow — review, testing, deployment — around AI-augmented steps, then measure throughput against your pre-engagement baseline.' },
    { name: 'GTM engineering', metric: 'Cut prospecting time 80%', deliv: ['ICP + intent model','Outreach orchestration','Pipeline reporting','SDR deprecation plan'], body: 'Sales motion rebuilt around signal, not activity. AI lead research, personalised outreach at scale, and RevOps automation turn your GTM team into a precision instrument. You ship fewer emails. You book more calls.' },
    { name: 'Finance operations', metric: 'Close 5 days faster', deliv: ['AP/AR automation','AI-assisted forecasting','Exception routing','Audit trail'], body: 'Your controllers are expensive judgement. We route everything else — reconciliation, categorisation, exception handling — to systems that don\'t need sleep. The books close faster. The team does the work that actually requires a brain.' },
    { name: 'Customer intelligence', metric: 'Know before they ask', deliv: ['Voice-of-customer synthesis','Churn signal model','Retention playbooks','Product feedback loop'], body: 'Support tickets, reviews, sales calls, and CS notes are a goldmine you\'re not mining. We build the pipes that turn unstructured customer noise into a weekly ranked list of what to fix, what to build, and who to call.' },
    { name: 'Executive AI coaching', metric: 'Lead the shift', deliv: ['1:1 cadence','Decision frameworks','Weekly reading list','Team cascading'], body: 'The hardest part of the AI transition is the founder\'s own fluency. One hour a week, direct 1:1 with an executive who has lived it. No deck. No framework-of-the-month. Just the specific decisions sitting on your desk this week — and how to make them faster.' },
    { name: 'AI readiness assessment', metric: '2-week baseline', deliv: ['Process map','Top-3 opportunities','Feasibility score','Go / no-go memo'], body: 'Before you hire, before you buy, before you commit — a two-week baseline of your operations. You leave with three ranked opportunities, a feasibility score, and the honest assessment of whether Vectory is the right next step. Often, it isn\'t.' },
  ];
  const [open, setOpen] = useState(0);
  return (
    <section id="services" className="vt-section">
      <div className="vt-container">
        <div className="vt-acc">
          <div className="vt-acc__side">
            <div className="vt-eyebrow">Where we work</div>
            <h2>Outcomes first.<br/>Always.</h2>
            <p>Every engagement opens with a baseline and closes with a measurement. If the number doesn't move, you don't pay.</p>
            <div className="motion">
              <div className="tag">ƒ(x) · Signal geometry</div>
              <MotionCanvas type={motionType === 'field' ? 'lissajous' : 'field'} speed={0.9*speed} density={0.8*density} background="ink"/>
            </div>
          </div>
          <div className="vt-acc__list">
            {svcs.map((s, i) => (
              <div key={i} className={`vt-acc__item ${open===i?'vt-acc__item--open':''}`} onClick={() => setOpen(open===i?-1:i)}>
                <div className="vt-acc__row">
                  <div className="vt-acc__n">0{i+1}</div>
                  <div className="vt-acc__name">{s.name}</div>
                  <div/>
                  <div className="vt-acc__metric">{s.metric}</div>
                  <div className="vt-acc__plus">+</div>
                </div>
                <div className="vt-acc__body">
                  <div className="vt-acc__body-inner">
                    <div/>
                    <div>
                      <p>{s.body}</p>
                      <ul>{s.deliv.map((d,di) => <li key={di}>{d}</li>)}</ul>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- FRAMEWORK BAR (dark strip) ---------------- */
function FrameworkBar() {
  const phases = [
    { n: '01', name: 'Baseline', d: 'Where you actually are. Map processes, measure current state, name the real bottleneck.' },
    { n: '02', name: 'Define',   d: 'Agree on what done looks like before a single line is written. Specific target. Clear date.' },
    { n: '03', name: 'Build',    d: 'Execute against the target. One project at a time. No scope creep, no distraction.' },
    { n: '04', name: 'Deploy',   d: 'Into production, not a demo. Where most AI projects die. We stay until it\'s live.' },
    { n: '05', name: 'Assess',   d: 'Measure against baseline. Document the delta. Decide what\'s next. Loop closes, compounds.' },
  ];
  return (
    <section id="framework" className="vt-framework-bar">
      <div className="vt-container">
        <div className="vt-framework-bar__head">
          <div>
            <div className="vt-eyebrow vt-eyebrow--on-dark">The Vector Framework</div>
            <h2>A repeatable path from curiosity to compounding outcomes.</h2>
          </div>
          <p>Direction without measurement is just movement. Every engagement follows the same five phases.</p>
        </div>
        <div className="vt-framework-bar__row">
          {phases.map((p, i) => (
            <div key={i} className="vt-phase-sm">
              <div className="n"><span>{p.n}</span><span className="chev">{i<4?'→':'●'}</span></div>
              <div className="name">{p.name}</div>
              <p className="desc">{p.d}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- PLATFORM (white, isometric) ---------------- */
function Platform() {
  return (
    <section id="platform" className="vt-platform">
      <div className="vt-platform__inner">
        <div className="vt-platform__copy">
          <div className="vt-eyebrow">Platform · Vector OS</div>
          <h2>We design, build, and operate the infrastructure that makes AI outcomes <em>compound.</em></h2>
          <p>Most AI work dies as a one-off pilot. We ship it as a system — with the measurement rails, the retrain loops, and the dashboards already wired — so the first outcome is the foundation of the next.</p>
          <p>Your second win is faster than your first. Your investments compound. That is the whole promise.</p>
          <div className="vt-platform__stats">
            <div className="vt-platform__stat">
              <div className="k">First outcome</div>
              <div className="v">6–10 wks</div>
              <div className="l">From kickoff to a live number that moves</div>
            </div>
            <div className="vt-platform__stat">
              <div className="k">Second outcome</div>
              <div className="v">3–5 wks</div>
              <div className="l">Built on the rails the first one shipped</div>
            </div>
          </div>
        </div>
        <div className="vt-platform__iso">
          <IsometricInfra speed={0.8}/>
        </div>
      </div>
    </section>
  );
}

/* ---------------- POV ---------------- */
function POV() {
  const items = [
    { q: '"AI doesn\'t have a technology problem. It has an operating-model problem."',
      b: 'The reason AI initiatives fail isn\'t the model, the tool, or the budget. It\'s that the underlying processes were already broken — and AI just made the chaos faster. Fix the operating model first. Then deploy.' },
    { q: '"Most AI failures are really prioritization failures."',
      b: 'Every business has three to five places where a focused AI intervention would produce an immediately visible result. The problem isn\'t knowing enough about AI. It\'s not being ruthless enough about where to start.' },
    { q: '"You don\'t have an AI talent problem. You have a clarity problem."',
      b: 'A senior AI hire costs $180K–$250K, takes 4–6 months to find, and spends their first 90 days figuring out what to work on. Answer that for them first. If you can\'t, you\'re not ready to hire — you\'re ready to get clear.' },
  ];
  return (
    <section id="why" className="vt-section">
      <div className="vt-container">
        <div className="vt-pov__head">
          <div className="vt-eyebrow">Point of view</div>
          <h2>Three things most AI consultants won't tell you.</h2>
        </div>
        <div className="vt-pov__list">
          {items.map((it, i) => (
            <div key={i} className="vt-pov__item">
              <div className="vt-pov__num">0{i+1}</div>
              <div>
                <h3 className="vt-pov__quote">{it.q}</h3>
                <p className="vt-pov__body">{it.b}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- CTA BAND with motion bg ---------------- */
function CTA({ motionType, speed, density }) {
  return (
    <section id="about" className="vt-cta-band">
      <div className="vt-cta-band__bg">
        <MotionCanvas type={motionType === 'harmonograph' ? 'torus' : 'harmonograph'} speed={0.6*speed} density={0.8*density} background="ink"/>
      </div>
      <div className="vt-cta-band__inner">
        <div className="vt-eyebrow vt-eyebrow--on-dark">Selective intake · Q2 accepting</div>
        <h2>Point the <em>arrow.</em></h2>
        <p>Two spots left for Q2 2026. We respond to every application within 48 hours with an honest read on whether we're a fit.</p>
        <div style={{display:'flex', gap:14, flexWrap:'wrap'}}>
          <a className="vt-btn vt-btn--primary" href="Apply.html">Apply to work with Vectory <span className="ar">→</span></a>
          <a className="vt-btn vt-btn--on-dark" href="Direction Score.html">Get your Direction Score</a>
        </div>
      </div>
    </section>
  );
}

/* ---------------- FOOTER ---------------- */
function Footer() {
  return (
    <footer className="vt-footer">
      <div className="vt-footer__inner">
        <div style={{display:'flex', alignItems:'center', gap:12, color:'#FAFAF7'}}>
          <img src="assets/logo-mark-inverse.svg" height="26" alt="" style={{display:'block'}}/>
          <span style={{fontFamily:'var(--font-display)', fontSize:20, letterSpacing:'-0.015em'}}>Vectory</span>
          <span className="vt-footer__meta" style={{marginLeft:12}}>© 2026 · Direction for growing businesses</span>
        </div>
      </div>
    </footer>
  );
}

window.Nav = Nav;
window.Hero = Hero;
window.Mission = Mission;
window.Services = Services;
window.FrameworkBar = FrameworkBar;
window.Platform = Platform;
window.POV = POV;
window.CTA = CTA;
window.Footer = Footer;
