/* tenant/ops_ marketing site — inline product mocks.
   Faithful, compact recreations of the real product surfaces, built from the
   same component DNA as src/eng-ops-agent.jsx + the OOB card. Used wherever the
   site shows "the real thing" rather than a captioned placeholder.
   All colors via the passed `pal`; type via MK_TYPE. */

const M = window.MK_TYPE;

/* quiet window chrome — three dots + connected status, per EngSurface */
function WinChrome({ pal, title, subtitle, status = "connected", children, style }) {
  return (
    <div style={{
      background: pal.bgPanel, border: `1px solid ${pal.border}`, borderRadius: 8,
      overflow: "hidden", display: "flex", flexDirection: "column",
      boxShadow: "0 1px 2px rgba(0,0,0,0.18), 0 18px 48px rgba(0,0,0,0.28)",
      ...style,
    }}>
      <div style={{
        height: 38, padding: "0 14px", background: pal.bgRaised,
        borderBottom: `1px solid ${pal.border}`,
        display: "flex", alignItems: "center", gap: 12, flexShrink: 0,
      }}>
        <div style={{ display: "flex", gap: 6 }}>
          {["#E0857A", "#E5B560", "#7CB68F"].map((c) => (
            <span key={c} style={{ width: 10, height: 10, borderRadius: "50%", background: c, opacity: 0.85 }} />
          ))}
        </div>
        <div style={{ display: "flex", alignItems: "baseline", gap: 9, flex: 1, minWidth: 0 }}>
          <span style={{ fontSize: 12.5, color: pal.fg, fontWeight: 500 }}>{title}</span>
          {subtitle && <span style={{ fontSize: 11, color: pal.fgFaint, fontFamily: M.mono, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{subtitle}</span>}
        </div>
        <span style={{ fontSize: 10.5, color: pal.fgFaint, fontFamily: M.mono, letterSpacing: "0.06em", display: "inline-flex", alignItems: "center", gap: 6 }}>
          <span style={{ width: 6, height: 6, borderRadius: "50%", background: pal.ok }} />
          {status}
        </span>
      </div>
      {children}
    </div>
  );
}

/* mono eyebrow inside mocks */
function Mk({ pal, k, v, tone = "neutral" }) {
  const tones = {
    neutral: { bg: pal.bgSubtle, kfg: pal.fgFaint, vfg: pal.fgDim },
    accent:  { bg: pal.accentBg, kfg: pal.accentDeep, vfg: pal.accentDeep },
    ok:      { bg: pal.okBg, kfg: pal.ok, vfg: pal.ok },
    err:     { bg: pal.errBg, kfg: pal.err, vfg: pal.err },
  }[tone];
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "2px 8px", borderRadius: 999, background: tones.bg, fontFamily: M.mono, fontSize: 11, fontWeight: 500 }}>
      {k && <span style={{ color: tones.kfg }}>{k}</span>}
      <span style={{ color: tones.vfg }}>{v}</span>
    </span>
  );
}

/* JSON block with 2px left rail — the "rendered code box" signal */
function JsonBox({ pal, label, code, tone = "neutral" }) {
  const lc = tone === "err" ? pal.err : tone === "ok" ? pal.ok : pal.fgFaint;
  return (
    <div>
      <div style={{ fontFamily: M.mono, fontSize: 9.5, fontWeight: 500, letterSpacing: "0.08em", textTransform: "uppercase", color: lc, marginBottom: 6, display: "flex", alignItems: "center", gap: 8 }}>
        <span>{label}</span>
        <span style={{ flex: 1, height: 1, background: pal.border }} />
        <span style={{ padding: "1px 6px", borderRadius: 3, background: pal.bgSubtle, color: pal.fgFaint, fontSize: 9, cursor: "pointer" }}>copy</span>
      </div>
      <pre style={{ margin: 0, padding: "9px 11px", background: pal.bgSubtle, border: `1px solid ${pal.border}`, borderLeft: `2px solid ${tone === "err" ? pal.err : pal.borderStrong}`, borderRadius: 4, fontFamily: M.mono, fontSize: 11, lineHeight: 1.55, color: pal.fgDim, overflow: "auto", whiteSpace: "pre" }}>{code}</pre>
    </div>
  );
}

