// 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;
const BASE_URL    = window.SITE_BASE_URL  || '';
const PAGE_TITLES = window.PAGE_TITLES    || {};
const PAGE_DESCS  = window.PAGE_DESCS     || {};
const TAHUN       = window.TAHUN          || new Date().getFullYear();


// =========================================================
// DESIGN TOKENS — Nilai konsisten untuk seluruh aplikasi
// Radius : card=rounded-2xl | btn=rounded-xl | chip=rounded-full | input=rounded-xl
// Shadow : card=shadow-md hover:shadow-xl | featured=shadow-xl | overlay=shadow-2xl
// Spacing: section py-20 | page pt-20 pb-24 | inner gap-8
// =========================================================
const DT = {
    card:    'bg-white rounded-2xl shadow-md border border-gray-100',
    cardHov: 'hover:shadow-xl hover:-translate-y-1 transition-all duration-300',
    btn:     'rounded-xl font-bold transition-all duration-200 active:scale-95',
    btnRed:  'bg-toyota-red text-white rounded-xl font-bold hover:bg-red-700 transition-all duration-200 active:scale-95 shadow',
    btnDark: 'bg-toyota-dark text-white rounded-xl font-bold hover:bg-black transition-all duration-200 active:scale-95 shadow',
    btnWA:   'bg-[#25D366] text-white rounded-xl font-bold hover:bg-[#1ebe5d] transition-all duration-200 active:scale-95 shadow',
    btnOut:  'border-2 border-toyota-red text-toyota-red rounded-xl font-bold hover:bg-toyota-red hover:text-white transition-all duration-200 active:scale-95',
    btnGhost:'bg-white/10 backdrop-blur-md border border-white/30 text-white rounded-full font-bold hover:bg-white hover:text-toyota-dark transition-all duration-200',
    input:   'w-full p-4 bg-gray-50 rounded-xl border border-gray-200 focus:ring-2 focus:ring-toyota-red outline-none transition',
    pageWrap:'min-h-screen pt-20 pb-24 bg-gray-50 page-enter-placeholder',
    secHdr:  (eyebrow, title, subtitle='') => `<div class="text-center mb-12">
        ${eyebrow ? `<span class="inline-block text-toyota-red font-bold tracking-widest text-xs uppercase mb-2">${eyebrow}</span>` : ''}
        <h2 class="text-3xl md:text-4xl font-bold text-gray-900">${title}</h2>
        ${subtitle ? `<p class="text-gray-500 mt-3 max-w-xl mx-auto">${subtitle}</p>` : ''}
    </div>`,
    emptyState: (icon, msg, btnLabel='', btnRoute='') => `
        <div class="flex flex-col items-center justify-center py-20 text-center">
            <div class="w-20 h-20 rounded-full bg-gray-100 flex items-center justify-center mb-5">
                <i class="fa-solid ${icon} text-3xl text-gray-400" aria-hidden="true"></i>
            </div>
            <p class="text-gray-500 font-medium mb-4">${msg}</p>
            ${btnLabel ? `<button onclick="navigate('${btnRoute}')" class="text-toyota-red font-bold hover:underline text-sm">${btnLabel} →</button>` : ''}
        </div>`,
};

let currentArticlePage = 1;
const ARTICLES_PER_PAGE = 6;

// =========================================================
// 2. SEO: UPDATE META PADA SETIAP NAVIGASI SPA
// =========================================================
function updatePageSEO(route, id) {
    let title = PAGE_TITLES[route] || PAGE_TITLES['home'];
    let desc  = PAGE_DESCS[route]  || PAGE_DESCS['home'];
    let canonical = BASE_URL + '/';
    const brand = SITE_CONFIG.brand || 'Mobil';
    const kota  = SITE_CONFIG.kota  || '';

    if (route === 'produk-detail' && id) {
        const p = DB.products.find(x => x.id == id);
        if (p) {
            title = 'Harga ' + p.name + ' ' + TAHUN + ' ' + kota + ' | ' + SITE_CONFIG.nama_cabang;
            desc  = 'Promo ' + p.name + ' DP ringan cicilan terjangkau di ' + SITE_CONFIG.nama_cabang + '. Stok ready, proses cepat.';
            canonical = BASE_URL + '/index.php?page=produk-detail&id=' + id;
        }
    } else if (route === 'artikel-detail' && id) {
        const a = DB.articles.find(x => x.id == id);
        if (a) {
            title = a.title + ' | ' + SITE_CONFIG.nama_cabang;
            const raw = a.content ? a.content.replace(/<[^>]+>/g, '') : '';
            desc = raw.substring(0, 155) + '...';
            canonical = BASE_URL + '/index.php?page=artikel-detail&id=' + id;
        }
    } else if (route === 'promo-detail' && id) {
        const pr = DB.promos.find(x => x.id == id);
        if (pr) {
            title = (pr.title || pr.judul) + ' | Promo ' + brand + ' | ' + SITE_CONFIG.nama_cabang;
            const raw = (pr.desc || pr.deskripsi || '').replace(/<[^>]+>/g, '');
            desc = raw.substring(0, 155) + '...';
            canonical = BASE_URL + '/index.php?page=promo-detail&id=' + id;
        }
    } else if (route !== 'home') {
        canonical = BASE_URL + '/index.php?page=' + route;
    }

    document.title = title;
    const metaDesc = document.querySelector('meta[name="description"]');
    if (metaDesc) metaDesc.setAttribute('content', desc);
    const ogTitle  = document.querySelector('meta[property="og:title"]');
    if (ogTitle) ogTitle.setAttribute('content', title);
    const ogDesc   = document.querySelector('meta[property="og:description"]');
    if (ogDesc) ogDesc.setAttribute('content', desc);
    const ogUrl    = document.querySelector('meta[property="og:url"]');
    if (ogUrl) ogUrl.setAttribute('content', canonical);
    const twTitle  = document.querySelector('meta[name="twitter:title"]');
    if (twTitle) twTitle.setAttribute('content', title);
    const twDesc   = document.querySelector('meta[name="twitter:description"]');
    if (twDesc) twDesc.setAttribute('content', desc);
    let canonicalTag = document.querySelector('link[rel="canonical"]');
    if (!canonicalTag) { canonicalTag = document.createElement('link'); canonicalTag.rel = 'canonical'; document.head.appendChild(canonicalTag); }
    canonicalTag.href = canonical;

    // GA4 SPA page_view tracking
    sendPageView(canonical);
}

// =========================================================
// 3. GOOGLE ADS & ANALYTICS
// =========================================================
function sendPageView(path) {
    if (typeof gtag !== 'function') return;
    gtag('event', 'page_view', {
        page_path: path,
        page_location: window.location.href,
        page_title: document.title
    });
}

function fireTrackingEvents(sourceRoute) {
    if (typeof gtag !== 'function') return;

    // GA4 generate_lead event
    gtag('event', 'generate_lead', {
        method: 'whatsapp',
        source_button: sourceRoute,
        transport_type: 'beacon',
        value: 1
    });

    // Google Ads conversion
    if (SITE_CONFIG && SITE_CONFIG.google_ads_wa_tag) {
        const adsTag = SITE_CONFIG.google_ads_wa_tag.trim();
        if (adsTag !== '') {
            gtag('event', 'conversion', { send_to: adsTag });
        }
    }
}

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

/**
 * Escape HTML untuk mencegah XSS saat render data dari DB ke DOM.
 */
function escapeHtml(str) {
    if (str === null || str === undefined) return '';
    return String(str)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

function roundUpToThousand(num) { return Math.ceil(num / 1000) * 1000; }

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();
}

function getMediaHtml(src, className = "w-full h-full object-cover", autoplay = false, soundOn = false, altText = "") {
    if (!altText) altText = 'Media ' + (SITE_CONFIG.brand || 'Kendaraan');
    if (!src) return `<img src="assets/images/no-image.jpg" class="${className}" alt="Gambar tidak tersedia" width="800" height="600" loading="lazy">`;
    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) {
        const vId = extractYoutubeId(src);
        let params = '?rel=0';
        if (autoplay) { const m = soundOn ? '0' : '1'; params = `?autoplay=1&mute=${m}&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 title="${altText}" loading="lazy" allow="autoplay; encrypted-media"></iframe>`;
    } else if (isVideoFile) {
        const mutedAttr    = (autoplay && !soundOn) ? 'muted' : '';
        const autoplayAttr = autoplay ? 'autoplay loop playsinline' : 'controls';
        return `<video class="${className}" ${autoplayAttr} ${mutedAttr} aria-label="${altText}"><source src="${src}" type="video/mp4">Browser Anda tidak mendukung tag video.</video>`;
    } else {
        return `<img src="${src}" class="${className}" alt="${altText}" width="800" height="450" loading="lazy" onerror="this.src='https://via.placeholder.com/800x600?text=Image+Error'">`;
    }
}

