;(function($) {
    'use strict';
    // Unlock Popup Anywhere - Initial placeholder
    console.log('[Unlock Popup Anywhere] JS loaded');
    function initPopupAnywhere($wrapper) {
        if ($wrapper.length === 0) return;
        var settings = $wrapper.data('settings') || {};
        var $overlay = $wrapper.find('.unlockafe-popup-anywhere-modal-overlay');
        var $modal = $wrapper.find('.unlockafe-popup-anywhere-modal-container');
        var shown = false;
        var frequencyKey = 'unlockafe_popup_anywhere_' + $wrapper.attr('id');
        function isEditor() {
            // Multiple ways to detect editor
            return (
                (window.elementorFrontend && window.elementorFrontend.isEditMode && window.elementorFrontend.isEditMode()) ||
                window.elementor ||
                $('body').hasClass('elementor-editor-active') ||
                $('body').hasClass('elementor-edit-mode') ||
                window.location.href.indexOf('elementor-preview') !== -1
            );
        }

        // Cookie management (same as Email Capture widget)
        var pageUrl = window.location.pathname;
        var cookieName = 'unlockafe_popup_modal_shown_' + pageUrl.replace(/[^a-zA-Z0-9]/g, '_');
        
        function getCookie(name) {
            var value = "; " + document.cookie;
            var parts = value.split("; " + name + "=");
            if (parts.length === 2) return parts.pop().split(";").shift();
            return null;
        }
        
        function setCookie(name, value, days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            document.cookie = name + '=' + value + '; expires=' + date.toUTCString() + '; path=/';
        }

        function shouldShow() {
            if (isEditor()) {
                return true; // Always show in editor
            }
            
            // Check page-level cookie first (most restrictive)
            var cookieValue = getCookie(cookieName);
            if (cookieValue) {
                return false;
            }
            
            // Then check frequency settings
            if (settings.frequency === 'always') return true;
            if (settings.frequency === 'session') {
                return !sessionStorage.getItem(frequencyKey);
            }
            if (settings.frequency === 'day') {
                var lastShown = localStorage.getItem(frequencyKey);
                if (!lastShown) return true;
                var last = new Date(parseInt(lastShown, 10));
                var now = new Date();
                return now.toDateString() !== last.toDateString();
            }
            return true;
        }

        function markShown() {
            if (isEditor()) {
                return; // Don't mark as shown in editor
            }
            
            // Set page-level cookie with configurable expiry
            var cookieExpiry = parseInt(settings.cookieExpiry || 7, 10);
            setCookie(cookieName, 'true', cookieExpiry);
            if (settings.frequency === 'session') {
                sessionStorage.setItem(frequencyKey, '1');
            } else if (settings.frequency === 'day') {
                localStorage.setItem(frequencyKey, Date.now().toString());
            }
        }

        function initCountdownTimer() {
            var $countdown = $modal.find('.countdown-timer');
            if ($countdown.length === 0) return;

            var endTimeStr = $countdown.data('countdown');
            if (!endTimeStr) {
                return;
            }
            // Parse the date with better handling
            var endTime = new Date(endTimeStr);
            if (isNaN(endTime.getTime())) {
                // Try alternative parsing
                endTime = new Date(endTimeStr.replace(' ', 'T'));
                if (isNaN(endTime.getTime())) {
                    console.error('[Unlock Popup Anywhere] Invalid date format:', endTimeStr);
                    return;
                }
            }
            
            var currentTime = new Date();
            // Ensure countdown HTML structure exists
            function ensureCountdownStructure() {
                if ($countdown.find('.time-unit').length === 0) {
                    console.log('[Unlock Popup Anywhere] Rebuilding countdown structure');
                    $countdown.html(`
                        <div class="time-unit">
                            <span class="time-number" id="hours">00</span>
                            <span class="time-label">Hours</span>
                        </div>
                        <div class="time-separator">:</div>
                        <div class="time-unit">
                            <span class="time-number" id="minutes">00</span>
                            <span class="time-label">Minutes</span>
                        </div>
                        <div class="time-separator">:</div>
                        <div class="time-unit">
                            <span class="time-number" id="seconds">00</span>
                            <span class="time-label">Seconds</span>
                        </div>
                    `);
                }
            }

            function updateCountdown() {
                var now = new Date().getTime();
                var distance = endTime.getTime() - now;

                console.log('[Unlock Popup Anywhere] Distance calculation:', {
                    now: now,
                    endTime: endTime.getTime(),
                    distance: distance,
                    readable: Math.floor(distance / 1000) + ' seconds'
                });

                if (distance < 0) {
                    $countdown.html('<div class="expired-message">⏰ Offer Expired!</div>');
                    return;
                }

                // Ensure structure exists
                ensureCountdownStructure();

                var days = Math.floor(distance / (1000 * 60 * 60 * 24));
                var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                var seconds = Math.floor((distance % (1000 * 60)) / 1000);

                // Update display - show days if available
                if (days > 0) {
                    // Show days if we have them
                    if ($countdown.find('#days').length === 0) {
                        // Add days unit if not present
                        var daysUnit = '<div class="time-unit"><span class="time-number" id="days">00</span><span class="time-label">Days</span></div><div class="time-separator">:</div>';
                        $countdown.find('.time-unit').first().before(daysUnit);
                    }
                    $countdown.find('#days').text(days.toString().padStart(2, '0'));
                }

                var $hours = $countdown.find('#hours');
                var $minutes = $countdown.find('#minutes');
                var $seconds = $countdown.find('#seconds');

                if ($hours.length) $hours.text(hours.toString().padStart(2, '0'));
                if ($minutes.length) $minutes.text(minutes.toString().padStart(2, '0'));
                if ($seconds.length) $seconds.text(seconds.toString().padStart(2, '0'));
            }

            // Initialize structure first
            ensureCountdownStructure();

            // Update immediately and then every second
            updateCountdown();
            
            // Run timer in both editor and frontend
            setInterval(updateCountdown, 1000);
        }

        function initTemplateFeatures() {
            var template = settings.template || 'promotion';
            
            if (template === 'counter') {
                initCountdownTimer();
                
                // Simulate dynamic viewer count
                if (!isEditor()) {
                    var $viewerCount = $modal.find('.viewers');
                    if ($viewerCount.length > 0) {
                        setInterval(function() {
                            var count = Math.floor(Math.random() * 10) + 15; // 15-25 viewers
                            $viewerCount.text('👥 ' + count + ' people viewing this offer');
                        }, 5000);
                    }
                }
            }
            
            if (template === 'offer') {
                // Simulate price updates or stock changes
                if (!isEditor()) {
                    var $savings = $modal.find('.savings');
                    if ($savings.length > 0) {
                        setTimeout(function() {
                            $savings.addClass('pulse-animation');
                        }, 2000);
                    }
                }
            }
            
            if (template === 'black_friday') {
                initBlackFridayTimer();
            }
            
            if (template === 'gaming') {
                initGamingEffects();
            }
            
            if (template === 'crypto') {
                initCryptoTicker();
            }
            
            if (template === 'social_media') {
                initSocialEngagement();
            }
        }

        function initBlackFridayTimer() {
            var $countdown = $modal.find('.bf-countdown');
            if ($countdown.length === 0) return;

            var endTimeStr = $countdown.data('countdown');
            if (!endTimeStr) {
                return;
            }
            var endTime = new Date(endTimeStr);

            function updateBFCountdown() {
                var now = new Date().getTime();
                var distance = endTime.getTime() - now;

                if (distance < 0) {
                    $countdown.html('<div style="color: #ff6b6b; font-weight: 700;">🔥 SALE ENDED!</div>');
                    return;
                }

                var days = Math.floor(distance / (1000 * 60 * 60 * 24));
                var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                var seconds = Math.floor((distance % (1000 * 60)) / 1000);

                // Show days if available
                if (days > 0) {
                    if ($countdown.find('#bf-days').length === 0) {
                        // Add days unit if not present
                        var daysUnit = '<div class="bf-time-unit"><span class="bf-time-number" id="bf-days">00</span><span class="bf-time-label">DAYS</span></div>';
                        $countdown.find('.bf-time-unit').first().before(daysUnit);
                    }
                    $countdown.find('#bf-days').text(days.toString().padStart(2, '0'));
                }

                $countdown.find('#bf-hours').text(hours.toString().padStart(2, '0'));
                $countdown.find('#bf-minutes').text(minutes.toString().padStart(2, '0'));
                $countdown.find('#bf-seconds').text(seconds.toString().padStart(2, '0'));
            }

            updateBFCountdown();
            
            // Run timer in both editor and frontend
            setInterval(updateBFCountdown, 1000);
        }

        function initGamingEffects() {
            var $levelProgress = $modal.find('.level-progress');
            if ($levelProgress.length === 0) return;

            // Animate level progress bar
            setTimeout(function() {
                $levelProgress.css('animation', 'progressFill 3s ease-in-out infinite');
            }, 500);

            // Simulate achievement notifications
            if (!isEditor()) {
                setTimeout(function() {
                    var $gamingContent = $modal.find('.gaming-content');
                    var achievement = $('<div class="achievement-popup" style="position: absolute; top: 10px; right: 10px; background: rgba(255, 215, 0, 0.9); color: #000; padding: 8px 12px; border-radius: 20px; font-size: 0.8rem; font-weight: 600; animation: fadeInOut 3s ease;">🏆 Epic Achievement Unlocked!</div>');
                    $gamingContent.append(achievement);
                    
                    setTimeout(function() {
                        achievement.remove();
                    }, 3000);
                }, 2000);
            }
        }

        function initCryptoTicker() {
            var $priceItems = $modal.find('.price-item');
            if ($priceItems.length === 0) return;

            if (!isEditor()) {
                // Simulate live price updates
                setInterval(function() {
                    $priceItems.each(function() {
                        var $price = $(this).find('.crypto-price');
                        var currentPrice = parseFloat($price.text().replace(/[^0-9.]/g, ''));
                        var change = (Math.random() - 0.5) * 100; // Random change
                        var newPrice = Math.max(100, currentPrice + change);
                        
                        $price.text('$' + newPrice.toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ","));
                        
                        // Flash effect
                        $price.addClass('flash-green');
                        setTimeout(function() {
                            $price.removeClass('flash-green');
                        }, 500);
                    });
                }, 5000);
            }

            // Add flash styles
            if (!$('head').find('#crypto-flash-styles').length) {
                $('head').append('<style id="crypto-flash-styles">.flash-green { transition: all 0.3s; background: rgba(0, 212, 170, 0.3) !important; }</style>');
            }
        }

        function initSocialEngagement() {
            var $likes = $modal.find('.likes');
            var $comments = $modal.find('.comments');
            var $shares = $modal.find('.shares');

            if (!isEditor() && ($likes.length || $comments.length || $shares.length)) {
                // Simulate real-time engagement updates
                setInterval(function() {
                    if ($likes.length) {
                        var currentLikes = parseFloat($likes.text().replace(/[^0-9.]/g, ''));
                        var newLikes = currentLikes + (Math.random() * 0.1);
                        $likes.html('❤️ ' + newLikes.toFixed(1) + 'M');
                    }
                    
                    if ($comments.length) {
                        var currentComments = parseFloat($comments.text().replace(/[^0-9.]/g, ''));
                        var newComments = currentComments + (Math.random() * 0.1);
                        $comments.html('💬 ' + newComments.toFixed(1) + 'K');
                    }
                    
                    if ($shares.length) {
                        var currentShares = parseFloat($shares.text().replace(/[^0-9.]/g, ''));
                        var newShares = currentShares + (Math.random() * 0.05);
                        $shares.html('🔄 ' + newShares.toFixed(1) + 'K');
                    }
                }, 8000);
            }
        }

        function showModal() {
            if (shown && !isEditor()) return;
            shown = true;
            if (isEditor()) {
                $overlay.removeAttr('style').css({
                    'display': 'flex',
                    'visibility': 'visible',
                    'opacity': '1'
                });
                $modal.removeAttr('style').css({
                    'display': 'block',
                    'visibility': 'visible',
                    'opacity': '1'
                });
            } else {
                // First remove any inline styles that might conflict
                $overlay.removeAttr('style');
                $modal.removeAttr('style');
                
                // Force proper modal overlay styles
                $overlay.css({
                    'position': 'fixed',
                    'top': '0',
                    'left': '0',
                    'right': '0',
                    'bottom': '0',
                    'z-index': '9999',
                    'background': 'rgba(0,0,0,0.85)',
                    'display': 'flex',
                    'align-items': 'center',
                    'justify-content': 'center',
                    'opacity': '0',
                    'visibility': 'visible'
                }).animate({'opacity': 1}, 300);
                
                // Force proper modal container styles
                $modal.css({
                    'display': 'block',
                    'visibility': 'visible',
                    'opacity': '0',
                    'transform': 'scale(0.85) translateY(40px)'
                }).animate({
                    'opacity': 1,
                    'transform': 'scale(1) translateY(0)'
                }, 400);
                
                // Add body class to prevent scrolling
                $('body').addClass('unlockafe-modal-open');
            }
            
            // Initialize template-specific features
            initTemplateFeatures();
            markShown();
        }

        function hideModal() {
            if (isEditor()) {
                return;
            }
            
            // Frontend: Proper modal hiding with animation
            $modal.animate({
                'opacity': 0,
                'transform': 'scale(0.85) translateY(40px)'
            }, 200, function() {
                $modal.css('display', 'none');
            });
            
            $overlay.animate({'opacity': 0}, 300, function() {
                $overlay.css('display', 'none');
                // Remove body class to restore scrolling
                $('body').removeClass('unlockafe-modal-open');
            });
        }

        function forceShowInEditor() {
            if (!isEditor()) return;
            // Remove any inline display:none styles
            $overlay.removeAttr('style');
            $modal.removeAttr('style');
            
            // Force visibility with CSS
            $overlay.css({
                'display': 'flex !important',
                'visibility': 'visible !important',
                'opacity': '1 !important',
                'z-index': '999999 !important'
            });
            
            $modal.css({
                'display': 'block !important',
                'visibility': 'visible !important',
                'opacity': '1 !important'
            });
            
            // Also add classes for CSS targeting
            $overlay.addClass('unlockafe-editor-visible');
            $modal.addClass('unlockafe-editor-visible');
            
            // Initialize template features in editor
            initTemplateFeatures();
            
            shown = true;
        }

        // Initialize based on environment
        if (isEditor()) {
            // Multiple attempts to show the modal
            setTimeout(forceShowInEditor, 50);
            setTimeout(forceShowInEditor, 200);
            setTimeout(forceShowInEditor, 500);
            setTimeout(forceShowInEditor, 1000);
            
        } else if (shouldShow()) {
            if (settings.showAsModal === 'yes') {
                if (settings.displayMode === 'delay') {
                    setTimeout(showModal, (settings.displayDelay || 5) * 1000);
                } else if (settings.displayMode === 'scroll') {
                    $(window).on('scroll.unlockafePopupAnywhere', function() {
                        var scrollTop = $(window).scrollTop();
                        var docHeight = $(document).height();
                        var winHeight = $(window).height();
                        var scrollPercent = (scrollTop) / (docHeight - winHeight) * 100;
                        if (scrollPercent > (settings.scrollPercentage || 50)) {
                            showModal();
                            $(window).off('scroll.unlockafePopupAnywhere');
                        }
                    });
                } else if (settings.displayMode === 'exit_intent') {
                    $(document).on('mouseleave.unlockafePopupAnywhere', function(e) {
                        if (e.clientY < 0) {
                            showModal();
                            $(document).off('mouseleave.unlockafePopupAnywhere');
                        }
                    });
                } else {
                    setTimeout(showModal, 500);
                }
            }
        }

        // Close button
        $wrapper.on('click', '.unlockafe-popup-anywhere-modal-close', function(e) {
            e.preventDefault();
            hideModal();
            // Set cookie when user closes modal (so it doesn't show again)
            if (!isEditor()) {
                var cookieExpiry = parseInt(settings.cookieExpiry || 7, 10);
                setCookie(cookieName, 'true', cookieExpiry);
                console.log('[Unlock Popup Anywhere] Cookie set on close:', cookieName, 'for', cookieExpiry, 'days');
            }
        });

        $wrapper.on('click', '.popup-cta-button', function(e) {
            var ctaUrl = $(this).attr('href');
            var popupId = $(this).data('popup-id');
            
            // Send AJAX for tracking (only on frontend)
            if (!isEditor()) {
                $.ajax({
                    url: window.ajaxurl || '/wp-admin/admin-ajax.php',
                    type: 'POST',
                    data: {
                        action: 'unlockafe_popup_anywhere_track',
                        popup_id: popupId,
                        cta_url: ctaUrl,
                        page_url: window.location.href
                    },
                    success: function(resp) {
                        // Optionally handle response
                    }
                });
            }
        });

        // Accessibility: close on ESC (only on frontend)
        if (!isEditor()) {
            $(document).on('keydown.unlockafePopupAnywhere', function(e) {
                if (e.key === 'Escape') hideModal();
            });
        }
        
        // Watch for countdown data changes in editor (for when settings are updated)
        if (isEditor()) {
            var originalCountdownData = {};
            
            // Store initial countdown data
            $modal.find('.countdown-timer, .bf-countdown').each(function() {
                var id = $(this).attr('class');
                originalCountdownData[id] = $(this).data('countdown');
            });
            
            // Check for changes periodically in editor
            setInterval(function() {
                $modal.find('.countdown-timer, .bf-countdown').each(function() {
                    var $this = $(this);
                    var id = $this.attr('class');
                    var currentData = $this.data('countdown');
                    
                    if (originalCountdownData[id] !== currentData) {
                        console.log('[Unlock Popup Anywhere] Countdown data changed, reinitializing:', id, originalCountdownData[id], '->', currentData);
                        originalCountdownData[id] = currentData;
                        
                        // Reinitialize countdown
                        setTimeout(function() {
                            initTemplateFeatures();
                        }, 100);
                    }
                });
            }, 2000);
        }
        
        // Store reference for debugging
        $wrapper.data('popup-instance', {
            showModal: showModal,
            hideModal: hideModal,
            forceShowInEditor: forceShowInEditor,
            isEditor: isEditor,
            initTemplateFeatures: initTemplateFeatures
        });
    }

    // Multiple initialization methods to ensure it works in all contexts
    function initAllPopups() {
        console.log('[Unlock Popup Anywhere] Initializing all popups');
        $('.unlockafe-popup-anywhere-wrapper').each(function() {
            initPopupAnywhere($(this));
        });
    }

    // Standard document ready
    $(document).ready(function() {
        initAllPopups();
    });

    // Elementor Frontend Ready
    if (typeof window.elementorFrontend !== 'undefined') {
        // Wait for Elementor to be ready
        $(window).on('elementor/frontend/init', function() {
            setTimeout(initAllPopups, 100);
        });

        // Widget-specific hook
        if (window.elementorFrontend.hooks) {
            window.elementorFrontend.hooks.addAction('frontend/element_ready/unlockafe-popup-anywhere.default', function($scope) {
                var $wrapper = $scope.find('.unlockafe-popup-anywhere-wrapper');
                if ($wrapper.length) {
                    setTimeout(function() {
                        initPopupAnywhere($wrapper);
                    }, 100);
                }
            });
        }
    }

    // Additional fallback for editor
    setTimeout(function() {
        if ($('body').hasClass('elementor-editor-active') || 
            $('body').hasClass('elementor-edit-mode') || 
            window.location.href.indexOf('elementor-preview') !== -1) {
            initAllPopups();
        }
    }, 1000);

    // Additional aggressive fallback
    setTimeout(function() {
        $('.unlockafe-popup-anywhere-wrapper').each(function() {
            var instance = $(this).data('popup-instance');
            if (instance && instance.isEditor() && !instance.shown) {
                instance.forceShowInEditor();
            }
        });
    }, 2000);

    // Expose functions globally for debugging
    window.unlockafe_init_popup = initAllPopups;
    window.unlockafe_force_show = function() {
        $('.unlockafe-popup-anywhere-wrapper').each(function() {
            var instance = $(this).data('popup-instance');
            if (instance) {
                instance.forceShowInEditor();
            }
        });
    };
    
    // Debug countdown specifically
    window.unlockafe_debug_countdown = function() {
        $('.countdown-timer').each(function() {
            var $this = $(this);
            var endTimeStr = $this.data('countdown');
            if (endTimeStr) {
                var endTime = new Date(endTimeStr);
                var now = new Date();
            }
        });
    };
    
    // Force reinitialize countdown
    window.unlockafe_reinit_countdown = function() {
        $('.unlockafe-popup-anywhere-wrapper').each(function() {
            var instance = $(this).data('popup-instance');
            if (instance && instance.initTemplateFeatures) {
                instance.initTemplateFeatures();
            }
        });
    };
    
    // Test countdown with specific time
    window.unlockafe_test_countdown = function(testTimeStr) {
        if (!testTimeStr) {
            testTimeStr = '2025-06-26 13:32:06';
        }
        var endTime = new Date(testTimeStr);
        if (isNaN(endTime.getTime())) {
            // Try alternative parsing
            endTime = new Date(testTimeStr.replace(' ', 'T'));
        }
        
        var now = new Date();
        // Test manual countdown update
        $('.countdown-timer').each(function() {
            var $countdown = $(this);
            $countdown.attr('data-countdown', testTimeStr);
        });
        
        unlockafe_reinit_countdown();
    };
    
    // Quick fix for testing - manually set a working countdown
    window.unlockafe_fix_countdown = function() {
        console.log('=== QUICK COUNTDOWN FIX ===');
        
        // Find all countdown timers
        $('.countdown-timer').each(function() {
            var $countdown = $(this);
            // Set a test time 5 minutes from now
            var futureTime = new Date(Date.now() + (5 * 60 * 1000)); // 5 minutes from now
            var timeString = futureTime.getFullYear() + '-' + 
                            String(futureTime.getMonth() + 1).padStart(2, '0') + '-' + 
                            String(futureTime.getDate()).padStart(2, '0') + ' ' + 
                            String(futureTime.getHours()).padStart(2, '0') + ':' + 
                            String(futureTime.getMinutes()).padStart(2, '0') + ':' + 
                            String(futureTime.getSeconds()).padStart(2, '0');
            
            $countdown.attr('data-countdown', timeString);
            
            // Rebuild structure
            $countdown.html(`
                <div class="time-unit">
                    <span class="time-number" id="hours">00</span>
                    <span class="time-label">Hours</span>
                </div>
                <div class="time-separator">:</div>
                <div class="time-unit">
                    <span class="time-number" id="minutes">05</span>
                    <span class="time-label">Minutes</span>
                </div>
                <div class="time-separator">:</div>
                <div class="time-unit">
                    <span class="time-number" id="seconds">00</span>
                    <span class="time-label">Seconds</span>
                </div>
            `);
        });
        
        // Reinitialize
        unlockafe_reinit_countdown();
    };

})(jQuery); 