import {
  getReadableText,
  isHiddenElement,
  isScreenReaderOnlyElement,
  isUnreadableElement,
  shouldKeepReadableText,
} from "../../utils/lisio-readable-dom";
import { LightBlock, LightInline, LightListItem } from "./light-reader-types";
import { pdfSourceOf, pdfTitleOf } from "./pdf-sources";

/** Sous-arbres jamais extraits (tableaux, formulaires, navigation, médias, UI Lisio). */
const SKIPPED_SELECTOR = [
  "table",
  "form",
  "nav",
  "aside",
  "dialog",
  "[role=navigation]",
  "[role=complementary]",
  "script",
  "style",
  "noscript",
  "template",
  "iframe",
  "video",
  "audio",
  "svg",
  "canvas",
  "object",
  "embed",
  "button",
  "input",
  "select",
  "textarea",
  "#lisio-shadow-env",
].join(", ");

/** Un footer dans l'un de ces ancêtres est celui d'un article / d'une carte, pas celui du site. */
const FOOTER_EXCLUDED_ANCESTORS = "article, main, aside, nav, dialog";

const INLINE_TAGS = new Set([
  "a",
  "abbr",
  "b",
  "bdi",
  "bdo",
  "cite",
  "code",
  "data",
  "del",
  "dfn",
  "em",
  "font",
  "i",
  "ins",
  "kbd",
  "label",
  "mark",
  "q",
  "s",
  "samp",
  "small",
  "span",
  "strong",
  "sub",
  "sup",
  "time",
  "u",
  "var",
]);

const BLOCK_DESCENDANT_SELECTOR =
  "address, article, blockquote, dd, details, div, dl, dt, figcaption, figure, footer, h1, h2, h3, h4, h5, h6, header, hr, li, main, ol, p, pre, section, summary, ul";

const ALLOWED_LINK_PROTOCOLS = new Set(["http:", "https:", "mailto:", "tel:"]);
const ALLOWED_IMAGE_PROTOCOLS = new Set(["http:", "https:", "data:"]);

const MAX_BLOCKS = 5000;

const SPRITE_CLASS_RE = /sprite/iu;

/** Résultat de l'extraction : les blocs et, pour chaque ancre `a`, son élément source. */
interface LightExtraction {
  anchors: Element[];
  blocks: LightBlock[];
}

interface LinkContext {
  blank: boolean;
  href: string;
}

function isSkipped(element: Element): boolean {
  return (
    element.matches(SKIPPED_SELECTOR) ||
    ((element instanceof HTMLElement || element instanceof SVGElement) &&
      isUnreadableElement(element))
  );
}

/**
 * Texte direct de `parent` rendu invisible par `font-size: 0` (ex. lien « étiré »
 * sur toute une carte, dont le texte doublonne le titre). Seul le texte est ignoré :
 * les enfants qui redéfinissent leur taille restent lisibles.
 */
function hasInvisibleText(parent: Element): boolean {
  return Number.parseFloat(window.getComputedStyle(parent).fontSize) === 0;
}

function safeUrl(url: string, allowed: Set<string>): string | undefined {
  try {
    const parsed = new URL(url);
    return allowed.has(parsed.protocol) ? parsed.href : undefined;
  } catch {
    return undefined;
  }
}

function linkOf(element: Element): LinkContext | undefined {
  if (!(element instanceof HTMLAnchorElement)) {
    return undefined;
  }
  const href = safeUrl(element.href, ALLOWED_LINK_PROTOCOLS);
  return href == undefined
    ? undefined
    : { href, blank: element.target === "_blank" };
}

function hasText(inlines: LightInline[]): boolean {
  return inlines.some((inline) =>
    typeof inline === "string"
      ? inline.trim() !== ""
      : "c" in inline && hasText(inline.c),
  );
}

