let interval;
let isReplaced = false;

const replaceTargetForSidebarLinks = () => {
  const sidebarcsLinks = document.getElementsByClassName("menu__link");
  const tileLinks = document.getElementsByClassName("link-box");
  const allLinks = [...sidebarcsLinks, ...tileLinks];

  const isRuLocale = window.location.pathname.search(/\/ru\//) !== -1;

  if (allLinks.length === 0) {
    return;
  }

  for (const item of allLinks) {
    if (isRuLocale) {
      const itemHref = item.getAttribute("href");

      if (itemHref.search(window.location.origin) !== -1) {
        const url = new URL(itemHref);
        const [, projectName, ...rest] = url.pathname.split("/");
        const newLink = [
          url.origin,
          projectName,
          "ru",
          ...rest.filter((item) => item !== "ru"),
        ].join("/");
        item.setAttribute("href", newLink);
      }
    }

    item.setAttribute("target", "_self");
  }

  let isReplaced = true;
  for (const item of allLinks) {
    if (item.getAttribute("target", "_self") !== "_self") {
      isReplaced = false;
      break;
    }
  }

  return isReplaced;
};

window.onload = () => {
  if (isReplaced) {
    if (interval) {
      clearInterval(interval);
    }
  } else {
    interval = setInterval(() => {
      isReplaced = replaceTargetForSidebarLinks();
    }, [100]);
  }
};

window.onclose = () => {
  if (interval) {
    clearInterval(interval);
  }
};
