// ParentAttentionBanner：家长关注横幅
// 依据：参考项目差距补齐 - 仪表盘关注预警
// - 检测：任一子女 pendingHomeworkCount > 0 或 attendanceRate < 0.9
// - 显示预警信息（逾期作业 / 出勤率偏低）
// - 可关闭（本地 state，不持久化）

"use client";

import { useState, useMemo } from "react";
import { cn, formatPercent } from "@/lib/utils";

interface AttentionItem {
  childId: string;
  childName: string;
  pendingHomeworkCount: number;
  attendanceRate: number;
}

interface ParentAttentionBannerProps {
  items: AttentionItem[];
}

interface Warning {
  childId: string;
  childName: string;
  message: string;
  level: "warning" | "danger";
}

export function ParentAttentionBanner({
  items,
}: ParentAttentionBannerProps): JSX.Element | null {
  const [dismissed, setDismissed] = useState(false);

  const warnings = useMemo<Warning[]>(() => {
    const result: Warning[] = [];
    for (const item of items) {
      if (item.pendingHomeworkCount > 0) {
        result.push({
          childId: item.childId,
          childName: item.childName,
          message: `${item.childName}有 ${item.pendingHomeworkCount} 份待办作业`,
          level: "warning",
        });
      }
      if (item.attendanceRate < 0.9) {
        result.push({
          childId: item.childId,
          childName: item.childName,
          message: `${item.childName}出勤率偏低（${formatPercent(item.attendanceRate)}）`,
          level: "danger",
        });
      }
    }
    return result;
  }, [items]);

  if (dismissed || warnings.length === 0) {
    return null;
  }

  const hasDanger = warnings.some((w) => w.level === "danger");

  return (
    <div
      role="alert"
      className={cn(
        "rounded border p-4",
        hasDanger ? "border-danger" : "border-warning",
      )}
      style={{
        backgroundColor: hasDanger
          ? "hsl(var(--danger) / 0.1)"
          : "hsl(var(--warning) / 0.1)",
      }}
    >
      <div className="flex items-start justify-between gap-3">
        <div className="flex-1 space-y-1">
          <p className="font-serif text-base">
            {hasDanger ? "需要关注" : "温馨提醒"}
          </p>
          <ul className="space-y-1 text-sm">
            {warnings.map((w, idx) => (
              <li
                key={`${w.childId}-${idx}`}
                className={cn(
                  w.level === "danger" ? "text-danger" : "text-warning",
                )}
              >
                {w.message}
              </li>
            ))}
          </ul>
        </div>
        <button
          type="button"
          onClick={() => setDismissed(true)}
          className="flex-shrink-0 rounded px-2 py-1 text-sm text-ink-muted hover:text-ink"
          aria-label="关闭横幅"
        >
          ×
        </button>
      </div>
    </div>
  );
}

export default ParentAttentionBanner;
