/* cucaracha.jsx — La Cucaracha per-VM operator runbook (detail view).
   A password-gated, internal demo runbook: 5 fixed sections per VM, CLI
   blocks with copy buttons, a posture badge, and an amber/green
   expected-result callout. {{PLACEHOLDERS}} render as TBD chips — never
   invent their values. Reached via the hash route #/cucaracha/<vmId>. */

// ---- TBD placeholder rendering -------------------------------------------
// Splits text on {{TOKENS}} and renders each as a clearly-marked chip.
function TbdText({ text, th }) {
  if (!text) return null;
  const parts = String(text).split(/(\{\{[^}]+\}\})/g);
  return (
    <>
      {parts.map((p, i) =>
        /^\{\{[^}]+\}\}$/.test(p) ? (
          <span key={i} className="mx-0.5 inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 align-baseline text-[0.82em] font-semibold" style={{ background: th.tbdBg, color: th.tbdInk, border: `1px dashed ${th.tbdBorder}`, fontFamily: "'JetBrains Mono', monospace" }}>
            <window.Icon name="Wrench" size={11} /> {p.replace(/[{}]/g, "")}
          </span>
        ) : (
          <React.Fragment key={i}>{p}</React.Fragment>
        )
      )}
    </>
  );
}

// monospace line with {{TOKENS}} tinted inline (no chip box — keeps the CLI legible)
function CodeLine({ text, th }) {
  const parts = String(text).split(/(\{\{[^}]+\}\})/g);
  return (
    <>
      {parts.map((p, i) =>
        /^\{\{[^}]+\}\}$/.test(p) ? (
          <span key={i} style={{ color: th.codeTbd, fontWeight: 600 }}>{p}</span>
        ) : (
          <React.Fragment key={i}>{p}</React.Fragment>
        )
      )}
    </>
  );
}

// Lives OUTSIDE the dark code box, on the light card surface — so it always has
// card-vs-ink contrast (never black-on-black inside the terminal block).
function CucCopyButton({ getText, th }) {
  const [done, setDone] = React.useState(false);
  const doCopy = () => {
    const t = getText(); if (t == null) return; const s = String(t);
    const flash = () => { setDone(true); setTimeout(() => setDone(false), 1400); };
    const ask = () => { try { window.prompt("Copy this command (⌘C / Ctrl-C), then press Enter:", s); } catch (e) {} };
    const fb = () => { try { const ta = document.createElement("textarea"); ta.value = s; ta.readOnly = true; ta.style.position = "fixed"; ta.style.top = "-9999px"; document.body.appendChild(ta); ta.focus(); ta.select(); ta.setSelectionRange(0, s.length); const ok = document.execCommand("copy"); document.body.removeChild(ta); ok ? flash() : ask(); } catch (e) { ask(); } };
    try { if (navigator.clipboard && navigator.clipboard.writeText && window.isSecureContext) { const p = navigator.clipboard.writeText(s); if (p && p.then) p.then(flash, fb); else flash(); } else { fb(); } } catch (e) { fb(); }
  };
  return (
    <button
      onClick={doCopy}
      className="inline-flex shrink-0 items-center gap-1.5 rounded-lg px-3 py-1.5 text-[11.5px] font-semibold transition-colors"
      style={{ background: done ? th.posEnforce.bg : th.chip, color: done ? th.posEnforce.ink : th.ink, border: `1px solid ${done ? th.posEnforce.border : th.cardBorder}`, fontFamily: "'JetBrains Mono', monospace", cursor: "pointer" }}
    >
      <window.Icon name={done ? "Check" : "Copy"} size={13} /> {done ? "Copied" : "Copy"}
    </button>
  );
}

function CodeBlock({ code, th }) {
  return (
    <div>
      <div className="mb-1.5 flex justify-end">
        <CucCopyButton getText={() => code} th={th} />
      </div>
      <div className="rounded-xl px-4 py-3.5" style={{ background: th.codeBg, border: `1px solid ${th.codeBorder}` }}>
        <code className="block min-w-0 whitespace-pre-wrap break-all text-[13px] leading-relaxed" style={{ color: th.codeInk, fontFamily: "'JetBrains Mono', monospace" }}>
          <CodeLine text={code} th={th} />
        </code>
      </div>
    </div>
  );
}

