// 인기 메뉴 카드와 갤러리 사진이 화면에 들어올 때 차례로 표시
const revealTargets = document.querySelectorAll(".menu-card, .gallery-item");
const prefersReducedMotion = window.matchMedia(
  "(prefers-reduced-motion: reduce)"
).matches;

if (prefersReducedMotion || !("IntersectionObserver" in window)) {
  revealTargets.forEach(function (target) {
    target.classList.add("is-revealed");
  });
} else {
  revealTargets.forEach(function (target, index) {
    target.classList.add("reveal-on-scroll");
    target.style.setProperty("--reveal-delay", `${(index % 6) * 70}ms`);
  });

  const revealObserver = new IntersectionObserver(
    function (entries, observer) {
      entries.forEach(function (entry) {
        if (!entry.isIntersecting) {
          return;
        }

        entry.target.classList.add("is-revealed");
        observer.unobserve(entry.target);
      });
    },
    {
      threshold: 0.15
    }
  );

  revealTargets.forEach(function (target) {
    revealObserver.observe(target);
  });
}

// 모바일 메뉴 열기와 닫기
const mobileMenuButton = document.querySelector(".mobile-menu-button");
const mainNavigation = document.querySelector(".main-navigation");
const navigationLinks = document.querySelectorAll(".main-navigation a");

mobileMenuButton.addEventListener("click", function () {
  const isMenuOpen = mainNavigation.classList.toggle("is-open");

  mobileMenuButton.classList.toggle("is-open");
  mobileMenuButton.setAttribute("aria-expanded", isMenuOpen);
  mobileMenuButton.setAttribute(
    "aria-label",
    isMenuOpen ? "메뉴 닫기" : "메뉴 열기"
  );
});

// 메뉴 링크를 누르면 모바일 메뉴 닫기
navigationLinks.forEach(function (link) {
  link.addEventListener("click", function () {
    mainNavigation.classList.remove("is-open");
    mobileMenuButton.classList.remove("is-open");
    mobileMenuButton.setAttribute("aria-expanded", "false");
    mobileMenuButton.setAttribute("aria-label", "메뉴 열기");
  });
});

// 현재 보고 있는 영역의 상단 메뉴 강조와 맨 위로 이동
const sectionNavigationLinks = document.querySelectorAll(
  '.main-navigation a[href="#about"], .main-navigation a[href="#menu"], .main-navigation a[href="#gallery"], .main-navigation a[href="#reviews"], .main-navigation a[href="#faq"], .main-navigation a[href="#reservation"]'
);
const trackedSections = Array.from(sectionNavigationLinks).map(function (link) {
  return document.querySelector(link.getAttribute("href"));
});
const scrollTopButton = document.querySelector(".scroll-top-button");

function updateScrollNavigation() {
  const topClearPoint = 120;
  const currentPoint = window.scrollY + window.innerHeight * 0.35;
  let activeSectionId = "";

  if (window.scrollY > topClearPoint) {
    trackedSections.forEach(function (section) {
      if (
        section &&
        currentPoint >= section.offsetTop &&
        currentPoint < section.offsetTop + section.offsetHeight
      ) {
        activeSectionId = section.id;
      }
    });
  }

  sectionNavigationLinks.forEach(function (link) {
    const isActive = link.getAttribute("href") === `#${activeSectionId}`;

    link.classList.toggle("is-current", isActive);

    if (isActive) {
      link.setAttribute("aria-current", "true");
    } else {
      link.removeAttribute("aria-current");
    }
  });

  scrollTopButton.classList.toggle(
    "is-visible",
    window.scrollY >= window.innerHeight
  );
}

window.addEventListener("scroll", updateScrollNavigation, { passive: true });
window.addEventListener("resize", updateScrollNavigation);
window.addEventListener("load", updateScrollNavigation);

scrollTopButton.addEventListener("click", function () {
  window.scrollTo({
    top: 0,
    behavior: "smooth"
  });
});

updateScrollNavigation();

// FAQ 답변 열기와 닫기
const faqButtons = document.querySelectorAll(".faq-button");

faqButtons.forEach(function (button) {
  button.addEventListener("click", function () {
    const currentFaqItem = button.closest(".faq-item");
    const wasOpen = currentFaqItem.classList.contains("is-open");

    faqButtons.forEach(function (otherButton) {
      const otherFaqItem = otherButton.closest(".faq-item");

      otherFaqItem.classList.remove("is-open");
      otherButton.setAttribute("aria-expanded", "false");
    });

    if (!wasOpen) {
      currentFaqItem.classList.toggle("is-open");
      button.setAttribute("aria-expanded", "true");
    }
  });
});

// FAQ 질문과 답변 검색
const faqSearchInput = document.querySelector("#faq-search");
const faqItems = document.querySelectorAll(".faq-item");
const faqNoResults = document.querySelector(".faq-no-results");

faqSearchInput.addEventListener("input", function () {
  const searchTerm = faqSearchInput.value.trim().toLowerCase();
  let visibleItemCount = 0;

  faqItems.forEach(function (item) {
    const question = item.querySelector(".faq-button span:first-child").textContent;
    const answer = item.querySelector(".faq-answer").textContent;
    const faqText = `${question} ${answer}`.toLowerCase();
    const isMatch = faqText.includes(searchTerm);

    item.hidden = !isMatch;

    if (isMatch) {
      visibleItemCount += 1;
    } else {
      item.classList.remove("is-open");
      item.querySelector(".faq-button").setAttribute("aria-expanded", "false");
    }
  });

  faqNoResults.classList.toggle("is-visible", visibleItemCount === 0);
});

