import { useParams } from 'react-router-dom';
import { useAtomValue } from 'jotai';
import { getCanonicalAliasRoomId, isRoomAlias } from '../../utils/matrix';
import { useMatrixClient } from '../useMatrixClient';
import { viewedRoomIdAtom } from '../../state/viewedRoom';

// Returns the id of the room the user is currently looking at. Resolution
// order: (1) URL param `roomIdOrAlias` for the canonical /direct, /home,
// /:spaceId/* routes; (2) `viewedRoomIdAtom` for routes whose URL key isn't
// the room id itself (e.g. /bots/:botId, where BotExperienceHost writes the
// derived control-room id into the atom on mount).
export const useSelectedRoom = (): string | undefined => {
  const mx = useMatrixClient();
  const viewedRoomId = useAtomValue(viewedRoomIdAtom);

  const { roomIdOrAlias } = useParams();
  if (roomIdOrAlias) {
    return isRoomAlias(roomIdOrAlias) ? getCanonicalAliasRoomId(mx, roomIdOrAlias) : roomIdOrAlias;
  }

  return viewedRoomId;
};
