// Navigation Button Active State
function setActiveNav(button) {
  // Remove active class from all nav buttons
  const navButtons = document.querySelectorAll(".nav-button");
  navButtons.forEach((btn) => btn.classList.remove("active"));
  // Add active class to clicked button
  button.classList.add("active");
}

// Tab Button Active State (for My Courses and similar pages)
function setActiveTab(button) {
  // Remove active class from all tab buttons
  const tabButtons = document.querySelectorAll(
    ".btn-tab-active, .btn-tab-deactive",
  );
  tabButtons.forEach((btn) => {
    btn.classList.remove("btn-tab-active");
    btn.classList.add("btn-tab-deactive");
  });
  // Add active class to clicked button
  button.classList.remove("btn-tab-deactive");
  button.classList.add("btn-tab-active");
}

// View Icon Button Active State (for Free Course, Recommended, etc.)
function setActiveView(button) {
  // Remove active class from all view buttons in the same group
  const viewButtons = button.parentElement.querySelectorAll(".view-icon-btn");
  viewButtons.forEach((btn) => btn.classList.remove("active"));
  // Add active class to clicked button
  button.classList.add("active");
}

// Bookmark Toggle Function
function toggleWishlist(element, event) {
  event.preventDefault();
  event.stopPropagation(); // Card link block korbe
  element.classList.toggle("is-active");
}

// Carousel Logic (Simple) - Supports Multiple Carousels
let currentSlide = 0;
function goToSlide(n, carouselId = "carousel", dotsId = "dots") {
  const carousel = document.getElementById(carouselId);
  const dotsContainer = document.getElementById(dotsId);
  const dots = dotsContainer
    ? dotsContainer.querySelectorAll(".dot")
    : document.querySelectorAll(".dot");
  currentSlide = n;
  carousel.style.transform = `translateX(-${n * 100}%)`;
  dots.forEach((dot) => dot.classList.remove("active"));
  dots[n].classList.add("active");
}

// ==========================================================================
// SCROLL ANIMATION SYSTEM
// ==========================================================================
// Initialize scroll animations on page load
function initScrollAnimations() {
  const observerOptions = {
    threshold: 0.1,
    rootMargin: "0px 0px -50px 0px",
  };

  // Create Intersection Observer for scroll animations
  const observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        // Add animation class based on data attribute
        const animationType = entry.target.dataset.animation || "fadeInUp";
        entry.target.classList.add(`animate-${animationType}`);

        // Optional: Remove observer after animation (if you want one-time animation)
        // observer.unobserve(entry.target);
      }
    });
  }, observerOptions);

  // Apply observer to all elements with data-animation attribute
  const animatedElements = document.querySelectorAll("[data-animation]");
  animatedElements.forEach((element) => {
    observer.observe(element);
  });

  // Auto-animate common components
  const components = document.querySelectorAll(
    "section, .course-card, .session-item-home, .rec-card, .card-square",
  );

  components.forEach((component) => {
    if (!component.dataset.animation) {
      observer.observe(component);
      // Apply random animation styles
      const animations = ["fadeInUp", "fadeInLeft", "fadeInRight", "scaleIn"];
      const randomAnimation =
        animations[Math.floor(Math.random() * animations.length)];

      // Set a staggered delay for child elements
      const children = component.querySelectorAll("*");
      children.forEach((child, index) => {
        child.style.animationDelay = `${index * 0.1}s`;
      });
    }
  });
}

// Run scroll animations when DOM is ready
document.addEventListener("DOMContentLoaded", initScrollAnimations);

// Optional: Re-initialize if content is dynamically added
function reinitializeAnimations() {
  initScrollAnimations();
}

// ==========================================================================
// PLACEHOLDER BUTTON ALERT SYSTEM
// ==========================================================================
const SWEET_ALERT_CDN = "https://cdn.jsdelivr.net/npm/sweetalert2@11";
let swalLoaderPromise = null;

function loadSweetAlertIfNeeded() {
  if (window.Swal) return Promise.resolve(true);
  if (swalLoaderPromise) return swalLoaderPromise;

  swalLoaderPromise = new Promise((resolve) => {
    const script = document.createElement("script");
    script.src = SWEET_ALERT_CDN;
    script.async = true;
    script.onload = () => resolve(true);
    script.onerror = () => resolve(false);
    document.head.appendChild(script);
  });

  return swalLoaderPromise;
}

function isPlaceholderButton(button) {
  if (!button || button.disabled) return false;
  if (button.hasAttribute("data-no-alert")) return false;
  if (button.closest("[data-no-alert='true']")) return false;
  if (button.hasAttribute("onclick")) return false;
  if (button.id) return false;

  const type = (button.getAttribute("type") || "").toLowerCase();
  const isInsideForm = !!button.closest("form");

  if (type === "submit" || type === "reset") return false;
  if (!type && isInsideForm) return false; // default submit behavior in forms

  return true;
}

function getButtonText(button) {
  return button.textContent?.trim() || "This";
}

