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 currentPage = 1;
let totalPages = 1;
let curSlide = 0;
let subtotalKeranjang = 0;
let allCitiesData = [];
let currentUser = JSON.parse(localStorage.getItem('nadhief_user')) || null;
let currentCategory = 'Semua';
let searchQuery = '';
let debounceTimer;

const CACHE_KEY = 'nadhief_products_cache';
const CACHE_EXPIRY = 5 * 60 * 1000;

const limitPerPage = () => window.innerWidth >= 600 ? 8 : 4;

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(() => 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 ==========
async function initSlider() {
    try {
        const res = await fetch(BASE_URL_CMS + '/api/content/items/banner_promo?api_key=' + API_KEY + '&filter[aktif]=true');
        const banners = await res.json();
        const wrapper = document.getElementById('slider-wrapper');
        const dots = document.getElementById('slider-dots');
        if (banners && banners.length > 0) {
            wrapper.innerHTML = banners.map(b => `
                <div class="slide"><a href="${b.link_tujuan || '#'}"><img src="${BASE_URL_CMS}/storage/uploads${b.gambar.path}" alt="${b.judul}" loading="lazy"></a></div>
            `).join('');
        } else {
            wrapper.innerHTML = `
                <div class="slide"><img src="https://www.senatorabadi.web.id/ecommerce_herbal/admin/assets/link/455a09d53532646a220001f7" alt="Promo 1" loading="lazy"></div>
                <div class="slide"><img src="https://www.senatorabadi.web.id/ecommerce_herbal/admin/assets/link/455a09cf666566d1c90000a6" alt="Promo 2" loading="lazy"></div>
            `;
        }
        const slides = document.querySelectorAll('.slide');
        dots.innerHTML = Array.from(slides).map((_, i) => `<div class="dot" onclick="goToSlide(${i})"></div>`).join('');
        setInterval(() => goToSlide((curSlide + 1) % slides.length), 5000);
    } catch (e) {
        console.warn('Slider fallback');
    }
}

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

// ========== SKELETON ==========
function renderSkeleton(count) {
    const list = document.getElementById('produk-list');
    list.innerHTML = '';
    for (let i = 0; i < count; i++) {
        list.innerHTML += `
            <div class="skeleton-card">
                <div class="skeleton-img"></div>
                <div class="skeleton-body">
                    <div class="skeleton-title"></div>
                    <div class="skeleton-price"></div>
                    <div class="skeleton-stock"></div>
                    <div class="skeleton-btn"></div>
                </div>
            </div>
        `;
    }
}

// ========== CACHE ==========
function getCachedProducts() {
    const cached = localStorage.getItem(CACHE_KEY);
    if (!cached) return null;
    try {
        const data = JSON.parse(cached);
        if (Date.now() - data.timestamp < CACHE_EXPIRY) return data.products;
    } catch (e) {}
    return null;
}

function setCachedProducts(products) {
    localStorage.setItem(CACHE_KEY, JSON.stringify({ timestamp: Date.now(), products }));
}

// ========== FETCH PRODUK (DIPERBAIKI) ==========
async function fetchProducts(page = 1, category = 'Semua', search = '') {
    renderSkeleton(limitPerPage());

    if (category === 'Semua' && search === '' && page === 1) {
        const cached = getCachedProducts();
        if (cached && cached.length > 0) {
            allProducts = cached;
            totalPages = Math.ceil(allProducts.length / limitPerPage());
            renderProductsPage(page);
            generateFilters();
            return;
        }
    }

    try {
        let url = API_URL;

        if (category !== 'Semua') {
            url += `&filter[kategori]=${encodeURIComponent(category)}`;
        }

        if (search) {
            const searchFilter = { nama_produk: { '$regex': search, '$options': 'i' } };
            url += `&filter=${encodeURIComponent(JSON.stringify(searchFilter))}`;
        }

        const skip = (page - 1) * limitPerPage();
        url += `&limit=${limitPerPage()}&skip=${skip}`;
        
        // Sort dalam format JSON string (PERBAIKAN)
        const sortObj = { _created: -1 };
        url += `&sort=${encodeURIComponent(JSON.stringify(sortObj))}`;

        console.log('Fetch URL:', url);

        const response = await fetch(url);
        if (!response.ok) throw new Error(`HTTP ${response.status}`);
        const products = await response.json();
        console.log('Products received:', products);

        let totalItems = 0;
        try {
            let countUrl = BASE_URL_CMS + '/api/content/items/produk?api_key=' + API_KEY + '&count=true';
            if (category !== 'Semua') countUrl += `&filter[kategori]=${encodeURIComponent(category)}`;
            if (search) {
                const searchFilter = { nama_produk: { '$regex': search, '$options': 'i' } };
                countUrl += `&filter=${encodeURIComponent(JSON.stringify(searchFilter))}`;
            }
            const countRes = await fetch(countUrl);
            const countData = await countRes.json();
            totalItems = countData.count || 0;
        } catch (e) {
            totalItems = products.length === limitPerPage() ? (page * limitPerPage() + 1) : ((page - 1) * limitPerPage() + products.length);
        }
        totalPages = Math.ceil(totalItems / limitPerPage()) || 1;
        console.log(`Total items: ${totalItems}, Total pages: ${totalPages}`);

        if (category === 'Semua' && search === '' && page === 1) {
            try {
                const allRes = await fetch(API_URL + '&limit=100&sort=' + encodeURIComponent(JSON.stringify({ _created: -1 })));
                allProducts = await allRes.json();
                setCachedProducts(allProducts);
                console.log('All products loaded for filters:', allProducts.length);
            } catch (e) {
                allProducts = products;
            }
            generateFilters();
        }

        renderProducts(products);
        renderPagination();
    } catch (error) {
        console.error('Fetch error:', error);
        document.getElementById('produk-list').innerHTML =
            '<p style="grid-column:1/-1; text-align:center; padding:30px; color:red;">Gagal memuat produk. Silakan refresh halaman.</p>';
        document.getElementById('pagination-container').innerHTML = '';
    }
}

function renderProductsPage(page) {
    const start = (page - 1) * limitPerPage();
    const products = allProducts.slice(start, start + limitPerPage());
    renderProducts(products);
    renderPagination();
}

function renderProducts(products) {
    const list = document.getElementById('produk-list');
    if (!products || products.length === 0) {
        list.innerHTML = '<p style="grid-column:1/-1; text-align:center; padding:30px;">Produk tidak ditemukan.</p>';
        document.getElementById('pagination-container').innerHTML = '';
        return;
    }
    list.innerHTML = products.map(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 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>' : '';
        return `<div class="card">${badge}<img src="${img}" class="card-img" onclick="showProductDetail('${item._id}')" alt="${item.nama_produk}" loading="lazy"><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>`;
    }).join('');
}

