export const state = {
  user: null,
  screen: null,
  notifications: [],
  _subs: new Map(),

  get(key) { return this[key]; },

  set(key, value) {
    const old = this[key];
    this[key] = value;
    if (this._subs.has(key)) {
      this._subs.get(key).forEach(fn => fn(value, old));
    }
  },

  on(key, fn) {
    if (!this._subs.has(key)) this._subs.set(key, new Set());
    this._subs.get(key).add(fn);
    return () => this._subs.get(key).delete(fn);
  },

  isLoggedIn() {
    return !!localStorage.getItem('el3ab_token');
  },

  getToken() {
    return localStorage.getItem('el3ab_token') || '';
  },

  getUser() {
    try { return JSON.parse(localStorage.getItem('el3ab_user')); } catch { return null; }
  },

  setAuth(token, user) {
    localStorage.setItem('el3ab_token', token);
    localStorage.setItem('el3ab_user', JSON.stringify(user));
    this.set('user', user);
  },

  logout() {
    localStorage.removeItem('el3ab_token');
    localStorage.removeItem('el3ab_user');
    this.set('user', null);
    window.location.href = '/';
  }
};
