/* chiquitito.jsx — "Chiquitito": AIRS on low-code (n8n).
   A tidy, read-only ONE-PAGER (route #/chiquitito, constant key="chiquitito").

   The action lives in n8n now, not the hub. You don't need to be a developer to
   secure AI: if you can drag a node onto a canvas, you can put Prisma AIRS in
   front of your automation. This page explains the wired-up lead-enrichment
   workflow, shows the static flow as illustration, tells you how to drive it,
   and hands off to the real editor via one primary "Open in n8n" button.

   The button is login-gated by n8n itself (it opens the live editor, which needs
   a sign-in) — a presenter gateway, not an anonymous playground. With no overlay
   wired (chiqEditorUrl() === null) the button renders DISABLED, never a fake URL,
   so the export stays self-contained. Cinnamon / sugar-amber bakery theme; the
   three AIRS touches run hotter red. */

/* ---- cinnamon / sugar-amber palette ---- */
const CH = {
  mono: "'JetBrains Mono', ui-monospace, monospace",
  sans: "'Manrope', system-ui, sans-serif",
  serif: "'Spectral', serif",
  page: "#f3e7d3",
  surface: "#fffdf8",
  surfaceAlt: "#faf1e1",
  raised: "#f4e7d1",
  line: "rgba(122,84,52,0.16)",
  lineSoft: "rgba(122,84,52,0.09)",
  ink: "#3a2517",
  sub: "#7a5a3f",
  faint: "#a98a6c",
  cinnamon: "#c4452a",
  cinnamonInk: "#fff4ef",
  cinnamonSoft: "rgba(196,69,42,0.10)",
  amber: "#d2851f",
  amberInk: "#3a2410",
  amberSoft: "rgba(210,133,31,0.14)",
  green: "#2f9e5f",
  greenSoft: "rgba(47,158,95,0.13)",
  greenBorder: "rgba(47,158,95,0.45)",
  redSoft: "rgba(196,69,42,0.10)",
  redBorder: "rgba(196,69,42,0.45)",
  ambient: "radial-gradient(900px 380px at 50% -10%, rgba(210,133,31,0.18), transparent 70%), radial-gradient(720px 320px at 92% 112%, rgba(196,69,42,0.12), transparent 70%)",
};

/* ---- read-only node graph (static flow strip) ---- */
function FlowNode({ n }) {
  const airs = n.kind === "airs";
  const tileBg = airs ? CH.cinnamon : n.kind === "model" ? "#fff" : CH.raised;
  const tileFg = airs ? CH.cinnamonInk : CH.sub;
  return (
    <div
      className="flex min-w-0 flex-1 items-center gap-2 rounded-2xl px-2.5 py-2.5"
      style={{
        background: airs ? CH.cinnamonSoft : CH.surface,
        border: `1px solid ${airs ? "rgba(196,69,42,0.4)" : CH.line}`,
        boxShadow: airs ? "0 6px 18px -12px rgba(196,69,42,0.5)" : "none",
      }}
    >
      <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-xl" style={{ background: tileBg, color: tileFg, border: n.kind === "model" ? `1px solid ${CH.line}` : "none" }}>
        {n.logo ? <img src={n.logo} alt="" className="h-4 w-4 object-contain" /> : <window.Icon name={n.icon} size={16} />}
      </span>
      <div className="min-w-0 leading-tight">
        <div className="flex items-center gap-1 truncate text-[11.5px] font-bold" style={{ color: airs ? CH.cinnamon : CH.ink }}>
          {airs && <span aria-hidden="true">🛡</span>}{n.label}
        </div>
        <div className="truncate text-[9.5px] font-semibold uppercase tracking-[0.1em]" style={{ color: CH.faint, fontFamily: CH.mono }}>{n.sub}</div>
      </div>
    </div>
  );
}

function FlowStrip() {
  const flow = window.CHIQ_FLOW || [];
  return (
    <div className="flex items-stretch gap-1.5">
      {flow.map((n, i) => (
        <React.Fragment key={n.id}>
          <FlowNode n={n} />
          {i < flow.length - 1 && (
            <window.Icon name="ArrowRight" size={14} style={{ color: CH.faint, flexShrink: 0, alignSelf: "center" }} />
          )}
        </React.Fragment>
      ))}
    </div>
  );
}

