const PDF_MIME = "application/pdf";
const ALLOWED_PDF_PROTOCOLS = new Set(["http:", "https:"]);
const PDF_PATH_RE = /\.pdf$/iu;

/**
 * La page elle-même est un PDF (visionneuse PDF du navigateur).
 * @param {Document} doc - Le document de la page hôte
 * @returns {boolean} `true` si le document est un PDF
 */
function isPdfDocument(doc: Document): boolean {
  return doc.contentType === PDF_MIME;
}

function httpUrl(url: string): URL | undefined {
  try {
    const parsed = new URL(url);
    return ALLOWED_PDF_PROTOCOLS.has(parsed.protocol) ? parsed : undefined;
  } catch {
    return undefined;
  }
}

/**
 * URL absolue du PDF affiché par un `<embed>`, `<object>` ou `<iframe>`.
 * @param {Element} element - Élément de la page hôte
 * @returns {string | undefined} L'URL http(s) du PDF, ou `undefined` si l'élément n'affiche pas de PDF
 */
function pdfSourceOf(element: Element): string | undefined {
  let src: string;
  let type = "";
  if (element instanceof HTMLEmbedElement) {
    src = element.src;
    type = element.type;
  } else if (element instanceof HTMLObjectElement) {
    src = element.data;
    type = element.type;
  } else if (element instanceof HTMLIFrameElement) {
    src = element.src;
  } else {
    return undefined;
  }
  const url = httpUrl(src);
  if (url == undefined) {
    return undefined;
  }
  return type.toLowerCase() === PDF_MIME || PDF_PATH_RE.test(url.pathname)
    ? url.href
    : undefined;
}

/**
 * Titre d'un PDF intégré : son `title` / `aria-label`, sinon le nom du fichier.
 * @param {Element} element - Élément qui affiche le PDF
 * @param {string} src - URL du PDF
 * @returns {string} Le titre à afficher
 */
function pdfTitleOf(element: Element, src: string): string {
  const label = (
    element.getAttribute("title") ||
    element.getAttribute("aria-label") ||
    ""
  ).trim();
  if (label !== "") {
    return label;
  }
  const fileName = new URL(src).pathname.split("/").pop() || "";
  try {
    return decodeURIComponent(fileName) || "Document PDF";
  } catch {
    return fileName || "Document PDF";
  }
}

export { isPdfDocument, pdfSourceOf, pdfTitleOf };
