/* global Square, fkwcsq_card_payment_params */

(function ($) {
    'use strict';

    // Keep track of card instance
    let card = null;
    let payments = null;
    let isInitialized = false;
    let isProcessing = false;
    let initializationInProgress = false; // New flag to prevent race conditions
    let previousBillingCountry = '';
    let isPaymentMethodChanging = false;
    let updateCheckoutInProgress = false; // Flag to track if update_checkout is running

    // Cleanup function to destroy existing card instance
    async function destroyCard() {
        if (card) {
            try {
                await card.destroy();
                card = null;
                isInitialized = false;
            } catch (error) {
                // Silently handle destroy errors
            }
        }
    }

    // Add this function to verify the payment form container
    function verifyPaymentFormContainer() {
        const container = $('#square-card-container');
        if (!container.length) {
            return false;
        }

        if (container.is(':visible')) {
            return true;
        }

        return false;
    }

    // Check if card is already functional to prevent unnecessary reinitializations
    function isCardFunctional() {
        // Check if card is initialized and has an iframe
        const hasIframe = $('#square-card-container iframe').length > 0;
        const isVisible = $('#square-card-container').is(':visible');

        // If container is empty but card is initialized, we need to reinitialize
        if (isInitialized && card && !hasIframe && isVisible) {
            return false;
        }

        return isInitialized && card && hasIframe && isVisible;
    }

    // Check if container is empty (needs initialization)
    function isContainerEmpty() {
        const container = $('#square-card-container');
        return container.length > 0 && container.is(':visible') && container.children().length === 0;
    }

    // Initialize Square payment form
    async function initializeSquarePayment() {

        if (!verifyPaymentFormContainer()) {
            return;
        }
        const selector = '.fkwcsq-square-payment-form .sq-card-iframe-container iframe';
        if ($(selector).length > 0) {
            isInitialized = true;
            return;
        }

        // Check if already initialized or initialization in progress
        if (isInitialized && !isContainerEmpty()) {
            return;
        }

        if (initializationInProgress) {
            return;
        }

        // Check if we're on order pay page
        const isOrderPayPage = $('body').hasClass('woocommerce-order-pay');

        // Shimmer is already loaded by PHP, no need to show it

        // Set flag to prevent concurrent initialization
        initializationInProgress = true;

        try {

            // Initialize Square payments
            payments = await Square.payments(fkwcsq_card_payment_params.application_id, fkwcsq_card_payment_params.location_id);
            card = await payments.card();

            const cardContainer = document.getElementById('square-card-container');
            if (!cardContainer) {
                initializationInProgress = false;
                return;
            }

            // Clear container and attach card (this will replace shimmer)
            $('#square-card-container').empty();
            await card.attach('#square-card-container');

            // Remove shimmer class immediately after attach (card.attach() replaces the content)
            $('#square-card-container').removeClass('square-shimmer-container').addClass('square-card-loaded');

            // For order pay page, use more aggressive shimmer removal
            if (isOrderPayPage) {
                // Immediately remove shimmer elements if they still exist
                $('#square-card-container .square-shimmer-line').remove();

                // Force remove shimmer class multiple times to ensure it's gone
                const removeShimmer = () => {
                    const container = $('#square-card-container');
                    container.removeClass('square-shimmer-container').addClass('square-card-loaded');
                    container.find('.square-shimmer-line').remove();
                };

                // Remove shimmer immediately and on multiple intervals
                removeShimmer();
                setTimeout(removeShimmer, 50);
                setTimeout(removeShimmer, 150);
                setTimeout(removeShimmer, 300);
            }

            // Add event listener to detect when card is fully loaded
            card.addEventListener('focusClassRemoved', (event) => {
                const { currentState } = event.detail;
                if (currentState.isCompletelyValid) {
                    // Ensure shimmer is removed and loaded class is added
                    $('#square-card-container').removeClass('square-shimmer-container').addClass('square-card-loaded');
                    $('#square-card-container .square-shimmer-line').remove();
                }
            });

            // Also listen for the card to be ready (alternative approach)
            card.addEventListener('cardBrandChanged', () => {
                // Ensure shimmer is removed and loaded class is added
                $('#square-card-container').removeClass('square-shimmer-container').addClass('square-card-loaded');
                $('#square-card-container .square-shimmer-line').remove();
            });

            // Fallback: Check for iframe presence after a short delay and ensure shimmer is removed
            setTimeout(() => {
                const container = $('#square-card-container');
                const iframe = container.find('iframe');
                if (iframe.length > 0 && iframe.is(':visible')) {
                    // Remove shimmer class and add loaded class
                    container.removeClass('square-shimmer-container').addClass('square-card-loaded');
                    container.find('.square-shimmer-line').remove();
                } else if (container.hasClass('square-shimmer-container')) {
                    // If iframe is not present but shimmer is still showing, something went wrong
                    // Remove shimmer class anyway to prevent indefinite display
                    container.removeClass('square-shimmer-container');
                    container.find('.square-shimmer-line').remove();
                }
            }, 100);

            // Safety timeout: Remove shimmer after 3 seconds regardless of state to prevent indefinite display
            setTimeout(() => {
                const container = $('#square-card-container');
                if (container.hasClass('square-shimmer-container')) {
                    container.removeClass('square-shimmer-container');
                    container.find('.square-shimmer-line').remove();
                    // Only add loaded class if iframe is present
                    if (container.find('iframe').length > 0) {
                        container.addClass('square-card-loaded');
                    }
                }
            }, 3000);

            isInitialized = true;

            // Shimmer is automatically replaced by card.attach(), so no need to hide it manually

        } catch (error) {
            console.error('Failed to initialize Square payment form:', error);
            $('#square-card-error')
                .text(`Failed to initialize Square payment form: ${error.message}`)
                .show();
        } finally {
            initializationInProgress = false;
        }
    }

    // Get billing contact details from form fields
    function getBillingContactDetails() {
        const billingContact = {};

        // Get billing details from form fields
        const firstName = $('#billing_first_name').val() || '';
        const lastName = $('#billing_last_name').val() || '';
        const email = $('#billing_email').val() || '';
        const country = $('#billing_country').val() || '';
        const city = $('#billing_city').val() || '';
        const address1 = $('#billing_address_1').val() || '';
        const address2 = $('#billing_address_2').val() || '';
        const state = $('#billing_state').val() || '';
        const postcode = $('#billing_postcode').val() || '';

        // Only add fields that have values
        if (firstName) billingContact.givenName = firstName;
        if (lastName) billingContact.familyName = lastName;
        if (email) billingContact.email = email;
        if (country) billingContact.countryCode = country.toUpperCase();
        if (city) billingContact.city = city;
        if (address1) billingContact.addressLines = [address1];
        if (address2 && billingContact.addressLines) {
            billingContact.addressLines.push(address2);
        }
        if (state) billingContact.region = state;
        if (postcode) billingContact.postalCode = postcode;

        return billingContact;
    }

    // Build buyer verification details for tokenization
    function buildBuyerVerificationDetails() {
        // Format amount as integer (cents)
        const amount = Math.round(parseFloat(fkwcsq_card_payment_params.amount) * 100);

        // Determine intent based on save card checkbox
        const intent = 'CHARGE_AND_STORE';

        // Get billing contact details from form
        const billingContact = getBillingContactDetails();

        // Build verification details object
        const verificationDetails = {
            amount: amount.toString(),
            currencyCode: fkwcsq_card_payment_params.currency.toUpperCase(),
            intent,
            customerInitiated: true,
            sellerKeyedIn: false,
            billingContact
        };

        return verificationDetails;
    }

    // Enhanced tokenization with buyer verification
    async function tokenizeWithBuyerVerification() {
        try {
            const verificationDetails = buildBuyerVerificationDetails();

            // Tokenize with buyer verification details included
            const result = await card.tokenize(verificationDetails);

            if (result.status === 'OK') {
                return {
                    token: result.token,
                    verifiedBuyer: result.verifiedBuyer || null
                };
            } else {
                // Handle specific error cases
                const errorMessage = result.errors[0].message;
                if (errorMessage.includes('card') || errorMessage.includes('invalid') || errorMessage.includes('required')) {
                    throw new Error('Please fill in all required card details.');
                }
                throw new Error(errorMessage);
            }
        } catch (error) {
            const errorMessage = error.message || '';
            const isCardValidationError = errorMessage.includes('card') || errorMessage.includes('invalid') || errorMessage.includes('required') || errorMessage.includes('Please fill in all required card details.');

            if (isCardValidationError) {
                // If it's a known card validation error, throw a user-friendly message without logging to console
                throw new Error('Please fill in all required card details.');
            } else {
                // For other errors, log to console and re-throw
                console.error('Tokenization with buyer verification failed:', error);
                throw error;
            }
        }
    }

    // Add this function to help with debugging
    function logPaymentError(_error, _context) {
        // Error logging function - can be used for debugging if needed
    }

    // Handle the checkout button click
    async function handleCheckoutButtonClick(event) {
        // Only process if Square is selected
        if (!$('#payment_method_fkwcsq_square').is(':checked')) {
            return true;
        }

        // Prevent default form submission
        event.preventDefault();

        if (isProcessing) {
            return false;
        }

        // Clear any previous error messages when user tries to submit again
        $('#square-card-error').hide();

        isProcessing = true;

        // Get the correct form based on page type
        const isOrderPayPage = $('body').hasClass('woocommerce-order-pay');
        const $form = isOrderPayPage ? $('form#order_review') : $('form.checkout');

        // Block the form UI
        $form.block({
            message: null,
            overlayCSS: {
                background: '#fff',
                opacity: 0.6
            }
        });

        try {
            // Clear any previous tokens and errors
            $('#square-card-error').hide();
            $('input[name="fkwcsq_square_nonce"]').remove();
            $('input[name="fkwcsq_verification_token"]').remove();

            // Ensure card is initialized
            if (!isInitialized) {
                logPaymentError('Card not initialized', 'handleCheckoutButtonClick');
                await initializeSquarePayment();
            }

            // Use enhanced tokenization with buyer verification
            const tokenizationResult = await tokenizeWithBuyerVerification();

            // Add payment nonce to form
            const nonceInput = $('<input>').attr({
                type: 'hidden',
                name: 'fkwcsq_square_nonce',
                value: tokenizationResult.token
            });

            // Add verified buyer token if available
            if (tokenizationResult.verifiedBuyer) {
                const verificationInput = $('<input>').attr({
                    type: 'hidden',
                    name: 'fkwcsq_verification_token',
                    value: tokenizationResult.verifiedBuyer
                });
                $form.append(verificationInput);
            }

            // Add save card flag if checkbox is checked
            if ($('#fkwcsq_square_save_card').is(':checked')) {
                const saveCardInput = $('<input>').attr({
                    type: 'hidden',
                    name: 'fkwcsq_square_save_card',
                    value: 'true'
                });
                $form.append(saveCardInput);
            }

            $form.append(nonceInput);

            // Verify nonce was added
            const addedNonce = $('input[name="fkwcsq_square_nonce"]').val();

            if (!addedNonce) {
                isProcessing = false;
                $form.unblock();
                $('#square-card-error').html('Payment Error: Failed to add payment information.').show();
                return false;
            }

            // Reset processing flag
            isProcessing = false;

            // Unblock the form
            $form.unblock();

            // Submit the form
            if (isOrderPayPage) {
                // For order pay page, use the specific submit button
                $('#place_order').trigger('click');
            } else {
                // For checkout page, submit the form
                $form.submit();
            }
            return true;
        } catch (error) {
            isProcessing = false;
            // Unblock the form on error
            $form.unblock();

            const errorMessage = error.message || '';
            const isCardValidationError = errorMessage.includes('Please fill in all required card details.');

            if (isCardValidationError) {
                // For card validation errors, just show the message without console logging
                $('#square-card-error')
                    .text(`Payment Error: ${error.message}`)
                    .show();
            } else {
                // For other errors, log to console and show error
                logPaymentError(error, 'handleCheckoutButtonClick');
                console.error('Payment error:', error);
                $('#square-card-error')
                    .text(`Payment Error: ${error.message}`)
                    .show();
            }
            return false;
        }
    }
    // Function to check if Square source exists
    function hasSquareSource() {
        return $('input[name="fkwcsq_square_nonce"]').length > 0 ? $('input[name="fkwcsq_square_nonce"]').val() : '';
    }
    function getDynamicSavedToken() {
        return new Promise((resolve, reject) => {
            const $selectedInput = $('input[name="wc-fkwcsq_square-payment-token"]:checked');
            const tokenId = $selectedInput.val();

            if (!tokenId || tokenId === 'new') {
                reject(new Error('No saved card selected'));
                return;
            }

            // Get token from data-token attribute
            const token = $selectedInput.attr('data-token');

            if (!token) {
                reject(new Error('Token not found in input element'));
                return;
            }

            resolve(token);
        });
    }
    // Process form submission
    function processCheckoutSubmit(e) {
        if (!$('#payment_method_fkwcsq_square').is(':checked')) {
            return true;
        }

        const savedCardValue = $('input[name="wc-fkwcsq_square-payment-token"]:checked').val();

        // If a saved card is selected and it's not 'new'
        if (savedCardValue && savedCardValue !== 'new') {
            if ($('input[name="fkwcsq_verification_token"]').length > 0) {
                return true;
            }
            getDynamicSavedToken()
                .then(savedToken => {
                    processSavedCardPayment(e, savedToken);
                })
                .catch(error => {
                    $('#square-card-error')
                        .text(`Payment Error: ${error.message}`)
                        .show();
                });

            return false;
        }

        // Check for existing nonce
        const source = hasSquareSource();
        if ('' === source) {
            // Ensure card is initialized before proceeding
            if (!isInitialized) {
                initializeSquarePayment().then(() => {
                    handleCheckoutButtonClick(e);
                }).catch(_error => {
                    $('#square-card-error')
                        .html('Payment Error: Failed to initialize payment form. Please try again.')
                        .show();
                });
            } else {
                handleCheckoutButtonClick(e);
            }
            return false;
        }

        return true;
    }
    // Build verification details for saved card payment
    function buildSavedCardVerificationDetails() {
        // Format amount as integer (cents)
        const amount = Math.round(parseFloat(fkwcsq_card_payment_params.amount) * 100);

        // Get billing contact details from form
        const billingContact = getBillingContactDetails();

        // Build verification details object for saved cards
        const verificationDetails = {
            amount: amount.toString(),
            currencyCode: fkwcsq_card_payment_params.currency.toUpperCase(),
            intent: 'CHARGE',
            customerInitiated: true,
            sellerKeyedIn: false,
            billingContact
        };

        return verificationDetails;
    }

    async function processSavedCardPayment(event, savedToken) {
        if (isProcessing) {
            return false;
        }

        isProcessing = true;

        // Get the correct form based on page type
        const isOrderPayPage = $('body').hasClass('woocommerce-order-pay');
        const $form = isOrderPayPage ? $('form#order_review') : $('form.checkout');

        // Block the form UI
        $form.block({
            message: null,
            overlayCSS: {
                background: '#fff',
                opacity: 0.6
            }
        });

        try {
            // Clear any previous errors
            $('#square-card-error').hide();
            $('input[name="fkwcsq_verification_token"]').remove();

            // Ensure payments object is initialized
            if (!payments) {
                payments = await Square.payments(fkwcsq_card_payment_params.application_id, fkwcsq_card_payment_params.location_id);
            }

            // For saved cards, we need to verify using the token directly
            let verificationToken = '';
            try {
                const verificationDetails = buildSavedCardVerificationDetails();
                const verificationResults = await payments.verifyBuyer(savedToken, verificationDetails);

                if (!verificationResults || !verificationResults.token) {
                    throw new Error('Invalid verification results received');
                }

                verificationToken = verificationResults.token;

                // If verification is successful, add token to form
                if (verificationToken) {
                    const verificationInput = $('<input>').attr({
                        type: 'hidden',
                        name: 'fkwcsq_verification_token',
                        value: verificationToken
                    });
                    $form.append(verificationInput);

                    // Only now reset flags and submit
                    isProcessing = false;
                    $form.unblock();

                    // For order pay page, submit the form directly instead of triggering the button
                    if (isOrderPayPage) {
                        $form.submit();
                    } else {
                        $form.submit();
                    }
                    return true;
                } else {
                    throw new Error('Verification failed: No verification token received.');
                }
            } catch (verificationError) {
                isProcessing = false;
                $form.unblock();
                $('#square-card-error').html(`Payment Error: ${verificationError.message}`).show();
                return false;
            }
        } catch (error) {
            isProcessing = false;
            $form.unblock();
            $('#square-card-error')
                .html(`Payment Error: ${error.message}`)
                .show();
            return false;
        }
    }

    // Flag to track if events have been attached
    let eventsAttached = false;

    // Initialize when document is ready
    $(document).ready(function () {
        // Prevent multiple event attachments
        if (eventsAttached) {
            return;
        }
        eventsAttached = true;

        // Initial check with debounce
        // Skip on order pay page - it has its own initialization logic
        const isOrderPayPage = $('body').hasClass('woocommerce-order-pay');
        if (!isOrderPayPage && $('#payment_method_fkwcsq_square').is(':checked')) {
            setTimeout(() => initializeSquarePayment(), 100);
        }

        // Handle payment method changes - using a debounced approach
        let paymentMethodChangeTimeout;

        // Track update_checkout events to detect when AJAX is running
        $('body').on('update_checkout', function () {
            updateCheckoutInProgress = true;
        });

        $('body').on('updated_checkout', function () {
            updateCheckoutInProgress = false;
        });

        $('body').on('payment_method_selected', function () {
            clearTimeout(paymentMethodChangeTimeout);
            isPaymentMethodChanging = true;
            paymentMethodChangeTimeout = setTimeout(function () {
                if ($('#payment_method_fkwcsq_square').is(':checked')) {
                    // Check if update_checkout is in progress
                    if (updateCheckoutInProgress) {
                        isPaymentMethodChanging = false;
                        return;
                    }

                    if (!isCardFunctional() && !initializationInProgress) {
                        // Only initialize if card is not functional and not in progress
                        initializeSquarePayment();
                    }
                } else {
                    destroyCard();
                }
                isPaymentMethodChanging = false;
            }, 100); // Reduced debounce for faster response
        });

        // Handle checkout updates separately to avoid conflicts
        // Skip this on order pay page as it doesn't use update_checkout AJAX
        $('body').on('updated_checkout', function () {
            // Skip on order pay page - it doesn't use update_checkout AJAX
            if ($('body').hasClass('woocommerce-order-pay')) {
                return;
            }

            // Initialize saved card handling
            initializeSavedCardHandling();

            // Only handle if not currently changing payment method
            if (!isPaymentMethodChanging) {
                clearTimeout(paymentMethodChangeTimeout);
                paymentMethodChangeTimeout = setTimeout(function () {
                    if ($('#payment_method_fkwcsq_square').is(':checked')) {
                        // After AJAX update, container might be replaced with shimmer HTML
                        // If container is empty (only has shimmer lines) or card is not functional, reset state and reinitialize
                        const container = $('#square-card-container');
                        const hasShimmerOnly = container.hasClass('square-shimmer-container') &&
                                               container.find('.square-shimmer-line').length > 0 &&
                                               container.find('iframe').length === 0;

                        if (hasShimmerOnly || (!isCardFunctional() || isContainerEmpty())) {
                            // Reset initialization state when container is replaced by AJAX
                            if (hasShimmerOnly || isContainerEmpty()) {
                                isInitialized = false;
                                card = null;
                            }

                            if (!initializationInProgress && container.is(':visible')) {
                                initializeSquarePayment();
                            }
                        }
                    } else {
                        destroyCard();
                    }
                }, 200); // Slightly longer debounce for checkout updates
            }
        });

        // Handle FunnelKit multi-step checkout step switching.
        // The payment container is hidden until the user navigates to the payment step,
        // so the initial init is silently skipped by verifyPaymentFormContainer().
        // This listener triggers init when the payment step becomes visible.
        $('body').on('wfacp_step_switching', function () {
            clearTimeout(paymentMethodChangeTimeout);
            paymentMethodChangeTimeout = setTimeout(function () {
                if ($('#payment_method_fkwcsq_square').is(':checked') && !isCardFunctional() && !initializationInProgress) {
                    initializeSquarePayment();
                }
            }, 500);
        });

        // Listen for payment errors from server-side
        $('body').on('checkout_error', function () {
            if ($('#payment_method_fkwcsq_square').is(':checked')) {
                // Just clear the tokens and errors, no need to reset the form
                $('#square-card-error').hide();
                $('input[name="fkwcsq_square_nonce"]').remove();
                $('input[name="fkwcsq_verification_token"]').remove();
                isProcessing = false;
            }
        });

        // Hook into the main WooCommerce checkout submission
        $('form.checkout').on('checkout_place_order', function (e) {
            if ($('#payment_method_fkwcsq_square').is(':checked')) {
                return processCheckoutSubmit(e);
            }
            return true;
        });

        // Additionally, keep the specific gateway hook as well
        $('form.checkout').on('checkout_place_order_fkwcsq_square', function (e) {
            return processCheckoutSubmit(e);
        });
        $('form.checkout')
            .off('checkout_place_order checkout_place_order_fkwcsq_square')
            .on('checkout_place_order checkout_place_order_fkwcsq_square', function (e) {
                if ($('#payment_method_fkwcsq_square').is(':checked')) {
                    return processCheckoutSubmit(e);
                }
                return true;
            });
        // Cleanup on page unload
        $(window).on('unload', function () {
            destroyCard();
        });

        // Handle saved card selection
        $('.funnelkit-square-saved-card').on('change', function () {
            const savedCardId = $(this).val();
            if (savedCardId) {
                $('#square-card-container').hide();
                $('.funnelkit-square-save-card-checkbox').hide();
            } else {
                $('#square-card-container').show();
                $('.funnelkit-square-save-card-checkbox').show();
            }
        });

        // Trigger initial state
        $('.funnelkit-square-saved-card').trigger('change');

        // Store initial billing country
        previousBillingCountry = $('#billing_country').val();

        // Listen for billing country changes
        $(document.body).on('change', '#billing_country', function() {
            const newCountry = $(this).val();
            if (newCountry !== previousBillingCountry) {
                previousBillingCountry = newCountry;
                if ($('#payment_method_fkwcsq_square').is(':checked')) {
                    reinitializeCardElement();
                }
            }
        });

        // Handle order pay page form submission
        if ($('body').hasClass('woocommerce-order-pay')) {
            // Remove any existing handlers to prevent duplicates
            $('form#order_review').off('submit');
            $('#place_order').off('click');

            // Add new submit handler
            $('form#order_review').on('submit', function(e) {
                if ($('#payment_method_fkwcsq_square').is(':checked')) {
                    return processCheckoutSubmit(e);
                }
                return true;
            });

            // Handle place order button click
            $('#place_order').on('click', function(e) {
                if ($('#payment_method_fkwcsq_square').is(':checked')) {
                    const savedCardValue = $('input[name="wc-fkwcsq_square-payment-token"]:checked').val();
                    if (savedCardValue && savedCardValue !== 'new') {
                        e.preventDefault();
                        e.stopPropagation(); // Prevent event bubbling

                        // Check if we already have a verification token
                        if ($('input[name="fkwcsq_verification_token"]').length > 0) {
                            // If we have a token, submit the form directly
                            $('form#order_review').submit();
                            return false;
                        }

                        // Otherwise, get the token and process payment
                        getDynamicSavedToken()
                            .then(savedToken => {
                                processSavedCardPayment(e, savedToken);
                            })
                            .catch(error => {
                                $('#square-card-error')
                                    .html(`Payment Error: ${  error.message}`)
                                    .show();
                            });
                        return false;
                    }
                }
                return true;
            });
        }

        // Ensure card is initialized on order pay page
        // Order pay page doesn't use update_checkout AJAX, so we need direct initialization
        if ($('body').hasClass('woocommerce-order-pay')) {
            // Initialize immediately if Square is selected
            if ($('#payment_method_fkwcsq_square').is(':checked')) {
                // Small delay to ensure DOM is ready
                setTimeout(() => {
                    initializeSquarePayment();
                }, 100);
            }

            // Also listen for payment method changes on order pay page
            $(document).on('change', 'input[name="payment_method"]', function() {
                if ($('#payment_method_fkwcsq_square').is(':checked')) {
                    setTimeout(() => {
                        initializeSquarePayment();
                    }, 100);
                } else {
                    destroyCard();
                }
            });
        }

        // Clear error message when user interacts with card fields
        $(document).on('input focus', '#square-card-container iframe, #square-card-container input', function() {
            if ($('#square-card-error').is(':visible')) {
                $('#square-card-error').hide();
            }
        });

        // Clear error message when user changes payment method
        $(document).on('change', 'input[name="payment_method"]', function() {
            $('#square-card-error').hide();
        });
    });

    function initializeSavedCardHandling() {
        const $cardContainer = $('#square-card-container');
        const $saveCardContainer = $('.form-row-wide:has(#fkwcsq_square_save_card)');
        const gatewayId = 'fkwcsq_square';
        const isOrderPayPage = $('body').hasClass('woocommerce-order-pay');

        // Handle saved card selection using WooCommerce's structure
        $(document).on('change', `input[name="wc-${gatewayId}-payment-token"]`, function () {
            const selectedValue = $(this).val();
            if (selectedValue && selectedValue !== 'new') {
                // Hide card form and save card option when using saved card
                $cardContainer.hide();
                $saveCardContainer.hide();

                // Destroy card instance if it exists
                if (card) {
                    destroyCard();
                }
            } else {
                // Show card form and save card option when using new card
                $cardContainer.show();
                $saveCardContainer.show();

                // Initialize card if not already initialized
                if (!isInitialized) {
                    initializeSquarePayment();
                }
            }
        });

        // Special handling for order pay page
        if (isOrderPayPage) {
            // Initialize card if no saved card is selected
            const selectedToken = $(`input[name="wc-${gatewayId}-payment-token"]:checked`).val();
            if (!selectedToken || selectedToken === 'new') {
                setTimeout(() => {
                    initializeSquarePayment();
                }, 500);
            }
        }

        // Trigger initial state
        $(`input[name="wc-${gatewayId}-payment-token"]:checked`).trigger('change');
    }

    // Initialize saved card handling when document is ready
    $(document).ready(function () {
        initializeSavedCardHandling();
    });

    async function reinitializeCardElement() {
        try {
            // Destroy existing card instance
            await destroyCard();

            // Clear initialization flags
            isInitialized = false;
            initializationInProgress = false;

            // Reinitialize card
            await initializeSquarePayment();

        } catch (error) {
            // Silently handle reinitialization errors
        }
    }

})(jQuery);
