import { useMemo, useSyncExternalStore } from "react";
import type { SchemetaStore, StoreState } from "../state";

type Selector<TSelected> = (state: StoreState) => TSelected;

export function useSchemetaStoreState(store: SchemetaStore): StoreState {
  return useSyncExternalStore(store.subscribe, store.getState, store.getState);
}

export function useSchemetaSelector<TSelected>(store: SchemetaStore, selector: Selector<TSelected>): TSelected {
  const state = useSchemetaStoreState(store);
  return useMemo(() => selector(state), [selector, state]);
}

export function useSchemetaActions(store: SchemetaStore): SchemetaStore["actions"] {
  return store.actions;
}
