let ytPlayer
let seek
let pendingVideoId = null
let seekTimer = null
let playing = false
let hideTimer = null

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

  if (!lectureId || !chapterId) return

  const titleEl = document.getElementById("lectureTitle")
  const lectureListEl = document.getElementById("lectureList")
  const notesListEl = document.getElementById("notesList")

  let lectures = []
  let currentIndex = -1

  try {
    const res = await fetch(`http://localhost:5000/api/user/lectures/${chapterId}`)
    lectures = await res.json()

    const lecture = lectures.find(l => l._id === lectureId)
    if (!lecture) return

    titleEl.innerText = lecture.title

    notesListEl.innerHTML = ""
    const pdfs = lectures.filter(l => l.contentType === "PDF")

    if (!pdfs.length) {
      notesListEl.innerHTML = "<p>No notes available</p>"
    } else {
      pdfs.forEach(pdf => {
        const a = document.createElement("a")
        a.href = `pdf.html?lectureId=${pdf._id}&chapterId=${chapterId}`
        a.innerText = pdf.title
        a.target = "_blank"
        notesListEl.appendChild(a)
      })
    }

    lectureListEl.innerHTML = ""
    const videoLectures = lectures.filter(l => l.contentType === "RECORDED")

    videoLectures.forEach((lec, idx) => {
      const div = document.createElement("div")
      div.className = "lecture-item"

      if (lec._id === lectureId) {
        div.classList.add("now-playing")
        currentIndex = idx
        div.innerHTML = `
          <div class="playing">
            <span></span><span></span><span></span><span></span>
          </div>
          <span class="now-text">Now Playing</span>
        `
      } else {
        div.textContent = ""
        const span = document.createElement("span")
        span.className = "lecture-title-text"
        span.textContent = lec.title
        div.appendChild(span)
      }

      div.onclick = () => {
        window.location.replace(
          `player.html?lectureId=${lec._id}&chapterId=${chapterId}`
        )
      }

      lectureListEl.appendChild(div)
    })

    window.__LECTURE_IDS__ = videoLectures.map(v => v._id)
    window.__CURRENT_INDEX__ = currentIndex

    if (lecture.contentType === "RECORDED") {
      const videoId = extractYoutubeId(lecture.contentUrl)
      loadYoutubePlayer(videoId)
    }
  } catch (e) {
    console.error(e)
  }
})

function onYouTubeIframeAPIReady() {
  if (pendingVideoId) {
    initSeniorPlayer(pendingVideoId)
    pendingVideoId = null
  }
}

function loadYoutubePlayer(videoId) {
  if (window.YT && YT.Player) {
    initSeniorPlayer(videoId)
  } else {
    pendingVideoId = videoId
  }
}

function initSeniorPlayer(videoId) {
  seek = document.getElementById("seek")

  if (ytPlayer) ytPlayer.destroy()
  if (seek) seek.value = 0

  ytPlayer = new YT.Player("ytplayer", {
    videoId,
    playerVars: {
      autoplay: 1,
      mute: 1,
      controls: 0,
      rel: 0,
      modestbranding: 1,
      playsinline: 1,
      fs: 0,
      disablekb: 1,
      iv_load_policy: 3
    },
    events: {
      onReady: e => {
        e.target.mute()
        e.target.playVideo()
      },
      onStateChange: e => {
        if (e.data === YT.PlayerState.PLAYING) {
          playing = true
          document.getElementById("toggleBtn").innerText = "Pause"
          ytPlayer.unMute()

          clearInterval(seekTimer)
          seekTimer = setInterval(() => {
            const d = ytPlayer.getDuration()
            if (!d || !seek) return
            seek.value = (ytPlayer.getCurrentTime() / d) * 100
          }, 300)
        }

        if (e.data === YT.PlayerState.PAUSED) {
          playing = false
          document.getElementById("toggleBtn").innerText = "Play"
        }

        if (e.data === YT.PlayerState.ENDED) {
          playNextLecture()
        }
      }
    }
  })

  if (seek) {
    seek.oninput = () => {
      const t = (seek.value / 100) * ytPlayer.getDuration()
      ytPlayer.seekTo(t, true)
    }
  }

  bindPlayerControls()
}