/** Fusionne les chaînes adjacentes et retire les espaces/sauts de ligne en bordure. */
function normalizeInlines(inlines: LightInline[]): LightInline[] {
  const merged: LightInline[] = [];
  for (const inline of inlines) {
    const last = merged[merged.length - 1];
    if (typeof inline === "string" && typeof last === "string") {
      merged[merged.length - 1] = `${last}${inline}`.replace(/\s+/gu, " ");
    } else {
      merged.push(inline);
    }
  }
  while (
    merged.length > 0 &&
    (merged[0] === " " || (typeof merged[0] !== "string" && merged[0].t === "br"))
  ) {
    merged.shift();
  }
  while (merged.length > 0) {
    const last = merged[merged.length - 1];
    if (last === " " || (typeof last !== "string" && last.t === "br")) {
      merged.pop();
    } else {
      break;
    }
  }
  if (typeof merged[0] === "string") {
    merged[0] = merged[0].trimStart();
  }
  const lastIndex = merged.length - 1;
  if (typeof merged[lastIndex] === "string") {
    merged[lastIndex] = (merged[lastIndex] as string).trimEnd();
  }
  return merged;
}

function wrapInLink(
  inlines: LightInline[],
  link: LinkContext | undefined,
): LightInline[] {
  return link == undefined ? inlines : [{ t: "a", ...link, c: inlines }];
}

function imageSrcOf(element: HTMLImageElement): string | undefined {
  return safeUrl(element.currentSrc || element.src, ALLOWED_IMAGE_PROTOCOLS);
}

/**
 * Repère les feuilles de sprites : une même image utilisée par plusieurs <img>
 * avec des alt différents (chaque balise n'en montre qu'une partie via le CSS,
 * ex. les logos clients de lisio.fr), ou une classe contenant « sprite ».
 * Afficher l'image entière n'aurait pas de sens : seul son alt est gardé.
 */
function findSpriteSources(root: HTMLElement): Set<string> {
  const altsBySrc = new Map<string, Set<string>>();
  const sprites = new Set<string>();
  for (const img of root.querySelectorAll("img")) {
    const src = imageSrcOf(img);
    if (src == undefined) {
      continue;
    }
    if (SPRITE_CLASS_RE.test(img.getAttribute("class") || "")) {
      sprites.add(src);
    }
    const alt = img.getAttribute("alt")?.trim();
    if (alt) {
      const alts = altsBySrc.get(src) ?? new Set<string>();
      alts.add(alt);
      altsBySrc.set(src, alts);
    }
  }
  for (const [src, alts] of altsBySrc) {
    if (alts.size > 1) {
      sprites.add(src);
    }
  }
  return sprites;
}

/**
 * Premier h1 lisible. Un h1 réservé aux lecteurs d'écran (sr-only, show-for-sr…)
 * est accepté : c'est le vrai titre de la page, seulement masqué visuellement.
 * À défaut de h1 lisible, le contenu commence au premier `main` lisible.
 */
function findStart(doc: Document): HTMLElement | undefined {
  const h1 = Array.from(doc.querySelectorAll<HTMLElement>("h1")).find(
    (element) =>
      element.closest(SKIPPED_SELECTOR) == undefined &&
      !isHiddenElement(element) &&
      // getReadableText vide un élément sr-only : son texte est lu directement.
      (isScreenReaderOnlyElement(element)
        ? (element.textContent || "").trim()
        : getReadableText(element)) !== "",
  );
  return (
    h1 ??
    Array.from(doc.querySelectorAll<HTMLElement>("main, [role=main]")).find(
      (main) =>
        main.closest(SKIPPED_SELECTOR) == undefined &&
        !isUnreadableElement(main) &&
        getReadableText(main) !== "",
    )
  );
}

