// trrc-app.js
import { TRRCStore } from './trrc-store.js';
import { TRRCRenderer } from './trrc-renderer.js';
import { TRRCUI } from './trrc-ui.js';

export class TRRCApp {
    // Constructor حالا یک شیء شامل 'element' و 'options' (که شامل apiUrl است) دریافت می‌کند.
    constructor({ container, element, api, apiUrl, tab }) {
        this.element = element || container;
        this.apiUrl = apiUrl || api;
        this.tab = tab;

        if (!this.element) {
            console.error('TRRCApp: Root element is missing.');
            return;
        }

        this.store = new TRRCStore();
        this.renderer = new TRRCRenderer();
        this.ui = new TRRCUI();

        this.load();
    }

    async load() {
        if (!this.apiUrl) {
            console.error("TRRCApp: API URL is missing.");
            return;
        }

        // helper for safe logging
        const log = (...args) => console.log("[TRRC DEBUG]", ...args);
        const warn = (...args) => console.warn("[TRRC WARN]", ...args);
        const err = (...args) => console.error("[TRRC ERROR]", ...args);

        const resolveUserIdFromUserContext = (uc) => {
            if (!uc) return null;

            // object case
            if (typeof uc === "object") {
                const candidates = [
                    uc.id,
                    uc.userId,
                    uc.ID,
                    uc.uid,
                    uc.username,
                    uc.login,
                ];

                for (const c of candidates) {
                    if (c !== null && c !== undefined && c !== "") return c;
                }

                return null;
            }

            // string case (e.g. "ostadowner")
            if (typeof uc === "string") {
                const s = uc.trim();
                if (!s) return null;

                // اگر رشته عددی بود، تبدیل به عدد
                if (/^\d+$/.test(s)) return Number(s);

                // در غیر این صورت، همان username را برمی‌گردانیم
                return s;
            }

            // number case
            if (typeof uc === "number") {
                if (Number.isFinite(uc) && uc > 0) return uc;
                return null;
            }

            return null;
        };

        const normalizeUserId = (id) => {
            if (id === null || id === undefined) return null;

            if (typeof id === "number" && Number.isFinite(id)) {
                return id;
            }

            if (typeof id === "string") {
                const v = id.trim();
                if (!v) return null;
                return v;
            }

            return null;
        };

        try {
            const url = new URL(this.apiUrl, window.location.origin);

            const userContext = this.tab?.userContext;
            const authUser = this.store?.get?.("auth")?.user;

            let userId = null;

            // 1) از tab.userContext
            userId = normalizeUserId(resolveUserIdFromUserContext(userContext));

            // 2) از auth.user.id
            if (!userId && authUser) {
                userId = normalizeUserId(authUser.id ?? authUser.userId);
            }

            log("apiUrl =", this.apiUrl);
            log("resolved tab.userContext =", userContext);
            log("resolved auth.user =", authUser);
            log("resolved userId =", userId);

            if (userId) {
                url.searchParams.set("userId", String(userId));
            } else {
                warn("No valid userId found. Fetching without userId.");
            }

            log("Fetching tree from:", url.toString());

            const res = await fetch(url.toString(), {
                credentials: "same-origin"
            });

            if (!res.ok) {
                const text = await res.text().catch(() => "");
                throw new Error(`HTTP ${res.status} ${res.statusText}: ${text.slice(0, 200)}`);
            }

            const contentType = res.headers.get("content-type") || "";
            if (!contentType.includes("application/json")) {
                const text = await res.text().catch(() => "");
                throw new Error(`Response is not JSON. content-type="${contentType}". sample="${text.slice(0, 200)}"`);
            }

            const json = await res.json();

            this.prepare(json);
            this.store.load(json);

            this.element.classList.add("trrc-container");
            this.render();

            this.ui.attachEvents(
                this.element,
                this.store,
                this.renderer,
                () => this.render()
            );

        } catch (e) {
            err("TRRC load failed:", e);
            const message = e?.message || String(e);
            this.element.innerHTML = `<div style="color:red">خطا در دریافت داده: ${message}</div>`;
        }
    }


    prepare(node, parent = null) {
        if (!node) return;

        node.parent = parent;

        if (node.children) {
            node.children.forEach(child => {
                this.prepare(child, node);
            });
        }
    }

    render() {
        this.element.innerHTML = this.renderer.render(this.store.getState());
    }
}
