"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 = { 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 (
{label} {value}/10
); } export default function ReadingPage() { const [uiState, setUiState] = useState("idle"); const [difficulty, setDifficulty] = useState("any"); const [contentSource, setContentSource] = useState("library"); const [urlInput, setUrlInput] = useState(""); const [pasteTitle, setPasteTitle] = useState(""); const [pasteText, setPasteText] = useState(""); const [article, setArticle] = useState(null); const [durationSecs, setDurationSecs] = useState(0); const [questions, setQuestions] = useState([]); const [answers, setAnswers] = useState>({}); const [result, setResult] = useState(null); const [error, setError] = useState(null); const [showLevelUp, setShowLevelUp] = useState(false); const [difficultyHint, setDifficultyHint] = useState(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[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 = { recall: "Recall", inference: "Inference", critical: "Critical Thinking", }; const questionTypeColor: Record = { recall: "#06b6d4", inference: "#8b5cf6", critical: "#f43f5e", }; return (
{/* ========== IDLE ========== */} {uiState === "idle" && ( <>

Deep Reading

Read in a distraction-free environment. No copy-paste. When you finish, Claude generates comprehension questions to test your retention and understanding.

{difficultyHint && (

📊 Recommended: {difficultyHint.charAt(0).toUpperCase() + difficultyHint.slice(1)}

)} {/* How it works */}

How it works

    {[ "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) => (
  1. {i + 1} {step}
  2. ))}
{/* Content source tabs */}
{SOURCE_TABS.map((tab) => ( ))}
{/* ---- Library source ---- */} {contentSource === "library" && ( <>
{DIFFICULTIES.map((d) => ( ))}
)} {/* ---- URL source ---- */} {contentSource === "url" && (
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()} />

Works best with blogs, articles, and essays. Pages behind paywalls or heavy JavaScript may not extract well.

)} {/* ---- Paste text source ---- */} {contentSource === "paste" && (
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, }} />