/* =====================================================================
   Innovare Renovations — main.js
   Single IIFE. ES5-safe, no libraries. Runtime includes + interactions.
   ===================================================================== */
(function () {
  'use strict';

  /* ---------- 1. includes ---------- */
  function loadIncludes() {
    var nodes = Array.prototype.slice.call(document.querySelectorAll('[data-include]'));
    return Promise.all(nodes.map(function (node) {
      var name = node.getAttribute('data-include');
      return 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 () {});
    }));
  }

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

    /* mega menu (desktop) */
    var megas = Array.prototype.slice.call(document.querySelectorAll('.has-mega'));
    megas.forEach(function (li) {
      var btn = li.querySelector('button');
      var closeTimer;
      function open() { clearTimeout(closeTimer); megas.forEach(function (o) { if (o !== li) o.classList.remove('open'); }); li.classList.add('open'); }
      function close() { li.classList.remove('open'); }
      if (isTouch) {
        if (btn) btn.addEventListener('click', function (e) { e.preventDefault(); li.classList.contains('open') ? close() : open(); });
      } else {
        li.addEventListener('mouseenter', open);
        li.addEventListener('mouseleave', function () { closeTimer = setTimeout(close, 120); });
        if (btn) btn.addEventListener('focus', open);
      }
    });
    document.addEventListener('keydown', function (e) { if (e.key === 'Escape') megas.forEach(function (o) { o.classList.remove('open'); }); });
    document.addEventListener('click', function (e) {
      if (!e.target.closest('.has-mega')) megas.forEach(function (o) { o.classList.remove('open'); });
    });

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

    /* mobile collapsible groups */
    Array.prototype.slice.call(document.querySelectorAll('.mp-group > button')).forEach(function (b) {
      b.addEventListener('click', function () {
        var g = b.parentNode;
        var sub = g.querySelector('.mp-sub');
        var isOpen = g.classList.toggle('open');
        if (sub) sub.style.maxHeight = isOpen ? sub.scrollHeight + 'px' : '0px';
      });
    });

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

  /* ---------- 3. accordions ---------- */
  function initAccordions() {
    var items = Array.prototype.slice.call(document.querySelectorAll('.acc-item'));
    items.forEach(function (item) {
      var q = item.querySelector('.acc-q');
      var body = item.querySelector('.acc-body');
      if (!q || !body) return;
      q.addEventListener('click', function () {
        var group = item.closest('.acc');
        var willOpen = !item.classList.contains('open');
        if (group) {
          Array.prototype.slice.call(group.querySelectorAll('.acc-item.open')).forEach(function (o) {
            if (o !== item) { o.classList.remove('open'); var ob = o.querySelector('.acc-body'); if (ob) ob.style.maxHeight = '0px'; }
          });
        }
        if (willOpen) { item.classList.add('open'); body.style.maxHeight = body.scrollHeight + 'px'; }
        else { item.classList.remove('open'); body.style.maxHeight = '0px'; }
      });
    });
    window.addEventListener('resize', function () {
      items.forEach(function (item) {
        if (item.classList.contains('open')) { var b = item.querySelector('.acc-body'); if (b) b.style.maxHeight = b.scrollHeight + 'px'; }
      });
    });
  }

  /* ---------- 4. project filters ---------- */
  function initFilters() {
    var rows = Array.prototype.slice.call(document.querySelectorAll('.filter-row'));
    rows.forEach(function (row) {
      var btns = Array.prototype.slice.call(row.querySelectorAll('.filter-btn'));
      var grid = document.querySelector(row.getAttribute('data-target') || '.project-grid');
      if (!grid) return;
      var cards = Array.prototype.slice.call(grid.querySelectorAll('[data-sector]'));
      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');
          cards.forEach(function (card) {
            var sectors = (card.getAttribute('data-sector') || '').split(/\s+/);
            var show = (f === 'all') || sectors.indexOf(f) !== -1;
            card.style.display = show ? '' : 'none';
          });
        });
      });
    });
  }

  /* ---------- 5. contact form ---------- */
  function initForm() {
    var form = document.querySelector('form[data-form]');
    if (!form) return;
    var emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    function validateField(field) {
      var input = field.querySelector('input,select,textarea');
      if (!input) return true;
      var val = (input.value || '').trim();
      var ok = true;
      if (input.hasAttribute('data-required') && !val) ok = false;
      if (ok && input.type === 'email' && val && !emailRe.test(val)) ok = false;
      field.classList.toggle('invalid', !ok);
      return ok;
    }
    Array.prototype.slice.call(form.querySelectorAll('.field')).forEach(function (field) {
      var input = field.querySelector('input,select,textarea');
      if (input) input.addEventListener('blur', function () { validateField(field); });
    });
    form.addEventListener('submit', function (e) {
      e.preventDefault();
      var fields = Array.prototype.slice.call(form.querySelectorAll('.field'));
      var allOk = true;
      fields.forEach(function (field) { if (!validateField(field)) allOk = false; });
      if (!allOk) { var bad = form.querySelector('.field.invalid'); if (bad) bad.querySelector('input,select,textarea').focus(); return; }
      var card = form.closest('.form-card');
      var success = document.querySelector('.form-success');
      if (card) card.classList.add('submitted');
      if (success) success.classList.add('show');
    });
  }

  /* ---------- 6. reveal on scroll ---------- */
  function initReveal() {
    var els = Array.prototype.slice.call(document.querySelectorAll('[data-reveal]'));
    if (!els.length) return;
    if (!('IntersectionObserver' in window) || window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
      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 ---------- */
  document.addEventListener('DOMContentLoaded', function () {
    loadIncludes().then(function () {
      initNav();
      initAccordions();
      initFilters();
      initForm();
      initReveal();
    });
  });
})();
