// Kestral v2 — page sections.

// Public beta installer links — fill in real URLs when ready.
const KESTRAL_DL = {
  windows: 'https://github.com/AEl-Mahdey/kestral-releases/releases/download/v0.5.2/Kestral-Setup-0.5.2.exe',
  macArm: 'https://github.com/AEl-Mahdey/kestral-releases/releases/download/v0.5.2/Kestral-0.5.2-arm64.dmg',
  macIntel: 'https://github.com/AEl-Mahdey/kestral-releases/releases/download/v0.5.2/Kestral-0.5.2-x64.dmg',
  version: '0.5.2',
};

const DISCORD_URL = 'https://discord.gg/DmVbrXzxS';
const CONTACT_URL = 'mailto:ahmed@buildwithkestral.com';

// OS detection — default the primary CTA to the visitor's platform.
const detectOS = () => {
  const p = (navigator.userAgentData && navigator.userAgentData.platform) || navigator.platform || '';
  return /win/i.test(p) ? 'windows' : 'mac';
};

const DlIcon = () => (
  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
    <path d="M7 1.5v7.5M3.8 6.2 7 9.4l3.2-3.2M2 12h10" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
  </svg>
);

const Eyebrow = ({ children }) => (
  <div className="font-mono text-[12px] text-paper3 tracking-[0.02em] mb-4">// {children}</div>
);

// ---------- NAV ----------
const Nav = () => (
  <header className="fixed top-0 inset-x-0 z-50 nav-blur hairline-b" style={{ background: 'rgba(10,11,13,0.78)' }}>
    <div className="max-page h-[60px] flex items-center justify-between">
      <a href="#" aria-label="Kestral home" style={{ filter: 'drop-shadow(0 0 14px rgba(91,95,255,0.45))' }}><KLogo h={30} /></a>
      <nav className="hidden md:flex items-center gap-7 text-[13px] text-paper2">
        <a href="#how" className="hover:text-paper transition-colors">How it works</a>
        <a href="#features" className="hover:text-paper transition-colors">Features</a>
        <a href="#iterate" className="hover:text-paper transition-colors">After the build</a>
        <a href="#agents" className="hover:text-paper transition-colors">Agents</a>
      </nav>
      <a href="#download" className="text-[13px] font-medium px-3.5 py-2 rounded-md inline-flex items-center gap-2 btn-indigo">
        <DlIcon /> Download
      </a>
    </div>
  </header>
);

// ---------- HERO ----------
const Hero = () => {
  const [os] = React.useState(detectOS);
  const primaryLabel = os === 'windows' ? 'Download for Windows' : 'Download for macOS';
  return (
    <section className="relative overflow-hidden hero-grid">
      <div className="absolute inset-0 hero-vignette pointer-events-none"></div>
      <div className="max-page relative pt-[150px] md:pt-[170px] pb-10 text-center">
        <Eyebrow>vague prompts produce vague apps</Eyebrow>
        <h1 className="h-display text-[44px] md:text-[68px] text-paper mx-auto max-w-[860px]">
          Design your project.<br />Ship it with <span className="accent">your agent</span>.
        </h1>
        <p className="text-[15.5px] md:text-[17px] text-paper2 leading-[1.6] max-w-[620px] mx-auto mt-6" style={{ textWrap: 'pretty' }}>
          Kestral is a visual blueprint builder for AI coding agents. Wireframe your screens,
          define your schema, spec your endpoints and logic. It all compiles into one
          <span className="codechip mx-1.5">blueprint.xml</span>
          and your agent builds exactly that. Then keep going after the build: iterate,
          run, and test with an agent that already knows your whole app.
        </p>
        <div className="mt-9 flex flex-col sm:flex-row items-center justify-center gap-4">
          <a href="#download" className="btn-indigo text-[14.5px] font-medium px-5 py-3 rounded-md inline-flex items-center gap-2.5">
            <DlIcon /> {primaryLabel}
            <span className="font-mono text-[10px] tracking-wide px-1.5 py-[3px] rounded bg-white/20">FREE</span>
          </a>
          <a href="#how" className="lnk text-[14px]">See how it works <span className="arr">↓</span></a>
        </div>
        <div className="mt-4 font-mono text-[11.5px] text-paper3">
          <span className="text-paper2">free during the public beta</span> · v{KESTRAL_DL.version} · macOS &amp; Windows
        </div>
        {/* hero visual */}
        <div className="relative mt-16 md:mt-20 text-left">
          <div className="absolute -inset-x-10 top-10 bottom-0 pointer-events-none" style={{ background: 'radial-gradient(58% 50% at 50% 38%, rgba(91,95,255,0.13), transparent 70%)' }}></div>
          <div className="relative tilt">
            <KShot src="assets/screen-schema-cropped.png" alt="Kestral schema editor: DBML on the left, live entity diagram on the right" title="Kestral · Backend / Schema" badge="● auto-saved" />
          </div>
          <div className="absolute -left-2 md:left-6 -bottom-8 hidden sm:block"><BlueprintSnippet /></div>
          <div className="absolute right-2 md:right-8 -top-6 hidden sm:block"><TokenChip /></div>
        </div>
      </div>
      <div className="h-16"></div>
    </section>
  );
};

