document.addEventListener('DOMContentLoaded', () => {
  // Mobile Menu Toggle
  const hamburger = document.querySelector('.hamburger');
  const navLinks = document.querySelector('.nav-links');
  if (hamburger) {
    hamburger.addEventListener('click', () => {
      navLinks.classList.toggle('active');
    });
  }

  // Scroll to top button
  const scrollTop = document.querySelector('.scroll-top');
  window.addEventListener('scroll', () => {
    if (window.scrollY > 300) {
      scrollTop.style.display = 'flex';
    } else {
      scrollTop.style.display = 'none';
    }
  });
  if (scrollTop) {
    scrollTop.addEventListener('click', () => {
      window.scrollTo({ top: 0, behavior: 'smooth' });
    });
  }

  // Fade-in animation on scroll
  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        entry.target.classList.add('visible');
      }
    });
  }, { threshold: 0.1 });

  document.querySelectorAll('.fade-in').forEach(el => observer.observe(el));

  // Load JSON and render products (used on index.html and menu.html)
  const menuGrid = document.getElementById('menu-grid');
  const popularGrid = document.getElementById('popular-grid');
  const tabsContainer = document.getElementById('category-tabs');

  if (menuGrid || popularGrid) {
    fetch('menü/trendyol_menu_full (6).json')
      .then(res => res.json())
      .then(data => {
        const products = data.products || [];
        
        // Removed popular products logic for Homepage since index.html was redesigned

        // Render for Menu Page
        if (menuGrid && tabsContainer) {
          // Define ordered categories
          const categories = [
            "Tostlar", "Menemenler", "Omletler", "Gözlemeler", 
            "Köfteler & Ekmek Arası", "Soğuk Sandviçler", "Tatlılar", 
            "Çorbalar", "İçecekler", "Aperatif"
          ];
          
          // Generate tabs
          categories.forEach((cat, index) => {
            const btn = document.createElement('button');
            btn.className = `tab-btn ${index === 0 ? 'active' : ''}`;
            btn.dataset.category = cat;
            btn.textContent = cat;
            tabsContainer.appendChild(btn);
          });

          // Filter functionality
          const tabBtns = document.querySelectorAll('.tab-btn');
          tabBtns.forEach(btn => {
            btn.addEventListener('click', (e) => {
              tabBtns.forEach(b => b.classList.remove('active'));
              e.target.classList.add('active');
              
              const cat = e.target.dataset.category;
              const filtered = products.filter(p => p.category === cat || p.groupName === cat); // groupName or category depending on JSON structure
              // Because JSON might not have exact match, fallback to contains:
              const fallbackFiltered = products.filter(p => {
                 const pCat = p.category ? p.category.toLowerCase() : '';
                 return pCat.includes(cat.toLowerCase());
              });
              
              renderCards(fallbackFiltered.length > 0 ? fallbackFiltered : products, menuGrid); // Fallback to all if category not found for robustness, but preferably fallbackFiltered
            });
          });

          // Initial render (first tab)
          const firstCat = categories[0];
          const initialProducts = products.filter(p => {
             const pCat = p.category ? p.category.toLowerCase() : '';
             return pCat.includes(firstCat.toLowerCase());
          });
          renderCards(initialProducts.length > 0 ? initialProducts : products.slice(0,20), menuGrid);
        }
      })
      .catch(err => console.error("JSON Error:", err));
  }

  function renderCards(items, container) {
    
    const htmls = items.map(item => {
      let imgUrl = item.imageUrl;
      if (!imgUrl || imgUrl.trim() === '') {
        const similar = items.find(p => p.imageUrl && p.title && p.category === item.category && p.category !== "Tatlılar");
        // Ensure we don't display drink images under desserts or wrong categories.
        imgUrl = similar ? similar.imageUrl : '../images/logo.png';
      }
      
      // Make design more subtle and refined
      return `

      <div class="card fade-in">
        <img src="${imgUrl}" alt="${item.title}" title="${item.title}">
        <div class="card-content">
          <h3>${item.title}</h3>
          <p>${item.description || ''}</p>
        </div>
      </div>
    `;
    });
    container.innerHTML = htmls.join('');
    // Re-observe new elements
    document.querySelectorAll('.fade-in').forEach(el => observer.observe(el));
  }
});
