(function () {
    const urlParams = new URLSearchParams(window.location.search);

    const baseData = {
        dig: urlParams.get("dig"),
        gclid: urlParams.get("gclid"),
        gbraid: urlParams.get("gbraid"),
        wbraid: urlParams.get("wbraid"),
        fbclid: urlParams.get("fbclid"),
        kwd: urlParams.get("kwd"),
        referrer: document.referrer,
        path: window.location.toString()
    };

    // Store initial data globally (without event yet)
    window.diggerData = { ...baseData };

    // Send data to backend
    fetch("/wp-json/digtective/v1/session", {
        method: "POST",
        credentials: "same-origin",
        keepalive: true,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(baseData)
    })
        .then(res => res.json())
        .then(serverData => {
            window.diggerData = { ...window.diggerData, ...serverData };

            const event = new CustomEvent("diggerDataReady", { detail: window.diggerData });
            window.dispatchEvent(event);
        })
        .catch(error => {
            console.error("Failed to fetch session data:", error);
        });
})();
