"use client";

import { useEffect, useState } from "react";
import { usePathname } from "next/navigation";

/** Live worker liveness in the masthead — polls /api/worker (heartbeat recency). */
export function WorkerStatus() {
  const [online, setOnline] = useState<boolean | null>(null);
  const pathname = usePathname();
  const onLogin = pathname === "/login";

  useEffect(() => {
    if (onLogin) return; // don't poll (would 401) on the login screen
    let alive = true;
    async function check() {
      try {
        const d = await (await fetch("/api/worker")).json();
        if (alive) setOnline(!!d.online);
      } catch {
        if (alive) setOnline(false);
      }
    }
    check();
    const id = setInterval(check, 10000);
    return () => {
      alive = false;
      clearInterval(id);
    };
  }, [onLogin]);

  if (onLogin) return null;
  const label = online === null ? "…" : online ? "listening" : "offline";
  return (
    <div className={`worker-status${online === false ? " off" : ""}`}>
      <span className="live-dot" />
      Worker · {label}
    </div>
  );
}
