import { useCallback, useSyncExternalStore } from 'react';

import { createStore } from './createStore';

type MenuStoreState = {
  openMenuId: string | null;
};

const menuStore = createStore<MenuStoreState>({ openMenuId: null });

export const useConversationMenuOpen = (id: string) => {
  const getSnapshot = useCallback(
    () => menuStore.getState().openMenuId === id,
    [id],
  );
  const isOpen = useSyncExternalStore(menuStore.subscribe, getSnapshot);

  const open = useCallback(() => menuStore.setState({ openMenuId: id }), [id]);
  const close = useCallback(() => {
    if (menuStore.getState().openMenuId === id) {
      menuStore.setState({ openMenuId: null });
    }
  }, [id]);

  return { isOpen, open, close };
};
