jQuery(document).ready(function($) {
    // Initialize color picker
    $('.color-picker').wpColorPicker();

    // Media uploader for thumbnail
    var mediaUploader;
    $('.upload-thumbnail').click(function(e) {
        e.preventDefault();

        if (mediaUploader) {
            mediaUploader.open();
            return;
        }

        mediaUploader = wp.media({
            title: 'Choose Product Image',
            button: {
                text: 'Use this image'
            },
            multiple: false
        });

        mediaUploader.on('select', function() {
            var attachment = mediaUploader.state().get('selection').first().toJSON();
            $('#wpayme_product_thumbnail').val(attachment.id);
            $('.thumbnail-preview').html('<img src="' + attachment.url + '" alt="">');
        });

        mediaUploader.open();
    });

    // Remove thumbnail
    $('.remove-thumbnail').click(function() {
        $('#wpayme_product_thumbnail').val('');
        $('.thumbnail-preview').empty();
    });

    // Add variant row
    $('.add-variant').click(function() {
        var index = $('.variant-row').length;
        var newRow = `
            <div class="variant-row">
                <input type="text" name="wpayme_variants[${index}][name]" placeholder="Variant Name">
                <input type="number" step="0.01" name="wpayme_variants[${index}][price]" placeholder="Price">
                <button type="button" class="button remove-variant">Remove</button>
            </div>
        `;
        $(this).before(newRow);
    });

    // Remove variant row
    $(document).on('click', '.remove-variant', function() {
        $(this).closest('.variant-row').remove();
    });

    // Handle amount method selection
    $('#wpayme-amount-method-select').on('change', function() {
        const selectedMethod = $(this).val();
        
        // Remove existing dynamic fields
        $('.wpayme-dynamic-amount-fields').remove();
        
        // Get the amount method and currency options elements
        const amountMethod = $(this).closest('.wpayme-amount-method');
        const currencyOptions = $('.wpayme-currency-options');
        
        switch(selectedMethod) {
            case 'fixed_price':
                // Insert fixed price fields between amount method and currency options
                appendFixedPriceFields(amountMethod);
                break;
            case 'input_only':
                // No additional fields needed for input only
                break;
            case 'choices_only':
            case 'choices_and_input':
                // Insert choices fields between amount method and currency options
                appendChoicesFields(amountMethod, selectedMethod);
                break;
        }
    });

    // Currency symbol mapping
    const currencySymbols = {
        'EUR': '€',
        'USD': '$',
        'GBP': '£',
        'AUD': 'A$',
        'CAD': 'C$',
        'JPY': '¥',
        'NZD': 'NZ$',
        'CHF': 'CHF',
        'HKD': 'HK$',
        'SGD': 'S$',
        'SEK': 'kr',
        'DKK': 'kr',
        'NOK': 'kr',
        'MXN': 'MX$',
        'BRL': 'R$',
        'PLN': 'zł',
        'ZAR': 'R',
        'INR': '₹',
        'AED': 'د.إ',
        'SAR': '﷼',
        'KRW': '₩',
        'TWD': 'NT$',
        'MYR': 'RM',
        'THB': '฿',
        'PHP': '₱',
        'CZK': 'Kč',
        'ILS': '₪',
        'HUF': 'Ft'
    };

    // Function to update currency symbols
    function updateCurrencySymbols(currency) {
        const symbol = currencySymbols[currency] || currency;
        
        // Update fixed price field
        $('.fixed-price-field .currency-symbol').text(symbol);
        
        // Update all amount choice fields
        $('.amount-choice-input-container .currency-symbol').text(symbol);
    }
    
    // Handle currency selection change
    $('.wpayme-currency-select').on('change', function() {
        const selectedCurrency = $(this).val();
        updateCurrencySymbols(selectedCurrency);
    });
    
    // Initialize with current currency on page load
    const initialCurrency = $('.wpayme-currency-select').val();
    if (initialCurrency) {
        updateCurrencySymbols(initialCurrency);
    }

    // Function to append fixed price fields
    function appendFixedPriceFields(amountMethodElement) {
        const html = `
            <div class="wpayme-field-row wpayme-dynamic-amount-fields">
                <label>${wpaymeL10n.fixedPriceLabel || 'Fixed Price Amount'}</label>
                <div class="fixed-price-field">
                    <span class="currency-symbol">${currencySymbols[$('.wpayme-currency-select').val()] || '€'}</span>
                    <input type="number" 
                           name="wpayme_fixed_price" 
                           value="${wpaymeData && wpaymeData.fixedPrice ? wpaymeData.fixedPrice : ''}"
                           step="0.01"
                           min="0"
                           placeholder="${wpaymeL10n.enterFixedPrice || 'Enter fixed price'}">
                </div>
            </div>
        `;
        amountMethodElement.after(html);
    }

    // Function to append choices fields
    function appendChoicesFields(amountMethodElement, method) {
        const html = `
            <div class="wpayme-field-row wpayme-dynamic-amount-fields">
                <div class="wpayme-amount-choices">
                    <label>${wpaymeL10n.amountChoices || 'Amount Choices'}</label>
                    <div class="amount-choices-container">
                        ${getExistingChoices()}
                    </div>
                    <button type="button" class="button add-amount-choice">
                        ${wpaymeL10n.addChoice || 'Add Amount Choice'}
                    </button>
                </div>
            </div>
        `;
        amountMethodElement.after(html);
        initChoicesHandlers();
    }

    // Function to get existing choices HTML
    function getExistingChoices() {
        let html = '';
        
        // Check if amountChoices exists and is an array
        if (wpaymeData && wpaymeData.amountChoices && Array.isArray(wpaymeData.amountChoices) && wpaymeData.amountChoices.length > 0) {
            wpaymeData.amountChoices.forEach((choice, index) => {
                html += getChoiceRowHtml(index, choice);
            });
        } else {
            // Always ensure at least one empty field
            html += getChoiceRowHtml(0, '');
        }
        
        return html;
    }

    // Function to get choice row HTML
    function getChoiceRowHtml(index, value) {
        // Ensure value is a string
        const safeValue = value !== undefined && value !== null ? value : '';
        // Get the current currency symbol
        const currencySymbol = currencySymbols[$('.wpayme-currency-select').val()] || '€';
        
        return `
            <div class="amount-choice-row">
                <div class="amount-choice-input-container">
                    <span class="currency-symbol">${currencySymbol}</span>
                    <input type="number" 
                           name="_wpayme_payment_form_amount_choices[]" 
                           value="${safeValue}"
                           step="0.01"
                           min="0"
                           data-choice-index="${index}"
                           class="wpayme-amount-choice-input"
                           placeholder="${wpaymeL10n.enterAmount || 'Enter amount'}">
                </div>
                <button type="button" class="button remove-amount-choice" ${!safeValue ? 'style="display:none;"' : ''}>
                    <span class="dashicons dashicons-no-alt"></span>
                </button>
            </div>
        `;
    }

    // Initialize handlers for amount choices
    function initChoicesHandlers() {
        // Add new choice
        $('.add-amount-choice').on('click', function() {
            const container = $(this).siblings('.amount-choices-container');
            const newIndex = container.find('.amount-choice-row').length;
            
            // Add the new row to the container
            container.append(getChoiceRowHtml(newIndex, ''));
            
            // Focus the new input
            container.find('.amount-choice-row:last-child input').focus();
        });

        // Remove choice
        $(document).on('click', '.remove-amount-choice', function() {
            // Don't remove if it's the last row
            const totalRows = $(this).closest('.amount-choices-container').find('.amount-choice-row').length;
            if (totalRows > 1) {
                $(this).closest('.amount-choice-row').remove();
            } else {
                // If it's the last row, just clear the value instead
                const input = $(this).closest('.amount-choice-row').find('input');
                input.val('');
                $(this).hide(); // Hide the remove button
            }
        });

        // Show remove button when value is entered
        $(document).on('input', '.amount-choice-row input', function() {
            const removeButton = $(this).closest('.amount-choice-row').find('.remove-amount-choice');
            removeButton.toggle(!!$(this).val());
            
            // If this is the last input and it has a value, add a new empty row below
            const currentRow = $(this).closest('.amount-choice-row');
            if (currentRow.is(':last-child') && $(this).val()) {
                const container = currentRow.parent();
                const newIndex = container.find('.amount-choice-row').length;
                
                // Add new row below
                container.append(getChoiceRowHtml(newIndex, ''));
            }
        });
    }

    // Trigger change on page load to set initial fields and move currency options
    const selectedMethod = $('#wpayme-amount-method-select').val();
    if (!selectedMethod) {
        $('#wpayme-amount-method-select').val('fixed_price');
    }
    
    // Manually trigger the change event to initialize fields based on the current selection
    $('#wpayme-amount-method-select').trigger('change');
    
    // If we have data for amount choices, make sure they're displayed
    if (selectedMethod === 'choices_only' || selectedMethod === 'choices_and_input') {
        // Check if form already has amount choice fields (in case the change event didn't create them)
        if ($('.amount-choice-row').length === 0 && wpaymeData && wpaymeData.amountChoices && wpaymeData.amountChoices.length > 0) {
            console.log('Manually initializing amount choices');
            appendChoicesFields($('.wpayme-amount-method'), selectedMethod);
        }
    }

    // Initialize all toggle switches and ensure proper display
    function initializeToggleSwitches() {
        $('.wpayme-toggle-switch input[type="checkbox"]').each(function() {
            // Make sure the toggle state matches the checkbox state
            if ($(this).is(':checked')) {
                $(this).next('.wpayme-toggle-slider').addClass('checked');
            } else {
                $(this).next('.wpayme-toggle-slider').removeClass('checked');
            }
        });
        
        // Show/hide stock quantity options based on stock control toggle
        if ($('input[name="wpayme_enable_stock"]').is(':checked')) {
            $('.wpayme-stock-quantity-option').show();
        } else {
            $('.wpayme-stock-quantity-option').hide();
        }
    }
    
    // Run initialization on document ready
    initializeToggleSwitches();
    
    // Handle stock control options
    $('input[name="wpayme_enable_stock"]').on('change', function() {
        if ($(this).is(':checked')) {
            $('.wpayme-stock-quantity-option').slideDown(200);
        } else {
            $('.wpayme-stock-quantity-option').slideUp(200);
        }
    });

    // Add animation effects for toggle switches
    $('.wpayme-toggle-switch input').on('change', function() {
        if ($(this).is(':checked')) {
            $(this).next('.wpayme-toggle-slider').addClass('checked');
        } else {
            $(this).next('.wpayme-toggle-slider').removeClass('checked');
        }
    });

    // Ensure amount choices are properly saved on form submission
    $('#post').on('submit', function() {
        // If we're using amount choices (choices_only or choices_and_input)
        const method = $('#wpayme-amount-method-select').val();
        if (method === 'choices_only' || method === 'choices_and_input') {
            // Check if we have any amount choices
            const choices = $('.wpayme-amount-choice-input');
            
            // Log the amount choices for debugging
            console.log(`Found ${choices.length} amount choices to save`);
            choices.each(function(index) {
                console.log(`Choice ${index}: ${$(this).val()}`);
            });
            
            // If there are no amount choices with values, add a hidden field to clear existing choices
            let hasValidChoices = false;
            choices.each(function() {
                if ($(this).val() && $(this).val() !== '') {
                    hasValidChoices = true;
                    return false; // break the loop
                }
            });
            
            // If no valid choices and we're using a choice method, add a field to clear existing choices
            // This ensures we don't lose the empty field when saving
            if (!hasValidChoices && (method === 'choices_only' || method === 'choices_and_input')) {
                // We always want to keep the empty field structure
                $(this).append('<input type="hidden" name="_wpayme_payment_form_clear_choices" value="keep_empty">');
            }
        }
    });
}); 