const API_KEY = 'API-df9da796f43d1241c36bcd39f85970223850134c';
const BASE_URL_CMS = 'https://www.senatorabadi.web.id/ecommerce_herbal/admin';
const API_URL = BASE_URL_CMS + '/api/content/items/produk?api_key=' + API_KEY;
const kotaBesar = ['Jakarta', 'Semarang', 'Surabaya', 'Bandung'];

let allProducts = [];
let cart = JSON.parse(localStorage.getItem('nadhief_cart')) || [];
let visibleCount = 0;
const rowsPerLoad = 4;
let cur = 0;
let subtotalKeranjang = 0;
let allCitiesData = [];

function getLimit() { return (window.innerWidth >= 600 ? 4 : 2) * rowsPerLoad; }

function showToast(msg) {
    const c = document.getElementById('toast-container');
    if (!c) return;
    const t = document.createElement('div');
    t.className = 'toast';
    t.innerText = msg;
    c.appendChild(t);
    setTimeout(function() { t.remove(); }, 2000);
}

function toggleSearch() {
    const inp = document.getElementById('search-input');
    if (!inp) return;
    inp.classList.toggle('active');
    if (inp.classList.contains('active')) inp.focus();
}

// SLIDER - Hanya aktif di beranda
function initSlider() {
    const slides = document.querySelectorAll('.slide');
    if (slides.length === 0) return;
    const dots = document.getElementById('slider-dots');
    if (dots) {
        dots.innerHTML = Array.from(slides).map(function(_, i) {
            return '<div class="dot" onclick="goTo(' + i + ')"></div>';
        }).join('');
    }
    setInterval(function() { goTo((cur + 1) % slides.length); }, 5000);
}

function goTo(i) {
    cur = i;
    const wrapper = document.getElementById('slider-wrapper');
    if (wrapper) wrapper.style.transform = 'translateX(-' + (i * 100) + '%)';
    document.querySelectorAll('.dot').forEach(function(el, idx) {
        el.classList.toggle('active', idx === i);
    });
}

// KATALOG
function renderProducts(products) {
    const list = document.getElementById('produk-list');
    const btnMore = document.getElementById('load-more-container');
    const loadEl = document.getElementById('loading-products');
    if (loadEl) loadEl.style.display = 'none';
    const sliced = products.slice(0, visibleCount);
    list.innerHTML = '';
    
    if (sliced.length === 0) {
        list.innerHTML = '<p style="grid-column:1/-1; text-align:center; padding:30px;">Produk tidak ditemukan.</p>';
        if (btnMore) btnMore.style.display = 'none';
        return;
    }
    
    sliced.forEach(function(item) {
        const img = item.gambar ? BASE_URL_CMS + '/storage/uploads' + item.gambar.path : 'https://via.placeholder.com/200';
        const harga = Number(item.harga).toLocaleString('id-ID');
        const stok = item.stok !== undefined && item.stok !== null ? parseInt(item.stok) : 'Tersedia';
        const habis = stok !== 'Tersedia' && stok <= 0;
        
        // PERBAIKAN: Hanya mengirim _id produk agar tidak merusak elemen HTML
        const btn = habis 
            ? '<button class="btn-add disabled" disabled>Stok Habis</button>' 
            : '<button class="btn-add" onclick="event.stopPropagation(); addToCart(\'' + item._id + '\')">Beli Sekarang +</button>';
            
        const badge = habis ? '<div class="badge-habis">Stok Habis</div>' : '';
        
        list.innerHTML += '<div class="card">' + badge + 
            '<img src="' + img + '" class="card-img" onclick="showProductDetail(\'' + item._id + '\')">' +
            '<div class="card-body">' +
            '<h3 class="card-title" onclick="showProductDetail(\'' + item._id + '\')">' + item.nama_produk + '</h3>' +
            '<div class="price">Rp ' + harga + '</div>' +
            '<div class="stock-info">Stok: <strong>' + stok + '</strong></div>' +
            btn + '</div></div>';
    });
    
    if (btnMore) btnMore.style.display = products.length > visibleCount ? 'flex' : 'none';
}

function generateFilters() {
    const cats = ['Semua'];
    allProducts.forEach(function(i) {
        if (i.kategori && cats.indexOf(i.kategori) === -1) cats.push(i.kategori);
    });
    const container = document.getElementById('category-filters');
    if (container) {
        container.innerHTML = cats.map(function(c) {
            return '<button class="filter-btn" onclick="filterByCategory(\'' + c + '\', this)">' + c + '</button>';
        }).join('');
    }
}

