const PRODUCTS = [
  {
    id: 1,
    name: "PLA Premium 1 kg - Preto",
    category: "filamentos",
    label: "Filamentos",
    price: 89.90,
    icon: "🧵",
    description: "Filamento PLA para impressões com ótimo acabamento. Cadastre aqui marca, diâmetro, cor e características."
  },
  {
    id: 2,
    name: "PLA Premium 1 kg - Azul",
    category: "filamentos",
    label: "Filamentos",
    price: 89.90,
    icon: "🔵",
    description: "Filamento PLA azul para protótipos, peças decorativas, brindes e projetos em geral."
  },
  {
    id: 3,
    name: "Impressora 3D",
    category: "impressoras",
    label: "Impressoras",
    price: 2199.00,
    icon: "🖨️",
    description: "Espaço para cadastrar impressoras 3D disponíveis, especificações técnicas, garantia e condições."
  },
  {
    id: 4,
    name: "Impressora 3D Profissional",
    category: "impressoras",
    label: "Impressoras",
    price: 3200.00,
    icon: "🖨️",
    description: "Modelo de demonstração para uma impressora de categoria superior ou equipamento em promoção."
  },
  {
    id: 5,
    name: "Bico de Impressão 0,4 mm",
    category: "acessorios",
    label: "Acessórios",
    price: 59.90,
    icon: "🔩",
    description: "Bico de impressão para hotend. Substitua o texto conforme o material, compatibilidade e diâmetro."
  },
  {
    id: 6,
    name: "Kit de Acessórios",
    category: "acessorios",
    label: "Acessórios",
    price: 79.90,
    icon: "⚙️",
    description: "Kit demonstrativo para organizar ferramentas, peças de reposição, agulhas, pinças e outros itens."
  },
  {
    id: 7,
    name: "Vaso Decorativo Espiral",
    category: "impressoes",
    label: "Impressões 3D",
    price: 79.90,
    icon: "🏺",
    description: "Peça decorativa impressa em 3D. Informe material, tamanho, cor e prazo de produção."
  },
  {
    id: 8,
    name: "Estátua Decorativa",
    category: "impressoes",
    label: "Impressões 3D",
    price: 129.90,
    icon: "🦁",
    description: "Exemplo de estátua personalizada. Ideal para mostrar modelos decorativos ou produtos sob encomenda."
  }
];

let activeFilter = "todos";
let searchTerm = "";
let cart = JSON.parse(localStorage.getItem("solution3d-cart") || "[]");
let selectedProduct = null;

const money = value => value.toLocaleString("pt-BR", { style: "currency", currency: "BRL" });

const grid = document.getElementById("productGrid");
const noResults = document.getElementById("noResults");

function renderProducts() {
  const visible = PRODUCTS.filter(p => {
    const categoryOk = activeFilter === "todos" || p.category === activeFilter;
    const textOk = (p.name + " " + p.description + " " + p.label)
      .toLowerCase()
      .includes(searchTerm.toLowerCase());
    return categoryOk && textOk;
  });

  grid.innerHTML = visible.map(p => `
    <article class="product-card">
      <div class="product-image">
        <span class="product-badge">${p.label}</span>
        <span>${p.icon}</span>
      </div>
      <div class="product-content">
        <h3>${p.name}</h3>
        <p>${p.description}</p>
        <div class="price">${money(p.price)}</div>
        <div class="product-actions">
          <button class="btn btn-primary" onclick="addToCart(${p.id})">COMPRAR</button>
          <button class="details" onclick="openProduct(${p.id})" aria-label="Detalhes">＋</button>
        </div>
      </div>
    </article>
  `).join("");

  noResults.style.display = visible.length ? "none" : "block";
}

document.querySelectorAll(".filter").forEach(button => {
  button.addEventListener("click", () => {
    document.querySelectorAll(".filter").forEach(b => b.classList.remove("active"));
    button.classList.add("active");
    activeFilter = button.dataset.filter;
    renderProducts();
  });
});

document.querySelectorAll("[data-category-link]").forEach(link => {
  link.addEventListener("click", () => {
    activeFilter = link.dataset.categoryLink;
    document.querySelectorAll(".filter").forEach(b => {
      b.classList.toggle("active", b.dataset.filter === activeFilter);
    });
    renderProducts();
  });
});

