import $ from "jquery";
import { gsap } from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
import { initIntroAnimation } from "./introAnimation.js";

gsap.registerPlugin(ScrollTrigger);

$(function () {
  initIntroAnimation();
  const $gnb = $("#gnb");
  const $hamburger = $(".gnb__hamburger");
  const $mobileNav = $(".gnb__mobileNav");
  const $mobileNavClose = $(".gnb__mobileNavClose");

  // 섹션 → nav 귀속 맵
  const sectionToNav = {
    intro: "intro",
    about: "about",
    history: "history",
    vision: "vision",
    project: "project",
    contact: "contact",
  };

  // GNB 스크롤 배경
  ScrollTrigger.create({
    start: "40px top",
    onEnter: () => $gnb.addClass("isScrolled"),
    onLeaveBack: () => $gnb.removeClass("isScrolled"),
  });

  // 현재 섹션에 따라 GNB 활성화
  const $navLinks = $(".gnb__navLink");
  const sections = $("section[id]").toArray();

  function setActiveNav(navId) {
    $navLinks.each(function () {
      const href = $(this).attr("href").replace("#", "");
      $(this).toggleClass("isActive", href === navId);
    });
  }

  function updateActiveNav() {
    const scrollY = window.scrollY + window.innerHeight / 3;
    let current = "";

    sections.forEach((el) => {
      if (el.offsetTop <= scrollY) {
        current = sectionToNav[el.id] || current;
      }
    });

    setActiveNav(current);
  }

  ScrollTrigger.create({
    trigger: document.body,
    start: "top top",
    end: "max",
    onUpdate: updateActiveNav,
  });

  updateActiveNav();

  // 햄버거 메뉴
  $hamburger.on("click", function () {
    const isOpen = $hamburger.toggleClass("isOpen").hasClass("isOpen");
    $hamburger.attr("aria-expanded", isOpen);
    $mobileNav.toggleClass("isOpen", isOpen);
  });

  // 모바일 메뉴 링크 클릭 시 닫기
  $(".gnb__mobileNavLink").on("click", function () {
    $hamburger.removeClass("isOpen").attr("aria-expanded", false);
    $mobileNav.removeClass("isOpen");
  });

  // 모바일 메뉴 닫기 버튼
  $mobileNavClose.on("click", function () {
    $hamburger.removeClass("isOpen").attr("aria-expanded", false);
    $mobileNav.removeClass("isOpen");
  });

  // History 아코디언
  $(".history__yearToggle").on("click", function () {
    const $group = $(this).closest(".history__yearGroup");
    const $list = $("#" + $(this).attr("aria-controls"));
    const isOpen = $group.hasClass("isOpen");

    $group.toggleClass("isOpen", !isOpen);
    $(this).attr("aria-expanded", !isOpen);

    if (isOpen) {
      $list.attr("hidden", "");
    } else {
      $list.removeAttr("hidden");
    }
  });

  // Contact 아코디언
  $(".contactAccordion__header").on("click", function () {
    const $item = $(this).closest(".contactAccordion__item");
    const $body = $("#" + $(this).attr("aria-controls"));
    const isOpen = $item.hasClass("isOpen");

    $item.toggleClass("isOpen", !isOpen);
    $(this).attr("aria-expanded", !isOpen);

    if (isOpen) {
      $body.attr("hidden", "");
    } else {
      $body.removeAttr("hidden");
    }
  });
});
