console.log("script.js loaded")

document.addEventListener("DOMContentLoaded", () => {
  let navbar = document.querySelector(".header .navbar")
  let menuBtn = document.querySelector("#menu-btn")
  let closeNavbar = document.querySelector("#close-navbar")

  if (menuBtn && navbar) {
    menuBtn.onclick = () => {
      navbar.classList.add("active")
    }
  }

  if (closeNavbar && navbar) {
    closeNavbar.onclick = () => {
      navbar.classList.remove("active")
    }
  }

  let registerBtn = document.querySelector(".account-form .register-btn")
  let loginBtn = document.querySelector(".account-form .login-btn")

  if (registerBtn && loginBtn) {
    registerBtn.onclick = () => {
      registerBtn.classList.add("active")
      loginBtn.classList.remove("active")
      document.querySelector(".account-form .login-form")?.classList.remove("active")
      document.querySelector(".account-form .register-form")?.classList.add("active")
    }

    loginBtn.onclick = () => {
      registerBtn.classList.remove("active")
      loginBtn.classList.add("active")
      document.querySelector(".account-form .login-form")?.classList.add("active")
      document.querySelector(".account-form .register-form")?.classList.remove("active")
    }
  }

  let accountForm = document.querySelector(".account-form")
  let accountBtn = document.querySelector("#account-btn")
  let closeForm = document.querySelector("#close-form")
  let dropdown = document.querySelector(".account-dropdown")

  console.log("Dropdown element:", dropdown)

  const token = localStorage.getItem("token")

  if (token && dropdown){
    dropdown.innerHTML =`
    <button id="logoutBtn" class="logout-btn">Logout</button>
    `

    document.getElementById("logoutBtn").onclick = () => {
      localStorage.removeItem("token")
      location.reload()
    }
  }

  if (accountBtn) {
    accountBtn.onclick = e => {
      e.preventDefault()
      if (window.innerWidth <= 768) {
        accountForm?.classList.add("active")
      } else {
        if (dropdown) {
          dropdown.style.display =
            dropdown.style.display === "flex" ? "none" : "flex"
        }
      }
    }
  }

  document.addEventListener("click", e => {
    if (!e.target.closest(".account-dropdown-wrapper")) {
      if (dropdown) dropdown.style.display = "none"
    }
  })

  if (closeForm) {
    closeForm.onclick = () => {
      accountForm?.classList.remove("active")
    }
  }


  if (typeof Swiper !== "undefined" && document.querySelector(".home-slider")) {
    new Swiper(".home-slider", {
      loop: true,
      grabCursor: true,
      speed: 900,
      autoplay: {
        delay: 3500,
        disableOnInteraction: false
      },
      effect: "slide",
      pagination: {
        el: ".swiper-pagination",
        clickable: true
      }
    })
  }

if (document.getElementById("courseTitle")) {
  const params = new URLSearchParams(window.location.search)
  const courseId = params.get("courseId")

  if (!courseId) return

  fetch(`http://localhost:5000/api/user/courses/${courseId}`,{
    headers: token
    ? { Authorization: `Bearer ${token}`}
    : {}
  })
    .then(res => res.json())
    .then(data => {
      console.log("COURSE FROM API:", data)

      const course = Array.isArray(data) ? data[0] : data
      if(!course) return

      document.getElementById("courseTitle").innerText = course.name || ""
      document.getElementById("courseSubtitle").innerText = course.description || ""
      
      const about = document.getElementById("courseAbout")
      if (about) about.innerText = course.description || ""

      const badge = document.querySelector(".badge")
      if (badge) badge.style.display = "none"

      const enrollBtn = document.querySelector(".enroll-btn")
      if (enrollBtn) {
        enrollBtn.style.display = course.isPaid ? "block" : "none"
      }
    })
    .catch(err => {
      console.error("Failed to load course details", err)
    })
}


if (document.getElementById("lecturesContainer")) {
  const params = new URLSearchParams(window.location.search)
  const courseId = params.get("courseId")

  if (courseId) {
    fetch(`http://localhost:5000/api/user/chapters/${courseId}`, {
      headers: token
      ? { Authorization: `Bearer ${token}`}
      :{}
    })
      .then(res => {
        if (!res.ok){
          return res.json().then(err =>{
            throw err
          })
        }
        return res.json()
      })
      .then(data => {
        console.log("CHAPTER API RESPONSE:", data)

        if(data.locked){
          showFrozenMessage("This Course content is locked by Admin")
          return
        }

        showChapters(data.chapter || [])
      })
      .catch(err => {
        const token = localStorage.getItem("token")

        if(!token) {
          showFrozenMessage("Please login to access this course")
          return
        }

        showFrozenMessage("This is a paid course. Purchase required.")
      })
  }
}

})

