// =========================================================================
// ARCHIVO: main.js
// DESCRIPCIÓN: Funcionalidad general de la página (Buscador, Navbar, etc.)
// =========================================================================

// Función para realizar búsqueda de platillos
function performSearch() {
  const searchInput = document.querySelector(".search-container input")
  const searchTerm = searchInput.value.trim().toLowerCase()

  if (!searchTerm) {
    alert("Por favor ingresa un término de búsqueda")
    return
  }

  const results = []

  // NOTA: 'restaurants' viene de data.js
  restaurants.forEach((restaurant) => {
    for (const category in restaurant.menu) {
      const items = restaurant.menu[category]
      const matchingItems = items.filter(
        (item) =>
          (item.name && item.name.toLowerCase().includes(searchTerm)) ||
          (item.description && item.description.toLowerCase().includes(searchTerm)),
      )

      matchingItems.forEach((item) => {
        results.push({
          dishName: item.name,
          dishDescription: item.description || "",
          restaurantId: restaurant.id,
          restaurantName: restaurant.name,
          category: category,
        })
      })
    }
  })

  const resultsContainer = document.getElementById("dish-search-results")

  if (results.length === 0) {
    resultsContainer.innerHTML = `
      <h3>No se encontraron resultados para "${searchTerm}"</h3>
      <p>Intenta con otro término de búsqueda.</p>
    `
  } else {
    let resultsHTML = `<h3>Resultados de búsqueda para "${searchTerm}" (${results.length} encontrados)</h3>`

    results.forEach((result) => {
      // openRestaurantModal es global gracias a restaurant-modal.js
      resultsHTML += `
        <div class="dish-result-item">
          <h4>${result.dishName}</h4>
          <p>${result.dishDescription}</p>
          <p class="restaurant-name">Restaurante: ${result.restaurantName}</p>
          <p>Categoría: ${result.category}</p>
          <button class="view-restaurant-btn" onclick="openRestaurantModal(${result.restaurantId}, '${result.category}', '${result.dishName}')">
            Ver Menú
          </button>
        </div>
      `
    })

    resultsContainer.innerHTML = resultsHTML
  }
}

// Inicialización general cuando el DOM está listo
document.addEventListener("DOMContentLoaded", () => {
  // Footer
  const yearElement = document.getElementById("current-year");
  if(yearElement) yearElement.textContent = new Date().getFullYear();

  // Tarjetas de restaurante clickeables
  const restaurantCards = document.querySelectorAll(".restaurant-card")
  restaurantCards.forEach((card) => {
    card.addEventListener("click", function () {
      const restaurantId = Number.parseInt(this.getAttribute("data-id"))
      openRestaurantModal(restaurantId)
    })
  })

  // Imágenes de tarjetas clickeables
  const restaurantImages = document.querySelectorAll(".restaurant-image")
  restaurantImages.forEach((image) => {
    image.addEventListener("click", function (e) {
      e.stopPropagation()
      const card = this.closest(".restaurant-card")
      const restaurantId = Number.parseInt(card.getAttribute("data-id"))
      openRestaurantModal(restaurantId)
    })
  })

  // Buscador con tecla Enter
  const searchInput = document.getElementById("search-input");
  if(searchInput) {
      searchInput.addEventListener("keypress", (event) => {
        if (event.key === "Enter") {
            performSearch()
        }
      })
  }

  // Cerrar modal al hacer clic fuera
  window.addEventListener("click", (event) => {
    const modal = document.getElementById("restaurant-modal")
    if (event.target === modal) {
      closeModal()
    }
  })

  // Cerrar modal con ESC
  document.addEventListener("keydown", (event) => {
    if (event.key === "Escape") {
      closeModal()
    }
  })

  // Botón "Ver restaurantes"
  const verRestaurantesBtn = document.getElementById("ver-restaurantes-btn")
  if (verRestaurantesBtn) {
    verRestaurantesBtn.addEventListener("click", () => {
      const section = document.getElementById("restaurantes")
      if(section) section.scrollIntoView({ behavior: "smooth" })
    })
  }

  // Menú móvil (Burger)
  const burger = document.querySelector(".burger")
  const nav = document.querySelector(".nav-links")
  if (burger && nav) {
    burger.addEventListener("click", () => {
      nav.classList.toggle("nav-active")
      burger.classList.toggle("toggle")
    })
  }
})