/* ISonTrack Landing — Main sections + Hero + Modal + Tweaks
   Depends on: window.DemoReel from demo-mocks.jsx
   ------------------------------------------------------------------------ */

const { useState, useEffect, useRef } = React;

/* Demo form submits to Formspree. Create a form at https://formspree.io set
   to forward to info@isontrack.com, then replace YOUR_FORM_ID below. */
const FORM_ENDPOINT = 'https://formspree.io/f/mgorpzga';

/* --- Tweakable defaults (editable via Tweaks panel) ------------------- */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "hero_theme": "dark",
  "hero_layout": "split",
  "motion": "balanced",
  "headline_variant": "less_paperwork"
} /*EDITMODE-END*/;

const HEADLINES = {
  less_paperwork: { pre: "Less paperwork.", grad: "More impact." },
  ai_copilot: { pre: "Your sustainability", grad: "copilot." },
  built_for_infra: { pre: "Built for the people", grad: "who build the world." },
  cut_admin: { pre: "Cut admin. Deliver", grad: "on time. On planet." }
};

/* --- App video placeholder — swap <video src> when real footage lands --- */
const AppVideoPlaceholder = ({ label = "App walkthrough · 00:42", caption = "Drop real screen recording here" }) =>
<div className="app-video-placeholder" aria-label="App preview placeholder">
    {/* When a real clip is ready, uncomment and point src at the mp4/webm:
      <video autoPlay muted loop playsInline poster="..." src="assets/app-preview.mp4"/>
    */}
    <div className="avp-inner">
      <DemoDashboard />
      <div className="avp-scrim" />
      <div className="avp-badge">
        <span className="rec" /><span>PREVIEW · PLACEHOLDER</span>
      </div>
      <div className="avp-caption">
        <div className="k">{label}</div>
        <div className="v">{caption}</div>
      </div>
      <button className="avp-play" aria-label="Play preview">
        <svg viewBox="0 0 24 24" width="22" height="22" fill="#fff">
          <path d="M8 5v14l11-7L8 5z" />
        </svg>
      </button>
    </div>
  </div>;


/* --- Brand lockup ----------------------------------------------------- */
const Brand = () =>
<div className="brand-lockup">
    <img src="assets/logo-mark.svg" alt="" className="mark" width="30" height="30" />
    <span>ISonTrack</span>
  </div>;


/* --- Icons ------------------------------------------------------------- */
const Icon = ({ name, ...props }) => {
  const paths = {
    sparkles: <><path d="M12 3v4M12 17v4M3 12h4M17 12h4M6 6l2.5 2.5M15.5 15.5L18 18M6 18l2.5-2.5M15.5 8.5L18 6" /><circle cx="12" cy="12" r="3" /></>,
    bolt: <path d="M13 2L4 14h7l-2 8 9-12h-7l2-8z" />,
    shield: <><path d="M12 2l8 4v6c0 5-3.5 9-8 10-4.5-1-8-5-8-10V6l8-4z" /><path d="M9 12l2 2 4-4" /></>,
    link: <><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" /><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" /></>,
    chart: <><path d="M3 3v18h18" /><path d="M7 14l4-4 4 4 5-5" /></>,
    users: <><circle cx="9" cy="7" r="4" /><path d="M3 21v-2a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v2" /><circle cx="17" cy="7" r="3" /><path d="M21 21v-2a4 4 0 0 0-3-3.87" /></>,
    check: <polyline points="5 12 10 17 19 8" />,
    close: <><path d="M18 6L6 18" /><path d="M6 6l12 12" /></>,
    play: <path d="M8 5v14l11-7L8 5z" />,
    modules: <><rect x="3" y="3" width="7" height="7" rx="1.5" /><rect x="14" y="3" width="7" height="7" rx="1.5" /><rect x="3" y="14" width="7" height="7" rx="1.5" /><rect x="14" y="14" width="7" height="7" rx="1.5" /></>
  };
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...props}>
      {paths[name]}
    </svg>);

};

