import React, { useEffect } from 'react';
import { useAtomValue, useSetAtom } from 'jotai';
import { AnimatedOutlet } from '../../../components/AnimatedOutlet';
import { CachedRooms } from '../../../features/room/CachedRooms';
import { useSelectedRoom } from '../../../hooks/router/useSelectedRoom';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { activeRoomIdAtom } from '../../../state/activeRoom';
import { roomViewCacheAtom } from '../../../state/roomViewCache';
import { useDirectRooms } from './useDirectRooms';

/**
 * Hosts the DM room keep-alive OUTSIDE the room route `<Outlet />`.
 * Room param changes must not remount CachedRooms — that was making every
 * "cached" switch as slow as a cold open.
 */
export function DirectLayout() {
  const mx = useMatrixClient();
  const selectedRoomId = useSelectedRoom();
  const directs = useDirectRooms();
  const cache = useAtomValue(roomViewCacheAtom);
  const setActiveRoomId = useSetAtom(activeRoomIdAtom);

  const room = selectedRoomId ? mx.getRoom(selectedRoomId) : undefined;
  const showingRoom = !!(room && directs.includes(room.roomId));
  // Keep the host mounted while we still have warm rooms, even on /direct/.
  const keepHost = showingRoom || cache.length > 0;

  useEffect(() => {
    if (!showingRoom) setActiveRoomId(undefined);
  }, [showingRoom, setActiveRoomId]);

  return (
    <div
      style={{
        flex: 1,
        minWidth: 0,
        minHeight: 0,
        position: 'relative',
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      {keepHost && (
        <div
          style={{
            flex: 1,
            minWidth: 0,
            minHeight: 0,
            display: showingRoom ? 'flex' : 'none',
            flexDirection: 'column',
            position: 'relative',
          }}
          aria-hidden={!showingRoom}
        >
          <CachedRooms />
        </div>
      )}
      <div
        style={{
          flex: 1,
          minWidth: 0,
          minHeight: 0,
          display: showingRoom ? 'none' : 'flex',
          flexDirection: 'column',
          position: 'relative',
        }}
      >
        <AnimatedOutlet />
      </div>
    </div>
  );
}
