//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 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);

  handleMenuItemClick = (e) => {
    // Check if the clicked item has a submenu (indicated by 'menu-item-has-children' class)
    if (e.currentTarget.classList.contains("menu-item-has-children")) {
      console.log(e.target.tagName);
      console.log(e.target.nextElementSibling);
      // Check if the clicked target is the 'a' tag itself, not its children
      if (e.target.tagName === "LI" && e.target.nextElementSibling) {
        e.preventDefault(); // Prevent default only if it's a submenu toggle
        e.stopPropagation(); // Stop event from bubbling up
        e.currentTarget.classList.toggle("show"); // Toggle submenu
      }
      if (e.target.tagName === "LI" && e.target.nextElementSibling == null) {
        e.currentTarget.classList.toggle("subshow"); // Toggle submenu
      }
    }
  };

  menuItems.forEach((menuItem) => {
    menuItem.addEventListener("click", handleMenuItemClick);
  });
}

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');

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

// 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) {
  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
  
  if(userID !== null){
    xhr.send("action=ftm_load_more_posts&offset=" + currentoffset + "&userID=" + userID);
  }else{
    xhr.send("action=ftm_load_more_posts&offset=" + currentoffset);
  }
}