/* --- Header ------------------------------------------------------------ */
const Header = ({ theme, onDemo }) => {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <header className={`site-header ${theme === 'light' ? 'light' : ''} ${scrolled ? 'scrolled' : ''}`}>
      <div className="wrap">
        <Brand />
        <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
          <a href="https://app.isontrack.com" className={`btn ${theme === 'light' ? 'btn-ghost-light' : 'btn-secondary'}`}>
            Log in
          </a>
          <button className="btn btn-primary" onClick={onDemo}>
            Book a demo
          </button>
        </div>
      </div>
    </header>);

};

/* --- Hero -------------------------------------------------------------- */
const Hero = ({ theme, layout, headlineKey, onDemo }) => {
  const headline = HEADLINES[headlineKey] || HEADLINES.less_paperwork;
  const Copy =
  <>
      <div className="hero-eyebrow">
        <span className="chip"><span className="dot" /> Early access · Design partners wanted</span>
      </div>
      <h1>
        {headline.pre}<br />
        <span className="grad">{headline.grad}</span>
      </h1>
      <p className="lede">
        ISonTrack is the AI platform for sustainability &amp; environmental managers
        on Aussie and Kiwi public infrastructure projects. Turn evidence, credits, and reporting
        into one live, auditable workspace — so your team spends its hours on
        outcomes, not spreadsheets.
      </p>
      <div className="hero-cta-row">
        <button className="btn btn-primary btn-lg" onClick={onDemo}>
          Book a demo
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <path d="M5 12h14M13 6l6 6-6 6" />
          </svg>
        </button>
        <a href="https://app.isontrack.com" className={`btn btn-lg ${theme === 'light' ? 'btn-ghost-light' : 'btn-secondary'}`}>
          Log in
        </a>
      </div>
    </>;


  const Visual =
  <div className="hero-visual hero-visual--video" data-reveal>
      <video
        className="hero-video"
        src="assets/intro.mp4"
        autoPlay
        muted
        loop
        playsInline
        preload="metadata"
        aria-label="ISonTrack product walkthrough" />
    </div>;


  return (
    <section className={`hero ${theme} ${layout}`}>
      <div className="hero-grid-bg" />
      <div className="hero-beams">
        <div className="beam b1" /><div className="beam b2" /><div className="beam b3" />
      </div>
      <div className="wrap hero-inner">
        {layout === 'split' ?
        <div className="hero-grid">
            <div>{Copy}</div>
            {Visual}
          </div> :

        <>{Copy}{Visual}</>
        }
      </div>
    </section>);

};

/* --- Frameworks strip — AU/NZ infrastructure imagery carousel -------- */
// Photos licensed under the Unsplash License. See assets/photos/CREDITS.md
// for the full attribution table.
const INFRA_SHOTS = [
  { loc: "Sea Cliff Bridge · NSW",           credit: "Tim Patch",            src: "assets/photos/tim-patch-AjEB8hubof8-unsplash.jpg" },
  { loc: "Melbourne tram corridor",          credit: "Shaun Low",            src: "assets/photos/shaun-low-g1fTtCjszM4-unsplash.jpg" },
  { loc: "Auckland motorway · Lightpath",    credit: "Ethan Johnson",        src: "assets/photos/ethan-johnson-ULAwIM4ISaw-unsplash.jpg" },
  { loc: "Coastal road · Aotearoa",          credit: "Alexander Zabrodskiy", src: "assets/photos/alexander-zabrodskiy-dnRDwxdVMhY-unsplash.jpg" },
  { loc: "Wellington cable car",             credit: "João Marcelo Martins", src: "assets/photos/joao-marcelo-martins-esv9rsglRSc-unsplash.jpg" },
  { loc: "Flinders Ranges highway · SA",     credit: "Michael Skopal",       src: "assets/photos/michael-skopal-dqrfDkAOeos-unsplash.jpg" }
];


const FRAMEWORKS = [
{ k: "IS v2.1 / v1.2", v: "Full credit register, evidence, and submission workflow", status: "live" },
{ k: "Water tracking", v: "Use, discharge, and quality — by meter, site, or reach", status: "live" },
{ k: "GHG emissions", v: "Scope 1–3 carbon, fuel, concrete, haulage", status: "live" },
{ k: "Materials & spoil", v: "Spoil movements, reuse rates, recycled content", status: "live" },
{ k: "Waste & circularity", v: "Diversion rates, streams, audit-grade evidence", status: "live" },
{ k: "Your internal framework", v: "Client KPIs, tender commitments, project-specific metrics", status: "live" },
{ k: "Recycle First (VIC)", v: "Victoria's recycled-material reporting", status: "soon" },
{ k: "Next IS rating version", v: "Updates included — no migration, no re-licence", status: "soon" }];


