/**
 * তজিয়া গ্রুপ — Main JavaScript
 */
document.addEventListener('DOMContentLoaded', () => {
  // Remove loader
  setTimeout(() => { const l = document.querySelector('.loader-wrap'); if(l) l.classList.add('hidden'); }, 800);

  // Theme toggle
  const theme = localStorage.getItem('theme') || 'dark';
  document.documentElement.setAttribute('data-theme', theme);
  document.querySelectorAll('.theme-toggle').forEach(btn => {
    btn.innerHTML = theme === 'dark' ? '<i class="fas fa-sun"></i>' : '<i class="fas fa-moon"></i>';
    btn.addEventListener('click', () => {
      const cur = document.documentElement.getAttribute('data-theme');
      const next = cur === 'dark' ? 'light' : 'dark';
      document.documentElement.setAttribute('data-theme', next);
      localStorage.setItem('theme', next);
      document.querySelectorAll('.theme-toggle').forEach(b => {
        b.innerHTML = next === 'dark' ? '<i class="fas fa-sun"></i>' : '<i class="fas fa-moon"></i>';
      });
    });
  });

  // Mobile nav toggle
  const navToggle = document.querySelector('.nav-toggle');
  const navLinks = document.querySelector('.nav-links');
  if (navToggle && navLinks) {
    navToggle.addEventListener('click', () => navLinks.classList.toggle('active'));
    document.addEventListener('click', (e) => {
      if (!e.target.closest('.navbar')) navLinks.classList.remove('active');
    });
  }

  // Hero slider
  const slides = document.querySelectorAll('.hero-slide');
  if (slides.length) {
    let idx = 0;
    setInterval(() => {
      slides[idx].classList.remove('active');
      idx = (idx + 1) % slides.length;
      slides[idx].classList.add('active');
    }, 3000);
  }

  // Scroll reveal
  const reveals = document.querySelectorAll('.reveal');
  const revealObserver = new IntersectionObserver((entries) => {
    entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add('visible'); revealObserver.unobserve(e.target); } });
  }, { threshold: 0.1 });
  reveals.forEach(el => revealObserver.observe(el));

  // Counter animation
  document.querySelectorAll('.counter').forEach(el => {
    const target = parseInt(el.getAttribute('data-target'));
    const observer = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting) {
        let current = 0;
        const step = Math.ceil(target / 60);
        const timer = setInterval(() => {
          current += step;
          if (current >= target) { current = target; clearInterval(timer); }
          el.textContent = toBn(current);
        }, 30);
        observer.unobserve(el);
      }
    });
    observer.observe(el);
  });

  // Bengali number conversion
  function toBn(n) {
    const bn = ['০','১','২','৩','৪','৫','৬','৭','৮','৯'];
    return String(n).replace(/[0-9]/g, d => bn[d]);
  }

  // Back to top
  const backTop = document.querySelector('.back-top');
  if (backTop) {
    window.addEventListener('scroll', () => {
      backTop.classList.toggle('show', window.scrollY > 500);
    });
    backTop.addEventListener('click', () => window.scrollTo({ top: 0, behavior: 'smooth' }));
  }

  // Lightbox
  const lightbox = document.getElementById('lightbox');
  const lightboxImg = document.getElementById('lightboxImg');
  if (lightbox) {
    document.querySelectorAll('[data-lightbox]').forEach(el => {
      el.addEventListener('click', () => {
        lightboxImg.src = el.getAttribute('data-lightbox');
        lightbox.classList.add('active');
      });
    });
    lightbox.addEventListener('click', (e) => {
      if (e.target === lightbox || e.target.classList.contains('lightbox-close')) {
        lightbox.classList.remove('active');
      }
    });
  }

  // Live search
  const searchInput = document.getElementById('liveSearch');
  const searchSuggestions = document.getElementById('searchSuggestions');
  if (searchInput && searchSuggestions) {
    let debounce;
    searchInput.addEventListener('input', () => {
      clearTimeout(debounce);
      const q = searchInput.value.trim();
      if (q.length < 2) { searchSuggestions.classList.remove('active'); return; }
      debounce = setTimeout(() => {
        fetch('search.php?ajax=1&q=' + encodeURIComponent(q))
          .then(r => r.json())
          .then(data => {
            if (data.length) {
              searchSuggestions.innerHTML = data.map(c =>
                `<a class="suggestion-item" href="couple.php?id=${c.id}">${c.boy_name} ❤ ${c.girl_name} — ${c.district || ''}</a>`
              ).join('');
              searchSuggestions.classList.add('active');
            } else {
              searchSuggestions.innerHTML = '<div class="suggestion-item">কোন ফলাফল পাওয়া যায়নি</div>';
              searchSuggestions.classList.add('active');
            }
          });
      }, 300);
    });
    document.addEventListener('click', (e) => {
      if (!e.target.closest('.search-box')) searchSuggestions.classList.remove('active');
    });
  }

  // Lazy load images
  const lazyImgs = document.querySelectorAll('img[data-src]');
  if (lazyImgs.length) {
    const imgObserver = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          e.target.src = e.target.dataset.src;
          e.target.removeAttribute('data-src');
          imgObserver.unobserve(e.target);
        }
      });
    });
    lazyImgs.forEach(img => imgObserver.observe(img));
  }

  // Floating hearts
  const heartsContainer = document.querySelector('.floating-hearts');
  if (heartsContainer) {
    const emojis = ['💕','❤️','💖','💗','💘','😍'];
    for (let i = 0; i < 8; i++) {
      const heart = document.createElement('span');
      heart.className = 'heart';
      heart.textContent = emojis[Math.floor(Math.random() * emojis.length)];
      heart.style.left = Math.random() * 100 + '%';
      heart.style.animationDelay = Math.random() * 8 + 's';
      heart.style.animationDuration = (6 + Math.random() * 6) + 's';
      heartsContainer.appendChild(heart);
    }
  }

  // View counter for couple page
  const coupleId = document.querySelector('[data-couple-id]');
  if (coupleId) {
    fetch('couple.php?id=' + coupleId.dataset.coupleId + '&view=1', { method: 'POST' });
  }
});

// Toast notification
function showToast(msg, type = 'success') {
  const container = document.querySelector('.toast-container') || document.body;
  const toast = document.createElement('div');
  toast.className = 'toast ' + type;
  toast.textContent = msg;
  container.appendChild(toast);
  setTimeout(() => toast.remove(), 4000);
}
