algospaced-dsa / algospaced-ui /src /components /review /ProblemSpecPanel.tsx
iamfebin's picture
feat: FSRS card manager, fantasy cartography art polish, and map progression effects
f0175ec
Raw History Blame Contribute Delete
48.6 kB
import React, { useState, useEffect } from 'react'; import { FileText, Code, TrendingUp, BookOpen, Zap, Copy, AlertTriangle, RefreshCw, Sparkles, BrainCircuit, Layers, Eye, EyeOff, Lock, Plus, Edit3, Trash2, CheckCircle2, X } from 'lucide-react'; import type { ProblemItem, ReviewItem, ParsedExample, ProblemSolution } from '../../types/reviewTypes'; import { renderInlineMarkdown, normalizeProblemSolutions } from '../../utils/problemContentParser'; import { MarkdownRenderer } from '../MarkdownRenderer'; import { updateProblemSolutions } from '../../services/reviewService'; const COMMON_PATTERNS = [ 'Arrays & Hashing', 'Two Pointers', 'Sliding Window', 'Stack', 'Binary Search', 'Linked List', 'Trees', 'Tries', 'Heap / Priority Queue', 'Backtracking', 'Graphs', 'Advanced Graphs', '1-D Dynamic Programming', '2-D Dynamic Programming', 'Greedy', 'Intervals', 'Math & Geometry', 'Bit Manipulation' ]; interface ProblemSpecPanelProps { leftTab: 'spec' | 'ref' | 'fsrs'; onSelectLeftTab: (tab: 'spec' | 'ref' | 'fsrs') => void; mobileView: 'spec' | 'code' | 'ref'; isNarrow?: boolean; problem: ProblemItem; parsed: { description: string; examples: ParsedExample[]; constraints: string[]; }; userSolution?: string; officialSolution?: string; effectiveReferenceCode: string; copiedSnippet: string | null; onCopyText: (text: string, id: string) => void; saveRefError?: string | null; aiSolutionLoading: boolean; aiSolutionError: string | null; onFetchAiSolution: () => void; explainLoading: boolean; explainError: string | null; explanationText: string | null; onExplainCode: (codeToExplain?: string, pattern?: string, timeC?: string, spaceC?: string) => void; activeReview: ReviewItem; onEditProblem?: () => void; onUpdateSolutions?: (solutions: ProblemSolution[]) => void; } function generateSolutionId(): string { if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') { return `sol-${crypto.randomUUID()}`; } return `sol-${Date.now()}`; } export const ProblemSpecPanel: React.FC<ProblemSpecPanelProps> = ({ leftTab, onSelectLeftTab, mobileView, isNarrow = false, problem, parsed, userSolution, officialSolution, effectiveReferenceCode, copiedSnippet, onCopyText, saveRefError, aiSolutionLoading, aiSolutionError, onFetchAiSolution, explainLoading, explainError, explanationText, onExplainCode, activeReview, onUpdateSolutions }) => { // Active Recall Spoiler state const [showComplexitySpoiler, setShowComplexitySpoiler] = useState(false); const [prevProblemKey, setPrevProblemKey] = useState<string>(() => problem.id || problem.name); // Multi-solution state const [selectedSolutionIndex, setSelectedSolutionIndex] = useState(0); const [isAddingSolution, setIsAddingSolution] = useState(false); const [editingSolutionId, setEditingSolutionId] = useState<string | null>(null); // Form state for adding/editing a solution const [solutionForm, setSolutionForm] = useState<{ name: string; pattern: string; time_complexity: string; space_complexity: string; code: string; explanation: string; is_optimal: boolean; }>({ name: '', pattern: 'Arrays & Hashing', time_complexity: 'O(N)', space_complexity: 'O(1)', code: '', explanation: '', is_optimal: false }); const [savingSolution, setSavingSolution] = useState(false); const [solutionFeedback, setSolutionFeedback] = useState<{ type: 'success' | 'error'; message: string } | null>(null); // Reset local state when active problem switches const currentProblemKey = problem.id || problem.name; if (prevProblemKey !== currentProblemKey) { setPrevProblemKey(currentProblemKey); setShowComplexitySpoiler(false); setSelectedSolutionIndex(0); setIsAddingSolution(false); setEditingSolutionId(null); setSolutionFeedback(null); } // Derive solutions list const solutions: ProblemSolution[] = normalizeProblemSolutions(problem, officialSolution, userSolution); const safeIndex = selectedSolutionIndex < solutions.length ? selectedSolutionIndex : 0; const activeSolution = solutions[safeIndex]; // Auto-dismiss feedback message after 3.5 seconds useEffect(() => { if (solutionFeedback) { const timer = setTimeout(() => setSolutionFeedback(null), 3500); return () => clearTimeout(timer); } }, [solutionFeedback]); // Handle saving (add or update) solution const handleSaveSolution = async () => { if (!solutionForm.name.trim()) { setSolutionFeedback({ type: 'error', message: 'Solution name cannot be empty.' }); return; } if (!solutionForm.code.trim()) { setSolutionFeedback({ type: 'error', message: 'Solution code cannot be empty.' }); return; } setSavingSolution(true); setSolutionFeedback(null); try { let updatedSolutions: ProblemSolution[]; if (editingSolutionId) { // Edit existing updatedSolutions = solutions.map((s) => { if (s.id === editingSolutionId) { return { ...s, name: solutionForm.name.trim(), pattern: solutionForm.pattern.trim() || 'General Algorithm', time_complexity: solutionForm.time_complexity.trim() || 'O(N)', space_complexity: solutionForm.space_complexity.trim() || 'O(1)', code: solutionForm.code, explanation: solutionForm.explanation.trim(), is_optimal: solutionForm.is_optimal }; } // If this one is marked optimal, unset others if (solutionForm.is_optimal && s.id !== editingSolutionId) { return { ...s, is_optimal: false }; } return s; }); } else { // Add new const newSolution: ProblemSolution = { id: generateSolutionId(), name: solutionForm.name.trim(), pattern: solutionForm.pattern.trim() || 'General Algorithm', time_complexity: solutionForm.time_complexity.trim() || 'O(N)', space_complexity: solutionForm.space_complexity.trim() || 'O(1)', code: solutionForm.code, explanation: solutionForm.explanation.trim(), is_optimal: solutionForm.is_optimal || solutions.length === 0 }; if (newSolution.is_optimal) { updatedSolutions = [ ...solutions.map((s): ProblemSolution => ({ ...s, is_optimal: false })), newSolution ]; } else { updatedSolutions = [...solutions, newSolution]; } } const optimalSol = updatedSolutions.find((s) => s.is_optimal) || updatedSolutions[0]; if (problem.id) { await updateProblemSolutions( problem.id, updatedSolutions, optimalSol?.time_complexity, optimalSol?.space_complexity, problem ); } onUpdateSolutions?.(updatedSolutions); setSolutionFeedback({ type: 'success', message: editingSolutionId ? 'Solution updated successfully!' : 'New solution added to problem dossier!' }); setIsAddingSolution(false); setEditingSolutionId(null); setSelectedSolutionIndex( editingSolutionId ? safeIndex : updatedSolutions.length - 1 ); } catch (err) { const msg = err instanceof Error ? err.message : 'Failed to save solution.'; setSolutionFeedback({ type: 'error', message: msg }); } finally { setSavingSolution(false); } }; // Handle deleting a solution const handleDeleteSolution = async (solutionIdToDelete: string) => { if (solutions.length <= 1) { setSolutionFeedback({ type: 'error', message: 'Problem must have at least one solution.' }); return; } if (!window.confirm('Are you sure you want to remove this solution?')) return; setSavingSolution(true); try { const updatedSolutions = solutions.filter((s) => s.id !== solutionIdToDelete); // Ensure at least one is optimal if (!updatedSolutions.some((s) => s.is_optimal) && updatedSolutions.length > 0) { updatedSolutions[0].is_optimal = true; } const optimalSol = updatedSolutions.find((s) => s.is_optimal) || updatedSolutions[0]; if (problem.id) { await updateProblemSolutions( problem.id, updatedSolutions, optimalSol?.time_complexity, optimalSol?.space_complexity, problem ); } onUpdateSolutions?.(updatedSolutions); setSelectedSolutionIndex(0); setSolutionFeedback({ type: 'success', message: 'Solution removed successfully.' }); } catch (err) { const msg = err instanceof Error ? err.message : 'Failed to delete solution.'; setSolutionFeedback({ type: 'error', message: msg }); } finally { setSavingSolution(false); } }; const getTabClassName = (isActive: boolean) => `cursor-pointer font-arcade text-[7.5px] min-[400px]:text-[8px] sm:text-[8.5px] transition-all flex items-center justify-center gap-1 sm:gap-1.5 focus:outline-none focus-visible:ring-2 focus-visible:ring-ink-black select-none whitespace-nowrap shrink-0 ${isActive ? 'h-10 px-2 sm:px-2.5 bg-paper-white text-ink-black font-extrabold border-t-2 border-x-2 border-b-0 border-ink-black relative z-10 -mb-[2px] pb-[10px] shadow-[0_-2px_0_0_rgba(30,41,59,0.06)] after:content-[\'\'] after:absolute after:-bottom-[2px] after:left-0 after:right-0 after:h-[2.5px] after:bg-paper-white after:z-10' : 'h-9 px-2 sm:px-2.5 bg-[#e8e4da] text-slate-700 hover:bg-[#efece3] hover:text-ink-black font-bold border-2 border-ink-black relative z-0 mb-0' }`; return ( <div className={`w-full ${isNarrow ? 'flex flex-1' : 'lg:w-[49%] flex' } flex-col bg-paper-white border-b-[3px] lg:border-b-0 ${isNarrow ? '' : 'lg:border-r-[3px]' } border-ink-black overflow-hidden ${isNarrow && mobileView !== 'spec' && mobileView !== 'ref' ? 'hidden' : 'flex' }`} > {/* Sub-tab strip */} <div className="shrink-0 bg-[#f4f1ea] border-b-2 border-ink-black px-1.5 sm:px-2.5 pt-2 flex items-end gap-1 relative z-10 overflow-x-auto no-scrollbar"> <button onClick={() => onSelectLeftTab('spec')} className={getTabClassName(leftTab === 'spec')} > <FileText className="w-3 h-3 text-purple-700 shrink-0" /> <span>{isNarrow ? 'SPEC' : 'SPECIFICATIONS'}</span> </button> <button onClick={() => onSelectLeftTab('ref')} className={getTabClassName(leftTab === 'ref')} > <Code className="w-3 h-3 text-blue-700 shrink-0" /> <span>{isNarrow ? `SOL (${solutions.length})` : `SOLUTIONS (${solutions.length})`}</span> </button> <button onClick={() => onSelectLeftTab('fsrs')} className={getTabClassName(leftTab === 'fsrs')} > <TrendingUp className="w-3 h-3 text-emerald-700 shrink-0" /> <span className="whitespace-nowrap">{isNarrow ? 'FSRS' : 'FSRS STATS'}</span> </button> </div> {/* Dossier Scroll Area */} <div className="flex-1 overflow-y-auto no-scrollbar p-4 sm:p-5 space-y-4"> {/* SUBTAB 1: PROBLEM SPEC (Active Recall Mode - No Spoilers!) */} {leftTab === 'spec' && ( <div className="space-y-4"> {/* Main Problem Specification & Description Container */} <div className="p-4 bg-white border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] space-y-3.5"> {/* Header: Title */} <div> <h2 className="text-base sm:text-lg font-extrabold text-ink-black font-headline-md leading-tight m-0 select-text"> {problem.name || 'Algorithm Problem'} </h2> </div> {/* Problem Description Body */} {parsed.description && ( <div className="pt-3.5 border-t border-slate-200"> <div className="text-[9px] font-arcade text-trash-gray uppercase font-bold mb-2 flex items-center gap-1"> <BookOpen className="w-3 h-3 text-primary" /> PROBLEM DESCRIPTION </div> <div className="font-sans text-xs sm:text-[13px] text-slate-800 leading-relaxed space-y-2 font-medium"> {parsed.description.split('\n').map((line: string, idx: number) => line.trim() ? ( <p key={idx} className="m-0 leading-relaxed whitespace-pre-wrap select-text"> {renderInlineMarkdown(line)} </p> ) : ( <div key={idx} className="h-1.5" /> ) )} </div> </div> )} {/* Structured Examples */} {parsed.examples.length > 0 && ( <div className="pt-3.5 border-t border-slate-200 space-y-2.5"> <div className="text-[9px] font-arcade text-trash-gray uppercase font-bold flex items-center gap-1.5"> <Zap className="w-3 h-3 text-amber-500" /> EXAMPLES ({parsed.examples.length}) </div> <div className="space-y-2.5"> {parsed.examples.map((ex, i) => ( <div key={i} className="p-3 bg-slate-50 border border-slate-200 space-y-2 text-xs" > <div className="flex items-center justify-between"> <span className="font-arcade text-[9px] font-bold text-primary"> EXAMPLE {i + 1} </span> {ex.input && ( <button onClick={() => onCopyText(ex.input, `ex-${i}`)} className="px-2 py-0.5 bg-white hover:bg-slate-100 border border-ink-black text-[9px] font-arcade text-ink-black flex items-center gap-1 cursor-pointer" title="Copy input data" > <Copy className="w-2.5 h-2.5" /> {copiedSnippet === `ex-${i}` ? 'COPIED!' : 'COPY'} </button> )} </div> {ex.input && ( <div className="space-y-1"> <span className="text-[9px] font-arcade text-trash-gray font-bold uppercase block"> Input: </span> <div className="bg-[#1E293B] text-[#4ADE80] font-code-mono p-2 border border-ink-black text-[11px] break-all select-text"> {ex.input} </div> </div> )} {ex.output && ( <div className="space-y-1"> <span className="text-[9px] font-arcade text-trash-gray font-bold uppercase block"> Output: </span> <div className="bg-[#1E293B] text-[#4ADE80] font-code-mono p-2 border border-ink-black text-[11px] break-all select-text"> {ex.output} </div> </div> )} {ex.explanation && ( <div className="text-[11px] font-sans text-slate-600 bg-white p-2 border border-slate-200"> <span className="font-bold text-slate-700">Explanation: </span> {renderInlineMarkdown(ex.explanation)} </div> )} </div> ))} </div> </div> )} {/* Constraints */} {parsed.constraints.length > 0 && ( <div className="pt-3.5 border-t border-slate-200"> <div className="text-[9px] font-arcade text-trash-gray uppercase font-bold mb-2"> CONSTRAINTS </div> <ul className="space-y-1.5 list-none m-0 p-0"> {parsed.constraints.map((c, i) => ( <li key={i} className="flex items-start gap-2 text-xs"> <span className="text-primary font-bold select-none">•</span> <code className="bg-slate-100 text-ink-black font-code-mono px-2 py-0.5 border border-slate-300 text-[11px] select-text"> {c} </code> </li> ))} </ul> </div> )} </div> {/* Optimal Complexity Target Spoiler Shield (Positioned below constraints for active recall) */} {!showComplexitySpoiler ? ( <div className="p-3 bg-amber-50/70 border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] flex items-center justify-between gap-2"> <div className="flex items-center gap-2"> <Lock className="w-4 h-4 text-amber-700 shrink-0" /> <div> <span className="font-arcade text-[9px] font-bold text-ink-black tracking-wide uppercase block"> OPTIMAL COMPLEXITY TARGET </span> <span className="text-[10px] font-sans text-slate-600 font-semibold"> Hidden to test active recall before coding </span> </div> </div> <button type="button" onClick={() => setShowComplexitySpoiler(true)} className="px-2.5 py-1 bg-white hover:bg-amber-100 border-2 border-ink-black font-arcade text-[8.5px] font-bold text-ink-black shadow-[1.5px_1.5px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer flex items-center gap-1.5 shrink-0" title="Click to reveal target time and space complexity" > <Eye className="w-3 h-3 text-amber-700" /> <span>REVEAL TARGET</span> </button> </div> ) : ( <div className="p-3 bg-amber-50 border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] flex flex-wrap items-center justify-between gap-2"> <div className="flex items-center gap-2 flex-wrap"> <Zap className="w-4 h-4 text-amber-600 shrink-0" /> <span className="font-arcade text-[9px] font-bold text-ink-black tracking-wide uppercase"> OPTIMAL TARGET: </span> <code className="bg-[#1E293B] text-[#4ADE80] font-code-mono px-2 py-0.5 text-[11px] border border-ink-black font-bold"> T: {problem.optimal_time || 'O(N)'} </code> <code className="bg-[#1E293B] text-[#4ADE80] font-code-mono px-2 py-0.5 text-[11px] border border-ink-black font-bold"> S: {problem.optimal_space || 'O(1)'} </code> </div> <button type="button" onClick={() => setShowComplexitySpoiler(false)} className="px-2 py-0.5 bg-white hover:bg-slate-100 border border-ink-black font-arcade text-[8px] text-trash-gray hover:text-ink-black cursor-pointer flex items-center gap-1" title="Conceal target complexity" > <EyeOff className="w-2.5 h-2.5" /> <span>HIDE</span> </button> </div> )} </div> )} {/* SUBTAB 2: SOLUTIONS (Methods Archive with Pattern, Complexity, & Code) */} {leftTab === 'ref' && ( <div className="space-y-4"> {/* Feedback alert */} {solutionFeedback && ( <div className={`p-2.5 border-2 border-ink-black text-xs font-bold flex items-center justify-between shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] ${solutionFeedback.type === 'success' ? 'bg-emerald-100 text-emerald-900 border-emerald-700' : 'bg-rose-100 text-rose-900 border-rose-700' }`} > <div className="flex items-center gap-2"> {solutionFeedback.type === 'success' ? ( <CheckCircle2 className="w-4 h-4 text-emerald-700 shrink-0" /> ) : ( <AlertTriangle className="w-4 h-4 text-rose-700 shrink-0" /> )} <span>{solutionFeedback.message}</span> </div> <button type="button" onClick={() => setSolutionFeedback(null)} className="text-slate-600 hover:text-ink-black cursor-pointer" > <X className="w-3.5 h-3.5" /> </button> </div> )} {/* SOLUTION SELECTOR TAB BAR */} <div className="flex items-center gap-1 p-1 bg-slate-200/90 border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] overflow-x-auto no-scrollbar"> {solutions.map((sol, idx) => { const isSelected = safeIndex === idx && !isAddingSolution && !editingSolutionId; return ( <button key={sol.id || idx} type="button" onClick={() => { setSelectedSolutionIndex(idx); setIsAddingSolution(false); setEditingSolutionId(null); }} className={`py-1 px-2 rounded-full font-arcade text-[8px] font-bold flex items-center justify-center gap-1 border-2 border-ink-black transition-all cursor-pointer whitespace-nowrap shrink-0 ${isSelected ? 'bg-sky-600 text-white shadow-[1px_1px_0px_0px_rgba(30,41,59,1)] -translate-y-0.5' : 'bg-white text-ink-black hover:bg-sky-50 shadow-none' }`} title={sol.name ? `${sol.name} (${sol.pattern || 'Algorithm'})` : `Solution ${idx + 1}`} > {sol.is_optimal ? <Sparkles className="w-3 h-3 text-amber-300" /> : <BookOpen className="w-3 h-3" />} <span>{`Sol ${idx + 1}`}</span> {sol.is_optimal && ( <span className="text-[6.5px] px-1 py-0.2 bg-amber-300 text-ink-black border border-ink-black font-extrabold rounded-full tracking-tight"> OPTIMAL </span> )} </button> ); })} <button type="button" onClick={() => { setIsAddingSolution(true); setEditingSolutionId(null); setSolutionForm({ name: `Method ${solutions.length + 1}`, pattern: 'Arrays & Hashing', time_complexity: 'O(N)', space_complexity: 'O(1)', code: '', explanation: '', is_optimal: false }); }} className={`h-6 w-6 rounded-full font-arcade text-[9px] font-bold flex items-center justify-center border-2 border-ink-black cursor-pointer shrink-0 active:translate-y-0.5 transition-all shadow-[1px_1px_0px_0px_rgba(30,41,59,1)] ${isAddingSolution ? 'bg-emerald-600 text-white' : 'bg-amber-300 text-ink-black hover:bg-amber-200' }`} title="Add another solution / method for this problem" aria-label="Add Solution" > <Plus className="w-3 h-3 stroke-[2.5]" /> </button> </div> {/* ADD OR EDIT SOLUTION FORM */} {(isAddingSolution || editingSolutionId) ? ( <div className="p-4 bg-white border-2 border-ink-black shadow-[3px_3px_0px_0px_rgba(30,41,59,1)] space-y-3.5"> <div className="flex items-center justify-between pb-2 border-b-2 border-dashed border-ink-black"> <div className="flex items-center gap-2"> <Edit3 className="w-4 h-4 text-purple-700" /> <span className="font-arcade text-[10px] font-bold text-ink-black uppercase"> {editingSolutionId ? 'EDIT SOLUTION' : 'ADD NEW SOLUTION / METHOD'} </span> </div> <button type="button" onClick={() => { setIsAddingSolution(false); setEditingSolutionId(null); }} className="text-xs font-arcade text-trash-gray hover:text-rose-600 cursor-pointer font-bold" > CANCEL </button> </div> <div className="grid grid-cols-1 sm:grid-cols-2 gap-3"> {/* Solution Name */} <div className="space-y-1"> <label className="font-arcade text-[8.5px] font-bold text-trash-gray uppercase block"> Solution / Method Name </label> <input type="text" value={solutionForm.name} onChange={(e) => setSolutionForm({ ...solutionForm, name: e.target.value })} placeholder="e.g. One-Pass Hash Map, Two Pointers" className="w-full p-2 border-2 border-ink-black text-xs font-bold bg-[#fdf8e1] focus:outline-none focus:bg-white" /> </div> {/* Pattern */} <div className="space-y-1"> <label className="font-arcade text-[8.5px] font-bold text-trash-gray uppercase block"> Pattern / Strategy </label> <select value={solutionForm.pattern} onChange={(e) => setSolutionForm({ ...solutionForm, pattern: e.target.value })} className="w-full p-2 border-2 border-ink-black text-xs font-bold bg-[#fdf8e1] focus:outline-none focus:bg-white" > {COMMON_PATTERNS.map((p) => ( <option key={p} value={p}>{p}</option> ))} </select> </div> {/* Time Complexity */} <div className="space-y-1"> <label className="font-arcade text-[8.5px] font-bold text-trash-gray uppercase block"> Time Complexity </label> <input type="text" value={solutionForm.time_complexity} onChange={(e) => setSolutionForm({ ...solutionForm, time_complexity: e.target.value })} placeholder="e.g. O(N), O(N log N), O(N^2)" className="w-full p-2 border-2 border-ink-black text-xs font-code-mono font-bold bg-[#fdf8e1] focus:outline-none focus:bg-white" /> </div> {/* Space Complexity */} <div className="space-y-1"> <label className="font-arcade text-[8.5px] font-bold text-trash-gray uppercase block"> Space Complexity </label> <input type="text" value={solutionForm.space_complexity} onChange={(e) => setSolutionForm({ ...solutionForm, space_complexity: e.target.value })} placeholder="e.g. O(1), O(N)" className="w-full p-2 border-2 border-ink-black text-xs font-code-mono font-bold bg-[#fdf8e1] focus:outline-none focus:bg-white" /> </div> </div> {/* Reference Code */} <div className="space-y-1"> <div className="flex items-center justify-between"> <label className="font-arcade text-[8.5px] font-bold text-trash-gray uppercase"> Python Reference Code </label> <button type="button" onClick={() => setSolutionForm({ ...solutionForm, code: effectiveReferenceCode })} className="text-[8.5px] font-arcade text-sky-700 hover:underline cursor-pointer" > Paste Current Code </button> </div> <textarea rows={8} value={solutionForm.code} onChange={(e) => setSolutionForm({ ...solutionForm, code: e.target.value })} placeholder="class Solution:&#10; def solve(self, nums):&#10; ..." className="w-full p-2.5 border-2 border-ink-black bg-[#1E293B] text-[#4ADE80] font-code-mono text-xs focus:outline-none no-scrollbar" /> </div> {/* Explanation */} <div className="space-y-1"> <label className="font-arcade text-[8.5px] font-bold text-trash-gray uppercase block"> Intuition / How to Solve (Optional) </label> <textarea rows={3} value={solutionForm.explanation} onChange={(e) => setSolutionForm({ ...solutionForm, explanation: e.target.value })} placeholder="Key insight, trade-offs, and state tracking notes..." className="w-full p-2 border-2 border-ink-black text-xs bg-[#fdf8e1] focus:outline-none focus:bg-white no-scrollbar" /> </div> {/* Is Optimal Checkbox */} <div className="flex items-center gap-2"> <input type="checkbox" id="is_optimal_solution" checked={solutionForm.is_optimal} onChange={(e) => setSolutionForm({ ...solutionForm, is_optimal: e.target.checked })} className="w-4 h-4 border-2 border-ink-black rounded cursor-pointer accent-emerald-600" /> <label htmlFor="is_optimal_solution" className="font-arcade text-[9px] font-bold text-ink-black cursor-pointer"> SET AS OPTIMAL / PRIMARY APPROACH FOR THIS PROBLEM </label> </div> {/* Action Buttons */} <div className="flex items-center justify-end gap-2 pt-2 border-t-2 border-dashed border-ink-black"> <button type="button" onClick={() => { setIsAddingSolution(false); setEditingSolutionId(null); }} className="px-3 py-1.5 bg-slate-100 hover:bg-slate-200 border-2 border-ink-black font-arcade text-[9px] font-bold text-ink-black cursor-pointer" > CANCEL </button> <button type="button" disabled={savingSolution} onClick={handleSaveSolution} className="px-4 py-1.5 bg-emerald-500 hover:bg-emerald-400 border-2 border-ink-black font-arcade text-[9px] font-bold text-white shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer disabled:opacity-50 flex items-center gap-1.5" > {savingSolution && <RefreshCw className="w-3 h-3 animate-spin" />} <span>{editingSolutionId ? 'UPDATE SOLUTION' : 'SAVE SOLUTION'}</span> </button> </div> </div> ) : activeSolution ? ( /* VIEWING ACTIVE SOLUTION */ <div className="space-y-3.5"> {/* Unified Solution Article Layout Container */} <div className="p-4 bg-white border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] space-y-3.5"> {/* Solution Metadata Header (Seamlessly precedes the implementation) */} <div className="flex flex-wrap items-center justify-between gap-2 pb-3 border-b border-slate-200"> <div className="flex items-center gap-2 flex-wrap min-w-0"> <h3 className="font-headline-md font-extrabold text-sm sm:text-base text-ink-black m-0 select-text break-words"> {activeSolution.name || `Solution ${safeIndex + 1}`} </h3> {activeSolution.is_optimal && ( <span className="px-2 py-0.5 bg-amber-300 border border-ink-black font-arcade text-[8px] font-bold text-ink-black shadow-[1px_1px_0px_0px_rgba(30,41,59,1)] shrink-0"> ★ OPTIMAL </span> )} </div> {/* Pattern & Complexities for this specific solution! */} <div className="flex items-center gap-2 flex-wrap sm:ml-auto"> <div className="flex items-center gap-1"> <span className="font-arcade text-[8px] text-trash-gray uppercase">Pattern:</span> <span className="px-2 py-0.5 bg-purple-50 border border-purple-300 font-arcade text-[8.5px] text-purple-800 font-bold"> {activeSolution.pattern || 'General Algorithm'} </span> </div> <div className="flex items-center gap-1.5"> <code className="bg-[#1E293B] text-[#4ADE80] font-code-mono px-1.5 py-0.5 text-[11px] border border-ink-black font-bold"> T: {activeSolution.time_complexity || 'O(N)'} </code> <code className="bg-[#1E293B] text-[#4ADE80] font-code-mono px-1.5 py-0.5 text-[11px] border border-ink-black font-bold"> S: {activeSolution.space_complexity || 'O(1)'} </code> </div> <div className="flex items-center gap-1 ml-auto"> <button type="button" onClick={() => { setEditingSolutionId(activeSolution.id); setIsAddingSolution(false); setSolutionForm({ name: activeSolution.name, pattern: activeSolution.pattern, time_complexity: activeSolution.time_complexity, space_complexity: activeSolution.space_complexity, code: activeSolution.code, explanation: activeSolution.explanation || '', is_optimal: Boolean(activeSolution.is_optimal) }); }} className="px-2 py-1 bg-white hover:bg-slate-100 border border-ink-black text-ink-black font-arcade text-[8px] font-bold flex items-center gap-1 cursor-pointer" title="Edit this solution" > <Edit3 className="w-3 h-3 text-slate-700" /> <span className="hidden sm:inline">EDIT</span> </button> {solutions.length > 1 && ( <button type="button" onClick={() => handleDeleteSolution(activeSolution.id)} className="px-1.5 py-1 bg-white hover:bg-rose-50 border border-ink-black text-rose-700 font-arcade text-[8px] font-bold flex items-center gap-1 cursor-pointer" title="Delete this solution" > <Trash2 className="w-3 h-3" /> </button> )} </div> </div> </div> {/* Reference Code Snippet */} {activeSolution.code ? ( <div className="border border-ink-black bg-[#0f172a] overflow-hidden"> <div className="bg-[#1e293b] px-2.5 sm:px-3 py-1.5 border-b border-ink-black flex items-center justify-between gap-1.5 flex-wrap min-w-0"> <span className="font-arcade text-[8px] text-slate-300 font-bold uppercase truncate min-w-0 flex-1"> {isNarrow ? 'PYTHON 3' : 'PYTHON 3 IMPLEMENTATION'} </span> <div className="flex items-center gap-1.5 shrink-0"> {/* Explain with Gemini Secondary Utility */} <button type="button" onClick={() => onExplainCode( activeSolution.code, activeSolution.pattern, activeSolution.time_complexity, activeSolution.space_complexity ) } disabled={explainLoading} className="px-2 py-0.5 bg-purple-50 hover:bg-purple-100 text-purple-800 border border-ink-black text-[9px] font-arcade font-bold flex items-center gap-1 cursor-pointer shrink-0 disabled:opacity-50 active:translate-y-0.5 transition-all" title="Explain this solution with AI" > {explainLoading ? ( <RefreshCw className="w-2.5 h-2.5 animate-spin text-purple-700" /> ) : ( <Sparkles className="w-2.5 h-2.5 text-purple-600" /> )} <span>Explain✦</span> </button> {/* Copy Code */} <button onClick={() => onCopyText(activeSolution.code, `sol-${activeSolution.id}`)} className="px-2 py-0.5 bg-white hover:bg-slate-100 text-ink-black border border-ink-black text-[9px] font-arcade font-bold flex items-center gap-1 cursor-pointer shrink-0 active:translate-y-0.5 transition-all" title="Copy solution code" > <Copy className="w-2.5 h-2.5" /> {copiedSnippet === `sol-${activeSolution.id}` ? 'COPIED!' : 'COPY'} </button> </div> </div> <div className="p-3 text-xs overflow-x-auto max-h-80 no-scrollbar"> <pre className="font-code-mono text-[#4ADE80] text-[11px] leading-relaxed select-text m-0"> <code>{activeSolution.code}</code> </pre> </div> </div> ) : ( <div className="p-4 bg-amber-50 border border-dashed border-amber-300 text-center space-y-3"> <p className="text-xs font-sans text-stone-700">No code implementation archived for this solution yet.</p> <button onClick={onFetchAiSolution} disabled={aiSolutionLoading} className="px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white font-arcade text-[9px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer inline-flex items-center gap-2 disabled:opacity-50" > {aiSolutionLoading ? ( <> <RefreshCw className="w-3.5 h-3.5 animate-spin" /> <span>Generating solution...</span> </> ) : ( <> <Sparkles className="w-3.5 h-3.5 text-amber-300" /> <span>Generate solution</span> </> )} </button> {aiSolutionError && ( <div className="text-xs text-rose-600 font-medium">{aiSolutionError}</div> )} </div> )} {/* Solution Explanation / Intuition */} {activeSolution.explanation && ( <div className="pt-3.5 border-t border-slate-200 space-y-1.5 select-text"> <span className="font-arcade text-[8.5px] text-trash-gray uppercase font-bold block"> SOLUTION INTUITION & STRATEGY: </span> <MarkdownRenderer content={activeSolution.explanation} /> </div> )} </div> {/* Gemini Code Breakdown Results */} {activeSolution.code && ( <div className="space-y-3"> {explainError && ( <div className="p-3 border-2 border-rose-500 bg-rose-50 text-rose-800 text-xs font-semibold"> {explainError} </div> )} {explanationText && ( <div className="p-4 bg-white border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] space-y-2 select-text"> <div className="flex items-center gap-1.5 pb-2 border-b-2 border-dashed border-ink-black"> <BrainCircuit className="w-4 h-4 text-purple-600" /> <span className="font-arcade text-[9px] font-bold text-ink-black uppercase"> Gemini Code Breakdown ({activeSolution.name}) </span> </div> <div className="max-h-96 overflow-y-auto no-scrollbar pt-1 select-text"> <MarkdownRenderer content={explanationText} /> </div> </div> )} </div> )} </div> ) : null} {saveRefError && ( <div className="p-2.5 border-2 border-rose-500 bg-rose-50 text-rose-800 text-xs font-bold flex items-center gap-2 shadow-[2px_2px_0px_0px_rgba(244,63,94,1)]"> <AlertTriangle className="w-4 h-4 text-rose-600 shrink-0" /> <div className="flex-1">{saveRefError}</div> </div> )} </div> )} {/* SUBTAB 3: FSRS TRACKER */} {leftTab === 'fsrs' && ( <div className="space-y-4"> <div className="p-4 bg-white border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] space-y-3"> <div className="text-[9px] font-arcade text-trash-gray uppercase font-bold flex items-center gap-1.5"> <Layers className="w-3 h-3 text-purple-600" /> SPACED REPETITION PROGRESSION </div> {/* FSRS State */} <div className="space-y-2"> {[ { state: 0, label: 'NEW', color: '#3b82f6' }, { state: 1, label: 'LEARNING', color: '#f59e0b' }, { state: 2, label: 'REVIEW', color: '#10b981' }, { state: 3, label: 'RELEARNING', color: '#ef4444' } ].map((stateItem) => { const isActive = (activeReview.fsrs_state ?? 0) === stateItem.state; return ( <div key={stateItem.state} className={`p-2.5 border-2 border-ink-black flex items-center justify-between transition-all ${isActive ? 'bg-amber-100 shadow-[3px_3px_0px_0px_rgba(30,41,59,1)] translate-x-1 font-bold' : 'bg-slate-50 opacity-70' }`} > <div className="flex items-center gap-2"> <span className="w-5 h-5 border border-ink-black flex items-center justify-center font-arcade text-[9px] text-white font-bold" style={{ backgroundColor: stateItem.color }} > {stateItem.state} </span> <span className="font-arcade text-[9px] text-ink-black"> {stateItem.label} </span> </div> <div className="flex items-center gap-2"> {isActive && ( <span className="px-1.5 py-0.5 bg-emerald-500 text-white font-arcade text-[7px] border border-ink-black font-bold"> CURRENT </span> )} </div> </div> ); })} </div> </div> {/* Historical Stats Card */} <div className="p-4 bg-white border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] space-y-3"> <div className="text-[9px] font-arcade text-trash-gray uppercase font-bold flex items-center gap-1.5"> <TrendingUp className="w-3 h-3 text-emerald-600" /> PERFORMANCE METRICS </div> <div className="grid grid-cols-2 gap-3"> <div className="p-2.5 bg-slate-50 border border-ink-black"> <span className="font-arcade text-[8px] text-trash-gray block uppercase"> Total Reviews </span> <span className="font-headline-md text-lg font-bold text-ink-black"> {activeReview.total_attempts || 0} </span> </div> <div className="p-2.5 bg-slate-50 border border-ink-black"> <span className="font-arcade text-[8px] text-trash-gray block uppercase"> Correct Recall </span> <span className="font-headline-md text-lg font-bold text-emerald-600"> {activeReview.times_correct || 0} </span> </div> </div> <div className="text-xs font-sans text-slate-600 pt-1"> Next Due Date:{' '} <span className="font-code-mono font-bold text-ink-black"> {activeReview.next_review ? new Date(activeReview.next_review).toLocaleDateString() : 'Today'} </span> </div> </div> </div> )} </div> </div> ); };
import React, { useState, useEffect } from 'react';
import {
FileText,
Code,
TrendingUp,
BookOpen,
Zap,
Copy,
AlertTriangle,
RefreshCw,
Sparkles,
BrainCircuit,
Layers,
Eye,
EyeOff,
Lock,
Plus,
Edit3,
Trash2,
CheckCircle2,
X
} from 'lucide-react';
import type { ProblemItem, ReviewItem, ParsedExample, ProblemSolution } from '../../types/reviewTypes';
import { renderInlineMarkdown, normalizeProblemSolutions } from '../../utils/problemContentParser';
import { MarkdownRenderer } from '../MarkdownRenderer';
import { updateProblemSolutions } from '../../services/reviewService';
const COMMON_PATTERNS = [
'Arrays & Hashing',
'Two Pointers',
'Sliding Window',
'Stack',
'Binary Search',
'Linked List',
'Trees',
'Tries',
'Heap / Priority Queue',
'Backtracking',
'Graphs',
'Advanced Graphs',
'1-D Dynamic Programming',
'2-D Dynamic Programming',
'Greedy',
'Intervals',
'Math & Geometry',
'Bit Manipulation'
];
interface ProblemSpecPanelProps {
leftTab: 'spec' | 'ref' | 'fsrs';
onSelectLeftTab: (tab: 'spec' | 'ref' | 'fsrs') => void;
mobileView: 'spec' | 'code' | 'ref';
isNarrow?: boolean;
problem: ProblemItem;
parsed: {
description: string;
examples: ParsedExample[];
constraints: string[];
};
userSolution?: string;
officialSolution?: string;
effectiveReferenceCode: string;
copiedSnippet: string | null;
onCopyText: (text: string, id: string) => void;
saveRefError?: string | null;
aiSolutionLoading: boolean;
aiSolutionError: string | null;
onFetchAiSolution: () => void;
explainLoading: boolean;
explainError: string | null;
explanationText: string | null;
onExplainCode: (codeToExplain?: string, pattern?: string, timeC?: string, spaceC?: string) => void;
activeReview: ReviewItem;
onEditProblem?: () => void;
onUpdateSolutions?: (solutions: ProblemSolution[]) => void;
}
function generateSolutionId(): string {
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
return `sol-${crypto.randomUUID()}`;
}
return `sol-${Date.now()}`;
}
export const ProblemSpecPanel: React.FC<ProblemSpecPanelProps> = ({
leftTab,
onSelectLeftTab,
mobileView,
isNarrow = false,
problem,
parsed,
userSolution,
officialSolution,
effectiveReferenceCode,
copiedSnippet,
onCopyText,
saveRefError,
aiSolutionLoading,
aiSolutionError,
onFetchAiSolution,