import { useSyncExternalStore } from "react";
import { readCssSections, type CssSection } from "./read-css-tokens";

// 선언 원문을 읽어 결과가 테마·뷰포트에 무관하므로 한 번만 읽어 캐시한다.
// getSnapshot이 매 렌더 호출되므로 매번 새 배열을 돌려주면 무한 루프가 된다.
let cached: CssSection[] | null = null;

function subscribe(): () => void {
  return () => {};
}

function getSnapshot(): CssSection[] | null {
  cached ??= readCssSections();
  return cached;
}

function getServerSnapshot(): CssSection[] | null {
  return null;
}

/** 서버 렌더·하이드레이션 첫 렌더에서는 `null`. */
export function useCssTokens(): CssSection[] | null {
  return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
}
