/**
 * Checkout Conflict Fix JavaScript
 * Handles conflicts with other checkout plugins and ensures proper element visibility
 */
jQuery(document).ready(function($) {
    const { __ } = (window.wp && window.wp.i18n) ? window.wp.i18n : { __: (s) => s };
    'use strict';
    
    // Flag to prevent interference during payment processing
    let isProcessingPayment = false;
    
    // Function to force element visibility without interfering with payment
    function forceElementVisibility() {
        // Don't interfere if payment is being processed
        if (isProcessingPayment) {
            return;
        }
        
        // Only force visibility of critical elements, not payment elements
        $("#shipping_methods_list").show().css({
            "display": "flex !important",
            "visibility": "visible !important",
            "opacity": "1 !important"
        });
        
        // Ensure payment methods are visible but don't force their styling
        if (!$("#payment").hasClass('processing')) {
            $(".wc_payment_methods").show().css({
                "display": "block !important",
                "visibility": "visible !important",
                "opacity": "1 !important"
            });
        }
    }
    
    // Function to handle hidden fields
    function handleHiddenFields() {
        $(".ckfylt25-hidden-field").each(function() {
            $(this).hide().css({
                "display": "none !important",
                "visibility": "hidden !important",
                "opacity": "0 !important",
                "height": "0 !important",
                "width": "0 !important",
                "overflow": "hidden !important",
                "position": "absolute !important",
                "left": "-9999px !important",
                "top": "-9999px !important"
            });
            
            // Clear values and unmark as required
            $(this).find("input, select, textarea").each(function() {
                $(this).val("").prop("required", false);
            });
        });
        
        // Also hide labels and containers of disabled fields
        $(".ckfylt25-hidden-field label, .ckfylt25-hidden-field .woocommerce-input-wrapper").hide();
    }
    
    // Disable Fluid Checkout scripts that might interfere
    $(document).off("fc_updated_checkout");
    $(document).off("fc_updated_checkout_steps");
    
    // Handle hidden fields immediately
    handleHiddenFields();
    
    // Execute visibility function immediately
    forceElementVisibility();
    
    // Execute every 2 seconds instead of 500ms to reduce interference
    setInterval(forceElementVisibility, 2000);
    
    // Monitor payment processing state
    $(document.body).on('checkout_place_order', function() {
        isProcessingPayment = true;
        console.log('Payment processing started - stopping interference');
    });
    
    $(document.body).on('checkout_complete checkout_error', function() {
        isProcessingPayment = false;
        console.log('Payment processing ended - resuming normal operation');
    });
    
    // Ensure place order button is always accessible
    $(document).on('click', '#place_order', function(e) {
        // Don't prevent the click, just ensure the button is accessible
        $(this).css({
            "z-index": "9999",
            "position": "relative"
        });
    });
    
    // Handle WooCommerce blockUI conflicts
    $(document).on('DOMNodeInserted', function(e) {
        const target = e.target;
        
        // Remove any blockUI overlays that might interfere
        if (target.classList && target.classList.contains('blockUI')) {
            $(target).remove();
        }
        
        // Ensure payment section is not blocked
        if (target.id === 'payment' || $(target).find('#payment').length > 0) {
            $('#payment').css({
                "z-index": "999",
                "position": "relative"
            });
        }
    });
    
    // Prevent other plugins from hiding critical elements
    $(document).on('DOMSubtreeModified', function() {
        if (!isProcessingPayment) {
            // Only run this check occasionally to avoid performance issues
            if (Math.random() < 0.1) { // 10% chance
                forceElementVisibility();
            }
        }
    });
    
    // Handle form submission more carefully
    $('form.checkout').on('submit', function(e) {
        const cfg = window.ckfylt25CheckoutConfig || {};
        const disabled = Array.isArray(cfg.disabledBillingFields) ? cfg.disabledBillingFields : [];
        
        // If admin allows checkout without address, skip client-side required alerts here
        if (cfg.allowWithoutAddress === true) {
            return; // rely on server-side validation in WooCommerce
        }
        
        // Ensure all required fields are filled, excluding hidden/disabled ones
        let isValid = true;
        $(this).find('input[required], select[required], textarea[required]').each(function() {
            const $el = $(this);
            const name = this.name || $el.attr('id') || '';
            const id = $el.attr('id') || '';
            const key = name || id;
            // Skip disabled or hidden fields
            if ($el.closest('.ckfylt25-hidden-field').length > 0) {
                return; // continue
            }
            if (disabled.indexOf(key) !== -1) {
                return; // continue
            }
            if (!$el.val().trim()) {
                isValid = false;
                $el.addClass('error');
            } else {
                $el.removeClass('error');
            }
        });
        
        if (!isValid) {
            e.preventDefault();
            alert( __('Please fill in all required fields.', 'checkoutify-lite') );
            return false;
        }
        
        // Set processing flag
        isProcessingPayment = true;
        
        // Ensure payment button is accessible
        $('#place_order').css({
            "z-index": "9999",
            "position": "relative"
        });
    });
    
    // Handle AJAX checkout updates
    $(document.body).on('updated_checkout', function() {
        // Re-run hidden field handling after checkout updates
        setTimeout(handleHiddenFields, 100);
        
        // Ensure payment section remains accessible
        setTimeout(function() {
            if (!isProcessingPayment) {
                $('#payment').css({
                    "z-index": "999",
                    "position": "relative"
                });
            }
        }, 200);
    });
});