/* ---- AIRS verdict chip ---- */
function AirsChip({ tone, children }) {
  const map = {
    allow: { c: CH.green, bg: CH.greenSoft, b: CH.greenBorder, icon: "ShieldCheck" },
    block: { c: CH.cinnamon, bg: CH.redSoft, b: CH.redBorder, icon: "ShieldX" },
    flag: { c: CH.amber, bg: CH.amberSoft, b: "rgba(210,133,31,0.45)", icon: "ShieldAlert" },
  };
  const m = map[tone] || map.allow;
  return (
    <span className="inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[11px] font-bold" style={{ background: m.bg, color: m.c, border: `1px solid ${m.b}`, fontFamily: CH.mono }}>
      <window.Icon name={m.icon} size={12} /> {children}
    </span>
  );
}

/* ---- copy-to-clipboard button ---- */
function CopyButton({ text, label = "Copy", className = "", style }) {
  const [done, setDone] = React.useState(false);
  function copy() {
    try {
      navigator.clipboard.writeText(text);
      setDone(true);
      setTimeout(() => setDone(false), 1400);
    } catch (e) {}
  }
  return (
    <button onClick={copy} className={"inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[11.5px] font-bold transition-all active:scale-[0.97] " + className} style={style}>
      <window.Icon name={done ? "Check" : "Copy"} size={13} /> {done ? "Copied" : label}
    </button>
  );
}

/* ---- section heading rule ---- */
function SectionLabel({ children }) {
  return (
    <div className="mb-3 flex items-center gap-2.5 text-[11px] font-bold uppercase tracking-[0.18em]" style={{ color: CH.faint, fontFamily: CH.mono }}>
      <span className="inline-block h-px w-7" style={{ background: CH.line }} /> {children}
    </div>
  );
}

/* ---- "What this is" prose card ---- */
function WhatThisIs() {
  return (
    <div className="rounded-2xl px-5 py-5" style={{ background: CH.surface, border: `1px solid ${CH.line}` }}>
      <p className="text-[15px] leading-relaxed" style={{ color: CH.ink }}>
        A teammate built a <span className="font-semibold">lead-enrichment automation in N8N</span> — a web form comes in, an AI tidies it up and drafts outreach, the record lands in the CRM. To secure it, they dropped in the <span className="font-semibold" style={{ color: CH.cinnamon }}>official Prisma AIRS node three times</span> (Prompt Scan · Mask Data · Response Scan).
      </p>
      <p className="mt-2.5 text-[15px] leading-relaxed" style={{ color: CH.ink }}>
        The drafting model is <span className="font-semibold">Amazon Nova on Bedrock</span>. There's <span className="font-semibold">no code and no SDK</span> on the canvas — and no API keys to wrangle here; AIRS authenticates from inside the node.
      </p>
    </div>
  );
}

/* ---- the three AIRS touches (same node, three operations) ---- */
function AirsTouches() {
  const ops = window.CHIQ_AIRS_OPS || [];
  return (
    <div className="grid grid-cols-1 gap-2.5 sm:grid-cols-3">
      {ops.map((o) => (
        <div key={o.op} className="rounded-xl px-3.5 py-3.5" style={{ background: CH.cinnamonSoft, border: `1px solid rgba(196,69,42,0.28)` }}>
          <div className="flex items-center gap-2 text-[12.5px] font-bold" style={{ color: CH.cinnamon }}>
            <window.Icon name={o.icon} size={14} /> {o.op}
          </div>
          <p className="mt-1.5 text-[12px] leading-relaxed" style={{ color: CH.sub }}>{o.note}</p>
        </div>
      ))}
    </div>
  );
}

/* ---- "How to use it" — 4 numbered steps ---- */
const CHIQ_STEPS = [
  { t: "Open the workflow", d: "Hit “Open in N8N” below and sign in — the canvas shows the lead-intake flow with the three AIRS nodes already wired in." },
  { t: "Send a lead", d: "Click the Webhook trigger and run it, then drop in one of the three preset leads below (or POST the curl snippet)." },
  { t: "Watch AIRS work", d: "The Prisma AIRS nodes fire in order — Prompt Scan → Mask Data → Response Scan — with nothing but nodes on the canvas." },
  { t: "Read the result", d: "A clean lead lands enriched at the CRM node; PII is masked first; an injection attempt is blocked before Nova is ever called." },
];

