import {createApp} from 'vue';
import App from './App.vue';
import './style.css';
import {VueTelegramPlugin} from 'vue-tg';
import {router} from './router';
import {createPinia} from 'pinia';
import {useSettingsStore} from "@/stores/SettingsStore.js";
import ApplicationError from "@/ApplicationError.vue";
import AppMetaInitializer from "@/utils/AppMetaInitializer.ts";
import {injectYaMetrika} from "@/utils/yaMetrika.js";
import {checkIsUserPrivacyConsented, saveTelegramCustomer} from "@/utils/ftch.js";

import {register} from 'swiper/element/bundle';
import 'swiper/element/bundle';
import 'swiper/css/bundle';
import AppLoading from "@/AppLoading.vue";
import {useProductFiltersStore} from "@/stores/ProductFiltersStore.js";
import {useBlocksStore} from "@/stores/BlocksStore.js";
import {getCssVarOklchRgb} from "@/helpers.js";

import {defaultConfig, plugin} from '@formkit/vue';
import config from './formkit.config.js';

register();

const pinia = createPinia();
const app = createApp(App);
app
    .use(pinia)
    .use(router)
    .use(VueTelegramPlugin)
    .use(plugin, defaultConfig(config))
;

const settings = useSettingsStore();
const blocks = useBlocksStore();

const appLoading = createApp(AppLoading);
appLoading.mount('#app');

function setTelegramUIColors() {
    const daisyUIBgColor = getCssVarOklchRgb('--color-base-100');
    window.Telegram.WebApp.setHeaderColor(daisyUIBgColor);
    window.Telegram.WebApp.setBackgroundColor(daisyUIBgColor);
}

settings.load()
    .then(() => window.Telegram.WebApp.lockOrientation())
    .then(() => {
        if (settings.app_enabled === false) {
            throw new Error('App disabled (maintenance mode)');
        }
    })
    .then(async () => {
        // Сохраняем данные Telegram-пользователя в базу данных
        const userData = window.Telegram?.WebApp?.initDataUnsafe?.user;
        if (userData) {
            try {
                console.debug('[Init] Saving Telegram customer data');
                await saveTelegramCustomer(userData);
                console.debug('[Init] Telegram customer data saved successfully');
            } catch (error) {
                // Не прерываем загрузку приложения, если не удалось сохранить пользователя
                console.warn('[Init] Failed to save Telegram customer data:', error);
            }
        }
    })
    .then(() => {
        (async () => {
            try {
                const response = await checkIsUserPrivacyConsented();
                settings.is_privacy_consented = response?.data?.is_privacy_consented;
                if (settings.is_privacy_consented) {
                    console.info('[Init] Privacy Policy consent given by user.');
                } else {
                    console.info('[Init] Privacy Policy consent NOT given by user.');
                }
            } catch (error) {
                console.error('[Init] Failed to check Telegram user consent.');
                settings.is_privacy_consented = false;
            }
        })();
    })
    .then(() => blocks.processBlocks(settings.mainpage_blocks))
    .then(async () => {
        console.debug('Load default filters for the main page');
        const filtersStore = useProductFiltersStore();
        filtersStore.applied = await filtersStore.fetchFiltersForMainPage();
    })
    .then(() => {
            console.debug('[Init] Set theme attributes');
            document.documentElement.setAttribute('data-theme', settings.theme[window.Telegram.WebApp.colorScheme]);
            if (settings.night_auto) {
                window.Telegram.WebApp.onEvent('themeChanged', function () {
                    document.documentElement.setAttribute('data-theme', settings.theme[this.colorScheme]);
                    setTelegramUIColors();
                });
            }

            const tgColorScheme = getComputedStyle(document.documentElement)
                .getPropertyValue('--tg-color-scheme')
                .trim();
            if (tgColorScheme) {
                document.documentElement.classList.add(tgColorScheme);
            }

            for (const key in settings.theme.variables) {
                document.documentElement.style.setProperty(key, settings.theme.variables[key]);
            }

            setTelegramUIColors();
        }
    )
    .then(() => new AppMetaInitializer(settings).init())
    .then(() => {
        appLoading.unmount();
        app.mount('#app');
    })
    .then(() => window.Telegram.WebApp.ready())
    .then(() => settings.ya_metrika_enabled && injectYaMetrika())
    .catch(error => {
        console.error(error);
        const errorApp = createApp(ApplicationError, {error});
        errorApp.mount('#app-error');
    });
