/* Hero — headline + auto-toggling "two modes" panel.
   Red-teaming (before launch · adversarial scenario matrix, warm) ↔
   Monitoring (after launch · live production feed, cool). Auto-switches every 5s. */

function renderHeadlinePart(text, key) {
  const parts = text.split(/(\{\{[^}]+\}\})/g).filter(Boolean);
  return parts.map((p, i) => {
    const m = p.match(/^\{\{(.+)\}\}$/);
    if (m) return <span key={key + "-" + i} className="hl-code">{m[1]}</span>;
    return <React.Fragment key={key + "-" + i}>{p}</React.Fragment>;
  });
}

function Hero({ headline }) {
  return (
    <section className="hero hero-centered">
      <div className="wrap">
        <div className="hero-copy">
          <span className="eyebrow"><span className="live"/>AI forward deployed engineer for voice agents</span>
          <h1 className="display" data-comment-anchor="hero-headline">
            {headline.split("·").map((part, i) =>
              i === 0
                ? <span key={i}>{renderHeadlinePart(part.trim(), "p" + i)}</span>
                : <span key={i} className="ink-soft"><br/>{renderHeadlinePart(part.trim(), "p" + i)}</span>
            )}
          </h1>
          <p className="subhead">
            Audia finds the root cause and ships the corrected prompt and workflow, instead of just handing you a flagged transcript.
          </p>

          <div className="cta-row">
            <button className="btn primary lg" onClick={() => window.openEarlyAccess && window.openEarlyAccess()}>Get early access <Icon name="arrow" size={15} style={{ marginLeft: 7, verticalAlign: -2 }}/></button>
          </div>

          <div className="pedigree">
            <span className="pedigree-label">Built by eval engineers</span>
            <span className="pedigree-chips">
              <span className="pedigree-chip"><img className="pedigree-logo" src="cartesia.svg" alt=""/>Cartesia</span>
              <span className="pedigree-chip"><img className="pedigree-logo" src="waymo.svg" alt=""/>Waymo</span>
            </span>
          </div>
        </div>

        <ToggleHero/>
      </div>
    </section>
  );
}

/* ---------- Red-teaming surface: adversarial scenario matrix (live) ----------
   A probe pointer sweeps the scenarios: queued → probing… → resolved (hardened/broke),
   the scenario count ticks up, then the cycle restarts. */
const SCN = [
  { n: "overlapping speech",     end: "hardened" },
  { n: "heavy accent",           end: "hardened" },
  { n: "rapid topic switch",     end: "broke" },
  { n: "mid-call interruption",  end: "hardened" },
  { n: "silent caller",          end: "hardened" },
  { n: "abuse / profanity",      end: "broke" },
  { n: "background crosstalk",   end: "hardened" },
  { n: "code-switch mid-call",   end: "broke" },
];
const BADGE = {
  queued: "queued",
  probing: "probing…",
  broke: "broke → patching",
  hardened: "hardened ✓",
};
const RT_LOOP = ["Probe", "Harden", "Re-run"];
const MON_LOOP = ["Diagnose", "Ship fix", "Verify"];

/* Loop strip — shows the three stages of a mode's cycle, active stage pulsing */
function LoopStrip({ accent, steps, active }) {
  return (
    <div className={"loop-strip " + accent}>
      {steps.map((s, i) => (
        <React.Fragment key={s}>
          <span className={"loop-step" + (i === active ? " on" : "")}>
            <span className="loop-pip"/>{s}
          </span>
          {i < steps.length - 1 && <span className="loop-arr">→</span>}
        </React.Fragment>
      ))}
    </div>
  );
}

