function toDrivePreview(url) {
  if (!url) return ""

  if (url.includes("/preview")) return url

  if (url.includes("drive.google.com")) {
    const match = url.match(/\/d\/([^/]+)/)
    if (match && match[1]) {
      return `https://drive.google.com/file/d/${match[1]}/preview`
    }
  }

  return url
}

console.log("pdf.js loaded")

document.addEventListener("DOMContentLoaded", async () => {
  console.log("PDF DOM loaded")

  const params = new URLSearchParams(window.location.search)
  const lectureId = params.get("lectureId")
  const chapterId = params.get("chapterId")

  if (!lectureId || !chapterId) {
    console.warn("Missing lectureId or chapterId")
    return
  }

  const pdfListEl = document.getElementById("pdfList")
  const pdfTitleEl = document.getElementById("pdfTitle")
  const pdfContainer = document.getElementById("pdfContainer")

  try {
    // 1️⃣ Fetch all lectures of chapter
    const listRes = await fetch(
      `http://localhost:5000/api/user/lectures/${chapterId}`
    )
    const allLectures = await listRes.json()

    // 2️⃣ Filter ONLY PDFs
    const pdfLectures = allLectures.filter(
      lec => lec.contentType === "PDF"
    )

    if (!pdfLectures.length) {
      pdfTitleEl.innerText = "No PDFs available"
      return
    }

    // 3️⃣ Render LEFT SIDEBAR (Notes)
    pdfListEl.innerHTML = ""

    pdfLectures.forEach(pdf => {
      const div = document.createElement("div")
      div.className = "lecture-item"
      div.innerText = pdf.title

      if (pdf._id === lectureId) {
        div.classList.add("active")
      }

      div.onclick = () => {
        window.location.href =
          `pdf.html?lectureId=${pdf._id}&chapterId=${chapterId}`
      }

      pdfListEl.appendChild(div)
    })

    // 4️⃣ Fetch CURRENT PDF
    const pdfRes = await fetch(
      `http://localhost:5000/api/user/lectures/single/${lectureId}`
    )
    const pdfLecture = await pdfRes.json()

    if (!pdfLecture || pdfLecture.contentType !== "PDF") {
      pdfTitleEl.innerText = "Invalid PDF"
      return
    }

    // 5️⃣ Title
    pdfTitleEl.innerText = pdfLecture.title

    // 6️⃣ Render PDF iframe
    pdfContainer.innerHTML = ""

    const iframe = document.createElement("iframe")
    iframe.src = toDrivePreview(pdfLecture.contentUrl)
    iframe.style.width = "100%"
    iframe.style.height = "100%"
    iframe.frameBorder = "0"
    iframe.allow = "autoplay"

    pdfContainer.appendChild(iframe)

  } catch (err) {
    console.error("PDF page error:", err)
  }
})
