import { ReaderObject } from "../adapters/reader/lisio-reader-adapter";
import {
  createCalendar,
  createForm,
  createImage,
  createTable,
  createVideo,
  domParser,
  handleOnClick,
  intersectionObserver,
} from "../reading-mode";

/**
 * Appends a single leaf `ReaderObject` into `parent`. This is the v2
 * counterpart of the per-tag dispatch inline in `reading-mode.ts`'s
 * BCMR_INIT_HTML handler (img/video/table/form/embed/calendar/generic),
 * deliberately duplicated rather than sharing code with it, so the existing
 * flat v1 rendering path is never at risk of being disturbed by v2 work —
 * with the flag off, v1 code isn't touched at all.
 *
 * Unlike v1, this does NOT do cross-item dropdown/slider grouping: block
 * kinds already provide that grouping semantically (header/footer/aside
 * collapse as whole blocks; detected carousels are collapsed into a single
 * `gallery` block — see structure/gallery-detect.ts — and rendered by
 * renderGallery instead of appearing here as loose leaves).
 *
 * `forceVisible` lets a caller render an image regardless of its source-page
 * `isHidden` flag: renderGallery uses it for every one of a carousel's own
 * slides, since all but the active one were hidden on the source page by
 * design. Outside of that, a hidden image is left out of Reading Mode
 * entirely — if it was hidden on the website, it stays hidden here too.
 */
export function renderLeaf(
  tag: ReaderObject,
  parent: HTMLElement,
  calendarLang: "fr" | "en",
  forceVisible = false,
): void {
  if (tag.name === "img") {
    if (tag.isHidden && !forceVisible) return;
    try {
      const img = createImage(tag, undefined, undefined, false);
      if (img != undefined) parent.append(img);
    } catch (error) {
      console.log(error, tag);
    }
    return;
  }

  if (tag.name === "video") {
    try {
      const video = createVideo(tag, undefined, undefined, false);
      if (video != undefined) parent.append(video);
    } catch (error) {
      console.log(error, tag);
    }
    return;
  }

  if (tag.name === "table") {
    createTable(tag, parent);
    return;
  }

  if (tag.name === "form") {
    if (tag.isHidden && !forceVisible) return;
    createForm(tag, parent, calendarLang);
    return;
  }

  if (tag.name === "object" || tag.name === "embed" || tag.name === "iframe") {
    const element = document.createElement(
      tag.name === "iframe" &&
        tag.src != "" &&
        !["youtube", "cdpn", "maps"].some((origin) =>
          new URL(tag.src || "localhost").origin.includes(origin),
        )
        ? "lisio-iframe"
        : tag.name,
    );
    element.dataset.position = tag.position.toString();
    if (element instanceof HTMLEmbedElement || element instanceof HTMLIFrameElement) {
      if (element instanceof HTMLIFrameElement) {
        if (tag.src != "" && new URL(tag.src || "localhost").origin.includes("youtube")) {
          element.srcdoc = `<style>*{padding:0;margin:0;overflow:hidden}html,body{height:100%}img,span{position:absolute;width:100%;top:0;bottom:0;margin:auto}span{height:1.5em;text-align:center;font:48px/1.5 sans-serif;color:white;text-shadow:0 0 0.5em black}</style><a href="${
            tag.src
          }"><img src="${
            import.meta.env.VITE_LISIO_DOMAIN
          }/solution/assets/youtube-placeholder.webp" alt='Cliquez 2 fois sur la vidéo pour lancer la lecture'><span>▶</span></a>`;
        }
        element.setAttribute("loading", tag.loading || "true");
      }
      element.src = tag.src || "";
    } else if (element instanceof HTMLObjectElement) {
      element.data = tag.src || "";
    }
    element.setAttribute("width", tag.width || "-1");
    element.setAttribute("height", tag.height || "-1");
    parent.append(element);
    return;
  }

  if (tag.name === "calendar") {
    createCalendar(tag, parent, calendarLang);
    return;
  }

  const parsed = domParser.parseFromString(tag.content || "", "text/html");
  const element = document.createElement(tag.name || "div");
  for (const child of parsed.body.childNodes) {
    if (child.textContent?.trim() != "") {
      element.append(child.cloneNode(true));
    }
  }
  element.className = tag.classes || "";
  element.dataset.position = tag.position.toString();
  if (tag.name === "a") {
    element.dataset.blank = tag.blank;
    element.dataset.href = tag.href;
  }
  parent.append(element);
  if (tag.clickable != undefined) {
    element.dataset.clickable = tag.clickable.toString();
    element.addEventListener("click", handleOnClick);
  }
  for (const child of element.querySelectorAll<HTMLElement>("[data-lisio-clickable]")) {
    child.dataset.clickable = child.dataset.lisioClickable;
    child.removeAttribute("data-lisio-clickable");
  }
  for (const child of element.querySelectorAll<HTMLElement>("[data-clickable]")) {
    child.addEventListener("click", handleOnClick);
  }
  intersectionObserver.observe(element);
}
