/**
 * Pages Module
 * Shared functionality across all pages
 */

document.addEventListener('DOMContentLoaded', () => {
  initNavigation();
  updateCartBadge();
  cart.subscribe(updateCartBadge);
});

/**
 * Initialize navigation functionality
 */
function initNavigation() {
  const menuToggle = document.getElementById('menu-toggle');
  const navMenu = document.getElementById('nav-menu');

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

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

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

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

/**
 * Open cart modal (if it exists on the page)
 */
function openCartModal() {
  const modal = document.getElementById('cart-modal');
  if (modal) {
    updateCartUI();
    modal.classList.add('active');

    // Setup close button
    const closeBtn = modal.querySelector('.modal-close');
    if (closeBtn) {
      closeBtn.addEventListener('click', closeCartModal);
    }

    // Close on background click
    modal.addEventListener('click', (e) => {
      if (e.target === modal) {
        closeCartModal();
      }
    });
  }
}

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

/**
 * Update cart UI
 */
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 = '';
    if (summaryContainer) 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
  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);
    });
  });

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

  // Update summary
  if (summaryContainer) {
    renderCartSummary(summaryContainer);
  }

  // Show checkout button
  if (checkoutBtn) {
    checkoutBtn.style.display = 'block';
    checkoutBtn.addEventListener('click', openCheckout);
  }

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

/**
 * Create cart item HTML
 */
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>
  `;
}

/**
 * Render cart summary
 */
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>
  `;
}

/**
 * Handle quantity change
 */
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);
  }
}

/**
 * Handle quantity input change
 */
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);
}
