"use client";

import { createContext, ReactNode, useContext, useEffect, useState } from "react";
import { AppSettings, DEFAULT_SETTINGS, fetchSettings } from "./settings";
import { useTranslation } from "@/lib/i18n/LanguageProvider";

interface SettingsContextValue {
  settings: AppSettings;
  loading: boolean;
}

const SettingsContext = createContext<SettingsContextValue | null>(null);

export function SettingsProvider({ children }: { children: ReactNode }) {
  const [settings, setSettings] = useState<AppSettings>(DEFAULT_SETTINGS);
  const [loading, setLoading] = useState(true);
  const { language } = useTranslation();

  useEffect(() => {
    let active = true;
    fetchSettings(language)
      .then((result) => active && setSettings(result))
      .catch(() => {
        // Settings are non-critical for rendering — keep the defaults and
        // fail silently rather than blocking the whole app on this fetch.
      })
      .finally(() => active && setLoading(false));
    return () => {
      active = false;
    };
    // Deliberately re-fetches on language change — paymentInstructions
    // is bilingual now (admin-authored English + optional Urdu), and
    // this is the one setting that actually needs to react live to a
    // switch, matching "must display the correct version based on the
    // user's language."
  }, [language]);

  const value: SettingsContextValue = { settings, loading };

  return <SettingsContext.Provider value={value}>{children}</SettingsContext.Provider>;
}

export function useSettings() {
  const ctx = useContext(SettingsContext);
  if (!ctx) throw new Error("useSettings must be used within SettingsProvider");
  return ctx;
}
