// ===== Dark Mode =====
const darkToggle = document.getElementById('darkToggle');
const html = document.documentElement;

const savedTheme = localStorage.getItem('theme');
if (savedTheme) {
  html.setAttribute('data-theme', savedTheme);
} else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  html.setAttribute('data-theme', 'dark');
}

darkToggle.addEventListener('click', () => {
  const current = html.getAttribute('data-theme');
  const next = current === 'dark' ? 'light' : 'dark';
  html.setAttribute('data-theme', next);
  localStorage.setItem('theme', next);
});

// ===== Mobile Nav Toggle =====
const navToggle = document.getElementById('navToggle');
const navMenu = document.getElementById('navMenu');

navToggle.addEventListener('click', () => {
  navMenu.classList.toggle('active');
  const icon = navToggle.querySelector('i');
  icon.classList.toggle('fa-bars');
  icon.classList.toggle('fa-times');
  navToggle.setAttribute('aria-expanded', navMenu.classList.contains('active'));
});

navMenu.querySelectorAll('a').forEach(link => {
  link.addEventListener('click', () => {
    navMenu.classList.remove('active');
    navToggle.setAttribute('aria-expanded', 'false');
    const icon = navToggle.querySelector('i');
    icon.classList.add('fa-bars');
    icon.classList.remove('fa-times');
  });
});

// Mobile nav dropdown toggle
const navDropdown = document.querySelector('.nav-dropdown');
const navDdBtn = document.querySelector('.nav-dd-btn');
if (navDropdown && navDdBtn) {
  navDdBtn.addEventListener('click', (e) => {
    if (window.innerWidth <= 768) {
      e.preventDefault();
      navDropdown.classList.toggle('active');
      navDdBtn.setAttribute('aria-expanded', navDropdown.classList.contains('active'));
    }
  });
  navDropdown.querySelectorAll('a').forEach(link => {
    link.addEventListener('click', () => {
      navDropdown.classList.remove('active');
      if (navDdBtn) navDdBtn.setAttribute('aria-expanded', 'false');
    });
  });
}

// ===== Active nav link on scroll =====
const sections = document.querySelectorAll('section[id]');
const navLinks = document.querySelectorAll('.nav a');
const ddLinks = document.querySelectorAll('.nav-dd-menu a');

window.addEventListener('scroll', () => {
  let current = '';
  sections.forEach(section => {
    const top = section.offsetTop - 130;
    const bottom = top + section.offsetHeight;
    if (window.scrollY >= top && window.scrollY < bottom) {
      current = section.getAttribute('id');
    }
  });
  navLinks.forEach(link => {
    link.classList.remove('active');
    if (link.getAttribute('href') === '#' + current) {
      link.classList.add('active');
    }
  });
  ddLinks.forEach(link => {
    link.classList.remove('active');
    if (link.getAttribute('href') === '#' + current) {
      link.classList.add('active');
    }
  });
});

// ===== Counter Animation =====
const counters = document.querySelectorAll('.counter');

const animateCounter = (counter) => {
  const target = parseInt(counter.getAttribute('data-target'));
  const duration = 2000;
  const step = Math.ceil(target / (duration / 16));
  let current = 0;

  const update = () => {
    current += step;
    if (current >= target) {
      counter.textContent = target;
      return;
    }
    counter.textContent = current;
    requestAnimationFrame(update);
  };

  update();
};

const counterObserver = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      animateCounter(entry.target);
      counterObserver.unobserve(entry.target);
    }
  });
}, { threshold: 0.5 });

counters.forEach(counter => counterObserver.observe(counter));

// ===== Lightbox =====
const modal = document.getElementById('lightboxModal');
const modalImg = document.getElementById('modalImage');
const modalClose = document.querySelector('.lightbox-close');

document.querySelectorAll('[data-lightbox]').forEach(item => {
  item.addEventListener('click', (e) => {
    e.preventDefault();
    modal.classList.add('active');
    modalImg.src = item.getAttribute('href');
    document.body.style.overflow = 'hidden';
  });
});

modalClose.addEventListener('click', closeModal);
modal.addEventListener('click', (e) => {
  if (e.target === modal) closeModal();
});

document.addEventListener('keydown', (e) => {
  if (e.key === 'Escape') closeModal();
});

function closeModal() {
  modal.classList.remove('active');
  document.body.style.overflow = '';
}

