// =========================================================================
// ARCHIVO: restaurant-modal.js
// DESCRIPCIÓN: Modal conectado a JSONBin
// =========================================================================

let currentSlideIndex = 0
let slideInterval = null

function openRestaurantModal(restaurantId, highlightCategory = null, highlightDish = null) {
  const restaurant = restaurants.find((r) => r.id === restaurantId)
  if (!restaurant) return

  const modal = document.getElementById("restaurant-modal")
  const modalContent = document.getElementById("modal-content-container")

  const content = `
    <div class="fullscreen-slideshow">
      <div class="slideshow-container">
        ${restaurant.images.map((image, index) => `
          <div class="slide ${index === 0 ? "active" : ""}" data-slide="${index}">
            <img src="${image}" alt="${restaurant.name}">
            <div class="slide-overlay"></div>
          </div>
        `).join("")}
        <div class="restaurant-title-overlay">
          <h1>${restaurant.name}</h1>
          <p>${restaurant.description}</p>
        </div>
        <div class="slide-indicators">
          ${restaurant.images.map((_, index) => `
            <span class="indicator ${index === 0 ? "active" : ""}" data-slide="${index}"></span>
          `).join("")}
        </div>
      </div>
    </div>

    <div class="restaurant-content-below">
      <div class="container restaurant-modal-grid">
        
        <aside class="modal-sidebar">
            <div id="sidebar-stats-${restaurant.id}" class="sidebar-rating-container">
                <div class="rating-big-score"><i class="fas fa-spinner fa-spin"></i></div>
                <div class="rating-stars-display">Cargando datos...</div>
                <div class="rating-count-label" style="margin-top:5px; font-weight:bold;">---</div>
            </div>

            <button onclick="showRatingAlert(${restaurant.id}, '${restaurant.name}')" class="btn-primary btn-rating-sidebar">
                <i class="fas fa-star"></i> Calificar
            </button>

            <div class="sidebar-info">
                <div class="info-item"><span class="info-label">Dirección:</span> ${restaurant.address}</div>
                <div class="info-item"><span class="info-label">Teléfono:</span> ${restaurant.phone}</div>
            </div>
        </aside>

        <main class="modal-main-content">
            <div class="menu-section">
              <h3>Menú</h3>
              ${generateMenuHTML(restaurant.menu, highlightCategory, highlightDish)}
            </div>
            <div class="restaurant-history">
              <h3>Historia</h3>
              <p>${restaurant.history}</p>
            </div>
        </main>
      </div>
    </div>
    
    <button class="back-to-restaurants" onclick="closeModal()">
      <i class="fas fa-arrow-left"></i>
    </button>
  `

  modalContent.innerHTML = content
  modal.style.display = "block"
  document.body.style.overflow = "hidden"

  initSlideshow(restaurant.images.length)
  initMenuAccordions(highlightCategory)

  // LLAMADA A LA NUBE (JSONBin)
  if (window.getRatingData && window.updateSidebarDOM) {
      window.getRatingData(restaurantId).then(data => {
          // Actualizamos la vista cuando lleguen los datos
          window.updateSidebarDOM(restaurantId, data);
      });
  }
}

// --- FUNCIONES AUXILIARES (NO CAMBIAN) ---
function initSlideshow(totalSlides) {
  currentSlideIndex = 0
  if (slideInterval) clearInterval(slideInterval)
  slideInterval = setInterval(() => { nextSlide(totalSlides) }, 1500)
  const indicators = document.querySelectorAll(".indicator")
  indicators.forEach((indicator, index) => {
    indicator.addEventListener("click", () => { goToSlide(index, totalSlides) })
  })
}

function nextSlide(totalSlides) {
  const currentSlide = document.querySelector(".slide.active")
  const currentIndicator = document.querySelector(".indicator.active")
  if(currentSlide) currentSlide.classList.remove("active")
  if(currentIndicator) currentIndicator.classList.remove("active")
  currentSlideIndex = (currentSlideIndex + 1) % totalSlides
  const nextSlide = document.querySelector(`[data-slide="${currentSlideIndex}"]`)
  const nextIndicator = document.querySelectorAll(".indicator")[currentSlideIndex]
  if(nextSlide) nextSlide.classList.add("active")
  if(nextIndicator) nextIndicator.classList.add("active")
}

function goToSlide(slideIndex, totalSlides) {
  const currentSlide = document.querySelector(".slide.active")
  const currentIndicator = document.querySelector(".indicator.active")
  if(currentSlide) currentSlide.classList.remove("active")
  if(currentIndicator) currentIndicator.classList.remove("active")
  currentSlideIndex = slideIndex
  const targetSlide = document.querySelector(`[data-slide="${slideIndex}"]`)
  const targetIndicator = document.querySelectorAll(".indicator")[slideIndex]
  if(targetSlide) targetSlide.classList.add("active")
  if(targetIndicator) targetIndicator.classList.add("active")
  if (slideInterval) { clearInterval(slideInterval); slideInterval = setInterval(() => { nextSlide(totalSlides) }, 1500) }
}

function closeModal() {
  const modal = document.getElementById("restaurant-modal")
  modal.style.display = "none"
  document.body.style.overflow = "auto"
  if (slideInterval) { clearInterval(slideInterval); slideInterval = null }
}

function generateMenuHTML(menu, highlightCategory = null, highlightDish = null) {
  let menuHTML = ""
  for (const category in menu) {
    const isHighlighted = category === highlightCategory
    menuHTML += `
      <div class="menu-category-section ${isHighlighted ? "highlight-category" : ""}">
        <h4 class="${isHighlighted ? "active" : ""}">${category}</h4>
        <div class="menu-list ${isHighlighted ? "active" : ""}">
          ${menu[category].map((item) => {
              const isHighlightedDish = highlightDish && item.name === highlightDish
              return `
                <div class="menu-item-simple ${isHighlightedDish ? "highlight-dish" : ""}">
                  <div class="menu-item-header"><span class="menu-item-name">${item.name}</span></div>
                  <p class="menu-item-description">${item.description || ""}</p>
                </div>`
            }).join("")}
        </div>
      </div>`
  }
  return menuHTML
}

function initMenuAccordions(highlightCategory = null) {
  const categoryHeaders = document.querySelectorAll(".menu-category-section h4")
  categoryHeaders.forEach((header) => {
    header.addEventListener("click", function () {
      this.classList.toggle("active")
      const menuList = this.nextElementSibling
      menuList.classList.toggle("active")
    })
    if (!highlightCategory && header === categoryHeaders[0]) {
      header.classList.add("active")
      header.nextElementSibling.classList.add("active")
    }
  })
  if (highlightCategory) {
    const highlightedCategory = document.querySelector(".highlight-category")
    if (highlightedCategory) setTimeout(() => { highlightedCategory.scrollIntoView({ behavior: "smooth", block: "center" }) }, 300)
  }
}

function scrollToHighlightedDish() {
  const highlightedDish = document.querySelector(".highlight-dish")
  if (highlightedDish) setTimeout(() => { highlightedDish.scrollIntoView({ behavior: "smooth", block: "center" }) }, 500)
}

window.openRestaurantModal = openRestaurantModal;
window.closeModal = closeModal;
window.scrollToHighlightedDish = scrollToHighlightedDish;