document.addEventListener('DOMContentLoaded', () => {
    let products = [];
    let cart = []; 
    let toastTimeout;
    let currentImageIndex = 0;
    let currentProductImages = [];
    const waAdminNumber = '6288989817520'; // GANTI DENGAN NOMOR WA ADMIN ANDA

    // --- Element Selectors ---
    const productContainer = document.getElementById('product-container');
    const searchInput = document.getElementById('search-input');
    const categorySelect = document.getElementById('category-select');
    const cartButton = document.getElementById('cart-button');
    const productModal = document.getElementById('product-modal');
    const cartModal = document.getElementById('cart-modal');
    const closeModalButtons = document.querySelectorAll('.close-button');
    const checkoutButton = document.getElementById('checkout-button');
    const toastNotification = document.getElementById('toast-notification');

    function trackEvent(type, productId) {
        const action = type === 'view' ? 'increment_view' : 'increment_cart';
        const formData = new FormData();
        formData.append('action', action);
        formData.append('id', productId);
        fetch('api.php', { method: 'POST', body: formData }).catch(e => console.error(e));
    }

    async function fetchProducts() {
        try {
            const response = await fetch(`api.php?action=get_products&v=${new Date().getTime()}`);
            if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
            products = await response.json();
            if (!Array.isArray(products)) throw new Error("Data produk tidak valid.");
            populateCategories(products);
            renderProducts();
        } catch (error) {
            console.error('Gagal memuat produk:', error);
            productContainer.innerHTML = '<p>Gagal memuat produk. Silakan coba lagi nanti.</p>';
        }
    }

    function populateCategories(productsToFilter) {
        const categories = [...new Set(productsToFilter.map(p => (p.category || '').trim()).filter(c => c))];
        categorySelect.innerHTML = '<option value="all">Semua Kategori</option>';
        categories.sort().forEach(c => categorySelect.innerHTML += `<option value="${c.toLowerCase()}">${c}</option>`);
    }

    function renderProducts() {
        const filter = searchInput.value.trim().toLowerCase();
        const category = categorySelect.value;
        const filtered = products.filter(p => 
            (category === 'all' || (p.category || '').trim().toLowerCase() === category) &&
            (p.name || '').toLowerCase().includes(filter)
        );
        productContainer.innerHTML = filtered.length ? '' : '<p>Produk tidak ditemukan.</p>';
        filtered.forEach(p => {
            const img = (p.images && p.images[0]) ? p.images[0] : 'https://via.placeholder.com/300';
            productContainer.innerHTML += `
                <div class="product-card" data-id="${p.id}">
                    <div class="card-image-container"><img src="${img}" alt="${p.name}"></div>
                    <div class="card-content">
                        <h3>${p.name}</h3>
                        <p>Rp ${Number(p.price).toLocaleString()}</p>
                        <button class="add-to-cart-card-button" data-id="${p.id}">Tambah ke Keranjang</button>
                    </div>
                </div>`;
        });
    }

    function openProductModal(id) {
        const product = products.find(p => p.id === parseInt(id));
        if (!product) return;
        trackEvent('view', id);
        currentProductImages = product.images?.length ? product.images : ['https://via.placeholder.com/400'];
        currentImageIndex = 0;
        productModal.querySelector('.product-details-content').innerHTML = `
            <div class="product-gallery">
                <div class="main-image-container">
                    <button class="gallery-arrow prev">&lt;</button>
                    <img src="${currentProductImages[0]}" alt="${product.name}" class="main-image">
                    <button class="gallery-arrow next">&gt;</button>
                </div>
                <div class="product-thumbnails"></div>
            </div>
            <div class="product-info">
                <h2>${product.name}</h2>
                <p class="price">Rp ${Number(product.price).toLocaleString()}</p>
                <p class="description">${product.description || 'Deskripsi belum tersedia.'}</p>
                <button class="add-to-cart-card-button" data-id="${product.id}">Tambah ke Keranjang</button>
            </div>`;
        updateGallery(id);
        productModal.style.display = 'block';
    }

    function updateGallery(productId) {
        const mainImg = productModal.querySelector('.main-image');
        const thumbnails = productModal.querySelector('.product-thumbnails');
        mainImg.src = currentProductImages[currentImageIndex];
        thumbnails.innerHTML = currentProductImages.map((img, i) => 
            `<img src="${img}" class="thumbnail-image ${i === currentImageIndex ? 'active' : ''}" data-index="${i}">`).join('');
        productModal.querySelectorAll('.gallery-arrow').forEach(a => a.style.display = currentProductImages.length > 1 ? 'block' : 'none');
    }

    function changeImage(dir, id) {
        currentImageIndex = (currentImageIndex + dir + currentProductImages.length) % currentProductImages.length;
        updateGallery(id);
    }

    function addToCart(id) {
        const product = products.find(p => p.id === parseInt(id));
        if (!product) return;
        trackEvent('cart', id);
        const item = cart.find(i => i.id === product.id);
        if (item) item.quantity++;
        else cart.push({ ...product, quantity: 1 });
        updateCartUI();
        showToast('Produk ditambahkan ke pesanan!');
    }

    function updateCartQuantity(id, change) {
        const itemIndex = cart.findIndex(i => i.id === parseInt(id));
        if (itemIndex === -1) return;
        cart[itemIndex].quantity += change;
        if (cart[itemIndex].quantity <= 0) cart.splice(itemIndex, 1);
        updateCartUI();
    }

    // --- PERBAIKAN: Fungsi untuk memperbarui semua elemen UI keranjang ---
    function updateCartUI() {
        const itemsContainer = document.getElementById('cart-items');
        const modalTotalPriceSpan = document.getElementById('cart-total-price');
        const buttonTotalPriceSpan = cartButton.querySelector('.cart-button-total'); // Total harga di tombol
        const cartCountBadge = cartButton.querySelector('.cart-count-badge'); // Badge jumlah item
        let totalItems = 0, totalPrice = 0;

        itemsContainer.innerHTML = cart.length ? '' : '<p>Pesanan Anda kosong.</p>';
        cart.forEach(item => {
            totalItems += item.quantity;
            totalPrice += item.price * item.quantity;
            const img = (item.images && item.images[0]) ? item.images[0] : 'https://via.placeholder.com/100';
            itemsContainer.innerHTML += `
                <div class="cart-item" data-id="${item.id}">
                    <img src="${img}" class="cart-item-image">
                    <div class="cart-item-details">
                        <p class="cart-item-name">${item.name}</p>
                        <div class="quantity-controls">
                            <button class="quantity-btn decrement-btn">-</button><span>${item.quantity}</span><button class="quantity-btn increment-btn">+</button>
                        </div>
                    </div>
                    <div class="cart-item-subtotal">
                        <p>Rp ${(item.price * item.quantity).toLocaleString()}</p>
                        <button class="remove-item-btn">Hapus</button>
                    </div>
                </div>`;
        });

        const formattedTotalPrice = `Rp ${totalPrice.toLocaleString()}`;
        modalTotalPriceSpan.textContent = formattedTotalPrice;
        buttonTotalPriceSpan.textContent = formattedTotalPrice; // Update total harga di tombol
        cartCountBadge.textContent = totalItems; // Update badge jumlah item

        cartCountBadge.style.display = totalItems > 0 ? 'flex' : 'none';
        cartButton.style.display = cart.length > 0 ? 'flex' : 'none';
    }

    async function handleCheckout() {
        const name = document.getElementById('customer-name').value.trim();
        const address = document.getElementById('customer-address').value.trim();
        const phone = document.getElementById('customer-phone').value.trim();
        const paymentMethod = document.querySelector('input[name="payment-method"]:checked').value;
        const notes = document.getElementById('customer-notes').value.trim();

        if (!name || !address || !phone) {
            alert('Mohon isi Nama, Alamat, dan No. WhatsApp.');
            return;
        }

        let totalPrice = 0;
        const itemsForAPI = cart.map(item => {
            totalPrice += item.price * item.quantity;
            return { id: item.id, name: item.name, quantity: item.quantity, price: item.price };
        });

        const orderData = {
            name, address, phone, notes, paymentMethod,
            items: itemsForAPI,
            total: totalPrice
        };

        try {
            checkoutButton.disabled = true;
            checkoutButton.textContent = 'Memproses...';
            const response = await fetch('api.php?action=save_order', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(orderData)
            });
            const result = await response.json();
            if (!result.success) throw new Error(result.error || 'Gagal menyimpan pesanan.');
            showToast(`Pesanan #${result.order_id} berhasil disimpan!`);
        } catch (error) {
            console.error('Error saat menyimpan pesanan:', error);
            alert('Terjadi kesalahan saat menyimpan pesanan Anda. Silakan coba lagi.');
            checkoutButton.disabled = false;
            checkoutButton.textContent = 'Kirim Pesanan ke WhatsApp';
            return; 
        }

        let message = `Halo Juragan Fiber, saya mau pesan:\n\n`;
        cart.forEach(item => {
            message += `*${item.name}*\n`;
            message += `  ${item.quantity} x Rp ${item.price.toLocaleString()} = Rp ${(item.quantity * item.price).toLocaleString()}\n`;
        });
        message += `\n*Total Pesanan: Rp ${totalPrice.toLocaleString()}*\n`;
        message += `\n*Metode Pembayaran: ${paymentMethod}*\n`;
        message += `\n-- DATA PEMESAN --\n`;
        message += `Nama: ${name}\n`;
        message += `Alamat: ${address}\n`;
        message += `No. HP: ${phone}\n`;
        if (notes) message += `Catatan: ${notes}\n`;
        message += `\nTerima kasih!`;

        window.open(`https://wa.me/${waAdminNumber}?text=${encodeURIComponent(message)}`, '_blank');
        
        cart = [];
        updateCartUI();
        cartModal.style.display = 'none';
        document.getElementById('checkout-form').reset();
        checkoutButton.disabled = false;
        checkoutButton.textContent = 'Kirim Pesanan ke WhatsApp';
    }

    function showToast(message) {
        toastNotification.textContent = message;
        toastNotification.classList.add('show');
        if (toastTimeout) clearTimeout(toastTimeout);
        toastTimeout = setTimeout(() => toastNotification.classList.remove('show'), 4000);
    }

    // --- Event Handlers ---
    checkoutButton.addEventListener('click', handleCheckout);
    productContainer.addEventListener('click', e => {
        const card = e.target.closest('.product-card');
        if (!card) return;
        if (e.target.closest('.add-to-cart-card-button')) { e.stopPropagation(); addToCart(card.dataset.id); }
        else { openProductModal(card.dataset.id); }
    });
    productModal.addEventListener('click', e => {
        const id = productModal.querySelector('.add-to-cart-card-button')?.dataset.id;
        if (e.target.matches('.add-to-cart-card-button')) addToCart(id);
        else if (e.target.matches('.thumbnail-image')) { currentImageIndex = parseInt(e.target.dataset.index); updateGallery(id); }
        else if (e.target.matches('.gallery-arrow.next')) changeImage(1, id);
        else if (e.target.matches('.gallery-arrow.prev')) changeImage(-1, id);
    });
    cartModal.addEventListener('click', e => {
        const id = e.target.closest('.cart-item')?.dataset.id;
        if (!id) return;
        if (e.target.matches('.increment-btn')) updateCartQuantity(id, 1);
        else if (e.target.matches('.decrement-btn')) updateCartQuantity(id, -1);
        else if (e.target.matches('.remove-item-btn')) updateCartQuantity(id, -Infinity);
    });
    cartButton.addEventListener('click', () => cartModal.style.display = 'block');
    closeModalButtons.forEach(b => b.addEventListener('click', () => b.closest('.modal').style.display = 'none'));
    searchInput.addEventListener('input', renderProducts);
    categorySelect.addEventListener('change', renderProducts);

    // --- Initial Load ---
    fetchProducts();
    updateCartUI();
});