"use client";

/**
 * 学习路径页（ai14，P4）
 *
 * - 消费 useLearningPath 查询
 * - 知识点卡片：标题、推荐顺序、掌握度进度条（0-100%）、推荐动作
 * - 可视化进度指示
 */

import { useLearningPath } from "@/lib/graphql/hooks";
import type { LearningPathNode } from "@/lib/graphql/types";

const STATUS_LABEL: Record<LearningPathNode["status"], string> = {
  locked: "未解锁",
  available: "可学习",
  "in-progress": "学习中",
  completed: "已完成",
};

function masteryPercent(node: LearningPathNode): number {
  return Math.round(Math.max(0, Math.min(1, node.mastery)) * 100);
}

function statusTone(status: LearningPathNode["status"]): string {
  switch (status) {
    case "completed":
      return "var(--color-success)";
    case "in-progress":
      return "var(--color-accent)";
    case "available":
      return "var(--color-info)";
    default:
      return "var(--color-ink-subtle)";
  }
}

function recommendedText(node: LearningPathNode): string {
  if (node.mastery >= 0.8) return "已掌握";
  if (node.mastery >= 0.5) return "建议练习";
  return "建议复习";
}

export default function LearningPathPage(): React.ReactNode {
  const { data, fetching, error, reexecute } = useLearningPath();
  const nodes = data ?? [];

  return (
    <main
      className="px-md py-lg max-w-4xl mx-auto"
      aria-labelledby="learning-path-title"
    >
      <header className="mb-lg">
        <h1 id="learning-path-title" className="font-serif text-2xl text-ink">
          学习路径
        </h1>
        <p className="mt-xs text-sm text-ink-muted">
          按知识点掌握度推荐的学习顺序
        </p>
      </header>

      <div className="rule-thin mb-lg" />

      {fetching ? (
        <p className="text-sm text-ink-muted" aria-live="polite">
          加载中…
        </p>
      ) : error ? (
        <div className="mark-left py-md px-md mb-md" aria-live="assertive">
          <p className="text-sm text-ink">{error.message || "加载失败"}</p>
          <button
            type="button"
            className="btn-secondary mt-sm"
            onClick={() => reexecute()}
          >
            重试
          </button>
        </div>
      ) : nodes.length === 0 ? (
        <p className="text-sm text-ink-muted" role="status">
          暂无学习路径数据
        </p>
      ) : (
        <ol className="space-y-md" aria-label="学习路径节点列表">
          {nodes.map((node, index) => {
            const pct = masteryPercent(node);
            return (
              <li key={node.id}>
                <article className="card-paper p-md">
                  <div className="flex items-start justify-between gap-md">
                    <div className="min-w-0 flex-1">
                      <div className="flex items-center gap-sm mb-xs">
                        <span className="text-xs text-ink-subtle">
                          第 {node.recommendedOrder || index + 1} 步
                        </span>
                        <span
                          className="badge"
                          style={{ color: statusTone(node.status) }}
                          aria-label={`状态：${STATUS_LABEL[node.status]}`}
                        >
                          {STATUS_LABEL[node.status]}
                        </span>
                      </div>
                      <h2 className="font-serif text-base text-ink text-truncate">
                        {node.name}
                      </h2>
                    </div>
                    <div className="text-right shrink-0">
                      <p className="text-xs text-ink-subtle">掌握度</p>
                      <p
                        className="font-serif text-xl"
                        style={{ color: statusTone(node.status) }}
                        aria-label={`掌握度 ${pct}%`}
                      >
                        {pct}%
                      </p>
                    </div>
                  </div>

                  {/* 进度条 */}
                  <div
                    className="mt-md h-2 w-full rounded"
                    style={{ background: "var(--color-rule)" }}
                    role="progressbar"
                    aria-valuenow={pct}
                    aria-valuemin={0}
                    aria-valuemax={100}
                    aria-label={`${node.name} 掌握度进度条`}
                  >
                    <div
                      className="h-2 rounded"
                      style={{
                        width: `${pct}%`,
                        background: statusTone(node.status),
                      }}
                    />
                  </div>

                  <p className="mt-md text-sm text-ink-muted">
                    <span className="text-ink-subtle">推荐动作：</span>
                    {recommendedText(node)}
                  </p>
                </article>
              </li>
            );
          })}
        </ol>
      )}
    </main>
  );
}
