jQuery(document).ready(function($) {
    'use strict';

    var selectedTemplateId = null;
    var selectedTemplatePrice = 0;
    var productPrice = 0;
    var productRegularPrice = 0;
    var productSalePrice = 0;
    var hasProductSale = false;

    // Get product price (including regular and sale price)
    function getProductPrice() {
        // First try to get from variation (WooCommerce stores it in data attribute)
        var $variationForm = $('form.variations_form');
        if ($variationForm.length > 0) {
            var variationData = $variationForm.data('product_variations');
            var $variationInputs = $variationForm.find('.variations select');

            // Get selected variation
            var selectedVariation = null;
            if (variationData && variationData.length > 0) {
                var allSelected = true;
                var selectedAttributes = {};

                $variationInputs.each(function() {
                    var $select = $(this);
                    var attrName = $select.attr('name');
                    var attrValue = $select.val();

                    if (!attrValue) {
                        allSelected = false;
                        return false;
                    }
                    selectedAttributes[attrName] = attrValue;
                });

                if (allSelected) {
                    // Find matching variation
                    for (var i = 0; i < variationData.length; i++) {
                        var variation = variationData[i];
                        var match = true;

                        for (var attr in selectedAttributes) {
                            if (variation.attributes[attr] !== selectedAttributes[attr]) {
                                match = false;
                                break;
                            }
                        }

                        if (match) {
                            selectedVariation = variation;
                            break;
                        }
                    }
                }
            }

            // If we found a variation, use its prices
            if (selectedVariation) {
                var displayPrice = parseFloat(selectedVariation.display_price) || 0;
                var regularPrice = parseFloat(selectedVariation.display_regular_price) || displayPrice;

                hasProductSale = displayPrice < regularPrice;
                productRegularPrice = regularPrice;
                productSalePrice = hasProductSale ? displayPrice : 0;

                console.log('Using variation price - Regular:', regularPrice, 'Sale:', displayPrice);
                return displayPrice;
            }
        }

        // Fallback: Get from price display in DOM
        var $priceContainer = $('.summary .price');
        var $delPrice = $priceContainer.find('del .woocommerce-Price-amount');
        var $insPrice = $priceContainer.find('ins .woocommerce-Price-amount');

        if ($delPrice.length > 0 && $insPrice.length > 0) {
            // Product is on sale
            hasProductSale = true;
            var regularText = $delPrice.first().text();
            var saleText = $insPrice.first().text();

            productRegularPrice = parseFloat(regularText.replace(/[^0-9.,]/g, '').replace(',', '.')) || 0;
            productSalePrice = parseFloat(saleText.replace(/[^0-9.,]/g, '').replace(',', '.')) || 0;

            return productSalePrice; // Return sale price as current price
        } else {
            // No sale, get regular price
            hasProductSale = false;
            var priceText = $priceContainer.find('.woocommerce-Price-amount').first().text();
            if (!priceText) {
                priceText = $('.summary .amount').first().text();
            }
            var price = parseFloat(priceText.replace(/[^0-9.,]/g, '').replace(',', '.')) || 0;
            productRegularPrice = price;
            productSalePrice = 0;

            return price;
        }
    }

    // Toggle gift form when checkbox is clicked
    $('#wpgv_add_gift_voucher').on('change', function() {
        if ($(this).is(':checked')) {
            $('#wpgv-gift-form-container').slideDown();
            // Don't add required attributes yet - wait for template selection
            productPrice = getProductPrice();
            loadTemplates();
        } else {
            $('#wpgv-gift-form-container').slideUp();
            // Remove required attributes when checkbox is unchecked
            $('#wpgv_your_name, #wpgv_recipient_name, #wpgv_recipient_email, #wpgv_your_email').prop('required', false);
            resetForm();
        }
    });

    // Load templates via AJAX
    function loadTemplates() {
        var $templatesList = $('#wpgv-templates-list');

        // show 5 placeholder skeleton items to match the grid while loading
        var placeholderHtml = '';
        for (var i = 0; i < 4; i++) {
            placeholderHtml += '<div class="wpgv-template-item loading" data-placeholder="1" style="min-height:100px;">';
            placeholderHtml += '<div class="wpgv-item-loading-label"><span class="wpgv-spinner"></span>Loading...</div>';
            placeholderHtml += '</div>';
        }
        $templatesList.addClass('loading').html(placeholderHtml);

        $.ajax({
            url: wpgv_product_gift_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'wpgv_get_modern_templates',
                nonce: wpgv_product_gift_ajax.nonce
            },
            success: function(response) {
                $templatesList.removeClass('loading');

                if (response.success && response.data && response.data.length > 0) {
                    renderTemplates(response.data);
                } else {
                    $templatesList.html('<p class="wpgv-templates-error">No templates found.</p>');
                }
            },
            error: function() {
                $templatesList.removeClass('loading');
                $templatesList.html('<p class="wpgv-templates-error">Failed to load templates. Please try again.</p>');
            }
        });
    }

    // Render templates
    function renderTemplates(templates) {
        var $templatesList = $('#wpgv-templates-list');
        var html = '';

        $.each(templates, function(index, template) {
            var priceLabel = '';
            if (template.price && template.price > 0) {
                priceLabel = '<div class="template-price-badge">+' + formatPrice(template.price) + '</div>';
            }

            var orientation = (typeof template.is_landscape !== 'undefined' && template.is_landscape) ? 'landscape' : 'portrait';
            html += '<div class="wpgv-template-item" data-template-id="' + template.id + '" data-template-price="' + (template.price || 0) + '" data-orientation="' + orientation + '">';
            html += priceLabel;
            html += '<img src="' + template.image + '" alt="' + template.title + '">';
            html += '<div class="template-title" style="display:none">' + template.title + '</div>';
            html += '<div class="selected-badge">✓</div>';
            html += '</div>';
        });

        $templatesList.html(html);

        // Attach click event to templates
        $('.wpgv-template-item').on('click', function() {
            selectTemplate($(this));
        });

        // Initialize template tabs (filtering)
        setupTemplateTabs();
    }

    // Setup tabs to filter templates by orientation
    function setupTemplateTabs() {
        var $tabs = $('#wpgv-template-tabs');
        if (!$tabs.length) return;

        $tabs.off('click', '.wpgv-template-tab').on('click', '.wpgv-template-tab', function() {
            var $btn = $(this);
            var orientation = $btn.data('orientation');

            // Toggle active class
            $tabs.find('.wpgv-template-tab').removeClass('active');
            $btn.addClass('active');

            // Show only items with matching data-orientation
            $('.wpgv-template-item').each(function() {
                var $item = $(this);
                if ($item.data('orientation') === orientation) {
                    $item.show();
                } else {
                    $item.hide();
                }
            });

            // If a selected template is hidden, deselect it and clear preview
            var $selected = $('.wpgv-template-item.selected');
            if ($selected.length && !$selected.is(':visible')) {
                $selected.removeClass('selected');
                selectedTemplateId = null;
                selectedTemplatePrice = 0;
                $('#wpgv_selected_template_id').val('');
                $('#wpgv-gift-form-fields').hide();

                // Remove required attributes from form fields
                $('#wpgv_your_name, #wpgv_recipient_name, #wpgv_recipient_email, #wpgv_your_email').prop('required', false);

                // Clear and hide preview
                var $previewContainer = $('#wpgv-template-preview-container');
                $previewContainer.hide();
                $('#wpgv_template_canvas_container').removeClass('selected loading').empty();
            }
        });

        // Default to landscape tab
        var $defaultTab = $tabs.find('.wpgv-template-tab[data-orientation="landscape"]');
        if ($defaultTab.length) {
            $defaultTab.trigger('click');
        } else {
            // If no tab found, show all
            $('.wpgv-template-item').show();
        }
    }

    // Toggle canvas preview skeleton during template load
    $(document).on('wpgv_template_load_start', function(e, templateId) {
        // Only show when this template is the currently selected (or when selection is in progress)
        // Add loading class and label
        var $container = $('#wpgv_template_canvas_container');
        $container.addClass('loading');
        if (!$container.find('.wpgv-canvas-loading-label').length) {
            $container.append('<div class="wpgv-canvas-loading-label">Loading preview...</div>');
        }
        // Ensure preview container visible while loading
        $('#wpgv-template-preview-container').slideDown();
    });

    $(document).on('wpgv_template_loaded.wpgvCanvasLoad', function(e, templateId) {
        var $container = $('#wpgv_template_canvas_container');
        $container.removeClass('loading');
        $container.find('.wpgv-canvas-loading-label').remove();
        // Mark preview container as selected and remove loading
        $container.removeClass('loading').addClass('selected');
    });

    $(document).on('wpgv_template_load_error.wpgvCanvasLoad', function(e, templateId, info) {
        var $container = $('#wpgv_template_canvas_container');
        $container.removeClass('loading');
        $container.find('.wpgv-canvas-loading-label').remove();
        // Optionally show a small inline error message inside preview
        if (!$container.find('.wpgv-canvas-error').length) {
            $container.append('<div class="wpgv-canvas-error">Failed to load preview.</div>');
        }
        // Remove preview container loading/selected state
        $container.removeClass('loading selected');
    });

    // Decode HTML entities
    function decodeHtmlEntities(text) {
        var textArea = document.createElement('textarea');
        textArea.innerHTML = text;
        return textArea.value;
    }

    // Format price with WooCommerce currency settings
    function formatPrice(price) {
        // Get currency settings from localized data or use defaults
        var symbol = wpgv_product_gift_ajax && wpgv_product_gift_ajax.currency_symbol
            ? decodeHtmlEntities(wpgv_product_gift_ajax.currency_symbol)
            : '£';
        var position = wpgv_product_gift_ajax && wpgv_product_gift_ajax.currency_position
            ? wpgv_product_gift_ajax.currency_position
            : 'right';

        // Remove decimals if price is whole number
        var priceValue = parseFloat(price);
        var formattedPrice = (priceValue % 1 === 0) ? priceValue.toFixed(0) : priceValue.toFixed(2);

        switch(position) {
            case 'left':
                return symbol + formattedPrice;
            case 'right':
                return formattedPrice + symbol;
            case 'left_space':
                return symbol + ' ' + formattedPrice;
            case 'right_space':
                return formattedPrice + ' ' + symbol;
            default:
                return formattedPrice + symbol;
        }
    }

    // Select template
    function selectTemplate($template) {
        // Clear any previous load event handlers
        $(document).off('.wpgvTemplateLoad');
        // Ensure only one selected state at a time (clear existing selection)
        $('.wpgv-template-item').removeClass('selected');

        // Mark clicked item as loading and disable others
        $('.wpgv-template-item').removeClass('loading').addClass('disabled');
        $template.removeClass('disabled').addClass('loading');

        // Add visible loading label + spinner inside the item
        if (!$template.find('.wpgv-item-loading-label').length) {
            $template.append('<div class="wpgv-item-loading-label"><span class="wpgv-spinner"></span>Loading...</div>');
        }

        // Store selected template ID and price immediately
        selectedTemplateId = $template.data('template-id');
        selectedTemplatePrice = parseFloat($template.data('template-price')) || 0;
        $('#wpgv_selected_template_id').val(selectedTemplateId);

        // Listen for load success or error (namespaced handlers)
        $(document).on('wpgv_template_loaded.wpgvTemplateLoad', function(e, templateId) {
            if (templateId != selectedTemplateId) return;

            // Remove loading state and enable items
            $('.wpgv-template-item').removeClass('disabled');
            $template.removeClass('loading').addClass('selected');
            $template.find('.wpgv-item-loading-label').remove();

            // Update price display and show form fields
            updatePriceDisplay();
            $('#wpgv-gift-form-fields').slideDown();
            $('#wpgv_your_name, #wpgv_recipient_name, #wpgv_recipient_email, #wpgv_your_email').prop('required', true);

            // Remove handlers
            $(document).off('.wpgvTemplateLoad');
        });

        $(document).on('wpgv_template_load_error.wpgvTemplateLoad', function(e, templateId, info) {
            if (templateId != selectedTemplateId) return;

            // Clear loading state and re-enable others
            $('.wpgv-template-item').removeClass('loading disabled');
            $template.removeClass('loading');
            $template.find('.wpgv-item-loading-label').remove();

            // Show error notice
            showNotice('Failed to load template preview. Please try again.', 'error');

            // Remove handlers
            $(document).off('.wpgvTemplateLoad');
        });

        // Trigger Konva loader
        if (typeof wpgvLoadTemplate === 'function') {
            wpgvLoadTemplate(selectedTemplateId);
        }
    }

    // Update price display
    function updatePriceDisplay() {
        var totalPrice = productPrice;
        var $priceContainer = $('.wpgv-gift-price');
        var priceHtml = '';

        // Display product price with sale info if applicable
        if (hasProductSale) {
            priceHtml += '<div class="wpgv-product-price" style="margin-bottom:10px;">';
            priceHtml += '<strong>Product Price:</strong><br>';
            priceHtml += '<span class="wpgv-product-price-regular" style="text-decoration: line-through; color: #999; margin-right:6px;">' + formatPrice(productRegularPrice) + '</span>';
            priceHtml += '<span class="wpgv-product-price-sale" style="color: #e2401c; font-weight: bold;">' + formatPrice(productSalePrice) + '</span>';
            priceHtml += ' <span class="wpgv-price-badge" style="background:#e2401c;color:#fff;padding:2px 6px;font-size:11px;border-radius:3px;margin-left:6px;">SALE</span>';
            priceHtml += '</div>';
        } else {
            priceHtml += '<div class="wpgv-product-price" style="margin-bottom: 10px;">';
            priceHtml += '<strong>Product Price:</strong> ';
            priceHtml += '<strong class="wpgv-product-price-main">' + formatPrice(productPrice) + '</strong>';
            priceHtml += '</div>';
        }

        // Display template price
        if (selectedTemplatePrice > 0) {
            // Template has fixed price
            totalPrice = productPrice + selectedTemplatePrice;
            priceHtml += '<div class="wpgv-gift-price-row" style="margin-bottom: 10px;">';
            priceHtml += '<strong>Gift Card Price:</strong> ';
            priceHtml += '<strong class="wpgv-gift-price-amount">+' + formatPrice(selectedTemplatePrice) + '</strong>';
            priceHtml += '</div>';
        } else {
            // Template has no price: double the product price
            totalPrice = productPrice + productPrice;
            priceHtml += '<div class="wpgv-gift-price-row" style="margin-bottom: 10px;">';
            priceHtml += '<strong>Gift Card Price:</strong> ';
            priceHtml += '<strong class="wpgv-gift-price-amount">+' + formatPrice(productPrice) + '</strong>';
            priceHtml += ' <span class="wpgv-same-as-product">(same as product)</span>';
            priceHtml += '</div>';
        }

        // Display total
        priceHtml += '<div class="wpgv-total-row" style="margin-top: 15px; padding-top: 10px;">';
        priceHtml += '<strong>Total:</strong> ';
        priceHtml += '<strong class="wpgv-total-price">' + formatPrice(totalPrice) + '</strong>';
        priceHtml += '</div>';

        $priceContainer.html(priceHtml);
    }

    // Export function to update gift price (called from Konva script)
    window.wpgvUpdateGiftPrice = function() {
        // Re-get current product price
        productPrice = getProductPrice();
        updatePriceDisplay();
    };

    // Listen for WooCommerce variation changes
    $('form.variations_form').on('found_variation', function(event, variation) {
        if ($('#wpgv_add_gift_voucher').is(':checked')) {
            console.log('Variation found in checkbox script:', variation);
            // Update product price when variation changes
            setTimeout(function() {
                productPrice = getProductPrice(); giftcard_logo
                updatePriceDisplay();
            }, 200); // Increased delay to ensure WooCommerce updates complete
        }
    });

    // Listen for variation reset
    $('form.variations_form').on('reset_data', function() {
        if ($('#wpgv_add_gift_voucher').is(':checked')) {
            console.log('Variation reset in checkbox script');
            setTimeout(function() {
                productPrice = getProductPrice();
                updatePriceDisplay();
            }, 200);
        }
    });

    // Reset form
    function resetForm() {
        selectedTemplateId = null;
        selectedTemplatePrice = 0;
        $('#wpgv_selected_template_id').val('');
        $('#wpgv-gift-form-fields').hide();
        $('.wpgv-template-item').removeClass('selected');

        // Clear all input fields
        $('#wpgv_your_name').val('');
        $('#wpgv_recipient_name').val('');
        $('#wpgv_recipient_email').val('');
        $('#wpgv_your_email').val('');
        $('#wpgv_personal_message').val('');
    }

    // Show WordPress notice
    function showNotice(message, type) {
        type = type || 'error';

        // Remove existing notices
        $('.woocommerce-notices-wrapper .woocommerce-' + type).remove();

        // Create notice HTML
        var noticeHtml = '<div class="woocommerce-' + type + '" role="alert">' + message + '</div>';

        // Find notices wrapper or create one
        var $noticesWrapper = $('.woocommerce-notices-wrapper').first();
        if (!$noticesWrapper.length) {
            $noticesWrapper = $('<div class="woocommerce-notices-wrapper"></div>');
            $('.product').prepend($noticesWrapper);
        }

        // Add notice
        $noticesWrapper.prepend(noticeHtml);

        // Scroll to notice
        $('html, body').animate({
            scrollTop: $noticesWrapper.offset().top - 100
        }, 500);
    }

    // Validate form before add to cart
    $('form.cart').on('submit', function(e) {
        var isGiftChecked = $('#wpgv_add_gift_voucher').is(':checked');

        // Only validate if checkbox is checked
        if (!isGiftChecked) {
            // Let the form submit normally without gift card
            return true;
        }

        // Checkbox is checked, validate gift card fields
        // Check if template is selected
        if (!selectedTemplateId) {
            e.preventDefault();
            showNotice(wpgv_product_gift_ajax.please_select_template, 'error');
            return false;
        }

        // Validate required fields
        var yourName = $('#wpgv_your_name').val().trim();
        var recipientName = $('#wpgv_recipient_name').val().trim();
        var recipientEmail = $('#wpgv_recipient_email').val().trim();
        var yourEmail = $('#wpgv_your_email').val().trim();

        if (!yourName || !recipientName || !recipientEmail || !yourEmail) {
            e.preventDefault();
            showNotice(wpgv_product_gift_ajax.please_fill_fields, 'error');
            return false;
        }

        // Validate email format
        var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(recipientEmail) || !emailRegex.test(yourEmail)) {
            e.preventDefault();
            showNotice('Please enter valid email addresses.', 'error');
            return false;
        }

        // Save canvas image before submitting
        if (typeof wpgvGetCanvasImage === 'function') {
            var canvasData = wpgvGetCanvasImage();
            if (canvasData) {
                // Store canvas data in hidden field for later retrieval
                if (!$('#wpgv_canvas_data').length) {
                    $('form.cart').append('<input type="hidden" id="wpgv_canvas_data" name="wpgv_canvas_data" value="">');
                }
                $('#wpgv_canvas_data').val(canvasData);
            }
        }

        // Save preview coupon code for backend to use
        if (typeof window.wpgvGetPreviewCouponCode === 'function') {
            var previewCoupon = window.wpgvGetPreviewCouponCode();
            if (previewCoupon) {
                if (!$('#wpgv_preview_coupon_code').length) {
                    $('form.cart').append('<input type="hidden" id="wpgv_preview_coupon_code" name="wpgv_preview_coupon_code" value="">');
                }
                $('#wpgv_preview_coupon_code').val(previewCoupon);
            }
        }

        // All validations passed
        return true;
    });
});