document.addEventListener("click", e => {
  const chapter = e.target.closest(".chapter-item")
  if (!chapter) return

  const courseId = new URLSearchParams(window.location.search).get("courseId")
  const chapterId = chapter.dataset.chapterId

  if (!courseId || !chapterId) return

  window.location.href = `chapter.html?courseId=${courseId}&chapterId=${chapterId}`
})



function showChapters(chapters) {
  const container = document.getElementById("lecturesContainer")
  if (!container) return

  container.innerHTML = chapters
    .sort((a, b) => a.order - b.order)
    .map((c, i) => `
      <div
       class="chapter-item"
        data-chapter-id="${c._id}"
        data-index="${i+1}"
        >
        <span>${c.title}</span>
      </div>
    `)
    .join("")
}

function showFrozenMessage(msg) {
  const container = document.getElementById("lecturesContainer")
  if (!container) return

  const token = localStorage.getItem("token")

  container.innerHTML = `
    <div class="paid-state">
      <h2>${token ? "Paid Course" : "Login Required"}</h2>
      <p>${msg}</p>
      ${
        token
          ? `<button id="buyBtn" class="paid-btn">Buy Course</button>`
          : `<button id="loginBtn" class="paid-btn">Login</button>`
      }
    </div>
  `

  const loginBtn = document.getElementById("loginBtn")
  const buyBtn = document.getElementById("buyBtn")

  if (loginBtn) loginBtn.onclick = () => location.href = "login.html"
  if (buyBtn) buyBtn.onclick = () => location.href = "contact.html"
}

/* ===============================
   CHAPTER TYPE SWITCH (REAL FIX)
=============================== */

const optionBtns = document.querySelectorAll(".option-btn");

if (optionBtns.length && document.getElementById("lecturesContainer")) {

  const params = new URLSearchParams(window.location.search);
  const courseId = params.get("courseId");

  function loadByType(type) {

    fetch(`http://localhost:5000/api/user/chapters/${courseId}?type=${type}`, {
      headers: localStorage.getItem("token")
        ? { Authorization: `Bearer ${localStorage.getItem("token")}` }
        : {}
    })
      .then(res => res.json())
      .then(data => {

        if (!data || !data.chapter || data.chapter.length === 0) {
          document.getElementById("lecturesContainer").innerHTML =
            `<div class="paid-state">
              <h2>No Content</h2>
              <p>No ${type} available at the moment</p>
            </div>`;
          return;
        }

        showChapters(data.chapter);
      })
      .catch(() => {
        document.getElementById("lecturesContainer").innerHTML =
          `<div class="paid-state">
            <h2>Error</h2>
            <p>Unable to load content</p>
          </div>`;
      });
  }

  optionBtns.forEach(btn => {
    btn.addEventListener("click", () => {

      optionBtns.forEach(b => b.classList.remove("active"));
      btn.classList.add("active");

      const type = btn.dataset.type;
      loadByType(type);

    });
  });

  /* default */
  optionBtns[0].classList.add("active");
}


// STYLING JS CODE

let lastScroll = 0;

window.addEventListener("scroll", () => {
  const header = document.querySelector(".header");
  const currentScroll = window.scrollY;

  if (currentScroll > lastScroll && currentScroll > 120) {
    header.classList.add("hide");
  } else {
    header.classList.remove("hide");
  }

  lastScroll = currentScroll;
});

const layers = document.querySelectorAll(".layer");

window.addEventListener("scroll", () => {
  const y = window.scrollY;

  layers.forEach((layer, index) => {
    const speed = (index + 1) * 0.08;
    layer.style.transform = `translateY(${y * speed}px)`;
  });
});

