/**
 * Mock 教材数据（content 域，P7 扩展）
 *
 * 维护者：ai13（teacher-portal）
 *
 * 覆盖：
 * - 8 本教材（语文/数学/英语/物理/化学/生物/历史/地理，覆盖小学/初中/高中）
 * - 每本教材含 5-10 章节，每章节含 3-8 知识点
 * - 章节支持嵌套（parentId），mock 数据保持单层便于阅读器渲染
 */

import type {
  TextbookItem,
  TextbookDetail,
  TextbookChapter,
  KnowledgePoint,
  TextbookCreateInput,
  TextbooksFilter,
  TextbooksPage,
} from "@/lib/graphql-p7-exams";

/** 学科 */
const SUBJECTS = [
  "语文",
  "数学",
  "英语",
  "物理",
  "化学",
  "生物",
  "历史",
  "地理",
] as const;

/** 年级 */
const GRADES = [
  "小学三年级",
  "小学六年级",
  "初中一年级",
  "初中三年级",
  "高中一年级",
  "高中三年级",
] as const;

/** 版本 */
const VERSIONS = ["人教版", "北师大版", "苏教版", "鲁科版"] as const;

/** 教材定义（8 本） */
interface TextbookDef {
  id: string;
  title: string;
  subject: (typeof SUBJECTS)[number];
  grade: (typeof GRADES)[number];
  version: (typeof VERSIONS)[number];
  chapterCount: number;
}

const TEXTBOOK_DEFS: TextbookDef[] = [
  {
    id: "tb-001",
    title: "小学语文三年级上册",
    subject: "语文",
    grade: "小学三年级",
    version: "人教版",
    chapterCount: 8,
  },
  {
    id: "tb-002",
    title: "小学数学六年级上册",
    subject: "数学",
    grade: "小学六年级",
    version: "北师大版",
    chapterCount: 10,
  },
  {
    id: "tb-003",
    title: "初中英语七年级上册",
    subject: "英语",
    grade: "初中一年级",
    version: "人教版",
    chapterCount: 9,
  },
  {
    id: "tb-004",
    title: "初中物理九年级全册",
    subject: "物理",
    grade: "初中三年级",
    version: "苏教版",
    chapterCount: 7,
  },
  {
    id: "tb-005",
    title: "高中化学必修一",
    subject: "化学",
    grade: "高中一年级",
    version: "鲁科版",
    chapterCount: 5,
  },
  {
    id: "tb-006",
    title: "高中生物必修一·分子与细胞",
    subject: "生物",
    grade: "高中一年级",
    version: "人教版",
    chapterCount: 6,
  },
  {
    id: "tb-007",
    title: "高中历史必修·中外历史纲要",
    subject: "历史",
    grade: "高中一年级",
    version: "人教版",
    chapterCount: 8,
  },
  {
    id: "tb-008",
    title: "高中地理必修一·自然地理",
    subject: "地理",
    grade: "高中一年级",
    version: "人教版",
    chapterCount: 6,
  },
];

/** 教材列表（含章节数） */
export const MOCK_TEXTBOOKS: TextbookItem[] = TEXTBOOK_DEFS.map((d) => ({
  id: d.id,
  title: d.title,
  subject: d.subject,
  grade: d.grade,
  version: d.version,
  coverUrl: null,
  chapterCount: d.chapterCount,
  createdAt: "2026-06-01T08:00:00.000Z",
}));

