/* ==========================================================================
   Innovare Demolitions — Global Script (all behavior, one file)
   IIFE · 'use strict' · vanilla ES5-compatible · no libraries, no build.
   ========================================================================== */
(function () {
  'use strict';

  /* ---- includes: fetch header/footer into [data-include] --------------- */
  function loadIncludes() {
    var nodes = document.querySelectorAll('[data-include]');
    var jobs = [];
    Array.prototype.forEach.call(nodes, function (node) {
      var name = node.getAttribute('data-include');
      var job = fetch('includes/' + name + '.html')
        .then(function (r) { return r.ok ? r.text() : ''; })
        .then(function (html) {
          if (html) {
            var tpl = document.createElement('div');
            tpl.innerHTML = html;
            node.replaceWith.apply(node, Array.prototype.slice.call(tpl.childNodes));
          }
        })
        .catch(function () { /* fail safe: leave node empty */ });
      jobs.push(job);
    });
    return Promise.all(jobs);
  }

  /* ---- nav: active state, mega menu, mobile panel, footer year --------- */
  function initNav() {
    var body = document.body;
    var page = body.getAttribute('data-page');

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

    // mega menu
    var servicesItem = document.querySelector('.nav-services');
    var toggle = document.getElementById('servicesToggle');
    var mega = document.getElementById('megaMenu');
    var isDesktop = function () { return window.matchMedia('(min-width:861px)').matches; };

    if (toggle && mega) {
      var openMega = function () { mega.classList.add('open'); toggle.setAttribute('aria-expanded', 'true'); };
      var closeMega = function () { mega.classList.remove('open'); toggle.setAttribute('aria-expanded', 'false'); };

      toggle.addEventListener('click', function (e) {
        e.preventDefault();
        if (mega.classList.contains('open')) { closeMega(); } else { openMega(); }
      });
      if (servicesItem) {
        servicesItem.addEventListener('mouseenter', function () { if (isDesktop()) { openMega(); } });
        servicesItem.addEventListener('mouseleave', function () { if (isDesktop()) { closeMega(); } });
      }
      document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape') { closeMega(); }
      });
      document.addEventListener('click', function (e) {
        if (servicesItem && !servicesItem.contains(e.target)) { closeMega(); }
      });
    }

    // mobile panel
    var burger = document.getElementById('navBurger');
    var panel = document.getElementById('mobilePanel');
    var closeBtn = document.getElementById('mobileClose');
    var scrim = document.getElementById('scrim');
    if (burger && panel) {
      var openPanel = function () {
        panel.classList.add('open');
        if (scrim) { scrim.classList.add('open'); }
        body.style.overflow = 'hidden';
        burger.setAttribute('aria-expanded', 'true');
      };
      var closePanel = function () {
        panel.classList.remove('open');
        if (scrim) { scrim.classList.remove('open'); }
        body.style.overflow = '';
        burger.setAttribute('aria-expanded', 'false');
      };
      burger.addEventListener('click', openPanel);
      if (closeBtn) { closeBtn.addEventListener('click', closePanel); }
      if (scrim) { scrim.addEventListener('click', closePanel); }
      document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape') { closePanel(); }
      });
    }
  }

  /* ---- accordions: single-open per group ------------------------------- */
  function initAccordions() {
    var groups = document.querySelectorAll('.acc');
    if (!groups.length) { return; }
    Array.prototype.forEach.call(groups, function (group) {
      var items = group.querySelectorAll('.acc-item');
      Array.prototype.forEach.call(items, function (item) {
        var q = item.querySelector('.acc-q');
        var body = item.querySelector('.acc-body');
        if (!q || !body) { return; }
        q.addEventListener('click', function () {
          var isOpen = item.classList.contains('open');
          // close siblings
          Array.prototype.forEach.call(items, function (other) {
            if (other !== item) {
              other.classList.remove('open');
              var ob = other.querySelector('.acc-body');
              if (ob) { ob.style.maxHeight = null; }
              var oq = other.querySelector('.acc-q');
              if (oq) { oq.setAttribute('aria-expanded', 'false'); }
            }
          });
          if (isOpen) {
            item.classList.remove('open');
            body.style.maxHeight = null;
            q.setAttribute('aria-expanded', 'false');
          } else {
            item.classList.add('open');
            body.style.maxHeight = body.scrollHeight + 'px';
            q.setAttribute('aria-expanded', 'true');
          }
        });
      });
    });
  }

  /* ---- filters: project grid ------------------------------------------- */
  function initFilters() {
    var rows = document.querySelectorAll('.filter-row');
    if (!rows.length) { return; }
    Array.prototype.forEach.call(rows, function (row) {
      var btns = row.querySelectorAll('.filter-btn');
      var grid = document.querySelector('.project-grid');
      if (!grid) { return; }
      var cards = grid.querySelectorAll('.project-card');
      Array.prototype.forEach.call(btns, function (btn) {
        btn.addEventListener('click', function () {
          var filter = btn.getAttribute('data-filter');
          Array.prototype.forEach.call(btns, function (b) { b.classList.remove('active'); });
          btn.classList.add('active');
          Array.prototype.forEach.call(cards, function (card) {
            var sector = card.getAttribute('data-sector') || '';
            if (filter === 'all' || sector.indexOf(filter) !== -1) {
              card.classList.remove('hide');
            } else {
              card.classList.add('hide');
            }
          });
        });
      });
    });
  }

  /* ---- form: validation + success swap --------------------------------- */
  function initForm() {
    var form = document.getElementById('enquiryForm');
    if (!form) { return; }
    var success = document.getElementById('formSuccess');
    var emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

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

    form.addEventListener('submit', function (e) {
      e.preventDefault();
      var valid = true;
      var required = form.querySelectorAll('[required]');
      Array.prototype.forEach.call(required, function (field) {
        var val = (field.value || '').trim();
        var ok = !!val;
        if (ok && field.type === 'email') { ok = emailRe.test(val); }
        setError(field, !ok);
        if (!ok && valid) { field.focus(); }
        if (!ok) { valid = false; }
      });
      if (!valid) { return; }
      form.style.display = 'none';
      if (success) { success.classList.add('show'); }
    });

    // clear error on input
    var fields = form.querySelectorAll('input, select, textarea');
    Array.prototype.forEach.call(fields, function (field) {
      field.addEventListener('input', function () { setError(field, false); });
    });
  }

  /* ---- reveal: IntersectionObserver, fail safe ------------------------- */
  function initReveal() {
    var els = document.querySelectorAll('[data-reveal]');
    if (!els.length) { return; }
    if (!('IntersectionObserver' in window)) {
      Array.prototype.forEach.call(els, function (el) { el.classList.add('in'); });
      return;
    }
    var io = new IntersectionObserver(function (entries) {
      entries.forEach(function (entry) {
        if (entry.isIntersecting) {
          entry.target.classList.add('in');
          io.unobserve(entry.target);
        }
      });
    }, { rootMargin: '0px 0px -8% 0px', threshold: 0.08 });
    Array.prototype.forEach.call(els, 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();
  }
})();
