import { NAV_RE } from "../structure/classify-block";
import { ReaderObject } from "../lisio-reader-adapter";

const SKIPPED_TAGS = new Set(["script", "noscript", "style", "template"]);
// Lisio's own injected UI (widget popin, disable band, translation label,
// shadow-root host, ...) is deliberately excluded — it's not part of the
// SOURCE page's content and can legitimately be hidden/toggled by Lisio
// itself, which has nothing to do with what this pass is for.
const LISIO_OWN_UI_SELECTOR =
  "#lisio-label, #lisio-disable-band, #lisio-popin, #lisio-shadow-env";
// Elements worth their own record regardless of whether they wrap further
// markup (a link may wrap a <span> icon; an image never has meaningful
// "own text" to fall back on) — mirrors the tag families the normal visible
// leaf pipeline treats as atomic content, not structural wrapping.
const MEDIA_LEAF_SELECTOR = "a[href], img, svg, video, button, input, select, textarea";

// Icon fonts (dropdown chevrons, decorative glyphs, ...) render a single
// character from the Unicode Private Use Area — real, non-whitespace
// `textContent`, so it isn't blank to any of the checks below, yet it has no
// glyph in Reading Mode's own accessible font and renders as nothing. Left
// in, an icon-only leaf reads as non-empty (skipping every "no real content"
// check) and surfaces as a useless blank `<li><span></span></li>`; stripped
// here, it collapses to the empty string it visually already is.
const PRIVATE_USE_RE = /[-\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/gu;

function collapseWhitespace(text: string): string {
  return text.replace(PRIVATE_USE_RE, "").replace(/\s+/gu, " ").trim();
}

/**
 * `el.textContent` walks script/style/template content too (skipping those
 * tags only stops the outer TreeWalker from visiting them AS records — it
 * doesn't stop them from leaking into an ancestor's `.textContent`). Strip
 * them from a clone rather than reusing the shared `cloneReadableElement`
 * (lisio-readable-dom.ts): that helper strips based on `isUnreadableElement`
 * too, which — since `visibility` is inherited — would zero out nearly
 * every descendant of an already-hidden container, defeating the point of
 * this pass.
 */
function extractText(el: HTMLElement | SVGElement): string {
  const clone = el.cloneNode(true) as HTMLElement | SVGElement;
  for (const child of Array.from(clone.querySelectorAll(Array.from(SKIPPED_TAGS).join(",")))) {
    child.remove();
  }
  return collapseWhitespace(clone.textContent || "");
}

/**
 * Deliberately NOT the shared `isUnreadableElement()` (lisio-readable-dom.ts):
 * that helper mixes two different notions of "hidden" — genuine CSS/visual
 * hiding (`display:none`, `visibility:hidden`, `opacity:0`, the `hidden`
 * attribute — content a sighted user genuinely cannot see) and
 * ASSISTIVE-TECH-only hiding (`aria-hidden="true"`, `sr-only`-style classes
 * — content that's often still perfectly VISIBLE on screen, just hidden
 * from screen readers, e.g. a decorative chevron/sprite icon next to a
 * dropdown label — or, for `sr-only` text, the OPPOSITE: already
 * accessible to screen readers, nothing to "reveal"). That distinction is
 * irrelevant for `isUnreadableElement()`'s own use case (should this be
 * read aloud/translated?), but it matters a great deal here: this pass
 * exists to find content sighted users can't currently SEE. Reusing it
 * wholesale meant an entirely VISIBLE menu's own decorative `aria-hidden`
 * icons (extremely common real-world markup) were miscounted as "hidden"
 * and could crowd out the real button/link sitting right next to them —
 * see the regression test built from the real https://lisio.fr/
 * `#skip-target-menu` markup.
 */
function isVisuallyHidden(element: HTMLElement | SVGElement): boolean {
  if (element instanceof HTMLElement && element.hidden) return true;
  const styles = window.getComputedStyle(element);
  return (
    styles.display === "none" ||
    styles.visibility === "hidden" ||
    Number.parseFloat(styles.opacity || "1") === 0
  );
}

/**
 * `visibility` is an inherited CSS property (a hidden container's
 * descendants report hidden too, with no extra check needed), but
 * `display`, `opacity` and the `hidden` attribute are NOT — a descendant of
 * a `display: none`/`opacity: 0` container computes its own default style
 * and would otherwise look perfectly readable on its own. Walk up to
 * `root` explicitly so every hiding mechanism is caught regardless of
 * which one the source page actually used.
 */
function isHiddenHere(el: HTMLElement | SVGElement, root: HTMLElement): boolean {
  let cur: Element | null = el;
  while (cur != undefined) {
    if (
      (cur instanceof HTMLElement || cur instanceof SVGElement) &&
      isVisuallyHidden(cur)
    ) {
      return true;
    }
    if (cur === root) break;
    cur = cur.parentElement;
  }
  return false;
}

function idClassOf(el: Element): string {
  return `${el.id} ${typeof el.className === "string" ? el.className : ""}`
    .trim()
    .toLowerCase();
}

function isNavShaped(el: Element): boolean {
  return (
    el.localName === "nav" ||
    el.getAttribute("role") === "navigation" ||
    NAV_RE.test(idClassOf(el))
  );
}

function isListItem(el: Element): boolean {
  return el.localName === "li" || el.getAttribute("role") === "listitem";
}

/**
 * Nav-shaped ancestor chains are frequently repeated at every wrapper level
 * on real sites (BEM naming like `.menu > .menu__wrapper > ...` re-matches
 * `NAV_RE` at each level — see segment-page.ts's nested-nav-in-nav fix for
 * the same phenomenon on VISIBLE content). Keep walking past the first
 * match so `found` ends up as the OUTERMOST nav-shaped ancestor: treat the
 * whole nested chain as ONE menu, not several.
 */
function findNavRoot(el: Element, root: HTMLElement): Element | undefined {
  let found: Element | undefined;
  let cur: Element | null = el;
  while (cur != undefined) {
    if (isNavShaped(cur)) found = cur;
    if (cur === root) break;
    cur = cur.parentElement;
  }
  return found;
}

/** Ordered closest-to-farthest list of `<li>`/`role="listitem"` ancestors between `el` and `stopAt` (exclusive of both). */
function listItemChain(el: Element, stopAt: Element): Element[] {
  const chain: Element[] = [];
  let cur: Element | null = el.parentElement;
  while (cur != undefined && cur !== stopAt) {
    if (isListItem(cur)) chain.push(cur);
    cur = cur.parentElement;
  }
  return chain;
}

/**
 * The visible DISCLOSURE control for a dropdown whose PANEL is hidden but
 * whose toggle isn't — real markup (lisio.fr's own mega-menu: a `<button
 * aria-expanded aria-controls="submenu-solutions">` sitting right next to
 * a `visibility:hidden;opacity:0` panel) very often keeps the label
 * genuinely visible and only hides the content it discloses. That toggle is
 * therefore never itself `isHiddenHere()` and never captured by the main
 * walk above, so it can't serve as a Tier-1 anchor through
 * `leafByOwnListItem` the way a fully-hidden off-canvas menu's own label
 * would (see the `#skip-target-menu` regression test, where the WHOLE nav —
 * label included — is `display:none`). Without this fallback every child of
 * every such dropdown comes back unparented at Tier 1, and the dropdown's
 * own label (e.g. "Solutions") never appears in the menu at all — exactly
 * the shape a two-hop CSS-hidden-panel-only menu produces. Only consulted
 * as a fallback, when no other captured (hidden) leaf owns `li` — see
 * `parentFor()` in `assignTiers()`.
 */
function findVisibleToggleLabel(
  li: Element,
  root: HTMLElement,
): { name: string; content: string; href?: string; classes?: string; blank?: string } | undefined {
  const walker = document.createTreeWalker(li, NodeFilter.SHOW_ELEMENT);
  let node = walker.nextNode() as Element | null;
  while (node != undefined) {
    if (
      (node instanceof HTMLElement || node instanceof SVGElement) &&
      !isHiddenHere(node, root)
    ) {
      const isMediaLeaf = node.matches(MEDIA_LEAF_SELECTOR);
      const isTextLeaf = node.children.length === 0;
      if (isMediaLeaf || isTextLeaf) {
        const text = extractText(node);
        // The visible label is often a real link in its own right (a
        // responsive nav's item link, as opposed to lisio.fr's own
        // mega-menu toggle which is a plain non-navigating <button>) —
        // carry its href/classes/target through so the synthesized parent
        // item `parentFor()` builds from this stays clickable instead of
        // silently downgrading to inert text.
        if (text !== "") {
          return {
            name: node.localName,
            content: text,
            href: node instanceof HTMLAnchorElement ? node.href : undefined,
            classes: typeof node.className === "string" ? node.className : undefined,
            blank: node instanceof HTMLAnchorElement ? `${node.target === "_blank"}` : undefined,
          };
        }
      }
    }
    node = walker.nextNode() as Element | null;
  }
  return undefined;
}

/**
 * Groups leaves captured under the same hidden nav root into tiers, using
 * actual parent/child LINKS rather than raw `<li>`-nesting depth. An
 * earlier version derived tier purely from `chain.length` (normalised to
 * the shallowest depth found) — that breaks as soon as one branch of the
 * SAME menu wraps its items one `<li>` deeper than another, which real
 * markup does: e.g. a two-column submenu that groups its links under an
 * extra `<li>` per column, purely for layout, while the menu's other
 * dropdowns don't (see the regression test built from the real
 * https://lisio.fr/ `#skip-target-menu` markup — its "À propos" dropdown
 * does exactly this). Depth-based tiering pushed that branch's items one
 * tier too deep AND broke their parent link entirely (nothing "owns" the
 * purely-structural grouping `<li>` in between), leaving them stranded as
 * dangling-parent root items instead of nested under their real dropdown.
 *
 * Instead: walk each leaf's own `<li>` ancestor chain (closest to
 * farthest) and take the FIRST ancestor that is itself some OTHER
 * captured leaf's own nearest `<li>` — that leaf is the real parent,
 * however many purely-structural wrapper `<li>`s sit in between. Tier
 * then simply follows the parent chain (`parent's tier + 1`), so those
 * wrapper levels never inflate the tier count either.
 *
 * Leaves with NO list-item ancestor at all (chain length 0) are left
 * untiered: on a real page these are typically promotional content sitting
 * alongside the actual menu (e.g. accelerator/teaser cards), not part of
 * its list-shaped hierarchy — forcing them into Tier 1 would misrepresent
 * them as menu items.
 *
 * Returns synthetic `ReaderObject`s created for visible-toggle labels (see
 * `findVisibleToggleLabel()`) — these were never part of `leaves` (they
 * were never hidden, so the main capture walk never saw them), so the
 * caller must fold them into its own returned array for their `position`s
 * to resolve on the reader side (`menu-overlay.ts`'s `buildTree()`).
 */
function assignTiers(
  leaves: { obj: ReaderObject; el: HTMLElement | SVGElement }[],
  root: HTMLElement,
): ReaderObject[] {
  const byNavRoot = new Map<Element, { obj: ReaderObject; el: HTMLElement | SVGElement; chain: Element[] }[]>();
  for (const leaf of leaves) {
    const navRoot = findNavRoot(leaf.el, root);
    if (navRoot == undefined) continue;
    const chain = listItemChain(leaf.el, navRoot);
    if (chain.length === 0) continue; // not part of the list hierarchy — see docstring
    const group = byNavRoot.get(navRoot) ?? [];
    group.push({ ...leaf, chain });
    byNavRoot.set(navRoot, group);
  }

  const synthesized: ReaderObject[] = [];
  let nextPosition = leaves.length;

  for (const [navRoot, group] of byNavRoot.entries()) {
    // Multiple captured leaves can share the exact same nearest-enclosing
    // <li> — real menus sometimes repeat a parent item's own link a second
    // time inside its own submenu panel (e.g. a "back to this page"
    // heading link, a sibling of the child <ul>, not a descendant of the
    // real item link — so it isn't caught by any dedup at capture time),
    // or an item's own decorative icon (aria-hidden, matched separately as
    // its own candidate leaf) sits under the same <li>. Only the FIRST
    // such leaf (document order) becomes that <li>'s tiered menu entry;
    // later ones sharing the same <li> are left untiered rather than
    // appearing as a confusing duplicate sibling at the same tier.
    const leafByOwnListItem = new Map<Element, ReaderObject>();
    const isCanonical = new Set<ReaderObject>();
    for (const g of group) {
      if (leafByOwnListItem.has(g.chain[0])) continue;
      // The <li> can ALSO hold a genuinely visible sibling label — e.g. a
      // real "Actualités" nav link sitting right next to a "+"
      // dropdown-disclosure toggle that only happens to be `display:none`
      // at the page's current breakpoint (a common responsive-nav pattern:
      // toggle and label are separate elements, and CSS can hide either one
      // depending on viewport width — handilab.com's own nav does exactly
      // this, hiding the "+" toggle only above ~960px). That visible text
      // is the item's real name; leave this <li> unclaimed here so
      // `parentFor()`'s `findVisibleToggleLabel()` fallback builds the
      // label from it instead of this hidden leaf's own (often decorative
      // or purely functional, e.g. "+") text.
      if (findVisibleToggleLabel(g.chain[0], root) != undefined) continue;
      leafByOwnListItem.set(g.chain[0], g.obj);
      isCanonical.add(g.obj);
    }

    const parentOf = new Map<ReaderObject, ReaderObject>();
    const syntheticByLi = new Map<Element, ReaderObject>();

    /**
     * The parent anchor for ancestor `<li>` `li`, or `undefined` if `li` is
     * purely structural. Checks real captured leaves first (a hidden
     * off-canvas menu's own label — see `#skip-target-menu`), then falls
     * back to synthesizing one from a visible toggle (lisio.fr's mega-menu
     * — see `findVisibleToggleLabel()`), memoized per `li` so every child
     * of the same dropdown shares ONE synthetic label rather than one each.
     * Recurses into `li`'s OWN ancestor chain so a synthetic label can
     * itself nest under a higher one, exactly like a real captured leaf can.
     */
    function parentFor(li: Element): ReaderObject | undefined {
      const existing = leafByOwnListItem.get(li);
      if (existing != undefined) return existing;
      const already = syntheticByLi.get(li);
      if (already != undefined) return already;

      const label = findVisibleToggleLabel(li, root);
      if (label == undefined) return undefined;

      const synthetic: ReaderObject = {
        position: nextPosition++,
        name: label.name,
        content: label.content,
        href: label.href,
        classes: label.classes,
        blank: label.blank,
      };
      syntheticByLi.set(li, synthetic); // set before recursing: guards a pathological self-referential chain
      synthesized.push(synthetic);

      for (const ancestorLi of listItemChain(li, navRoot)) {
        const higherParent = parentFor(ancestorLi);
        if (higherParent != undefined) {
          parentOf.set(synthetic, higherParent);
          break;
        }
      }
      return synthetic;
    }

    // Parent linkage: the first ancestor <li> (from closest to farthest,
    // excluding the leaf's own) that resolves to a parent anchor — see
    // `parentFor()` for why this skips purely structural wrapper <li>s
    // instead of assuming the very next one up is always the parent.
    for (const g of group) {
      if (!isCanonical.has(g.obj)) continue;
      for (let i = 1; i < g.chain.length; i++) {
        const candidate = parentFor(g.chain[i]);
        if (candidate != undefined && candidate !== g.obj) {
          parentOf.set(g.obj, candidate);
          break;
        }
      }
    }

    function resolveTier(obj: ReaderObject, visiting: Set<ReaderObject>): number {
      const parent = parentOf.get(obj);
      if (parent == undefined || visiting.has(obj)) return 1; // root, or defensive cycle guard
      visiting.add(obj);
      return resolveTier(parent, visiting) + 1;
    }

    for (const g of group) {
      if (!isCanonical.has(g.obj)) continue; // redundant duplicate — see above
      g.obj.tier = resolveTier(g.obj, new Set());
      const parent = parentOf.get(g.obj);
      if (parent != undefined) g.obj.parent = parent.position;
    }
    for (const synthetic of syntheticByLi.values()) {
      synthetic.tier = resolveTier(synthetic, new Set());
      const parent = parentOf.get(synthetic);
      if (parent != undefined) synthetic.parent = parent.position;
    }
  }

  return synthesized;
}

/**
 * Reading Mode only, plumbing-only capture of hidden content.
 *
 * The shared `isUnreadableElement()`/`getReadableText()` pipeline
 * (lisio-readable-dom.ts) deliberately ERASES hidden content for every
 * other Lisio feature (translation, speech synthesis, the main text-tree
 * walker, ...) — left untouched here on purpose (product decision: Reading
 * Mode only, plumbing only — no other feature should start seeing hidden
 * text, and nothing renders this yet either). This is instead a SEPARATE,
 * read-only, additional pass, used only by Reading Mode, that records
 * hidden elements (off-canvas menus, closed modals/search overlays, ...)
 * instead of silently dropping them, each flagged `isHidden: true`.
 * render-leaf.ts still only renders the position-ordered `texts` payload;
 * this is data for a future "reveal hidden content" feature to consume.
 *
 * One record per meaningful LEAF, not one blob per hidden container: an
 * off-canvas menu is exactly the case this exists for, and a menu is only
 * useful later if each link keeps its own `href` — collapsing a whole
 * hidden subtree into one record's concatenated text would throw that
 * away. A candidate only gets skipped as "purely structural" (an
 * un-recorded `<div>`/`<ul>`/`<li>` wrapper) when it has element children
 * AND isn't itself a link/media/form control — its content is then covered
 * by its own children's records instead.
 *
 * Leaves found inside a nav-shaped hidden ancestor (`<nav>`, `role`,
 * `NAV_RE` idClass — same heuristic classify-block.ts's `nav` rule uses)
 * additionally get `tier`/`parent` set — see `assignTiers()`.
 *
 * Elements matched by the page's "background image" selector set
 * (`allBackgroundImageTags` — see `getSelectors()` in
 * `lisio-reader-adapter.ts`) are excluded on request: those are CSS
 * background-image carriers, not something a user would want to reveal as
 * text/menu content.
 */
export function collectHiddenLeaves(
  root: HTMLElement,
  backgroundImageTags: ReadonlySet<Element>,
): ReaderObject[] {
  const captured: { obj: ReaderObject; el: HTMLElement | SVGElement }[] = [];
  const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
  let node = walker.nextNode() as (HTMLElement | SVGElement) | null;

  while (node != undefined) {
    const el = node;
    node = walker.nextNode() as (HTMLElement | SVGElement) | null;

    if (SKIPPED_TAGS.has(el.localName)) continue;
    if (backgroundImageTags.has(el)) continue;
    if (el.closest(LISIO_OWN_UI_SELECTOR) != undefined) continue;

    const isMediaLeaf = el instanceof Element && el.matches(MEDIA_LEAF_SELECTOR);
    const isTextLeaf = el.children.length === 0;
    if (!isMediaLeaf && !isTextLeaf) continue; // structural wrapper — its children speak for themselves

    if (!isHiddenHere(el, root)) continue;

    const text = extractText(el);
    const href = el instanceof HTMLAnchorElement ? el.href : undefined;
    const src = el instanceof HTMLImageElement ? el.src : undefined;
    // A media leaf with no text is only worth a record if it carries some
    // OTHER identifying value (a link's destination, an image's source) —
    // a decorative icon-only <svg>/<button> (dropdown toggle chevrons,
    // empty icon buttons, ...) has none of the three and would otherwise
    // surface as a blank, meaningless `<li><span></span></li>` menu entry.
    if (text === "" && href == undefined && src == undefined) continue;

    captured.push({
      el,
      obj: {
        name: el.localName,
        classes: typeof el.className === "string" ? el.className : "",
        content: text,
        href,
        blank: el instanceof HTMLAnchorElement ? `${el.target === "_blank"}` : undefined,
        src,
        isHidden: true,
        position: captured.length,
      },
    });
  }

  // Synthetic entries for visible dropdown TOGGLES whose panel is hidden but
  // whose own label isn't (lisio.fr's mega-menu — see
  // `findVisibleToggleLabel()`): never themselves hidden, so the walk above
  // never captures them, yet the real (hidden) items still need to nest
  // under something in the reader's menu tree — see `assignTiers()`.
  const synthesized = assignTiers(captured, root);

  return captured.map((c) => c.obj).concat(synthesized);
}