const InfraStrip = () => {
  const [idx, setIdx] = React.useState(0);
  const trackRef = React.useRef(null);

  React.useEffect(() => {
    const id = setInterval(() => setIdx((i) => (i + 1) % INFRA_SHOTS.length), 4500);
    return () => clearInterval(id);
  }, []);

  return (
    <section className="section frameworks-section">
      <div className="wrap">
        <div className="frameworks-intro">
          <div className="section-eyebrow" data-reveal>One workspace. Every framework.</div>
          <h2 data-reveal>Track any metric. Under any framework. All in one place.</h2>
          <p className="lede-2" data-reveal>
            IS ratings, water, GHG emissions, spoil management, your own client KPIs —
            ISonTrack is the single workspace for everything a sustainability team on
            infrastructure projects has to evidence and report.
          </p>
        </div>

        <ul className="framework-grid" data-reveal>
          {FRAMEWORKS.map((f) =>
          <li key={f.k} className={`framework-chip ${f.status}`}>
              <div className="fwk-head">
                <span className="fwk-k">{f.k}</span>
                {f.status === 'soon' && <span className="fwk-tag">Coming soon</span>}
                {f.status === 'live' && <span className="fwk-dot" aria-hidden="true" />}
              </div>
              <div className="fwk-v">{f.v}</div>
            </li>
          )}
        </ul>

        <div className="frameworks-carousel" data-reveal>
          <div className="fc-track" ref={trackRef} style={{ transform: `translateX(-${idx * 100}%)` }}>
            {INFRA_SHOTS.map((s, i) =>
            <div key={i} className="fc-slide">
                <img src={s.src} alt={s.loc} loading="lazy" />
                <div className="fc-caption">{s.loc}</div>
                <div className="fc-credit">Photo · {s.credit} / Unsplash</div>
              </div>
            )}
          </div>
          <div className="fc-dots">
            {INFRA_SHOTS.map((_, i) =>
            <button key={i} className={i === idx ? 'active' : ''} onClick={() => setIdx(i)} aria-label={`Photo ${i + 1}`} />
            )}
          </div>
        </div>
      </div>
    </section>);

};

/* --- Problem section --------------------------------------------------- */
const Problem = () =>
<section className="section dark" style={{ background: '#0B1322' }}>
    <div className="wrap">
      <div className="problem-grid">
        <div className="problem-copy">
          <div className="section-eyebrow" data-reveal>The status quo</div>
          <h2 data-reveal>Sustainability teams spend half the week chasing paperwork.</h2>
          <p className="lede-2" data-reveal>
            Environmental evidence lives in inboxes, SharePoints, and someone's laptop on site.
            IS credits get tracked in a spreadsheet nobody trusts by page two.
            Reporting eats the weekends — and the impact your crew fought for gets lost in the noise.
          </p>
          <div className="stat-stack">
            <div className="stat-card" data-reveal><div className="num">47%</div><div className="lbl">of a sustainability lead's week goes to admin &amp; reporting</div></div>
            <div className="stat-card" data-reveal><div className="num">6×</div><div className="lbl">different tools a typical Aussie or Kiwi project team uses to track ESG</div></div>
            <div className="stat-card" data-reveal><div className="num">3 wks</div><div className="lbl">average lag between evidence on-site and credit score updated</div></div>
            <div className="stat-card" data-reveal><div className="num">2 to 6</div><div className="lbl">FTE for IS submissions + consultants</div></div>
          </div>
        </div>
        <div className="problem-image" data-reveal>
          <img src="assets/photos/elton-sa-KuNCuOPcLUU-unsplash.jpg" alt="Aerial view of a coastal bridge hugging the Australian shoreline" loading="lazy" />
          <div className="photo-credit">Photo · Elton Sa / Unsplash</div>
          <div className="overlay-card">
            <div className="k">Roads · Rail · Bridges</div>
            <div className="v">Highway, rail and bridge programmes across Australia &amp; Aotearoa — where every tonne of carbon and every litre of water is on the record.</div>
          </div>
        </div>
      </div>
    </div>
  </section>;