// ---------- WHY KESTRAL / PITCH VIDEO ----------
const PitchVideo = () => (
  <section id="pitch" className="py-28 md:py-36 hairline-t relative overflow-hidden">
    <div className="absolute inset-0 pointer-events-none" style={{ background: 'radial-gradient(ellipse at 50% 0%, rgba(91,95,255,0.08) 0%, transparent 55%)' }}></div>
    <div className="max-page relative">
      <div className="rv max-w-[720px] mb-14">
        <Eyebrow>why kestral</Eyebrow>
        <h2 className="h-display text-[34px] md:text-[44px] text-paper">Why Kestral,<br />in five minutes.</h2>
        <p className="mt-5 text-[14.5px] md:text-[15.5px] text-paper2 max-w-[560px] leading-[1.65]" style={{ textWrap: 'pretty' }}>
          What Kestral is, how it works, and where it fits in a world of AI coding agents.
          A short walkthrough from the people building it.
        </p>
      </div>
      <div className="rv max-w-[1060px] mx-auto">
        <div className="rounded-[10px] overflow-hidden bg-ink2 lift">
          <div className="flex items-center justify-between px-3.5 h-9 hairline-b" style={{ background: '#0D0E12' }}>
            <KTrafficLights />
            <span className="text-[11.5px] font-mono text-paper3 inline-flex items-center gap-2">
              <span className="w-1.5 h-1.5 rounded-full pulse-dot" style={{ background: '#5B5FFF' }}></span>
              buildwithkestral.com / pitch
            </span>
            <a href="https://www.youtube.com/watch?v=xjdZIig96ow" target="_blank" rel="noreferrer" className="text-[10.5px] font-mono text-paper3 hover:text-paper2">youtube ↗</a>
          </div>
          <div className="relative bg-black" style={{ aspectRatio: '16 / 9' }}>
            <iframe
              src="https://www.youtube.com/embed/xjdZIig96ow?rel=0&modestbranding=1"
              title="Kestral · the pitch"
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; fullscreen"
              allowFullScreen
              className="absolute inset-0 w-full h-full"
              style={{ border: 0 }}>
            </iframe>
          </div>
        </div>
      </div>
    </div>
  </section>
);

// ---------- HOW IT WORKS ----------
const Step = ({ n, title, body, children }) => (
  <div className="rv flex flex-col">
    <div className="font-mono text-[12px] text-paper3 mb-3">{n}</div>
    <h3 className="text-[19px] font-medium text-paper tracking-tight mb-2.5">{title}</h3>
    <p className="text-[13.5px] text-paper2 leading-[1.65] mb-6" style={{ textWrap: 'pretty' }}>{body}</p>
    <div className="mt-auto">{children}</div>
  </div>
);

