/**
 * @jest-environment jsdom
 */
import { collectHiddenLeaves } from "../../../src/adapters/reader/helpers/explore-hidden-helper";

describe("collectHiddenLeaves", () => {
  it("captures a link nested several levels inside a hidden off-canvas menu, with its own href", () => {
    // Real shape from https://www.albi-tourisme.fr/'s .menu panel
    // (visibility: hidden; opacity: 0; ...): a link buried under
    // ul > li > a, itself sibling to yet more nested submenu markup.
    document.body.innerHTML = `
      <div class="menu" style="visibility: hidden; opacity: 0;">
        <ul class="menu__wrapper__pages">
          <li class="menu__item">
            <ul class="menu__item__parent-pages">
              <li class="menu__item__parent-pages__page">
                <a href="https://www.albi-tourisme.fr/decouvrir-albi/" class="menu__item__link not-link-style" target="">
                  Visiter Albi
                </a>
                <span class="menu__item__more fi fi--chevron-right"></span>
                <ul class="menu__item__child-pages">
                  <li class="menu__item__child-pages__page">
                    <a href="https://www.albi-tourisme.fr/decouvrir-albi/les-incontournables/">Les incontournables</a>
                  </li>
                </ul>
              </li>
            </ul>
          </li>
        </ul>
      </div>
    `;

    const result = collectHiddenLeaves(document.body, new Set());

    const visiterAlbi = result.find((r) => r.href === "https://www.albi-tourisme.fr/decouvrir-albi/");
    expect(visiterAlbi).toBeDefined();
    expect(visiterAlbi?.isHidden).toBe(true);
    expect(visiterAlbi?.content).toBe("Visiter Albi");

    const incontournables = result.find((r) =>
      r.href === "https://www.albi-tourisme.fr/decouvrir-albi/les-incontournables/",
    );
    expect(incontournables).toBeDefined();
    expect(incontournables?.content).toBe("Les incontournables");

    // Purely structural wrappers (ul/li with no own text) aren't recorded
    // as separate, redundant blobs — only the actual leaves are.
    expect(result.every((r) => r.name !== "ul" && r.name !== "li")).toBe(true);
  });

  it("groups menu items by tier: Tier 1 top-level, Tier 2 submenu of a Tier 1 item", () => {
    // Same Albi shape, extended with a second top-level item and its own
    // child, to check tiering isn't just "first item gets tier 1".
    document.body.innerHTML = `
      <div class="menu" style="visibility: hidden;">
        <ul class="menu__wrapper__pages">
          <li class="menu__item">
            <ul class="menu__item__parent-pages">
              <li class="menu__item__parent-pages__page">
                <a href="https://example.com/decouvrir-albi/">Visiter Albi</a>
                <ul class="menu__item__child-pages">
                  <li class="menu__item__child-pages__page"><a href="https://example.com/decouvrir-albi/les-incontournables/">Les incontournables</a></li>
                  <li class="menu__item__child-pages__page"><a href="https://example.com/decouvrir-albi/musees/">Musées et expositions</a></li>
                </ul>
              </li>
            </ul>
          </li>
          <li class="menu__item">
            <ul class="menu__item__parent-pages">
              <li class="menu__item__parent-pages__page">
                <a href="https://example.com/sejourner/">Organiser mon séjour</a>
                <ul class="menu__item__child-pages">
                  <li class="menu__item__child-pages__page"><a href="https://example.com/sejourner/hebergements/">Hébergements</a></li>
                </ul>
              </li>
            </ul>
          </li>
        </ul>
        <div class="menu__wrapper__accelerators">
          <a href="https://example.com/le-blog/">Le blog</a>
        </div>
      </div>
    `;

    const result = collectHiddenLeaves(document.body, new Set());
    const byHref = (href: string) => result.find((r) => r.href === href);

    const visiterAlbi = byHref("https://example.com/decouvrir-albi/")!;
    const sejour = byHref("https://example.com/sejourner/")!;
    const incontournables = byHref("https://example.com/decouvrir-albi/les-incontournables/")!;
    const musees = byHref("https://example.com/decouvrir-albi/musees/")!;
    const hebergements = byHref("https://example.com/sejourner/hebergements/")!;
    const blog = byHref("https://example.com/le-blog/")!;

    // Tier 1: both top-level items, no parent.
    expect(visiterAlbi.tier).toBe(1);
    expect(visiterAlbi.parent).toBeUndefined();
    expect(sejour.tier).toBe(1);
    expect(sejour.parent).toBeUndefined();

    // Tier 2: each submenu item points back at ITS OWN Tier-1 parent, not
    // just "the first" Tier 1 item.
    expect(incontournables.tier).toBe(2);
    expect(incontournables.parent).toBe(visiterAlbi.position);
    expect(musees.tier).toBe(2);
    expect(musees.parent).toBe(visiterAlbi.position);
    expect(hebergements.tier).toBe(2);
    expect(hebergements.parent).toBe(sejour.position);

    // Non-list content (promo card) alongside the menu isn't force-fit
    // into the tier hierarchy.
    expect(blog.tier).toBeUndefined();
    expect(blog.parent).toBeUndefined();
  });

  it("doesn't duplicate a Tier-1 entry when the source page repeats its link as a submenu-panel heading", () => {
    // Real Albi shape: the submenu panel opens with a heading that re-links
    // to the SAME parent page as the top-level item — a second <a>, same
    // href/text, sharing the exact same enclosing <li> as the real item.
    document.body.innerHTML = `
      <div class="menu" style="visibility: hidden;">
        <ul class="menu__wrapper__pages">
          <li class="menu__item">
            <ul class="menu__item__parent-pages">
              <li class="menu__item__parent-pages__page">
                <a href="https://example.com/decouvrir-albi/" class="menu__item__link">Visiter Albi</a>
                <ul class="menu__item__child-pages">
                  <p class="menu__item__child-pages__heading">
                    <a href="https://example.com/decouvrir-albi/" class="not-link-style">Visiter Albi</a>
                  </p>
                  <li class="menu__item__child-pages__page">
                    <a href="https://example.com/decouvrir-albi/les-incontournables/">Les incontournables</a>
                  </li>
                </ul>
              </li>
            </ul>
          </li>
        </ul>
      </div>
    `;

    const result = collectHiddenLeaves(document.body, new Set());
    const visiterAlbiEntries = result.filter((r) => r.href === "https://example.com/decouvrir-albi/");
    expect(visiterAlbiEntries).toHaveLength(2); // both still captured...

    const tiered = visiterAlbiEntries.filter((r) => r.tier != undefined);
    expect(tiered).toHaveLength(1); // ...but only ONE becomes a Tier-1 menu entry
    expect(tiered[0].tier).toBe(1);
    expect(tiered[0].classes).toBe("menu__item__link"); // the real item, not the heading duplicate

    const incontournables = result.find((r) =>
      r.href === "https://example.com/decouvrir-albi/les-incontournables/",
    )!;
    expect(incontournables.tier).toBe(2);
    // Points at the canonical (real) parent entry, not the untiered duplicate.
    expect(incontournables.parent).toBe(tiered[0].position);
  });

  it("correctly tiers a dropdown that wraps its links in an extra grouping <li> (real https://lisio.fr/ #skip-target-menu shape)", () => {
    // Trimmed real markup: a collapsed mobile off-canvas menu
    // (`#skip-target-menu`) whose dropdown TOGGLES are <button>s (no
    // href), and whose "À propos" panel additionally wraps its links in a
    // two-column layout — an extra <li> per column, purely for styling,
    // that no other dropdown in this same menu has. Every toggle/icon also
    // carries a decorative `aria-hidden="true"` SVG, as real sprite-icon
    // markup does.
    document.body.innerHTML = `
      <nav id="skip-target-menu" aria-label="Menu principal" class="header-nav" role="navigation" style="display: none;">
        <ul class="header-menu-list">
          <li class="header-dropdown">
            <button type="button" class="header-dropdown-toggle" aria-expanded="false" aria-controls="submenu-solutions">
              <span>Solutions</span>
              <svg class="header-dropdown-carret" aria-hidden="true"><path d="M2 5l6 6 6-6"/></svg>
            </button>
            <div id="submenu-solutions" class="header-dropdown-content">
              <ul>
                <li class="header-dropdown-item">
                  <a href="https://example.com/inclusion-numerique-lisio-humanity" class="header-dropdown-link">
                    <svg aria-hidden="true"><use href="#header-humanity"></use></svg>
                    <span>Lisio Humanity</span>
                  </a>
                </li>
                <li class="header-dropdown-item">
                  <a href="https://example.com/traduction-instantanee-lisio-welcome" class="header-dropdown-link">
                    <svg aria-hidden="true"><use href="#header-welcome"></use></svg>
                    <span>Lisio Welcome</span>
                  </a>
                </li>
              </ul>
            </div>
          </li>
          <li class="header-dropdown">
            <button type="button" class="header-dropdown-toggle" aria-expanded="false" aria-controls="submenu-a-propos">
              <span>À propos</span>
              <svg class="header-dropdown-carret" aria-hidden="true"><path d="M2 5l6 6 6-6"/></svg>
            </button>
            <div id="submenu-a-propos" class="header-dropdown-content">
              <ul class="col col-12">
                <li class="p-0 list-unstyled">
                  <ul>
                    <li class="header-dropdown-item">
                      <a href="https://example.com/a-propos-de-lisio" class="header-dropdown-link">Qui sommes-nous ?</a>
                    </li>
                    <li class="header-dropdown-item">
                      <a href="https://example.com/numerique-responsable" class="header-dropdown-link">Numérique Responsable</a>
                    </li>
                  </ul>
                </li>
                <li class="p-0 list-unstyled">
                  <ul>
                    <li class="header-dropdown-item">
                      <a href="https://example.com/articles" class="header-dropdown-link">Articles &amp; Livres blancs</a>
                    </li>
                  </ul>
                </li>
              </ul>
            </div>
          </li>
          <li class="header-link">
            <a href="https://example.com/tarifs" class="header-link-anchor">Tarifs</a>
          </li>
        </ul>
      </nav>
    `;

    const result = collectHiddenLeaves(document.body, new Set());
    const byContent = (content: string) => result.find((r) => r.content === content && r.tier != undefined)!;

    const solutions = byContent("Solutions");
    const aPropos = byContent("À propos");
    const tarifs = byContent("Tarifs");

    // Every dropdown toggle (button, no href) and the plain "Tarifs" link
    // land at Tier 1, side by side.
    expect(solutions.tier).toBe(1);
    expect(solutions.href).toBeUndefined();
    expect(aPropos.tier).toBe(1);
    expect(tarifs.tier).toBe(1);

    // "Solutions" only wraps its links in ONE <li> — the shallow case.
    expect(byContent("Lisio Humanity").tier).toBe(2);
    expect(byContent("Lisio Humanity").parent).toBe(solutions.position);
    expect(byContent("Lisio Welcome").tier).toBe(2);
    expect(byContent("Lisio Welcome").parent).toBe(solutions.position);

    // "À propos" wraps its links in an EXTRA grouping <li> per column —
    // its items must still land at Tier 2, parented directly on "À propos"
    // itself, not Tier 3 with a dangling/missing parent.
    const quiSommesNous = byContent("Qui sommes-nous ?");
    const numeriqueResponsable = byContent("Numérique Responsable");
    const articles = byContent("Articles & Livres blancs");
    expect(quiSommesNous.tier).toBe(2);
    expect(quiSommesNous.parent).toBe(aPropos.position);
    expect(numeriqueResponsable.tier).toBe(2);
    expect(numeriqueResponsable.parent).toBe(aPropos.position);
    expect(articles.tier).toBe(2);
    expect(articles.parent).toBe(aPropos.position);
  });

  it("parents hidden dropdown items under their VISIBLE toggle label, not just a hidden one (real https://lisio.fr/ desktop mega-menu shape)", () => {
    // The actual, live https://lisio.fr/ markup: unlike the mobile
    // off-canvas shape above (whole `<nav>` collapsed to `display: none`),
    // the desktop mega-menu keeps its `<nav>` and each dropdown's own
    // `<button>` toggle genuinely VISIBLE at all times — only the panel it
    // discloses (`.header-dropdown-content`, `id="submenu-solutions"`) is
    // hidden (`opacity: 0; visibility: hidden` pre-hover/click, verified
    // against the real fetched CSS). "Solutions" is therefore never itself
    // captured as a hidden leaf, so it can't serve as a Tier-1 anchor
    // through the "same <li> as some other captured leaf" mechanism alone —
    // without accounting for this, every real link ends up an unparented
    // Tier-1 item and "Solutions" never appears in the menu at all (the bug
    // this test guards against).
    document.body.innerHTML = `
      <nav id="skip-target-menu" aria-label="Menu principal" class="header-nav" role="navigation">
        <ul class="header-menu-list">
          <li class="header-dropdown">
            <button type="button" class="header-dropdown-toggle" aria-expanded="false" aria-controls="submenu-solutions">
              <span>Solutions</span>
              <svg class="header-dropdown-carret" aria-hidden="true"><path d="M2 5l6 6 6-6"/></svg>
            </button>
            <div id="submenu-solutions" class="header-dropdown-content" style="opacity: 0; visibility: hidden;">
              <ul>
                <li class="header-dropdown-item">
                  <a href="https://lisio.fr/inclusion-numerique-lisio-humanity" class="header-dropdown-link">
                    <svg aria-hidden="true"><use href="#header-humanity"></use></svg>
                    <span>Lisio Humanity</span>
                  </a>
                </li>
                <li class="header-dropdown-item">
                  <a href="https://lisio.fr/traduction-instantanee-lisio-welcome" class="header-dropdown-link">
                    <svg aria-hidden="true"><use href="#header-welcome"></use></svg>
                    <span>Lisio Welcome</span>
                  </a>
                </li>
              </ul>
            </div>
          </li>
          <li class="header-dropdown">
            <button type="button" class="header-dropdown-toggle" aria-expanded="false" aria-controls="submenu-clients">
              <span>Clients</span>
              <svg class="header-dropdown-carret" aria-hidden="true"><path d="M2 5l6 6 6-6"/></svg>
            </button>
            <div id="submenu-clients" class="header-dropdown-content" style="opacity: 0; visibility: hidden;">
              <ul>
                <li class="header-dropdown-item">
                  <a href="https://lisio.fr/references-clients" class="header-dropdown-link">
                    <span>Nos clients</span>
                  </a>
                </li>
              </ul>
            </div>
          </li>
        </ul>
      </nav>
    `;

    const result = collectHiddenLeaves(document.body, new Set());
    const solutions = result.find((r) => r.content === "Solutions")!;
    const clients = result.find((r) => r.content === "Clients")!;
    const lisioHumanity = result.find((r) => r.content === "Lisio Humanity")!;
    const lisioWelcome = result.find((r) => r.content === "Lisio Welcome")!;
    const nosClients = result.find((r) => r.content === "Nos clients")!;

    // "Solutions"/"Clients" were never CSS-hidden themselves — only their
    // panels were — so they're synthesized as Tier-1 group labels rather
    // than coming from the main hidden-leaf walk, and stay non-links.
    expect(solutions).toBeDefined();
    expect(solutions.tier).toBe(1);
    expect(solutions.href).toBeUndefined();
    expect(clients).toBeDefined();
    expect(clients.tier).toBe(1);

    expect(lisioHumanity.tier).toBe(2);
    expect(lisioHumanity.parent).toBe(solutions.position);
    expect(lisioHumanity.href).toBe("https://lisio.fr/inclusion-numerique-lisio-humanity");
    expect(lisioWelcome.tier).toBe(2);
    expect(lisioWelcome.parent).toBe(solutions.position);

    // Each dropdown's items parent onto THEIR OWN toggle, never onto the
    // other dropdown's — and never onto each other cross-panel.
    expect(nosClients.tier).toBe(2);
    expect(nosClients.parent).toBe(clients.position);
    expect(nosClients.parent).not.toBe(solutions.position);
  });

  it("doesn't let a decorative aria-hidden icon stand in for the real, fully VISIBLE menu item next to it", () => {
    // Same shape as above, but the whole nav is genuinely visible this
    // time (no `display: none`) — e.g. a desktop-width viewport where this
    // menu isn't collapsed at all. `aria-hidden` only hides from
    // assistive tech, never from sighted users, so nothing here should be
    // captured as "hidden" content to reveal later.
    document.body.innerHTML = `
      <nav id="skip-target-menu" role="navigation">
        <ul>
          <li class="header-dropdown">
            <button type="button">
              <span>Solutions</span>
              <svg aria-hidden="true"><path d="M2 5l6 6 6-6"/></svg>
            </button>
          </li>
        </ul>
      </nav>
    `;

    const result = collectHiddenLeaves(document.body, new Set());
    expect(result).toHaveLength(0);
  });

  it("parents a hidden dropdown under its VISIBLE sibling link, not a hidden '+' toggle sharing the same <li> (real https://www.handilab.com/ desktop nav shape)", () => {
    // Real https://www.handilab.com/ markup: each top-level item is TWO
    // sibling <a>s in the same <li> — the real, always-visible nav link
    // (e.g. "Actualités") and a separate "+" dropdown-disclosure toggle
    // that's only shown below a ~960px breakpoint (`.open-dropdown {
    // display: none }` by default). At desktop width the "+" toggle is the
    // ONE thing that's actually CSS-hidden, so — unlike the lisio.fr
    // mega-menu above, where the toggle is the visible element and the
    // panel is hidden — here the hidden leaf and the visible label are two
    // DIFFERENT elements sharing the same <li>. Naively using "the first
    // captured (hidden) leaf for this <li>" surfaces the meaningless "+" as
    // the group's own label instead of "Actualités" (the bug this test
    // guards against).
    document.body.innerHTML = `
      <nav class="navbar" role="navigation">
        <ul class="level_1">
          <li class="submenu trail">
            <a href="https://www.handilab.com/newsroom/actualites.html" class="submenu trail"><span>Actualités</span></a>
            <a href="https://www.handilab.com/#newsroom/actualites" class="open-dropdown" style="display: none;"><span>+</span></a>
            <ul class="level_2" style="display: none;">
              <li><a href="https://www.handilab.com/newsroom/actualites/appel-a-candidature.html">Appel à candidature</a></li>
            </ul>
          </li>
        </ul>
      </nav>
    `;

    const result = collectHiddenLeaves(document.body, new Set());
    const actualites = result.find((r) => r.content === "Actualités" && r.tier != undefined)!;
    const appel = result.find((r) => r.content === "Appel à candidature")!;
    const plus = result.find((r) => r.content === "+");

    expect(actualites).toBeDefined();
    expect(actualites.tier).toBe(1);
    // Synthesized from the visible link, so it stays clickable.
    expect(actualites.href).toBe("https://www.handilab.com/newsroom/actualites.html");

    expect(appel.tier).toBe(2);
    expect(appel.parent).toBe(actualites.position);

    // The "+" toggle was still captured (it IS hidden) but never becomes a
    // tiered menu entry of its own.
    expect(plus).toBeDefined();
    expect(plus?.tier).toBeUndefined();
  });

  it("does not record visible content", () => {
    document.body.innerHTML = `<main><h1>Visible content</h1></main>`;
    const result = collectHiddenLeaves(document.body, new Set());
    expect(result).toHaveLength(0);
  });

  it("catches hiding via display/opacity, not just inherited visibility", () => {
    document.body.innerHTML = `
      <div style="display: none;"><a href="https://example.com/a">Link A</a></div>
      <div style="opacity: 0;"><a href="https://example.com/b">Link B</a></div>
    `;
    const result = collectHiddenLeaves(document.body, new Set());
    expect(result.map((r) => r.href)).toEqual(
      expect.arrayContaining(["https://example.com/a", "https://example.com/b"]),
    );
  });

  it("excludes elements matched by the background-image selector set", () => {
    document.body.innerHTML = `
      <div style="visibility: hidden;">
        <span class="bg">decorative background carrier</span>
        <a href="https://example.com/real-link">Real link</a>
      </div>
    `;
    const bg = document.querySelector(".bg") as Element;

    const result = collectHiddenLeaves(document.body, new Set([bg]));

    expect(result.some((r) => r.content === "decorative background carrier")).toBe(false);
    expect(result.some((r) => r.href === "https://example.com/real-link")).toBe(true);
  });

  it("skips script/style content entirely", () => {
    document.body.innerHTML = `
      <div style="display: none;">
        <script>window.x = 1;</script>
        <style>.a { color: red; }</style>
      </div>
    `;
    const result = collectHiddenLeaves(document.body, new Set());
    expect(result).toHaveLength(0);
  });

  it("captures a hidden image (no text) via its src", () => {
    document.body.innerHTML = `
      <div style="opacity: 0;">
        <img src="https://example.com/x.png" alt="">
      </div>
    `;
    const result = collectHiddenLeaves(document.body, new Set());
    expect(result).toHaveLength(1);
    expect(result[0].src).toBe("https://example.com/x.png");
  });
});
