"use client";

import {
  createContext,
  useContext,
  useEffect,
  useState,
  type ReactNode,
} from "react";
import { createElement } from "react";
import type { CountryConfigResponse } from "../api-types";
import { api } from "../api-client";

interface AppConfigContextValue {
  config: CountryConfigResponse | null;
  loading: boolean;
}

const AppConfigContext = createContext<AppConfigContextValue>({
  config: null,
  loading: true,
});

export function AppConfigProvider({ children }: { children: ReactNode }) {
  const [config, setConfig] = useState<CountryConfigResponse | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    api.config
      .getCountry("UZ")
      .then(setConfig)
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  return createElement(
    AppConfigContext.Provider,
    { value: { config, loading } },
    children,
  );
}

export function useAppConfig() {
  return useContext(AppConfigContext);
}
