import rawDataset from "../../../../Mock-Data/dataset.json";

type SidebarLink = {
	label: string;
	detail?: string;
	icon: string;
	href?: string;
	active?: boolean;
};

type SpotlightStat = {
	label: string;
	value: string;
	tone: "purple" | "yellow" | "blue";
};

type QuickStat = {
	label: string;
	value: string;
};

type AssignmentCard = {
	title: string;
	lessons: string;
	accent: "yellow" | "pink" | "teal" | "blue";
	cta: string;
	href: string;
};

type AssignmentFocusStat = {
	label: string;
	value: string;
};

type AssignmentFocusItem = {
	title: string;
	meta: string;
	subMeta: string;
	statusLabel: string;
	progressText: string;
	tone: "yellow" | "teal" | "blue";
	primaryLabel: string;
	primaryHref: string;
	secondaryLabel: string;
	secondaryHref: string;
};

type AssignmentFocusGroup = {
	title: string;
	description: string;
	items: AssignmentFocusItem[];
};

type PracticeFocusStat = {
	label: string;
	value: string;
};

type PracticeFocusCard = {
	title: string;
	description: string;
	meta: string;
	tone: "yellow" | "teal" | "blue";
	primaryLabel: string;
	primaryHref: string;
	secondaryLabel: string;
	secondaryHref: string;
};

type MessageFocusStat = {
	label: string;
	value: string;
};

type MessageFocusThread = {
	sender: string;
	role: string;
	initials: string;
	preview: string;
	timestamp: string;
	unread?: boolean;
	actionLabel: string;
	actionHref: string;
};

type TopbarNotificationItem = {
	title: string;
	description: string;
	timestamp: string;
	href: string;
	tone: "blue" | "yellow" | "teal";
};

type SettingsFocusStat = {
	label: string;
	value: string;
};

type SettingsFocusPanel = {
	title: string;
	description: string;
	rows: Array<{
		label: string;
		value: string;
	}>;
	primaryLabel: string;
	primaryHref: string;
	secondaryLabel?: string;
	secondaryHref?: string;
};

type StudentSupportCard = {
	name: string;
	meta: string;
	initials: string;
	actionLabel: string;
	href: string;
};

type HighlightCard = {
	value: string;
	label: string;
	note: string;
	tone: "yellow" | "pink";
};

type PerformanceBar = {
	label: string;
	value: number;
	tone: "blue" | "purple" | "teal" | "pink" | "yellow";
};

type UsageItem = {
	label: string;
	value: number;
	tone: "blue" | "purple" | "teal" | "yellow";
};

type Dataset = {
	_meta: {
		reference_today: string;
		students: number;
		assignments: number;
		questions_in_bank: number;
		student_answers: number;
		expected_top_3_at_risk_student_ids: number[];
	};
	classroom: {
		name: string;
		invite_code: string;
		target_level: number;
	};
	tutor: {
		fullname: string;
		role: string;
	};
	students: Array<{
		id: number;
		fullname: string;
		_persona: string;
	}>;
	assignments: Array<{
		id: number;
		name: string;
		topic: string;
		status: "DRAFT" | "PUBLISHED" | "CLOSED";
		due_date: number;
		maximum_marks: number;
	}>;
	assignment_assignees: Array<{
		id: number;
		assignment_id: number;
		student_id: number;
		status: "NOT_STARTED" | "IN_PROGRESS" | "SUBMITTED";
		total_marks: number;
	}>;
	student_answers: Array<{
		assignee_id: number;
		_is_correct: boolean;
		_solve_mode: "just_answer" | "step_by_step" | "solve_together" | "handwritten";
		_question_topic: string;
		_answered_at: number;
	}>;
	activity_logs: Array<{
		timestamp: number;
		duration_seconds: number;
		_student_id: number;
	}>;
};

type StudentAssignment = Dataset["assignment_assignees"][number] & {
	assignment: Dataset["assignments"][number];
	answerCount: number;
	accuracy: number;
};

