import {
  LightBlock,
  LightInline,
  LightListItem,
} from "../adapters/reader/light-reader-types";

type LinkClickHandler = (event: MouseEvent, href: string, blank: boolean) => void;

function renderInlines(
  inlines: LightInline[],
  parent: HTMLElement,
  onLinkClick: LinkClickHandler,
) {
  const doc = parent.ownerDocument;
  for (const inline of inlines) {
    if (typeof inline === "string") {
      parent.append(doc.createTextNode(inline));
    } else if (inline.t === "br") {
      parent.append(doc.createElement("br"));
    } else if (inline.t === "a") {
      const a = doc.createElement("a");
      a.href = inline.href;
      a.dataset.blank = String(inline.blank);
      a.addEventListener("click", (event) =>
        onLinkClick(event, inline.href, inline.blank),
      );
      renderInlines(inline.c, a, onLinkClick);
      parent.append(a);
    } else {
      const element = doc.createElement(inline.t);
      renderInlines(inline.c, element, onLinkClick);
      parent.append(element);
    }
  }
}

/** `data-anchor` : ancre de l'élément source sur la page hôte (défilement synchronisé). */
function setAnchor(element: HTMLElement, anchor: number | undefined) {
  if (anchor != undefined) {
    element.dataset.anchor = String(anchor);
  } else {
    delete element.dataset.anchor;
  }
}

/** Bloc de premier niveau affiché, gardé pour les mises à jour (updateLightContent). */
interface RenderedBlock {
  // Éléments qui portent une ancre (bloc, items de liste…), dans l'ordre de anchorsOf.
  anchorSlots: HTMLElement[];
  element: HTMLElement;
  key: string;
}

const renderedBlocks = new WeakMap<HTMLElement, RenderedBlock[]>();

/** Contenu du bloc sans ses ancres : les ancres se décalent dès qu'un bloc précédent change. */
function keyOf(block: LightBlock): string {
  return JSON.stringify(block, (name, value: unknown) =>
    name === "a" ? undefined : value,
  );
}

/** Ancres du bloc, dans l'ordre où renderBlock remplit `anchorSlots`. */
function anchorsOf(block: LightBlock): (number | undefined)[] {
  if (block.type === "pdf") {
    return [];
  }
  const anchors: (number | undefined)[] = [block.a];
  if (block.type === "list") {
    for (const item of block.items) {
      anchors.push(item.a, ...item.children.flatMap(anchorsOf));
    }
  }
  return anchors;
}

function renderListItem(
  item: LightListItem,
  list: HTMLElement,
  onLinkClick: LinkClickHandler,
  anchorSlots: HTMLElement[],
) {
  const li = list.ownerDocument.createElement("li");
  setAnchor(li, item.a);
  anchorSlots.push(li);
  if (item.children.length > 0 && item.c.length > 0) {
    // Pas de texte à la racine d'un li qui contient des blocs : les adaptateurs (taille de police…)
    // s'appliqueraient au li entier et ses blocs hériteraient de la taille déjà agrandie
    const text = li.ownerDocument.createElement("p");
    renderInlines(item.c, text, onLinkClick);
    li.append(text);
  } else {
    renderInlines(item.c, li, onLinkClick);
  }
  for (const child of item.children) {
    const element = renderBlock(child, li.ownerDocument, onLinkClick, anchorSlots);
    if (element != undefined) {
      li.append(element);
    }
  }
  list.append(li);
}

function renderBlock(
  block: LightBlock,
  doc: Document,
  onLinkClick: LinkClickHandler,
  anchorSlots: HTMLElement[],
): HTMLElement | undefined {
  let element: HTMLElement;
  switch (block.type) {
    case "heading":
      element = doc.createElement(`h${block.level}`);
      break;
    case "paragraph":
      element = doc.createElement("p");
      break;
    case "quote":
      element = doc.createElement("blockquote");
      break;
    case "pre":
      element = doc.createElement("pre");
      element.textContent = block.text;
      break;
    case "list":
      element = doc.createElement(block.ordered ? "ol" : "ul");
      break;
    case "image": {
      const img = doc.createElement("img");
      img.src = block.src;
      img.alt = block.alt;
      img.setAttribute("loading", "lazy");
      element = img;
      break;
    }
    case "pdf":
      // Toujours résolu par la page hôte avant l'envoi.
      return undefined;
  }
  // Le bloc avant ses items de liste : même ordre que anchorsOf.
  setAnchor(element, block.a);
  anchorSlots.push(element);
  if (block.type === "list") {
    for (const item of block.items) {
      renderListItem(item, element, onLinkClick, anchorSlots);
    }
  } else if (
    block.type === "heading" ||
    block.type === "paragraph" ||
    block.type === "quote"
  ) {
    renderInlines(block.c, element, onLinkClick);
  }
  if (block.lang != undefined) {
    element.lang = block.lang;
  }
  return element;
}

