import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react"; import { fetchJson } from "@/lib/api"; export type YouTubeLiveEntry = { is_live?: boolean; live_url?: string; title?: string; channel_id?: string; source?: string; error?: string; }; export type YouTubeLiveMap = { ok?: boolean; checked_at?: number; live_count?: number; source?: string; entries?: Record; svc_error?: string; }; const YouTubeLiveContext = createContext<{ map: YouTubeLiveMap | null; loading: boolean; refresh: () => Promise; }>({ map: null, loading: false, refresh: async () => {}, }); export function groupLiveRef(groupId: string) { return `group:${groupId}`; } export function shortsLiveRef(channelPk: string) { return `shorts:${channelPk}`; } export function channelLiveRef(channelId: string) { return `channel:${channelId}`; } export function useYouTubeLiveProviderValue(intervalMs = 30000) { const [map, setMap] = useState(null); const [loading, setLoading] = useState(false); const [focused, setFocused] = useState(true); useEffect(() => { const unsub = window.desktop?.onWindowFocus?.((f) => setFocused(f)); const onVis = () => setFocused(document.visibilityState === "visible"); document.addEventListener("visibilitychange", onVis); return () => { unsub?.(); document.removeEventListener("visibilitychange", onVis); }; }, []); const refresh = useCallback(async (silent = false) => { if (!silent) setLoading(true); try { const data = (await fetchJson("/api/youtube/live-map")) as YouTubeLiveMap; setMap(data); } catch { /* keep last map */ } finally { if (!silent) setLoading(false); } }, []); useEffect(() => { void refresh(true); const ms = focused ? intervalMs : Math.max(intervalMs * 3, 45000); const id = window.setInterval(() => void refresh(true), ms); const onVis = () => { if (document.visibilityState === "visible") void refresh(true); }; document.addEventListener("visibilitychange", onVis); return () => { window.clearInterval(id); document.removeEventListener("visibilitychange", onVis); }; }, [intervalMs, refresh, focused]); return useMemo( () => ({ map, loading, refresh: () => refresh(false), }), [map, loading, refresh], ); } export const YouTubeLiveContextProvider = YouTubeLiveContext.Provider; export function useYouTubeLiveMap() { return useContext(YouTubeLiveContext); } export function useYouTubeLiveEntry(refKey?: string): YouTubeLiveEntry | null { const { map } = useYouTubeLiveMap(); if (!refKey) return null; return map?.entries?.[refKey] ?? null; } export function useYouTubeLiveCount() { const { map } = useYouTubeLiveMap(); return Number(map?.live_count || 0); }