/**
 * ServiceDashboardSection.js — داشبورد خدمات میدانی
 */
import SectionBase from "../../accounting/SectionBase.js";

export default class ServiceDashboardSection 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("service/dashboard");
            const d = res?.data ?? {};
            this.ref("wrap").innerHTML = `
            <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:12px;">
                ${this._card("📋 باز", d.open_requests, "#6366f1")}
                ${this._card("📅 امروز", d.today_requests, "#3b82f6")}
                ${this._card("✅ ماه", d.completed_month, "#059669")}
                ${this._card("💰 درآمد ماه", Number(d.revenue_month||0).toLocaleString("fa-IR"), "#1d4ed8")}
                ${this._card("📝 پیش‌نویس", d.draft_reports, "#f59e0b")}
                ${this._card("📅 PM فعال", d.pm_contracts, "#8b5cf6")}
            </div>`;
        } catch (e) {
            this.ref("wrap").innerHTML = `<div class="acc-error">❌ ${this.escape(e.message)}</div>`;
        }
    }

    _card(label, value, color) {
        return `
        <div style="background:#fff;border:1px solid #e2e8f0;border-radius:12px;padding:16px;border-top:3px solid ${color};">
            <div style="font-size:11px;color:#64748b;">${label}</div>
            <div style="font-size:22px;font-weight:800;color:${color};margin-top:4px;">${value ?? 0}</div>
        </div>`;
    }
}
