import type { JSX } from "react"
import { getAvailableCoursesForStudent, getStudentSelections } from "@/modules/elective/data-access-selections"
import { StudentAvailableCoursesSection } from "@/modules/elective/components/student-selection-view"
import { ElectiveFilters } from "@/modules/elective/components/elective-filters"
import { getParam, type SearchParams } from "@/shared/lib/search-params"

/**
 * 可选课程 - 异步 RSC loader
 * 独立 Suspense 边界，可流式渲染
 * 同时获取 mySelections（通过 React cache() 自动去重）以计算 selectedCourseIds
 * 过滤逻辑（搜索关键词 + 选课模式）在本 loader 内完成，保持组件纯净
 */
export async function AvailableCoursesLoader({
  studentId,
  searchParams,
}: {
  studentId: string
  searchParams: Promise<SearchParams>
}): Promise<JSX.Element> {
  const [sp, availableCourses, mySelections] = await Promise.all([
    searchParams,
    getAvailableCoursesForStudent(studentId),
    // 通过 React cache() 去重：若 MySelectionsLoader 已先一步获取，则此处直接返回缓存
    getStudentSelections(studentId),
  ])

  const q = (getParam(sp, "q") || "").toLowerCase().trim()
  const modeFilter = getParam(sp, "mode") || "all"

  const filteredCourses = availableCourses.filter((c) => {
    if (q && !c.name.toLowerCase().includes(q) && !(c.teacherName?.toLowerCase().includes(q) ?? false)) return false
    if (modeFilter !== "all" && c.selectionMode !== modeFilter) return false
    return true
  })

  const selectedCourseIds = new Set(
    mySelections
      .filter((s) => ["selected", "enrolled", "waitlist"].includes(s.status))
      .map((s) => s.courseId)
  )

  return (
    <div className="space-y-4">
      {availableCourses.length > 0 && <ElectiveFilters />}
      <StudentAvailableCoursesSection
        availableCourses={filteredCourses}
        selectedCourseIds={selectedCourseIds}
      />
    </div>
  )
}
