let courseData = [
  {
    id: 1,
    title: "Intro to Design",
    lessons: [
      {
        id: "v1",
        title: "What is UI Design?",
        duration: "05:10",
        videoUrl: "../assets/video/python-class.mp4",
        completed: false,
      },
      {
        id: "v2",
        title: "Design Mindset",
        duration: "10:20",
        videoUrl: "../assets/video/python-class.mp4",
        completed: false,
      },
    ],
  },
  {
    id: 2,
    title: "Visual Principles",
    lessons: [
      {
        id: "v3",
        title: "Color Theory Basics",
        duration: "15:00",
        videoUrl: "../assets/video/python-class.mp4",
        completed: false,
      },
      {
        id: "v4",
        title: "Typography Rules",
        duration: "12:45",
        videoUrl: "../assets/video/python-class.mp4",
        completed: false,
      },
    ],
  },
];

let currentPlayingIdx = { m: 0, l: 0 };

function renderCurriculum() {
  const container = document.getElementById("curriculum-container");
  container.innerHTML = "";
  let foundCurrent = false,
    total = 0,
    completedCount = 0;

  courseData.forEach((milestone, mIndex) => {
    const prevDone = courseData
      .slice(0, mIndex)
      .every((m) => m.lessons.every((l) => l.completed));
    const isMActive = !foundCurrent && prevDone;

    container.innerHTML += `
            <div class="border ${isMActive ? "active-border" : "border-white/10"} rounded-2xl overflow-hidden bg-[#1A1A1A]/30 ${!prevDone ? "locked-item" : ""}">
              <button onclick="toggleMilestone('m${milestone.id}')" class="w-full flex items-center justify-between p-4">
                <div class="flex items-center gap-4 text-left">
                  <div class="w-10 h-10 rounded-full ${milestone.lessons.every((l) => l.completed) ? "bg-green-500" : "bg-[#7B48FF]"} flex items-center justify-center">
                    <span class="text-white font-bold text-sm">${milestone.id}</span>
                  </div>
                  <div><h3 class="text-white text-sm font-semibold">${milestone.title}</h3><p class="text-[#A4ACB9] text-[10px]">${milestone.lessons.length} Lessons</p></div>
                </div>
                <img src="../assets/icons/dropdown.svg" class="w-5 h-5 transition-transform" id="icon-m${milestone.id}" />
              </button>
              <div id="m${milestone.id}" class="milestone-content ${isMActive ? "open" : ""}"><div class="p-3 pt-0 flex flex-col gap-2">
                ${milestone.lessons
                  .map((lesson, lIndex) => {
                    total++;
                    if (lesson.completed) completedCount++;
                    const isLocked =
                      (lIndex > 0 &&
                        !milestone.lessons[lIndex - 1].completed) ||
                      !prevDone;
                    const isPlaying =
                      !lesson.completed && !isLocked && !foundCurrent;
                    if (isPlaying) foundCurrent = true;

                    return `
                    <div onclick="${!isLocked ? `openVideo('${lesson.videoUrl}', '${lesson.title}', ${mIndex}, ${lIndex})` : ""}" 
                         class="flex items-center justify-between p-3 rounded-xl ${isPlaying ? "bg-[#7B48FF]/20 border border-[#7B48FF]/30" : "bg-white/5 border border-white/5"} ${isLocked ? "opacity-30" : "cursor-pointer"}">
                      <div class="flex items-center gap-3">
                        <img src="../assets/icons/acadamic.svg" class="w-4 h-4 ${isPlaying ? "text-[#7B48FF]" : "opacity-50"}" />
                        <span class="text-xs ${isPlaying ? "text-white font-bold" : "text-white/70"}">${lesson.title}</span>
                      </div>
                      ${lesson.completed ? '<img src="../assets/icons/downlodTik.svg" class="w-4 h-4 text-green-500" />' : `<span class="text-[8px] font-bold text-[#7B48FF]">${isPlaying ? "PLAYING" : ""}</span>`}
                    </div>`;
                  })
                  .join("")}
              </div></div>
            </div>`;
  });
  document.getElementById("progress-info").innerText =
    `Progress: ${completedCount}/${total} Lessons Completed`;
  updateBtn(completedCount === total);
}

function openVideo(url, title, mIdx, lIdx) {
  const modal = document.getElementById("videoModal");
  const player = document.getElementById("mainVideoPlayer");
  const source = document.getElementById("videoSource");

  currentPlayingIdx = { m: mIdx, l: lIdx };
  document.getElementById("modalVideoTitle").innerText = title;

  source.src = url;
  player.load();

  modal.classList.remove("hidden");
  modal.classList.add("flex");
  document.body.style.overflow = "hidden";

  player.play().catch((e) => console.log("Playback error:", e));

  player.onended = function () {
    courseData[currentPlayingIdx.m].lessons[currentPlayingIdx.l].completed =
      true;
    closeVideo();
    renderCurriculum();
  };
}

function closeVideo() {
  const modal = document.getElementById("videoModal");
  const player = document.getElementById("mainVideoPlayer");
  player.pause();
  modal.classList.add("hidden");
  modal.classList.remove("flex");
  document.body.style.overflow = "auto";
}

function updateBtn(done) {
  const btn = document.getElementById("main-action-btn");
  if (done) {
    btn.innerText = "Get Certificate";
    btn.style.background = "#22C55E";
    btn.onclick = () => (window.location.href = "./certification.html");
  } else {
    btn.innerText = "Continue Learning";
    btn.style.background = "#7B48FF";
  }
}

function toggleMilestone(id) {
  const el = document.getElementById(id);
  const icon = document.getElementById("icon-" + id);
  el.classList.toggle("open");
  icon.classList.toggle("rotate-180");
}

renderCurriculum();