const HowItWorks = () => (
  <section id="how" className="py-28 md:py-36 hairline-t">
    <div className="max-page">
      <div className="rv">
        <Eyebrow>how it works</Eyebrow>
        <h2 className="h-display text-[34px] md:text-[44px] text-paper max-w-[560px] mb-16">
          Complete clarity, <span className="accent">then</span> execution.
        </h2>
      </div>
      <div className="grid md:grid-cols-3 gap-10 md:gap-8">
        <Step n="01" title="Design it visually"
          body="Wireframe every screen on a canvas, write your schema in DBML, spec endpoints, business rules, and state machines. Toggle the services you need.">
          <MiniCanvas />
        </Step>
        <Step n="02" title="Kestral compiles it"
          body="Everything becomes blueprint.xml: a complete, machine-readable spec with token estimates. Deterministic and inspectable, not a black box.">
          <MiniBlueprint />
        </Step>
        <Step n="03" title="Your agent builds it"
          body="Kestral spawns Claude Code, Codex, or Antigravity locally and streams the build live: file-by-file activity, token usage, elapsed time.">
          <MiniBuildFeed />
        </Step>
      </div>
    </div>
  </section>
);

// ---------- FEATURE DEEP-DIVES ----------
const Feature = ({ id, eyebrow, title, body, points, flip, children, extra }) => (
  <div id={id} className="rv grid md:grid-cols-12 gap-10 md:gap-12 items-center py-16 md:py-20">
    <div className={`md:col-span-5 ${flip ? 'md:order-2' : ''}`}>
      <Eyebrow>{eyebrow}</Eyebrow>
      <h3 className="h-display text-[28px] md:text-[34px] text-paper mb-4">{title}</h3>
      <p className="text-[14.5px] text-paper2 leading-[1.65]" style={{ textWrap: 'pretty' }}>{body}</p>
      {points && (
        <ul className="mt-5 flex flex-col gap-2.5">
          {points.map((p, i) => (
            <li key={i} className="flex items-start gap-2.5 text-[13.5px] text-paper2">
              <span className="mt-[7px] w-1 h-1 rounded-full shrink-0" style={{ background: '#5B5FFF' }}></span>
              <span>{p}</span>
            </li>
          ))}
        </ul>
      )}
      {extra && <div className="mt-6">{extra}</div>}
    </div>
    <div className={`md:col-span-7 ${flip ? 'md:order-1' : ''}`}>{children}</div>
  </div>
);

