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

/** FR + EN carousel/slider vocabulary — same spirit as classify-block.ts's regexes. */
export const SLIDER_RE =
  /(^|[-_ ])(slider|carousel|swiper|slick|splide|owl-carousel|glide|diaporama|hero-slides?)([-_ ]|$)/i;

const MIN_SLIDES = 2;
const MOSTLY_HIDDEN_MIN = 3;
const STACK_TOLERANCE_PX = 4;

export interface SlideSignal {
  /** offsetParent-less / visibility:hidden / display:none / opacity:0 on the source page. */
  hidden: boolean;
  /** id/class of the slide or its container matches SLIDER_RE. */
  nameHit: boolean;
}

export interface GalleryVerdict {
  isGallery: boolean;
  /** Index of the first non-hidden slide, or 0 when none/all are hidden. */
  activeIndex: number;
}

/**
 * Pure decision: given per-slide hidden/name-match signals plus whether the
 * slides are geometrically stacked (same box on the page — only makes
 * sense if they're meant to be shown one at a time), decide whether this
 * repeat group of one-image elements is a carousel rather than an ordinary
 * run of inline images. Deliberately DOM-free so it's unit-testable exactly
 * like classifyBlock/fingerprint — the DOM-touching signal extraction lives
 * in `detectGallery` below.
 */
export function evaluateGallery(signals: SlideSignal[], stacked: boolean): GalleryVerdict {
  if (signals.length < MIN_SLIDES) return { isGallery: false, activeIndex: 0 };

  const hiddenCount = signals.filter((s) => s.hidden).length;
  const visibleCount = signals.length - hiddenCount;
  const nameHit = signals.some((s) => s.nameHit);
  // A run of >= 3 same-shaped image slides where the source page shows at
  // most one at a time is, on its own, already the definition of a
  // carousel — no id/class or geometry signal needed.
  const mostlyHidden = signals.length >= MOSTLY_HIDDEN_MIN && visibleCount <= 1 && hiddenCount >= 1;

  let activeIndex = signals.findIndex((s) => !s.hidden);
  if (activeIndex === -1) activeIndex = 0;

  return { isGallery: nameHit || stacked || mostlyHidden, activeIndex };
}

function idClassOf(el: Element): string {
  const className = typeof (el as HTMLElement).className === "string" ? (el as HTMLElement).className : "";
  return `${el.id} ${className}`.toLowerCase();
}

function isHiddenElement(el: Element): boolean {
  if (!(el instanceof HTMLElement)) return false;
  const styles = window.getComputedStyle(el);
  return (
    el.offsetParent == undefined ||
    styles.visibility === "hidden" ||
    styles.display === "none" ||
    parseFloat(styles.opacity) === 0
  );
}

export interface GalleryDetection {
  /** Per-slide leaf positions (image + any short caption), in slide order. */
  slideGroups: number[][];
  activeIndex: number;
}

/**
 * DOM-touching wrapper around `evaluateGallery`: finds which of `el`'s
 * split points are single-image slides, reads their hidden/name/geometry
 * signals straight off the live page, and — if the group reads as a
 * carousel — resolves each slide's own leaf positions (image + caption)
 * for the gallery renderer.
 *
 * Runs BEFORE classifyBlock/detectCardGroup in segment-page.ts: a carousel
 * has the exact same "repeated similar children" shape a cardList looks
 * for, but a fundamentally different intent (one slide visible at a time,
 * not a list to scan), so it must win the ambiguity outright rather than
 * be scored against cardList's rules.
 */
export function detectGallery(
  container: Element,
  points: HTMLElement[],
  geo: GeometryProvider,
  positionOf: (el: Element) => number | undefined,
): GalleryDetection | undefined {
  const slides = points
    .map((el) => {
      const img = el.matches("img") ? (el as unknown as HTMLImageElement) : el.querySelector<HTMLImageElement>("img");
      return img == undefined ? undefined : { el, img };
    })
    .filter((s): s is { el: HTMLElement; img: HTMLImageElement } => s != undefined);

  // A slide can carry a short caption, never prose of its own — otherwise
  // this is an article with inline images, not a carousel.
  if (slides.some(({ el }) => el.querySelectorAll("p, h1, h2, h3, h4, h5, h6").length > 1)) {
    return undefined;
  }

  const containerNameHit = SLIDER_RE.test(idClassOf(container));
  const signals: SlideSignal[] = slides.map(({ el }) => ({
    hidden: isHiddenElement(el),
    nameHit: containerNameHit || SLIDER_RE.test(idClassOf(el)),
  }));

  const geoms = slides.map(({ el }) => geo.measure(el));
  const stacked =
    geoms.length >= MIN_SLIDES &&
    geoms.every((g): g is BlockGeometry => g != undefined) &&
    geoms
      .slice(1)
      .every(
        (g) =>
          Math.abs(g.top - (geoms[0] as BlockGeometry).top) < STACK_TOLERANCE_PX &&
          Math.abs(g.left - (geoms[0] as BlockGeometry).left) < STACK_TOLERANCE_PX,
      );

  const verdict = evaluateGallery(signals, stacked);
  if (!verdict.isGallery) return undefined;

  const slideGroups = slides.map(({ el, img }) => {
    const slidePositions = new Set<number>();
    const imgPos = positionOf(img);
    if (imgPos != undefined) slidePositions.add(imgPos);
    for (const captionEl of el.querySelectorAll<HTMLElement>("figcaption, p, span, small")) {
      if (isUnreadableElement(captionEl) || getReadableText(captionEl).trim() === "") continue;
      const pos = positionOf(captionEl);
      if (pos != undefined) slidePositions.add(pos);
    }
    return Array.from(slidePositions).sort((a, b) => a - b);
  });

  return { slideGroups, activeIndex: verdict.activeIndex };
}
