"use client";

import { useEffect, useState } from "react";
import { usePollWhileVisible } from "@/lib/usePollWhileVisible";

export interface VitalsAgent { ok: boolean; version?: string }
export interface VitalsOpenclaw {
  ok: boolean;
  busy?: boolean;
  degraded?: boolean;
  sessions?: number;
  agents?: string[];
}
export interface VitalsHermes { ok: boolean; model?: string; provider?: string }
export interface VitalsData {
  claude?: VitalsAgent;
  openclaw?: VitalsOpenclaw;
  hermes?: VitalsHermes;
  antigravity?: VitalsAgent;
}
export interface TokensData {
  grand?: { totalTokens: number; todayTokens: number; todayCalls: number; costUsd: number };
}

export interface HomeStats {
  vitals: VitalsData | null;
  tokens: TokensData | null;
  userName: string | null;
  agentsOnline: number | null;
  tasksToday: number | null;
}

const POLL_MS = 12000;

// useHomeStats — the live numbers both home layouts share: vitals + token
// usage polled while the tab is visible, and the operator name from server
// config. Any endpoint may be down on a fresh install; consumers must render
// "—" for nulls, never crash.
export function useHomeStats(): HomeStats {
  const [vitals, setVitals] = useState<VitalsData | null>(null);
  const [tokens, setTokens] = useState<TokensData | null>(null);
  const [userName, setUserName] = useState<string | null>(null);

  // userName comes from server config (setup-status returns it alongside checks).
  useEffect(() => {
    let cancelled = false;
    fetch("/api/home/setup-status", { cache: "no-store" })
      .then((r) => r.json())
      .then((j) => { if (!cancelled && typeof j?.userName === "string" && j.userName) setUserName(j.userName); })
      .catch(() => { /* fallback name stays */ });
    return () => { cancelled = true; };
  }, []);

  // Live cockpit numbers — pause when the tab is hidden.
  usePollWhileVisible(async () => {
    const [v, t] = await Promise.allSettled([
      fetch("/api/vitals", { cache: "no-store" }).then((r) => r.json()),
      fetch("/api/tokens", { cache: "no-store" }).then((r) => r.json()),
    ]);
    if (v.status === "fulfilled" && v.value) setVitals(v.value as VitalsData);
    if (t.status === "fulfilled" && t.value) setTokens(t.value as TokensData);
  }, POLL_MS);

  const agentsOnline = vitals
    ? [vitals.claude?.ok, vitals.openclaw?.ok, vitals.hermes?.ok, vitals.antigravity?.ok].filter(Boolean).length
    : null;
  const tasksToday = tokens?.grand?.todayCalls ?? null;

  return { vitals, tokens, userName, agentsOnline, tasksToday };
}
