import React, { useMemo } from 'react';
import { PageRoot } from '../../components/page';
import { AnimatedOutlet } from '../../components/AnimatedOutlet';
import { MobileFriendlyPageNav } from '../../pages/MobileFriendly';
import { SPACE_PATH } from '../../pages/paths';
import { Space } from '../../pages/client/space/Space';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { useSelectedRoom } from '../../hooks/router/useSelectedRoom';
import { useSpace } from '../../hooks/useSpace';
import { isForumContainer, shouldShowForumLobby } from '../../utils/room';
import { ForumBoardProvider } from './ForumBoardContext';

/**
 * Space sidebar + outlet. Forum spaces render ForumFeedSidebar in Space.tsx.
 */
export function ForumAwareSpaceLayout() {
  const mx = useMatrixClient();
  const space = useSpace();
  const selectedRoomId = useSelectedRoom();

  const scope = useMemo(() => {
    const room = selectedRoomId ? mx.getRoom(selectedRoomId) : null;
    const topicRoomId =
      room && room.roomId !== space.roomId && !isForumContainer(room) ? room.roomId : undefined;
    return { forumSpaceId: space.roomId, topicRoomId };
  }, [mx, selectedRoomId, space.roomId]);

  const layout = (
    <PageRoot
      nav={
        <MobileFriendlyPageNav path={SPACE_PATH}>
          <Space />
        </MobileFriendlyPageNav>
      }
    >
      <AnimatedOutlet />
    </PageRoot>
  );

  if (!shouldShowForumLobby(space)) {
    return layout;
  }

  return (
    <ForumBoardProvider forumSpace={space} scope={scope}>
      {layout}
    </ForumBoardProvider>
  );
}
