"use strict";
const jsxRuntime = require("./jsx-runtime-B6vEU3CM.js");
const React = require("react");
const reactI18next = require("react-i18next");
const pathname_rental = require("./pathname.rental-C9fm1WTq.js");
const common = require("./common-B47boGYI.js");
const api = require("./api-BygscvSz.js");
const apiConfig = require("./api-config-DXwDMFn-.js");
const useAuth = require("./useAuth-vPRkzGjO.js");
const FALLBACK_LANGUAGES = [
  "en",
  // English as primary fallback
  "en-US",
  // US English as secondary
  pathname_rental.DEFAULT_LANG
  // Then default language
];
const createEnglishFallback = () => ({
  code: "en",
  label: "English",
  direction: "ltr"
});
const initialState = {
  languages: [],
  currentLanguage: null,
  isLoading: false,
  error: null,
  isFallbackActive: false
};
const findBestAvailableLanguage = (languages, preferredCode) => {
  if (!languages || languages.length === 0) return null;
  if (preferredCode) {
    const preferred = languages.find((lang) => lang.code === preferredCode);
    if (preferred) return preferred;
  }
  for (const fallbackCode of FALLBACK_LANGUAGES) {
    const fallback = languages.find((lang) => lang.code === fallbackCode);
    if (fallback) return fallback;
  }
  return languages[0] || null;
};
const languageReducer = (state, action) => {
  switch (action.type) {
    case "FETCH_LANGUAGES_START":
      return {
        ...state,
        isLoading: true,
        error: null
      };
    case "FETCH_LANGUAGES_SUCCESS":
      return {
        ...state,
        languages: action.payload,
        isLoading: false,
        error: null,
        isFallbackActive: false
      };
    case "FETCH_LANGUAGES_ERROR":
      return {
        ...state,
        isLoading: false,
        error: action.payload,
        isFallbackActive: true
      };
    case "SET_CURRENT_LANGUAGE":
      return {
        ...state,
        currentLanguage: action.payload,
        isFallbackActive: action.isFallback || false
      };
    case "SET_FALLBACK_ACTIVE":
      return {
        ...state,
        isFallbackActive: action.payload
      };
    default:
      return state;
  }
};
const LanguageContext = React.createContext(void 0);
const LanguageProvider = ({ children }) => {
  const [state, dispatch] = React.useReducer(languageReducer, initialState);
  const { i18n } = reactI18next.useTranslation();
  const { user, loading } = useAuth.useAuth();
  React.useEffect(() => {
    if (apiConfig.isApiConfigInitialized()) {
      api.setBaseUrl$1(`${apiConfig.getApiConfig().backendBaseUrl}/rbac`);
    }
  }, []);
  const safeChangeLanguage = async (langCode) => {
    if (i18n && typeof i18n.changeLanguage === "function") {
      try {
        await i18n.changeLanguage(langCode);
      } catch (error) {
        console.warn(`Failed to change language to "${langCode}"`, error);
      }
    } else {
      console.warn(
        "i18n.changeLanguage is unavailable. Ensure I18nextProvider is configured in the host application."
      );
    }
  };
  const applyLanguageSettings = (language) => {
    document.body.dir = language.direction || "ltr";
    safeChangeLanguage(language.code);
    localStorage.setItem("_language", language.code);
  };
  const fetchLanguages = async () => {
    var _a, _b;
    try {
      dispatch({ type: "FETCH_LANGUAGES_START" });
      const response = await api.getV1Languages({
        order: `id:1`,
        filters: `(is_active.in=[1])`,
        ...common.getToken()
      });
      const data = ((_a = response == null ? void 0 : response.data) == null ? void 0 : _a.languages) || [];
      const languages = (_b = data == null ? void 0 : data.filter((d) => d == null ? void 0 : d.is_active)) == null ? void 0 : _b.map((d) => ({
        label: d == null ? void 0 : d.name,
        code: d == null ? void 0 : d.code,
        direction: d == null ? void 0 : d.direction
      }));
      const hasEnglish = languages.some((lang) => lang.code === "en");
      if (!hasEnglish) {
        languages.unshift(createEnglishFallback());
      }
      dispatch({ type: "FETCH_LANGUAGES_SUCCESS", payload: languages });
      const savedLangCode = localStorage.getItem("_language");
      const bestLanguage = findBestAvailableLanguage(languages, savedLangCode || void 0);
      if (bestLanguage) {
        const isFallback = savedLangCode && savedLangCode !== bestLanguage.code;
        dispatch({
          type: "SET_CURRENT_LANGUAGE",
          payload: bestLanguage,
          isFallback
        });
        applyLanguageSettings(bestLanguage);
        if (isFallback) {
          console.warn(`Saved language "${savedLangCode}" not available. Using fallback: "${bestLanguage.code}"`);
        }
      } else {
        console.error("No languages available");
      }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : "Failed to fetch languages";
      dispatch({ type: "FETCH_LANGUAGES_ERROR", payload: errorMessage });
      const englishFallback = createEnglishFallback();
      const fallbackLanguages = [englishFallback];
      dispatch({ type: "FETCH_LANGUAGES_SUCCESS", payload: fallbackLanguages });
      dispatch({
        type: "SET_CURRENT_LANGUAGE",
        payload: englishFallback,
        isFallback: true
      });
      document.body.dir = "ltr";
      safeChangeLanguage("en");
      localStorage.setItem("_language", "en");
      console.warn("Language fetch failed, using English fallback");
    }
  };
  const changeLanguage = (langCode) => {
    const selectedLanguage = state.languages.find((lang) => lang.code === langCode);
    if (selectedLanguage) {
      dispatch({ type: "SET_CURRENT_LANGUAGE", payload: selectedLanguage });
      dispatch({ type: "SET_FALLBACK_ACTIVE", payload: false });
      applyLanguageSettings(selectedLanguage);
    } else {
      console.error(`Language "${langCode}" not found in available languages`);
      const englishFallback = createEnglishFallback();
      dispatch({
        type: "SET_CURRENT_LANGUAGE",
        payload: englishFallback,
        isFallback: true
      });
      applyLanguageSettings(englishFallback);
    }
  };
  React.useEffect(() => {
    if ((user == null ? void 0 : user.id) && !loading) {
      fetchLanguages();
    }
  }, [user == null ? void 0 : user.id, loading]);
  const contextValue = {
    ...state,
    changeLanguage,
    fetchLanguages
  };
  return /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(LanguageContext.Provider, { value: contextValue, children });
};
exports.LanguageContext = LanguageContext;
exports.LanguageProvider = LanguageProvider;
//# sourceMappingURL=languageContext-pgLo21vX.js.map