const dataset = rawDataset as Dataset;
const referenceTime = new Date(`${dataset._meta.reference_today}T00:00:00Z`).getTime();
const referenceDate = new Date(referenceTime);
const msPerDay = 1000 * 60 * 60 * 24;
const defaultStudentId = 201;

const students = dataset.students;
const assignments = [...dataset.assignments].sort((left, right) => left.due_date - right.due_date);
const assignees = dataset.assignment_assignees;
const answers = dataset.student_answers;
const activityLogs = dataset.activity_logs;

const student = students.find((entry) => entry.id === defaultStudentId) ?? students[0];

const initialsFor = (name: string) =>
	name
		.split(" ")
		.slice(0, 2)
		.map((part) => part[0])
		.join("")
		.toUpperCase();

const firstName = student.fullname.split(" ")[0];

const formatCompactNumber = (value: number) => new Intl.NumberFormat("en-GB", { notation: "compact", maximumFractionDigits: 1 }).format(value);
const formatPercent = (value: number) => `${Math.round(value)}%`;

const formatDueDate = (timestamp: number) =>
	new Intl.DateTimeFormat("en-GB", {
		month: "short",
		day: "numeric",
	}).format(new Date(timestamp));

const formatHours = (seconds: number) => `${(seconds / 3600).toFixed(1)}h`;

const daysUntil = (timestamp: number) => Math.max(0, Math.ceil((timestamp - referenceTime) / msPerDay));

const formatLastSeen = (timestamp: number) => {
	const dayDiff = Math.max(0, Math.round((referenceTime - timestamp) / msPerDay));
	if (dayDiff <= 0) return "today";
	if (dayDiff === 1) return "yesterday";
	return `${dayDiff} days ago`;
};

const topicTone = ["pink", "yellow", "blue", "purple", "teal"] as const;

const assignmentById = new Map(assignments.map((assignment) => [assignment.id, assignment]));
const assigneeById = new Map(assignees.map((assignee) => [assignee.id, assignee]));

const studentAnswers = answers.filter((answer) => assigneeById.get(answer.assignee_id)?.student_id === student.id);
const studentLogs = activityLogs.filter((log) => log._student_id === student.id);

const studentAssignments: StudentAssignment[] = assignees
	.filter((assignee) => assignee.student_id === student.id)
	.map((assignee) => {
		const assignment = assignmentById.get(assignee.assignment_id);
		if (!assignment) throw new Error(`Missing assignment ${assignee.assignment_id}`);

		const assignmentAnswers = studentAnswers.filter((answer) => answer.assignee_id === assignee.id);
		const answerCount = assignmentAnswers.length;
		const correct = assignmentAnswers.filter((answer) => answer._is_correct).length;

		return {
			...assignee,
			assignment,
			answerCount,
			accuracy: answerCount > 0 ? Math.round((correct / answerCount) * 100) : 0,
		};
	})
	.sort((left, right) => left.assignment.due_date - right.assignment.due_date);

const totalCorrectAnswers = studentAnswers.filter((answer) => answer._is_correct).length;
const overallAccuracy = studentAnswers.length > 0 ? (totalCorrectAnswers / studentAnswers.length) * 100 : 0;
const totalDurationSeconds = studentLogs.reduce((sum, log) => sum + log.duration_seconds, 0);
const latestActivityTime = Math.max(...studentLogs.map((log) => log.timestamp));

const submittedAssignments = studentAssignments.filter((assignment) => assignment.status === "SUBMITTED");
const inProgressAssignments = studentAssignments.filter((assignment) => assignment.status === "IN_PROGRESS");
const notStartedAssignments = studentAssignments.filter((assignment) => assignment.status === "NOT_STARTED");
const pendingAssignments = studentAssignments.filter((assignment) => assignment.status !== "SUBMITTED");

const currentAssignment = inProgressAssignments[0] ?? notStartedAssignments[0] ?? studentAssignments[studentAssignments.length - 1];
const nextNotStartedAssignment = notStartedAssignments[0];

