/* ============================================================
   Innovare Waterproofing — main.js
   Single IIFE. ES5-safe. No libraries.
   ============================================================ */
(function(){
  'use strict';

  /* ---- 1. Load header/footer 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');
        var url = 'includes/' + name + '.html';
        jobs.push(
          fetch(url).then(function(r){ return r.text(); }).then(function(html){
            var wrap = document.createElement('div');
            wrap.innerHTML = html.trim();
            var frag = document.createDocumentFragment();
            while(wrap.firstChild){ frag.appendChild(wrap.firstChild); }
            node.parentNode.replaceChild(frag, node);
          }).catch(function(err){
            console.error('Include failed:', url, err);
          })
        );
      })(nodes[i]);
    }
    return Promise.all(jobs);
  }

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

    /* Mega menu (desktop) */
    var megaItems = document.querySelectorAll('.nav-links li.has-mega');
    for(var i=0;i<megaItems.length;i++){
      (function(li){
        var btn = li.querySelector('button');
        var closeTimer;
        function open(){ clearTimeout(closeTimer); closeAllMega(li); li.classList.add('open'); if(btn) btn.setAttribute('aria-expanded','true'); }
        function close(){ li.classList.remove('open'); if(btn) btn.setAttribute('aria-expanded','false'); }
        if(!isTouch){
          li.addEventListener('mouseenter', open);
          li.addEventListener('mouseleave', function(){ closeTimer = setTimeout(close, 120); });
        }
        if(btn){
          btn.addEventListener('click', function(e){
            e.stopPropagation();
            if(li.classList.contains('open')) close(); else open();
          });
        }
      })(megaItems[i]);
    }
    function closeAllMega(except){
      var open = document.querySelectorAll('.nav-links li.open');
      for(var j=0;j<open.length;j++){ if(open[j]!==except){ open[j].classList.remove('open'); } }
    }
    document.addEventListener('click', function(){ closeAllMega(null); });
    document.addEventListener('keydown', function(e){
      if(e.key==='Escape'){ closeAllMega(null); closeMobile(); }
    });

    /* 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 openMobile(){ if(panel){ panel.classList.add('show'); } if(scrim){ scrim.classList.add('show'); } document.body.style.overflow='hidden'; }
    function closeMobile(){ if(panel){ panel.classList.remove('show'); } if(scrim){ scrim.classList.remove('show'); } document.body.style.overflow=''; }
    if(burger){ burger.addEventListener('click', openMobile); }
    if(closeBtn){ closeBtn.addEventListener('click', closeMobile); }
    if(scrim){ scrim.addEventListener('click', closeMobile); }

    /* Mobile collapsible groups */
    var groups = document.querySelectorAll('.mp-group');
    for(var g=0;g<groups.length;g++){
      (function(group){
        var gb = group.querySelector('button');
        var sub = group.querySelector('.mp-sub');
        if(gb && sub){
          gb.addEventListener('click', function(){
            var isOpen = group.classList.contains('open');
            if(isOpen){ group.classList.remove('open'); sub.style.maxHeight = '0px'; }
            else{ group.classList.add('open'); sub.style.maxHeight = sub.scrollHeight + 'px'; }
          });
        }
      })(groups[g]);
    }

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

  /* ---- 3. Accordions (single-open per group) ---- */
  function initAccordions(){
    var accs = document.querySelectorAll('.acc');
    for(var a=0;a<accs.length;a++){
      (function(acc){
        var items = acc.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');
              // close siblings in same acc
              for(var k=0;k<items.length;k++){
                items[k].classList.remove('open');
                var b = items[k].querySelector('.acc-body');
                if(b){ b.style.maxHeight = '0px'; }
                var qq = items[k].querySelector('.acc-q');
                if(qq){ qq.setAttribute('aria-expanded','false'); }
              }
              if(!isOpen){
                item.classList.add('open');
                body.style.maxHeight = body.scrollHeight + 'px';
                q.setAttribute('aria-expanded','true');
              }
            });
          })(items[i]);
        }
      })(accs[a]);
    }
    // recalc open items on resize
    var rt;
    window.addEventListener('resize', function(){
      clearTimeout(rt);
      rt = setTimeout(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'; }
      }, 150);
    });
  }

  /* ---- 4. Project filters ---- */
  function initFilters(){
    var rows = document.querySelectorAll('.filter-row');
    for(var r=0;r<rows.length;r++){
      (function(row){
        var btns = 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 b=0;b<btns.length;b++){
          (function(btn){
            btn.addEventListener('click', function(){
              for(var k=0;k<btns.length;k++){ btns[k].classList.remove('active'); }
              btn.classList.add('active');
              var target = btn.getAttribute('data-target');
              for(var c=0;c<cards.length;c++){
                var sectors = cards[c].getAttribute('data-sector') || '';
                var show = (target==='all') || (sectors.indexOf(target) !== -1);
                cards[c].style.display = show ? '' : 'none';
              }
            });
          })(btns[b]);
        }
      })(rows[r]);
    }
  }

  /* ---- 5. Contact form validation (no backend) ---- */
  function initForm(){
    var forms = document.querySelectorAll('form[data-contact-form]');
    for(var f=0;f<forms.length;f++){
      (function(form){
        var emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        form.addEventListener('submit', function(e){
          e.preventDefault();
          var required = form.querySelectorAll('[data-required]');
          var ok = true;
          for(var i=0;i<required.length;i++){
            var el = required[i];
            var field = el.closest('.field');
            var val = (el.value || '').trim();
            var invalid = !val;
            if(!invalid && el.type==='email'){ invalid = !emailRe.test(val); }
            if(invalid){ ok = false; if(field) field.classList.add('invalid'); }
            else if(field){ field.classList.remove('invalid'); }
          }
          if(!ok) return;
          var success = form.parentNode.querySelector('.form-success');
          form.style.display = 'none';
          if(success){ success.classList.add('show'); }
        });
        // clear invalid on input
        var fields = form.querySelectorAll('[data-required]');
        for(var j=0;j<fields.length;j++){
          fields[j].addEventListener('input', function(){
            var field = this.closest('.field');
            if(field){ field.classList.remove('invalid'); }
          });
        }
      })(forms[f]);
    }
  }

  /* ---- 6. Reveal on scroll ---- */
  function initReveal(){
    var els = document.querySelectorAll('[data-reveal]');
    if(!('IntersectionObserver' in window)){
      for(var i=0;i<els.length;i++){ els[i].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); }
      });
    }, { threshold:0.12, rootMargin:'0px 0px -40px 0px' });
    for(var k=0;k<els.length;k++){ io.observe(els[k]); }
  }

  /* ---- Boot ---- */
  document.addEventListener('DOMContentLoaded', function(){
    loadIncludes().then(function(){
      initNav();
      initAccordions();
      initFilters();
      initForm();
      initReveal();
    });
  });
})();
