// File: assets/js/script.js

// =========================================================
// 1. INISIALISASI & CONFIG
// =========================================================
const SITE_CONFIG = window.DATA_FROM_PHP.config;
const DB = window.DATA_FROM_PHP.db;
const CREDIT = window.DATA_FROM_PHP.credit;
// PAGINATION STATE
let currentArticlePage = 1;
const ARTICLES_PER_PAGE = 6;

// =========================================================
// 2. HELPER FUNCTIONS
// =========================================================

// Format Rupiah Indonesia
const formatRupiah = (number) => new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', maximumFractionDigits: 0 }).format(number);

// Pembulatan ke Ribuan Teratas
function roundUpToThousand(num) {
    return Math.ceil(num / 1000) * 1000;
}

// Bersihkan ID Youtube
function extractYoutubeId(urlOrId) {
    if (!urlOrId) return '';
    let id = urlOrId;
    if (id.includes('v=')) {
        id = id.split('v=')[1];
    } else if (id.includes('youtu.be/')) {
        id = id.split('youtu.be/')[1];
    } else if (id.includes('embed/')) {
        id = id.split('embed/')[1];
    }
    if (id.includes('&')) id = id.split('&')[0];
    if (id.includes('?')) id = id.split('?')[0];
    return id.trim();
}

/**
 * GENERATOR MEDIA HTML (Video/Image)
 */
function getMediaHtml(src, className = "w-full h-full object-cover", autoplay = false, soundOn = false) {
    if (!src) return `<img src="assets/images/no-image.jpg" class="${className}" onerror="this.src='https://via.placeholder.com/800x600?text=No+Media'">`;

    const lowerSrc = src.toLowerCase();
    const isYoutube = lowerSrc.includes('youtube.com') || lowerSrc.includes('youtu.be');
    const isVideoFile = lowerSrc.endsWith('.mp4') || lowerSrc.endsWith('.webm') || lowerSrc.endsWith('.ogg');

    if (isYoutube) {
        let vId = extractYoutubeId(src);
        let params = '?rel=0';
        if (autoplay) {
            const muteParam = soundOn ? '0' : '1';
            params = `?autoplay=1&mute=${muteParam}&loop=1&playlist=${vId}&controls=1&rel=0&playsinline=1`;
        }
        return `<iframe class="${className}" src="https://www.youtube.com/embed/${vId}${params}" frameborder="0" allowfullscreen></iframe>`;
    } else if (isVideoFile) {
        const mutedAttr = (autoplay && !soundOn) ? 'muted' : '';
        const autoplayAttr = autoplay ? 'autoplay loop playsinline' : 'controls';
        return `
            <video class="${className}" ${autoplayAttr} ${mutedAttr}>
                <source src="${src}" type="video/mp4">
                Browser Anda tidak mendukung tag video.
            </video>
        `;
    } else {
        return `<img src="${src}" class="${className}" onerror="this.src='https://via.placeholder.com/800x600?text=Image+Error'">`;
    }
}

// --- LEAD TRACKER & CHAT SYSTEM ---
function trackLeadAndChat(source, detail, message) {
    const formData = new FormData();
    formData.append('source', source);
    formData.append('detail', detail);
    fetch('api.php?action=track_lead', { method: 'POST', body: formData }).catch(err => console.log('Tracking error:', err));
    const waUrl = `https://wa.me/${SITE_CONFIG.sales.no_wa}?text=${encodeURIComponent(message)}`;
    window.open(waUrl, '_blank');
}

// --- DYNAMIC WHATSAPP FLOATING BUTTON (FIX: BUBBLE STYLE) ---
function initFloatingButton() {
    // Cek apakah tombol sudah ada, jika belum buat baru
    if (!document.getElementById('floating-wa')) {
        const btn = document.createElement('a');
        btn.id = 'floating-wa';
        btn.target = '_blank';
        // STYLE FIX: Bulat sempurna (w-16 h-16), warna WA resmi, shadow besar
        btn.className = 'fixed bottom-6 right-6 z-50 w-16 h-16 bg-[#25D366] hover:bg-[#20bd5a] text-white rounded-full shadow-[0_4px_14px_0_rgba(37,211,102,0.39)] flex items-center justify-center transition-all duration-300 transform hover:scale-110 hover:-translate-y-1 focus:outline-none group';
        btn.innerHTML = `
            <i class="fa-brands fa-whatsapp text-4xl leading-none"></i>
            <span class="absolute right-full mr-4 bg-white text-gray-800 text-xs font-bold px-3 py-2 rounded-lg shadow-lg opacity-0 group-hover:opacity-100 transition-opacity duration-300 whitespace-nowrap pointer-events-none">
                Hubungi Sales
                <div class="absolute top-1/2 -right-1 w-2 h-2 bg-white transform -translate-y-1/2 rotate-45"></div>
            </span>
        `;
        document.body.appendChild(btn);
    }
}

function updateFloatingContext(route, id) {
    const btn = document.getElementById('floating-wa');
    if (!btn) return;

    const sName = SITE_CONFIG.sales.nama_lengkap;
    let msg = `Halo ${sName}, saya melihat website Toyota dan ingin info lebih lanjut.`; // Default

    // LOGIKA PRE-FILLED MESSAGE BERDASARKAN HALAMAN
    if (route === 'home') {
        msg = `Halo ${sName}, saya mau tanya info mengenai mobil Toyota.`;
    } else if (route === 'produk') {
        msg = `Halo ${sName}, boleh minta Pricelist Toyota terbaru?`;
    } else if (route === 'produk-detail' && id) {
        const p = DB.products.find(x => x.id == id);
        if (p) msg = `Halo ${sName}, saya tertarik dengan *Toyota ${p.name}*. \nApakah ada stok ready atau promo khusus?`;
    } else if (route === 'promo') {
        msg = `Halo ${sName}, info dong promo Toyota bulan ini apa saja?`;
    } else if (route === 'promo-detail' && id) {
        const p = DB.promos.find(x => x.id == id);
        if (p) msg = `Halo ${sName}, saya mau tanya tentang promo: *${p.title || p.judul}*. \nBagaimana syaratnya?`;
    } else if (route === 'simulasi') {
        msg = `Halo ${sName}, tolong bantu hitungkan simulasi kredit Toyota dong.`;
    } else if (route === 'tradein') {
        msg = `Halo ${sName}, saya berencana Tukar Tambah mobil lama saya. Mohon bantuannya.`;
    } else if (route === 'artikel-detail' && id) {
        const a = DB.articles.find(x => x.id == id);
        if (a) msg = `Halo ${sName}, saya habis baca artikel "${a.title}". Mau tanya info terkait hal tersebut.`;
    } else if (route === 'testimoni') {
        msg = `Halo ${sName}, saya lihat testimoni customer. Saya juga berminat ambil unit Toyota.`;
    } else if (route === 'kontak') {
        msg = `Halo ${sName}, bisa minta share lokasi dealer atau janjian ketemuan?`;
    }

    btn.href = `https://wa.me/${SITE_CONFIG.sales.no_wa}?text=${encodeURIComponent(msg)}`;
    
    // Optional: Tracking klik floating button
    btn.onclick = () => {
        const formData = new FormData();
        formData.append('source', 'Floating WA');
        formData.append('detail', route);
        fetch('api.php?action=track_lead', { method: 'POST', body: formData });
    };
}

// --- COUNTDOWN TIMER SYSTEM ---
let countdownInterval;
function initCountdown() {
    if (countdownInterval) clearInterval(countdownInterval);
    const timerElements = document.querySelectorAll('.promo-timer');
    if (timerElements.length === 0) return;

    countdownInterval = setInterval(() => {
        timerElements.forEach(el => {
            const expiredDate = new Date(el.dataset.expired).getTime();
            const now = new Date().getTime();
            const distance = expiredDate - now;

            if (distance < 0) {
                el.innerHTML = '<span class="text-red-600 font-bold bg-red-100 px-2 py-1 rounded">PROMO BERAKHIR</span>';
                return;
            }
            const days = Math.floor(distance / (1000 * 60 * 60 * 24));
            const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            el.innerHTML = `<div class="flex gap-2 items-center text-red-600 font-bold bg-red-50 px-3 py-1 rounded-lg border border-red-100 text-xs md:text-sm shadow-sm inline-flex"><i class="fa-regular fa-clock fa-spin"></i><span>Sisa Waktu: ${days} Hari ${hours} Jam ${minutes} Mnt</span></div>`;
        });
    }, 1000);
}

