/**
 * Main Application Script
 * Handles DOM interactions and initializations
 */

// ============= SCROLL-TRIGGERED ANIMATIONS =============

function initScrollAnimations() {
  // Create Intersection Observer for scroll-triggered animations
  const observerOptions = {
    threshold: 0.1,
    rootMargin: '0px 0px -50px 0px'
  };

  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        entry.target.classList.add('animate-in-view');
        observer.unobserve(entry.target);
      }
    });
  }, observerOptions);

  // Observe product cards for fade-in animations
  const productCards = document.querySelectorAll('.product-card');
  productCards.forEach((card, index) => {
    card.style.setProperty('--animation-delay', (index * 0.1) + 's');
    observer.observe(card);
  });

  // Observe category banners
  const banners = document.querySelectorAll('.category-banner');
  banners.forEach((banner, index) => {
    banner.style.setProperty('--animation-delay', (index * 0.15) + 's');
    observer.observe(banner);
  });
}

// ============= AGE VERIFICATION =============

function initAgeVerification() {
  const ageVerificationModal = document.getElementById('age-verification-modal');
  const ageDeniedModal = document.getElementById('age-denied-modal');
  const yesBtn = document.getElementById('age-yes-btn');
  const noBtn = document.getElementById('age-no-btn');

  // Always show the age verification modal on page load
  if (ageVerificationModal) {
    ageVerificationModal.style.display = 'flex';
  }

  // Handle Yes button
  if (yesBtn) {
    yesBtn.addEventListener('click', () => {
      // Hide age verification modal
      if (ageVerificationModal) {
        ageVerificationModal.style.display = 'none';
      }

      // Show the rest of the website
      document.body.style.overflow = 'auto';
    });
  }

  // Handle No button
  if (noBtn) {
    noBtn.addEventListener('click', () => {
      // Hide verification modal
      if (ageVerificationModal) {
        ageVerificationModal.style.display = 'none';
      }

      // Show denied modal
      if (ageDeniedModal) {
        ageDeniedModal.style.display = 'flex';
      }

      // Prevent scrolling
      document.body.style.overflow = 'hidden';
    });
  }

  // Prevent body scroll while age verification is active
  document.body.style.overflow = 'hidden';
}

// ============= INITIALIZATION =============

document.addEventListener('DOMContentLoaded', () => {
  initAgeVerification();
  initNavigation();
  initProducts();
  initCart();
  initSearch();
  initCategoryFilter();
  initPriceFilter();
  initModals();
  initScrollAnimations();
});

// ============= NAVIGATION =============

function initNavigation() {
  const menuToggle = document.getElementById('menu-toggle');
  const navMenu = document.getElementById('nav-menu');

  if (menuToggle && navMenu) {
    menuToggle.addEventListener('click', () => {
      navMenu.classList.toggle('active');
      menuToggle.classList.toggle('active');
    });

    // Close menu when link is clicked
    navMenu.querySelectorAll('a').forEach(link => {
      link.addEventListener('click', () => {
        navMenu.classList.remove('active');
        menuToggle.classList.remove('active');
      });
    });
  }

  // Update cart badge
  const cartIcon = document.getElementById('cart-icon');
  if (cartIcon) {
    cartIcon.addEventListener('click', openCartModal);
  }

  // Subscribe to cart changes
  cart.subscribe(updateCartBadge);
  updateCartBadge();
}

function updateCartBadge() {
  const badge = document.getElementById('cart-badge');
  if (badge) {
    const count = cart.getItemCount();
    badge.textContent = count;
    badge.style.display = count > 0 ? 'flex' : 'none';
  }
}

// ============= PRODUCTS =============

function initProducts() {
  renderProducts(PRODUCTS);
}

function renderProducts(products) {
  const grid = document.getElementById('products-grid');
  if (!grid) return;

  if (products.length === 0) {
    grid.innerHTML = '<div style="text-align: center; grid-column: 1/-1; padding: 40px; color: var(--text-muted);">No products found</div>';
    return;
  }

  // Group products by category
  const groupedByCategory = {};
  const categoryOrder = [];

  products.forEach(product => {
    if (!groupedByCategory[product.category]) {
      groupedByCategory[product.category] = [];
      categoryOrder.push(product.category);
    }
    groupedByCategory[product.category].push(product);
  });

  // Create HTML with category sections and banners
  let html = '';

  categoryOrder.forEach(category => {
    const categoryProducts = groupedByCategory[category];
    
    // Category banner
    html += `
      <div class="category-section-wrapper" style="grid-column: 1/-1;">
        <div class="category-banner">
          <div class="category-banner-content">
            <h2 class="category-title">${category}</h2>
            <p class="category-subtitle">${categoryProducts.length} ${categoryProducts.length === 1 ? 'product' : 'products'}</p>
          </div>
          <div class="category-banner-icon">🍾</div>
        </div>
      </div>
    `;

    // Category products
    categoryProducts.forEach(product => {
      html += createProductCard(product);
    });
  });

  grid.innerHTML = html;

  // Add event listeners
  document.querySelectorAll('.btn-add-cart').forEach(btn => {
    btn.addEventListener('click', (e) => {
      const productId = parseInt(btn.dataset.productId);
      addToCart(productId);
    });
  });

  document.querySelectorAll('.btn-whatsapp').forEach(btn => {
    btn.addEventListener('click', (e) => {
      const productId = parseInt(btn.dataset.productId);
      const product = getProductById(productId);
      if (product) {
        paymentHandler.sendWhatsAppInquiry(product);
      }
    });
  });
}

