(function ($) {
  "use strict";

  // Wrap entire code inside foreach for each .dfs class element
  $(".dfs").each(function () {
    var $dfs = $(this);
    if ($dfs.find(".dfs_form").length) {
      $dfs.find(".dfs_form").validate();
    }

    var rawTemplate = $dfs.attr("data-template");

    var templateData = {};
    try {
      templateData = JSON.parse(rawTemplate);
    } catch (e) {
      console.error("Invalid JSON in data-template", e);
    }

    $dfs.find(".dfs_form").on("submit", function (e) {
      e.preventDefault();

      const $form = $(this);
      if (!$form.valid()) {
        return;
      }

      // Determine which form is being submitted
      let actionName = "dfs_form_submit";
      if ($form.hasClass("dfs_form_type_2")) {
        actionName = "dfs_transaction_form_submit";
      }

      function getBrowserName() {
        const userAgent = navigator.userAgent;

        if (userAgent.indexOf("Firefox") > -1) {
          return "Firefox";
        } else if (userAgent.indexOf("SamsungBrowser") > -1) {
          return "Samsung Internet";
        } else if (
          userAgent.indexOf("Opera") > -1 ||
          userAgent.indexOf("OPR") > -1
        ) {
          return "Opera";
        } else if (userAgent.indexOf("Edg") > -1) {
          return "Edge";
        } else if (userAgent.indexOf("Chrome") > -1) {
          return "Chrome";
        } else if (userAgent.indexOf("Safari") > -1) {
          return "Safari";
        } else {
          return "Unknown";
        }
      }

      let userData = {
        device: /Mobi|Android/i.test(navigator.userAgent)
          ? "Mobile"
          : "Desktop",
        browser: getBrowserName(), // function from earlier
        platform: navigator.platform,
        screen: screen.width + "x" + screen.height,
        language: navigator.language,
        vendor: navigator.vendor,
        url: window.location.href,
        referrer: document.referrer,
        ip: confirmation.ip,
      };

      const domainForSaleUserInfo = localStorage.getItem(
        "domain_for_sale_user_information"
      );
      const ipInfo = domainForSaleUserInfo
        ? JSON.parse(domainForSaleUserInfo)
        : {};
      const userInfo = { ...userData, ...ipInfo };

      var formData = $(this).serialize();
      var domain_name = templateData.domain_name;
      var sel_price = templateData.sel_price;
      var price_currency = templateData.price_currency;
      // check if "offer=" already exists
      if (!/(&|^)offer=/.test(formData)) {
        // insert before proposal if it exists
        if (/(&|^)proposal=/.test(formData)) {
          formData = formData.replace(
            /(&proposal=)/,
            "&offer=" + encodeURIComponent(sel_price) + "$1"
          );
        } else {
          // if proposal not found, just append at the end
          formData += "&offer=" + encodeURIComponent(sel_price);
        }
      }
      var formData =
        formData +
        "&domain=" +
        domain_name +
        "&price_currency=" +
        price_currency;

      $.ajax({
        url: confirmation.ajax_url,
        type: "post",
        data: {
          action: actionName,
          data: formData,
          userInfo,
          nonce: confirmation.nonce,
        },

        success: function (response) {
          if (response.type === "success") {
            Swal.fire({
              icon: "success",
              title: response.title,
              text: response.description,
              timer: 2000,
              showConfirmButton: false,
            }).then(function () {
              $form.trigger("reset");
            });
          } else {
            Swal.fire({
              icon: "error",
              title: response.title,
              text: `${response.title}\n${response.description}`,
              confirmButtonText: `${response.okay}`,
            });
          }
        },
        error: function (jqXHR, textStatus, errorThrown) {
          Swal.fire({
            icon: "error",
            title: "Error",
            text: errorThrown,
            confirmButtonText: "OK",
          });
        },
      });
    });
  });

  document.addEventListener("DOMContentLoaded", function () {
    const msg = document.querySelector(".dfs-verify-msg");
    if (msg) {
      setTimeout(() => {
        msg.style.transition = "opacity 0.6s ease";
        msg.style.opacity = "0";
        setTimeout(() => msg.remove(), 600); // fully remove after fade
      }, 3000); // 10000ms = 10 seconds
    }
  });
})(jQuery);

/******************** USER INFORMATION ********************/
async function userInformation() {
  const url = "https://ipwhois.app/json/";
  try {
    const response = await fetch(url);
    const result = await response.json();
    localStorage.setItem(
      "domain_for_sale_user_information",
      JSON.stringify(result)
    );
  } catch (error) {
    console.error(error.message);
  }
}
userInformation();