// =========================================================
// 3. ENGINE NAVIGASI (SPA + DYNAMIC URL)
// =========================================================

const app = document.getElementById('app-content');
let currentRouteIndex = 0;
const menuOrder = ['home', 'promo', 'produk', 'simulasi', 'tradein', 'artikel', 'testimoni', 'kontak'];

async function navigate(route, id = null, updateUrl = true) {
    updateActiveNav(route);
    document.getElementById('mobile-menu').classList.add('hidden');

    if (updateUrl) {
        let newUrl = '?page=' + route;
        if (id) newUrl += '&id=' + id;
        if (route === 'home') newUrl = window.location.pathname;
        window.history.pushState({ route: route, id: id }, '', newUrl);
    }

    // UPDATE FLOATING BUTTON CONTEXT
    updateFloatingContext(route, id);

    let targetIndex = menuOrder.indexOf(route);
    if (targetIndex === -1) {
        if (route.includes('produk-detail')) targetIndex = menuOrder.indexOf('produk');
        else if (route.includes('promo-detail')) targetIndex = menuOrder.indexOf('promo');
        else if (route.includes('artikel-detail')) targetIndex = menuOrder.indexOf('artikel');
        else targetIndex = 0;
    }

    const direction = targetIndex >= currentRouteIndex ? 'forward' : 'backward';
    const exitClass = direction === 'forward' ? 'page-exit-forward' : 'page-exit-backward';
    const enterClass = direction === 'forward' ? 'page-enter-forward' : 'page-enter-backward';

    if (app.firstElementChild) {
        app.firstElementChild.classList.remove('page-enter-forward', 'page-enter-backward');
        app.firstElementChild.classList.add(exitClass);
        await new Promise(r => setTimeout(r, 250));
    }
    
    window.scrollTo(0, 0);

    let html = '';
    switch(route) {
        case 'home': html = renderHome(); break;
        case 'produk': html = renderProducts(); break;
        case 'produk-detail': html = renderProductDetail(id); break;
        case 'simulasi': html = renderSimulasi(); break;
        case 'tradein': html = renderTradeIn(); break;
        case 'promo': html = renderPromo(); break;
        case 'promo-detail': html = renderPromoDetail(id); break;
        case 'artikel': html = renderArtikel(); break;
        case 'artikel-detail': html = renderArtikelDetail(id); break;
        case 'testimoni': html = renderTestimoni(); break;
        case 'kontak': html = renderKontak(); break;
        default: html = renderHome();
    }
    
    html = html.replace('page-enter-placeholder', enterClass);
    app.innerHTML = html;
    currentRouteIndex = targetIndex;
    initCountdown();
}

window.addEventListener('popstate', (event) => {
    if (event.state) { navigate(event.state.route, event.state.id, false); } else { navigate('home', null, false); }
});

function updateActiveNav(route) {
    let activeKey = route;
    if(route.includes('produk')) activeKey = 'produk';
    else if(route.includes('promo')) activeKey = 'promo';
    else if(route.includes('artikel')) activeKey = 'artikel';
    else if(route.includes('tradein')) activeKey = 'tradein';
    
    document.querySelectorAll('.nav-link').forEach(btn => {
        const onclickVal = btn.getAttribute('onclick');
        btn.classList.remove('text-toyota-red', 'border-toyota-red');
        btn.classList.add('border-transparent');
        if (onclickVal && onclickVal.includes(`'${activeKey}'`)) {
            btn.classList.add('text-toyota-red', 'border-toyota-red');
            btn.classList.remove('border-transparent');
        }
    });
    document.querySelectorAll('.mobile-link').forEach(btn => {
        const onclickVal = btn.getAttribute('onclick');
        btn.classList.remove('text-toyota-red');
        if (onclickVal && onclickVal.includes(`'${activeKey}'`)) btn.classList.add('text-toyota-red');
    });
}

// =========================================================
// 4. RENDER FUNCTIONS (VIEWS)
// =========================================================