const Features = () => (
  <section id="features" className="py-12 md:py-16 hairline-t">
    <div className="max-page">
      <div className="rv pt-12">
        <Eyebrow>the blueprint</Eyebrow>
        <h2 className="h-display text-[34px] md:text-[44px] text-paper max-w-[640px]">
          Specify everything. <span className="accent">Visually.</span>
        </h2>
      </div>

      <Feature id="canvas" eyebrow="01 · wireframe canvas" title="Draw every screen before anyone codes it."
        body="An infinite Excalidraw-based canvas for your whole frontend. Sketch each screen, link the flows, keep them all in view. Every frame is exported into the blueprint."
        points={[
          'Multi-screen: one canvas for the entire app',
          'Familiar drawing tools, zero learning curve',
          'Screens map 1:1 to routes in the compiled spec',
        ]}>
        <MockCanvas />
      </Feature>

      <Feature flip eyebrow="02 · live schema editor" title="Your schema, rendered as you type."
        body="Write DBML on the left and watch the entity diagram draw itself on the right. Relational or non-relational. Errors get inline squiggles before they ever reach an agent."
        points={[
          'Live DBML → entity-relationship diagram',
          'Relational and non-relational modes',
          'SQL export · inline error checking',
        ]}>
        <KShot src="assets/screen-schema-cropped.png" alt="Live DBML schema editor with entity diagram" title="Kestral · Backend / Schema" badge="schema.dbml" />
      </Feature>

      <Feature eyebrow="03 · endpoints & business logic" title="The behavior, written down."
        body="Structured endpoint tables with method, path, and auth instead of prose. Event-action rules capture what happens when. And every data model with a status field gets an auto-suggested state machine you can edit visually."
        extra={<MockStateMachine />}>
        <KShot src="assets/screen-endpoints-cropped.png" alt="Structured API endpoint table with method, path, and auth" title="Kestral · Backend / API Endpoints" badge="11 endpoints" />
      </Feature>

      <Feature flip eyebrow="04 · services" title="Integrations are a toggle, not a tutorial."
        body="17+ built-in services: auth, payments, email, hosting, databases. Flip them on and they're specified into the blueprint with env examples. Need something custom? Paste an npm package or URL and Kestral imports it automatically."
        points={[
          'Auth, payments, email, hosting, DB & more',
          'Example .env generated for enabled services',
          'Paste any npm package or URL → custom service',
        ]}>
        <KShot src="assets/screen-services-cropped.png" alt="Service integrations with toggles" title="Kestral · Services / Integrations" badge="4 enabled" />
      </Feature>

      <Feature eyebrow="05 · build screen" title="Watch the build, file by file."
        body="Kestral streams your agent's work live: files created and modified, commands run, real token usage against the estimate, elapsed time. When it's done, open in Finder or VS Code, or launch the dev server."
        points={[
          'Live activity feed with timestamps',
          'Real token usage vs. blueprint estimate',
          'Open in Finder / VS Code · run dev server',
        ]}>
        <KShot src="assets/screen-build-cropped.png" alt="Live build screen with file-by-file activity feed and token usage" title="Kestral · Build / Claude Code" badge="● building" />
      </Feature>

      <Feature flip eyebrow="06 · import existing project" title="Already have a codebase? Reverse it."
        body="Point Kestral at an existing JS/TS project and it reconstructs the blueprint: pages, schema, endpoints, services, business logic. Each section gets a confidence level so you know exactly what to review."
        points={[
          'Works on existing JavaScript / TypeScript repos',
          'Per-section confidence levels, nothing hidden',
          'Edit the recovered blueprint, then build forward',
        ]}>
        <MockImport />
      </Feature>
    </div>
  </section>
);

