/* chiquitito-itops.jsx — Demo B: IT-Ops helpdesk · AIRS in the TrueFoundry GATEWAY.
   A PREVIEW screen (route #/chiquitito/itops) that mirrors Demo A's structure but
   contrasts WHERE the guardrail lives: Demo A drops AIRS nodes on the n8n canvas;
   here AIRS runs as a guardrail INSIDE the TrueFoundry gateway, so every model call
   an IT-Ops/helpdesk agent makes is scanned centrally and a builder can't bypass it.

   MOCK-ONLY for now — the TrueFoundry integration isn't live yet. All verdicts come
   from window.sendChiquititoItops (mock by default; wires to
   LASTROSE_BACKENDS.chiquitito.itopsWebhookUrl once Demo B is built).

   Renders a BODY (placed inside the shared Chiquitito shell's scroll container).
   Reuses the cinnamon palette + helpers exported by chiquitito.jsx on window. */

const ICH = window.CHIQ_CH;
const ItopsAirsChip = window.ChiqAirsChip;
const ItopsSectionLabel = window.ChiqSectionLabel;

/* ---- one box in the read-only gateway diagram ---- */
function ItopsDiagBox({ label, sub, icon, logo, hot }) {
  return (
    <div
      className="flex min-w-0 flex-1 items-center gap-2.5 rounded-2xl px-3.5 py-3"
      style={{
        background: hot ? ICH.cinnamonSoft : ICH.surface,
        border: `1px solid ${hot ? "rgba(196,69,42,0.45)" : ICH.line}`,
        boxShadow: hot ? "0 8px 22px -12px rgba(196,69,42,0.55)" : "none",
      }}
    >
      <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl" style={{ background: hot ? ICH.cinnamon : ICH.raised, color: hot ? ICH.cinnamonInk : ICH.sub }}>
        {logo ? <img src={logo} alt="" className="h-5 w-5 object-contain" /> : <window.Icon name={icon} size={18} />}
      </span>
      <div className="min-w-0 leading-tight">
        <div className="flex items-center gap-1 text-[12.5px] font-bold" style={{ color: hot ? ICH.cinnamon : ICH.ink }}>
          {hot && <span aria-hidden="true">🛡</span>}{label}
        </div>
        <div className="truncate text-[9.5px] font-semibold uppercase tracking-[0.1em]" style={{ color: ICH.faint, fontFamily: ICH.mono }}>{sub}</div>
      </div>
    </div>
  );
}

function ItopsDiagram() {
  const Arrow = () => <window.Icon name="ArrowRight" size={15} style={{ color: ICH.faint, flexShrink: 0, alignSelf: "center" }} />;
  return (
    <div className="flex items-stretch gap-2">
      <ItopsDiagBox label="Helpdesk agent" sub="IT-Ops assistant" icon="LifeBuoy" />
      <Arrow />
      <ItopsDiagBox label="TrueFoundry gateway · AIRS" sub="guardrail runs inside" icon="ShieldCheck" hot />
      <Arrow />
      <ItopsDiagBox label="Mistral" sub="LLM" logo="images/mistral-color.svg" />
    </div>
  );
}

/* ---- labelled request input ---- */
function ItopsInput({ value, onChange, placeholder }) {
  const [focus, setFocus] = React.useState(false);
  return (
    <label className="block">
      <span className="text-[10px] font-bold uppercase tracking-[0.14em]" style={{ color: ICH.faint, fontFamily: ICH.mono }}>Request to the helpdesk agent</span>
      <textarea
        rows={2}
        value={value}
        onChange={onChange}
        placeholder={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: ICH.raised, color: ICH.ink, border: `1px solid ${focus ? ICH.cinnamon : ICH.line}`, fontFamily: ICH.sans }}
      />
    </label>
  );
}

/* ---- runnable preset request ---- */
const ITOPS_OUTCOME = {
  allow: { tone: "allow", label: "Gateway: allow", accent: "#2f9e5f" },
  flag: { tone: "flag", label: "Gateway: masked", accent: "#d2851f" },
  block: { tone: "block", label: "Gateway: block", accent: "#c4452a" },
};

