import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { useSpace } from '../../../hooks/useSpace';
import { shouldShowForumLobby } from '../../../utils/room';
import { getSpaceDefaultPath } from '../../pathUtils';
import { ForumFeedPage } from '../../../features/forum/ForumFeedPage';
import { useCompactNav } from '../../../hooks/useCompactNav';

/** Sends /:spaceId/ to the forum feed or space lobby (desktop). On compact nav, stay on index for the channel list. */
export function SpaceIndexRedirect() {
  const mx = useMatrixClient();
  const space = useSpace();
  const navigate = useNavigate();
  const compact = useCompactNav();
  const isForum = shouldShowForumLobby(space);

  useEffect(() => {
    if (compact) return;
    navigate(getSpaceDefaultPath(mx, space.roomId), { replace: true });
  }, [compact, mx, navigate, space.roomId]);

  if (compact) {
    return null;
  }

  // Avoid a blank main pane while redirecting forum spaces to /feed/.
  if (isForum) {
    return <ForumFeedPage />;
  }

  return null;
}
