/**
 * AccountingView.js
 * نمای اصلی ماژول حسابداری — ناوبری ۴ بخش با فلش‌کارت
 */

import BaseView from "../../core/BaseView.js";
import { viewRegistry } from "../../core/registries.js";
import ChartOfAccountsSection from "./sections/ChartOfAccountsSection.js";
import ArticleBankSection from "./sections/ArticleBankSection.js";
import DimensionsSection from "./sections/DimensionsSection.js";
import EventDefinitionSection from "./sections/EventDefinitionSection.js";
import DocumentIssuanceSection from "./sections/DocumentIssuanceSection.js";
import FinancialReportsSection from "./sections/FinancialReportsSection.js";
import AuditSection from "./sections/AuditSection.js";
import AccountingGraphSection from "./sections/AccountingGraphSection.js";

const SECTIONS = [
    {
        key: "coa",
        icon: "🗂",
        title: "سرفصل‌ها",
        desc: "مدیریت درخت حساب‌ها",
        Class: ChartOfAccountsSection,
    },
    {
        key: "articles",
        icon: "🔗",
        title: "بانک آرتیکل",
        desc: "جفت‌های بدهکار/بستانکار",
        Class: ArticleBankSection,
    },
    {
        key: "dimensions",
        icon: "🏷️",
        title: "ابعاد",
        desc: "تفصیلی: مشتری/پروژه/...",
        Class: DimensionsSection,
    },
    {
        key: "events",
        icon: "⚙️",
        title: "Template رویداد",
        desc: "نگاشت pair-based",
        Class: EventDefinitionSection,
    },
    {
        key: "documents",
        icon: "📄",
        title: "صدور سند",
        desc: "ثبت و تأیید رویداد",
        Class: DocumentIssuanceSection,
    },
    {
        key: "reports",
        icon: "📊",
        title: "گزارش مالی",
        desc: "تراز و دفتر کل",
        Class: FinancialReportsSection,
    },
    {
        key: "audit",
        icon: "🛡️",
        title: "حسابرسیِ پیوسته",
        desc: "کنترل‌های آنلاین",
        Class: AuditSection,
    },
    {
        key: "graph",
        icon: "🕸",
        title: "گراف حسابداری",
        desc: "نمودار جریان حساب‌ها",
        Class: AccountingGraphSection,
    },
];

export default class AccountingView extends BaseView {

    static title = "حسابداری هوشمند";

    useContextBadge = true;

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

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

    async afterRender() {
        this._bindNav();
        await this._mountSection(this._active);
    }

    _bindNav() {
        const nav = this.ref("navBar");
        if (!nav) return;

        nav.querySelectorAll(".acc-nav-card").forEach(card => {
            this.on(card, "click", () => this._switchSection(card.dataset.section));
            this.on(card, "keydown", e => {
                if (e.key === "Enter" || e.key === " ") this._switchSection(card.dataset.section);
            });
        });
    }

    async _switchSection(key) {
        if (key === this._active) return;

        // nav cards
        const nav = this.ref("navBar");
        nav?.querySelectorAll(".acc-nav-card").forEach(c => {
            c.classList.toggle("acc-nav-card--active", c.dataset.section === key);
        });

        // panels
        this.container?.querySelectorAll(".acc-section").forEach(p => {
            p.classList.toggle("acc-section--active", p.dataset.panel === key);
        });

        this._active = key;
        await this._mountSection(key);
    }

    async _mountSection(key) {
        if (this._sections[key]) return; // بار شده

        const def = SECTIONS.find(s => s.key === key);
        if (!def) return;

        const panel = this.ref(`panel-${key}`);
        if (!panel) return;

        const section = new def.Class({
            eventBus: this.eventBus,
            store:    this.store,
            tab:      this.tab,
            api:      this.api,
        });

        await section.render(panel);
        this._sections[key] = section;
    }

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

viewRegistry.register("accounting", AccountingView);
