const API = window.ACC_CFG?.api || '/acc-engine/api.php/acc/v1';

async function loadStats() {
    try {
        const r = await fetch(API + '/public/platform/stats');
        const j = await r.json();
        const d = j.data || {};
        document.getElementById('st-orders').textContent = (d.orders_total ?? 0).toLocaleString('fa-IR');
        document.getElementById('st-products').textContent = (d.products ?? 0).toLocaleString('fa-IR');
        if (d.api_endpoints) document.getElementById('st-api').textContent = d.api_endpoints + '+';
    } catch { /* ignore */ }
}

async function loadPlans() {
    const el = document.getElementById('pl-plans');
    try {
        const r = await fetch(API + '/public/platform/features');
        const j = await r.json();
        const plans = j.data?.plans || [];
        el.innerHTML = plans.map(p => `
        <div class="pl-plan${p.popular ? ' pl-plan--pop' : ''}">
            ${p.popular ? '<span class="pl-plan__badge">پرفروش</span>' : ''}
            <h3>${p.name}</h3>
            <div class="pl-plan__price">${p.price_label}</div>
            <div class="pl-plan__tag">${p.tagline}</div>
            <ul>${(p.features || []).slice(0, 8).map(f => `<li>${(j.data?.labels || {})[f] || f}</li>`).join('')}</ul>
        </div>`).join('');
    } catch {
        el.textContent = 'خطا در بارگذاری پلن‌ها';
    }
}

document.getElementById('pl-demo-form')?.addEventListener('submit', async e => {
    e.preventDefault();
    const msg = document.getElementById('pl-demo-msg');
    const fd = new FormData(e.target);
    const body = Object.fromEntries(fd.entries());
    msg.hidden = true;
    try {
        const r = await fetch(API + '/public/platform/demo-request', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(body),
        });
        const j = await r.json();
        if (!r.ok || !j.success) throw new Error(j.message || 'خطا');
        msg.hidden = false;
        msg.className = 'ok';
        msg.textContent = j.message || 'ثبت شد';
        e.target.reset();
    } catch (err) {
        msg.hidden = false;
        msg.className = 'err';
        msg.textContent = err.message;
    }
});

loadStats();
loadPlans();
