/**
 * Frame Locker v1.0
 * Content locking script with WebView detection and scroll position preservation
 */
(function() {
    /** Check if a URL parameter exists and has a specific value */
    function getUrlParam(name, defaultValue = null) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.has(name) ? urlParams.get(name) : defaultValue;
    }
    
    // Setup debug mode based on cl-debug parameter
    const debugMode = getUrlParam('cl-debug') !== null;
    
    // Custom logger that only outputs when debug mode is enabled
    const logger = {
        log: function(message, ...args) {
            if (debugMode) {
                console.log("CL:", message, ...args);
            }
        },
        warn: function(message, ...args) {
            if (debugMode) {
                console.warn("CL:", message, ...args);
            }
        },
        error: function(message, ...args) {
            // Always log errors regardless of debug mode
            console.error("CL:", message, ...args);
        }
    };
    
    // Check if the cl-on parameter exists in the URL
    if (getUrlParam('cl-on') === null) {
        logger.log('cl-on parameter not found, frame locker disabled');
        return;
    }
    logger.log('cl-on parameter detected, frame locker enabled');
    if (debugMode) {
        logger.log('Debug mode enabled - console logging active');
    }

    // Function to create a scroll position marker at a specific position
    function createScrollPositionMarker(position) {
        const scrollMarker = document.createElement('div');
        scrollMarker.id = 'scroll-position-marker';
        scrollMarker.className = 'scroll-position-marker';
        scrollMarker.style.position = 'absolute';
        scrollMarker.style.left = '0';
        scrollMarker.style.width = '100%';
        scrollMarker.style.height = '1px';
        scrollMarker.style.top = `${position}px`;
        scrollMarker.style.zIndex = '-1';
        scrollMarker.style.opacity = '0';
        document.body.appendChild(scrollMarker);
        logger.log('Scroll position marker created at position:', position);
    }

    // Handle cl-noLock logic
    if (getUrlParam('cl-noLock') !== null) {
        logger.log('cl-noLock parameter detected, frame locker disabled');

        document.addEventListener("DOMContentLoaded", function() {
            const scrollPosition = getUrlParam('cl-scrollPosition');
            const scrollY = scrollPosition !== null ? parseInt(scrollPosition, 10) : window.innerHeight - 80;

            if (!isNaN(scrollY)) {
                logger.log('Using scroll position from URL parameter:', scrollY);
                createScrollPositionMarker(scrollY);
                window.scrollTo(0, scrollY);
            } else {
                logger.log('Invalid scroll position, using default.');
                createScrollPositionMarker(window.innerHeight - 80);
            }

            if (getUrlParam('cl-newTab') !== null) {
                logger.log('New tab detected with cl-noLock, sending confirmation to opener');
                function sendConfirmationMessages() {
                    localStorage.removeItem('frameLocker_command');
                    const message = 'New tab opening is confirmed, ready to redirect|' + Date.now();
                    try {
                        localStorage.setItem('frameLocker_command', message);
                        logger.log('Sent confirmation via localStorage:', message);
                    } catch (e) {
                        logger.error('Error with localStorage:', e);
                    }

                    if (window.opener) {
                        try {
                            window.opener.postMessage('New tab opening is confirmed, ready to redirect', '*');
                            logger.log('Sent confirmation via postMessage');
                        } catch (e) {
                            logger.error('Error sending postMessage:', e);
                        }
                    } else {
                        logger.warn('window.opener is not available');
                    }
                }

                sendConfirmationMessages();
                setTimeout(sendConfirmationMessages, 500);
                setTimeout(sendConfirmationMessages, 1500);
                setTimeout(sendConfirmationMessages, 3000);
                setTimeout(sendConfirmationMessages, 6000);
            }
        });

        // Exit early and skip the rest of the frame locker logic
        return;
    }

    /** Detect if the browser is a webview (iOS, Android, or in-app browser) */
    function isWebView() {
        if (getUrlParam('debug_webview') === '0') {
            logger.log('WebView detection disabled via debug parameter');
            return false;
        }

        const ua = navigator.userAgent || navigator.vendor || window.opera;
        const isIOSWebView = /(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(ua);
        const isAndroidWebView = /\bwv\b|\.0\.0\.0/i.test(ua) || /Version\/[\d.]+.*Chrome/i.test(ua);
        const isInAppBrowser = /FBAN|FBAV|Instagram|Twitter|Line|LinkedIn|Snapchat|TikTok|GSA/i.test(ua);
        return isIOSWebView || isAndroidWebView || isInAppBrowser;
    }

    /** Detect if the current window is inside an iframe */
    function isInIframe() {
        try {
            return window.self !== window.top;
        } catch (e) {
            return true;
        }
    }

    const isInWebView = isWebView();
    logger.log("User Agent:", navigator.userAgent);
    logger.log("WebView Detected:", isInWebView);

    document.addEventListener("DOMContentLoaded", function () {
        if (isInWebView) {
            logger.log("In webview, skipping content locker.");
            return;
        }

        if (isInIframe()) {
            logger.log("In iframe, skipping content locker.");
            return;
        }

        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('cl-newTab') !== null) {
            setTimeout(function() {
                if (window.location.hash === '#scroll-position-marker') {
                    const marker = document.getElementById('scroll-position-marker');
                    if (marker) {
                        window.scrollTo({
                            top: marker.offsetTop,
                            behavior: 'smooth'
                        });
                        logger.log("Scrolled to marker position:", marker.offsetTop);
                    }
                }
            }, 500);
        }

        let frameVisible = false;
        let initialScrollY = 0;
        let contentUnlocked = false;
        let readMoreClicked = false;
        let redirectScheduled = false;
        let visibilityCheckTimeout = null;
        let visibilityHiddenTimeout = null;
        let lastProcessedCommand = '';

        window.addEventListener('storage', function(e) {
            if (e.key === 'frameLocker_command' && e.newValue && e.newValue !== lastProcessedCommand) {
                lastProcessedCommand = e.newValue;
                if (e.newValue === 'New tab successfully opened!') {
                    if (frameVisible) {
                        const frame = document.getElementById('contentLocker');
                        if (frame) {
                            unlockContent();
                            frame.remove();
                            redirectAfterDelay();
                        }
                    }
                }
            }
        });

        window.addEventListener("scroll", function () {
            const threshold = 200;
            if (window.scrollY >= threshold && !frameVisible) {
                frameVisible = true;
                initialScrollY = window.scrollY;
                createContentLock();
            }
        });

        function createContentLock() {
            const buttonPosition = initialScrollY + window.innerHeight - 80;
            document.body.style.height = `${initialScrollY + window.innerHeight}px`;
            document.body.style.overflow = "hidden";

            const frame = document.createElement("iframe");
            frame.id = "contentLocker";
            frame.style.position = "fixed";
            frame.style.top = "0";
            frame.style.left = "0";
            frame.style.width = "100%";
            frame.style.height = "100vh";
            frame.style.border = "none";
            frame.style.zIndex = "999999";
            frame.style.backgroundColor = "transparent";
            frame.allowTransparency = "true";
            document.body.appendChild(frame);

            // Get custom button text if provided
            const customBtnText = getUrlParam('cl-btn');
            const buttonText = customBtnText !== null ? decodeURIComponent(customBtnText) : 'Read more';
            logger.log('Button text:', buttonText);
            
            const frameDoc = frame.contentDocument || frame.contentWindow.document;
            frameDoc.open();
            frameDoc.write(`
                <!DOCTYPE html>
                <html>
                <head>
                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <style>
                        body {
                            margin: 0; padding: 0;
                            height: 100%; width: 100%;
                            background: transparent;
                            overflow: hidden;
                        }
                        .bar-container {
                            position: fixed;
                            bottom: 0; left: 0; width: 100%;
                            text-align: center; z-index: 999999;
                            -webkit-transform: translateZ(0);
                        }
                        .read-more-bar {
                            background: rgba(76, 175, 80, 0.9);
                            color: white; padding: 15px 0;
                            font-size: 18px; font-weight: bold;
                            text-transform: uppercase;
                            letter-spacing: 1px;
                            box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.3);
                            cursor: pointer;
                        }
                    </style>
                </head>
                <body>
                    <div class="bar-container">
                        <div class="read-more-bar" id="readMoreBtn">${buttonText}</div>
                    </div>
                    <script>
                        const scrollY = window.top.scrollY || window.top.pageYOffset;
                        const topLocation = window.top.location;
                        const newTabUrlObj = new URL(topLocation.href);

                        newTabUrlObj.searchParams.set('cl-newTab', '');
                        newTabUrlObj.searchParams.set('cl-noLock', '');
                        newTabUrlObj.searchParams.set('cl-scrollPosition', scrollY);
                        newTabUrlObj.hash = 'scroll-position-marker';

                        const newTabUrl = newTabUrlObj.toString();

                        document.getElementById('readMoreBtn').addEventListener('click', function () {
                            window.top.postMessage('unlockContent', '*');
                            try {
                                localStorage.setItem('frameLocker_unlock', 'unlock_' + Date.now());
                            } catch (e) {}
                            window.top.postMessage('readMoreButtonClicked', '*');
                            window.open(newTabUrl, '_blank');
                        });
                    </script>
                </body>
                </html>
            `);
            frameDoc.close();

            window.addEventListener("message", function (event) {
                if (event.data === "unlockContent" && !contentUnlocked) {
                    unlockContent();
                    frame.remove();
                    contentUnlocked = true;
                }

                if (event.data === "readMoreButtonClicked") {
                    readMoreClicked = true;
                    visibilityCheckTimeout = setTimeout(() => {
                        readMoreClicked = false;
                    }, 5000);
                }

                if (event.data === "New tab opening is confirmed, ready to redirect" && !redirectScheduled) {
                    logger.log("Message received from new tab via postMessage:", event.data);
                    if (contentUnlocked) {
                        redirectScheduled = true;
                        clearTimeout(visibilityHiddenTimeout);
                        logger.log("Redirect scheduled based on postMessage confirmation");
                        redirectAfterDelay();
                    }
                }
            });

            document.addEventListener("visibilitychange", function () {
                if (readMoreClicked && contentUnlocked && !redirectScheduled) {
                    if (document.visibilityState === "hidden") {
                        visibilityHiddenTimeout = setTimeout(() => {
                            if (!redirectScheduled) {
                                redirectScheduled = true;
                                redirectAfterDelay();
                            }
                        }, 5000);
                    } else {
                        clearTimeout(visibilityHiddenTimeout);
                        visibilityHiddenTimeout = null;
                    }
                }
            });

            window.addEventListener('storage', function(e) {
                if (e.key === 'frameLocker_command' && contentUnlocked && !redirectScheduled) {
                    if (e.newValue && (
                        e.newValue === 'New tab opening is confirmed, ready to redirect' ||
                        e.newValue.startsWith('New tab opening is confirmed, ready to redirect|')
                    )) {
                        logger.log("Message received from new tab via localStorage:", e.newValue);
                        redirectScheduled = true;
                        clearTimeout(visibilityHiddenTimeout);
                        clearTimeout(visibilityCheckTimeout);
                        readMoreClicked = false;
                        logger.log("Redirect scheduled based on localStorage confirmation");
                        setTimeout(redirectAfterDelay, 100);
                    }
                }
            });

            const storedCommand = localStorage.getItem('frameLocker_command');
            if (storedCommand && contentUnlocked && !redirectScheduled) {
                if (storedCommand === 'New tab opening is confirmed, ready to redirect' ||
                    storedCommand.startsWith('New tab opening is confirmed, ready to redirect|')) {
                    logger.log("Existing message found in localStorage:", storedCommand);
                    redirectScheduled = true;
                    logger.log("Redirect scheduled based on existing localStorage message");
                    setTimeout(redirectAfterDelay, 500);
                }
            }
        }

        function redirectAfterDelay() {
            logger.log("Redirecting in 5s...");
            
            // Get URL parameters for the redirect
            const urlParams = new URLSearchParams(window.location.search);
            const user_id = urlParams.get('user_id') || '';
            const campaign_id = urlParams.get('campaign_id') || '';
            const campaign_category = urlParams.get('campaign_category') || '';
            const traffic_source = urlParams.get('traffic_source') || '';
            const traffic_source_widget = urlParams.get('traffic_source_widget') || '';
            
            // Construct the redirect URL with all parameters
            const redirectUrl = new URL('https://asiahealth.info/promo/my-mys/feed/');
            redirectUrl.searchParams.append('user_id', user_id);
            redirectUrl.searchParams.append('campaign_id', campaign_id);
            redirectUrl.searchParams.append('campaign_category', campaign_category);
            redirectUrl.searchParams.append('traffic_source', traffic_source);
            redirectUrl.searchParams.append('traffic_source_widget', traffic_source_widget);
            redirectUrl.searchParams.append('click_source', 'contentLocker');
            
            logger.log("Redirect URL:", redirectUrl.toString());
            
            setTimeout(() => {
                window.location.href = redirectUrl.toString();
            }, 5000);
        }

        function unlockContent() {
            document.body.style.height = "auto";
            document.body.style.overflow = "auto";
            window.scrollTo(0, initialScrollY);
            logger.log("Content unlocked.");
        }
    });
})();
