<script type="module">
const textarea = document.getElementById("id_content");
const imageInput = document.getElementById("id_image");
const processingMessage = document.getElementById("processing_message");

async function convertHeicToJpeg(file) {
  const heic2any = (
    await import("/-/static-plugins/datasette_extract/heic2any-0.0.4.min.js")
  ).default;
  try {
    const blob = await heic2any({
      blob: file,
      toType: "image/jpeg",
      quality: 0.8,
    });
    return new File([blob], `converted-${file.name}.jpeg`, {
      type: "image/jpeg",
    });
  } catch (error) {
    console.error("Conversion error:", error);
    return null;
  }
}

function dragOverHandler(event) {
  event.preventDefault();
  event.stopPropagation();
  textarea.classList.add("drag-over");
}

function dragLeaveHandler(event) {
  event.preventDefault();
  event.stopPropagation();
  textarea.classList.remove("drag-over");
}

async function dropHandler(event) {
  event.preventDefault();
  event.stopPropagation();
  textarea.classList.remove("drag-over");

  const files = Array.from(event.dataTransfer.files);
  const imageOrPdfFiles = files.filter((file) => file.type.startsWith("image/") || file.type === "application/pdf");
  const otherFiles = files.filter(
    (file) =>
      !file.type.startsWith("image/") && file.type !== "application/pdf",
  );

  if (imageOrPdfFiles.length > 0) {
    processingMessage.style.display = "block";
    const convertedImages = await Promise.all(
      imageOrPdfFiles.map(async (file) => {
        if (file.type === "image/heic") {
          return await convertHeicToJpeg(file);
        }
        return file;
      }),
    );
    const validImages = convertedImages.filter((file) => file !== null);
    if (validImages.length > 0) {
      const dataTransfer = new DataTransfer();
      validImages.forEach((file) => dataTransfer.items.add(file));
      imageInput.files = dataTransfer.files;
    }
    processingMessage.style.display = "none";
  }

  if (otherFiles.length > 0) {
    const otherContents = await Promise.all(
      otherFiles.map(
        (file) =>
          new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = (e) => {
              resolve(e.target.result);
            };
            reader.onerror = (e) => {
              reject(new Error("Failed to read file"));
            };
            reader.readAsText(file);
          }),
      ),
    );
    textarea.value +=
      (textarea.value ? "\n\n" : "") + otherContents.join("\n\n");
  }
}

imageInput.addEventListener("change", async (event) => {
  const file = event.target.files[0];
  if (file && file.type === "image/heic") {
    processingMessage.style.display = "block";
    const convertedFile = await convertHeicToJpeg(file);
    if (convertedFile) {
      const dataTransfer = new DataTransfer();
      dataTransfer.items.add(convertedFile);
      imageInput.files = dataTransfer.files;
    }
    processingMessage.style.display = "none";
  }
});

textarea.addEventListener("dragover", dragOverHandler);
textarea.addEventListener("dragleave", dragLeaveHandler);
textarea.addEventListener("drop", dropHandler);
</script>