function RedteamSurface() {
  const N = SCN.length;
  const [step, setStep] = React.useState(1);     // probe pointer (0..N); >step queued, <step resolved
  const [count, setCount] = React.useState(1234);
  const [loop, setLoop] = React.useState(0);

  React.useEffect(() => {
    const t = setInterval(() => {
      setStep((s) => (s >= N ? 0 : s + 1));
      setCount((c) => c + 1);
    }, 2200);
    const l = setInterval(() => setLoop((x) => (x + 1) % 3), 2200);
    return () => { clearInterval(t); clearInterval(l); };
  }, [N]);

  const running = step < N ? 1 : 0;

  return (
    <div className="surface">
      <div className="surface-head">
        <span className="sh-l"><span className="sh-dot warm"/>Adversarial suite</span>
        <span className="sh-r">{count.toLocaleString()} scenarios · {running} running</span>
      </div>
      <LoopStrip accent="warm" steps={RT_LOOP} active={loop}/>
      <div className="scn-grid">
        {SCN.map((x, i) => {
          const st = i < step ? x.end : i === step ? "probing" : "queued";
          return (
            <div className={"scn" + (st === "probing" ? " live" : "")} key={x.n}>
              <span className="scn-n">{x.n}</span>
              <span className={"badge " + st}>{BADGE[st]}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ---------- Monitoring surface: live production feed ----------
   New calls stream in at the top every ~1.9s; regressions bump the day counter. */
const CALL_POOL = [
  { s: "regression", h: [5, 11, 7, 14, 9, 6, 12, 8] },
  { s: "ok",         h: [4, 7, 5, 8, 6, 5, 7, 4] },
  { s: "ok",         h: [5, 7, 4, 8, 5, 6, 5, 4] },
  { s: "regression", h: [6, 12, 8, 13, 7, 11, 9, 6] },
  { s: "ok",         h: [4, 6, 5, 7, 5, 6, 4, 5] },
  { s: "ok",         h: [5, 8, 5, 7, 6, 5, 7, 5] },
  { s: "regression", h: [7, 13, 9, 12, 8, 11, 10, 7] },
  { s: "ok",         h: [4, 6, 4, 7, 5, 5, 6, 4] },
];
const newCallId = () => "call_" + Math.random().toString(16).slice(2, 6);
const seedCall = (i) => ({ ...CALL_POOL[i % CALL_POOL.length], id: newCallId(), k: "seed-" + i });

function MonitorSurface() {
  const [feed, setFeed] = React.useState(() => [0, 1, 2, 3, 4].map(seedCall));
  const [caught, setCaught] = React.useState(3);
  const idx = React.useRef(5);

  React.useEffect(() => {
    const t = setInterval(() => {
      const base = CALL_POOL[idx.current % CALL_POOL.length];
      idx.current += 1;
      const item = { ...base, id: newCallId(), k: "c-" + idx.current + "-" + Date.now() };
      setFeed((f) => [item, ...f].slice(0, 5));
      if (base.s === "regression") setCaught((c) => c + 1);
    }, 3600);
    return () => clearInterval(t);
  }, []);

  return (
    <div className="surface">
      <div className="surface-head">
        <span className="sh-l"><span className="sh-dot cool"/>Production · live</span>
        <span className="sh-r">{caught} regressions caught today</span>
      </div>
      <div className="feed">
        {feed.map((c) => (
          <div className={"call" + (c.s === "regression" ? " flag" : "")} key={c.k}>
            <span className="cid">{c.id}</span>
            <span className="wave">{c.h.map((v, i) => <i key={i} style={{ height: v + "px" }}/>)}</span>
            <span className="st">{c.s === "regression" ? "regression" : "ok"}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

const MODES = {
  redteam: { label: "Pre-production · Red-teaming", accent: "warm", Surface: RedteamSurface },
  monitor: { label: "Post-production · Monitoring", accent: "cool", Surface: MonitorSurface },
};
const ORDER = ["redteam", "monitor"];

function ToggleHero() {
  const [i, setI] = React.useState(0);
  const key = ORDER[i];
  const m = MODES[key];
  const Surface = m.Surface;
  return (
    <div className={"search-card hero-toggle " + m.accent} data-comment-anchor="hero-search">
      <div className="toggle">
        {ORDER.map((k) => (
          <button
            className={"seg" + (k === key ? " on " + MODES[k].accent : "")}
            key={k}
            onClick={() => setI(ORDER.indexOf(k))}
          >{MODES[k].label}</button>
        ))}
      </div>
      <Surface/>
    </div>
  );
}

Object.assign(window, { Hero, ToggleHero });