const topicBuckets = new Map<string, { correct: number; total: number }>();
for (const answer of studentAnswers) {
	const bucket = topicBuckets.get(answer._question_topic) ?? { correct: 0, total: 0 };
	bucket.correct += Number(answer._is_correct);
	bucket.total += 1;
	topicBuckets.set(answer._question_topic, bucket);
}

const topicPerformance = [...topicBuckets.entries()].map(([label, bucket]) => ({
	label,
	value: Math.round((bucket.correct / bucket.total) * 100),
	total: bucket.total,
}));

const strongestTopic = [...topicPerformance].sort((left, right) => right.value - left.value || right.total - left.total)[0];
const weakestTopic = [...topicPerformance].sort((left, right) => left.value - right.value || right.total - left.total)[0];

const topicMasteryBars: PerformanceBar[] = [...topicPerformance]
	.sort((left, right) => right.total - left.total || left.value - right.value)
	.slice(0, 5)
	.sort((left, right) => left.value - right.value)
	.map((topic, index) => ({
		label: topic.label,
		value: topic.value,
		tone: topicTone[index % topicTone.length],
	}));

const solveModeBuckets = new Map<string, number>();
for (const answer of studentAnswers) {
	solveModeBuckets.set(answer._solve_mode, (solveModeBuckets.get(answer._solve_mode) ?? 0) + 1);
}

const solveModeToneMap: Record<string, UsageItem["tone"]> = {
	just_answer: "purple",
	step_by_step: "blue",
	solve_together: "teal",
	handwritten: "yellow",
};

const solveModeLabelMap: Record<string, string> = {
	just_answer: "Just answer",
	step_by_step: "Step by step",
	solve_together: "Solve together",
	handwritten: "Handwritten",
};

const solveModeUsage: UsageItem[] = [...solveModeBuckets.entries()]
	.map(([mode, count]) => ({
		label: solveModeLabelMap[mode] ?? mode,
		value: Math.round((count / studentAnswers.length) * 100),
		tone: solveModeToneMap[mode] ?? "blue",
	}))
	.sort((left, right) => right.value - left.value);

const topSolveMode = solveModeUsage[0];

const personaSummary: Record<string, { title: string; recommendation: string }> = {
	fraction_inversion: {
		title: "Fractions is your focus this week",
		recommendation: "Slow down on equivalent fractions and practise inversion rules before test prep.",
	},
	place_value_gaps: {
		title: "Place value is worth another pass",
		recommendation: "Use quick warm-ups before multi-step arithmetic to avoid slips early in the question.",
	},
	rushed_careless: {
		title: "A calmer pace will lift your accuracy",
		recommendation: "Use Step by step more often on tougher questions so careless mistakes do not snowball.",
	},
	solve_together_dependent: {
		title: "Independent confidence is your next goal",
		recommendation: "Try one question solo before switching to Solve together so you build recall first.",
	},
	word_problem_weak: {
		title: "Word problems are the main thing to unlock",
		recommendation: "Underline key information and turn the question into a quick number sentence first.",
	},
	stable_strong: {
		title: "You are in a strong learning rhythm",
		recommendation: "Keep stretching with harder mixed practice so the easier wins stay automatic.",
	},
	stable_mid: {
		title: "You are close to a really strong streak",
		recommendation: "A few focused sessions on weaker topics should move your average up quickly.",
	},
	stable_weak: {
		title: "A steadier routine will help most right now",
		recommendation: "Aim for short, regular practice blocks before trying bigger mixed assignments.",
	},
};

const activePersona = personaSummary[student._persona] ?? {
	title: "Keep building momentum",
	recommendation: "Stay focused on one weak area at a time and finish current work before starting new tasks.",
};

const assignmentAccent = (status: StudentAssignment["status"]): AssignmentCard["accent"] => {
	switch (status) {
		case "IN_PROGRESS":
			return "blue";
		case "NOT_STARTED":
			return "yellow";
		default:
			return "teal";
	}
};

const assignmentCta = (status: StudentAssignment["status"]) => {
	switch (status) {
		case "IN_PROGRESS":
			return "Resume now";
		case "NOT_STARTED":
			return "Start now";
		default:
			return "View recap";
	}
};

