import { LisioBroadcastChannelController } from "../../controllers/broadcastChannel/lisio-broadcast-channel-controller";
import { ReaderObject } from "../../adapters/reader/lisio-reader-adapter";

interface MenuNode extends ReaderObject {
  children: MenuNode[];
}

/** One tier's fully-built `<ul>`, plus the ancestor link needed to step back and to render the breadcrumb — see `buildLevel()`. */
interface MenuLevel {
  label: string;
  ul: HTMLUListElement;
  parent?: MenuLevel;
}

/** Rebuilds the Tier 1 -> Tier 2 -> ... parent/child tree from the flat, `parent`-pointer payload — see `assignTiers()` in explore-hidden-helper.ts. */
function buildTree(hiddenTexts: ReaderObject[]): MenuNode[] {
  const byPosition = new Map<number, MenuNode>();
  for (const item of hiddenTexts) {
    if (item.tier == undefined) continue;
    byPosition.set(item.position, { ...item, children: [] });
  }

  const roots: MenuNode[] = [];
  for (const node of byPosition.values()) {
    if (node.tier === 1) {
      roots.push(node);
      continue;
    }
    const parentNode = node.parent == undefined ? undefined : byPosition.get(node.parent);
    if (parentNode != undefined) parentNode.children.push(node);
    else roots.push(node); // defensive: dangling parent reference
  }
  return roots;
}

/**
 * Menu links have no `data-lisio-clickable` index (they were never part of
 * `LisioReaderAdapter._all` — see explore-hidden-helper.ts — so there's
 * nothing on the SOURCE page's side for the usual
 * broadcastChannel/`dataLisioClickable` click-replay round-trip in
 * reading-mode.ts's `handleOnClick` to look up). Sends the destination
 * straight to the main page over the broadcast channel instead of reaching
 * into `window.opener` directly from the reader window — see
 * `sendNavigateMessage` (lisio-broadcast-channel-controller.ts).
 */
function renderItemContent(
  node: MenuNode,
  broadcastChannel: LisioBroadcastChannelController,
): HTMLElement {
  if (node.href != undefined) {
    const a = document.createElement("a");
    a.textContent = node.content || "";
    a.className = node.classes || "";
    a.dataset.href = node.href;
    a.addEventListener("click", (event) => {
      event.preventDefault();
      broadcastChannel.sendNavigateMessage({
        href: node.href as string,
        blank: node.blank === "true",
      });
    });
    return a;
  }
  const span = document.createElement("span");
  span.textContent = node.content || "";
  return span;
}

