import { useEffect, type ReactNode } from "react";
import { useQuery } from "@tanstack/react-query";

import { api } from "../api/client";
import { keys } from "../api/query-keys";
import i18n, { LOCALE_KEY } from "../i18n";
import { ConfigContext, DEFAULTS, type ConfigView } from "./config-context";

export function ConfigProvider({ children }: { children: ReactNode }) {
  const { data } = useQuery({
    queryKey: keys.config(),
    queryFn: async (): Promise<ConfigView> => {
      const { data, error } = await api.GET("/api/config");

      if (error || !data) throw new Error("failed to load config");

      return data;
    },
    staleTime: Infinity,
  });

  // Default the UI language to the instance default, unless the user has chosen one for
  // this browser (LangSwitch persists to localStorage[LOCALE_KEY]).
  useEffect(() => {
    if (data && !localStorage.getItem(LOCALE_KEY)) {
      void i18n.changeLanguage(data.default_language);
    }
  }, [data]);

  return <ConfigContext.Provider value={data ?? DEFAULTS}>{children}</ConfigContext.Provider>;
}
