function debounce(func, wait) {
  let timeout;
  return function () {
    const context = this,
      args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(context, args), wait);
  };
}

const subVisualNavigation = () => {
  const container = $('.sub-navigation');
  const currentPage = $('.sub-navigation-btn > a');
  const menuList = $('.sub-navigation-btn > ul');
  const containerDepthList = $('.sub-navigation-list');
  const activeItem = containerDepthList.find('li').filter('.on');
  const headerHeight = () => $('.header').outerHeight(); // 동적으로 header 높이 계산

  gsap.registerPlugin(ScrollTrigger, ScrollToPlugin);
  const setupScrollTriggers = () => {
    // 기존의 ScrollTrigger 인스턴스 제거
    ScrollTrigger.getAll().forEach((trigger) => trigger.kill());

    const triggerSettings = {
      trigger: container,
      endTrigger: '#wrap',
      start: `top-=${headerHeight()} top`,
      pin: true,
      pinSpacing: false,
    };

    ScrollTrigger.matchMedia({
      '(min-width: 1024px)': () => gsap.to(container, { scrollTrigger: triggerSettings }),
      '(min-width: 768px) and (max-width: 1024px)': () =>
        gsap.to(container, { scrollTrigger: triggerSettings }),
      '(max-width: 767px)': () => gsap.to(container, { scrollTrigger: triggerSettings }),
    });
  };

  $(window).on(
    'resize',
    debounce(function () {
      setupScrollTriggers();
      ScrollTrigger.refresh(true);
    }, 250)
  ); // 250ms 동안 재호출 방지

  setupScrollTriggers();

  const clickMenuList = () => {
    currentPage.on('click', function (e) {
      e.preventDefault();
      $(this).toggleClass('on');
      menuList.toggle();
    });
  };

  clickMenuList();

  const loadActiveItem = () => {
    if (activeItem.length) {
      const pl = activeItem.position().left;

      setTimeout(() => {
        containerDepthList.animate(
          {
            scrollLeft: pl - 30,
          },
          500
        );
      });
    }
  };

  loadActiveItem();
};

// 3depth snb
const snb = () => {
  const snbWrap = $('#snb');
  const snbList = snbWrap.find('.snb-navi');
  const snbMobile = snbWrap.find('.snb-navi-mobile');

  snbList.each(function () {
    const snbItem = $(this).find('>.depth02');
    const snbActive = $(this).find('.active').text();
    const snbItemLength = snbItem.length;

    if (snbItemLength < 10) {
      $(this).addClass('snb-navi-length-0' + snbItemLength);
    } else {
      $(this).addClass('snb-navi-length-' + snbItemLength);
    }
    if (snbItemLength === 0) {
      snbWrap.remove();
    }

    snbMobile.find('.snb-navi-mobile-active').text(snbActive);
  });

  snbMobile.click(function () {
    if (!snbMobile.hasClass('active')) {
      snbMobile.addClass('active').find('i').removeClass().addClass('ri-arrow-up-s-line');
      snbList.slideDown();
    } else {
      snbMobile.removeClass('active').find('i').removeClass().addClass('ri-arrow-down-s-line');
      snbList.slideUp();
    }

    return false;
  });
};

// 개인정보처리방침 스크롤 부드럽게
const privacy = () => {
  $('.privacy-index > li > a').on('click', function (e) {
    e.preventDefault();

    const $this = $(this);
    const target = $this.attr('href');

    const position =
      $(target).offset().top -
      ($('.header').innerHeight() + $('.sub-navigation').innerHeight()) -
      30;

    $('body, html').animate({ scrollTop: position }, 400);
  });
};

//방산맵 팝업
const mapPopup = () => {
  let scrollPosition = 0;

  const bodyfixOn = () => {
    scrollPosition = $(window).scrollTop();
    $('body')
      .css('top', -scrollPosition + 'px')
      .attr('scroll-pos', scrollPosition);
  };

  const bodyfixOff = () => {
    $('body').css('top', '');
    $(window).scrollTop(scrollPosition);
  };

  const $popup = $('.bangsan-result-popup');
  const $popOpen = $('.bangsan-result-search-info .more');
  const $popClose = $('.popup-close');

  $popOpen.on('click', function (e) {
    e.preventDefault();
    bodyfixOn();
    $popup.addClass('active');
  });

  $popClose.on('click', function () {
    $popup.removeClass('active');
    bodyfixOff();
    return false;
  });
};

$(function () {
  // play
  subVisualNavigation();
  snb();
  privacy();

  $('.chosen-search').remove();

  // 접근성 관련
  $(window).on('load', function () {
    $('.CodeMirror textarea').attr('title', 'webeditor synchronization hidden area');
  });

  mapPopup();
});
