import {defineStore} from "pinia";
import {useSettingsStore} from "@/stores/SettingsStore.js";
import {toRaw} from "vue";
import {usePulseStore} from "@/stores/Pulse.js";

export const useYaMetrikaStore = defineStore('ya_metrika', {
    state: () => ({
        queue: [],
        prevPath: null,
    }),

    actions: {
        pushHit(url, params = {}) {
            if (!useSettingsStore().ya_metrika_enabled) {
                console.debug('[ym] Yandex Metrika disabled in settings.');
                return;
            }

            const fullUrl = `/#${url}`;

            params.referer = params.referer ?? this.prevPath;

            const pulse = usePulseStore();
            params.campaign_id = params.campaign_id || pulse.campaign_id || null;
            params.tracking_id = params.tracking_id || pulse.tracking_id || null;

            if (typeof window.ym === 'function' && window.YA_METRIKA_ID !== undefined) {
                console.debug('[ym] Hit ', fullUrl);
                console.debug('[ym] ID ', window.YA_METRIKA_ID);
                console.debug('[ym] params ', params);
                window.ym(window.YA_METRIKA_ID, 'hit', fullUrl, params);
            } else {
                console.debug('[ym] Yandex Metrika is not initialized. Pushed to queue.');
                this.queue.push({
                    event: 'hit',
                    payload: {
                        fullUrl,
                        params,
                    }
                });
            }
        },

        reachGoal(target, params = {}) {
            if (!useSettingsStore().ya_metrika_enabled) {
                console.debug('[ym] Yandex Metrika disabled in settings.');
                return;
            }

            if (! target) {
                return;
            }

            const pulse = usePulseStore();
            params.campaign_id = params.campaign_id || pulse.campaign_id || null;
            params.tracking_id = params.tracking_id || pulse.tracking_id || null;

            if (typeof window.ym === 'function' && window.YA_METRIKA_ID !== undefined) {
                console.debug('[ym] reachGoal ', target, ' params: ', params);
                window.ym(window.YA_METRIKA_ID, 'reachGoal', target, params);
            } else {
                console.debug('[ym] Yandex Metrika is not initialized. Pushed to queue.');
                this.queue.push({
                    event: 'reachGoal',
                    payload: {
                        target,
                        params
                    },
                });
            }
        },

        initUserParams() {
            if (!useSettingsStore().ya_metrika_enabled) {
                console.debug('[ym] Yandex Metrika disabled in settings.');
                return;
            }

            if (typeof window.ym === 'function' && window.YA_METRIKA_ID !== undefined) {
                const userParams = {
                    tracking_id: usePulseStore().tracking_id,
                    language: window.Telegram?.WebApp?.initDataUnsafe?.user?.language_code || 'unknown',
                    platform: window.Telegram?.WebApp?.platform || 'unknown',
                };

                window.ym(window.YA_METRIKA_ID, 'userParams', userParams);
                console.debug('[ym] User params initialized: ', userParams);
            } else {
                console.debug('[ym] Yandex Metrika is not initialized. Could not init user params.');
            }
        },

        processQueue() {
            if (this.queue.length === 0) {
                return;
            }

            console.debug('[ym] Start processing queue. Size: ', this.queue.length);

            while (this.queue.length > 0) {
                const item = this.queue.shift();
                if (item.event === 'hit') {
                    console.debug('[ym] Queue ', toRaw(item));
                    window.ym(window.YA_METRIKA_ID, 'hit', item.payload.fullUrl, item.payload.params);
                } else if (item.event === 'reachGoal') {
                    window.ym(window.YA_METRIKA_ID, 'reachGoal', item.payload.target, item.payload.params);
                } else if (item.event === 'dataLayer') {
                    console.debug('[ym] queue dataLayer push: ', item.payload);
                    window.dataLayer.push(item.payload);
                } else {
                    console.error('[ym] Unsupported queue event: ', item.event);
                }
            }

            console.debug('[ym] Queue processing complete. Size: ', this.queue.length);
        },

        dataLayerPush(object) {
            if (!useSettingsStore().ya_metrika_enabled) {
                console.debug('[ym] Yandex Metrika disabled in settings.');
                return;
            }

            const pulse = usePulseStore();
            const campaignId = pulse.campaign_id || null;
            object.ecommerce = object.ecommerce || {};

            if (campaignId) {
                object.ecommerce.promotions = object.ecommerce.promotions || [];
                object.ecommerce.promotions.push({ id: campaignId });
            }

            // Всегда добавляем ключи на верхнем уровне
            object.campaign_id = campaignId;
            object.tracking_id = pulse.tracking_id || null;

            if (Array.isArray(window.dataLayer)) {
                console.debug('[ym] dataLayer push: ', object);
                window.dataLayer.push(object);
            } else {
                console.debug('[ym] dataLayer inaccessible. Put to queue');
                this.queue.push({
                    event: 'dataLayer',
                    payload: object,
                });
            }
        }
    },
});