function filterProducts() {
    const inp = document.getElementById('search-input');
    if (!inp) return;
    const q = inp.value.toLowerCase();
    const filtered = allProducts.filter(function(i) { return i.nama_produk.toLowerCase().indexOf(q) !== -1; });
    visibleCount = getLimit();
    renderProducts(filtered);
}

function loadMore() { visibleCount += getLimit(); renderProducts(allProducts); }

function filterByCategory(cat, btn) {
    document.querySelectorAll('.filter-btn').forEach(function(el) { el.classList.remove('active'); });
    if (btn) btn.classList.add('active');
    const title = document.querySelector('.main-title');
    if (title) title.innerText = (cat === 'Semua' ? 'Katalog Produk' : cat);
    visibleCount = getLimit();
    const filtered = cat === 'Semua' ? allProducts : allProducts.filter(function(i) { return i.kategori === cat; });
    renderProducts(filtered);
}

// KERANJANG
function toggleCart() {
    const modal = document.getElementById('cart-modal');
    const overlay = document.getElementById('cart-overlay');
    if (!modal || !overlay) return;
    const isActive = modal.style.display === 'flex';
    modal.style.display = isActive ? 'none' : 'flex';
    overlay.style.display = isActive ? 'none' : 'block';
    document.body.style.overflow = isActive ? 'auto' : 'hidden';
    if (!isActive) updateCartUI();
}

function updateCartUI() {
    const container = document.getElementById('cart-items');
    const subEl = document.getElementById('cart-subtotal');
    const countEl = document.getElementById('cart-count');
    let total = 0, qty = 0;
    if (!container) return;
    if (cart.length === 0) {
        container.innerHTML = '<p style="text-align:center; color:#999; padding:20px;">Keranjang Kosong.</p>';
        if (subEl) subEl.innerText = 'Rp 0';
        if (countEl) countEl.innerText = '0';
        return;
    }
    container.innerHTML = cart.map(function(item) {
        const img = item.gambar ? BASE_URL_CMS + '/storage/uploads' + item.gambar.path : 'https://via.placeholder.com/40';
        total += item.harga * item.qty;
        qty += item.qty;
        const maxStok = item.stok !== undefined ? parseInt(item.stok) : 999;
        return '<div class="cart-item">' +
            '<img src="' + img + '" class="cart-item-img" alt="' + item.nama_produk + '">' +
            '<div class="cart-item-info"><h4>' + item.nama_produk + '</h4><p>Rp ' + Number(item.harga).toLocaleString('id-ID') + '</p></div>' +
            '<div class="cart-item-actions"><div class="qty-control">' +
            '<button class="qty-btn" onclick="updateCartQty(\'' + item._id + '\', -1)"' + (item.qty <= 1 ? ' disabled' : '') + '>−</button>' +
            '<span style="min-width:20px; text-align:center;">' + item.qty + '</span>' +
            '<button class="qty-btn" onclick="updateCartQty(\'' + item._id + '\', 1)"' + (item.qty >= maxStok ? ' disabled' : '') + '>+</button>' +
            '</div><i class="fas fa-trash-alt" onclick="removeFromCart(\'' + item._id + '\')" style="color:#e74c3c; cursor:pointer; margin-left:5px;"></i></div></div>';
    }).join('');
    if (countEl) countEl.innerText = qty;
    if (subEl) subEl.innerText = 'Rp ' + total.toLocaleString('id-ID');
}

// PERBAIKAN: Fungsi addToCart sekarang menerima ID sebagai parameter
function addToCart(id) {
    // Cari produk dari data global berdasarkan ID
    const p = allProducts.find(function(i) { return i._id === id; });
    if (!p) {
        showToast('Produk tidak ditemukan!');
        return;
    }
    
    const max = p.stok !== undefined ? parseInt(p.stok) : 9999;
    const ex = cart.find(function(i) { return i._id === id; });
    const curQty = ex ? ex.qty : 0;
    
    if (curQty + 1 > max) { showToast('Stok tidak mencukupi!'); return; }
    
    if (ex) {
        ex.qty++; 
    } else {
        cart.push(Object.assign({}, p, {qty: 1}));
    }
    
    saveCart();
    showToast('Ditambahkan ke keranjang!');
}