const assignmentStatusCopy = (assignment: StudentAssignment) => {
	if (assignment.status === "SUBMITTED") {
		return `${assignment.assignment.topic} · Submitted · Score ${assignment.total_marks}/${assignment.assignment.maximum_marks}`;
	}

	if (assignment.status === "IN_PROGRESS") {
		return `${assignment.assignment.topic} · ${assignment.answerCount} questions answered · Due ${formatDueDate(assignment.assignment.due_date)}`;
	}

	return `${assignment.assignment.topic} · Not started · Due ${formatDueDate(assignment.assignment.due_date)}`;
};

const assignmentCards: AssignmentCard[] = [...studentAssignments]
	.sort((left, right) => {
		const weight = { IN_PROGRESS: 0, NOT_STARTED: 1, SUBMITTED: 2 } as const;
		return weight[left.status] - weight[right.status] || left.assignment.due_date - right.assignment.due_date;
	})
	.slice(0, 4)
	.map((assignment) => ({
		title: assignment.assignment.name,
		lessons: assignmentStatusCopy(assignment),
		accent: assignmentAccent(assignment.status),
		cta: assignmentCta(assignment.status),
		href: `/assignment/${assignment.assignment.id}`,
	}));

const submittedTrend = submittedAssignments.slice(-6).map((assignment) => ({
	label: assignment.assignment.topic.length > 8 ? assignment.assignment.topic.slice(0, 8) : assignment.assignment.topic,
	value: assignment.assignment.maximum_marks > 0 ? Math.round((assignment.total_marks / assignment.assignment.maximum_marks) * 100) : 0,
}));

const usageSummary = {
	note: topSolveMode
		? `You use ${topSolveMode.label} for ${topSolveMode.value}% of your answers. When ${weakestTopic?.label?.toLowerCase() ?? "a topic"} gets tricky, try Step by step for a calmer second try.`
		: "Try a mix of independent and guided solving to learn what helps you most.",
};

export const classroomSummary = {
	name: dataset.classroom.name,
	targetLevel: dataset.classroom.target_level,
	inviteCode: dataset.classroom.invite_code,
	tutorName: dataset.tutor.fullname,
	tutorRole: "Lead tutor",
	tutorInitials: initialsFor(dataset.tutor.fullname),
};

export const sidebarLinks: SidebarLink[] = [
	{ label: "Home", detail: "Today", icon: "⌂", href: "/dashboard", active: true },
	{ label: "Assignments", detail: `${pendingAssignments.length} live`, icon: "✓", href: "/dashboard/assignments" },
	{ label: "Progress", detail: `${Math.round(overallAccuracy)}% accuracy`, icon: "↗", href: "/dashboard/progress" },
	{ label: "Practice", detail: weakestTopic?.label ?? "Mixed skills", icon: "✦", href: "/dashboard/practice" },
	{ label: "Messages", detail: dataset.tutor.fullname.split(" ")[0], icon: "✉", href: "/dashboard/messages" },
	{ label: "Settings", detail: "Profile & goals", icon: "⋯", href: "/dashboard/settings" },
];

export const sidebarSupport = {
	avatars: [currentAssignment.assignment.name.replace("HW", "H").split("—")[0].trim(), weakestTopic?.label.slice(0, 2) ?? "WK", nextNotStartedAssignment?.assignment.name.replace("HW", "H").split("—")[0].trim() ?? "GO"],
	title: "Today’s study plan",
	description: `Pick up ${currentAssignment.assignment.name.split("—")[0].trim()}, spend 15 minutes on ${weakestTopic?.label ?? "your focus topic"}, then start ${nextNotStartedAssignment ? nextNotStartedAssignment.assignment.name.split("—")[0].trim() : "your next task"} while it still feels easy.`,
	buttonLabel: "Open my plan",
	buttonHref: `/assignment/${currentAssignment.assignment.id}/work`,
};

export const topbarSummary = {
	searchPlaceholder: "Search assignments, hints, or question topics",
	profileName: student.fullname,
	profileRole: `${dataset.classroom.name} · Student`,
	profileBadge: initialsFor(student.fullname),
	notificationCount: 3,
	messageCount: 1,
};