function ItopsPresetCard({ p, onRun, running, active }) {
  const out = ITOPS_OUTCOME[p.expect] || ITOPS_OUTCOME.allow;
  return (
    <div className="flex flex-col rounded-2xl px-4 py-4" style={{ background: ICH.surface, border: `1px solid ${ICH.line}` }}>
      <span className="inline-flex items-center gap-1.5 text-[13px] font-bold" style={{ color: out.accent }}>
        <window.Icon name={p.icon} size={14} /> {p.label}
      </span>
      <p className="mt-2.5 flex-1 rounded-xl px-3 py-2.5 text-[12px] leading-relaxed" style={{ background: ICH.raised, color: ICH.ink, fontFamily: ICH.mono, border: `1px solid ${ICH.lineSoft}` }}>
        {p.request}
      </p>
      <div className="mt-3 flex items-center justify-between gap-2">
        <ItopsAirsChip tone={out.tone}>{out.label}</ItopsAirsChip>
        <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: out.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>
  );
}

/* ---- the single mock result panel ---- */
function ItopsResultPanel({ running, result, error }) {
  if (running) {
    return (
      <div className="flex items-center gap-3 rounded-2xl px-5 py-4" style={{ background: ICH.surface, border: `1px solid ${ICH.line}` }}>
        <window.Icon name="Loader2" size={18} className="animate-spin" style={{ color: ICH.cinnamon }} />
        <span className="text-[13px] font-semibold" style={{ color: ICH.sub }}>Routing through the TrueFoundry gateway — AIRS guardrail scanning…</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: ICH.amberSoft, color: ICH.sub, border: `1px solid rgba(210,133,31,0.4)` }}>
        <window.Icon name="WifiOff" size={16} style={{ color: ICH.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: ICH.line, color: ICH.faint, background: ICH.surfaceAlt }}>
        Run a preset or send a request above — the agent's reply and the gateway verdict show up here.
      </div>
    );
  }
  if (result.blocked) {
    return (
      <div className="rounded-2xl px-5 py-5" style={{ background: ICH.redSoft, border: `1px solid ${ICH.redBorder}` }}>
        <div className="flex flex-wrap items-center gap-2.5">
          <span className="text-[15px] font-extrabold" style={{ color: ICH.cinnamon }}>🚫 The gateway rejected the call (HTTP 400)</span>
          <ItopsAirsChip tone="block">AIRS @ gateway: block</ItopsAirsChip>
        </div>
        <p className="mt-2.5 text-[13.5px] leading-relaxed" style={{ color: ICH.ink }}>The agent <span className="font-semibold">never reached the model.</span></p>
        {result.reason && <p className="mt-1.5 text-[12.5px] leading-relaxed" style={{ color: ICH.sub }}>{result.reason}</p>}
      </div>
    );
  }
  const a = result.airs || {};
  const masked = a.maskApplied;
  return (
    <div className="rounded-2xl px-5 py-5" style={{ background: ICH.surface, border: `1px solid ${masked ? "rgba(210,133,31,0.45)" : ICH.greenBorder}` }}>
      <div className="flex flex-wrap items-center gap-2.5">
        <span className="text-[15px] font-extrabold" style={{ color: ICH.ink }}>🤖 Helpdesk reply</span>
        <ItopsAirsChip tone={masked ? "flag" : "allow"}>{masked ? "AIRS @ gateway: sensitive data masked" : "AIRS @ gateway: allow"}</ItopsAirsChip>
      </div>
      <p className="mt-3 text-[13.5px] leading-relaxed" style={{ color: ICH.ink }}>{result.reply}</p>
      {masked && result.maskedRequest && (
        <div className="mt-3.5">
          <div className="text-[10px] font-bold uppercase tracking-[0.14em]" style={{ color: ICH.faint, fontFamily: ICH.mono }}>Request, as the model saw it</div>
          <p className="mt-1 rounded-xl px-3 py-2.5 text-[12.5px] leading-relaxed" style={{ background: ICH.raised, color: ICH.ink, fontFamily: ICH.mono, border: `1px solid ${ICH.lineSoft}`, wordBreak: "break-word" }}>{result.maskedRequest}</p>
          <p className="mt-1.5 text-[11.5px] leading-relaxed" style={{ color: ICH.faint }}>Sensitive details were masked at the gateway — the model and any downstream log never see them.</p>
        </div>
      )}
    </div>
  );
}