function HowToUse() {
  return (
    <ol className="grid grid-cols-1 gap-2.5 sm:grid-cols-2">
      {CHIQ_STEPS.map((s, i) => (
        <li key={i} className="flex items-start gap-3.5 rounded-2xl px-4 py-3.5" style={{ background: CH.surface, border: `1px solid ${CH.line}` }}>
          <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-[13px] font-extrabold" style={{ background: CH.cinnamon, color: CH.cinnamonInk, fontFamily: CH.mono }}>{i + 1}</span>
          <div className="min-w-0 pt-0.5">
            <div className="text-[14px] font-bold" style={{ color: CH.ink }}>{s.t}</div>
            <p className="mt-0.5 text-[13px] leading-relaxed" style={{ color: CH.sub }}>{s.d}</p>
          </div>
        </li>
      ))}
    </ol>
  );
}

/* ---- preset leads (illustrative; each shows its expected AIRS verdict) ---- */
const CHIQ_PRESET_OUTCOME = {
  record: { tone: "allow", label: "Flows through · enriched" },
  masked: { tone: "flag", label: "PII masked · still saved" },
  rejected: { tone: "block", label: "Blocked at Prompt Scan" },
};

function PresetCard({ p, onRun, running, active }) {
  const out = CHIQ_PRESET_OUTCOME[p.expect] || CHIQ_PRESET_OUTCOME.record;
  const accent = p.expect === "rejected" ? CH.cinnamon : p.expect === "masked" ? CH.amber : CH.green;
  return (
    <div className="flex flex-col rounded-2xl px-4 py-4" style={{ background: CH.surface, border: `1px solid ${CH.line}` }}>
      <div className="flex items-center justify-between gap-2">
        <span className="inline-flex items-center gap-1.5 text-[13px] font-bold" style={{ color: accent }}>
          <window.Icon name={p.icon} size={14} /> {p.label}
        </span>
      </div>
      <p className="mt-2.5 flex-1 rounded-xl px-3 py-2.5 text-[12px] leading-relaxed" style={{ background: CH.raised, color: CH.ink, fontFamily: CH.mono, border: `1px solid ${CH.lineSoft}` }}>
        {p.message}
      </p>
      <div className="mt-3 flex items-center justify-between gap-2">
        <AirsChip tone={out.tone}>{out.label}</AirsChip>
        <button
          onClick={() => onRun(p)}
          disabled={running}
          className="inline-flex shrink-0 items-center gap-1.5 rounded-lg px-3 py-1.5 text-[12px] font-bold transition-all active:scale-[0.97] disabled:opacity-60"
          style={{ background: accent, color: "#fff", cursor: running ? "default" : "pointer" }}
        >
          {active && running ? (
            <window.Icon name="Loader2" size={13} className="animate-spin" />
          ) : (
            <>Run <window.Icon name="ArrowRight" size={13} /></>
          )}
        </button>
      </div>
    </div>
  );
}

/* ---- one labelled input/textarea for the free-form lead ---- */
function LeadInput({ label, value, onChange, placeholder, textarea }) {
  const [focus, setFocus] = React.useState(false);
  const common = {
    value, onChange, placeholder,
    onFocus: () => setFocus(true), onBlur: () => setFocus(false),
    className: "mt-1 w-full rounded-xl px-3 py-2 text-[13px] outline-none transition-colors",
    style: { background: CH.raised, color: CH.ink, border: `1px solid ${focus ? CH.cinnamon : CH.line}`, fontFamily: CH.sans },
  };
  return (
    <label className="block">
      <span className="text-[10px] font-bold uppercase tracking-[0.14em]" style={{ color: CH.faint, fontFamily: CH.mono }}>{label}</span>
      {textarea ? <textarea rows={2} {...common} /> : <input {...common} />}
    </label>
  );
}

