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 { useHomeRooms } from './useHomeRooms';
import { useSearchParamsViaServers } from '../../../hooks/router/useSearchParamsViaServers';

/**
 * Room-route gate only. HomeLayout's CachedRooms owns the UI.
 */
export function HomeRouteRoomProvider() {
  const mx = useMatrixClient();
  const rooms = useHomeRooms();

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

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

  return null;
}