// ---------- AFTER THE BUILD ----------
const PostBuild = () => (
  <section id="iterate" className="py-12 md:py-16 hairline-t">
    <div className="max-page">
      <div className="rv pt-12">
        <Eyebrow>after the build</Eyebrow>
        <h2 className="h-display text-[34px] md:text-[44px] text-paper max-w-[640px]">
          The first build is <span className="accent">the beginning</span>.
        </h2>
      </div>

      {/* 07 · iterate — full-width screenshot */}
      <div className="rv py-16 md:py-20">
        <div className="grid md:grid-cols-12 gap-10 md:gap-12 mb-10">
          <div className="md:col-span-5">
            <Eyebrow>07 · iterate</Eyebrow>
            <h3 className="h-display text-[28px] md:text-[34px] text-paper mb-4">Keep talking to the agent that built it.</h3>
            <p className="text-[14.5px] text-paper2 leading-[1.65]" style={{ textWrap: 'pretty' }}>
              The project stays open when the build finishes. Ask for new features, bug fixes,
              or refactors in plain language. The blueprint is already loaded as context,
              so the agent knows exactly what it built and why.
            </p>
          </div>
          <div className="md:col-span-6 md:col-start-7 md:self-end">
            <ul className="flex flex-col gap-2.5">
              {[
                'Blueprint loaded as context, no re-explaining your app',
                'Run the dev server and rebuild without leaving Kestral',
                'Changes and tests tracked per build, tab by tab',
              ].map((p, i) => (
                <li key={i} className="flex items-start gap-2.5 text-[13.5px] text-paper2">
                  <span className="mt-[7px] w-1 h-1 rounded-full shrink-0" style={{ background: '#5B5FFF' }}></span>
                  <span>{p}</span>
                </li>
              ))}
            </ul>
          </div>
        </div>
        <KShot src="assets/screen-agent-iterate-cropped.png" alt="Kestral agent tab after a completed build: ask Claude Code to change something, run dev, rebuild" title="Kestral · Agent / Build complete" badge="● build #1 complete" />
      </div>

      {/* 08 · architecture map */}
      <Feature flip eyebrow="08 · architecture" title="Every file, explained and connected."
        body="The Architecture tab maps the codebase your agent produced. Every file carries a plain-English description of what it does and what it exports, and edges trace what imports what, so you read the project like a diagram, not a directory."
        points={[
          'Per-file descriptions, generated from the code itself',
          'Exports surfaced: functions, components, types',
          'Files color-coded by role: pages, routes, models, config',
          'Jump from any node straight into VS Code',
        ]}>
        <KShot src="assets/screen-architecture-cropped.png" alt="Kestral architecture tab: dependency graph of generated files with an inspector showing env.ts description, exports, and imports" title="Kestral · Architecture / Files" badge="lib/env.ts" />
      </Feature>

      {/* 09 · playwright tests */}
      <Feature eyebrow="09 · tests" title="Generated tests, one click to run."
        body="Kestral generates a Playwright suite straight from your blueprint: every endpoint you specced, your auth rules, and your critical business flows become end-to-end tests. Run the whole suite or a single test and watch the output stream live."
        points={[
          'Suites for API endpoints, auth, and business flows',
          'Run all or one test at a time, with live output',
          'Pass, fail, and timing per test; open any spec in your editor',
        ]}>
        <KShot src="assets/screen-tests-cropped.png" alt="Kestral tests tab: generated Playwright suite with live output, all 22 tests passing, per-test run and open buttons" title="Kestral · Tests / Playwright" badge="22 passed (26.3s)" />
      </Feature>
    </div>
  </section>
);

// ---------- MULTI-AGENT STRIP ----------
const AgentCard = ({ name, vendor }) => (
  <div className="hairline rounded-lg bg-ink2 px-5 py-4 flex items-center justify-between gap-4">
    <div>
      <div className="text-[14.5px] font-medium text-paper tracking-tight">{name}</div>
      <div className="font-mono text-[11px] text-paper3 mt-0.5">{vendor}</div>
    </div>
    <span className="w-1.5 h-1.5 rounded-full" style={{ background: '#5B5FFF' }}></span>
  </div>
);

const Agents = () => (
  <section id="agents" className="py-24 md:py-28 hairline-t">
    <div className="max-page">
      <div className="rv grid md:grid-cols-12 gap-10 items-center">
        <div className="md:col-span-5">
          <Eyebrow>agents</Eyebrow>
          <h2 className="h-display text-[30px] md:text-[38px] text-paper mb-4">
            Bring the agent you already use.
          </h2>
          <p className="text-[14.5px] text-paper2 leading-[1.65]" style={{ textWrap: 'pretty' }}>
            No API keys to paste, no tokens to buy. Kestral drives the agent CLIs already
            installed and signed in on your machine. It hands them the blueprint and gets out of the way.
          </p>
        </div>
        <div className="md:col-span-7 grid sm:grid-cols-3 gap-3">
          <AgentCard name="Claude Code" vendor="Anthropic" />
          <AgentCard name="Codex" vendor="OpenAI" />
          <AgentCard name="Antigravity" vendor="Google" />
        </div>
      </div>
    </div>
  </section>
);

// ---------- DOWNLOAD ----------
const DlButton = ({ href, os, sub, primary }) => (
  <a href={href} className={`group rounded-lg px-5 py-4 flex items-center justify-between gap-4 transition-colors ${primary ? 'btn-indigo' : 'hairline bg-ink2 hover:bg-white/[0.04]'}`}>
    <span>
      <span className={`block text-[14.5px] font-medium tracking-tight ${primary ? '' : 'text-paper'}`}>{os}</span>
      <span className={`block font-mono text-[11px] mt-0.5 ${primary ? 'opacity-80' : 'text-paper3'}`}>{sub}</span>
    </span>
    <span className={primary ? '' : 'accent'}><DlIcon /></span>
  </a>
);

