/* =====================================================================
   Innovare Restoration — main.js
   Single IIFE. ES5-safe, no libraries.
   Loads shared header/footer, then wires nav, accordions, filters,
   contact form and scroll-reveal.
   ===================================================================== */
(function(){
  'use strict';

  /* ---------- 1. Includes ---------- */
  function loadIncludes(){
    var nodes = [].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){ if(!r.ok){ throw new Error(name); } return r.text(); })
        .then(function(html){
          var tmp = document.createElement('div');
          tmp.innerHTML = html;
          var frag = document.createDocumentFragment();
          while(tmp.firstChild){ frag.appendChild(tmp.firstChild); }
          node.parentNode.replaceChild(frag, node);
        })
        .catch(function(err){
          console.warn('Include failed:', err.message);
        });
    }));
  }

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

    /* Mega menu (desktop) */
    var megaItems = [].slice.call(document.querySelectorAll('.nav-links > li.has-mega'));
    var closeTimer;
    megaItems.forEach(function(li){
      var link = li.querySelector('a');
      if(!isTouch){
        li.addEventListener('mouseenter', function(){
          clearTimeout(closeTimer);
          megaItems.forEach(function(o){ if(o!==li){ o.classList.remove('open'); } });
          li.classList.add('open');
        });
        li.addEventListener('mouseleave', function(){
          closeTimer = setTimeout(function(){ li.classList.remove('open'); }, 120);
        });
      }
      if(link){
        link.addEventListener('click', function(e){
          if(isTouch || e.target.closest('.chev') || link.getAttribute('href') === '#'){
            e.preventDefault();
            var wasOpen = li.classList.contains('open');
            megaItems.forEach(function(o){ o.classList.remove('open'); });
            if(!wasOpen){ li.classList.add('open'); }
          }
        });
      }
    });
    document.addEventListener('click', function(e){
      if(!e.target.closest('.has-mega')){
        megaItems.forEach(function(o){ o.classList.remove('open'); });
      }
    });
    document.addEventListener('keydown', function(e){
      if(e.key === 'Escape'){
        megaItems.forEach(function(o){ o.classList.remove('open'); });
        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('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(closeBtn){ closeBtn.addEventListener('click', closeMobile); }
    if(scrim){ scrim.addEventListener('click', closeMobile); }

    /* Mobile collapsible groups */
    [].slice.call(document.querySelectorAll('.mp-group > button')).forEach(function(btn){
      btn.addEventListener('click', function(){
        btn.parentNode.classList.toggle('open');
      });
    });

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

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

  /* ---------- 4. Project filters ---------- */
  function initFilters(){
    var rows = [].slice.call(document.querySelectorAll('.filter-row'));
    rows.forEach(function(row){
      var grid = document.querySelector(row.getAttribute('data-target') || '.project-grid');
      if(!grid){ return; }
      var cards = [].slice.call(grid.querySelectorAll('[data-sector]'));
      var btns = [].slice.call(row.querySelectorAll('.filter-btn'));
      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 forms = [].slice.call(document.querySelectorAll('form[data-contact]'));
    var emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    forms.forEach(function(form){
      form.addEventListener('submit', function(e){
        e.preventDefault();
        var valid = true;
        [].slice.call(form.querySelectorAll('[data-required]')).forEach(function(input){
          var field = input.closest('.field');
          var val = (input.value || '').trim();
          var ok = val.length > 0;
          if(ok && input.type === 'email'){ ok = emailRe.test(val); }
          if(input.type === 'email' && val.length && !emailRe.test(val)){ ok = false; }
          if(field){ field.classList.toggle('invalid', !ok); }
          if(!ok){ valid = false; }
        });
        if(!valid){
          var firstBad = form.querySelector('.field.invalid input, .field.invalid textarea, .field.invalid select');
          if(firstBad){ firstBad.focus(); }
          return;
        }
        var success = form.parentNode.querySelector('.form-success');
        form.style.display = 'none';
        if(success){ success.classList.add('show'); }
      });
      [].slice.call(form.querySelectorAll('[data-required]')).forEach(function(input){
        input.addEventListener('input', function(){
          var field = input.closest('.field');
          if(field && field.classList.contains('invalid')){ field.classList.remove('invalid'); }
        });
      });
    });
  }

  /* ---------- 6. Scroll reveal ---------- */
  function initReveal(){
    var els = [].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(entry){
        if(entry.isIntersecting){
          entry.target.classList.add('in');
          io.unobserve(entry.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();
  }
})();
