/* global React, window */
const { useState, useEffect } = React;

/* ---------- Top bar ---------- */
function TopBar({ tweaks }) {
  return (
    <div className="topbar">
      <div className="wrap topbar-inner">
        <a href="#top" className="brand">
          <span className="mark"><img src="assets/bastion-3d-mark-cutout.png" alt="Bastion AI" style={{width: 36, height: 36, objectFit: 'contain', display: 'block', filter: 'drop-shadow(0 2px 4px rgba(12,17,23,0.18))'}} /></span>
          <span>Bastion</span>
          <span className="tag">AI</span>
        </a>
        <nav className="topnav">
          <a href="#sprint-narrative">Sprint</a>
          <a href="#systems">Systems</a>
          <a href="#offer">Offer</a>
          <a href="#approach">Approach</a>
          <a href="#contact" className="cta">Build your workbench</a>
        </nav>
      </div>
    </div>
  );
}

/* ---------- Hero ---------- */
function Hero({ tweaks }) {
  const showAmbient = tweaks.ambient !== false;
  return (
    <section className="hero" id="top">
      {showAmbient && (
        <>
          <video
            className="hero-video"
            src="assets/hero-ambient-loop.mp4"
            autoPlay muted loop playsInline
          />
          <div className="hero-video-veil"></div>
        </>
      )}
      <div className="wrap hero-grid">
        <div className="hero-copy">
          <window.Reveal><window.Eyebrow>AI implementation for small businesses</window.Eyebrow></window.Reveal>
          <window.Reveal delay={80}>
            <h1 className="h-display">
              Turn AI into an operator <br />
              for the systems your business <br />
              <span style={{ color: 'rgba(12,17,23,0.5)' }}>already runs.</span>
            </h1>
          </window.Reveal>
          <window.Reveal delay={160}>
            <p className="lead">
              We’re a small consulting team that helps small businesses put Claude, Codex,
              and modern AI agents to work inside the tools you already use. We map your
              systems, train your people, build the custom tooling, and leave you running it.
            </p>
          </window.Reveal>
          <window.Reveal delay={240}>
            <div className="cta-row">
              <a href="#contact" className="btn btn-primary">
                Build Your AI Workbench <span className="arrow"></span>
              </a>
              <a href="#sprint-narrative" className="btn btn-ghost">
                <span className="play"></span> See How It Works
              </a>
            </div>
          </window.Reveal>
          <window.Reveal delay={320}>
            <div className="hero-meta">
              <span><span className="dot cyan"></span>Routed</span>
              <span><span className="dot amber"></span>Approved</span>
              <span><span className="dot green"></span>Verified</span>
              <span>· Consulting · Implementation · Enablement</span>
            </div>
          </window.Reveal>
        </div>

        <window.Reveal delay={200} className="hero-object-wrap">
          <div className="hero-object">
            <div className="grain"></div>
            <div className="ring"></div>
            <div className="ring inner"></div>
            <img className="mark-3d" src="assets/bastion-3d-mark.png" alt="Bastion mark — premium 3D shield with the B insignia" />

            <div className="anno anno-a">
              <span className="pip" style={{ background: 'var(--cyan)' }}></span>
              ROUTED · cyan rail
              <div className="lead-line"></div>
            </div>
            <div className="anno anno-b">
              <span className="pip" style={{ background: 'var(--green)' }}></span>
              VERIFIED · green light
              <div className="lead-line"></div>
            </div>
            <div className="anno anno-c">
              <span className="pip" style={{ background: 'var(--amber)' }}></span>
              APPROVAL GATE
              <div className="lead-line"></div>
            </div>
          </div>
        </window.Reveal>
      </div>
    </section>
  );
}

