import { useState, useEffect } from 'react'; import { supabase } from '../supabaseClient'; interface PythonChallengeData { title: string; description: string; difficulty: string; points: number; starter_code: string; completed: boolean; total_score: number; } export default function PythonChallenge() { const [challenge, setChallenge] = useState(null); const [code, setCode] = useState(''); const [submitting, setSubmitting] = useState(false); const [results, setResults] = useState([]); const [error, setError] = useState(''); const [loading, setLoading] = useState(true); const [globalScore, setGlobalScore] = useState(0); const fetchChallenge = async () => { setLoading(true); setError(''); try { const { data: { session } } = await supabase.auth.getSession(); if (!session) { setError('Unauthenticated session'); return; } const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/challenges/python/daily`, { headers: { 'Authorization': `Bearer ${session.access_token}` } }); if (res.ok) { const data = await res.json(); setChallenge(data); setCode(data.starter_code); setGlobalScore(data.total_score); } else { setError('Failed to load challenge from server.'); } } catch { setError('Connection timed out.'); } finally { setLoading(false); } }; useEffect(() => { fetchChallenge(); }, []); const handleSubmit = async () => { setSubmitting(true); setError(''); setResults([]); try { const { data: { session } } = await supabase.auth.getSession(); if (!session) { setError('Unauthenticated session'); return; } const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/challenges/python/submit`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${session.access_token}` }, body: JSON.stringify({ code }) }); if (res.ok) { const data = await res.json(); if (data.success) { setResults(data.results); if (data.all_passed) { setGlobalScore(data.total_score); setChallenge(prev => prev ? { ...prev, completed: true } : null); } } else { setError(data.error); } } else { setError('Submission failed at server host.'); } } catch { setError('Network connection lost.'); } finally { setSubmitting(false); } }; if (loading) { return (
LOADING CHALLENGE...
); } if (!challenge) { return (
error
{error || 'No active challenge found.'}
); } return (
{/* Workspace Body */}
{/* Info Header */}
{challenge.difficulty} +{challenge.points} PTS {challenge.completed ? ( COMPLETED ) : ( INCOMPLETE )}
TOTAL SCORE: {globalScore}
{/* Description */}

description Problem: {challenge.title}

{challenge.description}

{/* Code Editor */}
code Write Python Solution: