/* ================================================================
   MindRealigned V3 — Script (countdown, FAQ, sticky bar, scroll, register)
   ================================================================ */

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

  /* ── Smooth scroll CTAs (prevent hash sticking on refresh) ──── */
  if (window.location.hash) {
    history.replaceState(null, '', window.location.pathname);
    window.scrollTo(0, 0);
  }
  document.querySelectorAll('a[href="#register-form"]').forEach(link => {
    link.addEventListener('click', (e) => {
      e.preventDefault();
      const target = document.getElementById('register-form');
      if (target) target.scrollIntoView({ behavior: 'smooth', block: 'center' });
    });
  });

  /* ── Countdown Timers ────────────────────────────────────────── */
  document.querySelectorAll('.countdown').forEach(el => {
    const deadline = el.dataset.deadline;
    if (!deadline) return;
    const target = new Date(deadline.replace(' ', 'T'));

    function tick() {
      const now = new Date();
      let diff = target - now;
      if (diff <= 0) diff = 0;
      const s = Math.floor(diff / 1000);
      const d = Math.floor(s / 86400);
      const h = Math.floor((s % 86400) / 3600);
      const m = Math.floor((s % 3600) / 60);
      const sec = s % 60;
      const pad = n => String(n).padStart(2, '0');
      const cards = el.querySelectorAll('.countdown-card');
      if (cards[0]) cards[0].querySelector('.val').textContent = pad(d);
      if (cards[1]) cards[1].querySelector('.val').textContent = pad(h);
      if (cards[2]) cards[2].querySelector('.val').textContent = pad(m);
      if (cards[3]) cards[3].querySelector('.val').textContent = pad(sec);
    }
    tick();
    setInterval(tick, 1000);
  });

  /* ── Sticky Bottom Bar ───────────────────────────────────────── */
  const stickyBar = document.querySelector('.sticky-bar');
  if (stickyBar) {
    let timer = 15 * 60;
    const timerEl = stickyBar.querySelector('.timer');
    setInterval(() => {
      const mm = Math.floor(timer / 60);
      const ss = timer % 60;
      if (timerEl) timerEl.textContent =
        String(mm).padStart(2, '0') + ':' + String(ss).padStart(2, '0');
      if (--timer < 0) timer = 15 * 60;
    }, 1000);

    window.addEventListener('scroll', () => {
      stickyBar.classList.toggle('visible', window.scrollY > 400);
    });
  }

  /* ── FAQ Accordion ───────────────────────────────────────────── */
  document.querySelectorAll('.faq-item .faq-q').forEach(q => {
    q.addEventListener('click', () => {
      const item = q.parentElement;
      const wasOpen = item.classList.contains('open');
      document.querySelectorAll('.faq-item.open').forEach(i => i.classList.remove('open'));
      if (!wasOpen) item.classList.add('open');
    });
  });

  /* ── Scroll Reveal (all variants) ──────────────────────────── */
  const revealSelectors = '.reveal, .reveal-left, .reveal-right, .reveal-scale, .stagger-children';
  const reveals = document.querySelectorAll(revealSelectors);
  if (reveals.length) {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          e.target.classList.add('revealed');
          observer.unobserve(e.target);
        }
      });
    }, { threshold: 0.1, rootMargin: '0px 0px -50px 0px' });
    reveals.forEach(el => observer.observe(el));
  }
});

/* ── Registration Form Handler ─────────────────────────────── */
function handleRegister(e) {
  e.preventDefault();
  const name = document.getElementById('reg-name').value.trim();
  const email = document.getElementById('reg-email').value.trim();
  const phone = document.getElementById('reg-phone').value.trim();

  if (!name || !email || !phone) {
    alert('Please fill in all fields.');
    return false;
  }

  // Store locally (wire to your backend/API as needed)
  const registration = { name, email, phone, timestamp: new Date().toISOString() };
  const existing = JSON.parse(localStorage.getItem('mr_registrations') || '[]');
  existing.push(registration);
  localStorage.setItem('mr_registrations', JSON.stringify(existing));

  // Show success
  const form = e.target;
  form.innerHTML = '<div style="text-align:center;padding:30px 0">'
    + '<svg width="60" height="60" viewBox="0 0 60 60" fill="none"><circle cx="30" cy="30" r="30" fill="#f0faf0"/><path d="M20 30l7 7 13-13" stroke="#228B22" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/></svg>'
    + '<h3 style="margin-top:16px;color:#228B22;font-size:20px">You\'re In!</h3>'
    + '<p style="color:#666;margin-top:8px;font-size:14px">Check your inbox for the Zoom link and your free Pre-Webinar Workbook.</p>'
    + '<p style="color:#999;margin-top:12px;font-size:13px">See you on Saturday, April 5 at 11:00 AM IST!</p>'
    + '</div>';

  return false;
}