function bindPlayerControls() {
  const toggleBtn = document.getElementById("toggleBtn")
  const volume = document.getElementById("volume")
  const volIcon = document.getElementById("volIcon")
  const shell = document.getElementById("playerShell")
  const controls = document.getElementById("controls")

  if (!toggleBtn || !controls || !shell) return

  function updateVolumeIcon(v) {
    if (v == 0) volIcon.className = "fa-solid fa-volume-xmark"
    else if (v < 50) volIcon.className = "fa-solid fa-volume-low"
    else volIcon.className = "fa-solid fa-volume-high"
  }

  toggleBtn.onclick = () =>
    playing ? ytPlayer.pauseVideo() : ytPlayer.playVideo()

  volume.oninput = () => {
    ytPlayer.setVolume(volume.value)
    updateVolumeIcon(volume.value)
  }

  let hideTimer

  function showControls() {
    controls.classList.remove("hidden")
    clearTimeout(hideTimer)
    hideTimer = setTimeout(() => {
      controls.classList.add("hidden")
    }, 1500) // ✅ 1 second
  }

  shell.addEventListener("mousemove", showControls)
  shell.addEventListener("mouseenter", showControls)

    const gearBtn = document.getElementById("gearBtn")
  const settingsBox = document.getElementById("settingsBox")
  const qualityOpen = document.getElementById("qualityOpen")
  const speedOpen = document.getElementById("speedOpen")
  const qualityMenu = document.getElementById("qualityMenu")
  const speedMenu = document.getElementById("speedMenu")

  if (!gearBtn || !settingsBox) return

  gearBtn.onclick = () => {
    settingsBox.classList.toggle("show")
    qualityMenu.style.display = "none"
    speedMenu.style.display = "none"
    document.querySelector(".menu.main").style.display = "block"
  }

  qualityOpen.onclick = () => {
    document.querySelector(".menu.main").style.display = "none"
    qualityMenu.style.display = "block"
  }

  speedOpen.onclick = () => {
    document.querySelector(".menu.main").style.display = "none"
    speedMenu.style.display = "block"
  }

  document.querySelectorAll(".back").forEach(b => {
    b.onclick = () => {
      qualityMenu.style.display = "none"
      speedMenu.style.display = "none"
      document.querySelector(".menu.main").style.display = "block"
    }
  })

    document.querySelectorAll("[data-s]").forEach(o => {
    o.onclick = () => {
      ytPlayer.setPlaybackRate(Number(o.dataset.s))
      document.getElementById("sLabel").innerText = o.dataset.s + "x"
      settingsBox.classList.remove("show")
    }
  })

  document.querySelectorAll("[data-q]").forEach(o => {
    o.onclick = () => {
      ytPlayer.setPlaybackQuality(o.dataset.q)
      document.getElementById("qLabel").innerText = o.innerText
      settingsBox.classList.remove("show")
    }
  })

}


function playNextLecture() {
  const params = new URLSearchParams(window.location.search)
  const chapterId = params.get("chapterId")

  const list = window.__LECTURE_IDS__
  const idx = window.__CURRENT_INDEX__

  if (!list || idx === -1) return
  const next = list[idx + 1]
  if (!next) return

  window.location.replace(
    `player.html?lectureId=${next}&chapterId=${chapterId}`
  )
}

function extractYoutubeId(url) {
  if (!url) return null
  if (url.includes("embed/")) return url.split("embed/")[1].split("?")[0]
  if (url.includes("youtu.be/")) return url.split("youtu.be/")[1].split("?")[0]
  if (url.includes("watch?v=")) return url.split("watch?v=")[1].split("&")[0]
  return null
}


function forceMobileImmersive() {
  if (window.innerWidth > 768) return

  const shell = document.getElementById("playerShell")
  if (!shell) return

  document.body.classList.add("mobile-player")

  const goFullscreen = () => {
    const req =
      shell.requestFullscreen ||
      shell.webkitRequestFullscreen ||
      shell.msRequestFullscreen

    if (req) req.call(shell)

    if (screen.orientation && screen.orientation.lock) {
      screen.orientation.lock("landscape").catch(() => {})
    }
  }

  shell.addEventListener("click", goFullscreen, { once: true })
}

window.addEventListener("load", forceMobileImmersive)

function activateMobilePlayerMode() {
  if (window.innerWidth > 768) return

  const shell = document.getElementById("playerShell")
  if (!shell) return

  shell.classList.add("mobile-player-mode")

  if (screen.orientation && screen.orientation.lock) {
    screen.orientation.lock("landscape").catch(() => {})
  }
}

window.addEventListener("load", activateMobilePlayerMode)
