jQuery(function ($) {
  let bani_submit = false;
  $("#wc-bani-form").hide();
  $("body").block({
    message: null,
    overlayCSS: {
      background: "#fff",
      opacity: 0.6,
    },
    css: {
      cursor: "wait",
    },
  });

  /**
   * SECURITY: Validate Bani checkout URLs to prevent malicious redirects
   * This function monitors iframe creation and validates URLs before payment processing
   */
  function validateBaniCheckoutURL() {
    // Allowed Bani checkout URLs
    const allowedURLs = [
      "https://live-checkout.getbani.com/",
      "https://stage-checkout.getbani.com/",
    ];

    // Use MutationObserver to detect iframe creation
    const observer = new MutationObserver(function (mutations) {
      mutations.forEach(function (mutation) {
        mutation.addedNodes.forEach(function (node) {
          if (node.nodeName === "IFRAME" && node.getAttribute("title")?.includes("bani-frame")) {
            const iframeSrc = node.getAttribute("src");

            // Validate iframe URL
            const isValidURL = allowedURLs.some(function (url) {
              return iframeSrc && iframeSrc.indexOf(url) === 0;
            });

            if (!isValidURL) {
              // SECURITY VIOLATION DETECTED
              console.error("BANI SECURITY ALERT: Malicious payment redirect detected!");
              console.error("Blocked URL:", iframeSrc);
              console.error("Expected URLs:", allowedURLs);

              // Remove malicious iframe immediately
              if (node.parentNode) {
                node.parentNode.removeChild(node);
              }

              // Unblock UI
              $("body").unblock();
              $("#wc-bani-form").show();

              // Alert user
              alert(
                "SECURITY ALERT: A malicious payment redirect was detected and blocked.\n\n" +
                "Your payment has NOT been processed.\n\n" +
                "Please contact the site administrator immediately and report this incident.\n\n" +
                "DO NOT attempt to make payment until this issue is resolved."
              );

              // Send alert to server for logging
              if (typeof wc_bani_params !== "undefined") {
                $.ajax({
                  url: wc_bani_params.ajax_url || "/wp-admin/admin-ajax.php",
                  method: "POST",
                  data: {
                    action: "bani_report_security_violation",
                    blocked_url: iframeSrc,
                    expected_urls: allowedURLs.join(", "),
                    nonce: wc_bani_params.security_nonce,
                  },
                });
              }

              return false;
            }
          }
        });
      });
    });

    // Start observing DOM for iframe additions
    observer.observe(document.body, {
      childList: true,
      subtree: true,
    });
  }

  // Initialize URL validation
  validateBaniCheckoutURL();

  /**
   * SECURITY: Add postMessage validation to prevent amount manipulation
   * Monitor all postMessage events and validate signatures
   */
  function validatePostMessageSecurity() {
    const originalPostMessage = window.postMessage;
    let messageInterceptActive = false;

    // Intercept postMessage to validate payment data
    window.addEventListener("message", function (event) {
      // Only intercept messages related to Bani payment
      if (event.data && typeof event.data === "object" && event.data.checkoutReady) {
        // Validate origin for messages coming FROM iframe
        const allowedOrigins = [
          "https://live-checkout.getbani.com",
          "https://stage-checkout.getbani.com",
        ];

        // Check if message is from allowed origin
        if (event.origin && !allowedOrigins.includes(event.origin)) {
          console.error("BANI SECURITY ALERT: postMessage from unauthorized origin blocked!");
          console.error("Blocked origin:", event.origin);
          event.stopImmediatePropagation();
          return false;
        }
      }

      // Validate payment data integrity using signature
      if (event.data && typeof event.data === "object" && event.data.amount) {
        // Check if payment data has been tampered with
        if (typeof wc_bani_params !== "undefined" && wc_bani_params.amount) {
          const expectedAmount = parseInt(wc_bani_params.amount);
          const receivedAmount = parseInt(event.data.amount);

          if (receivedAmount !== expectedAmount) {
            console.error("BANI SECURITY ALERT: Payment amount mismatch detected!");
            console.error("Expected:", expectedAmount, "Received:", receivedAmount);

            // Alert user and block payment
            alert(
              "SECURITY ALERT: Payment amount mismatch detected.\n\n" +
              "Expected amount: " + (expectedAmount / 100) + "\n" +
              "Received amount: " + (receivedAmount / 100) + "\n\n" +
              "This payment has been blocked for your protection.\n" +
              "Please contact the site administrator immediately."
            );

            // Report to server
            if (wc_bani_params.ajax_url) {
              $.ajax({
                url: wc_bani_params.ajax_url || "/wp-admin/admin-ajax.php",
                method: "POST",
                data: {
                  action: "bani_report_amount_tampering",
                  expected_amount: expectedAmount,
                  received_amount: receivedAmount,
                  order_id: wc_bani_params.orderId,
                  signature: wc_bani_params.paymentSignature,
                },
              });
            }

            event.stopImmediatePropagation();
            return false;
          }
        }
      }
    }, true); // Use capture phase for priority

    // Validate signature before sending payment data
    if (typeof wc_bani_params !== "undefined" && wc_bani_params.paymentSignature) {
      console.log("BANI SECURITY: Payment signature validation active");
    }
  }

  // Initialize postMessage security
  validatePostMessageSecurity();

  wcPayWithBani();

  jQuery("#bani-payment-button").click(function () {
    return wcPayWithBani("ONCLICK");
  });

  jQuery("#bani_form form#order_review").submit(function () {
    return wcPayWithBani("ON SUBMIT");
  });
  function wcPayWithBani(msg) {
    $("body").unblock();

    if (bani_submit) {
      bani_submit = false;
      return true;
    }
    let $form = $("form#payment-form, form#order_review"),
      bani_txnref = $form.find("input.bani_txnref"),
      bani_txnstatus = $form.find("input.bani_txnstatus"),
      bani_txntype = $form.find("input.bani_txntype");
    bani_txnref.val("");
    bani_txnstatus.val("");
    bani_txntype.val("");
    let amount = Number(wc_bani_params.amount);
    amount = amount / 100;
    let resRef;
    let bani_callback = function (response) {
      resRef = response?.reference || "";
      let resStatus = response?.status || "";
      let resType = response?.type || "";
      let resExtRef = response?.external_ref || "";

      // SECURITY FIX: Use jQuery methods to safely set values and prevent XSS
      $("<input>")
        .attr("type", "hidden")
        .attr("class", "bani_txnref")
        .attr("name", "bani_txnref")
        .val(resRef)
        .appendTo($form);

      $("<input>")
        .attr("type", "hidden")
        .attr("class", "bani_txnstatus")
        .attr("name", "bani_txnstatus")
        .val(resStatus)
        .appendTo($form);

      $("<input>")
        .attr("type", "hidden")
        .attr("class", "bani_txntype")
        .attr("name", "bani_txntype")
        .val(resType)
        .appendTo($form);

      $("<input>")
        .attr("type", "hidden")
        .attr("class", "bani_txnextref")
        .attr("name", "bani_txnextref")
        .val(resExtRef)
        .appendTo($form);
      if (resRef) {
        bani_submit = true;
        $form.submit();

        $("body").block({
          message: null,
          overlayCSS: {
            background: "#fff",
            opacity: 0.6,
          },
          css: {
            cursor: "wait",
          },
        });
      } else {
        return false;
      }
    };

    let handler = baniPlugin.init({
      amount: amount,
      phoneNumber: wc_bani_params?.phoneNumber,
      merchantKey: wc_bani_params?.merchantKey,
      ref: wc_bani_params?.txnref,
      email: wc_bani_params?.email,
      firstName: wc_bani_params?.firstName,
      lastName: wc_bani_params?.lastName,
      showUserName: wc_bani_params?.showUserName,
      showUserAccountName: wc_bani_params?.showUserAccountName,
      onClose: (e) => {
        $("#wc-bani-form").show();
        $(this.el).unblock();
        bani_callback(e);
      },
      metadata: wc_bani_params?.metadata,
      callback: bani_callback,
    });
    handler;
    return false;
  }
});
