/**
 * GGM Commerce Quick View
 *
 * Handles Quick View popup functionality - AJAX loading of product popup content
 */

jQuery(document).ready(function($) {

    // Prevent multiple initializations
    if (window.ggmCommerceQuickViewInitialized) {
        return;
    }
    window.ggmCommerceQuickViewInitialized = true;

    // State
    var isLoading = false;
    var $overlay = null;
    var $popup = null;

    /**
     * Initialize Quick View functionality
     */
    function init() {
        // Bind click events to Quick View buttons
        $(document).on('click', '.quick-view-btn', handleQuickViewClick);

        // Create overlay and popup elements
        createPopupStructure();

        // Bind close events
        bindCloseEvents();
    }

    /**
     * Create popup HTML structure
     */
    function createPopupStructure() {
        // Only create if not already exists
        if ($('#ggmc-quick-view-overlay').length) {
            $overlay = $('#ggmc-quick-view-overlay');
            $popup = $('#ggmc-quick-view-popup');
            return;
        }

        var html = '<div id="ggmc-quick-view-overlay" class="ggmc-quick-view-overlay">' +
                       '<div id="ggmc-quick-view-popup" class="ggmc-quick-view-popup">' +
                           '<button class="ggmc-quick-view-close" aria-label="Close Quick View">' +
                               '<span class="dashicons dashicons-no-alt"></span>' +
                           '</button>' +
                           '<div class="ggmc-quick-view-content"></div>' +
                       '</div>' +
                   '</div>';

        $('body').append(html);
        $overlay = $('#ggmc-quick-view-overlay');
        $popup = $('#ggmc-quick-view-popup');
    }

    /**
     * Bind close events
     */
    function bindCloseEvents() {
        // Close button
        $(document).on('click', '.ggmc-quick-view-close', closePopup);

        // Click outside popup (on overlay)
        $(document).on('click', '#ggmc-quick-view-overlay', function(e) {
            if ($(e.target).is('#ggmc-quick-view-overlay')) {
                closePopup();
            }
        });

        // Escape key
        $(document).on('keydown', function(e) {
            if (e.key === 'Escape' && $overlay && $overlay.hasClass('active')) {
                closePopup();
            }
        });

        // Close popup when clicking "View Full Details" link (or any link with ggmc-close-quick-view class)
        $(document).on('click', '.ggmc-close-quick-view', function() {
            // Allow the link to navigate normally, just close the popup first
            closePopup();
        });
    }

    /**
     * Handle Quick View button click
     */
    function handleQuickViewClick(e) {
        e.preventDefault();
        e.stopPropagation();

        if (isLoading) {
            return;
        }

        var $button = $(this);
        var productId = $button.data('product-id');

        if (!productId) {
            console.error('Quick View: No product ID found');
            return;
        }

        loadQuickView(productId, $button);
    }

    /**
     * Load Quick View content via AJAX
     */
    function loadQuickView(productId, $button) {
        isLoading = true;

        // Show loading state
        showLoading($button);

        // Make AJAX request
        $.ajax({
            url: ggmCommerceQuickView.ajax_url,
            type: 'POST',
            data: {
                action: 'ggm_commerce_quick_view',
                product_id: productId,
                nonce: ggmCommerceQuickView.nonce
            },
            success: function(response) {
                if (response.success) {
                    displayPopup(response.data);
                } else {
                    showError(response.data.message || 'Failed to load Quick View');
                }
            },
            error: function(xhr, status, error) {
                showError('An error occurred. Please try again.');
                console.error('Quick View AJAX error:', error);
            },
            complete: function() {
                isLoading = false;
                hideLoading($button);
            }
        });
    }

    /**
     * Display the popup with content
     */
    function displayPopup(data) {
        if (!$popup || !$overlay) {
            createPopupStructure();
        }

        var $content = $popup.find('.ggmc-quick-view-content');

        // Insert content
        $content.html(data.html);

        // Show popup
        $overlay.addClass('active');
        $popup.addClass('active');

        // Prevent body scroll
        $('body').addClass('ggmc-quick-view-open');

        // Re-initialize any Elementor widgets/swiper/etc
        reinitializeWidgets($content);

        // Trigger custom event
        $(document).trigger('ggm_commerce_quick_view_opened', {
            product_id: data.product_id,
            product_name: data.product_name
        });
    }

    /**
     * Close the popup
     */
    function closePopup() {
        if (!$overlay || !$popup) {
            return;
        }

        $overlay.removeClass('active');
        $popup.removeClass('active');

        // Allow body scroll
        $('body').removeClass('ggmc-quick-view-open');

        // Clear content after animation
        setTimeout(function() {
            $popup.find('.ggmc-quick-view-content').html('');
        }, 300);

        // Trigger custom event
        $(document).trigger('ggm_commerce_quick_view_closed');
    }

    /**
     * Re-initialize widgets after AJAX load
     */
    function reinitializeWidgets($container) {
        // Trigger Elementor frontend init if available
        if (typeof elementorFrontend !== 'undefined' && elementorFrontend.elementsHandler) {
            try {
                // Find all Elementor widgets in the container
                $container.find('.elementor-widget').each(function() {
                    elementorFrontend.elementsHandler.runReadyTrigger($(this));
                });
            } catch (e) {
                // Elementor widget re-init not available
            }
        }

        // Re-trigger any Swiper instances
        if (typeof Swiper !== 'undefined') {
            $container.find('.swiper-container, .swiper').each(function() {
                var $swiper = $(this);
                if ($swiper.data('swiper')) {
                    $swiper.data('swiper').update();
                }
            });
        }

        // Trigger GGM Commerce cart widget handlers
        $(document).trigger('ggm_commerce_widgets_loaded', [$container]);
    }

    /**
     * Show loading state
     */
    function showLoading($button) {
        if ($button && $button.length) {
            $button.addClass('loading');
            $button.prop('disabled', true);
        }

        // Show overlay with loading indicator
        if ($overlay) {
            $overlay.addClass('active loading');
            $popup.find('.ggmc-quick-view-content').html(
                '<div class="ggmc-quick-view-loading">' +
                    '<div class="ggmc-loading-spinner"></div>' +
                    '<p>Loading...</p>' +
                '</div>'
            );
            $popup.addClass('active');
        }
    }

    /**
     * Hide loading state
     */
    function hideLoading($button) {
        if ($button && $button.length) {
            $button.removeClass('loading');
            $button.prop('disabled', false);
        }

        if ($overlay) {
            $overlay.removeClass('loading');
        }
    }

    /**
     * Show error message
     */
    function showError(message) {
        if ($popup && $popup.find('.ggmc-quick-view-content').length) {
            $popup.find('.ggmc-quick-view-content').html(
                '<div class="ggmc-quick-view-error">' +
                    '<div class="ggmc-error-icon"><span class="dashicons dashicons-warning"></span></div>' +
                    '<p>' + message + '</p>' +
                    '<button class="ggmc-quick-view-close-btn">Close</button>' +
                '</div>'
            );

            // Bind close button in error state
            $popup.find('.ggmc-quick-view-close-btn').on('click', closePopup);
        } else {
            // Fallback to alert
            alert(message);
        }
    }

    // Initialize on document ready
    init();

});