export const topbarNotifications: TopbarNotificationItem[] = [
	{
		title: `${currentAssignment.assignment.name.split("—")[0].trim()} is still live`,
		description: currentAssignment.status === "SUBMITTED"
			? `You have already finished this task. Open the review and clean up any missed marks.`
			: `${currentAssignment.answerCount} questions are already touched. Finish it before ${formatDueDate(currentAssignment.assignment.due_date)}.`,
		timestamp: `${daysUntil(currentAssignment.assignment.due_date)}d left`,
		href: currentAssignment.status === "SUBMITTED" ? `/assignment/${currentAssignment.assignment.id}` : `/assignment/${currentAssignment.assignment.id}/work`,
		tone: currentAssignment.status === "SUBMITTED" ? "teal" : "blue",
	},
	{
		title: `${weakestTopic?.label ?? "Focus practice"} needs a quick pass`,
		description: weakestTopic
			? `${weakestTopic.value}% accuracy across ${weakestTopic.total} recent questions. A short focused block here should move the needle fastest.`
			: "Open a short practice block and work through your next weak spot.",
		timestamp: "Practice now",
		href: "/dashboard/practice",
		tone: "yellow",
	},
	{
		title: `${dataset.tutor.fullname.split(" ")[0]} left feedback`,
		description: `There is a fresh tutor message waiting with a calm next-step suggestion for ${weakestTopic?.label?.toLowerCase() ?? "your current focus"}.`,
		timestamp: "Today",
		href: "/dashboard/messages",
		tone: "teal",
	},
];

export const heroSummary = {
	eyebrow: `Welcome back, ${firstName}`,
	title: activePersona.title,
	description: `You have finished ${submittedAssignments.length} assignments so far. Right now, the best next step is to keep ${currentAssignment.assignment.name.split("—")[0].trim()} moving and give ${weakestTopic?.label ?? "your focus topic"} a short confidence boost.`,
	visualBadges: [formatPercent(overallAccuracy), `${currentAssignment.assignment.name.split("—")[0].trim()} live`, `${weakestTopic?.label ?? "Focus"} focus`],
};

export const spotlightStats: SpotlightStat[] = [
	{ label: "Assignments done", value: `${submittedAssignments.length}/${studentAssignments.length}`, tone: "purple" },
	{ label: "Current focus", value: weakestTopic?.label ?? "Mixed practice", tone: "yellow" },
	{ label: "Best topic", value: strongestTopic?.label ?? "Building", tone: "blue" },
];

export const heroSideCard = {
	title: currentAssignment.status === "SUBMITTED" ? `Nice work on ${currentAssignment.assignment.name.split("—")[0].trim()}` : `Pick up where you left off`,
	description:
		currentAssignment.status === "SUBMITTED"
			? `You scored ${currentAssignment.total_marks}/${currentAssignment.assignment.maximum_marks}. A quick recap now will make the next assignment feel easier.`
			: `${currentAssignment.answerCount} questions are already done. Finish it by ${formatDueDate(currentAssignment.assignment.due_date)} while the topic is still fresh.`,
	buttonLabel: currentAssignment.status === "SUBMITTED" ? "Review this work" : "Resume assignment",
	buttonHref: currentAssignment.status === "SUBMITTED" ? `/assignment/${currentAssignment.assignment.id}` : `/assignment/${currentAssignment.assignment.id}/work`,
};

export const quickStats: QuickStat[] = [
	{ label: "Next due", value: `${daysUntil(currentAssignment.assignment.due_date)}d` },
	{ label: "Last active", value: formatLastSeen(latestActivityTime) },
];

export { assignmentCards };

export const assignmentFocusStats: AssignmentFocusStat[] = [
	{ label: "Live now", value: `${pendingAssignments.length}` },
	{ label: "Completed", value: `${submittedAssignments.length}` },
	{ label: "Average score", value: formatPercent(overallAccuracy) },
	{ label: "Next due", value: formatDueDate(currentAssignment.assignment.due_date) },
];

