/**
 * WpProductsView.js — محصولات فروشگاه وردپرس
 * بخش‌ها: نمایش محصولات | دسته‌بندی‌ها
 */

import BaseView from "../../core/BaseView.js";
import { viewRegistry } from "../../core/registries.js";
import WppShopSection       from "./sections/WppShopSection.js";
import WppCategoriesSection from "./sections/WppCategoriesSection.js";

const SECTIONS = [
    { key: "shop",       icon: "🛍️", title: "محصولات",       Class: WppShopSection       },
    { key: "categories", icon: "📂", title: "دسته‌بندی‌ها",   Class: WppCategoriesSection },
];

export default class WpProductsView extends BaseView {

    static title = "🛍️ محصولات فروشگاه";
    useContextBadge = false;

    constructor(props = {}) {
        super(props);
        this.api       = props.api;
        this._active   = "shop";
        this._sections = {};
    }

    async template() {
        // تب‌های بخش — ردیف زیر هدر BaseView
        const sectionTabs = SECTIONS.map(s => `
            <button class="wpp-sec-tab ${s.key === this._active ? "wpp-sec-tab--active" : ""}"
                    data-section="${s.key}" type="button">
                ${s.icon} ${s.title}
            </button>
        `).join("");

        const panels = SECTIONS.map(s => `
            <div class="acc-section ${s.key === this._active ? "acc-section--active" : ""}"
                 data-panel="${s.key}" data-ref="panel-${s.key}"></div>
        `).join("");

        return `
            <div class="wpp-sec-tabs" data-ref="navBar">${sectionTabs}</div>
            <div class="wpp-sec-panels">${panels}</div>
        `;
    }

    async afterRender() {
        this.ref("navBar").querySelectorAll(".wpp-sec-tab").forEach(btn => {
            this.on(btn, "click", () => this._switch(btn.dataset.section));
        });
        await this._mount(this._active);
    }

    async _switch(key) {
        if (key === this._active) return;
        this.ref("navBar").querySelectorAll(".wpp-sec-tab").forEach(b =>
            b.classList.toggle("wpp-sec-tab--active", b.dataset.section === key)
        );
        this.container.querySelectorAll(".acc-section").forEach(p =>
            p.classList.toggle("acc-section--active", p.dataset.panel === key)
        );
        this._active = key;
        await this._mount(key);
    }

    async _mount(key) {
        if (this._sections[key]) return;
        const def   = SECTIONS.find(s => s.key === key);
        const panel = this.ref(`panel-${key}`);
        if (!def || !panel) return;
        const sec = new def.Class({ eventBus: this.eventBus, store: this.store, tab: this.tab, api: this.api });
        await sec.render(panel);
        this._sections[key] = sec;
    }

    destroy() {
        Object.values(this._sections).forEach(s => s?.destroy?.());
        super.destroy();
    }
}

viewRegistry.register("wpproducts", WpProductsView);