function renderHome() {
    // A. PROMO FEATURED
    let featuredPromos = DB.promos.filter(p => p.is_featured == 1);
    if (featuredPromos.length === 0 && DB.promos.length > 0) featuredPromos = DB.promos.slice(0, 3);
    else featuredPromos = featuredPromos.slice(0, 3);

    let promoSectionHtml = '';
    if (featuredPromos.length === 0) {
        promoSectionHtml = `<div class="text-center py-10 bg-white rounded-3xl border border-dashed border-gray-300"><p class="text-gray-400">Nantikan promo menarik dari kami!</p></div>`;
    } else if (featuredPromos.length === 1) {
        const p = featuredPromos[0];
        const mediaHtml = getMediaHtml(p.video || p.image || p.gambar_url, "w-full h-full object-cover", true, false);
        let timerHtml = '';
        if (p.expired && new Date(p.expired) > new Date()) {
            timerHtml = `<div class="mb-4 promo-timer" data-expired="${p.expired}"></div>`;
        }
        promoSectionHtml = `
            <div class="flex flex-col md:flex-row items-center bg-white rounded-3xl shadow-xl overflow-hidden border border-gray-100">
                <div class="md:w-1/2 h-64 md:h-96 relative bg-black">
                    ${mediaHtml}
                    <div class="absolute top-4 left-4 bg-toyota-red text-white text-xs font-bold px-3 py-1 rounded-full uppercase tracking-wider shadow-sm">Promo Utama</div>
                </div>
                <div class="p-8 md:p-12 md:w-1/2">
                    <h3 class="text-3xl font-bold mb-4 text-toyota-dark leading-tight">${p.title || p.judul}</h3>
                    ${timerHtml}
                    <div class="flex gap-4 mt-8">
                        <button onclick="navigate('promo-detail', ${p.id})" class="bg-toyota-dark text-white px-8 py-3 rounded-xl font-bold hover:bg-black transition">Lihat Detail</button>
                        <button onclick="trackLeadAndChat('Home Promo', '${p.title || p.judul}', 'Halo, saya mau tanya promo ${p.title || p.judul}')" class="border-2 border-toyota-red text-toyota-red px-8 py-3 rounded-xl font-bold hover:bg-toyota-red hover:text-white transition">Tanya Sales</button>
                    </div>
                </div>
            </div>`;
    } else {
        let cardsHtml = featuredPromos.map(p => {
            const media = getMediaHtml(p.video || p.image || p.gambar_url, "w-full h-56 object-cover transform group-hover:scale-110 transition duration-700", true, false);
            let timerHtml = '';
            if (p.expired && new Date(p.expired) > new Date()) {
                timerHtml = `<div class="mb-3 promo-timer" data-expired="${p.expired}"></div>`;
            }
            return `
                <div class="bg-white rounded-2xl shadow-lg overflow-hidden group border border-gray-100 hover:shadow-2xl transition hover:-translate-y-1">
                    <div class="relative overflow-hidden bg-gray-900">
                        ${media}
                        <div class="absolute top-4 left-4 bg-toyota-red text-white text-xs font-bold px-3 py-1 rounded-full shadow">Hot Promo</div>
                    </div>
                    <div class="p-6">
                        <h3 class="text-xl font-bold mb-3 text-gray-800 line-clamp-2">${p.title || p.judul}</h3>
                        ${timerHtml}
                        <button onclick="navigate('promo-detail', ${p.id})" class="w-full border-2 border-toyota-red text-toyota-red font-bold py-2 rounded-lg hover:bg-toyota-red hover:text-white transition mt-4">Lihat Promo</button>
                    </div>
                </div>
            `;
        }).join('');
        const gridCols = featuredPromos.length === 2 ? 'md:grid-cols-2' : 'md:grid-cols-3';
        promoSectionHtml = `<div class="grid grid-cols-1 ${gridCols} gap-8">${cardsHtml}</div>`;
    }

    // B. PRODUK FAVORIT
    let featuredProducts = DB.products.filter(p => p.is_featured == 1);
    if (featuredProducts.length === 0 && DB.products.length > 0) { featuredProducts = DB.products.slice(0, 3); } else { featuredProducts = featuredProducts.slice(0, 3); }
    let productSectionHtml = '';
    if (featuredProducts.length > 0) {
        const productCards = featuredProducts.map((p, i) => `
            <div class="group bg-white rounded-2xl shadow-lg overflow-hidden border border-gray-100 hover:shadow-2xl transition-all duration-500 transform hover:-translate-y-2">
                <div class="relative h-64 overflow-hidden">
                    <img src="${p.image}" class="w-full h-full object-cover transform group-hover:scale-110 transition duration-700" onerror="this.src='https://via.placeholder.com/400x300?text=No+Image'">
                </div>
                <div class="p-6">
                    <h3 class="text-xl font-bold mb-1">${p.name}</h3>
                    <p class="text-toyota-red font-bold text-lg mb-4">${formatRupiah(p.price)}</p>
                    <button onclick="navigate('produk-detail', ${p.id})" class="w-full py-3 rounded-lg border border-gray-200 font-semibold hover:bg-toyota-dark hover:text-white transition-colors">Detail</button>
                </div>
            </div>
        `).join('');
        productSectionHtml = `
        <section class="py-20 bg-white">
            <div class="container mx-auto px-4">
                <div class="text-center mb-16">
                    <span class="text-toyota-red font-bold tracking-widest text-sm uppercase">Best Seller</span>
                    <h2 class="text-4xl font-bold mt-2">Pilihan Favorit</h2>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-8">
                    ${productCards}
                </div>
                <div class="text-center mt-12">
                     <button onclick="navigate('produk')" class="inline-flex items-center text-toyota-red font-bold text-lg hover:underline group">
                        Lihat Semua Model <i class="fa-solid fa-arrow-right ml-2 group-hover:translate-x-1 transition"></i>
                     </button>
                </div>
            </div>
        </section>`;
    } else {
        productSectionHtml = `<section class="py-20 bg-white"><div class="container mx-auto px-4 text-center"><p class="text-gray-400">Belum ada produk unggulan.</p></div></section>`;
    }

    // C. ARTIKEL HOME
    let artikelHtml = '';
    const articlesList = (DB.articles && Array.isArray(DB.articles)) ? DB.articles : [];
    if (articlesList.length > 0) {
        const topArticles = articlesList.slice(0, 3);
        const articleCards = topArticles.map(a => `
            <div onclick="navigate('artikel-detail', ${a.id})" class="cursor-pointer group bg-white rounded-xl shadow-sm hover:shadow-md transition overflow-hidden border border-gray-100 flex flex-col h-full transform hover:-translate-y-1">
                <div class="relative h-56 overflow-hidden shrink-0">
                    <img src="${a.image}" class="w-full h-full object-cover group-hover:scale-110 transition duration-700" onerror="this.src='https://via.placeholder.com/400x300?text=No+Image'">
                    <div class="absolute inset-0 bg-gradient-to-t from-black/50 to-transparent opacity-0 group-hover:opacity-100 transition duration-300"></div>
                </div>
                <div class="p-6 flex flex-col flex-1">
                    <div class="flex items-center gap-2 text-xs text-gray-400 mb-3">
                        <i class="fa-regular fa-calendar"></i>
                        <span>${a.date}</span>
                    </div>
                    <h3 class="text-xl font-bold text-gray-800 group-hover:text-toyota-red transition mb-3 line-clamp-2 leading-snug">${a.title}</h3>
                    <div class="mt-auto pt-4 border-t border-gray-50 flex justify-between items-center">
                        <span class="text-sm text-toyota-red font-semibold">Baca Selengkapnya</span>
                        <i class="fa-solid fa-arrow-right text-toyota-red text-sm transform group-hover:translate-x-1 transition"></i>
                    </div>
                </div>
            </div>
        `).join('');
        artikelHtml = `
        <section class="py-20 bg-gray-50 border-t border-gray-100">
            <div class="container mx-auto px-4">
                <div class="text-center mb-12">
                    <h2 class="text-3xl font-bold text-gray-800">Berita & Tips</h2>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-8 mb-10">
                    ${articleCards}
                </div>
                <div class="text-center">
                    <button onclick="navigate('artikel')" class="text-toyota-red font-bold hover:underline">Lihat Semua Artikel &rarr;</button>
                </div>
            </div>
        </section>`;
    } else {
        artikelHtml = `<section class="py-20 bg-gray-50 border-t border-gray-100"><div class="container mx-auto px-4 text-center"><h2 class="text-3xl font-bold text-gray-800 mb-4">Berita & Tips</h2><div class="p-8 bg-white rounded-2xl border border-dashed border-gray-300 inline-block"><p class="text-gray-500"><i class="fa-solid fa-newspaper mr-2"></i> Belum ada update artikel terbaru.</p></div></div></section>`;
    }

    // D. TESTIMONI HOME
    let testimoniHtml = '';
    const testimonialsList = (DB.testimonials && Array.isArray(DB.testimonials)) ? DB.testimonials : [];
    if (testimonialsList.length > 0) {
        const topTesti = [...testimonialsList].sort((a, b) => parseInt(b.rating) - parseInt(a.rating)).slice(0, 3);
        const testiCards = topTesti.map(t => {
            let stars = ''; const rating = parseInt(t.rating) || 5; for(let i=0; i<5; i++) stars += i < rating ? '<i class="fa-solid fa-star"></i>' : '<i class="fa-regular fa-star"></i>';
            return `<div class="bg-white p-6 rounded-2xl shadow-sm border border-gray-100 hover:shadow-md transition text-left"><div class="flex text-yellow-400 mb-3 text-sm">${stars}</div><p class="text-gray-600 italic text-sm mb-4 line-clamp-3">"${t.text}"</p><div class="flex items-center gap-3"><img src="${t.delivery_photo}" class="w-10 h-10 rounded-full object-cover border border-gray-200"><div><h4 class="font-bold text-sm text-gray-800">${t.name}</h4><p class="text-xs text-gray-500 truncate w-32">${t.car}</p></div></div></div>`;
        }).join('');
        testimoniHtml = `<div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-10 max-w-5xl mx-auto">${testiCards}</div>`;
    }

    // E. CONTACT SECTION (HOME)
    const s = SITE_CONFIG.sales;
    let sosmedHtml = '';
    if(s.youtube_url || s.instagram_url || s.tiktok_url || s.facebook_url) {
        sosmedHtml += '<div class="grid grid-cols-4 md:grid-cols-2 gap-4 mt-6 md:w-32">';
        if(s.youtube_url) sosmedHtml += `<a href="${s.youtube_url}" target="_blank" class="w-10 h-10 rounded-full bg-gray-800 flex items-center justify-center text-gray-400 hover:text-white hover:bg-red-600 transition shadow-lg border border-gray-700"><i class="fa-brands fa-youtube text-lg"></i></a>`;
        if(s.instagram_url) sosmedHtml += `<a href="${s.instagram_url}" target="_blank" class="w-10 h-10 rounded-full bg-gray-800 flex items-center justify-center text-gray-400 hover:text-white hover:bg-pink-600 transition shadow-lg border border-gray-700"><i class="fa-brands fa-instagram text-lg"></i></a>`;
        if(s.tiktok_url) sosmedHtml += `<a href="${s.tiktok_url}" target="_blank" class="w-10 h-10 rounded-full bg-gray-800 flex items-center justify-center text-gray-400 hover:text-white hover:bg-black transition shadow-lg border border-gray-700"><i class="fa-brands fa-tiktok text-lg"></i></a>`;
        if(s.facebook_url) sosmedHtml += `<a href="${s.facebook_url}" target="_blank" class="w-10 h-10 rounded-full bg-gray-800 flex items-center justify-center text-gray-400 hover:text-white hover:bg-blue-600 transition shadow-lg border border-gray-700"><i class="fa-brands fa-facebook-f text-lg"></i></a>`;
        sosmedHtml += '</div>';
    }
    const contactSectionHtml = `
    <section class="py-20 bg-white border-t border-gray-200">
        <div class="container mx-auto px-4 max-w-5xl">
            <div class="text-center mb-12">
                <h2 class="text-3xl font-bold text-toyota-dark">Hubungi Kami</h2>
            </div>
            <div class="bg-gradient-to-br from-toyota-dark to-black rounded-[2.5rem] p-12 shadow-2xl mb-12 text-white flex flex-col md:flex-row items-center gap-10 relative overflow-hidden">
                <img src="${s.foto_profil_url}" class="w-48 h-48 rounded-full border-4 border-toyota-red object-cover relative z-10">
                <div class="flex-1 relative z-10">
                    <h2 class="text-4xl font-bold mb-1">${s.nama_lengkap}</h2>
                    <p class="text-toyota-red font-bold text-xl uppercase tracking-wider">${s.jabatan}</p>
                    <p class="mt-4 text-gray-300">${SITE_CONFIG.nama_cabang}</p>
                    <div class="flex gap-4 mt-6">
                        <a href="tel:${s.no_wa}" class="bg-white text-toyota-dark px-6 py-2 rounded-full font-bold hover:bg-gray-200 transition">Telepon</a>
                        <button onclick="trackLeadAndChat('Kontak', 'General', 'Halo ${s.nama_lengkap}, saya mau tanya info Toyota.')" class="bg-green-500 text-white px-6 py-2 rounded-full font-bold hover:bg-green-600 transition">WhatsApp</button>
                    </div>
                </div>
                ${sosmedHtml}
                <div class="absolute top-0 right-0 w-64 h-64 bg-toyota-red opacity-10 rounded-full blur-3xl -mr-16 -mt-16 pointer-events-none"></div>
            </div>
            <div class="rounded-3xl overflow-hidden h-96 shadow-lg">
                <iframe src="${SITE_CONFIG.google_map_embed}" width="100%" height="100%" style="border:0;" allowfullscreen="" loading="lazy"></iframe>
            </div>
        </div>
    </section>`;
    
    return `
    <div class="page-enter-placeholder">
        <header class="relative h-screen flex items-center justify-center overflow-hidden bg-parallax" style="background-image: url('${SITE_CONFIG.hero_image_url}');">
            <div class="absolute inset-0 bg-black/50 z-10"></div>
            <div class="relative z-20 text-center px-4 max-w-5xl">
                <h2 class="text-white text-lg md:text-xl font-semibold tracking-[0.3em] uppercase mb-4 animate-[fadeIn_1s_ease-out]">${SITE_CONFIG.nama_cabang}</h2>
                <h1 class="text-5xl md:text-8xl font-extrabold text-white mb-8 tracking-tighter leading-none animate-[slideInRight_1s_ease-out]">DRIVE <span class="text-transparent bg-clip-text bg-gradient-to-r from-toyota-red to-red-500">PROUD</span></h1>
                <p class="text-gray-200 text-lg md:text-2xl mb-10 max-w-2xl mx-auto font-light animate-[fadeIn_1.5s_ease-out]">Penawaran eksklusif dari <span class="font-bold text-white">${SITE_CONFIG.sales.nama_lengkap}</span>. Proses cepat & Mudah.</p>
                <div class="flex flex-col sm:flex-row gap-4 justify-center animate-[fadeIn_2s_ease-out]">
                    <button onclick="navigate('simulasi')" class="bg-toyota-red text-white px-10 py-4 rounded-full font-bold text-lg hover:bg-red-700 transition transform hover:-translate-y-1 shadow-lg">Simulasi Kredit</button>
                    <button onclick="navigate('produk')" class="bg-white/10 backdrop-blur-md border border-white/30 text-white px-10 py-4 rounded-full font-bold text-lg hover:bg-white hover:text-toyota-dark transition">Lihat Mobil</button>
                </div>
            </div>
        </header>

        <section class="py-16 bg-gray-50 border-b border-gray-200">
            <div class="container mx-auto px-4">
                <div class="text-center mb-10">
                    <h2 class="text-3xl font-bold text-toyota-dark">Promo Spesial</h2>
                    <p class="text-gray-500 mt-2">Penawaran terbaik bulan ini khusus untuk Anda</p>
                </div>
                ${promoSectionHtml}
            </div>
        </section>

        ${productSectionHtml}

        ${artikelHtml}
        
        <section class="py-20 bg-gray-100">
            <div class="container mx-auto px-4 text-center">
                 <h2 class="text-3xl font-bold mb-8">Apa Kata Mereka?</h2>
                 ${testimoniHtml}
                 <button onclick="navigate('testimoni')" class="bg-white px-8 py-3 rounded-full shadow font-bold text-toyota-red hover:bg-gray-50 border border-gray-200 transition transform hover:-translate-y-1">
                    Lihat Gallery Serah Terima & Testimoni
                 </button>
            </div>
        </section>

        ${contactSectionHtml}
    </div>`;
}

