// 인기 메뉴 카드와 갤러리 사진이 화면에 들어올 때 차례로 표시
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();

// 인기 메뉴 검색과 조건 필터
const menuSearchInput = document.querySelector("#menu-search");
const menuCards = document.querySelectorAll(".menu-card");
const menuNoResults = document.querySelector(".menu-no-results");
const menuFilterButtons = document.querySelectorAll(".menu-filter-button");
const menuFilterClearButton = document.querySelector(".menu-filter-clear");
const menuFavoritesFilterButton = document.querySelector(".menu-favorites-filter");
const menuFavoritesCount = document.querySelector(".menu-favorites-count");
const menuFavoritesClearButton = document.querySelector(".menu-favorites-clear");
const favoriteToast = document.querySelector(".favorite-toast");
let favoriteToastTimer;

function showFavoriteToast(message) {
  window.clearTimeout(favoriteToastTimer);
  favoriteToast.textContent = message;
  favoriteToast.classList.add("is-visible");

  favoriteToastTimer = window.setTimeout(function () {
    favoriteToast.classList.remove("is-visible");
  }, 2000);
}

const favoriteStorageKey = "mellow-favorites";
let selectedCategory = "전체";
let showFavoritesOnly = false;
const excludedIngredients = new Set();
let menuSearchTimer;
let favoriteMenuNames = loadFavoriteMenuNames();

function loadFavoriteMenuNames() {
  try {
    const savedFavorites = JSON.parse(window.localStorage.getItem(favoriteStorageKey) || "[]");
    return new Set(Array.isArray(savedFavorites) ? savedFavorites.filter(function (name) { return typeof name === "string"; }) : []);
  } catch (error) {
    return new Set();
  }
}

function saveFavoriteMenuNames() {
  window.localStorage.setItem(favoriteStorageKey, JSON.stringify(Array.from(favoriteMenuNames)));
}

function setMenuFilterButtonState(button, isSelected) {
  button.classList.toggle("is-selected", isSelected);
  button.setAttribute("aria-pressed", String(isSelected));
}

function updateCategoryButtons() {
  document.querySelectorAll('[data-filter-type="category"]').forEach(function (button) {
    setMenuFilterButtonState(button, button.dataset.filterValue === selectedCategory);
  });
}

function updateFavoriteButtons() {
  menuCards.forEach(function (card) {
    const menuName = card.querySelector("h3").textContent.trim();
    const favoriteButton = card.querySelector(".menu-favorite-button");
    const isFavorite = favoriteMenuNames.has(menuName);
    favoriteButton.classList.toggle("is-selected", isFavorite);
    favoriteButton.setAttribute("aria-pressed", String(isFavorite));
    favoriteButton.setAttribute("aria-label", isFavorite ? `${menuName} 즐겨찾기에서 빼기` : `${menuName} 즐겨찾기에 담기`);
    favoriteButton.textContent = isFavorite ? "♥" : "♡";
  });
  menuFavoritesCount.textContent = favoriteMenuNames.size;
  menuFavoritesClearButton.disabled = favoriteMenuNames.size === 0;
  setMenuFilterButtonState(menuFavoritesFilterButton, showFavoritesOnly);
}

function getActiveMenuConditions() {
  const conditions = [];
  const searchTerm = menuSearchInput.value.trim();
  if (searchTerm) conditions.push(`검색어 ‘${searchTerm}’`);
  if (selectedCategory !== "전체") conditions.push(`종류 ‘${selectedCategory}’`);
  excludedIngredients.forEach(function (ingredient) { conditions.push(`‘${ingredient} 없는 것’`); });
  if (showFavoritesOnly) conditions.push("내가 고른 메뉴");
  return conditions;
}

