var { registerPaymentMethod } = wc.wcBlocksRegistry;
var { __ } = wp.i18n;
var creditCardBlocksSettings = wc.wcSettings.getSetting('anet_data');
var { decodeEntities } = wp.htmlEntities;
var expiryMonth, expiryYear;
var number, securityCode;
var currentYear = new Date().getFullYear();
var currentMonth = new Date().getMonth();
const { useSelect } = window.wp.data;
const { CHECKOUT_STORE_KEY } = window.wc.wcBlocksData;
var canMakePayment = () => {
  return true;
};
// Card: - Function to detect card type from card number
var getCardType = (cardNumber) => {
  var cleanNumber = cardNumber.replace(/\D/g, '');
  // Visa
  if (/^4/.test(cleanNumber)) {
    return 'visa';
  }
  // Mastercard
  if (/^5[1-5]|^2[2-7]/.test(cleanNumber)) {
    return 'mastercard';
  }
  // American Express
  if (/^3[47]/.test(cleanNumber)) {
    return 'amex';
  }
  // Discover
  if (/^(6011|622(12[6-9]|1[3-9][0-9]|[2-8][0-9]{2}|9[0-1][0-9]|92[0-5]|64[4-9])|65)/.test(cleanNumber)) {
    return 'discover';
  }
  // JCB
  if (/^35(2[89]|[3-8][0-9])/.test(cleanNumber)) {
    return 'jcb';
  }
  // Diners Club
  if (/^3[0689]/.test(cleanNumber)) {
    return 'diners-club';
  }
  return 'unknown';
};
// Card: Function to check if card type is allowed
var isCardTypeAllowed = (cardType, allowedTypes) => {
  if (!allowedTypes || allowedTypes.length === 0) {
    return false; // If no card types are configured, don't allow any payments
  }
  return allowedTypes.indexOf(cardType) !== -1;
};
//Card : Function to update card type logo in input field
var updateCardTypeLogo = (cardNumber, siteUrl) => {
  const inputField = document.getElementById('number-container-1');
  if (!inputField) return;
  // Extract WordPress root directory from current URL
  const url = new URL(window.location.href);
  const pathSegments = url.pathname.split('/').filter(Boolean);
  const baseSegment = pathSegments.length > 0 ? pathSegments[0] : '';
  // Construct the base URL
  const baseUrl = `${url.origin}/${baseSegment}`;
  const pluginBaseUrl = baseUrl + '/wp-content/plugins/authorize-net-payments-for-woocommerce/assets/img/';
  const cardType = getCardType(cardNumber);
  // Card type to image mapping
  const cardImages = {
    'visa': 'card-visa.png',
    'mastercard': 'card-mastercard.png',
    'amex': 'card-amex.png',
    'discover': 'card-discover.png',
    'jcb': 'card-jcb.png',
    'diners-club': 'card-dinersclub.png'
  };
  if (cardType && cardImages[cardType]) {
    inputField.style.backgroundImage = `url('${pluginBaseUrl}${cardImages[cardType]}')`;
    inputField.style.backgroundRepeat = 'no-repeat';
    inputField.style.backgroundPosition = 'right 10px center';
    inputField.style.backgroundSize = '32px 20px';
    inputField.style.paddingRight = '50px';
  } else {
    // Clear the background if no card type matches or unknown card
    inputField.style.backgroundImage = 'none';
    inputField.style.paddingRight = '';
  }
};
// Card: Function to get card max length based on card type
var getCardMaxLength = (cardNumber) => {
  const cardType = getCardType(cardNumber);
  const maxLengths = {
    'visa': 16,
    'mastercard': 16,
    'amex': 15,
    'discover': 16,
    'jcb': 16,
    'diners-club': 14
  };
  return maxLengths[cardType] || 19; // Default max length for unknown cards
};
// CVV: Function to get CVV max length based on card type
var getCVVMaxLength = (cardNumber) => {
  const cardType = getCardType(cardNumber);
  const cvvLengths = {
    'visa': 3,
    'mastercard': 3,
    'amex': 4,
    'discover': 3,
    'jcb': 3,
    'diners-club': 3
  };
  return cvvLengths[cardType] || 4; // Default max length for unknown cards
};
// Function to compare version strings
function compareVersions(version1, version2) {
  const v1parts = version1.split('.').map(Number);
  const v2parts = version2.split('.').map(Number);
  const maxLength = Math.max(v1parts.length, v2parts.length);
  for (let i = 0; i < maxLength; i++) {
    const v1part = v1parts[i] || 0;
    const v2part = v2parts[i] || 0;
    if (v1part > v2part) return 1;
    if (v1part < v2part) return -1;
  }
  return 0;
}
// Get WooCommerce version used for both Credit Card and Echeck
const woocommerceVersionCreditCard = creditCardBlocksSettings?.woocommerce_version || '0.0.0';
// CVV: Function to get required CVV length based on card type
var getRequiredCVVLength = (cardNumber) => {
  const cardType = getCardType(cardNumber);
  if (cardType === 'amex') {
    return 4;
  }
  return 3; // Default for all other known cards
};
// Function to validate billing and shipping addresses for Blocks checkout
function validateBlocksAddresses() {
  // Use the correct selectors based on the HTML structure
  const billingAddress1 = document.querySelector('input[id="billing-address_1"]')?.value || '';
  const billingAddress2 = document.querySelector('input[id="billing-address_2"]')?.value || '';
  const shippingAddress1 = document.querySelector('input[id="shipping-address_1"]')?.value || '';
  const shippingAddress2 = document.querySelector('input[id="shipping-address_2"]')?.value || '';
  // Get name and postcode fields
  const billingFirstName = document.querySelector('input[id="billing-first_name"]')?.value || '';
  const billingLastName = document.querySelector('input[id="billing-last_name"]')?.value || '';
  const billingPostcode = document.querySelector('input[id="billing-postcode"]')?.value || '';
  const billingCity = document.querySelector('input[id="billing-city"]')?.value || '';
  const billingPhone = document.querySelector('input[id="billing-phone"]')?.value || '';
  const shippingFirstName = document.querySelector('input[id="shipping-first_name"]')?.value || '';
  const shippingLastName = document.querySelector('input[id="shipping-last_name"]')?.value || '';
  const shippingPostcode = document.querySelector('input[id="shipping-postcode"]')?.value || '';
  const shippingCity = document.querySelector('input[id="shipping-city"]')?.value || '';
  const shippingPhone = document.querySelector('input[id="shipping-phone"]')?.value || '';
  // Collect all validation errors
  const errors = [];
  // Validate shipping address if different from billing
  if (shippingAddress1) {
    if (shippingAddress1.includes('<') || shippingAddress1.includes('>') || !/^[a-zA-Z0-9\s\-\.]+$/.test(shippingAddress1)) {
      errors.push('Shipping Address is invalid. Special characters are not allowed.');
    }
  }
  // Validate shipping address line 2 if provided
  if (shippingAddress2 && shippingAddress2.trim() !== '') {
    if (shippingAddress2.includes('<') || shippingAddress2.includes('>') || !/^[a-zA-Z0-9\s\-\.]+$/.test(shippingAddress2)) {
      errors.push('Shipping Address is invalid. Special characters are not allowed.');
    }
  }
  // Validate billing address
  if (billingAddress1) {
    if (billingAddress1.includes('<') || billingAddress1.includes('>') || !/^[a-zA-Z0-9\s\-\.]+$/.test(billingAddress1)) {
      errors.push('Billing Address is invalid. Special characters are not allowed.');
    }
  }
  // Validate billing address if provided
  if (billingAddress2 && billingAddress2.trim() !== '') {
    if (billingAddress2.includes('<') || billingAddress2.includes('>') || !/^[a-zA-Z0-9\s\-\.]+$/.test(billingAddress2)) {
      errors.push('Billing Address is invalid. Special characters are not allowed.');
    }
  }
  // Validate shipping first name
  if (shippingFirstName) {
    if (shippingFirstName.includes('<') || shippingFirstName.includes('>') || !/^[a-zA-Z\s\-\.]+$/.test(shippingFirstName)) {
      errors.push('Shipping First name is invalid. Special characters are not allowed.');
    }
  }
  // Validate shipping last name
  if (shippingLastName) {
    if (shippingLastName.includes('<') || shippingLastName.includes('>') || !/^[a-zA-Z\s\-\.]+$/.test(shippingLastName)) {
      errors.push('Shipping Last name is invalid. Special characters are not allowed.');
    }
  }
  // Validate shipping postcode
  if (shippingPostcode) {
    if (shippingPostcode.includes('<') || shippingPostcode.includes('>') || !/^[a-zA-Z0-9\s\-]+$/.test(shippingPostcode)) {
      errors.push('Shipping ZIP Code is invalid. Special characters are not allowed.');
    }
  }
  // Validate billing first name
  if (billingFirstName) {
    if (billingFirstName.includes('<') || billingFirstName.includes('>') || !/^[a-zA-Z\s\-\.]+$/.test(billingFirstName)) {
      errors.push('Billing First name is invalid. Special characters are not allowed.');
    }
  }
  // Validate billing last name
  if (billingLastName) {
    if (billingLastName.includes('<') || billingLastName.includes('>') || !/^[a-zA-Z\s\-\.]+$/.test(billingLastName)) {
      errors.push('Billing Last name is invalid. Special characters are not allowed.');
    }
  }
  // Validate billing postcode
  if (billingPostcode) {
    if (billingPostcode.includes('<') || billingPostcode.includes('>') || !/^[a-zA-Z0-9\s\-]+$/.test(billingPostcode)) {
      errors.push('Billing ZIP Code is invalid. Special characters are not allowed.');
    }
  }
  // Validate shipping city
  if (shippingCity) {
    if (shippingCity.includes('<') || shippingCity.includes('>') || !/^[a-zA-Z\s\-\.]+$/.test(shippingCity)) {
      errors.push('Shipping City is invalid. Special characters are not allowed.');
    }
  }
  // Validate shipping phone if provided
  if (shippingPhone && shippingPhone.trim() !== '') {
    if (shippingPhone.includes('<') || shippingPhone.includes('>') || !/^[a-zA-Z0-9\s\-\+\(\)\.]+$/.test(shippingPhone)) {
      errors.push('Shipping Phone is invalid. Special characters are not allowed.');
    }
  }
  // Validate billing city
  if (billingCity) {
    if (billingCity.includes('<') || billingCity.includes('>') || !/^[a-zA-Z\s\-\.]+$/.test(billingCity)) {
      errors.push('Billing City is invalid. Special characters are not allowed.');
    }
  }
  // Validate billing phone if provided
  if (billingPhone && billingPhone.trim() !== '') {
    if (billingPhone.includes('<') || billingPhone.includes('>') || !/^[a-zA-Z0-9\s\-\+\(\)\.]+$/.test(billingPhone)) {
      errors.push('Billing Phone is invalid. Special characters are not allowed.');
    }
  }
  // Return all errors at once
  if (errors.length > 0) {
    return {
      valid: false,
      message: errors.join('<br/>'),
    };
  }
  return { valid: true };
}
if (compareVersions(woocommerceVersionCreditCard, '8.3.0') > 0) {
  // React components for Month and Year dropdowns
  class MonthDropdownAnet extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        selectedMonth: ''
      };
    }
    handleMonthChange = (event) => {
      const selectedMonth = event.target.value;
      this.setState({ selectedMonth }, () => {
        this.props.onMonthChange(selectedMonth);
      });
    };
    render() {
      return React.createElement(
        'div',
        { id: 'exp-month-div', className: 'form-row form-row-first' },
        React.createElement(
          'label',
          { htmlFor: 'month', className: "credit-card-form-label", style: { fontWeight: 'normal', fontSize: 'large' } },
          'Expiry Month '
        ),
        React.createElement(
          'select',
          { id: 'month', value: this.state.selectedMonth, onChange: this.handleMonthChange },
          React.createElement('option', { value: 'Select' }, 'Select Month'), // Placeholder
          React.createElement('option', { value: '01' }, 'January'),
          React.createElement('option', { value: '02' }, 'February'),
          React.createElement('option', { value: '03' }, 'March'),
          React.createElement('option', { value: '04' }, 'April'),
          React.createElement('option', { value: '05' }, 'May'),
          React.createElement('option', { value: '06' }, 'June'),
          React.createElement('option', { value: '07' }, 'July'),
          React.createElement('option', { value: '08' }, 'August'),
          React.createElement('option', { value: '09' }, 'September'),
          React.createElement('option', { value: '10' }, 'October'),
          React.createElement('option', { value: '11' }, 'November'),
          React.createElement('option', { value: '12' }, 'December')
        )
      );
    }
  }
  class YearDropdownAnet extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        selectedYear: ''
      };
    }
    handleYearChange = (event) => {
      const selectedYear = event.target.value;
      this.setState({ selectedYear }, () => {
        this.props.onYearChange(selectedYear);
      });
    };
    render() {
      const currentYear = new Date().getFullYear();
      const years = Array.from({ length: 10 }, (_, index) => currentYear + index);
      const optionElements = years.map((year) => {
        return React.createElement('option', { value: year.toString() }, year.toString());
      });
      return React.createElement(
        'div',
        { id: 'exp-year-div', className: 'form-row form-row-last' },
        React.createElement(
          'label',
          { htmlFor: 'year', className: "credit-card-form-label", style: { fontWeight: 'normal', fontSize: 'large' } },
          'Expiry Year '
        ),
        React.createElement(
          'select',
          { id: 'year', value: this.state.selectedYear, onChange: this.handleYearChange },
          optionElements
        )
      );
    }
  }
  handleMonthChange = (selectedMonth) => {
    expiryMonth = selectedMonth;
  };
  handleYearChange = (selectedYear) => {
    expiryYear = selectedYear;
  };
}
const creditCardStoredCardComponentsAnet = (props) => {
  const { token, eventRegistration, emitResponse } = props;
  const { onPaymentProcessing, onCheckoutFail } = eventRegistration;
  React.useEffect(() => {
    const creditCardStoredCardPaymentComponent = onPaymentProcessing(async () => {
      // Network connectivity check for saved cards
      if (!navigator.onLine) {
        return {
          type: emitResponse.responseTypes.ERROR,
          message: 'You appear to be offline. Please check your internet connection and try again.',
          messageContext: emitResponse.noticeContexts.PAYMENTS,
        };
      }
      return {
        type: emitResponse.responseTypes.SUCCESS,
        meta: {
          paymentMethodData: {
            token: token,
          },
        },
      };
    });
    const creditCardStoredCardPaymentComponentFail = onCheckoutFail((processingResponse) => {
      const errorResponse = processingResponse;
      if (errorResponse.processingResponse?.paymentDetails?.message) {
        return {
          type: emitResponse.responseTypes.ERROR,
          message: errorResponse.processingResponse.paymentDetails.message,
          messageContext: emitResponse.noticeContexts.PAYMENTS,
        };
      }
      return true;
    });
    return () => {
      creditCardStoredCardPaymentComponent();
      creditCardStoredCardPaymentComponentFail();
    };
  }, [onPaymentProcessing, onCheckoutFail, emitResponse]);
  return [];
}
const creditCardComponentsAnet = (props) => {
  const { onSubmit, eventRegistration, emitResponse } = props;
  const { onPaymentProcessing, onCheckoutFail } = eventRegistration;
  React.useEffect(() => {
    const creditCardPaymentComponent = onPaymentProcessing(async () => {
      // Network connectivity check before processing
      if (!navigator.onLine) {
        return {
          type: emitResponse.responseTypes.ERROR,
          message: 'You appear to be offline. Please check your internet connection and try again.',
          messageContext: emitResponse.noticeContexts.PAYMENTS,
        };
      }
      // Validate billing and shipping addresses
      const addressValidation = validateBlocksAddresses();
      if (!addressValidation.valid) {
        return {
          type: emitResponse.responseTypes.ERROR,
          message: addressValidation.message,
          messageContext: emitResponse.noticeContexts.CHECKOUT,
        };
      }
      const cardNumber = document.getElementById('number-container-1').value;
      const securityCode = document.getElementById('securityCode-container').value;
      // Declare variables outside the conditional blocks
      let expiryMonth, expiryYear;
      if (compareVersions(woocommerceVersionCreditCard, '8.3.0') > 0) {
        expiryMonth = document.getElementById('month').value;
        expiryYear = document.getElementById('year').value;
      } else {
        expiryMonth = selectedExpiryMonth;
        expiryYear = selectedExpiryYear;
      }
      // Prepare data for Accept.js
      const authData = {
        clientKey: anet_params_cc.client_key,
        apiLoginID: anet_params_cc.login_id,
      };
      const cardData = {
        cardNumber: cardNumber.replace(/\s/g, ''),
        month: expiryMonth.toString(),
        year: expiryYear.toString().slice(-2),
        cardCode: securityCode,
      };
      // Card: type validation - check if card type is allowed
      const cardType = getCardType(cardData.cardNumber);
      const allowedCardTypes = creditCardBlocksSettings.allowed_card_types || [];
      if (!isCardTypeAllowed(cardType, allowedCardTypes)) {
        jQuery('.wc-anet-error').remove();
        let errorMsg;
        if (!allowedCardTypes || allowedCardTypes.length === 0) {
          errorMsg = 'No card types have been configured in admin. Please contact support.';
        } else {
          errorMsg = 'This card type (' + cardType + ') is not accepted. Please use a different card.';
        }
        return {
          type: emitResponse.responseTypes.ERROR,
          message: errorMsg,
          messageContext: emitResponse.noticeContexts.PAYMENTS,
        };
      }
      // CVV: validation - check if CVV length matches card type requirements
      const requiredCVVLength = getRequiredCVVLength(cardData.cardNumber);
      if (securityCode.length !== requiredCVVLength) {
        jQuery('.wc-anet-error').remove();
        const errorMsg = cardType === 'amex' ?
          'Please enter a valid 4-digit CVV for American Express.' :
          'Please enter a valid 3-digit CVV.';
        return {
          type: emitResponse.responseTypes.ERROR,
          message: errorMsg,
          messageContext: emitResponse.noticeContexts.PAYMENTS,
        };
      }
      // Basic validation for required fields
      if (!cardData.cardNumber || cardData.cardNumber.length < 13) {
        return {
          type: emitResponse.responseTypes.ERROR,
          message: 'Please enter a valid card number.',
          messageContext: emitResponse.noticeContexts.PAYMENTS,
        };
      }
      if (compareVersions(woocommerceVersionCreditCard, '8.3.0') > 0) {
        if (!expiryMonth || expiryMonth === 'Select') {
          return {
            type: emitResponse.responseTypes.ERROR,
            message: 'Please select a valid expiry month.',
            messageContext: emitResponse.noticeContexts.PAYMENTS,
          };
        }
        if (!expiryYear || expiryYear === 'Select') {
          return {
            type: emitResponse.responseTypes.ERROR,
            message: 'Please select a valid expiry year.',
            messageContext: emitResponse.noticeContexts.PAYMENTS,
          };
        }
      } else {
        if (!selectedExpiryMonth) {
          return {
            type: emitResponse.responseTypes.ERROR,
            message: 'Please select a valid expiry month.',
            messageContext: emitResponse.noticeContexts.PAYMENTS,
          };
        }
        if (!selectedExpiryYear) {
          return {
            type: emitResponse.responseTypes.ERROR,
            message: 'Please select a valid expiry year.',
            messageContext: emitResponse.noticeContexts.PAYMENTS,
          };
        }
      }
      const secureData = {
        authData: authData,
        cardData: cardData,
      };
      // Generate payment nonce using Accept.js
      const paymentNonce = await new Promise((resolve, reject) => {
        // Start network monitoring for Accept.js processing
        const networkTimeout = setTimeout(() => {
          resolve({
            error: new Error('Processing timeout - please check your connection and try again.'),
          });
        }, 30000);
        const networkHandler = () => {
          clearTimeout(networkTimeout);
          resolve({
            error: new Error('Connection lost during processing - please check your internet connection.'),
          });
        };
        window.addEventListener('offline', networkHandler);
        Accept.dispatchData(secureData, (response) => {
          // Clear network monitoring on response
          clearTimeout(networkTimeout);
          window.removeEventListener('offline', networkHandler);
          jQuery('.wc-anet-error').remove();
          if (response.messages.resultCode === 'Error') {
            // Handle errors from Accept.js
            var i = 0;
            var $errorMessages = jQuery('<ul>', {
              class: 'woocommerce_error woocommerce-error wc-anet-error'
            });
            while (i < response.messages.message.length) {
              console.log(response.messages.message[i].code + ": " + response.messages.message[i].text);
              // For Client Potential XSS - Create error message safely 
              var messageText = response.messages.message[i].text;
              if (typeof messageText === 'string') {
                // Create text node for the error message
                var errorItem = document.createElement('li');
                errorItem.textContent = messageText; // .textContent handles escaping automatically
                $errorMessages[0].appendChild(errorItem);
              }
              i = i + 1;
            }
            // Display the error messages in the UI
            jQuery('.wc-block-components-form-credit-card').before($errorMessages);
            resolve({
              error: new Error(__('Unable to load the payment form. Please contact customer care for any assistance.', 'authorize-net-payments-for-woocommerce')),
            });
          } else {
            // Successfully generated payment nonce
            resolve({
              nonce: response.opaqueData.dataValue,
              descriptor: response.opaqueData.dataDescriptor,
            });
          }
        });
      });
      // Pass the payment nonce and descriptor to WooCommerce
      if (paymentNonce.error) {
        return {
          type: emitResponse.responseTypes.ERROR
        };
      }
      const { shouldSavePayment } = props; // Provided by WooCommerce Blocks
      return {
        type: emitResponse.responseTypes.SUCCESS,
        meta: {
          paymentMethodData: {
            anet_save_payment_method: shouldSavePayment,
            anet_nonce: paymentNonce.nonce,
            anet_data_descriptor: paymentNonce.descriptor,
          },
        },
      };
    });
    const creditCardPaymentComponentFail = onCheckoutFail((processingResponse) => {
      const errorResponse = processingResponse;
      if (errorResponse.processingResponse?.paymentDetails?.message) {
        return {
          type: emitResponse.responseTypes.ERROR,
          message: errorResponse.processingResponse.paymentDetails.message,
          messageContext: emitResponse.noticeContexts.PAYMENTS,
        };
      }
      return true;
    });
    // Cleanup when the component is unmounted
    return () => {
      creditCardPaymentComponent();
      creditCardPaymentComponentFail();
    };
  }, [onPaymentProcessing, onCheckoutFail, emitResponse]);
  const [cardNumber, setCardNumber] = React.useState('');
  const [securityCode, setSecurityCode] = React.useState('');
  const [cardNumberTouched, setCardNumberTouched] = React.useState(false);
  const [securityCodeTouched, setSecurityCodeTouched] = React.useState(false);
  // State for higher version (>8.3.0)
  const [expiryMonth, setExpiryMonth] = React.useState('Select');
  const [expiryYear, setExpiryYear] = React.useState('Select');
  const [expiryMonthTouched, setExpiryMonthTouched] = React.useState(false);
  const [expiryYearTouched, setExpiryYearTouched] = React.useState(false);
  // State for lower version (<=8.3.0) - combobox fields
  const currentYear = new Date().getFullYear();
  const expiryYearOptions = Array.from({ length: 20 }, (_, i) => String(currentYear + i));
  const expiryMonthOptions = [
    { value: '01', label: 'January' },
    { value: '02', label: 'February' },
    { value: '03', label: 'March' },
    { value: '04', label: 'April' },
    { value: '05', label: 'May' },
    { value: '06', label: 'June' },
    { value: '07', label: 'July' },
    { value: '08', label: 'August' },
    { value: '09', label: 'September' },
    { value: '10', label: 'October' },
    { value: '11', label: 'November' },
    { value: '12', label: 'December' },
  ];
  const [expiryMonthQuery, setExpiryMonthQuery] = React.useState('Select Month');
  const [selectedExpiryMonth, setSelectedExpiryMonth] = React.useState('');
  const [expiryMonthActiveIndex, setExpiryMonthActiveIndex] = React.useState(0);
  const [expiryMonthFocused, setExpiryMonthFocused] = React.useState(false);
  const [expiryYearQuery, setExpiryYearQuery] = React.useState('Select Year');
  const [selectedExpiryYear, setSelectedExpiryYear] = React.useState('');
  const [expiryYearActiveIndex, setExpiryYearActiveIndex] = React.useState(0);
  const [expiryYearFocused, setExpiryYearFocused] = React.useState(false);
  // Responsive state for mobile/desktop layout
  const [isMobile, setIsMobile] = React.useState(window.innerWidth <= 768);
  // Handle window resize for responsive layout
  React.useEffect(() => {
    const handleResize = () => {
      setIsMobile(window.innerWidth <= 768);
    };
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);
  React.useEffect(() => {
    const numberInput = document.getElementById('number-container-1');
    const securityCodeInput = document.getElementById('securityCode-container');
    const handleFocus = (e) => {
      e.target.parentNode.classList.add('is-active');
      e.target.parentNode.classList.remove('has-error');
    };
    const handleBlur = (e) => {
      const value = e.target.value.trim();
      if (!value) {
        e.target.parentNode.classList.remove('is-active');
        e.target.parentNode.classList.add('has-error');
      }
    };
    //  Only add listeners if elements exist
    if (numberInput) {
      numberInput.addEventListener('focus', handleFocus);
      numberInput.addEventListener('blur', handleBlur);
    }
    if (securityCodeInput) {
      securityCodeInput.addEventListener('focus', handleFocus);
      securityCodeInput.addEventListener('blur', handleBlur);
    }
    //  Cleanup listeners safely
    return () => {
      if (numberInput) {
        numberInput.removeEventListener('focus', handleFocus);
        numberInput.removeEventListener('blur', handleBlur);
      }
      if (securityCodeInput) {
        securityCodeInput.removeEventListener('focus', handleFocus);
        securityCodeInput.removeEventListener('blur', handleBlur);
      }
    };
  }, []);
  //Card: Dynamic URL construction for WooCommerce payment method icons
  const url = new URL(window.location.href);
  const pathSegments = url.pathname.split('/').filter(Boolean);
  const baseSegment = pathSegments.length > 0 ? pathSegments[0] : '';
  // Construct the base URL
  const baseUrl = `${url.origin}/${baseSegment}`;
  const pluginBaseUrl = baseUrl + '/wp-content/plugins/authorize-net-payments-for-woocommerce/assets/img/';
  // Get allowed card types from settings
  const allowedCardTypes = creditCardBlocksSettings?.allowed_card_types || [];
  // Function to create card icon if card type is allowed
  const createCardIcon = (cardType, imageName, altText) => {
    if (allowedCardTypes.length > 0 && allowedCardTypes.indexOf(cardType) !== -1) { // to show allowed card only  
      return React.createElement("img", {
        className: `wc-block-components-payment-method-icon wc-block-components-payment-method-icon--${cardType}`,
        style: {
          border: '1px solid black'
        },
        src: `${pluginBaseUrl}${imageName}`,
        alt: altText
      });
    }
    return null;
  };
  const creditCardComponent = React.createElement("div", { className: "wc-blocks-credit-card-component" },
    // Card Icons Section - Display only allowed card types 
    React.createElement("div", {
      className: "wc-block-components-payment-method-icons wc-block-components-payment-method-icons--align-left"
    },
      createCardIcon('visa', 'card-visa.png', 'Visa'),
      createCardIcon('mastercard', 'card-mastercard.png', 'Mastercard'),
      createCardIcon('amex', 'card-amex.png', 'American Express'),
      createCardIcon('discover', 'card-discover.png', 'Discover'),
      createCardIcon('jcb', 'card-jcb.png', 'JCB'),
      createCardIcon('diners-club', 'card-dinersclub.png', 'Diners Club')
    ),
    React.createElement("div", {}, creditCardBlocksSettings?.description),
    React.createElement("div", { className: 'wc-block-components-form-credit-card' },
      React.createElement("div", { className: "card-details-row" }, // Div to show card num and cvv in same row
        React.createElement("div", { className: "wc-block-components-text-input" },
          React.createElement("input", {
            type: 'text',
            id: 'number-container-1',
            placeholder: " ",
            value: cardNumber,
            onChange: (e) => {
              let value = e.target.value.replace(/[^0-9]/g, '');
              // Get max length for the card type and trim if necessary
              const maxLength = getCardMaxLength(value);
              if (value.length > maxLength) {
                value = value.slice(0, maxLength);
              }
              setCardNumber(value);
              // Update card type logo in the input field
              const siteUrl = window.location.origin;
              updateCardTypeLogo(value, siteUrl);
            },
            onBlur: () => setCardNumberTouched(true),
            required: true,
            autoCapitalize: "sentences",
            autoComplete: "card-number",
            "aria-label": "Card Number",
            "aria-describedby": "",
            "aria-invalid": cardNumberTouched && cardNumber.length < 13 ? "true" : "false",
            "aria-errormessage": "validate-error-card-number",
            title: "Enter your card number"
          }),
          React.createElement("label", {
            htmlFor: 'number-container-1'
          }, __("Card Number", "authorize-net-payments-for-woocommerce")),
          // Error message element     
          React.createElement("span", {
            id: "validate-error-card-number",
            className: "error-message",
            style: {
              color: 'red',
              fontSize: 'small',
              display: cardNumberTouched && cardNumber.length < 13 ? 'flex' : 'none',
              alignItems: 'center',
              gap: '6px'
            }
          },
            // SVG Alert Icon
            React.createElement("svg", {
              xmlns: "http://www.w3.org/2000/svg",
              viewBox: "-2 -2 24 24",
              width: "24",
              height: "24",
              "aria-hidden": "true",
              focusable: "false",
              style: { fill: 'red' }
            },
              React.createElement("path", {
                d: "M10 2c4.42 0 8 3.58 8 8s-3.58 8-8 8-8-3.58-8-8 3.58-8 8-8zm1.13 9.38l.35-6.46H8.52l.35 6.46h2.26zm-.09 3.36c.24-.23.37-.55.37-.96 0-.42-.12-.74-.36-.97s-.59-.35-1.06-.35-.82.12-1.07.35-.37.55-.37.97c0 .41.13.73.38.96.26.23.61.34 1.06.34s.8-.11 1.05-.34z"
              })
            ), __("Please enter a valid card number.", "authorize-net-payments-for-woocommerce"))
        ),
        React.createElement("div", { className: "wc-block-components-text-input" },
          React.createElement("input", {
            type: 'password',
            id: 'securityCode-container',
            placeholder: " ",
            value: securityCode,
            onChange: (e) => {
              const value = e.target.value.replace(/[^0-9]/g, '');
              const maxCVVLength = getCVVMaxLength(cardNumber);
              // Trim value to max CVV length for the card type
              const trimmedValue = value.length > maxCVVLength ? value.slice(0, maxCVVLength) : value;
              setSecurityCode(trimmedValue);
            },
            onBlur: () => setSecurityCodeTouched(true),
            required: true,
            // minLength: 3,
            //maxLength: getCVVMaxLength(cardNumber),
            autoCapitalize: "sentences",
            autoComplete: "Security-Code",
            "aria-label": "Card Security Code",
            "aria-describedby": "",
            "aria-invalid": securityCodeTouched && (securityCode.length !== getRequiredCVVLength(cardNumber)) ? "true" : "false",
            "aria-errormessage": "validate-error-cvv",
            title: "Enter your Security code"
          }),
          React.createElement("label", { htmlFor: 'securityCode-container' }, __("Card Security Code(CVV)", "authorize-net-payments-for-woocommerce")),
          React.createElement("span", {
            id: "validate-error-cvv",
            className: "error-message validate-error-cvv",
            style: {
              color: 'red',
              fontSize: 'small',
              display: securityCodeTouched && (securityCode.length !== getRequiredCVVLength(cardNumber)) ? 'flex' : 'none',
              alignItems: 'center',
              gap: '6px'
            }
          },
            // SVG Alert Icon
            React.createElement("svg", {
              xmlns: "http://www.w3.org/2000/svg",
              viewBox: "-2 -2 24 24",
              width: "24",
              height: "24",
              "aria-hidden": "true",
              focusable: "false",
              style: { fill: 'red' }
            },
              React.createElement("path", {
                d: "M10 2c4.42 0 8 3.58 8 8s-3.58 8-8 8-8-3.58-8-8 3.58-8 8-8zm1.13 9.38l.35-6.46H8.52l.35 6.46h2.26zm-.09 3.36c.24-.23.37-.55.37-.96 0-.42-.12-.74-.36-.97s-.59-.35-1.06-.35-.82.12-1.07.35-.37.55-.37.97c0 .41.13.73.38.96.26.23.61.34 1.06.34s.8-.11 1.05-.34z"
              })
            ), getCardType(cardNumber) === 'amex' ?
            __("Please enter a valid CVV (4 digits for American Express).", "authorize-net-payments-for-woocommerce") :
            __("Please enter a valid CVV (3 digits).", "authorize-net-payments-for-woocommerce"))
        ),  // End of cvv-row div
      ), // End of card-details-row
      // Conditional rendering based on WooCommerce version
      compareVersions(woocommerceVersionCreditCard, '8.3.0') > 0 ?
        React.createElement("div", { className: "expiry-details-row" }, // Div to show month,year in same row
          React.createElement("div", { className: "wc-block-components-state-input" },
            React.createElement("div", { id: 'wc-credit-card-expiry-fields', className: 'wc-blocks-components-select' },
              React.createElement("div", { className: "wc-blocks-components-select__container" },
                React.createElement("label", {
                  htmlFor: 'month',
                  className: "wc-blocks-components-select__label"
                }, __("Expiry Month", "authorize-net-payments-for-woocommerce")),
                React.createElement("select", {
                  id: 'month',
                  className: 'wc-blocks-components-select__select',
                  required: true,
                  autoComplete: "month",
                  "aria-invalid": expiryMonthTouched && expiryMonth === 'Select' ? "true" : "false",
                  "aria-errormessage": "validate-error-month",
                  defaultValue: '',
                  onChange: (e) => setExpiryMonth(e.target.value),
                  onBlur: () => setExpiryMonthTouched(true)
                },
                  React.createElement('option', { value: 'Select' }, 'Select Month'),
                  React.createElement('option', { value: '01' }, 'January'),
                  React.createElement('option', { value: '02' }, 'February'),
                  React.createElement('option', { value: '03' }, 'March'),
                  React.createElement('option', { value: '04' }, 'April'),
                  React.createElement('option', { value: '05' }, 'May'),
                  React.createElement('option', { value: '06' }, 'June'),
                  React.createElement('option', { value: '07' }, 'July'),
                  React.createElement('option', { value: '08' }, 'August'),
                  React.createElement('option', { value: '09' }, 'September'),
                  React.createElement('option', { value: '10' }, 'October'),
                  React.createElement('option', { value: '11' }, 'November'),
                  React.createElement('option', { value: '12' }, 'December')
                ),
                React.createElement("span", {
                  id: "validate-error-month",
                  className: "error-message",
                  style: {
                    color: 'red',
                    fontSize: 'small',
                    display: expiryMonthTouched && expiryMonth === 'Select' ? 'flex' : 'none',
                     alignItems: 'center',
                      gap: '6px'
                  }
                }, // SVG Alert Icon
                  React.createElement("svg", {
                    xmlns: "http://www.w3.org/2000/svg",
                    viewBox: "-2 -2 24 24",
                    width: "24",
                    height: "24",
                    "aria-hidden": "true",
                    focusable: "false",
                    style: { fill: 'red' }
                  },
                    React.createElement("path", {
                      d: "M10 2c4.42 0 8 3.58 8 8s-3.58 8-8 8-8-3.58-8-8 3.58-8 8-8zm1.13 9.38l.35-6.46H8.52l.35 6.46h2.26zm-.09 3.36c.24-.23.37-.55.37-.96 0-.42-.12-.74-.36-.97s-.59-.35-1.06-.35-.82.12-1.07.35-.37.55-.37.97c0 .41.13.73.38.96.26.23.61.34 1.06.34s.8-.11 1.05-.34z"
                    })
                  ), __("Please select a valid expiry month.", "authorize-net-payments-for-woocommerce")),
                // SVG Icon
                React.createElement("svg", {
                  viewBox: "0 0 24 24",
                  xmlns: "http://www.w3.org/2000/svg",
                  width: "24",
                  height: "24",
                  className: "wc-blocks-components-select__expand",
                  "aria-hidden": "true",
                  focusable: "false"
                },
                  React.createElement("path", {
                    d: "M17.5 11.6L12 16l-5.5-4.4.9-1.2L12 14l4.5-3.6 1 1.2z"
                  })
                )
              ),
            ),
          ),
          React.createElement("div", { className: "wc-block-components-state-input" },
            React.createElement("div", { id: 'wc-credit-card-expiry-fields', className: 'wc-blocks-components-select' },
              React.createElement("div", { className: "wc-blocks-components-select__container" },
                React.createElement("label", {
                  htmlFor: 'year',
                  className: "wc-blocks-components-select__label"
                }, __("Expiry Year", "authorize-net-payments-for-woocommerce")),
                React.createElement("select", {
                  id: 'year',
                  className: 'wc-blocks-components-select__select',
                  required: true,
                  autoComplete: "year",
                  "aria-invalid": expiryYearTouched && expiryYear === 'Select' ? "true" : "false",
                  "aria-errormessage": "validate-error-year",
                  defaultValue: '',
                  onChange: (e) => setExpiryYear(e.target.value),
                  onBlur: () => setExpiryYearTouched(true)
                },
                  React.createElement('option', { value: 'Select' }, 'Select Year'),
                  ...Array.from({ length: 10 }, (_, i) => {
                    const year = new Date().getFullYear() + i;
                    return React.createElement('option', { value: year }, year);
                  })
                ),
                React.createElement("span", {
                  id: "validate-error-year",
                  className: "error-message",
                  style: {
                    color: 'red',
                    fontSize: 'small',
                    display: expiryYearTouched && expiryYear === 'Select' ? 'flex' : 'none',
                     alignItems: 'center',
                    gap: '6px'
                  }
                }, // SVG Alert Icon
                  React.createElement("svg", {
                    xmlns: "http://www.w3.org/2000/svg",
                    viewBox: "-2 -2 24 24",
                    width: "24",
                    height: "24",
                    "aria-hidden": "true",
                    focusable: "false",
                    style: { fill: 'red' }
                  },
                    React.createElement("path", {
                      d: "M10 2c4.42 0 8 3.58 8 8s-3.58 8-8 8-8-3.58-8-8 3.58-8 8-8zm1.13 9.38l.35-6.46H8.52l.35 6.46h2.26zm-.09 3.36c.24-.23.37-.55.37-.96 0-.42-.12-.74-.36-.97s-.59-.35-1.06-.35-.82.12-1.07.35-.37.55-.37.97c0 .41.13.73.38.96.26.23.61.34 1.06.34s.8-.11 1.05-.34z"
                    })
                  ), __("Please select a valid expiry year.", "authorize-net-payments-for-woocommerce")),
                // SVG Icon
                React.createElement("svg", {
                  viewBox: "0 0 24 24",
                  xmlns: "http://www.w3.org/2000/svg",
                  width: "24",
                  height: "24",
                  className: "wc-blocks-components-select__expand",
                  "aria-hidden": "true",
                  focusable: "false"
                },
                  React.createElement("path", {
                    d: "M17.5 11.6L12 16l-5.5-4.4.9-1.2L12 14l4.5-3.6 1 1.2z"
                  })
                )
              ), // end of select
            ),
          ),
        ) : // End of Expiry-card-details for version > 8.3.0 // 7.6.0
        React.createElement("div", {
          className: "expiry-details-row",
          style: {
            display: 'flex',
            gap: '16px',
            width: '100%',
            flexDirection: isMobile ? 'column' : 'row'
          }
        },
          // Expiry Month
          React.createElement("div", {
            className: "wc-block-components-country-input",
            style: {
              flex: '1',
              width: isMobile ? '100%' : '50%'
            }
          },
            React.createElement("div", {
              id: "expiry-month",
              className: "wc-block-components-combobox is-active"
            },
              React.createElement("div", {},
                React.createElement("div", {
                  className: "components-base-control wc-block-components-combobox-control components-combobox-control css-1wzzj1a e1puf3u3"
                },
                  React.createElement("div", {
                    className: "components-base-control__field css-1kyqli5 e1puf3u2"
                  },
                    React.createElement("label", {
                      className: "components-base-control__label css-4dk55l e1puf3u1",
                      htmlFor: "expiry-month-input",
                      style: {
                        color: expiryMonthTouched && !selectedExpiryMonth ? '#e74c3c' : 'inherit'
                      }
                    }, __("Expiry Month", "authorize-net-payments-for-woocommerce")),
                    // Input and Suggestions Container
                    React.createElement("div", { className: "components-combobox-control__suggestions-container", tabIndex: "-1" },
                      React.createElement("div", {
                        "data-wp-c16t": "true",
                        "data-wp-component": "Flex",
                        className: "components-flex css-dfwk0q css-0 em57xhy0"
                      },
                        React.createElement("div", {
                          "data-wp-c16t": "true",
                          "data-wp-component": "FlexBlock",
                          className: "components-flex-item components-flex-block css-106zala css-0 em57xhy0"
                        },
                          React.createElement("input", {
                            id: "expiry-month-input",
                            type: "text",
                            "aria-label": "Expiry Month",
                            className: "components-combobox-control__input components-form-token-field__input",
                            autoComplete: "off",
                            role: "combobox",
                            "aria-expanded": expiryMonthFocused ? "true" : "false",
                            "aria-autocomplete": "list",
                            "aria-describedby": "components-form-token-suggestions-howto-month",
                            value: expiryMonthQuery,
                            size: expiryMonthQuery.length > 0 ? Math.max(expiryMonthQuery.length, 10) : 10,
                            style: {
                              border: expiryMonthTouched && !selectedExpiryMonth ? '1px solid #e74c3c' : '1px solid #757575',
                              borderColor: expiryMonthTouched && !selectedExpiryMonth ? '#e74c3c' : '#757575',
                              boxShadow: expiryMonthTouched && !selectedExpiryMonth ? '0 0 3px rgba(231, 76, 60, 0.3)' : 'none'
                            },
                            onChange: (e) => {
                              setExpiryMonthQuery(e.target.value);
                              setExpiryMonthTouched(true);
                            },
                            onFocus: () => {
                              setExpiryMonthFocused(true);
                              if (expiryMonthQuery === 'Select Month') {
                                setExpiryMonthQuery('');
                              }
                            },
                            onBlur: () => {
                              setTimeout(() => {
                                setExpiryMonthFocused(false);
                                if (!selectedExpiryMonth && expiryMonthQuery.trim() === '') {
                                  setExpiryMonthQuery('Select Month');
                                }
                              }, 150);
                              setExpiryMonthTouched(true);
                            },
                            onKeyDown: (e) => {
                              const searchQuery = expiryMonthQuery === 'Select Month' ? '' : expiryMonthQuery;
                              const filteredOptions = expiryMonthOptions.filter(m =>
                                m.label.toLowerCase().includes(searchQuery.toLowerCase())
                              );
                              if (e.key === 'ArrowDown') {
                                e.preventDefault();
                                setExpiryMonthActiveIndex(prev =>
                                  prev < filteredOptions.length - 1 ? prev + 1 : 0
                                );
                              } else if (e.key === 'ArrowUp') {
                                e.preventDefault();
                                setExpiryMonthActiveIndex(prev =>
                                  prev > 0 ? prev - 1 : filteredOptions.length - 1
                                );
                              } else if (e.key === 'Enter') {
                                e.preventDefault();
                                if (filteredOptions[expiryMonthActiveIndex]) {
                                  const selectedMonth = filteredOptions[expiryMonthActiveIndex];
                                  setSelectedExpiryMonth(selectedMonth.value);
                                  setExpiryMonthQuery(selectedMonth.label);
                                  setExpiryMonthFocused(false);
                                }
                              } else if (e.key === 'Escape') {
                                setExpiryMonthFocused(false);
                              }
                            },
                            "aria-activedescendant": `components-form-token-suggestions-month-${expiryMonthActiveIndex}`
                          })
                        )
                      ),
                      // Month suggestions list - only show when focused
                      expiryMonthFocused && React.createElement("ul", {
                        className: "components-form-token-field__suggestions-list",
                        id: "components-form-token-suggestions-month",
                        role: "listbox"
                      },
                        expiryMonthOptions
                          .filter(m => {
                            const searchQuery = expiryMonthQuery === 'Select Month' ? '' : expiryMonthQuery;
                            return m.label.toLowerCase().includes(searchQuery.toLowerCase());
                          })
                          .map((month, index) =>
                            React.createElement("li", {
                              key: index,
                              id: `components-form-token-suggestions-month-${index}`,
                              role: "option",
                              className: `components-form-token-field__suggestion ${index === expiryMonthActiveIndex ? 'is-selected' : ''}`,
                              "aria-selected": index === expiryMonthActiveIndex,
                              onMouseEnter: () => setExpiryMonthActiveIndex(index),
                              onMouseDown: (e) => {
                                e.preventDefault(); // Prevent blur
                                setSelectedExpiryMonth(month.value);
                                setExpiryMonthQuery(month.label);
                                setExpiryMonthFocused(false);
                              }
                            }, month.label)
                          )
                      )
                    )
                  )
                )
              )
            ),
            // Error Message
            React.createElement("span", {
              id: "validate-error-month",
              className: "error-message",
              style: {
                color: 'red',
                fontSize: 'small',
                display: expiryMonthTouched && !selectedExpiryMonth ? 'flex' : 'none',
                alignItems: 'center',
                gap: '6px'
              }
            },
              React.createElement("svg", {
                xmlns: "http://www.w3.org/2000/svg",
                viewBox: "-2 -2 24 24",
                width: "24",
                height: "24",
                "aria-hidden": "true",
                focusable: "false",
                style: { fill: 'red' }
              },
                React.createElement("path", {
                  d: "M10 2c4.42 0 8 3.58 8 8s-3.58 8-8 8-8-3.58-8-8 3.58-8 8-8zm1.13 9.38l.35-6.46H8.52l.35 6.46h2.26zm-.09 3.36c.24-.23.37-.55.37-.96 0-.42-.12-.74-.36-.97s-.59-.35-1.06-.35-.82.12-1.07.35-.37.55-.37.97c0 .41.13.73.38.96.26.23.61.34 1.06.34s.8-.11 1.05-.34z"
                })
              ),
              __("Please select a valid expiry month.", "authorize-net-payments-for-woocommerce")
            )
          ),
          // Expiry Year
          React.createElement("div", {
            className: "wc-block-components-country-input",
            style: {
              flex: '1',
              width: isMobile ? '100%' : '50%'
            }
          },
            React.createElement("div", {
              id: "expiry-year",
              className: "wc-block-components-combobox is-active"
            },
              React.createElement("div", {},
                React.createElement("div", {
                  className: "components-base-control wc-block-components-combobox-control components-combobox-control css-1wzzj1a e1puf3u3"
                },
                  React.createElement("div", {
                    className: "components-base-control__field css-1kyqli5 e1puf3u2"
                  },
                    React.createElement("label", {
                      className: "components-base-control__label css-4dk55l e1puf3u1",
                      htmlFor: "expiry-year-input",
                      style: {
                        color: expiryYearTouched && !selectedExpiryYear ? '#e74c3c' : 'inherit'
                      }
                    }, __("Expiry Year", "authorize-net-payments-for-woocommerce")),
                    React.createElement("div", { className: "components-combobox-control__suggestions-container", tabIndex: "-1" },
                      React.createElement("div", {
                        "data-wp-c16t": "true",
                        "data-wp-component": "Flex",
                        className: "components-flex css-dfwk0q css-0 em57xhy0"
                      },
                        React.createElement("div", {
                          "data-wp-c16t": "true",
                          "data-wp-component": "FlexBlock",
                          className: "components-flex-item components-flex-block css-106zala css-0 em57xhy0"
                        },
                          React.createElement("input", {
                            id: "expiry-year-input",
                            type: "text",
                            "aria-label": "Expiry Year",
                            className: "components-combobox-control__input components-form-token-field__input",
                            autoComplete: "off",
                            role: "combobox",
                            "aria-expanded": expiryYearFocused ? "true" : "false",
                            "aria-autocomplete": "list",
                            "aria-describedby": "components-form-token-suggestions-howto-year",
                            value: expiryYearQuery,
                            size: expiryYearQuery.length > 0 ? Math.max(expiryYearQuery.length, 8) : 8,
                            style: {
                              border: expiryYearTouched && !selectedExpiryYear ? '1px solid #e74c3c' : '1px solid #757575',
                              borderColor: expiryYearTouched && !selectedExpiryYear ? '#e74c3c' : '#757575',
                              boxShadow: expiryYearTouched && !selectedExpiryYear ? '0 0 3px rgba(231, 76, 60, 0.3)' : 'none'
                            },
                            onChange: (e) => {
                              setExpiryYearQuery(e.target.value);
                              setExpiryYearTouched(true);
                            },
                            onFocus: () => {
                              setExpiryYearFocused(true);
                              if (expiryYearQuery === 'Select Year') {
                                setExpiryYearQuery('');
                              }
                            },
                            onBlur: () => {
                              setTimeout(() => {
                                setExpiryYearFocused(false);
                                if (!selectedExpiryYear && String.prototype.trim.call(expiryYearQuery) === '') {
                                  setExpiryYearQuery('Select Year');
                                }
                              }, 150);
                              setExpiryYearTouched(true);
                            },
                            onKeyDown: (e) => {
                              const searchQuery = expiryYearQuery === 'Select Year' ? '' : expiryYearQuery;
                              const filteredOptions = expiryYearOptions.filter(year =>
                                year.includes(searchQuery)
                              );
                              if (e.key === 'ArrowDown') {
                                e.preventDefault();
                                setExpiryYearActiveIndex(prev =>
                                  prev < filteredOptions.length - 1 ? prev + 1 : 0
                                );
                              } else if (e.key === 'ArrowUp') {
                                e.preventDefault();
                                setExpiryYearActiveIndex(prev =>
                                  prev > 0 ? prev - 1 : filteredOptions.length - 1
                                );
                              } else if (e.key === 'Enter') {
                                e.preventDefault();
                                if (filteredOptions[expiryYearActiveIndex]) {
                                  const selectedYear = filteredOptions[expiryYearActiveIndex];
                                  setSelectedExpiryYear(selectedYear);
                                  setExpiryYearQuery(selectedYear);
                                  setExpiryYearFocused(false);
                                }
                              } else if (e.key === 'Escape') {
                                setExpiryYearFocused(false);
                              }
                            },
                            "aria-activedescendant": `components-form-token-suggestions-year-${expiryYearActiveIndex}`
                          })
                        )
                      ),
                      // Year suggestions list - only show when focused
                      expiryYearFocused && React.createElement("ul", {
                        className: "components-form-token-field__suggestions-list",
                        id: "components-form-token-suggestions-year",
                        role: "listbox"
                      },
                        expiryYearOptions
                          .filter(year => {
                            const searchQuery = expiryYearQuery === 'Select Year' ? '' : expiryYearQuery;
                            return year.includes(searchQuery);
                          })
                          .map((year, index) =>
                            React.createElement("li", {
                              key: index,
                              id: `components-form-token-suggestions-year-${index}`,
                              role: "option",
                              className: `components-form-token-field__suggestion ${index === expiryYearActiveIndex ? 'is-selected' : ''}`,
                              "aria-selected": index === expiryYearActiveIndex,
                              onMouseEnter: () => setExpiryYearActiveIndex(index),
                              onMouseDown: (e) => {
                                e.preventDefault(); // Prevent blur
                                setSelectedExpiryYear(year);
                                setExpiryYearQuery(year);
                                setExpiryYearFocused(false);
                              }
                            }, year)
                          )
                      )
                    )
                  )
                )
              )
            ),
            React.createElement("span", {
              id: "validate-error-year",
              className: "error-message",
              style: {
                color: 'red',
                fontSize: 'small',
                display: expiryYearTouched && !selectedExpiryYear ? 'flex' : 'none',
                alignItems: 'center',
                gap: '6px'
              }
            },
              React.createElement("svg", {
                xmlns: "http://www.w3.org/2000/svg",
                viewBox: "-2 -2 24 24",
                width: "24",
                height: "24",
                "aria-hidden": "true",
                focusable: "false",
                style: { fill: 'red' }
              },
                React.createElement("path", {
                  d: "M10 2c4.42 0 8 3.58 8 8s-3.58 8-8 8-8-3.58-8-8 3.58-8 8-8zm1.13 9.38l.35-6.46H8.52l.35 6.46h2.26zm-.09 3.36c.24-.23.37-.55.37-.96 0-.42-.12-.74-.36-.97s-.59-.35-1.06-.35-.82.12-1.07.35-.37.55-.37.97c0 .41.13.73.38.96.26.23.61.34 1.06.34s.8-.11 1.05-.34z"
                })
              ),
              __("Please select a valid expiry year.", "authorize-net-payments-for-woocommerce")
            )
          )
        )
      /* end of month and year */
    )
  );
  // Show error message if configuration is invalid
  if (!(creditCardBlocksSettings.validate_configuration_key)) {
    jQuery('.blocks-error-div-credit-card').show();
    jQuery('.wc-blocks-credit-card-component').hide();
  }
  const errorDiv = React.createElement("p", {
    className: 'blocks-error-div-credit-card',
    style: {
      display: "none",
      color: 'red'
    }
  }, __('Unable to load the payment form. Please contact customer care for any assistance.'));
  const notice = React.createElement(window.wc.blocksCheckout.StoreNoticesContainer, {
    context: 'anet_notice_container'
  });
  return [creditCardComponent, errorDiv, notice];
}
const anetOptions = {
  name: "anet",
  label: React.createElement("div", {}, creditCardBlocksSettings?.title),
  content: React.createElement(creditCardComponentsAnet, {}, null),
  edit: React.createElement(creditCardComponentsAnet, {}, null),
  canMakePayment,
  paymentMethodId: "anet",
  ariaLabel: "Authorize.net Credit Card Block",
  supports: {
    showSaveOption: creditCardBlocksSettings?.tokenization,
    features: creditCardBlocksSettings?.supports ?? [],
  },
  savedTokenComponent: React.createElement(creditCardStoredCardComponentsAnet, {}, null),
};
if (creditCardBlocksSettings?.is_subscription_order) {
  window.wp.data.dispatch('core/notices').createInfoNotice(
    __('One or more items in your order is a subscription/recurring purchase. By continuing with payment, you agree that your payment method will be automatically charged at the price and frequency listed here until it ends or you cancel.'),
    { id: "checkout", context: "anet_notice_container", isDismissible: false }
  );
}
registerPaymentMethod(anetOptions);
