import { useState, useEffect, useRef } from "react";
import { useSearchParams } from "react-router-dom";
import CoursesVideoPlayer from "@/components/CoursesVideoPlayer";
import PublicCourseList from "@/components/PublicCourseList";
import { mockData } from "@/data/mockData";
import "./index.css";

const PublicCourses = () => {
  // 默认不选中任何课程，显示黑屏状态
  const [selectedCourse, setSelectedCourse] = useState(null);
  const [searchParams] = useSearchParams();
  const publicCourseListRef = useRef(null);
  
  // 检查URL参数，如果有courseId则自动打开对应课程
  useEffect(() => {
    const courseId = searchParams.get('courseId');
    const courseTitle = searchParams.get('courseTitle');
    
    console.log('PublicCourses - URL params:', { courseId, courseTitle });
    
    if (courseId || courseTitle) {
      // 需要给组件时间加载数据
      const timer = setTimeout(() => {
        if (publicCourseListRef.current) {
          console.log('PublicCourses - Calling selectCourse via ref');
          publicCourseListRef.current.selectCourse(courseId, courseTitle);
        }
      }, 500); // 等待数据加载
      
      return () => clearTimeout(timer);
    }
  }, [searchParams]);

  const handleCourseClick = (course) => {
    setSelectedCourse(course);
  };

  return (
    <div className="public-courses-page">
      <div className="public-courses-content">
        <CoursesVideoPlayer 
          selectedCourse={selectedCourse} 
          teacherData={mockData.teacherData} 
          unitPosters={mockData.publicCourseBackgrounds}
          isPublicCourse={true}
        />
        <PublicCourseList 
          ref={publicCourseListRef}
          onCourseClick={handleCourseClick}
        />
      </div>
    </div>
  );
};

export default PublicCourses;
