window.addEventListener("diggerDataReady", function (event) {
    console.log("Event: ", event.detail)
    console.log("Window: ", window.diggerData)
    const diggerData = window.diggerData;
    const digPath = window.location.toString();

    const queryString = new URLSearchParams({
        ...(diggerData.keyword && { kwd: diggerData.keyword }),
        ...(diggerData.dig && { dig: diggerData.dig }),
        ...(diggerData.gclid && { gclid: diggerData.gclid }),
        ...(diggerData.wbraid && { wbraid: diggerData.wbraid }),
        ...(diggerData.gbraid && { gbraid: diggerData.gbraid }),
        ...(diggerData.originalReferrer && { originalReferrer: diggerData.originalReferrer }),
        ...(diggerData.sessionId && { sessionId: diggerData.sessionId }),
        ...(digPath && { digPath }),
        ...(diggerData.fbclid && { fbclid: diggerData.fbclid })
    }).toString();

    if (queryString) {
        const currentHost = window.location.hostname.replace(/^www\./, '');

        document.querySelectorAll('a:not([href^="#"])').forEach(link => {
            try {
                const url = new URL(link.href);

                // Compare base domain (e.g., digtective.com), ignore subdomains
                const linkHost = url.hostname.replace(/^www\./, '');

                if (linkHost !== currentHost) {
                    url.search += (url.search ? '&' : '') + queryString;
                    link.href = url.toString();
                }
            } catch (e) {
                console.warn('Invalid URL', link.href, e);
            }
        });
    }
});
