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

/**
 * Hosts home room keep-alive OUTSIDE the room route `<Outlet />`.
 */
export function HomeLayout() {
  const mx = useMatrixClient();
  const selectedRoomId = useSelectedRoom();
  const rooms = useHomeRooms();
  const cache = useAtomValue(roomViewCacheAtom);
  const setActiveRoomId = useSetAtom(activeRoomIdAtom);

  const room = selectedRoomId ? mx.getRoom(selectedRoomId) : undefined;
  const showingRoom = !!(room && rooms.includes(room.roomId));
  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>
  );
}
