import { useSyncExternalStore } from "react";
import type { SourceStatus } from "@/lib/types";

// Client UI state, not server state: the snapshot exists only as the 202 body of
// POST /api/blocklists/update and no GET can refetch it. Held here so it outlives
// the query cache's gcTime instead of vanishing from an unsubscribed cache entry.
let snapshot: SourceStatus[] | null = null;
const listeners = new Set<() => void>();

function subscribe(listener: () => void): () => void {
	listeners.add(listener);
	return () => listeners.delete(listener);
}

function getSnapshot(): SourceStatus[] | null {
	return snapshot;
}

export function setRefreshStatus(sources: SourceStatus[]): void {
	snapshot = sources;
	for (const listener of listeners) listener();
}

export function clearRefreshStatus(): void {
	snapshot = null;
	for (const listener of listeners) listener();
}

export function useRefreshStatus(): SourceStatus[] | null {
	return useSyncExternalStore(subscribe, getSnapshot);
}
