// Home page
function HomePage({ onNavigate, openCaseStudy }) {
  return (
    <div className="page">
      {/* Hero */}
      <section className="hero">
        <div className="aurora"><div className="blob"></div></div>
        <div className="aurora-grid"></div>
        <div className="container">
          <div className="hero-grid">
            <div>
              <div className="rise" data-d="1" style={{ marginBottom: 24 }}>
                <span className="eyebrow">UK-built · Since 2014 · NHS &amp; government trusted</span>
              </div>
              <h1 className="hero-headline rise" data-d="2">
                Bespoke software,<br/><em className="grad-text">built right.</em>
              </h1>
              <p className="lead rise" data-d="3" style={{ marginTop: 28, maxWidth: 520 }}>
                We design, build and ship custom business software on our own development platform — so you get production-ready software in weeks, not quarters.
              </p>
              <div className="rise" data-d="4" style={{ display: "flex", gap: 12, marginTop: 36, flexWrap: "wrap" }}>
                <button className="btn btn-primary" onClick={() => onNavigate("contact")}>
                  Let's chat
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
                </button>
                <button className="btn btn-ghost" onClick={() => onNavigate("bespoke")}>
                  How we work
                </button>
              </div>
              <div className="rise" data-d="5" style={{ display: "flex", gap: 28, marginTop: 56, flexWrap: "wrap" }}>
                <Stat n="300+" l="Apps shipped" />
                <Stat n="2014" l="Building since" />
                <Stat n="99.998%" l="Platform uptime" />
              </div>
            </div>
            <div className="rise" data-d="3">
              <PlatformMock />
            </div>
          </div>
        </div>
      </section>

      {/* Trusted by — logo wall */}
      <section style={{ paddingBlock: 64, borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)" }}>
        <div className="container">
          <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", flexWrap: "wrap", gap: 16, marginBottom: 28 }}>
            <span className="mono" style={{ color: "var(--fg-faint)" }}>TRUSTED BY UK ORGANISATIONS</span>
            <a href="#/about" onClick={(e) => { e.preventDefault(); onNavigate("about"); }} className="btn-link">All clients <span className="arrow">→</span></a>
          </div>
          <div className="logo-wall">
            {TRUST_LOGOS.map((l) => (
              <div key={l.name} className="cell">
                <ClientLogo name={l.name} glyph={l.glyph} size={16} />
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Two paths */}
      <section>
        <div className="container">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 56, flexWrap: "wrap", gap: 24 }}>
            <div>
              <span className="eyebrow">How we help</span>
              <h2 className="h-large" style={{ marginTop: 16, maxWidth: 600 }}>
                Two paths. <span style={{ color: "var(--fg-faint)" }}>One platform.</span>
              </h2>
            </div>
            <p className="body" style={{ maxWidth: 380 }}>
              Whether you have a vision and need a partner to build it, or a team that wants to build it themselves — we have you covered.
            </p>
          </div>
          <div className="grid-2">
            <PathCard
              num="01"
              tag="Let us build it (recommended)"
              title="Bespoke software, delivered."
              copy="Bring us the idea — a brief, an itch, or a napkin sketch. We design, build, deliver and support production-ready software, on our own platform, so it's yours to extend forever. Most engagements ship in 6–12 weeks."
              cta="Talk to us about your project"
              onClick={() => onNavigate("bespoke")}
              accent
            />
            <PathCard
              num="02"
              tag="Build it yourself · waitlist"
              title="The ActiveManage Platform."
              copy="The visual development environment your in-house team has been waiting for. We onboard a small batch of new platform tenants per quarter to keep quality high — join the waitlist and we'll be in touch."
              cta="Join the platform waitlist"
              onClick={() => onNavigate("platform")}
            />
          </div>
        </div>
      </section>

      {/* Apple-style anatomy section */}
      <AnatomySection />

      {/* Use cases — buyer-language entry points */}
      <UseCasesSection onNavigate={onNavigate} />

      {/* Comparison */}
      <section style={{ background: "var(--bg-sunken)", borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)" }}>
        <div className="container">
          <span className="eyebrow">Why ActiveManage</span>
          <h2 className="h-large" style={{ marginTop: 16, marginBottom: 8, maxWidth: 800 }}>
            We replaced the framework, the database tier, and the boilerplate.
          </h2>
          <p className="lead" style={{ marginBottom: 48 }}>
            Compare against how everyone else still builds software in 2026.
          </p>

          <div className="cmp">
            <div className="cmp-row cmp-heading">
              <div className="cmp-metric"></div>
              <div className="cmp-old">
                <span className="cmp-coltag">The old way</span>
                <span className="cmp-colname">Manual development</span>
              </div>
              <div className="cmp-new">
                <span className="cmp-badge">Recommended</span>
                <span className="cmp-coltag" style={{ color: "var(--accent-ink)", opacity: 0.7 }}>The AM way</span>
                <span className="cmp-colname">ActiveManage</span>
              </div>
            </div>
            {[
              ["clock",   "Time to market",       "9–18 months",        "2–8 weeks"],
              ["wrench",  "Maintenance burden",   "Falls on your team", "Included in the platform"],
              ["shield",  "Security posture",     "Do-it-yourself",     "OWASP+, CREST-tested"],
              ["server",  "Hosting & scaling",    "Provision it yourself", "UK-sovereign, one click"],
              ["key",     "Knowledge lock-in",    "High — walks out the door", "Visual, kept in-house"],
              ["refresh", "Update cadence",       "Whenever you can",   "Continuous, inherited"],
              ["coins",   "Cost over 5 years",    "£££",                "£"],
            ].map(([icon, metric, oldv, newv], i) => (
              <div className="cmp-row" key={metric}>
                <div className="cmp-metric"><CmpIcon name={icon} /> {metric}</div>
                <div className="cmp-old"><Cross /> <span>{oldv}</span></div>
                <div className="cmp-new"><Check /> <span>{newv}</span></div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Apple-style interactive builder */}
      <BuilderSection />

      {/* AI onboarding */}
      <AiOnboardingSection />

      {/* Integrated ITSM — support built into every app */}
      <ItsmSection onNavigate={onNavigate} />

      {/* Case studies — hidden
      <section>
        <div className="container">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 48, flexWrap: "wrap", gap: 24 }}>
            <div>
              <span className="eyebrow">Selected work</span>
              <h2 className="h-large" style={{ marginTop: 16 }}>Case studies.</h2>
            </div>
            <button className="btn-link" onClick={() => onNavigate("about")}>
              All case studies <span className="arrow">→</span>
            </button>
          </div>
          <div className="grid-2">
            <CaseCard
              slug="oneportal"
              client="OnePortal"
              title="First-aid incident recording for UK schools, GDPR-grade."
              tags={["EdTech", "Multi-tenant", "Safeguarding"]}
              metric={{ k: "injury categories", v: "16" }}
              onClick={() => openCaseStudy("oneportal")}
              accent
            />
            <CaseCard
              slug="halliday"
              client="Halliday Lighting"
              title="Asset tracking and digital site-maintenance for the UK's only dedicated sports-lighting specialist."
              tags={["Field services", "Mobile", "Barcode"]}
              metric={{ k: "asset types", v: "18" }}
              onClick={() => openCaseStudy("halliday")}
            />
          </div>
          <div className="grid-2" style={{ marginTop: 24 }}>
            <CaseCard
              slug="compliantepc"
              client="Compliant EPC"
              title="Quote, invoice and release certificates — from one back-office."
              tags={["Field services", "Stripe", "Documents"]}
              metric={{ k: "less time chasing payment", v: "80%" }}
              onClick={() => openCaseStudy("compliantepc")}
            />
            <CaseCard
              slug="leaphub"
              client="LeapHub"
              title="Work-experience applications, processed end-to-end."
              tags={["EdTech", "Multi-sided", "Schools"]}
              metric={{ k: "weeks to MVP", v: "6" }}
              onClick={() => openCaseStudy("leaphub")}
            />
          </div>
        </div>
      </section>
      */}

      {/* Testimonials */}
      <section className="section-warm" style={{ borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)" }}>
        <div className="container">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 48, flexWrap: "wrap", gap: 24 }}>
            <div>
              <span className="eyebrow">What clients say</span>
              <h2 className="h-large" style={{ marginTop: 16 }}>Taken at <em style={{ fontFamily: "Instrument Serif, serif", fontStyle: "italic", fontWeight: 400 }} className="grad-text">their word.</em></h2>
            </div>
            <p className="body" style={{ maxWidth: 340 }}>
              We don't do case-study theatre. These are the people who use the software every day.
            </p>
          </div>
          <div className="testis">
            <div className="testi">
              <blockquote>“They understood safeguarding better than vendors who'd been in education for a decade. Schools actually enjoy using it.”</blockquote>
              <footer>
                <span className="avatar" style={{ background: "oklch(0.5 0.18 264)" }}>OP</span>
                <div>
                  <div className="who">Founder</div>
                  <div className="role">ONEPORTAL</div>
                </div>
              </footer>
            </div>
            <div className="testi">
              <blockquote>“Every piece of kit is accounted for — for the first time in the company's history. The engineers took to it in a fortnight.”</blockquote>
              <footer>
                <span className="avatar" style={{ background: "oklch(0.32 0.04 260)" }}>HL</span>
                <div>
                  <div className="who">Operations Director</div>
                  <div className="role">HALLIDAY LIGHTING</div>
                </div>
              </footer>
            </div>
            <div className="testi">
              <blockquote>“Invoicing that used to eat evenings now happens on its own. The system pays for itself monthly.”</blockquote>
              <footer>
                <span className="avatar" style={{ background: "oklch(0.55 0.16 145)" }}>CE</span>
                <div>
                  <div className="who">Director</div>
                  <div className="role">COMPLIANT EPC</div>
                </div>
              </footer>
            </div>
          </div>
        </div>
      </section>

      {/* Big CTA */}
      <section className="section-dark" style={{ borderRadius: 0 }}>
        <div className="container" style={{ textAlign: "center", paddingBlock: 60 }}>
          <span className="eyebrow" style={{ color: "rgba(255,255,255,0.6)" }}>Ready when you are</span>
          <h2 className="h-display" style={{ marginTop: 24, marginBottom: 24 }}>
            Stop rebuilding<br/><em style={{ fontStyle: "italic", fontFamily: "Instrument Serif, serif", fontWeight: 400 }}>foundations.</em> Start shipping.
          </h2>
          <p className="lead" style={{ margin: "0 auto 36px", color: "rgba(255,255,255,0.7)" }}>
            Talk to us about replacing your stack of frameworks, plug-ins and consultancies with one platform.
          </p>
          <div style={{ display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap" }}>
            <button className="btn btn-accent" onClick={() => onNavigate("platform")}>
              Join the platform waitlist
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
            </button>
            <button className="btn btn-ghost" style={{ borderColor: "rgba(255,255,255,0.25)", color: "white" }} onClick={() => onNavigate("platform")}>
              See the platform
            </button>
          </div>
        </div>
      </section>
    </div>
  );
}

function Stat({ n, l }) {
  const [txt, setTxt] = React.useState(n);
  const ref = React.useRef(null);
  React.useEffect(() => {
    const m = n.match(/^([^0-9]*)([\d.,]+)(.*)$/);
    if (!m || !ref.current) return;
    const target = parseFloat(m[2].replace(/,/g, ""));
    const decimals = (m[2].split(".")[1] || "").length;
    const io = new IntersectionObserver(([e]) => {
      if (!e.isIntersecting) return;
      io.disconnect();
      const t0 = performance.now();
      const tick = (t) => {
        const p = Math.min(1, (t - t0) / 1300);
        const eased = 1 - Math.pow(1 - p, 3);
        setTxt(m[1] + (target * eased).toLocaleString("en-GB", { minimumFractionDigits: decimals, maximumFractionDigits: decimals, useGrouping: false }) + m[3]);
        if (p < 1) requestAnimationFrame(tick);
      };
      requestAnimationFrame(tick);
    }, { threshold: 0.6 });
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  return (
    <div ref={ref}>
      <div style={{ fontFamily: "var(--font-display)", fontSize: 28, fontWeight: 500, letterSpacing: "-0.025em", fontFeatureSettings: '"tnum"' }}>{txt}</div>
      <div className="mono" style={{ color: "var(--fg-faint)", marginTop: 2 }}>{l}</div>
    </div>
  );
}

function PathCard({ num, tag, title, copy, cta, onClick, accent }) {
  return (
    <button
      onClick={onClick}
      style={{
        textAlign: "left",
        background: accent ? "var(--fg)" : "var(--bg-elev)",
        color: accent ? "var(--bg)" : "var(--fg)",
        border: "1px solid var(--line)",
        borderColor: accent ? "var(--fg)" : "var(--line)",
        borderRadius: 16,
        padding: "40px",
        position: "relative",
        overflow: "hidden",
        transition: "transform 0.3s, box-shadow 0.3s",
        cursor: "pointer",
        minHeight: 360,
        display: "flex",
        flexDirection: "column",
        justifyContent: "space-between",
      }}
      onMouseEnter={(e) => { e.currentTarget.style.transform = "translateY(-4px)"; e.currentTarget.style.boxShadow = "var(--shadow-lg)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.transform = ""; e.currentTarget.style.boxShadow = ""; }}
    >
      <div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 56 }}>
          <span className="mono" style={{ color: accent ? "color-mix(in srgb, var(--bg) 55%, transparent)" : "var(--fg-faint)" }}>{num} / {tag}</span>
          {accent && <span className="chip-accent chip">Most popular</span>}
        </div>
        <h3 className="h-medium" style={{ marginBottom: 16 }}>{title}</h3>
        <p style={{ color: accent ? "color-mix(in srgb, var(--bg) 72%, transparent)" : "var(--fg-muted)", maxWidth: 420, fontSize: 16 }}>{copy}</p>
      </div>
      <div style={{ display: "inline-flex", alignItems: "center", gap: 8, marginTop: 32, fontWeight: 500 }}>
        {cta} <span>→</span>
      </div>
    </button>
  );
}

function CmpIcon({ name }) {
  const p = {
    clock:   <><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></>,
    wrench:  <path d="M14 7a4 4 0 0 1-5 5l-5 5 3 3 5-5a4 4 0 0 0 5-5l-2 2-3-3z"/>,
    shield:  <path d="M12 3 5 6v5c0 4 3 7 7 8 4-1 7-4 7-8V6z"/>,
    server:  <><rect x="4" y="4" width="16" height="7" rx="1.5"/><rect x="4" y="13" width="16" height="7" rx="1.5"/><path d="M8 7.5h.01M8 16.5h.01"/></>,
    key:     <><circle cx="8" cy="12" r="4"/><path d="M12 12h9M17 12v4M20 12v3"/></>,
    refresh: <><path d="M4 12a8 8 0 0 1 14-5l2 2M20 12a8 8 0 0 1-14 5l-2-2"/><path d="M20 4v5h-5M4 20v-5h5"/></>,
    coins:   <><ellipse cx="9" cy="7" rx="6" ry="3"/><path d="M3 7v5c0 1.7 2.7 3 6 3M3 12v5c0 1.7 2.7 3 6 3"/><ellipse cx="16" cy="15" rx="5" ry="2.5"/></>,
  }[name] || <circle cx="12" cy="12" r="8"/>;
  return <svg className="cmp-ic" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">{p}</svg>;
}
function Check() { return <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M5 13l4 4L19 7"/></svg>; }
function Cross() { return <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 6l12 12M18 6L6 18"/></svg>; }

function CaseCard({ slug, client, title, tags, metric, accent, onClick }) {
  const logo = slug && CLIENT_LOGOS[slug];
  // Per-card colour — gives the case-study row visual variety in light mode
  const tints = {
    oneportal:    { bg: "linear-gradient(135deg, oklch(0.55 0.18 264), oklch(0.42 0.2 280))", ink: "#fff", pat: "#fff" },
    halliday:     { bg: "linear-gradient(135deg, oklch(0.32 0.04 260), oklch(0.2 0.03 260))", ink: "#fff", pat: "var(--accent-4)" },
    compliantepc: { bg: "linear-gradient(135deg, oklch(0.62 0.18 145), oklch(0.5 0.16 155))", ink: "#fff", pat: "#fff" },
    leaphub:      { bg: "linear-gradient(135deg, oklch(0.65 0.21 28), oklch(0.5 0.2 18))",   ink: "#fff", pat: "#fff" },
  };
  const tint = (slug && tints[slug]) || { bg: accent ? "var(--accent)" : "var(--bg-sunken)", ink: accent ? "var(--accent-ink)" : "var(--fg)", pat: "currentColor" };

  return (
    <button onClick={onClick} className="card" style={{
      textAlign: "left",
      cursor: "pointer",
      padding: 0,
      overflow: "hidden",
      display: "flex",
      flexDirection: "column",
      minHeight: 420,
    }}
    onMouseEnter={(e) => { e.currentTarget.style.transform = "translateY(-4px)"; e.currentTarget.style.boxShadow = "var(--shadow-md)"; }}
    onMouseLeave={(e) => { e.currentTarget.style.transform = ""; e.currentTarget.style.boxShadow = ""; }}
    >
      <div style={{
        height: 220,
        background: tint.bg,
        display: "flex",
        alignItems: "flex-end",
        justifyContent: "space-between",
        padding: 28,
        position: "relative",
        overflow: "hidden",
        color: tint.ink,
      }}>
        {/* Pattern */}
        <svg style={{ position: "absolute", inset: 0, width: "100%", height: "100%", opacity: 0.12, color: tint.pat }} aria-hidden>
          <defs>
            <pattern id={`p-${slug || client}`} width="28" height="28" patternUnits="userSpaceOnUse">
              <circle cx="2" cy="2" r="1.2" fill="currentColor" />
            </pattern>
          </defs>
          <rect width="100%" height="100%" fill={`url(#p-${slug || client})`} />
        </svg>
        {/* Big logo */}
        <div style={{ display: "flex", flexDirection: "column", justifyContent: "space-between", height: "100%", width: "100%", position: "relative", zIndex: 1 }}>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 10, fontFamily: "var(--font-mono)", fontSize: 11, opacity: 0.85, letterSpacing: "0.06em", textTransform: "uppercase" }}>
            <span style={{ width: 6, height: 6, borderRadius: 3, background: "currentColor" }}></span>
            Case study
          </div>
          <CaseCardWordmark slug={slug} ink={tint.ink} />
        </div>
      </div>
      <div style={{ padding: 28, flex: 1, display: "flex", flexDirection: "column", justifyContent: "space-between" }}>
        <div>
          <div style={{ display: "flex", gap: 6, marginBottom: 16, flexWrap: "wrap" }}>
            {tags.map(t => <span key={t} className="chip">{t}</span>)}
          </div>
          <h3 className="h-small" style={{ marginBottom: 12 }}>{title}</h3>
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginTop: 24 }}>
          <div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 32, fontWeight: 500, letterSpacing: "-0.025em" }}>{metric.v}</div>
            <div className="mono" style={{ color: "var(--fg-faint)" }}>{metric.k}</div>
          </div>
          <span style={{ fontSize: 13, fontWeight: 500, display: "inline-flex", alignItems: "center", gap: 6 }}>
            Read case study →
          </span>
        </div>
      </div>
    </button>
  );
}

Object.assign(window, { HomePage });
