// assets/js/core/Store.js
export default class Store {

    constructor(eventBus) {

        this.eventBus = eventBus;

        this.state = {

            auth: {
                user: null,
                nonce: null,
                loggedIn: false
            },

            ui: {
                loading: false
            },

            context: {
                project: null   // { id, title, code, ... } — پروژه‌ای که در همه تب‌ها به عنوان فیلتر فعال است
            },

            modules: {}

        };
    }

    get(path) {
        const keys = path.split('.');
        let value = this.state;

        for (const key of keys) {
            if (value[key] === undefined) return null;
            value = value[key];
        }

        return value;
    }

    set(path, value) {
        const keys = path.split('.');
        let obj = this.state;

        for (let i = 0; i < keys.length - 1; i++) {
            const key = keys[i];
            if (!obj[key]) obj[key] = {};
            obj = obj[key];
        }

        obj[keys[keys.length - 1]] = value;

        this.eventBus.emit(`store:changed:${path}`, value);
    }

    update(path, updater) {
        const current = this.get(path);
        const newValue = updater(current);
        this.set(path, newValue);
    }
}
