// assets/js/app.js

import EventBus from "./core/EventBus.js";
import Store from "./core/Store.js";
import ApiClient from "./core/ApiClient.js";
import HomeView from "./views/HomeView.js";
import acl from "./core/AclService.js";

// ✅ Registries
// import tabConfigRegistry from "./core/TabConfigRegistry.js";
// import viewResolver from "./core/ViewResolver.js";

import { tabConfigRegistry, viewResolver } from "./core/registries.js";

/*
|--------------------------------------------------------------------------
| Import tab configs & views (self-registration)
|--------------------------------------------------------------------------
| فقط ایمپورت کافیست؛ کد ثبت داخل خود فایل‌ها اجرا می‌شود
*/

import "./tabs/modules.js";

class App {
    constructor() {
        this.eventBus = new EventBus();
        this.store = new Store(this.eventBus);

        this.api = new ApiClient({
            config: { apiUrl: window.ACC_CONFIG.api },
            eventBus: this.eventBus,
            store: this.store,
        });

        this.tabManager = null;

        /* -------------------------
           Auth Events
        --------------------------*/

        this.eventBus.on("auth:login:success", (session) => {
            this.store.set("auth", {
                user: session.user,
                nonce: session.nonce,
                loggedIn: true,
            });
            if (session.token) {
                this.store.set("session", {
                    user: session.user,
                    token: session.token,
                    isCustomLogin: true,
                });
            }

            if (session.user?.id) {
                window.accCurrentUserId = +session.user.id;
            }
            window.dispatchEvent(new Event("erp:login"));

            acl._loaded = false;
            acl.load(this.api).then(() => {
                const role = acl.roles?.[0]?.name || acl.roles?.[0]?.slug || "";
                if (role) {
                    const auth = this.store.get("auth") || {};
                    this.store.set("auth", {
                        ...auth,
                        user: { ...(auth.user || session.user || {}), role },
                        loggedIn: true,
                    });
                }
                this.initShellUI().then(() => {
                    this.showWorkspace();
                    this._consumePendingTab();
                });
            });
        });

        this.eventBus.on("auth:unauthorized", () => {
            try { sessionStorage.removeItem("acc_token"); } catch {}
            this.store.set("auth", {
                user: null,
                nonce: null,
                loggedIn: false,
            });
            this.store.set("session", null);
            this.showLogin();
        });

        /* -------------------------
           Test / Legacy Events (unchanged)
        --------------------------*/

        this.eventBus.on("tabs:switchUser", ({ tabId }) => {
            const newUser = prompt("Enter username:");
            if (newUser) {
                this.eventBus.emit("modal:userSelected", {
                    tabId,
                    user: { username: newUser },
                });
            }
        });

        this.eventBus.on("view:switchUser", ({ view }) => {
            const newUser = prompt("Enter username:");
            if (newUser) {
                this.eventBus.emit("modal:userSelected", {
                    tabId: view.tab?.id,
                    user: { username: newUser },
                });
            }
        });


        /* -------------------------
        Global Tab Open Listener
        --------------------------*/

        this.eventBus.on("tab:open", ({ key, params }) => {
            if (!this.tabManager) {
                console.warn("TabManager not ready yet.");
                return;
            }

            const userContext = this.getCurrentUserContext();

            this.tabManager.openTab(key, {
                userContext,
                params: params || {},
            });
        });

    }

    /* -------------------------
       App Entry
    --------------------------*/
    async start() {
        const pendingTab = new URLSearchParams(window.location.search).get('tab')
            || sessionStorage.getItem('acc_pending_tab');
        if (pendingTab) sessionStorage.setItem('acc_pending_tab', pendingTab);

        /* بازیابی جلسه از JWT — مثل پورتال‌ها */
        const restored = await this._restoreSession();
        if (restored) {
            try { await this._reloadAcl(); } catch { try { await acl.load(this.api); } catch {} }
            await this.initShellUI();
            this.showWorkspace();
            this._consumePendingTab();
            return;
        }

        const auth = this.store.get("auth");
        if (auth?.loggedIn) {
            if (auth.user?.id) window.accCurrentUserId = +auth.user.id;
            try { await acl.load(this.api); } catch {}
            await this.initShellUI();
            this.showWorkspace();
            this._consumePendingTab();
        } else {
            await this.initShellUI();
            this.showLogin();
            if (new URLSearchParams(window.location.search).get('auth') === '1') {
                setTimeout(() => this._openLoginPanel(), 300);
            }
        }
    }

    async _reloadAcl() {
        acl._loaded = false;
        await acl.load(this.api);
    }

    async _restoreSession() {
        const token = sessionStorage.getItem('acc_token');
        if (!token) return false;
        try {
            const me = await this.api.get('/acl/me');
            if (!me?.user_id && !me?.user) throw new Error('no user');
            const user = me.user || { id: me.user_id, display_name: 'کاربر' };
            const role = me.roles?.[0]?.name || me.roles?.[0]?.slug || '';
            this.store.set('auth', {
                user: { ...user, role },
                nonce: null,
                loggedIn: true,
            });
            this.store.set('session', { user, token, isCustomLogin: true });
            if (user.id) window.accCurrentUserId = +user.id;
            window.dispatchEvent(new Event('erp:login'));
            return true;
        } catch {
            sessionStorage.removeItem('acc_token');
            this.store.set('auth', { user: null, nonce: null, loggedIn: false });
            return false;
        }
    }

    _openLoginPanel() {
        const panel = document.querySelector('#lp-auth-panel');
        const btn = document.querySelector('#lp-open-auth');
        if (panel) {
            panel.classList.add('lp-auth-panel--open');
            panel.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        } else if (btn) btn.click();
    }