async function showSaveChangesAlert(pageName = "Settings") {
  const hasSwal = await loadSweetAlertIfNeeded();
  const message = `${pageName} changes saved successfully.`;

  if (hasSwal && window.Swal) {
    return window.Swal.fire({
      icon: "success",
      title: "Saved",
      text: message,
      width: "400px",
      confirmButtonText: "OK",
      confirmButtonColor: "#E9B402",
      background: "#121212",
      color: "#EEF2F6",
    });
  }

  alert(message);
  return Promise.resolve({ isConfirmed: true });
}

window.showSaveChangesAlert = showSaveChangesAlert;

async function showPlaceholderAlert(button) {
  const label = getButtonText(button);
  const message = `“${label}” action completed successfully.`;
  const hasSwal = await loadSweetAlertIfNeeded();

  if (hasSwal && window.Swal) {
    window.Swal.fire({
      icon: "success",
      title: "Success",
      text: message,
      width: "400px",
      confirmButtonText: "OK",
      confirmButtonColor: "#E9B402",
      background: "#121212",
      color: "#EEF2F6",
    });
    return;
  }

  alert(message);
}

function initPlaceholderButtonAlerts() {
  document.addEventListener("click", (event) => {
    const button = event.target.closest("button");
    if (!button || !isPlaceholderButton(button)) return;

    event.preventDefault();
    showPlaceholderAlert(button);
  });
}

document.addEventListener("DOMContentLoaded", initPlaceholderButtonAlerts);

document.addEventListener("DOMContentLoaded", () => {
  const downloadBtn = document.getElementById("downloadBtn");
  const downloadModal = document.getElementById("downloadModal");
  const closeModalBtn = document.getElementById("closeModalBtn");

  if (downloadBtn) {
    downloadBtn.onclick = () => downloadModal.classList.remove("hidden");
  }
  if (closeModalBtn) {
    closeModalBtn.onclick = () => downloadModal.classList.add("hidden");
  }
});

document.addEventListener("DOMContentLoaded", () => {
  const socialIcons = document.querySelectorAll(".social-icon");

  socialIcons.forEach((icon) => {
    icon.addEventListener("click", async () => {
      const hasSwal = await loadSweetAlertIfNeeded();

      if (hasSwal && window.Swal) {
        window.Swal.fire({
          icon: "info",
          title: "Coming Soon",
          text: "Social sharing is under development!",
          width: "300px",
          confirmButtonText: "Got it",
          confirmButtonColor: "#E9B402",
          background: "#1A1A1A",
          color: "#EEF2F6",
          showClass: {
            popup: "animate__animated animate__fadeInUp animate__faster",
          },
        });
      } else {
        alert("Social sharing coming soon!");
      }
    });
  });
});

document.addEventListener("DOMContentLoaded", () => {
  const shareIcon = document.querySelector('img[alt="Share course"]');
  const bookmarkIcon = document.querySelector('img[alt="Bookmark course"]');

  if (shareIcon) {
    shareIcon.addEventListener("click", async () => {
      const hasSwal = await loadSweetAlertIfNeeded();
      if (hasSwal && window.Swal) {
        window.Swal.fire({
          icon: "info",
          title: "Share Feature",
          text: "Sharing options will be available soon!",
          width: "300px",
          confirmButtonColor: "#E9B402",
          background: "#1A1A1A",
          color: "#EEF2F6",
        });
      }
    });
  }

  if (bookmarkIcon) {
    bookmarkIcon.addEventListener("click", async () => {
      const hasSwal = await loadSweetAlertIfNeeded();
      if (hasSwal && window.Swal) {
        window.Swal.fire({
          icon: "success",
          title: "Bookmarked",
          text: "Course added to your wishlist!",
          width: "300px",
          confirmButtonColor: "#E9B402",
          background: "#1A1A1A",
          color: "#EEF2F6",
          timer: 2000,
          showConfirmButton: false,
        });
      }
    });
  }
});

function openVideoModal(videoId) {
    const modal = document.getElementById('videoModal');
    const iframe = document.getElementById('videoIframe');
    
    iframe.src = `https://www.youtube.com/embed/${videoId}?autoplay=1`;
    
    modal.classList.remove('hidden');
    modal.classList.add('flex');
  }

  function closeVideoModal() {
    const modal = document.getElementById('videoModal');
    const iframe = document.getElementById('videoIframe');
    
    iframe.src = "";
    modal.classList.add('hidden');
    modal.classList.remove('flex');
  }

  window.onclick = function(event) {
    const modal = document.getElementById('videoModal');
    if (event.target == modal) {
      closeVideoModal();
    }
  }

  function toggleAboutText() {
  const moreText = document.getElementById("moreText");
  const btnText = document.getElementById("seeMoreBtn");

  if (moreText.classList.contains("hidden")) {
    moreText.classList.remove("hidden");
    btnText.innerText = " See Less";
  } else {
    moreText.classList.add("hidden");
    btnText.innerText = " See More...";
  }
}