(function () {
  'use strict';

  var header = document.querySelector('.header');
  var stuckThreshold = 60;
  function updateHeaderStuck() {
    if (!header) return;
    if (window.innerWidth < 1024) {
      header.classList.remove('is-stuck');
      return;
    }
    if (window.scrollY > stuckThreshold) {
      header.classList.add('is-stuck');
    } else {
      header.classList.remove('is-stuck');
    }
  }
  if (header) {
    window.addEventListener('scroll', updateHeaderStuck, { passive: true });
    window.addEventListener('resize', updateHeaderStuck);
    updateHeaderStuck();
  }

  var burger = document.querySelector('[data-burger]');
  var nav = document.querySelector('.header-nav');
  var burgerIcon = document.querySelector('[data-burger-icon]');
  var mobileDrawerLayer = document.getElementById('mobile-drawer-layer');
  var mobileMenuBackdrop = document.getElementById('mobile-menu-backdrop');
  var headerBar = document.querySelector('.header-bar');

  function isMobileNavViewport() {
    return window.innerWidth < 1024;
  }

  function restoreBodyOverflowIfNeeded() {
    var modalEl = document.getElementById('request-modal');
    if (modalEl && modalEl.getAttribute('aria-hidden') === 'false') return;
    document.body.style.overflow = '';
  }

  function closeMobileMenu() {
    if (!nav) return;
    nav.classList.remove('open');
    if (mobileDrawerLayer) {
      mobileDrawerLayer.classList.remove('is-open');
      mobileDrawerLayer.setAttribute('aria-hidden', 'true');
    }
    restoreBodyOverflowIfNeeded();
    if (burgerIcon) {
      burgerIcon.classList.add('fa-bars');
      burgerIcon.classList.remove('fa-xmark');
    }
    if (burger) burger.setAttribute('aria-expanded', 'false');
    nav.querySelectorAll('.nav-dropdown.open').forEach(function (el) {
      el.classList.remove('open');
    });
    if (headerBar && nav.parentNode === mobileDrawerLayer) {
      var headerRight = headerBar.querySelector('.header-right');
      headerBar.insertBefore(nav, headerRight);
    }
  }

  function openMobileMenu() {
    if (!nav) return;
    if (mobileDrawerLayer && nav.parentNode !== mobileDrawerLayer) {
      mobileDrawerLayer.appendChild(nav);
    }
    nav.classList.add('open');
    if (mobileDrawerLayer) {
      mobileDrawerLayer.classList.add('is-open');
      mobileDrawerLayer.setAttribute('aria-hidden', 'false');
    }
    document.body.style.overflow = 'hidden';
    if (burgerIcon) {
      burgerIcon.classList.remove('fa-bars');
      burgerIcon.classList.add('fa-xmark');
    }
    if (burger) burger.setAttribute('aria-expanded', 'true');
  }

  if (burger && nav) {
    burger.addEventListener('click', function () {
      if (!isMobileNavViewport()) return;
      if (nav.classList.contains('open')) closeMobileMenu();
      else openMobileMenu();
    });
  }

  if (mobileDrawerLayer) {
    mobileDrawerLayer.addEventListener('click', function (e) {
      if (e.target === mobileMenuBackdrop || e.target === mobileDrawerLayer) closeMobileMenu();
    });
  }

  document.querySelectorAll('[data-mobile-menu-close]').forEach(function (btn) {
    btn.addEventListener('click', closeMobileMenu);
  });

  window.addEventListener('resize', function () {
    if (!isMobileNavViewport() && nav && nav.classList.contains('open')) {
      closeMobileMenu();
    }
  });

  document.addEventListener('keydown', function (e) {
    if (e.key !== 'Escape' || !nav || !nav.classList.contains('open') || !isMobileNavViewport()) return;
    var so = document.getElementById('search-overlay');
    if (so && so.classList.contains('is-open')) return;
    closeMobileMenu();
  });

  if (nav) {
    nav.addEventListener('click', function (e) {
      var a = e.target.closest && e.target.closest('a[href^="#"]');
      if (!a || !isMobileNavViewport() || !nav.classList.contains('open')) return;
      var href = a.getAttribute('href');
      if (href && href.length > 1) closeMobileMenu();
    });
  }

  var searchBtn = document.querySelector('[data-search-toggle]');
  var searchOverlay = document.getElementById('search-overlay');
  var searchInput = document.getElementById('header-search-input');
  var searchClose = document.querySelector('[data-search-close]');
  if (searchBtn && searchOverlay) {
    function openSearch() {
      searchOverlay.hidden = false;
      searchOverlay.setAttribute('aria-hidden', 'false');
      searchOverlay.classList.add('is-open');
      if (searchInput) {
        searchInput.value = '';
        searchInput.focus();
      }
    }
    function closeSearch() {
      searchOverlay.classList.remove('is-open');
      searchOverlay.setAttribute('aria-hidden', 'true');
      searchOverlay.hidden = true;
    }
    searchBtn.addEventListener('click', openSearch);
    if (searchClose) searchClose.addEventListener('click', closeSearch);
    if (searchInput) {
      searchInput.addEventListener('keydown', function (e) {
        if (e.key === 'Escape') closeSearch();
      });
    }
    document.addEventListener('keydown', function (e) {
      if (e.key === 'Escape' && searchOverlay.classList.contains('is-open')) closeSearch();
    });

    var drawerSearch = document.querySelector('[data-mobile-drawer-search]');
    if (drawerSearch) {
      drawerSearch.addEventListener('focus', function () {
        if (!isMobileNavViewport()) return;
        closeMobileMenu();
        openSearch();
      });
    }
  }

  /* Contact / Request popup – #request ve Contact us tıklanınca açılır */
  var requestModal = document.getElementById('request-modal');
  var requestOpenButtons = document.querySelectorAll('[data-request-open]');
  var requestCloseButtons = document.querySelectorAll('[data-request-close]');
  function openRequestModal() {
    if (!requestModal) return;
    requestModal.removeAttribute('hidden');
    requestModal.setAttribute('aria-hidden', 'false');
    document.body.style.overflow = 'hidden';
  }
  function closeRequestModal() {
    if (!requestModal) return;
    requestModal.setAttribute('hidden', '');
    requestModal.setAttribute('aria-hidden', 'true');
    document.body.style.overflow = '';
  }
  requestOpenButtons.forEach(function (btn) {
    btn.addEventListener('click', function (e) {
      e.preventDefault();
      openRequestModal();
    });
  });
  requestCloseButtons.forEach(function (btn) {
    btn.addEventListener('click', closeRequestModal);
  });
  if (requestModal) {
    document.addEventListener('keydown', function (e) {
      if (e.key === 'Escape' && requestModal.getAttribute('aria-hidden') === 'false') closeRequestModal();
    });
    var requestForm = document.getElementById('request-form');
    if (requestForm) {
      requestForm.addEventListener('submit', function (e) {
        e.preventDefault();
        closeRequestModal();
      });
      requestForm.querySelectorAll('.request-modal__input, .request-modal__textarea').forEach(function (el) {
        function toggleHasValue() {
          if (el.value.length > 0) el.classList.add('has-value'); else el.classList.remove('has-value');
        }
        el.addEventListener('input', toggleHasValue);
        el.addEventListener('change', toggleHasValue);
        toggleHasValue();
      });
    }
  }

  document.querySelectorAll('.nav-dropdown').forEach(function (dropdown) {
    var btn = dropdown.querySelector('.nav-trigger');
    if (btn) {
      btn.addEventListener('click', function (e) {
        if (window.innerWidth < 1024) {
          e.preventDefault();
          dropdown.classList.toggle('open');
        }
      });
    }
  });

  /* Alt menü: Congress and Conference Systems – mobilde tıklanınca aç/kapa */
  document.querySelectorAll('.dropdown-submenu-trigger').forEach(function (trigger) {
    trigger.addEventListener('click', function (e) {
      if (window.innerWidth < 1024) {
        e.preventDefault();
        var sub = trigger.closest('.dropdown-submenu');
        if (sub) {
          sub.classList.toggle('open');
          trigger.setAttribute('aria-expanded', sub.classList.contains('open'));
        }
      }
    });
  });

  var langBlock = document.querySelector('[data-lang]');
  var langDropdown = langBlock && langBlock.querySelector('.header-lang-dropdown');
  var langFlag = langBlock && langBlock.querySelector('.header-lang-flag');
  var langNameEl = langBlock && langBlock.querySelector('[data-lang-name]');
  if (langBlock && langDropdown) {
    langBlock.querySelectorAll('[data-lang-option]').forEach(function (link) {
      link.addEventListener('click', function (e) {
        e.preventDefault();
        var code = link.getAttribute('data-lang-option');
        var label = link.getAttribute('data-lang-label');
        if (langFlag) langFlag.className = 'header-lang-flag fi fi-' + code;
        if (langNameEl && label) langNameEl.textContent = label;
      });
    });
  }

  /* We in figures: sayılar viewport’a girince sayıldırma animasyonu + görünür */
  var figuresNumbers = document.querySelectorAll('[data-figures-number]');
  var duration = 2000;
  var easeOutExpo = function (t) {
    return t === 1 ? 1 : 1 - Math.pow(2, -10 * t);
  };

  function animateCount(el, to, startTime) {
    var start = 0;
    to = parseInt(to, 10) || 0;
    if (to === 0) {
      el.classList.add('is-visible');
      return;
    }
    function step(timestamp) {
      if (!startTime) startTime = timestamp;
      var elapsed = timestamp - startTime;
      var progress = Math.min(elapsed / duration, 1);
      var eased = easeOutExpo(progress);
      var current = Math.round(start + (to - start) * eased);
      el.textContent = current;
      if (progress < 1) {
        requestAnimationFrame(step);
      } else {
        el.textContent = to;
      }
    }
    el.classList.add('is-visible');
    requestAnimationFrame(step);
  }

  if (figuresNumbers.length && 'IntersectionObserver' in window) {
    var figuresObserver = new IntersectionObserver(
      function (entries) {
        entries.forEach(function (entry) {
          if (!entry.isIntersecting) return;
          var el = entry.target;
          if (el.dataset.figuresDone) return;
          el.dataset.figuresDone = '1';
          var to = el.getAttribute('data-figures-to');
          animateCount(el, to);
          figuresObserver.unobserve(el);
        });
      },
      { rootMargin: '0px 0px -80px 0px', threshold: 0.1 }
    );
    figuresNumbers.forEach(function (el) {
      figuresObserver.observe(el);
    });
  } else if (figuresNumbers.length) {
    figuresNumbers.forEach(function (el) {
      var to = el.getAttribute('data-figures-to');
      animateCount(el, to);
    });
  }

  /* Figures kartları: ışıklı blur alanı mouse ile takip eder */
  document.querySelectorAll('.figures__card').forEach(function (card) {
    var inner = card.querySelector('.figures__card-inner');
    if (!inner) return;
    function setBlurPosition(e) {
      var rect = inner.getBoundingClientRect();
      var x = ((e.clientX - rect.left) / rect.width) * 100;
      var y = ((e.clientY - rect.top) / rect.height) * 100;
      inner.style.setProperty('--figures-blur-x', x + '%');
      inner.style.setProperty('--figures-blur-y', y + '%');
    }
    inner.addEventListener('mouseenter', function () {
      inner.classList.add('figures__card-inner--mouse');
    });
    inner.addEventListener('mousemove', setBlurPosition);
    /* Çıkışta eski yerine dönmesin, çıktığın yerde kalsın */
  });

  /* Gallery: YouTube video modal */
  var galleryModal = document.getElementById('gallery-modal');
  var galleryPlayer = document.getElementById('gallery-modal-player');
  var galleryCloseButtons = document.querySelectorAll('[data-gallery-close]');
  var galleryCards = document.querySelectorAll('.gallery__card[data-youtube-id]');

  function openGalleryVideo(id) {
    if (!id || !galleryModal || !galleryPlayer) return;
    var src = 'https://www.youtube.com/embed/' + id + '?autoplay=1';
    galleryPlayer.innerHTML = '<iframe src="' + src + '" title="YouTube video" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';
    galleryModal.removeAttribute('hidden');
    galleryModal.setAttribute('aria-hidden', 'false');
    document.body.style.overflow = 'hidden';
  }

  function closeGalleryVideo() {
    if (!galleryModal || !galleryPlayer) return;
    galleryPlayer.innerHTML = '';
    galleryModal.setAttribute('hidden', '');
    galleryModal.setAttribute('aria-hidden', 'true');
    document.body.style.overflow = '';
  }

  galleryCards.forEach(function (btn) {
    btn.addEventListener('click', function () {
      var id = (btn.getAttribute('data-youtube-id') || '').trim();
      if (id) {
        openGalleryVideo(id);
      } else {
        var cta = document.querySelector('.gallery__cta');
        if (cta && cta.href) {
          window.open(cta.href, '_blank', 'noopener,noreferrer');
        }
      }
    });
  });

  galleryCloseButtons.forEach(function (btn) {
    btn.addEventListener('click', closeGalleryVideo);
  });
  if (galleryModal) {
    galleryModal.addEventListener('keydown', function (e) {
      if (e.key === 'Escape') closeGalleryVideo();
    });
  }

  /* Footer: e-posta kopyala */
  var copyEmailBtn = document.querySelector('[data-copy-email]');
  if (copyEmailBtn) {
    var emailLink = copyEmailBtn.closest('.footer__email-row') && copyEmailBtn.closest('.footer__email-row').querySelector('.footer__email-link');
    var email = emailLink ? (emailLink.getAttribute('href') || '').replace(/^mailto:/i, '').trim() : '';
    copyEmailBtn.addEventListener('click', function () {
      if (!email) return;
      if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(email).then(function () {
          var icon = copyEmailBtn.querySelector('i');
          if (icon) {
            icon.classList.remove('fa-regular', 'fa-copy');
            icon.classList.add('fa-solid', 'fa-check');
            setTimeout(function () {
              icon.classList.remove('fa-solid', 'fa-check');
              icon.classList.add('fa-regular', 'fa-copy');
            }, 2000);
          }
        });
      } else {
        var ta = document.createElement('textarea');
        ta.value = email;
        ta.setAttribute('readonly', '');
        ta.style.position = 'absolute';
        ta.style.left = '-9999px';
        document.body.appendChild(ta);
        ta.select();
        try {
          document.execCommand('copy');
          var icon = copyEmailBtn.querySelector('i');
          if (icon) {
            icon.classList.remove('fa-regular', 'fa-copy');
            icon.classList.add('fa-solid', 'fa-check');
            setTimeout(function () {
              icon.classList.remove('fa-solid', 'fa-check');
              icon.classList.add('fa-regular', 'fa-copy');
            }, 2000);
          }
        } catch (e) {}
        document.body.removeChild(ta);
      }
    });
  }

  /* Team: yatay slide + kart içi scale/translate */
  if (typeof Swiper !== 'undefined') {
    var teamSwiperEl = document.querySelector('.swiper-team');
    if (teamSwiperEl) {
      var teamSlideCount = teamSwiperEl.querySelectorAll('.swiper-slide').length;
      var teamSwiper = new Swiper('.swiper-team', {
        initialSlide: 0,
        slidesPerView: 'auto',
        centeredSlides: true,
        spaceBetween: 20,
        speed: 450,
        loop: teamSlideCount >= 3,
        loopAdditionalSlides: Math.max(4, teamSlideCount),
        watchSlidesProgress: true,
        slideToClickedSlide: true,
        breakpoints: {
          1024: {
            spaceBetween: 32
          }
        },
        on: {
          init: function (sw) {
            /* Loop’ta ilk slayt bazen klon oluyor; 0. kişi ortada, sağ = 1,2,3… */
            if (sw.params.loop && typeof sw.slideToLoop === 'function') {
              sw.slideToLoop(0, 0, false);
              requestAnimationFrame(function () {
                if (sw.realIndex !== 0) {
                  sw.slideToLoop(0, 0, false);
                }
              });
            }
          }
        }
      });
      /* Sağ ok = ileri (slideNext); sol = geri — Navigation modülü yerine sabit bağlantı */
      var teamBtnNext = document.getElementById('our-team-next');
      var teamBtnPrev = document.getElementById('our-team-prev');
      if (teamBtnNext) {
        teamBtnNext.addEventListener('click', function (e) {
          e.preventDefault();
          teamSwiper.slideNext();
        });
      }
      if (teamBtnPrev) {
        teamBtnPrev.addEventListener('click', function (e) {
          e.preventDefault();
          teamSwiper.slidePrev();
        });
      }
    }
  }

  /* Products: kaydırmalı carousel (Team üstü) */
  if (typeof Swiper !== 'undefined') {
    var productsSwiperEl = document.querySelector('.swiper-products');
    if (productsSwiperEl) {
      var productsSwiper = new Swiper('.swiper-products', {
        slidesPerView: 1,
        spaceBetween: 20,
        speed: 400,
        loop: true,
        grabCursor: true,
        autoplay: {
          delay: 4000,
          disableOnInteraction: false
        },
        breakpoints: {
          640: { slidesPerView: 2, spaceBetween: 24 },
          768: { slidesPerView: 3, spaceBetween: 24 },
          992: { slidesPerView: 4, spaceBetween: 28 },
          1200: { slidesPerView: 5, spaceBetween: 28 },
          1400: { slidesPerView: 6, spaceBetween: 28 }
        }
      });
      var productsBtnNext = document.getElementById('products-next');
      var productsBtnPrev = document.getElementById('products-prev');
      if (productsBtnNext) {
        productsBtnNext.addEventListener('click', function (e) {
          e.preventDefault();
          productsSwiper.slideNext();
        });
      }
      if (productsBtnPrev) {
        productsBtnPrev.addEventListener('click', function (e) {
          e.preventDefault();
          productsSwiper.slidePrev();
        });
      }
    }
  }

  /* Trust: marquee – referans logoları tek tek ilerler, animasyonu tetikle */
  (function initTrustMarquee() {
    var track = document.querySelector('.trust__track');
    if (!track) return;
    var anim = 'trust-marquee 50s linear infinite';
    track.style.animation = 'none';
    track.style.webkitAnimation = 'none';
    track.offsetHeight; /* reflow */
    track.style.animation = anim;
    track.style.webkitAnimation = anim;
  })();

})();
