/**
 * InventoryView.js — ماژول انبارداری
 * بخش‌ها: موجودی | اسناد | محصولات | انبارها | بچ | سریال | گزارش‌ها
 */

import BaseView from "../../core/BaseView.js";
import { viewRegistry } from "../../core/registries.js";
import StockSection      from "./sections/StockSection.js";
import VouchersSection   from "./sections/VouchersSection.js";
import InvProductsSection from "./sections/InvProductsSection.js";
import WarehousesSection from "./sections/WarehousesSection.js";
import BatchesSection    from "./sections/BatchesSection.js";
import SerialsSection    from "./sections/SerialsSection.js";
import InvReportsSection from "./sections/InvReportsSection.js";

const SECTIONS = [
    { key: "stock",      icon: "📊", title: "موجودی انبار",   desc: "وضعیت فعلی",       Class: StockSection },
    { key: "vouchers",   icon: "📄", title: "اسناد حرکت",     desc: "ورود و خروج",       Class: VouchersSection },
    { key: "products",   icon: "🗂️", title: "محصولات",         desc: "کالاها و دسته‌ها",  Class: InvProductsSection },
    { key: "warehouses", icon: "🏭", title: "انبارها",          desc: "مکان‌های نگهداری",  Class: WarehousesSection },
    { key: "batches",    icon: "📦", title: "بچ / لات",         desc: "دسته‌های تولیدی",   Class: BatchesSection },
    { key: "serials",    icon: "🔢", title: "سریال نامبر",      desc: "ردیابی تک‌واحدی",   Class: SerialsSection },
    { key: "reports",    icon: "📈", title: "گزارش‌ها",          desc: "کاردکس و ارزش‌گذاری", Class: InvReportsSection },
];

export default class InventoryView extends BaseView {

    static title = "انبار";

    useContextBadge = true;

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

    async template() {
        const cards = SECTIONS.map(s => `
            <div class="sp-nav-card ${s.key === this._active ? "sp-nav-card--active" : ""}"
                 data-section="${s.key}" role="button" tabindex="0">
                <span class="sp-nav-card__icon">${s.icon}</span>
                <div class="sp-nav-card__title">${s.title}</div>
                <div class="sp-nav-card__desc">${s.desc}</div>
            </div>
        `).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="sp-section-nav" data-ref="navBar">${cards}</div>
            <div>${panels}</div>
        `;
    }

    async afterRender() {
        this.ref("navBar").querySelectorAll(".sp-nav-card").forEach(c => {
            this.on(c, "click", () => this._switch(c.dataset.section));
        });
        await this._mount(this._active);
    }

    async _switch(key) {
        if (key === this._active) return;
        this.ref("navBar").querySelectorAll(".sp-nav-card").forEach(c =>
            c.classList.toggle("sp-nav-card--active", c.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("inventory", InventoryView);
