/**
 * WppCategoriesSection.js — دسته‌بندی‌های محصولات
 */
import SectionBase from "../../accounting/SectionBase.js";

export default class WppCategoriesSection extends SectionBase {

    _categories = [];

    async template() {
        return `
        <div class="acc-section-wrap" dir="rtl">
            <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() {
        this.on(this.ref("refreshBtn"), "click", () => this._load());
        await this._load();
    }

    async _load() {
        this.ref("wrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            const res = await this.api.get("wp/categories");
            this._categories = res?.data ?? [];
            this._render();
        } catch (e) {
            this.ref("wrap").innerHTML = `<div class="acc-error">❌ ${this.escape(e.message)}</div>`;
        }
    }

    _render() {
        const wrap = this.ref("wrap");
        if (!this._categories.length) {
            wrap.innerHTML = `<div class="acc-empty">دسته‌بندی‌ای یافت نشد</div>`;
            return;
        }
        wrap.innerHTML = `
        <div class="wpp-cat-grid">
            ${this._categories.map(c => `
            <div class="wpp-cat-card">
                <div class="wpp-cat-card-img">
                    ${c.image ? `<img src="${this.escape(c.image)}" alt="${this.escape(c.name)}">` : `<div class="wpp-cat-card-placeholder">📂</div>`}
                </div>
                <div class="wpp-cat-card-body">
                    <h3 class="wpp-cat-card-title">${this.escape(c.name)}</h3>
                    ${c.description ? `<p class="wpp-cat-card-desc">${this.escape(c.description.slice(0, 80))}${c.description.length > 80 ? '…' : ''}</p>` : ''}
                    <span class="wpp-cat-card-count">${c.count} محصول</span>
                </div>
            </div>`).join("")}
        </div>`;
    }

    escape(s) { return String(s ?? "").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"); }
}
