import React, { ReactNode, useEffect } from 'react';
import { Room as MatrixRoom } from 'matrix-js-sdk';
import { useSetAtom } from 'jotai';
import { IsOneOnOneProvider, RoomProvider } from '../../../hooks/useRoom';
import { useIsOneOnOneRoom } from '../../../hooks/useIsOneOnOneRoom';
import { viewedRoomIdAtom } from '../../../state/viewedRoom';

type BotRoomProviderProps = {
  room: MatrixRoom;
  children: ReactNode;
};

export function BotRoomProvider({ room, children }: BotRoomProviderProps) {
  const isOneOnOne = useIsOneOnOneRoom(room);
  const setViewedRoomId = useSetAtom(viewedRoomIdAtom);

  // /bots/:botId routes don't carry the control room id in the URL — write
  // the resolved id into a global atom so consumers like ClientNonUIFeatures
  // (notification suppression) and CallStatusRenderer can recognise that
  // this room is on screen. Cleared on unmount to avoid leaking the bot DM
  // id to other routes.
  useEffect(() => {
    setViewedRoomId(room.roomId);
    return () => setViewedRoomId(undefined);
  }, [room.roomId, setViewedRoomId]);

  return (
    <RoomProvider key={room.roomId} value={room}>
      <IsOneOnOneProvider value={isOneOnOne}>{children}</IsOneOnOneProvider>
    </RoomProvider>
  );
}
