/**
 * ShippingDashboardSection.js — داشبورد حمل و نقل
 */
import SectionBase from "../../accounting/SectionBase.js";

const STATUS_COLORS = {
    pending:'#94a3b8', ordered:'#6366f1', preparing:'#3b82f6', packed:'#06b6d4',
    picked_up:'#8b5cf6', in_transit:'#f59e0b', out_for_delivery:'#f97316',
    arrived:'#10b981', inspection:'#eab308', received:'#059669',
    delivered:'#059669', rejected:'#ef4444', failed:'#ef4444',
    returned:'#dc2626', cancelled:'#64748b',
};

const STATUS_LABELS = {
    pending:'در انتظار', ordered:'سفارش شده', preparing:'آماده‌سازی', packed:'بسته‌بندی شده',
    picked_up:'تحویل به حمل', in_transit:'در حال حمل', out_for_delivery:'ارسال نهایی',
    arrived:'رسید', inspection:'بازرسی', received:'پذیرفته شد',
    delivered:'تحویل مشتری', rejected:'رد شد', failed:'ناموفق',
    returned:'مرجوعی', cancelled:'لغو شد',
};

export default class ShippingDashboardSection extends SectionBase {

    async template() {
        return `
        <div class="acc-section-wrap">
            <div class="acc-toolbar">
                <h2 class="acc-section-title">📊 داشبورد حمل و نقل</h2>
                <button class="acc-btn acc-btn--secondary" data-ref="refreshBtn">🔄</button>
            </div>
            <div data-ref="wrap"><div class="acc-loading">⏳ بارگذاری...</div></div>
        </div>`;
    }

    async afterRender() {
        await this._load();
        this.on(this.ref("refreshBtn"), "click", () => this._load());
    }

    async _load() {
        this.ref("wrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            const res = await this.api.get("/ship/dashboard");
            this._render(res);
        } catch { this.ref("wrap").innerHTML = `<div class="acc-error">❌ خطا</div>`; }
    }

    _render(d) {
        const byStatus = (d.by_status ?? []).reduce((acc, r) => {
            const k = `${r.direction}:${r.status}`;
            acc[k] = (acc[k] ?? 0) + parseInt(r.cnt);
            return acc;
        }, {});

        const inboundStatuses  = ['pending','ordered','preparing','picked_up','in_transit','arrived','inspection','received'];
        const outboundStatuses = ['pending','preparing','packed','picked_up','in_transit','out_for_delivery','delivered'];

        const renderRow = (direction, statuses, title, icon) => {
            const total = statuses.reduce((s, st) => s + (byStatus[`${direction}:${st}`] ?? 0), 0);
            return `
            <div style="background:#fff;border:1px solid #e2e8f0;border-radius:10px;padding:14px;margin-bottom:12px;">
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;">
                    <h3 style="margin:0;font-size:14px;">${icon} ${title}</h3>
                    <span style="background:#eff6ff;color:#1e40af;padding:2px 10px;border-radius:10px;font-size:12px;font-weight:700;">جمع: ${total}</span>
                </div>
                <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(110px,1fr));gap:6px;">
                    ${statuses.map(st => {
                        const cnt = byStatus[`${direction}:${st}`] ?? 0;
                        const color = STATUS_COLORS[st] ?? '#64748b';
                        return `
                        <div style="background:${color}1a;border:1px solid ${color}55;border-radius:8px;padding:8px;text-align:center;cursor:pointer;"
                             data-filter='{"direction":"${direction}","status":"${st}"}'>
                            <div style="font-size:10px;color:${color};font-weight:600;">${STATUS_LABELS[st]}</div>
                            <div style="font-size:18px;font-weight:700;color:${color};">${cnt}</div>
                        </div>`;
                    }).join("")}
                </div>
            </div>`;
        };

        this.ref("wrap").innerHTML = `
        <!-- KPI cards -->
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px;margin-bottom:16px;">
            <div style="background:linear-gradient(135deg,#3b82f6,#1d4ed8);color:#fff;padding:14px;border-radius:10px;">
                <div style="font-size:11px;opacity:.85;">🚚 محموله فعال</div>
                <div style="font-size:28px;font-weight:700;margin-top:4px;">${d.active_count ?? 0}</div>
            </div>
            <div style="background:linear-gradient(135deg,#ef4444,#dc2626);color:#fff;padding:14px;border-radius:10px;">
                <div style="font-size:11px;opacity:.85;">⏰ تأخیردار</div>
                <div style="font-size:28px;font-weight:700;margin-top:4px;">${d.delayed_count ?? 0}</div>
            </div>
            <div style="background:linear-gradient(135deg,#10b981,#059669);color:#fff;padding:14px;border-radius:10px;">
                <div style="font-size:11px;opacity:.85;">⭐ کیفیت میانگین</div>
                <div style="font-size:28px;font-weight:700;margin-top:4px;">${d.avg_quality ?? 0}<small style="font-size:14px;">/100</small></div>
            </div>
            <div style="background:linear-gradient(135deg,#f59e0b,#d97706);color:#fff;padding:14px;border-radius:10px;">
                <div style="font-size:11px;opacity:.85;">⏱️ زمان میانگین (ساعت)</div>
                <div style="font-size:28px;font-weight:700;margin-top:4px;">${d.avg_time?.avg_hours ? Math.round(d.avg_time.avg_hours) : '—'}</div>
            </div>
        </div>

        ${renderRow('inbound',  inboundStatuses,  'محموله‌های ورودی (خرید)', '📥')}
        ${renderRow('outbound', outboundStatuses, 'محموله‌های خروجی (فروش)', '📤')}
        `;

        this.ref("wrap").querySelectorAll("[data-filter]").forEach(el =>
            el.addEventListener("click", () => this._toast("💡 برای فیلتر دقیق به بخش «محموله‌ها» بروید", "#3b82f6"))
        );
    }

    escape(s) { return String(s ?? "").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"); }
    _toast(m, b = "#10b981") {
        const t = document.createElement("div");
        t.style.cssText = `position:fixed;bottom:24px;left:24px;background:${b};color:#fff;padding:12px 20px;border-radius:10px;font-size:13px;z-index:9999;`;
        t.textContent = m; document.body.appendChild(t); setTimeout(() => t.remove(), 3000);
    }
}