/* --- Demo reel --------------------------------------------------------- */
const DemoReelSection = ({ onDemo }) =>
<section className="section">
    <div className="wrap">
      <div className="section-eyebrow" data-reveal>The product</div>
      <h2 data-reveal>Everything your project needs — in one calm place.</h2>
      <p className="lede-2" data-reveal>
        A live, AI-grounded workspace for credits, evidence, carbon, and reporting.
        Replace six tools with one — and give every stakeholder the same source of truth.
      </p>

      <DemoReel />

      <div className="extras-grid" data-reveal>
        <aside className="extra-card">
          <div className="ic"><Icon name="modules" /></div>
          <h3>Hire only what you need</h3>
          <p>Mix and match modules to fit the project: IS-rating credits, resource tracking (water, energy, materials, waste), auto-generated reports — plus project consents and spoil management coming soon. Pay for the scope you're delivering, nothing more.</p>
        </aside>
        <aside className="extra-card">
          <div className="ic"><Icon name="users" /></div>
          <h3>One truth, every stakeholder</h3>
          <p>Designers, contractors, clients, and auditors each get the view they need — no exports, no version wars, no "which deck is latest?". Free read-only auditor seats included.</p>
        </aside>
      </div>
    </div>
  </section>;


/* --- Founders ---------------------------------------------------------- */
const FOUNDERS = [
{
  name: "David Maucor",
  role: "Co-founder",
  bio: "Fifteen-plus years in the trenches of HSE and sustainability — on big infrastructure builds across Australia, New Zealand and Europe. A registered ISAP, ISO 14001-trained, and an ISC regular since 2016 (audits, ISP reviews, the lot). He's seen how good teams lose weekends to paperwork — and he's here to fix that.",
  initials: "DM",
  photo: "assets/founders/david.png"
},
{
  name: "Kevin Anderson",
  role: "Co-founder",
  bio: "A civil engineer and sustainability consultant — ten years on complex infrastructure builds across Australia, New Zealand and Latin America. UNSW-trained (Master's in Sustainable Systems Engineering), a former ISAP, and a trusted hand at Watercare, Auckland Transport, Transport for New South Wales and VicTrack — here to build the future of infrastructure sustainability management.",
  initials: "KA",
  photo: "assets/founders/kevin.jpg"
}];


const FounderCard = ({ f }) =>
<article className="founder-card" data-reveal>
    <div className="portrait">
      {f.photo ?
        <img src={f.photo} alt={f.name} className="portrait-photo" loading="lazy" /> :
        <svg viewBox="0 0 120 120" aria-hidden="true" className="portrait-svg">
          <defs>
            <pattern id={`stripe-${f.initials}`} width="6" height="6" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
              <rect width="6" height="6" fill="#0B1322" />
              <rect width="3" height="6" fill="#0F1A2E" />
            </pattern>
          </defs>
          <rect width="120" height="120" fill={`url(#stripe-${f.initials})`} />
          <circle cx="60" cy="50" r="20" fill="rgba(255,255,255,0.08)" stroke="rgba(2,227,167,0.35)" strokeWidth="1" />
          <path d="M26 120 C 26 92, 42 80, 60 80 C 78 80, 94 92, 94 120 Z" fill="rgba(255,255,255,0.06)" stroke="rgba(2,227,167,0.25)" strokeWidth="1" />
          <text x="60" y="56" textAnchor="middle" fill="rgba(255,255,255,0.55)" fontFamily="var(--font-mono)" fontSize="14" fontWeight="600" letterSpacing="0.12em">{f.initials}</text>
        </svg>
      }
    </div>
    <div className="founder-body">
      <div className="founder-role">{f.role}</div>
      <h3>{f.name}</h3>
      <p>{f.bio}</p>
    </div>
  </article>;


const Founders = () =>
<section className="section founders-section" style={{ background: 'var(--light)' }}>
    <div className="wrap">
      <div className="section-eyebrow" data-reveal>The people behind it</div>
      <h2 data-reveal>Two founders. Both sick of spreadsheets.</h2>
      <div className="founder-grid">
        {FOUNDERS.map((f) => <FounderCard key={f.name} f={f} />)}
      </div>
    </div>
  </section>;


