// Fleet scan terminal — types out a live `aurek fleet scan` command output.
// The most viscerally compelling section. Stats animate in sequentially.
const { useState: useStateFL, useEffect: useEffectFL, useRef: useRefFL } = React;

function useTypedSequence(steps, startDelay = 200) {
  // steps: array of {ms, action: () => void}
  useEffectFL(() => {
    let cancelled = false;
    let timeout;
    let i = 0;
    function next() {
      if (cancelled || i >= steps.length) return;
      const s = steps[i++];
      timeout = setTimeout(() => {
        s.action();
        next();
      }, s.ms);
    }
    timeout = setTimeout(next, startDelay);
    return () => { cancelled = true; clearTimeout(timeout); };
  }, []);
}

function CountUp({ to, ms = 1200, suffix = "", color = "var(--text)" }) {
  const [n, setN] = useStateFL(0);
  useEffectFL(() => {
    const start = performance.now();
    let raf;
    function tick(now) {
      const t = Math.min(1, (now - start) / ms);
      const eased = 1 - Math.pow(1 - t, 3);
      setN(Math.round(to * eased));
      if (t < 1) raf = requestAnimationFrame(tick);
    }
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [to, ms]);
  return <span style={{ color }}>{n}{suffix}</span>;
}

function FleetScanTerminal() {
  const [phase, setPhase] = useStateFL(0); // 0..7
  useTypedSequence([
    { ms: 0,    action: () => setPhase(1) }, // typing
    { ms: 700,  action: () => setPhase(2) }, // scanning networks
    { ms: 900,  action: () => setPhase(3) }, // detected
    { ms: 700,  action: () => setPhase(4) }, // registered
    { ms: 600,  action: () => setPhase(5) }, // unregistered
    { ms: 800,  action: () => setPhase(6) }, // risky
    { ms: 800,  action: () => setPhase(7) }, // posture
  ]);

  return (
    <div style={{
      border: "1px solid var(--line)",
      borderRadius: 8,
      background: "linear-gradient(180deg, rgba(8,8,10,0.95), rgba(4,4,5,0.98))",
      overflow: "hidden",
      fontFamily: "JetBrains Mono, monospace",
    }}>
      <div style={{
        padding: "10px 14px",
        borderBottom: "1px solid var(--line)",
        display: "flex",
        alignItems: "center",
        gap: 10,
        fontSize: 11,
        color: "var(--text-faint)",
        letterSpacing: "0.1em",
      }}>
        <span style={{ width: 10, height: 10, borderRadius: "50%", background: "#ff5f57" }}/>
        <span style={{ width: 10, height: 10, borderRadius: "50%", background: "#febc2e" }}/>
        <span style={{ width: 10, height: 10, borderRadius: "50%", background: "#28c840" }}/>
        <span style={{ marginLeft: 14, textTransform: "uppercase", letterSpacing: "0.22em" }}>
          aurek fleet scan
        </span>
        <span style={{ marginLeft: "auto", color: "oklch(0.80 0.14 145)", 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 6px oklch(0.80 0.14 145 / 0.8)" }}/>
          live
        </span>
      </div>

      <div style={{ padding: "20px 22px 22px", fontSize: 13, lineHeight: 1.85 }}>
        {/* Command */}
        <div>
          <span style={{ color: "var(--amber)" }}>$</span>{" "}
          <span style={{ color: "var(--text)" }}>aurek fleet scan</span>{" "}
          <span style={{ color: "var(--text-dim)" }}>--org acme --depth full</span>
          {phase === 1 && <span style={{ color: "var(--amber)", animation: "blink 1s steps(2) infinite" }}>▍</span>}
        </div>

        {phase >= 2 && (
          <div style={{ marginTop: 14, color: "var(--text-dim)", fontSize: 12 }}>
            <div>→ scanning subnets, k8s namespaces, ci/cd hosts...</div>
            <div>→ querying iam role assumptions, llm api keys...</div>
            <div>→ fingerprinting frameworks (langchain, crewai, custom)...</div>
          </div>
        )}

        {phase >= 3 && (
          <div style={{ marginTop: 22, display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14 }}>
            <StatBlock
              label="agents detected"
              value={<CountUp to={47} color="var(--text)"/>}
              tone="neutral"
              show
            />
            <StatBlock
              label="registered"
              value={<CountUp to={39} color="oklch(0.80 0.14 145)"/>}
              tone="ok"
              show={phase >= 4}
            />
            <StatBlock
              label="unregistered"
              value={<CountUp to={8} color="var(--amber)"/>}
              tone="warn"
              show={phase >= 5}
            />
            <StatBlock
              label="prod-write access"
              value={<CountUp to={3} color="oklch(0.70 0.18 25)"/>}
              tone="risk"
              show={phase >= 6}
            />
          </div>
        )}

        {phase >= 7 && (
          <div style={{
            marginTop: 22,
            border: "1px solid oklch(0.70 0.18 25 / 0.4)",
            borderRadius: 6,
            padding: "14px 16px",
            background: "linear-gradient(90deg, oklch(0.70 0.18 25 / 0.08), transparent)",
            opacity: 0,
            animation: "fadeUp .5s ease forwards",
          }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
              <span style={{ fontSize: 11, letterSpacing: "0.18em", color: "var(--text-faint)", textTransform: "uppercase" }}>
                fleet posture report
              </span>
              <span style={{ fontSize: 10, color: "var(--text-faint)" }}>generated 14:22:08 UTC</span>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 18 }}>
              <PostureCell label="Posture score" value="7.2 / 10" sub="↓ 0.4 vs last week" tone="warn" bar={0.72}/>
              <PostureCell label="EU AI Act readiness" value="HIGH RISK" sub="3 unregistered prod-writers" tone="risk"/>
              <PostureCell label="OWASP agentic coverage" value="84%" sub="3 of 19 categories failing" tone="warn" bar={0.84}/>
            </div>
            <div style={{ marginTop: 14, fontSize: 12, color: "var(--text-dim)", lineHeight: 1.6 }}>
              <div style={{ color: "oklch(0.70 0.18 25)" }}>
                ⚠ <span style={{ color: "var(--text)" }}>release-bot-v2</span> · <span style={{ color: "var(--text-faint)" }}>unregistered</span> · last seen pushing to <span style={{ color: "var(--text)" }}>postgres.prod</span> 4m ago
              </div>
              <div style={{ color: "oklch(0.70 0.18 25)" }}>
                ⚠ <span style={{ color: "var(--text)" }}>analyst-shadow</span> · <span style={{ color: "var(--text-faint)" }}>unregistered</span> · 2.4M tokens / day · no policy
              </div>
              <div style={{ color: "var(--amber)" }}>
                ⚡ <span style={{ color: "var(--text)" }}>deploy-agent</span> · drift detected: tool surface +6 since baseline
              </div>
            </div>
            <div style={{ marginTop: 14, display: "flex", gap: 10, fontSize: 11 }}>
              <span style={{ padding: "5px 10px", border: "1px solid var(--amber)", color: "var(--amber)", borderRadius: 3, letterSpacing: "0.1em" }}>
                aurek fleet enforce →
              </span>
              <span style={{ padding: "5px 10px", border: "1px solid var(--line-strong)", color: "var(--text-dim)", borderRadius: 3, letterSpacing: "0.1em" }}>
                export report.pdf
              </span>
            </div>
          </div>
        )}
      </div>
      <style>{`
        @keyframes blink { 50% { opacity: 0; } }
        @keyframes fadeUp { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0);} }
      `}</style>
    </div>
  );
}

function StatBlock({ label, value, tone, show }) {
  const color = tone === "ok" ? "oklch(0.80 0.14 145 / 0.4)" :
                tone === "warn" ? "oklch(0.82 0.14 75 / 0.5)" :
                tone === "risk" ? "oklch(0.70 0.18 25 / 0.5)" :
                "var(--line-strong)";
  return (
    <div style={{
      border: "1px solid " + color,
      borderRadius: 6,
      padding: "14px 14px",
      background: "rgba(14,14,16,0.6)",
      opacity: show ? 1 : 0,
      transform: show ? "translateY(0)" : "translateY(6px)",
      transition: "all .4s ease",
    }}>
      <div style={{ fontSize: 10, letterSpacing: "0.18em", color: "var(--text-faint)", textTransform: "uppercase", marginBottom: 6 }}>
        {label}
      </div>
      <div style={{ fontSize: 30, fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>
        {show ? value : "—"}
      </div>
    </div>
  );
}

function PostureCell({ label, value, sub, tone, bar }) {
  const color = tone === "risk" ? "oklch(0.70 0.18 25)" : "var(--amber)";
  return (
    <div>
      <div style={{ fontSize: 10, letterSpacing: "0.18em", color: "var(--text-faint)", textTransform: "uppercase", marginBottom: 6 }}>
        {label}
      </div>
      <div style={{ fontSize: 18, color, fontWeight: 600 }}>{value}</div>
      <div style={{ fontSize: 11, color: "var(--text-faint)", marginTop: 2 }}>{sub}</div>
      {bar != null && (
        <div style={{ height: 3, marginTop: 8, borderRadius: 2, background: "rgba(255,255,255,0.08)", overflow: "hidden" }}>
          <div style={{ height: "100%", width: (bar * 100) + "%", background: color, transition: "width 1s" }}/>
        </div>
      )}
    </div>
  );
}

function FleetSection() {
  return (
    <section id="fleet" style={{ padding: "120px 28px", borderBottom: "1px solid var(--line)", position: "relative" }}>
      <div style={{ maxWidth: 1200, margin: "0 auto" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1.4fr", gap: 60, alignItems: "start" }}>
          <div>
            <div className="mono" style={{ fontSize: 10, letterSpacing: "0.3em", color: "var(--text-faint)", textTransform: "uppercase", marginBottom: 16 }}>
              ▸ Aurek Fleet
            </div>
            <h2 style={{ fontSize: 44, margin: "0 0 18px", letterSpacing: "-0.02em", fontWeight: 600, lineHeight: 1.08 }}>
              You can't govern<br/>what you can't see.
            </h2>
            <p style={{ fontSize: 16, color: "var(--text-dim)", lineHeight: 1.65, margin: "0 0 24px" }}>
              Most orgs underestimate their agent footprint by 3–5×. Fleet
              scans your subnets, your IaC, your IAM, and your LLM gateway
              keys to build a complete inventory — registered or not — and
              scores it against the frameworks regulators care about.
            </p>
            <ul style={{ listStyle: "none", padding: 0, margin: 0 }}>
              {[
                "Agent discovery via passive + active scanning",
                "Posture scoring against OWASP / EU AI Act / NIST",
                "Behavioral baselines and drift detection",
                "Block unregistered agents from production",
              ].map((x) => (
                <li key={x} className="mono" style={{ fontSize: 13, padding: "10px 0", borderBottom: "1px dashed var(--line)", color: "var(--text-dim)", display: "flex", gap: 10 }}>
                  <span style={{ color: "var(--amber)" }}>›</span>{x}
                </li>
              ))}
            </ul>
          </div>
          <FleetScanTerminal/>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { FleetSection, FleetScanTerminal });
