/* global Square, fkwcsq_add_payment_method_params */

(function($) {
    'use strict';

    // Keep track of card instance
    let card = null;
    let payments = null;
    let isInitialized = false;
    let isProcessing = false;

    // Function to check if Square source exists
    function hasSquareSource() {
        return $('input[name="fkwcsq_square_nonce"]').length > 0 ?
            $('input[name="fkwcsq_square_nonce"]').val() : '';
    }

    // Initialize Square payment form
    async function initializeSquarePayment() {
        try {
            // Ensure card container is empty
            $('#square-card-container').empty();

            // Initialize Square Payments
            payments = await Square.payments(
                fkwcsq_add_payment_method_params.application_id,
                fkwcsq_add_payment_method_params.location_id
            );

            // Create card payment method
            card = await payments.card();

            // Attach card to container
            const cardContainer = document.getElementById('square-card-container');
            if (!cardContainer) {
                return;
            }

            await card.attach('#square-card-container');
            isInitialized = true;

        } catch (error) {
            console.error(`Initialization Error: ${error.message}`);
            $('#square-card-error')
                .html(`Failed to initialize payment form: ${error.message}`)
                .show();
        }
    }

    // Build buyer verification details for STORE flow
    function buildStoreVerificationDetails() {
        const verificationDetails = {
            intent: 'STORE',
            customerInitiated: true,
            sellerKeyedIn: false,
            billingContact: {
                givenName: fkwcsq_add_payment_method_params.billing_first_name || '',
                familyName: fkwcsq_add_payment_method_params.billing_last_name || '',
                email: fkwcsq_add_payment_method_params.billing_email || ''
            }
        };

        // Add optional billing address fields if available
        if (fkwcsq_add_payment_method_params.billing_country) {
            verificationDetails.billingContact.countryCode = fkwcsq_add_payment_method_params.billing_country.toUpperCase();
        }
        if (fkwcsq_add_payment_method_params.billing_city) {
            verificationDetails.billingContact.city = fkwcsq_add_payment_method_params.billing_city;
        }
        if (fkwcsq_add_payment_method_params.billing_address_1) {
            verificationDetails.billingContact.addressLines = [fkwcsq_add_payment_method_params.billing_address_1];
        }
        if (fkwcsq_add_payment_method_params.billing_address_2) {
            if (!verificationDetails.billingContact.addressLines) {
                verificationDetails.billingContact.addressLines = [];
            }
            verificationDetails.billingContact.addressLines.push(fkwcsq_add_payment_method_params.billing_address_2);
        }
        if (fkwcsq_add_payment_method_params.billing_state) {
            verificationDetails.billingContact.region = fkwcsq_add_payment_method_params.billing_state;
        }
        if (fkwcsq_add_payment_method_params.billing_postcode) {
            verificationDetails.billingContact.postalCode = fkwcsq_add_payment_method_params.billing_postcode;
        }

        return verificationDetails;
    }

    // Enhanced tokenization with buyer verification for STORE flow
    async function tokenizeWithBuyerVerification() {
        try {
            const verificationDetails = buildStoreVerificationDetails();

            // 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;
            }
        }
    }

    // Process add payment method submission
    async function processAddPaymentMethodSubmit(event) {
        // Prevent default form submission
        event.preventDefault();

        if (isProcessing) {
            return false;
        }

        isProcessing = true;

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

        try {
            // Ensure card is initialized
            if (!isInitialized) {
                await initializeSquarePayment();
            }

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

            // Add payment nonce to form
            const $form = $('#add_payment_method');
            $('<input>')
                .attr('type', 'hidden')
                .attr('name', 'fkwcsq_square_nonce')
                .val(tokenizationResult.token)
                .appendTo($form);

            // Add verified buyer token if available
            if (tokenizationResult.verifiedBuyer) {
                $('<input>')
                    .attr('type', 'hidden')
                    .attr('name', 'fkwcsq_verification_token')
                    .val(tokenizationResult.verifiedBuyer)
                    .appendTo($form);
            }

            // Verify nonce was added
            const addedNonce = $('input[name="fkwcsq_square_nonce"]').val();
            if (!addedNonce) {
                $('#square-card-error')
                    .html('Payment Error: Failed to add payment information.')
                    .show();

                isProcessing = false;
                return false;
            }

            // Submit the form
            isProcessing = false;
            $form.off('submit').submit();
            return true;
        } catch (error) {
            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')
                    .html(`Payment Error: ${error.message}`)
                    .show();
            } else {
                // For other errors, log to console and show error
                console.error('Payment error:', error);
                $('#square-card-error')
                    .html(`Payment Error: ${error.message}`)
                    .show();
            }

            isProcessing = false;
            return false;
        }
    }

    // Document Ready
    $(document).ready(function() {
        // Initialize Square payment on page load
        if ($('#square-card-container').length) {
            initializeSquarePayment();
        }

        // Form submission handler
        $('#add_payment_method').on('submit', function(e) {
            // Check if this is a Square payment method
            const selectedMethod = $('input[name="payment_method"]:checked').val();

            if (selectedMethod === 'fkwcsq_square') {
                // Check if we already have a nonce
                const source = hasSquareSource();

                if (source === '') {
                    return processAddPaymentMethodSubmit(e);
                }
            }

            // Let the form submit normally
            return true;
        });

        // 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();
        });
    });

})(jQuery);