// Lead Tracker + WA — dengan visual feedback pada tombol
function trackLeadAndChat(source, detail, message, btnEl) {
    const sourceLabel = `Button: ${source} - ${detail}`;
    fireTrackingEvents(sourceLabel);

    // Visual feedback: tampilkan spinner pada tombol yang diklik
    if (btnEl) {
        const origHtml = btnEl.innerHTML;
        btnEl.disabled = true;
        btnEl.innerHTML = '<i class="fa-solid fa-spinner fa-spin mr-2"></i> Menghubungkan...';
        setTimeout(() => { if (btnEl) { btnEl.disabled = false; btnEl.innerHTML = origHtml; } }, 2500);
    }

    const formData = new FormData();
    formData.append('source', source);
    formData.append('detail', detail);
    fetch('api.php?action=track_lead', { method: 'POST', body: formData }).catch(() => {});

    setTimeout(() => {
        window.open(`https://wa.me/${SITE_CONFIG.sales.no_wa}?text=${encodeURIComponent(message)}`, '_blank', 'noopener,noreferrer');
    }, 400);
}

// Floating WA Button
function initFloatingButton() {
    if (document.getElementById('floating-wa')) return;
    const btn = document.createElement('a');
    btn.id = 'floating-wa';
    btn.href = 'javascript:void(0)';
    btn.target = '_blank';
    btn.rel = 'noopener noreferrer';
    btn.setAttribute('aria-label', 'Hubungi Sales via WhatsApp');
    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" aria-hidden="true"></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" aria-hidden="true">
            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;
    const brand = SITE_CONFIG.brand || 'Mobil';
    let msg = `Halo ${sName}, saya melihat website ${brand} dan ingin info lebih lanjut.`;
    if (route === 'home')            msg = `Halo ${sName}, saya mau tanya info mengenai mobil ${brand}.`;
    else if (route === 'produk')     msg = `Halo ${sName}, boleh minta Pricelist ${brand} terbaru?`;
    else if (route === 'produk-detail' && id) { const p = DB.products.find(x => x.id == id); if (p) msg = `Halo ${sName}, saya tertarik dengan *${brand} ${escapeHtml(p.name)}*.\nApakah ada stok ready atau promo khusus?`; }
    else if (route === 'promo')      msg = `Halo ${sName}, info dong promo ${brand} 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: *${escapeHtml(p.title || p.judul)}*.\nBagaimana syaratnya?`; }
    else if (route === 'simulasi')   msg = `Halo ${sName}, tolong bantu hitungkan simulasi kredit ${brand} 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 "${escapeHtml(a.title)}". Mau tanya info terkait.`; }
    else if (route === 'testimoni')  msg = `Halo ${sName}, saya lihat testimoni customer. Saya juga berminat ambil unit ${brand}.`;
    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)}`;
    btn.onclick = () => {
        fireTrackingEvents('Floating WA - ' + route);
        const fd = new FormData(); fd.append('source', 'Floating WA'); fd.append('detail', route);
        fetch('api.php?action=track_lead', { method: 'POST', body: fd });
    };
}

// Countdown Timer
let countdownInterval;
function initCountdown() {
    if (countdownInterval) clearInterval(countdownInterval);
    const timerEls = document.querySelectorAll('.promo-timer');
    if (!timerEls.length) return;
    countdownInterval = setInterval(() => {
        timerEls.forEach(el => {
            const dist = new Date(el.dataset.expired).getTime() - Date.now();
            if (dist < 0) { el.innerHTML = '<span class="text-red-600 font-bold bg-red-100 px-2 py-1 rounded">PROMO BERAKHIR</span>'; return; }
            const d = Math.floor(dist / 86400000);
            const h = Math.floor((dist % 86400000) / 3600000);
            const m = Math.floor((dist % 3600000) / 60000);
            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" role="timer" aria-live="polite"><i class="fa-regular fa-clock fa-spin" aria-hidden="true"></i><span>Sisa Waktu: ${d} Hari ${h} Jam ${m} Mnt</span></div>`;
        });
    }, 1000);
}

// =========================================================
// 5. ENGINE NAVIGASI (SPA)
// =========================================================
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');
    updatePageSEO(route, id);
    if (updateUrl) {
        let newUrl = '?page=' + route;
        if (id) newUrl += '&id=' + id;
        if (route === 'home') newUrl = window.location.pathname;
        window.history.pushState({ route, id }, document.title, newUrl);
    }
    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 = renderNotFound(route);
    }
    html = html.replace('page-enter-placeholder', enterClass);
    app.innerHTML = html;
    currentRouteIndex = targetIndex;
    initCountdown();
    // Restore state form simulasi jika kembali ke halaman simulasi
    if (route === 'simulasi') {
        try {
            const m = sessionStorage.getItem('sim_model');
            const d = sessionStorage.getItem('sim_dp');
            const t = sessionStorage.getItem('sim_tenor');
            if (m) { const el = document.getElementById('sim-model'); if(el) el.value = m; }
            if (d) { const el = document.getElementById('sim-dp');    if(el) el.value = d; document.getElementById('dp-label').innerText = d + '%'; }
            if (t) { const el = document.getElementById('sim-tenor'); if(el) el.value = t; }
            if (m || d || t) calcSimulasi();
        } catch(e) {}
    }
}

window.addEventListener('popstate', (e) => {
    if (e.state) navigate(e.state.route, e.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 oc = btn.getAttribute('onclick') || '';
        btn.classList.remove('text-toyota-red', 'border-toyota-red');
        btn.classList.add('border-transparent');
        if (oc.includes(`'${activeKey}'`)) { btn.classList.add('text-toyota-red', 'border-toyota-red'); btn.classList.remove('border-transparent'); }
    });
    document.querySelectorAll('.mobile-link').forEach(btn => {
        const oc = btn.getAttribute('onclick') || '';
        btn.classList.remove('text-toyota-red');
        if (oc.includes(`'${activeKey}'`)) btn.classList.add('text-toyota-red');
    });
}


// =========================================================
// 6. RENDER FUNCTIONS
// =========================================================

// ---- SECTION HEADER HELPER ----
function secHdr(eyebrow, title, subtitle='') {
    return `<div class="text-center mb-12">
        ${eyebrow ? `<span class="inline-block text-toyota-red font-bold tracking-widest text-xs uppercase mb-2 px-3 py-1 bg-red-50 rounded-full">${eyebrow}</span>` : ''}
        <h2 class="text-3xl md:text-4xl font-bold text-gray-900 mt-2">${title}</h2>
        ${subtitle ? `<p class="text-gray-500 mt-3 max-w-xl mx-auto">${subtitle}</p>` : ''}
    </div>`;
}

// ---- EMPTY STATE HELPER ----
function emptyState(icon, msg, btnLabel='', btnRoute='') {
    return `<div class="flex flex-col items-center justify-center py-20 text-center">
        <div class="w-20 h-20 rounded-full bg-gray-100 flex items-center justify-center mb-5">
            <i class="fa-solid ${icon} text-3xl text-gray-400" aria-hidden="true"></i>
        </div>
        <p class="text-gray-500 font-medium mb-4">${msg}</p>
        ${btnLabel ? `<button onclick="navigate('${btnRoute}')" class="text-toyota-red font-bold hover:underline text-sm">${btnLabel} →</button>` : ''}
    </div>`;
}

// ---- SOSMED LINKS HELPER ----
function buildSosmedLinks(s) {
    const links = [
        { url: s.youtube_url,   icon: 'fa-youtube',    label: 'YouTube',   hover: 'hover:bg-red-600' },
        { url: s.instagram_url, icon: 'fa-instagram',  label: 'Instagram', hover: 'hover:bg-pink-600' },
        { url: s.tiktok_url,    icon: 'fa-tiktok',     label: 'TikTok',    hover: 'hover:bg-black' },
        { url: s.facebook_url,  icon: 'fa-facebook-f', label: 'Facebook',  hover: 'hover:bg-blue-600' },
    ].filter(sm => sm.url);
    if (!links.length) return '';
    return `<div class="flex flex-wrap gap-3 mt-6" aria-label="Media sosial">` +
        links.map(sm => `<a href="${sm.url}" target="_blank" rel="noopener noreferrer" aria-label="${sm.label} ${escapeHtml(s.nama_lengkap)}"
            class="w-10 h-10 rounded-full bg-gray-800 flex items-center justify-center text-gray-400 hover:text-white ${sm.hover} transition border border-gray-700 active:scale-90">
            <i class="fa-brands ${sm.icon} text-base" aria-hidden="true"></i></a>`).join('') + `</div>`;
}

