import {
    Platform
} from "react-native";
import Navigation from "./navigation";
import defaultLocaleJSON from "./variants/locales/default.json";
import defaultThemeJSON from "./variants/themes/default.json";
import {
    type NCoreUIKitConfig,
    setupNCoreUIKit,
    Host
} from "ncore-ui-kit";
import {
    useFonts
} from "expo-font";
import "moment/locale/tr";
import moment from "moment";

if (Platform.OS === "web" && typeof window !== "undefined") {
    window.addEventListener("error", (e) => {
        if (
            e.message === "ResizeObserver loop limit exceeded" ||
            e.message === "ResizeObserver loop completed with undelivered notifications."
        ) {
            e.stopImmediatePropagation();
        }
    });
}

let NCoreConfig: NCoreUIKitConfig = {
    projectThemes: defaultThemeJSON as NCoreUIKit.Palette,
    initialSelectedGapPropagation: "spacious",
    projectLocales: defaultLocaleJSON,
    initialSelectedPalette: "nibgat",
    initialSelectedTheme: "light"
};

const themeStorage = Platform.OS === "web" ? window.localStorage.getItem("theme") : null;

if(themeStorage) {
    const parsedThemeStorage = JSON.parse(themeStorage);

    NCoreConfig = {
        ...NCoreConfig,
        initialSelectedGapPropagation: parsedThemeStorage.activeGapPropagation,
        initialSelectedActiveSharpness: parsedThemeStorage.activeSharpness,
        initialSelectedTheme: parsedThemeStorage.activeTheme
    };
}

const localeStorage = Platform.OS === "web" ? window.localStorage.getItem("locale") : null;

if(localeStorage) {
    const parsedLocaleStorage = JSON.parse(localeStorage);

    NCoreConfig = {
        ...NCoreConfig,
        initialSelectedLocale: parsedLocaleStorage.activeLocale
    };
}

if (Platform.OS === "web") {
    const urlParams = new URLSearchParams(window.location.search);
    const langParam = urlParams.get("lang");

    if (langParam) {
        const isValidLocale = defaultLocaleJSON.some(item => item.locale === langParam);

        if (isValidLocale) {
            NCoreConfig.initialSelectedLocale = langParam as keyof NCoreUIKit.LocaleKey;
        }
    }

    if (!NCoreConfig.initialSelectedLocale) {
        const browserLang = window.navigator.language || "";

        const exactMatch = defaultLocaleJSON.find(item => item.locale === browserLang);

        if (exactMatch) {
            NCoreConfig.initialSelectedLocale = exactMatch.locale as keyof NCoreUIKit.LocaleKey;
        } else {
            const primaryLang = (browserLang.split(/[-_]/)[0] || "").toLowerCase();

            const similarMatch = defaultLocaleJSON.find(item =>
                item.locale.toLowerCase() === primaryLang ||
                item.locale.toLowerCase().startsWith(`${primaryLang}-`)
            );

            if (similarMatch) {
                NCoreConfig.initialSelectedLocale = similarMatch.locale as keyof NCoreUIKit.LocaleKey;
            } else {
                NCoreConfig.initialSelectedLocale = (primaryLang === "tr" ? "tr-TR" : "en-US") as keyof NCoreUIKit.LocaleKey;
            }
        }
    }
}

const NCoreUIKitBase = setupNCoreUIKit(NCoreConfig);

moment.locale("tr");

const App = () => {
    return <Navigation/>;
};

const isExpo = typeof globalThis !== "undefined" && ("__expo" in globalThis || "Expo" in globalThis);

const ContextAPI = () => {
    if(isExpo) {
        /* eslint-disable @typescript-eslint/no-require-imports */
        const [loaded] = useFonts({
            "Geist-ExtraLight": require("./assets/fonts/Geist-ExtraLight.ttf"),
            "Geist-ExtraBold": require("./assets/fonts/Geist-ExtraBold.ttf"),
            "Geist-SemiBold": require("./assets/fonts/Geist-SemiBold.ttf"),
            "Geist-Regular": require("./assets/fonts/Geist-Regular.ttf"),
            "Geist-Medium": require("./assets/fonts/Geist-Medium.ttf"),
            "Geist-Black": require("./assets/fonts/Geist-Black.ttf"),
            "Geist-Light": require("./assets/fonts/Geist-Light.ttf"),
            "Geist-Bold": require("./assets/fonts/Geist-Bold.ttf"),
            "Geist-Thin": require("./assets/fonts/Geist-Thin.ttf")
        });

        if (!loaded) return null;
    }

    return <NCoreUIKitBase.Provider>
        <Host
            name="main-header"
        >
            <App/>
        </Host>
    </NCoreUIKitBase.Provider>;
};
export default ContextAPI;
