/**
 * Minimal reactive store for shared application state.
 *
 * Uses EventTarget for change notification. Components subscribe via
 * store.on('sessions', callback) and unsubscribe via store.off().
 *
 * Usage:
 *   import { store } from './store.js';
 *   store.sessions = [...];              // triggers 'sessions' event
 *   store.on('sessions', (sessions) => { ... });
 */
class AppStore extends EventTarget {
  #state = {
    sessions: [],
    viewingSession: null,
    viewingRemoteId: '',
    viewMode: 'grid',
    activeView: 'all',
    serverSettings: null,
    gridViewMode: 'flat',
    deviceId: '',
  };

  /** Get a state value. */
  get(key) { return this.#state[key]; }

  /** Set a state value and dispatch a change event. */
  set(key, value) {
    const old = this.#state[key];
    if (old === value) return;
    this.#state[key] = value;
    this.dispatchEvent(new CustomEvent(key, { detail: { value, old } }));
    this.dispatchEvent(new CustomEvent('change', { detail: { key, value, old } }));
  }

  /** Batch-set multiple keys; fires one event per key then one 'batch'. */
  batch(updates) {
    const changed = [];
    for (const [key, value] of Object.entries(updates)) {
      const old = this.#state[key];
      if (old !== value) {
        this.#state[key] = value;
        this.dispatchEvent(new CustomEvent(key, { detail: { value, old } }));
        changed.push(key);
      }
    }
    if (changed.length > 0) {
      this.dispatchEvent(new CustomEvent('batch', { detail: { keys: changed } }));
    }
  }

  /** Subscribe to a state key change. Returns unsubscribe function. */
  on(key, fn) {
    const handler = (e) => fn(e.detail.value, e.detail.old);
    this.addEventListener(key, handler);
    return () => this.removeEventListener(key, handler);
  }

  /** Remove a specific listener. */
  off(key, fn) {
    this.removeEventListener(key, fn);
  }

  // Convenience accessors for hot paths
  get sessions() { return this.#state.sessions; }
  set sessions(v) { this.set('sessions', v); }
  get activeView() { return this.#state.activeView; }
  set activeView(v) { this.set('activeView', v); }
  get serverSettings() { return this.#state.serverSettings; }
  set serverSettings(v) { this.set('serverSettings', v); }
}

export const store = new AppStore();