/* =========================================================================
   Innovare Roofing — main.js
   Single IIFE, ES5-safe, no libraries.
   Handles: runtime includes, nav (mega + mobile), accordions, project
   filters, contact form validation, scroll reveal.
   ========================================================================= */
(function () {
  'use strict';

  /* ---------- 1. Includes ---------- */
  function loadIncludes() {
    var nodes = document.querySelectorAll('[data-include]');
    var jobs = [];
    for (var i = 0; i < nodes.length; i++) {
      (function (node) {
        var name = node.getAttribute('data-include');
        jobs.push(
          fetch('includes/' + name + '.html')
            .then(function (r) { return r.ok ? r.text() : ''; })
            .then(function (html) {
              if (!html) return;
              var wrap = document.createElement('div');
              wrap.innerHTML = html;
              var frag = document.createDocumentFragment();
              while (wrap.firstChild) frag.appendChild(wrap.firstChild);
              node.parentNode.replaceChild(frag, node);
            })
            .catch(function () {})
        );
      })(nodes[i]);
    }
    return Promise.all(jobs);
  }

  /* ---------- 2. Nav ---------- */
  function initNav() {
    var isTouch = window.matchMedia('(hover: none)').matches || 'ontouchstart' in window;

    /* Mega menu (desktop) */
    var megas = document.querySelectorAll('.has-mega');
    for (var i = 0; i < megas.length; i++) {
      (function (li) {
        var link = li.querySelector('a');
        if (!isTouch) {
          li.addEventListener('mouseenter', function () { closeAllMega(); li.classList.add('open'); });
          li.addEventListener('mouseleave', function () { li.classList.remove('open'); });
        }
        if (link) {
          link.addEventListener('click', function (e) {
            if (li.querySelector('.mega')) {
              e.preventDefault();
              var wasOpen = li.classList.contains('open');
              closeAllMega();
              if (!wasOpen) li.classList.add('open');
            }
          });
        }
      })(megas[i]);
    }
    function closeAllMega() {
      for (var j = 0; j < megas.length; j++) megas[j].classList.remove('open');
    }
    document.addEventListener('click', function (e) {
      if (!e.target.closest('.has-mega')) closeAllMega();
    });
    document.addEventListener('keydown', function (e) {
      if (e.key === 'Escape') { closeAllMega(); closeMobile(); }
    });

    /* Mobile panel */
    var burger = document.querySelector('.nav-burger');
    var panel = document.querySelector('.mobile-panel');
    var scrim = document.querySelector('.scrim');
    var close = document.querySelector('.mp-close');
    function openMobile() { if (panel) panel.classList.add('open'); if (scrim) scrim.classList.add('open'); document.body.style.overflow = 'hidden'; }
    function closeMobile() { if (panel) panel.classList.remove('open'); if (scrim) scrim.classList.remove('open'); document.body.style.overflow = ''; }
    if (burger) burger.addEventListener('click', openMobile);
    if (close) close.addEventListener('click', closeMobile);
    if (scrim) scrim.addEventListener('click', closeMobile);

    /* Mobile collapsible service groups */
    var toggles = document.querySelectorAll('.mp-group-toggle');
    for (var k = 0; k < toggles.length; k++) {
      toggles[k].addEventListener('click', function () {
        var group = this.parentNode;
        var list = group.querySelector('.mp-group-list');
        var isOpen = group.classList.toggle('open');
        list.style.maxHeight = isOpen ? list.scrollHeight + 'px' : '0';
      });
    }

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

  /* ---------- 3. Accordions ---------- */
  function initAccordions() {
    var groups = document.querySelectorAll('.acc');
    for (var g = 0; g < groups.length; g++) {
      (function (group) {
        var items = group.querySelectorAll('.acc-item');
        for (var i = 0; i < items.length; i++) {
          (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');
              for (var j = 0; j < items.length; j++) {
                items[j].classList.remove('open');
                var b = items[j].querySelector('.acc-body');
                if (b) b.style.maxHeight = '0';
              }
              if (!isOpen) {
                item.classList.add('open');
                body.style.maxHeight = body.scrollHeight + 'px';
              }
            });
          })(items[i]);
        }
      })(groups[g]);
    }
    window.addEventListener('resize', function () {
      var open = document.querySelectorAll('.acc-item.open .acc-body');
      for (var i = 0; i < open.length; i++) open[i].style.maxHeight = open[i].scrollHeight + 'px';
    });
  }

  /* ---------- 4. Project filters ---------- */
  function initFilters() {
    var rows = document.querySelectorAll('.filter-row');
    for (var r = 0; r < rows.length; r++) {
      (function (row) {
        var buttons = row.querySelectorAll('.filter-btn');
        var gridSel = row.getAttribute('data-grid') || '.project-grid';
        var grid = document.querySelector(gridSel);
        if (!grid) return;
        var cards = grid.querySelectorAll('[data-sector]');
        for (var i = 0; i < buttons.length; i++) {
          buttons[i].addEventListener('click', function () {
            for (var j = 0; j < buttons.length; j++) buttons[j].classList.remove('active');
            this.classList.add('active');
            var target = this.getAttribute('data-target');
            for (var c = 0; c < cards.length; c++) {
              var sectors = cards[c].getAttribute('data-sector').split(/\s+/);
              var show = target === 'all' || sectors.indexOf(target) !== -1;
              cards[c].style.display = show ? '' : 'none';
            }
          });
        }
      })(rows[r]);
    }
  }

  /* ---------- 5. Contact form ---------- */
  function initForm() {
    var forms = document.querySelectorAll('form[data-contact]');
    var emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    for (var f = 0; f < forms.length; f++) {
      (function (form) {
        form.addEventListener('submit', function (e) {
          e.preventDefault();
          var fields = form.querySelectorAll('[data-required]');
          var ok = true;
          for (var i = 0; i < fields.length; i++) {
            var input = fields[i];
            var wrap = input.closest('.field');
            var val = (input.value || '').trim();
            var valid = !!val;
            if (valid && input.type === 'email') valid = emailRe.test(val);
            if (wrap) wrap.classList.toggle('invalid', !valid);
            if (!valid) ok = false;
          }
          if (!ok) {
            var firstBad = form.querySelector('.field.invalid input, .field.invalid select, .field.invalid textarea');
            if (firstBad) firstBad.focus();
            return;
          }
          var body = form.querySelector('.form-body');
          var success = form.querySelector('.form-success');
          if (body) body.style.display = 'none';
          if (success) success.classList.add('show');
        });
        /* clear error as user types */
        var inputs = form.querySelectorAll('input, select, textarea');
        for (var n = 0; n < inputs.length; n++) {
          inputs[n].addEventListener('input', function () {
            var wrap = this.closest('.field');
            if (wrap) wrap.classList.remove('invalid');
          });
        }
      })(forms[f]);
    }
  }

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

  /* ---------- Boot ---------- */
  function boot() {
    loadIncludes().then(function () {
      initNav();
      initAccordions();
      initFilters();
      initForm();
      initReveal();
    });
  }
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', boot);
  } else {
    boot();
  }
})();
