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 = ({ 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(() => problem.id || problem.name); // Multi-solution state const [selectedSolutionIndex, setSelectedSolutionIndex] = useState(0); const [isAddingSolution, setIsAddingSolution] = useState(false); const [editingSolutionId, setEditingSolutionId] = useState(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 (
{/* Sub-tab strip */}
{/* Dossier Scroll Area */}
{/* SUBTAB 1: PROBLEM SPEC (Active Recall Mode - No Spoilers!) */} {leftTab === 'spec' && (
{/* Main Problem Specification & Description Container */}
{/* Header: Title */}

{problem.name || 'Algorithm Problem'}

{/* Problem Description Body */} {parsed.description && (
PROBLEM DESCRIPTION
{parsed.description.split('\n').map((line: string, idx: number) => line.trim() ? (

{renderInlineMarkdown(line)}

) : (
) )}
)} {/* Structured Examples */} {parsed.examples.length > 0 && (
EXAMPLES ({parsed.examples.length})
{parsed.examples.map((ex, i) => (
EXAMPLE {i + 1} {ex.input && ( )}
{ex.input && (
Input:
{ex.input}
)} {ex.output && (
Output:
{ex.output}
)} {ex.explanation && (
Explanation: {renderInlineMarkdown(ex.explanation)}
)}
))}
)} {/* Constraints */} {parsed.constraints.length > 0 && (
CONSTRAINTS
    {parsed.constraints.map((c, i) => (
  • • {c}
  • ))}
)}
{/* Optimal Complexity Target Spoiler Shield (Positioned below constraints for active recall) */} {!showComplexitySpoiler ? (
OPTIMAL COMPLEXITY TARGET Hidden to test active recall before coding
) : (
OPTIMAL TARGET: T: {problem.optimal_time || 'O(N)'} S: {problem.optimal_space || 'O(1)'}
)}
)} {/* SUBTAB 2: SOLUTIONS (Methods Archive with Pattern, Complexity, & Code) */} {leftTab === 'ref' && (
{/* Feedback alert */} {solutionFeedback && (
{solutionFeedback.type === 'success' ? ( ) : ( )} {solutionFeedback.message}
)} {/* SOLUTION SELECTOR TAB BAR */}
{solutions.map((sol, idx) => { const isSelected = safeIndex === idx && !isAddingSolution && !editingSolutionId; return ( ); })}
{/* ADD OR EDIT SOLUTION FORM */} {(isAddingSolution || editingSolutionId) ? (
{editingSolutionId ? 'EDIT SOLUTION' : 'ADD NEW SOLUTION / METHOD'}
{/* Solution Name */}
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" />
{/* Pattern */}
{/* Time Complexity */}
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" />
{/* Space Complexity */}
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" />
{/* Reference Code */}