function PostureBadge({ posture, th }) {
  const enforce = posture === "enforce";
  const c = enforce ? th.posEnforce : th.posObserve;
  return (
    <span className="inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[10.5px] font-bold uppercase tracking-[0.14em]" style={{ background: c.bg, color: c.ink, border: `1px solid ${c.border}`, fontFamily: "'JetBrains Mono', monospace" }}>
      <window.Icon name={enforce ? "ShieldCheck" : "Eye"} size={12} /> {enforce ? "Enforcing" : "Observe-only"}
    </span>
  );
}

// numbered section shell
function Section({ n, icon, title, th, children }) {
  return (
    <section className="relative">
      <div className="mb-3 flex items-center gap-3">
        <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg text-[12px] font-bold" style={{ background: th.numBg, color: th.numInk, fontFamily: "'JetBrains Mono', monospace" }}>{n}</span>
        <span className="inline-flex items-center gap-2 text-[12px] font-bold uppercase tracking-[0.16em]" style={{ color: th.faint, fontFamily: "'JetBrains Mono', monospace" }}>
          <window.Icon name={icon} size={14} /> {title}
        </span>
      </div>
      <div className="pl-10">{children}</div>
    </section>
  );
}

function ResultCallout({ result, th }) {
  const green = result.tone === "green";
  const c = green ? th.calloutGreen : th.calloutAmber;
  return (
    <div className="rounded-2xl p-4" style={{ background: c.bg, border: `1px solid ${c.border}` }}>
      <div className="flex items-start gap-3">
        <span className="mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-lg" style={{ background: c.iconBg, color: c.ink }}>
          <window.Icon name={green ? "ShieldCheck" : "TriangleAlert"} size={16} />
        </span>
        <div>
          <div className="text-[15px] font-extrabold leading-snug" style={{ color: c.ink, fontFamily: "'Manrope', sans-serif" }}>{result.headline}</div>
          <p className="mt-1 text-[13.5px] leading-relaxed" style={{ color: c.detail }}>{result.detail}</p>
        </div>
      </div>
    </div>
  );
}

