(function() {
    // Get the 'pe_debug' and 'pe_goal_ts' parameters from the URL
    const params = new URLSearchParams(window.location.search);
    const debugMode = params.get('pe_debug') === '1';  // Enable debug mode if 'pe_debug=1' in the URL
    const peGoalTs = params.get('pe_goal_ts') || '0';  // Set '0' as the default if 'pe_goal_ts' is empty or not provided

    // Predefined constant for the base path
    const basePath = '/promo/my-mys/event-handlers/';  // Update this to your actual base path

    // Get the current domain
    const currentDomain = window.location.origin;

    // Custom log function to handle debug mode
    function debugLog(message, ...optionalParams) {
        if (debugMode) {
            console.log("Page Events:", message, ...optionalParams);
        }
    }

    // Initialize tracking state
    let isTrackingStopped = false;
    let interactionDetected = false;  // To track 'event9' (interaction)
    let goalTriggered = false;  // To prevent multiple goal triggers per session

    debugLog(`Initial state of isTrackingStopped: ${isTrackingStopped}`);

    // Variables for tracking time, scroll depth, and tokens
    let startTime = null;
    let scrollDepth = 0;
    let tokens = {};

    // Function to start tracking time
    function startTimer() {
        if (!startTime) {
            startTime = Date.now();
            debugLog('Timer started at', startTime);
        }
    }

    // Function to calculate and return time on page in seconds, capped at 600 seconds
    function getTimeOnPage() {
        const elapsedTime = Math.round((Date.now() - startTime) / 1000);  // Calculate time in seconds
        const timeOnPage = Math.min(elapsedTime, 600);  // Enforce a max of 600 seconds (10 minutes)
        debugLog('Time on page calculated:', timeOnPage, 'seconds (capped at 600)');
        return timeOnPage;
    }

    // Function to track scroll depth
    function trackScrollDepth() {
        if (isTrackingStopped) {
            debugLog('Tracking stopped. Skipping scroll depth tracking.');
            return;
        }

        const h = document.documentElement;
        const b = document.body;
        const scrollTop = h.scrollTop || b.scrollTop;
        const scrollHeight = h.scrollHeight || b.scrollHeight;
        const clientHeight = h.clientHeight;
        const currentDepth = Math.round((scrollTop / (scrollHeight - clientHeight)) * 100);

        if (currentDepth > scrollDepth) {
            scrollDepth = currentDepth;
            debugLog(`Scroll depth updated to: ${scrollDepth}%`);
        }
    }

    // Function to detect user interaction (event9) on movement and set event9 flag
    function trackInteraction() {
        if (!interactionDetected) {
            interactionDetected = true;
            tokens['event9'] = 1;  // Track the interaction event
            debugLog('Interaction detected. event9 triggered.');
        }
    }

    // Function to update tokens (time and scroll depth)
    function updateTokens() {
        tokens['event7'] = getTimeOnPage();  // Time on page
        tokens['event10'] = scrollDepth;     // Scroll depth
        debugLog('Tokens updated:', tokens);
    }

    // Function to send tracking data to events.php
    function sendTrackingData() {
        if (isTrackingStopped) {
            debugLog("Tracking is stopped. No data will be sent.");
            return;
        }

        const uclick = params.get('uclick');
        const uclickhash = params.get('uclickhash');
        const externalid = params.get('externalid');
        debugLog('Tracking params:', { uclick, uclickhash, externalid });

        let updateUrl = `${currentDomain}${basePath}events.php?uclick=${uclick}&uclickhash=${uclickhash}`;

        updateTokens();  // Update tokens with time and scroll depth

        // Append other tokens to the URL
        for (const key in tokens) {
            if (tokens.hasOwnProperty(key)) {
                updateUrl += `&${key}=${tokens[key]}`;
            }
        }

        debugLog('Sending data to URL:', updateUrl);

        // Use sendBeacon to send data or fallback to image request
        if (navigator.sendBeacon) {
            navigator.sendBeacon(updateUrl);
            debugLog('Data sent using sendBeacon.');
        } else {
            let img = new Image();
            img.src = updateUrl;
            debugLog('Data sent using fallback image request.');
        }
    }

    // Function to send data to goal.php (Allow in both MainLP and SecondaryLP)
    function sendGoalData() {
        if (goalTriggered) {
            debugLog("Goal already triggered. No further goal events will be sent.");
            return;
        }

        const uclick = params.get('uclick');
        const uclickhash = params.get('uclickhash');
        const externalid = params.get('externalid');
        debugLog('Goal params:', { uclick, uclickhash, externalid });

        let goalUrl = `${currentDomain}${basePath}goal.php?uclick=${uclick}&uclickhash=${uclickhash}&externalid=${externalid}`;

        // Add the custom 'goal_ts' parameter from 'pe_goal_ts' if it exists
        if (peGoalTs) {
            goalUrl += `&goal_ts=${peGoalTs}`;
            debugLog('Custom goal_ts parameter added:', peGoalTs);
        }

        debugLog('Sending goal data to URL:', goalUrl);

        if (navigator.sendBeacon) {
            navigator.sendBeacon(goalUrl);
            debugLog('Goal data sent using sendBeacon.');
        } else {
            let img = new Image();
            img.src = goalUrl;
            debugLog('Goal data sent using fallback image request.');
        }

        goalTriggered = true;  // Mark goal as triggered to avoid multiple triggers
    }

    // Function to check if the goal should be triggered
    function checkAndSendGoal() {
        const timeOnPage = getTimeOnPage();
        if (scrollDepth >= 10 && timeOnPage >= 30 && !goalTriggered) {
            debugLog("Goal conditions met: Scroll depth >= 10% and time on page >= 30 seconds.");
            sendGoalData();  // Trigger goal if conditions are met
        }
    }

    // Polling function to check for goal conditions every second, stops if tracking is stopped
    function setupGoalPolling() {
        const pollInterval = setInterval(function() {
            if (isTrackingStopped) {
                debugLog("Tracking is stopped. Stopping goal polling.");
                clearInterval(pollInterval);  // Stop polling if tracking is stopped
                return;
            }

            checkAndSendGoal();  // Continue checking and sending goal if conditions are met
            if (goalTriggered) {
                clearInterval(pollInterval);  // Stop polling once the goal is triggered
            }
        }, 1000);  // Poll every second
    }

    // Event handler for the `beforeunload` event
    function handleBeforeUnload() {
        debugLog('beforeunload event triggered. Sending data and checking goal.');
        sendTrackingData();
        checkAndSendGoal();
    }

    // Event handler for the `unload` event
    function handleUnload() {
        debugLog('unload event triggered. Sending data and checking goal.');
        sendTrackingData();
        checkAndSendGoal();
    }

    // Event handler for the `visibilitychange` event
    function handleVisibilityChange() {
        if (isTrackingStopped) {
            debugLog('Tracking is stopped. Visibility change ignored.');
            return;
        }

        if (document.visibilityState === 'hidden') {
            debugLog('Visibility state is hidden. Sending data and checking goal.');
            sendTrackingData();
            checkAndSendGoal();
        }
    }

    //Event handler for mousemove
    function handleMousemove() {
        trackInteraction();
    }

    //Event handler for touchmove
    function handleTouchmove() {
        trackInteraction();
    }

    // Event handler for the `scroll` event
    function handleScroll() {
        trackInteraction();
        trackScrollDepth();
    }

    // Add event listeners for tracking events
    function addTrackingListeners() {
        // Interaction events (once per page load)
        document.addEventListener('mousemove', handleMousemove, { once: true });
        document.addEventListener('touchmove', handleTouchmove, { once: true });
        debugLog('Added interaction event listeners (mousemove and touchmove).');

        // Scroll event
        document.addEventListener('scroll', handleScroll);
        debugLog('Added scroll event listener.');

        // Visibility change event
        document.addEventListener('visibilitychange', handleVisibilityChange);
        debugLog('Added visibilitychange event listener.');

        // Unload events
        window.addEventListener('beforeunload', handleBeforeUnload);
        debugLog('Added beforeunload event listener.');

        window.addEventListener('unload', handleUnload);
        debugLog('Added unload event listener.');
    }

    // Function to stop tracking and remove event listeners
    function stopTracking() {
        if (isTrackingStopped) {
            debugLog('Tracking has already been stopped.');
            return;
        }

        isTrackingStopped = true;  // Set flag to stop further tracking
        debugLog('Tracking stopped. isTrackingStopped state set to true.');

        // Remove all event listeners related to tracking
        document.removeEventListener('scroll', handleScroll);
        document.removeEventListener('mousemove', handleMousemove);
        document.removeEventListener('touchmove', handleTouchmove);
        debugLog('Removed scroll and interaction event listeners.');

        window.removeEventListener('beforeunload', handleBeforeUnload);
        debugLog('Removed beforeunload event listener.');

        window.removeEventListener('unload', handleUnload);
        debugLog('Removed unload event listener.');

        document.removeEventListener('visibilitychange', handleVisibilityChange);
        debugLog('Removed visibilitychange event listener.');
    }

    // Iframe visibility and postMessage logic
    function checkIframeVisibility() {
        const iframe = document.querySelector('iframe#LandFrame');
        if (iframe) {
            const displayStyle = window.getComputedStyle(iframe).display;
            debugLog(`Iframe display style is: ${displayStyle}`);
            if (displayStyle !== 'none') {
                debugLog("Iframe is now visible. Sending message to SecondaryLP.");
                iframe.contentWindow.postMessage('iframeVisible', '*');
                sendTrackingData();  // Trigger data send when iframe becomes visible
                stopTracking();  // Stop tracking in MainLP once iframe is visible
            } else {
                debugLog("Iframe is still not visible (display: 'none').");
            }
        } else {
            debugLog("Iframe with ID 'LandFrame' not found.");
        }
    }

    function delayedIframeCheck() {
        debugLog("Waiting 1 second before checking iframe visibility...");
        setTimeout(checkIframeVisibility, 1000);  // Wait 1 second before checking
    }

    // MainLP logic
    function runMainLogic() {
        if (isTrackingStopped) {
            debugLog('Tracking already stopped before starting MainLP logic.');
            return;
        }

        debugLog("Running MainLP logic.");
        startTimer();
        addTrackingListeners();  // Add event listeners for tracking
        setupGoalPolling();  // Start goal polling

        // Check iframe visibility and listen for popstate event
        checkIframeVisibility();
        window.addEventListener('popstate', delayedIframeCheck);
    }

    // SecondaryLP logic
    function runIframeLogic() {
        debugLog("Running SecondaryLP (iframe) logic.");

        window.addEventListener('message', function(event) {
            debugLog("Message received in SecondaryLP:", event);
            if (event.data === 'iframeVisible') {
                debugLog("Received 'iframeVisible' message from MainLP. Starting tracking.");
                startTimer();
                addTrackingListeners();
                setupGoalPolling();
            }
        });

        debugLog("Listening for messages from MainLP.");
    }

    // Function to detect if we are in an iframe or main window
    function runPageLogic() {
        if (window.self === window.top) {
            runMainLogic();  // MainLP logic
        } else {
            runIframeLogic();  // SecondaryLP logic
        }
    }

    // Document ready function
    function documentReady(fn) {
        if (document.readyState === "complete" || document.readyState === "interactive") {
            setTimeout(fn, 1);  // Call on next available tick
        } else {
            document.addEventListener("DOMContentLoaded", fn);
        }
    }

    // Run the appropriate logic based on the context (MainLP or SecondaryLP)
    documentReady(runPageLogic);

})();