const Callout = ({ os, title, body }) => (
  <div className="hairline rounded-lg p-4">
    <div className="font-mono text-[10.5px] text-paper3 mb-1.5">{os}</div>
    <div className="text-[12.5px] text-paper font-medium mb-1">{title}</div>
    <p className="text-[12px] text-paper2 leading-[1.6]" style={{ textWrap: 'pretty' }}>{body}</p>
  </div>
);

const Download = () => {
  const [os] = React.useState(detectOS);
  return (
    <section id="download" className="py-28 md:py-36 hairline-t relative overflow-hidden">
      <div className="absolute inset-0 pointer-events-none" style={{ background: 'radial-gradient(50% 60% at 50% 100%, rgba(91,95,255,0.09), transparent 70%)' }}></div>
      <div className="max-page relative">
        <div className="rv grid md:grid-cols-12 gap-12 items-start">
          <div className="md:col-span-5">
            <Eyebrow>download</Eyebrow>
            <h2 className="h-display text-[36px] md:text-[44px] text-paper mb-5">Get the public beta.</h2>
            <p className="text-[14.5px] text-paper2 leading-[1.65] max-w-[380px]" style={{ textWrap: 'pretty' }}>
              Free during the beta. You'll need at least one supported agent CLI installed
              and signed in: Claude Code, Codex, or Antigravity.
            </p>
            <div className="mt-7 flex items-center gap-2 font-mono text-[11.5px] text-paper3">
              <span className="w-1.5 h-1.5 rounded-full pulse-dot" style={{ background: '#5B5FFF' }}></span>
              v{KESTRAL_DL.version} · macOS &amp; Windows
            </div>
          </div>
          <div className="md:col-span-7">
            <div className="hairline rounded-xl bg-ink2/60 p-6 md:p-7">
              <div className="grid gap-3">
                <DlButton href={KESTRAL_DL.windows} os="Windows" sub=".exe installer · x64" primary={os === 'windows'} />
                <DlButton href={KESTRAL_DL.macArm} os="macOS · Apple Silicon" sub=".dmg · M-series" primary={os === 'mac'} />
                <DlButton href={KESTRAL_DL.macIntel} os="macOS · Intel" sub=".dmg · x64" />
              </div>
              <div className="mt-5 pt-5 hairline-t grid sm:grid-cols-2 gap-3">
                <Callout os="macOS" title='Gatekeeper will object once.'
                  body='Beta builds are unsigned. Right-click the app and choose Open, or allow it under System Settings, Privacy & Security, "Open Anyway".' />
                <Callout os="Windows" title="SmartScreen will warn you."
                  body='Click "More info", then "Run anyway". We know. Signing certificates are coming after the beta.' />
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

// ---------- FOOTER ----------
const Footer = () => (
  <footer className="hairline-t py-10">
    <div className="max-page flex flex-col sm:flex-row items-center justify-between gap-5">
      <div className="flex items-center gap-3">
        <KLogo h={20} />
        <span className="font-mono text-[11px] text-paper3">plan still · build fast</span>
      </div>
      <nav className="flex items-center gap-6 text-[13px] text-paper2">
        <a href={DISCORD_URL} className="hover:text-paper transition-colors">Discord</a>
        <a href={CONTACT_URL} className="hover:text-paper transition-colors">Contact</a>
        <a href="#download" className="hover:text-paper transition-colors">Download</a>
      </nav>
      <span className="font-mono text-[11px] text-paper3">© 2026 Kestral</span>
    </div>
  </footer>
);

Object.assign(window, { Nav, Hero, PitchVideo, HowItWorks, Features, PostBuild, Agents, Download, Footer });