// ---- the page ------------------------------------------------------------
function CucarachaRunbook({ vmId, mode, navigate, onBack }) {
  const base = window.SHELL_THEMES[mode] || window.SHELL_THEMES.dark;
  const rb = window.getRunbook(vmId);
  React.useEffect(() => { if (!rb) navigate("#/hub"); }, [rb]);
  if (!rb) return null;

  // Sections 1-5 are always present; the optional tail blocks number themselves
  // so a card missing one does not leave a gap in the sequence.
  const secN = (() => { let i = 5; const o = {};
    for (const k of ["inspect", "runtime", "activityDemo", "troubleshoot", "reset"]) if (rb[k]) o[k] = ++i;
    return o; })();

  // derived runbook-specific tokens layered on the shell theme
  const dark = mode === "dark";
  const th = {
    ...base,
    faint: base.sub,
    numBg: dark ? "rgba(255,255,255,0.07)" : "rgba(42,28,34,0.06)",
    numInk: base.inkStrong,
    codeBg: dark ? "rgba(0,0,0,0.34)" : "#0f172a",
    codeInk: dark ? "#dfe7ef" : "#e6edf6",
    codeBorder: dark ? "rgba(255,255,255,0.10)" : "rgba(15,23,42,0.5)",
    codeTbd: "#f6b24b",
    copyBg: "rgba(255,255,255,0.14)",
    copyInk: "#eaf0f7",
    copyBorder: "rgba(255,255,255,0.30)",
    tbdBg: dark ? "rgba(246,178,75,0.12)" : "rgba(180,120,20,0.10)",
    tbdInk: dark ? "#f6b24b" : "#9a6a12",
    tbdBorder: dark ? "rgba(246,178,75,0.5)" : "rgba(180,120,20,0.45)",
    posObserve: { bg: dark ? "rgba(246,178,75,0.12)" : "rgba(180,120,20,0.10)", ink: dark ? "#f6b24b" : "#9a6a12", border: dark ? "rgba(246,178,75,0.4)" : "rgba(180,120,20,0.4)" },
    posEnforce: { bg: "rgba(63,174,106,0.14)", ink: dark ? "#5fd398" : "#2e9c63", border: "rgba(63,174,106,0.45)" },
    calloutAmber: { bg: dark ? "rgba(246,178,75,0.08)" : "rgba(246,178,75,0.12)", border: dark ? "rgba(246,178,75,0.32)" : "rgba(200,140,30,0.4)", iconBg: dark ? "rgba(246,178,75,0.16)" : "rgba(246,178,75,0.25)", ink: dark ? "#f6b24b" : "#8a5e10", detail: dark ? "#cbb48c" : "#7a5e2e" },
    calloutGreen: { bg: dark ? "rgba(63,174,106,0.08)" : "rgba(63,174,106,0.10)", border: "rgba(63,174,106,0.34)", iconBg: "rgba(63,174,106,0.16)", ink: dark ? "#5fd398" : "#1f8a52", detail: dark ? "#a7cbb6" : "#3a6a4e" },
  };

  // sibling nav among the four runbooks
  const ids = Object.keys(window.CUCARACHA_RUNBOOKS);
  const pos = ids.indexOf(vmId);
  const prev = ids[(pos - 1 + ids.length) % ids.length];
  const next = ids[(pos + 1) % ids.length];
  const sib = (id) => { const r = window.getRunbook(id); return r ? r.title + " · " + r.os : ""; };

  const vscodeDisabled = rb.connect.kind === "vscode" && /\{\{/.test(rb.connect.vscodeUrl || "");
  const pc = rb.accent || (rb.posture === "enforce" ? "#1f9d57" : "#dd7a26"); // posture brand color (matches hub card)

  return (
    <div className="h-full w-full overflow-y-auto lr-scroll" style={{ background: th.page, fontFamily: "'Manrope', sans-serif" }}>
      <div className="pointer-events-none fixed inset-0">
        <div className="absolute -top-40 left-1/2 h-[520px] w-[860px] -translate-x-1/2 rounded-full" style={{ background: `radial-gradient(circle, ${th.glow1}, transparent 65%)` }} />
      </div>

      {/* top bar */}
      <header className="sticky top-0 z-20 border-b" style={{ borderColor: th.headerBorder, background: th.header, backdropFilter: "blur(14px)" }}>
        <div className="mx-auto flex max-w-[1440px] items-center justify-between px-6 py-3.5">
          <a href="#/hub" onClick={(e) => { if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return; e.preventDefault(); onBack(); }}
            className="inline-flex items-center gap-2 rounded-xl px-3 py-2 text-[13px] font-medium transition-colors" style={{ color: th.ink, background: th.chip, border: `1px solid ${th.cardBorder}` }}>
            <window.Icon name="ArrowLeft" size={15} /> Showroom
          </a>
          <div className="flex items-center gap-2.5">
            <span className="inline-flex items-center gap-1.5 text-[12px] font-semibold uppercase tracking-[0.16em]" style={{ color: th.faint, fontFamily: "'JetBrains Mono', monospace" }}>
              <window.Icon name={(rb.pillar && rb.pillar.icon) || "Bug"} size={14} /> {(rb.pillar && rb.pillar.label) || "La Cucaracha"}
            </span>
            <window.OpenInNewTab href={"#/cucaracha/" + vmId} size={14} className="h-8 w-8" title="Open this runbook in a new tab" style={{ color: th.faint, background: th.chip, border: `1px solid ${th.cardBorder}` }} />
          </div>
        </div>
      </header>

      <main className="relative z-10 mx-auto max-w-[1440px] px-6 pb-24 pt-10">
        <div className="grid items-start gap-7 lg:grid-cols-3">
          {/* ---- left identity rail (sticky) ---- */}
          <aside className="space-y-4 lg:sticky lg:top-24 a-fade-up">
            <div className="overflow-hidden rounded-3xl" style={{ background: th.card, border: `1px solid ${th.cardBorder}`, boxShadow: th.cardShadow }}>
              {/* posture-colored band */}
              <div className="relative h-24 w-full overflow-hidden" style={{ background: `linear-gradient(120deg, ${pc}, color-mix(in oklab, ${pc} 52%, #050508))` }}>
                <div className="absolute -right-5 -top-8" style={{ opacity: 0.22 }}><window.Icon name={rb.posture === "enforce" ? "ShieldCheck" : (rb.pillar ? "Skull" : "Bug")} size={120} style={{ color: "#fff" }} strokeWidth={1.1} /></div>
                <div className="absolute left-5 top-5 flex h-11 w-11 items-center justify-center rounded-2xl" style={{ background: "rgba(5,5,8,0.32)", color: "#fff", border: "1px solid rgba(255,255,255,0.22)" }}>
                  <window.Icon name={rb.osIcon} size={22} strokeWidth={2} />
                </div>
              </div>
              <div className="p-5">
                <div className="flex flex-wrap items-center gap-2">
                  <span className="inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[10.5px] font-semibold uppercase tracking-[0.14em]" style={{ background: th.chip, color: th.sub, fontFamily: "'JetBrains Mono', monospace" }}>
                    <window.Icon name={rb.osIcon} size={12} /> {rb.os}
                  </span>
                  <PostureBadge posture={rb.posture} th={th} />
                </div>
                <h1 style={{ fontFamily: "'Cormorant Garamond', serif", color: th.inkStrong }} className="mt-3 text-[34px] font-medium leading-none">{rb.title}</h1>
                <div className="mt-2.5 flex items-center gap-2 text-[12.5px]" style={{ color: th.faint }}>
                  <window.Icon name="Server" size={13} />
                  <span style={{ fontFamily: "'JetBrains Mono', monospace" }}>{rb.vm}</span>
                </div>
                <div className="mt-1 text-[12.5px]" style={{ color: th.faint }}>{rb.osLabel}</div>
                <p className="mt-3 text-[13px] leading-relaxed" style={{ color: th.ink }}><TbdText text={rb.whatIsIt} th={th} /></p>
              </div>
            </div>

          </aside>

          {/* ---- right sections card ---- */}
          <div className="space-y-9 rounded-3xl p-7 sm:p-10 lg:col-span-2 a-fade-up" style={{ background: th.card, border: `1px solid ${th.cardBorder}`, boxShadow: th.cardShadow, animationDelay: "60ms" }}>
          <Section n="1" icon="Info" title="What this is" th={th}>
            <p className="text-[15px] leading-relaxed" style={{ color: th.inkStrong }}><TbdText text={rb.whatIsIt} th={th} /></p>
          </Section>

          <div className="h-px w-full" style={{ background: th.cardBorder }} />

          <Section n="2" icon="Plug" title="Connect" th={th}>
            {rb.connect.kind === "cli" ? (
              <div className="space-y-3">
                <div className="inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-[11px] font-semibold" style={{ background: th.chip, color: th.sub, fontFamily: "'JetBrains Mono', monospace" }}>
                  <window.Icon name="Apple" size={12} /> {rb.connect.note}
                </div>
                {rb.connect.steps.map((s, i) => <CodeBlock key={i} code={s} th={th} />)}
                <p className="text-[13.5px] leading-relaxed" style={{ color: th.ink }}><TbdText text={rb.connect.after} th={th} /></p>
              </div>
            ) : (
              <div className="space-y-3">
                <div className="flex flex-wrap items-center gap-3">
                  <button
                    disabled={vscodeDisabled}
                    onClick={() => { if (!vscodeDisabled) window.open(rb.connect.vscodeUrl, "_blank", "noopener,noreferrer"); }}
                    title={vscodeDisabled ? "Enabled once the VS Code URL is provisioned" : "Open VS Code on the VM"}
                    className="inline-flex items-center gap-2 rounded-xl px-4 py-2.5 text-[13.5px] font-bold transition-all"
                    style={vscodeDisabled
                      ? { background: th.chip, color: th.sub, border: `1px dashed ${th.dashed}`, cursor: "not-allowed" }
                      : { background: th.accent, color: "#fff", border: "1px solid transparent" }}
                  >
                    <window.Icon name="Code2" size={16} /> Open Terminal <window.Icon name="ArrowUpRight" size={15} />
                  </button>
                  {vscodeDisabled && (
                    <span className="inline-flex items-center gap-1.5 text-[12px]" style={{ color: th.faint }}>
                      <window.Icon name="Lock" size={12} /> opens <TbdText text={rb.connect.vscodeUrl} th={th} /> in a new tab once provisioned
                    </span>
                  )}
                </div>
                <p className="text-[13.5px] leading-relaxed" style={{ color: th.ink }}><TbdText text={rb.connect.after} th={th} /></p>
              </div>
            )}
          </Section>

          <div className="h-px w-full" style={{ background: th.cardBorder }} />

          <Section n="3" icon="Swords" title="Run the attack" th={th}>
            <p className="text-[15px] leading-relaxed" style={{ color: th.inkStrong }}><TbdText text={rb.attack} th={th} /></p>
          </Section>

          <div className="h-px w-full" style={{ background: th.cardBorder }} />

          <Section n="4" icon="Eye" title="What you'll see" th={th}>
            <ResultCallout result={rb.result} th={th} />
          </Section>

          <div className="h-px w-full" style={{ background: th.cardBorder }} />

          <Section n="5" icon="MonitorCheck" title={rb.watchTitle || "Watch in Koi"} th={th}>
            <p className="text-[15px] leading-relaxed" style={{ color: th.inkStrong }}><TbdText text={rb.watch} th={th} /></p>
            {rb.health && (
              <div className="mt-5 space-y-3">
                <div className="inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-[11px] font-semibold" style={{ background: th.chip, color: th.sub, fontFamily: "'JetBrains Mono', monospace" }}>
                  <window.Icon name="Stethoscope" size={12} /> {rb.health.note}
                </div>
                {(rb.health.steps || []).map((s, i) => <CodeBlock key={i} code={s} th={th} />)}
                {rb.health.after && <p className="text-[13.5px] leading-relaxed" style={{ color: th.ink }}><TbdText text={rb.health.after} th={th} /></p>}
              </div>
            )}
          </Section>

          {rb.inspect && (<>
            <div className="h-px w-full" style={{ background: th.cardBorder }} />
            <Section n={String(secN.inspect)} icon="FileCode2" title="Inspect the agent" th={th}>
              <div className="space-y-3">
                <p className="text-[15px] leading-relaxed" style={{ color: th.inkStrong }}><TbdText text={rb.inspect.note} th={th} /></p>
                {(rb.inspect.steps || []).map((s, i) => <CodeBlock key={i} code={s} th={th} />)}
                {rb.inspect.after && <p className="text-[13.5px] leading-relaxed" style={{ color: th.ink }}><TbdText text={rb.inspect.after} th={th} /></p>}
              </div>
            </Section>
          </>)}

          {rb.runtime && (<>
            <div className="h-px w-full" style={{ background: th.cardBorder }} />
            <Section n={String(secN.runtime)} icon="Activity" title="Runtime hooks & agent activity" th={th}>
              <div className="space-y-3">
                <p className="text-[15px] leading-relaxed" style={{ color: th.inkStrong }}><TbdText text={rb.runtime.note} th={th} /></p>
                {(rb.runtime.steps || []).map((s, i) => <CodeBlock key={i} code={s} th={th} />)}
                {rb.runtime.after && <p className="text-[13.5px] leading-relaxed" style={{ color: th.ink }}><TbdText text={rb.runtime.after} th={th} /></p>}
              </div>
            </Section>
          </>)}

          {rb.activityDemo && (<>
            <div className="h-px w-full" style={{ background: th.cardBorder }} />
            <Section n={String(secN.activityDemo)} icon="Activity" title="Demo — generate agent activity" th={th}>
              <div className="space-y-3">
                <p className="text-[15px] leading-relaxed" style={{ color: th.inkStrong }}><TbdText text={rb.activityDemo.note} th={th} /></p>
                {(rb.activityDemo.steps || []).map((s, i) => <CodeBlock key={i} code={s} th={th} />)}
                {rb.activityDemo.after && <p className="text-[13.5px] leading-relaxed" style={{ color: th.ink }}><TbdText text={rb.activityDemo.after} th={th} /></p>}
              </div>
            </Section>
          </>)}

          {rb.troubleshoot && (<>
            <div className="h-px w-full" style={{ background: th.cardBorder }} />
            <Section n={String(secN.troubleshoot)} icon="Wrench" title="Troubleshooting" th={th}>
              <div className="space-y-3">
                <p className="text-[15px] leading-relaxed" style={{ color: th.inkStrong }}><TbdText text={rb.troubleshoot.note} th={th} /></p>
                {(rb.troubleshoot.steps || []).map((s, i) => <CodeBlock key={i} code={s} th={th} />)}
                {rb.troubleshoot.after && <p className="text-[13.5px] leading-relaxed" style={{ color: th.ink }}><TbdText text={rb.troubleshoot.after} th={th} /></p>}
              </div>
            </Section>
          </>)}

          {rb.reset && (<>
            <div className="h-px w-full" style={{ background: th.cardBorder }} />
            <Section n={String(secN.reset)} icon="RotateCcw" title="Reset for the next PoC" th={th}>
              <div className="space-y-3">
                <p className="text-[15px] leading-relaxed" style={{ color: th.inkStrong }}><TbdText text={rb.reset.note} th={th} /></p>
                {(rb.reset.steps || []).map((s, i) => <CodeBlock key={i} code={s} th={th} />)}
                {rb.reset.after && <p className="text-[13.5px] leading-relaxed" style={{ color: th.ink }}><TbdText text={rb.reset.after} th={th} /></p>}
              </div>
            </Section>
          </>)}
          </div>
        </div>
      </main>
    </div>
  );
}

window.CucarachaRunbook = CucarachaRunbook;