/* ---- one key/value row in the enriched CRM record ---- */
function ResultKV({ label, value, mono, full }) {
  return (
    <div className={full ? "sm:col-span-2" : ""}>
      <div className="text-[10px] font-bold uppercase tracking-[0.14em]" style={{ color: CH.faint, fontFamily: CH.mono }}>{label}</div>
      <div className="mt-1 text-[13px] leading-relaxed" style={{ color: CH.ink, fontFamily: mono ? CH.mono : CH.sans, wordBreak: mono ? "break-word" : "normal" }}>{value || "—"}</div>
    </div>
  );
}

/* ---- the single result panel below the testers ---- */
function ResultPanel({ running, result, error }) {
  if (running) {
    return (
      <div className="flex items-center gap-3 rounded-2xl px-5 py-4" style={{ background: CH.surface, border: `1px solid ${CH.line}` }}>
        <window.Icon name="Loader2" size={18} className="animate-spin" style={{ color: CH.cinnamon }} />
        <span className="text-[13px] font-semibold" style={{ color: CH.sub }}>Running through the workflow — Prompt Scan → Mask Data → Nova → Response Scan…</span>
      </div>
    );
  }
  if (error) {
    return (
      <div className="flex items-start gap-2.5 rounded-2xl px-4 py-3.5 text-[12.5px] leading-relaxed" style={{ background: CH.amberSoft, color: CH.sub, border: `1px solid rgba(210,133,31,0.4)` }}>
        <window.Icon name="WifiOff" size={16} style={{ color: CH.amber, flexShrink: 0, marginTop: 1 }} /> {error}
      </div>
    );
  }
  if (!result) {
    return (
      <div className="rounded-2xl border border-dashed px-5 py-4 text-[12.5px] leading-relaxed" style={{ borderColor: CH.line, color: CH.faint, background: CH.surfaceAlt }}>
        Run a preset or submit a lead above — the enriched CRM record (or the AIRS block) lands here.
      </div>
    );
  }
  if (result.rejected) {
    return (
      <div className="rounded-2xl px-5 py-5" style={{ background: CH.redSoft, border: `1px solid ${CH.redBorder}` }}>
        <div className="flex flex-wrap items-center gap-2.5">
          <span className="text-[15px] font-extrabold" style={{ color: CH.cinnamon }}>🚫 Lead rejected</span>
          <AirsChip tone="block">AIRS: block · prompt</AirsChip>
        </div>
        <p className="mt-2.5 text-[13.5px] leading-relaxed" style={{ color: CH.ink }}>Prisma AIRS blocked it before enrichment. <span className="font-semibold">The model was never called.</span></p>
        {result.reason && <p className="mt-1.5 text-[12.5px] leading-relaxed" style={{ color: CH.sub }}>{result.reason}</p>}
      </div>
    );
  }
  if (result.withheld) {
    return (
      <div className="rounded-2xl px-5 py-5" style={{ background: CH.amberSoft, border: `1px solid rgba(210,133,31,0.45)` }}>
        <div className="flex flex-wrap items-center gap-2.5">
          <span className="text-[15px] font-extrabold" style={{ color: CH.amber }}>⚠️ Enrichment withheld</span>
          <AirsChip tone="block">AIRS: block · response</AirsChip>
        </div>
        <p className="mt-2.5 text-[13.5px] leading-relaxed" style={{ color: CH.ink }}>AIRS flagged the model output before it could be written to the CRM.</p>
        {result.reason && <p className="mt-1.5 text-[12.5px] leading-relaxed" style={{ color: CH.sub }}>{result.reason}</p>}
      </div>
    );
  }
  const r = result.record || {};
  const a = result.airs || {};
  return (
    <div className="rounded-2xl px-5 py-5" style={{ background: CH.surface, border: `1px solid ${CH.greenBorder}` }}>
      <div className="flex flex-wrap items-center gap-2.5">
        <span className="text-[15px] font-extrabold" style={{ color: CH.ink }}>✍️ Ready for your CRM</span>
        <AirsChip tone="allow">AIRS: allow · prompt + mask + response</AirsChip>
        {a.maskApplied && (
          <span className="inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-[11px] font-bold" style={{ background: CH.amberSoft, color: CH.amber, border: `1px solid rgba(210,133,31,0.45)`, fontFamily: CH.mono }}>🛡 PII masked</span>
        )}
      </div>
      <div className="mt-4 grid grid-cols-1 gap-3.5 sm:grid-cols-2">
        <ResultKV label="Name" value={r.name} />
        <ResultKV label="Company" value={r.company} />
        <ResultKV label="Message (as stored)" value={r.maskedMessage} mono full />
        <ResultKV label="Summary" value={r.summary} full />
        <ResultKV label="Suggested outreach" value={r.suggestedOutreach} full />
        <ResultKV label="Segment" value={r.segment} />
      </div>
    </div>
  );
}

