RotNot / src /app /reading /page.tsx
deploy
Deploy RotNot
9580dce
Raw History Blame Contribute Delete
25.2 kB
"use client";
import { useState, useCallback, useEffect } from "react";
import { motion } from "framer-motion";
import { Reader } from "@/components/reading/reader";
import { XpResults } from "@/components/shared/xp-results";
import { LevelUpOverlay } from "@/components/shared/level-up";
import { SkillUnlockToast } from "@/components/shared/skill-unlock-toast";
import { apiClient, ApiClientError } from "@/lib/api-client";
import type { ReadingArticle as ApiReadingArticle } from "@/lib/api-client";
import type { ArticleDifficulty } from "@/lib/reading/articles";
import type { ComprehensionQuestion } from "@/app/api/reading/questions/route";
const GREEN = "#10b981";
type UIState =
| "idle"
| "loading-article"
| "reading"
| "generating-questions"
| "quiz"
| "scoring"
| "results";
type Difficulty = "any" | ArticleDifficulty;
type ContentSource = "library" | "url" | "paste";
interface ScoreResult {
scores: { questionId: number; score: number; feedback: string }[];
overallFeedback: string;
avgScore: number;
xp: { baseXp: number; totalXp: number; qualityBonus: number; isCriticalHit: boolean; multiplierBonus?: number; multiplierPercent?: number };
levelUp: boolean;
categoryXp: { currentXp: number; xpToNext: number; level: number; levelUp: boolean };
newTitle?: string;
unlocks?: string[];
streakFreezesGranted?: number;
}
/** Extended article with optional source metadata for custom content */
type ReadingArticle = ApiReadingArticle;
const DIFFICULTIES: Difficulty[] = ["any", "beginner", "intermediate", "advanced"];
const DIFFICULTY_LABELS: Record<Difficulty, string> = {
any: "Any Level",
beginner: "Beginner",
intermediate: "Intermediate",
advanced: "Advanced",
};
const SOURCE_TABS: { id: ContentSource; label: string; icon: string }[] = [
{ id: "library", label: "Library", icon: "📚" },
{ id: "url", label: "From URL", icon: "🔗" },
{ id: "paste", label: "Paste Text", icon: "📋" },
];
function ScoreBar({
label,
value,
delay,
}: {
label: string;
value: number;
delay: number;
}) {
const color = value >= 7 ? "#22c55e" : value >= 4 ? "#eab308" : "#ef4444";
return (
<div className="mb-4">
<div className="flex justify-between mb-1">
<span className="text-sm font-medium" style={{ color: "var(--text-secondary)" }}>
{label}
</span>
<span
className="text-sm font-bold"
style={{ color, fontFamily: "var(--font-mono)" }}
>
{value}/10
</span>
</div>
<div className="w-full h-3 rounded-full" style={{ background: "rgba(255,255,255,0.08)" }}>
<motion.div
className="h-3 rounded-full"
style={{ background: color }}
initial={{ width: 0 }}
animate={{ width: `${(value / 10) * 100}%` }}
transition={{ duration: 0.8, delay, ease: "easeOut" }}
/>
</div>
</div>
);
}
export default function ReadingPage() {
const [uiState, setUiState] = useState<UIState>("idle");
const [difficulty, setDifficulty] = useState<Difficulty>("any");
const [contentSource, setContentSource] = useState<ContentSource>("library");
const [urlInput, setUrlInput] = useState("");
const [pasteTitle, setPasteTitle] = useState("");
const [pasteText, setPasteText] = useState("");
const [article, setArticle] = useState<ReadingArticle | null>(null);
const [durationSecs, setDurationSecs] = useState(0);
const [questions, setQuestions] = useState<ComprehensionQuestion[]>([]);
const [answers, setAnswers] = useState<Record<number, string>>({});
const [result, setResult] = useState<ScoreResult | null>(null);
const [error, setError] = useState<string | null>(null);
const [showLevelUp, setShowLevelUp] = useState(false);
const [difficultyHint, setDifficultyHint] = useState<string | null>(null);
useEffect(() => {
apiClient.getCoachDifficulty()
.then((data) => {
const rec = data.recommendations?.reading;
if (rec?.boost !== undefined && rec.difficulty) setDifficultyHint(rec.difficulty);
})
.catch(() => {});
}, []);
const handleStartLibrary = useCallback(async () => {
setUiState("loading-article");
setError(null);
try {
const data = await apiClient.getReadingContent(
difficulty !== "any" ? { difficulty } : {},
);
if (!data.article) throw new Error("Failed to load article");
setArticle(data.article);
setUiState("reading");
} catch (err) {
setError(
err instanceof ApiClientError
? ((err.body as { error?: string })?.error ?? "Failed to load article")
: err instanceof Error
? err.message
: "Failed to load article",
);
setUiState("idle");
}
}, [difficulty]);
const handleStartUrl = useCallback(async () => {
if (!urlInput.trim()) {
setError("Enter a URL to fetch");
return;
}
setUiState("loading-article");
setError(null);
try {
const data = await apiClient.fetchReadingContent({ url: urlInput.trim() });
if (!data.article) throw new Error("Failed to fetch URL");
const fetched = data.article;
setArticle({
slug: `url-${Date.now()}`,
title: fetched.title,
difficulty: "intermediate" as ArticleDifficulty,
domain: fetched.domain,
estimatedMinutes: fetched.estimatedMinutes,
wordCount: fetched.wordCount,
body: fetched.body,
sourceUrl: fetched.sourceUrl,
isCustom: true,
});
setUiState("reading");
} catch (err) {
setError(
err instanceof ApiClientError
? ((err.body as { error?: string })?.error ?? "Failed to fetch URL")
: err instanceof Error
? err.message
: "Failed to fetch URL",
);
setUiState("idle");
}
}, [urlInput]);
const handleStartPaste = useCallback(() => {
if (!pasteText.trim() || pasteText.trim().length < 200) {
setError("Text must be at least 200 characters for a meaningful reading exercise");
return;
}
setError(null);
const words = pasteText.trim().split(/\s+/).length;
setArticle({
slug: `paste-${Date.now()}`,
title: pasteTitle.trim() || "Custom Reading",
difficulty: "intermediate" as ArticleDifficulty,
domain: "Custom",
estimatedMinutes: Math.max(1, Math.round(words / 200)),
wordCount: words,
body: pasteText.trim(),
isCustom: true,
});
setUiState("reading");
}, [pasteText, pasteTitle]);
const handleStart = useCallback(() => {
if (contentSource === "url") return handleStartUrl();
if (contentSource === "paste") return handleStartPaste();
return handleStartLibrary();
}, [contentSource, handleStartUrl, handleStartPaste, handleStartLibrary]);
const handleFinishedReading = useCallback(
async (secs: number) => {
if (!article) return;
setDurationSecs(secs);
setUiState("generating-questions");
setError(null);
try {
const requestBody = article.isCustom
? { content: { title: article.title, body: article.body } }
: { slug: article.slug };
const data = await apiClient.generateReadingQuestions(requestBody);
if (!data.questions) throw new Error("Failed to generate questions");
setQuestions(data.questions as ComprehensionQuestion[]);
setAnswers({});
setUiState("quiz");
} catch (err) {
setError(
err instanceof ApiClientError
? ((err.body as { error?: string })?.error ?? "Failed to generate questions")
: err instanceof Error
? err.message
: "Failed to generate questions",
);
setUiState("reading");
}
},
[article],
);
const handleSubmitQuiz = useCallback(async () => {
if (!article || questions.length === 0) return;
setUiState("scoring");
setError(null);
try {
const answerList = questions.map((q) => ({
questionId: q.id,
answer: answers[q.id] ?? "",
}));
const scoreBody = article.isCustom
? {
content: {
title: article.title,
body: article.body,
sourceUrl: article.sourceUrl,
},
answers: answerList,
questions,
durationSecs,
}
: {
slug: article.slug,
answers: answerList,
questions,
durationSecs,
};
const data = await apiClient.scoreReading(scoreBody as unknown as Parameters<typeof apiClient.scoreReading>[0]);
const scored = data as unknown as ScoreResult;
setResult(scored);
setShowLevelUp(scored.categoryXp?.levelUp ?? false);
setUiState("results");
} catch (err) {
setError(
err instanceof ApiClientError
? ((err.body as { error?: string })?.error ?? `Request failed (${err.status})`)
: err instanceof Error
? err.message
: "Something went wrong",
);
setUiState("quiz");
}
}, [article, questions, answers, durationSecs]);
const handleReset = useCallback(() => {
setArticle(null);
setQuestions([]);
setAnswers({});
setResult(null);
setError(null);
setUrlInput("");
setPasteTitle("");
setPasteText("");
setUiState("idle");
}, []);
const allAnswered = questions.every(
(q) => (answers[q.id] ?? "").trim().length > 10,
);
const questionTypeLabel: Record<ComprehensionQuestion["type"], string> = {
recall: "Recall",
inference: "Inference",
critical: "Critical Thinking",
};
const questionTypeColor: Record<ComprehensionQuestion["type"], string> = {
recall: "#06b6d4",
inference: "#8b5cf6",
critical: "#f43f5e",
};
return (
<div className="max-w-4xl mx-auto">
{/* ========== IDLE ========== */}
{uiState === "idle" && (
<>
<h1
className="text-3xl font-bold mb-2"
style={{ fontFamily: "var(--font-mono)", color: GREEN }}
>
Deep Reading
</h1>
<p className="mb-2" style={{ color: "var(--text-secondary)" }}>
Read in a distraction-free environment. No copy-paste.
When you finish, Claude generates comprehension questions to test
your retention and understanding.
</p>
{difficultyHint && (
<p className="text-xs mb-4" style={{ color: "var(--text-muted)" }}>
📊 Recommended: {difficultyHint.charAt(0).toUpperCase() + difficultyHint.slice(1)}
</p>
)}
{/* How it works */}
<div className="glass rounded-2xl p-6 mb-6">
<h3 className="font-bold mb-3">How it works</h3>
<ol className="space-y-2">
{[
"Pick a source: curated library, any URL, or paste your own text",
"The article is copy-paste protected — read it, don't skim",
"Finish reading (minimum 60 seconds) and click Done",
"Answer comprehension questions from memory",
"Claude scores your answers and awards XP",
].map((step, i) => (
<li key={i} className="flex gap-3 text-sm" style={{ color: "var(--text-secondary)" }}>
<span
className="w-5 h-5 rounded-full flex-shrink-0 flex items-center justify-center text-xs font-bold"
style={{ background: GREEN, color: "#000" }}
>
{i + 1}
</span>
{step}
</li>
))}
</ol>
</div>
{/* Content source tabs */}
<div className="flex gap-1 mb-6 p-1 rounded-xl" style={{ background: "rgba(255,255,255,0.04)" }}>
{SOURCE_TABS.map((tab) => (
<button
key={tab.id}
onClick={() => { setContentSource(tab.id); setError(null); }}
className="flex-1 px-3 py-2 rounded-lg text-sm font-medium transition-all"
style={{
background: contentSource === tab.id ? "rgba(255,255,255,0.1)" : "transparent",
color: contentSource === tab.id ? GREEN : "var(--text-secondary)",
}}
>
{tab.icon} {tab.label}
</button>
))}
</div>
{/* ---- Library source ---- */}
{contentSource === "library" && (
<>
<div className="flex flex-wrap gap-2 mb-6">
{DIFFICULTIES.map((d) => (
<button
key={d}
onClick={() => setDifficulty(d)}
className="px-3 py-1.5 rounded-lg text-sm font-medium transition-colors"
style={{
background: difficulty === d ? GREEN : "rgba(255,255,255,0.06)",
color: difficulty === d ? "#000" : "var(--text-secondary)",
}}
>
{DIFFICULTY_LABELS[d]}
</button>
))}
</div>
</>
)}
{/* ---- URL source ---- */}
{contentSource === "url" && (
<div className="glass rounded-2xl p-6 mb-6">
<label className="block text-sm font-medium mb-2" style={{ color: "var(--text-secondary)" }}>
Article URL
</label>
<input
type="url"
value={urlInput}
onChange={(e) => setUrlInput(e.target.value)}
placeholder="https://example.com/article..."
className="w-full rounded-xl px-4 py-3 text-sm focus:outline-none focus:ring-2"
style={{
background: "rgba(0,0,0,0.4)",
color: "var(--text-primary)",
borderColor: "rgba(255,255,255,0.1)",
borderWidth: 1,
fontFamily: "var(--font-mono)",
}}
onKeyDown={(e) => e.key === "Enter" && handleStart()}
/>
<p className="text-xs mt-2" style={{ color: "var(--text-muted)" }}>
Works best with blogs, articles, and essays. Pages behind paywalls or heavy JavaScript may not extract well.
</p>
</div>
)}
{/* ---- Paste text source ---- */}
{contentSource === "paste" && (
<div className="glass rounded-2xl p-6 mb-6">
<label className="block text-sm font-medium mb-2" style={{ color: "var(--text-secondary)" }}>
Title (optional)
</label>
<input
type="text"
value={pasteTitle}
onChange={(e) => setPasteTitle(e.target.value)}
placeholder="Article title..."
className="w-full rounded-xl px-4 py-3 text-sm focus:outline-none focus:ring-2 mb-4"
style={{
background: "rgba(0,0,0,0.4)",
color: "var(--text-primary)",
borderColor: "rgba(255,255,255,0.1)",
borderWidth: 1,
}}
/>
<label className="block text-sm font-medium mb-2" style={{ color: "var(--text-secondary)" }}>
Article Text
</label>
<textarea
value={pasteText}
onChange={(e) => setPasteText(e.target.value)}
placeholder="Paste the article text here (minimum 200 characters)..."
className="w-full rounded-xl px-4 py-3 text-sm focus:outline-none focus:ring-2 resize-y"
style={{
minHeight: 180,
background: "rgba(0,0,0,0.4)",
color: "var(--text-primary)",
borderColor: "rgba(255,255,255,0.1)",
borderWidth: 1,
fontFamily: "var(--font-mono)",
fontSize: "0.8rem",
}}
/>
<div className="flex justify-between mt-2">
<p className="text-xs" style={{ color: "var(--text-muted)" }}>
Paste any article, essay, or text you want to practice with.
</p>
<p
className="text-xs"
style={{
color: pasteText.length >= 200 ? GREEN : "var(--text-muted)",
fontFamily: "var(--font-mono)",
}}
>
{pasteText.length} chars
</p>
</div>
</div>
)}
{error && <p className="text-red-400 text-sm mb-4">{error}</p>}
<button
onClick={handleStart}
className="px-6 py-3 rounded-xl font-bold text-lg transition-transform hover:scale-105"
style={{ background: GREEN, color: "#000" }}
>
{contentSource === "url" ? "Fetch & Read" : contentSource === "paste" ? "Start Reading" : "Start Reading"}
</button>
</>
)}
{/* ========== LOADING ARTICLE ========== */}
{uiState === "loading-article" && (
<div className="flex flex-col items-center justify-center py-20">
<div
className="w-10 h-10 border-4 rounded-full animate-spin mb-4"
style={{
borderColor: `${GREEN} transparent transparent transparent`,
}}
/>
<p style={{ color: "var(--text-secondary)" }}>Loading article...</p>
</div>
)}
{/* ========== READING ========== */}
{uiState === "reading" && article && (
<Reader article={article} onFinished={handleFinishedReading} />
)}
{/* ========== GENERATING QUESTIONS ========== */}
{uiState === "generating-questions" && (
<div className="flex flex-col items-center justify-center py-20">
<div
className="w-10 h-10 border-4 rounded-full animate-spin mb-4"
style={{
borderColor: `${GREEN} transparent transparent transparent`,
}}
/>
<p style={{ color: "var(--text-secondary)" }}>
Generating comprehension questions...
</p>
</div>
)}
{/* ========== QUIZ ========== */}
{uiState === "quiz" && article && (
<div className="max-w-3xl mx-auto">
<h1
className="text-3xl font-bold mb-2"
style={{ fontFamily: "var(--font-mono)", color: GREEN }}
>
Comprehension Quiz
</h1>
<p className="mb-6 text-sm" style={{ color: "var(--text-secondary)" }}>
Answer from memory — the article is no longer visible. Brief,
focused answers score better than vague ones.
</p>
<div
className="glass rounded-xl px-4 py-3 mb-6 text-sm"
style={{ color: "var(--text-secondary)" }}
>
Article: <span style={{ color: GREEN }}>{article.title}</span>
</div>
<div className="space-y-6">
{questions.map((q, i) => (
<div key={q.id} className="glass rounded-2xl p-6">
<div className="flex items-center gap-2 mb-3">
<span
className="text-xs px-2 py-0.5 rounded-full font-medium"
style={{
background: `${questionTypeColor[q.type]}22`,
color: questionTypeColor[q.type],
}}
>
{questionTypeLabel[q.type]}
</span>
<span
className="text-xs"
style={{ color: "var(--text-secondary)", fontFamily: "var(--font-mono)" }}
>
Q{i + 1}
</span>
</div>
<p className="font-medium mb-4">{q.question}</p>
<textarea
value={answers[q.id] ?? ""}
onChange={(e) =>
setAnswers((prev) => ({ ...prev, [q.id]: e.target.value }))
}
placeholder="Your answer..."
className="w-full rounded-xl p-4 resize-y focus:outline-none focus:ring-2"
style={{
minHeight: 100,
fontFamily: "var(--font-mono)",
fontSize: "0.875rem",
background: "rgba(0,0,0,0.4)",
color: "var(--text-primary)",
borderColor: "rgba(255,255,255,0.1)",
borderWidth: 1,
}}
/>
</div>
))}
</div>
{error && (
<p className="text-red-400 text-sm mt-4">{error}</p>
)}
<div className="flex gap-3 mt-8">
<button
onClick={handleSubmitQuiz}
disabled={!allAnswered}
className="px-6 py-3 rounded-xl font-bold transition-transform hover:scale-105 disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:scale-100"
style={{ background: GREEN, color: "#000" }}
>
Submit Answers
</button>
<button
onClick={handleReset}
className="px-4 py-3 rounded-xl font-medium transition-colors"
style={{
background: "rgba(255,255,255,0.06)",
color: "var(--text-secondary)",
}}
>
Start Over
</button>
</div>
</div>
)}
{/* ========== SCORING ========== */}
{uiState === "scoring" && (
<div className="flex flex-col items-center justify-center py-20">
<div
className="w-10 h-10 border-4 rounded-full animate-spin mb-4"
style={{
borderColor: `${GREEN} transparent transparent transparent`,
}}
/>
<p style={{ color: "var(--text-secondary)" }}>
Claude is scoring your answers...
</p>
</div>
)}
{/* ========== RESULTS ========== */}
{uiState === "results" && result && article && (
<div className="max-w-3xl mx-auto">
<h1
className="text-3xl font-bold mb-2"
style={{ fontFamily: "var(--font-mono)", color: GREEN }}
>
Results
</h1>
<p className="mb-6 text-sm" style={{ color: "var(--text-secondary)" }}>
{article.title}
</p>
{/* Per-question scores */}
<div className="glass rounded-2xl p-6 mb-6">
<h3 className="text-lg font-bold mb-4">Question Scores</h3>
{result.scores.map((s, i) => (
<div key={s.questionId} className="mb-5 last:mb-0">
<ScoreBar
label={`Q${i + 1}: ${questions[i]?.question ?? ""}`}
value={s.score}
delay={i * 0.1}
/>
<p
className="text-xs mt-1 ml-0.5"
style={{ color: "var(--text-secondary)" }}
>
{s.feedback}
</p>
</div>
))}
</div>
{/* Overall feedback */}
<div className="glass rounded-2xl p-6 mb-6">
<h3 className="text-lg font-bold mb-3">Overall Feedback</h3>
<p
className="text-sm leading-relaxed"
style={{ color: "var(--text-secondary)" }}
>
{result.overallFeedback}
</p>
</div>
{/* XP Results panel */}
<XpResults
category="reading"
baseXp={result.xp.baseXp}
qualityBonus={result.xp.qualityBonus}
isCriticalHit={result.xp.isCriticalHit}
totalXp={result.xp.totalXp}
score={result.avgScore / 10}
categoryCurrentXp={result.categoryXp.currentXp}
categoryXpToNext={result.categoryXp.xpToNext}
categoryLevel={result.categoryXp.level}
levelUp={result.categoryXp.levelUp}
multiplierBonus={result.xp.multiplierBonus}
multiplierPercent={result.xp.multiplierPercent}
onNext={handleReset}
nextLabel="Read Another"
/>
{result.unlocks && result.unlocks.length > 0 && (
<SkillUnlockToast
unlocks={result.unlocks}
streakFreezesGranted={result.streakFreezesGranted}
category="reading"
/>
)}
<LevelUpOverlay
show={showLevelUp}
level={result.categoryXp.level}
title={result.newTitle}
category="reading"
onDismiss={() => setShowLevelUp(false)}
/>
</div>
)}
</div>
);
}