// 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
// =========================================================
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);

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 safeHtml(html) {
    if (typeof DOMPurify !== 'undefined') {
        return DOMPurify.sanitize(html || '', {
            ALLOWED_TAGS: ['p','br','b','strong','i','em','u','ul','ol','li','h2','h3','h4','span','a','img','table','thead','tbody','tr','th','td','div','blockquote'],
            ALLOWED_ATTR: ['href','src','alt','class','target','rel','style','width','height'],
            ALLOW_DATA_ATTR: false,
        });
    }
    return (html || '').replace(/<script[\s\S]*?<\/script>/gi, '');
}

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.onerror=null;this.src='assets/images/no-image.svg'">`;
    }
}

function trackLeadAndChat(source, detail, message, btnEl) {
    const sourceLabel = `Button: ${source} - ${detail}`;
    fireTrackingEvents(sourceLabel);

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

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

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
// =========================================================

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>`;
}

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>`;
}

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.onerror=null;this.src='assets/images/no-image.svg'">
                    <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.onerror=null;this.src='assets/images/no-image.svg'">
                    <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 ---
    let testimonialsList = Array.isArray(DB.testimonials) ? [...DB.testimonials] : [];
    testimonialsList.sort((a, b) => {
        const dateA = new Date(a.tanggal_serah_terima || 0);
        const dateB = new Date(b.tanggal_serah_terima || 0);
        return dateB - dateA;
    });

    let testimoniHtml = '';
    if (testimonialsList.length) {
        const topTesti = testimonialsList.slice(0, 3);
        const testiCards = topTesti.map(t => renderSingleCard(t)).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">

        <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>

        <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>

        ${productSectionHtml}

        ${artikelHtml}

        <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>

        <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>`;
}

// ============================================================
// 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.onerror=null;this.src='assets/images/no-image.svg'">
                <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('');
}

window.applyProductFilter = function() {
    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'); }
};

window.resetFilter = function() {
    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 (FIXED)
// ============================================================
function renderTestimoni() {
    let testimonials = Array.isArray(DB.testimonials) ? [...DB.testimonials] : [];
    
    // Sort aman: cek apakah tanggal valid
    testimonials.sort((a, b) => {
        const dateA = new Date(a.tanggal_serah_terima || 0);
        const dateB = new Date(b.tanggal_serah_terima || 0);
        return dateB - dateA;
    });

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

    // Bagi data ke 3 kolom secara bergantian (Zig-zag)
    const colData = [[], [], []]; 
    testimonials.forEach((t, idx) => {
        colData[idx % 3].push(t);
    });

    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() !== '';

    // Avatar
    const name        = t.name || 'Customer';
    const initial     = name.charAt(0).toUpperCase();
    const bgColor     = isGoogle ? '4285F4' : 'EB0A1E';
    const avatarFallback = `https://ui-avatars.com/api/?name=${encodeURIComponent(initial)}&size=96&background=${bgColor}&color=fff&bold=true&length=1`;
    const avatarSrc   = (t.profile_photo && !t.profile_photo.includes('foto_serah'))
        ? t.profile_photo : avatarFallback;

    // Bintang SVG
    let stars = '';
    for (let i = 0; i < 5; i++) {
        stars += `<svg width="14" height="14" viewBox="0 0 24 24" fill="${i < rating ? '#FBBC04' : '#E0E0E0'}" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
            <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
        </svg>`;
    }

    function relativeDate(dateStr) {
        if (!dateStr) return '';
        const d = new Date(dateStr);
        if (isNaN(d)) return dateStr;
        const diff = Math.floor((Date.now() - d) / 1000);
        if (diff < 60)     return 'Baru saja';
        if (diff < 3600)   return Math.floor(diff/60) + ' menit lalu';
        if (diff < 86400)  return Math.floor(diff/3600) + ' jam lalu';
        if (diff < 604800) return Math.floor(diff/86400) + ' hari lalu';
        if (diff < 2592000) return Math.floor(diff/604800) + ' minggu lalu';
        if (diff < 31536000) return Math.floor(diff/2592000) + ' bulan lalu';
        return Math.floor(diff/31536000) + ' tahun lalu';
    }

    const MAX_LEN = 180;
    const fullText  = hasText ? escapeHtml(t.text) : '';
    const shortText = fullText.length > MAX_LEN
        ? fullText.slice(0, MAX_LEN).trimEnd() + '…'
        : fullText;
    const needsExpand = fullText.length > MAX_LEN;
    const cardId = 'tcard_' + (t.id || Math.random().toString(36).slice(2));

    const textHtml = hasText ? `
        <div class="mt-3">
            <p id="${cardId}_short" class="text-[13.5px] text-gray-700 leading-relaxed">${shortText}${needsExpand
                ? ` <button onclick="toggleReview('${cardId}')" class="text-blue-600 font-medium hover:underline text-[13px] ml-1">Selengkapnya</button>`
                : ''}</p>
            ${needsExpand ? `<p id="${cardId}_full" class="text-[13.5px] text-gray-700 leading-relaxed hidden">${fullText}
                <button onclick="toggleReview('${cardId}')" class="text-blue-600 font-medium hover:underline text-[13px] ml-1">Lebih sedikit</button></p>` : ''}
        </div>` : '';

    const deliveryHtml = hasDelivery ? `
        <div class="mt-3 rounded-xl overflow-hidden relative bg-gray-100 cursor-pointer"
             onclick="openLightbox('${t.delivery_photo}', '${escapeHtml(t.car || 'Serah Terima')}')"
             role="button" aria-label="Lihat foto serah terima ${escapeHtml(t.car || '')}">
            <img src="${t.delivery_photo}"
                 class="w-full object-cover max-h-52 hover:opacity-90 transition"
                 loading="lazy"
                 onerror="this.closest('.mt-3').style.display='none'"
                 alt="Foto serah terima ${escapeHtml(t.car || 'Toyota')}">
            <div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/50 to-transparent px-3 py-2 pointer-events-none">
                <span class="text-white text-[11px] font-semibold">${escapeHtml(t.car || 'Serah Terima Unit')}</span>
            </div>
        </div>` : '';

    const sourceBadge = isGoogle
        ? `<div class="flex items-center gap-1 ml-auto flex-shrink-0" title="Ulasan dari Google">
               <svg width="14" height="14" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-label="Google">
                   <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
                   <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
                   <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.84z" fill="#FBBC05"/>
                   <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/>
               </svg>
           </div>`
        : '';

    return `
    <article class="bg-white rounded-2xl shadow-sm border border-gray-100 p-4 hover:shadow-md transition-shadow">
        <div class="flex items-start gap-3">
            <img src="${avatarSrc}"
                 class="w-10 h-10 rounded-full object-cover flex-shrink-0 border border-gray-100"
                 loading="lazy"
                 onerror="this.src='${avatarFallback}'"
                 alt="Foto ${escapeHtml(name)}">
            <div class="flex-1 min-w-0">
                <div class="flex items-center gap-2">
                    <h3 class="font-semibold text-[14px] text-gray-900 truncate leading-tight">${escapeHtml(name)}</h3>
                    ${sourceBadge}
                </div>
                <div class="flex items-center gap-1.5 mt-1">
                    <div class="flex items-center gap-0.5">${stars}</div>
                    <span class="text-gray-400 text-[11px]">·</span>
                    <time class="text-gray-400 text-[11px]">${relativeDate(t.tanggal_serah_terima)}</time>
                </div>
            </div>
        </div>
        ${textHtml}
        ${deliveryHtml}
    </article>`;
}

