Spaces:
Running
Running
Download algospaced-ui/src/components/CreateProblemForm.tsx from iamfebin/algospaced-dsa: direct link, hf CLI and curl.
- Browser
- Download file 50.4 kB
-
https://huggingface.co/spaces/iamfebin/algospaced-dsa/resolve/main/algospaced-ui/src/components/CreateProblemForm.tsx
- Command line
-
hf download hf://spaces/iamfebin/algospaced-dsa/algospaced-ui/src/components/CreateProblemForm.tsx
-
curl -L -o CreateProblemForm.tsx https://huggingface.co/spaces/iamfebin/algospaced-dsa/resolve/main/algospaced-ui/src/components/CreateProblemForm.tsx
50.4 kB
import React, { useState } from 'react';
import { supabase } from '../firebaseClient';
import type { ProblemItem, ProblemSolution } from '../types/reviewTypes';
interface CreateProblemFormProps {
onClose: () => void;
onSuccess: () => void;
initialProblem?: ProblemItem | null;
mode?: 'create' | 'edit';
}
interface ExampleItem {
input: string;
output: string;
explanation?: string;
}
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'
];
function generateSolutionId(): string {
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
return `sol-${crypto.randomUUID()}`;
}
return `sol-${Date.now()}`;
}
export default function CreateProblemForm({
onClose,
onSuccess,
initialProblem,
mode = initialProblem ? 'edit' : 'create'
}: CreateProblemFormProps) {
const isEditMode = mode === 'edit' || Boolean(initialProblem);
// Navigation / Tab
const [activeTab, setActiveTab] = useState<'form' | 'preview'>('form');
// URL / Quick import
const [urlQuery, setUrlQuery] = useState('');
const [fetchingUrl, setFetchingUrl] = useState(false);
// Form Fields
const [newFileName, setNewFileName] = useState(() => {
if (initialProblem?.name) return initialProblem.name;
try {
const draft = localStorage.getItem('algospaced_prefill_draft');
if (draft) return JSON.parse(draft).name || '';
} catch {
/* ignore invalid json */
}
return '';
});
const [newFileProblemNumber, setNewFileProblemNumber] = useState<number | ''>(() => {
if (initialProblem?.problem_number !== undefined && initialProblem?.problem_number !== null) {
return initialProblem.problem_number;
}
return '';
});
const [newFilePattern, setNewFilePattern] = useState(() => {
if (initialProblem?.pattern) return initialProblem.pattern;
try {
const draft = localStorage.getItem('algospaced_prefill_draft');
if (draft) return JSON.parse(draft).pattern || '';
} catch {
/* ignore invalid json */
}
return 'Arrays & Hashing';
});
const [newFileDifficulty, setNewFileDifficulty] = useState<'Easy' | 'Medium' | 'Hard'>(() => {
if (initialProblem?.difficulty === 'Easy' || initialProblem?.difficulty === 'Medium' || initialProblem?.difficulty === 'Hard') {
return initialProblem.difficulty;
}
return 'Medium';
});
const [newFileOptimalTime, setNewFileOptimalTime] = useState(() => initialProblem?.optimal_time || 'O(N)');
const [newFileOptimalSpace, setNewFileOptimalSpace] = useState(() => initialProblem?.optimal_space || 'O(1)');
const [newFileDescription, setNewFileDescription] = useState(() => initialProblem?.description || '');
const [newFileExamples, setNewFileExamples] = useState<ExampleItem[]>(() => {
if (initialProblem?.examples && Array.isArray(initialProblem.examples) && initialProblem.examples.length > 0) {
return initialProblem.examples.map((ex: { input?: unknown; output?: unknown; explanation?: string } | string) =>
typeof ex === 'string'
? { input: ex, output: '', explanation: '' }
: { input: String(ex?.input ?? ''), output: String(ex?.output ?? ''), explanation: ex?.explanation || '' }
);
}
return [{ input: '', output: '', explanation: '' }];
});
const [newFileConstraints, setNewFileConstraints] = useState(() => {
if (initialProblem?.constraints) {
if (Array.isArray(initialProblem.constraints)) return initialProblem.constraints.join('\n');
return String(initialProblem.constraints);
}
return '';
});
const [newFileHowToSolve, setNewFileHowToSolve] = useState(
() => (initialProblem as { how_to_solve?: string } | undefined)?.how_to_solve || ''
);
const [newFileCode, setNewFileCode] = useState(() => {
if (initialProblem?.reference_code) return initialProblem.reference_code;
try {
const draft = localStorage.getItem('algospaced_prefill_draft');
if (draft) return JSON.parse(draft).code || '';
} catch {
/* ignore invalid json */
}
return '';
});
// Multi-solution state
const [solutions, setSolutions] = useState<ProblemSolution[]>(() => {
if (initialProblem?.solutions && Array.isArray(initialProblem.solutions) && initialProblem.solutions.length > 0) {
return initialProblem.solutions.map((s, idx) => ({
id: s.id || `sol-${idx + 1}`,
name: s.name || `Method ${idx + 1}`,
pattern: s.pattern || initialProblem.pattern || 'Arrays & Hashing',
time_complexity: s.time_complexity || initialProblem.optimal_time || 'O(N)',
space_complexity: s.space_complexity || initialProblem.optimal_space || 'O(1)',
code: s.code || '',
explanation: s.explanation || '',
is_optimal: s.is_optimal ?? (idx === 0)
}));
}
let initCode = initialProblem?.reference_code || '';
let initPattern = initialProblem?.pattern || 'Arrays & Hashing';
try {
const draft = localStorage.getItem('algospaced_prefill_draft');
if (draft) {
const parsed = JSON.parse(draft);
if (parsed.code && !initCode) initCode = parsed.code;
if (parsed.pattern && !initPattern) initPattern = parsed.pattern;
}
} catch {
/* ignore invalid json */
}
return [
{
id: 'sol-1',
name: 'Optimal Method',
pattern: initPattern,
time_complexity: initialProblem?.optimal_time || 'O(N)',
space_complexity: initialProblem?.optimal_space || 'O(1)',
code: initCode,
explanation: (initialProblem as { how_to_solve?: string } | undefined)?.how_to_solve || '',
is_optimal: true
}
];
});
const [activeSolutionIdx, setActiveSolutionIdx] = useState(0);
const activeSolution = solutions[activeSolutionIdx] || solutions[0] || {
id: 'sol-1',
name: 'Method 1',
pattern: 'Arrays & Hashing',
time_complexity: 'O(N)',
space_complexity: 'O(1)',
code: '',
explanation: '',
is_optimal: true
};
const updateActiveSolution = (updates: Partial<ProblemSolution>) => {
setSolutions(prev => {
const next = [...prev];
const targetIdx = activeSolutionIdx < next.length ? activeSolutionIdx : 0;
next[targetIdx] = { ...next[targetIdx], ...updates };
if (updates.is_optimal) {
next.forEach((s, idx) => {
if (idx !== targetIdx) s.is_optimal = false;
});
if (next[targetIdx].time_complexity) setNewFileOptimalTime(next[targetIdx].time_complexity);
if (next[targetIdx].space_complexity) setNewFileOptimalSpace(next[targetIdx].space_complexity);
if (next[targetIdx].pattern) setNewFilePattern(next[targetIdx].pattern);
}
return next;
});
};
const addSolution = () => {
const nextNum = solutions.length + 1;
const newSol: ProblemSolution = {
id: generateSolutionId(),
name: `Method ${nextNum}`,
pattern: newFilePattern || 'Arrays & Hashing',
time_complexity: 'O(N)',
space_complexity: 'O(1)',
code: '',
explanation: '',
is_optimal: solutions.length === 0
};
setSolutions(prev => [...prev, newSol]);
setActiveSolutionIdx(solutions.length);
};
const removeSolution = (idxToRemove: number) => {
if (solutions.length <= 1) return;
setSolutions(prev => {
const next = prev.filter((_, i) => i !== idxToRemove);
if (!next.some(s => s.is_optimal)) {
next[0].is_optimal = true;
}
return next;
});
if (activeSolutionIdx >= solutions.length - 1) {
setActiveSolutionIdx(Math.max(0, solutions.length - 2));
}
};
// Dual-write & Status
const [syncToGDoc, setSyncToGDoc] = useState(true);
const [createError, setCreateError] = useState('');
const [createSuccess, setCreateSuccess] = useState('');
const [creating, setCreating] = useState(false);
// AI loading flags
const [loadingIntuition, setLoadingIntuition] = useState(false);
const [loadingComments, setLoadingComments] = useState(false);
const [prefilling, setPrefilling] = useState(false);
React.useEffect(() => {
if (!isEditMode) {
localStorage.removeItem('algospaced_prefill_draft');
}
}, [isEditMode]);
const getHeaders = async () => {
const { data: { session } } = await supabase.auth.getSession();
const token = session ? session.access_token : 'sandbox';
const customKey = localStorage.getItem('algospaced_custom_api_key') || localStorage.getItem('sandbox_gemini_api_key') || '';
const customProvider = localStorage.getItem('algospaced_custom_ai_provider') || 'default';
const headers: Record<string, string> = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
};
if (customProvider && customProvider !== 'default' && customKey && customKey.trim()) {
headers['x-custom-api-key'] = customKey.trim();
headers['x-gemini-api-key'] = customKey.trim();
headers['x-ai-provider'] = customProvider;
}
return headers;
};
// 1. Fetch LeetCode Details via URL or Title
const handleFetchLeetCode = async () => {
if (!urlQuery.trim()) return;
setFetchingUrl(true);
setCreateError('');
try {
const headers = await getHeaders();
const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/explorer/problems/fetch-leetcode`, {
method: 'POST',
headers,
body: JSON.stringify({ query: urlQuery.trim() })
});
if (res.ok) {
const data = await res.json();
if (data.problem_number !== undefined && data.problem_number !== null) {
setNewFileProblemNumber(data.problem_number);
}
if (data.title) setNewFileName(data.title);
if (data.difficulty) setNewFileDifficulty(data.difficulty as 'Easy' | 'Medium' | 'Hard');
if (data.pattern) setNewFilePattern(data.pattern);
if (data.optimal_time) setNewFileOptimalTime(data.optimal_time);
if (data.optimal_space) setNewFileOptimalSpace(data.optimal_space);
if (data.description) setNewFileDescription(data.description);
if (data.how_to_solve) setNewFileHowToSolve(data.how_to_solve);
if (data.starter_code && !newFileCode.trim()) setNewFileCode(data.starter_code);
setSolutions(prev => {
const next = [...prev];
const active = { ...next[activeSolutionIdx] };
if (data.pattern) active.pattern = data.pattern;
if (data.optimal_time) active.time_complexity = data.optimal_time;
if (data.optimal_space) active.space_complexity = data.optimal_space;
if (data.how_to_solve) active.explanation = data.how_to_solve;
if (data.starter_code && !active.code?.trim()) active.code = data.starter_code;
next[activeSolutionIdx] = active;
return next;
});
if (Array.isArray(data.examples) && data.examples.length > 0) {
setNewFileExamples(data.examples);
}
if (Array.isArray(data.constraints)) {
setNewFileConstraints(data.constraints.join('\n'));
} else if (typeof data.constraints === 'string') {
setNewFileConstraints(data.constraints);
}
} else {
const errData = await res.json();
setCreateError(errData.detail || 'Failed to fetch LeetCode problem data.');
}
} catch {
setCreateError('Fetch request failed due to connection error.');
} finally {
setFetchingUrl(false);
}
};
// 1b. AI Prefill based on Problem Title / Code
const handlePrefill = async () => {
const codeToUse = activeSolution.code || newFileCode;
if (!newFileName.trim() && !codeToUse.trim()) return;
setPrefilling(true);
setCreateError('');
try {
const headers = await getHeaders();
const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/explorer/problems/prefill`, {
method: 'POST',
headers,
body: JSON.stringify({ name: newFileName, code: codeToUse })
});
if (res.ok) {
const data = await res.json();
if (data.problem_number !== undefined && data.problem_number !== null) {
setNewFileProblemNumber(data.problem_number);
}
if (data.title && !newFileName) setNewFileName(data.title);
if (data.pattern) setNewFilePattern(data.pattern);
if (data.difficulty) setNewFileDifficulty(data.difficulty as 'Easy' | 'Medium' | 'Hard');
if (data.optimal_time) setNewFileOptimalTime(data.optimal_time);
if (data.optimal_space) setNewFileOptimalSpace(data.optimal_space);
if (data.description) setNewFileDescription(data.description);
if (data.reference_code && !codeToUse.trim()) setNewFileCode(data.reference_code);
setSolutions(prev => {
const next = [...prev];
const active = { ...next[activeSolutionIdx] };
if (data.pattern) active.pattern = data.pattern;
if (data.optimal_time) active.time_complexity = data.optimal_time;
if (data.optimal_space) active.space_complexity = data.optimal_space;
if (data.reference_code && !active.code?.trim()) active.code = data.reference_code;
next[activeSolutionIdx] = active;
return next;
});
} else {
const errData = await res.json();
setCreateError(errData.detail || 'Prefill failed.');
}
} catch {
setCreateError('Prefill request failed due to connection error.');
} finally {
setPrefilling(false);
}
};
// 2. AI Assist: Generate "How to solve?" Intuition
const handleGenerateIntuition = async () => {
const codeToUse = activeSolution.code || newFileCode;
if (!newFileName.trim() && !codeToUse.trim()) {
setCreateError('Please enter a problem name or code first.');
return;
}
setLoadingIntuition(true);
setCreateError('');
try {
const headers = await getHeaders();
const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/explorer/problems/assist-field`, {
method: 'POST',
headers,
body: JSON.stringify({
field: 'intuition',
title: newFileName,
code: codeToUse,
description: newFileDescription
})
});
if (res.ok) {
const data = await res.json();
if (data.how_to_solve) {
setNewFileHowToSolve(data.how_to_solve);
updateActiveSolution({ explanation: data.how_to_solve });
}
} else {
const errData = await res.json();
setCreateError(errData.detail || 'Failed to generate intuition.');
}
} catch {
setCreateError('Intuition generator failed due to connection error.');
} finally {
setLoadingIntuition(false);
}
};
// 3. AI Assist: Format Code with Step-by-Step Comments
const handleFormatCode = async () => {
const codeToUse = activeSolution.code || newFileCode;
if (!codeToUse.trim()) {
setCreateError('Please enter some Python code to format.');
return;
}
setLoadingComments(true);
setCreateError('');
try {
const headers = await getHeaders();
const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/explorer/problems/assist-field`, {
method: 'POST',
headers,
body: JSON.stringify({
field: 'comments',
title: newFileName,
code: codeToUse
})
});
if (res.ok) {
const data = await res.json();
if (data.formatted_code) {
setNewFileCode(data.formatted_code);
updateActiveSolution({ code: data.formatted_code });
}
} else {
const errData = await res.json();
setCreateError(errData.detail || 'Failed to format code.');
}
} catch {
setCreateError('Code formatter failed due to connection error.');
} finally {
setLoadingComments(false);
}
};
// 4. Submit Problem (Dual-write to Database & Google Docs)
const handleCreateProblem = async (e: React.FormEvent) => {
e.preventDefault();
if (!newFileName.trim()) {
setCreateError('Problem name cannot be empty');
return;
}
setCreating(true);
setCreateError('');
setCreateSuccess('');
try {
const headers = await getHeaders();
const constraintsList = newFileConstraints
.split('\n')
.map(c => c.trim())
.filter(Boolean);
const optimalSol = solutions.find(s => s.is_optimal) || solutions[0];
const finalPattern = optimalSol?.pattern || newFilePattern.trim() || 'General';
const finalCode = optimalSol?.code || newFileCode;
const finalHowToSolve = optimalSol?.explanation || newFileHowToSolve;
const finalOptimalTime = newFileOptimalTime || optimalSol?.time_complexity || 'O(N)';
const finalOptimalSpace = newFileOptimalSpace || optimalSol?.space_complexity || 'O(1)';
let res: Response;
if (isEditMode && initialProblem) {
const targetId = initialProblem.id || (initialProblem.problem_number ? String(initialProblem.problem_number) : '') || newFileName.trim();
res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/explorer/problems/${encodeURIComponent(targetId)}`, {
method: 'PUT',
headers,
body: JSON.stringify({
name: newFileName.trim(),
pattern: finalPattern,
difficulty: newFileDifficulty,
reference_code: finalCode,
description: newFileDescription,
problem_number: newFileProblemNumber === '' ? null : Number(newFileProblemNumber),
optimal_time: finalOptimalTime,
optimal_space: finalOptimalSpace,
examples: newFileExamples.filter(ex => ex.input.trim() || ex.output.trim()),
constraints: constraintsList,
how_to_solve: finalHowToSolve,
solutions: solutions
})
});
} else {
res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/explorer/problems/create`, {
method: 'POST',
headers,
body: JSON.stringify({
name: newFileName.trim(),
pattern: finalPattern,
difficulty: newFileDifficulty,
reference_code: finalCode,
description: newFileDescription,
problem_number: newFileProblemNumber === '' ? null : Number(newFileProblemNumber),
optimal_time: finalOptimalTime,
optimal_space: finalOptimalSpace,
examples: newFileExamples.filter(ex => ex.input.trim() || ex.output.trim()),
constraints: constraintsList,
how_to_solve: finalHowToSolve,
sync_to_gdoc: syncToGDoc,
solutions: solutions
})
});
}
const data = await res.json();
if (res.ok && (data.success || data.problem_id)) {
setCreateSuccess(isEditMode ? 'Problem updated successfully!' : 'Problem saved and synced successfully!');
setTimeout(() => {
onSuccess();
onClose();
}, 1000);
} else {
setCreateError(data.detail || (isEditMode ? 'Failed to update problem.' : 'Failed to create problem.'));
}
} catch {
setCreateError('Connection timed out.');
} finally {
setCreating(false);
}
};
const addExample = () => {
setNewFileExamples([...newFileExamples, { input: '', output: '', explanation: '' }]);
};
const removeExample = (idx: number) => {
if (newFileExamples.length <= 1) return;
setNewFileExamples(newFileExamples.filter((_, i) => i !== idx));
};
const updateExample = (idx: number, field: keyof ExampleItem, val: string) => {
const next = [...newFileExamples];
next[idx] = { ...next[idx], [field]: val };
setNewFileExamples(next);
};
return (
<form onSubmit={handleCreateProblem} className="flex flex-col h-full bg-[#fdf8e1] text-ink-black font-sans overflow-hidden">
{/* Top Header & Tab Bar */}
<div className="bg-[#f0e6c8] p-2.5 border-b-2 border-ink-black flex flex-col gap-2 shrink-0">
<div className="flex items-center justify-between">
<div className="flex items-center gap-1.5">
<span className="font-arcade text-xs text-primary-purple">✦</span>
<h2 className="text-xs font-bold font-arcade tracking-tight uppercase">
{isEditMode ? 'Edit Problem Specification' : 'Problem & Note Studio'}
</h2>
{isEditMode && (
<span className="text-[9px] bg-primary-purple/10 text-primary-purple font-mono px-1.5 py-0.5 rounded border border-primary-purple/30 font-bold">
EDIT MODE
</span>
)}
</div>
{/* Tab Switcher */}
<div className="flex border-2 border-ink-black bg-white rounded overflow-hidden shadow-[1px_1px_0px_#1E293B]">
<button
type="button"
onClick={() => setActiveTab('form')}
className={`px-3 py-1 text-[10px] font-bold uppercase transition-colors ${activeTab === 'form' ? 'bg-primary-purple text-white' : 'hover:bg-slate-100'
}`}
>
✏️ Editor
</button>
<button
type="button"
onClick={() => setActiveTab('preview')}
className={`px-3 py-1 text-[10px] font-bold uppercase transition-colors ${activeTab === 'preview' ? 'bg-primary-purple text-white' : 'hover:bg-slate-100'
}`}
>
📄 Doc Preview
</button>
</div>
</div>
{/* Quick LeetCode Fetch Bar */}
<div className="flex gap-1.5 items-center">
<input
type="text"
value={urlQuery}
onChange={(e) => setUrlQuery(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); handleFetchLeetCode(); } }}
placeholder="Paste LeetCode URL (e.g. https://leetcode.com/problems/two-sum/) or Title..."
className="flex-1 bg-white border-2 border-ink-black px-2 py-1 text-xs outline-none focus:ring-1 focus:ring-primary-purple font-medium"
/>
<button
type="button"
onClick={handleFetchLeetCode}
disabled={fetchingUrl || !urlQuery.trim()}
className="bg-[#ffe24c] hover:bg-yellow-300 disabled:opacity-50 text-ink-black font-arcade text-[9px] font-bold px-2.5 py-1.5 border-2 border-ink-black shadow-[1px_1px_0px_#1E293B] active:translate-y-0.5 cursor-pointer flex items-center gap-1 shrink-0"
>
<span>⚡</span> {fetchingUrl ? 'FETCHING...' : 'FETCH LEETCODE'}
</button>
</div>
</div>
{/* Messages */}
{createError && (
<div className="mx-3 mt-2 p-2 border-2 border-red-500 bg-red-50 text-red-800 text-[11px] font-mono leading-relaxed shrink-0">
⚠️ {createError}
</div>
)}
{createSuccess && (
<div className="mx-3 mt-2 p-2 border-2 border-green-500 bg-green-50 text-green-800 text-[11px] font-mono leading-relaxed shrink-0">
✅ {createSuccess}
</div>
)}
{/* Main Body */}
<div className="flex-1 overflow-y-auto custom-scrollbar p-3 space-y-3">
{activeTab === 'form' ? (
<>
{/* Row 1: Problem #, Title, Difficulty */}
<div className="grid grid-cols-12 gap-2">
<div className="col-span-3 flex flex-col gap-1">
<label className="text-[10px] font-bold text-slate-600 uppercase">Problem #:</label>
<input
type="number"
value={newFileProblemNumber}
onChange={(e) => setNewFileProblemNumber(e.target.value === '' ? '' : Number(e.target.value))}
placeholder="e.g. 1"
className="bg-white border-2 border-ink-black p-1.5 text-xs outline-none focus:ring-1 focus:ring-primary-purple font-bold"
/>
</div>
<div className="col-span-6 flex flex-col gap-1">
<div className="flex justify-between items-center">
<label className="text-[10px] font-bold text-slate-600 uppercase">Title:</label>
<button
type="button"
onClick={handlePrefill}
disabled={prefilling || (!newFileName.trim() && !activeSolution.code?.trim())}
className="text-[8px] font-arcade font-bold px-1.5 py-0.5 border border-ink-black bg-[#ffe24c] hover:bg-yellow-300 disabled:opacity-50 flex items-center gap-1 cursor-pointer"
>
<span>✦</span> {prefilling ? '...' : 'AUTO-FILL'}
</button>
</div>
<input
type="text"
required
value={newFileName}
onChange={(e) => setNewFileName(e.target.value)}
placeholder="e.g. Two Sum"
className="bg-white border-2 border-ink-black p-1.5 text-xs outline-none focus:ring-1 focus:ring-primary-purple font-bold"
/>
</div>
<div className="col-span-3 flex flex-col gap-1">
<label className="text-[10px] font-bold text-slate-600 uppercase">Difficulty:</label>
<select
value={newFileDifficulty}
onChange={(e) => setNewFileDifficulty(e.target.value as 'Easy' | 'Medium' | 'Hard')}
className={`border-2 border-ink-black p-1.5 text-xs font-bold outline-none cursor-pointer ${newFileDifficulty === 'Easy'
? 'bg-emerald-100 text-emerald-900'
: newFileDifficulty === 'Medium'
? 'bg-amber-100 text-amber-900'
: 'bg-rose-100 text-rose-900'
}`}
>
<option value="Easy">Easy</option>
<option value="Medium">Medium</option>
<option value="Hard">Hard</option>
</select>
</div>
</div>
{/* Row 2: Target Optimal Complexities (Active Recall Shielded on Review) */}
<div className="grid grid-cols-2 gap-2 bg-[#f6edd2] p-2 border-2 border-ink-black rounded">
<div className="flex flex-col gap-1">
<div className="flex items-center justify-between">
<label className="text-[10px] font-bold text-slate-700 uppercase flex items-center gap-1">
<span>⏱️</span> Target Optimal Time:
</label>
<span className="text-[8px] font-mono text-slate-500">(hidden behind spoiler on review)</span>
</div>
<input
type="text"
value={newFileOptimalTime}
onChange={(e) => setNewFileOptimalTime(e.target.value)}
placeholder="e.g. O(N)"
className="bg-white border-2 border-ink-black p-1.5 text-xs outline-none focus:ring-1 focus:ring-primary-purple font-mono font-bold"
/>
</div>
<div className="flex flex-col gap-1">
<div className="flex items-center justify-between">
<label className="text-[10px] font-bold text-slate-700 uppercase flex items-center gap-1">
<span>📦</span> Target Optimal Space:
</label>
<span className="text-[8px] font-mono text-slate-500">(hidden behind spoiler on review)</span>
</div>
<input
type="text"
value={newFileOptimalSpace}
onChange={(e) => setNewFileOptimalSpace(e.target.value)}
placeholder="e.g. O(1)"
className="bg-white border-2 border-ink-black p-1.5 text-xs outline-none focus:ring-1 focus:ring-primary-purple font-mono font-bold"
/>
</div>
</div>
{/* Row 3: Problem Description */}
<div className="flex flex-col gap-1">
<label className="text-[10px] font-bold text-slate-600 uppercase">Problem Description:</label>
<textarea
value={newFileDescription}
onChange={(e) => setNewFileDescription(e.target.value)}
placeholder="Given an array of integers nums and an integer target..."
className="bg-white border-2 border-ink-black p-2 text-xs outline-none focus:ring-1 focus:ring-primary-purple font-sans h-20 resize-y leading-relaxed"
/>
</div>
{/* Row 4: Examples */}
<div className="flex flex-col gap-1.5 bg-[#f6edd2] p-2.5 border-2 border-ink-black rounded">
<div className="flex justify-between items-center">
<label className="text-[10px] font-bold text-slate-700 uppercase flex items-center gap-1">
<span>🧪</span> Examples ({newFileExamples.length})
</label>
<button
type="button"
onClick={addExample}
className="text-[9px] font-bold px-2 py-0.5 border border-ink-black bg-white hover:bg-slate-100 cursor-pointer shadow-[1px_1px_0px_#1E293B]"
>
+ Add Example
</button>
</div>
{newFileExamples.map((ex, idx) => (
<div key={idx} className="bg-white border border-ink-black p-2 space-y-1.5 rounded relative text-xs">
<div className="flex justify-between items-center">
<span className="font-bold text-[10px] text-slate-500">Example {idx + 1}:</span>
{newFileExamples.length > 1 && (
<button
type="button"
onClick={() => removeExample(idx)}
className="text-[10px] text-red-600 hover:text-red-800 font-bold cursor-pointer"
>
✕
</button>
)}
</div>
<div className="grid grid-cols-2 gap-2">
<input
type="text"
value={ex.input}
onChange={(e) => updateExample(idx, 'input', e.target.value)}
placeholder="Input: nums = [2,7,11,15], target = 9"
className="bg-slate-50 border border-slate-300 p-1 text-[11px] font-mono outline-none"
/>
<input
type="text"
value={ex.output}
onChange={(e) => updateExample(idx, 'output', e.target.value)}
placeholder="Output: [0,1]"
className="bg-slate-50 border border-slate-300 p-1 text-[11px] font-mono outline-none"
/>
</div>
<input
type="text"
value={ex.explanation || ''}
onChange={(e) => updateExample(idx, 'explanation', e.target.value)}
placeholder="Explanation (Optional): Because nums[0] + nums[1] == 9, we return [0, 1]."
className="bg-slate-50 border border-slate-300 p-1 text-[11px] outline-none w-full"
/>
</div>
))}
</div>
{/* Row 5: Constraints */}
<div className="flex flex-col gap-1">
<label className="text-[10px] font-bold text-slate-600 uppercase">Constraints (1 per line):</label>
<textarea
value={newFileConstraints}
onChange={(e) => setNewFileConstraints(e.target.value)}
placeholder="2 <= nums.length <= 10^4 -10^9 <= nums[i] <= 10^9 Only one valid answer exists."
className="bg-white border-2 border-ink-black p-2 text-xs font-mono outline-none focus:ring-1 focus:ring-primary-purple h-16 resize-y leading-snug"
/>
</div>
{/* Row 6: Solutions & Methods*/}
<div className="border-2 border-ink-black bg-[#faf6eb] p-3 rounded space-y-3">
<div className="flex flex-wrap items-center justify-between gap-2 border-b-2 border-ink-black pb-2">
<div className="flex items-center gap-2">
<span className="text-xs">💡</span>
<label className="text-[11px] font-bold font-arcade uppercase tracking-wide">
Solutions & Methods ({solutions.length})
</label>
<span className="text-[9px] bg-slate-200 text-slate-700 font-mono px-1.5 py-0.5 rounded border border-slate-300">
Visible on the Solutions tab during review
</span>
</div>
<button
type="button"
onClick={addSolution}
className="px-2.5 py-1 text-[9px] font-bold font-arcade bg-[#ffe24c] hover:bg-yellow-300 border-2 border-ink-black shadow-[1px_1px_0px_#1E293B] cursor-pointer flex items-center gap-1"
>
<span>+</span> ADD METHOD
</button>
</div>
{/* Solution Tabs */}
<div className="flex flex-wrap gap-1.5">
{solutions.map((sol, idx) => (
<button
key={sol.id || idx}
type="button"
onClick={() => setActiveSolutionIdx(idx)}
className={`px-2.5 py-1 text-[10px] font-bold border-2 border-ink-black flex items-center gap-1.5 cursor-pointer rounded transition-colors ${activeSolutionIdx === idx
? 'bg-primary-purple text-white shadow-[1px_1px_0px_#1E293B]'
: 'bg-white text-slate-700 hover:bg-slate-100'
}`}
>
<span>{sol.name || `Method ${idx + 1}`}</span>
{sol.is_optimal && (
<span className={`text-[8px] px-1 py-0.2 rounded font-mono uppercase font-black ${activeSolutionIdx === idx ? 'bg-amber-400 text-ink-black' : 'bg-amber-200 text-amber-900'
}`}>
★ Optimal
</span>
)}
</button>
))}
</div>
{/* Active Solution Fields */}
<div className="bg-white border-2 border-ink-black p-3 rounded space-y-2.5">
<div className="flex flex-wrap items-center justify-between gap-2 border-b border-slate-200 pb-2">
<div className="flex items-center gap-2">
<span className="text-xs font-bold text-slate-500">Method #{activeSolutionIdx + 1}:</span>
<input
type="text"
value={activeSolution.name}
onChange={(e) => updateActiveSolution({ name: e.target.value })}
placeholder="e.g. Hash Map Lookup or Two Pointers"
className="border border-ink-black px-2 py-0.5 text-xs font-bold bg-[#fffdf5] outline-none focus:ring-1 focus:ring-primary-purple w-56"
/>
</div>
<div className="flex items-center gap-3">
<label className="flex items-center gap-1.5 text-[10px] font-bold text-amber-800 cursor-pointer select-none">
<input
type="checkbox"
checked={Boolean(activeSolution.is_optimal)}
onChange={(e) => updateActiveSolution({ is_optimal: e.target.checked })}
className="w-3.5 h-3.5 accent-amber-500 cursor-pointer"
/>
<span>Mark as Optimal Solution</span>
</label>
{solutions.length > 1 && (
<button
type="button"
onClick={() => removeSolution(activeSolutionIdx)}
className="text-[10px] font-bold text-red-600 hover:text-red-800 border border-red-300 hover:border-red-500 px-2 py-0.5 rounded cursor-pointer"
>
Remove Method
</button>
)}
</div>
</div>
{/* Method Pattern and Big-O */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-2">
<div className="flex flex-col gap-1">
<label className="text-[10px] font-bold text-slate-600 uppercase">Pattern / Technique:</label>
<input
type="text"
list="pattern-suggestions"
value={activeSolution.pattern || ''}
onChange={(e) => updateActiveSolution({ pattern: e.target.value })}
placeholder="e.g. Arrays & Hashing"
className="bg-[#fafafa] border border-ink-black p-1 text-xs outline-none focus:ring-1 focus:ring-primary-purple font-medium"
/>
<datalist id="pattern-suggestions">
{COMMON_PATTERNS.map(p => (
<option key={p} value={p} />
))}
</datalist>
</div>
<div className="flex flex-col gap-1">
<label className="text-[10px] font-bold text-slate-600 uppercase">Method Time Complexity:</label>
<input
type="text"
value={activeSolution.time_complexity || ''}
onChange={(e) => updateActiveSolution({ time_complexity: e.target.value })}
placeholder="e.g. O(N)"
className="bg-[#fafafa] border border-ink-black p-1 text-xs outline-none focus:ring-1 focus:ring-primary-purple font-mono font-semibold"
/>
</div>
<div className="flex flex-col gap-1">
<label className="text-[10px] font-bold text-slate-600 uppercase">Method Space Complexity:</label>
<input
type="text"
value={activeSolution.space_complexity || ''}
onChange={(e) => updateActiveSolution({ space_complexity: e.target.value })}
placeholder="e.g. O(1)"
className="bg-[#fafafa] border border-ink-black p-1 text-xs outline-none focus:ring-1 focus:ring-primary-purple font-mono font-semibold"
/>
</div>
</div>
{/* Method Intuition */}
<div className="flex flex-col gap-1">
<div className="flex justify-between items-center">
<label className="text-[10px] font-bold text-slate-600 uppercase flex items-center gap-1">
<span>💡</span> Intuition / Mental Model:
</label>
<button
type="button"
onClick={handleGenerateIntuition}
disabled={loadingIntuition}
className="text-[8px] font-arcade font-bold px-2 py-0.5 border border-ink-black bg-[#ffe24c] hover:bg-yellow-300 disabled:opacity-50 flex items-center gap-1 cursor-pointer"
>
<span>✦</span> {loadingIntuition ? 'GENERATING...' : 'AI INTUITION'}
</button>
</div>
<textarea
value={activeSolution.explanation || ''}
onChange={(e) => updateActiveSolution({ explanation: e.target.value })}
placeholder="Explain how this specific method works, key data structures, invariants, or edge cases..."
className="bg-[#fafafa] border border-ink-black p-2 text-xs outline-none focus:ring-1 focus:ring-primary-purple font-sans h-20 resize-y leading-relaxed"
/>
</div>
{/* Method Python Code */}
<div className="flex flex-col gap-1">
<div className="flex justify-between items-center">
<label className="text-[10px] font-bold text-slate-600 uppercase flex items-center gap-1">
<span>🐍</span> Method Python Code:
</label>
<button
type="button"
onClick={handleFormatCode}
disabled={loadingComments || !activeSolution.code?.trim()}
className="text-[8px] font-arcade font-bold px-2 py-0.5 border border-ink-black bg-[#a7f3d0] hover:bg-emerald-300 disabled:opacity-50 flex items-center gap-1 cursor-pointer text-emerald-950"
>
<span>✨</span> {loadingComments ? 'FORMATTING...' : 'ADD EMOJI COMMENTS'}
</button>
</div>
<textarea
value={activeSolution.code || ''}
onChange={(e) => updateActiveSolution({ code: e.target.value })}
placeholder="def twoSum(nums: list[int], target: int) -> list[int]: # 1. 🗺️ Initialize lookup map seen = {} ... return []"
className="bg-slate-900 text-[#4ADE80] font-mono p-2.5 border-2 border-ink-black rounded outline-none h-44 text-xs leading-relaxed resize-y w-full"
/>
</div>
</div>
</div>
</>
) : (
/* Real-time Google Docs Preview */
<div className="bg-white border-2 border-ink-black p-6 rounded shadow-sm font-sans space-y-4 text-slate-800">
<div className="border-b pb-2">
<span className="text-[10px] font-mono uppercase bg-purple-100 text-purple-800 px-2 py-0.5 rounded font-bold">
Google Doc Preview (Exact formatting preview)
</span>
</div>
{/* Title */}
<h1 className="text-xl font-bold text-slate-900">
{newFileProblemNumber ? `${newFileProblemNumber}. ` : ''}{newFileName || 'Problem Title'}
</h1>
{/* Difficulty Badge */}
<div>
<span className={`text-xs font-bold px-2.5 py-0.5 rounded ${newFileDifficulty === 'Easy'
? 'bg-emerald-100 text-[#137c36]'
: newFileDifficulty === 'Medium'
? 'bg-amber-100 text-[#c06100]'
: 'bg-rose-100 text-[#c5221f]'
}`}>
{newFileDifficulty}
</span>
</div>
{/* Description */}
{newFileDescription && (
<div className="text-xs text-slate-700 leading-relaxed whitespace-pre-wrap">
{newFileDescription}
</div>
)}
{/* Examples */}
{newFileExamples.some(ex => ex.input.trim() || ex.output.trim()) && (
<div className="space-y-3 pt-2">
{newFileExamples.map((ex, i) => (
<div key={i} className="text-xs space-y-1">
<div className="font-bold text-slate-800">Example {i + 1}:</div>
{ex.input && (
<div>
<span className="text-slate-600">Input: </span>
<span className="bg-[#d9d9d9] font-mono px-1.5 py-0.5 rounded text-[11px]">{ex.input}</span>
</div>
)}
{ex.output && (
<div>
<span className="text-slate-600">Output: </span>
<span className="bg-[#d9d9d9] font-mono px-1.5 py-0.5 rounded text-[11px]">{ex.output}</span>
</div>
)}
{ex.explanation && (
<div>
<span className="text-slate-600">Explanation: </span>
<span className="bg-[#d9d9d9] font-mono px-1.5 py-0.5 rounded text-[11px]">{ex.explanation}</span>
</div>
)}
</div>
))}
</div>
)}
{/* Constraints */}
{newFileConstraints && (
<div className="space-y-1.5 pt-2">
<div className="font-bold text-xs text-slate-800">Constraints:</div>
<ul className="list-disc pl-5 text-xs space-y-1">
{newFileConstraints.split('\n').filter(Boolean).map((c, i) => (
<li key={i}>
<span className="bg-[#d9d9d9] font-mono px-1.5 py-0.5 rounded text-[11px]">{c.replace(/^[•\-*]\s*/, '')}</span>
</li>
))}
</ul>
</div>
)}
{/* Target Optimal Complexities */}
<div className="p-2.5 bg-slate-50 border border-slate-200 rounded space-y-1 text-xs">
<div className="font-bold text-slate-700">Target Optimal Complexities (Active Recall Shielded on Review):</div>
<div className="flex gap-4 font-mono text-slate-900">
<span>Time: {newFileOptimalTime}</span>
<span>Space: {newFileOptimalSpace}</span>
</div>
</div>
{/* Methods & Solutions List */}
<div className="pt-3 space-y-4">
<div className="font-bold text-sm text-slate-900 border-b pb-1">
Solutions & Methods ({solutions.length})
</div>
{solutions.map((sol, i) => (
<div key={sol.id || i} className="border border-slate-300 p-3 rounded space-y-2 bg-[#fdfdfd]">
<div className="flex items-center justify-between">
<span className="font-bold text-xs text-slate-900">
{sol.name || `Method ${i + 1}`}
</span>
<div className="flex items-center gap-1.5">
{sol.is_optimal && (
<span className="text-[9px] bg-amber-100 text-amber-800 font-bold px-1.5 py-0.5 rounded border border-amber-300">
★ Optimal
</span>
)}
<span className="text-[9px] bg-purple-100 text-primary-purple font-bold px-1.5 py-0.5 rounded border border-purple-200">
{sol.pattern || 'Standard'}
</span>
</div>
</div>
<div className="flex gap-4 text-xs font-mono text-slate-600">
<span>T: {sol.time_complexity || 'O(?)'}</span>
<span>S: {sol.space_complexity || 'O(?)'}</span>
</div>
{sol.explanation && (
<div className="text-xs text-slate-700 leading-relaxed whitespace-pre-wrap bg-slate-50 p-2 rounded">
{sol.explanation}
</div>
)}
{sol.code && (
<div className="bg-[#f8fafc] border border-slate-200 p-2.5 rounded font-mono text-[11px] leading-relaxed text-slate-900 overflow-x-auto whitespace-pre">
{sol.code}
</div>
)}
</div>
))}
</div>
</div>
)}
</div>
{/* Bottom Footer & Submit */}
<div className="p-3 bg-[#f0e6c8] border-t-2 border-ink-black flex flex-wrap items-center justify-between gap-2 shrink-0">
{/* Sync Checkbox (hide in edit mode) */}
{!isEditMode ? (
<label className="flex items-center gap-2 text-xs font-bold text-slate-700 cursor-pointer select-none">
<input
type="checkbox"
checked={syncToGDoc}
onChange={(e) => setSyncToGDoc(e.target.checked)}
className="w-4 h-4 accent-primary-purple cursor-pointer"
/>
<span>Format & Sync to Google Doc</span>
</label>
) : (
<div className="text-[11px] text-slate-600 font-mono flex items-center gap-1.5">
<span className="w-2 h-2 rounded-full bg-primary-purple inline-block"></span>
Editing #{initialProblem?.problem_number ?? '—'} {initialProblem?.name}
</div>
)}
{/* Action Buttons */}
<div className="flex items-center gap-2">
<button
type="button"
onClick={onClose}
className="px-3 py-1.5 bg-white hover:bg-slate-50 border-2 border-ink-black text-xs font-bold cursor-pointer"
>
CANCEL
</button>
<button
type="submit"
disabled={creating}
className="px-4 py-1.5 bg-primary-purple hover:bg-purple-600 text-white font-arcade text-[10px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_#1E293B] active:translate-y-0.5 active:shadow-none cursor-pointer flex items-center gap-1.5"
>
<span>{isEditMode ? '✏️' : '💾'}</span>{' '}
{creating
? isEditMode
? 'UPDATING...'
: 'SAVING...'
: isEditMode
? 'UPDATE PROBLEM'
: 'SAVE SOLUTION'}
</button>
</div>
</div>
</form>
);
}
import React, { useState } from 'react';
import { supabase } from '../firebaseClient';
import type { ProblemItem, ProblemSolution } from '../types/reviewTypes';
interface CreateProblemFormProps {
onClose: () => void;
onSuccess: () => void;
initialProblem?: ProblemItem | null;
mode?: 'create' | 'edit';
}
interface ExampleItem {
input: string;
output: string;
explanation?: string;
}
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'
];
function generateSolutionId(): string {
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
return `sol-${crypto.randomUUID()}`;
}
return `sol-${Date.now()}`;
}
export default function CreateProblemForm({
onClose,
onSuccess,
initialProblem,
mode = initialProblem ? 'edit' : 'create'
}: CreateProblemFormProps) {
const isEditMode = mode === 'edit' || Boolean(initialProblem);
// Navigation / Tab
const [activeTab, setActiveTab] = useState<'form' | 'preview'>('form');
// URL / Quick import
const [urlQuery, setUrlQuery] = useState('');
const [fetchingUrl, setFetchingUrl] = useState(false);
// Form Fields
const [newFileName, setNewFileName] = useState(() => {
if (initialProblem?.name) return initialProblem.name;
try {
const draft = localStorage.getItem('algospaced_prefill_draft');
if (draft) return JSON.parse(draft).name || '';
} catch {
/* ignore invalid json */
}
return '';
});
const [newFileProblemNumber, setNewFileProblemNumber] = useState<number | ''>(() => {
if (initialProblem?.problem_number !== undefined && initialProblem?.problem_number !== null) {
return initialProblem.problem_number;
}
return '';
});
const [newFilePattern, setNewFilePattern] = useState(() => {
if (initialProblem?.pattern) return initialProblem.pattern;
try {
const draft = localStorage.getItem('algospaced_prefill_draft');
if (draft) return JSON.parse(draft).pattern || '';
} catch {
/* ignore invalid json */
}
return 'Arrays & Hashing';
});
const [newFileDifficulty, setNewFileDifficulty] = useState<'Easy' | 'Medium' | 'Hard'>(() => {
if (initialProblem?.difficulty === 'Easy' || initialProblem?.difficulty === 'Medium' || initialProblem?.difficulty === 'Hard') {
return initialProblem.difficulty;
}
return 'Medium';
});
const [newFileOptimalTime, setNewFileOptimalTime] = useState(() => initialProblem?.optimal_time || 'O(N)');
const [newFileOptimalSpace, setNewFileOptimalSpace] = useState(() => initialProblem?.optimal_space || 'O(1)');
const [newFileDescription, setNewFileDescription] = useState(() => initialProblem?.description || '');