/* ═══════════════════════════════════════════════════════════════
   THE HINDU — Main JavaScript
═══════════════════════════════════════════════════════════════ */

(function () {
  'use strict';

  // ── Mega Menu ────────────────────────────────────────────────
  const menuToggle  = document.getElementById('menuToggle');
  const megaMenu    = document.getElementById('megaMenu');
  const menuClose   = document.getElementById('menuClose');
  const menuOverlay = document.getElementById('menuOverlay');

  function openMenu() {
    if (!megaMenu) return;
    megaMenu.classList.add('active');
    menuOverlay && menuOverlay.classList.add('active');
    menuToggle && menuToggle.setAttribute('aria-expanded', 'true');
    document.body.style.overflow = 'hidden';
  }

  function closeMenu() {
    if (!megaMenu) return;
    megaMenu.classList.remove('active');
    menuOverlay && menuOverlay.classList.remove('active');
    menuToggle && menuToggle.setAttribute('aria-expanded', 'false');
    document.body.style.overflow = '';
  }

  menuToggle  && menuToggle.addEventListener('click', openMenu);
  menuClose   && menuClose.addEventListener('click', closeMenu);
  menuOverlay && menuOverlay.addEventListener('click', closeMenu);

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

  // ── Subscribe Modal ──────────────────────────────────────────
  const openBtn   = document.getElementById('openModal');
  const closeBtn  = document.getElementById('closeModal');
  const modal     = document.getElementById('subscribeModal');

  openBtn  && openBtn.addEventListener('click', function () { modal && modal.classList.add('show'); });
  closeBtn && closeBtn.addEventListener('click', function () { modal && modal.classList.remove('show'); });
  modal    && modal.addEventListener('click', function (e) { if (e.target === modal) modal.classList.remove('show'); });

  // AJAX subscribe form
  const subForm = document.getElementById('subscribeForm');
  if (subForm) {
    subForm.addEventListener('submit', async function (e) {
      e.preventDefault();
      const msg = document.getElementById('subscribeMsg');
      const btn = subForm.querySelector('.subscribe-submit');
      const orig = btn.textContent;
      btn.textContent = 'Subscribing…';
      btn.disabled = true;
      try {
        const fd = new FormData(subForm);
        const res = await fetch(subForm.action, {
          method: 'POST',
          headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' },
          body: fd,
        });
        const data = await res.json();
        if (msg) {
          msg.textContent = data.message || 'Thank you for subscribing!';
          msg.style.color = res.ok ? 'green' : 'red';
        }
        if (res.ok) subForm.reset();
      } catch (err) {
        if (msg) { msg.textContent = 'Something went wrong. Please try again.'; msg.style.color = 'red'; }
      } finally {
        btn.textContent = orig;
        btn.disabled = false;
      }
    });
  }

  // ── Back to Top ──────────────────────────────────────────────
  const backTop = document.getElementById('backToTop');
  if (backTop) {
    backTop.addEventListener('click', function () {
      window.scrollTo({ top: 0, behavior: 'smooth' });
    });
    window.addEventListener('scroll', function () {
      backTop.style.opacity = window.scrollY > 400 ? '1' : '0.3';
    }, { passive: true });
  }

  // ── Lazy image loading fallback ──────────────────────────────
  if ('loading' in HTMLImageElement.prototype === false) {
    const imgs = document.querySelectorAll('img[loading="lazy"]');
    const io = new IntersectionObserver(function (entries) {
      entries.forEach(function (entry) {
        if (entry.isIntersecting) {
          const img = entry.target;
          if (img.dataset.src) { img.src = img.dataset.src; }
          io.unobserve(img);
        }
      });
    });
    imgs.forEach(function (img) { io.observe(img); });
  }

  // ── Share copy button feedback ──────────────────────────────
  document.querySelectorAll('.share-copy').forEach(function (btn) {
    btn.addEventListener('click', function () {
      const orig = btn.innerHTML;
      btn.innerHTML = '<i class="fa-solid fa-check"></i>';
      setTimeout(function () { btn.innerHTML = orig; }, 1500);
    });
  });

  // ── Header scroll shadow ────────────────────────────────────
  const header = document.getElementById('site-header');
  if (header) {
    window.addEventListener('scroll', function () {
      header.style.boxShadow = window.scrollY > 30
        ? '0 2px 12px rgba(0,0,0,.15)'
        : '0 1px 4px rgba(0,0,0,.08)';
    }, { passive: true });
  }

  // ── Reading progress bar ─────────────────────────────────────
  if (document.querySelector('.det-body')) {
    const bar = document.createElement('div');
    bar.style.cssText = 'position:fixed;top:0;left:0;height:3px;background:#c40018;z-index:9999;width:0;transition:width .1s;';
    document.body.appendChild(bar);
    window.addEventListener('scroll', function () {
      const el = document.documentElement;
      const pct = (el.scrollTop / (el.scrollHeight - el.clientHeight)) * 100;
      bar.style.width = Math.min(pct, 100) + '%';
    }, { passive: true });
  }

})();

// Search toggle
const searchToggle = document.getElementById('searchToggle');
const searchDropdown = document.getElementById('searchDropdown');
const searchInput = document.getElementById('searchInput');

searchToggle.addEventListener('click', () => {
  const isOpen = searchDropdown.classList.toggle('open');
  searchToggle.setAttribute('aria-expanded', isOpen);
  searchDropdown.setAttribute('aria-hidden', !isOpen);
  if (isOpen) searchInput.focus();
});

// Close on outside click
document.addEventListener('click', (e) => {
  if (!searchDropdown.contains(e.target) && !searchToggle.contains(e.target)) {
    searchDropdown.classList.remove('open');
    searchToggle.setAttribute('aria-expanded', false);
  }
});

// Close on Escape
document.addEventListener('keydown', (e) => {
  if (e.key === 'Escape') searchDropdown.classList.remove('open');
});