/* --- Features ---------------------------------------------------------- */
const Features = () =>
<section className="section" style={{ background: 'var(--light)' }}>
    <div className="wrap">
      <div className="section-eyebrow" data-reveal>Built for the work</div>
      <h2 data-reveal>Fewer tools. More time. Cleaner audits.</h2>
      <div className="feat-grid">
        <div className="feat-card ai" data-reveal>
          <span className="ai-tag">AI</span>
          <div className="ic"><Icon name="sparkles" /></div>
          <h3>Evidence autopilot</h3>
          <p>Drop a PDF, photo, or email. ISonTrack extracts the data, classifies it, and links it to the right IS credit — with a citation every auditor will love.</p>
        </div>
        <div className="feat-card ai" data-reveal>
          <span className="ai-tag">AI</span>
          <div className="ic"><Icon name="bolt" /></div>
          <h3>Reporting, written for you</h3>
          <p>Ask for a monthly ESG update, a board pack, or an audit response. Get a drafted, sourced, on-brand report in seconds — grounded only in your project's data.</p>
        </div>
        <div className="feat-card ai" data-reveal>
          <span className="ai-tag">AI</span>
          <div className="ic"><Icon name="shield" /></div>
          <h3>Audit-ready by default</h3>
          <p>Every claim links back to source evidence, every change is versioned, every number explains itself. Submission reviews go from weeks to afternoons.</p>
        </div>
        <div className="feat-card" data-reveal>
          <div className="ic"><Icon name="chart" /></div>
          <h3>Live credit tracker</h3>
          <p>See every IS credit, every target, every owner — colour-coded and refreshed the moment evidence lands. No more spreadsheet archaeology.</p>
        </div>
        <div className="feat-card" data-reveal>
          <div className="ic"><Icon name="modules" /></div>
          <h3>Hire only what you need</h3>
          <p>Mix and match modules to fit the project: IS-rating credits, resource tracking (water, energy, materials, waste), auto-generated reports — plus project consents and spoil management coming soon. Pay for the scope you're delivering, nothing more.</p>
        </div>
        <div className="feat-card" data-reveal>
          <div className="ic"><Icon name="users" /></div>
          <h3>One truth, every stakeholder</h3>
          <p>Designers, contractors, clients, and auditors each get the view they need — no exports, no version wars, no "which deck is latest?".</p>
        </div>
      </div>
    </div>
  </section>;


/* --- How it works ------------------------------------------------------ */
const HowItWorks = () =>
<section className="section dark" style={{ background: 'linear-gradient(180deg, #0B1322 0%, #050B1A 100%)' }}>
    <div className="wrap">
      <div className="section-eyebrow" data-reveal>How it works</div>
      <h2 data-reveal>Set up on Monday. Audit-ready by Friday.</h2>
      <p className="lede-2" data-reveal>
        No migrations. No six-month rollouts. Bring your existing credit register and evidence, and we'll do the structuring for you.
      </p>
      <div className="how-grid">
        <div className="how-step" data-reveal>
          <span className="badge">1 · Connect</span>
          <div className="n">01</div>
          <h3>Point us at what you already have</h3>
          <p>Upload your IS credit register, sync SharePoint, and plug in email. Our AI reads existing evidence and maps it to the right credits automatically.</p>
        </div>
        <div className="how-step" data-reveal>
          <span className="badge">2 · Work</span>
          <div className="n">02</div>
          <h3>Your team works. The data follows.</h3>
          <p>Site photos, meeting notes, supplier PDFs — everything flows into one auditable timeline. No forms to fill, no folders to nest.</p>
        </div>
        <div className="how-step" data-reveal>
          <span className="badge">3 · Report</span>
          <div className="n">03</div>
          <h3>Report in one click, defend in one minute</h3>
          <p>Generate IS submissions, monthly ESG updates, and audit responses with a single prompt. Every answer cites the evidence behind it.</p>
        </div>
      </div>
    </div>
  </section>;