document.addEventListener("DOMContentLoaded", () => {

  const infoItems = document.querySelectorAll(".course-info-item");
  const images = document.querySelectorAll(".course-images img");
  const section = document.querySelector(".courses-sticky");

  if (!section) return;

  const total = infoItems.length;

  /* ===============================
     FLOATING CHALK ENGINE
  =============================== */

  const container = document.getElementById("floatingChalk");

  if (!container) {
  console.error("Floating chalk container not found");
  return;
  }

  const themes = [
    ["π","√x","∫","sinθ","Δ","x²+y²=r²","θ"],
    ["E=mc²","F=ma","λ","Ω","orbit","ψ"],
    ["H₂O","NaCl","C₆H₆","→","⚗","CO₂","pH"],
    ["DNA","cell","neuron","leaf","🧬","pulse"]
  ];

  let chalkNodes = [];
  let currentTheme = -1;

  function createTheme(index){

    const oldNodes = [...chalkNodes];
    const newNodes = [];

    const symbols = themes[index];

    for(let i=0;i<16;i++){   // density control
      const text = symbols[Math.floor(Math.random()*symbols.length)];
      const el = document.createElement("span");
      el.className = "chalk";
      el.innerText = text;

      el.style.fontSize = (3 + Math.random()*1.5) + "rem";

      el.x = Math.random() * section.clientWidth;
      el.y = Math.random() * window.innerHeight;

      el.vx = (Math.random()-0.5)*0.25;
      el.vy = (Math.random()-0.5)*0.25;
      el.noise = Math.random()*1000;

      el.style.left = el.x+"px";
      el.style.top = el.y+"px";

      container.appendChild(el);
      newNodes.push(el);
    }

    chalkNodes = newNodes;

    requestAnimationFrame(()=>{
      newNodes.forEach(el=>el.classList.add("show"));
    });

    setTimeout(()=>{
      oldNodes.forEach(n=>{
        n.classList.remove("show");
        setTimeout(()=>n.remove(),600);
      });
    },150);
  }

  function animate(){
    chalkNodes.forEach(el=>{

      el.noise += 0.008;

      const driftX = Math.sin(el.noise) * 0.35;
      const driftY = Math.cos(el.noise * 1.2) * 0.35;

      el.vx += driftX;
      el.vy += driftY;

      const speed = Math.sqrt(el.vx*el.vx + el.vy*el.vy);
      const maxSpeed = 2;

      if(speed > maxSpeed){
        el.vx *= maxSpeed / speed;
        el.vy *= maxSpeed / speed;
      }

      el.x += el.vx;
      el.y += el.vy;

      const margin = 100;

      if(el.x < margin || el.x > section.clientWidth - margin){
        el.vx *= -1;
      }

      if(el.y < margin || el.y > window.innerHeight - margin){
        el.vy *= -1;
      }

      el.style.left = el.x + "px";
      el.style.top = el.y + "px";
    });

    requestAnimationFrame(animate);
  }

  animate();

  function toggleChalkVisibility(){
    const rect = section.getBoundingClientRect();

    const visible = rect.top < window.innerHeight && rect.bottom > 0;

    if(visible){
      container.style.opacity = "1";
      container.style.pointerEvents = "none"
    } else {
      container.style.opacity = "0";
    }
  }

  window.addEventListener("scroll", toggleChalkVisibility);
  toggleChalkVisibility();


  window.addEventListener("mousemove",e=>{
    chalkNodes.forEach(el=>{
      const dx = el.x - e.clientX;
      const dy = el.y - e.clientY;
      const dist = Math.sqrt(dx*dx+dy*dy);

      if(dist < 140){
        el.x += dx * 0.06;
        el.y += dy * 0.06;
        el.style.transform = "scale(1.2)";
      } else {
        el.style.transform = "scale(1)";
      }
    });
  });

  /* ===============================
     COURSE SCROLL + CHALK SYNC
  =============================== */

  function updateCourses() {
    const rect = section.getBoundingClientRect();
    const sectionHeight = section.offsetHeight;
    const windowHeight = window.innerHeight;

    let progress = -rect.top / (sectionHeight - windowHeight);
    progress = Math.max(0, Math.min(progress, 1));

    const index = Math.min(total - 1, Math.floor(progress * total));

    infoItems.forEach(el => el.classList.remove("active"));
    images.forEach(el => el.classList.remove("active"));

    if (infoItems[index]) infoItems[index].classList.add("active");
    if (images[index]) images[index].classList.add("active");

    const themeIndex = Math.min(Math.floor(index / 3), themes.length - 1);

    if(themeIndex !== currentTheme){
      currentTheme = themeIndex;
      createTheme(themeIndex);
    }
  }

  window.addEventListener("scroll", updateCourses);
  updateCourses();

});

