/* ====================== OKTRA — sections ====================== */

const TICKER = [
  'Top 1% of AI usage', 'Production-grade, not prototypes', 'We build with the tools, not slides',
  'Claude Code, with guardrails', 'Custom SaaS', 'AI integrations', 'Ops automation',
  'Systems architecture', 'Real companies, rebuilt',
];

function Ticker() {
  const row = [...TICKER, ...TICKER];
  const trackRef = useRef(null);
  const wrapRef = useRef(null);
  useEffect(() => {
    const track = trackRef.current;
    const wrapEl = wrapRef.current;
    let raf = 0, x = 0, last = 0, paused = false;
    const cs = getComputedStyle(document.documentElement);
    const onEnter = () => { paused = true; };
    const onLeave = () => { paused = false; };
    wrapEl.addEventListener('mouseenter', onEnter);
    wrapEl.addEventListener('mouseleave', onLeave);
    const tick = (now) => {
      if (!last) last = now;
      const dt = Math.min(64, now - last); last = now;
      const motion = parseFloat(cs.getPropertyValue('--motion')) || 1;
      if (!paused) {
        x -= (dt / 1000) * 62 * motion;
        const half = track.scrollWidth / 2;
        if (half > 0 && -x >= half) x += half;
        track.style.transform = `translateX(${x}px)`;
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => { cancelAnimationFrame(raf); wrapEl.removeEventListener('mouseenter', onEnter); wrapEl.removeEventListener('mouseleave', onLeave); };
  }, []);
  return (
    <div className="ticker" aria-hidden="true" ref={wrapRef}>
      <div className="ticker-track" ref={trackRef}>
        {row.map((t, i) => (
          <span className="item" key={i}><span className="star">✦</span>{t}</span>
        ))}
      </div>
    </div>
  );
}

const SERVICES = [
  { n: '01', t: 'Custom software & SaaS', tag: 'Build',
    d: 'From a half-formed idea to a deployed product. Real architecture, real users, shipped at a pace that used to be impossible.',
    gives: ['Architecture & data model', 'Production web app + APIs', 'Auth, billing, dashboards', 'Deploy pipeline you own'],
    tags: ['Web apps', 'APIs', 'Dashboards', 'MVP → scale'] },
  { n: '02', t: 'AI integrations & automation', tag: 'Integrate',
    d: 'We wire models into the work that actually matters, connected to your data, your tools, and your existing stack so they earn their place.',
    gives: ['Model + data pipeline', 'Retrieval over your sources', 'Agentic workflows', 'Evals so it stays honest'],
    tags: ['LLM pipelines', 'RAG', 'Agents', 'Eval'] },
  { n: '03', t: 'Dev workflow & Claude Code setups', tag: 'Equip',
    d: 'The internal tooling, hooks, and guardrails that let a team move fast with AI without handing it the keys to break production.',
    gives: ['Guardrails & review gates', 'Custom hooks & commands', 'Team conventions baked in', 'Onboarding your devs'],
    tags: ['Guardrails', 'Hooks', 'CLI tooling', 'Review gates'] },
  { n: '04', t: 'Systems & process consulting', tag: 'Diagnose',
    d: 'Architecture, not band-aids. We map how your systems actually work end-to-end, then redesign the parts that quietly cost you the most.',
    gives: ['End-to-end systems map', 'Bottleneck & risk audit', 'Target architecture', 'Sequenced roadmap'],
    tags: ['Audits', 'Architecture', 'Data flow'] },
  { n: '05', t: 'Workflow & ops automation', tag: 'Automate',
    d: 'Remove the manual steps, keep the human judgement. We automate the repetitive middle so your team spends time where it counts.',
    gives: ['Process mapping', 'Automation build-out', 'Human-in-the-loop checks', 'Handoff & docs'],
    tags: ['Ops', 'Back-office', 'Internal tools'] },
];

function ServiceSchematic({ idx }) {
  // a small animated node diagram that reshapes per service — feels like a live system
  const nodes = 5;
  return (
    <div className="svc-schematic" aria-hidden="true">
      <svg viewBox="0 0 220 140" width="100%" height="100%" preserveAspectRatio="xMidYMid meet">
        {Array.from({ length: nodes }).map((_, i) => {
          const a = (i / nodes) * Math.PI * 2 + idx * 0.6;
          const cx = 110 + Math.cos(a) * (44 + (idx % 3) * 10);
          const cy = 70 + Math.sin(a) * (30 + (idx % 2) * 12);
          return <line key={'l' + i} x1="110" y1="70" x2={cx} y2={cy} stroke="var(--accent-line)" strokeWidth="1" />;
        })}
        {Array.from({ length: nodes }).map((_, i) => {
          const a = (i / nodes) * Math.PI * 2 + idx * 0.6;
          const cx = 110 + Math.cos(a) * (44 + (idx % 3) * 10);
          const cy = 70 + Math.sin(a) * (30 + (idx % 2) * 12);
          return <circle key={'n' + i} cx={cx} cy={cy} r="3.4" fill="var(--accent)" opacity={0.5 + (i === idx % nodes ? 0.5 : 0.1)} />;
        })}
        <circle cx="110" cy="70" r="6" fill="none" stroke="var(--accent)" strokeWidth="1.4" />
        <circle cx="110" cy="70" r="2.4" fill="var(--accent)" />
      </svg>
    </div>
  );
}

function ServiceDetail({ s, idx, instant }) {
  const [shown, setShown] = useState(!!instant);
  useEffect(() => {
    if (instant) return;
    const r = requestAnimationFrame(() => setShown(true));
    return () => cancelAnimationFrame(r);
  }, [instant]);
  return (
    <div className={'svc-detail' + (shown ? ' in' : '')}>
      <div className="svc-detail-top">
        <span className="svc-kicker mono">{s.tag} · {s.n} / 05</span>
        <ServiceSchematic idx={idx} />
      </div>
      <h3 className="svc-detail-title">{s.t}</h3>
      <p className="svc-detail-desc">{s.d}</p>
      <div className="svc-gives">
        <div className="svc-gives-h mono">What you get</div>
        <ul>
          {s.gives.map((g, i) => (
            <li key={g} style={{ '--gi': `${120 + i * 70}ms` }}><span className="gv-mk"><Check size={15} /></span>{g}</li>
          ))}
        </ul>
      </div>
      <div className="svc-detail-foot">
        <div className="tags">
          {s.tags.map((t) => <span className="tag" key={t}>{t}</span>)}
        </div>
        <button className="btn btn-primary" style={{ '--bh': '44px' }} onClick={() => scrollToId('contact')}>
          <span className="label">Scope this <ArrowUR /></span>
        </button>
      </div>
    </div>
  );
}

function OpenCard() {
  return (
    <div className="svc-detail svc-detail-open in">
      <div className="svc-detail-top">
        <span className="svc-kicker mono">Open · 06 / 05</span>
      </div>
      <h3 className="svc-detail-title">Something else entirely?</h3>
      <p className="svc-detail-desc">If it is technical and AI can make it meaningfully better, it is
        in scope. Tell us the problem and we will tell you straight whether we are the right team.</p>
      <div className="svc-detail-foot" style={{ marginTop: 28 }}>
        <button className="btn btn-primary" style={{ '--bh': '44px' }} onClick={() => scrollToId('contact')}>
          <span className="label">Start a conversation <ArrowUR /></span>
        </button>
      </div>
    </div>
  );
}

function ServicesMobile() {
  const trackRef = useRef(null);
  const [active, setActive] = useState(0);
  const count = SERVICES.length + 1;

  function nearestIndex() {
    const track = trackRef.current;
    if (!track) return 0;
    const center = track.scrollLeft + track.clientWidth / 2;
    let best = 0, bd = Infinity;
    Array.from(track.children).forEach((c, i) => {
      const cc = c.offsetLeft + c.offsetWidth / 2;
      const d = Math.abs(cc - center);
      if (d < bd) { bd = d; best = i; }
    });
    return best;
  }
  function onScroll() {
    const i = nearestIndex();
    setActive((prev) => (i !== prev ? i : prev));
  }
  function goTo(i) {
    const track = trackRef.current;
    if (!track) return;
    const c = track.children[i];
    if (!c) return;
    const left = c.offsetLeft - (track.clientWidth - c.offsetWidth) / 2;
    track.scrollTo({ left, behavior: 'smooth' });
  }

  return (
    <div className="svc-mobile reveal">
      <div className="svc-track" ref={trackRef} onScroll={onScroll}>
        {SERVICES.map((s, i) => (
          <div className="svc-slide" key={s.n}><ServiceDetail s={s} idx={i} instant /></div>
        ))}
        <div className="svc-slide"><OpenCard /></div>
      </div>
      <div className="svc-pager">
        <div className="svc-dots">
          {Array.from({ length: count }).map((_, i) => (
            <button key={i} className={'svc-dot' + (active === i ? ' on' : '')}
              aria-label={'Go to build ' + (i + 1)} onClick={() => goTo(i)}>
              <span></span>
            </button>
          ))}
        </div>
        <span className="svc-swipe mono">{String(active + 1).padStart(2, '0')} / {String(count).padStart(2, '0')} · swipe →</span>
      </div>
    </div>
  );
}

function Services() {
  const [sel, setSel] = useState(0);
  const s = SERVICES[sel];
  const listRef = useRef(null);

  function onKey(e) {
    if (e.key === 'ArrowDown') { e.preventDefault(); setSel((v) => (v + 1) % SERVICES.length); }
    if (e.key === 'ArrowUp') { e.preventDefault(); setSel((v) => (v - 1 + SERVICES.length) % SERVICES.length); }
  }

  return (
    <section className="section" id="services" data-screen-label="services">
      <div className="wrap">
        <div className="section-head reveal">
          <div className="eyebrow">What we do</div>
          <h2>Five ways we put serious AI to work for you.</h2>
          <p>One studio, the whole stack: strategy, build, and the hardening most people skip.
            Pick a capability to see exactly what an engagement delivers.</p>
        </div>

        <div className="svc-explorer svc-desktop reveal">
          <div className="svc-list" role="tablist" aria-label="Services" ref={listRef} tabIndex={0} onKeyDown={onKey}>
            {SERVICES.map((it, i) => (
              <button
                key={it.n}
                role="tab"
                aria-selected={sel === i}
                className={'svc-row' + (sel === i ? ' active' : '')}
                onMouseEnter={() => setSel(i)}
                onClick={() => setSel(i)}
              >
                <span className="svc-row-n mono">{it.n}</span>
                <span className="svc-row-t">{it.t}</span>
                <span className="svc-row-arrow"><ArrowUR size={15} cls="" /></span>
              </button>
            ))}
            <button className="svc-row svc-row-open" onClick={() => scrollToId('contact')}>
              <span className="svc-row-n mono">06</span>
              <span className="svc-row-t">Something else entirely?</span>
              <span className="svc-row-arrow"><ArrowUR size={15} cls="" /></span>
            </button>
          </div>

          <ServiceDetail key={sel} s={s} idx={sel} />
        </div>

        <ServicesMobile />
      </div>
    </section>
  );
}

const STEPS = [
  { n: '01', t: 'Diagnose', d: 'We get inside how your systems and team actually work, not the org chart version. Where the time goes, where the risk hides, where AI is a multiplier and where it is a liability.', m: 'week 1' },
  { n: '02', t: 'Architect', d: 'We design the right approach before writing the fun part: the data flow, the failure modes, and the guardrails that keep AI inside the lines once it is loose in your environment.', m: 'week 1–2' },
  { n: '03', t: 'Build', d: 'Production-grade, fast. You see working software early and often, not a slide deck at the end. We use the same AI-native workflow that lets us out-build teams many times our size.', m: 'weeks 2–6' },
  { n: '04', t: 'Harden & hand off', d: 'We tighten the edges, document the system, and make sure your people can run and extend it confidently, with the understanding and not just the keys. You own it. Fully.', m: 'ongoing' },
];

function Process() {
  return (
    <section className="section process" id="process" data-screen-label="process">
      <div className="wrap">
        <div className="section-head reveal">
          <div className="eyebrow">How we work</div>
          <h2>A way of working built for how fast things move now.</h2>
          <p>Short, intense engagements with working software in front of you from week one. No
            six-month discovery phase. The world won't wait that long, and neither should you.</p>
        </div>
        <div className="steps">
          {STEPS.map((s, i) => (
            <div className="step reveal-l" style={{ '--d': `${i * 90}ms` }} key={s.n}>
              <div className="st-num mono">{s.n}</div>
              <div className="st-body">
                <h3>{s.t}</h3>
                <p>{s.d}</p>
              </div>
              <div className="st-meta">{s.m}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

const PRINCIPLES = [
  { n: '01', t: 'Guardrails before horsepower', d: 'Hooks, gates, and review layers so AI can move fast without quietly breaking what matters. Speed is only an asset if it is safe.' },
  { n: '02', t: 'You leave understanding it', d: 'We hand off clean systems and the mental model to run them. No black boxes, no dependency on us forever. The goal is your independence.' },
  { n: '03', t: 'Depth over hype', d: "We've rebuilt real companies with this, the operations and the software both, not weekend demos. We tell you when AI is the wrong tool, too." },
];

function RightWay() {
  return (
    <section className="section right-way" id="approach" data-screen-label="right-way">
      <div className="wrap">
        <div className="eyebrow reveal" style={{ marginBottom: 28 }}>The right way</div>
        <p className="big-quote reveal" style={{ '--d': '60ms' }}>
          Most AI efforts don't fail because the model is wrong. They fail because <span className="hl">nobody set the guardrails</span>, and nobody knew the risks until it was live.
        </p>
        <div className="principles">
          {PRINCIPLES.map((p, i) => (
            <div className="principle reveal" style={{ '--d': `${i * 80}ms` }} key={p.n}>
              <div className="pnum mono">{p.n}</div>
              <h4>{p.t}</h4>
              <p>{p.d}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Cases() {
  return (
    <section className="section" id="work" data-screen-label="cases">
      <div className="wrap">
        <div className="section-head reveal" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 24 }}>
          <div style={{ display: 'grid', gap: 22 }}>
            <div className="eyebrow">Selected work</div>
            <h2 style={{ margin: 0 }}>Proof, not promises.</h2>
          </div>
          <p style={{ maxWidth: '40ch' }}>Our deepest case studies involve our own companies and client systems, so we walk
            through them live, under NDA, on an intro call rather than posting them publicly.</p>
        </div>
        <div className="cases">
          <article className="case reveal">
            <div className="ghost-grid"></div>
            <div className="case-tag">● Internal · Real estate</div>
            <h3>A real estate company, rebuilt end-to-end with AI.</h3>
            <p>Operations, internal software, and day-to-day workflows reworked around an AI-native
              stack. The systems now run on tooling we designed and hardened ourselves.</p>
            <div className="redacted">
              {[120, 80, 150, 60, 100, 90].map((w, i) => <span className="rd" key={i} style={{ width: w }}></span>)}
            </div>
            <div className="case-foot">
              <span className="locked"><Lock /> Full walkthrough on a call</span>
              <button className="mono" onClick={() => scrollToId('contact')} style={{ background: 'none', border: 0, color: 'var(--accent-2)', cursor: 'pointer', fontSize: 12 }}>Request access →</button>
            </div>
          </article>
          <article className="case reveal" style={{ '--d': '90ms' }}>
            <div className="ghost-grid"></div>
            <div className="case-tag">● Tooling · Developer workflow</div>
            <h3>A Claude Code companion, with guards and hooks built in.</h3>
            <p>A safety and productivity layer for AI-assisted development: guardrails, hooks, and
              review gates so teams can move fast without exposing themselves to the obvious risks.</p>
            <div className="redacted">
              {[90, 130, 70, 110, 60, 140].map((w, i) => <span className="rd" key={i} style={{ width: w }}></span>)}
            </div>
            <div className="case-foot">
              <span className="locked"><Lock /> Full walkthrough on a call</span>
              <button className="mono" onClick={() => scrollToId('contact')} style={{ background: 'none', border: 0, color: 'var(--accent-2)', cursor: 'pointer', fontSize: 12 }}>Request access →</button>
            </div>
          </article>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Ticker, Services, Process, RightWay, Cases });
