(
@@ -958,6 +1076,83 @@ const OnlineDebateRoom = (): JSX.Element => {
return false;
}, [roomId, currentUser, setRoomOwnerId]);
+ const handleRematch = useCallback(async () => {
+ if (!roomId) return;
+
+ try {
+ const token = getAuthToken();
+ const response = await fetch(`${BASE_URL}/rooms/${roomId}/rematch`, {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ });
+
+ let data: { id?: string; inviteToken?: string; error?: string } = {};
+ try {
+ data = await response.json();
+ } catch {
+ setJoinError("Failed to create rematch room");
+ return;
+ }
+
+ if (response.ok && data.id && data.inviteToken) {
+ navigate(`/debate-room/${data.id}?invite=${data.inviteToken}`);
+ return;
+ }
+
+ setJoinError(data.error || "Failed to create rematch room");
+ } catch {
+ setJoinError("Failed to create rematch room");
+ }
+ }, [roomId, navigate]);
+
+ useEffect(() => {
+ const joinChallengeRoom = async () => {
+ if (!roomId || !currentUserId) return;
+
+ const joinKey = `${roomId}:${inviteToken ?? ""}:${currentUserId}`;
+ if (joinAttemptedRef.current === joinKey) return;
+ joinAttemptedRef.current = joinKey;
+
+ try {
+ const token = getAuthToken();
+ const body: { inviteToken?: string } = {};
+ if (inviteToken) {
+ body.inviteToken = inviteToken;
+ }
+
+ const response = await fetch(`${BASE_URL}/rooms/${roomId}/join`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${token}`,
+ },
+ body: JSON.stringify(body),
+ });
+
+ if (response.ok) {
+ const room = await response.json();
+ if (room.inviteToken) {
+ setIsChallengeRoom(true);
+ }
+ if (room.topic) {
+ setTopic((current) => current || room.topic);
+ }
+ } else if (inviteToken) {
+ const data = await response.json();
+ setJoinError(data.error || "Failed to join challenge room");
+ }
+ } catch {
+ if (inviteToken) {
+ setJoinError("Failed to join challenge room");
+ }
+ }
+ };
+
+ joinChallengeRoom();
+ }, [roomId, currentUserId, inviteToken]);
+
// Function to fetch room participants
const fetchRoomParticipants = useCallback(
async (retryCount = 0, background = false) => {
@@ -1212,13 +1407,27 @@ const OnlineDebateRoom = (): JSX.Element => {
const data: WSMessage = JSON.parse(event.data);
switch (data.type) {
case "topicChange":
- if (data.topic !== undefined) setTopic(data.topic);
+ if (data.topic !== undefined) {
+ setTopic((current) => current || data.topic || "");
+ }
break;
case "roleSelection":
- if (data.role) setPeerRole(data.role);
+ if (data.role === "for" || data.role === "against") {
+ if (data.userId === currentUserIdRef.current) {
+ setLocalRole(data.role);
+ } else {
+ setPeerRole(data.role);
+ }
+ }
break;
case "ready":
- if (data.ready !== undefined) setPeerReady(data.ready);
+ if (data.ready !== undefined) {
+ if (data.userId === currentUserIdRef.current) {
+ setLocalReady(data.ready);
+ } else {
+ setPeerReady(data.ready);
+ }
+ }
break;
case "roleSelectionRejected":
if (data.role) {
@@ -1329,6 +1538,7 @@ const OnlineDebateRoom = (): JSX.Element => {
data.roomParticipants
);
setRoomParticipants(data.roomParticipants);
+ applyParticipantRoles(data.roomParticipants);
// Update local and opponent user details when participants change
const activeUser = currentUserRef.current;
if (activeUser && data.roomParticipants.length >= 1) {
@@ -1421,10 +1631,22 @@ const OnlineDebateRoom = (): JSX.Element => {
break;
}
if (pcRef.current && data.offer) {
- await pcRef.current.setRemoteDescription(data.offer!);
- const answer = await pcRef.current.createAnswer();
- await pcRef.current.setLocalDescription(answer);
- wsRef.current?.send(JSON.stringify({ type: "answer", answer }));
+ try {
+ const pc = pcRef.current;
+ if (pc.signalingState === "have-local-offer") {
+ if (shouldCreateDebateOffer()) {
+ break;
+ }
+ await pc.setLocalDescription({ type: "rollback" });
+ }
+ await pc.setRemoteDescription(data.offer);
+ await flushPeerCandidates(pc);
+ const answer = await pc.createAnswer();
+ await pc.setLocalDescription(answer);
+ wsRef.current?.send(JSON.stringify({ type: "answer", answer }));
+ } catch (error) {
+ console.error("Failed to handle debate offer:", error);
+ }
}
break;
case "answer":
@@ -1464,7 +1686,13 @@ const OnlineDebateRoom = (): JSX.Element => {
) {
// Spectator answer meant for the other debater; ignore.
} else if (pcRef.current && data.answer) {
- await pcRef.current.setRemoteDescription(data.answer);
+ try {
+ const pc = pcRef.current;
+ await pc.setRemoteDescription(data.answer);
+ await flushPeerCandidates(pc);
+ } catch (error) {
+ console.error("Failed to handle debate answer:", error);
+ }
}
break;
case "candidate":
@@ -1497,7 +1725,16 @@ const OnlineDebateRoom = (): JSX.Element => {
}
}
} else if (pcRef.current && data.candidate) {
- await pcRef.current.addIceCandidate(data.candidate);
+ try {
+ const pc = pcRef.current;
+ if (pc.remoteDescription?.type) {
+ await pc.addIceCandidate(data.candidate);
+ } else {
+ pendingPeerCandidatesRef.current.push(data.candidate);
+ }
+ } catch (error) {
+ console.error("Failed to add ICE candidate:", error);
+ }
}
break;
}
@@ -1517,7 +1754,16 @@ const OnlineDebateRoom = (): JSX.Element => {
};
pc.ontrack = (event) => {
- setRemoteStream(event.streams[0]);
+ const [stream] = event.streams;
+ if (stream) {
+ setRemoteStream(stream);
+ }
+ };
+
+ pc.onconnectionstatechange = () => {
+ if (pc.connectionState === "failed") {
+ void establishDebateConnectionRef.current();
+ }
};
const getMedia = async () => {
@@ -1595,6 +1841,20 @@ const OnlineDebateRoom = (): JSX.Element => {
flushSpectatorOfferQueue();
}, [flushSpectatorOfferQueue]);
+ useEffect(() => {
+ if (roomParticipants.length < 2 || !localStream) return;
+ void establishDebateConnection();
+ }, [
+ roomParticipants.length,
+ localStream,
+ localRole,
+ peerRole,
+ opponentUser?.id,
+ localReady,
+ peerReady,
+ establishDebateConnection,
+ ]);
+
// Attach streams to video elements
useEffect(() => {
if (localVideoRef.current && localStream) {
@@ -2147,7 +2407,11 @@ const OnlineDebateRoom = (): JSX.Element => {
return;
}
setLocalRole(role);
- const message = JSON.stringify({ type: "roleSelection", role });
+ const message = JSON.stringify({
+ type: "roleSelection",
+ role,
+ userId: currentUserIdRef.current,
+ });
wsRef.current?.send(message);
};
@@ -2163,6 +2427,16 @@ const OnlineDebateRoom = (): JSX.Element => {
const newReadyState = !localReady;
socket.send(JSON.stringify({ type: "ready", ready: newReadyState }));
setLocalReady(newReadyState);
+
+ wsRef.current?.send(
+ JSON.stringify({
+ type: "ready",
+ ready: newReadyState,
+ userId: currentUserIdRef.current,
+ })
+ );
+
+
};
// Manage setup popup visibility
@@ -2181,6 +2455,19 @@ const OnlineDebateRoom = (): JSX.Element => {
if (countdown !== null && countdown > 0) {
const timer = setTimeout(() => setCountdown(countdown - 1), 1000);
return () => clearTimeout(timer);
+
+ } else if (countdown === 0) {
+ setDebatePhase(DebatePhase.OpeningFor);
+ wsRef.current?.send(
+ JSON.stringify({ type: "phaseChange", phase: DebatePhase.OpeningFor })
+ );
+ console.debug(
+ `Countdown finished. Starting debate at ${DebatePhase.OpeningFor} for ${localRole}`
+ );
+ void establishDebateConnection();
+ }
+ }, [countdown, localRole, establishDebateConnection]);
+
} else if (countdown === 0 && debatePhase === DebatePhase.Setup) {
if (localRole === "for") {
wsRef.current?.send(
@@ -2201,6 +2488,7 @@ const OnlineDebateRoom = (): JSX.Element => {
}
}, [countdown, debatePhase, localRole]);
+
// Clear input fields on phase change
useEffect(() => {
// Clear any audio-related state if needed
@@ -2248,6 +2536,23 @@ const OnlineDebateRoom = (): JSX.Element => {
);
}
+
+ if (joinError) {
+ return (
+
+
+
{joinError}
+
+
+
+ );
+ }
+
const handleCopyRoomId = async () => {
if (!roomId) return;
@@ -2268,6 +2573,7 @@ const OnlineDebateRoom = (): JSX.Element => {
}
};
+
// Render UI
return (
@@ -2609,11 +2915,17 @@ const OnlineDebateRoom = (): JSX.Element => {
}
opponentAvatarUrl={opponentUser?.avatarUrl || null}
ratingSummary={ratingSummary}
+
+ showRematch={isChallengeRoom}
+ onRematch={handleRematch}
+ onClose={() => setShowJudgment(false)}
+
topic={topic}
onClose={() => {
setShowJudgment(false);
navigate("/startDebate");
}}
+
/>
)}
diff --git a/frontend/src/Pages/Profile.tsx b/frontend/src/Pages/Profile.tsx
index ae8d71b5..e7e36a20 100644
--- a/frontend/src/Pages/Profile.tsx
+++ b/frontend/src/Pages/Profile.tsx
@@ -50,6 +50,7 @@ import {
Image as ImageIcon,
ChevronRight,
Flame,
+ Swords,
} from "lucide-react";
import { FaTrophy, FaMedal, FaAward } from "react-icons/fa";
import { format, isSameDay, subDays } from "date-fns";
@@ -79,6 +80,7 @@ import { getAuthToken } from "@/utils/auth";
import { useNavigate } from "react-router-dom";
import { DateRange } from "react-day-picker";
import AvatarModal from "../components/AvatarModal";
+import ChallengeModal from "../components/ChallengeModal";
import SavedTranscripts from "../components/SavedTranscripts";
import ProfileHover from "../components/ProfileHover";
import { useUser } from "../hooks/useUser";
@@ -169,6 +171,7 @@ const Profile: React.FC = () => {
"7days" | "30days" | "all" | "custom"
>("all");
const [isAvatarModalOpen, setIsAvatarModalOpen] = useState(false);
+ const [showChallengeModal, setShowChallengeModal] = useState(false);
const [debateStatsLoading, setDebateStatsLoading] = useState(true);
const [usernameStatus, setUsernameStatus] = useState<
"idle" | "checking" | "available" | "taken"
@@ -844,6 +847,14 @@ const Profile: React.FC = () => {
Streak: {profile.currentStreak} days
)}
+
@@ -1231,6 +1242,9 @@ const Profile: React.FC = () => {
)}
+ {showChallengeModal && (
+ setShowChallengeModal(false)} />
+ )}
);
};
diff --git a/frontend/src/components/ChallengeModal.tsx b/frontend/src/components/ChallengeModal.tsx
new file mode 100644
index 00000000..c7e44a03
--- /dev/null
+++ b/frontend/src/components/ChallengeModal.tsx
@@ -0,0 +1,186 @@
+import React, { useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+import { X, Copy, Check } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import { getAuthToken } from '@/utils/auth';
+import { useUser } from '@/hooks/useUser';
+
+interface ChallengeModalProps {
+ onClose: () => void;
+}
+
+type ChallengeRoom = {
+ id: string;
+ inviteToken: string;
+ topic: string;
+};
+
+const BASE_URL = import.meta.env.VITE_BASE_URL || 'http://localhost:1313';
+
+const ChallengeModal: React.FC = ({ onClose }) => {
+ const navigate = useNavigate();
+ const { user } = useUser();
+ const [opponentUsername, setOpponentUsername] = useState('');
+ const [topic, setTopic] = useState('');
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState('');
+ const [challenge, setChallenge] = useState(null);
+ const [copied, setCopied] = useState(false);
+ const [copyError, setCopyError] = useState('');
+
+ const inviteLink = challenge
+ ? `${window.location.origin}/debate-room/${challenge.id}?invite=${challenge.inviteToken}`
+ : '';
+
+ const handleCreate = async () => {
+ if (!topic.trim()) {
+ setError('Please enter a debate topic');
+ return;
+ }
+
+ setLoading(true);
+ setError('');
+
+ const trimmedOpponent = opponentUsername.trim();
+ const currentName = user?.displayName?.trim() ?? '';
+ const resolvedOpponent =
+ trimmedOpponent &&
+ currentName &&
+ trimmedOpponent.localeCompare(currentName, undefined, {
+ sensitivity: 'accent',
+ }) === 0
+ ? ''
+ : trimmedOpponent;
+
+ try {
+ const token = getAuthToken();
+ const response = await fetch(`${BASE_URL}/rooms/challenge`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${token}`,
+ },
+ body: JSON.stringify({
+ opponentUsername: resolvedOpponent,
+ topic: topic.trim(),
+ }),
+ });
+
+ const data = await response.json();
+ if (!response.ok) {
+ setError(data.error || 'Failed to create challenge');
+ return;
+ }
+
+ setChallenge({
+ id: data.id,
+ inviteToken: data.inviteToken,
+ topic: data.topic,
+ });
+ } catch {
+ setError('Failed to create challenge');
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const handleCopy = async () => {
+ if (!inviteLink) return;
+ try {
+ await navigator.clipboard.writeText(inviteLink);
+ setCopyError('');
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ } catch {
+ setCopyError('Could not copy link. Please copy it manually from the field above.');
+ }
+ };
+
+ const handleEnterRoom = () => {
+ if (!challenge) return;
+ navigate(`/debate-room/${challenge.id}?invite=${challenge.inviteToken}`);
+ onClose();
+ };
+
+ return (
+
+
+
+
+ {!challenge ? (
+ <>
+
Challenge a Friend
+
+
+
+
setOpponentUsername(e.target.value)}
+ placeholder='e.g. LogicLord (or leave blank)'
+ className='mt-1'
+ />
+
+ Leave blank to share the invite link with anyone.
+
+
+
+
+ setTopic(e.target.value)}
+ placeholder='e.g. Should AI replace teachers?'
+ className='mt-1'
+ />
+
+ {error && (
+
{error}
+ )}
+
+
+ >
+ ) : (
+ <>
+
Challenge Created
+
+ Share this link with your opponent. Topic: {challenge.topic}
+
+
+
+
+
+ {copyError && (
+
{copyError}
+ )}
+
+
+
+
+ >
+ )}
+
+
+ );
+};
+
+export default ChallengeModal;
diff --git a/frontend/src/components/JudgementPopup.tsx b/frontend/src/components/JudgementPopup.tsx
index 28d31b2f..1bfbf928 100644
--- a/frontend/src/components/JudgementPopup.tsx
+++ b/frontend/src/components/JudgementPopup.tsx
@@ -83,7 +83,12 @@ type JudgmentPopupProps = {
opponentDisplayName?: string | null;
opponentAvatarUrl?: string | null;
ratingSummary?: RatingSummary | null;
+
+ showRematch?: boolean;
+ onRematch?: () => void;
+
topic?: string;
+
onClose: () => void;
};
@@ -127,7 +132,12 @@ const JudgmentPopup: React.FC = ({
opponentDisplayName,
opponentAvatarUrl,
ratingSummary,
+
+ showRematch,
+ onRematch,
+
topic,
+
onClose,
}) => {
const navigate = useNavigate();
@@ -753,6 +763,17 @@ const player2RatingSummary =
{/* Buttons */}
+
+
+ {showRematch && onRematch && (
+
+ )}
+
+