function createProductCard(product) {
  return `
    <div class="product-card fade-in">
      <div class="product-image" data-placeholder="Product Image">
        <img src="${product.image}" alt="${product.name}" onerror="this.src='https://via.placeholder.com/250x300?text=${encodeURIComponent(product.name)}'">
      </div>
      <div class="product-info">
        <div class="product-name">${product.name}</div>
        <div class="product-category">${product.category}</div>
        <div class="product-price">${formatPrice(product.price)}</div>
        <div class="product-actions">
          <button class="btn-add-cart" data-product-id="${product.id}">
            🛒 Add to Cart
          </button>
          <button class="btn-whatsapp" data-product-id="${product.id}" title="Inquire via WhatsApp">
            <img src="https://png.pngtree.com/png-vector/20221018/ourmid/pngtree-whatsapp-icon-png-image_6315990.png" alt="WhatsApp" class="whatsapp-icon"> Inquire
          </button>
        </div>
      </div>
    </div>
  `;
}

// ============= CART =============

function initCart() {
  cart.subscribe((event) => {
    if (event.eventType === 'itemAdded' || event.eventType === 'itemRemoved' || event.eventType === 'quantityUpdated') {
      updateCartUI();
    }
  });

  updateCartUI();
}

function updateCartUI() {
  const container = document.getElementById('cart-items-container');
  const summaryContainer = document.getElementById('cart-summary-container');
  const checkoutBtn = document.getElementById('btn-checkout');
  const emptyMessage = document.getElementById('empty-cart-message');
  const checkoutTotal = document.getElementById('checkout-total');

  if (!container) return;

  if (cart.isEmpty()) {
    container.innerHTML = '';
    summaryContainer.innerHTML = '';
    if (checkoutBtn) checkoutBtn.style.display = 'none';
    if (emptyMessage) emptyMessage.style.display = 'block';
    return;
  }

  // Clear empty message
  if (emptyMessage) emptyMessage.style.display = 'none';

  // Render cart items
  const items = cart.getItems();
  container.innerHTML = items.map(item => createCartItem(item)).join('');

  // Add event listeners to cart controls
  document.querySelectorAll('.qty-btn').forEach(btn => {
    btn.addEventListener('click', handleQuantityChange);
  });

  document.querySelectorAll('.cart-item-remove').forEach(btn => {
    btn.addEventListener('click', (e) => {
      const productId = parseInt(btn.dataset.productId);
      cart.removeItem(productId);
    });
  });

  // Update quantity inputs
  document.querySelectorAll('.qty-input').forEach(input => {
    input.addEventListener('change', handleQuantityInput);
  });

  // Render summary
  renderCartSummary(summaryContainer);

  // Show checkout button
  if (checkoutBtn) checkoutBtn.style.display = 'block';

  // Update checkout total
  if (checkoutTotal) {
    checkoutTotal.querySelector('p:last-child').textContent = formatPrice(cart.getTotal());
  }
}

function createCartItem(item) {
  return `
    <div class="cart-item">
      <div class="cart-item-info">
        <div class="cart-item-name">${item.product.name}</div>
        <div class="cart-item-price">${formatPrice(item.product.price)} each</div>
      </div>
      <div class="cart-item-qty">
        <button class="qty-btn" data-product-id="${item.productId}" data-action="decrease">−</button>
        <input type="number" class="qty-input" data-product-id="${item.productId}" value="${item.quantity}" min="1">
        <button class="qty-btn" data-product-id="${item.productId}" data-action="increase">+</button>
      </div>
      <div style="text-align: right;">
        <div style="color: var(--accent-amber); font-weight: bold; margin-bottom: 5px;">${formatPrice(item.product.price * item.quantity)}</div>
        <button class="cart-item-remove" data-product-id="${item.productId}">Remove</button>
      </div>
    </div>
  `;
}

