/**
 * Side Cart Functionality
 * Floating cart button that opens a side panel with cart contents
 */

(function($) {
    'use strict';

    // Utility functions
    function isSideCartEnabled() {
        return window.ckfylt25SideCartEnabled === true;
    }

    function getSideCartConfig() {
        return window.ckfylt25SideCartConfig || {};
    }

    function isPopupCart() {
        return getSideCartConfig().type === 'popup';
    }

    function isAutoOpenEnabled() {
        return getSideCartConfig().autoOpen === true;
    }

    // Clean HTML function
    function cleanHtml(html) {
        return html.replace(/<[^>]*>/g, '').trim();
    }

    // Create floating button
    function createFloatingButton() {
        if (!isSideCartEnabled()) return;

        const config = getSideCartConfig();
        const buttonColor = config.buttonColor || '#0073aa';

        const button = $(`
            <div id="ckfylt25-floating-cart" style="background-color: ${buttonColor};">
                <span class="ckfylt25-cart-icon">🛒</span>
                <span class="ckfylt25-cart-count">0</span>
            </div>
        `);

        $('body').append(button);
        updateCartCount();
    }

    // Create cart panel (side or popup)
    function createCartPanel() {
        if (!isSideCartEnabled()) return;

        const config = getSideCartConfig();
        const bgColor = config.backgroundColor || '#ffffff';
        const modalColor = config.modalColor || '#ffffff';
        const buttonColor = config.buttonColor || '#0073aa';

        if (isPopupCart()) {
            // Create popup modal
            const modal = $(`
                <div id="ckfylt25-cart-modal" class="ckfylt25-modal-overlay">
                    <div class="ckfylt25-modal-content" style="background-color: ${modalColor};">
                        <div class="ckfylt25-modal-header">
                            <h3>Your Cart</h3>
                            <button class="ckfylt25-modal-close">×</button>
                        </div>
                        <div class="ckfylt25-modal-body">
                            <div class="ckfylt25-cart-items"></div>
                            <div class="ckfylt25-cart-empty" style="display: none;">
                                <p>Your cart is empty</p>
                            </div>
                        </div>
                        <div class="ckfylt25-modal-footer">
                            <div class="ckfylt25-total-section">
                                <strong>Total: <span class="ckfylt25-total-amount">$0.00</span></strong>
                            </div>
                            <button class="ckfylt25-checkout-btn" style="background-color: ${buttonColor};">
                                Checkout
                            </button>
                        </div>
                    </div>
                </div>
            `);
            $('body').append(modal);
        } else {
            // Create side cart panel
            const overlay = $('<div class="ckfylt25-side-cart-overlay"></div>');
            $('body').append(overlay);

            const panel = $(`
                <div id="ckfylt25-side-cart" style="background-color: ${bgColor};">
                    <div class="ckfylt25-side-cart-header">
                        <h3>Your Cart</h3>
                        <button class="ckfylt25-side-cart-close">×</button>
                    </div>
                    <div class="ckfylt25-side-cart-content">
                        <div class="ckfylt25-side-cart-items"></div>
                        <div class="ckfylt25-side-cart-empty" style="display: none;">
                            <p>Your cart is empty</p>
                        </div>
                    </div>
                    <div class="ckfylt25-side-cart-footer">
                        <div class="ckfylt25-total-section">
                            <strong>Total: <span class="ckfylt25-total-amount">$0.00</span></strong>
                        </div>
                        <button class="ckfylt25-side-cart-checkout" style="background-color: ${buttonColor};">
                            Checkout
                        </button>
                    </div>
                </div>
            `);
            $('body').append(panel);
        }
    }

    // Update cart count
    function updateCartCount() {
        $.ajax({
            url: ckfylt25SideCartData.ajaxUrl,
            type: 'POST',
            data: {
                action: 'ckfylt25_get_cart_count',
                nonce: ckfylt25SideCartData.nonce
            },
            success: function(response) {
                if (response.success) {
                    $('.ckfylt25-cart-count').text(response.data.count);
                }
            }
        });
    }

    // Load cart contents
    function loadCartContents() {
        $.ajax({
            url: ckfylt25SideCartData.ajaxUrl,
            type: 'POST',
            data: {
                action: 'ckfylt25_get_cart_contents',
                nonce: ckfylt25SideCartData.nonce
            },
            success: function(response) {
                if (response.success) {
                    console.log('Side Cart: Cart contents loaded', response.data);
                    displayCartItems(response.data.items);
                    updateTotal(response.data.total);
                }
            }
        });
    }

    // Display cart items
    function displayCartItems(items) {
        const container = isPopupCart() ? $('.ckfylt25-cart-items') : $('.ckfylt25-side-cart-items');
        const emptyMessage = isPopupCart() ? $('.ckfylt25-cart-empty') : $('.ckfylt25-side-cart-empty');

        if (items.length === 0) {
            container.hide();
            emptyMessage.show();
            return;
        }

        container.show();
        emptyMessage.hide();

        let html = '';
        items.forEach(function(item) {
            const cleanName = cleanHtml(item.name);
            const cleanPrice = cleanHtml(item.price);
            
            html += `
                <div class="ckfylt25-cart-item" data-key="${item.key}">
                    <div class="ckfylt25-cart-item-image">
                        <img src="${item.image}" alt="${item.name}" />
                    </div>
                    <div class="ckfylt25-cart-item-details">
                        <div class="ckfylt25-cart-item-name">${item.name}</div>
                        <div class="ckfylt25-cart-item-price">${cleanPrice}</div>
                        <div class="ckfylt25-cart-item-quantity">
                            <button class="ckfylt25-quantity-btn ckfylt25-quantity-minus" data-key="${item.key}">-</button>
                            <span class="ckfylt25-quantity-value">${item.quantity}</span>
                            <button class="ckfylt25-quantity-btn ckfylt25-quantity-plus" data-key="${item.key}">+</button>
                        </div>
                    </div>
                    <button class="ckfylt25-cart-item-remove" data-key="${item.key}">×</button>
                </div>
            `;
        });

        container.html(html);
    }

    // Update total
    function updateTotal(total) {
        const cleanTotal = cleanHtml(total);
        $('.ckfylt25-total-amount').text(cleanTotal);
    }

    // Open cart
    function openCart() {
        if (isPopupCart()) {
            $('#ckfylt25-cart-modal').addClass('ckfylt25-modal-active');
            loadCartContents();
        } else {
            $('#ckfylt25-side-cart').addClass('ckfylt25-side-cart-open');
            $('.ckfylt25-side-cart-overlay').addClass('ckfylt25-overlay-active');
            loadCartContents();
        }
    }

    // Close cart
    function closeCart() {
        if (isPopupCart()) {
            $('#ckfylt25-cart-modal').removeClass('ckfylt25-modal-active');
        } else {
            $('#ckfylt25-side-cart').removeClass('ckfylt25-side-cart-open');
            $('.ckfylt25-side-cart-overlay').removeClass('ckfylt25-overlay-active');
        }
    }

    // Handle quantity change
    function handleQuantityChange(key, change) {
        $.ajax({
            url: ckfylt25SideCartData.ajaxUrl,
            type: 'POST',
            data: {
                action: 'ckfylt25_update_cart_quantity',
                key: key,
                change: change,
                nonce: ckfylt25SideCartData.nonce
            },
            success: function(response) {
                if (response.success) {
                    updateCartCount();
                    loadCartContents();
                }
            }
        });
    }

    // Handle item removal
    function handleItemRemove(key) {
        $.ajax({
            url: ckfylt25SideCartData.ajaxUrl,
            type: 'POST',
            data: {
                action: 'ckfylt25_remove_cart_item',
                key: key,
                nonce: ckfylt25SideCartData.nonce
            },
            success: function(response) {
                if (response.success) {
                    updateCartCount();
                    loadCartContents();
                }
            }
        });
    }

    // Bind events
    function bindEvents() {
        if (!isSideCartEnabled()) return;

        // Floating button click
        $(document).on('click', '#ckfylt25-floating-cart', function(e) {
            e.preventDefault();
            openCart();
        });

        // Close buttons
        $(document).on('click', '.ckfylt25-side-cart-close, .ckfylt25-modal-close', function(e) {
            e.preventDefault();
            closeCart();
        });

        // Overlay click (side cart only)
        $(document).on('click', '.ckfylt25-side-cart-overlay', function(e) {
            closeCart();
        });

        // Modal overlay click (popup cart)
        $(document).on('click', '.ckfylt25-modal-overlay', function(e) {
            if (e.target === e.currentTarget) {
                closeCart();
            }
        });

        // Quantity buttons
        $(document).on('click', '.ckfylt25-quantity-minus', function(e) {
            e.preventDefault();
            const key = $(this).data('key');
            handleQuantityChange(key, -1);
        });

        $(document).on('click', '.ckfylt25-quantity-plus', function(e) {
            e.preventDefault();
            const key = $(this).data('key');
            handleQuantityChange(key, 1);
        });

        // Remove item
        $(document).on('click', '.ckfylt25-cart-item-remove', function(e) {
            e.preventDefault();
            const key = $(this).data('key');
            handleItemRemove(key);
        });

        // Checkout button
        $(document).on('click', '.ckfylt25-side-cart-checkout, .ckfylt25-checkout-btn', function(e) {
            e.preventDefault();
            window.location.href = ckfylt25SideCartData.checkoutUrl;
        });

        // Auto open on add to cart
        if (isAutoOpenEnabled()) {
            $(document.body).on('added_to_cart', function() {
                updateCartCount();
                openCart();
            });
        } else {
            $(document.body).on('added_to_cart removed_from_cart updated_cart_totals', function() {
                updateCartCount();
            });
        }
    }

    // Initialize
    function initSideCart() {
        console.log('Side Cart: Checking if enabled...', isSideCartEnabled());
        if (isSideCartEnabled()) {
            if (window.location.href.includes('/cart/') || 
                window.location.href.includes('/checkout/') || 
                window.location.href.includes('/my-account/')) {
                console.log('Side Cart: Skipping on cart/checkout/my-account page');
                return;
            }
            createFloatingButton();
            createCartPanel();
            bindEvents();
            console.log('Side Cart enabled and initialized', {
                type: getSideCartConfig().type,
                autoOpen: getSideCartConfig().autoOpen
            });
        } else {
            console.log('Side Cart: Not enabled');
        }
    }

    // Document ready
    $(document).ready(function() {
        console.log('Side Cart: Document ready, checking if enabled...');
        initSideCart();
    });

    // WooCommerce fragment refresh
    $(document.body).on('wc_fragment_refresh', function() {
        updateCartCount();
    });

})(jQuery);