/* ---- the LIVE tester — free-form form + runnable presets + result panel ---- */
function LiveTester() {
  const presets = window.CHIQ_PRESETS || [];
  const [form, setForm] = React.useState({ name: "", company: "", message: "" });
  const [running, setRunning] = React.useState(false);
  const [result, setResult] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [ranKey, setRanKey] = React.useState(null);

  async function run(lead, key) {
    setRunning(true); setError(null); setResult(null); setRanKey(key);
    try {
      const out = await window.sendChiquitito(lead);
      setResult(out);
    } catch (e) {
      setError("Couldn't reach the live workflow. Wire chiquitito.webhookUrl to run against n8n — or try a preset to see the mock result.");
    } finally {
      setRunning(false);
    }
  }

  const canSubmit = (form.message || "").trim().length > 0 && !running;
  const set = (k) => (e) => { const v = e.target.value; setForm((f) => ({ ...f, [k]: v })); };

  return (
    <div>
      <SectionLabel>Try it live · run a lead through the workflow</SectionLabel>
      <form
        onSubmit={(e) => { e.preventDefault(); if (canSubmit) run({ name: form.name, company: form.company, message: form.message }, "form"); }}
        className="rounded-2xl px-4 py-4"
        style={{ background: CH.surface, border: `1px solid ${CH.line}` }}
      >
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
          <LeadInput label="Name" value={form.name} onChange={set("name")} placeholder="Jane Smith" />
          <LeadInput label="Company" value={form.company} onChange={set("company")} placeholder="Globex" />
        </div>
        <div className="mt-3">
          <LeadInput label="Message" value={form.message} onChange={set("message")} placeholder="What does the lead want? (try pasting a phone number or card to watch AIRS mask it)" textarea />
        </div>
        <div className="mt-3 flex flex-wrap items-center justify-between gap-2">
          <span className="text-[11.5px] leading-relaxed" style={{ color: CH.faint }}>AIRS scans every submission — prompt, mask, response.</span>
          <button
            type="submit"
            disabled={!canSubmit}
            className="inline-flex items-center gap-1.5 rounded-xl px-4 py-2 text-[13px] font-bold transition-all active:scale-[0.98]"
            style={{ background: canSubmit ? CH.cinnamon : CH.raised, color: canSubmit ? CH.cinnamonInk : CH.faint, cursor: canSubmit ? "pointer" : "not-allowed" }}
          >
            Submit lead <window.Icon name="ArrowRight" size={15} />
          </button>
        </div>
      </form>

      <div className="mb-2.5 mt-4 text-[11px] font-bold uppercase tracking-[0.16em]" style={{ color: CH.faint, fontFamily: CH.mono }}>Or run a preset lead</div>
      <div className="grid grid-cols-1 gap-3 md:grid-cols-3">
        {presets.map((p) => (
          <PresetCard
            key={p.key}
            p={p}
            running={running}
            active={ranKey === p.key}
            onRun={(pp) => run({ name: pp.name, company: pp.company, message: pp.message }, pp.key)}
          />
        ))}
      </div>

      <div className="mt-4"><ResultPanel running={running} result={result} error={error} /></div>
    </div>
  );
}

/* ---- collapsible, copy-able curl snippet ---- */
function curlFor(webhookUrl, preset) {
  const host = webhookUrl || "https://your-n8n.example/webhook/lead-intake";
  const body = JSON.stringify({ name: preset.name, company: preset.company, message: preset.message });
  return `curl -X POST ${host} \\\n  -H "Content-Type: application/json" \\\n  -d '${body}'`;
}