function renderPagination() {
    const container = document.getElementById('pagination-container');
    if (totalPages <= 1) { container.innerHTML = ''; return; }
    let html = `<button class="pagination-btn" onclick="goToPage(${currentPage - 1})" ${currentPage === 1 ? 'disabled' : ''}><i class="fas fa-chevron-left"></i></button>`;
    const maxVisible = 5;
    let startPage = Math.max(1, currentPage - Math.floor(maxVisible / 2));
    let endPage = Math.min(totalPages, startPage + maxVisible - 1);
    if (endPage - startPage < maxVisible - 1) startPage = Math.max(1, endPage - maxVisible + 1);
    for (let i = startPage; i <= endPage; i++) html += `<button class="pagination-btn ${i === currentPage ? 'active' : ''}" onclick="goToPage(${i})">${i}</button>`;
    html += `<button class="pagination-btn" onclick="goToPage(${currentPage + 1})" ${currentPage === totalPages ? 'disabled' : ''}><i class="fas fa-chevron-right"></i></button>`;
    container.innerHTML = html;
}

function goToPage(page) {
    if (page < 1 || page > totalPages) return;
    currentPage = page;
    if (allProducts.length && currentCategory === 'Semua' && searchQuery === '') renderProductsPage(page);
    else fetchProducts(currentPage, currentCategory, searchQuery);
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

function generateFilters() {
    const cats = ['Semua'];
    allProducts.forEach(i => { if (i.kategori && !cats.includes(i.kategori)) cats.push(i.kategori); });
    const container = document.getElementById('category-filters');
    if (container) container.innerHTML = cats.map(c => `<button class="filter-btn ${c === currentCategory ? 'active' : ''}" onclick="filterByCategory('${c}', this)">${c}</button>`).join('');
}

function filterByCategory(cat, btn) {
    document.querySelectorAll('.filter-btn').forEach(el => el.classList.remove('active'));
    if (btn) btn.classList.add('active');
    currentCategory = cat;
    currentPage = 1;
    document.querySelector('.main-title').innerText = cat === 'Semua' ? 'Katalog Produk' : cat;
    fetchProducts(currentPage, currentCategory, searchQuery);
}

function debouncedFilterProducts() {
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(() => {
        searchQuery = document.getElementById('search-input').value.trim();
        currentPage = 1;
        fetchProducts(currentPage, currentCategory, searchQuery);
    }, 500);
}

// ========== KERANJANG ==========
function toggleCart() {
    const modal = document.getElementById('cart-modal');
    const overlay = document.getElementById('cart-overlay');
    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 modal = document.getElementById('cart-modal');
    const countEl = document.getElementById('cart-count');
    let total = 0, qty = 0;
    if (cart.length === 0) {
        modal.innerHTML = `<div class="section-header"><i class="fas fa-shopping-cart"></i><h3>Keranjang Belanja</h3><i class="fas fa-times" style="margin-left:auto; cursor:pointer;" onclick="toggleCart()"></i></div><div class="cart-items-container"><p style="text-align:center; color:#999; padding:20px;">Keranjang Kosong.</p></div><div class="checkout-totals"><div class="total-line grand"><span>Total Estimasi:</span><span id="cart-subtotal">Rp 0</span></div></div><button class="btn-pay" onclick="goToCheckoutPage()">Lanjut ke Checkout</button>`;
        countEl.innerText = '0';
        return;
    }
    let itemsHtml = '';
    cart.forEach(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;
        itemsHtml += `<div class="cart-item"><img src="${img}" class="cart-item-img"><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;"></i></div></div>`;
    });
    modal.innerHTML = `<div class="section-header"><i class="fas fa-shopping-cart"></i><h3>Keranjang Belanja</h3><i class="fas fa-times" style="margin-left:auto; cursor:pointer;" onclick="toggleCart()"></i></div><div class="cart-items-container">${itemsHtml}</div><div class="checkout-totals"><div class="total-line grand"><span>Total Estimasi:</span><span id="cart-subtotal">Rp ${total.toLocaleString('id-ID')}</span></div></div><button class="btn-pay" onclick="goToCheckoutPage()">Lanjut ke Checkout</button>`;
    countEl.innerText = qty;
}

