import React, { useState, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import { useAuth } from 'react-oidc-context'; import { motion } from 'framer-motion'; import { BrainCircuit, Play, Loader2, BookmarkPlus, ChevronDown, ChevronUp, AlertCircle, LogIn } from 'lucide-react'; import toast from 'react-hot-toast'; import type { Quiz, Question, GameConfig } from '../types'; import { useAuthenticatedFetch } from '../hooks/useAuthenticatedFetch'; const BACKEND_URL = import.meta.env.VITE_BACKEND_URL || 'http://localhost:3001'; interface SharedQuizData { title: string; source: 'manual' | 'ai_generated'; aiTopic?: string; gameConfig: GameConfig | null; questions: Question[]; questionCount: number; sharedBy?: string | null; } interface SharedQuizViewProps { onHostQuiz: (quiz: Quiz) => void; shareToken: string; } export const SharedQuizView: React.FC = ({ onHostQuiz, shareToken }) => { const token = shareToken; const navigate = useNavigate(); const auth = useAuth(); const { authFetch } = useAuthenticatedFetch(); const [quizData, setQuizData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [saving, setSaving] = useState(false); const [showQuestions, setShowQuestions] = useState(false); useEffect(() => { const fetchSharedQuiz = async () => { if (!token) { setError('Invalid share link'); setLoading(false); return; } try { const response = await fetch(`${BACKEND_URL}/api/shared/${token}`); if (!response.ok) { if (response.status === 404) { setError('This quiz is no longer available'); } else { setError('Failed to load quiz'); } setLoading(false); return; } const data = await response.json(); setQuizData(data); } catch { setError('Failed to load quiz'); } finally { setLoading(false); } }; fetchSharedQuiz(); }, [token]); const handleHost = () => { if (!quizData) return; const quiz: Quiz = { title: quizData.title, questions: quizData.questions, config: quizData.gameConfig || undefined, }; onHostQuiz(quiz); }; const handleSaveToLibrary = async () => { if (!token || !auth.isAuthenticated) return; setSaving(true); try { const response = await authFetch(`/api/shared/${token}/copy`, { method: 'POST', }); if (!response.ok) { throw new Error('Failed to save quiz'); } const data = await response.json(); toast.success(`"${data.title}" saved to your library!`); } catch { toast.error('Failed to save quiz to library'); } finally { setSaving(false); } }; if (loading) { return (

Loading shared quiz...

); } if (error || !quizData) { return (

Quiz Not Found

{error || 'This quiz is no longer available'}

); } return (

{quizData.sharedBy ? `Shared by ${quizData.sharedBy}` : 'Shared Quiz'}

{quizData.title}

{quizData.questionCount} question{quizData.questionCount !== 1 ? 's' : ''} {quizData.aiTopic && • {quizData.aiTopic}}

{auth.isAuthenticated ? ( ) : ( )}
{showQuestions && ( {quizData.questions.map((q, i) => (

Question {i + 1}

{q.text}

))}
)}
); };