/**
 * Minimalista Template JavaScript
 * Handles template-specific functionality
 */
jQuery(document).ready(function($) {
    const { __ } = (window.wp && window.wp.i18n) ? window.wp.i18n : { __: (s) => s };
    // Initialize currency formatting
    if (typeof window.ckfylt25Currency !== 'undefined') {
        // Currency formatting functions can be added here if needed
        console.log('Currency initialized:', window.ckfylt25Currency);
    }
    
    // Handle shipping method changes
    $(document).on('change', 'input[name^="shipping_method"]', function() {
        // Trigger checkout update when shipping method changes
        $(document.body).trigger('update_checkout');
    });
    
    // Handle quantity changes in order summary
    $(document).on('change', '.ckfylt25-product-qty', function() {
        // Update cart quantities and trigger checkout update
        $(document.body).trigger('update_checkout');
    });
    
    // Handle form validation
    $(document).on('submit', '.woocommerce-checkout', function(e) {
        // Respect admin setting to allow checkout without address
        var cfg = window.ckfylt25CheckoutConfig || {};
        if (cfg.allowWithoutAddress === true) {
            // Skip template-level required-field checks; rely on WooCommerce server-side validation
            return;
        }
        
        var isValid = true;
        var disabled = Array.isArray(cfg.disabledBillingFields) ? cfg.disabledBillingFields : [];
        
        // Example: Check if required fields are filled, excluding disabled/hidden ones
        $('.woocommerce-checkout input[required]').each(function() {
            var $el = $(this);
            var name = this.name || $el.attr('id') || '';
            var id = $el.attr('id') || '';
            var key = name || id;
            // Skip checks for fields that are hidden/disabled by plugin
            if ($el.closest('.ckfylt25-hidden-field').length > 0) {
                return; // continue
            }
            if (disabled.indexOf(key) !== -1) {
                return; // continue
            }
            if (!$el.val()) {
                isValid = false;
                $el.addClass('error');
            } else {
                $el.removeClass('error');
            }
        });
        
        if (!isValid) {
            e.preventDefault();
            alert( __('Please fill in all required fields.', 'checkoutify-lite') );
        }
    });
    
    // Handle payment method changes
    $(document).on('change', 'input[name="payment_method"]', function() {
        // Trigger checkout update when payment method changes
        $(document.body).trigger('update_checkout');
    });
    
    // Handle billing field changes
    $(document).on('change', 'input[name^="billing_"]', function() {
        // Trigger checkout update when billing fields change
        $(document.body).trigger('update_checkout');
    });
    
    // Handle shipping field changes
    $(document).on('change', 'input[name^="shipping_"]', function() {
        // Trigger checkout update when shipping fields change
        $(document.body).trigger('update_checkout');
    });
    
    // Handle coupon code submission
    $(document).on('submit', '.woocommerce-form-coupon', function(e) {
        e.preventDefault();
        var couponCode = $(this).find('input[name="coupon_code"]').val();
        
        if (couponCode) {
            // Apply coupon via AJAX
            $.ajax({
                url: (typeof ckfylt25_checkout_params !== 'undefined' ? ckfylt25_checkout_params.ajax_url : (typeof wc_checkout_params !== 'undefined' ? wc_checkout_params.ajax_url : '')),
                type: 'POST',
                data: {
                    action: 'woocommerce_apply_coupon',
                    coupon_code: couponCode,
                    security: (typeof ckfylt25_checkout_params !== 'undefined' ? ckfylt25_checkout_params.apply_coupon_nonce : (typeof wc_checkout_params !== 'undefined' ? wc_checkout_params.apply_coupon_nonce : ''))
                },
                success: function(response) {
                    if (response && response.success) {
                        $(document.body).trigger('update_checkout');
                    } else {
                        alert( (response && response.data) || __('Invalid coupon code.', 'checkoutify-lite') );
                    }
                }
            });
        }
    });
    
    // Handle order bump interactions
    $(document).on('click', '.ckfylt25-order-bump-btn', function(e) {
        e.preventDefault();
        // This will be handled by the order-bump.js file
    });
    
    // Handle testimonial interactions
    $(document).on('click', '.ckfylt25-testimonial', function() {
        // Add any testimonial-specific interactions here
        $(this).addClass('active');
    });
    
    // Handle responsive behavior
    function handleResponsive() {
        if ($(window).width() <= 768) {
            // Mobile-specific adjustments
            $('.ckfylt25-minimalista-container').addClass('mobile');
        } else {
            $('.ckfylt25-minimalista-container').removeClass('mobile');
        }
    }
    
    // Run on load and resize
    handleResponsive();
    $(window).resize(handleResponsive);
    
    // Handle smooth scrolling for anchor links
    $(document).on('click', 'a[href^="#"]', function(e) {
        var target = $(this.getAttribute('href'));
        if (target.length) {
            e.preventDefault();
            $('html, body').animate({
                scrollTop: target.offset().top - 100
            }, 500);
        }
    });
    
    // Handle form field focus states
    $(document).on('focus', '.ckfylt25-input, .ckfylt25-select', function() {
        $(this).closest('.ckfylt25-field-group').addClass('focused');
    }).on('blur', '.ckfylt25-input, .ckfylt25-select', function() {
        $(this).closest('.ckfylt25-field-group').removeClass('focused');
    });
    
    // Handle loading states
    $(document).on('checkout_place_order', function() {
        $('.woocommerce-checkout').addClass('processing');
        $('#place_order').prop('disabled', true).text( __('Processing...', 'checkoutify-lite') );
        
        // Ensure button remains accessible even when disabled
        $('#place_order').css({
            'position': 'relative',
            'z-index': '9999',
            'pointer-events': 'auto'
        });
    });
    
    // Handle checkout completion
    $(document).on('checkout_complete', function() {
        $('.woocommerce-checkout').removeClass('processing');
        $('#place_order').prop('disabled', false).text( __('Complete Order', 'checkoutify-lite') );
    });
    
    // Handle checkout errors
    $(document.body).on('checkout_error', function() {
        $('.woocommerce-checkout').removeClass('processing');
        $('#place_order').prop('disabled', false).text( __('Complete Order', 'checkoutify-lite') );
    });
    
    // Ensure payment button is always accessible
    $(document).on('click', '#place_order', function(e) {
        // Ensure the button is clickable
        $(this).css({
            'position': 'relative',
            'z-index': '9999',
            'pointer-events': 'auto'
        });
    });
});
