ChinaPayments.Component['woocommerce-payment-handler'] = {

  container: {},
  configuration: {
    stripe_publishable_key: '',
    payment_intent_id: '',
    payment_intent_secret: '',
    setup_intent_id: '',
    setup_intent_secret: '',
    payment_method: '',
    return_url: '',
    return_url_error: '',
    error_message: ''
  },

  _stripeSDK: null,

  Init: function (container) {
    this.container = container;

    let objectInstance = this;

    china_payments_component_configuration_parse(this, function () {
      if (typeof window.Stripe === "undefined") {
        ChinaPayments.LoadAssets('https://js.stripe.com/v3/', function () {
          objectInstance.__initStripeSDKLoaded();
        }, false);

        return;
      }

      objectInstance.__initStripeSDKLoaded();
    });
  },

  __initStripeSDKLoaded: function () {
    if (this._stripeSDK === null)
      this._stripeSDK = window.Stripe(this.configuration.stripe_publishable_key);

    if (this.configuration.payment_method === 'alipay') {
      this._handleAlipay();
    } else if (this.configuration.payment_method === 'wechat_pay') {
      this._handleWeChatPay();
    } else if (this.configuration.payment_method === 'card') {
      this._handleCard();
    }
  },

  _handleCard: function () {
    let objectInstance = this;
    let elements = this._stripeSDK.elements();
    let cardElement = elements.create('card', {
      style: {
        base: {
          fontSize: '16px',
          color: '#32325d',
          fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, sans-serif',
          '::placeholder': {
            color: '#aab7c4'
          }
        },
        invalid: {
          color: '#fa755a',
          iconColor: '#fa755a'
        }
      },
      hidePostalCode: true
    });

    this.container.html(
      '<div style="margin:20px 0;">' +
      '<p style="font-size:14px;color:#555;margin-bottom:12px;">Enter your UnionPay card details below:</p>' +
      '<div id="china-payments-card-element" style="padding:12px;border:1px solid #e0e0e0;border-radius:6px;background:#fff;"></div>' +
      '<div id="china-payments-card-errors" style="color:#fa755a;font-size:13px;margin-top:8px;"></div>' +
      '<button id="china-payments-card-submit" style="display:block;width:100%;margin-top:16px;padding:12px;background:#0073aa;color:#fff;border:none;border-radius:6px;font-size:16px;cursor:pointer;font-weight:600;">Pay Now</button>' +
      '</div>'
    );

    cardElement.mount('#china-payments-card-element');

    let errorDisplay = document.getElementById('china-payments-card-errors');
    cardElement.on('change', function (event) {
      errorDisplay.textContent = event.error ? event.error.message : '';
    });

    let submitButton = document.getElementById('china-payments-card-submit');
    submitButton.addEventListener('click', function () {
      submitButton.disabled = true;
      submitButton.textContent = 'Processing...';
      submitButton.style.opacity = '0.7';

      objectInstance._stripeSDK.confirmCardPayment(
        objectInstance.configuration.payment_intent_secret,
        {
          payment_method: {
            card: cardElement,
          }
        }
      ).then(function (result) {
        if (result.error) {
          errorDisplay.textContent = result.error.message;
          submitButton.disabled = false;
          submitButton.textContent = 'Pay Now';
          submitButton.style.opacity = '1';

          if (result.error.type === 'card_error' || result.error.type === 'validation_error') {
            return;
          }

          // Non-card error, redirect after delay
          objectInstance.container.html('<div data-china-payments-notification="danger">' + objectInstance.configuration.error_message + '</div>');
          setTimeout(function () {
            window.location.href = objectInstance.configuration.return_url_error;
          }, 4000);
          return;
        }

        if (result.paymentIntent && result.paymentIntent.status === 'succeeded') {
          submitButton.textContent = 'Payment Successful!';
          submitButton.style.background = '#28a745';
          window.location.href = objectInstance.configuration.return_url;
        } else if (result.paymentIntent && result.paymentIntent.status === 'requires_action') {
          // 3DS handled automatically by Stripe
          submitButton.textContent = 'Authenticating...';
        }
      });
    });
  },

  _handleAlipay: function () {
    let objectInstance = this;

    this._stripeSDK.confirmAlipayPayment(
      this.configuration.payment_intent_secret,
      {
        return_url: this.configuration.return_url
      }
    ).then(function (result) {
      if (result.error) {
        objectInstance.container.html('<div data-china-payments-notification="danger">' + objectInstance.configuration.error_message + '</div>')

        setTimeout(function () {
          window.location.href = objectInstance.configuration.return_url_error;
        }, 4000);
        // Inform the customer that there was an error.
      }

      if (typeof result.paymentIntent !== 'undefined' && result.paymentIntent.status === "succeeded")
        window.location.href = objectInstance.configuration.return_url;
    });
  },

  _handleWeChatPay: function () {
    let objectInstance = this;

    this.container.html('');

    this._stripeSDK.confirmWechatPayPayment(
      this.configuration.payment_intent_secret,
      {
        payment_method_options: {
          wechat_pay: {
            client: 'web',
          },
        }
      },
    ).then(function (response) {
      if (typeof response.paymentIntent === "undefined" || response.paymentIntent.status !== "succeeded") {
        objectInstance.container.html('<div data-china-payments-notification="danger">' + objectInstance.configuration.error_message + '</div>')

        setTimeout(function () {
          window.location.href = objectInstance.configuration.return_url_error;
        }, 4000);

        return;
      }

      window.location.href = objectInstance.configuration.return_url;
    });
  }

};