/* ============================================================
   Innovare Commercial — Global JS (assets/js/main.js)
   - Loads global header/footer includes
   - Wires nav (mega menu, mobile panel, active state)
   - FAQ accordions, project filters, contact form, scroll reveal
   ============================================================ */
(function () {
  'use strict';

  /* ---------- Include loader ---------- */
  function loadIncludes() {
    var nodes = document.querySelectorAll('[data-include]');
    return Promise.all(Array.prototype.map.call(nodes, function (el) {
      var name = el.getAttribute('data-include');
      return fetch('includes/' + name + '.html')
        .then(function (r) { return r.ok ? r.text() : ''; })
        .then(function (html) { el.outerHTML = html; })
        .catch(function () {});
    }));
  }

  /* ---------- Navigation ---------- */
  function initNav() {
    var page = document.body.getAttribute('data-page');

    // active link
    if (page) {
      document.querySelectorAll('.nav-links [data-nav]').forEach(function (el) {
        if (el.getAttribute('data-nav') === page) el.classList.add('active');
      });
    }

    var servicesToggle = document.getElementById('servicesToggle');
    var mega = document.getElementById('megaMenu');
    var backdrop = document.getElementById('megaBackdrop');

    function closeMega() {
      if (!mega) return;
      mega.classList.remove('open');
      backdrop.classList.remove('show');
      servicesToggle.classList.remove('open');
      servicesToggle.setAttribute('aria-expanded', 'false');
    }
    function openMega() {
      mega.classList.add('open');
      backdrop.classList.add('show');
      servicesToggle.classList.add('open');
      servicesToggle.setAttribute('aria-expanded', 'true');
    }
    if (servicesToggle && mega) {
      servicesToggle.addEventListener('click', function (e) {
        e.stopPropagation();
        mega.classList.contains('open') ? closeMega() : openMega();
      });
      backdrop.addEventListener('click', closeMega);
      document.addEventListener('keydown', function (e) { if (e.key === 'Escape') closeMega(); });
      // open on hover (desktop)
      var navBar = servicesToggle.closest('.nav-bar');
      if (navBar && window.matchMedia('(min-width:861px)').matches) {
        var hideTimer;
        servicesToggle.addEventListener('mouseenter', function () { clearTimeout(hideTimer); openMega(); });
        navBar.addEventListener('mouseleave', function () { hideTimer = setTimeout(closeMega, 180); });
        navBar.addEventListener('mouseenter', function () { clearTimeout(hideTimer); });
      }
    }

    // mobile panel
    var burger = document.getElementById('burger');
    var panel = document.getElementById('mobilePanel');
    var mpClose = document.getElementById('mpClose');
    function openPanel() { panel.classList.add('open'); document.body.style.overflow = 'hidden'; }
    function closePanel() { panel.classList.remove('open'); document.body.style.overflow = ''; }
    if (burger && panel) {
      burger.addEventListener('click', openPanel);
      mpClose.addEventListener('click', closePanel);
      panel.querySelectorAll('a').forEach(function (a) { a.addEventListener('click', closePanel); });
    }

    // footer year
    var y = document.getElementById('footYear');
    if (y) y.textContent = new Date().getFullYear();
  }

  /* ---------- FAQ accordion ---------- */
  function initAccordions() {
    document.querySelectorAll('.acc-q').forEach(function (q) {
      q.addEventListener('click', function () {
        var item = q.closest('.acc-item');
        var body = item.querySelector('.acc-body');
        var isOpen = item.classList.contains('open');
        // optional single-open per accordion group
        var group = q.closest('.acc');
        if (group && !isOpen) {
          group.querySelectorAll('.acc-item.open').forEach(function (other) {
            other.classList.remove('open');
            other.querySelector('.acc-body').style.maxHeight = null;
          });
        }
        if (isOpen) {
          item.classList.remove('open');
          body.style.maxHeight = null;
        } else {
          item.classList.add('open');
          body.style.maxHeight = body.scrollHeight + 'px';
        }
      });
    });
  }

  /* ---------- Project filters ---------- */
  function initFilters() {
    var btns = document.querySelectorAll('.filter-btn');
    if (!btns.length) return;
    btns.forEach(function (btn) {
      btn.addEventListener('click', function () {
        btns.forEach(function (b) { b.classList.remove('active'); });
        btn.classList.add('active');
        var f = btn.getAttribute('data-filter');
        document.querySelectorAll('.project-card').forEach(function (card) {
          var match = f === 'all' || card.getAttribute('data-sector') === f;
          card.classList.toggle('hide', !match);
        });
      });
    });
  }

  /* ---------- Contact form ---------- */
  function initForm() {
    var form = document.getElementById('enquiryForm');
    if (!form) return;
    var success = document.getElementById('formSuccess');

    function setError(field, on) {
      var wrap = field.closest('.field');
      if (wrap) wrap.classList.toggle('error', on);
    }

    form.addEventListener('submit', function (e) {
      e.preventDefault();
      var valid = true;
      var required = form.querySelectorAll('[required]');
      required.forEach(function (field) {
        var val = (field.value || '').trim();
        var ok = !!val;
        if (ok && field.type === 'email') {
          ok = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val);
        }
        setError(field, !ok);
        if (!ok) valid = false;
      });
      if (!valid) {
        var firstErr = form.querySelector('.field.error input, .field.error select, .field.error textarea');
        if (firstErr) firstErr.focus();
        return;
      }
      // success state (no backend — replace action with your endpoint to go live)
      form.style.display = 'none';
      if (success) {
        success.classList.add('show');
        success.scrollIntoView ? null : null;
      }
    });

    // clear error on input
    form.querySelectorAll('input,select,textarea').forEach(function (field) {
      field.addEventListener('input', function () { setError(field, false); });
    });
  }

  /* ---------- Scroll reveal ---------- */
  function initReveal() {
    var els = document.querySelectorAll('[data-reveal]');
    if (!els.length) return;
    if (!('IntersectionObserver' in window)) {
      els.forEach(function (el) { el.classList.add('in'); });
      return;
    }
    var io = new IntersectionObserver(function (entries) {
      entries.forEach(function (en) {
        if (en.isIntersecting) { en.target.classList.add('in'); io.unobserve(en.target); }
      });
    }, { threshold: 0.12, rootMargin: '0px 0px -8% 0px' });
    els.forEach(function (el) { io.observe(el); });
  }

  /* ---------- Boot ---------- */
  function boot() {
    loadIncludes().then(function () {
      initNav();
    });
    initAccordions();
    initFilters();
    initForm();
    initReveal();
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', boot);
  } else {
    boot();
  }
})();