/**
 * Renders a fixed "Menu" button plus the full-screen drill-down overlay it
 * opens. Built on the SAME tiered hierarchy `collectHiddenLeaves()`
 * (explore-hidden-helper.ts) already computes — this is the "menu design"
 * pass: rather than dumping the whole tree as one long nested list, one
 * tier is shown at a time. An item with children gets a "Voir les
 * sous-menus" button, right below its own text in the same item container,
 * to drill into them; the header's breadcrumb ("Fil d'ariane") tracks the
 * path back to the root and lets the user jump back to any ancestor level
 * directly.
 *
 * The header's top-left button is contextual, mirroring standard
 * drill-down navigation: at the root (Tier 1) there's no "previous" level
 * to go back to, so it's hidden entirely — the top-right "Fermer" button
 * is the only closing action; one level in or deeper it appears, reading
 * "Menu précédent", and only pops back ONE tier, so drilling several
 * levels deep doesn't force the user to lose their place and start over.
 * The top-right "Fermer" button is the unconditional escape hatch — it
 * always closes the overlay outright, regardless of how deep the user has
 * drilled.
 *
 * Appended to `parent` (defaults to `document.body`) rather than reading
 * mode's `<main>`: the overlay is meant to overlap the ENTIRE reading-mode
 * screen (fixed positioning), not sit inside `main`'s normal content flow.
 *
 * Plain light-DOM content — not shadow DOM. Reading Mode runs its own full
 * Lisio widget instance (see `LisioReaderAdapter.adapt()`'s popup setup),
 * whose accessibility features (font size/line height/word spacing) only
 * ever scale elements reachable by walking `document.body`'s light DOM
 * (`LisioTextTreeWalker`); the menu's own text (button labels, breadcrumb,
 * links) is genuine content and needs that same scaling, same as anything
 * else Reading Mode renders — an EARLIER version isolated this menu inside
 * a shadow root to dodge a growing-button bug, which also opted it out of
 * that scaling entirely, an unwanted side effect.
 *
 * EVERY tier is built once, up front, right here — not one tier at a time
 * as the user drills in. `reading-mode.ts` only calls this again when the
 * payload's domain changes (see `menuOverlayDomain` there), not on every
 * in-reader navigation within the same site; in the
 * same spirit, the whole menu tree — every "Voir les sous-menus" level down
 * to its deepest leaf — is fully constructed as real HTML at that same
 * moment, each non-root tier's `<ul>` starting `hidden`. Drilling in/out
 * afterwards only ever toggles which `<ul>` is `hidden` (see `showLevel()`)
 * — no `<li>` is ever created, destroyed, or repopulated once the menu
 * exists. Two direct benefits over building each tier on demand: (1) every
 * item gets Lisio's accessibility scaling applied immediately, instead of a
 * fresh drill-in racing the (debounced) mutation-observer reapply for
 * content that didn't exist a moment ago; (2) it sidesteps an entire class
 * of DOM-churn bugs by construction, rather than by discipline — see below.
 *
 * The growing-button bug itself came from something narrower, back when
 * tiers WERE rebuilt on demand: `LisioMutationObserverController` watches
 * `document.body` and, debounced, reapplies accessibility scaling to
 * whatever it finds — and a PERSISTENT element whose own text is repeatedly
 * re-set in place (not recreated) apparently gets rescaled from its OWN
 * already-scaled state each time rather than from a stable original
 * baseline, compounding with every reapply. The old code did exactly that:
 * `backButton.textContent = "Menu précédent"` ran again on every single
 * click. Fixed by setting that label ONCE at creation (see below) and never
 * touching it again — `updateBackButton()` only ever toggles `.hidden` (an
 * attribute change, which this MutationObserver doesn't even watch — only
 * childList/subtree/characterData).
 */