/* single expandable tool-call row */
function ToolRow({ pal, name, ms, summary, status = "ok", args, response, defaultOpen = false }) {
  const [open, setOpen] = React.useState(defaultOpen);
  const sc = status === "ok" ? pal.ok : status === "err" ? pal.err : pal.warn;
  const sl = { ok: "ok", err: "error", run: "running" }[status];
  return (
    <div style={{ border: `1px solid ${pal.border}`, borderRadius: 4, background: open ? pal.bgPanel : pal.bgSubtle, overflow: "hidden" }}>
      <button onClick={() => setOpen(!open)} style={{ width: "100%", textAlign: "left", padding: "7px 11px", background: "transparent", border: 0, cursor: "pointer", display: "flex", alignItems: "center", gap: 9, fontFamily: M.mono, fontSize: 11.5, color: pal.fgDim }}>
        <span style={{ width: 9, color: pal.fgFaint, transform: open ? "rotate(90deg)" : "none", transition: "transform .12s ease", fontSize: 9 }}>▸</span>
        <span style={{ width: 6, height: 6, borderRadius: "50%", background: sc, flexShrink: 0 }} />
        <span style={{ color: pal.fg, fontWeight: 500 }}>{name}</span>
        <span style={{ color: pal.fgFaint }}>{ms}ms</span>
        <span style={{ color: pal.boxLine }}>│</span>
        <span style={{ color: status === "err" ? pal.err : pal.fgMuted, flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{summary}</span>
        <span style={{ padding: "1px 8px", borderRadius: 999, background: status === "ok" ? pal.okBg : status === "err" ? pal.errBg : pal.warnBg, color: sc, fontFamily: M.mono, fontSize: 10, fontWeight: 500, letterSpacing: "0.04em", flexShrink: 0 }}>{sl}</span>
      </button>
      {open && (
        <div style={{ borderTop: `1px solid ${pal.border}`, padding: "11px 12px 12px", display: "flex", flexDirection: "column", gap: 11, background: pal.bgPanel }}>
          <JsonBox pal={pal} label="arguments" code={args || "{}"} />
          <JsonBox pal={pal} label={status === "err" ? "error" : "response"} code={response || ""} tone={status === "err" ? "err" : "ok"} />
        </div>
      )}
    </div>
  );
}

/* RAF streaming text with sand caret at the tip (per CLAUDE.md §2.4.1) */
function StreamText({ pal, text, charsPerSec = 78 }) {
  const [n, setN] = React.useState(0);
  React.useEffect(() => {
    let raf, start = null;
    const tick = (t) => {
      if (start == null) start = t;
      const c = Math.min(text.length, Math.floor((t - start) / 1000 * charsPerSec));
      setN(c);
      if (c < text.length) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [text]);
  const done = n >= text.length;
  return (
    <span style={{ whiteSpace: "pre-wrap" }}>
      {text.slice(0, n)}
      {!done && <span className="ops-caret" style={{ color: pal.accent, fontFamily: M.mono, fontWeight: 500, marginLeft: 1 }}>_</span>}
    </span>
  );
}

/* ── The canonical Ops Agent thread (compact) ─────────────────── */
function AgentThreadMock({ pal, stream = true }) {
  return (
    <WinChrome pal={pal} title="Ops Agent" subtitle="Tenant_Ops__Test-Tenant">
      <div style={{ background: pal.bg, padding: "18px 20px", display: "flex", flexDirection: "column", gap: 16 }}>
        {/* user */}
        <div style={{ display: "flex", justifyContent: "flex-end" }}>
          <div style={{ background: pal.accentBg, border: `1px solid ${pal.accent}40`, borderRadius: 6, padding: "9px 13px", maxWidth: 380 }}>
            <div style={{ fontFamily: M.mono, fontSize: 9.5, color: pal.accentDeep, letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 4, fontWeight: 500 }}>You · 14:21</div>
            <div style={{ fontSize: 13.5, color: pal.fg, lineHeight: 1.5 }}>How many guest users are in this tenant?</div>
          </div>
        </div>
        {/* tool rows */}
        <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
          <ToolRow pal={pal} name="activate_toolset" ms={42} summary="admin domain activated" args={`{ "name": "admin" }`} response={`{ "activated": true, "scope": "User.Read.All" }`} />
          <ToolRow pal={pal} name="list_users" ms={188} summary="0 users matched" defaultOpen
            args={`{\n  "filter": "userType eq 'Guest'",\n  "top": 100\n}`}
            response={`{\n  "value": [],\n  "@odata.count": 0\n}`} />
        </div>
        {/* agent */}
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 8 }}>
            <div style={{ width: 28, height: 21, borderRadius: 3, background: pal.bgRaised, border: `1px solid ${pal.border}`, display: "inline-flex", alignItems: "center", justifyContent: "center", lineHeight: 1, fontFamily: M.mono, fontSize: 13, fontWeight: 500 }}>
              <span style={{ color: pal.accent }}>/</span><span className="ops-caret-soft" style={{ color: pal.accent }}>_</span>
            </div>
            <span style={{ fontFamily: M.mono, fontSize: 10, color: pal.fgFaint, letterSpacing: "0.08em", textTransform: "uppercase", fontWeight: 500 }}>Ops Agent</span>
            <span style={{ padding: "1px 7px", borderRadius: 999, background: pal.bgSubtle, color: pal.fgMuted, fontFamily: M.mono, fontSize: 9.5 }}>Sonnet</span>
            <span style={{ flex: 1 }} />
            <span style={{ fontFamily: M.mono, fontSize: 10, color: pal.fgFaint }}>14:21:08</span>
          </div>
          <div style={{ fontSize: 13.5, lineHeight: 1.6, color: pal.fgDim, paddingLeft: 37 }}>
            {stream
              ? <StreamText pal={pal} text={'There are currently 0 guest users in your tenant. The empty result confirms no external collaborators have been invited or accepted.'} />
              : 'There are currently 0 guest users in your tenant. The empty result confirms no external collaborators have been invited or accepted.'}
          </div>
        </div>
      </div>
      {/* composer */}
      <div style={{ padding: "11px 20px 14px", borderTop: `1px solid ${pal.border}`, background: pal.bg }}>
        <div style={{ background: pal.bgPanel, border: `1px solid ${pal.border}`, borderRadius: 6, padding: "10px 12px", display: "flex", alignItems: "center", gap: 12 }}>
          <span style={{ flex: 1, fontSize: 13.5, color: pal.fgFaint }}>Ask the Ops Agent about your tenant…</span>
          <span style={{ fontFamily: M.mono, fontSize: 10, color: pal.fgFaint, border: `1px solid ${pal.border}`, borderRadius: 3, padding: "1px 5px" }}>⌘ ⏎</span>
          <span style={{ padding: "6px 14px", borderRadius: 6, background: pal.accent, color: pal.accentInk, fontSize: 12.5, fontWeight: 500, display: "inline-flex", gap: 6, alignItems: "center" }}>Send <span style={{ fontFamily: M.mono }}>↗</span></span>
        </div>
      </div>
    </WinChrome>
  );
}

/* ── Approval card (in-chat confirmation DNA) ─────────────────── */
function ApprovalCardMock({ pal, variant = "confirm" }) {
  const isOob = variant === "oob";
  const rail = isOob ? pal.err : pal.warn;
  const eyebrowC = isOob ? pal.err : pal.warn;
  return (
    <div style={{ background: pal.bgPanel, border: `1px solid ${pal.border}`, borderRadius: 8, overflow: "hidden" }}>
      <div style={{ padding: "13px 18px 13px 0", background: pal.bgRaised, borderBottom: `1px solid ${pal.border}`, display: "flex", alignItems: "center", gap: 13 }}>
        <div style={{ width: 4, alignSelf: "stretch", background: rail }} />
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: M.mono, fontSize: 10, fontWeight: 500, letterSpacing: "0.08em", textTransform: "uppercase", color: eyebrowC, marginBottom: 4 }}>{isOob ? "Browser approval required" : "Confirmation required"}</div>
          <div style={{ fontWeight: 600, fontSize: 16.5, letterSpacing: "-0.015em", color: pal.fg, lineHeight: 1.25 }}>{isOob ? "Out-of-band approval · CRITICAL" : "Update user · Anna Test"}</div>
        </div>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "2px 10px", borderRadius: 999, background: isOob ? pal.errBg : pal.warnBg, color: rail, fontFamily: M.mono, fontSize: 11, fontWeight: 500 }}>
          <span style={{ width: 6, height: 6, borderRadius: "50%", background: rail }} />{isOob ? "CRITICAL" : "awaiting · 0m 12s"}
        </span>
      </div>
      <div style={{ padding: "9px 18px", borderBottom: `1px solid ${pal.border}`, display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap", fontFamily: M.mono, fontSize: 11, color: pal.fgFaint }}>
        <span><span style={{ color: pal.fgMuted }}>operation</span>  {isOob ? "noop_test_critical" : "update_user"}</span>
        <span style={{ color: pal.boxLine }}>│</span>
        <span><span style={{ color: pal.fgMuted }}>target</span>  anna.test@…onmicrosoft.com</span>
      </div>
      <div style={{ padding: 18 }}>
        <div style={{ fontFamily: M.mono, fontSize: 10, fontWeight: 500, letterSpacing: "0.08em", textTransform: "uppercase", color: pal.fgFaint, marginBottom: 10 }}>Preview</div>
        <div style={{ background: pal.bgSubtle, border: `1px solid ${pal.border}`, borderLeft: `2px solid ${pal.borderStrong}`, borderRadius: 4, padding: "12px 14px", fontFamily: M.mono, fontSize: 11.5, color: pal.fgDim, lineHeight: 1.7 }}>
          <div style={{ color: pal.fgFaint, marginBottom: 5 }}>--- preview ---</div>
          <div><span style={{ color: pal.fgMuted }}>action</span>  <span style={{ color: pal.fg, fontWeight: 500 }}>UPDATE USER</span></div>
          <div style={{ marginTop: 6 }}><span style={{ color: pal.fgMuted }}>changes</span></div>
          <div style={{ paddingLeft: 14 }}>
            <span style={{ color: pal.fgFaint }}>jobTitle</span>{"  "}
            <span style={{ color: pal.fgFaint, textDecoration: "line-through" }}>(empty)</span>{"  →  "}
            <span style={{ color: pal.ok, fontWeight: 500 }}>Elicitation Test</span>
          </div>
        </div>
        <div style={{ display: "flex", gap: 8, marginTop: 13, flexWrap: "wrap" }}>
          <Mk pal={pal} k="scope" v="User.ReadWrite.All" />
          <Mk pal={pal} k="risk" v="reversible" tone="ok" />
        </div>
      </div>
      <div style={{ padding: "13px 18px", borderTop: `1px solid ${pal.border}`, background: pal.bgRaised, display: "flex", alignItems: "center", gap: 12 }}>
        <span style={{ fontFamily: M.mono, fontSize: 11, color: pal.fgFaint }}>{isOob ? "expires in 04:23" : "confirm before 14:22:31"}</span>
        <span style={{ flex: 1 }} />
        <span className="btn" style={{ pointerEvents: "none" }}>Decline</span>
        <span className="btn btn--primary" style={{ pointerEvents: "none" }}>{isOob ? "Open approval page ↗" : "Approve"}<span className="btn__kbd">⌘⏎</span></span>
      </div>
    </div>
  );
}

