import React, { useState, useEffect, useRef, createContext, useContext } from 'react';
import { useClassroom , Role } from './useClassroom.ts';

type ClassroomContextType = ReturnType<typeof useClassroom>;

const ClassroomContext = createContext<ClassroomContextType | null>(null);

export const ClassroomProvider: React.FC<{children: React.ReactNode}> = ({ children }) => {
  const classroom = useClassroom();

  useEffect(() => {
    // 解析URL参数中的classId
    const params = new URLSearchParams(window.location.search);
    const classId = params.get('classId');
    if (classId) {
      classroom.setClassId(classId);
      classroom.setRole(Role.Student);
    }
  }, []);

  return (
    <ClassroomContext.Provider value={classroom}>
      {children}
    </ClassroomContext.Provider>
  );
};

export const useClassroomContext = () => {
  const context = useContext(ClassroomContext);
  if (!context) {
    throw new Error('useClassroomContext must be used within a ClassroomProvider');
  }
  return context;
};