/**
 * Feature scripts for Product Display
 * 
 * Handles functionality for product features:
 * - Quick View
 * - Wishlist
 * - Compare
 * - Add to Cart AJAX
 */

(function ($) {
    'use strict';

    // WCPS Features Object
    var PRODDISP_Features = {
        /**
         * Initialize
         */
        init: function () {
            this.initQuickView();
            this.initWishlist();
        },

        /**
         * Initialize Quick View
         */
        initQuickView: function () {
            // Quick view button click
            $(document).on('click', '.wcps-quickview', function (e) {
                e.preventDefault();

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

                // Create modal if it doesn't exist
                if (!$('#wcps-quickview-modal').length) {
                    $('body').append('<div id="wcps-quickview-modal" class="wcps-modal"><div class="wcps-modal-content"><span class="wcps-modal-close">&times;</span><div class="wcps-modal-body"></div></div></div>');
                }

                var $modal = $('#wcps-quickview-modal');
                var $modalBody = $modal.find('.wcps-modal-body');

                // Show loading
                $modalBody.html('<div class="wcps-loading-spinner"></div>');
                $modal.addClass('wcps-modal-open');

                // Fetch product data with AJAX
                $.ajax({
                    url: proddisp_params.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'proddisp_quickview',
                        nonce: proddisp_params.nonce,
                        product_id: productId
                    },
                    success: function (response) {
                        if (response.success) {
                            $modalBody.html(response.data.html);

                            // Init our custom quickview gallery (thumbnail switching)
                            PRODDISP_Features.initQuickViewGallery($modalBody);

                            // Initialize quantity buttons (WC native +/- buttons)
                            PRODDISP_Features.initQuantityButtons($modalBody);

                            // Initialize variation form if product is variable
                            if ($.fn.wc_variation_form) {
                                $modalBody.find('.variations_form').each(function () {
                                    $(this).wc_variation_form();
                                });
                            }
                        } else {
                            $modalBody.html('<p class="wcps-error">' + response.data.message + '</p>');
                        }
                    },
                    error: function () {
                        $modalBody.html('<p class="wcps-error">Error loading product. Please try again.</p>');
                    }
                });
            });

            // Close quick view modal
            $(document).on('click', '#wcps-quickview-modal .wcps-modal-close', function () {
                $('#wcps-quickview-modal').removeClass('wcps-modal-open');
            });

            $(document).on('click', '#wcps-quickview-modal', function (e) {
                if (e.target === this) {
                    $('#wcps-quickview-modal').removeClass('wcps-modal-open');
                }
            });

            // Close on escape key
            $(document).on('keyup', function (e) {
                if (e.key === 'Escape' && $('#wcps-quickview-modal').hasClass('wcps-modal-open')) {
                    $('#wcps-quickview-modal').removeClass('wcps-modal-open');
                }
            });
        },

        /**
         * Initialize Wishlist modal and button functionality
         */
        initWishlist: function () {
            // Wishlist button click
            $(document).on('click', '.wcps-wishlist', function (e) {
                e.preventDefault();

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

                // Check if AJAX is already in progress
                if ($button.hasClass('wcps-loading')) {
                    return;
                }

                // Add loading class
                $button.addClass('wcps-loading');

                // Toggle wishlist with AJAX
                $.ajax({
                    url: proddisp_params.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'proddisp_toggle_wishlist',
                        nonce: proddisp_params.nonce,
                        product_id: productId
                    },
                    success: function (response) {
                        $button.removeClass('wcps-loading');

                        if (response.success) {
                            // Update button state
                            var $allButtons = $('.wcps-wishlist[data-product-id="' + productId + '"]');
                            if (response.data.in_wishlist) {
                                $allButtons.addClass('in-wishlist');
                                $allButtons.attr('title', 'Remove from Wishlist');
                                $allButtons.find('.wcps-btn-cta').text('Remove from Wishlist');
                                // Open the wishlist modal after adding
                                PRODDISP_Features.openWishlistModal();
                            } else {
                                $allButtons.removeClass('in-wishlist');
                                $allButtons.attr('title', 'Add to Wishlist');
                                $allButtons.find('.wcps-btn-cta').text('Add to Wishlist');
                            }
                            // Show notification
                            PRODDISP_Features.showNotification(response.data.message);
                            // Update wishlist counter if exists
                            if (response.data.count !== undefined) {
                                $('.wcps-wishlist-count').text(response.data.count);
                            }
                        } else {
                            PRODDISP_Features.showNotification(response.data.message, 'error');
                        }
                    },
                    error: function () {
                        $button.removeClass('wcps-loading');
                        PRODDISP_Features.showNotification('Error processing request. Please try again.', 'error');
                    }
                });
            });

            // Open wishlist modal
            $(document).on('click', '.wcps-wishlist-open-modal', function (e) {
                e.preventDefault();
                PRODDISP_Features.openWishlistModal();
            });

            // Close wishlist modal
            $(document).on('click', '.wcps-modal-close, .wcps-modal-overlay', function (e) {
                e.preventDefault();
                PRODDISP_Features.closeWishlistModal();
            });

            // Close modal when clicking outside content
            $(document).on('click', '#wcps-wishlist-modal', function (e) {
                if (e.target === this) {
                    PRODDISP_Features.closeWishlistModal();
                }
            });

            // Close modal with ESC key
            $(document).keyup(function (e) {
                if (e.key === "Escape" && $('#wcps-wishlist-modal').hasClass('wcps-modal-open')) {
                    PRODDISP_Features.closeWishlistModal();
                }
            });


        },

        // Wishlist open and close 
        
        /**
         * Open the shared lightbox with a single image (used by compare table).
         */
        openSingleLightbox: function (src, alt) {
            // Ensure lightbox DOM exists (may not if quickview was never opened)
            if (!$('#wcps-qv-lightbox').length) {
                $('body').append(
                    '<div id="wcps-qv-lightbox" role="dialog" aria-modal="true" aria-label="Image gallery">' +
                        '<div class="wcps-lb-overlay"></div>' +
                        '<div class="wcps-lb-inner">' +
                            '<button class="wcps-lb-close" aria-label="Close">&times;</button>' +
                            '<button class="wcps-lb-nav wcps-lb-prev" aria-label="Previous image">&#8249;</button>' +
                            '<div class="wcps-lb-img-wrap">' +
                                '<img class="wcps-lb-img" src="" alt="" />' +
                                '<div class="wcps-lb-loader"></div>' +
                            '</div>' +
                            '<button class="wcps-lb-nav wcps-lb-next" aria-label="Next image">&#8250;</button>' +
                            '<div class="wcps-lb-counter"></div>' +
                        '</div>' +
                    '</div>'
                );

                var $lb = $('#wcps-qv-lightbox');
                $lb.find('.wcps-lb-close').on('click', function () {
                    $lb.removeClass('wcps-lb-open');
                    $('body').removeClass('wcps-lb-body-lock');
                });
                $lb.find('.wcps-lb-overlay').on('click', function () {
                    $lb.removeClass('wcps-lb-open');
                    $('body').removeClass('wcps-lb-body-lock');
                });
                $(document).on('keydown.wcpslb', function (e) {
                    if (e.key === 'Escape' && $lb.hasClass('wcps-lb-open')) {
                        $lb.removeClass('wcps-lb-open');
                        $('body').removeClass('wcps-lb-body-lock');
                    }
                });
            }

            var $lb      = $('#wcps-qv-lightbox');
            var $lbImg   = $lb.find('.wcps-lb-img');
            var $lbLoader = $lb.find('.wcps-lb-loader');

            // Single image: hide nav arrows and counter
            $lb.find('.wcps-lb-nav').hide();
            $lb.find('.wcps-lb-counter').hide();

            $lbImg.css('opacity', 0);
            $lbLoader.show();

            var tmp = new Image();
            tmp.onload = function () {
                $lbImg.attr('src', src).attr('alt', alt);
                $lbLoader.hide();
                $lbImg.css({ opacity: 1, transition: 'opacity 0.25s ease' });
            };
            tmp.src = src;

            $lb.addClass('wcps-lb-open');
            $('body').addClass('wcps-lb-body-lock');
        },

        /**
         * Refresh Compare Table
         */
        refreshCompareTable: function () {
            var $modal = $('#wcps-compare-modal');
            var $modalBody = $modal.find('.wcps-modal-body');

            // Show loading
            $modalBody.html('<div class="wcps-loading-spinner"></div>');

            // Fetch compare data with AJAX
            $.ajax({
                url: proddisp_params.ajax_url,
                type: 'POST',
                data: {
                    action: 'proddisp_get_compare_table',
                    nonce: proddisp_params.nonce
                },
                success: function (response) {
                    if (response.success) {
                        $modalBody.html(response.data.html);
                    } else {
                        $modalBody.html('<p class="wcps-error">' + response.data.message + '</p>');
                    }
                },
                error: function () {
                    $modalBody.html('<p class="wcps-error">Error loading compare data. Please try again.</p>');
                }
            });
        },

        
        /**
         * Show notification
         */
        showNotification: function (message, type) {
            type = type || 'success';

            // Remove existing notification
            $('.wcps-notification').remove();

            // Create notification
            var $notification = $('<div class="wcps-notification wcps-notification-' + type + '">' + message + '</div>');
            $('body').append($notification);

            // Show notification with animation
            setTimeout(function () {
                $notification.addClass('wcps-notification-show');
            }, 10);

            // Hide notification after delay
            setTimeout(function () {
                $notification.removeClass('wcps-notification-show');
                setTimeout(function () {
                    $notification.remove();
                }, 300);
            }, 3000);
        }
    };

    // Initialize on document ready
    $(document).ready(function () {
        PRODDISP_Features.init();
    });

    // Add this outside the AJAX handler, after PRODDISP_Features.initAjaxAddToCart definition
    $(document).on('click', '.wcps-view-cart-btn .wcps-btn-cta', function (e) {
        e.preventDefault();
        var $btn = $(this).closest('.wcps-view-cart-btn');
        var $hiddenViewCart = $btn.siblings('.added_to_cart.wc-forward:visible:first');
        if ($hiddenViewCart.length) {
            $hiddenViewCart[0].click();
        } else {
            window.location.href = '/cart/';
        }
    });

})(jQuery);