function removeFromCart(id) { cart = cart.filter(function(i) { return i._id !== id; }); saveCart(); }

window.updateCartQty = function(id, delta) {
    const item = cart.find(function(i) { return i._id === id; });
    if (!item) return;
    const newQty = item.qty + delta;
    const maxStok = item.stok !== undefined ? parseInt(item.stok) : 999;
    if (newQty < 1 || newQty > maxStok) return;
    item.qty = newQty;
    saveCart();
};

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

// CHECKOUT & ONGKIR
function goToCheckoutPage() {
    if (cart.length === 0) { showToast('Keranjang kosong!'); return; }
    toggleCart();
    document.getElementById('home-page').style.display = 'none';
    document.getElementById('detail-page').style.display = 'none';
    document.getElementById('category-page').style.display = 'none';
    document.getElementById('checkout-page').style.display = 'block';
    document.getElementById('home-slider').style.display = 'none';
    window.scrollTo(0, 0);
    renderCheckoutSummary();
    loadKotaSuggestions();
}

function backToHomeFromCheckout() {
    document.getElementById('checkout-page').style.display = 'none';
    document.getElementById('home-page').style.display = 'block';
    document.getElementById('home-slider').style.display = 'block';
    window.scrollTo(0, 0);
}

async function loadKotaSuggestions() {
    try {
        const res = await fetch(BASE_URL_CMS + '/api/content/items/ongkir?api_key=' + API_KEY);
        allCitiesData = await res.json();
    } catch (e) { console.error('Gagal muat kota:', e); }
}

function showDefaultCities() { renderDropdown(kotaBesar); }

function handleKotaInput(val) {
    if (val.length < 1) { showDefaultCities(); return; }
    const filtered = allCitiesData.filter(function(item) { return item.kota.toLowerCase().indexOf(val.toLowerCase()) !== -1; }).map(function(item) { return item.kota; });
    renderDropdown(filtered);
}

