// Page sections
const { useState: useStateS } = React;

/* ─── Duotone image slot (one hue per fold) ─── */
function Duo({ id, hue, label, className = '', placeholder = 'Drop an image', src }) {
  return (
    <div className={`duo duo-${hue} ${className}`}>
      <image-slot id={id} placeholder={placeholder} shape="rounded" radius="10" src={src}></image-slot>
      <span className="duo-tint" />
      <span className="duo-grad" />
      {label ? <span className="duo-tag">{label}</span> : null}
    </div>);

}

/* ─── NAV ─── */
function Nav() {
  return (
    <nav className="nav">
      <div className="wrap nav-inner">
        <a className="logo" href="#top">
          <Wordmark />
        </a>
        <div className="nav-links">
          <a href="#service">Service</a>
          <a href="#cases">Work</a>
          <a href="#uses">Use cases</a>
          <a href="#contact">Contact</a>
        </div>
        <div>
          <a href="#contact" className="btn btn-primary" style={{ padding: '10px 18px', fontSize: 13 }}>
            Book a pilot <span className="btn-arrow" />
          </a>
        </div>
      </div>
    </nav>);

}

/* ─── HERO (Obsidian) — headline left, image right ─── */
function Hero() {
  return (
    <section id="top" className="fold hero">
      <div className="hero-aurora" />
      <div className="grain" />
      <div className="wrap hero-grid">
        <div className="hero-2col">
          <div>
            <Reveal as="h1">
              Build the<br />
              <span className="soft">Almost‑Perfect</span><br />
              Agent Workforce.
            </Reveal>
            <Reveal as="p" className="lede" delay={140}>
              Agents trained on how your team actually works.
            </Reveal>
            <Reveal className="hero-actions" delay={220}>
              <Btn href="#contact">Book a pilot</Btn>
              <Btn variant="ghost" href="#service">See how it works</Btn>
            </Reveal>
          </div>
          <Reveal delay={120}>
            <Duo id="hero-main" hue="obsidian" className="hero-media" label="// your agents, in context" placeholder="Drop a hero image" src="https://images.unsplash.com/photo-1517586979036-b7d1e86b3345?auto=format&fit=crop&w=1000&q=70" />
          </Reveal>
        </div>
        <Reveal className="hero-foot" delay={320}>
          {[
          ['What we build', 'AI agents'],
          ['Delivered as', 'Real software'],
          ['Embedded in', 'Your stack'],
          ['Backed by', 'Evals']].
          map(([k, v]) =>
          <div className="hero-foot-item" key={k}>
              <div className="k">{k}</div>
              <div className="v"><CountUp value={v} /></div>
            </div>
          )}
        </Reveal>
      </div>
    </section>);

}

/* ─── SERVICE (Cobalt) — text left, image right ─── */
function Service() {
  const pillars = [
  ['01', 'Trained on your context'],
  ['02', 'Your data policy by default'],
  ['03', 'Embedded where work happens'],
  ['04', 'Shipped like real software']];

  return (
    <section id="service" className="fold fold-cobalt">
      <div className="wrap">
        <div className="service-split">
          <Reveal>
            <h2 className="h-display" style={{ fontSize: 'clamp(40px,5vw,76px)', lineHeight: 0.95 }}>
              Replace generic AI tools with <em style={{ fontStyle: 'normal', color: 'var(--cobalt-accent)' }}>context‑specific</em> agents.
            </h2>
            <p className="service-lead">
              <strong>Stop writing prompts over and over again.
</strong> nthStudio builds agents around your data, policies and edge cases.
            </p>
            <a href="#contact" className="btn btn-ghost" style={{ marginTop: 28, borderColor: 'var(--cobalt-line)', color: 'var(--cobalt-fg)' }}>
              Request a walkthrough <span className="btn-arrow" />
            </a>
          </Reveal>
          <Reveal delay={120}>
            <Duo id="service-img" hue="cobalt" className="service-media" label="// agents as teammates" placeholder="Drop an image" src="https://images.unsplash.com/photo-1482053450283-3e0b78b09a70?auto=format&fit=crop&w=1000&q=70" />
          </Reveal>
        </div>

        <div className="pillars-slim">
          {pillars.map(([num, title], i) => <Reveal key={num} className="pillar-slim" delay={i * 80}>
              <div className="num">{num}</div>
              <h3>{title}</h3>
            </Reveal>
          )}
        </div>
      </div>
    </section>);

}

