import './bootstrap';
import { createApp } from "vue";
import { createPinia } from "pinia";
import PerfectScrollbar from "vue3-perfect-scrollbar";
import App from "./main/views/App.vue";
import routes from "./main/router";
import { setupI18n, loadInitialTranslations, loadRemainingLanguages } from "./common/i18n";
import { useAuthStore } from "./main/store/authStore";
import { useModulesMenuStore } from "./main/store/modulesMenu";
import installAntDesign from './ant-design';
import installGlobalComponents from './global-components';

async function startApp() {
    const app = createApp(App);
    const pinia = createPinia();
    app.use(pinia);

    const authStore = useAuthStore();
    const menuStore = useModulesMenuStore();
    window.__modulesMenuStore = menuStore;

    // Fetch app settings first to get company's default language
    let defaultLang = authStore.lang;
    try {
        const appResponse = await axiosAdmin.get("/app");
        if (appResponse.data.app) {
            authStore.updateApp(appResponse.data.app);
            authStore.updateAddMenus(appResponse.data.shortcut_menus?.credentials || []);
            authStore.updateEmailVerifiedSetting(appResponse.data.email_setting_verified);
            authStore.updateEmailVariables(appResponse.data.email_variables);

            // Use company's default language if user hasn't selected one yet
            const storedLang = window.localStorage.getItem('selected_lang');
            if (!storedLang && appResponse.data.app.lang?.key) {
                defaultLang = appResponse.data.app.lang.key;
                authStore.updateLang(defaultLang);
            }
        }
    } catch (error) {
        console.error('Failed to fetch app settings:', error);
    }

    const i18n = setupI18n({
        legacy: false,
        globalInjection: true,
        locale: defaultLang,
        warnHtmlMessage: false,
    });
    await loadInitialTranslations(i18n, defaultLang);

    if (authStore.isLoggedIn) {
        authStore.updateUserAction();
        authStore.fetchAllBusinessesAction();
    }

    authStore.updateGlobalSettingAction();
    authStore.updateAllLangsAction();
    authStore.updateActiveModules(window.config.modules);
    authStore.updateVisibleSubscriptionModulesAction();

    app.use(i18n);
    app.use(PerfectScrollbar);
    
    installAntDesign(app);
    installGlobalComponents(app);

    app.use(routes);

    window.i18n = i18n;
    window.__app = app;
    window.__appRouter = routes;

    routes.isReady().then(() => {
        app.mount("#app");

        // Load remaining languages in the background after app is mounted
        loadRemainingLanguages(i18n);
    });
}

startApp();
