document.addEventListener("DOMContentLoaded", function () {
  const pdfItems = document.querySelectorAll(".pdf-gallery-item");

  if (typeof window.pdfjsLib === "undefined") {
    console.error(
      "[FontAwesome] pdfjsLib non è disponibile. Assicurati che pdf.js sia caricato."
    );
    const errorIcon = document.createElement("i");
    errorIcon.className = "fas fa-exclamation-triangle";
    errorIcon.style.color = "red";
    errorIcon.style.marginRight = "6px";

    pdfItems.forEach((item) => {
      const iconContainer = item.querySelector(".pdf-icon");
      if (iconContainer) {
        iconContainer.innerHTML = "";
        iconContainer.appendChild(errorIcon.cloneNode(true));
        const message = document.createElement("span");
        message.textContent = " PDF non disponibile";
        iconContainer.appendChild(message);
      }
    });

    return;
  }

  pdfjsLib.GlobalWorkerOptions.workerSrc =
    "https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js";

  pdfItems.forEach((item) => {
    const url = item.getAttribute("data-url");
    const iconContainer = item.querySelector(".pdf-icon");

    if (!url || !iconContainer) return;

    pdfjsLib
      .getDocument(url)
      .promise.then((pdf) => {
        return pdf.getPage(1);
      })
      .then((page) => {
        const scale = 0.5;
        const viewport = page.getViewport({ scale });

        const canvas = document.createElement("canvas");
        const context = canvas.getContext("2d");
        canvas.width = viewport.width;
        canvas.height = viewport.height;

        return page
          .render({ canvasContext: context, viewport: viewport })
          .promise.then(() => {
            const img = document.createElement("img");
            img.src = canvas.toDataURL("image/png");
            img.alt = "Anteprima PDF";
            iconContainer.innerHTML = "";
            iconContainer.appendChild(img);
          });
      })
      .catch((err) => {
        console.error("Errore durante il rendering PDF:", err.message);

        // Mostra icona errore anche qui
        iconContainer.innerHTML = "";
        const errorIcon = document.createElement("i");
        errorIcon.className = "fas fa-exclamation-circle";
        errorIcon.style.color = "#dc3545";
        errorIcon.style.marginRight = "6px";

        iconContainer.appendChild(errorIcon);
        const message = document.createElement("span");
        message.textContent = " Impossibile caricare PDF";
        iconContainer.appendChild(message);
      });
  });
});