/** 章节模板（按学科生成不同内容） */
function generateChapter(
  textbookId: string,
  order: number,
  subject: string,
): TextbookChapter {
  const chapterId = `${textbookId}-ch-${String(order).padStart(2, "0")}`;
  const titlePrefix = `第${order}章`;
  const titles: Record<string, string[]> = {
    语文: ["春天的故事", "古诗词赏析", "现代文阅读", "写作训练", "文言文入门"],
    数学: ["数与代数", "图形与几何", "统计与概率", "函数初步", "方程与不等式"],
    英语: ["Greetings", "Family", "School Life", "Hobbies", "Festivals"],
    物理: ["运动与力", "声与光", "热现象", "电与磁", "能量守恒"],
    化学: ["物质分类", "原子结构", "化学键", "氧化还原", "元素周期律"],
    生物: ["细胞结构", "细胞代谢", "细胞增殖", "遗传基础", "生物进化"],
    历史: ["古代政治", "近代变革", "世界大战", "冷战格局", "改革开放"],
    地理: ["地球运动", "大气环流", "水循环", "地貌演化", "自然环境"],
  };
  const subjectTitles = titles[subject] ?? ["导论", "正文", "拓展", "总结", "复习"];
  const titleIndex = (order - 1) % subjectTitles.length;
  const titleSuffix = subjectTitles[titleIndex] ?? "导论";
  // 知识点数量 3-8（按章节顺序周期性变化）
  const kpCount = 3 + (order % 6); // 3..8
  const knowledgePoints: KnowledgePoint[] = [];
  for (let k = 1; k <= kpCount; k++) {
    knowledgePoints.push({
      id: `${chapterId}-kp-${String(k).padStart(2, "0")}`,
      name: `${titleSuffix}·知识点${k}`,
      description: `本节涉及${titleSuffix}的第 ${k} 个核心知识点，建议结合实例理解。`,
    });
  }
  return {
    id: chapterId,
    textbookId,
    title: `${titlePrefix} ${titleSuffix}`,
    order,
    content: `# ${titlePrefix} ${titleSuffix}\n\n## 学习目标\n\n掌握${titleSuffix}的核心概念与基本方法。\n\n## 知识概览\n\n本章节将系统介绍${titleSuffix}的主要内容，分为 ${kpCount} 个知识点逐一讲解。\n\n## 正文\n\n${titleSuffix}是${subject}学科的重要组成部分，理解其基本原理对后续学习至关重要。本节通过实例分析与练习巩固，帮助学生建立完整知识体系。\n\n## 小结\n\n通过本章学习，应能够独立完成相关习题，并能将${titleSuffix}的方法迁移到实际问题中。`,
    parentId: null,
    knowledgePoints,
  };
}

/** 教材详情（含章节树 + 知识点） */
export const MOCK_TEXTBOOK_DETAILS: TextbookDetail[] = TEXTBOOK_DEFS.map(
  (d) => {
    const chapters: TextbookChapter[] = [];
    for (let i = 1; i <= d.chapterCount; i++) {
      chapters.push(generateChapter(d.id, i, d.subject));
    }
    return {
      id: d.id,
      title: d.title,
      subject: d.subject,
      grade: d.grade,
      version: d.version,
      coverUrl: null,
      chapters,
    };
  },
);

/** 按教材 ID 查询详情 */
export function findTextbookDetail(id: string): TextbookDetail | null {
  return MOCK_TEXTBOOK_DETAILS.find((t) => t.id === id) ?? null;
}

/** 按筛选条件过滤教材（分页） */
export function filterTextbooks(filter: TextbooksFilter): TextbooksPage {
  const q = (filter.q ?? "").trim().toLowerCase();
  const subject = filter.subject ?? null;
  const grade = filter.grade ?? null;
  const page = Math.max(1, filter.page ?? 1);
  const pageSize = Math.max(1, filter.pageSize ?? 20);

  let items = MOCK_TEXTBOOKS;
  if (q) {
    items = items.filter((t) => t.title.toLowerCase().includes(q));
  }
  if (subject && subject !== "all") {
    items = items.filter((t) => t.subject === subject);
  }
  if (grade && grade !== "all") {
    items = items.filter((t) => t.grade === grade);
  }

  const total = items.length;
  const start = (page - 1) * pageSize;
  const paged = items.slice(start, start + pageSize);
  return { items: paged, total, page, pageSize };
}

/** 创建新教材（基于 input 生成 TextbookItem，章节数为 0） */
export function createMockTextbook(input: TextbookCreateInput): TextbookItem {
  const randomId = `tb-${Math.random().toString(36).slice(2, 8)}`;
  return {
    id: randomId,
    title: input.title,
    subject: input.subject,
    grade: input.grade,
    version: input.version,
    coverUrl: input.coverUrl ?? null,
    chapterCount: 0,
    createdAt: new Date().toISOString(),
  };
}

/** 学科列表（用于筛选下拉） */
export const TEXTBOOK_SUBJECTS: readonly string[] = SUBJECTS;

/** 年级列表（用于筛选下拉） */
export const TEXTBOOK_GRADES: readonly string[] = GRADES;

/** 版本列表（用于筛选下拉） */
export const TEXTBOOK_VERSIONS: readonly string[] = VERSIONS;
