import {GET} from '../modules/fetch.ts';
import {initStickySideMenuIndicators} from './common-page.ts';

function isPlainLeftClick(event: MouseEvent) {
  return event.button === 0 && !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey;
}

export function initRepoActionsSidebarNavigation() {
  const page = document.querySelector<HTMLElement>('.page-content.repository.actions');
  if (!page) return;

  let isUpdating = false;

  const updatePage = async (url: string, updateHistory: 'push' | 'replace' | 'none') => {
    if (isUpdating) return;

    const container = page.querySelector<HTMLElement>(':scope > .ui.container');
    const currentMenu = page.querySelector<HTMLElement>('#repo-actions-side-menu');
    if (!container) return;

    const menuScrollTop = currentMenu?.scrollTop ?? 0;
    isUpdating = true;
    document.documentElement.classList.add('restoring-repo-actions-menu-scroll');

    try {
      const response = await GET(url);
      if (!response.ok) {
        window.location.assign(url);
        return;
      }

      const html = await response.text();
      const doc = new DOMParser().parseFromString(html, 'text/html');
      const newPage = doc.querySelector<HTMLElement>('.page-content.repository.actions');
      const newContainer = newPage?.querySelector<HTMLElement>(':scope > .ui.container');
      if (!newPage || !newContainer) {
        window.location.assign(url);
        return;
      }

      container.innerHTML = newContainer.innerHTML;
      document.title = doc.title;
      initStickySideMenuIndicators(page);

      const restoredMenu = page.querySelector<HTMLElement>('#repo-actions-side-menu');
      if (restoredMenu) restoredMenu.scrollTop = menuScrollTop;

      if (updateHistory === 'push') window.history.pushState(null, '', url);
      if (updateHistory === 'replace') window.history.replaceState(null, '', url);
    } catch {
      window.location.assign(url);
    } finally {
      document.documentElement.classList.remove('restoring-repo-actions-menu-scroll');
      isUpdating = false;
    }
  };

  page.addEventListener('click', async (event) => {
    const target = event.target as HTMLElement;
    const link = target.closest<HTMLAnchorElement>('#repo-actions-side-menu a.item[href]');
    if (!link || !isPlainLeftClick(event)) return;
    if (link.target && link.target !== '_self') return;
    event.preventDefault();
    await updatePage(link.href, 'push');
  });

  window.addEventListener('popstate', async () => {
    if (!document.body.contains(page)) return;
    await updatePage(window.location.href, 'none');
  });
}
