import React from 'react';
import { useParams } from 'react-router-dom';
import { decodeRouteParam } from '../../pathUtils';
import { useSelectedRoom } from '../../../hooks/router/useSelectedRoom';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { JoinBeforeNavigate } from '../../../features/join-before-navigate';
import { useDirectRooms } from './useDirectRooms';

/**
 * Room-route gate only. The actual room UI is rendered by DirectLayout's
 * CachedRooms host so keep-alive survives room id changes.
 */
export function DirectRouteRoomProvider() {
  const mx = useMatrixClient();
  const rooms = useDirectRooms();

  const { roomIdOrAlias: rawRoomIdOrAlias, eventId: rawEventId } = useParams();
  const roomIdOrAlias = decodeRouteParam(rawRoomIdOrAlias);
  const eventId = decodeRouteParam(rawEventId);
  const roomId = useSelectedRoom();
  const room = mx.getRoom(roomId);

  if (!room || !rooms.includes(room.roomId)) {
    return (
      <JoinBeforeNavigate
        roomIdOrAlias={roomIdOrAlias ?? rawRoomIdOrAlias!}
        eventId={eventId}
      />
    );
  }

  // Valid room — DirectLayout / CachedRooms owns the UI.
  return null;
}