/* ─── CASES (Emerald) — list + image beside heading ─── */
function Cases() {
  const cases = [
  ['01', 'Production & ESG reporting', 'Manufacturing', 'Pull plant, ERP and sustainability data into one place so production and ESG reports write themselves instead of living in spreadsheets.'],
  ['02', 'Shipping document handling', 'Logistics & ports', 'Read bills of lading, customs forms and manifests automatically, and surface the exceptions your ops team would otherwise chase by hand.'],
  ['03', 'Order & inventory sync', 'Retail & distribution', 'Keep your OMS, WMS and ERP in step without the spreadsheet reconciliation, and clear returns and stock mismatches as they show up.'],
  ['04', 'Service-ops copilot', 'Telco & enterprise services', 'Put an agent on top of legacy provisioning and service systems so routine requests get handled without the swivel-chair work.'],
  ['05', 'Onboarding & reconciliation', 'Financial services ops', 'Assemble KYC and onboarding packs from scattered documents and reconcile transactions before anyone opens a spreadsheet.'],
  ['06', 'Proposals & billing admin', 'Professional services', 'Draft proposals from your past work and tidy up timesheet and billing admin, so billable hours go to clients instead of paperwork.']];


  const marquee = [
  'Custom AI agents', 'Workflow automation', 'Systems integration', 'Document processing',
  'Ops copilots', 'Built on your data', 'Live in weeks', 'We build, you own'];


  return (
    <section id="cases" className="fold fold-emerald">
      <div className="wrap">
        <div className="cases-head" style={{ alignItems: "center" }}>
          <Reveal><h2 className="h-display" style={{ fontSize: "96px" }}>For teams whose<br />systems don't talk.</h2></Reveal>
          <Reveal delay={120}>
            <Duo id="cases-img" hue="emerald" className="cases-media" label="// across your systems" placeholder="Drop an image" src="https://images.unsplash.com/photo-1526666923127-b2970f64b422?auto=format&fit=crop&w=1000&q=70" />
          </Reveal>
        </div>

        <div className="cases" role="list">
          {cases.map(([idx, client, sub, desc], i) =>
          <Reveal role="listitem" className="case" key={idx} delay={i * 70}>
              <div className="idx">{idx}</div>
              <div className="client">{client}<span className="sub">{sub}</span></div>
              <div className="desc">{desc}</div>
            </Reveal>
          )}
        </div>

        <div className="marquee" aria-hidden="true">
          <div className="marquee-track">
            {[...marquee, ...marquee].map((t, i) =>
            <span className="marquee-item" key={i}>
                <span className="sep" />
                <span>{t}</span>
              </span>
            )}
          </div>
        </div>
      </div>
    </section>);

}

/* ─── USES (Plum) — image cards ─── */
function Uses() {
  const items = [
  ['01 / Sales', 'Account research & outbound'],
  ['02 / Ops', 'SOP execution & exceptions'],
  ['03 / Support', 'Tier‑1 triage & responses'],
  ['04 / Finance', 'Reconciliation & variance'],
  ['05 / People', 'Onboarding & policy Q&A'],
  ['06 / Research', 'Evidence synthesis & memos']];

  const u = (id) => `https://images.unsplash.com/photo-${id}?auto=format&fit=crop&w=800&q=70`;
  // Structural-abstraction set: real infrastructure shot as geometry.
  const useImgs = [
  u('1482053450283-3e0b78b09a70'), // white latticework facade
  u('1526666923127-b2970f64b422'), // radio telescope dish
  u('1517586979036-b7d1e86b3345'), // aerial crossing
  u('1526666923127-b2970f64b422'),
  u('1517586979036-b7d1e86b3345'),
  u('1482053450283-3e0b78b09a70')];

  return (
    <section id="uses" className="fold fold-plum">
      <div className="wrap">
        <div className="uses-head">
          <Reveal><h2 className="h-display" style={{ fontSize: "96px" }}>Plugged in <em style={{ fontSize: "96px" }}>wherever</em> work already lives.</h2></Reveal>
        </div>
        <div className="uses">
          {items.map(([tag, h], i) =>
          <Reveal className="use-card" key={tag} delay={i * 60}>
              <Duo id={`use-${i + 1}`} hue="plum" className="use-media" placeholder="Drop an image" src={useImgs[i]} />
              <div className="use-body">
                <div className="tag" style={{ fontSize: "14px" }}>{tag}</div>
                <h3>{h}</h3>
              </div>
            </Reveal>
          )}
        </div>
      </div>
    </section>);

}