// --- TRADE-IN PAGE ---
function renderTradeIn() {
    let productOptions = '<option value="">-- Pilih Mobil Baru --</option>';
    DB.products.forEach(p => { productOptions += `<option value="${p.name}">${p.name}</option>`; });
    return `<div class="bg-gray-50 pt-10 pb-20 min-h-screen page-enter-placeholder"><div class="container mx-auto px-4 max-w-3xl"><div class="text-center mb-10"><h2 class="text-3xl font-bold text-gray-800">Trade-in</h2><p class="text-gray-500 mt-2">Dapatkan penawaran harga terbaik untuk mobil lama Anda.</p></div><div class="bg-white p-8 rounded-3xl shadow-xl border border-gray-100"><form onsubmit="submitTradeIn(event)">
    <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
        <div class="md:col-span-2">
            <label class="block text-sm font-bold text-gray-700 mb-2">Mobil Lama Anda (Merk, Tipe)</label>
            <input type="text" id="trade-old-car" class="w-full p-4 bg-gray-50 rounded-xl border border-gray-200 focus:ring-2 focus:ring-toyota-red outline-none" placeholder="Contoh: Toyota Avanza G" required>
        </div>
        <div>
            <label class="block text-sm font-bold text-gray-700 mb-2">Tahun Pembuatan</label>
            <input type="number" id="trade-year" class="w-full p-4 bg-gray-50 rounded-xl border border-gray-200 focus:ring-2 focus:ring-toyota-red outline-none" placeholder="Contoh: 2018" required>
        </div>
    </div>
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6"><div><label class="block text-sm font-bold text-gray-700 mb-2">Warna Mobil</label><input type="text" id="trade-color" class="w-full p-4 bg-gray-50 rounded-xl border border-gray-200 focus:ring-2 focus:ring-toyota-red outline-none" placeholder="Contoh: Putih" required></div><div><label class="block text-sm font-bold text-gray-700 mb-2">Transmisi</label><select id="trade-transmisi" class="w-full p-4 bg-gray-50 rounded-xl border border-gray-200 focus:ring-2 focus:ring-toyota-red outline-none"><option value="Automatic">Automatic (AT)</option><option value="Manual">Manual (MT)</option></select></div></div><div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6"><div><label class="block text-sm font-bold text-gray-700 mb-2">Jarak Tempuh (KM/Odometer)</label><input type="number" id="trade-km" class="w-full p-4 bg-gray-50 rounded-xl border border-gray-200 focus:ring-2 focus:ring-toyota-red outline-none" placeholder="Contoh: 45000" required></div><div><label class="block text-sm font-bold text-gray-700 mb-2">Pajak Berlaku Sampai</label><input type="month" id="trade-pajak" class="w-full p-4 bg-gray-50 rounded-xl border border-gray-200 focus:ring-2 focus:ring-toyota-red outline-none" required><p class="text-xs text-gray-400 mt-1">Pilih Bulan & Tahun habis pajak.</p></div></div><div class="mb-6"><label class="block text-sm font-bold text-gray-700 mb-2">Rencana Ganti Ke</label><select id="trade-new-car" class="w-full p-4 bg-gray-50 rounded-xl border border-gray-200 focus:ring-2 focus:ring-toyota-red outline-none" required>${productOptions}</select></div><div class="mb-8"><label class="block text-sm font-bold text-gray-700 mb-2">Nama Anda</label><input type="text" id="trade-name" class="w-full p-4 bg-gray-50 rounded-xl border border-gray-200 focus:ring-2 focus:ring-toyota-red outline-none" placeholder="Nama Lengkap" required></div><button type="submit" class="w-full bg-green-500 hover:bg-green-600 text-white font-bold py-4 rounded-xl text-center transition shadow-lg flex items-center justify-center gap-2"><i class="fa-brands fa-whatsapp text-xl"></i> Minta Penawaran via WA</button></form></div><div class="mt-8 text-center text-gray-500 text-sm"><p>Tim kami akan segera menghubungi Anda untuk estimasi harga & inspeksi gratis.</p></div></div></div>`;
}