function findEnd(doc: Document, start: HTMLElement): HTMLElement | undefined {
  return Array.from(
    doc.querySelectorAll<HTMLElement>("footer, [role=contentinfo]"),
  ).find(
    (footer) =>
      (start.compareDocumentPosition(footer) &
        Node.DOCUMENT_POSITION_FOLLOWING) !==
        0 &&
      !footer.contains(start) &&
      footer.parentElement?.closest(FOOTER_EXCLUDED_ANCESTORS) == undefined &&
      footer.closest("#lisio-shadow-env") == undefined,
  );
}

class LightExtractor {
  private _anchors: Element[] = [];
  private _blocks: LightBlock[] = [];
  private _count = 0;
  private _done = false;
  private _end: HTMLElement;
  // Images et PDF rencontrés à l'intérieur d'un texte : émis juste après le bloc qui les contient.
  private _pendingBlocks: { block: LightBlock; source: Element }[] = [];
  // Une image déjà affichée n'est pas répétée (logo en double, clones de carrousel…).
  private _seenImages = new Set<string>();
  private _spriteSources: Set<string>;
  private _start: HTMLElement;
  private _started = false;

  constructor(start: HTMLElement, end: HTMLElement, root: HTMLElement) {
    this._start = start;
    this._end = end;
    this._spriteSources = findSpriteSources(root);
  }

  public extract(body: HTMLElement): LightExtraction {
    this.walkContainer(body, this._blocks, undefined);
    return { blocks: this._blocks, anchors: this._anchors };
  }

  private anchor(source: Element): number {
    return this._anchors.push(source) - 1;
  }

  private push(out: LightBlock[], block: LightBlock, source: Element) {
    if (this._count >= MAX_BLOCKS) {
      this._done = true;
      return;
    }
    this._count++;
    block.a = this.anchor(source);
    // Langue propre au bloc (ex. citation en anglais) : le découpage
    // syllabique de la fenêtre de lecture ne doit pas la traiter en français.
    const lang = source.closest("[lang]")?.getAttribute("lang") ?? "";
    if (lang !== "" && lang !== source.ownerDocument.documentElement.lang) {
      block.lang = lang;
    }
    out.push(block);
  }

  private flushPendingBlocks(out: LightBlock[]) {
    for (const { block, source } of this._pendingBlocks.splice(0, Infinity)) {
      this.push(out, block, source);
    }
  }

  private flushRun(
    run: LightInline[],
    out: LightBlock[],
    link: LinkContext | undefined,
    source: Element,
  ) {
    const inlines = normalizeInlines(run.splice(0, Infinity));
    if (hasText(inlines)) {
      this.push(out, { type: "paragraph", c: wrapInLink(inlines, link) }, source);
    }
    this.flushPendingBlocks(out);
  }

  private isDecorativeImage(element: HTMLImageElement): boolean {
    // Une image sans alt (ou alt="") est gardée : beaucoup de sites n'en renseignent pas.
    return (
      ["presentation", "none"].includes(element.getAttribute("role") || "") ||
      ["0", "1"].includes(element.getAttribute("width") || "") ||
      ["0", "1"].includes(element.getAttribute("height") || "") ||
      isSkipped(element)
    );
  }

  /** Alt d'une image de feuille de sprites, restitué comme texte ; `undefined` sinon. */
  private spriteAltOf(element: HTMLImageElement): string | undefined {
    const src = imageSrcOf(element);
    if (
      src == undefined ||
      !this._spriteSources.has(src) ||
      this.isDecorativeImage(element)
    ) {
      return undefined;
    }
    const alt = element.getAttribute("alt")?.replace(/\s+/gu, " ").trim();
    return alt || undefined;
  }

  private imageOf(element: HTMLImageElement): LightBlock | undefined {
    const src = imageSrcOf(element);
    if (
      src == undefined ||
      this._spriteSources.has(src) ||
      this._seenImages.has(src) ||
      this.isDecorativeImage(element)
    ) {
      return undefined;
    }
    this._seenImages.add(src);
    return { type: "image", src, alt: element.getAttribute("alt") || "" };
  }