/* ─── CONTACT ─── */
function Contact() {
  const [form, setForm] = useStateS({ name: '', email: '', company: '', size: '51–250', what: '', company_url: '' });
  const [status, setStatus] = useStateS('idle'); // idle | sending | sent | error
  const [error, setError] = useStateS('');
  const sizes = ['1–50', '51–250', '251–1,000', '1,000+'];
  const sent = status === 'sent';

  const on = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));
  const submit = async (e) => {
    e.preventDefault();
    if (status === 'sending' || sent) return;
    setStatus('sending');
    setError('');
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify(form),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data.ok) throw new Error(data.error || 'Something went wrong.');
      setStatus('sent');
    } catch (err) {
      setStatus('error');
      setError(err.message || 'Could not send. Email hello@nthstudio.ai instead.');
    }
  };

  return (
    <section id="contact" className="fold fold-contact">
      <div className="wrap">
        <div className="contact-grid">
          <Reveal className="contact-head">
            <h2 className="h-display">Tell us what your team does.</h2>
            <p>30‑min discovery. Options memo in a week. Pilot in three.</p>
          </Reveal>

          <Reveal delay={120}>
            <form className="form-card" onSubmit={submit}>
              <div className="form-head">
                <div className="title">
                  <span className="dot" />
                  Start a pilot
                </div>
                <div className="step">~60 sec</div>
              </div>

              <div className="form-body">
                <div className="field-v">
                  <label>Full name <span className="req">*</span></label>
                  <input value={form.name} onChange={on('name')} placeholder="Jane Doe" required />
                </div>
                <div className="field-v">
                  <label>Work email <span className="req">*</span></label>
                  <input type="email" value={form.email} onChange={on('email')} placeholder="jane@company.com" required />
                </div>
                <div className="field-v">
                  <label>Company</label>
                  <input value={form.company} onChange={on('company')} placeholder="Company name" />
                </div>
                <div className="field-v">
                  <label>Team size</label>
                  <div className="chip-row">
                    {sizes.map((s) =>
                    <button type="button" key={s}
                    className={`chip ${form.size === s ? 'active' : ''}`}
                    onClick={() => setForm((f) => ({ ...f, size: s }))}>
                        {s}
                      </button>
                    )}
                  </div>
                </div>
                <div className="field-v full">
                  <label>What are you trying to solve? <span className="req">*</span></label>
                  <textarea value={form.what} onChange={on('what')} placeholder="A paragraph is plenty." required />
                </div>
                {/* Honeypot — hidden from humans, catches bots */}
                <input
                  type="text" tabIndex={-1} autoComplete="off"
                  className="hp" aria-hidden="true"
                  value={form.company_url} onChange={on('company_url')} />
              </div>

              {status === 'error' &&
              <div className="form-error" role="alert">{error}</div>}

              <div className="form-foot">
                <span className="small">
                  <span className="lock" />
                  {sent ? 'Thanks — we’ll be in touch within 24 hours' : 'We reply within 24 hours'}
                </span>
                <button type="submit" className="btn btn-primary" disabled={status === 'sending' || sent}>
                  {status === 'sending' ? 'Sending…' : sent ? 'Sent ✓' : <>Book a pilot <span className="btn-arrow" /></>}
                </button>
              </div>
            </form>
          </Reveal>
        </div>
      </div>
    </section>);

}

/* ─── FOOTER ─── */
function Footer() {
  return (
    <footer>
      <div className="wrap">
        <div className="foot-grid">
          <div className="foot-col">
            <a className="logo" href="#top">
              <Wordmark />
            </a>
            <p style={{ color: 'var(--obsidian-mute)', fontSize: 14, marginTop: 16, maxWidth: '30ch' }}>
              An AI services studio. Context‑specific agents for teams that have outgrown generic AI tools.
            </p>
          </div>
          <div className="foot-col">
            <h4>Explore</h4>
            <ul>
              <li><a href="#service">Service</a></li>
              <li><a href="#uses">Use cases</a></li>
              <li><a href="#cases">Work</a></li>
              <li><a href="#contact">Contact</a></li>
            </ul>
          </div>
        </div>
        <div className="foot-wordmark" aria-hidden="true" style={{ fontSize: "90px" }}>
          nth<span className="faint">Studio</span>
        </div>
        <div className="foot-bottom">
          <span>© 2026 nthStudio · a Zuno company.</span>
          <span>Made for teams that want agents, not chatbots.</span>
        </div>
      </div>
    </footer>);

}

Object.assign(window, { Nav, Hero, Service, Cases, Uses, Contact, Footer });