/* ── Dashboard tile grid (compact, §4.4) ──────────────────────── */
function DashboardMock({ pal }) {
  const Tile = ({ eyebrow, metric, sub, children, status }) => (
    <div style={{ background: pal.bgPanel, border: `1px solid ${pal.border}`, borderRadius: 8, padding: "18px 18px", display: "flex", flexDirection: "column", gap: 8, minWidth: 0 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <span style={{ fontFamily: M.mono, fontSize: 10, fontWeight: 500, letterSpacing: "0.08em", textTransform: "uppercase", color: pal.fgFaint }}>{eyebrow}</span>
        {status && <span style={{ marginLeft: "auto", display: "inline-flex", alignItems: "center", gap: 5, padding: "1px 8px", borderRadius: 999, background: pal.okBg, color: pal.ok, fontFamily: M.mono, fontSize: 9.5, fontWeight: 500 }}><span style={{ width: 5, height: 5, borderRadius: "50%", background: pal.ok }} />{status}</span>}
      </div>
      {metric && <div style={{ fontWeight: 500, fontSize: 46, letterSpacing: "-0.035em", lineHeight: 1, color: pal.fg, fontVariantNumeric: "tabular-nums" }}>{metric}</div>}
      {sub && <div style={{ fontSize: 12, color: pal.fgMuted }}>{sub}</div>}
      {children}
    </div>
  );
  return (
    <WinChrome pal={pal} title="Dashboard" subtitle="tenant overview">
      <div style={{ background: pal.bg, padding: 18, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <Tile eyebrow="Users" metric="1,284" sub="42 added · 30d" status="operational" />
        <Tile eyebrow="Security score" metric="86%" sub="+4 pts · 30d" />
        <Tile eyebrow="Licenses" sub="">
          <div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: 2 }}>
            {[["E5", 220, 240], ["E3", 640, 800], ["Teams", 1100, 1200]].map(([k, a, b]) => (
              <div key={k}>
                <div style={{ display: "flex", justifyContent: "space-between", fontFamily: M.mono, fontSize: 11, color: pal.fgMuted, marginBottom: 4 }}><span>{k}</span><span style={{ color: pal.fgFaint }}>{a}/{b}</span></div>
                <div style={{ height: 4, borderRadius: 999, background: pal.bgSubtle, overflow: "hidden" }}><div style={{ width: `${(a / b) * 100}%`, height: "100%", background: pal.accent }} /></div>
              </div>
            ))}
          </div>
        </Tile>
        <Tile eyebrow="Attention" sub="">
          <div style={{ display: "flex", flexDirection: "column", gap: 7, marginTop: 2 }}>
            {[["3 stale app credentials", pal.warn, "degraded"], ["1 admin without MFA", pal.err, "critical"], ["12 devices · 90d idle", pal.fgMuted, "review"]].map(([t, c, s]) => (
              <div key={t} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12.5, color: pal.fgDim }}>
                <span style={{ width: 6, height: 6, borderRadius: "50%", background: c, flexShrink: 0 }} />
                <span style={{ flex: 1 }}>{t}</span>
                <span style={{ fontFamily: M.mono, fontSize: 9.5, color: pal.fgFaint, textTransform: "uppercase", letterSpacing: "0.04em" }}>{s}</span>
              </div>
            ))}
          </div>
        </Tile>
      </div>
    </WinChrome>
  );
}

Object.assign(window, { WinChrome, JsonBox, ToolRow, StreamText, AgentThreadMock, ApprovalCardMock, DashboardMock, MkChip: Mk });