// 갤러리 이미지 확대 모달
const galleryItems = document.querySelectorAll(".gallery-item");
const galleryModal = document.querySelector(".gallery-modal");
const modalImage = document.querySelector(".modal-image");
const modalCloseButton = document.querySelector(".modal-close-button");
const modalPreviousButton = document.querySelector(".modal-previous-button");
const modalNextButton = document.querySelector(".modal-next-button");
const modalCounter = document.querySelector(".modal-counter");
const modalDescription = document.querySelector(".modal-description");
let currentGalleryIndex = 0;

function updateGalleryModal() {
  const currentItem = galleryItems[currentGalleryIndex];
  const currentImage = currentItem.querySelector("img");

  modalImage.src = currentItem.dataset.fullImage;
  modalImage.alt = currentImage.alt;
  modalCounter.textContent = `${currentGalleryIndex + 1} / ${galleryItems.length}`;
  modalDescription.textContent = currentImage.alt;

  const isFirstImage = currentGalleryIndex === 0;
  const isLastImage = currentGalleryIndex === galleryItems.length - 1;

  modalPreviousButton.disabled = isFirstImage;
  modalNextButton.disabled = isLastImage;
}

function openGalleryModal(imageIndex) {
  currentGalleryIndex = imageIndex;
  updateGalleryModal();
  galleryModal.classList.add("is-open");
  galleryModal.setAttribute("aria-hidden", "false");
  document.body.classList.add("modal-open");
  modalCloseButton.focus();
}

function closeGalleryModal() {
  galleryModal.classList.remove("is-open");
  galleryModal.setAttribute("aria-hidden", "true");
  document.body.classList.remove("modal-open");
  modalImage.src = "";
  modalImage.alt = "";
  modalCounter.textContent = "";
  modalDescription.textContent = "";
}

function showPreviousImage() {
  if (currentGalleryIndex > 0) {
    currentGalleryIndex -= 1;
    updateGalleryModal();
  }
}

function showNextImage() {
  if (currentGalleryIndex < galleryItems.length - 1) {
    currentGalleryIndex += 1;
    updateGalleryModal();
  }
}

galleryItems.forEach(function (item, index) {
  item.addEventListener("click", function () {
    openGalleryModal(index);
  });
});

modalPreviousButton.addEventListener("click", showPreviousImage);
modalNextButton.addEventListener("click", showNextImage);
modalCloseButton.addEventListener("click", closeGalleryModal);

galleryModal.addEventListener("click", function (event) {
  if (event.target === galleryModal) {
    closeGalleryModal();
  }
});

document.addEventListener("keydown", function (event) {
  if (!galleryModal.classList.contains("is-open")) {
    return;
  }

  if (event.key === "Escape") {
    closeGalleryModal();
  } else if (event.key === "ArrowLeft") {
    showPreviousImage();
  } else if (event.key === "ArrowRight") {
    showNextImage();
  }
});

// 예약 폼 필수 입력값 확인
const reservationForm = document.querySelector("#reservation-form");
const customerName = document.querySelector("#customer-name");
const customerPhone = document.querySelector("#customer-phone");
const visitDate = document.querySelector("#visit-date");
const visitTime = document.querySelector("#visit-time");
const guestCount = document.querySelector("#guest-count");
const inquiryMessage = document.querySelector("#inquiry-message");
const formSuccessMessage = document.querySelector("#form-success-message");

function showError(inputElement, errorElementId, message) {
  const errorElement = document.querySelector(errorElementId);

  inputElement.classList.add("input-error");
  inputElement.setAttribute("aria-invalid", "true");
  errorElement.textContent = message;
}

function clearError(inputElement, errorElementId) {
  const errorElement = document.querySelector(errorElementId);

  inputElement.classList.remove("input-error");
  inputElement.removeAttribute("aria-invalid");
  errorElement.textContent = "";
}

reservationForm.addEventListener("submit", function (event) {
  event.preventDefault();

  let isFormValid = true;
  formSuccessMessage.textContent = "";

  if (customerName.value.trim() === "") {
    showError(
      customerName,
      "#customer-name-error",
      "이름을 입력해 주세요."
    );
    isFormValid = false;
  } else {
    clearError(customerName, "#customer-name-error");
  }

  if (customerPhone.value.trim() === "") {
    showError(
      customerPhone,
      "#customer-phone-error",
      "연락처를 입력해 주세요."
    );
    isFormValid = false;
  } else {
    clearError(customerPhone, "#customer-phone-error");
  }

  if (visitDate.value === "") {
    showError(
      visitDate,
      "#visit-date-error",
      "방문 날짜를 선택해 주세요."
    );
    isFormValid = false;
  } else {
    clearError(visitDate, "#visit-date-error");
  }

  if (visitTime.value === "") {
    showError(
      visitTime,
      "#visit-time-error",
      "방문 시간을 선택해 주세요."
    );
    isFormValid = false;
  } else {
    clearError(visitTime, "#visit-time-error");
  }

  if (guestCount.value === "") {
    showError(
      guestCount,
      "#guest-count-error",
      "방문 인원을 선택해 주세요."
    );
    isFormValid = false;
  } else {
    clearError(guestCount, "#guest-count-error");
  }

  if (inquiryMessage.value.trim() === "") {
    showError(
      inquiryMessage,
      "#inquiry-message-error",
      "문의 내용을 입력해 주세요."
    );
    isFormValid = false;
  } else {
    clearError(inquiryMessage, "#inquiry-message-error");
  }

  if (isFormValid) {
    formSuccessMessage.textContent =
      "예약 문의가 접수되었습니다. 확인 후 연락드리겠습니다.";

    reservationForm.reset();
  }
});
