/* MAIN - the primary version. Centered, whitespace-rich hero (from V2) +
   pixel animation (from V5). Green/coral pixel blocks use the real gradient
   texture assets for structure. Free scroll, light interactivity. */
const { Reveal, ConsoleStream, ClayTable, EnablementGrid, FeedbackLoop, SectionRail, HubLink, TexturePanel, ScrollZoom, CrtConsole, ClaySweep } = window;
const { AssetScroll } = window;
const { FO5: FeedbackAperture } = window;
const { hero, sources, dbSources, dbSourceGroups, dbStages, dbOut, signals } = window.SD;
const SourcingScroll = window.SS2_COMBO.ComboEndDark;
const { HeroFloats, useTweaks, TweaksPanel, TweakSection, TweakSelect, TweakRadio } = window;
const { ProblemSection, FitDiff, Engagement, LogoMarquee, FinalCTA } = window;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "heroLink": "loop",
  "heroCopy": "embedded"
}/*EDITMODE-END*/;

const SYS_LEDE = (
  <React.Fragment>Senior enough to architect it, hands-on enough to build it, temporary by design. For 3-12 months I embed in your marketing, sales and RevOps team and build your AI-driven ABM, outbound and inbound systems in Clay, Claude Code and your CRM. Then I leave you the running system and a team that can run it.</React.Fragment>
);

/* hero headline + lede alternates - surfaced in the Tweaks panel */
const HERO_ALTS = {
  embedded: {
    h: <React.Fragment>I build your<br className="sd-h1br" />AI GTM system<br />from <span className="sd-em">inside your team</span></React.Fragment>,
    sub: SYS_LEDE,
  },
  operator: {
    h: <React.Fragment>I build your<br className="sd-h1br" />AI GTM system<br />from <span className="sd-em">inside your team</span></React.Fragment>,
    sub: <React.Fragment>One senior operator doing hands-on GTM engineering, part-time, in your stack. Your people learn to run it, and it stays when I leave.</React.Fragment>,
  },
  agency: {
    h: <React.Fragment>You don't need another agency. You need an operator who engineers your <span className="sd-em">AI GTM system</span> inside the team</React.Fragment>,
    sub: <React.Fragment>Part-time, hands-on GTM engineering next to marketing, sales and RevOps. I build it, your team owns it.</React.Fragment>,
  },
};

function Kick({ n, label }) {
  return <div className="sd-kicker"><span className="bar" /><span className="sd-secnum">{n} / 04</span><Tag tone="ember">{label}</Tag></div>;
}

/* hero structure mosaic - same deterministic pixel grid as the green
   canvases (TexturePanel), but tinted with neutral black/white alpha so it
   reads as STRUCTURE over any ground. Revealed only on the slate themes.
   Cells breathe opacity VERY slowly (40-90s) for a barely-alive surface. */
function HeroMosaic({ cols = 38, rows = 22, seed = 23 }) {
  const rnd = window.ABM.mulberry(seed);
  const cells = [];
  for (let i = 0; i < cols * rows; i++) {
    const r = rnd();
    let bg = "transparent";
    if (r < 0.10) bg = "rgba(24,33,31,0.06)";
    else if (r < 0.21) bg = "rgba(24,33,31,0.03)";
    else if (r < 0.35) bg = "rgba(255,255,255,0.09)";
    else if (r < 0.43) bg = "rgba(255,255,255,0.18)";
    const dur = 40 + rnd() * 50;          // 40-90s - very slow
    const delay = -(rnd() * dur);          // desync each cell
    const lo = 0.25 + rnd() * 0.35;        // dim floor of the breathe
    cells.push({ bg, dur, delay, lo });
  }
  return (
    <div className="sd-mhero-mosaic" aria-hidden="true">
      <div className="sd-mhero-mosaic-grid" style={{ gridTemplateColumns: `repeat(${cols},1fr)`, gridTemplateRows: `repeat(${rows},1fr)` }}>
        {cells.map((c, i) => (
          <i key={i} style={c.bg === "transparent"
            ? { background: "transparent" }
            : { background: c.bg, animationDuration: c.dur.toFixed(1) + "s", animationDelay: c.delay.toFixed(1) + "s", "--lo": c.lo.toFixed(2) }} />
        ))}
      </div>
    </div>
  );
}

