import { useEffect, useMemo, useState } from "react";
import { apiJson } from "@/utils/api";
import type { MediaMtxPathsListResponse } from "@/types/api";

export function usePathsStatus(pollMs: number) {
  const [data, setData] = useState<MediaMtxPathsListResponse | null>(null);

  useEffect(() => {
    let isMounted = true;
    let t: number | undefined;

    const tick = async () => {
      try {
        const res = await apiJson<MediaMtxPathsListResponse>("/paths", { method: "GET" });
        if (isMounted) setData(res);
      } catch {
        if (isMounted) setData(null);
      } finally {
        t = window.setTimeout(tick, pollMs);
      }
    };

    tick();
    return () => {
      isMounted = false;
      if (t) window.clearTimeout(t);
    };
  }, [pollMs]);

  const readyByName = useMemo(() => {
    const map = new Map<string, boolean>();
    for (const it of data?.items ?? []) {
      map.set(it.name, Boolean(it.ready));
    }
    return map;
  }, [data]);

  return { raw: data, readyByName };
}