const searchBar = document.getElementById("searchBar");
document.getElementById("searchButton").addEventListener("click", () => {
  searchBar.classList.toggle("show");
  if (searchBar.classList.contains("show")) {
    setTimeout(() => document.getElementById("searchInput").focus(), 50);
  }
});
document.getElementById("closeSearch").addEventListener("click", () => searchBar.classList.remove("show"));
document.getElementById("searchInput").addEventListener("input", e => {
  searchTerm = e.target.value.trim();
  renderProducts();
});

const nav = document.getElementById("mainNav");
document.getElementById("mobileToggle").addEventListener("click", () => nav.classList.toggle("show"));
nav.querySelectorAll("a").forEach(a => a.addEventListener("click", () => nav.classList.remove("show")));

function addToCart(id) {
  const product = PRODUCTS.find(p => p.id === id);
  const item = cart.find(i => i.id === id);
  if (item) item.qty += 1;
  else cart.push({ id: product.id, qty: 1 });

  saveCart();
  renderCart();
  openCart();
}

function removeFromCart(id) {
  cart = cart.filter(i => i.id !== id);
  saveCart();
  renderCart();
}

function saveCart() {
  localStorage.setItem("solution3d-cart", JSON.stringify(cart));
}

function renderCart() {
  const itemsEl = document.getElementById("cartItems");
  const count = cart.reduce((s, i) => s + i.qty, 0);
  document.getElementById("cartCount").textContent = count;

  if (!cart.length) {
    itemsEl.innerHTML = '<div class="empty-cart">Seu carrinho está vazio.</div>';
    document.getElementById("cartTotal").textContent = money(0);
    return;
  }

  let total = 0;
  itemsEl.innerHTML = cart.map(item => {
    const p = PRODUCTS.find(prod => prod.id === item.id);
    total += p.price * item.qty;
    return `
      <div class="cart-item">
        <div class="cart-thumb">${p.icon}</div>
        <div>
          <strong>${p.name}</strong>
          <small>${item.qty} × ${money(p.price)}</small>
        </div>
        <button class="remove-item" onclick="removeFromCart(${p.id})">×</button>
      </div>
    `;
  }).join("");

  document.getElementById("cartTotal").textContent = money(total);
}

const overlay = document.getElementById("overlay");
const drawer = document.getElementById("cartDrawer");

function openCart() {
  drawer.classList.add("show");
  overlay.classList.add("show");
  document.body.classList.add("no-scroll");
}
function closeCart() {
  drawer.classList.remove("show");
  overlay.classList.remove("show");
  document.body.classList.remove("no-scroll");
}
document.getElementById("cartButton").addEventListener("click", openCart);
document.getElementById("closeCart").addEventListener("click", closeCart);
overlay.addEventListener("click", closeCart);

document.getElementById("checkoutButton").addEventListener("click", () => {
  if (!cart.length) return alert("Adicione algum produto ao carrinho.");

  const lines = cart.map(item => {
    const p = PRODUCTS.find(prod => prod.id === item.id);
    return `${item.qty}x ${p.name} - ${money(p.price * item.qty)}`;
  });

  const total = cart.reduce((sum, item) => {
    const p = PRODUCTS.find(prod => prod.id === item.id);
    return sum + p.price * item.qty;
  }, 0);

  const text = encodeURIComponent(
    "Olá! Vim pelo site da Solution 3D e gostaria de comprar:\n\n" +
    lines.join("\n") +
    "\n\nTotal: " + money(total)
  );

  window.open(`https://wa.me/5562999999999?text=${text}`, "_blank");
});

const modal = document.getElementById("productModal");

function openProduct(id) {
  selectedProduct = PRODUCTS.find(p => p.id === id);
  document.getElementById("modalImage").textContent = selectedProduct.icon;
  document.getElementById("modalTag").textContent = selectedProduct.label;
  document.getElementById("modalTitle").textContent = selectedProduct.name;
  document.getElementById("modalDescription").textContent = selectedProduct.description;
  document.getElementById("modalPrice").textContent = money(selectedProduct.price);
  modal.classList.add("show");
  document.body.classList.add("no-scroll");
}

function closeProduct() {
  modal.classList.remove("show");
  document.body.classList.remove("no-scroll");
}

document.getElementById("modalClose").addEventListener("click", closeProduct);
modal.addEventListener("click", e => {
  if (e.target === modal) closeProduct();
});
document.getElementById("modalAdd").addEventListener("click", () => {
  if (selectedProduct) {
    closeProduct();
    addToCart(selectedProduct.id);
  }
});

document.getElementById("year").textContent = new Date().getFullYear();

renderProducts();
renderCart();