function CurlBlock() {
  const [open, setOpen] = React.useState(false);
  const presets = window.CHIQ_PRESETS || [];
  const webhookUrl = window.chiqWebhookUrl ? window.chiqWebhookUrl() : null;
  const [pick, setPick] = React.useState(presets[0] ? presets[0].key : "clean");
  const preset = presets.find((p) => p.key === pick) || presets[0] || { name: "", company: "", message: "" };
  const snippet = curlFor(webhookUrl, preset);

  return (
    <div className="overflow-hidden rounded-2xl" style={{ border: `1px solid ${CH.line}`, background: CH.surface }}>
      <button onClick={() => setOpen((o) => !o)} className="flex w-full items-center gap-2 px-4 py-3 text-left text-[13px] font-semibold" style={{ color: CH.ink }}>
        <window.Icon name={open ? "ChevronDown" : "ChevronRight"} size={16} style={{ color: CH.amber }} />
        Prefer the terminal? Copy the curl
        <span className="ml-auto text-[11px] font-medium" style={{ color: CH.faint, fontFamily: CH.mono }}>POST · webhook</span>
      </button>
      {open && (
        <div className="border-t px-4 py-4" style={{ borderColor: CH.lineSoft }}>
          <div className="mb-3 flex flex-wrap items-center gap-2">
            <span className="text-[10px] font-bold uppercase tracking-[0.16em]" style={{ color: CH.faint, fontFamily: CH.mono }}>Lead</span>
            <div className="inline-flex rounded-full p-0.5" style={{ background: CH.surfaceAlt, border: `1px solid ${CH.line}` }}>
              {presets.map((p) => {
                const on = pick === p.key;
                return (
                  <button key={p.key} onClick={() => setPick(p.key)} className="rounded-full px-3 py-1 text-[11.5px] font-bold transition-all" style={{ background: on ? CH.cinnamon : "transparent", color: on ? CH.cinnamonInk : CH.sub }}>
                    {p.label}
                  </button>
                );
              })}
            </div>
          </div>
          <div className="relative overflow-hidden rounded-xl" style={{ background: "#2a1a10", border: `1px solid ${CH.line}` }}>
            <div className="absolute right-2 top-2">
              <CopyButton text={snippet} style={{ background: "rgba(255,255,255,0.08)", color: "#f3e7d3" }} />
            </div>
            <pre className="lr-scroll overflow-x-auto px-4 py-3.5 text-[12px] leading-relaxed" style={{ color: "#f7ede0", fontFamily: CH.mono, whiteSpace: "pre" }}>{snippet}</pre>
          </div>
          {!webhookUrl && (
            <p className="mt-2 text-[11px] leading-relaxed" style={{ color: CH.faint }}>
              The host above is a placeholder — wire <span style={{ fontFamily: CH.mono }}>chiquitito.webhookUrl</span> in the release overlay to fill in the live test webhook.
            </p>
          )}
        </div>
      )}
    </div>
  );
}

