/**
 * @jest-environment jsdom
 * @jest-environment-options {"url": "https://example.com/page/"}
 */
import { extractLightContent } from "../../../src/adapters/reader/light-extract";
import { LightBlock } from "../../../src/adapters/reader/light-reader-types";

/** Blocks without their scroll anchors (`a`), which have dedicated tests below. */
function extract(html: string): LightBlock[] | undefined {
  document.body.innerHTML = html;
  const blocks = extractLightContent(document)?.blocks;
  return blocks == undefined
    ? undefined
    : (JSON.parse(
        JSON.stringify(blocks, (key, value) => (key === "a" ? undefined : value)),
      ) as LightBlock[]);
}

describe("extractLightContent — bounds", () => {
  it("keeps content from h1 (included) up to the site footer (excluded)", () => {
    const blocks = extract(`
      <header><p>Logo</p></header>
      <main>
        <h1>Titre</h1>
        <p>Contenu</p>
      </main>
      <footer><p>Mentions légales</p></footer>
      <p>Après le footer</p>
    `);
    expect(blocks).toEqual([
      { type: "heading", level: 1, c: ["Titre"] },
      { type: "paragraph", c: ["Contenu"] },
    ]);
  });

  it("returns undefined when the page has no h1", () => {
    expect(extract(`<h2>Titre</h2><p>Texte</p><footer>Pied</footer>`)).toBeUndefined();
  });

  it("starts at main when there is no readable h1 (h1 in a closed header menu)", () => {
    const blocks = extract(`
      <header role="banner">
        <p>Logo</p>
        <div style="display:none;visibility:hidden"><h1 class="screenreader">Musée</h1><p>Menu</p></div>
      </header>
      <main role="main"><h2>Expositions</h2><p>Texte</p></main>
      <footer role="contentinfo">Pied</footer>
    `);
    expect(blocks).toEqual([
      { type: "heading", level: 2, c: ["Expositions"] },
      { type: "paragraph", c: ["Texte"] },
    ]);
  });

  it("prefers a readable h1 over main", () => {
    const blocks = extract(`
      <main><p>Intro</p><h1>Titre</h1><p>Texte</p></main>
      <footer>Pied</footer>
    `);
    expect(blocks?.[0]).toEqual({ type: "heading", level: 1, c: ["Titre"] });
  });

  it("accepts role=main as the fallback start", () => {
    const blocks = extract(`
      <div role="main"><p>Texte</p></div>
      <footer>Pied</footer>
    `);
    expect(blocks).toEqual([{ type: "paragraph", c: ["Texte"] }]);
  });

  it("returns undefined when there is no site footer", () => {
    expect(extract(`<h1>Titre</h1><p>Texte</p>`)).toBeUndefined();
  });

  it("does not stop at an article's own footer", () => {
    const blocks = extract(`
      <main>
        <h1>Titre</h1>
        <article><p>Carte</p><footer>Publié le 1er mai</footer></article>
        <p>Suite</p>
      </main>
      <footer>Pied du site</footer>
    `);
    expect(blocks?.map((b) => ("c" in b ? b.c : undefined))).toEqual([
      ["Titre"],
      ["Carte"],
      ["Publié le 1er mai"],
      ["Suite"],
    ]);
  });

  it("returns undefined when the only footer is inside an article", () => {
    expect(
      extract(`<h1>Titre</h1><article><p>A</p><footer>F</footer></article>`),
    ).toBeUndefined();
  });

  it("accepts role=contentinfo as the site footer", () => {
    const blocks = extract(
      `<h1>Titre</h1><p>A</p><div role="contentinfo">Pied</div>`,
    );
    expect(blocks).toHaveLength(2);
  });

  it("ignores a hidden h1", () => {
    expect(
      extract(`<h1 hidden>Caché</h1><p>A</p><footer>F</footer>`),
    ).toBeUndefined();
  });

  it("accepts a screen-reader-only h1 (sr-only class) and keeps it as the title", () => {
    const blocks = extract(`
      <main><h1 class="sr-only">Titre</h1><p>A</p></main>
      <footer>F</footer>
    `);
    expect(blocks).toEqual([
      { type: "heading", level: 1, c: ["Titre"] },
      { type: "paragraph", c: ["A"] },
    ]);
  });

  it("accepts an h1 visually hidden by styles (Foundation show-for-sr)", () => {
    const blocks = extract(`
      <main>
        <h1 class="show-for-sr" style="position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0)">Office de Tourisme</h1>
        <p>A</p>
      </main>
      <footer role="contentinfo">F</footer>
    `);
    expect(blocks?.[0]).toEqual({
      type: "heading",
      level: 1,
      c: ["Office de Tourisme"],
    });
  });

  it("walks out of the h1's wrappers and continues with following siblings", () => {
    const blocks = extract(`
      <div class="hero"><div><h1>Titre</h1></div></div>
      <section><h2>Partie</h2><p>Texte</p></section>
      <footer>Pied</footer>
    `);
    expect(blocks?.map((b) => b.type)).toEqual(["heading", "heading", "paragraph"]);
  });
});

