// useChildTrend：获取子女学习趋势数据
// 依据：02-architecture-design.md §4.2 GraphQL 接入
// 对标 student-portal /dashboard/trend 页面

"use client";

import { useQuery } from "urql";
import { CHILD_TREND } from "@/lib/graphql/operations";
import type { LearningTrend, TrendDataPoint } from "@/types";
import { useChildStore } from "@/store/child-store";

interface ChildTrendResponse {
  childTrend: LearningTrend;
}

export type TrendPeriod = "week" | "month" | "semester";

export function useChildTrend(period: TrendPeriod = "month") {
  const currentChildId = useChildStore((s) => s.currentChildId);

  const [result] = useQuery<ChildTrendResponse>({
    query: CHILD_TREND,
    variables: { childId: currentChildId, period },
    pause: !currentChildId,
  });

  const dataPoints: TrendDataPoint[] =
    result.data?.childTrend?.dataPoints ?? [];

  // 汇总统计
  const scores = dataPoints.map((d) => d.score);
  const avgScore =
    scores.length > 0 ? scores.reduce((a, b) => a + b, 0) / scores.length : 0;
  const maxScore = scores.length > 0 ? Math.max(...scores) : 0;
  const minScore = scores.length > 0 ? Math.min(...scores) : 0;

  // 趋势方向
  let trendDirection: "up" | "down" | "stable" = "stable";
  if (scores.length >= 2) {
    const last = scores.at(-1);
    const prev = scores.at(-2);
    if (last !== undefined && prev !== undefined) {
      if (last > prev + 1) trendDirection = "up";
      else if (last < prev - 1) trendDirection = "down";
    }
  }

  return {
    dataPoints,
    period,
    avgScore: Math.round(avgScore * 10) / 10,
    maxScore,
    minScore,
    trendDirection,
    loading: result.fetching,
    error: result.error,
  };
}
