// State management
let products = [];
let cart = [];
// DOM Elements
const productsContainer = document.getElementById('products-container');
const cartItems = document.getElementById('cart-items');
const cartTotal = document.getElementById('cart-total');
const cartCount = document.getElementById('cart-count');
// Fetch products from API
async function fetchProducts() {
const response = await fetch('/api/products');
products = await response.json();
renderProducts();
}
// Render products
function renderProducts() {
productsContainer.innerHTML = products.map(product => `
${product.name}
${product.description}
€${product.price.toFixed(2)}
`).join('');
}
// Add to cart
async function addToCart(productId) {
const response = await fetch('/api/cart', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ productId })
});
cart = await response.json();
updateCart();
}
// Remove from cart
async function removeFromCart(productId) {
const response = await fetch(`/api/cart/${productId}`, {
method: 'DELETE'
});
cart = await response.json();
updateCart();
}
// Update quantity
async function updateQuantity(productId, quantity) {
if (quantity < 1) return;
const response = await fetch(`/api/cart/${productId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ quantity })
});
cart = await response.json();
updateCart();
}
// Update cart display
function updateCart() {
cartItems.innerHTML = cart.map(item => `
${item.product.name}
${item.quantity}
€${(item.product.price * item.quantity).toFixed(2)}
`).join('');
const total = cart.reduce((sum, item) => sum + (item.product.price * item.quantity), 0);
cartTotal.innerHTML = `Gesamt: €${total.toFixed(2)}`;
cartCount.innerHTML = cart.reduce((sum, item) => sum + item.quantity, 0);
}
// Initialize
fetchProducts();
updateCart();