describe("extractLightContent — exclusions", () => {
  it("skips tables, forms, nav, aside and hidden content", () => {
    const blocks = extract(`
      <h1>Titre</h1>
      <table><tr><td>Cellule</td></tr></table>
      <form><label>Nom <input></label></form>
      <nav><a href="/a">Menu</a></nav>
      <aside><p>Pub</p></aside>
      <div role="navigation"><p>Nav</p></div>
      <p style="display:none">Masqué</p>
      <p aria-hidden="true">Masqué aussi</p>
      <p class="sr-only">Lecteur d'écran</p>
      <p>Visible</p>
      <footer>Pied</footer>
    `);
    expect(blocks).toEqual([
      { type: "heading", level: 1, c: ["Titre"] },
      { type: "paragraph", c: ["Visible"] },
    ]);
  });
});

describe("extractLightContent — content", () => {
  it("keeps inline emphasis and line breaks", () => {
    const blocks = extract(`
      <h1>Titre</h1>
      <p>Un <strong>mot</strong> et <em>un autre</em><br>ligne 2 <b>gras</b> <i>ital</i></p>
      <footer>Pied</footer>
    `);
    expect(blocks?.[1]).toEqual({
      type: "paragraph",
      c: [
        "Un ",
        { t: "strong", c: ["mot"] },
        " et ",
        { t: "em", c: ["un autre"] },
        { t: "br" },
        "ligne 2 ",
        { t: "strong", c: ["gras"] },
        " ",
        { t: "em", c: ["ital"] },
      ],
    });
  });

  it("keeps a hidden whitespace separator as a space", () => {
    const blocks = extract(`
      <h1>Titre</h1>
      <div><span>Lourdes</span><span><span style="display: none !important">&nbsp;</span>Lumière des Pyrénées</span></div>
      <footer>F</footer>
    `);
    expect(blocks?.[1]).toEqual({
      type: "paragraph",
      c: ["Lourdes Lumière des Pyrénées"],
    });
  });

  it("ignores the text of a font-size:0 overlay link (no duplicated card title)", () => {
    const blocks = extract(`
      <h1>Titre</h1>
      <div class="card">
        <h3><span>Saint-Gobain finalise l'acquisition</span></h3>
        <div class="card__link"><a href="https://example.com/a.pdf" style="font-size:0;position:absolute;inset:0">See Saint-Gobain finalise l'acquisition</a></div>
      </div>
      <footer>F</footer>
    `);
    expect(blocks).toEqual([
      { type: "heading", level: 1, c: ["Titre"] },
      { type: "heading", level: 3, c: ["Saint-Gobain finalise l'acquisition"] },
    ]);
  });

  it("keeps children that reset the font size of a font-size:0 container", () => {
    const blocks = extract(`
      <h1>Titre</h1>
      <div style="font-size:0"><span style="font-size:16px">Visible</span></div>
      <footer>F</footer>
    `);
    expect(blocks?.[1]).toEqual({ type: "paragraph", c: ["Visible"] });
  });

  it("resolves links to absolute URLs and drops unsafe ones", () => {
    const blocks = extract(`
      <h1>Titre</h1>
      <p>
        <a href="../autre">Relatif</a>
        <a href="https://ext.org" target="_blank">Externe</a>
        <a href="javascript:alert(1)">Script</a>
        <a href="mailto:a@b.fr">Mail</a>
      </p>
      <footer>Pied</footer>
    `);
    expect(blocks?.[1]).toEqual({
      type: "paragraph",
      c: [
        { t: "a", href: "https://example.com/autre", blank: false, c: ["Relatif"] },
        " ",
        { t: "a", href: "https://ext.org/", blank: true, c: ["Externe"] },
        " Script ",
        { t: "a", href: "mailto:a@b.fr", blank: false, c: ["Mail"] },
      ],
    });
  });

  it("keeps a link wrapping block content (card links)", () => {
    const blocks = extract(`
      <h1>Titre</h1>
      <a href="/article"><div><h3>Carte</h3><p>Résumé</p></div></a>
      <footer>Pied</footer>
    `);
    const link = { t: "a", href: "https://example.com/article", blank: false };
    expect(blocks?.slice(1)).toEqual([
      { type: "heading", level: 3, c: [{ ...link, c: ["Carte"] }] },
      { type: "paragraph", c: [{ ...link, c: ["Résumé"] }] },
    ]);
  });

  it("builds nested lists", () => {
    const blocks = extract(`
      <h1>Titre</h1>
      <ol>
        <li>Un</li>
        <li>Deux
          <ul><li>Deux A</li></ul>
        </li>
      </ol>
      <footer>Pied</footer>
    `);
    expect(blocks?.[1]).toEqual({
      type: "list",
      ordered: true,
      items: [
        { c: ["Un"], children: [] },
        {
          c: ["Deux"],
          children: [
            { type: "list", ordered: false, items: [{ c: ["Deux A"], children: [] }] },
          ],
        },
      ],
    });
  });

  it("turns loose text in divs into paragraphs", () => {
    const blocks = extract(`
      <h1>Titre</h1>
      <div>Texte libre <span>suite</span><div>Bloc</div>fin</div>
      <footer>Pied</footer>
    `);
    expect(blocks?.slice(1)).toEqual([
      { type: "paragraph", c: ["Texte libre suite"] },
      { type: "paragraph", c: ["Bloc"] },
      { type: "paragraph", c: ["fin"] },
    ]);
  });

  it("keeps images, even without alt, and skips decorative ones", () => {
    const blocks = extract(`
      <h1>Titre</h1>
      <img src="/photo.jpg" alt="Une photo">
      <img src="/empty-alt.png" alt="">
      <img src="/no-alt.png">
      <img src="/deco2.png" role="presentation" alt="x">
      <img src="/pixel.gif" width="1" height="1" alt="pixel">
      <p>Texte <img src="/inline.png" alt="Inline"> suite</p>
      <footer>Pied</footer>
    `);
    expect(blocks?.slice(1)).toEqual([
      { type: "image", src: "https://example.com/photo.jpg", alt: "Une photo" },
      { type: "image", src: "https://example.com/empty-alt.png", alt: "" },
      { type: "image", src: "https://example.com/no-alt.png", alt: "" },
      // An image in the middle of text splits the paragraph, keeping reading order.
      { type: "paragraph", c: ["Texte"] },
      { type: "image", src: "https://example.com/inline.png", alt: "Inline" },
      { type: "paragraph", c: ["suite"] },
    ]);
  });

  it("shows a repeated image only once", () => {
    const blocks = extract(`
      <h1>Titre</h1>
      <img src="/logo.png" alt="Logo">
      <p>Texte</p>
      <img src="/logo.png" alt="Logo">
      <footer>Pied</footer>
    `);
    expect(blocks?.slice(1)).toEqual([
      { type: "image", src: "https://example.com/logo.png", alt: "Logo" },
      { type: "paragraph", c: ["Texte"] },
    ]);
  });

  it("renders spritesheet images (same src, different alts) as their alt text", () => {
    const blocks = extract(`
      <h1>Titre</h1>
      <ul>
        <li><img src="/sprite.webp" alt="EDF"></li>
        <li><a href="/hellfest"><img src="/sprite.webp" alt="Hellfest"></a></li>
      </ul>
      <footer>Pied</footer>
    `);
    expect(blocks?.[1]).toEqual({
      type: "list",
      ordered: false,
      items: [
        { c: ["EDF"], children: [] },
        {
          c: [{ t: "a", href: "https://example.com/hellfest", blank: false, c: ["Hellfest"] }],
          children: [],
        },
      ],
    });
  });

  it("treats an image with a sprite class as a sprite even when used once", () => {
    const blocks = extract(`
      <h1>Titre</h1>
      <div><img src="/icons.webp" class="sprite icon-logo" alt="Lisio Humanity"></div>
      <footer>Pied</footer>
    `);
    expect(blocks?.slice(1)).toEqual([{ type: "paragraph", c: ["Lisio Humanity"] }]);
  });

  it("detects a sprite even when its other uses are outside the h1 → footer range", () => {
    const blocks = extract(`
      <header><img src="/sprite.webp" alt="Accueil"></header>
      <h1>Titre</h1>
      <div><img src="/sprite.webp" alt="EDF"></div>
      <footer>Pied</footer>
    `);
    expect(blocks?.slice(1)).toEqual([{ type: "paragraph", c: ["EDF"] }]);
  });

  it("maps blockquote and pre", () => {
    const blocks = extract(`
      <h1>Titre</h1>
      <blockquote><p>Citation</p></blockquote>
      <pre>ligne 1
  ligne 2</pre>
      <footer>Pied</footer>
    `);
    expect(blocks?.slice(1)).toEqual([
      { type: "quote", c: ["Citation"] },
      { type: "pre", text: "ligne 1\n  ligne 2" },
    ]);
  });
});