// ===== Contact Form =====
const contactForm = document.getElementById('contactForm');
if (contactForm) {
  contactForm.addEventListener('submit', (e) => {
    e.preventDefault();
    const btn = contactForm.querySelector('button[type="submit"]');
    const original = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Mengirim...';

    fetch(contactForm.action, {
      method: 'POST',
      body: new FormData(contactForm),
      headers: { 'X-Requested-With': 'XMLHttpRequest' },
    })
      .then((r) => r.json())
      .then((res) => {
        if (res.success) {
          btn.innerHTML = '<i class="fas fa-check"></i> Terkirim!';
          btn.style.background = '#10b981';
          contactForm.reset();
          setTimeout(() => {
            btn.innerHTML = original;
            btn.style.background = '';
            btn.disabled = false;
          }, 3000);
        } else {
          let errText = Object.values(res.errors || {}).join(', ');
          btn.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Gagal';
          btn.style.background = '#ef4444';
          setTimeout(() => {
            btn.innerHTML = original;
            btn.style.background = '';
            btn.disabled = false;
          }, 2500);
          if (errText) alert(errText);
        }
      })
      .catch(() => {
        btn.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Error';
        btn.style.background = '#ef4444';
        setTimeout(() => {
          btn.innerHTML = original;
          btn.style.background = '';
          btn.disabled = false;
        }, 2500);
      });
  });
}

// ===== Carousel =====
function initCarousel(trackId, prevId, nextId, dotsId) {
  const track = document.getElementById(trackId);
  const prev = document.getElementById(prevId);
  const next = document.getElementById(nextId);
  const dots = document.getElementById(dotsId);
  if (!track || track.children.length === 0) return;

  const cards = track.children;
  let current = 0;
  let visible = 4;

  const updateVisible = () => {
    const w = track.parentElement.offsetWidth - 88;
    const card = cards[0];
    if (!card) return;
    const gap = 20;
    const cardW = card.offsetWidth;
    visible = Math.max(1, Math.floor((w + gap) / (cardW + gap)));
    if (current > cards.length - visible) {
      current = Math.max(0, cards.length - visible);
    }
    render();
  };

  const render = () => {
    const card = cards[0];
    if (!card) return;
    const gap = 20;
    const cardW = card.offsetWidth;
    const offset = current * (cardW + gap);
    track.style.transform = `translateX(-${offset}px)`;
    renderDots();
  };

  const renderDots = () => {
    if (!dots) return;
    const total = Math.max(1, cards.length - visible + 1);
    dots.innerHTML = '';
    for (let i = 0; i < total; i++) {
      const btn = document.createElement('button');
      btn.setAttribute('role', 'tab');
      if (i === current) btn.classList.add('active');
      btn.addEventListener('click', () => { current = i; render(); });
      dots.appendChild(btn);
    }
  };

  prev.addEventListener('click', () => {
    if (current > 0) { current--; render(); }
  });

  next.addEventListener('click', () => {
    if (current < cards.length - visible) { current++; render(); }
  });

  window.addEventListener('resize', updateVisible);
  updateVisible();
}

initCarousel('teacherTrack', 'teacherPrev', 'teacherNext', 'teacherDots');

// ===== FAQ Accordion =====
const faqItems = document.querySelectorAll('.faq-item');

faqItems.forEach(item => {
  const question = item.querySelector('.faq-question');
  question.addEventListener('click', () => {
    const isActive = item.classList.contains('active');
    faqItems.forEach(i => i.classList.remove('active'));
    if (!isActive) {
      item.classList.add('active');
      question.setAttribute('aria-expanded', 'true');
    } else {
      question.setAttribute('aria-expanded', 'false');
    }
  });
});

// ===== Back to Top =====
const backToTop = document.getElementById('backToTop');

window.addEventListener('scroll', () => {
  if (window.scrollY > 400) {
    backToTop.classList.add('show');
  } else {
    backToTop.classList.remove('show');
  }
});

backToTop.addEventListener('click', () => {
  window.scrollTo({ top: 0, behavior: 'smooth' });
});

// ===== Scroll reveal =====
const revealEls = document.querySelectorAll(
  '.programs-card, .news-card, .gallery-item, .counter-card, .about-grid, .contact-grid, .hero-card, .carousel-wrap, .achievement-card, .extracurricular-card, .testimonial-card, .event-card, .faq-item'
);

const revealObserver = new IntersectionObserver((entries) => {
  entries.forEach((entry, i) => {
    if (entry.isIntersecting) {
      entry.target.style.opacity = '1';
      entry.target.style.transform = 'translateY(0)';
      revealObserver.unobserve(entry.target);
    }
  });
}, { threshold: 0.06 });

revealEls.forEach((el, i) => {
  el.style.opacity = '0';
  el.style.transform = 'translateY(24px)';
  el.style.transition = `all 0.5s ease ${i % 3 * 0.08}s`;
  revealObserver.observe(el);
});

// ===== Filter berita (news.js) =====
const filterBtns = document.querySelectorAll('.nf-btn');
const newsCards = document.querySelectorAll('.news-card');

filterBtns.forEach(btn => {
  btn.addEventListener('click', () => {
    filterBtns.forEach(b => b.classList.remove('active'));
    btn.classList.add('active');

    const filter = btn.getAttribute('data-filter');
    newsCards.forEach(card => {
      if (filter === 'all' || card.getAttribute('data-category') === filter) {
        card.style.display = '';
        card.style.animation = 'none';
        card.offsetHeight;
        card.style.animation = 'fadeInUp 0.4s ease';
      } else {
        card.style.display = 'none';
      }
    });
  });
});
