// "One control plane. Every action." — animated interceptor diagram.
// Shows tool-calls flowing from agents on the left, through Aurek in the
// middle (where they're evaluated), to resources on the right. Some packets
// get allowed through; some get denied and fired back.
const { useRef: useRefIc, useEffect: useEffectIc, useState: useStateIc } = React;

function InterceptorDiagram() {
  const ref = useRefIc(null);
  const [decisions, setDecisions] = useStateIc({ allow: 0, deny: 0, escalate: 0 });

  useEffectIc(() => {
    const canvas = ref.current;
    const ctx = canvas.getContext("2d");
    const dpr = Math.min(window.devicePixelRatio || 1, 2);
    const W = 1100, H = 380;
    canvas.width = W * dpr;
    canvas.height = H * dpr;
    canvas.style.width = "100%";
    canvas.style.height = H + "px";
    canvas.style.maxWidth = W + "px";
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);

    const agents = [
      { x: 80, y: 80, label: "agent:rag" },
      { x: 80, y: 160, label: "agent:ops" },
      { x: 80, y: 240, label: "agent:analyst" },
      { x: 80, y: 320, label: "agent:release" },
    ];
    const resources = [
      { x: W - 100, y: 80, label: "postgres" },
      { x: W - 100, y: 160, label: "s3://prod" },
      { x: W - 100, y: 240, label: "slack.api" },
      { x: W - 100, y: 320, label: "git.push" },
    ];
    const core = { x: W / 2, y: 200, w: 180, h: 200 };

    const toolCalls = [
      "vector_query", "read_file", "http_post", "list_resources",
      "sql_select", "push_git", "send_message", "exec_shell",
    ];

    const packets = [];
    let pulseT = 0;
    let spawnT = 0;
    let lastDecisions = { allow: 0, deny: 0, escalate: 0 };

    function spawn() {
      const src = agents[Math.floor(Math.random() * agents.length)];
      const dst = resources[Math.floor(Math.random() * resources.length)];
      const kind = Math.random();
      const verdict = kind < 0.7 ? "allow" : kind < 0.88 ? "deny" : "escalate";
      packets.push({
        src, dst, verdict,
        t: 0,
        speed: 0.004 + Math.random() * 0.003,
        label: toolCalls[Math.floor(Math.random() * toolCalls.length)],
        decided: false,
      });
    }

    function drawNode(n, side) {
      // small panel
      const w = 130, h = 34;
      const x = n.x - w / 2, y = n.y - h / 2;
      ctx.fillStyle = "rgba(20,20,22,0.85)";
      ctx.strokeStyle = "rgba(255,255,255,0.18)";
      ctx.lineWidth = 1;
      ctx.beginPath();
      ctx.roundRect(x, y, w, h, 4);
      ctx.fill();
      ctx.stroke();

      // dot
      ctx.fillStyle = side === "left" ? "rgba(243,240,234,0.85)" : "oklch(0.82 0.14 75 / 0.9)";
      ctx.beginPath();
      ctx.arc(x + 12, y + h / 2, 3, 0, Math.PI * 2);
      ctx.fill();

      ctx.font = "500 11px 'JetBrains Mono', monospace";
      ctx.fillStyle = "rgba(243,240,234,0.85)";
      ctx.textBaseline = "middle";
      ctx.fillText(n.label, x + 22, y + h / 2 + 1);
    }

    function drawCore(pulse) {
      const { x, y, w, h } = core;
      const left = x - w / 2, top = y - h / 2;

      // glow
      const grad = ctx.createRadialGradient(x, y, 10, x, y, 180);
      grad.addColorStop(0, `oklch(0.82 0.14 75 / ${0.18 + pulse * 0.12})`);
      grad.addColorStop(1, "rgba(0,0,0,0)");
      ctx.fillStyle = grad;
      ctx.fillRect(left - 60, top - 60, w + 120, h + 120);

      // panel
      ctx.fillStyle = "rgba(10,10,12,0.92)";
      ctx.strokeStyle = "oklch(0.82 0.14 75 / 0.55)";
      ctx.lineWidth = 1.5;
      ctx.beginPath();
      ctx.roundRect(left, top, w, h, 6);
      ctx.fill();
      ctx.stroke();

      // inner border
      ctx.strokeStyle = "rgba(255,255,255,0.06)";
      ctx.lineWidth = 1;
      ctx.beginPath();
      ctx.roundRect(left + 6, top + 6, w - 12, h - 12, 4);
      ctx.stroke();

      // label
      ctx.font = "600 10px 'JetBrains Mono', monospace";
      ctx.fillStyle = "oklch(0.82 0.14 75)";
      ctx.textBaseline = "top";
      ctx.fillText("AUREK · POLICY ENGINE", left + 14, top + 14);

      // text lines
      ctx.font = "400 10px 'JetBrains Mono', monospace";
      ctx.fillStyle = "rgba(243,240,234,0.55)";
      const lines = [
        "intercept()",
        "evaluate(ctx,policy)",
        "decide → allow|deny",
        "audit.write()",
      ];
      lines.forEach((l, i) => ctx.fillText(l, left + 14, top + 38 + i * 16));

      // scanning line
      const scanY = top + 10 + ((pulseT * 60) % (h - 20));
      ctx.strokeStyle = "oklch(0.82 0.14 75 / 0.4)";
      ctx.lineWidth = 1;
      ctx.beginPath();
      ctx.moveTo(left + 6, scanY);
      ctx.lineTo(left + w - 6, scanY);
      ctx.stroke();

      // corner ticks (decorative)
      ctx.strokeStyle = "oklch(0.82 0.14 75 / 0.7)";
      ctx.lineWidth = 1.5;
      const c = 8;
      [[left, top, 1, 1], [left + w, top, -1, 1], [left, top + h, 1, -1], [left + w, top + h, -1, -1]].forEach(([cx, cy, dx, dy]) => {
        ctx.beginPath();
        ctx.moveTo(cx + dx * c, cy);
        ctx.lineTo(cx, cy);
        ctx.lineTo(cx, cy + dy * c);
        ctx.stroke();
      });
    }

    function tick(now) {
      pulseT += 0.016;
      spawnT += 16;
      if (spawnT > 280) { spawn(); spawnT = 0; }

      ctx.clearRect(0, 0, W, H);

      // faint connection lines from each agent → core, core → each resource
      ctx.strokeStyle = "rgba(255,255,255,0.05)";
      ctx.lineWidth = 1;
      for (const a of agents) {
        ctx.beginPath();
        ctx.moveTo(a.x + 65, a.y);
        ctx.lineTo(core.x - core.w / 2, core.y);
        ctx.stroke();
      }
      for (const r of resources) {
        ctx.beginPath();
        ctx.moveTo(core.x + core.w / 2, core.y);
        ctx.lineTo(r.x - 65, r.y);
        ctx.stroke();
      }

      // draw core
      drawCore(Math.sin(pulseT * 2) * 0.5 + 0.5);

      // packets
      for (let i = packets.length - 1; i >= 0; i--) {
        const p = packets[i];
        p.t += p.speed;

        // Path: agent → coreLeft → coreRight (if allow/escalate) → resource
        // Segment 0: agent to coreLeft (0..0.35)
        // Segment 1: inside core (0.35..0.55)  — decision happens at 0.45
        // Segment 2: coreRight to resource (0.55..1.0), unless deny (reflects back)

        const coreLeft = { x: core.x - core.w / 2, y: core.y };
        const coreRight = { x: core.x + core.w / 2, y: core.y };

        let x, y, color, size = 3;
        if (p.t < 0.35) {
          const tt = p.t / 0.35;
          x = p.src.x + 65 + (coreLeft.x - (p.src.x + 65)) * tt;
          y = p.src.y + (coreLeft.y - p.src.y) * tt;
          color = "rgba(243,240,234,0.85)";
        } else if (p.t < 0.55) {
          const tt = (p.t - 0.35) / 0.2;
          x = coreLeft.x + (coreRight.x - coreLeft.x) * tt;
          y = core.y;
          // mark decision at tt=0.5
          if (!p.decided && tt > 0.5) {
            p.decided = true;
            lastDecisions = { ...lastDecisions };
            lastDecisions[p.verdict]++;
            setDecisions({ ...lastDecisions });
          }
          color = p.verdict === "allow" ? "oklch(0.80 0.14 145)" :
                  p.verdict === "deny"  ? "oklch(0.70 0.18 25)" :
                  "oklch(0.82 0.14 75)";
          size = 3.4;
        } else {
          if (p.verdict === "deny") {
            // Reflect back toward agent
            const tt = (p.t - 0.55) / 0.45;
            const back = Math.min(tt, 1);
            x = coreLeft.x + ((p.src.x + 65) - coreLeft.x) * back;
            y = core.y + (p.src.y - core.y) * back;
            color = "oklch(0.70 0.18 25)";
          } else {
            const tt = (p.t - 0.55) / 0.45;
            x = coreRight.x + ((p.dst.x - 65) - coreRight.x) * tt;
            y = core.y + (p.dst.y - core.y) * tt;
            color = p.verdict === "allow" ? "oklch(0.80 0.14 145)" : "oklch(0.82 0.14 75)";
          }
        }

        // trail
        ctx.fillStyle = color.replace(")", " / 0.2)").replace("oklch(", "oklch(");
        ctx.beginPath();
        ctx.arc(x, y, size + 3, 0, Math.PI * 2);
        ctx.fill();
        // core
        ctx.fillStyle = color;
        ctx.beginPath();
        ctx.arc(x, y, size, 0, Math.PI * 2);
        ctx.fill();

        // label near packet (fades in then out)
        const labelAlpha = p.t < 0.15 ? p.t / 0.15 : p.t > 0.85 ? (1 - p.t) / 0.15 : 1;
        ctx.font = "400 9px 'JetBrains Mono', monospace";
        ctx.fillStyle = `rgba(243,240,234,${0.55 * Math.max(0, labelAlpha)})`;
        ctx.fillText(p.label, x + 8, y - 6);

        if (p.t >= 1) packets.splice(i, 1);
      }

      // draw nodes ON TOP of lines
      for (const a of agents) drawNode(a, "left");
      for (const r of resources) drawNode(r, "right");

      raf = requestAnimationFrame(tick);
    }

    let raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  return (
    <div style={{ position: "relative" }}>
      <canvas ref={ref} style={{ display: "block", margin: "0 auto" }} />
      <div
        className="mono"
        style={{
          position: "absolute",
          top: 14,
          left: 14,
          fontSize: 10,
          letterSpacing: "0.2em",
          color: "var(--text-faint)",
          textTransform: "uppercase",
        }}
      >
        live · inference
      </div>
      <div
        className="mono"
        style={{
          position: "absolute",
          top: 14,
          right: 14,
          display: "flex",
          gap: 18,
          fontSize: 11,
        }}
      >
        <span style={{ color: "oklch(0.80 0.14 145)" }}>● ALLOW {decisions.allow}</span>
        <span style={{ color: "oklch(0.70 0.18 25)" }}>● DENY {decisions.deny}</span>
        <span style={{ color: "oklch(0.82 0.14 75)" }}>● ESCALATE {decisions.escalate}</span>
      </div>
    </div>
  );
}

function Interceptor() {
  return (
    <section
      id="platform"
      style={{
        position: "relative",
        padding: "120px 28px",
        borderBottom: "1px solid var(--line)",
      }}
    >
      <div
        aria-hidden
        style={{
          position: "absolute",
          inset: 0,
          background: "radial-gradient(ellipse 70% 60% at 50% 50%, rgba(255,255,255,0.02), transparent 70%)",
          pointerEvents: "none",
        }}
      />
      <div style={{ maxWidth: 1200, margin: "0 auto", position: "relative" }}>
        <div
          className="mono"
          style={{
            fontSize: 10,
            letterSpacing: "0.3em",
            color: "var(--text-faint)",
            textTransform: "uppercase",
            marginBottom: 16,
          }}
        >
          ▸ The Platform
        </div>
        <h2
          style={{
            fontSize: 52,
            margin: "0 0 16px",
            letterSpacing: "-0.02em",
            fontWeight: 600,
          }}
        >
          One control plane.<br/>
          <span style={{ color: "var(--text-dim)" }}>Every action.</span>
        </h2>
        <p
          style={{
            fontSize: 16,
            color: "var(--text-dim)",
            maxWidth: 620,
            lineHeight: 1.6,
            margin: "0 0 60px",
          }}
        >
          Every tool call and resource access flows through Aurek. Policy is
          evaluated deterministically — same inputs, same outcome, every time —
          and every decision is written to an immutable audit log.
        </p>

        <div
          style={{
            border: "1px solid var(--line)",
            borderRadius: 8,
            background: "linear-gradient(180deg, rgba(14,14,16,0.6), rgba(8,8,10,0.9))",
            padding: "30px 20px 20px",
            position: "relative",
            overflow: "hidden",
          }}
        >
          <InterceptorDiagram />
        </div>

        <div
          style={{
            display: "grid",
            gridTemplateColumns: "repeat(3, 1fr)",
            gap: 24,
            marginTop: 40,
          }}
        >
          {[
            { tag: "IN", title: "Intercept",
              body: "Every tool call and resource access goes through Aurek before execution. Nothing reaches your tools or data stores without a policy decision first." },
            { tag: "EX", title: "Enforce",
              body: "Policy evaluated deterministically in under 0.1ms. Allow, deny, or escalate to a human — same inputs, same outcome, every time." },
            { tag: "AU", title: "Audit",
              body: "Every decision logged with tamper-evident context. Export a compliance report that satisfies regulators." },
          ].map((c) => (
            <div
              key={c.tag}
              style={{
                border: "1px solid var(--line)",
                borderRadius: 8,
                padding: 28,
                background: "linear-gradient(180deg, rgba(14,14,16,0.5), rgba(8,8,10,0.3))",
              }}
            >
              <div
                className="mono"
                style={{
                  display: "inline-block",
                  padding: "4px 8px",
                  border: "1px solid var(--line-strong)",
                  fontSize: 10,
                  letterSpacing: "0.2em",
                  color: "var(--text-dim)",
                  marginBottom: 20,
                }}
              >
                {c.tag}
              </div>
              <h3 style={{ fontSize: 20, margin: "0 0 12px", fontWeight: 600 }}>{c.title}</h3>
              <p style={{ fontSize: 14, color: "var(--text-dim)", lineHeight: 1.6, margin: 0 }}>
                {c.body}
              </p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Interceptor, InterceptorDiagram });