describe("extractLightContent — scroll anchors", () => {
  it("maps every block and list item to its source element", () => {
    document.body.innerHTML = `
      <h1 id="t">Titre</h1>
      <div id="d">Texte libre <span id="s">suite</span></div>
      <ul id="l"><li id="i1">Un</li><li id="i2">Deux</li></ul>
      <img id="img" src="/photo.jpg" alt="Photo">
      <footer>Pied</footer>
    `;
    const extraction = extractLightContent(document);
    expect(extraction).toBeDefined();
    const { blocks, anchors } = extraction as NonNullable<typeof extraction>;
    const idOf = (a: number | undefined) =>
      a == undefined ? undefined : anchors[a]?.id;
    expect(blocks.map((b) => idOf(b.a))).toEqual(["t", "d", "l", "img"]);
    const list = blocks[2];
    expect(list.type === "list" && list.items.map((i) => idOf(i.a))).toEqual([
      "i1",
      "i2",
    ]);
  });

  it("anchors a paragraph starting with an inline element to that element", () => {
    document.body.innerHTML = `
      <h1>Titre</h1>
      <div><a id="lnk" href="/x">Lien</a> puis texte<p>Bloc</p></div>
      <footer>Pied</footer>
    `;
    const { blocks, anchors } = extractLightContent(document) as NonNullable<
      ReturnType<typeof extractLightContent>
    >;
    expect(anchors[blocks[1].a as number].id).toBe("lnk");
    expect(anchors[blocks[2].a as number].localName).toBe("p");
  });
});

