/**
 * CpmView.js — تب کنترل پروژه
 * بخش‌ها: پروژه‌ها | وظایف | منابع | اعضا | پیام‌ها | گانت | مالی
 */
import BaseView        from "../../core/BaseView.js";
import { viewRegistry } from "../../core/registries.js";
import ProjectsCPMSection from "./sections/ProjectsCPMSection.js";
import TasksSection       from "./sections/TasksSection.js";
import ResourcesSection   from "./sections/ResourcesSection.js";
import MembersSection     from "./sections/MembersSection.js";
import MessagesSection    from "./sections/MessagesSection.js";
import GanttSection       from "./sections/GanttSection.js";
import FinancialsSection  from "./sections/FinancialsSection.js";
import WorkflowSection         from "./sections/WorkflowSection.js";
import WorkflowTemplatesSection from "./sections/WorkflowTemplatesSection.js";

const SECTIONS = [
    { key: "projects",   icon: "🏗",  title: "پروژه‌ها",  desc: "مدیریت پروژه‌ها",    Class: ProjectsCPMSection },
    { key: "workflow",   icon: "🔄",  title: "Workflow",  desc: "ساختار پروژه",         Class: WorkflowSection    },
    { key: "wf-tpl",     icon: "🎨",  title: "قالب‌ها",   desc: "قالب workflow",        Class: WorkflowTemplatesSection },
    { key: "tasks",      icon: "✅",  title: "وظایف",     desc: "تسک و WBS",            Class: TasksSection       },
    { key: "resources",  icon: "👷",  title: "منابع",      desc: "منابع و تخصیص",        Class: ResourcesSection   },
    { key: "members",    icon: "👥",  title: "اعضا",       desc: "تیم پروژه",             Class: MembersSection     },
    { key: "messages",   icon: "💬",  title: "پیام‌ها",    desc: "انتقال پیام",           Class: MessagesSection    },
    { key: "gantt",      icon: "📊",  title: "گانت",       desc: "نمودار گانت",           Class: GanttSection       },
    { key: "financials", icon: "💰",  title: "مالی",       desc: "یکپارچه‌سازی مالی",     Class: FinancialsSection  },
];

export default class CpmView extends BaseView {
    static title = "📊 کنترل پروژه";
    useContextBadge = true;

    constructor(props = {}) {
        super(props);
        this.api      = props.api;
        this._active  = "projects";
        this._sections = {};
        this._projectId = null; // پروژه فعال
        this._selectedProject = null;
    }

    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>
        `).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="cpm-header-bar" data-ref="headerBar">
                <div class="cpm-project-badge" data-ref="projectBadge" style="display:none">
                    <span class="cpm-badge-icon">🏗</span>
                    <span data-ref="projectBadgeText">—</span>
                    <button class="cpm-badge-close" data-ref="clearProject" title="برگشت به لیست">✕</button>
                </div>
            </div>
            <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))
        );
        this.on(this.ref("clearProject"), "click", () => this._clearProject());
        await this._mount(this._active);
    }

    // ── انتخاب پروژه از سکشن Projects ─────────────────────────
    selectProject(project) {
        this._projectId = project.id;
        this._selectedProject = project;
        const badge = this.ref("projectBadge");
        badge.style.display = "flex";
        this.ref("projectBadgeText").textContent = `${project.name} (#${project.id})`;

        // اطلاع رسانی به همه سکشن‌های فعال
        Object.values(this._sections).forEach(sec => {
            if (typeof sec.onProjectChange === "function") {
                sec.onProjectChange(project);
            }
        });
    }

    _clearProject() {
        this._projectId = null;
        this._selectedProject = null;
        this.ref("projectBadge").style.display = "none";
        Object.values(this._sections).forEach(sec => {
            if (typeof sec.onProjectChange === "function") sec.onProjectChange(null);
        });
    }

    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);

        // اگر سکشن جدید پروژه فعال دارد، اطلاع بده
        const sec = this._sections[key];
        if (sec && this._selectedProject && typeof sec.onProjectChange === "function") {
            sec.onProjectChange(this._selectedProject);
        }
    }

    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,
            cpmView:  this,   // reference به parent view
        });
        await sec.render(panel);
        this._sections[key] = sec;
    }

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

// جایگزین CpmProjectView قدیمی
viewRegistry.register("cpm", CpmView);