// ============================================================
// HOME
// ============================================================
function renderHome() {
    const brand = SITE_CONFIG.brand || 'Mobil';
    const s = SITE_CONFIG.sales;

    // --- PROMO SECTION ---
    let featuredPromos = DB.promos.filter(p => p.is_featured == 1);
    if (!featuredPromos.length && DB.promos.length) featuredPromos = DB.promos.slice(0, 3);
    else featuredPromos = featuredPromos.slice(0, 3);

    let promoHtml = '';
    if (!featuredPromos.length) {
        promoHtml = emptyState('fa-tag', 'Nantikan promo menarik dari kami!');
    } else if (featuredPromos.length === 1) {
        const p = featuredPromos[0];
        const media = getMediaHtml(p.video || p.image || p.gambar_url, "w-full h-full object-cover", true, false, `Promo ${escapeHtml(p.title || p.judul)}`);
        let timer = p.expired && new Date(p.expired) > new Date() ? `<div class="mb-4 promo-timer" data-expired="${p.expired}"></div>` : '';
        promoHtml = `
            <article class="flex flex-col md:flex-row bg-white rounded-2xl shadow-xl overflow-hidden border border-gray-100">
                <div class="md:w-1/2 aspect-video md:aspect-auto md:min-h-80 relative bg-gray-900 overflow-hidden">
                    ${media}
                    <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">Promo Utama</div>
                </div>
                <div class="p-8 md:p-10 md:w-1/2 flex flex-col justify-center">
                    <h3 class="text-2xl md:text-3xl font-bold mb-4 text-gray-900 leading-tight">${escapeHtml(p.title || p.judul)}</h3>
                    ${timer}
                    <div class="flex flex-wrap gap-3 mt-6">
                        <button onclick="navigate('promo-detail', ${p.id})"
                            class="bg-toyota-dark text-white px-7 py-3 rounded-xl font-bold hover:bg-black transition active:scale-95 shadow">Lihat Detail</button>
                        <button onclick="trackLeadAndChat('Home Promo', '${(p.title||p.judul).replace(/'/g,"\\'")}', 'Halo, saya mau tanya promo ${(p.title||p.judul).replace(/'/g,"\\'")}', this)"
                            class="border-2 border-toyota-red text-toyota-red px-7 py-3 rounded-xl font-bold hover:bg-toyota-red hover:text-white transition active:scale-95">Tanya Sales</button>
                    </div>
                </div>
            </article>`;
    } else {
        const gridCols = featuredPromos.length === 2 ? 'md:grid-cols-2' : 'md:grid-cols-3';
        promoHtml = `<div class="grid grid-cols-1 ${gridCols} gap-6">` + featuredPromos.map(p => {
            const media = getMediaHtml(p.video || p.image || p.gambar_url, "w-full h-full object-cover group-hover:scale-110 transition duration-700", false, false, `Promo ${escapeHtml(p.title || p.judul)}`);
            let timer = p.expired && new Date(p.expired) > new Date() ? `<div class="mb-3 promo-timer" data-expired="${p.expired}"></div>` : '';
            return `<article class="bg-white rounded-2xl shadow-md border border-gray-100 overflow-hidden group hover:shadow-xl hover:-translate-y-1 transition-all duration-300 flex flex-col">
                <div class="relative overflow-hidden bg-gray-900 aspect-video">${media}
                    <div class="absolute top-4 left-4 bg-toyota-red text-white text-xs font-bold px-3 py-1 rounded-full">Hot Promo</div>
                </div>
                <div class="p-6 flex flex-col flex-1">
                    <h3 class="text-lg font-bold mb-3 text-gray-900 line-clamp-2">${escapeHtml(p.title || p.judul)}</h3>
                    ${timer}
                    <div class="mt-auto pt-4">
                        <button onclick="navigate('promo-detail', ${p.id})"
                            class="w-full border-2 border-toyota-red text-toyota-red font-bold py-2.5 rounded-xl hover:bg-toyota-red hover:text-white transition active:scale-95">Lihat Promo</button>
                    </div>
                </div>
            </article>`;
        }).join('') + `</div>`;
    }

    // --- PRODUK FEATURED ---
    let featuredProducts = DB.products.filter(p => p.is_featured == 1);
    if (!featuredProducts.length && DB.products.length) featuredProducts = DB.products.slice(0, 3);
    else featuredProducts = featuredProducts.slice(0, 3);

    let productSectionHtml = '';
    if (featuredProducts.length) {
        const productCards = featuredProducts.map(p => `
            <article class="bg-white rounded-2xl shadow-md border border-gray-100 overflow-hidden group hover:shadow-xl hover:-translate-y-1 transition-all duration-300">
                <div class="aspect-[4/3] overflow-hidden bg-gray-100 relative">
                    <img src="${p.image}" class="w-full h-full object-cover group-hover:scale-110 transition duration-700"
                         alt="${escapeHtml(p.name)} - ${brand} ${escapeHtml(SITE_CONFIG.nama_cabang)}" width="400" height="300" loading="lazy"
                         onerror="this.src='https://via.placeholder.com/400x300?text=No+Image'">
                    <div class="absolute inset-0 bg-gradient-to-t from-black/20 to-transparent opacity-0 group-hover:opacity-100 transition"></div>
                </div>
                <div class="p-6">
                    <h3 class="text-xl font-bold text-gray-900 mb-1">${escapeHtml(p.name)}</h3>
                    <p class="text-xs text-gray-400 font-semibold uppercase tracking-wide mb-1">Mulai dari</p>
                    <p class="text-toyota-red font-bold text-lg mb-5">${formatRupiah(p.price)}</p>
                    <button onclick="navigate('produk-detail', ${p.id})"
                        class="w-full py-2.5 rounded-xl font-bold border-2 border-gray-200 text-gray-700 hover:border-toyota-dark hover:bg-toyota-dark hover:text-white transition active:scale-95">
                        Lihat Detail</button>
                </div>
            </article>`).join('');
        productSectionHtml = `
        <section class="py-20 bg-white border-t border-gray-100" aria-label="Produk unggulan">
            <div class="container mx-auto px-4">
                ${secHdr('Best Seller', 'Pilihan Favorit', 'Model-model terlaris yang paling diminati pelanggan kami')}
                <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 gap-2 text-toyota-red font-bold text-base hover:underline group">
                        Lihat Semua Model <i class="fa-solid fa-arrow-right group-hover:translate-x-1 transition" aria-hidden="true"></i>
                    </button>
                </div>
            </div>
        </section>`;
    }

    // --- ARTIKEL HOME ---
    const articlesList = Array.isArray(DB.articles) ? DB.articles : [];
    let artikelHtml = '';
    if (articlesList.length) {
        const articleCards = articlesList.slice(0, 3).map(a => `
            <article onclick="navigate('artikel-detail', ${a.id})"
                class="cursor-pointer bg-white rounded-2xl shadow-md border border-gray-100 overflow-hidden group hover:shadow-xl hover:-translate-y-1 transition-all duration-300 flex flex-col">
                <div class="aspect-[16/9] overflow-hidden bg-gray-100 relative">
                    <img src="${a.image}" class="w-full h-full object-cover group-hover:scale-110 transition duration-700"
                         alt="${escapeHtml(a.title)}" width="400" height="225" loading="lazy"
                         onerror="this.src='https://via.placeholder.com/400x225?text=No+Image'">
                    <div class="absolute inset-0 bg-gradient-to-t from-black/40 to-transparent opacity-0 group-hover:opacity-100 transition"></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" aria-hidden="true"></i>
                        <time datetime="${a.raw_date || a.date}">${a.date}</time>
                    </div>
                    <h3 class="text-lg font-bold text-gray-900 group-hover:text-toyota-red transition line-clamp-2 leading-snug flex-1">${escapeHtml(a.title)}</h3>
                    <div class="mt-4 pt-4 border-t border-gray-100 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 group-hover:translate-x-1 transition" aria-hidden="true"></i>
                    </div>
                </div>
            </article>`).join('');
        artikelHtml = `
        <section class="py-20 bg-gray-50 border-t border-gray-100" aria-label="Artikel terbaru">
            <div class="container mx-auto px-4">
                ${secHdr('', 'Berita &amp; Tips', 'Informasi seputar kendaraan dan dunia otomotif')}
                <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="inline-flex items-center gap-2 text-toyota-red font-bold hover:underline">
                        Lihat Semua Artikel <i class="fa-solid fa-arrow-right" aria-hidden="true"></i>
                    </button>
                </div>
            </div>
        </section>`;
    }

    // --- TESTIMONI HOME ---
    const testimonialsList = Array.isArray(DB.testimonials) ? DB.testimonials : [];
    let testimoniHtml = '';
    if (testimonialsList.length) {
        const topTesti = [...testimonialsList].sort((a, b) => parseInt(b.rating) - parseInt(a.rating)).slice(0, 3);
        const testiCards = topTesti.map(t => {
            const rating    = parseInt(t.rating) || 5;
            const isGoogle  = t.source === 'google';
            const hasText   = t.text && t.text.trim().length > 0;
            const avatarSrc = t.profile_photo
                || `https://ui-avatars.com/api/?name=${encodeURIComponent(t.name||'?')}&size=88&background=${isGoogle?'4285F4':'EB0A1E'}&color=ffffff&bold=true`;
            let stars = '';
            for (let i = 0; i < 5; i++) stars += `<i class="fa-${i < rating ? 'solid' : 'regular'} fa-star" aria-hidden="true"></i>`;
            return `<div class="bg-white p-6 rounded-2xl shadow-md border border-gray-100 hover:shadow-xl transition text-left flex flex-col">
                <div class="flex items-center gap-2 mt-0.5">
                    <div class="flex text-yellow-400 mb-3 text-sm" aria-label="Rating ${rating} dari 5 bintang">${stars}</div>
                    <span class="text-gray-200 text-[10px]">|</span>
                    <time class="text-[10px] text-gray-400 font-medium">${t.tanggal_serah_terima}</time>
                </div>
                <p class="text-gray-600 italic text-sm mb-5 line-clamp-3 flex-1">${hasText ? `"${escapeHtml(t.text)}"` : '<span class="text-gray-300">—</span>'}</p>
                <div class="flex items-center gap-3 pt-4 border-t border-gray-100">
                    <div class="relative flex-shrink-0">
                        <img src="${avatarSrc}"
                             class="w-11 h-11 rounded-full object-cover border-2 border-gray-100"
                             alt="Foto ${escapeHtml(t.name)}" width="44" height="44" loading="lazy"
                             onerror="this.src='https://ui-avatars.com/api/?name=${encodeURIComponent(t.name||'?')}&size=88&background=${isGoogle?'4285F4':'EB0A1E'}&color=fff&bold=true'">
                        ${isGoogle ? `<div class="absolute -bottom-0.5 -right-0.5 w-4 h-4 bg-white rounded-full flex items-center justify-center shadow border border-gray-100">
                            <i class="fa-brands fa-google text-[8px] text-blue-500"></i>
                        </div>` : ''}
                    </div>
                    <div>
                        <h4 class="font-bold text-sm text-gray-900">${escapeHtml(t.name)}</h4>
                        <p class="text-xs text-gray-400 truncate max-w-[160px]">${escapeHtml(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>`;
    }

    // --- KONTAK HOME ---
    const sosmedHtml = buildSosmedLinks(s);

    return `
    <div class="page-enter-placeholder">

        <!-- HERO -->
        <header class="hero-section relative flex items-center justify-center overflow-hidden" role="banner"
                style="background-image: url('${SITE_CONFIG.hero_image_url}');">
            <div class="absolute inset-0 bg-black/55 z-10" aria-hidden="true"></div>
            <div class="relative z-20 text-center px-4 max-w-5xl py-24 md:py-0">
                <p class="text-white/80 text-sm md:text-base font-semibold tracking-[0.3em] uppercase mb-4">
                    ${escapeHtml(SITE_CONFIG.nama_cabang)}
                </p>
                <h1 class="text-5xl md:text-8xl font-extrabold text-white mb-6 tracking-tighter leading-none">
                    DRIVE <span class="text-transparent bg-clip-text bg-gradient-to-r from-toyota-red to-red-400">PROUD</span>
                </h1>
                <p class="text-gray-200 text-base md:text-xl mb-10 max-w-2xl mx-auto font-light">
                    Penawaran eksklusif dari <span class="font-bold text-white">${escapeHtml(s.nama_lengkap)}</span>. Proses cepat &amp; Mudah.
                </p>
                <div class="flex flex-col sm:flex-row gap-4 justify-center">
                    <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 active:scale-95 shadow-xl">
                        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 active:scale-95">
                        Lihat Mobil
                    </button>
                </div>
            </div>
        </header>

        <!-- PROMO -->
        <section class="py-20 bg-white" aria-label="Promo spesial">
            <div class="container mx-auto px-4">
                ${secHdr('Penawaran Terbatas', 'Promo Spesial', 'Penawaran terbaik bulan ini khusus untuk Anda')}
                ${promoHtml}
            </div>
        </section>

        <!-- PRODUK FEATURED -->
        ${productSectionHtml}

        <!-- ARTIKEL -->
        ${artikelHtml}

        <!-- TESTIMONI -->
        <section class="py-20 bg-white border-t border-gray-100" aria-label="Testimoni pelanggan">
            <div class="container mx-auto px-4">
                ${secHdr('Customer Stories', 'Apa Kata Mereka?', 'Kepuasan pelanggan adalah prioritas kami')}
                ${testimoniHtml}
                <div class="text-center mt-4">
                    <button onclick="navigate('testimoni')"
                        class="inline-flex items-center gap-2 bg-white px-7 py-3 rounded-xl font-bold text-toyota-red hover:bg-gray-50 border-2 border-toyota-red transition active:scale-95 shadow-sm">
                        <i class="fa-solid fa-images" aria-hidden="true"></i> Gallery Serah Terima &amp; Testimoni
                    </button>
                </div>
            </div>
        </section>

        <!-- KONTAK -->
        <section class="py-20 bg-gray-50 border-t border-gray-100" aria-label="Hubungi kami">
            <div class="container mx-auto px-4 max-w-5xl">
                ${secHdr('', 'Hubungi Kami', 'Siap membantu Anda menemukan kendaraan impian')}
                <div class="bg-gradient-to-br from-toyota-dark to-gray-900 rounded-2xl p-8 md:p-12 shadow-2xl text-white flex flex-col md:flex-row items-center gap-8 md:gap-12 relative overflow-hidden">
                    <img src="${s.foto_profil_url}" class="w-36 h-36 md:w-44 md:h-44 rounded-full border-4 border-toyota-red object-cover relative z-10 shrink-0"
                         alt="Foto ${escapeHtml(s.nama_lengkap)}" width="176" height="176" loading="lazy">
                    <div class="flex-1 relative z-10 text-center md:text-left">
                        <h3 class="text-3xl md:text-4xl font-bold mb-1">${escapeHtml(s.nama_lengkap)}</h3>
                        <p class="text-toyota-red font-bold text-lg uppercase tracking-wider">${escapeHtml(s.jabatan || 'Sales Executive')}</p>
                        <p class="mt-2 text-gray-400 text-sm">${escapeHtml(SITE_CONFIG.nama_cabang)}</p>
                        <div class="flex flex-wrap justify-center md:justify-start gap-3 mt-6">
                            <a href="tel:${s.no_wa}"
                               class="bg-white text-toyota-dark px-6 py-2.5 rounded-xl font-bold hover:bg-gray-100 transition active:scale-95">
                               <i class="fa-solid fa-phone mr-1" aria-hidden="true"></i> Telepon
                            </a>
                            <button onclick="trackLeadAndChat('Kontak', 'General', 'Halo ${escapeHtml(s.nama_lengkap)}, saya mau tanya info ${SITE_CONFIG.brand || 'Mobil'}.', this)"
                               class="bg-[#25D366] text-white px-6 py-2.5 rounded-xl font-bold hover:bg-[#1ebe5d] transition active:scale-95">
                               <i class="fa-brands fa-whatsapp mr-1" aria-hidden="true"></i> WhatsApp
                            </button>
                        </div>
                        ${sosmedHtml}
                    </div>
                    <div class="absolute top-0 right-0 w-72 h-72 bg-toyota-red opacity-5 rounded-full blur-3xl -mr-20 -mt-20 pointer-events-none" aria-hidden="true"></div>
                </div>
                <div class="rounded-2xl overflow-hidden h-80 shadow-md border border-gray-200 mt-8">
                    <iframe src="${SITE_CONFIG.google_map_embed}" width="100%" height="100%" style="border:0;"
                            allowfullscreen loading="lazy" title="Peta lokasi ${escapeHtml(SITE_CONFIG.nama_cabang)}"></iframe>
                </div>
            </div>
        </section>
    </div>`;
}

// ============================================================
// TRADE-IN
// ============================================================
function renderTradeIn() {
    const brand = SITE_CONFIG.brand || 'Mobil';
    let productOptions = '<option value="">-- Pilih Mobil Baru --</option>';
    DB.products.forEach(p => { productOptions += `<option value="${escapeHtml(p.name)}">${escapeHtml(p.name)}</option>`; });

    return `
    <div class="bg-gray-50 min-h-screen pt-20 pb-24 page-enter-placeholder">
        <div class="container mx-auto px-4 max-w-3xl">
            ${secHdr('', 'Trade-in Mobil Lama', 'Dapatkan penawaran harga terbaik untuk kendaraan Anda')}
            <div class="bg-white p-8 rounded-2xl shadow-md border border-gray-100">
                <form onsubmit="submitTradeIn(event)" aria-label="Formulir trade-in" novalidate>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-5 mb-5">
                        <div class="md:col-span-2">
                            <label for="trade-old-car" class="block text-sm font-bold text-gray-700 mb-2">Mobil Lama (Merk, Tipe) <span class="text-red-500">*</span></label>
                            <input type="text" id="trade-old-car" name="mobil_lama" autocomplete="off"
                                class="w-full p-4 bg-gray-50 rounded-xl border border-gray-200 focus:ring-2 focus:ring-toyota-red outline-none transition"
                                placeholder="Contoh: ${brand} Avanza G" required aria-required="true">
                        </div>
                        <div>
                            <label for="trade-year" class="block text-sm font-bold text-gray-700 mb-2">Tahun <span class="text-red-500">*</span></label>
                            <input type="number" id="trade-year" name="tahun" min="1990" max="${TAHUN}"
                                class="w-full p-4 bg-gray-50 rounded-xl border border-gray-200 focus:ring-2 focus:ring-toyota-red outline-none transition"
                                placeholder="${TAHUN - 5}" required aria-required="true">
                        </div>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-5 mb-5">
                        <div>
                            <label for="trade-color" class="block text-sm font-bold text-gray-700 mb-2">Warna <span class="text-red-500">*</span></label>
                            <input type="text" id="trade-color" name="warna" autocomplete="off"
                                class="w-full p-4 bg-gray-50 rounded-xl border border-gray-200 focus:ring-2 focus:ring-toyota-red outline-none transition"
                                placeholder="Contoh: Putih" required aria-required="true">
                        </div>
                        <div>
                            <label for="trade-transmisi" class="block text-sm font-bold text-gray-700 mb-2">Transmisi</label>
                            <select id="trade-transmisi" name="transmisi"
                                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="Automatic">Automatic (AT)</option>
                                <option value="Manual">Manual (MT)</option>
                            </select>
                        </div>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-5 mb-5">
                        <div>
                            <label for="trade-km" class="block text-sm font-bold text-gray-700 mb-2">Jarak Tempuh (KM) <span class="text-red-500">*</span></label>
                            <input type="number" id="trade-km" name="km" min="0"
                                class="w-full p-4 bg-gray-50 rounded-xl border border-gray-200 focus:ring-2 focus:ring-toyota-red outline-none transition"
                                placeholder="Contoh: 45000" required aria-required="true">
                        </div>
                        <div>
                            <label for="trade-pajak" class="block text-sm font-bold text-gray-700 mb-2">Pajak Berlaku Sampai <span class="text-red-500">*</span></label>
                            <input type="month" id="trade-pajak" name="pajak"
                                class="w-full p-4 bg-gray-50 rounded-xl border border-gray-200 focus:ring-2 focus:ring-toyota-red outline-none transition"
                                required aria-required="true">
                            <p class="text-xs text-gray-400 mt-1">Pilih Bulan &amp; Tahun habis pajak.</p>
                        </div>
                    </div>
                    <div class="mb-5">
                        <label for="trade-new-car" class="block text-sm font-bold text-gray-700 mb-2">Rencana Ganti Ke</label>
                        <select id="trade-new-car" name="mobil_baru"
                            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">
                            ${productOptions}
                        </select>
                    </div>
                    <div class="mb-8">
                        <label for="trade-name" class="block text-sm font-bold text-gray-700 mb-2">Nama Anda <span class="text-red-500">*</span></label>
                        <input type="text" id="trade-name" name="nama" autocomplete="name"
                            class="w-full p-4 bg-gray-50 rounded-xl border border-gray-200 focus:ring-2 focus:ring-toyota-red outline-none transition"
                            placeholder="Nama Lengkap" required aria-required="true">
                    </div>
                    <button type="submit"
                        class="w-full bg-[#25D366] hover:bg-[#1ebe5d] text-white font-bold py-4 rounded-xl transition active:scale-95 shadow-md flex items-center justify-center gap-2">
                        <i class="fa-brands fa-whatsapp text-xl" aria-hidden="true"></i> Minta Penawaran via WA
                    </button>
                </form>
            </div>
            <p class="mt-6 text-center text-gray-400 text-sm">Tim kami akan segera menghubungi Anda untuk estimasi harga &amp; inspeksi gratis.</p>
        </div>
    </div>`;
}

// ============================================================
// PRODUK LIST
// ============================================================
function renderProducts() {
    const brand = SITE_CONFIG.brand || 'Mobil';
    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 min-h-screen pt-20 pb-24 page-enter-placeholder">
        <div class="container mx-auto px-4">
            ${secHdr('', `Daftar Harga ${brand}`, 'Temukan kendaraan yang sesuai kebutuhan dan anggaran Anda')}
            <div class="bg-white p-5 rounded-2xl shadow-sm border border-gray-100 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 pointer-events-none" aria-hidden="true"></i>
                        <label for="filter-search" class="sr-only">Cari nama mobil</label>
                        <input type="search" id="filter-search" oninput="applyProductFilter()"
                            class="w-full pl-10 p-3 border border-gray-200 rounded-xl focus:ring-2 focus:ring-toyota-red outline-none transition"
                            placeholder="Cari nama mobil..." aria-label="Cari nama mobil">
                    </div>
                    <div class="relative">
                        <i class="fa-solid fa-layer-group absolute left-4 top-3.5 text-gray-400 pointer-events-none" aria-hidden="true"></i>
                        <label for="filter-category" class="sr-only">Filter kategori</label>
                        <select id="filter-category" onchange="applyProductFilter()"
                            class="w-full pl-10 p-3 border border-gray-200 rounded-xl focus:ring-2 focus:ring-toyota-red 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" aria-hidden="true"></i>
                    </div>
                    <div class="relative">
                        <i class="fa-solid fa-coins absolute left-4 top-3.5 text-gray-400 pointer-events-none" aria-hidden="true"></i>
                        <label for="filter-price" class="sr-only">Filter harga</label>
                        <select id="filter-price" onchange="applyProductFilter()"
                            class="w-full pl-10 p-3 border border-gray-200 rounded-xl focus:ring-2 focus:ring-toyota-red 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" aria-hidden="true"></i>
                    </div>
                </div>
            </div>
            <div id="product-grid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">${generateProductCards(DB.products)}</div>
            <div id="empty-state" class="hidden">${emptyState('fa-car-burst', 'Mobil yang Anda cari tidak ditemukan.', 'Reset Filter', '')}</div>
        </div>
    </div>`;
}

function generateProductCards(products) {
    const brand = SITE_CONFIG.brand || 'Mobil';
    if (!products.length) return emptyState('fa-car', 'Belum ada produk tersedia.', 'Kembali ke Beranda', 'home');
    return products.map(p => `
        <article class="bg-white rounded-2xl shadow-md border border-gray-100 overflow-hidden group hover:shadow-xl hover:-translate-y-1 transition-all duration-300">
            <div class="aspect-[4/3] overflow-hidden bg-gray-100 relative">
                <img src="${p.image}" class="w-full h-full object-cover group-hover:scale-110 transition duration-700"
                     alt="${escapeHtml(p.name)} ${brand} - ${p.kategori || ''}" width="400" height="300" loading="lazy"
                     onerror="this.src='https://via.placeholder.com/400x300?text=No+Image'">
                <div class="absolute top-3 left-3 bg-white/90 backdrop-blur px-3 py-1 rounded-full text-xs font-bold text-gray-700 border border-gray-200">${p.kategori || 'Umum'}</div>
            </div>
            <div class="p-6">
                <h2 class="text-xl font-bold text-gray-900 mb-1">${escapeHtml(p.name)}</h2>
                <p class="text-xs text-gray-400 font-semibold uppercase tracking-wide mb-1">Mulai Dari</p>
                <p class="text-toyota-red font-bold text-lg mb-5">${formatRupiah(p.price)}</p>
                <button onclick="navigate('produk-detail', ${p.id})"
                    class="w-full py-2.5 rounded-xl font-bold border-2 border-gray-200 text-gray-700 hover:border-toyota-dark hover:bg-toyota-dark hover:text-white transition active:scale-95">
                    Lihat Detail
                </button>
            </div>
        </article>`).join('');
}

function applyProductFilter() {
    const search = document.getElementById('filter-search').value.toLowerCase();
    const cat    = document.getElementById('filter-category').value;
    const priceR = document.getElementById('filter-price').value;
    const filtered = DB.products.filter(p => {
        const matchName  = p.name.toLowerCase().includes(search);
        const matchCat   = !cat || p.kategori === cat;
        const price      = parseFloat(p.price);
        let matchPrice   = true;
        if (priceR === '1') matchPrice = price < 300000000;
        else if (priceR === '2') matchPrice = price >= 300000000 && price <= 600000000;
        else if (priceR === '3') matchPrice = price > 600000000;
        return matchName && matchCat && matchPrice;
    });
    const grid  = document.getElementById('product-grid');
    const empty = document.getElementById('empty-state');
    if (filtered.length) { grid.innerHTML = generateProductCards(filtered); grid.classList.remove('hidden'); empty.classList.add('hidden'); }
    else { grid.innerHTML = ''; grid.classList.add('hidden'); empty.classList.remove('hidden'); }
}
function resetFilter() { document.getElementById('filter-search').value = ''; document.getElementById('filter-category').value = ''; document.getElementById('filter-price').value = ''; applyProductFilter(); }

// ============================================================
// ARTIKEL LIST
// ============================================================
window.changeArticlePage = (p) => { currentArticlePage = p; navigate('artikel', null, false); };

function renderArtikel() {
    const arts = DB.articles || [];
    if (!arts.length) return `<div class="bg-gray-50 min-h-screen pt-20 pb-24 page-enter-placeholder"><div class="container mx-auto px-4">
        ${secHdr('', 'Berita &amp; Tips')}${emptyState('fa-newspaper', 'Belum ada artikel tersedia.', 'Kembali ke Beranda', 'home')}</div></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 => `
        <article onclick="navigate('artikel-detail', ${a.id})"
            class="cursor-pointer bg-white rounded-2xl shadow-md border border-gray-100 overflow-hidden group hover:shadow-xl hover:-translate-y-1 transition-all duration-300">
            <div class="aspect-[16/9] overflow-hidden bg-gray-100">
                <img src="${a.image}" class="w-full h-full object-cover group-hover:scale-110 transition duration-700"
                     alt="${escapeHtml(a.title)}" width="400" height="225" loading="lazy"
                     onerror="this.src='assets/images/no-image.jpg'">
            </div>
            <div class="p-6">
                <time class="text-xs font-semibold text-gray-400 uppercase tracking-widest"
                      datetime="${a.raw_date || a.date}">${a.date}</time>
                <h2 class="text-lg font-bold text-gray-900 group-hover:text-toyota-red transition line-clamp-2 mt-2 leading-snug">${escapeHtml(a.title)}</h2>
                <div class="flex items-center gap-1 mt-4 text-sm text-toyota-red font-semibold">
                    Baca Selengkapnya <i class="fa-solid fa-arrow-right group-hover:translate-x-1 transition" aria-hidden="true"></i>
                </div>
            </div>
        </article>`).join('');
    let pagUI = '';
    if (totalP > 1) {
        pagUI = `<nav aria-label="Pagination artikel" class="flex justify-center gap-2 mt-12">`;
        for (let i = 1; i <= totalP; i++) pagUI += `<button onclick="changeArticlePage(${i})"
            aria-label="Halaman ${i}" ${i === currentArticlePage ? 'aria-current="page"' : ''}
            class="w-12 h-12 rounded-xl font-bold transition active:scale-95 ${i === currentArticlePage ? 'bg-toyota-red text-white shadow-md' : 'bg-white border border-gray-200 text-gray-500 hover:bg-gray-50'}">${i}</button>`;
        pagUI += `</nav>`;
    }
    return `<div class="bg-gray-50 min-h-screen pt-20 pb-24 page-enter-placeholder">
        <div class="container mx-auto px-4">
            ${secHdr('', 'Berita &amp; Tips', 'Informasi terkini seputar kendaraan dan otomotif')}
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">${cards}</div>
            ${pagUI}
        </div>
    </div>`;
}

// ============================================================
// TESTIMONI (Update Kolom: tanggal_serah_terima)
// ============================================================
function renderTestimoni() {
    let testimonials = Array.isArray(DB.testimonials) ? [...DB.testimonials] : [];
    
    // 1. Sort Terbaru ke Terlama
    testimonials.sort((a, b) => new Date(b.tanggal_serah_terima) - new Date(a.tanggal_serah_terima));

    if (!testimonials.length) return emptyState('fa-star', 'Belum ada testimoni.', 'Home', 'home');

    // 2. Bagi data ke 3 kolom secara bergantian (Zig-zag)
    // Supaya urutan 1 di Kiri, 2 di Tengah, 3 di Kanan, 4 balik ke Kiri lagi
    const colData = [[], [], []]; 
    testimonials.forEach((t, idx) => {
        colData[idx % 3].push(t);
    });

    // 3. Render 3 kolom sejajar
    const columnsHtml = colData.map(col => `
        <div class="flex flex-col gap-6 flex-1">
            ${col.map(t => renderSingleCard(t)).join('')}
        </div>
    `).join('');

    return `
    <div class="bg-gray-50 min-h-screen pt-20 pb-24 page-enter-placeholder">
        <div class="container mx-auto px-4">
            ${secHdr('Happy Customers', 'Gallery Serah Terima', 'Kepuasan pelanggan adalah prioritas kami')}
            <div class="flex flex-col md:flex-row gap-6 items-start">
                ${columnsHtml}
            </div>
        </div>
    </div>`;
}

// Fungsi pembantu biar kode bersih
function renderSingleCard(t) {
    const rating = parseInt(t.rating) || 5;
    const isGoogle = t.source === 'google';
    const hasText = t.text && t.text.trim().length > 0;
    const hasDelivery = t.delivery_photo && t.delivery_photo.trim() !== '';
    const avatarSrc = t.profile_photo || `https://ui-avatars.com/api/?name=${encodeURIComponent(t.name||'?')}&size=88&background=${isGoogle?'4285F4':'EB0A1E'}&color=fff&bold=true`;
    
    let stars = '';
    for (let i = 0; i < 5; i++) stars += `<i class="fa-${i < rating ? 'solid' : 'regular'} fa-star"></i>`;

    return `
    <article class="bg-white rounded-2xl shadow-sm border border-gray-100 p-5 hover:shadow-md transition-all flex flex-col h-auto w-full">
        <div class="flex items-center gap-3 mb-3">
            <div class="relative flex-shrink-0">
                <img src="${avatarSrc}" class="w-11 h-11 rounded-full object-cover border-2 border-gray-100" onerror="this.src='https://ui-avatars.com/api/?name=?&background=ddd'">
                ${isGoogle ? `<div class="absolute -bottom-0.5 -right-0.5 w-4 h-4 bg-white rounded-full flex items-center justify-center shadow border border-gray-100"><i class="fa-brands fa-google text-[8px] text-blue-500"></i></div>` : ''}
            </div>
            <div class="min-w-0 flex-1">
                <div class="flex items-center justify-between gap-2">
                    <h3 class="font-bold text-gray-900 text-sm truncate m-0">${escapeHtml(t.name)}</h3>
                    <span class="text-[10px] text-gray-400 font-medium">Review Google</span>
                </div>
                <div class="flex items-center gap-2 mt-0.5">
                    <div class="flex text-yellow-400 text-[10px]">${stars}</div>
                    <span class="text-gray-200 text-[10px]">|</span>
                    <time class="text-[10px] text-gray-400 font-medium">${t.tanggal_serah_terima}</time>
                </div>
            </div>
        </div>
        <div class="mb-3">
            <p class="text-gray-600 text-sm italic leading-relaxed">${hasText ? `"${escapeHtml(t.text)}"` : '—'}</p>
        </div>
        ${hasDelivery ? `
        <div class="rounded-xl overflow-hidden aspect-video bg-gray-50 relative mt-2">
            <img src="${t.delivery_photo}" class="w-full h-full object-cover" loading="lazy">
            <div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/60 to-transparent px-3 py-2">
                <span class="text-white text-[10px] font-bold uppercase tracking-wide">${escapeHtml(t.car || 'Toyota')}</span>
            </div>
        </div>` : ''}
    </article>`;
}

// ============================================================
// PROMO LIST
// ============================================================
function renderPromo() {
    const promos = Array.isArray(DB.promos) ? DB.promos : [];
    const inner = !promos.length
        ? emptyState('fa-tag', 'Belum ada promo aktif saat ini. Pantau terus ya!', 'Kembali ke Beranda', 'home')
        : `<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">${promos.map(p => {
            const media = getMediaHtml(p.video||p.image||p.gambar_url, "w-full h-full object-cover group-hover:scale-110 transition duration-700", false, false, `Promo ${escapeHtml(p.title||p.judul)}`);
            let timer = p.expired && new Date(p.expired) > new Date() ? `<div class="mb-3 promo-timer" data-expired="${p.expired}"></div>` : '';
            return `<article class="bg-white rounded-2xl shadow-md border border-gray-100 overflow-hidden group hover:shadow-xl hover:-translate-y-1 transition-all duration-300 flex flex-col">
                <div class="aspect-video relative bg-gray-900 overflow-hidden">${media}
                    <div class="absolute top-4 right-4 bg-toyota-red text-white text-xs font-bold px-3 py-1 rounded-full">Promo</div>
                </div>
                <div class="p-6 flex flex-col flex-1">
                    <h2 class="text-lg font-bold text-gray-900 mb-3 line-clamp-2">${escapeHtml(p.title||p.judul)}</h2>
                    ${timer}
                    <div class="mt-auto pt-4">
                        <button onclick="navigate('promo-detail', ${p.id})"
                            class="w-full border-2 border-toyota-red text-toyota-red font-bold py-2.5 rounded-xl hover:bg-toyota-red hover:text-white transition active:scale-95">
                            Lihat Selengkapnya
                        </button>
                    </div>
                </div>
            </article>`;
        }).join('')}</div>`;
    return `<div class="bg-gray-50 min-h-screen pt-20 pb-24 page-enter-placeholder">
        <div class="container mx-auto px-4">
            ${secHdr('Penawaran Terbatas', 'Promo Spesial', 'Manfaatkan penawaran eksklusif sebelum berakhir')}
            ${inner}
        </div>
    </div>`;
}

// ============================================================
// PRODUK DETAIL
// ============================================================
function renderProductDetail(id) {
    const p = DB.products.find(x => x.id == id);
    if (!p) return `<div class="p-20 text-center">${emptyState('fa-car-burst', 'Produk tidak ditemukan.', 'Lihat Semua Produk', 'produk')}</div>`;
    const brand = SITE_CONFIG.brand || 'Mobil';
    let variants = [];
    try { if (p.varian) variants = typeof p.varian === 'string' ? JSON.parse(p.varian) : p.varian; } catch(e) {}
    let varianTableHtml = '';
    if (Array.isArray(variants) && variants.length) {
        const rows = variants.map(v => `
            <tr class="border-b border-gray-100 last:border-0 hover:bg-gray-50 transition">
                <td class="py-3 px-4 text-gray-700">${escapeHtml(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">
                <h3 class="text-base font-bold text-gray-800 mb-3 flex items-center gap-2">
                    <span class="w-1 h-5 bg-toyota-red rounded-full inline-block"></span> Daftar Tipe &amp; Harga
                </h3>
                <div class="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
                    <table class="w-full text-sm" aria-label="Daftar tipe dan harga ${escapeHtml(p.name)}">
                        <thead class="bg-gray-50 text-gray-500 text-xs uppercase tracking-wider border-b border-gray-100">
                            <tr><th class="py-3 px-4 text-left font-semibold" scope="col">Tipe / Varian</th>
                                <th class="py-3 px-4 text-right font-semibold" scope="col">Harga OTR</th></tr>
                        </thead>
                        <tbody>${rows}</tbody>
                    </table>
                </div>
            </div>`;
    }
    let brosurBtn = p.brochure
        ? `<a href="${p.brochure}" target="_blank" rel="noopener noreferrer"
               class="w-full flex items-center justify-center gap-2 border-2 border-red-200 text-red-600 py-3.5 rounded-xl font-bold hover:bg-red-50 transition active:scale-95"
               aria-label="Download brosur ${escapeHtml(p.name)}">
               <i class="fa-solid fa-file-pdf text-lg" aria-hidden="true"></i> Download E-Brosur</a>` : '';
    const videoHtml = p.video
        ? `<div class="rounded-2xl overflow-hidden shadow-md border border-gray-100 aspect-video mt-6">
               ${getMediaHtml(p.video, "w-full h-full", false, false, `Video ${escapeHtml(p.name)}`)}</div>` : '';
    const breadcrumbHtml = `
        <nav aria-label="Breadcrumb" class="mb-8">
            <ol class="flex items-center gap-2 text-sm text-gray-400">
                <li><button onclick="navigate('home')" class="hover:text-toyota-red transition">Home</button></li>
                <li aria-hidden="true"><i class="fa-solid fa-chevron-right text-xs"></i></li>
                <li><button onclick="navigate('produk')" class="hover:text-toyota-red transition">Produk ${brand}</button></li>
                <li aria-hidden="true"><i class="fa-solid fa-chevron-right text-xs"></i></li>
                <li class="text-gray-700 font-medium" aria-current="page">${escapeHtml(p.name)}</li>
            </ol>
        </nav>`;
    return `
    <div class="bg-white min-h-screen pt-20 pb-24 page-enter-placeholder">
        <div class="container mx-auto px-4">
            ${breadcrumbHtml}
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-12 items-start">
                <div class="lg:sticky lg:top-24">
                    <div class="rounded-2xl overflow-hidden shadow-xl border border-gray-100 aspect-[4/3] relative group bg-gray-100">
                        <img src="${p.image}" class="w-full h-full object-cover group-hover:scale-105 transition duration-700"
                             alt="${escapeHtml(p.name)} ${brand} - ${escapeHtml(SITE_CONFIG.nama_cabang)}" width="600" height="450" loading="eager">
                    </div>
                    ${videoHtml}
                </div>
                <div>
                    <div class="inline-block bg-gray-100 text-gray-600 text-xs font-bold uppercase px-3 py-1 rounded-full mb-3">${p.kategori || ''}</div>
                    <h1 class="text-3xl md:text-4xl font-extrabold text-gray-900 mb-1 leading-tight">${escapeHtml(p.name)}</h1>
                    <p class="text-gray-400 text-sm mb-5">Model ${TAHUN} &bull; ${escapeHtml(SITE_CONFIG.nama_cabang)}</p>
                    <div class="flex items-center gap-3 mb-8 p-4 bg-red-50 rounded-2xl border border-red-100">
                        <div>
                            <p class="text-xs text-gray-400 font-semibold uppercase tracking-wide">Harga Mulai Dari</p>
                            <p class="text-3xl text-toyota-red font-bold">${formatRupiah(p.price)}</p>
                        </div>
                    </div>
                    <div class="space-y-3 mb-8">
                        <button onclick="navigate('simulasi')"
                            class="w-full bg-green-500 text-white py-4 rounded-xl font-bold hover:bg-green-600 active:scale-95 shadow-md flex items-center justify-center gap-2 transition">
                            <i class="fa-solid fa-calculator" aria-hidden="true"></i> Simulasi Kredit
                        </button>
                        <button onclick="trackLeadAndChat('Produk Detail', '${p.name.replace(/'/g,"\\'")}', 'Halo, saya tertarik dengan ${p.name.replace(/'/g,"\\'")}', this)"
                            class="w-full bg-[#25D366] text-white py-4 rounded-xl font-bold hover:bg-[#1ebe5d] active:scale-95 shadow-md flex items-center justify-center gap-2 transition">
                            <i class="fa-brands fa-whatsapp text-xl" aria-hidden="true"></i> Hubungi Sales
                        </button>
                        ${brosurBtn}
                    </div>
                    ${varianTableHtml}
                    <div class="article-content bg-gray-50 p-6 rounded-2xl border border-gray-100 leading-relaxed text-gray-600">
                        ${p.desc || '<p class="text-gray-400">Belum ada deskripsi untuk produk ini.</p>'}
                    </div>
                </div>
            </div>
        </div>
    </div>`;
}

// ============================================================
// SIMULASI KREDIT
// ============================================================
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) {
            productOptions += `<optgroup label="${escapeHtml(p.name)}">`;
            variants.forEach(v => { productOptions += `<option value="${p.id}" data-price="${v.harga}">${escapeHtml(p.name)} - ${escapeHtml(v.nama)}</option>`; });
            productOptions += `</optgroup>`;
        } else productOptions += `<option value="${p.id}" data-price="${p.price}">${escapeHtml(p.name)}</option>`;
    });
    const activeTenors = CREDIT.tenors.filter(t => String(t.is_active) === '1').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 min-h-screen pt-20 pb-24 page-enter-placeholder">
        <div class="container mx-auto px-4 max-w-4xl">
            ${secHdr('', 'Simulasi Kredit', 'Hitung estimasi cicilan kendaraan impian Anda')}
            <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
                <!-- Input Panel -->
                <div class="bg-white p-8 rounded-2xl shadow-md border border-gray-100">
                    <form oninput="calcSimulasi()" aria-label="Form simulasi kredit" novalidate>
                        <div class="mb-6">
                            <label for="sim-model" 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 transition">
                                <option value="" data-price="0">-- Pilih Mobil --</option>${productOptions}
                            </select>
                        </div>
                        <div class="mb-6">
                            <label for="sim-price-display" 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 aria-readonly="true" placeholder="Rp 0">
                        </div>
                        <div class="mb-6">
                            <div class="flex justify-between mb-2">
                                <label for="sim-dp" class="block text-sm font-bold text-gray-700">DP Murni (%)</label>
                                <span id="dp-label" class="font-bold text-toyota-red" aria-live="polite">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-full appearance-none cursor-pointer accent-toyota-red"
                                aria-label="Persentase uang muka">
                            <div class="flex justify-between text-xs text-gray-400 mt-1"><span>20%</span><span>80%</span></div>
                        </div>
                        <div class="mb-2">
                            <label for="sim-tenor" class="block text-sm font-bold text-gray-700 mb-2">Tenor Cicilan</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 transition">
                                ${tenorOptions}
                            </select>
                        </div>
                    </form>
                </div>
                <!-- Result Panel -->
                <div class="bg-toyota-dark text-white p-8 rounded-2xl shadow-xl flex flex-col justify-between relative overflow-hidden">
                    <div class="absolute top-0 right-0 w-56 h-56 bg-toyota-red opacity-10 rounded-full blur-3xl -mr-16 -mt-16 pointer-events-none" aria-hidden="true"></div>
                    <div class="relative z-10">
                        <h2 class="text-sm font-bold text-gray-400 mb-8 uppercase tracking-widest">Hasil Simulasi</h2>
                        <div class="mb-8 p-5 bg-white/5 rounded-2xl border border-white/10">
                            <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" aria-live="polite">Rp 0</p>
                        </div>
                        <div class="mb-8 p-5 bg-white/5 rounded-2xl border border-white/10">
                            <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" aria-live="polite">Rp 0</p>
                        </div>
                    </div>
                    <a id="wa-link" href="#" target="_blank" rel="noopener noreferrer"
                        class="relative z-10 w-full block bg-[#25D366] hover:bg-[#1ebe5d] text-white font-bold py-4 rounded-xl text-center transition active:scale-95 shadow-lg flex items-center justify-center gap-2">
                        <i class="fa-brands fa-whatsapp text-xl" aria-hidden="true"></i> Ajukan Sekarang
                    </a>
                </div>
            </div>
            <p class="text-center text-xs text-gray-400 mt-6 max-w-2xl mx-auto">
                * Simulasi bersifat estimasi. Angka final dapat berbeda tergantung kebijakan leasing, asuransi, dan promo yang berlaku.
            </p>
        </div>
    </div>`;
}

// ============================================================
// PROMO DETAIL
// ============================================================
function renderPromoDetail(id) {
    const p = DB.promos.find(x => x.id == id);
    if (!p) return renderPromo();
    const mediaHtml = getMediaHtml(p.video || p.image || p.gambar_url, "w-full h-full object-cover", true, true, `Promo ${escapeHtml(p.title || p.judul)}`);
    const breadcrumbHtml = `
        <nav aria-label="Breadcrumb" class="mb-8">
            <ol class="flex items-center gap-2 text-sm text-gray-400">
                <li><button onclick="navigate('home')" class="hover:text-toyota-red transition">Home</button></li>
                <li aria-hidden="true"><i class="fa-solid fa-chevron-right text-xs"></i></li>
                <li><button onclick="navigate('promo')" class="hover:text-toyota-red transition">Promo</button></li>
                <li aria-hidden="true"><i class="fa-solid fa-chevron-right text-xs"></i></li>
                <li class="text-gray-700 font-medium" aria-current="page">${escapeHtml(p.title || p.judul)}</li>
            </ol>
        </nav>`;
    return `
    <div class="bg-white min-h-screen pt-20 pb-24 page-enter-placeholder">
        <div class="container mx-auto px-4 max-w-3xl">
            ${breadcrumbHtml}
            <h1 class="text-2xl md:text-3xl font-bold text-gray-900 mb-6 leading-tight">${escapeHtml(p.title || p.judul)}</h1>
            <div class="rounded-2xl overflow-hidden shadow-xl mb-8 border border-gray-100 aspect-video">
                ${mediaHtml}
            </div>
            <div class="article-content text-gray-700">
                ${p.desc || p.deskripsi || '<p>Segera manfaatkan promo ini. Berlaku terbatas!</p>'}
            </div>
            <div class="mt-10 p-6 bg-gray-50 rounded-2xl border border-gray-100">
                <p class="text-gray-600 text-sm mb-4">Tertarik dengan promo ini? Hubungi sales kami sekarang.</p>
                <button onclick="trackLeadAndChat('Promo Detail', '${(p.title||p.judul).replace(/'/g,"\\'")}', 'Halo, saya mau tanya tentang promo: ${(p.title||p.judul).replace(/'/g,"\\'")}', this)"
                    class="w-full bg-[#25D366] text-white py-4 rounded-xl font-bold hover:bg-[#1ebe5d] transition active:scale-95 flex items-center justify-center gap-2 shadow-md">
                    <i class="fa-brands fa-whatsapp text-xl" aria-hidden="true"></i> Tanya Promo Ini
                </button>
            </div>
        </div>
    </div>`;
}

// ============================================================
// ARTIKEL DETAIL
// ============================================================
function renderArtikelDetail(id) {
    const a = DB.articles.find(x => x.id == id);
    if (!a) return `<div class="p-20 text-center">${emptyState('fa-newspaper', 'Artikel tidak ditemukan.', 'Lihat Semua Artikel', 'artikel')}</div>`;
    const isoDate = a.raw_date ? new Date(a.raw_date).toISOString() : '';
    const breadcrumbHtml = `
        <nav aria-label="Breadcrumb" class="mb-8">
            <ol class="flex items-center gap-2 text-sm text-gray-400">
                <li><button onclick="navigate('home')" class="hover:text-toyota-red transition">Home</button></li>
                <li aria-hidden="true"><i class="fa-solid fa-chevron-right text-xs"></i></li>
                <li><button onclick="navigate('artikel')" class="hover:text-toyota-red transition">Artikel</button></li>
                <li aria-hidden="true"><i class="fa-solid fa-chevron-right text-xs"></i></li>
                <li class="text-gray-700 font-medium line-clamp-1 max-w-xs" aria-current="page">${escapeHtml(a.title)}</li>
            </ol>
        </nav>`;
    return `
    <div class="bg-white min-h-screen pt-20 pb-24 page-enter-placeholder">
        <div class="container mx-auto px-4 max-w-3xl">
            ${breadcrumbHtml}
            <h1 class="text-2xl md:text-3xl font-bold text-gray-900 mb-4 leading-tight">${escapeHtml(a.title)}</h1>
            <div class="flex items-center gap-2 text-sm text-gray-400 mb-8 pb-6 border-b border-gray-100">
                <i class="fa-regular fa-calendar" aria-hidden="true"></i>
                <time datetime="${isoDate}">${a.date}</time>
            </div>
            <img src="${a.image}" class="w-full rounded-2xl shadow-md mb-10 border border-gray-100 aspect-[16/9] object-cover"
                 alt="${escapeHtml(a.title)}" width="800" height="450" loading="eager"
                 onerror="this.src='https://via.placeholder.com/800x450?text=No+Image'">
            <div class="article-content">${a.content}</div>
            <div class="mt-12 pt-8 border-t border-gray-100">
                <button onclick="navigate('artikel')"
                    class="inline-flex items-center gap-2 text-toyota-red font-bold hover:underline">
                    <i class="fa-solid fa-arrow-left" aria-hidden="true"></i> Kembali ke Daftar Artikel
                </button>
            </div>
        </div>
    </div>`;
}

// ============================================================
// KONTAK
// ============================================================
function renderKontak() {
    const s = SITE_CONFIG.sales;
    const brand = SITE_CONFIG.brand || 'Mobil';
    const sosmedHtml = buildSosmedLinks(s);
    return `
    <div class="bg-gray-50 min-h-screen pt-20 pb-24 page-enter-placeholder">
        <div class="container mx-auto px-4 max-w-5xl">
            ${secHdr('', 'Hubungi Kami', 'Siap membantu Anda menemukan kendaraan impian')}
            <div class="bg-gradient-to-br from-toyota-dark to-gray-900 rounded-2xl p-8 md:p-12 shadow-2xl text-white flex flex-col md:flex-row items-center gap-8 md:gap-12 relative overflow-hidden mb-8">
                <img src="${s.foto_profil_url}" class="w-36 h-36 md:w-44 md:h-44 rounded-full border-4 border-toyota-red object-cover relative z-10 shrink-0"
                     alt="Foto ${escapeHtml(s.nama_lengkap)}" width="176" height="176" loading="eager">
                <div class="flex-1 relative z-10 text-center md:text-left">
                    <h2 class="text-3xl md:text-4xl font-bold mb-1">${escapeHtml(s.nama_lengkap)}</h2>
                    <p class="text-toyota-red font-bold text-lg uppercase tracking-wider">${escapeHtml(s.jabatan || 'Sales Executive')}</p>
                    <p class="mt-2 text-gray-400 text-sm">${escapeHtml(SITE_CONFIG.nama_cabang)}</p>
                    <div class="flex flex-wrap justify-center md:justify-start gap-3 mt-6">
                        <a href="tel:${s.no_wa}"
                            class="bg-white text-toyota-dark px-6 py-2.5 rounded-xl font-bold hover:bg-gray-100 transition active:scale-95"
                            aria-label="Telepon ${escapeHtml(s.nama_lengkap)}">
                            <i class="fa-solid fa-phone mr-1" aria-hidden="true"></i> Telepon
                        </a>
                        <button onclick="trackLeadAndChat('Kontak', 'General', 'Halo ${escapeHtml(s.nama_lengkap)}, saya mau tanya info ${brand}.', this)"
                            class="bg-[#25D366] text-white px-6 py-2.5 rounded-xl font-bold hover:bg-[#1ebe5d] transition active:scale-95">
                            <i class="fa-brands fa-whatsapp mr-1" aria-hidden="true"></i> WhatsApp
                        </button>
                    </div>
                    ${sosmedHtml}
                </div>
                <div class="absolute top-0 right-0 w-72 h-72 bg-toyota-red opacity-5 rounded-full blur-3xl -mr-20 -mt-20 pointer-events-none" aria-hidden="true"></div>
            </div>
            <div class="rounded-2xl overflow-hidden h-80 shadow-md border border-gray-200">
                <iframe src="${SITE_CONFIG.google_map_embed}" width="100%" height="100%" style="border:0;"
                        allowfullscreen loading="lazy" title="Peta lokasi ${escapeHtml(SITE_CONFIG.nama_cabang)}"></iframe>
            </div>
        </div>
    </div>`;
}

// =========================================================
// TOAST NOTIFICATION
// =========================================================
function showToast(msg, type = 'info') {
    let container = document.getElementById('toast-container');
    if (!container) {
        container = document.createElement('div');
        container.id = 'toast-container';
        container.style.cssText = 'position:fixed;top:80px;right:16px;z-index:9998;display:flex;flex-direction:column;gap:8px;';
        document.body.appendChild(container);
    }
    const colors = { success: '#16a34a', error: '#dc2626', info: '#2563eb', warning: '#d97706' };
    const icons  = { success: 'fa-check-circle', error: 'fa-circle-exclamation', info: 'fa-circle-info', warning: 'fa-triangle-exclamation' };
    const toast  = document.createElement('div');
    toast.style.cssText = `background:${colors[type]||colors.info};color:#fff;padding:12px 18px;border-radius:10px;font-size:14px;font-weight:600;max-width:320px;box-shadow:0 4px 12px rgba(0,0,0,.15);display:flex;align-items:center;gap:8px;animation:fadeIn .3s ease;`;
    toast.innerHTML = `<i class="fa-solid ${icons[type]||icons.info}"></i><span>${escapeHtml(msg)}</span>`;
    container.appendChild(toast);
    setTimeout(() => { toast.style.opacity = '0'; toast.style.transition = 'opacity .3s'; setTimeout(() => toast.remove(), 300); }, 3500);
}

