(() => {
  const toggle = document.querySelector('[data-menu-toggle]');
  const menu = document.querySelector('[data-menu]');
  if (toggle && menu) {
    toggle.addEventListener('click', () => {
      const open = menu.classList.toggle('open');
      toggle.setAttribute('aria-expanded', String(open));
    });
  }

  let analyticsLoaded = false;
  const loadAnalytics = () => {
    if (analyticsLoaded) return;
    const cfg = window.NEKRUT_ANALYTICS || {};
    if (cfg.gtm) {
      analyticsLoaded = true;
      window.dataLayer = window.dataLayer || [];
      window.dataLayer.push({'gtm.start': Date.now(), event: 'gtm.js'});
      const script = document.createElement('script');
      script.async = true;
      script.src = 'https://www.googletagmanager.com/gtm.js?id=' + encodeURIComponent(cfg.gtm);
      document.head.appendChild(script);
      return;
    }
    if (cfg.ga) {
      analyticsLoaded = true;
      window.dataLayer = window.dataLayer || [];
      window.gtag = function(){ window.dataLayer.push(arguments); };
      window.gtag('js', new Date());
      window.gtag('config', cfg.ga, {anonymize_ip: true});
      const script = document.createElement('script');
      script.async = true;
      script.src = 'https://www.googletagmanager.com/gtag/js?id=' + encodeURIComponent(cfg.ga);
      document.head.appendChild(script);
    }
  };

  const banner = document.querySelector('[data-cookie]');
  const consentRequired = (window.NEKRUT_ANALYTICS || {}).consentRequired !== false;
  const consent = localStorage.getItem('nekrut_cookie_consent');
  if (!consentRequired || consent === 'accepted') loadAnalytics();
  if (banner && consentRequired && consent === null) banner.hidden = false;

  document.querySelector('[data-cookie-accept]')?.addEventListener('click', () => {
    localStorage.setItem('nekrut_cookie_consent', 'accepted');
    if (banner) banner.hidden = true;
    loadAnalytics();
  });

  document.querySelector('[data-cookie-reject]')?.addEventListener('click', () => {
    localStorage.setItem('nekrut_cookie_consent', 'rejected');
    if (banner) banner.hidden = true;
  });
})();