function renderDropdown(list) {
    const dd = document.getElementById('kota-dropdown');
    if (!dd) return;
    if (list.length === 0) { dd.style.display = 'none'; return; }
    dd.innerHTML = list.slice(0, 10).map(function(k) {
        return '<div class="dropdown-item" onclick="selectCity(\'' + k.replace(/'/g, "\\'") + '\')">' + k + '</div>';
    }).join('');
    dd.style.display = 'block';
}

function selectCity(nama) {
    document.getElementById('co-kota').value = nama;
    document.getElementById('kota-dropdown').style.display = 'none';
    fetchOngkirFromCockpit(nama);
}

document.addEventListener('click', function(e) {
    const wrap = document.querySelector('.autocomplete-wrapper');
    const dd = document.getElementById('kota-dropdown');
    if (wrap && dd && !wrap.contains(e.target)) dd.style.display = 'none';
});

async function fetchOngkirFromCockpit(kota) {
    const container = document.getElementById('shipping-options-container');
    container.innerHTML = '<p style="text-align:center; padding:10px;"><i class="fas fa-spinner fa-spin"></i> Menghitung ongkir...</p>';
    try {
        const filter = encodeURIComponent(JSON.stringify({kota: kota}));
        const res = await fetch(BASE_URL_CMS + '/api/content/items/ongkir?api_key=' + API_KEY + '&filter=' + filter);
        const result = await res.json();
        if (result && result.length > 0) {
            const hargaJnT = parseInt(result[0].biaya);
            const kurir = [
                { nama: 'J&T (Standard)', harga: hargaJnT, est: '2-3 Hari' },
                { nama: 'JNE (Express)', harga: hargaJnT + 5000, est: '1-2 Hari' },
                { nama: 'Ninja (Economy)', harga: hargaJnT - 3000, est: '4-5 Hari' }
            ];
            container.innerHTML = kurir.map(function(k, i) {
                return '<label style="display:flex; justify-content:space-between; align-items:center; margin-bottom:10px; cursor:pointer;">' +
                    '<span><input type="radio" name="pengiriman" value="' + k.harga + '" data-kurir="' + k.nama + '" onchange="updateGrandTotal()" ' + (i === 0 ? 'checked' : '') + '> ' + k.nama + ' <small style="color:#888;">(' + k.est + ')</small></span>' +
                    '<strong>Rp ' + k.harga.toLocaleString('id-ID') + '</strong></label>';
            }).join('');
            updateGrandTotal();
        } else {
            container.innerHTML = '<p style="color:red; font-size:0.8rem; text-align:center;">Pengiriman ke kota ini belum tersedia.</p>';
        }
    } catch (e) {
        container.innerHTML = '<p style="color:red; font-size:0.8rem; text-align:center;">Gagal mengambil data ongkir.</p>';
    }
}

function renderCheckoutSummary() {
    const container = document.getElementById('co-items-container');
    if (!container) return;
    subtotalKeranjang = 0;
    if (cart.length === 0) {
        container.innerHTML = '<p style="text-align:center; padding:20px; color:#888;">Keranjang kosong.</p>';
        updateGrandTotal();
        return;
    }
    let html = '';
    cart.forEach(function(item) {
        subtotalKeranjang += item.harga * item.qty;
        const img = item.gambar ? BASE_URL_CMS + '/storage/uploads' + item.gambar.path : 'https://via.placeholder.com/60';
        const maxStok = item.stok !== undefined ? parseInt(item.stok) : 999;
        html += '<div class="checkout-item">' +
            '<img src="' + img + '" class="checkout-item-img" alt="' + item.nama_produk + '">' +
            '<div class="checkout-item-info"><h4>' + item.nama_produk + '</h4><span class="checkout-item-price">Rp ' + Number(item.harga).toLocaleString('id-ID') + '</span></div>' +
            '<div class="checkout-item-actions">' +
            '<button class="checkout-qty-btn" onclick="updateCheckoutQty(\'' + item._id + '\', -1)"' + (item.qty <= 1 ? ' disabled' : '') + '>−</button>' +
            '<span style="min-width:24px; text-align:center;">' + item.qty + '</span>' +
            '<button class="checkout-qty-btn" onclick="updateCheckoutQty(\'' + item._id + '\', 1)"' + (item.qty >= maxStok ? ' disabled' : '') + '>+</button>' +
            '<button class="checkout-remove-btn" onclick="removeFromCheckout(\'' + item._id + '\')"><i class="fas fa-trash-alt"></i></button>' +
            '</div></div>';
    });
    container.innerHTML = html;
    updateGrandTotal();
}

window.updateCheckoutQty = function(id, delta) {
    const item = cart.find(function(i) { return i._id === id; });
    if (!item) return;
    const nQ = item.qty + delta;
    const max = item.stok !== undefined ? parseInt(item.stok) : 999;
    if (nQ < 1 || nQ > max) return;
    item.qty = nQ;
    saveCart();
    renderCheckoutSummary();
};

window.removeFromCheckout = function(id) {
    cart = cart.filter(function(i) { return i._id !== id; });
    saveCart();
    renderCheckoutSummary();
    if (cart.length === 0) document.getElementById('co-items-container').innerHTML = '<p style="text-align:center; padding:20px; color:#888;">Keranjang kosong.</p>';
};

function updateGrandTotal() {
    const sel = document.querySelector('input[name="pengiriman"]:checked');
    const ongkir = sel ? parseInt(sel.value) : 0;
    const total = subtotalKeranjang + ongkir;
    const sEl = document.getElementById('co-subtotal');
    const oEl = document.getElementById('co-ongkir-display');
    const gEl = document.getElementById('co-grand-total');
    if (sEl) sEl.innerText = 'Rp ' + subtotalKeranjang.toLocaleString('id-ID');
    if (oEl) oEl.innerText = ongkir > 0 ? 'Rp ' + ongkir.toLocaleString('id-ID') : 'Rp 0';
    if (gEl) gEl.innerText = 'Rp ' + total.toLocaleString('id-ID');
}

async function payAndProcessOrder() {
    const nama = document.getElementById('co-nama').value;
    const wa = document.getElementById('co-wa').value;
    const kota = document.getElementById('co-kota').value;
    const alamat = document.getElementById('co-alamat').value;
    const sel = document.querySelector('input[name="pengiriman"]:checked');
    if (!nama || !wa || !kota || !alamat || !sel) { alert('Lengkapi semua data & pilih kurir!'); return; }
    const btn = document.getElementById('btn-pay-now');
    const orig = btn.innerHTML;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Menghubungkan...';
    btn.disabled = true;
    try {
        const payload = { nama: nama, wa: wa, kota: kota, alamat: alamat, cart: cart, ongkir: parseInt(sel.value), kurir: sel.getAttribute('data-kurir'), subtotal: subtotalKeranjang };
        const res = await fetch('checkout.php', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(payload) });
        const data = await res.json();
        if (data.success && data.invoice_url) {
            cart = [];
            localStorage.removeItem('nadhief_cart');
            window.location.href = data.invoice_url;
        } else {
            alert('Error: ' + (data.message || 'Gagal memproses.'));
        }
    } catch (err) {
        alert('Koneksi gagal: ' + err.message);
    } finally {
        btn.innerHTML = orig;
        btn.disabled = false;
    }
}

