"use client";

import { useEffect, useState } from "react";
import { Activity, AlertCircle } from "lucide-react";
import { checkHealth } from "@/lib/api";

/**
 * Tiny live ping that surfaces whether the Rust ui-server is reachable.
 *
 * Sits in the bottom status bar so the user always knows if Simulate will
 * work before clicking it. Polls every 15s + once immediately on focus regain.
 */
export default function ApiHealthIndicator() {
  const [status, setStatus] = useState<"ok" | "down" | "checking">("checking");

  useEffect(() => {
    let active = true;
    let timer: ReturnType<typeof setInterval> | null = null;

    const ping = async () => {
      const ok = await checkHealth();
      if (active) setStatus(ok ? "ok" : "down");
    };

    ping();
    timer = setInterval(ping, 15000);

    const onFocus = () => ping();
    window.addEventListener("focus", onFocus);

    return () => {
      active = false;
      if (timer) clearInterval(timer);
      window.removeEventListener("focus", onFocus);
    };
  }, []);

  if (status === "ok") {
    return (
      <span
        className="flex items-center gap-1.5 rounded bg-emerald-500/15 px-2 py-0.5 text-[10.5px] font-semibold text-emerald-700"
        title="Rust ui-server is reachable on :3030 — Simulate will work"
      >
        <Activity size={11} className="text-emerald-600" />
        API ready
      </span>
    );
  }
  if (status === "down") {
    return (
      <span
        className="flex items-center gap-1.5 rounded bg-red-500/15 px-2 py-0.5 text-[10.5px] font-semibold text-red-700"
        title="Rust ui-server is DOWN — run: cargo run -p entropyk-demo --bin ui-server"
      >
        <AlertCircle size={11} className="text-red-600" />
        API down — run ui-server
      </span>
    );
  }
  return (
    <span className="flex items-center gap-1.5 rounded bg-[var(--chrome-2)] px-2 py-0.5 text-[10.5px] text-[var(--ink-faint)]">
      <Activity size={11} className="animate-pulse" />
      Checking…
    </span>
  );
}