/* --- Design-partner call-out ------------------------------------------ */
const Partner = ({ onDemo }) =>
<section className="section">
    <div className="wrap">
      <div className="section-eyebrow" data-reveal>Early access</div>
      <h2 data-reveal>We're picking 3 design partners across active projects.</h2>
      <p className="lede-2" data-reveal>
        ISonTrack is in private beta with a small group of sustainability leaders on
        live Australian and New Zealand infrastructure programmes. If you're shaping
        an IS submission in the next 12 months, we'd like to build this with you —
        not for you. Tea, coffee, or a flat white — we'll come to site.
      </p>
      <div className="partner-card" data-reveal>
        <div>
          <div className="label">For public infra sustainability teams</div>
          <h3>Design-partner programme</h3>
          <p>
            Work directly with our team. Help shape the product. Get white-glove onboarding, a dedicated solution engineer, and founder-rate pricing for life.
          </p>
          <button className="btn btn-primary btn-lg" onClick={onDemo}>Apply as a design partner</button>
        </div>
        <ul className="partner-perks">
          <li><span className="chk"><Icon name="check" width="12" height="12" /></span><div><strong>Weekly build sessions</strong>Direct input into roadmap &amp; features</div></li>
          <li><span className="chk"><Icon name="check" width="12" height="12" /></span><div><strong>Dedicated onboarding</strong>Your IS register migrated &amp; modelled for you</div></li>
          <li><span className="chk"><Icon name="check" width="12" height="12" /></span><div><strong>Founder pricing, locked in</strong>Early-access rates that stay with you</div></li>
          <li><span className="chk"><Icon name="check" width="12" height="12" /></span><div><strong>No commitment</strong>60-day pilot, walk away with your data</div></li>
        </ul>
      </div>
    </div>
  </section>;


/* --- FAQ --------------------------------------------------------------- */
const FAQ = () => {
  const items = [
  { q: "Which rating schemes do you support?",
    a: "IS v2.1 and v1.2, plus Non-rating (resource tracking) out of the box, with future IS rating versions update guaranteed. Multiple government frameworks on the roadmap — priority set by our design partners." },
  { q: "My project doesn't pursue an IS rating. Do I still get value from ISonTrack?",
    a: "Absolutely. Any project tracking ESG metrics — water, energy and carbon, materials, waste, or social outcomes — benefits from ISonTrack as a shared workspace for data capture, validation, analysis, and reporting. You still get the collaboration layer, evidence quality scoring, and auto-generated reports — just without the IS credit framework layered on top." },
  { q: "How is ISonTrack different from a document-management tool?",
    a: "DMS tools store files. ISonTrack understands them — extracting evidence, linking it to credits, and keeping your IS score, carbon, and reporting live against that evidence. It's also a collaboration workspace: assign owners, process submissions, and run structured review cycles where every piece of evidence is scored for quality, completeness, and audit-readiness before it ever reaches a verifier. Think 'AI teammate' rather than 'Dropbox'." },
  { q: "Where does my data live? Is it secure?",
    a: "Your data lives in enterprise-grade cloud infrastructure hosted in Sydney, Australia (ISO 27001 / SOC 2 certified), encrypted at rest and in transit, with strict access controls so every user only sees their own project. We layer on mandatory two-factor authentication for sensitive roles, continuous monitoring, and a full trail of every access and change. Auditors love an audit trail — so do we." },
  { q: "Can our auditor / verifier use it too?",
    a: "Yes — read-only auditor seats are free. They see every credit, every piece of evidence, and every change — no exports, no emails, no 'can you resend the latest?'." },
  { q: "What does onboarding actually look like?",
    a: "Week 1: import your evidence sources and your IS register. Week 2: ready for AI to structure your existing evidence, flag gaps, and produce reports — ISonTrack fills in the rest." },
  { q: "How much does it cost?",
    a: "Design partners get founder-rate pricing, locked in for life. We'll walk through specifics in the demo — pricing is per project, not per seat, so your whole team and your auditors can use it. Get the outputs of +2 FTE for a fraction of the cost of 1 FTE." }];

  return (
    <section className="section" style={{ background: 'var(--cream)' }}>
      <div className="wrap">
        <div className="section-eyebrow" data-reveal>FAQ</div>
        <h2 data-reveal>Questions people ask on the first call.</h2>
        <div className="faq-list">
          {items.map((it, i) =>
          <details key={i} className="faq-item" data-reveal>
              <summary>
                {it.q}
                <span className="toggle"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M12 5v14M5 12h14" /></svg></span>
              </summary>
              <div className="body">{it.a}</div>
            </details>
          )}
        </div>
      </div>
    </section>);

};