    _consumePendingTab() {
        const params = new URLSearchParams(window.location.search);
        const tab = params.get('tab') || sessionStorage.getItem('acc_pending_tab');
        if (!tab || !this.tabManager) return;

        sessionStorage.removeItem('acc_pending_tab');
        const userContext = this.getCurrentUserContext();
        this.tabManager.openTab(tab, { userContext });

        if (params.get('tab')) {
            const clean = window.location.pathname + window.location.hash;
            history.replaceState({}, '', clean);
        }
    }

    /* -------------------------
       Shell UI Init
    --------------------------*/
    async initShellUI() {
        const userNameEl = document.getElementById("acc-user-name");
        const userRoleEl = document.getElementById("acc-user-role");
        const logoutBtn = document.getElementById("acc-logout-btn");
        const shellHdr = document.getElementById("erp-shell-header");

        const auth = this.store.get("auth");

        if (auth?.user && userNameEl) {
            userNameEl.textContent =
                auth.user.display_name ||
                auth.user.user_login ||
                "کاربر";
        }

        if (userRoleEl) {
            const role = auth?.user?.role || "";
            userRoleEl.textContent = role;
            userRoleEl.style.display = role ? "" : "none";
        }

        if (shellHdr) {
            shellHdr.hidden = !(auth?.loggedIn);
        }

        if (logoutBtn && !logoutBtn.__accBound) {
            logoutBtn.__accBound = true;
            logoutBtn.addEventListener("click", (e) => {
                e.preventDefault();
                this._logout();
            });
        }

        if (!this.tabManager) {
            const { default: TabManager } = await import("./core/TabManager.js");

            this.tabManager = new TabManager({
                eventBus: this.eventBus,
                store: this.store,
                api: this.api,
                cache: this.cache,
                auth: this.auth,
                tabbarSelector: "#acc-tabbar",
                contentSelector: "#acc-tab-content",
                tabConfigRegistry,
                viewResolver,
            });

        }
    }

    _logout() {
        try {
            sessionStorage.removeItem("acc_token");
            sessionStorage.removeItem("acc_tabs_state");
            sessionStorage.removeItem("acc_pending_tab");
            localStorage.removeItem("acc_token");
        } catch { /* ignore */ }

        this.store.set("auth", { user: null, nonce: null, loggedIn: false });
        this.store.set("session", null);
        window.accCurrentUserId = null;
        window.dispatchEvent(new Event("erp:logout"));

        const shellHdr = document.getElementById("erp-shell-header");
        if (shellHdr) shellHdr.hidden = true;

        /* ریست تب‌ها و بازگشت به لندینگ */
        try {
            if (this.tabManager?.tabs?.clear) this.tabManager.tabs.clear();
        } catch { /* ignore */ }

        this.showLogin();
    }

    /* -------------------------
       Login Screen
    --------------------------*/
    showLogin() {
        const loginContainer = document.getElementById("acc-login-container");
        const tabbar = document.getElementById("acc-tabbar");
        const tabContent = document.getElementById("acc-tab-content");
        const shellHdr = document.getElementById("erp-shell-header");

        if (!loginContainer) return;

        if (shellHdr) shellHdr.hidden = true;
        if (tabbar) {
            tabbar.style.display = "none";
            tabbar.innerHTML = "";
        }
        if (tabContent) {
            tabContent.style.display = "none";
            tabContent.innerHTML = "";
        }

        loginContainer.style.display = "block";
        loginContainer.innerHTML = "";

        const view = new HomeView({
            api: this.api,
            store: this.store,
            eventBus: this.eventBus,
        });
        view.render(loginContainer);
    }

    /* -------------------------
       Workspace
    --------------------------*/
    async showWorkspace() {
        const loginContainer = document.getElementById("acc-login-container");
        const tabbar = document.getElementById("acc-tabbar");
        const tabContent = document.getElementById("acc-tab-content");
        const shellHdr = document.getElementById("erp-shell-header");

        if (loginContainer) {
            loginContainer.style.display = "none";
            loginContainer.innerHTML = "";
        }

        if (shellHdr) shellHdr.hidden = false;
        if (tabbar) tabbar.style.display = "flex";
        if (tabContent) tabContent.style.display = "block";

        await this.initShellUI();

        // ✅ Open fixed tabs only once
        //  if (this.tabManager && this.tabManager.tabs.size === 0) 
        if (this.tabManager) {
            const userContext = this.getCurrentUserContext();

            this.tabManager.openTab("sidebar", {
                fixed: true,
                userContext,
            });

            // this.tabManager.openTab("dashboard", {
            //     fixed: true,
            //     userContext,
            // });
        }

        this.initMenuHandlers();
    }

    /* -------------------------
       Menu Click Handler
    --------------------------*/
    initMenuHandlers() {
        const menuRoot = document.getElementById("acc-menu-root");
        if (!menuRoot || menuRoot.__acc_bound) return;
        menuRoot.__acc_bound = true;

        menuRoot.addEventListener("click", (e) => {
            const item = e.target.closest(".acc-menu-item");
            if (!item) return;

            const tabKey = item.dataset.view;
            if (!tabKey) return;

            const userContext = this.getCurrentUserContext();

            this.tabManager.openTab(tabKey, {
                userContext,
            });
        });
    }

    /* -------------------------
       User Context Helpers
    --------------------------*/
    getCurrentUser() {
        return this.store.get("auth")?.user ?? null;
    }

    getCurrentUserContext() {
        const user = this.getCurrentUser();
        if (!user) return null;

        return {
            id: user.id ?? null,
            display_name:
                user.display_name ||
                user.fullname ||
                user.name ||
                user.user_login ||
                user.username ||
                "کاربر",
            username: user.user_login || user.username || null,
        };
    }
}

/* -------------------------
   Boot
--------------------------*/
const app = new App();
app.start();

export default app;
