import React, { createContext, useContext } from 'react';
import { Room } from 'matrix-js-sdk';
import { useForumBoard, type ForumBoardScope } from './useForumBoard';

type ForumBoardContextValue = ReturnType<typeof useForumBoard>;

const ForumBoardContext = createContext<ForumBoardContextValue | null>(null);

export function ForumBoardProvider({
  forumSpace,
  scope,
  children,
}: {
  forumSpace: Room;
  scope: ForumBoardScope;
  children: React.ReactNode;
}) {
  const value = useForumBoard(scope, forumSpace);
  return <ForumBoardContext.Provider value={value}>{children}</ForumBoardContext.Provider>;
}

export function useForumBoardContext(): ForumBoardContextValue {
  const ctx = useContext(ForumBoardContext);
  if (!ctx) {
    throw new Error('useForumBoardContext must be used within ForumBoardProvider');
  }
  return ctx;
}

export function useForumBoardContextOptionally(): ForumBoardContextValue | null {
  return useContext(ForumBoardContext);
}