/* existing sticky logic untouched */

const sticky = document.querySelector(".courses-wrapper");
const section = document.querySelector(".courses-sticky");

window.addEventListener("scroll", () => {
  if (!sticky || !section) return;

  const rect = section.getBoundingClientRect();

  if (rect.top <= 0 && rect.bottom > window.innerHeight) {
    sticky.style.position = "fixed";
    sticky.style.top = "0";
    sticky.style.left = "0";
    sticky.style.right = "0";
  } 
  else if (rect.bottom <= window.innerHeight) {
    sticky.style.position = "absolute";
    sticky.style.top = `${section.offsetHeight - window.innerHeight}px`;
  } 
  else {
    sticky.style.position = "relative";
    sticky.style.top = "0";
  }
});

const courses = document.querySelector(".courses-sticky");

window.addEventListener("scroll", () => {
  if (!courses) return;

  const rect = courses.getBoundingClientRect();
  const max = courses.offsetHeight - window.innerHeight;

  let progress = -rect.top / max;
  progress = Math.max(0, Math.min(progress, 1));

  const start = { r: 11, g: 46, b: 92 };
  const end   = { r: 30, g: 78, b: 140 };

  const r = Math.round(start.r + (end.r - start.r) * progress);
  const g = Math.round(start.g + (end.g - start.g) * progress);
  const b = Math.round(start.b + (end.b - start.b) * progress);

  courses.style.backgroundColor = `rgb(${r}, ${g}, ${b})`;
});

/* ===============================
   CLASS SELECTOR LOGIC
=============================== */
const selector = document.querySelector(".class-selector")
const coursesSection = document.querySelector(".courses-page")
const backBtn = document.getElementById("backToClasses")

if (selector && coursesSection) {

  const savedClass = localStorage.getItem("selectedClass")

  if (savedClass) {
    selector.classList.add("hidden")
    backBtn.classList.remove("hidden")
    loadCourses(savedClass)
  }

  document.querySelectorAll(".class-cell").forEach(cell => {
    cell.onclick = () => {
      const chosen = cell.dataset.class
      localStorage.setItem("selectedClass", chosen)
      selector.classList.add("hidden")
      backBtn.classList.remove("hidden")
      loadCourses(chosen)
    }
  })

  backBtn.onclick = () => {
    localStorage.removeItem("selectedClass")
    selector.classList.remove("hidden")
    document.getElementById("coursesContainer").innerHTML = ""
    backBtn.classList.add("hidden")
    window.scrollTo({ top: 0, behavior: "smooth" })
  }

  function loadCourses(selectedClass) {
    fetch("http://localhost:5000/api/user/courses/public")
      .then(res => res.json())
      .then(courses => {

        const filtered = courses.filter(
          c => c.class.trim() === selectedClass.trim()
        )

        const container = document.getElementById("coursesContainer")

        if (!filtered.length) {
          container.innerHTML = "<p>No courses for this class</p>"
          return
        }

        container.innerHTML = filtered.map(course => `
          <div class="course-title">
            <img src="http://localhost:5000/uploads/${course.thumbnail}"/>
            <div class="course-body">
              <h3>${course.name}</h3>
              <p>${course.description || ""}</p>
              <span>${course.isPaid ? "Paid" : "Free"}</span>
            </div>
            <a href="course-details.html?courseId=${course._id}" class="course-btn">
              View Details
            </a>
          </div>
        `).join("")
      })
  }
}