/* --- Final CTA --------------------------------------------------------- */
const FinalCTA = ({ onDemo }) =>
<section className="final-cta">
    <div className="hero-grid-bg" />
    <div className="hero-beams"><div className="beam b1" /><div className="beam b2" /></div>
    <div className="wrap inner">
      <h2 data-reveal>Less paperwork.<br /><span className="grad">More impact.</span></h2>
      <p data-reveal>30-minute demo. Bring your toughest project metric — we'll show you the workflow you'd use to track it from tender to handover.</p>
      <div className="hero-cta-row" style={{ justifyContent: 'center' }} data-reveal>
        <button className="btn btn-primary btn-lg" onClick={onDemo}>
          Book a demo
        </button>
        <a href="https://app.isontrack.com" className="btn btn-secondary btn-lg">Log in</a>
      </div>
    </div>
  </section>;


/* --- Footer ------------------------------------------------------------ */
const Footer = () =>
<footer className="site-footer">
    <div className="wrap row">
      <Brand />
      <div className="links">
        <span className="soon">Terms &amp; conditions <em>(coming soon)</em></span>
        <span className="soon">Privacy policy <em>(coming soon)</em></span>
        <span className="soon">Contact <em>(coming soon)</em></span>
      </div>
      <div className="copy">© 2026 OnTrack Tech Ltd.</div>
    </div>
  </footer>;


/* --- Demo modal -------------------------------------------------------- */
const DemoModal = ({ open, onClose }) => {
  const [status, setStatus] = useState('idle');
  const [form, setForm] = useState({ name: '', company: '', role: '', email: '' });

  useEffect(() => {
    if (!open) {setStatus('idle');setForm({ name: '', company: '', role: '', email: '' });}
    const onKey = (e) => {if (e.key === 'Escape') onClose();};
    if (open) document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [open]);

  if (!open) return null;

  const submit = async (e) => {
    e.preventDefault();
    setStatus('sending');
    try {
      const res = await fetch(FORM_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          company: form.company,
          role: form.role,
          _subject: `Demo request — ${form.company || form.name}`,
          _replyto: form.email
        })
      });
      if (!res.ok) throw new Error(`Submit failed: ${res.status}`);
      setStatus('sent');
    } catch (err) {
      console.error(err);
      setStatus('error');
    }
  };

  const sending = status === 'sending';
  const sent = status === 'sent';
  const errored = status === 'error';

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true">
        <button className="modal-close" onClick={onClose} aria-label="Close">
          <Icon name="close" width="16" height="16" />
        </button>
        {sent ?
        <div className="modal-success">
            <div className="check"><Icon name="check" width="22" height="22" /></div>
            <h3>You're on the list.</h3>
            <p>We'll reach out within one business day to book a time. Check your inbox for a confirmation.</p>
          </div> :

        <>
            <div className="modal-header">
              <div className="hdr-bg" />
              <h3>Book a 30-minute demo</h3>
              <p>Tell us a little about you. We'll tailor the walkthrough to your project needs.</p>
            </div>
            <form className="modal-body" onSubmit={submit}>
              <div className="field-row">
                <div className="field">
                  <label>Full name</label>
                  <input type="text" required value={form.name}
                onChange={(e) => setForm({ ...form, name: e.target.value })}
                placeholder="Ana Ribeiro" />
                </div>
                <div className="field">
                  <label>Work email</label>
                  <input type="email" required value={form.email}
                onChange={(e) => setForm({ ...form, email: e.target.value })}
                placeholder="ana@agency.gov.au" />
                </div>
              </div>
              <div className="field">
                <label>Company or agency</label>
                <input type="text" required value={form.company}
              onChange={(e) => setForm({ ...form, company: e.target.value })}
              placeholder="Transport for NSW" />
              </div>
              <div className="field">
                <label>Your role</label>
                <select required value={form.role} onChange={(e) => setForm({ ...form, role: e.target.value })}>
                  <option value="">Select one…</option>
                  <option>Sustainability Manager</option>
                  <option>Environmental Manager</option>
                  <option>Project Director / PMO</option>
                  <option>Client / Asset Owner</option>
                  <option>Other</option>
                </select>
              </div>
              {errored &&
            <div className="form-error">
                  Something went wrong sending your request. Please email <a href="mailto:info@isontrack.com">info@isontrack.com</a> directly.
                </div>
            }
              <button type="submit" className="btn btn-primary" disabled={sending}>
                {sending ? 'Sending…' : 'Request my demo'}
              </button>
            </form>
          </>
        }
      </div>
    </div>);

};

