console.log("FRONTEND chapter.js loaded")

document.addEventListener("DOMContentLoaded", async () => {
  const params = new URLSearchParams(window.location.search)
  const chapterId = params.get("chapterId")

  if (!chapterId) return

  const contentContainer = document.getElementById("contentContainer")
  const contentTitle = document.getElementById("contentTitle")
  const buttons = document.querySelectorAll(".option-btn")

  let allLectures = []

  function groupByTopic(lectures) {
    const map = {}

    lectures.forEach(l => {
      if (!map[l.topicTitle]) {
        map[l.topicTitle] = []
      }
      map[l.topicTitle].push(l)
    })

    return map
  }

  function render(type) {
    contentContainer.innerHTML = ""

    const filtered = allLectures.filter(l => {
      if (type === "recorded") return l.contentType === "RECORDED"
      if (type === "live") return l.contentType === "LIVE"
      if (type === "pdfs") return l.contentType === "PDF"
    })

    if (!filtered.length) {
      contentContainer.innerHTML = "<p>No lecture uploaded at the moment</p>"
      return
    }

    const grouped = groupByTopic(filtered)

    Object.keys(grouped).forEach(topic => {

      const topicDiv = document.createElement("div")
      topicDiv.className = "topic-block"

      const topicHeader = document.createElement("div")
      topicHeader.className = "topic-header"
      topicHeader.innerText = topic

      const lectureList = document.createElement("div")
      lectureList.className = "topic-lectures"
      lectureList.style.display = "none"

      topicHeader.onclick = () => {

        const allTopics = document.querySelectorAll(".topic-block")

        allTopics.forEach(t => {
          if (t !== topicDiv) {
            t.classList.remove("open")
            const list = t.querySelector(".topic-lectures")
            if (list) list.style.display = "none"
          }
        })

        const isOpen = topicDiv.classList.toggle("open")

        lectureList.style.display = isOpen ? "block" : "none"
      }

      grouped[topic].forEach(lecture => {

        const div = document.createElement("div")
        div.className = "lecture-item"
        div.innerText = lecture.title

        div.onclick = () => {
          if (lecture.contentType === "LIVE") {
            window.open(lecture.contentUrl, "_blank")
            return
          }

          if (lecture.contentType === "PDF") {
            window.location.href = `pdf.html?lectureId=${lecture._id}&chapterId=${chapterId}`
            return
          }

          window.location.href = `player.html?lectureId=${lecture._id}&chapterId=${chapterId}`
        }

        lectureList.appendChild(div)
      })

      topicDiv.appendChild(topicHeader)
      topicDiv.appendChild(lectureList)
      contentContainer.appendChild(topicDiv)
    })
  }

  try {
    const token = localStorage.getItem("token")

    const topicRes = await fetch(`http://127.0.0.1:5000/api/user/topics/${chapterId}`, {
      headers: {
        "Authorization": `Bearer ${token}`
      }
    })
    const topics = await topicRes.json()

    console.log("Topic loaded:", topics)

    for (const topic of topics) {

      const token = localStorage.getItem("token")

      const lecturesRes = await fetch(`http://127.0.0.1:5000/api/user/lectures/topic/${topic._id}`, {
        headers: {
          "Authorization": `Bearer ${token}`
        }
      })

      const lectures = await lecturesRes.json()

      lectures.forEach(l => {
        l.topicTitle = topic.title
        allLectures.push(l)
      })
    }

    // default load
    contentTitle.innerText = "Recorded Lectures"
    render("recorded")

    // button click logic
    buttons.forEach(btn => {
      btn.onclick = () => {
        buttons.forEach(b => b.classList.remove("active"))
        btn.classList.add("active")

        const type = btn.dataset.type

        if (type === "recorded") contentTitle.innerText = "Recorded Lectures"
        if (type === "live") contentTitle.innerText = "Live Sessions"
        if (type === "pdfs") contentTitle.innerText = "PDFs"

        render(type)
      }
    })

  } catch (err) {
    console.error(err)
    contentContainer.innerHTML = "<p>Error loading lectures</p>"
  }
})
