document.addEventListener('DOMContentLoaded', async () => {

    // ── Authentication & Modal Management ────────────────────────────────────
    let currentCustomer = null;

    window.openAuthModal = function(tab = 'login') {
        const modal = document.getElementById('authModal');
        const overlay = document.getElementById('authModalOverlay');
        if (modal && overlay) {
            modal.classList.add('open');
            overlay.classList.add('open');
            window.switchAuthTab(tab);
        }
    };

    window.closeAuthModal = function() {
        const modal = document.getElementById('authModal');
        const overlay = document.getElementById('authModalOverlay');
        if (modal && overlay) {
            modal.classList.remove('open');
            overlay.classList.remove('open');
        }
    };

    window.switchAuthTab = function(tab) {
        const tabLoginBtn = document.getElementById('tabLoginBtn');
        const tabRegisterBtn = document.getElementById('tabRegisterBtn');
        const loginForm = document.getElementById('loginForm');
        const registerForm = document.getElementById('registerForm');
        
        if (tab === 'login') {
            tabLoginBtn?.classList.add('active');
            tabRegisterBtn?.classList.remove('active');
            loginForm?.style.setProperty('display', 'block');
            registerForm?.style.setProperty('display', 'none');
        } else {
            tabLoginBtn?.classList.remove('active');
            tabRegisterBtn?.classList.add('active');
            loginForm?.style.setProperty('display', 'none');
            registerForm?.style.setProperty('display', 'block');
        }
    };

    function updateAuthUI(customer) {
        currentCustomer = customer;
        
        const btnNavbarLogin = document.getElementById('btnNavbarLogin');
        const navUserProfile = document.getElementById('navUserProfile');
        const navbarUserAvatar = document.getElementById('navbarUserAvatar');
        const dropdownUserTitle = document.getElementById('dropdownUserTitle');
        const dropdownUserEmail = document.getElementById('dropdownUserEmail');
        
        // Mobile UI Elements
        const btnMobileLogin = document.getElementById('btnMobileLogin');
        const btnMobileLogout = document.getElementById('btnMobileLogout');
        const mobileUserProfile = document.getElementById('mobileUserProfile');
        const mobileUserAvatar = document.getElementById('mobileUserAvatar');
        const mobileUserName = document.getElementById('mobileUserName');
        const mobileUserEmail = document.getElementById('mobileUserEmail');

        if (customer) {
            // Logged in Desktop
            if (btnNavbarLogin) btnNavbarLogin.style.display = 'none';
            if (navUserProfile) navUserProfile.style.display = 'flex';
            if (navbarUserAvatar) navbarUserAvatar.textContent = customer.initials || customer.name[0].toUpperCase();
            if (dropdownUserTitle) dropdownUserTitle.textContent = customer.name;
            if (dropdownUserEmail) dropdownUserEmail.textContent = customer.email;
            
            // Logged in Mobile
            if (btnMobileLogin) btnMobileLogin.style.display = 'none';
            if (btnMobileLogout) btnMobileLogout.style.display = 'flex';
            if (mobileUserProfile) mobileUserProfile.style.display = 'block';
            if (mobileUserAvatar) mobileUserAvatar.textContent = customer.initials || customer.name[0].toUpperCase();
            if (mobileUserName) mobileUserName.textContent = customer.name;
            if (mobileUserEmail) mobileUserEmail.textContent = customer.email;
        } else {
            // Logged out Desktop
            if (btnNavbarLogin) btnNavbarLogin.style.display = 'flex';
            if (navUserProfile) navUserProfile.style.display = 'none';
            
            // Logged out Mobile
            if (btnMobileLogin) btnMobileLogin.style.display = 'flex';
            if (btnMobileLogout) btnMobileLogout.style.display = 'none';
            if (mobileUserProfile) mobileUserProfile.style.display = 'none';
        }
    }

    function showLoginRequiredAlert() {
        if (window.Swal) {
            Swal.fire({
                title: 'Akses Terbatas',
                text: 'Silakan masuk atau daftar akun terlebih dahulu untuk bertransaksi.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Masuk / Daftar',
                cancelButtonText: 'Batal',
                background: '#1E293B',
                color: '#F8FAFC',
                confirmButtonColor: '#FF3385'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.openAuthModal('login');
                }
            });
        } else {
            if (confirm('Silakan masuk atau daftar akun terlebih dahulu untuk bertransaksi. Buka halaman masuk?')) {
                window.openAuthModal('login');
            }
        }
    }

    // Check customer session on load
    async function initAuth() {
        const token = localStorage.getItem('bilinggo_customer_token');
        if (token) {
            try {
                const customer = await BilinggoDataStore.verifyCustomerToken(token);
                if (customer) {
                    updateAuthUI(customer);
                } else {
                    localStorage.removeItem('bilinggo_customer_token');
                    updateAuthUI(null);
                }
            } catch (e) {
                console.error('Session verify failed', e);
                localStorage.removeItem('bilinggo_customer_token');
                updateAuthUI(null);
            }
        } else {
            updateAuthUI(null);
        }
    }

    // Setup Auth Event Listeners
    const btnNavbarLogin = document.getElementById('btnNavbarLogin');
    if (btnNavbarLogin) {
        btnNavbarLogin.addEventListener('click', () => window.openAuthModal('login'));
    }

    const btnCloseAuthModal = document.getElementById('btnCloseAuthModal');
    const authModalOverlay = document.getElementById('authModalOverlay');
    if (btnCloseAuthModal) btnCloseAuthModal.addEventListener('click', () => window.closeAuthModal());
    if (authModalOverlay) authModalOverlay.addEventListener('click', () => window.closeAuthModal());

    // Avatar Dropdown Toggle
    const navbarUserAvatar = document.getElementById('navbarUserAvatar');
    const userDropdownMenu = document.getElementById('userDropdownMenu');
    if (navbarUserAvatar && userDropdownMenu) {
        navbarUserAvatar.addEventListener('click', (e) => {
            e.stopPropagation();
            userDropdownMenu.classList.toggle('open');
        });
        document.addEventListener('click', () => {
            userDropdownMenu.classList.remove('open');
        });
    }

    // Form Submissions
    const loginForm = document.getElementById('loginForm');
    if (loginForm) {
        loginForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            const email = document.getElementById('login-email').value;
            const password = document.getElementById('login-password').value;
            
            if (window.Swal) Swal.showLoading();
            
            const res = await BilinggoDataStore.loginCustomer(email, password);
            if (res.success) {
                localStorage.setItem('bilinggo_customer_token', res.token);
                updateAuthUI(res.customer);
                window.closeAuthModal();
                loginForm.reset();
                if (window.Swal) Swal.fire({ title: 'Berhasil!', text: res.message, icon: 'success', background: '#1E293B', color: '#F8FAFC' });
            } else {
                if (window.Swal) Swal.fire({ title: 'Gagal!', text: res.message || 'Login gagal.', icon: 'error', background: '#1E293B', color: '#F8FAFC' });
                else alert(res.message || 'Login gagal.');
            }
        });
    }

    const registerForm = document.getElementById('registerForm');
    if (registerForm) {
        registerForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            const name = document.getElementById('reg-name').value;
            const email = document.getElementById('reg-email').value;
            const phone = document.getElementById('reg-phone').value;
            const password = document.getElementById('reg-password').value;
            const confirm = document.getElementById('reg-confirm-password').value;
            
            if (password !== confirm) {
                if (window.Swal) Swal.fire({ title: 'Peringatan!', text: 'Konfirmasi password tidak cocok.', icon: 'warning', background: '#1E293B', color: '#F8FAFC' });
                else alert('Konfirmasi password tidak cocok.');
                return;
            }

            if (window.Swal) Swal.showLoading();
            
            const res = await BilinggoDataStore.registerCustomer(name, email, phone, password, confirm);
            if (res.success) {
                localStorage.setItem('bilinggo_customer_token', res.token);
                updateAuthUI(res.customer);
                window.closeAuthModal();
                registerForm.reset();
                if (window.Swal) Swal.fire({ title: 'Berhasil!', text: res.message, icon: 'success', background: '#1E293B', color: '#F8FAFC' });
            } else {
                if (window.Swal) Swal.fire({ title: 'Gagal!', text: res.message || 'Registrasi gagal.', icon: 'error', background: '#1E293B', color: '#F8FAFC' });
                else alert(res.message || 'Registrasi gagal.');
            }
        });
    }

    // Logout Function
    const handleLogout = async () => {
        if (window.Swal) Swal.showLoading();
        const token = localStorage.getItem('bilinggo_customer_token');
        if (token) {
            try {
                // Call logout API
                const url = new URL(`${window.location.origin}/api/auth.php`);
                url.searchParams.set('action', 'logout');
                await fetch(url.toString(), {
                    method: 'GET',
                    headers: { 'Authorization': `Bearer ${token}` }
                });
            } catch(e) {}
        }
        localStorage.removeItem('bilinggo_customer_token');
        updateAuthUI(null);
        if (window.Swal) Swal.fire({ title: 'Keluar Akun', text: 'Anda telah keluar dari akun.', icon: 'info', background: '#1E293B', color: '#F8FAFC', timer: 1500, showConfirmButton: false });
    };

    document.getElementById('btnNavbarLogout')?.addEventListener('click', handleLogout);
    document.getElementById('btnMobileLogout')?.addEventListener('click', handleLogout);

    // Run auth check on load
    await initAuth();

    // ── Load data from API/localStorage ─────────────────────────────────────
    let data = {};
    try {
        data = await BilinggoDataStore.loadAsync();
    } catch(e) {
        data = BilinggoDataStore.load();
    }

    // ── Cart State ───────────────────────────────────────────────────────────
    let cart = [];
    try {
        const storedCart = localStorage.getItem('bilinggo_cart');
        if (storedCart) cart = JSON.parse(storedCart);
    } catch(e) { cart = []; }

    function saveCart() {
        localStorage.setItem('bilinggo_cart', JSON.stringify(cart));
        updateCartBadge();
        renderCartItems();
    }

    function updateCartBadge() {
        const badge = document.getElementById('cartCountBadge');
        const floatBtn = document.getElementById('floatingCartBtn');
        if (badge && floatBtn) {
            const count = cart.reduce((sum, item) => sum + item.quantity, 0);
            badge.textContent = count;
            floatBtn.style.display = count > 0 ? 'flex' : 'none';
        }
    }

    function parsePrice(str) {
        if (!str) return 0;
        return parseInt(str.replace(/[^0-9]/g, '')) || 0;
    }

    function formatRupiah(num) {
        return 'Rp ' + num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    }

    // ── Dynamic Content Renderer ─────────────────────────────────────────────

    function initDynamicContent() {
        // 1. Hero Slides
        const slidesContainer = document.querySelector('.hero-slides-container');
        const sliderDots = document.querySelector('.slider-dots');
        if (slidesContainer && data.slides) {
            slidesContainer.innerHTML = '';
            if (sliderDots) sliderDots.innerHTML = '';
            const activeSlides = data.slides.filter(s => s.isActive);
            activeSlides.forEach((slide, idx) => {
                const activeClass = idx === 0 ? 'active' : '';
                let html = '';
                if (slide.type === 'original') {
                    html = `<div class="hero-slide ${activeClass}">
                        <div class="container hero-container">
                            <div class="hero-content">
                                <h2 class="tech-text" data-text="${slide.techText}">${slide.techText}</h2>
                                <h1 class="hero-title">${slide.title}</h1>
                                <a href="#webinar-form" class="btn btn-primary">${slide.btnText}</a>
                            </div>
                            <div class="hero-image-wrapper"><div class="hero-image-container">
                                <div class="laptop-glow"></div>
                                <img src="${slide.image}" alt="${slide.alt||''}" class="hero-image">
                            </div></div>
                        </div></div>`;
                } else {
                    const outcomesList = (slide.outcomes||[]).map(o=>`<li>${o}</li>`).join('');
                    html = `<div class="hero-slide toefl-hero-slide ${activeClass}">
                        <div class="toefl-hero-decor toefl-decor-circle-1"></div>
                        <div class="toefl-hero-decor toefl-decor-circle-2"></div>
                        <div class="container hero-container toefl-hero-container">
                            <div class="hero-content toefl-hero-content">
                                <span class="toefl-hero-tag">${slide.tag||'WEBINAR SPESIAL'}</span>
                                <h2 class="toefl-hero-title">${slide.title}</h2>
                                <h3 class="toefl-hero-subtitle">${slide.subtitle||''}</h3>
                                <p class="toefl-hero-tagline">${slide.tagline||''}</p>
                                <div class="toefl-hero-outcomes"><h4 class="outcomes-title">Apa yang akan Anda kuasai:</h4>
                                    <ul class="outcomes-list">${outcomesList}</ul></div>
                                <div class="toefl-hero-ticket">
                                    <div class="ticket-item"><i class="fa-solid fa-calendar-days text-pink"></i><span>${slide.date||''}</span></div>
                                    <div class="ticket-item"><i class="fa-solid fa-tags text-pink"></i><span class="old-price">${slide.oldPrice||''}</span> <span class="new-price">${slide.newPrice||''}</span></div>
                                </div>
                                <a href="#webinar-form" class="btn btn-primary toefl-hero-btn">${slide.btnText}</a>
                            </div>
                            <div class="hero-image-wrapper toefl-hero-image-wrapper">
                                <div class="speaker-hero-wrapper">
                                    <div class="speaker-hero-ring-1"></div><div class="speaker-hero-ring-2"></div>
                                    <div class="speaker-hero-img-container">
                                        <img src="${slide.speakerImage||''}" alt="${slide.speakerName||''}" class="speaker-hero-img">
                                    </div>
                                    <div class="speaker-hero-info">
                                        <h4 class="speaker-hero-name">${slide.speakerName||''}</h4>
                                        <p class="speaker-hero-credentials">${slide.speakerTitle1||''}</p>
                                        <p class="speaker-hero-credentials">${slide.speakerTitle2||''}</p>
                                    </div>
                                </div>
                            </div>
                        </div></div>`;
                }
                slidesContainer.insertAdjacentHTML('beforeend', html);
                if (sliderDots) sliderDots.insertAdjacentHTML('beforeend', `<span class="${idx===0?'dot active':'dot'}"></span>`);
            });
        }

        // 2. Sessions Grid
        const sessionsGrid = document.querySelector('.sessions-grid');
        if (sessionsGrid && data.sessions) {
            sessionsGrid.innerHTML = '';
            data.sessions.forEach(s => {
                sessionsGrid.insertAdjacentHTML('beforeend', `
                    <div class="session-card ${s.bgColor||''} ${s.tall?'card-tall':''}">
                        <div class="session-date">${s.date} <i class="fa-solid fa-arrow-up-right-from-square"></i></div>
                        <h4 class="session-name">${s.name}</h4>
                        <p class="session-desc">${s.desc}</p>
                    </div>`);
            });
        }

        // 3. Topics Dropdown
        const topicSelect = document.getElementById('webinar-topic');
        if (topicSelect && data.topics) {
            topicSelect.innerHTML = '<option value="" disabled selected>Pilih Topik Sesi</option>';
            data.topics.forEach(t => {
                const opt = document.createElement('option');
                opt.value = t.value; opt.textContent = t.label;
                topicSelect.appendChild(opt);
            });
        }

        // 4. News Grid
        const newsGrid = document.getElementById('news-grid-container');
        if (newsGrid && data.news) {
            newsGrid.innerHTML = '';
            data.news.forEach(item => {
                newsGrid.insertAdjacentHTML('beforeend', `
                    <div class="news-card">
                        <div class="news-img-wrapper">
                            <img src="${item.image||''}" alt="${item.title}" class="news-img">
                            <span class="news-date-badge">${item.date||item.news_date||''}</span>
                        </div>
                        <div class="news-content">
                            <h4 class="news-card-title">${item.title}</h4>
                            <p class="news-card-desc">${item.desc||item.description||''}</p>
                        </div>
                    </div>`);
            });
        }

        // 5. Product Catalog
        const catalogGrid = document.getElementById('catalog-grid-container');
        if (catalogGrid && data.products) {
            window.renderCatalogProducts = function(category = 'all') {
                catalogGrid.innerHTML = '';
                const filtered = category === 'all' ? data.products : data.products.filter(p => p.category === category);
                if (!filtered.length) {
                    catalogGrid.innerHTML = '<div style="grid-column:1/-1;text-align:center;color:var(--text-light);padding:40px;">Belum ada produk untuk kategori ini.</div>';
                    return;
                }
                filtered.forEach(p => {
                    const catMap = { ebook: {label:'E-Book',cls:'ebook'}, course: {label:'Kursus',cls:'course'}, test: {label:'Simulasi/Ujian',cls:'test'} };
                    const cat = catMap[p.category] || {label:'Produk',cls:'ebook'};
                    const waNum = data.whatsappNumber || '6282118940782';
                    const waMsg = encodeURIComponent(`Halo CS BilînGo, saya ingin bertanya tentang produk: *${p.name}*`);
                    const oldPriceHtml = p.price ? `<span class="product-old-price">${p.price}</span>` : '';
                    catalogGrid.insertAdjacentHTML('beforeend', `
                        <div class="product-card" data-category="${p.category}">
                            <div class="product-img-wrapper">
                                <span class="product-badge ${cat.cls}">${cat.label}</span>
                                <img src="${p.image||''}" alt="${p.name}" class="product-img">
                            </div>
                            <div class="product-info">
                                <h4 class="product-title">${p.name}</h4>
                                <p class="product-desc">${p.desc||p.description||''}</p>
                                <div class="product-price-wrapper">
                                    ${oldPriceHtml}
                                    <span class="product-price">${p.promoPrice||p.price||''}</span>
                                </div>
                                <div class="product-actions-vertical" style="display:flex;flex-direction:column;gap:8px;margin-top:16px;">
                                    <button onclick="window.openPaymentOptions(${p.id})" class="btn-buy" style="width:100%;border:none;display:flex;align-items:center;justify-content:center;gap:8px;font-weight:600;cursor:pointer;">
                                        <i class="fa-solid fa-credit-card"></i> Beli Sekarang
                                    </button>
                                    <div style="display:grid;grid-template-columns:1.1fr 0.9fr;gap:8px;">
                                        <a href="https://wa.me/${waNum}?text=${waMsg}" target="_blank" class="btn-action-outline btn-cs" style="text-align:center;padding:8px 4px;display:flex;align-items:center;justify-content:center;gap:4px;font-size:12px;font-weight:600;text-decoration:none;border-radius:30px;transition:all 0.3s;">
                                            <i class="fa-brands fa-whatsapp"></i> Hubungi CS
                                        </a>
                                        <button onclick="window.addToCart(${p.id})" class="btn-action-outline btn-add-cart" style="padding:8px 4px;display:flex;align-items:center;justify-content:center;gap:4px;font-size:12px;font-weight:600;border-radius:30px;background:transparent;cursor:pointer;transition:all 0.3s;">
                                            <i class="fa-solid fa-cart-plus"></i> + Keranjang
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>`);
                });
            };
            window.renderCatalogProducts('all');

            const filterContainer = document.getElementById('catalog-filters-container');
            if (filterContainer) {
                filterContainer.querySelectorAll('.filter-btn').forEach(btn => {
                    btn.addEventListener('click', () => {
                        filterContainer.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
                        btn.classList.add('active');
                        window.renderCatalogProducts(btn.getAttribute('data-category'));
                    });
                });
            }
        }

        // 6. Book Gallery Renderer
        const bookGrid = document.getElementById('book-gallery-grid-container');
        if (bookGrid) {
            let activeBookCategory = 'all';
            let activeBookSearch = '';

            window.renderBookGallery = function(category = activeBookCategory, searchQuery = activeBookSearch) {
                activeBookCategory = category;
                activeBookSearch = searchQuery;

                bookGrid.innerHTML = '';
                const booksList = data.books || [];
                let filtered = category === 'all' ? booksList : booksList.filter(b => b.category === category);
                
                if (searchQuery.trim()) {
                    const q = searchQuery.toLowerCase().trim();
                    filtered = filtered.filter(b => 
                        (b.title && b.title.toLowerCase().includes(q)) ||
                        (b.author && b.author.toLowerCase().includes(q)) ||
                        (b.desc && b.desc.toLowerCase().includes(q)) ||
                        (b.categoryLabel && b.categoryLabel.toLowerCase().includes(q))
                    );
                }

                if (!filtered.length) {
                    bookGrid.innerHTML = '<div style="grid-column:1/-1;text-align:center;color:var(--text-light);padding:40px;">Tidak ada buku yang sesuai dengan pencarian.</div>';
                    return;
                }
                filtered.forEach(book => {
                    const starsHtml = `<i class="fa-solid fa-star text-yellow"></i> ${book.rating || '5.0'} <span class="review-cnt">(${book.reviewsCount || 100} Ulasan)</span>`;
                    bookGrid.insertAdjacentHTML('beforeend', `
                        <div class="book-card" data-category="${book.category}">
                            <div class="book-cover-wrapper">
                                <span class="book-badge">${book.badge||'BESTSELLER'}</span>
                                <img src="${book.image}" alt="${book.title}" class="book-cover-img">
                                <div class="book-overlay-actions">
                                    <button class="btn-quick-preview" onclick="window.openBookDetail(${book.id})">
                                        <i class="fa-solid fa-eye"></i> Pratinjau Buku
                                    </button>
                                </div>
                            </div>
                            <div class="book-card-info">
                                <div class="book-rating">${starsHtml}</div>
                                <h4 class="book-card-title">${book.title}</h4>
                                <p class="book-author"><i class="fa-solid fa-feather"></i> ${book.author}</p>
                                <p class="book-specs"><i class="fa-solid fa-file-pdf"></i> ${book.pages}</p>
                                
                                <div class="book-price-row">
                                    <div class="book-prices">
                                        ${book.price ? `<span class="book-old-price">${book.price}</span>` : ''}
                                        <span class="book-new-price">${book.promoPrice||book.price}</span>
                                    </div>
                                </div>
                                <div class="book-card-btns">
                                    <button class="btn-book-preview" onclick="window.openBookDetail(${book.id})">
                                        <i class="fa-solid fa-circle-info"></i> Detail
                                    </button>
                                    <button class="btn-book-buy" onclick="window.addBookToCart(${book.id})">
                                        <i class="fa-solid fa-cart-plus"></i> Beli
                                    </button>
                                </div>
                            </div>
                        </div>
                    `);
                });
            };
            window.renderBookGallery('all', '');

            const bookFilters = document.getElementById('book-filters-container');
            if (bookFilters) {
                bookFilters.querySelectorAll('.book-filter-btn').forEach(btn => {
                    btn.addEventListener('click', () => {
                        bookFilters.querySelectorAll('.book-filter-btn').forEach(b => b.classList.remove('active'));
                        btn.classList.add('active');
                        window.renderBookGallery(btn.getAttribute('data-book-cat'), activeBookSearch);
                    });
                });
            }

            const bookSearchInput = document.getElementById('bookSearchInput');
            if (bookSearchInput) {
                bookSearchInput.addEventListener('input', (e) => {
                    window.renderBookGallery(activeBookCategory, e.target.value);
                });
            }
        }
    }

    // ── Book Gallery Interaction Functions ──────────────────────────────────

    window.addBookToCart = function(bookId) {
        if (!currentCustomer) {
            showLoginRequiredAlert();
            return;
        }
        const booksList = data.books || [];
        const book = booksList.find(b => b.id === bookId);
        if (!book) return;
        const existing = cart.find(i => i.id === book.id);
        if (existing) existing.quantity += 1;
        else cart.push({ id: book.id, name: book.title, price: book.promoPrice||book.price, image: book.image, quantity: 1 });
        saveCart();
        if (window.Swal) Swal.fire({ title:'Berhasil Ditambahkan!', text:`"${book.title}" dimasukkan ke keranjang belanja.`, icon:'success', timer:1500, showConfirmButton:false, background:'#1E293B', color:'#F8FAFC' });
        else alert(`"${book.title}" berhasil ditambahkan ke keranjang.`);
    };

    window.openBookDetail = function(bookId) {
        const booksList = data.books || [];
        const book = booksList.find(b => b.id === bookId);
        if (!book) return;

        const modal = document.getElementById('bookDetailModal');
        const overlay = document.getElementById('bookModalOverlay');
        if (!modal || !overlay) return;

        document.getElementById('bookModalImage').src = book.image;
        document.getElementById('bookModalCategory').textContent = book.categoryLabel || 'E-Book Akademik';
        document.getElementById('bookModalTitle').textContent = book.title;
        document.getElementById('bookModalAuthor').textContent = 'Oleh ' + book.author;
        document.getElementById('bookModalPages').textContent = book.pages;
        document.getElementById('bookModalLang').textContent = book.language || 'Bahasa Indonesia & Inggris';
        document.getElementById('bookModalDesc').textContent = book.desc;
        document.getElementById('bookModalOldPrice').textContent = book.price || '';
        document.getElementById('bookModalPrice').textContent = book.promoPrice || book.price;

        const listEl = document.getElementById('bookModalHighlightsList');
        if (listEl) {
            listEl.innerHTML = (book.highlights||[]).map(h => `<li><i class="fa-solid fa-circle-check text-pink"></i> ${h}</li>`).join('');
        }

        const btnCart = document.getElementById('btnBookModalCart');
        const btnBuy = document.getElementById('btnBookModalBuy');
        if (btnCart) {
            btnCart.onclick = () => {
                window.addBookToCart(book.id);
                window.closeBookDetail();
            };
        }
        if (btnBuy) {
            btnBuy.onclick = () => {
                window.closeBookDetail();
                window.addBookToCart(book.id);
                const drawer = document.getElementById('cartDrawer');
                const drawerOv = document.getElementById('cartDrawerOverlay');
                if (drawer && drawerOv) {
                    drawer.classList.add('open');
                    drawerOv.classList.add('open');
                }
            };
        }

        modal.classList.add('open');
        overlay.classList.add('open');
    };

    window.closeBookDetail = function() {
        const modal = document.getElementById('bookDetailModal');
        const overlay = document.getElementById('bookModalOverlay');
        if (modal && overlay) {
            modal.classList.remove('open');
            overlay.classList.remove('open');
        }
    };

    document.getElementById('btnCloseBookModal')?.addEventListener('click', window.closeBookDetail);
    document.getElementById('bookModalOverlay')?.addEventListener('click', window.closeBookDetail);

    // ── Cart Functions ───────────────────────────────────────────────────────

    window.addToCart = function(productId) {
        if (!currentCustomer) {
            showLoginRequiredAlert();
            return;
        }
        const prod = data.products.find(p => p.id === productId);
        if (!prod) return;
        const existing = cart.find(i => i.id === productId);
        if (existing) existing.quantity += 1;
        else cart.push({ id: prod.id, name: prod.name, price: prod.promoPrice||prod.price, image: prod.image, quantity: 1 });
        saveCart();
        if (window.Swal) Swal.fire({ title:'Ditambahkan!', text:`${prod.name} dimasukkan ke keranjang.`, icon:'success', timer:1500, showConfirmButton:false, background:'#1E293B', color:'#F8FAFC' });
        else alert(`${prod.name} berhasil ditambahkan ke keranjang.`);
    };

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

    window.updateCartQuantity = function(productId, qty) {
        const item = cart.find(i => i.id === productId);
        if (item) { item.quantity = parseInt(qty)||1; if (item.quantity <= 0) { window.removeFromCart(productId); return; } }
        saveCart();
    };

    function renderCartItems() {
        const container = document.getElementById('cartItemsList');
        const totalSpan = document.getElementById('cartTotalPrice');
        if (!container) return;
        if (!cart.length) {
            container.innerHTML = `<div class="cart-empty-state" style="text-align:center;padding:40px 20px;color:#94a3b8;"><i class="fa-solid fa-basket-shopping" style="font-size:40px;margin-bottom:12px;color:var(--primary-pink);"></i><p>Keranjang belanja Anda masih kosong</p></div>`;
            if (totalSpan) totalSpan.textContent = 'Rp 0';
            return;
        }
        let html = '', total = 0;
        cart.forEach(item => {
            const priceNum = parsePrice(item.price);
            const subtotal = priceNum * item.quantity;
            total += subtotal;
            html += `<div class="cart-item" style="display:flex;gap:12px;padding:12px;border-bottom:1px solid rgba(255,255,255,0.1);align-items:center;">
                <img src="${item.image}" alt="${item.name}" style="width:50px;height:50px;object-fit:cover;border-radius:6px;">
                <div style="flex:1;text-align:left;">
                    <h5 style="margin:0;font-size:14px;font-weight:600;color:#f8fafc;">${item.name}</h5>
                    <p style="margin:4px 0 0;font-size:13px;color:var(--primary-pink);font-weight:700;">${item.price}</p>
                    <div style="display:flex;align-items:center;gap:8px;margin-top:8px;">
                        <button onclick="window.updateCartQuantity(${item.id},${item.quantity-1})" style="background:rgba(255,255,255,0.1);color:#f8fafc;border:none;width:24px;height:24px;border-radius:4px;cursor:pointer;">-</button>
                        <span style="font-size:14px;font-weight:600;color:#f8fafc;">${item.quantity}</span>
                        <button onclick="window.updateCartQuantity(${item.id},${item.quantity+1})" style="background:rgba(255,255,255,0.1);color:#f8fafc;border:none;width:24px;height:24px;border-radius:4px;cursor:pointer;">+</button>
                    </div>
                </div>
                <button onclick="window.removeFromCart(${item.id})" style="background:none;border:none;color:#ef4444;cursor:pointer;font-size:16px;"><i class="fa-solid fa-trash-can"></i></button>
            </div>`;
        });
        container.innerHTML = html;
        if (totalSpan) totalSpan.textContent = formatRupiah(total);
    }

    // ── Payment Modal ────────────────────────────────────────────────────────

    window.openPaymentOptions = function(productId) {
        if (!currentCustomer) {
            showLoginRequiredAlert();
            return;
        }
        const prod = data.products.find(p => p.id === productId);
        if (!prod) return;
        const modal = document.getElementById('paymentOptionsModal');
        const overlay = document.getElementById('paymentModalOverlay');
        if (!modal || !overlay) return;
        const img = document.getElementById('paymentProductImg');
        const nameEl = document.getElementById('paymentProductName');
        const priceEl = document.getElementById('paymentProductPrice');
        const vaText = document.getElementById('vaDetailsText');
        const optionShopee = document.getElementById('optionShopee');
        const optionTokopedia = document.getElementById('optionTokopedia');
        const confirmBtn = document.getElementById('btnConfirmVAWA');
        if (img) img.src = prod.image;
        if (nameEl) nameEl.textContent = prod.name;
        if (priceEl) priceEl.textContent = prod.promoPrice || prod.price;
        if (vaText) vaText.textContent = prod.vaDetails || 'Bank BCA 1234567890 a/n Bilinggo Global Academy';
        if (optionShopee) { optionShopee.href = prod.shopeeUrl||'#'; optionShopee.style.display = prod.shopeeUrl ? 'block' : 'none'; }
        if (optionTokopedia) { optionTokopedia.href = prod.tokopediaUrl||'#'; optionTokopedia.style.display = prod.tokopediaUrl ? 'block' : 'none'; }
        if (confirmBtn) {
            confirmBtn.onclick = () => {
                const waNum = data.whatsappNumber || '6282118940782';
                const msg = `Halo BilînGo, saya telah melakukan transfer untuk pembelian produk: *${prod.name}* (${prod.promoPrice||prod.price}).\n\nBerikut terlampir bukti transfer saya.`;
                window.open(`https://wa.me/${waNum}?text=${encodeURIComponent(msg)}`, '_blank');
            };
        }
        modal.classList.add('open');
        overlay.classList.add('open');
    };

    // ── Cart Drawer & Checkout ───────────────────────────────────────────────
    const floatBtn   = document.getElementById('floatingCartBtn');
    const closeBtn   = document.getElementById('btnCloseCart');
    const drawer     = document.getElementById('cartDrawer');
    const drawerOv   = document.getElementById('cartDrawerOverlay');
    const checkoutBtn = document.getElementById('btnCheckoutCart');
    const payModal   = document.getElementById('paymentOptionsModal');
    const payOverlay = document.getElementById('paymentModalOverlay');
    const closePayBtn = document.getElementById('btnClosePaymentModal');
    const optionVA   = document.getElementById('optionVA');
    const vaCollapse = document.getElementById('vaDetailsCollapse');

    if (floatBtn && drawer) {
        floatBtn.addEventListener('click', () => { drawer.classList.add('open'); drawerOv?.classList.add('open'); });
        const closeCart = () => { drawer.classList.remove('open'); drawerOv?.classList.remove('open'); };
        closeBtn?.addEventListener('click', closeCart);
        drawerOv?.addEventListener('click', closeCart);
    }

    if (checkoutBtn) {
        checkoutBtn.addEventListener('click', async () => {
            if (!currentCustomer) {
                showLoginRequiredAlert();
                return;
            }
            if (!cart.length) return;
            const waNum = data.whatsappNumber || '6282118940782';
            let total = 0;
            let msg = `Halo BilînGo, saya (${currentCustomer.name}) ingin membeli produk berikut:\n\n`;
            cart.forEach((item, idx) => {
                const num = parsePrice(item.price);
                total += num * item.quantity;
                msg += `${idx+1}. *${item.name}* (Qty: ${item.quantity}) - ${item.price}\n`;
            });
            msg += `\n*Total*: ${formatRupiah(total)}\n\nMohon info detail pembayaran. Terima kasih!`;
            // Save order to API
            try {
                await BilinggoDataStore.createOrder({ 
                    customer_name: currentCustomer.name, 
                    customer_phone: currentCustomer.phone || waNum, 
                    items: cart, 
                    total_price: total, 
                    payment_method: 'whatsapp' 
                });
            } catch(e) {}
            window.open(`https://wa.me/${waNum}?text=${encodeURIComponent(msg)}`, '_blank');
        });
    }

    if (payModal && payOverlay) {
        const closePayModal = () => { payModal.classList.remove('open'); payOverlay.classList.remove('open'); if (vaCollapse) vaCollapse.style.display = 'none'; };
        closePayBtn?.addEventListener('click', closePayModal);
        payOverlay.addEventListener('click', closePayModal);
        if (optionVA && vaCollapse) {
            optionVA.addEventListener('click', e => {
                if (e.target.closest('.va-instructions')) return;
                vaCollapse.style.display = vaCollapse.style.display === 'none' ? 'block' : 'none';
            });
        }
    }

    // ── Init ─────────────────────────────────────────────────────────────────
    initDynamicContent();
    saveCart();

    // ── Smooth Scroll ────────────────────────────────────────────────────────
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function(e) {
            const href = this.getAttribute('href');
            if (href === '#') return;
            e.preventDefault();
            const target = document.querySelector(href);
            if (target) {
                const y = target.getBoundingClientRect().top + window.scrollY - (document.getElementById('mainNavbar')?.offsetHeight || 70);
                window.scrollTo({ top: y, behavior: 'smooth' });
            }
        });
    });

    // ── Scroll Reveal ────────────────────────────────────────────────────────
    const revealObserver = new IntersectionObserver((entries, obs) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) { entry.target.style.opacity = 1; entry.target.style.transform = 'translateY(0)'; obs.unobserve(entry.target); }
        });
    }, { threshold: 0.1 });
    document.querySelectorAll('section > .container').forEach(el => {
        el.style.opacity = 0; el.style.transform = 'translateY(30px)'; el.style.transition = 'opacity 0.8s ease-out, transform 0.8s ease-out';
        revealObserver.observe(el);
    });

    // ── Navbar Scroll ────────────────────────────────────────────────────────
    const navbar = document.getElementById('mainNavbar');
    const handleScroll = () => { if (navbar) navbar.classList.toggle('scrolled', window.scrollY > 40); };
    window.addEventListener('scroll', handleScroll, { passive: true });
    handleScroll();

    // ── Mobile Menu ──────────────────────────────────────────────────────────
    const menuToggle = document.getElementById('mobileMenuToggle');
    const navOverlay = document.getElementById('mobileNavOverlay');
    const navClose   = document.getElementById('mobileNavClose');
    window.closeMobileMenu = function() {
        navOverlay?.classList.remove('open');
        menuToggle?.classList.remove('active');
        if (menuToggle) menuToggle.setAttribute('aria-expanded', 'false');
        document.body.style.overflow = '';
    };
    menuToggle?.addEventListener('click', () => {
        const isOpen = navOverlay?.classList.contains('open');
        if (isOpen) window.closeMobileMenu();
        else { navOverlay?.classList.add('open'); menuToggle.classList.add('active'); menuToggle.setAttribute('aria-expanded', 'true'); document.body.style.overflow = 'hidden'; }
    });
    navClose?.addEventListener('click', window.closeMobileMenu);
    navOverlay?.addEventListener('click', e => { if (e.target === navOverlay) window.closeMobileMenu(); });
    document.addEventListener('keydown', e => { if (e.key === 'Escape') window.closeMobileMenu(); });

    // ── Mobile CTA Bar ───────────────────────────────────────────────────────
    const ctaBar = document.getElementById('mobileCTABar');
    const regForm = document.getElementById('webinar-form');
    if (ctaBar && regForm) {
        new IntersectionObserver(entries => {
            entries.forEach(e => { ctaBar.style.transform = e.isIntersecting ? 'translateY(120%)' : 'translateY(0)'; ctaBar.style.transition = 'transform 0.4s cubic-bezier(0.4,0,0.2,1)'; });
        }, { threshold: 0.3 }).observe(regForm);
    }

    // ── Webinar Form ─────────────────────────────────────────────────────────
    const webinarForm = document.getElementById('webinar-form');
    if (webinarForm) {
        webinarForm.addEventListener('submit', async e => {
            e.preventDefault();
            const reg = {
                name:     document.getElementById('webinar-name').value.trim(),
                topic:    document.getElementById('webinar-topic').value,
                phone:    document.getElementById('webinar-phone').value.trim(),
                email:    document.getElementById('webinar-email').value.trim(),
                referral: document.getElementById('webinar-referral').value.trim(),
            };
            try { await BilinggoDataStore.addRegistrationAsync(reg); } catch(e) { BilinggoDataStore.addRegistration(reg); }
            const waNum = data.whatsappNumber || '6282118940782';
            let msg = `Halo BilinGo, saya ingin memesan tiket webinar!\n\n*Nama:* ${reg.name}\n*Topik:* ${reg.topic}\n*WhatsApp:* ${reg.phone}\n*Email:* ${reg.email}`;
            if (reg.referral) msg += `\n*Referral:* ${reg.referral}`;
            window.open(`https://wa.me/${waNum}?text=${encodeURIComponent(msg)}`, '_blank');
        });
    }

    // ── Hero Slider ──────────────────────────────────────────────────────────
    function initSlider() {
        const slides = document.querySelectorAll('.hero-slide');
        const dots   = document.querySelectorAll('.slider-dots .dot');
        let current = 0, interval;
        function showSlide(idx) {
            slides.forEach(s => s.classList.remove('active'));
            dots.forEach(d => d.classList.remove('active'));
            if (slides[idx]) slides[idx].classList.add('active');
            if (dots[idx]) dots[idx].classList.add('active');
            current = idx;
        }
        function next() { showSlide((current + 1) % slides.length); }
        function start() { interval = setInterval(next, 3000); }
        function stop()  { clearInterval(interval); }
        dots.forEach((d, i) => d.addEventListener('click', () => { stop(); showSlide(i); start(); }));
        const heroSlider = document.querySelector('.hero-slider');
        if (heroSlider) {
            let touchStart = 0;
            heroSlider.addEventListener('touchstart', e => { touchStart = e.changedTouches[0].screenX; }, { passive: true });
            heroSlider.addEventListener('touchend', e => {
                const diff = touchStart - e.changedTouches[0].screenX;
                if (Math.abs(diff) > 50) { stop(); showSlide(diff > 0 ? (current+1)%slides.length : (current-1+slides.length)%slides.length); start(); }
            }, { passive: true });
        }
        if (slides.length > 0) start();
    }
    // Re-init slider after dynamic content renders
    setTimeout(initSlider, 100);
});
