//console.log('global init');
var loading = false;
let is_mobile = false;

// Define event handlers
let handleMenuTriggerClick;
let handleMenuItemClick;

function checkScreenWidth() {
  if (window.innerWidth <= 1024) {
    if (!is_mobile) {
      is_mobile = true;
      setupMobileMenu();
    }
  } else {
    if (is_mobile) {
      is_mobile = false;
      teardownMobileMenu();
    }
  }
}

function setupMobileMenu() {
  const menuItems = document.querySelectorAll(".menu-item-has-children");
  const menuTrigger = document.getElementById("ftm-mobile-menu-trigger");
  const siteNavigation = document.getElementById("site-navigation");
  //const menuItems = document.querySelectorAll(
  //  "li.menu-item.menu-item-has-children"
  //);

  handleMenuTriggerClick = () => {
    siteNavigation.classList.toggle("show");
    menuTrigger.classList.toggle("show");
  };

  menuTrigger.addEventListener("click", handleMenuTriggerClick);

  menuItems.forEach(item => {
      item.addEventListener("click", function (e) {
          // Prevent event from affecting nested links
          if (e.target.tagName === "A") return;

          e.preventDefault(); // Prevent unintended behaviors

          // Toggle "show" class for top-level menu items
          this.classList.toggle("show");
      });

      // Handle second-level submenu clicks without affecting the parent
      const subMenuItems = item.querySelectorAll(".menu-item-has-children");
      subMenuItems.forEach(subItem => {
          subItem.addEventListener("click", function (e) {
              if (e.target.tagName === "A") return;

              e.preventDefault();
              e.stopPropagation(); // Prevent the click from bubbling up to parent elements

              this.classList.toggle("subshow");
          });
      });
  });
}

function teardownMobileMenu() {
  const menuTrigger = document.getElementById("ftm-mobile-menu-trigger");
  if (menuTrigger) {
    menuTrigger.removeEventListener("click", handleMenuTriggerClick);
  }

  const menuItems = document.querySelectorAll(
    "li.menu-item.menu-item-has-children"
  );
  menuItems.forEach((menuItem) => {
    menuItem.removeEventListener("click", handleMenuItemClick);
  });
}

window.addEventListener("DOMContentLoaded", function () {
  checkScreenWidth();
  window.addEventListener("resize", checkScreenWidth);

  try {
    MicroModal.init({
      awaitCloseAnimation: true,
      disableScroll: true,
      onClose: function (modal) {
        const selectedValue = getSelectedValue();
        setCookie("currState", selectedValue);

        // Reload the page after setting the cookie
        location.reload();
      },
    });
  } catch (e) {
    console.log("micromodal error: ", e);
  }

  try {
    const swiper = new Swiper(".swiper", {
      // Optional parameters
      direction: "horizontal",
      loop: true,

      // Navigation arrows
      navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev",
      },
    });
  } catch (e) {
    console.log("Swiper init error: ", e);
  }

  // Check if an element with the class "ftm_load_more" exists
  var ftmloadMoreElement = document.querySelector(".ftm_load_more");

  if (ftmloadMoreElement !== null) {
    var userId = ftmloadMoreElement.getAttribute('data-user-id');
    var postType = ftmloadMoreElement.getAttribute('data-post-type');

    if (userId !== null) {
      // Check if the user has scrolled to the footer
      window.addEventListener("scroll", function (userID, postType) {
        if (
            window.innerHeight + window.scrollY >=
            document.body.offsetHeight - 500
        ) {
            loadMorePosts(userID, postType);
        }
      }.bind(null, userId, postType));
    } else {
      // Check if the user has scrolled to the footer
      window.addEventListener("scroll", function (postType) {
        if (
          window.innerHeight + window.scrollY >=
          document.body.offsetHeight - 500
        ) {
          loadMorePosts(null, postType);
        }
      }.bind(null, postType));
    }   
  }
});

// Function to set the cookie
function setCookie(name, value) {
  document.cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
}

// Function to get the selected value of the select element
function getSelectedValue() {
  const selectElement = document.getElementById("ftm-header__state");
  return selectElement.value;
}

// Function to load more posts via AJAX
function loadMorePosts(userID = null, postType = null) {
  if (loading) return;
  loading = true;

  var xhr = new XMLHttpRequest();
  xhr.open("POST", pw_script_vars.ajaxurl, true);
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xhr.onreadystatechange = function () {
    var loadMoreLogo = document.querySelector(".ftm_load_more");
    loadMoreLogo.classList.add("active");

    if (xhr.readyState === 4 && xhr.status === 200) {
      var response = xhr.responseText;
      var postContainer = document.getElementById("latest_post_wrapper");
      var currentoffset = document.getElementById("latest_posts_offset");
      var offset = Number(currentoffset.value);

      if (response !== "no-more-posts") {
        // Append the new posts to your container
        postContainer.insertAdjacentHTML("beforeend", response);

        // Increment the offset for the next request
        offset += 9; // Change to match the posts_per_page value
        currentoffset.value = offset;
      } else {
        // No more posts to load
        $no_more_control = document.getElementById("no-more-posts");
        if (!$no_more_control) {
          postContainer.insertAdjacentHTML(
            "beforeend",
            '<div id="no-more-posts">-- No More Posts to Load --</div>'
          );
        }
      }

      loading = false;
    }

    loadMoreLogo.classList.remove("active");
  };

  var currentoffset = Number(
    document.getElementById("latest_posts_offset").value
  );
  currentoffset += 9; // Change to match the posts_per_page value
  
  var params = "action=ftm_load_more_posts&offset=" + currentoffset;
  if (userID !== null) {
    params += "&userID=" + userID;
  }
  if (postType !== null) {
    params += "&postType=" + postType;
  }
  xhr.send(params);
}
