// Live Policy Feed — a streaming terminal of policy decisions.
// New entries fly in from the top; oldest scroll off the bottom.
const { useState: useStateF, useEffect: useEffectF } = React;

const ACTIONS = [
  ["vector_query",  "agent:rag-pipeline",   "allow"],
  ["read_file",     "agent:compiler-7",     "allow"],
  ["http_post",     "agent:ops-runner",     "deny"],
  ["list_resources","agent:governor-1",     "allow"],
  ["sql_select",    "agent:analyst-3",      "allow"],
  ["push_git",      "agent:release-bot",    "deny"],
  ["send_slack",    "agent:oncall-triage",  "allow"],
  ["exec_shell",    "agent:devops-7",       "escalate"],
  ["fetch_secret",  "agent:deploy-agent",   "escalate"],
  ["vector_upsert", "agent:ingestor-2",     "allow"],
  ["delete_row",    "agent:db-ops",         "deny"],
  ["call_tool",     "agent:coord-mesh",     "allow"],
  ["embed_doc",     "agent:rag-pipeline",   "allow"],
  ["s3_put",        "agent:archive-worker", "allow"],
  ["kube_apply",    "agent:platform-01",    "escalate"],
];

function randMs() {
  // 0.01ms - 0.14ms
  return (0.01 + Math.random() * 0.13).toFixed(2);
}

function PolicyFeed() {
  const [rows, setRows] = useStateF(() => {
    return Array.from({ length: 8 }, (_, i) => {
      const [action, agent, verdict] = ACTIONS[Math.floor(Math.random() * ACTIONS.length)];
      return { id: Date.now() - i * 100, action, agent, verdict, ms: randMs(), fresh: false };
    });
  });

  useEffectF(() => {
    const id = setInterval(() => {
      const [action, agent, verdict] = ACTIONS[Math.floor(Math.random() * ACTIONS.length)];
      setRows((r) => {
        const next = [{ id: Date.now() + Math.random(), action, agent, verdict, ms: randMs(), fresh: true }, ...r];
        return next.slice(0, 11);
      });
    }, 900);
    return () => clearInterval(id);
  }, []);

  useEffectF(() => {
    const id = setTimeout(() => {
      setRows((r) => r.map((x) => ({ ...x, fresh: false })));
    }, 500);
    return () => clearTimeout(id);
  }, [rows]);

  const verdictColor = (v) => v === "allow" ? "oklch(0.80 0.14 145)" :
                              v === "deny"  ? "oklch(0.70 0.18 25)" :
                                              "oklch(0.82 0.14 75)";

  return (
    <div
      style={{
        border: "1px solid var(--line)",
        borderRadius: 8,
        background: "linear-gradient(180deg, rgba(10,10,12,0.9), rgba(5,5,6,0.95))",
        overflow: "hidden",
      }}
    >
      <div
        className="mono"
        style={{
          padding: "12px 18px",
          borderBottom: "1px solid var(--line)",
          fontSize: 10,
          letterSpacing: "0.22em",
          color: "var(--text-faint)",
          textTransform: "uppercase",
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
        }}
      >
        <span>live policy feed · /var/log/aurek/decisions</span>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
          <span
            style={{
              width: 6, height: 6, borderRadius: "50%",
              background: "oklch(0.80 0.14 145)",
              boxShadow: "0 0 8px oklch(0.80 0.14 145 / 0.8)",
              animation: "pulseDot 1.4s infinite",
            }}
          />
          streaming
        </span>
      </div>
      <div
        className="mono"
        style={{
          padding: "14px 18px",
          fontSize: 13,
          lineHeight: 1.85,
          minHeight: 340,
        }}
      >
        {rows.map((r) => (
          <div
            key={r.id}
            style={{
              display: "grid",
              gridTemplateColumns: "70px 180px 1fr 80px 120px",
              gap: 16,
              opacity: r.fresh ? 0 : 1,
              transform: r.fresh ? "translateY(-6px)" : "translateY(0)",
              transition: "opacity .35s ease, transform .35s ease",
              whiteSpace: "nowrap",
            }}
          >
            <span style={{ color: verdictColor(r.verdict), fontWeight: 600 }}>
              {r.verdict.toUpperCase()}
            </span>
            <span style={{ color: "var(--text)" }}>{r.action}</span>
            <span style={{ color: "var(--text-dim)" }}>{r.agent}</span>
            <span style={{ color: "var(--text-faint)" }}>{r.ms}ms</span>
            <span style={{ color: r.verdict === "escalate" ? "oklch(0.82 0.14 75)" : "var(--text-faint)" }}>
              {r.verdict === "escalate" ? "→ escalated" : r.verdict === "deny" ? "→ blocked" : ""}
            </span>
          </div>
        ))}
      </div>
      <style>{`
        @keyframes pulseDot { 0%,100% { opacity: 1 } 50% { opacity: 0.35 } }
      `}</style>
    </div>
  );
}

function HowItWorks() {
  return (
    <section
      id="protocol"
      style={{
        padding: "120px 28px 100px",
        borderBottom: "1px solid var(--line)",
        position: "relative",
      }}
    >
      <div style={{ maxWidth: 1200, margin: "0 auto" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1.3fr", gap: 80, alignItems: "start" }}>
          <div>
            <div
              className="mono"
              style={{
                fontSize: 10,
                letterSpacing: "0.3em",
                color: "var(--text-faint)",
                textTransform: "uppercase",
                marginBottom: 16,
              }}
            >
              ▸ Decisions, not guesses
            </div>
            <h2
              style={{
                fontSize: 44,
                margin: "0 0 20px",
                letterSpacing: "-0.02em",
                fontWeight: 600,
                lineHeight: 1.1,
              }}
            >
              Deterministic, auditable, sub-millisecond.
            </h2>
            <p style={{ fontSize: 16, color: "var(--text-dim)", lineHeight: 1.65, margin: "0 0 28px" }}>
              No LLM in the policy path. Every decision is a pure function of
              context + policy, so identical inputs always produce identical
              outcomes — the property your legal, security, and SRE teams have
              been asking for.
            </p>
            <ul style={{ listStyle: "none", padding: 0, margin: 0 }}>
              {[
                ["p50 latency", "0.07ms"],
                ["p99 latency", "0.14ms"],
                ["Policies evaluated / day", "3.4B+"],
                ["OWASP agentic coverage", "100%"],
              ].map(([k, v]) => (
                <li
                  key={k}
                  className="mono"
                  style={{
                    display: "flex",
                    justifyContent: "space-between",
                    padding: "12px 0",
                    borderBottom: "1px dashed var(--line)",
                    fontSize: 13,
                  }}
                >
                  <span style={{ color: "var(--text-dim)", letterSpacing: "0.05em" }}>{k}</span>
                  <span style={{ color: "var(--amber)" }}>{v}</span>
                </li>
              ))}
            </ul>
          </div>
          <PolicyFeed />
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { HowItWorks, PolicyFeed });