  /** PDF intégré (embed/object/iframe) : bloc `pdf`, remplacé par son texte avant l'envoi. */
  private pdfOf(element: Element): LightBlock | undefined {
    const src = pdfSourceOf(element);
    if (
      src == undefined ||
      (element instanceof HTMLElement && isUnreadableElement(element))
    ) {
      return undefined;
    }
    return { type: "pdf", src, title: pdfTitleOf(element, src) };
  }

  private inlineChildren(element: Element): LightInline[] {
    const inlines: LightInline[] = [];
    for (const child of element.childNodes) {
      if (child.nodeType === Node.TEXT_NODE) {
        const text = child.textContent || "";
        if (text.trim() === "") {
          inlines.push(" ");
        } else if (
          shouldKeepReadableText(text, element) &&
          !hasInvisibleText(element)
        ) {
          inlines.push(text.replace(/\s+/gu, " "));
        }
      } else if (child instanceof Element) {
        inlines.push(...this.inlineOf(child));
      }
    }
    return inlines;
  }

  private inlineOf(element: Element): LightInline[] {
    const tag = element.localName;
    if (tag === "br") {
      return [{ t: "br" }];
    }
    if (element instanceof HTMLImageElement) {
      const spriteAlt = this.spriteAltOf(element);
      if (spriteAlt != undefined) {
        return [spriteAlt];
      }
      const image = this.imageOf(element);
      if (image != undefined) {
        this._pendingBlocks.push({ block: image, source: element });
      }
      return [];
    }
    const pdf = this.pdfOf(element);
    if (pdf != undefined) {
      this._pendingBlocks.push({ block: pdf, source: element });
      return [];
    }
    if (isSkipped(element)) {
      // Séparateur masqué (ex. `<span style="display:none">&nbsp;</span>`) : garde l'espace.
      const text = element.textContent || "";
      return text !== "" && text.trim() === "" ? [" "] : [];
    }
    const children = this.inlineChildren(element);
    if (!hasText(children)) {
      return children.length > 0 ? [" "] : [];
    }
    if (tag === "a") {
      const link = linkOf(element);
      return link == undefined ? children : [{ t: "a", ...link, c: children }];
    }
    if (tag === "strong" || tag === "b") {
      return [{ t: "strong", c: children }];
    }
    if (tag === "em" || tag === "i") {
      return [{ t: "em", c: children }];
    }
    return children;
  }

  private isInline(element: Element): boolean {
    return (
      INLINE_TAGS.has(element.localName) &&
      element.querySelector(BLOCK_DESCENDANT_SELECTOR) == undefined
    );
  }

  private walkContainer(
    container: Element,
    out: LightBlock[],
    link: LinkContext | undefined,
  ) {
    const run: LightInline[] = [];
    // Élément source du paragraphe en cours : le premier élément inline du run, sinon le conteneur.
    let runSource: Element | undefined;
    const flush = () => {
      this.flushRun(run, out, link, runSource ?? container);
      runSource = undefined;
    };
    for (const child of container.childNodes) {
      if (this._done) {
        break;
      }
      if (child.nodeType === Node.TEXT_NODE) {
        if (this._started) {
          const text = child.textContent || "";
          if (text.trim() === "") {
            run.push(" ");
          } else if (
            shouldKeepReadableText(text, container) &&
            !hasInvisibleText(container)
          ) {
            run.push(text.replace(/\s+/gu, " "));
            runSource ??= container;
          }
        }
        continue;
      }
      if (!(child instanceof Element)) {
        continue;
      }
      if (child === this._end) {
        this._done = true;
        break;
      }
      const leadsToStart = !this._started && child.contains(this._start);
      const leadsToEnd = child.contains(this._end);
      if (this._started) {
        const pdf = this.pdfOf(child);
        if (pdf != undefined) {
          flush();
          this.push(out, pdf, child);
          continue;
        }
      }
      if (!leadsToStart && !leadsToEnd && isSkipped(child)) {
        continue;
      }
      if (!this._started) {
        if (child === this._start) {
          this._started = true;
        } else {
          if (leadsToStart) {
            this.walkContainer(child, out, linkOf(child) ?? link);
          }
          continue;
        }
      }

      if (child instanceof HTMLImageElement) {
        const spriteAlt = this.spriteAltOf(child);
        if (spriteAlt != undefined) {
          run.push(" ", spriteAlt, " ");
          runSource ??= child;
        } else {
          flush();
          const image = this.imageOf(child);
          if (image != undefined) {
            this.push(out, image, child);
          }
        }
      } else if (!leadsToEnd && (child.localName === "br" || this.isInline(child))) {
        run.push(...this.inlineOf(child));
        runSource ??= child;
      } else {
        flush();
        this.handleBlock(child, out, link);
      }
    }
    flush();
  }