function renderCartSummary(container) {
  if (!container) return;

  const total = cart.getTotal();
  const itemCount = cart.getItemCount();

  container.innerHTML = `
    <div class="cart-summary">
      <div class="summary-row">
        <span>Subtotal:</span>
        <span>${formatPrice(total)}</span>
      </div>
      <div class="summary-row">
        <span>Items:</span>
        <span>${itemCount}</span>
      </div>
      <div class="summary-row">
        <span>Delivery:</span>
        <span>Free</span>
      </div>
      <div class="summary-row total">
        <span>Total:</span>
        <span>${formatPrice(total)}</span>
      </div>
    </div>
  `;
}

function handleQuantityChange(e) {
  const btn = e.target;
  const productId = parseInt(btn.dataset.productId);
  const action = btn.dataset.action;
  const currentQuantity = cart.getQuantity(productId);

  if (action === 'increase') {
    cart.updateQuantity(productId, currentQuantity + 1);
  } else if (action === 'decrease') {
    cart.updateQuantity(productId, currentQuantity - 1);
  }
}

function handleQuantityInput(e) {
  const input = e.target;
  const productId = parseInt(input.dataset.productId);
  let quantity = parseInt(input.value) || 1;

  if (quantity < 1) quantity = 1;
  cart.updateQuantity(productId, quantity);
}

// ============= SEARCH =============

function initSearch() {
  const searchBtn = document.getElementById('search-btn');
  const searchInput = document.getElementById('search-input');

  if (searchBtn) {
    searchBtn.addEventListener('click', handleSearch);
  }

  if (searchInput) {
    // Live search on input
    searchInput.addEventListener('input', handleLiveSearch);
    
    // Full search on Enter
    searchInput.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') {
        handleSearch();
      }
    });

    // Close dropdown when clicking outside
    document.addEventListener('click', (e) => {
      if (!e.target.closest('.search-bar-wrapper')) {
        closeLiveSearchResults();
      }
    });
  }
}

function handleLiveSearch() {
  const searchInput = document.getElementById('search-input');
  const resultsContainer = document.getElementById('live-search-results');

  if (!searchInput || !resultsContainer) return;

  const query = searchInput.value.trim();

  // If empty, hide results
  if (query === '') {
    closeLiveSearchResults();
    return;
  }

  // Search products
  const results = searchProducts(query);

  // Display results
  if (results.length === 0) {
    resultsContainer.innerHTML = '<div class="empty">No products found</div>';
    resultsContainer.classList.add('empty');
    resultsContainer.style.display = 'block';
    return;
  }

  // Create result items
  resultsContainer.classList.remove('empty');
  resultsContainer.innerHTML = results.slice(0, 8).map(product => `
    <div class="search-result-item" onclick="selectSearchResult(${product.id})">
      <img src="${product.image}" alt="${product.name}" class="search-result-image" onerror="this.src='https://via.placeholder.com/50x50?text=${encodeURIComponent(product.name)}'">
      <div class="search-result-info">
        <div class="search-result-name">${product.name}</div>
        <div class="search-result-category">${product.category}</div>
        <div class="search-result-price">${formatPrice(product.price)}</div>
      </div>
    </div>
  `).join('');

  resultsContainer.style.display = 'block';
}

function selectSearchResult(productId) {
  const product = getProductById(productId);
  if (!product) return;

  // Close dropdown
  closeLiveSearchResults();

  // Clear search
  const searchInput = document.getElementById('search-input');
  if (searchInput) {
    searchInput.value = product.name;
  }

  // Scroll to product or show full results
  const results = PRODUCTS.filter(p => p.name.toLowerCase().includes(product.name.toLowerCase()));
  renderProducts(results);
}

function closeLiveSearchResults() {
  const resultsContainer = document.getElementById('live-search-results');
  if (resultsContainer) {
    resultsContainer.style.display = 'none';
  }
}

function handleSearch() {
  const searchInput = document.getElementById('search-input');
  if (!searchInput) return;

  const query = searchInput.value.trim();

  if (query === '') {
    renderProducts(PRODUCTS);
    return;
  }

  const results = searchProducts(query);
  renderProducts(results);

  // Close dropdown
  closeLiveSearchResults();

  if (results.length === 0) {
    showNotification('No products found for your search', 'info');
  }
}

// ============= CATEGORY FILTER =============

function initCategoryFilter() {
  const filterContainer = document.getElementById('category-filter');
  if (!filterContainer) return;

  const categories = getCategories();
  filterContainer.innerHTML = categories.map(category => `
    <button class="filter-btn ${category === 'All' ? 'active' : ''}" data-category="${category}">
      ${category}
    </button>
  `).join('');

  filterContainer.querySelectorAll('.filter-btn').forEach(btn => {
    btn.addEventListener('click', handleCategoryFilter);
  });
}