function submitTradeIn(e) {
    e.preventDefault();
    const oldCar = document.getElementById('trade-old-car').value;
    const year = document.getElementById('trade-year').value;
    const color = document.getElementById('trade-color').value;
    const trans = document.getElementById('trade-transmisi').value;
    const km = document.getElementById('trade-km').value;
    const pajak = document.getElementById('trade-pajak').value;
    const newCar = document.getElementById('trade-new-car').value;
    const name = document.getElementById('trade-name').value;
    const pajakDate = new Date(pajak);
    const options = { month: 'long', year: 'numeric' };
    const pajakStr = pajakDate.toLocaleDateString('id-ID', options);
    const message = `Halo ${SITE_CONFIG.sales.nama_lengkap}, saya ${name}. \nSaya mau Trade-In mobil lama saya: \n\n🚗 Mobil: ${oldCar} (${year})\n🎨 Warna: ${color} \n⚙️ Transmisi: ${trans} \n🛣️ KM: ${km} \n📅 Pajak: ${pajakStr} \n\nRencana ganti ke: *${newCar}*. \n\nMohon info estimasi harganya. Terima kasih.`;
    trackLeadAndChat('Trade In', `Tukar ${oldCar} ke ${newCar}`, message);
}

// --- RENDER PRODUCTS (SEARCH & FILTER FEATURE) ---
function renderProducts() {
    const brandName = (SITE_CONFIG.brand) ? SITE_CONFIG.brand : 'Toyota';
    let filteredProducts = DB.products;
    
    // Get Categories for dropdown
    const categories = [...new Set(DB.products.map(p => p.kategori || 'Umum'))];
    const catOptions = categories.map(c => `<option value="${c}">${c}</option>`).join('');

    return `
    <div class="bg-gray-50 pt-24 pb-20 min-h-screen page-enter-placeholder">
        <div class="container mx-auto px-4">
            <h2 class="text-3xl font-bold text-center mb-8">Daftar Harga ${brandName}</h2>
            
            <div class="bg-white p-6 rounded-2xl shadow-sm border border-gray-200 mb-10 max-w-4xl mx-auto">
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div class="relative">
                        <i class="fa-solid fa-search absolute left-4 top-3.5 text-gray-400"></i>
                        <input type="text" id="filter-search" oninput="applyProductFilter()" class="w-full pl-10 p-3 border rounded-xl focus:ring-2 focus:ring-red-500 outline-none" placeholder="Cari nama mobil...">
                    </div>
                    <div class="relative">
                         <i class="fa-solid fa-filter absolute left-4 top-3.5 text-gray-400"></i>
                         <select id="filter-category" onchange="applyProductFilter()" class="w-full pl-10 p-3 border rounded-xl focus:ring-2 focus:ring-red-500 outline-none bg-white appearance-none cursor-pointer">
                            <option value="">Semua Kategori</option>
                            ${catOptions}
                        </select>
                         <i class="fa-solid fa-chevron-down absolute right-4 top-4 text-gray-400 pointer-events-none"></i>
                    </div>
                    <div class="relative">
                        <i class="fa-solid fa-tags absolute left-4 top-3.5 text-gray-400"></i>
                        <select id="filter-price" onchange="applyProductFilter()" class="w-full pl-10 p-3 border rounded-xl focus:ring-2 focus:ring-red-500 outline-none bg-white appearance-none cursor-pointer">
                            <option value="">Semua Harga</option>
                            <option value="1">Di bawah 300 Juta</option>
                            <option value="2">300 - 600 Juta</option>
                            <option value="3">Di atas 600 Juta</option>
                        </select>
                        <i class="fa-solid fa-chevron-down absolute right-4 top-4 text-gray-400 pointer-events-none"></i>
                    </div>
                </div>
            </div>

            <div id="product-grid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                ${generateProductCards(filteredProducts)}
            </div>
            
            <div id="empty-state" class="hidden text-center py-10">
                <div class="inline-block p-4 rounded-full bg-gray-200 text-gray-500 mb-3"><i class="fa-solid fa-car-crash text-3xl"></i></div>
                <p class="text-gray-500">Mobil yang Anda cari tidak ditemukan.</p>
                <button onclick="resetFilter()" class="mt-2 text-red-600 font-bold hover:underline">Reset Filter</button>
            </div>
        </div>
    </div>`;
}

// Generate Product Cards Helper
function generateProductCards(products) {
    return products.map(p => `
        <div class="bg-white rounded-2xl shadow-md overflow-hidden hover:shadow-xl transition-all group border border-gray-100">
            <div class="relative h-56 overflow-hidden">
                <img src="${p.image}" class="w-full h-full object-cover transform group-hover:scale-110 transition duration-700" onerror="this.src='https://via.placeholder.com/400x300?text=No+Image'">
                <div class="absolute top-3 right-3 bg-white/90 backdrop-blur px-3 py-1 rounded-full text-xs font-bold text-gray-700 shadow-sm border border-gray-200">
                    ${p.kategori || 'Umum'}
                </div>
            </div>
            <div class="p-6">
                <h3 class="text-xl font-bold mb-1 text-gray-800">${p.name}</h3>
                
                <div class="flex items-center justify-between mb-5">
                    <div class="text-xs text-gray-400 font-semibold uppercase tracking-wide">Mulai Dari</div>
                    <div class="text-red-600 font-bold text-lg">${formatRupiah(p.price)}</div>
                </div>
                
                <button onclick="navigate('produk-detail', ${p.id})" class="w-full bg-gray-50 text-gray-800 py-3 rounded-xl font-bold hover:bg-gray-800 hover:text-white transition border border-gray-200">
                    Lihat Detail
                </button>
            </div>
        </div>
    `).join('');
}

// Filter Logic
function applyProductFilter() {
    const search = document.getElementById('filter-search').value.toLowerCase();
    const cat = document.getElementById('filter-category').value;
    const priceRange = document.getElementById('filter-price').value;

    const filtered = DB.products.filter(p => {
        const matchName = p.name.toLowerCase().includes(search);
        const matchCat = cat === '' || (p.kategori && p.kategori === cat);
        let matchPrice = true;
        const price = parseFloat(p.price);
        // Logic Harga: < 300, 300-600, > 600
        if (priceRange === '1') matchPrice = price < 300000000;
        else if (priceRange === '2') matchPrice = price >= 300000000 && price <= 600000000;
        else if (priceRange === '3') matchPrice = price > 600000000;

        return matchName && matchCat && matchPrice;
    });

    const grid = document.getElementById('product-grid');
    const emptyState = document.getElementById('empty-state');
    
    if (filtered.length > 0) {
        grid.innerHTML = generateProductCards(filtered);
        grid.classList.remove('hidden');
        emptyState.classList.add('hidden');
    } else {
        grid.innerHTML = '';
        grid.classList.add('hidden');
        emptyState.classList.remove('hidden');
    }
}

function resetFilter() {
    document.getElementById('filter-search').value = '';
    document.getElementById('filter-category').value = '';
    document.getElementById('filter-price').value = '';
    applyProductFilter();
}

// --- RENDER ARTIKEL LIST (FIX: Tambah Fallback) ---
// PAGINATION LOGIC INJECTED
window.changeArticlePage = (p) => { currentArticlePage = p; navigate('artikel', null, false); };

