import { useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { apiPublicPlaybackMode } from "@/lib/nadiAuth";
import { setPlaybackMode } from "@/lib/playbackMode";

/**
 * Fetches the admin's global playback-mode setting from the public endpoint
 * and mirrors it into localStorage, so VideoPlayer's synchronous
 * `getPlaybackMode()` reads the latest value.
 *
 * Runs once on app mount. Cached for 5 minutes to avoid hammering the
 * backend, refetches on window focus so a change in the admin panel
 * propagates to connected devices without requiring an app restart.
 */
export const usePlaybackMode = () => {
  const { data } = useQuery({
    queryKey: ["public", "playback-mode"],
    queryFn: apiPublicPlaybackMode,
    staleTime: 5 * 60 * 1000, // 5 min
    refetchOnWindowFocus: true,
    retry: 1,
  });

  useEffect(() => {
    if (!data) return;
    setPlaybackMode(data.external_player_enabled ? "external" : "internal");
  }, [data]);

  return data;
};
