/**

 * ServiceView.js — ماژول خدمات میدانی

 */

import BaseView from "../../core/BaseView.js";

import { viewRegistry } from "../../core/registries.js";

import ServiceRequestsSection from "./sections/ServiceRequestsSection.js";

import ServiceDevicesSection    from "./sections/ServiceDevicesSection.js";

import ServiceReportsSection    from "./sections/ServiceReportsSection.js";

import ServiceDispatchSection   from "./sections/ServiceDispatchSection.js";

import ServiceDashboardSection  from "./sections/ServiceDashboardSection.js";

import ServicePmSection         from "./sections/ServicePmSection.js";

import ServicePartsSection      from "./sections/ServicePartsSection.js";

import ServiceEquipmentSection  from "./sections/ServiceEquipmentSection.js";

import ServiceSeniorSection     from "./sections/ServiceSeniorSection.js";

import ServiceTechnicianSection from "./sections/ServiceTechnicianSection.js";

import ServiceAccountingSection from "./sections/ServiceAccountingSection.js";



const ALL_SECTIONS = [

    { key: "dashboard",  icon: "📊", title: "داشبورد",       desc: "آمار کلی",          roles: ["admin", "senior"] },

    { key: "accounting", icon: "💰", title: "صدور سند",      desc: "حسابدار — صف سند", roles: ["admin", "accountant"] },

    { key: "senior",     icon: "👨‍💼", title: "کارشناس ارشد", desc: "مدیریت تیم",        roles: ["admin", "senior"] },

    { key: "technician", icon: "🔧", title: "صف کار من",     desc: "کارشناس میدانی",    roles: ["admin", "technician"] },

    { key: "dispatch",   icon: "🚐", title: "Dispatch",      desc: "تخصیص کارشناس",     roles: ["admin", "senior"] },

    { key: "requests",   icon: "📋", title: "درخواست‌ها",    desc: "صف درخواست",        roles: ["admin", "senior"] },

    { key: "reports",    icon: "📄", title: "گزارش فنی",     desc: "SRD + فاکتور",      roles: ["admin", "senior", "technician", "accountant"] },

    { key: "pm",         icon: "📅", title: "PM",            desc: "سرویس دوره‌ای",     roles: ["admin", "senior"] },

    { key: "parts",      icon: "📦", title: "قطعات",         desc: "سفارش تأمین",       roles: ["admin", "senior"] },

    { key: "equipment",  icon: "🏭", title: "تجهیزات",       desc: "استعلام خرید",      roles: ["admin", "senior"] },

    { key: "devices",    icon: "❄️", title: "دستگاه‌ها",     desc: "پرونده تجهیز",      roles: ["admin", "senior"] },

];



const SECTION_CLASS = {

    dashboard:  ServiceDashboardSection,

    accounting: ServiceAccountingSection,

    senior:     ServiceSeniorSection,

    technician: ServiceTechnicianSection,

    dispatch:   ServiceDispatchSection,

    requests:   ServiceRequestsSection,

    reports:    ServiceReportsSection,

    pm:         ServicePmSection,

    parts:      ServicePartsSection,

    equipment:  ServiceEquipmentSection,

    devices:    ServiceDevicesSection,

};



export default class ServiceView extends BaseView {

    static title = "خدمات میدانی";

    useContextBadge = true;



    constructor(props = {}) {

        super(props);

        this.api = props.api;

        this._active = null;

        this._sections = {};

        this._role = "admin";

        this._sectionDefs = [];

    }



    _resolveRole(data) {

        if (data?.is_admin) return "admin";

        if (data?.is_accountant) return "accountant";

        if (data?.is_senior) return "senior";

        if (data?.is_technician) return "technician";

        return data?.role || "admin";

    }



    _buildSections(role) {

        return ALL_SECTIONS

            .filter(s => s.roles.includes(role))

            .map(s => ({ ...s, Class: SECTION_CLASS[s.key] }));

    }



    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 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._role === "accountant"
            ? (this._sectionDefs.find(s => s.key === "accounting")?.key || this._sectionDefs[0]?.key)
            : (this._sectionDefs[0]?.key || "dashboard");

    }



    async afterRender() {

        this.ref("navBar").querySelectorAll(".sp-nav-card").forEach(c => {

            this.on(c, "click", () => this._switch(c.dataset.section));

        });

        this.eventBus?.on?.("service:open-report", async ({ id }) => {

            await this._switch("reports");

            if (!this._sections.reports) await this._mount("reports");

            await this._sections.reports?._openWizard?.(id);

        });

        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 = 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("service", ServiceView);