function renderArtikel() {
    const arts = DB.articles || []; if(arts.length===0) return '<div class="py-40 text-center uppercase font-black opacity-20">Belum ada artikel.</div>';
    const totalP = Math.ceil(arts.length / ARTICLES_PER_PAGE);
    const paginated = arts.slice((currentArticlePage-1)*ARTICLES_PER_PAGE, currentArticlePage*ARTICLES_PER_PAGE);

    const cards = paginated.map(a => `
        <div onclick="navigate('artikel-detail', ${a.id})" class="cursor-pointer group bg-white rounded-3xl overflow-hidden border border-gray-100 shadow-sm hover:shadow-xl transition-all">
            <img src="${a.image}" class="h-56 w-full object-cover group-hover:scale-110 transition duration-700" onerror="this.src='assets/images/no-image.jpg'">
            <div class="p-8">
                <span class="text-[10px] font-bold text-gray-400 uppercase tracking-widest">${a.date}</span>
                <h3 class="text-xl font-bold text-slate-800 line-clamp-2 mt-2 uppercase tracking-tighter">${a.title}</h3>
            </div>
        </div>`).join('');

    let pagUI = ''; if (totalP > 1) {
        pagUI = `<div class="flex justify-center gap-2 mt-12">`;
        for (let i = 1; i <= totalP; i++) pagUI += `<button onclick="changeArticlePage(${i})" class="w-12 h-12 rounded-2xl font-black transition ${i === currentArticlePage ? 'bg-toyota-red text-white shadow-lg' : 'bg-white border text-gray-400 hover:bg-gray-50'}">${i}</button>`;
        pagUI += `</div>`;
    }
    return `<div class="bg-gray-50 pt-24 pb-20 min-h-screen page-enter-placeholder"><div class="container mx-auto px-4"><h2 class="text-5xl font-black text-center mb-16 tracking-tighter uppercase">Berita & Tips</h2><div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">${cards}</div>${pagUI}</div></div>`;
}

// --- RENDER TESTIMONI LIST (FIX: Tambah Fallback) ---
function renderTestimoni() {
    const testimonials = (DB.testimonials && Array.isArray(DB.testimonials)) ? DB.testimonials : [];

    if (testimonials.length === 0) {
        return `
        <div class="bg-white pt-24 pb-20 min-h-screen page-enter-placeholder">
            <div class="container mx-auto px-4 text-center">
                <h2 class="text-3xl font-bold text-center mb-12">Gallery Serah Terima & Testimoni</h2>
                <div class="p-10 bg-gray-50 rounded-3xl border border-dashed border-gray-300 inline-block">
                    <p class="text-gray-400 text-lg">Belum ada testimoni saat ini.</p>
                </div>
            </div>
        </div>`;
    }

    return `
    <div class="bg-white pt-10 pb-20 min-h-screen page-enter-placeholder">
        <div class="container mx-auto px-4">
            <h2 class="text-3xl font-bold text-center mb-12">Gallery Serah Terima & Testimoni</h2>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                 ${testimonials.map(t=>`<div class="bg-gray-50 rounded-2xl overflow-hidden shadow-md hover:shadow-xl transition"><div class="h-64 overflow-hidden relative group"><img src="${t.delivery_photo}" class="w-full h-full object-cover transform group-hover:scale-110 transition duration-700"><div class="absolute bottom-0 left-0 bg-toyota-red text-white text-xs px-3 py-1 font-bold">Delivery</div></div><div class="p-6"><div class="flex text-yellow-400 mb-2 text-sm"><i class="fa-solid fa-star"></i><i class="fa-solid fa-star"></i><i class="fa-solid fa-star"></i><i class="fa-solid fa-star"></i><i class="fa-solid fa-star"></i></div><p class="text-gray-700 italic mb-4">"${t.text}"</p><h4 class="font-bold text-toyota-dark">${t.name}</h4><p class="text-xs text-gray-500 uppercase">Unit: ${t.car}</p></div></div>`).join('')}
            </div>
        </div>
    </div>`;
}

// --- RENDER PROMO LIST (FIX: Grid 3 Kolom + Autoplay Mute) ---
function renderPromo() {
    const promos = (DB.promos && Array.isArray(DB.promos)) ? DB.promos : [];

    if (promos.length === 0) {
        return `
        <div class="bg-gray-50 pt-24 pb-20 min-h-screen page-enter-placeholder">
            <div class="container mx-auto px-4 text-center">
                <h2 class="text-3xl font-bold text-center mb-12">Promo Spesial Bulan Ini</h2>
                <div class="p-10 bg-white rounded-3xl border border-dashed border-gray-300 inline-block">
                    <p class="text-gray-400 text-lg">Belum ada promo aktif saat ini.</p>
                </div>
            </div>
        </div>`;
    }

    return `<div class="bg-gray-50 pt-10 pb-20 min-h-screen page-enter-placeholder">
        <div class="container mx-auto px-4">
            <h2 class="text-3xl font-bold text-center mb-12">Promo Spesial Bulan Ini</h2>
            
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                ${promos.map(p => {
                    // LIST PROMO: AUTOPLAY = TRUE, SOUND = FALSE
                    const media = getMediaHtml(p.video || p.image || p.gambar_url, "w-full h-full object-cover", true, false);

                    return `
                    <div class="bg-white rounded-2xl shadow-lg overflow-hidden group border border-gray-100 hover:shadow-2xl transition hover:-translate-y-1 flex flex-col">
                        <div class="h-56 relative bg-black">
                            ${media}
                             <div class="absolute top-4 right-4 bg-toyota-red text-white text-xs font-bold px-3 py-1 rounded-full shadow">Promo</div>
                        </div>
                        <div class="p-6 flex flex-col flex-1">
                            <h3 class="text-xl font-bold mb-4 line-clamp-2">${p.title || p.judul}</h3>
                            <div class="mt-auto">
                                <button onclick="navigate('promo-detail', ${p.id})" class="w-full border-2 border-toyota-red text-toyota-red font-bold py-2 rounded-lg hover:bg-toyota-red hover:text-white transition">Lihat Selengkapnya</button>
                            </div>
                        </div>
                    </div>`;
                }).join('')}
            </div>
        </div>
    </div>`;
}

