/**
 * ChatView.js — تب چت و پشتیبانی در ERP
 */
import BaseView                   from "../../core/BaseView.js";
import { viewRegistry }           from "../../core/registries.js";
import ChatSupportSection         from "./sections/ChatSupportSection.js";
import ChatInternalSection        from "./sections/ChatInternalSection.js";
import ChatSettingsSection        from "./sections/ChatSettingsSection.js";
import ChatTechnicianSection      from "./sections/ChatTechnicianSection.js";

const ALL_SECTIONS = [
    { key: "technician", icon: "👷", title: "چت مشتریان من", desc: "پاسخ به مشتریان تخصیص‌یافته", roles: ["technician"] },
    { key: "support",    icon: "🎧", title: "Live Chat",       desc: "همه گفتگوها (ارشد/مدیر)",      roles: ["admin", "senior"] },
    { key: "internal",   icon: "💼", title: "چت داخلی",        desc: "گفتگوی بین کارمندان",            roles: ["admin", "senior", "technician"] },
    { key: "settings",   icon: "⚙️", title: "تنظیمات",         desc: "پیکربندی ویجت چت",               roles: ["admin"] },
];

const SECTION_CLASS = {
    technician: ChatTechnicianSection,
    support:    ChatSupportSection,
    internal:   ChatInternalSection,
    settings:   ChatSettingsSection,
};

export default class ChatView extends BaseView {

    static title = "💬 چت و پشتیبانی";
    useContextBadge = false;

    constructor(props = {}) {
        super(props);
        this.api = props.api;
        this._active = null;
        this._sections = {};
        this._role = "admin";
        this._sectionDefs = [];
    }

    _resolveRole(data) {
        if (data?.is_technician && !data?.is_admin && !data?.is_senior) return "technician";
        if (data?.is_senior && !data?.is_admin) return "senior";
        if (data?.is_admin || data?.role === "admin") return "admin";
        return "admin";
    }

    _buildSections(role) {
        return ALL_SECTIONS
            .filter(s => s.roles.includes(role))
            .map(s => ({ ...s, Class: SECTION_CLASS[s.key] }));
    }

    async beforeRender() {
        try {
            const res = await this.api.get("service/me/role");
            this._role = this._resolveRole(res?.data);
        } catch {
            this._role = "admin";
        }
        this._sectionDefs = this._buildSections(this._role);
        this._active = this._sectionDefs[0]?.key || "support";
    }

    async template() {
        const cards = this._sectionDefs.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 = this._sectionDefs.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);

        this.listen("chat:support:openRoom", () => {
            if (this._role === "technician" && this._sectionDefs.some(s => s.key === "technician")) {
                this._switch("technician");
            }
        });
    }

    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 = this._sectionDefs.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("chat", ChatView);