function applyMenuFilters() {
  const searchTerm = menuSearchInput.value.trim().toLowerCase();
  let visibleCardCount = 0;
  menuCards.forEach(function (card) {
    const menuName = card.querySelector("h3").textContent.trim();
    const menuDescription = card.querySelector(".menu-card-content > p").textContent;
    const searchableText = `${menuName} ${menuDescription}`.toLowerCase();
    const category = card.dataset.category || "";
    const ingredients = (card.dataset.ingredients || "").split(/\s+/).filter(Boolean);
    const matchesSearch = searchableText.includes(searchTerm);
    const matchesCategory = selectedCategory === "전체" || category === selectedCategory;
    const matchesIngredients = Array.from(excludedIngredients).every(function (ingredient) { return !ingredients.includes(ingredient); });
    const matchesFavorites = !showFavoritesOnly || favoriteMenuNames.has(menuName);
    const isMatch = matchesSearch && matchesCategory && matchesIngredients && matchesFavorites;
    card.hidden = !isMatch;
    if (isMatch) visibleCardCount += 1;
  });
  const hasNoResults = visibleCardCount === 0;
  menuNoResults.classList.toggle("is-visible", hasNoResults);
  if (!hasNoResults) { menuNoResults.textContent = ""; return; }
  if (showFavoritesOnly && favoriteMenuNames.size === 0) {
    menuNoResults.textContent = "아직 고른 메뉴가 없습니다. 하트를 눌러 담아 보세요.";
    return;
  }
  const activeConditions = getActiveMenuConditions();
  const conditionText = activeConditions.length > 0 ? `현재 조건: ${activeConditions.join(", ")}. ` : "";
  menuNoResults.textContent = `${conditionText}조건에 맞는 메뉴가 없습니다. 조건을 하나 줄여 보세요.`;
}

menuSearchInput.addEventListener("input", function () {
  window.clearTimeout(menuSearchTimer);
  menuSearchTimer = window.setTimeout(applyMenuFilters, 300);
});

menuFilterButtons.forEach(function (button) {
  button.addEventListener("click", function () {
    const filterType = button.dataset.filterType;
    const filterValue = button.dataset.filterValue;
    if (filterType === "category") {
      if (filterValue === "전체") selectedCategory = "전체";
      else if (selectedCategory === filterValue) selectedCategory = "전체";
      else selectedCategory = filterValue;
      updateCategoryButtons();
    }
    if (filterType === "exclude") {
      if (excludedIngredients.has(filterValue)) {
        excludedIngredients.delete(filterValue);
        setMenuFilterButtonState(button, false);
      } else {
        excludedIngredients.add(filterValue);
        setMenuFilterButtonState(button, true);
      }
    }
    if (filterType === "favorites") {
      showFavoritesOnly = !showFavoritesOnly;
      setMenuFilterButtonState(button, showFavoritesOnly);
    }
    window.clearTimeout(menuSearchTimer);
    applyMenuFilters();
  });
});

document.querySelectorAll(".menu-favorite-button").forEach(function (button) {
  button.addEventListener("click", function (event) {
    event.preventDefault();
    event.stopPropagation();
    const card = button.closest(".menu-card");
    const menuName = card.querySelector("h3").textContent.trim();
    let favoriteMessage;

    if (favoriteMenuNames.has(menuName)) {
      favoriteMenuNames.delete(menuName);
      favoriteMessage = "즐겨찾기에서 뺐습니다";
    } else {
      favoriteMenuNames.add(menuName);
      favoriteMessage = "즐겨찾기에 담았습니다";
    }

    saveFavoriteMenuNames();
    updateFavoriteButtons();
    applyMenuFilters();
    showFavoriteToast(favoriteMessage);
  });
});

menuFavoritesClearButton.addEventListener("click", function () {
  if (favoriteMenuNames.size === 0) return;
  if (!window.confirm("고른 메뉴를 모두 지울까요?")) return;
  favoriteMenuNames.clear();
  saveFavoriteMenuNames();
  updateFavoriteButtons();
  applyMenuFilters();
});

menuFilterClearButton.addEventListener("click", function () {
  window.clearTimeout(menuSearchTimer);
  menuSearchInput.value = "";
  selectedCategory = "전체";
  showFavoritesOnly = false;
  excludedIngredients.clear();
  updateCategoryButtons();
  document.querySelectorAll('[data-filter-type="exclude"]').forEach(function (button) { setMenuFilterButtonState(button, false); });
  setMenuFilterButtonState(menuFavoritesFilterButton, false);
  applyMenuFilters();
  menuSearchInput.focus();
});

updateFavoriteButtons();
applyMenuFilters();

// 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();
  }
});