  private handleBlock(
    element: Element,
    out: LightBlock[],
    link: LinkContext | undefined,
  ) {
    const tag = element.localName;
    const headingMatch = /^h([1-6])$/u.exec(tag);
    if (headingMatch != null) {
      const inlines = normalizeInlines(this.inlineChildren(element));
      if (hasText(inlines)) {
        this.push(
          out,
          {
            type: "heading",
            level: Number(headingMatch[1]) as 1 | 2 | 3 | 4 | 5 | 6,
            c: wrapInLink(inlines, link),
          },
          element,
        );
      }
      this.flushPendingBlocks(out);
    } else if (tag === "pre") {
      const text = (element.textContent || "").replace(/^\n+|\s+$/gu, "");
      if (text !== "") {
        this.push(out, { type: "pre", text }, element);
      }
    } else if (tag === "blockquote") {
      const inner: LightBlock[] = [];
      this.walkContainer(element, inner, link);
      // Already counted and anchored by walkContainer: moved as-is.
      for (const block of inner) {
        out.push(
          block.type === "paragraph"
            ? { type: "quote", c: block.c, a: block.a, lang: block.lang }
            : block,
        );
      }
    } else if (tag === "ul" || tag === "ol") {
      this.handleList(element, out, link, tag === "ol");
    } else {
      this.walkContainer(element, out, linkOf(element) ?? link);
    }
  }

  private handleList(
    list: Element,
    out: LightBlock[],
    link: LinkContext | undefined,
    ordered: boolean,
  ) {
    const items: LightListItem[] = [];
    for (const child of list.children) {
      if (this._done) {
        break;
      }
      if (child === this._end) {
        this._done = true;
        break;
      }
      if (child.localName !== "li" || isSkipped(child)) {
        continue;
      }
      const inner: LightBlock[] = [];
      this.walkContainer(child, inner, link);
      const first = inner[0];
      const c = first?.type === "paragraph" ? first.c : [];
      const children = first?.type === "paragraph" ? inner.slice(1) : inner;
      if (c.length > 0 || children.length > 0) {
        items.push({ c, children, a: this.anchor(child) });
      }
    }
    if (items.length > 0) {
      this.push(out, { type: "list", ordered, items }, list);
    }
  }
}

/**
 * Extrait le contenu lisible de la page, du premier h1 (inclus), ou à défaut du premier main, jusqu'au footer
 * du site (exclu). Tableaux, formulaires, nav, aside et contenus masqués sont ignorés.
 * @param {Document} doc - Le document de la page hôte
 * @returns {LightExtraction | undefined} Les blocs extraits et leurs éléments source, ou `undefined` s'il n'y a ni h1 ni main, ou pas de footer
 */
function extractLightContent(doc: Document): LightExtraction | undefined {
  const start = findStart(doc);
  if (start == undefined) {
    return undefined;
  }
  const end = findEnd(doc, start);
  if (end == undefined) {
    return undefined;
  }
  return new LightExtractor(start, end, doc.body).extract(doc.body);
}

export { extractLightContent };
export type { LightExtraction };
