/*****************************************************
 * credit-card.js (No-destroy, consistent reattach)
 *****************************************************/

window.squareCard = null; // We'll store the Square card instance globally

// Update this mapping if you need specific brand codes.
const cardTypeMapping = {
  visa: "VISA",
  mastercard: "MASTERCARD",
  amex: "AMERICAN_EXPRESS",
  discover: "DISCOVER",
  jcb: "JCB",
  diners: "DINERS_CLUB",
  union: "UNIONPAY",
};

/**
 * Initialize Credit Card Payment (attach the card fields if not already).
 *
 * Called by square-gateway.js after forcibly removing old .sq-card-wrapper.
 */
function initCreditCardPayment(payments, paymentRequest) {
  const container = document.getElementById("card-container");
  if (!container) {
    console.error("No #card-container found on the page.");
    return;
  }

  // If there's already an iframe in the container, skip creating another
  const existingIframe = container.querySelector(".sq-card-iframe-container iframe");
  if (existingIframe) {
    return;
  }

  payments
    .card()
    .then((cardInstance) => {
      window.squareCard = cardInstance;

      // The attach call is async; returns a promise once the field is mounted
      cardInstance.attach("#card-container");
    })
    .catch((e) => {
      console.error("Failed to initialize card:", e);
    });
}

/**
 * Process Credit Card Payment
 */
async function processCreditCardPayment(payments, creditCardPaymentRequest) {
  const savedPaymentToken = jQuery(
    'input[name="wc-squaresync_credit-payment-token"]:checked'
  ).val();
  if (savedPaymentToken && savedPaymentToken !== "new") {
    // Using a saved payment method, skip card processing
    return true;
  }

  if (!window.squareCard) {
    console.error("Card form not initialized (no 'window.squareCard' instance).");
    logPaymentError("Card form not initialized.");
    return false;
  }

  if (!creditCardPaymentRequest || !creditCardPaymentRequest.total) {
    console.error("Payment request object is missing or total is missing.");
    logPaymentError("Payment request object is not available.");
    return false;
  }

  try {
    jQuery("#payment-loader").show();

    // Tokenize with the global card instance
    const tokenResult = await window.squareCard.tokenize();

    if (tokenResult.status === "OK") {
      const token = tokenResult.token;
      const cardBrand = tokenResult.details.card.brand || "";

      // Convert accepted credit cards into the Square SDK card brands
      const acceptedBrands = (SquareConfig.availableCardTypes || []).map(
        (type) => cardTypeMapping[type]
      );

      // Check if the card brand is accepted
      if (!acceptedBrands.includes(cardBrand)) {
        logPaymentError("The card brand " + cardBrand + " is not accepted.");
        jQuery("#payment-loader").hide();
        return false;
      }

      // Attach the token to the form (or My Account form)
      if (SquareConfig.context === "account") {
        attachTokenToMyAccountForm(token);
      } else {
        attachTokenToForm(token);
      }

      // If we're just adding a card in My Account, no buyer verification needed
      if (SquareConfig.context === "account") {
        jQuery("#payment-loader").hide();
        return true;
      }

      // Otherwise, verify buyer
      const billingData = {
        familyName: jQuery("#billing_last_name").val() || "",
        givenName: jQuery("#billing_first_name").val() || "",
        email: jQuery("#billing_email").val() || "",
        phone: jQuery("#billing_phone").val() || "",
        country: jQuery("#billing_country").val() || "",
        region: jQuery("#billing_state").val() || "",
        city: jQuery("#billing_city").val() || "",
        postalCode: jQuery("#billing_postcode").val() || "",
        addressLines: [
          jQuery("#billing_address_1").val(),
          jQuery("#billing_address_2").val(),
        ].filter(Boolean),
      };

      const orderTotal = creditCardPaymentRequest.total.amount;
      const verificationDetails = buildVerificationDetails(
        billingData,
        token,
        orderTotal
      );

      const verificationResult = await payments.verifyBuyer(token, verificationDetails);

      if (verificationResult.token) {
        attachVerificationTokenToForm(verificationResult.token);
        jQuery("#payment-loader").hide();
        return true;
      } else {
        logPaymentError("Buyer verification failed.");
        jQuery("#payment-loader").hide();
        clearStoredTokens();
        return false;
      }
    } else {
      const errorMsg = tokenResult.errors
        ? tokenResult.errors.map((error) => error.message).join(", ")
        : "Unknown error";
      logPaymentError("Card tokenization failed: " + errorMsg);
      jQuery("#payment-loader").hide();
      clearStoredTokens();
      return false;
    }
  } catch (e) {
    logPaymentError("Tokenization or verification error: " + e.message);
    jQuery("#payment-loader").hide();
    clearStoredTokens();
    return false;
  }
}