function renderTopLevel(
  block: LightBlock,
  doc: Document,
  onLinkClick: LinkClickHandler,
): RenderedBlock | undefined {
  const anchorSlots: HTMLElement[] = [];
  const element = renderBlock(block, doc, onLinkClick, anchorSlots);
  return element == undefined
    ? undefined
    : { element, key: keyOf(block), anchorSlots };
}

/**
 * Affiche le contenu du mode lecture allégé. Le DOM est construit uniquement
 * avec createElement/textContent : aucun contenu de la page hôte n'est parsé en HTML.
 * @param {LightBlock[]} blocks - Blocs extraits par light-extract.ts
 * @param {HTMLElement} container - Élément qui reçoit le contenu
 * @param {LinkClickHandler} onLinkClick - Appelé au clic sur un lien
 */
function renderLightContent(
  blocks: LightBlock[],
  container: HTMLElement,
  onLinkClick: LinkClickHandler,
) {
  const rendered: RenderedBlock[] = [];
  for (const block of blocks) {
    const result = renderTopLevel(block, container.ownerDocument, onLinkClick);
    if (result != undefined) {
      container.append(result.element);
      rendered.push(result);
    }
  }
  renderedBlocks.set(container, rendered);
}

/**
 * Met à jour un contenu déjà affiché par renderLightContent : les blocs
 * inchangés gardent leurs éléments (et les adaptations Lisio qu'ils portent),
 * seuls les blocs modifiés sont recréés. Sans cela, chaque renvoi de la page
 * (ex. carrousel qui tourne) reconstruit tout le lecteur, qui clignote le temps
 * d'être ré-adapté. Seules les ancres des blocs gardés sont réécrites.
 * @param {LightBlock[]} blocks - Nouveaux blocs extraits par light-extract.ts
 * @param {HTMLElement} container - Élément déjà rempli par renderLightContent
 * @param {LinkClickHandler} onLinkClick - Appelé au clic sur un lien
 */
function updateLightContent(
  blocks: LightBlock[],
  container: HTMLElement,
  onLinkClick: LinkClickHandler,
) {
  const previous = renderedBlocks.get(container);
  // Conteneur vidé ou remplacé depuis (message d'erreur, « clear »…) : rendu complet.
  if (
    previous == undefined ||
    previous.some(({ element }) => element.parentNode !== container)
  ) {
    container.textContent = "";
    renderLightContent(blocks, container, onLinkClick);
    return;
  }
  const reusable = new Map<string, RenderedBlock[]>();
  for (const block of previous) {
    const sameKey = reusable.get(block.key) ?? [];
    sameKey.push(block);
    reusable.set(block.key, sameKey);
  }
  const next: { block: LightBlock; reused?: RenderedBlock }[] = blocks.map(
    (block) => ({ block, reused: reusable.get(keyOf(block))?.shift() }),
  );
  for (const unused of reusable.values()) {
    for (const { element } of unused) {
      element.remove();
    }
  }
  const rendered: RenderedBlock[] = [];
  let cursor = container.firstChild;
  for (const { block, reused } of next) {
    let current = reused;
    if (current != undefined) {
      const anchors = anchorsOf(block);
      current.anchorSlots.forEach((slot, index) =>
        setAnchor(slot, anchors[index]),
      );
    } else {
      current = renderTopLevel(block, container.ownerDocument, onLinkClick);
      if (current == undefined) {
        continue;
      }
    }
    // Un élément déjà à sa place n'est pas déplacé (pas de mutation inutile).
    if (current.element === cursor) {
      cursor = cursor.nextSibling;
    } else {
      container.insertBefore(current.element, cursor);
    }
    rendered.push(current);
  }
  renderedBlocks.set(container, rendered);
}

export { renderLightContent, updateLightContent };
export type { LinkClickHandler };
