const READABLE_HIDDEN_CLASSES =
  /\b(?:sr-only(?:-list)?|visually-hidden|visuallyhidden|screen-reader(?:-text)?|screenreader)\b/i;
const READABLE_STRUCTURED_DATA = /^\s*(?:\{[\s\S]*\}|\[[\s\S]*\])\s*$/u;
const READABLE_TEXT_CONTAINERS = new Set([
  "code",
  "kbd",
  "pre",
  "samp",
  "textarea",
]);
const READABLE_SKIPPED_TAGS = new Set([
  "NOSCRIPT",
  "SCRIPT",
  "STYLE",
  "TEMPLATE",
]);

function collapseReadableWhitespace(text: string): string {
  return text.replace(/\s+/gu, " ").trim();
}

function looksLikeStructuredData(text: string): boolean {
  const trimmed = text.trim();
  if (!READABLE_STRUCTURED_DATA.test(trimmed)) {
    return false;
  }

  const hasObjectShape =
    /"(?:[^"\\]|\\.)+"\s*:/.test(trimmed) ||
    /'(?:[^'\\]|\\.)+'\s*:/.test(trimmed);
  if (!hasObjectShape) {
    return false;
  }

  try {
    JSON.parse(trimmed);
    return true;
  } catch {
    return false;
  }
}

function hasScreenReaderOnlyStyles(element: HTMLElement | SVGElement): boolean {
  const styles = window.getComputedStyle(element);
  const width = Number.parseFloat(styles.width || "0");
  const height = Number.parseFloat(styles.height || "0");
  const clip = styles.clip;
  const clipPath = styles.clipPath;

  return (
    styles.overflow === "hidden" &&
    width <= 1 &&
    height <= 1 &&
    (clip !== "auto" || clipPath !== "none")
  );
}

function pruneCloneNodes(sourceParent: Node, cloneParent: Node): void {
  const sourceChildren = Array.from(sourceParent.childNodes);
  let cloneIndex = 0;

  for (const sourceChild of sourceChildren) {
    const cloneChild = cloneParent.childNodes[cloneIndex];
    if (cloneChild == undefined) {
      break;
    }

    if (sourceChild.nodeType === Node.TEXT_NODE) {
      if (
        !shouldKeepReadableText(
          sourceChild.textContent,
          sourceParent instanceof Element ? sourceParent : null,
        )
      ) {
        cloneChild.remove();
        continue;
      }
      cloneIndex++;
      continue;
    }

    if (
      sourceChild.nodeType === Node.ELEMENT_NODE &&
      cloneChild.nodeType === Node.ELEMENT_NODE &&
      (sourceChild instanceof HTMLElement || sourceChild instanceof SVGElement) &&
      (cloneChild instanceof HTMLElement || cloneChild instanceof SVGElement)
    ) {
      if (isUnreadableElement(sourceChild)) {
        cloneChild.remove();
        continue;
      }
      pruneCloneNodes(sourceChild, cloneChild);
      cloneIndex++;
      continue;
    }

    cloneChild.remove();
  }

  while (cloneParent.childNodes.length > cloneIndex) {
    cloneParent.lastChild?.remove();
  }
}

function isReadableTextContainer(element: Element | null | undefined): boolean {
  return (
    element != undefined &&
    READABLE_TEXT_CONTAINERS.has(element.localName.toLowerCase())
  );
}

function shouldStripByAria(element: HTMLElement | SVGElement): boolean {
  return element.getAttribute("aria-hidden") === "true";
}

export function shouldKeepReadableText(
  text: string | null | undefined,
  parentElement?: Element | null,
): boolean {
  const trimmed = text?.trim() || "";
  if (trimmed === "") {
    return false;
  }

  if (isReadableTextContainer(parentElement)) {
    return true;
  }

  return !looksLikeStructuredData(trimmed);
}

export function isUnreadableElement(element: HTMLElement | SVGElement): boolean {
  return isHiddenElement(element) || isScreenReaderOnlyElement(element);
}

/** Élément dont le contenu n'est jamais du texte (script, style…). */
export function isNonTextElement(element: Element): boolean {
  return READABLE_SKIPPED_TAGS.has(element.tagName);
}

/** Élément masqué pour tout le monde, technologies d'assistance comprises. */
export function isHiddenElement(element: HTMLElement | SVGElement): boolean {
  if (READABLE_SKIPPED_TAGS.has(element.tagName)) {
    return true;
  }

  if (shouldStripByAria(element)) {
    return true;
  }

  if (element instanceof HTMLElement && element.hidden) {
    return true;
  }

  const styles = window.getComputedStyle(element);
  return (
    styles.display === "none" ||
    styles.visibility === "hidden" ||
    Number.parseFloat(styles.opacity || "1") === 0
  );
}

/** Élément masqué visuellement mais destiné aux lecteurs d'écran (sr-only, show-for-sr…). */
export function isScreenReaderOnlyElement(
  element: HTMLElement | SVGElement,
): boolean {
  const className =
    typeof element.className === "string"
      ? element.className
      : element.getAttribute("class") || "";
  return (
    READABLE_HIDDEN_CLASSES.test(className) || hasScreenReaderOnlyStyles(element)
  );
}

export function cloneReadableElement<T extends HTMLElement | SVGElement>(
  source: T,
): T {
  const clone = source.cloneNode(true) as T;
  if (isUnreadableElement(source)) {
    clone.textContent = "";
    return clone;
  }

  pruneCloneNodes(source, clone);
  return clone;
}

export function getReadableText(source: HTMLElement | SVGElement): string {
  if (
    source instanceof HTMLInputElement ||
    source instanceof HTMLTextAreaElement
  ) {
    return collapseReadableWhitespace(source.value);
  }

  const clone = cloneReadableElement(source);
  return collapseReadableWhitespace(clone.textContent || "");
}
