"use client";

import { useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { publicApi } from "@/lib/api/client";
import { useAuthStore } from "@/lib/store/auth-store";
import { setCmsCache, type CmsField } from "@/lib/hooks/use-translation";

/**
 * CmsProvider — loads global CMS sections (TOAST, VALIDATION, COMMON, STATUS_LABELS)
 * into a global cache so that tToast() and zMsg() work outside React components.
 *
 * Mount this once near the root of your app (e.g., in layout.tsx).
 */
const GLOBAL_SECTIONS = ["TOAST", "VALIDATION", "COMMON", "STATUS_LABELS"];

export function CmsProvider({ children }: { children: React.ReactNode }) {
  const language = useAuthStore((s) => s.language);

  const { data } = useQuery<Record<string, CmsField[]>>({
    queryKey: ["cms-global", ...GLOBAL_SECTIONS],
    queryFn: async () => {
      const res = await publicApi.cmsBulk(GLOBAL_SECTIONS);
      return res.data ?? {};
    },
    staleTime: 10 * 60 * 1000,
  });

  // Sync to global cache whenever data or language changes
  useEffect(() => {
    if (data) {
      setCmsCache(data, language);
    }
  }, [data, language]);

  return <>{children}</>;
}