window.toggleReview = function(cardId) {
    const short = document.getElementById(cardId + '_short');
    const full  = document.getElementById(cardId + '_full');
    if (!short || !full) return;
    short.classList.toggle('hidden');
    full.classList.toggle('hidden');
};

window.openLightbox = function(src, caption) {
    const existing = document.getElementById('lb_overlay');
    if (existing) existing.remove();
    const overlay = document.createElement('div');
    overlay.id = 'lb_overlay';
    overlay.className = 'fixed inset-0 z-[9999] bg-black/90 flex flex-col items-center justify-center p-4 cursor-zoom-out';
    overlay.setAttribute('role', 'dialog');
    overlay.setAttribute('aria-label', caption || 'Foto');
    overlay.innerHTML = `
        <button onclick="document.getElementById('lb_overlay').remove()"
                class="absolute top-4 right-4 text-white text-3xl leading-none hover:text-gray-300" aria-label="Tutup">&times;</button>
        <img src="${src}" class="max-w-full max-h-[85vh] rounded-xl object-contain shadow-2xl" alt="${caption || 'Foto'}">
        ${caption ? `<p class="text-white/70 text-sm mt-3 text-center">${caption}</p>` : ''}`;
    overlay.addEventListener('click', e => { if (e.target === overlay) overlay.remove(); });
    document.body.appendChild(overlay);
};