export function renderMenuOverlay(
  hiddenTexts: ReaderObject[] | undefined,
  broadcastChannel: LisioBroadcastChannelController,
  parent: HTMLElement = document.body,
): void {
  // reading-mode.ts only calls this again when the payload's domain changes
  // (see `menuOverlayDomain` there) rather than on every in-reader
  // navigation, so the whole menu overlay's DOM — and the accessibility
  // rescale it triggers — isn't rebuilt on every same-site page change. This
  // removal step means a same-domain re-render (or any other/future caller,
  // including tests that call this function directly more than once against
  // the same `parent`) still replaces rather than stacks.
  parent.querySelectorAll(".lisio-menu-toggle, .lisio-menu-overlay").forEach((el) => el.remove());

  if (hiddenTexts == undefined || hiddenTexts.length === 0) return;
  const roots = buildTree(hiddenTexts);
  if (roots.length === 0) return;

  const toggleButton = document.createElement("button");
  toggleButton.type = "button";
  toggleButton.className = "lisio-menu-toggle";
  toggleButton.textContent = "Menu";

  const overlay = document.createElement("div");
  overlay.className = "lisio-menu-overlay";
  overlay.setAttribute("role", "dialog");
  overlay.setAttribute("aria-modal", "true");
  overlay.setAttribute("aria-label", "Menu");
  overlay.hidden = true;

  const header = document.createElement("header");
  header.className = "lisio-menu-header";

  const backButton = document.createElement("button");
  backButton.type = "button";
  backButton.className = "lisio-menu-back";
  // Set ONCE, here, and never touched again — see docstring above for why
  // repeatedly re-setting a persistent element's own text is exactly what
  // caused the growing-button bug. Only `.hidden` (an attribute, not text)
  // ever changes after this.
  backButton.textContent = "Menu précédent";

  const breadcrumb = document.createElement("nav");
  breadcrumb.className = "lisio-menu-breadcrumb";
  breadcrumb.setAttribute("aria-label", "Fil d'ariane");

  const closeButton = document.createElement("button");
  closeButton.type = "button";
  closeButton.className = "lisio-menu-close";
  closeButton.textContent = "Fermer";

  header.append(backButton, breadcrumb, closeButton);

  // Every tier's <ul> lives here, as a flat sibling list rather than nested
  // inside its parent's <li> — that's what lets a single `.hidden` flip
  // switch which tier is on screen without moving anything else.
  const levelsContainer = document.createElement("div");
  levelsContainer.className = "lisio-menu-levels";

  overlay.append(header, levelsContainer);

  /**
   * Builds this tier's <ul> AND (recursively) every descendant tier's <ul>
   * — the full subtree exists as real HTML the moment this returns, not
   * only once the user clicks down into it. See the "EVERY tier is built
   * once" section of the docstring above.
   */
  function buildLevel(label: string, items: MenuNode[], parentLevel: MenuLevel | undefined): MenuLevel {
    const ul = document.createElement("ul");
    ul.className = "lisio-menu-list";
    ul.hidden = true;
    const level: MenuLevel = { label, ul, parent: parentLevel };

    for (const node of items) {
      // renderItemContent() can only ever show a link (node.href) or plain
      // text (node.content) — a node with neither, and no children to drill
      // into either, has nothing it could possibly render (e.g. a captured
      // <img> leaf: its `src` is never read here, so empty-alt-text icons
      // would otherwise surface as a bare, useless `<li><span></span></li>`).
      if (!node.href && !node.content && node.children.length === 0) continue;

      const li = document.createElement("li");
      li.className = "lisio-menu-item";
      li.append(renderItemContent(node, broadcastChannel));
      if (node.children.length > 0) {
        const childLevel = buildLevel(node.content || "", node.children, level);
        const subMenuButton = document.createElement("button");
        subMenuButton.type = "button";
        subMenuButton.className = "lisio-menu-item-toggle";
        subMenuButton.textContent = "Voir les sous-menus";
        subMenuButton.addEventListener("click", () => showLevel(childLevel));
        li.append(subMenuButton);
      }
      ul.append(li);
    }

    levelsContainer.append(ul);
    return level;
  }

  const rootLevel = buildLevel("Menu", roots, undefined);
  let currentLevel = rootLevel;

  // Rebuilt on every navigation — cheap (one entry per tier of depth, not
  // per item) and, unlike the tiers themselves, inherently tied to
  // "current position", so there's nothing meaningful to pre-build here.
  function renderBreadcrumb(): void {
    breadcrumb.textContent = "";
    const chain: MenuLevel[] = [];
    for (let level: MenuLevel | undefined = currentLevel; level != undefined; level = level.parent) {
      chain.unshift(level);
    }
    chain.forEach((level, index) => {
      const isCurrent = index === chain.length - 1;
      if (isCurrent) {
        const current = document.createElement("span");
        current.className = "lisio-menu-breadcrumb-current";
        current.textContent = level.label;
        current.setAttribute("aria-current", "location");
        breadcrumb.append(current);
        return;
      }
      const link = document.createElement("button");
      link.type = "button";
      link.className = "lisio-menu-breadcrumb-link";
      link.textContent = level.label;
      link.addEventListener("click", () => showLevel(level));
      breadcrumb.append(link, document.createTextNode(" › "));
    });
  }

  // Top-left button is contextual: at the root there's nothing to step
  // back to, so it's hidden entirely; deeper in, it reappears to step back
  // one tier — see docstring above. Its label is set once at creation and
  // never touched here — only `.hidden` changes.
  function updateBackButton(): void {
    backButton.hidden = currentLevel.parent == undefined;
  }

  /** The only thing that changes when navigating: which pre-built `<ul>` is `.hidden`. */
  function showLevel(level: MenuLevel): void {
    currentLevel.ul.hidden = true;
    level.ul.hidden = false;
    currentLevel = level;
    renderBreadcrumb();
    updateBackButton();
  }

  function openMenu(): void {
    showLevel(rootLevel);
    overlay.hidden = false;
    closeButton.focus();
  }

  function closeMenu(): void {
    overlay.hidden = true;
    toggleButton.focus();
  }

  toggleButton.addEventListener("click", openMenu);
  // Only ever visible/clickable one level in or deeper — see
  // `updateBackButton()` — so it only needs to step back one tier.
  backButton.addEventListener("click", () => {
    if (currentLevel.parent != undefined) showLevel(currentLevel.parent);
  });
  closeButton.addEventListener("click", closeMenu);
  overlay.addEventListener("keydown", (event) => {
    if (event.key === "Escape") closeMenu();
  });

  parent.append(toggleButton, overlay);
}
