/* ==========================================================
   MILPAT PORTUGAL — milpat.pt
   Comportements client : nav sticky, burger, smooth scroll,
   formulaires (Formspree), cookie banner RGPD.
   ========================================================== */
(function () {
  'use strict';

  /* --- 1. Header scrolled state --- */
  var header = document.querySelector('.site-header');
  if (header) {
    var onScroll = function () {
      if (window.scrollY > 8) header.classList.add('scrolled');
      else header.classList.remove('scrolled');
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
  }

  /* --- 2. Burger menu (mobile) --- */
  var burger = document.querySelector('.burger');
  var navLinks = document.querySelector('.nav-links');
  if (burger && navLinks) {
    burger.addEventListener('click', function () {
      var isOpen = navLinks.classList.toggle('open');
      burger.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
    });
    // Close on link click (mobile)
    navLinks.querySelectorAll('a').forEach(function (link) {
      link.addEventListener('click', function () {
        navLinks.classList.remove('open');
        burger.setAttribute('aria-expanded', 'false');
      });
    });
  }

  /* --- 3. Smooth scroll for anchor links with offset --- */
  document.querySelectorAll('a[href^="#"]').forEach(function (a) {
    a.addEventListener('click', function (e) {
      var id = a.getAttribute('href');
      if (id.length < 2) return;
      var target = document.querySelector(id);
      if (!target) return;
      e.preventDefault();
      var headerH = header ? header.offsetHeight : 0;
      var y = target.getBoundingClientRect().top + window.pageYOffset - headerH - 8;
      window.scrollTo({ top: y, behavior: 'smooth' });
    });
  });

  /* --- 4. Forms : Formspree integration --- */
  /* IMPORTANT : replace "YOUR_FORMSPREE_ID" with the real endpoint
     after creating the forms at https://formspree.io.
     Each form has its own endpoint so submissions are tagged. */
  document.querySelectorAll('form[data-formspree]').forEach(function (form) {
    form.addEventListener('submit', function (e) {
      e.preventDefault();
      var endpoint = form.getAttribute('data-formspree');
      var msg = form.querySelector('.form-msg');
      var btn = form.querySelector('button[type=submit]');
      if (msg) { msg.textContent = ''; msg.className = 'form-msg'; }
      if (btn) { btn.disabled = true; btn.dataset.originalText = btn.textContent; btn.textContent = '…'; }

      var data = new FormData(form);

      fetch(endpoint, {
        method: 'POST',
        body: data,
        headers: { 'Accept': 'application/json' }
      }).then(function (r) {
        if (r.ok) {
          if (msg) {
            msg.className = 'form-msg ok';
            msg.textContent = form.getAttribute('data-msg-ok') || 'Pedido enviado. Respondemos em menos de 24h úteis.';
          }
          form.reset();
        } else {
          return r.json().then(function (body) {
            throw new Error((body.error || 'Erro no envio'));
          });
        }
      }).catch(function (err) {
        if (msg) {
          msg.className = 'form-msg err';
          msg.textContent = form.getAttribute('data-msg-err') || 'Não foi possível enviar. Tenta de novo ou contacta-nos por email.';
        }
        console.error('Form error', err);
      }).finally(function () {
        if (btn) { btn.disabled = false; btn.textContent = btn.dataset.originalText || 'Enviar'; }
      });
    });
  });

  /* --- 5. Cookie banner (RGPD minimal) --- */
  var CKEY = 'milpat_cookie_v1';
  var banner = document.querySelector('.cookie-banner');
  if (banner) {
    try {
      if (!localStorage.getItem(CKEY)) {
        banner.classList.add('visible');
      }
    } catch (e) { /* ignore private mode */ }

    banner.querySelectorAll('[data-cookie]').forEach(function (b) {
      b.addEventListener('click', function () {
        try { localStorage.setItem(CKEY, b.getAttribute('data-cookie')); } catch (e) {}
        banner.classList.remove('visible');
      });
    });
  }

  /* --- 6. Current year in footer --- */
  var yearEls = document.querySelectorAll('[data-year]');
  var y = new Date().getFullYear();
  yearEls.forEach(function (el) { el.textContent = y; });
})();