function renderProductDetail(id) {
    const p = DB.products.find(x => x.id == id);
    if (!p) return `<div class="p-20 text-center">Produk tidak ditemukan</div>`;
    let varianTableHtml = ''; let variants = []; try { if(p.varian) variants = typeof p.varian === 'string' ? JSON.parse(p.varian) : p.varian; } catch(e) {}
    if (Array.isArray(variants) && variants.length > 0) {
        const rows = variants.map(v => `<tr class="border-b hover:bg-gray-50 last:border-0 transition duration-150"><td class="py-3 px-4 text-gray-700 font-medium">${v.nama}</td><td class="py-3 px-4 text-right font-bold text-toyota-red">${formatRupiah(v.harga)}</td></tr>`).join('');
        varianTableHtml = `<div class="mt-8 mb-8 animate-[fadeIn_0.5s_ease-out]"><h3 class="text-lg font-bold text-gray-800 mb-3 border-l-4 border-toyota-red pl-3 uppercase tracking-wide">Daftar Tipe & Harga</h3><div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden"><table class="w-full text-sm"><thead class="bg-gray-100 text-gray-500 uppercase text-xs tracking-wider font-semibold"><tr><th class="py-3 px-4 text-left">Tipe / Varian</th><th class="py-3 px-4 text-right">Harga OTR</th></tr></thead><tbody>${rows}</tbody></table></div></div>`;
    }
    let brosurBtn = '';
    if (p.brochure) {
        brosurBtn = `<a href="${p.brochure}" target="_blank" class="w-full bg-red-100 text-red-600 py-4 rounded-xl font-bold shadow-sm hover:bg-red-200 flex items-center justify-center gap-2 transform hover:-translate-y-1 transition border border-red-200"><i class="fa-solid fa-file-pdf text-xl"></i> Download E-Brosur</a>`;
    }
    
    // FIX: Gunakan getMediaHtml untuk video di detail produk
    const videoHtml = p.video ? `<div class="rounded-2xl overflow-hidden shadow-lg border border-gray-200 h-64 md:h-80">${getMediaHtml(p.video, "w-full h-full", false)}</div>` : '';

    return `<div class="bg-white pt-8 pb-20 min-h-screen page-enter-placeholder"><div class="container mx-auto px-4"><button onclick="navigate('produk')" class="mb-6 text-gray-500 hover:text-toyota-red flex items-center gap-2 group"><i class="fa-solid fa-arrow-left group-hover:-translate-x-1 transition"></i> Kembali</button><div class="grid grid-cols-1 lg:grid-cols-2 gap-12 items-start"><div class="lg:sticky lg:top-24"><div class="relative rounded-3xl overflow-hidden shadow-2xl mb-6 group"><img src="${p.image}" class="w-full object-cover transform group-hover:scale-105 transition duration-700"></div>${videoHtml}</div><div><h1 class="text-4xl md:text-5xl font-extrabold text-toyota-dark mb-2 leading-tight">${p.name}</h1><div class="flex items-center gap-2 mb-6"><span class="px-3 py-1 bg-gray-100 text-gray-600 rounded-full text-xs font-bold uppercase">Mulai Dari</span><p class="text-3xl text-toyota-red font-bold">${formatRupiah(p.price)}</p></div><div class="mb-8 space-y-3"><button onclick="navigate('simulasi')" class="w-full bg-green-500 text-white py-4 rounded-xl font-bold mb-4 shadow hover:bg-green-600 flex items-center justify-center gap-2 transform hover:-translate-y-1 transition"><i class="fa-solid fa-calculator"></i> Simulasi Kredit</button><button onclick="trackLeadAndChat('Produk Detail', '${p.name}', 'Halo, saya tertarik dengan ${p.name}')" class="w-full bg-toyota-dark text-white py-4 rounded-xl font-bold shadow hover:bg-black flex items-center justify-center gap-2 transform hover:-translate-y-1 transition"><i class="fa-brands fa-whatsapp"></i> Hubungi Sales</button>${brosurBtn}</div>${varianTableHtml}<div class="text-gray-600 mb-6 bg-gray-50 p-6 rounded-2xl border border-gray-100 leading-relaxed">${p.desc || 'Belum ada deskripsi.'}</div></div></div></div></div>`;
}

function renderSimulasi() {
    let productOptions = '';
    DB.products.forEach(p => {
        let variants = []; try { if (p.varian) variants = typeof p.varian === 'string' ? JSON.parse(p.varian) : p.varian; } catch(e) {}
        if (Array.isArray(variants) && variants.length > 0) {
            productOptions += `<optgroup label="${p.name}">`;
            variants.forEach(v => { productOptions += `<option value="${p.id}" data-price="${v.harga}">${p.name} - ${v.nama}</option>`; });
            productOptions += `</optgroup>`;
        } else {
            productOptions += `<option value="${p.id}" data-price="${p.price}">${p.name}</option>`;
        }
    });

    const activeTenors = CREDIT.tenors.filter(t => String(t.is_active) === '1');
    activeTenors.sort((a,b) => a.tenor_tahun - b.tenor_tahun);
    const tenorOptions = activeTenors.map(t => `<option value="${t.tenor_tahun}">${t.tenor_tahun} Tahun</option>`).join('');
    
    return `<div class="bg-gray-50 pt-10 pb-20 min-h-screen page-enter-placeholder"><div class="container mx-auto px-4 max-w-4xl"><h2 class="text-3xl font-bold text-center mb-12">Simulasi Kredit Cerdas</h2><div class="grid grid-cols-1 md:grid-cols-2 gap-8"><div class="bg-white p-8 rounded-3xl shadow-xl border border-gray-100"><form oninput="calcSimulasi()"><div class="mb-6"><label class="block text-sm font-bold text-gray-700 mb-2">Pilih Tipe Mobil</label><select id="sim-model" class="w-full p-4 bg-gray-50 rounded-xl border border-gray-200 focus:ring-2 focus:ring-toyota-red outline-none cursor-pointer"><option value="" data-price="0">-- Pilih Mobil --</option>${productOptions}</select></div><div class="mb-6"><label class="block text-sm font-bold text-gray-700 mb-2">Harga OTR</label><input type="text" id="sim-price-display" class="w-full p-4 bg-gray-100 rounded-xl border border-gray-200 text-gray-500 font-bold" readonly placeholder="Rp 0"></div><div class="mb-6"><div class="flex justify-between mb-2"><label class="block text-sm font-bold text-gray-700">DP Murni (%)</label><span id="dp-label" class="font-bold text-toyota-red">20%</span></div><input type="range" id="sim-dp" min="20" max="80" step="5" value="20" class="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-toyota-red"></div><div class="mb-6"><label class="block text-sm font-bold text-gray-700 mb-2">Tenor</label><select id="sim-tenor" onchange="calcSimulasi()" class="w-full p-4 bg-gray-50 rounded-xl border border-gray-200 focus:ring-2 focus:ring-toyota-red outline-none cursor-pointer">${tenorOptions}</select></div></form></div><div class="bg-toyota-dark text-white p-8 rounded-3xl shadow-xl flex flex-col justify-between relative overflow-hidden"><div class="absolute top-0 right-0 w-64 h-64 bg-toyota-red opacity-10 rounded-full blur-3xl -mr-16 -mt-16 pointer-events-none"></div><div class="flex flex-col justify-center h-full"><h3 class="text-xl font-bold text-gray-400 mb-8 uppercase tracking-widest">Hasil Simulasi</h3><div class="mb-8"><p class="text-sm text-gray-400 mb-1">Total Uang Muka (TDP)</p><p id="res-dp" class="text-4xl font-bold text-white">Rp 0</p></div><div class="mb-4"><p class="text-sm text-gray-400 mb-1">Angsuran per Bulan</p><p id="res-monthly" class="text-3xl md:text-4xl font-extrabold text-toyota-red">Rp 0</p></div></div><a id="wa-link" href="#" onclick="trackLeadAndChat('Simulasi', 'General', 'Halo')" target="_blank" class="w-full block bg-green-500 hover:bg-green-600 text-white font-bold py-4 rounded-xl text-center transition shadow-lg flex items-center justify-center gap-2"><i class="fa-brands fa-whatsapp text-xl"></i> Ajukan Sekarang</a></div></div></div></div>`;
}