/* ---- the PRIMARY CTA — "Open in n8n" (login-gated by n8n itself) ---- */
function OpenInN8n() {
  const url = (window.chiqEditorUrl && window.chiqEditorUrl()) || "https://n8n.io";
  const live = !!url;
  return (
    <div className="rounded-2xl px-6 py-6" style={{ background: live ? CH.cinnamonSoft : CH.surfaceAlt, border: `1px solid ${live ? "rgba(196,69,42,0.4)" : CH.line}` }}>
      <div className="text-[17px] font-extrabold" style={{ color: CH.ink, fontFamily: CH.sans }}>Drive it yourself</div>
      <p className="mt-1 text-[13px] leading-relaxed" style={{ color: CH.sub }}>
        The button opens the <span className="font-semibold">live N8N editor</span>, which asks you to sign in — so it's a presenter gateway, not an anonymous playground.
      </p>
      <div className="mt-4">
        {live ? (
          <a href={url} target="_blank" rel="noopener noreferrer"
            className="flex w-full items-center justify-center gap-2.5 rounded-xl px-5 py-3.5 text-[15px] font-bold transition-all hover:-translate-y-0.5 active:scale-[0.99]"
            style={{ background: CH.cinnamon, color: CH.cinnamonInk, boxShadow: "0 14px 32px -16px rgba(196,69,42,0.7)" }}>
            <img src="images/n8n-color.svg" alt="" className="h-5 w-auto" style={{ filter: "brightness(0) invert(1)" }} />
            Open in N8N <window.Icon name="ArrowUpRight" size={18} />
          </a>
        ) : (
          <div className="flex w-full cursor-not-allowed items-center justify-center gap-2.5 rounded-xl px-5 py-3.5 text-[15px] font-bold opacity-55" style={{ background: CH.raised, color: CH.sub, border: `1px solid ${CH.line}` }} aria-disabled="true" title="No editor URL wired — running as the self-contained demo">
            <window.Icon name="Lock" size={17} /> Open in N8N
          </div>
        )}
      </div>
      {!live && (
        <p className="mt-3 text-[11.5px] leading-relaxed" style={{ color: CH.faint }}>
          No editor wired — this export runs as the self-contained demo. Set <span style={{ fontFamily: CH.mono }}>chiquitito.editorUrl</span> in the release overlay to light the button up.
        </p>
      )}
    </div>
  );
}

/* ---- one tab in the Demo A / Demo B switcher ---- */
function ChiqTab({ href, active, children }) {
  return (
    <a
      href={href}
      className="inline-flex items-center gap-1.5 rounded-xl px-3 py-1.5 text-[12.5px] font-bold transition-all"
      style={active ? { background: CH.cinnamon, color: CH.cinnamonInk } : { color: CH.sub, background: "transparent" }}
    >
      {children}
    </a>
  );
}