/* ---- the MOCK tester ---- */
function ItopsTester() {
  const presets = window.CHIQ_ITOPS_PRESETS || [];
  const [text, setText] = React.useState("");
  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(request, key) {
    setRunning(true); setError(null); setResult(null); setRanKey(key);
    try {
      const out = await window.sendChiquititoItops({ request });
      setResult(out);
    } catch (e) {
      setError("Couldn't reach the gateway preview. This screen is mock-only for now — try a preset to see an illustrative verdict.");
    } finally {
      setRunning(false);
    }
  }

  const canSubmit = (text || "").trim().length > 0 && !running;

  return (
    <div>
      <ItopsSectionLabel>Try it live · run a request through the gateway</ItopsSectionLabel>
      <form
        onSubmit={(e) => { e.preventDefault(); if (canSubmit) run(text, "form"); }}
        className="rounded-2xl px-4 py-4"
        style={{ background: ICH.surface, border: `1px solid ${ICH.line}` }}
      >
        <ItopsInput value={text} onChange={(e) => setText(e.target.value)} placeholder="Ask the IT-Ops helpdesk agent something (try pasting a password or token to watch the gateway react)" />
        <div className="mt-3 flex flex-wrap items-center justify-between gap-2">
          <span className="text-[11.5px] leading-relaxed" style={{ color: ICH.faint }}>Every call is scanned at the gateway — the agent can't opt out.</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 ? ICH.cinnamon : ICH.raised, color: canSubmit ? ICH.cinnamonInk : ICH.faint, cursor: canSubmit ? "pointer" : "not-allowed" }}
          >
            Send request <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: ICH.faint, fontFamily: ICH.mono }}>Or run a preset request</div>
      <div className="grid grid-cols-1 gap-3 md:grid-cols-3">
        {presets.map((p) => (
          <ItopsPresetCard key={p.key} p={p} running={running} active={ranKey === p.key} onRun={(pp) => run(pp.request, pp.key)} />
        ))}
      </div>

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

/* ============================================================ */
function ChiquititoItops() {
  return (
    <div className="mx-auto max-w-[1360px] px-6 py-7 sm:px-9" data-screen-label="Chiquitito · Demo B (IT-Ops)">
      {/* header */}
      <div className="mt-1 a-fade-up">
        <div className="flex flex-wrap items-center gap-2.5">
          <img src="images/truefoundry-color.png" alt="" aria-hidden="true" style={{ width: 30, height: 30 }} className="object-contain" />
          <h1 style={{ fontFamily: ICH.serif, color: ICH.ink }} className="text-[30px] font-medium leading-none">IT-Ops helpdesk</h1>
          <span className="text-[13px]" style={{ color: ICH.faint, fontFamily: ICH.mono }}>· AIRS in the gateway</span>
        </div>
        <p className="mt-3 max-w-4xl text-[15.5px] leading-relaxed" style={{ color: ICH.ink }}>
          Same protection as Demo A, but enforced at the <span className="font-semibold" style={{ color: ICH.cinnamon }}>gateway</span> — not as a node on the canvas.
        </p>
      </div>

      {/* explainer + diagram */}
      <div className="mt-7">
        <ItopsSectionLabel>How it's wired · agent → gateway → model</ItopsSectionLabel>
        <div className="rounded-2xl px-5 py-6" style={{ background: ICH.surface, border: `1px solid ${ICH.line}` }}>
          <ItopsDiagram />
          <p className="mt-4 text-[13px] leading-relaxed" style={{ color: ICH.sub }}>
            An IT-Ops / helpdesk agent's model calls route through the <span className="font-semibold" style={{ color: ICH.ink }}>TrueFoundry AI gateway</span>, where <span className="font-semibold" style={{ color: ICH.cinnamon }}>Prisma AIRS runs as a guardrail inside it</span> — every call scanned centrally, and a builder <span className="font-semibold">can't bypass it</span>. Model: <span className="font-semibold">Mistral</span>. No AIRS node on the canvas.
          </p>
        </div>
      </div>

      {/* test window (mock) */}
      <div className="mt-8 max-w-[920px]">
        <ItopsTester />
      </div>

      {/* footer note — parallel to Demo A's honest rail */}
      <p className="mt-7 max-w-3xl text-[11.5px] leading-relaxed" style={{ color: ICH.faint }}>
        AIRS runs as a guardrail <span style={{ color: ICH.sub }}>inside</span> the TrueFoundry gateway (allow · mask · block) — every model call an IT-Ops agent makes is scanned centrally, and a builder can't opt out. Verdicts shown here are the expected gateway outcomes. No keys are exposed.
      </p>
    </div>
  );
}

window.ChiquititoItops = ChiquititoItops;
