// Minimal reactive store — Svelte-compatible interface, no Svelte dependency.
export interface Readable<T> {
  subscribe(run: (value: T) => void): () => void;
}
export interface Writable<T> extends Readable<T> {
  set(value: T): void;
  update(fn: (value: T) => T): void;
  get(): T;
}

export function writable<T>(initial: T): Writable<T> {
  let value = initial;
  const subs = new Set<(v: T) => void>();
  return {
    subscribe(fn) { subs.add(fn); fn(value); return () => subs.delete(fn); },
    set(v) { value = v; subs.forEach(fn => fn(v)); },
    update(fn) { this.set(fn(value)); },
    get() { return value; },
  };
}

export function readable<T>(initial: T, start?: (set: (v: T) => void) => () => void): Readable<T> {
  const w = writable(initial);
  if (start) {
    let stop: (() => void) | null = null;
    let subscribers = 0;
    return {
      subscribe(fn) {
        subscribers++;
        if (subscribers === 1) stop = start(w.set.bind(w));
        const unsub = w.subscribe(fn);
        return () => {
          unsub();
          subscribers--;
          if (subscribers === 0 && stop) { stop(); stop = null; }
        };
      }
    };
  }
  return w;
}