/* ============================================================ */
function Chiquitito({ screen, navigate, onBack }) {
  const active = screen === "itops" ? "itops" : "demo";
  const tabHref = active === "itops" ? "#/chiquitito/itops" : "#/chiquitito";
  return (
    <div className="relative flex h-full w-full flex-col overflow-hidden a-fade" style={{ background: CH.page, fontFamily: CH.sans }} data-screen-label="Chiquitito">
      <div className="pointer-events-none absolute inset-0" style={{ background: CH.ambient }} />

      {/* presenter toolbar */}
      <div className="relative z-10 flex h-12 shrink-0 items-center justify-between px-4" style={{ background: "rgba(243,231,211,0.84)", backdropFilter: "blur(14px)", borderBottom: `1px solid ${CH.line}` }}>
        <button onClick={onBack} className="inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[13px] font-medium" style={{ color: CH.sub }}>
          <window.Icon name="ArrowLeft" size={16} /> Back to hub
        </button>
        <div className="flex items-center gap-2">
          <window.RoseMark size={18} color={CH.cinnamon} petals={6} />
          <span className="hidden text-[12px] sm:inline" style={{ color: CH.faint }}>Last Rose · <span style={{ color: CH.sub }}>Chiquitito</span></span>
          <window.OpenInNewTab href={tabHref} size={13} className="h-7 w-7" title="Open Chiquitito in new tab" style={{ color: CH.sub, background: CH.surface, border: `1px solid ${CH.line}` }} />
        </div>
        <div className="flex items-center gap-2">
          <img src="images/n8n-color.svg" alt="N8N" className="h-4 w-auto" />
          <span className="inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[12.5px] font-semibold" style={{ background: CH.cinnamonSoft, color: CH.cinnamon, border: `1px solid rgba(196,69,42,0.3)` }}>
            <window.Icon name="Zap" size={14} /> Low-code
          </span>
        </div>
      </div>

      {/* demo switcher tabs */}
      <div className="relative z-10 flex shrink-0 items-center gap-1.5 px-4 py-2" style={{ background: "rgba(243,231,211,0.7)", borderBottom: `1px solid ${CH.line}` }}>
        <ChiqTab href="#/chiquitito" active={active === "demo"}>
          <img src="images/n8n-color.svg" alt="" className="h-3.5 w-auto" /> Demo A · Node on canvas
        </ChiqTab>
        <ChiqTab href="#/chiquitito/itops" active={active === "itops"}>
          <img src="images/truefoundry-color.png" alt="" className="h-3.5 w-auto" /> Demo B · IT-Ops gateway
        </ChiqTab>
      </div>

      {/* body — both screens stay mounted; toggled by visibility so typed text survives a flip */}
      <div className="lr-scroll relative z-10 flex-1 overflow-y-auto">
        <div style={{ display: active === "demo" ? "block" : "none" }}>
        <div className="mx-auto max-w-[1360px] px-6 py-8 sm:px-9">
          {/* header — full width */}
          <div className="a-fade-up">
            <div className="flex items-center gap-3">
              <img src="images/chiquitito-nodes.png" alt="" aria-hidden="true" style={{ width: 38, height: 38 }} className="object-contain" />
              <h1 style={{ fontFamily: CH.serif, color: CH.ink }} className="text-[34px] font-medium leading-none">Chiquitito</h1>
              <span className="text-[13px]" style={{ color: CH.faint, fontFamily: CH.mono }}>· AIRS on low-code (N8N)</span>
            </div>
            <p className="mt-3 max-w-4xl text-[15.5px] leading-relaxed" style={{ color: CH.ink }}>
              If you can drag a node onto a canvas, you can put Prisma AIRS in front of your automation — <span className="font-semibold" style={{ color: CH.cinnamon }}>no code, no SDK</span>.
            </p>
            <p className="mt-1.5 max-w-2xl text-[12.5px] leading-relaxed" style={{ color: CH.faint }}>
              <span className="font-semibold" style={{ color: CH.sub }}>What's N8N?</span> A low-code tool where you wire "nodes" together on a canvas — each does one step.
            </p>
          </div>

          {/* full-width flow strip illustration */}
          <div className="mt-8">
            <SectionLabel>The flow · new lead → enrich → (masked) into the CRM</SectionLabel>
            <div className="rounded-2xl px-5 py-6" style={{ background: CH.surface, border: `1px solid ${CH.line}` }}>
              <FlowStrip />
              <p className="mt-4 text-[12.5px] leading-relaxed" style={{ color: CH.sub }}>
                Read left to right. The three red nodes are all the <span className="font-semibold" style={{ color: CH.cinnamon }}>same official Prisma AIRS node</span>, each set to a different operation:
              </p>
              <div className="mt-3.5"><AirsTouches /></div>
            </div>
          </div>

          {/* two-column body: sticky narrative + action rail on the left, the details on the right */}
          <div className="mt-8 grid grid-cols-1 gap-8 lg:grid-cols-[minmax(0,400px)_minmax(0,1fr)]" style={{ alignItems: "start" }}>
            {/* LEFT RAIL */}
            <div className="min-w-0 space-y-6 lg:sticky lg:top-0">
              <WhatThisIs />
              <OpenInN8n />
              <p className="text-[11.5px] leading-relaxed" style={{ color: CH.faint }}>
                AIRS runs as the official N8N node (Prompt Scan · Mask Data · Response Scan) and the drafting model is Amazon Nova on Bedrock. This page is read-only — the live run happens inside n8n once you open the editor and sign in. Verdicts shown on the preset cards are the expected outcomes, not live calls. No keys are exposed here.
              </p>
            </div>

            {/* RIGHT — how-to + live tester */}
            <div className="min-w-0 space-y-9">
              <div>
                <SectionLabel>How to use it</SectionLabel>
                <HowToUse />
              </div>
              <div>
                <LiveTester />
                <div className="mt-4"><CurlBlock /></div>
              </div>
            </div>
          </div>
        </div>
        </div>
        <div style={{ display: active === "itops" ? "block" : "none" }}>{window.ChiquititoItops ? <window.ChiquititoItops /> : null}</div>
      </div>
    </div>
  );
}

window.Chiquitito = Chiquitito;
// shared with chiquitito-itops.jsx (separate babel script — needs these on window)
window.CHIQ_CH = CH;
window.ChiqAirsChip = AirsChip;
window.ChiqSectionLabel = SectionLabel;
window.ChiqCopyButton = CopyButton;