function calcSimulasi() {
    const sel = document.querySelector('#sim-model option:checked');
    if(!sel) return;
    const price = parseFloat(sel.dataset.price) || 0;
    const dpP = document.getElementById('sim-dp').value;
    const tenor = parseInt(document.getElementById('sim-tenor').value);
    document.getElementById('sim-price-display').value = formatRupiah(price);
    document.getElementById('dp-label').innerText = dpP + "%";
    if (price === 0) return;
    
    // FETCH RATE ASURANSI & LAINNYA
    const rateData = CREDIT.tenors.find(t => parseInt(t.tenor_tahun) === tenor);
    const bungaFlat = rateData ? parseFloat(rateData.bunga_per_tahun) : 0.05;
    const rateACP = rateData ? parseFloat(rateData.rate_acp) : 0; 
    const biayaAdmin = rateData ? parseFloat(rateData.biaya_admin) : 2500000;
    
    let rateAsuransi = 0.025; // Default fallback
    if (CREDIT.insurance && Array.isArray(CREDIT.insurance)) {
        const insFound = CREDIT.insurance.find(ins => price >= parseFloat(ins.min_price) && price <= parseFloat(ins.max_price));
        if (insFound) {
            const key = 'tenor_' + tenor;
            if (insFound[key]) rateAsuransi = parseFloat(insFound[key]) / 100;
        }
    }
    
    const rateProvisi = parseFloat(CREDIT.umum.rate_provisi);
    const biayaFiducia = parseFloat(CREDIT.umum.biaya_fiducia);

    // LOGIKA HITUNG BARU:
    // 1. DP Murni
    const dpMurni = price * (dpP / 100);
    
    // 2. Base Hutang
    const baseHutang = price - dpMurni;
    
    // 3. Biaya Kapitalisasi
    const biayaAsuransi = price * rateAsuransi;
    const biayaACP = baseHutang * rateACP * tenor; // Biaya ACP Total
    const biayaProvisi = baseHutang * rateProvisi;

    // 4. Bunga Total (Dari Pokok + Asuransi)
    const pokokBunga = baseHutang + biayaAsuransi;
    const totalBunga = pokokBunga * bungaFlat * tenor;

    // 5. Total Hutang (Plafon Kredit) = PH Awal + Bunga + ACP + Provisi
    const plafonKredit = baseHutang + totalBunga + biayaACP + biayaProvisi;
    
    // 6. Angsuran = Plafon / Tenor Bulan
    const angsuran = plafonKredit / (tenor * 12);
    
    // 7. TDP = DP Murni + Admin + Fiducia
    const tdp = dpMurni + biayaAdmin + biayaFiducia; 
    
    document.getElementById('res-dp').innerText = formatRupiah(roundUpToThousand(tdp));
    document.getElementById('res-monthly').innerText = formatRupiah(roundUpToThousand(angsuran)) + " x " + (tenor * 12);
    
    const model = sel.text.trim();
    const wa = `Halo ${SITE_CONFIG.sales.nama_lengkap}, simulasi kredit ${model}.\nHarga: ${formatRupiah(price)}\nDP: ${dpP}%\nTenor: ${tenor} Thn\n\n*Estimasi:*\nTDP: ${formatRupiah(roundUpToThousand(tdp))}\nAngsuran: ${formatRupiah(roundUpToThousand(angsuran))}`;
    document.getElementById('wa-link').onclick = () => trackLeadAndChat('Simulasi', model, wa);
}


function renderPromoDetail(id){
    const p=DB.promos.find(x=>x.id==id);
    if(!p)return renderPromo();
    
    // DETAIL PROMO: AUTOPLAY = TRUE, SOUND = TRUE (SUARA AKTIF)
    const mediaHtml = getMediaHtml(p.video || p.image || p.gambar_url, "w-full rounded-xl shadow-lg", true, true);
    
    return`<div class="bg-white pt-10 pb-20 min-h-screen page-enter-placeholder"><div class="container mx-auto px-4 max-w-3xl"><button onclick="navigate('promo')" class="mb-6 text-gray-500"><i class="fa-solid fa-arrow-left"></i> Kembali</button><h1 class="text-3xl font-bold mb-6">${p.title||p.judul}</h1><div class="rounded-2xl overflow-hidden shadow-2xl mb-8">${mediaHtml}</div><div class="prose max-w-none text-gray-700"><p class="text-lg">${p.desc||p.deskripsi} Segera manfaatkan promo ini. Berlaku terbatas! Hubungi ${SITE_CONFIG.sales.nama_lengkap} sekarang juga.</p></div></div></div>`;
}

function renderArtikelDetail(id){const a=DB.articles.find(x=>x.id==id);if(!a)return`<div class="p-20 text-center">Artikel tidak ditemukan</div>`;return`<div class="bg-white pt-10 pb-20 min-h-screen page-enter-placeholder"><div class="container mx-auto px-4 max-w-3xl"><button onclick="navigate('artikel')" class="mb-6 text-gray-500"><i class="fa-solid fa-arrow-left"></i> Kembali</button><h1 class="text-3xl font-bold mb-4">${a.title}</h1><img src="${a.image}" class="w-full rounded-2xl shadow-lg mb-8"><div class="prose max-w-none text-gray-700 leading-loose">${a.content}</div></div></div>`;}
function renderKontak(){
    // UPDATE KONTAK DENGAN SOSMED (SUDAH DIPASTIKAN ADA)
    let sosmedHtml = '';
    const s = SITE_CONFIG.sales;
    if(s.youtube_url || s.instagram_url || s.tiktok_url || s.facebook_url) {
        sosmedHtml += '<div class="grid grid-cols-4 md:grid-cols-2 gap-4 mt-6 md:w-32">';
        if(s.youtube_url) sosmedHtml += `<a href="${s.youtube_url}" target="_blank" class="w-10 h-10 rounded-full bg-gray-800 flex items-center justify-center text-gray-400 hover:text-white hover:bg-red-600 transition shadow-lg border border-gray-700"><i class="fa-brands fa-youtube text-lg"></i></a>`;
        if(s.instagram_url) sosmedHtml += `<a href="${s.instagram_url}" target="_blank" class="w-10 h-10 rounded-full bg-gray-800 flex items-center justify-center text-gray-400 hover:text-white hover:bg-pink-600 transition shadow-lg border border-gray-700"><i class="fa-brands fa-instagram text-lg"></i></a>`;
        if(s.tiktok_url) sosmedHtml += `<a href="${s.tiktok_url}" target="_blank" class="w-10 h-10 rounded-full bg-gray-800 flex items-center justify-center text-gray-400 hover:text-white hover:bg-black transition shadow-lg border border-gray-700"><i class="fa-brands fa-tiktok text-lg"></i></a>`;
        if(s.facebook_url) sosmedHtml += `<a href="${s.facebook_url}" target="_blank" class="w-10 h-10 rounded-full bg-gray-800 flex items-center justify-center text-gray-400 hover:text-white hover:bg-blue-600 transition shadow-lg border border-gray-700"><i class="fa-brands fa-facebook-f text-lg"></i></a>`;
        sosmedHtml += '</div>';
    }

    return `
    <div class="bg-white pt-10 pb-20 min-h-screen page-enter-placeholder">
        <div class="container mx-auto px-4 max-w-5xl">
            <div class="bg-gradient-to-br from-toyota-dark to-black rounded-[2.5rem] p-12 shadow-2xl mb-12 text-white flex flex-col md:flex-row items-center gap-10 relative overflow-hidden">
                <img src="${s.foto_profil_url}" class="w-48 h-48 rounded-full border-4 border-toyota-red object-cover relative z-10">
                <div class="flex-1 relative z-10">
                    <h2 class="text-4xl font-bold mb-1">${s.nama_lengkap}</h2>
                    <p class="text-toyota-red font-bold text-xl uppercase tracking-wider">${s.jabatan}</p>
                    <p class="mt-4 text-gray-300">${SITE_CONFIG.nama_cabang}</p>
                    <div class="flex gap-4 mt-6">
                        <a href="tel:${s.no_wa}" class="bg-white text-toyota-dark px-6 py-2 rounded-full font-bold hover:bg-gray-200 transition">Telepon</a>
                        <button onclick="trackLeadAndChat('Kontak', 'General', 'Halo ${s.nama_lengkap}, saya mau tanya info Toyota.')" class="bg-green-500 text-white px-6 py-2 rounded-full font-bold hover:bg-green-600 transition">WhatsApp</button>
                    </div>
                </div>
                ${sosmedHtml}
                
                <div class="absolute top-0 right-0 w-64 h-64 bg-toyota-red opacity-10 rounded-full blur-3xl -mr-16 -mt-16 pointer-events-none"></div>
            </div>
            <div class="rounded-3xl overflow-hidden h-96 shadow-lg">
                <iframe src="${SITE_CONFIG.google_map_embed}" width="100%" height="100%" style="border:0;" allowfullscreen="" loading="lazy"></iframe>
            </div>
        </div>
    </div>`;
}

window.toggleMobileMenu=function(){document.getElementById('mobile-menu').classList.toggle('hidden');}
window.mobileNavClick=function(route){navigate(route);}

// URL PARAMETER HANDLING (Sitemap Support)
window.addEventListener('load', () => {
    initFloatingButton(); // ADDED: Init Floating Button
    const urlParams = new URLSearchParams(window.location.search);
    const page = urlParams.get('page');
    const id = urlParams.get('id');

    setTimeout(() => {
        document.getElementById('loader').style.opacity = '0';
        setTimeout(() => {
            document.getElementById('loader').style.display = 'none';
            if (page) { navigate(page, id); } else { navigate('home'); }
        }, 400);
    }, 500);
});