;(function ($) {
    "use strict";
    
/**
 * Email Capture Widget Frontend Fix
 * This script ensures the modal functionality works correctly
 */
// Debug helper function
function logDebug(message, data) {
    console.log('%c[EMAIL CAPTURE] ' + message, 'color: #3498db; font-weight: bold;', data || '');
}

function logError(message, error) {
    console.error('%c[EMAIL CAPTURE ERROR] ' + message, 'color: red; font-weight: bold;', error || '');
}

function logWarning(message, data) {
    console.warn('%c[EMAIL CAPTURE WARNING] ' + message, 'color: orange; font-weight: bold;', data || '');
}

function logSuccess(message, data) {
    console.log('%c[EMAIL CAPTURE SUCCESS] ' + message, 'color: green; font-weight: bold;', data || '');
}

// Debug DOM structure
function debugDOMStructure($element, prefix) {
    prefix = prefix || '';
    if (!$element || $element.length === 0) {
        logWarning(prefix + 'Element not found or empty');
        return;
    }

    logDebug(prefix + 'Element found: ' + $element[0].tagName + (($element.attr('class')) ? '.' + $element.attr('class').replace(/ /g, '.') : ''));
    logDebug(prefix + 'Visible:', $element.is(':visible'));
    logDebug(prefix + 'Display:', $element.css('display'));
    logDebug(prefix + 'Height:', $element.height());
    logDebug(prefix + 'Children count:', $element.children().length);
}

// Function to initialize email capture widgets
function initEmailCapture($wrappers) {
    logDebug('Initializing ' + $wrappers.length + ' widget(s)');

    // Find all email capture wrappers
    $wrappers.each(function () {
        var $wrapper = $(this);
        var widgetId = $wrapper.attr('id') || 'unknown';

        logDebug('Processing widget: ' + widgetId);
        debugDOMStructure($wrapper, 'Widget wrapper: ');

        // Skip if already initialized
        if ($wrapper.data('initialized')) {
            logWarning('Widget already initialized, skipping: ' + widgetId);
            return;
        }

        // Mark as initialized
        $wrapper.data('initialized', true);
        logSuccess('Widget marked as initialized: ' + widgetId);

        // Debug form fields
        var $formFields = $wrapper.find('.form-group');
        logDebug('Form fields found: ' + $formFields.length);
        debugDOMStructure($formFields, 'Form fields: ');

        // Try to parse settings, fallback to empty object if fails
        var settings;
        try {
            settings = $wrapper.data('settings');
            logDebug('Raw settings:', settings);

            // If settings is undefined, empty, or not an object
            if (!settings || typeof settings !== 'object') {
                logWarning('Settings not found or invalid, fallback to empty object');
                settings = {};
            }

            // If settings is a string, try to parse it as JSON
            if (typeof settings === 'string') {
                logDebug('Settings is a string, parsing as JSON');
                settings = JSON.parse(settings);
            }
        } catch (e) {
            logError('Error parsing widget settings', e);
            settings = {};
        }

        logDebug('Processed settings:', settings);

        // Make sure form fields are visible
        logDebug('Attempting to show form fields');
        var $formGroups = $wrapper.find('.form-group');
        logDebug('Form groups found:', $formGroups.length);
        debugDOMStructure($formGroups, 'Form groups: ');

        // Force display with multiple methods to ensure visibility
        $formGroups.show();
        $formGroups.css('display', 'block');
        $formGroups.removeClass('elementor-hidden');
        logSuccess('Form groups display forced to show');

        // Handle modal functionality
        if (settings.showAsModal === 'yes') {
            var $modalOverlay = $wrapper.find('.unlockafe-email-modal-overlay');
            var $modalContainer = $wrapper.find('.unlockafe-email-modal-container');
            var $closeBtn = $wrapper.find('.unlockafe-email-modal-close');
            var modalShown = false;

            // Function to show modal
            function showModal() {
                console.log('Showing modal');
                // Scroll to top for best UX
                window.scrollTo({ top: 0, behavior: 'smooth' });
                $modalOverlay.fadeIn();
                $modalContainer.fadeIn();
                modalShown = true;
                // Focus the first input in the modal form
                setTimeout(function () {
                    var $firstInput = $modalContainer.find('input:visible, textarea:visible, select:visible').first();
                    if ($firstInput.length) $firstInput.focus();
                }, 400);
            }

            // Modal closure functions - consolidated for reliability
            function closeAllModals() {
                $('.unlockafe-email-modal-overlay, .unlockafe-email-modal-container').fadeOut();
                logSuccess('All modals closed');
            }

            function closeThisModal() {
                $modalOverlay.fadeOut();
                $modalContainer.fadeOut();
                logSuccess('This modal closed');
            }

            // Use a single cookie per page to track modal display
            var pageUrl = $wrapper.data('page-url') || window.location.pathname;
            var cookieName = 'unlockafe_email_modal_shown_' + pageUrl.replace(/[^a-zA-Z0-9]/g, '_');
            var cookieValue = (function (name) {
                var value = "; " + document.cookie;
                var parts = value.split("; " + name + "=");
                if (parts.length === 2) return parts.pop().split(";").shift();
                return null;
            })(cookieName);
            console.log('[EMAIL CAPTURE FINAL DEBUG] Cookie name:', cookieName, '| Value:', cookieValue);
            // Only show if the page-level cookie is not set
            if (!cookieValue) {
                var displayMode = settings.displayMode || 'immediate';
                var displayDelay = parseInt(settings.displayDelay || 5, 10) * 1000;
                var scrollPercentage = parseInt(settings.scrollPercentage || 50, 10);
                console.log('[EMAIL CAPTURE FINAL DEBUG] Modal will show (cookie not set). Display mode:', displayMode);
                // Show based on the display mode
                if (displayMode === 'delay') {
                    setTimeout(showModal, displayDelay);
                } else if (displayMode === 'scroll') {
                    $(window).on('scroll', function () {
                        if (modalShown) return;
                        var scrollTop = $(window).scrollTop();
                        var docHeight = $(document).height();
                        var winHeight = $(window).height();
                        var scrollPercent = (scrollTop) / (docHeight - winHeight) * 100;
                        if (scrollPercent > scrollPercentage) {
                            showModal();
                            $(window).off('scroll');
                        }
                    });
                } else if (displayMode === 'exit_intent') {
                    $(document).on('mouseleave', function (e) {
                        if (modalShown) return;
                        if (e.clientY < 0) {
                            showModal();
                            $(document).off('mouseleave');
                        }
                    });
                } else {
                    setTimeout(showModal, 500);
                }
            } else {
                console.log('[EMAIL CAPTURE FINAL DEBUG] Modal will NOT show (cookie found):', cookieName);
            }
        }

        // Handle form submission with AJAX
        var $form = $wrapper.find('.email-capture-form');
        
        if ($form.length === 0) {
            console.log('[EMAIL CAPTURE] Form not found with selector .email-capture-form');
            return;
        }
        
        console.log('[EMAIL CAPTURE] Form found, setting up submission handler');

        // Unbind any previous submit handlers to prevent duplicates
        $form.off('submit.unlockafeEmailCapture').on('submit.unlockafeEmailCapture', function (e) {
            e.preventDefault();
            var $form = $(this);
            var formData = $form.serialize();

            // Always hide both messages before new submit
            $wrapper.find('.success-message').hide();
            $wrapper.find('.error-message').hide();

            $.ajax({
                url: $form.attr('action'),
                type: 'POST',
                data: formData,
                success: function (response) {
                    if (response.success) {
                        $form.hide();
                        $wrapper.find('.error-message').hide(); // Hide error
                        $wrapper.find('.success-message').show(); // Show success

                        // Set cookie to prevent showing again
                        var cookieExpiry = parseInt(settings.cookieExpiry || 7, 10);
                        var date = new Date();
                        date.setTime(date.getTime() + (cookieExpiry * 24 * 60 * 60 * 1000));
                        document.cookie = cookieName + '=true; expires=' + date.toUTCString() + '; path=/';

                        // Close modal after short delay if present
                        setTimeout(function () {
                            $wrapper.find('.unlockafe-email-modal-overlay, .unlockafe-email-modal-container').fadeOut();
                        }, 1200);
                    } else {
                        $form.show();
                        $wrapper.find('.success-message').hide(); // Hide success
                        var msg = response.message || (response.data && response.data.message) || 'An error occurred. Please try again.';
                        $wrapper.find('.error-message').text(msg).show().delay(4000).fadeOut();
                    }
                },
                error: function () {
                    $form.show();
                    $wrapper.find('.success-message').hide(); // Hide success
                    $wrapper.find('.error-message').text('An error occurred. Please try again.').show().delay(4000).fadeOut();
                }
            });
        });
    });
}

// Run initialization when DOM is ready
$(document).ready(function () {
    initEmailCapture($('.unlockafe-email-capture-wrapper'));
    // Reliable close button for all modals (event delegation)
    $(document).on('click', '.unlockafe-email-modal-close', function (e) {
        e.preventDefault();
        e.stopPropagation();
        var $modalOverlay = $(this).closest('.unlockafe-email-modal-overlay');
        var $modalContainer = $(this).closest('.unlockafe-email-modal-container');
        if ($modalOverlay.length) $modalOverlay.fadeOut();
        if ($modalContainer.length) $modalContainer.fadeOut();
        // Fallback: hide all overlays/containers if above fails
        if (!$modalOverlay.length && !$modalContainer.length) {
            $('.unlockafe-email-modal-overlay, .unlockafe-email-modal-container').fadeOut();
        }
        setModalCookieForPage();
    });
});

// Try to attach to document for direct DOM manipulation as a backup approach
$(document).on('click', '.elementor-widget-unlockafe-email-capture', function () {
    logDebug('Widget clicked - emergency display fix activated');
    var $widget = $(this);

    // Force display of all form groups anywhere in this widget
    $widget.find('.form-group, .unlockafe-email-form-field').each(function () {
        var $field = $(this);
        logDebug('Found field, forcing display:', $field);
        $field.attr('style', 'display: block !important; visibility: visible !important;');
        // Also show all children 
        $field.find('*').attr('style', 'display: block !important; visibility: visible !important;');
    });

    // Also try to find form fields directly
    $widget.find('input, select, textarea').each(function () {
        var $input = $(this);
        logDebug('Found input, ensuring display:', $input);
        $input.closest('.form-group, .unlockafe-email-form-field').attr('style', 'display: block !important; visibility: visible !important;');
    });
});

// Find and process all widgets immediately after page load
window.addEventListener('load', function () {
    logDebug('Window loaded - aggressive search for email widgets');

    var widgets = document.querySelectorAll('.elementor-widget-unlockafe-email-capture, .unlockafe-email-capture-wrapper');
    widgets.forEach(function (widget) {
        logDebug('Found widget on page load:', widget);

        // Force display of form fields
        var formFields = widget.querySelectorAll('.form-group, .unlockafe-email-form-field');
        formFields.forEach(function (field) {
            field.style.display = 'block';
            field.style.visibility = 'visible';
        });

        var inputs = widget.querySelectorAll('input, select, textarea');
        inputs.forEach(function (input) {
            var closestGroup = input.closest('.form-group, .unlockafe-email-form-field');
            if (closestGroup) {
                closestGroup.style.display = 'block';
                closestGroup.style.visibility = 'visible';
            }
        });
    });
});


// Fix for Elementor preview mode
if (typeof elementorFrontend !== 'undefined') {
    logDebug('Elementor frontend detected');

    // Special handler for Elementor editor preview
    if (typeof elementorFrontend.isEditMode === 'function' && elementorFrontend.isEditMode()) {
        logDebug('EDITOR MODE DETECTED - Special handling activated');

        // Make sure all form groups are visible in editor mode
        $('.elementor-widget-unlockafe-email-capture, .unlockafe-email-capture-wrapper').each(function () {
            var $widget = $(this);

            // Force all form fields to be visible with !important
            $widget.find('.form-group, .unlockafe-email-form-field, form, input, button, select, textarea').each(function () {
                $(this).attr('style', 'display: block !important; visibility: visible !important; opacity: 1 !important;');
            });

            // Only make buttons inline-block
            $widget.find('button, .submit-button').attr('style', 'display: inline-block !important; visibility: visible !important; opacity: 1 !important;');

            logSuccess('Editor mode visibility enforced for: ' + ($widget.attr('id') || 'unnamed widget'));
        });

        // Hide modal elements in editor mode
        $('.unlockafe-email-modal-overlay, .unlockafe-email-modal-container').hide();
    }

    try {
        // Check if hooks is available
        if (elementorFrontend.hooks) {
            logDebug('Elementor hooks found, registering handlers');

            // Handle global elements
            try {
                elementorFrontend.hooks.addAction('frontend/element_ready/global', function ($element) {
                    logDebug('Global element ready fired');

                    // Look for our widget specifically
                    var $widgetWrapper = $element.find('.unlockafe-email-capture-wrapper');

                    if ($widgetWrapper.length > 0) {
                        logDebug('Found widget in global hook, initializing');
                        initEmailCapture($widgetWrapper);

                        // Force display of form fields
                        $element.find('.form-group, .unlockafe-email-form-field').attr('style', 'display: block !important; visibility: visible !important;');
                    }
                });
                logDebug('Global hook registered successfully');
            } catch (hookError) {
                logError('Error registering global hook:', hookError);
            }

            // Handle our specific widget type
            try {
                elementorFrontend.hooks.addAction('frontend/element_ready/unlockafe-email-capture.default', function ($scope) {
                    logDebug('Specific widget hook fired');

                    // Force form fields to display immediately
                    $scope.find('.form-group, .unlockafe-email-form-field').attr('style', 'display: block !important; visibility: visible !important;');

                    // Also force any inputs to be visible
                    $scope.find('input, select, textarea').each(function () {
                        $(this).closest('.form-group, .unlockafe-email-form-field').attr('style', 'display: block !important; visibility: visible !important;');
                    });

                    // Initialize the widget if wrapper exists
                    var $widgetWrapper = $scope.find('.unlockafe-email-capture-wrapper');
                    if ($widgetWrapper.length > 0) {
                        initEmailCapture($widgetWrapper);
                    }
                });
                logDebug('Specific widget hook registered successfully');
            } catch (widgetHookError) {
                logError('Error registering specific widget hook:', widgetHookError);
            }
        } else {
            logWarning('Elementor frontend exists but hooks is undefined!');

            // Fallback for when hooks is undefined
            $(document).ready(function () {
                $('.elementor-widget-unlockafe-email-capture, .unlockafe-email-capture-wrapper').each(function () {
                    var $widget = $(this);
                    initEmailCapture($widget.find('.unlockafe-email-capture-wrapper'));
                });
            });
        }
    } catch (e) {
        logError('Error while setting up Elementor hooks:', e);
    }
} else {
    logWarning('Elementor frontend NOT detected');
}

// Helper: set the page-level modal cookie so modal won't show again
function setModalCookieForPage() {
    var pageUrl = window.location.pathname;
    var cookieName = 'unlockafe_email_modal_shown_' + pageUrl.replace(/[^a-zA-Z0-9]/g, '_');
    var cookieExpiry = 7; // default 7 days
    var date = new Date();
    date.setTime(date.getTime() + (cookieExpiry * 24 * 60 * 60 * 1000));
    document.cookie = cookieName + '=true; expires=' + date.toUTCString() + '; path=/';
}

})(jQuery);