const trackMetaPageView = (url) => {
    if (typeof window.fbq !== "function") {
        return;
    }

    const eventUrl = String(url || window.location.href);
    const lastPageView = window.__vitiMetaLastPageView || {};
    const now = Date.now();

    if (lastPageView.url === eventUrl && now - (lastPageView.time || 0) < 1000) {
        return;
    }

    window.__vitiMetaLastPageView = { url: eventUrl, time: now };

    window.fbq("track", "PageView", {
        page_location: eventUrl
    });
};

export const installMetaPageViewTracking = () => {
    const previousHandlers = window.__vitiMetaPageViewHandlers;

    if (previousHandlers) {
        document.removeEventListener("turbo:load", previousHandlers.load);
    }

    const load = (event) => {
        trackMetaPageView(event?.detail?.url || window.location.href);
    };

    document.addEventListener("turbo:load", load);

    window.__vitiMetaPageViewHandlers = { load };
};
