import {createApp, ref} from 'vue';
import App from './App.vue';
import './style.css';
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} from "@/utils/ftch.js";

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

import {defaultConfig, plugin} from '@formkit/vue';
import config from './formkit.config.js';
import {TC_PULSE_EVENTS} from "@/constants/tPulseEvents.js";
import {usePulseStore} from "@/stores/Pulse.js";
import {TelegramInitDataError} from '@/errors.js';
import WrongPlatformError from "@/WrongPlatformError.vue";

register();

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

const settings = useSettingsStore();
const blocks = useBlocksStore();
const pulse = usePulseStore();
const tg = window.Telegram.WebApp;

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

function setTelegramUIColors() {
    const daisyUIBgColor = getCssVarOklchRgb('--color-base-200');
    tg.setHeaderColor(daisyUIBgColor);
    tg.setBackgroundColor(daisyUIBgColor);
}

settings.load()
    .then(() => tg.lockOrientation())
    .then(() => {
        if (settings.app_enabled === false) {
            throw new Error('App disabled (maintenance mode)');
        }
    })
    .then(() => settings.ya_metrika_enabled && injectYaMetrika())
    .then(() => {
        if (! tg.initData) {
            throw new TelegramInitDataError('Invalid init data. Application not in Telegram View');
        }
    })
    .then(() => pulse.initFromStartParams())
    .then(() => pulse.catchTelegramCustomerFromInitData())
    .then(() => pulse.ingest(TC_PULSE_EVENTS.WEBAPP_OPEN))
    .then(() => {
        pulse.heartbeat();
    })
    .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(() => {
            console.debug('[Init] Set theme attributes');
            document.documentElement.setAttribute('data-theme', settings.theme[tg.colorScheme]);
            if (settings.night_auto) {
                tg.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]);
            }

            try {
                setTelegramUIColors();
            } catch (e) {
                console.error('Could not set Telegram UI Colors', e);
            }
        }
    )
    .then(() => new AppMetaInitializer(settings).init())
    .then(() => {
        appLoading.unmount();
        app.mount('#app');
    })
    .then(() => tg.ready())
    .then(() => {
        if (tg.platform !== 'tdesktop') {
            tg.disableVerticalSwipes();
            tg.requestFullscreen();
        }
    })
    .catch(error => {
        console.error(error);
        const code = error.code ?? error?.response?._data.code;
        let ErrorComponent;

        switch (code) {
            case 'NO_INIT_DATA':
                ErrorComponent = WrongPlatformError;
                break;

            default:
                ErrorComponent = ApplicationError;
        }

        const errorApp = createApp(ErrorComponent, { error });
        errorApp.mount('#app-error');
    });
