"use strict";

function setMenuItemUrls() {
  const items = document.querySelectorAll(".cl-language-switcher-link");
  if (!items.length) return;

  items.forEach(function (menuItem) {
    const encoded = menuItem.getAttribute("data-href-encoded");
    if (!encoded) return;
    const decodedUrl = atob(encoded);
    if (decodedUrl) menuItem.setAttribute("href", decodedUrl);
  });
}

function updateCurrentLanguageDisplay(hreflang) {
  if (!hreflang) return;
  hreflang = hreflang.toLowerCase();

  const menuItems = document.querySelectorAll(
    ".clonable-menu-item-language-switcher",
  );
  if (!menuItems.length) return;

  const normalizedHreflang = hreflang.replace(/_/g, "-");
  const primaryHreflang = normalizedHreflang.split("-")[0];

  menuItems.forEach(function (menuItem) {
    let submenu = menuItem.querySelector(".sub-menu");
    if (!submenu) {
      const firstLink = menuItem.querySelector("a");
      if (firstLink) {
        submenu = firstLink.nextElementSibling;
      }
    }
    if (!submenu) return;

    const links = submenu.querySelectorAll(".cl-language-switcher-menu-item a");

    let exactMatch = null;
    let subtagMatch = null;

    links.forEach(function (link) {
      const linkHreflang = (link.getAttribute("hreflang") || "").toLowerCase().replace(/_/g, "-");
      if (linkHreflang === normalizedHreflang) {
        exactMatch = link.innerHTML;
      } else if (linkHreflang.split("-")[0] === primaryHreflang) {
        subtagMatch = link.innerHTML;
      }
    });

    const matchedLinkHTML = exactMatch || subtagMatch;
    if (!matchedLinkHTML) return;

    // Update the top-level <a> content to reflect the current language
    const topLevelLink = menuItem.querySelector("a:not(.sub-menu a)");

    if (topLevelLink) {
      topLevelLink.innerHTML = matchedLinkHTML;
      // prevent default click behavior on the top-level link since it's not a real link
      topLevelLink.addEventListener("click", function (event) {
        event.preventDefault();
      });
    }
  });
}

function updateBlockMenuItemDisplay(hreflang) {
  if (!hreflang) return;
  hreflang = hreflang.toLowerCase();

  const menuItems = document.querySelectorAll(
    ".clonable-language-switcher-block-submenu-item",
  );
  if (!menuItems.length) return;

  menuItems.forEach(function (menuItem) {
    const submenu = menuItem.querySelector(
      ".clonable-language-switcher-block-submenu",
    );
    if (!submenu) return;

    const normalizedHreflang = hreflang.replace(/_/g, "-");
    const primaryHreflang = normalizedHreflang.split("-")[0];

    // Find the matching link by comparing hreflang case-insensitively
    const links = submenu.querySelectorAll(".cl-language-switcher-link");
    let exactMatch = null;
    let subtagMatch = null;
    links.forEach(function (link) {
      const linkHreflang = (link.getAttribute("hreflang") || "").toLowerCase().replace("_", "-");
      if (linkHreflang === normalizedHreflang) {
        exactMatch = link;
      } else if (linkHreflang.split("-")[0] === primaryHreflang) {
        subtagMatch = link;
      }
    });
    const matchedLink = exactMatch || subtagMatch;
    if (!matchedLink) return;

    const matchedHTML = matchedLink.innerHTML;
    if (!matchedHTML) return;

    // Update the top-level <a> content to reflect the current language
    const topLevelLink = menuItem.querySelector(
      ":scope > a.wp-block-navigation-item__content",
    );
    
    if (topLevelLink) {
      topLevelLink.innerHTML = matchedHTML;
    }
  });
}

function hoverMenuItemShortcodeMenu() {
  const shortcodeMenus = document.querySelectorAll(
    ".clonable-language-switcher-shortcode",
  );
  if (!shortcodeMenus.length) return;

  shortcodeMenus.forEach(function (menu) {
    const navlinks = menu.querySelector("#menu-navlinks");
    if (!navlinks) return;

    navlinks.addEventListener("mouseenter", function () {
      menu.classList.add("is-hovered");
    });
    navlinks.addEventListener("mouseleave", function () {
      menu.classList.remove("is-hovered");
    });

    // Prevent click on top-level links to avoid confusion as they are not real links
    menu
      .querySelectorAll(".clonable-language-switcher")
      .forEach(function (link) {
        link.addEventListener("click", function (event) {
          event.preventDefault();
        });
      });
  });
}

document.addEventListener("DOMContentLoaded", function () {
  const html = document.documentElement;
  let hreflang = (html.getAttribute("lang") || html.lang || "").trim();

  if (hreflang) {
    updateCurrentLanguageDisplay(hreflang);
    updateBlockMenuItemDisplay(hreflang);
  }

  setMenuItemUrls();
  hoverMenuItemShortcodeMenu();

  /* after initializing the menu, remove the data-loading attribute to show the menu items */
  document.querySelectorAll("[data-loading]").forEach((el) => {
    el.removeAttribute("data-loading");
  });
});