/* textured pixel reservoir (green asset) with floating db-stage chips */
function Reservoir() {
  return (
    <div style={{ position: "relative" }}>
      <TexturePanel tex="green" cols={26} rows={13} seed={14} style={{ minHeight: 470 }}>
        <div style={{ position: "absolute", left: 18, top: 16, zIndex: 2 }}><span className="abm-tag" style={{ color: "rgba(255,255,255,0.92)" }}>THE DATABASE</span></div>
        <div style={{ position: "absolute", right: 18, top: 16, zIndex: 2 }}><span className="abm-tag" style={{ color: "rgba(255,255,255,0.92)" }}>12 FEEDS IN → 1 TAM OUT</span></div>
        <div style={{ position: "absolute", inset: 0, padding: "52px 26px 26px", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, alignContent: "start", zIndex: 2 }}>
          {dbStages.map((s, i) => (
            <Reveal key={s.id} dir="scale" delay={i * 80}>
              <div className="abm-float" style={{ position: "static", display: "flex", alignItems: "center", gap: 12, padding: "13px 15px", borderColor: s.crm ? "var(--abm-blue)" : "rgba(7,19,29,0.1)", gridColumn: i === 4 ? "1 / -1" : "auto", overflow: "hidden" }}>
                <span className={"abm-itile " + (s.crm ? "abm-itile--blue" : "")} style={{ width: 34, height: 34 }}><Icon name={s.icon} size={17} /></span>
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600, letterSpacing: "-0.01em", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{s.label}</div>
                  {s.crm && <div className="abm-tag" style={{ color: "var(--abm-blue)", marginTop: 3 }}>SALESFORCE</div>}
                </div>
                <span style={{ flex: "0 0 auto", fontFamily: "var(--abm-mono)", fontSize: 13, fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{s.count}</span>
              </div>
            </Reveal>
          ))}
        </div>
      </TexturePanel>
      <div style={{ display: "flex", alignItems: "center", gap: 16, padding: "18px 22px", background: "var(--abm-ember)", color: "#fff", marginTop: -1 }}>
        <Icon name="check" size={22} />
        <div><div className="abm-tag" style={{ color: "rgba(255,255,255,0.85)" }}>{dbOut.label.toUpperCase()}</div><div style={{ fontSize: 28, fontWeight: 600, fontVariantNumeric: "tabular-nums", letterSpacing: "-0.02em" }}>{dbOut.count} <span style={{ fontSize: 14, fontWeight: 400, opacity: 0.85 }}>{dbOut.unit}</span></div></div>
      </div>
    </div>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  window.__setTweak = setTweak; // lets previews/QA flip variants programmatically
  return (
    <div className="abm sd-page">

      {/* HERO - centered, whitespace, grain texture, gridlines */}
      <header className={"sd-mhero sd-mhero--" + t.heroLink}>
        <HeroMosaic />
        <HeroFloats variant={t.heroLink} />
        <div className="sd-gridlines"><span style={{ left: "16%" }} /><span style={{ left: "38%" }} /><span style={{ left: "62%" }} /><span style={{ left: "84%" }} /></div>
        <div className="sd-wrap">
          <Reveal dir="up" delay={80}><h1>{(HERO_ALTS[t.heroCopy] || HERO_ALTS.embedded).h}</h1></Reveal>
          <Reveal dir="up" delay={160}><p className="sd-lede">{(HERO_ALTS[t.heroCopy] || HERO_ALTS.embedded).sub}</p></Reveal>
          <Reveal dir="up" delay={240}><div className="sd-mhero-cta"><PillBtn label={hero.cta} variant="ember" chev={false} href="https://calendar.app.google/weNhUP588e9kF5zc7" /></div></Reveal>
          <Reveal dir="up" delay={280}><button type="button" className="sd-mhero-cta2" data-modal-open="ws-modal">Or book a working session · 2 hours · $500 →</button></Reveal>
          <Reveal dir="up" delay={320}>
            <div className="sd-trust">
              <span className="sd-trust-ava" aria-hidden="true">J</span>
              <span className="sd-trust-txt">Direct with the founder. <span className="sd-trust-dim">No discovery rep.</span></span>
            </div>
          </Reveal>
        </div>
        <div className="sd-wrap" style={{ position: "absolute", left: 0, right: 0, bottom: 30, zIndex: 1 }}>
          <div className="sd-scrollcue" style={{ position: "static", justifyContent: "center" }}><span className="dot" /><span className="abm-tag">SCROLL · WATCH IT BUILD</span></div>
        </div>
      </header>

      {/* 01 SOURCING - full-bleed scroll-driven TAM build animation (End · Dark) */}
      <section id="source">
        <SourcingScroll />
      </section>

      <div className="sd-seam sd-seam--i1p" aria-hidden="true"></div>

      {/* 02 CONSOLE - pinned in view, agent avatar, signals printed as final record */}
      <section id="enrich" className="sd-sec" style={{ paddingBottom: 40 }}>
        <div className="sd-wrap sd-wrap--wide">
          <div style={{ textAlign: "center", maxWidth: 760, margin: "0 auto" }}>
            <Reveal dir="up" delay={60}><h2 className="sd-h2">Claude researches every account, inside your stack</h2></Reveal>
            <Reveal dir="up" delay={120}><p className="sd-lede" style={{ margin: "12px auto 0" }}>I wire a Claude Code agent into your CRM and Clay. It enriches from 10 sources, reads the company across the web and tracks every buying signal, then writes the record to your sales table.</p></Reveal>
          </div>
        </div>
        {/* pin track: zoom into the retro monitor - it powers on, the agent
            dances awake, then Claude Code boots & streams inside the glass */}
        <CrtConsole />
      </section>

      {/* 03 CLAY - the enrichment sweep: one short scroll runs the table */}
      <section id="clay" className="sd-sec">
        <div className="sd-wrap sd-wrap--wide">
          <div className="u-stack-sm" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 40, alignItems: "end", marginBottom: 28 }}>
            <Reveal dir="up" delay={60}><h2 className="sd-h2" style={{ maxWidth: 520 }}>One Clay table routes your whole motion</h2></Reveal>
            <Reveal dir="up" delay={120}><p className="sd-lede" style={{ marginTop: 0 }}>Every enriched account lands in your team's Clay table, classified, tiered and wired to its next action across reps, ad campaigns, sequences, cold call and ABM. I build the table, your team runs it. Scroll once and the whole table runs.</p></Reveal>
          </div>
        </div>
        <ClaySweep />
      </section>

      {/* 04 THE ASSET - research compiles into the ABM page (dark, full-bleed) */}
      <div className="sd-seam sd-seam--pi2" aria-hidden="true"></div>
      <section id="asset">
        <AssetScroll />
      </section>

      {/* 05 FEEDBACK - the self-improving system (dark, full-bleed aperture) */}
      <section id="feedback" style={{ height: 880, position: "relative" }}>
        <FeedbackAperture />
      </section>

      {/* THE PROBLEM - bridges out of the animation into the pitch */}
      <ProblemSection />

      {/* FIT + DIFFERENTIATION */}
      <FitDiff />

      {/* THE ENGAGEMENT */}
      <Engagement />

      <TweaksPanel>
        <TweakSection label="Hero" />
        <TweakSelect
          label="Headline + lede"
          value={t.heroCopy}
          options={[
            { value: "embedded", label: "Embedded - engineered from inside your team" },
            { value: "operator", label: "Operator - I build your AI GTM system" },
            { value: "agency", label: "Agency contrast - you don't need another agency" },
          ]}
          onChange={(v) => setTweak("heroCopy", v)}
        />
        <TweakSelect
          label="Clay ↔ Claude link"
          value={t.heroLink}
          options={[
            { value: "wire", label: "Grounded wire - bottom duo" },
            { value: "circuit", label: "Circuit route - corners" },
            { value: "loop", label: "Orbit loop - around headline" },
            { value: "corners", label: "Corners - no link" },
          ]}
          onChange={(v) => setTweak("heroLink", v)}
        />
      </TweaksPanel>
    </div>
  );
}

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