import type { KeyboardEvent } from "react";

function activate(items: readonly HTMLButtonElement[], index: number): void {
  const item = items[index];
  if (!item) return;
  item.focus();
  item.click();
}

export function handleTreeNavigation(
  event: KeyboardEvent<HTMLButtonElement>,
): void {
  const tree = event.currentTarget.closest('[role="tree"]');
  const items = tree
    ? Array.from(
        tree.querySelectorAll<HTMLButtonElement>('button[role="treeitem"]'),
      )
    : [];
  const index = items.indexOf(event.currentTarget);
  if (index < 0) return;

  let target = index;
  switch (event.key) {
    case "ArrowDown":
      target = Math.min(items.length - 1, index + 1);
      break;
    case "ArrowUp":
      target = Math.max(0, index - 1);
      break;
    case "Home":
      target = 0;
      break;
    case "End":
      target = items.length - 1;
      break;
    case "ArrowRight": {
      const currentLevel = Number(
        event.currentTarget.getAttribute("aria-level"),
      );
      const nextLevel = Number(items[index + 1]?.getAttribute("aria-level"));
      if (nextLevel === currentLevel + 1) target = index + 1;
      break;
    }
    case "ArrowLeft": {
      const currentLevel = Number(
        event.currentTarget.getAttribute("aria-level"),
      );
      for (let candidate = index - 1; candidate >= 0; candidate -= 1) {
        if (
          Number(items[candidate]?.getAttribute("aria-level")) ===
          currentLevel - 1
        ) {
          target = candidate;
          break;
        }
      }
      break;
    }
    default:
      return;
  }

  event.preventDefault();
  activate(items, target);
}
