import {useYaMetrikaStore} from "@/stores/yaMetrikaStore.js";

function getMetrikaId() {
    // Пробуем найти все элементы <script> с mc.yandex.ru
    const scripts = Array.from(document.scripts);
    for (const s of scripts) {
        if (s.src.includes('mc.yandex.ru/metrika/tag.js')) {
            const match = s.src.match(/id=(\d+)/);
            if (match) return match[1];
        }
    }
    return null;
}

export function injectYaMetrika() {
    const script = document.createElement('script');
    script.src = '/index.php?route=extension/tgshop/handle/ya_metrika';
    // script.async = true;
    document.head.appendChild(script);
    console.debug('[ym] Yandex Metrika injected to the page.');

    script.onload = () => {
        window.YA_METRIKA_ID = getMetrikaId();
        console.debug('[ym] Detected Yandex.Metrika ID:', window.YA_METRIKA_ID);
        const yaMetrika = useYaMetrikaStore();
        yaMetrika.initUserParams();
        window.dataLayer = window.dataLayer || [];
        yaMetrika.processQueue();
    }
}
