/* =========================================
   MC TRADUÇÕES & CONSULTORIA ACADÉMICA
   script.js
   ========================================= */

document.addEventListener('DOMContentLoaded', () => {

  /* =====================================================
     1. COOKIE CONSENT
  ====================================================== */
  const cookieBanner = document.getElementById('cookie-banner');
  const cookieAccept = document.getElementById('cookie-accept');
  const cookieReject = document.getElementById('cookie-reject');
  const COOKIE_KEY   = 'mc_cookie_consent';

  function setCookie(val) {
    const exp = new Date();
    exp.setFullYear(exp.getFullYear() + 1);
    document.cookie = `${COOKIE_KEY}=${val}; expires=${exp.toUTCString()}; path=/; SameSite=Lax`;
  }

  function getCookie(name) {
    return document.cookie.split('; ').find(r => r.startsWith(name + '='))?.split('=')[1] || null;
  }

  function activatePixels() {
    /*
     * ---- ÁREA DE PIXELS ----
     * Cole aqui os seus pixels depois do utilizador aceitar cookies.
     *
     * Google Tag Manager:
     *   (function(w,d,s,l,i){...})(window,document,'script','dataLayer','GTM-XXXXXX');
     *
     * Meta Pixel:
     *   !function(f,b,e,v,n,t,s){...}
     *   fbq('init', 'SEU_PIXEL_ID');
     *   fbq('track', 'PageView');
     *
     * Google Analytics 4:
     *   const s = document.createElement('script');
     *   s.src = 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX';
     *   s.async = true; document.head.appendChild(s);
     *   window.dataLayer = window.dataLayer || [];
     *   function gtag(){dataLayer.push(arguments);}
     *   gtag('js', new Date()); gtag('config', 'G-XXXXXXXXXX');
    */
    console.log('[MC] Pixels ativados.');
  }

  // Clear any previously saved consent so banner always shows on fresh open
  document.cookie = `${COOKIE_KEY}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;

  const consent = getCookie(COOKIE_KEY);
  if (!consent) {
    // Show after short delay so page loads first
    setTimeout(() => {
      if (cookieBanner) cookieBanner.classList.add('visible');
    }, 1800);
  } else if (consent === 'accepted') {
    activatePixels();
  }

  cookieAccept?.addEventListener('click', () => {
    setCookie('accepted');
    cookieBanner.classList.remove('visible');
    activatePixels();
  });

  cookieReject?.addEventListener('click', () => {
    setCookie('rejected');
    cookieBanner.classList.remove('visible');
  });


  /* =====================================================
     1b. HERO SCROLL BUTTON
  ====================================================== */
  const heroScrollBtn = document.getElementById('hero-scroll-btn');
  if (heroScrollBtn) {
    heroScrollBtn.addEventListener('click', () => {
      const stats = document.querySelector('.stats-section');
      if (stats) {
        stats.scrollIntoView({ behavior: 'smooth' });
      }
    });
  }

  /* =====================================================
     2. HEADER — scroll effect
  ====================================================== */
  const headerWrap = document.getElementById('site-header');

  window.addEventListener('scroll', () => {
    if (!headerWrap) return;
    // .scrolled controls dark vs glass style via CSS
    headerWrap.classList.toggle('scrolled', window.scrollY > 60);
    updateActiveNav();
  }, { passive: true });


  /* =====================================================
     3. ACTIVE NAV on scroll
  ====================================================== */
  function updateActiveNav() {
    const ids    = ['inicio','servicos','pacotes','equipa','contacto'];
    const scrollY = window.scrollY + 120;

    ids.forEach(id => {
      const el   = document.getElementById(id);
      const link = document.querySelector(`.main-nav .nav-link[href="#${id}"]`);
      if (!el || !link) return;
      const active = scrollY >= el.offsetTop && scrollY < el.offsetTop + el.offsetHeight;
      link.classList.toggle('active', active);
    });
  }


  /* =====================================================
     4. HAMBURGER / MOBILE NAV
  ====================================================== */
  const hamburger = document.getElementById('hamburger');
  const mobileNav = document.getElementById('mobile-nav');

  if (hamburger && mobileNav) {
    hamburger.addEventListener('click', () => {
      const open = hamburger.classList.toggle('open');
      mobileNav.classList.toggle('open', open);
      hamburger.setAttribute('aria-expanded', String(open));
    });

    mobileNav.querySelectorAll('a').forEach(link => {
      link.addEventListener('click', () => {
        hamburger.classList.remove('open');
        mobileNav.classList.remove('open');
        hamburger.setAttribute('aria-expanded', 'false');
      });
    });

    document.addEventListener('click', (e) => {
      if (!mobileNav.classList.contains('open')) return;
      if (!mobileNav.contains(e.target) && !hamburger.contains(e.target)) {
        hamburger.classList.remove('open');
        mobileNav.classList.remove('open');
        hamburger.setAttribute('aria-expanded', 'false');
      }
    });
  }


  /* =====================================================
     5. SMOOTH SCROLL
  ====================================================== */
  document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', (e) => {
      const target = document.querySelector(anchor.getAttribute('href'));
      if (!target) return;
      e.preventDefault();
      const top = target.getBoundingClientRect().top + window.scrollY - 90;
      window.scrollTo({ top, behavior: 'smooth' });
    });
  });


  /* =====================================================
     6. SCROLL REVEAL
  ====================================================== */
  const revealEls = document.querySelectorAll('.reveal-up');

  if ('IntersectionObserver' in window) {
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (!entry.isIntersecting) return;
        const delay = parseInt(entry.target.dataset.delay || '0', 10);
        setTimeout(() => entry.target.classList.add('visible'), delay);
        obs.unobserve(entry.target);
      });
    }, { threshold: 0.1, rootMargin: '0px 0px -40px 0px' });

    revealEls.forEach(el => obs.observe(el));
  } else {
    revealEls.forEach(el => el.classList.add('visible'));
  }


  /* =====================================================
     7. ANIMATED COUNTER
  ====================================================== */
  const counters = document.querySelectorAll('.stat-number[data-target]');

  if ('IntersectionObserver' in window) {
    const cObs = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (!entry.isIntersecting) return;
        const el     = entry.target;
        const target = parseInt(el.dataset.target, 10);
        const prefix = el.dataset.prefix || '';
        const suffix = el.dataset.suffix || '';
        const dur    = 1800;
        const start  = performance.now();

        function tick(now) {
          const p = Math.min((now - start) / dur, 1);
          const e = 1 - Math.pow(1 - p, 4);
          el.textContent = `${prefix}${Math.round(e * target)}${suffix}`;
          if (p < 1) requestAnimationFrame(tick);
        }
        requestAnimationFrame(tick);
        cObs.unobserve(el);
      });
    }, { threshold: 0.5 });

    counters.forEach(el => cObs.observe(el));
  }


  /* =====================================================
     8. PACKAGE CARD — hover border
  ====================================================== */
  document.querySelectorAll('.package-card:not(.package-card--featured)').forEach(card => {
    card.addEventListener('mouseenter', () => card.style.borderColor = 'var(--red)');
    card.addEventListener('mouseleave', () => card.style.borderColor = '');
  });


  /* =====================================================
     9. HERO PARALLAX (subtle)
  ====================================================== */
  const heroBg = document.querySelector('.hero-bg-pattern');
  const heroGrid = document.querySelector('.hero-grid');

  window.addEventListener('scroll', () => {
    const y = window.scrollY * 0.18;
    if (heroBg)   heroBg.style.transform   = `translateY(${y}px)`;
    if (heroGrid) heroGrid.style.transform  = `translateY(${y * 0.6}px)`;
  }, { passive: true });


  /* =====================================================
     10. NAV ACTIVE UNDERLINE (CSS injection)
  ====================================================== */
  const style = document.createElement('style');
  style.textContent = `
    .main-nav .nav-link.active { color: #888; }
  `;
  document.head.appendChild(style);

});