/* --- Tweaks panel ------------------------------------------------------ */
const TweaksPanel = ({ state, setState, visible }) => {
  const persist = (patch) => {
    const next = { ...state, ...patch };
    setState(next);
    try {
      window.parent.postMessage({ type: '__edit_mode_set_keys', edits: patch }, '*');
    } catch (e) {}
  };
  const Seg = ({ field, options }) =>
  <div className="tw-seg">
      {options.map((opt) =>
    <button key={opt.val} className={state[field] === opt.val ? 'active' : ''} onClick={() => persist({ [field]: opt.val })}>
          {opt.label}
        </button>
    )}
    </div>;

  return (
    <div className={`tweaks-panel ${visible ? 'visible' : ''}`}>
      <h4><Icon name="sparkles" width="14" height="14" /> Tweaks</h4>
      <div className="tw-row">
        <div className="tw-label">Hero theme</div>
        <Seg field="hero_theme" options={[{ val: 'dark', label: 'Dark' }, { val: 'light', label: 'Light' }]} />
      </div>
      <div className="tw-row">
        <div className="tw-label">Hero layout</div>
        <Seg field="hero_layout" options={[{ val: 'centered', label: 'Split' }, { val: 'split', label: 'Split' }]} />
      </div>
      <div className="tw-row">
        <div className="tw-label">Motion</div>
        <Seg field="motion" options={[{ val: 'off', label: 'Off' }, { val: 'subtle', label: 'Subtle' }, { val: 'balanced', label: 'Balanced' }]} />
      </div>
      <div className="tw-row">
        <div className="tw-label">Headline</div>
        <Seg field="headline_variant" options={[
        { val: 'less_paperwork', label: 'Paper' },
        { val: 'ai_copilot', label: 'AI' },
        { val: 'built_for_infra', label: 'Infra' },
        { val: 'cut_admin', label: 'Metric' }]
        } />
      </div>
    </div>);

};

/* --- App --------------------------------------------------------------- */
const App = () => {
  const [state, setState] = useState(TWEAK_DEFAULTS);
  const [modalOpen, setModalOpen] = useState(false);
  const [tweaksVisible, setTweaksVisible] = useState(false);

  // Motion class on body
  useEffect(() => {
    document.body.classList.remove('motion-off', 'motion-subtle', 'motion-balanced');
    document.body.classList.add(`motion-${state.motion}`);
  }, [state.motion]);

  // Scroll reveal
  useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {if (e.isIntersecting) {e.target.classList.add('in');io.unobserve(e.target);}});
    }, { threshold: 0.08, rootMargin: '0px 0px -40px 0px' });
    document.querySelectorAll('[data-reveal]').forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);

  // Host edit-mode protocol
  useEffect(() => {
    const onMsg = (e) => {
      const d = e.data || {};
      if (d.type === '__activate_edit_mode') setTweaksVisible(true);
      if (d.type === '__deactivate_edit_mode') setTweaksVisible(false);
    };
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  const onDemo = () => setModalOpen(true);

  return (
    <div className={`landing landing--${state.hero_theme}`} data-screen-label="01 Landing">
      <Header theme={state.hero_theme} onDemo={onDemo} />
      <Hero theme={state.hero_theme} layout={state.hero_layout} headlineKey={state.headline_variant} onDemo={onDemo} />
      <Problem />
      <InfraStrip />
      <DemoReelSection />
      <HowItWorks />
      <Founders />
      <Partner onDemo={onDemo} />
      <FAQ />
      <FinalCTA onDemo={onDemo} />
      <Footer />
      <DemoModal open={modalOpen} onClose={() => setModalOpen(false)} />
      <TweaksPanel state={state} setState={setState} visible={tweaksVisible} />
    </div>);

};

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