import { renderLeaf } from "../render-leaf";
import { BlockTreeNode } from "../block-tree";
import { RenderContext } from "../render-context";

/**
 * Renders a detected slider/carousel (see structure/gallery-detect.ts) as
 * ONE image container behind previous/next buttons that step through the
 * source page's slides, instead of dumping every slide — including the
 * ones the source page kept hidden off-screen — as loose inline images.
 * Each slide's own caption/legend leaves travel with it and swap in and
 * out together with its image (`renderLeaf(..., forceVisible: true)`,
 * since a slide's image is `isHidden` on the source page for every slide
 * but the one initially shown).
 */
export function renderGallery(block: BlockTreeNode, ctx: RenderContext, parent: HTMLElement): void {
  const slideGroups = block.gs;
  if (slideGroups == undefined || slideGroups.length === 0) return;

  const leavesByPosition = new Map(ctx.leavesOf(block).map((leaf) => [leaf.position, leaf]));

  const slides = slideGroups
    .map((positions) =>
      positions
        .map((position) => leavesByPosition.get(position))
        .filter((leaf): leaf is NonNullable<typeof leaf> => leaf != undefined),
    )
    .filter((leaves) => leaves.length > 0);
  if (slides.length === 0) return;

  const figure = document.createElement("figure");
  figure.className = "lisio-gallery";

  const viewport = document.createElement("div");
  viewport.className = "lisio-gallery-viewport";

  const slideElements = slides.map((leaves) => {
    const slide = document.createElement("div");
    slide.className = "lisio-gallery-slide";
    for (const leaf of leaves) renderLeaf(leaf, slide, ctx.calendarLang, true);
    return slide;
  });

  const counter = document.createElement("span");
  counter.className = "lisio-gallery-counter";

  let active = block.ga != undefined && block.ga >= 0 && block.ga < slideElements.length ? block.ga : 0;

  function show(index: number): void {
    active = (index + slideElements.length) % slideElements.length;
    viewport.replaceChildren(slideElements[active]);
    counter.textContent = `${active + 1} / ${slideElements.length}`;
  }

  figure.append(viewport);

  if (slideElements.length > 1) {
    const nav = document.createElement("div");
    nav.className = "lisio-gallery-nav";

    const prev = document.createElement("button");
    prev.type = "button";
    prev.className = "lisio-gallery-prev";
    prev.setAttribute("aria-label", "Image précédente");
    prev.textContent = "‹";
    prev.addEventListener("click", () => show(active - 1));

    const next = document.createElement("button");
    next.type = "button";
    next.className = "lisio-gallery-next";
    next.setAttribute("aria-label", "Image suivante");
    next.textContent = "›";
    next.addEventListener("click", () => show(active + 1));

    nav.append(prev, counter, next);
    figure.append(nav);
  }

  show(active);
  if (viewport.childNodes.length > 0) parent.append(figure);
}