// =========================================================
// 7. UTILITIES
// =========================================================

// Halaman 404
function renderNotFound(route) {
    return `
    <div class="min-h-screen flex items-center justify-center bg-gray-50 page-enter-placeholder">
        <div class="text-center px-4">
            <div class="text-9xl font-black text-gray-200 mb-4">404</div>
            <h1 class="text-3xl font-bold text-gray-700 mb-2">Halaman Tidak Ditemukan</h1>
            <p class="text-gray-500 mb-8">Halaman <code class="bg-gray-100 px-2 py-1 rounded text-sm">${escapeHtml(route)}</code> tidak tersedia.</p>
            <button onclick="navigate('home')" class="bg-toyota-red text-white px-8 py-3 rounded-full font-bold hover:bg-red-700 transition">
                <i class="fa-solid fa-house mr-2" aria-hidden="true"></i> Kembali ke Beranda
            </button>
        </div>
    </div>`;
}

window.toggleMobileMenu = function() {
    const menu = document.getElementById('mobile-menu');
    const btn  = document.querySelector('button[aria-controls="mobile-menu"]');
    const isHidden = menu.classList.toggle('hidden');
    if (btn) btn.setAttribute('aria-expanded', String(!isHidden));
};
window.mobileNavClick = function(route) { navigate(route); };

// =========================================================
// 8. INIT
// =========================================================
window.addEventListener('load', () => {
    initFloatingButton();
    const params = new URLSearchParams(window.location.search);
    const page   = params.get('page');
    const id     = params.get('id');
    setTimeout(() => {
        const loader = document.getElementById('loader');
        loader.style.opacity = '0';
        setTimeout(() => {
            loader.style.display = 'none';
            if (page) navigate(page, id);
            else navigate('home');
        }, 400);
    }, 500);
});