/* ---------- Stack strip / marquee ---------- */
function StackStrip() {
  const items = [
    'Shopify', 'Salesforce', 'HubSpot', 'GitHub', 'Vercel', 'Notion', 'Airtable',
    'Slack', 'Google Workspace', 'Claude', 'Claude Code', 'Codex', 'ChatGPT',
    'GA4 / GTM', 'Webhooks', 'CLIs',
  ];
  return (
    <section className="stack-strip">
      <div className="wrap">
        <div className="label">We work inside the stack your team already runs</div>
        <div className="stack-row">
          {[...items, ...items].map((it, i) => <span key={i}>{it}</span>)}
        </div>
      </div>
    </section>
  );
}

/* ---------- Problem ---------- */
function Problem() {
  return (
    <section className="section" id="problem">
      <div className="wrap problem">
        <div>
          <window.Reveal>
            <window.SectionIdx num="01" label="The gap" />
          </window.Reveal>
          <window.Reveal delay={60}>
            <h2 className="h-section">
              You don't need <br />another AI demo.
            </h2>
          </window.Reveal>
          <window.Reveal delay={120}>
            <p className="lead" style={{ marginTop: 22 }}>
              You need a small, senior team to sit with you, look at how your business actually
              runs, and help you put AI to work inside the tools you already use — then leave
              you with the skills to keep going.
            </p>
          </window.Reveal>
        </div>
        <div className="problem-list">
          {window.PROBLEMS.map((p, i) => (
            <window.Reveal key={p.title} delay={i * 80}>
              <div className="problem-row">
                <span className="num">/ {String(i + 1).padStart(2, '0')}</span>
                <div className="body">
                  <strong>{p.title}</strong>
                  <p>{p.body}</p>
                </div>
              </div>
            </window.Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- Teardown intro (dark cinematic copy block — video lives in TeardownStage) ---------- */
function TeardownIntro() {
  return (
    <section className="section teardown-intro" aria-hidden="false">
      <div className="wrap teardown-content">
        <window.Reveal><window.Eyebrow dark>The mark opens</window.Eyebrow></window.Reveal>
        <window.Reveal delay={80}>
          <h2 className="h-section" style={{ color: 'var(--ivory)', marginTop: 18, maxWidth: '14ch' }}>
            Six layers <br />of the sprint.
          </h2>
        </window.Reveal>
        <window.Reveal delay={160}>
          <p className="lead" style={{ marginTop: 22, maxWidth: '52ch' }}>
            What looks like a single mark is really six pieces of work we do alongside your team
            — mapping, training, custom tooling, knowledge, routines, and shipped wins.
          </p>
        </window.Reveal>
      </div>
    </section>
  );
}

/* ---------- Teardown stage — scroll-scrubbed frame sequence (canvas, smooth) ---------- */
function TeardownStage() {
  const stageRef = React.useRef(null);
  const canvasRef = React.useRef(null);

  React.useEffect(() => {
    const FRAMES = 60;
    const stage = stageRef.current;
    const canvas = canvasRef.current;
    if (!stage || !canvas) return;

    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const ctx = canvas.getContext('2d');
    const dpr = Math.min(2, window.devicePixelRatio || 1);

    const setCanvasSize = () => {
      const parent = canvas.parentElement;
      const rect = parent.getBoundingClientRect();
      const w = Math.max(1, Math.round(rect.width * dpr));
      const h = Math.max(1, Math.round(rect.height * dpr));
      if (canvas.width !== w || canvas.height !== h) {
        canvas.width = w;
        canvas.height = h;
      }
    };

    // Preload all frames — browser caches them so swap is instant
    const images = new Array(FRAMES);
    for (let i = 0; i < FRAMES; i++) {
      const img = new Image();
      img.decoding = 'async';
      img.src = `assets/frames/${String(i).padStart(3, '0')}.jpg`;
      images[i] = img;
    }

    const drawCover = (img) => {
      if (!img || !img.complete || !img.naturalWidth) return;
      const cw = canvas.width, ch = canvas.height;
      const iw = img.naturalWidth, ih = img.naturalHeight;
      const zoom = 1.40; // crop the dark side margins baked into the source frames
      const scale = Math.max(cw / iw, ch / ih) * zoom;
      const w = iw * scale, h = ih * scale;
      const x = (cw - w) / 2, y = (ch - h) / 2;
      ctx.drawImage(img, x, y, w, h);
    };

    const state = { target: 0, current: 0, lastIdx: -1 };

    const compute = () => {
      const rect = stage.getBoundingClientRect();
      const total = Math.max(1, stage.offsetHeight - window.innerHeight);
      const p = Math.max(0, Math.min(1, -rect.top / total));
      state.target = p * (FRAMES - 1);
    };

    // Initial paint when first frame loads (so the background isn't blank)
    const paintFirst = () => {
      setCanvasSize();
      drawCover(images[Math.max(0, Math.min(FRAMES - 1, Math.round(state.target)))]);
    };
    images[0].addEventListener('load', paintFirst);
    if (images[0].complete) paintFirst();

    if (reduced) {
      compute();
      setCanvasSize();
      drawCover(images[Math.round(state.target)]);
      return () => {};
    }

    let raf = 0;
    const tick = () => {
      const k = 0.10;
      const diff = state.target - state.current;
      state.current += diff * k;
      if (Math.abs(diff) < 0.0008) state.current = state.target;

      // Crossfade between the two adjacent frames for sub-frame smoothness.
      const f = Math.max(0, Math.min(FRAMES - 1, state.current));
      const i0 = Math.floor(f);
      const i1 = Math.min(FRAMES - 1, i0 + 1);
      const t = f - i0;
      ctx.globalAlpha = 1;
      drawCover(images[i0]);
      if (i1 !== i0 && t > 0.0001) {
        ctx.globalAlpha = t;
        drawCover(images[i1]);
        ctx.globalAlpha = 1;
      }
      raf = requestAnimationFrame(tick);
    };

    const onResize = () => { setCanvasSize(); state.lastIdx = -1; compute(); };

    window.addEventListener('scroll', compute, { passive: true });
    window.addEventListener('resize', onResize);
    compute();
    raf = requestAnimationFrame(tick);

    return () => {
      window.removeEventListener('scroll', compute);
      window.removeEventListener('resize', onResize);
      images[0].removeEventListener('load', paintFirst);
      if (raf) cancelAnimationFrame(raf);
    };
  }, []);

  return (
    <div ref={stageRef} className="teardown-stage">
      <div className="teardown-stage-bg" aria-hidden="true">
        <canvas ref={canvasRef} className="teardown-stage-canvas"></canvas>
        <div className="teardown-stage-veil"></div>
        <div className="teardown-stage-grain"></div>
      </div>
      <div className="teardown-stage-content">
        <window.TeardownIntro />
        <window.SprintNarrative />
      </div>
      <div className="teardown-stage-fade"></div>
    </div>
  );
}

/* ---------- Six-slab sprint narrative ---------- */
function SprintNarrative() {
  const [openIdx, setOpenIdx] = useState(null);
  return (
    <section className="section dark slabs-bg" id="sprint-narrative">
      <div className="wrap">
        <div className="slabs-header">
          <window.Reveal><window.Eyebrow dark>The AI Systems Sprint · Six layers</window.Eyebrow></window.Reveal>
          <window.Reveal delay={60}>
            <h2 className="h-section" style={{ color: 'var(--ivory)' }}>
              The sprint, in six layers.
            </h2>
          </window.Reveal>
          <window.Reveal delay={120}>
            <p className="lead">
              Not decorative cards. Each layer is real work we do alongside your team
              — the conversations, the tooling we build, the habits we leave behind.
            </p>
          </window.Reveal>
        </div>
        <div className="slabs-grid">
          {window.SLABS.map((s, i) => (
            <window.Reveal key={s.n} delay={i * 70}>
              <window.Slab
                data={s}
                open={openIdx === i}
                onToggle={() => setOpenIdx(openIdx === i ? null : i)}
              />
            </window.Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- Proof section ---------- */
function ProofSection() {
  return (
    <section className="proof-section">
      <window.ProofRail />
    </section>
  );
}

/* ---------- Example systems ---------- */
function ExampleSystems() {
  return (
    <section className="section" id="systems">
      <div className="wrap">
        <div style={{ maxWidth: 760, marginBottom: 48 }}>
          <window.Reveal><window.SectionIdx num="03" label="Where we plug in" /></window.Reveal>
          <window.Reveal delay={60}>
            <h2 className="h-section">The tools your team already lives in.</h2>
          </window.Reveal>
          <window.Reveal delay={120}>
            <p className="lead" style={{ marginTop: 18 }}>
              We don’t ask you to switch stacks. We work inside the commerce, CRM, builder,
              and ops tools you already run — and build the small, custom pieces that let AI
              actually do work there.
            </p>
          </window.Reveal>
        </div>
        <div className="systems-grid">
          {window.SYSTEMS_GROUPS.map((g, i) => (
            <window.Reveal key={g.label} delay={i * 80}>
              <div className="sys-card">
                <span className="sys-label">{g.label}</span>
                <h4>{g.name}</h4>
                <p>{g.desc}</p>
                <div className="chip-row" style={{ marginTop: 'auto' }}>
                  {g.chips.map((c) => <window.Chip key={c}>{c}</window.Chip>)}
                </div>
              </div>
            </window.Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- Offer / sprint tiers ---------- */
function Offer() {
  return (
    <section className="section sprint" id="offer">
      <div className="wrap">
        <div className="sprint-header">
          <window.Reveal><window.Eyebrow dark>The offer</window.Eyebrow></window.Reveal>
          <window.Reveal delay={60}>
            <h2 className="h-section">The AI Systems Sprint.</h2>
          </window.Reveal>
          <window.Reveal delay={120}>
            <p className="lead">
              A focused engagement where we sit with your team, look at your tools, pick 1–3
              high-value workflows, build the custom AI tooling they need, train the people
              who’ll use it, and leave you running it. Deeper partnership can follow if useful.
            </p>
          </window.Reveal>
        </div>
        <div className="sprint-grid">
          {window.TIERS.map((t, i) => (
            <window.Reveal key={t.name} delay={i * 80}>
              <div className={`tier ${t.feature ? 'feature' : ''}`}>
                <span className="tier-tag">{t.tag}</span>
                <h3>{t.name}</h3>
                <span className="price">{t.duration} · scope-based</span>
                <ul>{t.bullets.map((b) => <li key={b}>{b}</li>)}</ul>
                <a href="#contact" className="btn btn-ghost" style={{
                  marginTop: 12,
                  color: 'var(--ivory)',
                  borderColor: 'rgba(247,241,230,0.25)',
                }}>
                  Start a conversation <span className="arrow"></span>
                </a>
              </div>
            </window.Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- Operator trust / principles ---------- */
function Operator() {
  return (
    <section className="section" id="approach">
      <div className="wrap operator">
        <div>
          <window.Reveal><window.SectionIdx num="05" label="How we operate" /></window.Reveal>
          <window.Reveal delay={60}>
            <h2 className="h-section">
              Calm control <br />over messy systems.
            </h2>
          </window.Reveal>
          <window.Reveal delay={120}>
            <p className="lead" style={{ marginTop: 18 }}>
              We’re a small consulting team. We work inside your tools, respect your access
              boundaries, and leave behind runbooks and habits your people can actually keep using.
            </p>
          </window.Reveal>
          <window.Reveal delay={180}>
            <div style={{ marginTop: 26 }}>
              <div className="chip-row">
                <window.Chip tone="cyan">Scoped access</window.Chip>
                <window.Chip tone="amber">Approval gates</window.Chip>
                <window.Chip tone="green">Verified output</window.Chip>
                <window.Chip>Audit trail</window.Chip>
                <window.Chip>Rollback</window.Chip>
                <window.Chip>Human review</window.Chip>
              </div>
            </div>
          </window.Reveal>
        </div>
        <div className="principles">
          {window.PRINCIPLES.map((p, i) => (
            <window.Reveal key={p.n} delay={i * 80}>
              <div className="principle">
                <span className="num">{p.n}</span>
                <div>
                  <h4>{p.title}</h4>
                  <p>{p.body}</p>
                </div>
              </div>
            </window.Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- Lead form ---------- */
function LeadForm() {
  const [submitted, setSubmitted] = useState(false);
  const [data, setData] = useState({
    name: '', email: '', company: '', website: '', role: '',
    systems: '', tools: '', budget: '',
  });
  const [prefilled, setPrefilled] = useState(false);

  // Pick up Atlas demo answers when the user clicks "Send a longer note instead"
  useEffect(() => {
    const onPrefill = (e) => {
      const a = e.detail || window.__bastionAnswers || {};
      setData((d) => ({
        ...d,
        company: a.business ? a.business.split(/[.,\n]/)[0].slice(0, 80) : d.company,
        role: a.team && /founder|ceo|owner|operator|head/i.test(a.team) ? (a.team.match(/founder|ceo|owner|operator|head/i)?.[0] || d.role) : d.role,
        systems: a.pain ? `Painful workflow we'd love to fix: ${a.pain}` : d.systems,
        tools: a.tools || d.tools,
      }));
      setPrefilled(true);
      // Clear the flag chip after a moment
      setTimeout(() => setPrefilled(false), 6500);
    };
    window.addEventListener('bastion:prefill-contact', onPrefill);
    // Also pick up if answers were stashed before form mounted
    if (window.__bastionAnswers) onPrefill({ detail: window.__bastionAnswers });
    return () => window.removeEventListener('bastion:prefill-contact', onPrefill);
  }, []);

  const update = (k) => (e) => {
    if (!data[k]) window.bastionAnalytics?.leadFormStart('contact_section');
    setData({ ...data, [k]: e.target.value });
  };

  function handleSubmit(e) {
    e.preventDefault();
    // No real backend — this is a prototype. Show success state.
    window.bastionAnalytics?.leadFormSubmitSuccess(data, 'contact_section');
    setSubmitted(true);
  }

  return (
    <section className="section cta-final" id="contact">
      <div className="wrap cta-grid">
        <div>
          <window.Reveal><window.SectionIdx num="06" label="Start here" /></window.Reveal>
          <window.Reveal delay={60}>
            <h2 className="h-section">
              Build Your <br />AI Workbench.
            </h2>
          </window.Reveal>
          <window.Reveal delay={120}>
            <p className="lead" style={{ marginTop: 18 }}>
              Tell us about your business, the tools you use, and where you’d like AI to help.
              We’ll come back within two business days with a scoped sprint and next steps.
            </p>
          </window.Reveal>
          <window.Reveal delay={180}>
            <div className="cta-aside">
              <span>Direct: <a href="mailto:matt@bastionai.co" onClick={() => window.bastionAnalytics?.primaryCtaClick('matt@bastionai.co', 'contact_aside')}>matt@bastionai.co</a></span>
              <span>Sprint windows: 1–2 weeks · 2–4 weeks · ongoing</span>
              <span>Small, senior team. Built for small businesses.</span>
            </div>
          </window.Reveal>
        </div>

        <window.Reveal delay={120}>
          <form className="form-card" onSubmit={handleSubmit}>
            {submitted ? (
              <div className="form-success">
                <span className="check">✓</span>
                <strong>Thanks — we'll be in touch.</strong>
                <p style={{ margin: '10px 0 0 40px', color: 'rgba(12,17,23,0.65)', fontSize: 14.5 }}>
                  Matt will reply within two business days with next steps and a scoped sprint outline.
                </p>
              </div>
            ) : (
              <>
                {prefilled && (
                  <div style={{
                    marginBottom: 18, padding: '10px 14px',
                    background: 'rgba(50,213,131,0.08)',
                    border: '1px solid rgba(50,213,131,0.35)',
                    borderRadius: 8,
                    fontFamily: 'JetBrains Mono, monospace',
                    fontSize: 11.5, letterSpacing: '0.06em',
                    color: 'rgba(12,17,23,0.78)',
                    display: 'flex', alignItems: 'center', gap: 10,
                  }}>
                    <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--green)', boxShadow: '0 0 0 3px rgba(50,213,131,0.2)' }}></span>
                    Pulled in your answers from Atlas — feel free to edit.
                  </div>
                )}
                <div className="form-row split">
                  <div>
                    <label htmlFor="f-name">Name</label>
                    <input id="f-name" required value={data.name} onChange={update('name')} placeholder="Your name" />
                  </div>
                  <div>
                    <label htmlFor="f-email">Email</label>
                    <input id="f-email" type="email" required value={data.email} onChange={update('email')} placeholder="you@company.com" />
                  </div>
                </div>
                <div className="form-row split">
                  <div>
                    <label htmlFor="f-company">Company</label>
                    <input id="f-company" required value={data.company} onChange={update('company')} placeholder="Company name" />
                  </div>
                  <div>
                    <label htmlFor="f-website">Website</label>
                    <input id="f-website" value={data.website} onChange={update('website')} placeholder="https://" />
                  </div>
                </div>
                <div className="form-row">
                  <label htmlFor="f-role">Role</label>
                  <input id="f-role" value={data.role} onChange={update('role')} placeholder="Founder / Ops / Eng lead / ..." />
                </div>
                <div className="form-row">
                  <label htmlFor="f-systems">What systems do you want AI to help with?</label>
                  <textarea id="f-systems" value={data.systems} onChange={update('systems')} placeholder="Shopify orders, CRM lifecycle, GA4 audits, support workflows, repo cleanup..." />
                </div>
                <div className="form-row">
                  <label htmlFor="f-tools">What tools do you already use?</label>
                  <input id="f-tools" value={data.tools} onChange={update('tools')} placeholder="Shopify, HubSpot, GitHub, Slack, Notion..." />
                </div>
                <div className="form-row">
                  <label htmlFor="f-budget">Budget / timeline <span className="muted">(optional)</span></label>
                  <input id="f-budget" value={data.budget} onChange={update('budget')} placeholder="e.g. start within 30 days · sprint-scale" />
                </div>
                <div className="form-submit">
                  <span className="form-meta">
                    <span className="dot cyan" style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--cyan)', display: 'inline-block' }}></span>
                    Routed → matt@bastionai.co
                  </span>
                  <button type="submit" className="btn btn-primary">
                    Build my workbench <span className="arrow"></span>
                  </button>
                </div>
              </>
            )}
          </form>
        </window.Reveal>
      </div>
    </section>
  );
}

/* ---------- Footer ---------- */
function Foot() {
  return (
    <footer>
      <div className="wrap foot-inner">
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <img src="assets/bastion-3d-mark-cutout.png" alt="" style={{width: 28, height: 28, objectFit: 'contain'}} />
          <span>© Bastion AI · AI implementation for small businesses</span>
        </div>
        <div className="foot-links">
          <a href="#sprint-narrative">Sprint</a>
          <a href="#systems">Systems</a>
          <a href="#offer">Offer</a>
          <a href="mailto:matt@bastionai.co">matt@bastionai.co</a>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, {
  TopBar, Hero, StackStrip, Problem, TeardownIntro, TeardownStage, SprintNarrative,
  ProofSection, ExampleSystems, Offer, Operator, LeadForm, Foot,
});