// ============================================================
// 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">
                        ${safeHtml(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">
                <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>
                <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">
                ${safeHtml(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.onerror=null;this.src='assets/images/no-image.svg'">
            <div class="article-content">${safeHtml(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>`;
}

// ============================================================
// 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>`;
}

// =========================================================
// 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');
        if(loader) loader.style.opacity = '0';
        setTimeout(() => {
            if(loader) loader.style.display = 'none';
            if (page) navigate(page, id);
            else navigate('home');
        }, 400);
    }, 500);
});

// =========================================================
// 9. SIMULASI KREDIT — KALKULASI
// =========================================================
async function calcSimulasi() {
    const modelEl  = document.getElementById('sim-model');
    const dpEl     = document.getElementById('sim-dp');
    const tenorEl  = document.getElementById('sim-tenor');
    const dpLabel  = document.getElementById('dp-label');
    const dispEl   = document.getElementById('sim-price-display');
    const resDp    = document.getElementById('res-dp');
    const resMonthly = document.getElementById('res-monthly');
    const waLink   = document.getElementById('wa-link');

    if (!modelEl || !dpEl || !tenorEl) return;

    if (dpLabel) dpLabel.textContent = dpEl.value + '%';

    const selectedOption = modelEl.options[modelEl.selectedIndex];
    const price = parseFloat(selectedOption?.dataset?.price || 0);
    const dp    = parseInt(dpEl.value || 20);
    const tenor = parseInt(tenorEl.value || 1);

    try {
        sessionStorage.setItem('sim_model', modelEl.value);
        sessionStorage.setItem('sim_dp', dpEl.value);
        sessionStorage.setItem('sim_tenor', tenorEl.value);
    } catch(e) {}

    if (dispEl) dispEl.value = price > 0 ? formatRupiah(price) : 'Rp 0';

    if (!price || price <= 0) {
        if (resDp)     resDp.textContent = 'Rp 0';
        if (resMonthly) resMonthly.textContent = 'Rp 0';
        return;
    }

    if (resDp)     resDp.textContent = '...';
    if (resMonthly) resMonthly.textContent = '...';

    try {
        const fd = new FormData();
        fd.append('price', price);
        fd.append('dp', dp);
        fd.append('tenor', tenor);

        const res  = await fetch('api.php?action=calculate_credit', { method: 'POST', body: fd });
        const data = await res.json();

        if (data.total_dp !== undefined) {
            if (resDp)     resDp.textContent = formatRupiah(data.total_dp);
            if (resMonthly) resMonthly.textContent = formatRupiah(data.angsuran);

            if (waLink) {
                const modelName = selectedOption?.text || 'Kendaraan Pilihan';
                const msg = `Halo ${SITE_CONFIG.sales?.nama_lengkap || 'Sales'}, saya tertarik dengan:\n\n` +
                    `🚗 *${modelName}*\n` +
                    `💰 Harga OTR: ${formatRupiah(price)}\n` +
                    `📊 DP (${dp}%): ${formatRupiah(price * dp / 100)}\n` +
                    `📅 Tenor: ${tenor} Tahun\n` +
                    `💳 Estimasi TDP: ${formatRupiah(data.total_dp)}\n` +
                    `📆 Cicilan/Bulan: ${formatRupiah(data.angsuran)}\n\n` +
                    `Bisa bantu proses lebih lanjut?`;
                waLink.href = `https://wa.me/${SITE_CONFIG.sales?.no_wa}?text=${encodeURIComponent(msg)}`;
                waLink.onclick = () => {
                    fireTrackingEvents('Simulasi Kredit - ' + modelName);
                    const ffd = new FormData();
                    ffd.append('source', 'Simulasi'); ffd.append('detail', modelName.split(' - ')[0] || modelName);
                    fetch('api.php?action=track_lead', { method: 'POST', body: ffd }).catch(() => {});
                };
            }
        } else {
            if (resDp)     resDp.textContent = 'Error';
            if (resMonthly) resMonthly.textContent = data.status || 'Error';
        }
    } catch(err) {
        console.error('calcSimulasi error:', err);
        if (resDp)     resDp.textContent = 'Gagal';
        if (resMonthly) resMonthly.textContent = 'Cek koneksi';
    }
}

// =========================================================
// 10. TRADE-IN SUBMIT
// =========================================================
function submitTradeIn(event) {
    event.preventDefault();

    const oldCar  = document.getElementById('trade-old-car')?.value?.trim();
    const year    = document.getElementById('trade-year')?.value?.trim();
    const color   = document.getElementById('trade-color')?.value?.trim();
    const km      = document.getElementById('trade-km')?.value?.trim();
    const pajak   = document.getElementById('trade-pajak')?.value?.trim();
    const name    = document.getElementById('trade-name')?.value?.trim();

    if (!oldCar || !year || !color || !km || !pajak || !name) {
        showToast('Mohon lengkapi semua field yang wajib diisi.', 'warning');
        return;
    }

    const transmisi = document.getElementById('trade-transmisi')?.value || 'Automatic';
    const newCar    = document.getElementById('trade-new-car')?.value || '';

    const [pajY, pajM] = pajak.split('-');
    const bulanArr = ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Ags','Sep','Okt','Nov','Des'];
    const pajakStr = bulanArr[parseInt(pajM, 10) - 1] + ' ' + pajY;

    const salesName = SITE_CONFIG.sales?.nama_lengkap || 'Sales';
    const msg = `Halo ${salesName}, saya ingin Trade-In mobil lama saya:\n\n` +
        `🚗 *Mobil Lama:*\n` +
        `  • Merek/Tipe : ${oldCar}\n` +
        `  • Tahun      : ${year}\n` +
        `  • Warna      : ${color}\n` +
        `  • Transmisi  : ${transmisi}\n` +
        `  • KM Odometer: ${parseInt(km, 10).toLocaleString('id-ID')} km\n` +
        `  • Pajak s/d  : ${pajakStr}\n` +
        (newCar ? `\n🆕 *Rencana Ganti:* ${newCar}\n` : '') +
        `\n👤 Nama saya: *${name}*\n\n` +
        `Mohon bantu estimasi harga dan proses Trade-In-nya. Terima kasih!`;

    fireTrackingEvents('Trade-In - ' + (oldCar || 'General'));
    const fd = new FormData();
    fd.append('source', 'Trade-In'); fd.append('detail', oldCar || 'General');
    fetch('api.php?action=track_lead', { method: 'POST', body: fd }).catch(() => {});

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

    showToast('Membuka WhatsApp...', 'success');
}

window.calcSimulasi  = calcSimulasi;
window.submitTradeIn = submitTradeIn;