(() => {
  'use strict';

  /* ---------- Header: solid background after scroll ---------- */
  const header = document.getElementById('header');
  const backToTop = document.getElementById('backToTop');
  const onScroll = () => {
    const scrolled = window.scrollY > 40;
    header.classList.toggle('is-scrolled', scrolled);
    backToTop.classList.toggle('is-visible', window.scrollY > 700);
  };
  document.addEventListener('scroll', onScroll, { passive: true });
  onScroll();

  backToTop.addEventListener('click', () => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  });

  /* ---------- Mobile nav toggle (slide-in drawer + backdrop) ---------- */
  const navToggle = document.getElementById('navToggle');
  const nav = document.getElementById('nav');
  const navBackdrop = document.getElementById('navBackdrop');

  const closeNav = () => {
    nav.classList.remove('is-open');
    if (navBackdrop) navBackdrop.classList.remove('is-open');
    navToggle.classList.remove('is-active');
    navToggle.setAttribute('aria-expanded', 'false');
    document.body.style.overflow = '';
  };

  navToggle.addEventListener('click', () => {
    const isOpen = nav.classList.toggle('is-open');
    if (navBackdrop) navBackdrop.classList.toggle('is-open', isOpen);
    navToggle.classList.toggle('is-active', isOpen);
    navToggle.setAttribute('aria-expanded', String(isOpen));
    document.body.style.overflow = isOpen ? 'hidden' : '';
  });

  if (navBackdrop) navBackdrop.addEventListener('click', closeNav);

  nav.querySelectorAll('.nav__link, .nav__submenu-link').forEach(link => {
    link.addEventListener('click', closeNav);
  });

  /* ---------- Produtos submenu: collapsed on mobile, toggled by the chevron ---------- */
  document.querySelectorAll('.nav__submenu-toggle').forEach(toggle => {
    toggle.addEventListener('click', () => {
      const item = toggle.closest('.nav__item--has-submenu');
      const isExpanded = item.classList.toggle('is-expanded');
      toggle.setAttribute('aria-expanded', String(isExpanded));
    });
  });

  /* ---------- Language switcher dropdown ---------- */
  const langSwitch = document.getElementById('langSwitch');
  const langSwitchTrigger = document.getElementById('langSwitchTrigger');
  if (langSwitch && langSwitchTrigger) {
    langSwitchTrigger.addEventListener('click', (e) => {
      e.stopPropagation();
      const isOpen = langSwitch.classList.toggle('is-open');
      langSwitchTrigger.setAttribute('aria-expanded', String(isOpen));
    });
    document.addEventListener('click', (e) => {
      if (!langSwitch.contains(e.target)) {
        langSwitch.classList.remove('is-open');
        langSwitchTrigger.setAttribute('aria-expanded', 'false');
      }
    });
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape') {
        langSwitch.classList.remove('is-open');
        langSwitchTrigger.setAttribute('aria-expanded', 'false');
      }
    });
  }

  /* ---------- Scroll reveal ---------- */
  const revealItems = document.querySelectorAll('.reveal');
  if ('IntersectionObserver' in window) {
    const revealObserver = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          entry.target.classList.add('is-visible');
          revealObserver.unobserve(entry.target);
        }
      });
    }, { threshold: 0.15, rootMargin: '0px 0px -60px 0px' });
    revealItems.forEach(el => revealObserver.observe(el));
  } else {
    revealItems.forEach(el => el.classList.add('is-visible'));
  }

  /* ---------- Hero video play/pause ---------- */
  const heroVideo = document.querySelector('#heroVideo video');
  const videoToggle = document.getElementById('videoToggle');
  if (heroVideo && videoToggle) {
    videoToggle.addEventListener('click', () => {
      if (heroVideo.paused) {
        heroVideo.play();
        videoToggle.setAttribute('aria-label', 'Pausar vídeo');
      } else {
        heroVideo.pause();
        videoToggle.setAttribute('aria-label', 'Reproduzir vídeo');
      }
    });
  }

  /* ---------- Processo tabs ---------- */
  const processTabs = document.querySelectorAll('#processTabs button');
  const processPanels = document.querySelectorAll('#processPanels .industry-panel');
  processTabs.forEach(btn => {
    btn.addEventListener('click', () => {
      const index = btn.dataset.tab;
      processTabs.forEach(b => b.classList.toggle('is-active', b === btn));
      processPanels.forEach(p => p.classList.toggle('is-active', p.dataset.panel === index));
    });
  });

  /* ---------- Materials marquee: duplicate cards in-track for seamless loop ---------- */
  const materialsTrack = document.getElementById('materialsTrack');
  if (materialsTrack) {
    Array.from(materialsTrack.children).forEach(card => {
      const clone = card.cloneNode(true);
      clone.setAttribute('aria-hidden', 'true');
      materialsTrack.appendChild(clone);
    });
  }

  /* ---------- Scrollspy: highlight nav link for the section in view ----------
     Sections carry a hash key (e.g. "#about"); the hero has no hash and falls
     back to the current page path, so this works regardless of which folder
     depth or domain root the site is deployed under. */
  const navLinks = document.querySelectorAll('[data-nav-link]');
  const navSections = document.querySelectorAll('[data-nav-section]');
  if ('IntersectionObserver' in window && navSections.length) {
    const setActive = (key) => {
      navLinks.forEach(link => {
        const url = new URL(link.getAttribute('href'), window.location.href);
        const linkKey = url.hash || url.pathname;
        link.classList.toggle('is-active', linkKey === key);
      });
    };
    const spyObserver = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          setActive(entry.target.dataset.navSection || window.location.pathname);
        }
      });
    }, { rootMargin: '-45% 0px -50% 0px', threshold: 0 });
    navSections.forEach(section => spyObserver.observe(section));
  }

  /* ---------- Contact form: submits to Netlify Forms (works once deployed on Netlify) ---------- */
  const contactForm = document.getElementById('contactForm');
  const contactFeedback = document.getElementById('contactFeedback');
  if (contactForm) {
    const formStrings = {
      pt: { sending: 'A enviar...', success: 'Pedido enviado. A nossa equipa entrará em contacto brevemente.', error: 'Não foi possível enviar. Tente novamente ou contacte-nos por email para geral@dgzoup.com.' },
      en: { sending: 'Sending...', success: 'Request sent. Our team will be in touch shortly.', error: 'Something went wrong. Please try again or email us at geral@dgzoup.com.' },
      fr: { sending: 'Envoi en cours...', success: 'Demande envoyée. Notre équipe vous contactera prochainement.', error: "Une erreur s'est produite. Veuillez réessayer ou nous contacter par email à geral@dgzoup.com." }
    };
    const pageLang = (document.documentElement.lang || 'pt').slice(0, 2);
    const t = formStrings[pageLang] || formStrings.pt;

    contactForm.addEventListener('submit', (e) => {
      e.preventDefault();
      if (!contactForm.checkValidity()) {
        contactForm.reportValidity();
        return;
      }
      const submitBtn = contactForm.querySelector('button[type="submit"]');
      if (submitBtn) submitBtn.disabled = true;
      contactFeedback.textContent = t.sending;

      fetch(contactForm.getAttribute('action') || window.location.pathname, {
        method: 'POST',
        body: new FormData(contactForm)
      })
        .then((response) => {
          if (!response.ok) throw new Error('Request failed');
          contactFeedback.textContent = t.success;
          contactForm.reset();
        })
        .catch(() => {
          contactFeedback.textContent = t.error;
        })
        .finally(() => {
          if (submitBtn) submitBtn.disabled = false;
        });
    });
  }

  /* ---------- Cookie banner ----------
     Consent choice is stored in localStorage under "dgzoup-cookie-consent"
     ("accepted" | "rejected"). Any future analytics/pixel snippet should
     check this value before loading and only run when it equals "accepted". */
  const cookieBanner = document.getElementById('cookieBanner');
  if (cookieBanner) {
    const CONSENT_KEY = 'dgzoup-cookie-consent';
    const acceptBtn = document.getElementById('cookieAccept');
    const rejectBtn = document.getElementById('cookieReject');

    const setBackToTopOffset = (open) => {
      if (!backToTop) return;
      if (open) {
        const h = cookieBanner.getBoundingClientRect().height;
        backToTop.style.bottom = `calc(${getComputedStyle(backToTop).bottom} + ${h}px)`;
      } else {
        backToTop.style.bottom = '';
      }
    };

    const hideBanner = () => {
      cookieBanner.classList.remove('is-visible');
      setBackToTopOffset(false);
    };

    if (!localStorage.getItem(CONSENT_KEY)) {
      window.setTimeout(() => {
        cookieBanner.classList.add('is-visible');
        setBackToTopOffset(true);
      }, 600);
    }

    if (acceptBtn) acceptBtn.addEventListener('click', () => {
      localStorage.setItem(CONSENT_KEY, 'accepted');
      hideBanner();
    });
    if (rejectBtn) rejectBtn.addEventListener('click', () => {
      localStorage.setItem(CONSENT_KEY, 'rejected');
      hideBanner();
    });
  }
})();
