/* eslint-disable */
(function ($) {
  "use strict";

  $(document).ready(() => {
    const config = window.peachpayNMIConfig || {};

    // Only run in Collect.js mode
    if (!config.isCollectJs) {
      return;
    }

    const publicTokenizationKey =
      typeof config.publicTokenizationKey === "string"
        ? config.publicTokenizationKey.trim()
        : "";
    const hasValidKey = publicTokenizationKey.length >= 10;
    // State
    let isInitializing = false;
    let isConfigured = false;
    let initAttempts = 0;
    const MAX_INIT_ATTEMPTS = 3;

    // UI helpers
    function getElements() {
      return {
        container: document.getElementById("nmi-component-container"),
        loading: document.getElementById("nmi-loading"),
        error: document.getElementById("nmi-error-message"),
        tokenField: document.getElementById("nmi-payment-token"),
      };
    }

    function showLoading() {
      const els = getElements();
      if (els.loading) els.loading.style.display = "block";
      if (els.container) els.container.style.display = "none";
    }

    function hideLoading() {
      const els = getElements();
      if (els.loading) els.loading.style.display = "none";
      if (els.container) els.container.style.display = "block";
    }

    function showError(msg) {
      console.error("[NMI] showError:", msg);
      hideLoading();
      const els = getElements();
      if (els.error) {
        els.error.textContent = msg;
        els.error.style.display = "block";
      }
    }

    function hideError() {
      const els = getElements();
      if (els.error) els.error.style.display = "none";
    }

    function storeToken(token) {
      window.nmiPaymentToken = token;
      const els = getElements();
      if (els.tokenField) els.tokenField.value = token || "";
    }

    function hasIframes() {
      const els = getElements();
      if (!els.container) return false;
      const iframes = els.container.querySelectorAll("iframe");
      return iframes.length >= 3;
    }

    function createFieldsHTML() {
      return `
        <div class="nmi-field" style="margin-bottom:12px">
          <label style="display:block;margin-bottom:4px;font-weight:500">Card Number</label>
          <div id="ccnumber" style="min-height:44px;border:1px solid #ddd;border-radius:4px"></div>
        </div>
        <div style="display:flex;gap:12px">
          <div style="flex:1">
            <label style="display:block;margin-bottom:4px;font-weight:500">Expiry</label>
            <div id="ccexp" style="min-height:44px;border:1px solid #ddd;border-radius:4px"></div>
          </div>
          <div style="flex:1">
            <label style="display:block;margin-bottom:4px;font-weight:500">CVV</label>
            <div id="nmi-cvv" style="min-height:44px;border:1px solid #ddd;border-radius:4px"></div>
          </div>
        </div>
      `;
    }

    function configureCollectJS() {
      if (!window.CollectJS) {
        console.error("[NMI] CollectJS not available!");
        showError("Payment library not available. Please refresh.");
        return false;
      }

      try {
        // Configure WITHOUT paymentSelector - we handle submit manually
        window.CollectJS.configure({
          fields: {
            ccnumber: { selector: "#ccnumber", title: "Card Number" },
            ccexp: { selector: "#ccexp", title: "Expiration" },
            cvv: { selector: "#nmi-cvv", title: "CVV" },
          },
          customCss: {
            height: "44px",
            "min-height": "44px",
            "font-size": "16px",
            padding: "10px 12px",
            "box-sizing": "border-box",
            border: "none",
            "background-color": "transparent",
          },
          fieldsAvailableCallback: function () {
            isConfigured = true;
            hideLoading();
            hideError();
          },
          timeoutCallback: function () {
            console.error("[NMI] timeoutCallback - Collect.js timed out");
            showError("Payment form timed out. Please refresh.");
          },
          validationCallback: function (field, status, message) {
            if (status === "error" && message) {
              showError(message);
            }
          },
          callback: function (response) {
            if (response && response.token) {
              storeToken(response.token);
              hideError();
              
              // NOW submit the form - we have the token
              const $form = $("form.checkout");
              if ($form.length) {
                // Use WooCommerce's submit_checkout method if available
                if (typeof wc_checkout_form !== "undefined" && wc_checkout_form.submit_checkout) {
                  wc_checkout_form.submit_checkout();
                } else {
                  $form.submit();
                }
              }
            } else {
              const errorMsg = response?.error?.message || response?.errorMessage || "Card tokenization failed";
              console.error("[NMI] Tokenization error:", errorMsg);
              showError(errorMsg);
            }
          },
        });
        return true;
      } catch (err) {
        console.error("[NMI] CollectJS.configure() error:", err);
        showError("Failed to initialize payment form: " + err.message);
        return false;
      }
    }

    function waitForCollectJS(callback) {
      let attempts = 0;
      const maxAttempts = 30; // 6 seconds

      const timer = setInterval(() => {
        attempts++;

        if (window.CollectJS && typeof window.CollectJS.configure === "function") {
          clearInterval(timer);
          callback();
        } else if (attempts >= maxAttempts) {
          clearInterval(timer);
          console.error("[NMI] CollectJS library failed to load after", maxAttempts * 200, "ms");
          showError("Payment library not loaded. Please refresh the page.");
        }
      }, 200);
    }

    function mountCollectJS() {
      const els = getElements();
      if (!els.container) {
        console.error("[NMI] Container not found!");
        showError("Payment container not found.");
        return;
      }

      // Clear and create fields
      els.container.innerHTML = createFieldsHTML();
      els.container.style.display = "block";

      // Small delay to ensure DOM is ready
      setTimeout(() => {
        if (configureCollectJS()) {
          // Safety timeout - if fieldsAvailableCallback doesn't fire
          setTimeout(() => {
            if (!isConfigured && !hasIframes()) {
              console.warn("[NMI] Safety timeout - fields not loaded, hiding loading");
              hideLoading();
            }
          }, 5000);
        }
      }, 100);
    }

    function init() {
      // Prevent multiple parallel initializations
      if (isInitializing) {
        return;
      }

      // Check if already configured and iframes exist
      if (isConfigured && hasIframes()) {
        hideLoading();
        return;
      }

      // Limit attempts to prevent infinite loop
      if (initAttempts >= MAX_INIT_ATTEMPTS) {
        console.error("[NMI] Max init attempts reached");
        showError("Payment form failed to load. Please refresh.");
        return;
      }

      initAttempts++;
      isInitializing = true;
      isConfigured = false;
      showLoading();

      // Validate key
      if (!hasValidKey) {
        console.error("[NMI] No valid tokenization key");
        showError("Payment not configured. Please contact store administrator.");
        isInitializing = false;
        return;
      }

      // Wait for CollectJS then mount
      waitForCollectJS(() => {
        mountCollectJS();
        isInitializing = false;
      });
    }

    function reset() {
      isInitializing = false;
      isConfigured = false;
      initAttempts = 0;
      storeToken(null);
      hideError();
    }

    // =====================================================
    // EVENT HANDLERS
    // =====================================================

    // Form submission - handle tokenization manually
    $("form.checkout").on("checkout_place_order_peachpay_nmi_card", function (e) {
      if (!hasValidKey) {
        console.error("[NMI] No valid key, blocking");
        showError("Payment configuration error.");
        return false;
      }

      // If we already have a token, allow the submit
      if (window.nmiPaymentToken) {
        return true;
      }

      // No token yet - need to tokenize first
      // Check if CollectJS is ready
      if (!window.CollectJS || !isConfigured) {
        console.error("[NMI] CollectJS not ready");
        showError("Payment form not ready. Please wait and try again.");
        return false;
      }

      // Start tokenization - this will call the callback with the token
      // The callback will then submit the form
      try {
        window.CollectJS.startPaymentRequest();
      } catch (err) {
        console.error("[NMI] startPaymentRequest error:", err);
        showError("Failed to process card. Please try again.");
      }

      // Block this submit - we'll submit again after tokenization
      return false;
    });

    // Payment method change
    $(document).on("change", 'input[name="payment_method"]', function () {
      if (this.value === "peachpay_nmi_card") {
        reset();
        // Delay to let WooCommerce finish DOM updates
        setTimeout(init, 500);
      } else {
        reset();
        hideLoading();
      }
    });

    // WooCommerce updated_checkout event - this is critical!
    // WooCommerce replaces the payment method HTML, destroying Collect.js iframes
    $(document.body).on("updated_checkout", function () {
      const selectedMethod = $('input[name="payment_method"]:checked').val();

      if (selectedMethod !== "peachpay_nmi_card") {
        return;
      }

      // Check if iframes were destroyed
      setTimeout(() => {
        if (!hasIframes()) {
          reset();
          setTimeout(init, 300);
        } else {
          hideLoading();
        }
      }, 200);
    });

    // WooCommerce payment fragment refresh
    $(document.body).on("wc_fragments_refreshed wc_fragments_loaded", function () {});

    // =====================================================
    // INITIAL LOAD
    // =====================================================

    // Check if NMI is the selected payment method on page load
    const initialMethod = $('input[name="payment_method"]:checked').val();

    if (initialMethod === "peachpay_nmi_card") {
      // Wait for WooCommerce to finish its initial setup
      // Use a longer delay to wait for WooCommerce AJAX updates
      setTimeout(() => {
        init();
      }, 1000);
    }

    // Expose for debugging
    window.nmiDebug = {
      init,
      reset,
      hasIframes,
      getElements,
      state: () => ({ isInitializing, isConfigured, initAttempts }),
    };

  });
})(jQuery);