export const progressFocusStats: AssignmentFocusStat[] = [
	{ label: "Accuracy", value: formatPercent(overallAccuracy) },
	{ label: "Marked", value: `${submittedAssignments.length}` },
	{ label: "Strongest", value: strongestTopic?.label ?? "Building" },
	{ label: "Study time", value: formatHours(totalDurationSeconds) },
];

export const practiceFocusStats: PracticeFocusStat[] = [
	{ label: "Focus topic", value: weakestTopic?.label ?? "Mixed skills" },
	{ label: "Topic score", value: weakestTopic ? formatPercent(weakestTopic.value) : "--" },
	{ label: "Best support", value: topSolveMode?.label ?? "Try mixed modes" },
	{ label: "Ready now", value: currentAssignment.assignment.name.split("—")[0].trim() },
];

export const practiceFocusCards: PracticeFocusCard[] = [
	{
		title: `Rebuild ${weakestTopic?.label ?? "your focus topic"}`,
		description: `Start with the topic that is costing you the most marks right now, then return to your current assignment while the method is still fresh.`,
		meta: weakestTopic ? `${weakestTopic.total} recent questions · ${weakestTopic.value}% accuracy` : "Short, focused practice is the fastest win.",
		tone: "yellow",
		primaryLabel: "Open practice",
		primaryHref: `/assignment/${currentAssignment.assignment.id}/work`,
		secondaryLabel: "View progress",
		secondaryHref: "/dashboard/progress",
	},
	{
		title: "Try one independent pass",
		description: topSolveMode
			? `${topSolveMode.label} is your default. Try answering one question solo before switching modes so you build stronger recall.`
			: "Use one question to test yourself first, then bring in guided help if you need it.",
		meta: `Current assignment: ${currentAssignment.assignment.name}`,
		tone: "blue",
		primaryLabel: currentAssignment.status === "IN_PROGRESS" ? "Resume work" : "Start assignment",
		primaryHref: `/assignment/${currentAssignment.assignment.id}/work`,
		secondaryLabel: "Review task",
		secondaryHref: `/assignment/${currentAssignment.assignment.id}`,
	},
	{
		title: `Finish with ${strongestTopic?.label ?? "a strong topic"}`,
		description: `Once the hard bit is done, finish your session on something you usually get right so your next study block starts with confidence.`,
		meta: strongestTopic ? `${strongestTopic.value}% accuracy in ${strongestTopic.label}` : "Pick a familiar topic for a strong finish.",
		tone: "teal",
		primaryLabel: "See assignments",
		primaryHref: "/dashboard/assignments",
		secondaryLabel: "Open dashboard",
		secondaryHref: "/dashboard",
	},
];

export const messageFocusStats: MessageFocusStat[] = [
	{ label: "Tutor", value: dataset.tutor.fullname.split(" ")[0] },
	{ label: "Unread", value: "3" },
	{ label: "Latest topic", value: weakestTopic?.label ?? "Mixed skills" },
	{ label: "Last active", value: formatLastSeen(latestActivityTime) },
];

export const messageFocusThreads: MessageFocusThread[] = [
	{
		sender: dataset.tutor.fullname,
		role: "Tutor",
		initials: initialsFor(dataset.tutor.fullname),
		preview: `Let’s spend the next session tightening up ${weakestTopic?.label?.toLowerCase() ?? "your focus topic"}. You only need a couple of calm wins here to lift your confidence.`,
		timestamp: "Today",
		unread: true,
		actionLabel: "Open practice",
		actionHref: "/dashboard/practice",
	},
	{
		sender: "Assignment check-in",
		role: currentAssignment.assignment.name.split("—")[0].trim(),
		initials: currentAssignment.assignment.name.replace("HW", "H").split("—")[0].trim(),
		preview: currentAssignment.status === "SUBMITTED"
			? `Nice work finishing this one. Review the marked questions before you start the next task.`
			: `${currentAssignment.answerCount} questions are already done. Finish this assignment before ${formatDueDate(currentAssignment.assignment.due_date)} while it still feels familiar.`,
		timestamp: currentAssignment.status === "SUBMITTED" ? "Yesterday" : `${daysUntil(currentAssignment.assignment.due_date)}d left`,
		actionLabel: currentAssignment.status === "SUBMITTED" ? "Open review" : "Resume work",
		actionHref: currentAssignment.status === "SUBMITTED" ? `/assignment/${currentAssignment.assignment.id}` : `/assignment/${currentAssignment.assignment.id}/work`,
	},
	{
		sender: "Study coach",
		role: "Quick reminder",
		initials: "SC",
		preview: `Your strongest topic is ${strongestTopic?.label ?? "building"}. End today with one easier question there after you practise ${weakestTopic?.label?.toLowerCase() ?? "your focus topic"}.`,
		timestamp: "2 days ago",
		actionLabel: "View progress",
		actionHref: "/dashboard/progress",
	},
];