function addToCart(id) {
    const p = allProducts.find(i => i._id === id);
    if (!p) { showToast('Produk tidak ditemukan!'); return; }
    const max = p.stok !== undefined ? parseInt(p.stok) : 9999;
    const ex = cart.find(i => i._id === id);
    if ((ex ? ex.qty : 0) + 1 > max) { showToast('Stok tidak mencukupi!'); return; }
    ex ? ex.qty++ : cart.push({...p, qty: 1});
    saveCart(); showToast('Ditambahkan ke keranjang!');
}

function removeFromCart(id) { cart = cart.filter(i => i._id !== id); saveCart(); }
window.updateCartQty = function(id, delta) {
    const item = cart.find(i => i._id === id);
    if (!item) return;
    const nQ = item.qty + delta;
    if (nQ < 1 || nQ > (item.stok || 999)) return;
    item.qty = nQ;
    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('orders-page').style.display = 'none';
    document.getElementById('checkout-page').style.display = 'block';
    document.getElementById('home-slider').style.display = 'none';
    renderCheckoutSummary(); loadKotaSuggestions();
    if (currentUser) prefillCheckoutForm();
}
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) {} }
function handleKotaInput(val) { renderDropdown(val.length < 1 ? kotaBesar : allCitiesData.filter(i => i.kota.toLowerCase().includes(val.toLowerCase())).map(i => i.kota)); }
function renderDropdown(list) {
    const dd = document.getElementById('kota-dropdown');
    if (!dd) return;
    if (!list.length) { dd.style.display = 'none'; return; }
    dd.innerHTML = list.slice(0,10).map(k => `<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); }
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}));
        const res = await fetch(BASE_URL_CMS + '/api/content/items/ongkir?api_key=' + API_KEY + '&filter=' + filter);
        const result = await res.json();
        if (result?.length) {
            const harga = parseInt(result[0].biaya);
            const kurir = [{ nama: 'J&T (Standard)', harga, est: '2-3 Hari' }, { nama: 'JNE (Express)', harga: harga+5000, est: '1-2 Hari' }, { nama: 'Ninja (Economy)', harga: harga-3000, est: '4-5 Hari' }];
            container.innerHTML = kurir.map((k,i) => `<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;">Pengiriman ke kota ini belum tersedia.</p>';
    } catch (e) { container.innerHTML = '<p style="color:red;">Gagal mengambil data ongkir.</p>'; }
}
function renderCheckoutSummary() {
    const container = document.getElementById('co-items-container');
    subtotalKeranjang = 0;
    if (!cart.length) { container.innerHTML = '<p style="text-align:center;">Keranjang kosong.</p>'; updateGrandTotal(); return; }
    let html = '';
    cart.forEach(item => {
        subtotalKeranjang += item.harga * item.qty;
        const img = item.gambar ? BASE_URL_CMS + '/storage/uploads' + item.gambar.path : 'https://via.placeholder.com/60';
        html += `<div class="checkout-item"><img src="${img}" class="checkout-item-img"><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;">${item.qty}</span><button class="checkout-qty-btn" onclick="updateCheckoutQty('${item._id}', 1)" ${item.qty>=(item.stok||999)?'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(i => i._id === id); if (!item) return; const nQ = item.qty + delta; if (nQ<1 || nQ>(item.stok||999)) return; item.qty = nQ; saveCart(); renderCheckoutSummary(); };
window.removeFromCheckout = function(id) { cart = cart.filter(i => i._id !== id); saveCart(); renderCheckoutSummary(); };
function updateGrandTotal() {
    const sel = document.querySelector('input[name="pengiriman"]:checked');
    const ongkir = sel ? parseInt(sel.value) : 0;
    const total = subtotalKeranjang + ongkir;
    document.getElementById('co-subtotal').innerText = 'Rp ' + subtotalKeranjang.toLocaleString('id-ID');
    document.getElementById('co-ongkir-display').innerText = ongkir ? 'Rp ' + ongkir.toLocaleString('id-ID') : 'Rp 0';
    document.getElementById('co-grand-total').innerText = 'Rp ' + total.toLocaleString('id-ID');
}
async function payAndProcessOrder() {
    const nama = document.getElementById('co-nama').value, wa = document.getElementById('co-wa').value, kota = document.getElementById('co-kota').value, alamat = document.getElementById('co-alamat').value;
    const sel = document.querySelector('input[name="pengiriman"]:checked');
    if (!nama || !wa || !kota || !alamat || !sel) { alert('Lengkapi data!'); return; }
    const btn = document.getElementById('btn-pay-now');
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Menghubungkan...';
    btn.disabled = true;
    try {
        const payload = { nama, wa, kota, alamat, cart, ongkir: parseInt(sel.value), kurir: sel.dataset.kurir, subtotal: subtotalKeranjang };
        const res = await fetch('api/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.'); }
    finally { btn.innerHTML = '<i class="fas fa-credit-card"></i> Bayar Sekarang'; btn.disabled = false; }
}

// ========== USER ==========
function toggleUserModal() {
    const modal = document.getElementById('user-modal'), overlay = document.getElementById('user-overlay');
    const isActive = modal.style.display === 'flex';
    if (!isActive) { renderUserModal(); modal.style.display = 'flex'; overlay.style.display = 'block'; document.body.style.overflow = 'hidden'; }
    else { modal.style.display = 'none'; overlay.style.display = 'none'; document.body.style.overflow = 'auto'; }
}
function renderUserModal() {
    const modal = document.getElementById('user-modal');
    if (currentUser) modal.innerHTML = `<div class="modal-header"><h3>Akun Saya</h3><i class="fas fa-times" onclick="toggleUserModal()" style="cursor:pointer;"></i></div><div class="user-profile-info"><p><i class="fas fa-user-circle"></i> ${currentUser.nama_lengkap}</p><p><i class="fab fa-whatsapp"></i> ${currentUser.no_whatsapp}</p><button class="btn-user-action" onclick="goToUserOrders()">📋 Riwayat Pesanan</button><button class="btn-user-action" style="background:#e74c3c;" onclick="logoutUser()">Keluar</button></div>`;
    else modal.innerHTML = `<div class="modal-header"><h3>Masuk / Daftar</h3><i class="fas fa-times" onclick="toggleUserModal()" style="cursor:pointer;"></i></div><div id="login-step-1"><div class="user-form-group"><label>Nomor WhatsApp</label><input type="tel" id="login-wa" placeholder="08123456789"></div><button class="btn-user-action" onclick="checkUserExists()">Lanjutkan</button><div class="user-modal-footer">Belum punya akun? <a onclick="showRegisterForm()">Daftar</a></div></div><div id="register-form" style="display:none;"><div class="user-form-group"><label>Nama Lengkap</label><input type="text" id="reg-nama"></div><div class="user-form-group"><label>WhatsApp</label><input type="tel" id="reg-wa"></div><div class="user-form-group"><label>Alamat</label><textarea id="reg-alamat" rows="2"></textarea></div><button class="btn-user-action" onclick="registerUser()">Daftar</button><div class="user-modal-footer"><a onclick="showLoginForm()">Masuk</a></div></div>`;
}
function showRegisterForm() { document.getElementById('login-step-1').style.display = 'none'; document.getElementById('register-form').style.display = 'block'; }
function showLoginForm() { document.getElementById('register-form').style.display = 'none'; document.getElementById('login-step-1').style.display = 'block'; }
async function checkUserExists() {
    const wa = document.getElementById('login-wa').value.trim();
    if (!wa) { showToast('Masukkan nomor WA'); return; }
    const filter = encodeURIComponent(JSON.stringify({ no_whatsapp: wa }));
    const res = await fetch(`${BASE_URL_CMS}/api/content/items/pelanggan?api_key=${API_KEY}&filter=${filter}`);
    const data = await res.json();
    if (data.length) loginSuccess(data[0]);
    else { showRegisterForm(); document.getElementById('reg-wa').value = wa; }
}
async function registerUser() {
    const nama = document.getElementById('reg-nama').value.trim(), wa = document.getElementById('reg-wa').value.trim(), alamat = document.getElementById('reg-alamat').value.trim();
    if (!nama || !wa) { showToast('Nama dan WA wajib'); return; }
    const payload = { data: { nama_lengkap: nama, no_whatsapp: wa, alamat_lengkap: alamat, status: 'aktif', tanggal_daftar: new Date().toISOString() } };
    const res = await fetch(`${BASE_URL_CMS}/api/content/item/pelanggan?api_key=${API_KEY}`, { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(payload) });
    const result = await res.json();
    if (result._id) loginSuccess({ _id: result._id, nama_lengkap: nama, no_whatsapp: wa, alamat_lengkap: alamat });
    else showToast('Gagal daftar');
}
function loginSuccess(user) { currentUser = user; localStorage.setItem('nadhief_user', JSON.stringify(user)); toggleUserModal(); showToast(`Selamat datang, ${user.nama_lengkap}!`); updateUserUI(); }
function logoutUser() { currentUser = null; localStorage.removeItem('nadhief_user'); toggleUserModal(); showToast('Anda telah keluar'); updateUserUI(); }
function updateUserUI() { const icon = document.querySelector('.user-icon-btn i'); if (currentUser) { icon.style.color = 'var(--primary)'; icon.classList.remove('fa-user'); icon.classList.add('fa-user-check'); } else { icon.style.color = ''; icon.classList.remove('fa-user-check'); icon.classList.add('fa-user'); } }
function prefillCheckoutForm() { if (currentUser) { document.getElementById('co-nama').value = currentUser.nama_lengkap || ''; document.getElementById('co-wa').value = currentUser.no_whatsapp || ''; if (currentUser.alamat_lengkap) document.getElementById('co-alamat').value = currentUser.alamat_lengkap; } }
function goToUserOrders() { toggleUserModal(); document.querySelectorAll('.page').forEach(p => p.style.display = 'none'); document.getElementById('orders-page').style.display = 'block'; document.getElementById('home-slider').style.display = 'none'; loadUserOrders(); }
async function loadUserOrders() {
    const container = document.getElementById('orders-list');
    if (!currentUser) return;
    const filter = encodeURIComponent(JSON.stringify({ no_whatsapp: currentUser.no_whatsapp }));
    const res = await fetch(`${BASE_URL_CMS}/api/content/items/pesanan?api_key=${API_KEY}&filter=${filter}&sort=${encodeURIComponent(JSON.stringify({ _created: -1 }))}`);
    const orders = await res.json();
    container.innerHTML = orders.length ? orders.map(o => `<div class="order-card"><div class="order-header"><span>📅 ${o.tanggal||'-'}</span><span class="order-status ${o.status_pembayaran||'pending'}">${o.status_pembayaran||'pending'}</span></div><div class="order-body"><p><strong>Total:</strong> Rp ${Number(o.total_harga).toLocaleString('id-ID')}</p><p><strong>Kurir:</strong> ${o.kurir||'-'}</p><p><strong>Resi:</strong> ${o.resi_pengiriman||'Belum tersedia'}</p>${o.invoice_url?`<a href="${o.invoice_url}" target="_blank" class="btn-order-detail">Lihat Invoice</a>`:''}</div></div>`).join('') : '<p style="text-align:center;">Belum ada pesanan.</p>';
}

// ========== NAVIGASI & DETAIL ==========
function closeAllPages() {
    document.querySelectorAll('.page').forEach(p => p.style.display = 'none');
    document.getElementById('home-page').style.display = 'block';
    document.getElementById('home-slider').style.display = 'block';
}
function showProductDetail(id) {
    const p = allProducts.find(i => i._id === id);
    if (!p) return;
    closeAllPages();
    document.getElementById('home-page').style.display = 'none';
    document.getElementById('home-slider').style.display = 'none';
    document.getElementById('detail-page').style.display = 'block';
    document.getElementById('bread-cat').innerText = p.kategori || 'Herbal';
    document.getElementById('bread-name').innerText = p.nama_produk;
    document.getElementById('detail-content').innerHTML = getDetailTemplate(p, BASE_URL_CMS);
}
function showCategoryPage(cat) {
    closeAllPages();
    document.getElementById('home-page').style.display = 'none';
    document.getElementById('category-page').style.display = 'block';
    document.getElementById('cat-page-name').innerText = cat;
    document.getElementById('cat-page-title').innerText = cat;
    const filtered = allProducts.filter(p => p.kategori === cat);
    const list = document.getElementById('category-produk-list');
    list.innerHTML = filtered.map(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 btn = habis ? '<button class="btn-add disabled" disabled>Stok Habis</button>' : `<button class="btn-add" onclick="event.stopPropagation(); addToCart('${item._id}')">Beli Sekarang +</button>`;
        return `<div class="card">${habis?'<div class="badge-habis">Stok Habis</div>':''}<img src="${img}" class="card-img" onclick="showProductDetail('${item._id}')" loading="lazy"><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>`;
    }).join('');
}

// ========== INIT ==========
async function init() {
    initSlider();
    await fetchProducts(1);
    updateCartUI();
    updateUserUI();
}
document.addEventListener('DOMContentLoaded', init);
document.addEventListener('click', e => { if (!e.target.closest('.autocomplete-wrapper')) document.getElementById('kota-dropdown').style.display = 'none'; });