const FREE_SHIPPING = 149;

function getCart() {
  try {
    return JSON.parse(localStorage.getItem('hotwheels_cart') || '[]');
  } catch {
    return [];
  }
}

function saveCart(cart) {
  localStorage.setItem('hotwheels_cart', JSON.stringify(cart));
  updateCartUI();
}

function addToCart(product, qty = 1) {
  const cart = getCart();
  const i = cart.findIndex(item => item.id === product.id);
  if (i >= 0) cart[i].quantity += qty;
  else cart.push({ ...product, quantity: qty });
  saveCart(cart);
  openCart();
}

function updateQuantity(id, delta) {
  const cart = getCart();
  const i = cart.findIndex(item => item.id === id);
  if (i < 0) return;
  cart[i].quantity += delta;
  if (cart[i].quantity <= 0) cart.splice(i, 1);
  saveCart(cart);
  renderCart();
}

function removeFromCart(id) {
  saveCart(getCart().filter(item => item.id !== id));
  renderCart();
}

function getTotal() {
  return getCart().reduce((s, i) => s + i.price * i.quantity, 0);
}

function getItemCount() {
  return getCart().reduce((s, i) => s + i.quantity, 0);
}

function updateCartUI() {
  const el = document.getElementById('cartCount');
  const badge = document.getElementById('cartBadge');
  const n = getItemCount();
  if (el) el.textContent = n;
  if (badge) badge.textContent = n;
}

function openCart() {
  document.getElementById('cartOverlay').classList.add('open');
  document.getElementById('cartDrawer').classList.add('open');
  renderCart();
}

function closeCart() {
  document.getElementById('cartOverlay').classList.remove('open');
  document.getElementById('cartDrawer').classList.remove('open');
}

function renderFreeShipping() {
  const total = getTotal();
  const remaining = Math.max(0, FREE_SHIPPING - total);
  const bar = document.getElementById('freeShippingBar');
  if (!bar) return;
  bar.innerHTML = remaining > 0
    ? `🚚 Gaste mais R$ ${remaining.toFixed(2).replace('.', ',')} e ganhe frete grátis!`
    : '🚚 Você ganhou frete grátis!';
}

function renderCart() {
  const cart = getCart();
  const container = document.getElementById('cartItems');
  const totalEl = document.getElementById('cartTotal');
  updateCartUI();
  renderFreeShipping();

  if (!container) return;

  if (cart.length === 0) {
    container.innerHTML = '<p style="color:#666">Seu carrinho está vazio</p>';
    if (totalEl) totalEl.textContent = 'R$ 0,00';
    return;
  }

  container.innerHTML = cart.map(item => `
    <div class="cart-item">
      <img src="${item.image}" alt="${item.name}">
      <div class="details">
        <p style="font-weight:600;margin-bottom:4px;font-size:14px">${item.name}</p>
        <p style="font-size:16px;font-weight:700;color:var(--primary);margin-bottom:8px">R$ ${(item.price * item.quantity).toFixed(2).replace('.', ',')}</p>
        <div class="qty-controls">
          <button class="qty-btn" onclick="updateQuantity('${item.id}', -1)">−</button>
          <span>${item.quantity}</span>
          <button class="qty-btn" onclick="updateQuantity('${item.id}', 1)">+</button>
          <button class="remove" onclick="removeFromCart('${item.id}')">Remover</button>
        </div>
      </div>
    </div>
  `).join('');

  if (totalEl) totalEl.textContent = `R$ ${getTotal().toFixed(2).replace('.', ',')}`;
}

function renderProducts(products) {
  const grid = document.getElementById('productsGrid');
  if (!grid) return;
  grid.innerHTML = products.map(p => `
    <div class="product-card">
      <a href="produto.html?id=${p.id}">
        <img src="${p.image}" alt="${p.name}">
        <div class="info">
          <h3>${p.name}</h3>
          <p class="price-label">Preço promocional</p>
          <p class="price">R$ ${p.price.toFixed(2).replace('.', ',')}</p>
          <p class="parcelas">Até ${p.parcelas}</p>
        </div>
      </a>
      <div style="padding:0 16px 16px">
        <button class="btn-secondary" onclick="addProductById('${p.id}')" style="border-radius:60px">+ Adicionar rápido</button>
      </div>
    </div>
  `).join('');
}

function addProductById(id) {
  const p = PRODUCTS.find(x => x.id === id);
  if (p) addToCart(p);
}

function handleSearch(e) {
  e.preventDefault();
  const input = document.getElementById('search') || document.getElementById('searchFooter');
  const q = input ? input.value.trim() : '';
  if (q) location.href = `catalogo.html?q=${encodeURIComponent(q)}`;
}