function handleCategoryFilter(e) {
  const btn = e.target;
  const category = btn.dataset.category;

  // Update active state
  document.querySelectorAll('.filter-btn').forEach(b => {
    b.classList.remove('active');
  });
  btn.classList.add('active');

  // Clear search
  const searchInput = document.getElementById('search-input');
  if (searchInput) searchInput.value = '';

  // Filter products
  const products = getProductsByCategory(category);
  renderProducts(products);
}

// ============= PRICE FILTER =============

function initPriceFilter() {
  const priceFilter = document.getElementById('price-filter');
  if (!priceFilter) return;

  priceFilter.querySelectorAll('.filter-btn-option').forEach(btn => {
    btn.addEventListener('click', handlePriceFilter);
  });
}

function handlePriceFilter(e) {
  const btn = e.target;
  const selectedPrice = btn.dataset.price;

  // Update active state
  document.querySelectorAll('#price-filter .filter-btn-option').forEach(b => {
    b.classList.remove('active');
  });
  btn.classList.add('active');

  applyAllFilters();
}

// ============= APPLY ALL FILTERS =============

function applyAllFilters() {
  // Get active category
  const activeCategory = document.querySelector('.filter-btn.active');
  const category = activeCategory ? activeCategory.dataset.category : 'All';

  // Get active price
  const activePriceBtn = document.querySelector('#price-filter .filter-btn-option.active');
  const price = activePriceBtn ? activePriceBtn.dataset.price : 'all';

  // Get products
  let products = getProductsByCategory(category);

  // Filter by price
  if (price !== 'all') {
    products = filterProductsByPrice(products, price);
  }

  renderProducts(products);
}

function filterProductsByPrice(products, priceRange) {
  const [min, max] = priceRange.split('-').map(Number);
  
  if (!max) {
    // For "1000+" case
    return products.filter(p => p.price >= min);
  }
  
  return products.filter(product => product.price >= min && product.price <= max);
}

// ============= MODALS =============

function initModals() {
  // Cart modal
  const cartModal = document.getElementById('cart-modal');
  const cartModalClose = document.getElementById('cart-modal-close');
  const checkoutBtn = document.getElementById('btn-checkout');

  if (cartModalClose) {
    cartModalClose.addEventListener('click', closeCartModal);
  }

  if (cartModal) {
    cartModal.addEventListener('click', (e) => {
      if (e.target === cartModal) {
        closeCartModal();
      }
    });
  }

  if (checkoutBtn) {
    checkoutBtn.addEventListener('click', openCheckout);
  }

  // Checkout modal
  const checkoutModal = document.getElementById('checkout-modal');
  const checkoutModalClose = document.getElementById('checkout-modal-close');

  if (checkoutModalClose) {
    checkoutModalClose.addEventListener('click', closeCheckoutModal);
  }

  if (checkoutModal) {
    checkoutModal.addEventListener('click', (e) => {
      if (e.target === checkoutModal) {
        closeCheckoutModal();
      }
    });
  }

  // Confirmation modal
  const confirmationModal = document.getElementById('order-confirmation-modal');
  const confirmationModalClose = document.getElementById('confirmation-modal-close');

  if (confirmationModalClose) {
    confirmationModalClose.addEventListener('click', () => {
      closeModal('order-confirmation-modal');
    });
  }

  if (confirmationModal) {
    confirmationModal.addEventListener('click', (e) => {
      if (e.target === confirmationModal) {
        closeModal('order-confirmation-modal');
      }
    });
  }
}

function openCartModal() {
  const modal = document.getElementById('cart-modal');
  if (modal) {
    modal.classList.add('active');
  }
}

function closeCartModal() {
  const modal = document.getElementById('cart-modal');
  if (modal) {
    modal.classList.remove('active');
  }
}

function closeCheckoutModal() {
  const modal = document.getElementById('checkout-modal');
  if (modal) {
    modal.classList.remove('active');
  }
}

// ============= UTILITIES =============

/**
 * Show toast notification
 */
function showToast(message, duration = 3000) {
  const toast = document.createElement('div');
  toast.style.cssText = `
    position: fixed;
    bottom: 20px;
    left: 20px;
    background-color: var(--accent-gold);
    color: var(--primary-dark);
    padding: 15px 20px;
    border-radius: 5px;
    z-index: 3000;
    font-weight: bold;
    box-shadow: var(--shadow-lg);
  `;
  toast.textContent = message;

  document.body.appendChild(toast);

  setTimeout(() => {
    toast.style.animation = 'fadeOut 0.3s ease-in';
    setTimeout(() => toast.remove(), 300);
  }, duration);
}
