import { getReadableText, isUnreadableElement } from "../../../utils/lisio-readable-dom";
import { CardSlots } from "./block-types";
import { GeometryProvider } from "./geometry-provider";

const META_RE =
  /^\s*(\d{1,2}[/.-]\d{1,2}[/.-]\d{2,4}|\d+\s*(min|€|\$|%)|\d{4})\s*$/;

function isReadable(el: Element): boolean {
  return (
    (el instanceof HTMLElement || el instanceof SVGElement) &&
    !isUnreadableElement(el)
  );
}

/**
 * Maps a detected card's element to leaf `position`s for title/image/
 * summary/link/meta. `positionOf` returns undefined for elements that are
 * not themselves entries of `readerAdapter.all` (e.g. a `<div>` wrapper);
 * only text/media leaves have a meaningful position.
 */
export function extractCardSlots(
  card: Element,
  positionOf: (el: Element) => number | undefined,
  geo?: GeometryProvider,
): CardSlots {
  const slots: CardSlots = {};
  const usedElements = new Set<Element>();

  const heading = Array.from(card.querySelectorAll<HTMLElement>("h1,h2,h3,h4,h5,h6")).find(
    (el) => isReadable(el) && getReadableText(el).trim() !== "",
  );
  const anchors = Array.from(card.querySelectorAll<HTMLAnchorElement>("a[href]")).filter(isReadable);
  const titleAnchor = anchors.find((a) => getReadableText(a).trim().length >= 8);

  let titleEl: Element | undefined = heading;
  if (titleEl == undefined && titleAnchor != undefined) {
    titleEl = titleAnchor;
  }
  if (titleEl == undefined) {
    const candidates = Array.from(card.querySelectorAll<HTMLElement>("*")).filter(
      (el) => isReadable(el) && el.children.length === 0,
    );
    titleEl = candidates.find((el) => {
      const text = getReadableText(el).trim();
      return text.length > 0 && text.length < 120;
    });
  }
  if (titleEl != undefined) {
    let pos = positionOf(titleEl);
    if (pos == undefined) {
      // `titleEl` is a wrapper (e.g. `<h3><a data-lisio-position="…">…</a></h3>`)
      // that isn't itself a `readerAdapter.all` entry, so it has no position
      // of its own. Fall back to the positioned leaf inside it — preferring
      // the title anchor, since that's the element `linkEl` below would
      // otherwise grab on its own, leaving the title unrendered and the
      // anchor misfiled into the "read more" link slot instead.
      const inner =
        titleAnchor != undefined && titleEl.contains(titleAnchor)
          ? titleAnchor
          : Array.from(titleEl.querySelectorAll<HTMLElement>("*")).find(
              (el) => positionOf(el) != undefined,
            );
      if (inner != undefined) {
        pos = positionOf(inner);
        titleEl = inner;
      }
    }
    if (pos != undefined) {
      slots.title = pos;
      usedElements.add(titleEl);
    }
  }

  const images = Array.from(
    card.querySelectorAll<HTMLElement>("img, picture, svg, figure"),
  ).filter(isReadable);
  let imageEl: Element | undefined;
  if (images.length === 1) {
    imageEl = images[0];
  } else if (images.length > 1 && geo != undefined) {
    let bestArea = -1;
    for (const img of images) {
      const rect = geo.measure(img);
      const area = rect ? rect.width * rect.height : 0;
      if (area > bestArea) {
        bestArea = area;
        imageEl = img;
      }
    }
  } else if (images.length > 1) {
    imageEl = images[0];
  }
  if (imageEl != undefined) {
    const pos = positionOf(imageEl);
    if (pos != undefined) {
      slots.image = pos;
      usedElements.add(imageEl);
    }
  }

  const linkEl =
    card instanceof HTMLAnchorElement
      ? card
      : (titleAnchor ?? anchors[0]);
  if (linkEl != undefined) {
    const pos = positionOf(linkEl);
    if (pos != undefined) {
      slots.link = pos;
    }
  }

  const paragraphs = Array.from(card.querySelectorAll<HTMLElement>("p")).filter(
    (el) => isReadable(el) && !usedElements.has(el),
  );
  const summaryEl =
    paragraphs.find((el) => getReadableText(el).trim().length >= 40) ?? paragraphs[0];
  if (summaryEl != undefined) {
    const pos = positionOf(summaryEl);
    if (pos != undefined) {
      slots.summary = pos;
      usedElements.add(summaryEl);
    }
  }

  const metaCandidates = Array.from(card.querySelectorAll<HTMLElement>("time, span, small"))
    .filter((el) => isReadable(el) && !usedElements.has(el))
    .filter((el) => META_RE.test(getReadableText(el).trim()));
  if (metaCandidates.length > 0) {
    const metaPositions = metaCandidates
      .map((el) => positionOf(el))
      .filter((p): p is number => p != undefined);
    if (metaPositions.length > 0) slots.meta = metaPositions;
  }

  return slots;
}
