import store from "./store";
import { $themeConfig } from "./theme.config";

export default {
    init() {
        // Cork / versiones antiguas guardaban "en" por fallback o plantilla; era el idioma por defecto erróneo.
        const enResetKey = "i18n_reset_accidental_en_v1";
        if (localStorage.getItem("i18n_locale") === "en" && !localStorage.getItem(enResetKey)) {
            localStorage.removeItem("i18n_locale");
            localStorage.setItem(enResetKey, "1");
        }

        // set default styles
        let val = localStorage.getItem("dark_mode"); // light, dark, system
        if (!val) {
            val = $themeConfig.theme;
        }
        store.commit("toggleDarkMode", val);

        val = localStorage.getItem("menu_style"); // vertical, collapsible-vertical, horizontal
        if (!val) {
            val = $themeConfig.navigation;
        }
        store.commit("toggleMenuStyle", val);

        val = localStorage.getItem("layout_style"); // full, boxed-layout, large-boxed-layout
        if (!val) {
            val = $themeConfig.layout;
        }
        store.commit("toggleLayoutStyle", val);

        const savedLocale = localStorage.getItem("i18n_locale"); // en, da, de, el, es, …
        if (!savedLocale || savedLocale !== "es") {
            this.toggleLanguage(store.state.countryList.find((i) => i.code === "es"));
        } else {
            this.toggleLanguage();
        }
    },

    toggleLanguage(item) {
        const lang =
            store.state.countryList.find((d) => d.code === "es") ||
            item ||
            store.state.countryList.find((d) => d.code === $themeConfig.lang);

        store.commit("toggleLocale", "es");
        return lang;
    },

    toggleMode(mode) {
        if (!mode) {
            let val = localStorage.getItem("dark_mode"); //light|dark|system
            mode = val;
            if (!val) {
                mode = "light";
            }
        }
        store.commit("toggleDarkMode", mode || "light");
        return mode;
    },
};
