jQuery(document).ready(function ($) {
  // Only run on the checkout page if we have giftcard_data
  if (typeof giftcard_data === 'undefined') {
    return;
  }

  const nonce   = giftcard_data.nonce;
  const ajaxUrl = giftcard_data.ajax_url;

  // Prevent "Enter" key from submitting the entire checkout form:
  // Instead, it will click our Apply Gift Card button.
  $(document).on('keypress', '#gift_card_code_input', function (e) {
    if (e.which === 13) {
      e.preventDefault();
      $('#apply_gift_card_btn').trigger('click');
    }
  });

  /**
   * Utility function to show a message inline
   * @param {string} message - Text message
   * @param {string} type - 'success' or 'error'
   */
  function showGiftCardMessage(message, type) {
    const $msg = $('#gift_card_message');
    if (!$msg.length) return;

    // Clear previous classes
    $msg.removeClass('giftcard-success giftcard-error');

    // Add new class for color styling
    if (type === 'success') {
      $msg.addClass('giftcard-success').text(message);
    } else {
      $msg.addClass('giftcard-error').text(message);
    }
  }

  // APPLY GIFT CARD
  $(document).on('click', '#apply_gift_card_btn', function (e) {
    e.preventDefault();
    const giftCardCode = $('#gift_card_code_input').val();

    // Clear old messages
    showGiftCardMessage('', '');

    if (!giftCardCode) {
      showGiftCardMessage('Please enter a gift card code first.', 'error');
      return;
    }

    $.ajax({
      url: ajaxUrl,
      type: 'POST',
      dataType: 'json',
      data: {
        action: 'squarewoosync_pro_apply_gift_card',
        nonce: nonce,
        gift_card_code: giftCardCode
      },
      beforeSend: function () {
        // Optionally show a loader/spinner
      },
      success: function (response) {
        if (response.success) {
          // Show success inline
          showGiftCardMessage(response.data.message || 'Gift Card Applied!', 'success');
          // Trigger WooCommerce checkout refresh
          $(document.body).trigger('update_checkout');
        } else {
          // Show error inline
          if (response.data && response.data.message) {
            showGiftCardMessage(response.data.message, 'error');
          } else {
            showGiftCardMessage('Error applying gift card.', 'error');
          }
        }
      },
      error: function (xhr, status, error) {
        console.error('AJAX error:', error);
        showGiftCardMessage('Error applying gift card.', 'error');
      }
    });
  });

  // REMOVE GIFT CARD
  $(document).on('click', '#remove_gift_card_btn', function (e) {
    e.preventDefault();

    // Clear old messages
    showGiftCardMessage('', '');

    $.ajax({
      url: ajaxUrl,
      type: 'POST',
      dataType: 'json',
      data: {
        action: 'squarewoosync_pro_remove_gift_card',
        nonce: nonce
      },
      beforeSend: function () {
        // Optionally show a loader/spinner
      },
      success: function (response) {
        if (response.success) {
          // Show success inline
          showGiftCardMessage(response.data.message || 'Gift Card Removed!', 'success');
          // Trigger WooCommerce checkout refresh
          $(document.body).trigger('update_checkout');
        } else {
          // Show error inline
          if (response.data && response.data.message) {
            showGiftCardMessage(response.data.message, 'error');
          } else {
            showGiftCardMessage('Error removing gift card.', 'error');
          }
        }
      },
      error: function (xhr, status, error) {
        console.error('AJAX error:', error);
        showGiftCardMessage('Error removing gift card.', 'error');
      }
    });
  });
});
