File size: 9,154 Bytes
811126d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 |
"use client";
import { useState, useRef } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ArrowLeft, Mic, MicOff } from "lucide-react";
import Link from "next/link";
import { toast } from "@/hooks/use-toast";
import "../styles/background-pattern.css";
export default function CreateGroup() {
const router = useRouter();
const [groupName, setGroupName] = useState("");
const [userName, setUserName] = useState("");
const [isRecording, setIsRecording] = useState(false);
const [audioBlob, setAudioBlob] = useState<Blob | null>(null);
const [isLoading, setIsLoading] = useState(false);
const mediaRecorder = useRef<MediaRecorder | null>(null);
const audioChunks = useRef<Blob[]>([]);
const startRecording = async () => {
try {
console.log("Requesting microphone access...");
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
console.log("Microphone access granted");
mediaRecorder.current = new MediaRecorder(stream);
audioChunks.current = [];
mediaRecorder.current.ondataavailable = (event) => {
console.log("Audio data received");
audioChunks.current.push(event.data);
};
mediaRecorder.current.onstop = () => {
console.log("Recording finished, creating blob");
const audioBlob = new Blob(audioChunks.current, { type: "audio/wav" });
setAudioBlob(audioBlob);
console.log("Audio blob created:", audioBlob.size, "bytes");
};
mediaRecorder.current.start();
setIsRecording(true);
console.log("Recording started");
toast({
title: "Recording Started",
description: "Speak into your microphone...",
});
} catch (error) {
console.error("Error accessing microphone:", error);
toast({
title: "Error",
description: "Could not access microphone. Check your permissions.",
variant: "destructive",
});
}
};
const stopRecording = () => {
if (mediaRecorder.current && isRecording) {
console.log("Stopping recording...");
mediaRecorder.current.stop();
setIsRecording(false);
mediaRecorder.current.stream.getTracks().forEach((track) => track.stop());
toast({
title: "Recording Complete",
description: "Your voice has been recorded successfully.",
});
}
};
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!groupName.trim() || !userName.trim() || !audioBlob) {
toast({
title: "Error",
description: "Please fill in all fields and record your voice",
variant: "destructive",
});
return;
}
setIsLoading(true);
try {
// Create user and upload voice first
const formData = new FormData();
formData.append("audio", audioBlob);
formData.append("name", userName);
const voiceResponse = await fetch("/api/voice", {
method: "POST",
body: formData,
});
if (!voiceResponse.ok) throw new Error("Error uploading voice");
const userData = await voiceResponse.json();
// Save user information in cookies
const expirationDate = new Date();
expirationDate.setDate(expirationDate.getDate() + 30);
document.cookie = `userId=${
userData.id
};expires=${expirationDate.toUTCString()};path=/`;
document.cookie = `userName=${encodeURIComponent(
userName
)};expires=${expirationDate.toUTCString()};path=/`;
// Create group with existing user
console.log("Creating group with:", {
name: groupName,
userId: userData.id,
});
try {
const groupResponse = await fetch("/api/group", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
name: groupName,
userId: userData.id,
}),
});
console.log("Response status:", groupResponse.status);
const responseText = await groupResponse.text();
console.log("Raw response:", responseText);
let groupData;
try {
groupData = JSON.parse(responseText);
console.log("Parsed response:", groupData);
} catch (e) {
console.error("JSON parsing error:", e);
throw new Error("Invalid server response");
}
if (!groupResponse.ok) {
throw new Error(groupData.error || "Error creating group");
}
toast({
title: "Success",
description: "Your game has been created successfully!",
});
// Redirect to group page
router.push(`/group/${groupData.inviteCode}`);
} catch (error) {
console.error("Complete error:", error);
toast({
title: "Error",
description: "An error occurred while creating the group",
variant: "destructive",
});
}
} catch (error) {
console.error("Error:", error);
toast({
title: "Error",
description: "An error occurred while creating the group",
variant: "destructive",
});
} finally {
setIsLoading(false);
}
};
return (
<div className="min-h-screen relative overflow-hidden">
<div className="background-pattern" />
<div className="background-overlay" />
<div className="background-vignette" />
<div className="relative z-10 p-4">
<div className="max-w-md mx-auto bg-gray-100 bg-opacity-90 backdrop-blur-sm rounded-lg shadow-xl p-8">
<div className="flex justify-between items-center mb-8">
<Link href="/">
<Button
variant="outline"
className="border-orange-400 text-orange-600 hover:bg-orange-100"
>
<ArrowLeft className="mr-2 h-4 w-4" />
Back
</Button>
</Link>
<h1 className="text-3xl font-grobold font-normal text-center text-orange-600">
Create Game
</h1>
</div>
<form onSubmit={handleSubmit} className="space-y-6">
<div className="space-y-2">
<label className="text-lg font-grobold font-normal text-orange-600">
Game Name
</label>
<Input
type="text"
value={groupName}
onChange={(e) => setGroupName(e.target.value)}
className="bg-orange-50 text-orange-800 placeholder-orange-300 border-orange-200 focus:border-orange-400 focus:ring-orange-400"
placeholder="Enter game name"
required
/>
</div>
<div className="space-y-2">
<label className="text-lg font-grobold font-normal text-orange-600">
Your Username
</label>
<Input
type="text"
value={userName}
onChange={(e) => setUserName(e.target.value)}
className="bg-orange-50 text-orange-800 placeholder-orange-300 border-orange-200 focus:border-orange-400 focus:ring-orange-400"
placeholder="Enter your username"
required
/>
</div>
<div className="space-y-2">
<label className="text-lg font-grobold font-normal text-orange-600">
Your Voice
</label>
<div className="flex items-center space-x-4">
<Button
type="button"
onClick={isRecording ? stopRecording : startRecording}
className={`flex-1 py-6 ${
isRecording
? "bg-red-500 hover:bg-red-600"
: "bg-orange-500 hover:bg-orange-600"
} text-white`}
>
{isRecording ? (
<>
<MicOff className="mr-2 h-5 w-5" />
Stop
</>
) : (
<>
<Mic className="mr-2 h-5 w-5" />
Record
</>
)}
</Button>
</div>
{audioBlob && !isRecording && (
<div className="text-green-600 font-medium text-center mt-2">
✓ Voice recorded
</div>
)}
</div>
<Button
type="submit"
disabled={isLoading || !audioBlob}
className={`w-full py-6 text-lg font-grobold font-normal ${
isLoading || !audioBlob
? "bg-gray-400"
: "bg-green-500 hover:bg-green-600"
} text-white`}
>
{isLoading ? "Creating..." : "Create Game"}
</Button>
</form>
</div>
</div>
</div>
);
}
|