// DRotten Eggs — main React app
// Single-file artifact. All sections and roster state.

const { useState, useEffect, useMemo, useRef, useCallback } = React;

// --- helpers ---
const fmt = (n) => n.toLocaleString("en-US");
const useLocal = (key, init) => {
  const [v, setV] = useState(() => {
    try { const raw = localStorage.getItem(key); return raw ? JSON.parse(raw) : init; } catch { return init; }
  });
  useEffect(() => { try { localStorage.setItem(key, JSON.stringify(v)); } catch {} }, [key, v]);
  return [v, setV];
};

// Simple count-up on viewport
function useCountUp(end, opts = {}) {
  const { duration = 1400, start = 0 } = opts;
  const [val, setVal] = useState(start);
  const [active, setActive] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(([e]) => { if (e.isIntersecting) setActive(true); }, { threshold: 0.4 });
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  useEffect(() => {
    if (!active) return;
    const t0 = performance.now();
    let raf;
    const loop = (t) => {
      const k = Math.min(1, (t - t0) / duration);
      const eased = 1 - Math.pow(1 - k, 3);
      setVal(Math.round(start + (end - start) * eased));
      if (k < 1) raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, [active, end]);
  return [val, ref];
}

// --- TopNav ---
function TopNav({ onDeploy }) {
  return (
    <nav className="nav">
      <a href="#top" className="nav__logo" aria-label="DRotten Eggs — home">
        <img className="nav__logo-img" src={(window.__resources && window.__resources.logo) || "assets/drotten-logo.png"} alt="DRotten Eggs" />
        <span className="nav__logo-text">Brands that never sleep</span>
      </a>
      <div className="nav__links">
        <a href="#mechanic">Solution</a>
        <a href="#builder">Agents</a>
        <a href="#squads">Pricing</a>
        <a href="#blog">Field Notes</a>
        <a href="#faq">FAQ</a>
      </div>
      <button className="btn btn--gold btn--small" onClick={onDeploy}>Deploy Roster →</button>
    </nav>
  );
}

// --- Scroll progress + side counter ---
function ScrollProgress() {
  const [pct, setPct] = useState(0);
  const [live, setLive] = useState(47);
  useEffect(() => {
    const onScroll = () => {
      const h = document.documentElement;
      const max = h.scrollHeight - h.clientHeight;
      setPct(max > 0 ? (h.scrollTop / max) * 100 : 0);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  useEffect(() => {
    const t = setInterval(() => {
      setLive(v => Math.max(42, Math.min(58, v + (Math.random() < 0.5 ? -1 : 1))));
    }, 4000 + Math.random() * 3000);
    return () => clearInterval(t);
  }, []);
  return (
    <React.Fragment>
      <div className="progress-rail"><div className="progress-rail__fill" style={{ height: pct + "%" }} /></div>
      <div className="live-counter"><span className="dot"></span>Agents Live · {live}</div>
    </React.Fragment>
  );
}

// --- Cursor dot ---
function CursorDot() {
  const ref = useRef(null);
  useEffect(() => {
    const dot = ref.current;
    if (!dot) return;
    let x = -100, y = -100;
    const onMove = (e) => {
      x = e.clientX; y = e.clientY;
      dot.style.left = x + "px";
      dot.style.top = y + "px";
    };
    const onOver = (e) => {
      const t = e.target;
      if (t.closest && t.closest("a, button, .agent, .squad-card, .tab, .chip, .faq-item__q")) {
        dot.classList.add("cursor-dot--big");
      } else {
        dot.classList.remove("cursor-dot--big");
      }
    };
    window.addEventListener("mousemove", onMove);
    window.addEventListener("mouseover", onOver);
    return () => { window.removeEventListener("mousemove", onMove); window.removeEventListener("mouseover", onOver); };
  }, []);
  return <div ref={ref} className="cursor-dot" />;
}

// --- Hero ---
const HERO_ORBS = [
  { x: 12, y: 18, label: "BrandMind", big: false },
  { x: 32, y: 8,  label: "CampaignBot", big: true },
  { x: 60, y: 14, label: "DesignFlow" },
  { x: 78, y: 26, label: "VideoForge" },
  { x: 86, y: 50, label: "QA Sentinel", big: true },
  { x: 70, y: 70, label: "PenTest", small: true },
  { x: 48, y: 80, label: "SocialPulse" },
  { x: 22, y: 64, label: "Insight Oracle" },
  { x: 6,  y: 46, label: "ChatOps", small: true },
  { x: 42, y: 38, label: "SEO Sentinel" },
  { x: 56, y: 52, label: "Lead Hunter", big: true },
  { x: 90, y: 80, label: "CopyCraft", small: true },
];

function Hero({ onDeploy, onSeeRun }) {
  const wrap = useRef(null);
  const [mouse, setMouse] = useState(null);

  useEffect(() => {
    const onMove = (e) => {
      const r = wrap.current?.getBoundingClientRect();
      if (!r) return;
      setMouse({ x: ((e.clientX - r.left) / r.width) * 100, y: ((e.clientY - r.top) / r.height) * 100 });
    };
    window.addEventListener("mousemove", onMove);
    return () => window.removeEventListener("mousemove", onMove);
  }, []);

  // 3 nearest orbs to mouse
  const lines = useMemo(() => {
    if (!mouse) return [];
    const withDist = HERO_ORBS.map((o, i) => ({ ...o, i, d: Math.hypot(o.x - mouse.x, o.y - mouse.y) }));
    return withDist.sort((a,b) => a.d - b.d).slice(0, 3);
  }, [mouse]);

  return (
    <section className="hero" ref={wrap}>
      <div className="hero__bg">
        <div className="constellation">
          {HERO_ORBS.map((o, i) => {
            const offX = mouse ? (mouse.x - 50) * 0.04 * (o.big ? 1.4 : 1) : 0;
            const offY = mouse ? (mouse.y - 50) * 0.04 * (o.big ? 1.4 : 1) : 0;
            return (
              <div
                key={i}
                className={"orb " + (o.big ? "orb--big " : "") + (o.small ? "orb--small " : "")}
                style={{
                  left: `calc(${o.x}% + ${offX}px)`,
                  top: `calc(${o.y}% + ${offY}px)`,
                  animationDelay: `${i * 0.7}s`,
                }}
              >
                <span className="orb__label">{o.label}</span>
              </div>
            );
          })}
          <svg className="hero__lines" viewBox="0 0 100 100" preserveAspectRatio="none">
            {mouse && lines.map((o, i) => (
              <line key={i} x1={mouse.x} y1={mouse.y} x2={o.x} y2={o.y} />
            ))}
          </svg>
        </div>
      </div>

      <div className="container hero__inner">
        <div className="eyebrow">// AI MARKETING AGENCY <span className="dash">·</span> ROSTER v2.0</div>
        <h1 className="hero__title">
          ASSEMBLE THE TEAM<br/>
          THAT NEVER <span className="gold">SLEEPS.</span>
        </h1>
        <p className="hero__sub">
          Hand-pick autonomous AI agents. Watch them deploy in 48 hours. Cancel any time.
        </p>
        <div className="hero__ctas">
          <button className="btn btn--gold" onClick={onDeploy}>Deploy a Roster →</button>
          <button className="btn btn--ghost" onClick={onSeeRun}>See an Agent Run →</button>
        </div>
        <div className="hero__pill"><span className="dot"></span>47 agents currently online for 12 brands</div>
      </div>
    </section>
  );
}

// --- Live Counters ---
function LiveCounters() {
  const [agents, agentsRef] = useCountUp(47);
  const [brands, brandsRef] = useCountUp(12);
  const [tasks, tasksRef] = useCountUp(184392);
  const [up, upRef] = useCountUp(9997);
  const [tickTasks, setTickTasks] = useState(0);

  useEffect(() => {
    const t = setInterval(() => setTickTasks(v => v + (1 + Math.floor(Math.random() * 4))), 2200);
    return () => clearInterval(t);
  }, []);

  return (
    <section className="counters">
      <div className="counters__row">
        <div className="counter" ref={agentsRef}>
          <div className="counter__num">{agents}</div>
          <div className="counter__label">Agents Deployed</div>
        </div>
        <div className="counter" ref={brandsRef}>
          <div className="counter__num">{brands}</div>
          <div className="counter__label">Brands Running 24/7</div>
        </div>
        <div className="counter" ref={tasksRef}>
          <div className="counter__num">{fmt(tasks + tickTasks)}</div>
          <div className="counter__label">Tasks Executed This Week</div>
        </div>
        <div className="counter" ref={upRef}>
          <div className="counter__num">{(up / 100).toFixed(2)}%</div>
          <div className="counter__label">Uptime</div>
        </div>
      </div>
    </section>
  );
}

// --- Mechanic ---
function Mechanic() {
  const steps = [
    { n: "01", h: "Pick your agents", body: "Choose individual agents or a pre-built squad. Total updates live." },
    { n: "02", h: "We connect your stack", body: "Brand kit, channels, ad accounts, CRM, analytics — wired up by your onboarding lead in 48 hours." },
    { n: "03", h: "Agents go live", body: "Your roster runs 24/7. You get a Friday brief. You sleep." },
  ];
  const diagrams = [
    <svg width="80" height="40" viewBox="0 0 80 40" fill="none" stroke="currentColor" strokeWidth="1.4"><rect x="2" y="6" width="22" height="28"/><rect x="29" y="6" width="22" height="28"/><rect x="56" y="6" width="22" height="28"/><circle cx="13" cy="20" r="3" fill="currentColor"/><circle cx="40" cy="20" r="3" fill="currentColor"/></svg>,
    <svg width="80" height="40" viewBox="0 0 80 40" fill="none" stroke="currentColor" strokeWidth="1.4"><circle cx="14" cy="20" r="8"/><circle cx="40" cy="20" r="8"/><circle cx="66" cy="20" r="8"/><line x1="22" y1="20" x2="32" y2="20"/><line x1="48" y1="20" x2="58" y2="20"/></svg>,
    <svg width="80" height="40" viewBox="0 0 80 40" fill="none" stroke="currentColor" strokeWidth="1.4"><path d="M4 20 L18 20 L24 8 L34 32 L42 14 L48 26 L56 20 L76 20"/></svg>,
  ];
  return (
    <section className="mech container" id="mechanic">
      <div className="mech__head">
        <div>
          <div className="eyebrow">// THE MECHANIC</div>
          <h2 className="mech__title">How a roster<br/>comes online.</h2>
        </div>
        <div className="mute mono" style={{maxWidth:280, fontSize:"0.8rem"}}>Three steps. Forty-eight hours. No proposal deck.</div>
      </div>
      <div className="mech__grid">
        {steps.map((s, i) => (
          <div key={i} className="mech-step">
            <div className="mech-step__num">{s.n}</div>
            <div className="mech-step__h">{s.h}</div>
            <div className="mech-step__body">{s.body}</div>
            <div className="mech-step__diagram">{diagrams[i]}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

// --- Agent card ---
function AgentCard({ agent, billing, added, onToggle, onOpen }) {
  const price = billing === "monthly" ? agent.priceMonthly : agent.priceOneTime;
  const unit = billing === "monthly" ? "/mo" : " deploy";
  return (
    <div
      className={"agent " + (added ? "agent--added" : "")}
      data-agent={agent.id}
      onClick={(e) => { if (!e.target.closest("button")) onOpen(agent); }}
    >
      <div className="agent__top">
        <div className="agent__glyph-wrap"><AgentGlyph name={agent.glyph} animated /></div>
        <div className="agent__status"><span className="dot"></span>Online</div>
      </div>
      <div>
        <div className="agent__row">
          <div className="agent__name">{agent.name}</div>
          <div className="agent__price">
            <span key={price + billing} style={{display:"inline-block"}}>${fmt(price)}</span>
            <span className="unit">{unit}</span>
          </div>
        </div>
        <div className="agent__role"><span className="div-tag">{agent.division}</span> · {agent.role}</div>
      </div>
      <div className="agent__desc">{agent.description}</div>
      <div className="agent__meta">
        <div className="meta-row"><span className="arrow">▸</span><span className="label">Throughput</span><span className="val">{agent.throughput}</span></div>
        <div className="meta-row"><span className="arrow">▸</span><span className="label">Powered by</span><span className="val">{agent.stack.join(" · ")}</span></div>
      </div>
      <div className="agent__cta">
        <button
          className={"btn " + (added ? "btn--ghost" : "btn--gold") + " btn--small"}
          onClick={(e) => { e.stopPropagation(); onToggle(agent.id); }}
        >
          {added ? "✓ Added · Remove" : "+ Add to Roster"}
        </button>
        {agent.nda && <span className="nda">🔒 NDA-eligible</span>}
      </div>
    </div>
  );
}

// --- Roster ---
function Roster({ rosterIds, billing, onRemove, onLock, scrollRef }) {
  const items = rosterIds.map(id => AGENTS.find(a => a.id === id)).filter(Boolean);
  const total = items.reduce((s, a) => s + (billing === "monthly" ? a.priceMonthly : a.priceOneTime), 0);
  const human = items.reduce((s, a) => s + a.humanEquivalentSalary, 0);
  const savings = Math.max(0, human - total);
  const savingsPct = human > 0 ? Math.round((savings / human) * 100) : 0;
  const fillPct = Math.min(100, Math.round((items.length / AGENTS.length) * 100));
  const taskTotal = items.length * 240; // approximate

  return (
    <aside className="roster" ref={scrollRef}>
      <div className="roster__head">
        <span>Your Roster</span>
        <span className="live"><span className="dot"></span>Live</span>
      </div>

      <div className={"roster__list " + (items.length ? "roster__list--filled" : "")}>
        {items.length === 0 && (
          <div className="roster__empty">Drop agents here.</div>
        )}
        {items.map(a => (
          <div key={a.id} className="roster-row">
            <div>
              <div className="roster-row__name">{a.name}</div>
              <div className="roster-row__div">{a.division}</div>
            </div>
            <div className="roster-row__price">${fmt(billing === "monthly" ? a.priceMonthly : a.priceOneTime)}<span className="mute">{billing === "monthly" ? "/mo" : ""}</span></div>
            <button className="roster-row__rm" onClick={() => onRemove(a.id)} aria-label={"Remove " + a.name}>×</button>
          </div>
        ))}
      </div>

      <div className="roster__throughput">
        Your roster will execute ~<strong>{fmt(taskTotal)}</strong> tasks/mo across <strong>{Math.min(items.length, 6)}</strong> channels.
      </div>

      <div className="money">
        <div className="money__big">
          <span>${fmt(total)}</span>
          <span className="unit">{billing === "monthly" ? "/month" : "deploy"}</span>
        </div>
        {items.length > 0 && (
          <React.Fragment>
            <div className="money__strike">vs <s>${fmt(human)}/mo</s> for human equivalents</div>
            <div className="money__save">You save ${fmt(savings)}/mo · {savingsPct}% below human-hire cost</div>
          </React.Fragment>
        )}
        <div className="money__bar"><span style={{width: fillPct + "%"}}></span></div>
        <div className="money__bar-label"><span>Roster size</span><span>{items.length} / {AGENTS.length}</span></div>
      </div>

      <button className="btn btn--gold btn--block" onClick={onLock} style={{padding:"20px 22px", fontSize:"0.84rem"}}>
        Lock this Roster →
      </button>

      <div className="trust-strip">
        <div><svg width="12" height="12" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M3 8l3 3 7-7"/></svg>No card to start</div>
        <div><svg width="12" height="12" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M3 8l3 3 7-7"/></svg>NDA on request</div>
        <div><svg width="12" height="12" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M3 8l3 3 7-7"/></svg>Cancel any month</div>
      </div>
    </aside>
  );
}

// --- Builder ---
function Builder({ rosterIds, addAgent, removeAgent, billing, setBilling, onLock, onOpenAgent, builderRef }) {
  const [tab, setTab] = useState("ALL");
  const [q, setQ] = useState("");

  const filtered = AGENTS.filter(a => {
    if (tab !== "ALL" && a.division !== tab) return false;
    if (q && !(a.name + " " + a.role + " " + a.description).toLowerCase().includes(q.toLowerCase())) return false;
    return true;
  });

  const toggle = (id) => {
    if (rosterIds.includes(id)) removeAgent(id);
    else addAgent(id);
  };

  return (
    <section className="builder" id="builder" ref={builderRef}>
      <div className="container">
        <div className="builder__head">
          <div>
            <div className="eyebrow"><span className="gold">●</span> THE CENTERPIECE / SECTION 04</div>
            <h2 className="builder__title">Assemble your AI<br/>marketing team.</h2>
          </div>
          <div className="mute mono" style={{maxWidth:280, fontSize:"0.8rem"}}>13 autonomous agents. Four divisions. One roster.</div>
        </div>

        <div className="builder__layout">
          <div className="builder__left">
            <div className="cat__sticky">
              <div className="tabs">
                {DIVISIONS.map(d => (
                  <button key={d} className={"tab " + (tab === d ? "tab--active" : "")} onClick={() => setTab(d)}>{d}</button>
                ))}
              </div>
              <div className="cat__controls">
                <div className="search">
                  <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4"><circle cx="7" cy="7" r="5"/><path d="M11 11l3 3"/></svg>
                  <input placeholder="search agents..." value={q} onChange={(e) => setQ(e.target.value)} />
                </div>
                <div className="billing-toggle" role="group" aria-label="Billing mode">
                  <button aria-pressed={billing === "monthly"} onClick={() => setBilling("monthly")}>Monthly retainer</button>
                  <button aria-pressed={billing === "one-time"} onClick={() => setBilling("one-time")}>One-time deploy</button>
                </div>
              </div>
            </div>

            <div className="agents-grid">
              {filtered.map(a => (
                <AgentCard
                  key={a.id}
                  agent={a}
                  billing={billing}
                  added={rosterIds.includes(a.id)}
                  onToggle={toggle}
                  onOpen={onOpenAgent}
                />
              ))}
            </div>
            {filtered.length === 0 && (
              <div className="mute mono" style={{padding:"40px 0", textAlign:"center", letterSpacing:"0.16em"}}>NO AGENTS MATCH.</div>
            )}
          </div>

          <Roster
            rosterIds={rosterIds}
            billing={billing}
            onRemove={removeAgent}
            onLock={onLock}
          />
        </div>
      </div>
    </section>
  );
}

// --- Divisions editorial ---
function CalendarMock() {
  const cells = Array.from({length: 14}, (_, i) => i);
  const evts = {2:"VideoForge", 4:"BrandMind", 5:"DesignFlow", 7:"SocialPulse", 9:"BrandMind", 11:"VideoForge", 12:"CopyCraft"};
  return (
    <div className="mock">
      <div className="mock__bar"><div className="dots"><span/><span/><span/></div><span>SCHEDULER · 2-WEEK VIEW</span></div>
      <div className="mock__body">
        <div className="cal-grid">
          {cells.map(i => (
            <div key={i} className="cal-cell">
              <div>{i + 12}</div>
              {evts[i] && <div className={"pill " + (i%3===0 ? "pill--bone" : "")}>{evts[i]}</div>}
              {i % 5 === 2 && <div className="pill pill--bone">Insight</div>}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
function DashboardMock() {
  return (
    <div className="mock">
      <div className="mock__bar"><div className="dots"><span/><span/><span/></div><span>INSIGHT ORACLE · LIVE</span></div>
      <div className="mock__body">
        <div className="dash-grid">
          <div className="dash-card"><div className="lbl">CPA · META</div><div className="val">$11.40</div><div className="delta">↓ 23% w/w</div><div className="dash-spark"/></div>
          <div className="dash-card"><div className="lbl">Organic CTR</div><div className="val">4.7%</div><div className="delta">↑ 0.6 pp</div><div className="dash-spark"/></div>
          <div className="dash-card"><div className="lbl">Pipeline</div><div className="val">$284K</div><div className="delta">↑ 18%</div><div className="dash-spark"/></div>
          <div className="dash-card"><div className="lbl">MRR Add</div><div className="val">$41.2K</div><div className="delta">↑ 9%</div><div className="dash-spark"/></div>
        </div>
      </div>
    </div>
  );
}
function SecurityMock() {
  return (
    <div className="mock">
      <div className="mock__bar"><div className="dots"><span/><span/><span/></div><span>PENTEST PHANTOM · WEEK 17</span></div>
      <div className="mock__body">
        <div className="report-row"><span className="sev-ok">▪ OK</span><span>OWASP A01 — Broken Access Control</span><span className="mute">passed</span></div>
        <div className="report-row"><span className="sev-md">▪ MED</span><span>CVE-2026-1142 · lib/markdown@4.2</span><span className="mute">patch ready</span></div>
        <div className="report-row"><span className="sev-hi">▪ HIGH</span><span>Exposed admin route /internal/_debug</span><span className="mute">9m to fix</span></div>
        <div className="report-row"><span className="sev-ok">▪ OK</span><span>Dependency tree · 248 packages</span><span className="mute">clean</span></div>
        <div className="report-row"><span className="sev-ok">▪ OK</span><span>TLS · cipher suites · HSTS</span><span className="mute">A+</span></div>
      </div>
    </div>
  );
}
function OpsMock() {
  return (
    <div className="mock">
      <div className="mock__bar"><div className="dots"><span/><span/><span/></div><span>CHATOPS · LIVE QUEUE</span></div>
      <div className="mock__body">
        <div className="log-row"><span className="t">14:02</span><span>Resolved IG DM · sizing question</span><span className="n">auto</span></div>
        <div className="log-row"><span className="t">14:04</span><span>Routed FB comment · refund · → human</span><span className="n">handoff</span></div>
        <div className="log-row"><span className="t">14:06</span><span>Resolved live chat · order status</span><span className="n">auto</span></div>
        <div className="log-row"><span className="t">14:08</span><span>Resolved IG DM · gift wrap</span><span className="n">auto</span></div>
        <div className="log-row"><span className="t">14:11</span><span>Resolved email · shipping ETA</span><span className="n">auto</span></div>
        <div className="log-row"><span className="t">14:14</span><span>Routed TikTok comment · partnership</span><span className="n">handoff</span></div>
      </div>
    </div>
  );
}

function Divisions({ scrollToBuilder, addAgent, rosterIds }) {
  const blocks = [
    {
      num: "01 / GROWTH",
      h: "Marketing that compounds while you sleep.",
      copy: "Six agents that prospect, plan, post, optimize, and report — together. They share a brand-memory, watch each other's metrics, and rebid your campaigns hourly. The Friday brief is what your CMO reads with coffee.",
      mock: <CalendarMock />,
      agents: ["brandmind","campaignbot","seo-sentinel","socialpulse","insight-oracle","lead-hunter"],
      stat: <span><strong>+218%</strong> average pipeline lift across Growth deployments, Q1 2026.</span>,
    },
    {
      num: "02 / CREATIVE",
      h: "Studio output, no studio overhead.",
      copy: "Three agents that draft, design, and edit on your visual identity. They learn from what's already converted and ship more of it — with the rough edges only humans should be allowed to smooth.",
      mock: <DashboardMock />,
      agents: ["designflow","videoforge","copycraft"],
      stat: <span><strong>4,200+</strong> on-brand assets shipped in the last 30 days. Zero stock photos.</span>,
      reverse: true,
    },
    {
      num: "03 / ENGINEERING GUARDIANS",
      h: "Marketing is wasted on a site that breaks.",
      copy: "Three agents that audit and protect the digital products you're spending money to drive traffic to. They run on every deploy, and they file the ticket before the support inbox does.",
      mock: <SecurityMock />,
      agents: ["qa-sentinel","stressforge","pentest-phantom"],
      stat: <span>Engineering Guardians prevented <strong>1,247 incidents</strong> this quarter.</span>,
    },
    {
      num: "04 / OPERATIONS",
      h: "Conversations, handled. Until they shouldn't be.",
      copy: "ChatOps holds the line on inbound — DMs, comments, live chat — across every surface. It hands off to a human only when the message actually needs one. The handoff comes with context, not a transcript.",
      mock: <OpsMock />,
      agents: ["chatops"],
      stat: <span><strong>91%</strong> of inbound resolved without human touch. The other 9% gets there fast.</span>,
      reverse: true,
    },
  ];
  return (
    <section className="divisions container" id="divisions">
      <div className="eyebrow" style={{marginBottom:36}}>// THE DIVISIONS</div>
      {blocks.map((b, i) => (
        <div key={i} className={"div-block " + (b.reverse ? "reverse" : "")}>
          <div>{b.mock}</div>
          <div>
            <div className="div-block__num">{b.num}</div>
            <h3 className="div-block__h">{b.h}</h3>
            <p className="div-block__copy">{b.copy}</p>
            <div className="div-block__agents">
              {b.agents.map(id => {
                const a = AGENTS.find(x => x.id === id);
                if (!a) return null;
                const added = rosterIds.includes(id);
                return (
                  <button
                    key={id}
                    className={"chip " + (added ? "chip--active" : "")}
                    onClick={() => { addAgent(id); scrollToBuilder(); }}
                  >
                    {added ? "✓ " : "+ "}{a.name}
                  </button>
                );
              })}
            </div>
            <div className="div-block__stat">{b.stat}</div>
          </div>
        </div>
      ))}
    </section>
  );
}

// --- Squads ---
function Squads({ loadSquad }) {
  return (
    <section className="squads container" id="squads">
      <div className="squads__head">
        <div>
          <div className="eyebrow">// SQUAD PRESETS</div>
          <h2 className="squads__title">One-click rosters,<br/>for the impatient.</h2>
        </div>
        <div className="mute mono" style={{maxWidth:300, fontSize:"0.8rem"}}>Click a squad. Your roster fills. Customize from there.</div>
      </div>
      <div className="squads__row">
        {SQUADS.map(s => (
          <div key={s.id} className="squad-card" onClick={() => loadSquad(s.id)}>
            <div className="eyebrow">{s.id === "launch" ? "FAVORITE" : s.id === "enterprise" ? "FLAGSHIP" : "PRESET"}</div>
            <div className="squad-card__h">{s.name}</div>
            <div className="squad-card__price">${fmt(s.price)}<span className="unit">/mo</span></div>
            <div className="squad-card__pitch">{s.pitch}</div>
            <div className="squad-card__list">
              {s.agents.map(id => AGENTS.find(a => a.id === id)?.name).filter(Boolean).join(" · ")}
            </div>
            <button className="btn btn--ghost btn--small">Load Squad →</button>
          </div>
        ))}
      </div>
    </section>
  );
}

// --- Compare table ---
function Compare() {
  const rows = [
    { d: "Time to deploy", h: "6–12 weeks", a: "48 hours" },
    { d: "Loaded monthly cost (1 marketer)", h: "$7,500–$12,000", a: "$700–$2,400 per agent" },
    { d: "Working hours", h: "~160/mo", a: "720/mo (every hour)" },
    { d: "Output ceiling", h: "Linear", a: "Configurable, scalable" },
    { d: "Sick days / PTO", h: "Yes", a: "None" },
    { d: "Strategic judgment", h: "High", a: "Medium-high (and improving)", honest: true },
    { d: "Brand intuition", h: "High", a: "Medium (we co-train on your brand)", honest: true },
  ];
  return (
    <section className="compare container">
      <div className="compare__head">
        <div>
          <div className="eyebrow">// HUMAN VS. AI ROSTER</div>
          <h2 className="compare__title">An honest comparison.<br/>Including what we don't do as well.</h2>
        </div>
      </div>
      <table className="compare__table">
        <thead>
          <tr><th>Dimension</th><th>Hiring Humans</th><th className="win">Deploying Agents</th></tr>
        </thead>
        <tbody>
          {rows.map((r, i) => (
            <tr key={i} className={r.honest ? "row-honest" : ""}>
              <td>{r.d}</td>
              <td>{r.h}</td>
              <td>{r.a}</td>
            </tr>
          ))}
        </tbody>
      </table>
      <div className="compare__callout">
        That's why every roster has a human onboarding lead. We're not replacing your judgment. We're cloning your output.
      </div>
    </section>
  );
}

// --- Stack ---
function Stack() {
  return (
    <section className="stack">
      <div className="container stack__row">
        <div>
          <div className="eyebrow">// STACK & TRUST</div>
          <h3 className="h-display" style={{fontSize:"clamp(2rem, 4vw, 3.4rem)", margin:"14px 0 24px"}}>Frontier models. Boring infrastructure. Loud results.</h3>
          <div className="stack__logos">
            <div className="stack-logo">Anthropic</div>
            <div className="stack-logo">OpenAI</div>
            <div className="stack-logo">Google AI</div>
            <div className="stack-logo">Stripe</div>
            <div className="stack-logo">Supabase</div>
          </div>
        </div>
        <div>
          <p className="stack__copy">
            Every agent is a thin scaffold around a frontier model and a stack you've already heard of. We don't run our own LLM. We don't fine-tune on your data. We orchestrate, guard, and ship.
          </p>
          <div className="trust-chips">
            <div className="chip">SOC2 Type II in progress</div>
            <div className="chip">GDPR-aligned</div>
            <div className="chip">Data export on request, every time</div>
          </div>
        </div>
      </div>
    </section>
  );
}

// --- Ticker ---
function Ticker() {
  const items = useMemo(() => {
    const arr = [];
    const now = new Date();
    for (let i = 0; i < 14; i++) {
      const tpl = TICKER_TEMPLATES[Math.floor(Math.random() * TICKER_TEMPLATES.length)];
      const brand = TICKER_BRANDS[Math.floor(Math.random() * TICKER_BRANDS.length)];
      const t = new Date(now.getTime() - i * 1000 * 60 * (1 + Math.random() * 4));
      const text = tpl
        .replace("{n}", Math.floor(2 + Math.random() * 24))
        .replace("{m}", Math.floor(3 + Math.random() * 14))
        .replace("{p}", Math.floor(8 + Math.random() * 30))
        .replace("{brand}", brand);
      arr.push({ t: `${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`, text });
    }
    return arr;
  }, []);
  const doubled = [...items, ...items];
  return (
    <section className="ticker" aria-hidden="true">
      <div className="ticker__lbl"><span className="dot"></span>Live · Roster Activity</div>
      <div className="ticker__track">
        {doubled.map((it, i) => (
          <span key={i}><span className="t">●</span><span className="b">{it.t}</span> {it.text}</span>
        ))}
      </div>
    </section>
  );
}

// --- FAQ ---
function FAQ() {
  const [open, setOpen] = useState(0);
  return (
    <section className="faq container" id="faq">
      <div className="eyebrow" style={{marginBottom:14}}>// FAQ</div>
      <h2 className="faq__title">Things you should ask<br/>before you sign anything.</h2>
      <div className="faq__list">
        {FAQS.map((f, i) => (
          <div key={i} className={"faq-item " + (open === i ? "faq-item--open" : "")}>
            <button className="faq-item__q" onClick={() => setOpen(open === i ? -1 : i)}>
              <span>{f.q}</span><span className="plus">+</span>
            </button>
            <div className="faq-item__a"><div className="faq-item__a-inner">{f.a}</div></div>
          </div>
        ))}
      </div>
    </section>
  );
}

// --- Final CTA + Footer ---
function FinalCta({ onDeploy }) {
  return (
    <section className="final container">
      <div className="eyebrow" style={{marginBottom:24}}>// LAST WORD</div>
      <h2 className="final__h">Prevent your brand<br/>from <span className="gold">egging.</span></h2>
      <button className="btn btn--gold" onClick={onDeploy} style={{padding:"22px 28px"}}>Deploy a Roster →</button>
      <div className="final__contact">Info@drotteneggs.com · drotteneggs.com</div>
    </section>
  );
}

function Footer() {
  const linkAgent = (id) => () => {
    const el = document.getElementById("builder");
    if (el) el.scrollIntoView({ behavior: "smooth" });
  };
  return (
    <footer className="foot">
      <div className="container">
        <div className="foot__cols">
          <div className="foot__col">
            <h4>DROTTEN EGGS</h4>
            <p className="mute mono" style={{fontSize:"0.74rem", lineHeight:1.6}}>
              A 360° AI marketing agency. Brands that never sleep. Built in 2026.
            </p>
          </div>
          <div className="foot__col">
            <h4>Agents</h4>
            <ul>{AGENTS.slice(0,7).map(a => <li key={a.id}><a href="#builder" onClick={linkAgent(a.id)}>{a.name}</a></li>)}</ul>
          </div>
          <div className="foot__col">
            <h4>Squads</h4>
            <ul>{SQUADS.map(s => <li key={s.id}><a href="#squads">{s.name}</a></li>)}</ul>
          </div>
          <div className="foot__col">
            <h4>Legal</h4>
            <ul>
              <li><a href="#">Privacy</a></li>
              <li><a href="#">Terms</a></li>
              <li><a href="#">DPA</a></li>
              <li><a href="#">Security</a></li>
            </ul>
          </div>
        </div>
        <div className="foot__sign">
          <span>© 2026 DROTTEN EGGS</span>
          <span>BRANDS THAT NEVER SLEEP.</span>
        </div>
        <div className="foot__neon">© 2026 DROTTEN EGGS · BRANDS THAT NEVER SLEEP.</div>
      </div>
    </footer>
  );
}

// --- Lock sheet ---
function LockSheet({ open, onClose, total, count }) {
  const [submitted, setSubmitted] = useState(false);
  const [form, setForm] = useState({ name: "", email: "", brand: "", goal: "" });
  if (!open) return null;
  return (
    <div className="sheet" onClick={(e) => { if (e.target.classList.contains("sheet")) onClose(); }}>
      <div className="sheet__panel">
        <button className="sheet__close" onClick={onClose}>CLOSE</button>
        {!submitted ? (
          <React.Fragment>
            <div className="eyebrow" style={{marginBottom:10}}>// LOCK ROSTER</div>
            <h3 className="sheet__h">Lock {count} agents · ${fmt(total)}/mo</h3>
            <p className="sheet__sub">No card. Your onboarding lead is in touch within one business hour.</p>
            <form onSubmit={(e) => { e.preventDefault(); setSubmitted(true); }}>
              <div className="field"><label>Your name</label><input required value={form.name} onChange={(e) => setForm({...form, name: e.target.value})}/></div>
              <div className="field"><label>Work email</label><input required type="email" value={form.email} onChange={(e) => setForm({...form, email: e.target.value})}/></div>
              <div className="field"><label>Brand</label><input required value={form.brand} onChange={(e) => setForm({...form, brand: e.target.value})}/></div>
              <div className="field"><label>One-line goal</label><textarea value={form.goal} onChange={(e) => setForm({...form, goal: e.target.value})}/></div>
              <button type="submit" className="btn btn--gold btn--block" style={{padding:"18px 22px"}}>Lock Roster →</button>
            </form>
          </React.Fragment>
        ) : (
          <div className="sheet__success">
            <div className="check">✓</div>
            <h3 className="sheet__h">Locked.</h3>
            <p className="sheet__sub">We're spinning up your onboarding workspace. You'll get a Calendly + a brand-kit checklist in your inbox within the next hour.</p>
            <button className="btn btn--ghost" onClick={onClose}>Close</button>
          </div>
        )}
      </div>
    </div>
  );
}

// --- See an Agent Run modal ---
function DemoModal({ open, onClose }) {
  if (!open) return null;
  return (
    <div className="sheet" onClick={(e) => { if (e.target.classList.contains("sheet")) onClose(); }}>
      <div className="sheet__panel" style={{width:"min(720px, 100%)"}}>
        <button className="sheet__close" onClick={onClose}>CLOSE</button>
        <div className="eyebrow" style={{marginBottom:10}}>// 30S DEMO</div>
        <h3 className="sheet__h">CampaignBot · live ad rebid</h3>
        <p className="sheet__sub">A 30-second muted loop. The agent watches a Meta campaign for an hour, detects under-performers, and rebids without supervision.</p>
        <div style={{aspectRatio:"16/9", background:"var(--ink-3)", border:"1px solid var(--hair)", display:"flex", alignItems:"center", justifyContent:"center", marginTop:14, position:"relative"}}>
          <div className="mono mute" style={{letterSpacing:"0.2em", fontSize:"0.75rem"}}>[ 00:14 / 00:30 — DEMO LOOP ]</div>
          <div style={{position:"absolute", inset:14, border:"1px dashed var(--hair-2)"}}/>
        </div>
        <p className="mono mute" style={{marginTop:14, fontSize:"0.74rem"}}>video placeholder · supply your own .mp4 to slot in here</p>
      </div>
    </div>
  );
}

// --- Agent datasheet panel ---
function AgentSheet({ agent, onClose, onAdd, added }) {
  if (!agent) return null;
  return (
    <div className="sheet" onClick={(e) => { if (e.target.classList.contains("sheet")) onClose(); }}>
      <div className="sheet__panel">
        <button className="sheet__close" onClick={onClose}>CLOSE</button>
        <div className="eyebrow" style={{marginBottom:10}}>// AGENT · {agent.division}</div>
        <h3 className="sheet__h">{agent.name}</h3>
        <p className="sheet__sub">{agent.role} — {agent.description}</p>
        <div style={{display:"flex", gap:14, alignItems:"center", marginBottom:24}}>
          <div className="agent__glyph-wrap" style={{width:80, height:80}}><AgentGlyph name={agent.glyph} animated /></div>
          <div>
            <div className="h-display" style={{fontSize:"2.4rem", color:"var(--gold)"}}>${fmt(agent.priceMonthly)}<span className="mono mute" style={{fontSize:"0.7rem"}}>/mo</span></div>
            <div className="mono mute" style={{fontSize:"0.7rem", letterSpacing:"0.14em"}}>or ${fmt(agent.priceOneTime)} one-time deploy</div>
          </div>
        </div>
        <div className="div-block__stat" style={{marginTop:0, marginBottom:16}}>
          <strong>Throughput:</strong> {agent.throughput}
        </div>
        <div className="div-block__stat" style={{marginTop:0, marginBottom:16}}>
          <strong>Stack:</strong> {agent.stack.join(" · ")}
        </div>
        <div className="mock" style={{marginBottom:20}}>
          <div className="mock__bar"><div className="dots"><span/><span/><span/></div><span>SAMPLE OUTPUT · LAST 24H</span></div>
          <div className="mock__body">
            <div className="log-row"><span className="t">09:14</span><span>Generated brief · Q2 paid acquisition · 3 channels</span><span className="n">ok</span></div>
            <div className="log-row"><span className="t">11:02</span><span>Shipped {agent.name} task · approved by guardrail</span><span className="n">ok</span></div>
            <div className="log-row"><span className="t">13:48</span><span>Friday brief · 412 KPIs · summary attached</span><span className="n">ok</span></div>
            <div className="log-row"><span className="t">17:30</span><span>Re-ran on new brand-kit upload · variance 4%</span><span className="n">ok</span></div>
          </div>
        </div>
        <button
          className={"btn " + (added ? "btn--ghost" : "btn--gold") + " btn--block"}
          onClick={() => { onAdd(agent.id); }}
          style={{padding:"18px 22px"}}
        >
          {added ? "✓ Added · Remove from Roster" : "+ Add to Roster"}
        </button>
      </div>
    </div>
  );
}

// --- App ---
function App() {
  const [rosterIds, setRosterIds] = useLocal("dre.roster", []);
  const [billing, setBilling] = useLocal("dre.billing", "monthly");
  const [toast, setToast] = useState(null);
  const [lockOpen, setLockOpen] = useState(false);
  const [demoOpen, setDemoOpen] = useState(false);
  const [agentOpen, setAgentOpen] = useState(null);
  const builderRef = useRef(null);

  const addAgent = useCallback((id) => {
    setRosterIds(prev => prev.includes(id) ? prev : [...prev, id]);
  }, []);
  const removeAgent = useCallback((id) => {
    setRosterIds(prev => prev.filter(x => x !== id));
  }, []);
  const scrollToBuilder = useCallback(() => {
    if (builderRef.current) builderRef.current.scrollIntoView({ behavior: "smooth", block: "start" });
  }, []);

  const loadSquad = useCallback((id) => {
    const s = SQUADS.find(x => x.id === id);
    if (!s) return;
    setRosterIds([...s.agents]);
    setToast({ msg: `${s.name} loaded. Scroll up to customize.`, action: scrollToBuilder });
  }, []);

  useEffect(() => {
    if (!toast) return;
    const t = setTimeout(() => setToast(null), 4000);
    return () => clearTimeout(t);
  }, [toast]);

  const total = rosterIds.reduce((s, id) => {
    const a = AGENTS.find(x => x.id === id); if (!a) return s;
    return s + (billing === "monthly" ? a.priceMonthly : a.priceOneTime);
  }, 0);

  return (
    <React.Fragment>
      <div className="noise" />
      <CursorDot />
      <ScrollProgress />
      <TopNav onDeploy={() => setLockOpen(true)} />

      <Hero onDeploy={scrollToBuilder} onSeeRun={() => setDemoOpen(true)} />
      <LiveCounters />
      <Mechanic />
      <Builder
        rosterIds={rosterIds}
        addAgent={addAgent}
        removeAgent={removeAgent}
        billing={billing}
        setBilling={setBilling}
        onLock={() => setLockOpen(true)}
        onOpenAgent={setAgentOpen}
        builderRef={builderRef}
      />
      <Divisions scrollToBuilder={scrollToBuilder} addAgent={addAgent} rosterIds={rosterIds} />
      <Squads loadSquad={loadSquad} />
      <Compare />
      <Stack />
      <Ticker />
      <Blog />
      <FAQ />
      <FinalCta onDeploy={() => setLockOpen(true)} />
      <Footer />

      {toast && (
        <div className="toast" onClick={() => { toast.action && toast.action(); setToast(null); }}>
          ● {toast.msg}
        </div>
      )}

      <LockSheet open={lockOpen} onClose={() => setLockOpen(false)} total={total} count={rosterIds.length} />
      <DemoModal open={demoOpen} onClose={() => setDemoOpen(false)} />
      <AgentSheet
        agent={agentOpen}
        added={agentOpen && rosterIds.includes(agentOpen.id)}
        onClose={() => setAgentOpen(null)}
        onAdd={(id) => {
          if (rosterIds.includes(id)) removeAgent(id);
          else { addAgent(id); setAgentOpen(null); }
        }}
      />
    </React.Fragment>
  );
}

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