// Behavioral intelligence — anomaly feed showing call-volume spikes
// and async Slack blocking.
const { useState: useStateB, useEffect: useEffectB, useRef: useRefB } = React;

function SparkBar({ values, anomalyAt }) {
  return (
    <div style={{ display: "flex", alignItems: "flex-end", gap: 2, height: 36 }}>
      {values.map((v, i) => (
        <div key={i} style={{
          width: 4,
          height: (v * 100) + "%",
          background: i === anomalyAt ? "oklch(0.70 0.18 25)" :
                       i > anomalyAt ? "var(--amber)" : "rgba(255,255,255,0.25)",
          borderRadius: 1,
          transition: "all .3s",
        }}/>
      ))}
    </div>
  );
}

function BehaviorSection() {
  const [events, setEvents] = useStateB(() => seed());
  function seed() {
    return [
      { id: 1, agent: "release-bot", kind: "VOLUME SPIKE", desc: "calls/min 14× baseline", ts: "00:04 ago", tone: "risk", action: "Blocked at gateway" },
      { id: 2, agent: "rag-pipeline", kind: "TOOL DRIFT", desc: "+3 new tools since baseline", ts: "12:11 ago", tone: "warn", action: "Awaiting review" },
      { id: 3, agent: "deploy-agent", kind: "OFF-HOURS", desc: "exec at 03:14 UTC (Sun)", ts: "1h ago", tone: "warn", action: "Slack ping → on-call" },
    ];
  }
  useEffectB(() => {
    const id = setInterval(() => {
      const samples = [
        { agent: "ops-runner", kind: "VOLUME SPIKE", desc: "calls/min 6× baseline", tone: "risk", action: "Blocked" },
        { agent: "analyst-3",  kind: "DATA EGRESS", desc: "new s3 bucket destination", tone: "warn", action: "Slack ping" },
        { agent: "router-1",   kind: "PROMPT DRIFT", desc: "system prompt hash changed", tone: "warn", action: "Frozen" },
        { agent: "exec-9",     kind: "TOOL DRIFT", desc: "+1 tool: shell_exec", tone: "risk", action: "Blocked" },
      ];
      const s = samples[Math.floor(Math.random() * samples.length)];
      setEvents((arr) => [{ id: Date.now(), ...s, ts: "just now" }, ...arr].slice(0, 5));
    }, 4500);
    return () => clearInterval(id);
  }, []);

  // animated traffic
  const [bars, setBars] = useStateB(() => Array.from({ length: 28 }, () => 0.2 + Math.random() * 0.35));
  useEffectB(() => {
    const id = setInterval(() => {
      setBars((arr) => {
        const next = arr.slice(1);
        // sometimes spike
        next.push(Math.random() < 0.18 ? 0.85 + Math.random() * 0.15 : 0.2 + Math.random() * 0.35);
        return next;
      });
    }, 600);
    return () => clearInterval(id);
  }, []);
  const anomalyAt = bars.findIndex((v) => v > 0.8);

  const toneColor = (t) => t === "risk" ? "oklch(0.70 0.18 25)" : "var(--amber)";

  return (
    <section id="behavior" style={{ padding: "120px 28px", borderBottom: "1px solid var(--line)", position: "relative" }}>
      <div style={{ maxWidth: 1200, margin: "0 auto" }}>
        <div className="mono" style={{ fontSize: 10, letterSpacing: "0.3em", color: "var(--text-faint)", textTransform: "uppercase", marginBottom: 16 }}>
          ▸ Behavioral intelligence
        </div>
        <h2 style={{ fontSize: 44, margin: "0 0 16px", letterSpacing: "-0.02em", fontWeight: 600, lineHeight: 1.08 }}>
          Agents go off-script.<br/>
          <span style={{ color: "var(--text-dim)" }}>You should know first.</span>
        </h2>
        <p style={{ fontSize: 16, color: "var(--text-dim)", maxWidth: 700, lineHeight: 1.65, margin: "0 0 50px" }}>
          Fleet baselines every agent's normal — call volume, tool surface,
          time-of-day. Anomalies trigger immediate gateway action, then a
          Slack ping with full attribution context.
        </p>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }}>
          <div style={{
            border: "1px solid var(--line)",
            borderRadius: 8,
            padding: "20px 22px",
            background: "linear-gradient(180deg, rgba(14,14,16,0.6), rgba(8,8,10,0.9))",
          }}>
            <div className="mono" style={{ fontSize: 10, letterSpacing: "0.22em", color: "var(--text-faint)", textTransform: "uppercase", marginBottom: 12 }}>
              live · agent traffic · release-bot
            </div>
            <SparkBar values={bars} anomalyAt={anomalyAt}/>
            <div className="mono" style={{ display: "flex", justifyContent: "space-between", marginTop: 14, fontSize: 11, color: "var(--text-faint)" }}>
              <span>baseline: 12 calls/min</span>
              <span style={{ color: anomalyAt >= 0 ? "oklch(0.70 0.18 25)" : "var(--text-faint)" }}>
                {anomalyAt >= 0 ? "● spike: 14× detected" : "○ within baseline"}
              </span>
            </div>
            <div style={{
              marginTop: 20,
              borderRadius: 6,
              border: "1px solid " + (anomalyAt >= 0 ? "oklch(0.70 0.18 25 / 0.4)" : "var(--line)"),
              background: anomalyAt >= 0 ? "oklch(0.70 0.18 25 / 0.06)" : "rgba(14,14,16,0.5)",
              padding: "12px 14px",
              transition: "all .4s",
            }}>
              <div className="mono" style={{ fontSize: 11, color: anomalyAt >= 0 ? "oklch(0.70 0.18 25)" : "var(--text-faint)", letterSpacing: "0.12em", marginBottom: 6 }}>
                {anomalyAt >= 0 ? "ACTION TAKEN" : "MONITORING"}
              </div>
              <div className="mono" style={{ fontSize: 12, color: "var(--text)", lineHeight: 1.6 }}>
                {anomalyAt >= 0
                  ? <>Calls blocked at gateway · async Slack ping → <span style={{ color: "var(--amber)" }}>#fleet-alerts</span></>
                  : <>Behavior nominal · last spike 04:12 ago</>}
              </div>
            </div>
          </div>

          <div style={{
            border: "1px solid var(--line)",
            borderRadius: 8,
            padding: "20px 22px",
            background: "linear-gradient(180deg, rgba(14,14,16,0.6), rgba(8,8,10,0.9))",
          }}>
            <div className="mono" style={{ fontSize: 10, letterSpacing: "0.22em", color: "var(--text-faint)", textTransform: "uppercase", marginBottom: 12 }}>
              anomaly feed
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {events.map((e) => (
                <div key={e.id} className="mono" style={{
                  border: "1px solid " + (e.tone === "risk" ? "oklch(0.70 0.18 25 / 0.3)" : "var(--line)"),
                  borderLeft: `3px solid ${toneColor(e.tone)}`,
                  background: "rgba(14,14,16,0.7)",
                  borderRadius: 4,
                  padding: "10px 12px",
                  fontSize: 12,
                  lineHeight: 1.55,
                  animation: "slideIn .4s ease",
                }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                    <span style={{ color: toneColor(e.tone), fontWeight: 600, letterSpacing: "0.08em" }}>{e.kind}</span>
                    <span style={{ color: "var(--text-faint)", fontSize: 10 }}>{e.ts}</span>
                  </div>
                  <div style={{ color: "var(--text)", marginTop: 2 }}>
                    <span style={{ color: "var(--text-dim)" }}>agent:</span> {e.agent} · {e.desc}
                  </div>
                  <div style={{ color: "var(--text-faint)", fontSize: 11, marginTop: 2 }}>
                    → {e.action}
                  </div>
                </div>
              ))}
            </div>
            <style>{`@keyframes slideIn { from{opacity:0;transform:translateY(-6px)} to{opacity:1;transform:translateY(0)} }`}</style>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { BehaviorSection });
