amount_cents = 0;
jQuery(function ($) {


  $(".chama-form").validate();
  $(document.body).on('change paste keyup', '#chama_subscription_amount', function (event) {
    var symbol = $(this).data("symbol");
    var type = $(this).data("type");
    amount = $(this).val();
    var currency_min = $(this).data("currency-min");
    var formatted_amount = symbol + amount;
    amount_cents = parseFloat(amount) * parseFloat(currency_min);
    //console.log(formatted_amount);
    //$(this).data('amount-cents',  amount_cents );
    $(this).attr('data-amount-cents', amount_cents);
    $('.chama-' + type + ' .chama-summary-amount').text(formatted_amount);
  });

  /*=============================================INITIALIZE PAYMENT ELEMENT=============================================*/
  const publishable_key = $('#chama_pub_key').val();
  const stripe = Stripe(publishable_key);


  amount_cents = $('#chama_subscription_amount').data('amount-cents');
  var currency = $('#chama_subscription_amount').data('currency').toLowerCase();
  var stripe_configuration_id = $('#chama_stripe_configuration_id').val();
  var stripe_customer_session_client_secret = $('#chama_stripe_customer_session_client_secret').val();
  if ($('#chama_stripe_customer_session_client_secret').val()) {
    stripe_customer_session_client_secret = $('#chama_stripe_customer_session_client_secret').val();
  }
  const options = {
    mode: 'subscription',
    setup_future_usage: 'off_session',
    customerSessionClientSecret: stripe_customer_session_client_secret,
    payment_method_configuration: stripe_configuration_id,
    loader: 'always',
    amount: amount_cents,
    currency: currency,
    layout: {
      type: 'tabs',
      defaultCollapsed: false,
    },
    // Fully customizable with appearance API.
    appearance: {
      variables: {
        labels: 'floating',
        fontLineHeight: '1.4',
        fontSizeBase: '16px',
        colorText: '#000000',
        colorPrimary: '#3867d6',
        colorDanger: '#eb3b5a',
        focusBoxShadow: '0 0 0 1px #3867d6',
        borderRadius: '7px',
        borderColor: '#000000'
      },
      rules: {
        '.Input': {
          border: '1px solid #000000',
          boxShadow: 'none',
        }
      }
    },
  };
  // Set up Stripe.js and Elements to use in checkout form
  const elements = stripe.elements(options);
  // Create and mount the Payment Element
  const payment_element = elements.create('payment');
  /*=============================================HANDLE FORM ERROR=============================================*/
  payment_element.on('change', function (event) {
    //billingDataChange();
    if (event.error) {
      handle_error(event.error.message);
      return;
    } else {
      jQuery('#chama-payment-errors').removeClass('show');
    }
    if (event.complete) {
      // enable payment button
      payment_form.querySelector('.chama-pay-button').disabled = false;
      $('.chama-pay-button').removeClass('chama-disabled-button');
    }
  });
  /*=============================================MOUNT PAYMENT ELEMENT=============================================*/
  payment_element.mount('#chama-payment-element');

  /*=============================================
  HANDLE FORM SUBMISSION
  =============================================*/
  const payment_form = document.querySelector('.chama-payment-form');

  payment_form.addEventListener('submit', async (e) => {
    e.preventDefault();

    // Show loader
    $('.chama-loader-wrapper').css('display', 'flex');

    // Disable button
    const payBtn = payment_form.querySelector('.chama-pay-button');
    payBtn.disabled = true;
    $('.chama-pay-button').addClass('chama-disabled-button');

    // Collect values
    const base_rest_url = $('#chama_base_rest_url').val();
    let confirmation_url = $('#chama_confirmation_url').val();
    const email = $('#chama_email').val();
    const nonce = $('#_wpnonce').val();
    const description = $('#chama_description').val();
    const transaction_type = $('#chama_type').val();
    const tier_id = $('#chama_tier_id').val();
    const product_id = $('#chama_product_id').val();
    const price_id = $('#chama_price_id').val();
    const input_amount = $('#chama_subscription_amount').val();

    const form_data = {
      '_wpnonce': nonce,
      'amount': input_amount,
      'type': transaction_type,
      'tier_id': tier_id,
    };

    try {
      // Validate form with Stripe backend
      const { error: submitError } = await elements.submit();
      if (submitError) throw new Error(submitError.message);

      let validateResponse;
      try {
        validateResponse = await $.ajax({
          url: base_rest_url + "v1/stripe/validate",
          type: "POST",
          data: form_data,
        });
      } catch (xhr) {
        showError(xhr.responseText || "Validation failed.");
        return;
      }

      const { status, message } = validateResponse;
      if (status !== 'passed') {
        showError(message || "Validation did not pass.");
        return;
      }

      // Build billing details
      let full_name = null;
      let billing_details = { email: email };
      if ($('#chama_first_name').val() && $('#chama_last_name').val()) {
        full_name = $('#chama_first_name').val() + ' ' + $('#chama_last_name').val();
        billing_details.name = full_name;
      }

      // Prepare subscription values
      let values = {
        '_wpnonce': nonce,
        'base_amount': input_amount,
        'amount': amount_cents,
        'description': description,
        'tier_id': tier_id,
        'product_id': product_id,
        'price_id': price_id,
        'email': email,
        'type': transaction_type,
        'name': full_name,
      };
      if ($('#chama-captcha-response').val()) {
        values.captcha_response = $('#chama-captcha-response').val();
      }

      // Create subscription
      let subscriptionResponse;
      try {
        subscriptionResponse = await $.ajax({
          url: base_rest_url + "v1/stripe/subscription",
          type: "POST",
          data: values,
        });
      } catch (xhr) {
        showError(xhr.responseText || "Subscription request failed.");
        return;
      }

      const { type, clientSecret, subscriptionId, receiptId, paymentIntent } = subscriptionResponse;

      // Handle Stripe confirmation
      const confirmIntent = type === "setup" ? stripe.confirmSetup : stripe.confirmPayment;
      if (subscriptionId) {
        confirmation_url += '&subscription_id=' + subscriptionId + '&receipt_id=' + receiptId + '&payment_intent=' + paymentIntent;
      }
      if (clientSecret) {
        const { error } = await confirmIntent({
          elements,
          clientSecret,
          confirmParams: {
            return_url: confirmation_url,
            payment_method_data: { billing_details }
          },
        });

        if (error) throw new Error(error.message);
      }

    } catch (err) {
      // Any JS/Stripe thrown errors
      showError(err.message || "An unexpected error occurred.");
    } finally {
      // Always hide loader and re-enable form
      $('.chama-loader-wrapper').css('display', 'none');
      payBtn.disabled = false;
      $('.chama-pay-button').removeClass('chama-disabled-button');
    }
  });

  /*=============================================
    HELPER: show error messages
  =============================================*/
  function showError(msg) {
    $('#chama-payment-errors').html(msg);
    $('#chama-payment-errors').addClass('show');
    $('.chama-loader-wrapper').css('display', 'none');
    const payBtn = document.querySelector('.chama-pay-button');
    if (payBtn) {
      payBtn.disabled = false;
      $('.chama-pay-button').removeClass('chama-disabled-button');
    }
  }


});

function handle_error(message) {
  jQuery('#chama-payment-errors').html(message);
  jQuery('#chama-payment-errors').addClass('show');
  jQuery('.chama-loader-wrapper').css('display', 'none');
}