import React, { useEffect } from 'react';
import { Outlet } from 'react-router-dom';
import { useAtom, useAtomValue } from 'jotai';
import { pendingRoomNavigationAtom } from '../state/pendingRoomNavigation';
import { useMatrixClient } from '../hooks/useMatrixClient';
import { IsDirectRoomProvider, RoomProvider } from '../hooks/useRoom';
import { mDirectAtom } from '../state/mDirectList';
import { useSelectedRoom } from '../hooks/router/useSelectedRoom';
import { RoomFrame } from '../features/room/Room';
import * as css from './AnimatedOutlet.css';

/** Chrome-only shell for the press→navigate gap (no timeline — avoids scroll fights). */
function PendingRoomShell({ roomId }: { roomId: string }) {
  const mx = useMatrixClient();
  const mDirects = useAtomValue(mDirectAtom);
  const room = mx.getRoom(roomId);

  if (!room) return null;

  return (
    <div className={css.PendingOverlay} aria-busy aria-label={`Opening ${room.name}`}>
      <RoomProvider key={room.roomId} value={room}>
        <IsDirectRoomProvider value={mDirects.has(room.roomId)}>
          <RoomFrame room={room} pending />
        </IsDirectRoomProvider>
      </RoomProvider>
    </div>
  );
}

/** Optimistic room navigation: brief pending chrome until the route settles. */
export function AnimatedOutlet() {
  const selectedRoomId = useSelectedRoom();
  const [pendingRoomId, setPendingRoomId] = useAtom(pendingRoomNavigationAtom);

  // Safety: if navigation never lands, don't leave pending forever.
  useEffect(() => {
    if (!pendingRoomId) return undefined;
    const t = window.setTimeout(() => setPendingRoomId(null), 4000);
    return () => window.clearTimeout(t);
  }, [pendingRoomId, setPendingRoomId]);

  // Only cover the gap before the target room route is active.
  const showOverlay =
    typeof pendingRoomId === 'string' &&
    pendingRoomId.length > 0 &&
    pendingRoomId !== selectedRoomId;

  return (
    <div
      style={{
        flex: 1,
        minWidth: 0,
        minHeight: 0,
        position: 'relative',
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      {showOverlay && <PendingRoomShell roomId={pendingRoomId} />}
      {/*
        Do NOT key this by pathname — room switches share CachedRooms keep-alive.
        Remounting here wiped the cache and made warm rooms feel as slow as cold ones.
      */}
      <div className={css.RoutePane}>
        <Outlet />
      </div>
    </div>
  );
}
