/**
 * Hyperpay Saved Cards JavaScript
 */

(function ($) {
    'use strict';

    $(document).ready(function () {


        // Handle remove card from checkout
        $(document).on('click', '.hyperpay-delete-card', function (e) {
            e.preventDefault();
            e.stopPropagation();


            if (typeof hyperpay_saved_cards === 'undefined') {
                alert('Error: Script not properly loaded. Please refresh the page.');
                return false;
            }

            const confirmMessage = hyperpay_saved_cards.confirm_delete || 'Are you sure you want to remove this card?';
            if (!confirm(confirmMessage)) {

                return false;
            }

            const registrationId = $(this).data('id');
            const $cardItem = $(this).closest('.hyperpay-saved-card-item');


            // Show loading state
            $(this).text('Deleting...').prop('disabled', true);

            // Send AJAX request to delete card
            $.ajax({
                url: hyperpay_saved_cards.ajax_url,
                type: 'POST',
                data: {
                    action: 'hyperpay_delete_card',
                    registration_id: registrationId,
                    _wpnonce: hyperpay_saved_cards.hyperpay_process_checkout_nonce
                },
                success: function (response) {

                    if (response.success) {
                        // Remove card from list
                        $cardItem.fadeOut(300, function () {
                            $(this).remove();

                            // If no more saved cards, hide section and show new card option
                            if ($('.hyperpay-saved-card-item').not('.hyperpay-new-card-option').length === 0) {
                                $('.hyperpay-saved-cards-section').fadeOut(300);
                                $('.hyperpay-save-card-option').slideDown();
                            } else {
                                // Select first remaining card
                                $('.hyperpay-saved-card-item:first input[type="radio"]').prop('checked', true).trigger('change');
                            }
                        });
                    } else {
                        alert(response.data || 'Failed to delete card');
                        $(this).html('<span class="dashicons dashicons-trash"></span>').prop('disabled', false);
                    }
                },
                error: function (xhr, status, error) {
                    alert('Network error. Please try again.');
                    $(this).html('<span class="dashicons dashicons-trash"></span>').prop('disabled', false);
                }
            });
        });
    });
})(jQuery);