/**
 * Wishlist Sidebar JavaScript functionality
 */
(function($) {
    'use strict';

    const WishlistSidebar = {
        settings: {},
        isOpen: false,
        products: [],
        
        // Initialize the wishlist sidebar
        init() {
            this.loadSettings();
            this.bindEvents();
            this.createFloatingButton();
        },

        // Load wishlist settings from backend
        loadSettings() {
            // Default settings (will be overridden by backend)
            this.settings = {
                enable_wishlist: false,
                enable_floating_button: false,
                floating_button_position: 'bottom-right',
                floating_button_style: 'circle',
                floating_button_color: '#e91e63',
                floating_button_text_color: '#ffffff',
                floating_button_size: 'medium',
                sidebar_width: 400,
                enable_quantity_controls: true,
                enable_total_calculation: true,
                show_product_images: true,
                auto_remove_after_cart: false
            };

            // Load settings from localized script if available
            if (typeof proddisp_wishlist_settings !== 'undefined') {
                this.settings = { ...this.settings, ...proddisp_wishlist_settings };
            }
        },

        // Bind all event listeners
        bindEvents() {
            // Floating button click (handle both class names)
            $(document).on('click', '.wcps-floating-wishlist-btn, .proddisp-floating-wishlist', this.toggleSidebar.bind(this));
            
            // Sidebar close
            $(document).on('click', '.wcps-wishlist-sidebar-close, .wcps-wishlist-sidebar-overlay', this.closeSidebar.bind(this));
            
            // Quantity controls
            $(document).on('click', '.wcps-wishlist-qty-plus', this.increaseQuantity.bind(this));
            $(document).on('click', '.wcps-wishlist-qty-minus', this.decreaseQuantity.bind(this));
            $(document).on('change', '.wcps-wishlist-qty-input', this.updateQuantity.bind(this));
            
            // Remove from wishlist
            $(document).on('click', '.wcps-wishlist-sidebar-remove', this.removeFromWishlist.bind(this));
            
            // Add to cart from sidebar
            $(document).on('click', '.wcps-wishlist-sidebar-add-to-cart', this.addToCartFromSidebar.bind(this));
            
            // Checkout and wishlist page buttons
            $(document).on('click', '.wcps-wishlist-checkout-btn', this.goToCheckout.bind(this));
            $(document).on('click', '.wcps-wishlist-page-btn', this.goToWishlistPage.bind(this));
            
            // Listen for wishlist updates
            $(document).on('wcps_wishlist_updated', this.loadWishlistData.bind(this));
            
            // Escape key to close sidebar
            $(document).on('keydown', (e) => {
                if (e.key === 'Escape' && this.isOpen) {
                    this.closeSidebar();
                }
            });
        },

        // Enhance existing floating button or create new one
        createFloatingButton() {
            if (!this.settings.enable_wishlist || !this.settings.enable_floating_button) {
                console.log('Floating button not created:', {
                    enable_wishlist: this.settings.enable_wishlist,
                    enable_floating_button: this.settings.enable_floating_button
                });
                return;
            }

            console.log('Setting up floating button...');
            
            // Check if floating button already exists (created by PHP)
            let $existingButton = $('#proddisp-floating-wishlist');
            
            if ($existingButton.length) {
                console.log('Enhancing existing floating button for sidebar');
                // Add sidebar classes to existing button
                $existingButton.addClass('wcps-floating-wishlist-btn');
                
                // Make sure it has the right click handler (will be bound by bindEvents)
                return;
            }

            // If no existing button, create new one
            console.log('Creating new floating button...');
            const buttonHtml = `
                <div id="proddisp-floating-wishlist" class="wcps-floating-wishlist-btn proddisp-floating-wishlist ${this.settings.floating_button_style} ${this.settings.floating_button_size} ${this.settings.floating_button_position}"
                     style="background-color: ${this.settings.floating_button_color}; color: ${this.settings.floating_button_text_color};">
                    <span class="proddisp-floating-icon">
                        <i class="fas fa-heart"></i>
                    </span>
                    <span class="wcps-wishlist-count proddisp-floating-count">0</span>
                </div>
            `;

            $('body').append(buttonHtml);
            console.log('New floating button HTML appended to body');
        },

        // Create sidebar
        createSidebar() {
            if (!this.settings.enable_wishlist) {
                console.log('Sidebar not created: wishlist disabled');
                return;
            }
            
            console.log('Creating sidebar...');

            const sidebarHtml = `
                <div class="wcps-wishlist-sidebar-overlay"></div>
                <div class="wcps-wishlist-sidebar" style="width: ${this.settings.sidebar_width}px;">
                    <div class="wcps-wishlist-sidebar-header">
                        <h3>
                            <i class="fas fa-heart"></i>
                            My Wishlist
                            <span class="wcps-wishlist-sidebar-count">(0)</span>
                        </h3>
                        <button class="wcps-wishlist-sidebar-close">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    <div class="wcps-wishlist-sidebar-content">
                        <div class="wcps-wishlist-sidebar-products">
                            <!-- Products will be loaded here -->
                        </div>
                    </div>
                    <div class="wcps-wishlist-sidebar-footer">
                        <div class="wcps-wishlist-total" style="display: ${this.settings.enable_total_calculation ? 'block' : 'none'};">
                            <strong>Total: <span class="wcps-wishlist-total-amount">$0.00</span></strong>
                        </div>
                        <div class="wcps-wishlist-sidebar-actions">
                            <button class="wcps-wishlist-checkout-btn wcps-btn wcps-btn-primary">
                                <i class="fas fa-shopping-cart"></i>
                                Go to Checkout
                            </button>
                            <button class="wcps-wishlist-page-btn wcps-btn wcps-btn-outline">
                                <i class="fas fa-heart"></i>
                                Wishlist Page
                            </button>
                        </div>
                    </div>
                </div>
            `;

            $('body').append(sidebarHtml);
            console.log('Sidebar HTML appended to body');
        },

        // Toggle sidebar
        toggleSidebar() {
            console.log('Toggle sidebar clicked, isOpen:', this.isOpen);
            if (this.isOpen) {
                this.closeSidebar();
            } else {
                this.openSidebar();
            }
        },

        // Open 
        goToCheckout() {
            if (typeof wc_checkout_params !== 'undefined' && wc_checkout_params.checkout_url) {
                window.location.href = wc_checkout_params.checkout_url;
            } else {
                window.location.href = '/checkout/';
            }
        },

        // Go to wishlist page
        goToWishlistPage() {
            // Try to find wishlist page URL from settings or use default
            const wishlistPageUrl = proddisp_params.wishlist_page_url || '/wishlist/';
            window.location.href = wishlistPageUrl;
        },

        // Show notification
        showNotification(message, type = 'info') {
            // Remove existing notifications
            $('.wcps-notification-sidebar').remove();
            
            const $notification = $(`
                <div class="wcps-notification-sidebar wcps-notification-sidebar-${type}">
                    <span class="wcps-notification-sidebar-message">${message}</span>
                    <button class="wcps-notification-sidebar-close">&times;</button>
                </div>
            `);
            
            $('body').append($notification);
            
            // Show notification
            setTimeout(() => {
                $notification.addClass('show');
            }, 100);
            
            // Auto hide after 5 seconds
            setTimeout(() => {
                this.hideNotification($notification);
            }, 5000);
            
            // Close button
            $notification.find('.wcps-notification-sidebar-close').on('click', () => {
                this.hideNotification($notification);
            });
        },

        // Hide notification
        hideNotification($notification) {
            $notification.removeClass('show');
            setTimeout(() => {
                $notification.remove();
            }, 300);
        }
    };

    // Initialize when document is ready
    $(document).ready(() => {
        console.log('Initializing WishlistSidebar...');
        
        // Check if sidebar CSS is loaded
        const testElement = $('<div class="wcps-wishlist-sidebar" style="position: absolute; top: -9999px;"></div>');
        $('body').append(testElement);
        const hasCSS = testElement.css('z-index') === '9999';
        testElement.remove();
        console.log('Sidebar CSS loaded:', hasCSS);
        
        // Wait a bit to ensure main wishlist is initialized first
        setTimeout(() => {
            WishlistSidebar.init();
        }, 100);
    });

    // Make it globally available
    window.WishlistSidebar = WishlistSidebar;

})(jQuery);