// utils.js

let paymentRequestRef = null; // This replaces the useRef in React
let paymentRequest = null; // This replaces the useState in React

function initPaymentRequest(payments, needsShipping, couponApplied) {
  if (!payments) {
    console.error("Payments object is required to create payment request.");
    return null;
  }

  // Get the selected payment method from WooCommerce
  const selectedPaymentMethod = jQuery(
    'input[name="payment_method"]:checked'
  ).val();
  const selectedShippingMethod = jQuery(
    'input[name="shipping_method[0]"]:checked'
  ).val();

  // Ensure we are only processing if the selected method is Google Pay or Apple Pay
  if (selectedPaymentMethod !== "squaresync_credit") {
    return null;
  }

  // Fetch and create or update the payment request
  return getPaymentRequest()
    .then((__paymentRequestJson) => {
      try {
        const __paymentRequestObject = JSON.parse(__paymentRequestJson);
        // Filter out other shipping options and include only the selected shipping method
        if (__paymentRequestObject) {
          if (Array.isArray(__paymentRequestObject.lineItems)) {
            // const shippingIndex = __paymentRequestObject.lineItems.findIndex(
            //   (item) => item.label?.toLowerCase().includes("shipping")
            // );
            // if (shippingIndex !== -1) {
            //   __paymentRequestObject.lineItems.splice(shippingIndex, 1);
            // }

            const discountIndex = __paymentRequestObject.lineItems.findIndex(
              (item) => item.label?.toLowerCase().includes("discount")
            );
            if (discountIndex !== -1) {
              __paymentRequestObject.lineItems.splice(discountIndex, 1);
            }
          }

          if (needsShipping) {
            __paymentRequestObject.requestShippingAddress = true;
            // const shippingOptions = await buildAdvancedShippingOptions();
            // __paymentRequestObject.shippingOptions = shippingOptions;
          }
        }

        if (!paymentRequestRef) {
          // Create a new payment request
          paymentRequestRef = payments.paymentRequest(__paymentRequestObject);
          paymentRequest = paymentRequestRef; // Set state
        } else {
          // Update the existing payment request
          paymentRequestRef.update(__paymentRequestObject);
        }

        return paymentRequestRef; // Return the created/updated payment request
      } catch (error) {
        console.error("Failed to create or update payment request:", error);
        return null;
      }
    })
    .catch((error) => {
      console.error("Error fetching payment request from the server:", error);
      return null;
    });
}

function getPaymentRequest() {
  return new Promise((resolve, reject) => {
    const data = {
      context: SquareConfig.context,
      security: SquareConfig.paymentRequestNonce,
      is_pay_for_order_page: false,
    };

    jQuery.ajax({
      url: SquareConfig.ajax_url,
      type: "POST",
      data: {
        action: "get_payment_request", // Your PHP handler action
        ...data, // Spread the data into the request
      },
      success: function (response) {
        if (response.success) {
          resolve(response.data); // Resolve with the data
        } else {
          reject(response.data); // Reject with the error data
        }
      },
      error: function (error) {
        reject("Error occurred: " + error.statusText);
      },
    });
  });
}

async function getAjaxUrl(action) {
  return SquareConfig.wc_ajax_url.replace(
    "%%endpoint%%",
    `square_digital_wallet_${action}`
  );
}

async function recalculateTotals(data) {
  return new Promise((resolve, reject) => {
    jQuery.ajax({
      url: SquareConfig.ajax_url,
      type: "POST",
      data: {
        action: "recalculate_totals", // Your PHP handler action
        ...data, // Spread the data into the request
      },
      success: function (response) {
        if (response.success) {
          resolve(response.data); // Resolve with the data
        } else {
          reject(response.data); // Reject with the error data
        }
      },
      error: function (error) {
        reject("Error occurred: " + error.statusText);
      },
    });
  });
}

async function handleShippingAddressChanged(shippingContact) {
  const data = {
    context: "checkout",
    shipping_contact: shippingContact,
    security: SquareConfig.recalculate_totals_nonce,
    is_pay_for_order_page: "false",
  };

  const response = await recalculateTotals(data);
  return response;
}

/**
 * @param {Object} option
 *   Example: { amount: "15.00", id: "flat_rate:1", label: "Flat rate" }
 */
async function handleShippingOptionChanged(option) {
  // option.id typically matches the WooCommerce shipping method input value: "flat_rate:1", "free_shipping:2", etc.
  const shippingRadio = jQuery(
    `input[name="shipping_method[0]"][value="${option.id}"]`
  );

  if (shippingRadio.length) {
    // Check the radio for this shipping method
    shippingRadio.prop("checked", true);

    // Trigger WooCommerce to recalculate totals
    // Many themes or plugins watch these events:
    shippingRadio.trigger("change");
    jQuery("body").trigger("update_checkout");
  } else {
    console.warn(
      `No matching shipping method input found in WooCommerce for "${option.id}"`
    );
  }
}

function attachTokenToForm(token) {
  jQuery("<input>")
    .attr({
      type: "hidden",
      name: "square_payment_token",
      value: token,
    })
    .prependTo("form.checkout");
}

function attachTokenToMyAccountForm(token) {
  jQuery("<input>")
    .attr({
      type: "hidden",
      name: "square_payment_token",
      value: token,
    })
    .prependTo("#add_payment_method");
}

function attachVerificationTokenToForm(verificationToken) {
  jQuery("<input>")
    .attr({
      type: "hidden",
      name: "square_verification_token",
      value: verificationToken,
    })
    .prependTo("form.checkout");
}

// Function to check if shipping is required
function checkNeedsShipping() {
  return new Promise((resolve, reject) => {
    jQuery.ajax({
      url: SquareConfig.ajax_url, // WooCommerce AJAX URL
      type: "POST",
      data: {
        action: "get_needs_shipping", // Action defined in your PHP class
      },
      success: function (response) {
        if (response.success) {
          resolve(response.data.needs_shipping);
        } else {
          reject("Failed to retrieve shipping information.");
        }
      },
      error: function (error) {
        reject("Error occurred: " + error);
      },
    });
  });
}

// Utility function to log payment errors to a specific container
function logPaymentError(message) {
  const paymentStatusContainer = document.getElementById(
    "payment-status-container"
  );
  if (paymentStatusContainer) {
    // Clear any previous errors
    paymentStatusContainer.innerHTML = "";

    // Create error message element
    const errorMessage = document.createElement("p");
    errorMessage.classList.add("payment-error-message"); // Add a CSS class for styling
    errorMessage.textContent = message;

    // Append error message to the container
    paymentStatusContainer.appendChild(errorMessage);
  } else {
    console.error("Payment status container not found.");
  }
}

function buildVerificationDetails(billingData, token, total) {
  return {
    intent: "CHARGE",
    amount: total,
    currencyCode: SquareConfig.currency,
    billingContact: billingData, // Use the prepared billing contact details
    token: token,
  };
}

function clearStoredTokens() {
  // Remove hidden token fields if they exist
  jQuery('input[name="square_payment_token"]').remove();
  jQuery('input[name="square_verification_token"]').remove();
}
