export const createStore = <T extends object>(initialState: T) => {
  let state = initialState;
  const subscribers = new Set<() => void>();

  const subscribe = (callback: () => void) => {
    subscribers.add(callback);
    return () => {
      subscribers.delete(callback);
      if (subscribers.size === 0) state = initialState;
    };
  };

  const getState = () => state;

  const setState = (patch: Partial<T>) => {
    const next = { ...state, ...patch };
    const changed = (Object.keys(patch) as (keyof T)[]).some(
      key => patch[key] !== state[key],
    );
    if (!changed) return;
    state = next;
    subscribers.forEach(cb => {
      cb();
    });
  };

  return { subscribe, getState, setState };
};