// DETAIL & KATEGORI
function showProductDetail(id) {
    const p = allProducts.find(function(i) { return i._id === id; });
    if (!p) return;
    document.getElementById('home-page').style.display = 'none';
    document.getElementById('category-page').style.display = 'none';
    document.getElementById('checkout-page').style.display = 'none';
    document.getElementById('detail-page').style.display = 'block';
    document.getElementById('home-slider').style.display = 'none';
    const bCat = document.getElementById('bread-cat');
    const bName = document.getElementById('bread-name');
    const dCont = document.getElementById('detail-content');
    if (bCat) bCat.innerText = p.kategori || 'Herbal';
    if (bName) bName.innerText = p.nama_produk;
    if (dCont) dCont.innerHTML = getDetailTemplate(p, BASE_URL_CMS);
    window.scrollTo(0, 0);
}

function closeProductDetail() {
    document.getElementById('detail-page').style.display = 'none';
    document.getElementById('category-page').style.display = 'none';
    document.getElementById('checkout-page').style.display = 'none';
    document.getElementById('home-page').style.display = 'block';
    document.getElementById('home-slider').style.display = 'block';
    window.scrollTo(0, 0);
}

function showCategoryPage(cat) {
    document.getElementById('home-page').style.display = 'none';
    document.getElementById('detail-page').style.display = 'none';
    document.getElementById('checkout-page').style.display = 'none';
    document.getElementById('category-page').style.display = 'block';
    document.getElementById('home-slider').style.display = 'none';
    const n = document.getElementById('cat-page-name');
    const t = document.getElementById('cat-page-title');
    if (n) n.innerText = cat;
    if (t) t.innerText = cat;
    renderCategoryProducts(cat);
    window.scrollTo(0, 0);
}

// PERBAIKAN: Juga di halaman kategori, tombol memanggil _id
function renderCategoryProducts(cat) {
    const list = document.getElementById('category-produk-list');
    const filtered = allProducts.filter(function(p) { return p.kategori === cat; });
    list.innerHTML = '';
    
    filtered.forEach(function(item) {
        const img = item.gambar ? BASE_URL_CMS + '/storage/uploads' + item.gambar.path : 'https://via.placeholder.com/200';
        const harga = Number(item.harga).toLocaleString('id-ID');
        const stok = item.stok !== undefined ? parseInt(item.stok) : 'Tersedia';
        const habis = stok !== 'Tersedia' && stok <= 0;
        
        const badge = habis ? '<div class="badge-habis">Stok Habis</div>' : '';
        const btn = habis 
            ? '<button class="btn-add disabled" disabled>Stok Habis</button>' 
            : '<button class="btn-add" onclick="event.stopPropagation(); addToCart(\'' + item._id + '\')">Beli Sekarang +</button>';
            
        list.innerHTML += '<div class="card">' + badge + 
            '<img src="' + img + '" class="card-img" onclick="showProductDetail(\'' + item._id + '\')">' +
            '<div class="card-body"><h3 class="card-title" onclick="showProductDetail(\'' + item._id + '\')">' + item.nama_produk + '</h3>' +
            '<div class="price">Rp ' + harga + '</div><div class="stock-info">Stok: <strong>' + stok + '</strong></div>' + 
            btn + '</div></div>';
    });
}

// FETCH & INIT
async function fetchProducts() {
    try {
        initSlider();
        const res = await fetch(API_URL);
        const data = await res.json();
        allProducts = data.sort(function(a, b) { return a.nama_produk.localeCompare(b.nama_produk); });
        visibleCount = getLimit();
        renderProducts(allProducts);
        generateFilters();
        updateCartUI();
    } catch (e) {
        console.error(e);
        const loadEl = document.getElementById('loading-products');
        if (loadEl) loadEl.innerHTML = '<p style="text-align:center; color:red;">Gagal memuat produk.</p>';
    }
}
fetchProducts();