// 班级列表页面（家长查看子女班级）
// 依据：02-architecture-design.md §3.1 路由结构
// 路由：/parent/classes
// 对标 student-portal /my-classes（家长只读视角）

"use client";

import { useChildClasses } from "@/hooks/useChildClasses";
import { useChildSwitcher } from "@/hooks/useChildSwitcher";
import type { ClassInfo } from "@/types";

export default function ClassesPage(): JSX.Element {
  const { currentChild } = useChildSwitcher();
  const { classes, loading, error } = useChildClasses();

  if (loading) {
    return (
      <div className="space-y-4" role="status" aria-live="polite">
        <span className="skeleton h-8 w-48 rounded" aria-hidden="true" />
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
          <span className="skeleton h-40 w-full rounded" aria-hidden="true" />
          <span className="skeleton h-40 w-full rounded" aria-hidden="true" />
          <span className="skeleton h-40 w-full rounded" aria-hidden="true" />
        </div>
        <span className="sr-only">加载班级列表中...</span>
      </div>
    );
  }

  if (error) {
    return (
      <div
        role="alert"
        className="rounded border border-danger p-4 text-sm text-danger"
      >
        加载失败：{error.message}
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <h1 className="font-serif text-2xl">{currentChild?.name}的班级</h1>

      {classes.length === 0 ? (
        <p className="text-sm text-ink-muted">暂未分配到班级</p>
      ) : (
        <section
          aria-label="班级列表"
          className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3"
        >
          {classes.map((cls) => (
            <ClassCard key={cls.id} cls={cls} />
          ))}
        </section>
      )}
    </div>
  );
}

function ClassCard({ cls }: { cls: ClassInfo }): JSX.Element {
  return (
    <article className="rounded border border-rule bg-paper-elevated p-4">
      <div className="flex items-start justify-between gap-3">
        <div className="min-w-0 flex-1">
          <p className="text-xs text-ink-muted">
            {cls.grade} · {cls.year} 学年
          </p>
          <h2 className="mt-1 font-serif text-lg">{cls.name}</h2>
        </div>
        <span
          className="flex-shrink-0 rounded bg-accent-soft px-2 py-1 text-xs text-ink"
          aria-label={`共 ${cls.studentCount} 名学生`}
        >
          {cls.studentCount} 人
        </span>
      </div>

      <div className="mt-3 border-t border-rule pt-3">
        <dl className="space-y-1 text-sm">
          <div className="flex items-baseline justify-between">
            <dt className="text-xs text-ink-muted">班主任</dt>
            <dd>{cls.homeroomTeacher}</dd>
          </div>
        </dl>
      </div>
    </article>
  );
}