export const topbarMessages = messageFocusThreads.slice(0, 3);

export const settingsFocusStats: SettingsFocusStat[] = [
	{ label: "Student", value: firstName },
	{ label: "Class", value: `Year ${dataset.classroom.target_level}` },
	{ label: "Focus", value: weakestTopic?.label ?? "Mixed skills" },
	{ label: "Goal", value: `${Math.max(Math.round(overallAccuracy) + 10, 70)}%` },
];

export const settingsFocusPanels: SettingsFocusPanel[] = [
	{
		title: "Profile",
		description: "The learner details and classroom context this dashboard is currently designed around.",
		rows: [
			{ label: "Name", value: student.fullname },
			{ label: "Role", value: `${dataset.classroom.name} · Student` },
			{ label: "Tutor", value: dataset.tutor.fullname },
			{ label: "Invite code", value: dataset.classroom.invite_code },
		],
		primaryLabel: "Open messages",
		primaryHref: "/dashboard/messages",
		secondaryLabel: "View progress",
		secondaryHref: "/dashboard/progress",
	},
	{
		title: "Learning preferences",
		description: "A few smart defaults for how this learner is currently working best.",
		rows: [
			{ label: "Best support mode", value: topSolveMode?.label ?? "Mixed support" },
			{ label: "Strongest topic", value: strongestTopic?.label ?? "Building confidence" },
			{ label: "Needs attention", value: weakestTopic?.label ?? "Mixed skills" },
			{ label: "Last active", value: formatLastSeen(latestActivityTime) },
		],
		primaryLabel: "Open practice",
		primaryHref: "/dashboard/practice",
		secondaryLabel: "See assignments",
		secondaryHref: "/dashboard/assignments",
	},
	{
		title: "Goals and reminders",
		description: "Settings-like controls can start by summarising the targets and nudges this learner should keep in view.",
		rows: [
			{ label: "Current goal", value: `Lift ${weakestTopic?.label?.toLowerCase() ?? "focus work"} by 10%` },
			{ label: "Live assignments", value: `${pendingAssignments.length}` },
			{ label: "Study time", value: formatHours(totalDurationSeconds) },
			{ label: "Next due", value: formatDueDate(currentAssignment.assignment.due_date) },
		],
		primaryLabel: "Open today’s plan",
		primaryHref: `/assignment/${currentAssignment.assignment.id}/work`,
		secondaryLabel: "Go to dashboard",
		secondaryHref: "/dashboard",
	},
];

