import { createContext, MutableRefObject, useContext } from 'react';
import { useAtomValue } from 'jotai';
import { useRoom } from '../../hooks/useRoom';
import { activeRoomIdAtom } from '../../state/activeRoom';

/**
 * Mutable visibility flag for keep-alive rooms. Updating `.current` does not
 * re-render consumers — use for timeline side-effects / paginator gates.
 */
export const RoomVisibilityRefContext = createContext<MutableRefObject<boolean>>({
  current: true,
});

export const useRoomVisibilityRef = (): MutableRefObject<boolean> =>
  useContext(RoomVisibilityRefContext);

/**
 * True when this room is the visible/selected room.
 * Subscribes to `activeRoomIdAtom` (set by ActiveRoomEffects) so headers/call
 * UI update without forcing the timeline tree to re-render.
 */
export const useRoomViewActive = (): boolean => {
  const room = useRoom();
  const activeRoomId = useAtomValue(activeRoomIdAtom);
  return activeRoomId === room.roomId;
};

/** @deprecated Prefer useRoomViewActive / useRoomVisibilityRef. */
export const RoomViewActiveContext = createContext(true);