describe("extractLightContent — language", () => {
  afterEach(() => {
    document.documentElement.removeAttribute("lang");
  });

  it("marks only the blocks whose language differs from the page", () => {
    document.documentElement.lang = "fr";
    const blocks = extract(`
      <h1>Titre</h1>
      <p>Texte</p>
      <p lang="fr">Texte aussi</p>
      <blockquote lang="en"><p>Quote</p></blockquote>
      <div lang="en-GB"><ul><li>Item</li></ul></div>
      <footer>Pied</footer>
    `);
    expect(blocks).toEqual([
      { type: "heading", level: 1, c: ["Titre"] },
      { type: "paragraph", c: ["Texte"] },
      { type: "paragraph", c: ["Texte aussi"] },
      { type: "quote", c: ["Quote"], lang: "en" },
      {
        type: "list",
        ordered: false,
        items: [{ c: ["Item"], children: [] }],
        lang: "en-GB",
      },
    ]);
  });
});

describe("extractLightContent — embedded PDFs", () => {
  it("emits an anchored pdf placeholder, in order, for embed/object/iframe PDFs", () => {
    document.body.innerHTML = `
      <h1>Titre</h1>
      <p>Avant</p>
      <embed id="e" type="application/pdf" src="/docs/rapport.pdf" title="Rapport annuel">
      <object data="notice.PDF"><p>Télécharger</p></object>
      <iframe src="https://cdn.example.org/files/guide%20complet.pdf"></iframe>
      <iframe src="https://example.com/video"></iframe>
      <footer>Pied</footer>
    `;
    const extraction = extractLightContent(document);
    const blocks = extraction?.blocks ?? [];
    expect(
      JSON.parse(JSON.stringify(blocks, (key, value) => (key === "a" ? undefined : value))),
    ).toEqual([
      { type: "heading", level: 1, c: ["Titre"] },
      { type: "paragraph", c: ["Avant"] },
      { type: "pdf", src: "https://example.com/docs/rapport.pdf", title: "Rapport annuel" },
      { type: "pdf", src: "https://example.com/page/notice.PDF", title: "notice.PDF" },
      {
        type: "pdf",
        src: "https://cdn.example.org/files/guide%20complet.pdf",
        title: "guide complet.pdf",
      },
    ]);
    expect(extraction?.anchors[blocks[2].a as number].id).toBe("e");
  });

  it("ignores PDFs outside the h1 → footer range", () => {
    const blocks = extract(`
      <embed type="application/pdf" src="/avant.pdf">
      <h1>Titre</h1>
      <footer>Pied <embed type="application/pdf" src="/apres.pdf"></footer>
    `);
    expect(blocks).toEqual([{ type: "heading", level: 1, c: ["Titre"] }]);
  });

  it("emits a PDF nested in inline content after its paragraph", () => {
    const blocks = extract(`
      <h1>Titre</h1>
      <p>Voir <span><embed type="application/pdf" src="/x.pdf"></span> ici</p>
      <footer>Pied</footer>
    `);
    expect(blocks?.slice(1)).toEqual([
      { type: "paragraph", c: ["Voir ici"] },
      { type: "pdf", src: "https://example.com/x.pdf", title: "x.pdf" },
    ]);
  });
});