const mapAssignmentFocusItem = (assignment: StudentAssignment): AssignmentFocusItem => {
	const isSubmitted = assignment.status === "SUBMITTED";
	const isInProgress = assignment.status === "IN_PROGRESS";

	return {
		title: assignment.assignment.name,
		meta: assignment.assignment.topic,
		subMeta: isSubmitted
			? `Marked ${assignment.total_marks}/${assignment.assignment.maximum_marks} · Reviewed ${assignment.answerCount} questions`
			: `Due ${formatDueDate(assignment.assignment.due_date)} · ${assignment.answerCount} questions touched so far`,
		statusLabel: isSubmitted ? "Completed" : isInProgress ? "In progress" : "Ready to start",
		progressText: isSubmitted ? `${assignment.accuracy}% accuracy` : `${daysUntil(assignment.assignment.due_date)}d left`,
		tone: isSubmitted ? "teal" : isInProgress ? "blue" : "yellow",
		primaryLabel: isSubmitted ? "Open review" : isInProgress ? "Resume work" : "Start assignment",
		primaryHref: isSubmitted ? `/assignment/${assignment.assignment.id}` : `/assignment/${assignment.assignment.id}/work`,
		secondaryLabel: isSubmitted ? "Open workspace" : "See review",
		secondaryHref: isSubmitted ? `/assignment/${assignment.assignment.id}/work` : `/assignment/${assignment.assignment.id}`,
	};
};

export const assignmentFocusGroups: AssignmentFocusGroup[] = [
	{
		title: "Continue now",
		description: "Assignments that already have momentum and are best finished next.",
		items: studentAssignments.filter((assignment) => assignment.status === "IN_PROGRESS").map(mapAssignmentFocusItem),
	},
	{
		title: "Coming up",
		description: "Work that is live but not started yet, so you can choose what to begin early.",
		items: studentAssignments.filter((assignment) => assignment.status === "NOT_STARTED").map(mapAssignmentFocusItem),
	},
	{
		title: "Completed",
		description: "Marked work you can revisit for review, correction, and confidence boosts.",
		items: studentAssignments.filter((assignment) => assignment.status === "SUBMITTED").map(mapAssignmentFocusItem),
	},
].filter((group) => group.items.length > 0);

export const activitySummary = {
	title: "Recent results",
	note: `${submittedAssignments.length} assignments have been marked so far. Use this as a quick check on what is improving and what still needs another pass.`,
	badge: `${submittedAssignments.length} marked`,
};

export const progressPoints = submittedTrend.map((point) => point.value);
export const progressLabels = submittedTrend.map((point) => point.label);

export const highlightCards: HighlightCard[] = [
	{
		value: `${studentAnswers.length}`,
		label: "Questions answered",
		note: `You have already submitted ${submittedAssignments.length} assignments and still have ${pendingAssignments.length} live tasks to work through.`,
		tone: "yellow",
	},
	{
		value: formatHours(totalDurationSeconds),
		label: "Time invested",
		note: `Last active ${formatLastSeen(latestActivityTime)}. ${activePersona.recommendation}`,
		tone: "pink",
	},
];

export const studentSupportList: StudentSupportCard[] = [
	{
		name: `Review ${weakestTopic?.label ?? "your focus topic"}`,
		meta: `${weakestTopic?.value ?? 0}% accuracy across ${weakestTopic?.total ?? 0} questions. A short refresher here should give you the fastest win.`,
		initials: weakestTopic?.label.slice(0, 2).toUpperCase() ?? "WK",
		actionLabel: "Start practice",
		href: `/assignment/${currentAssignment.assignment.id}/work`,
	},
	{
		name: `Finish ${currentAssignment.assignment.name.split("—")[0].trim()}`,
		meta:
			currentAssignment.status === "IN_PROGRESS"
				? `${currentAssignment.answerCount} questions are already done. One more focused block should move this over the line.`
				: `This is your next live assignment. Starting early will make it feel much lighter later in the week.`,
		initials: currentAssignment.assignment.name.replace("HW", "H").split("—")[0].trim(),
		actionLabel: currentAssignment.status === "IN_PROGRESS" ? "Resume" : "Start",
		href: `/assignment/${currentAssignment.assignment.id}/work`,
	},
	{
		name: "Try one question solo",
		meta: topSolveMode
			? `${topSolveMode.label} is your default mode. Try one independent attempt before asking for help on the next tricky question.`
			: "Try guided support on tougher questions, then return to independent practice.",
		initials: "IP",
		actionLabel: "Use this tip",
		href: `/assignment/${currentAssignment.assignment.id}/work`,
	},
];

export { topicMasteryBars };

export const overallPassRate = Math.round(overallAccuracy);

export { solveModeUsage, usageSummary };
