"use client"; import { creditTicker } from "@/lib/credits-brand"; import { useState, useEffect } from "react"; import { io, Socket } from "socket.io-client"; const T = creditTicker(); interface Room { id: string; wageBLW: number; creatorId: string; } export function CoinFlipRoom({ userId, balance }: { userId: string; balance: number }) { const [rooms, setRooms] = useState([]); const [wager, setWager] = useState(50); const [phase, setPhase] = useState<"lobby" | "waiting" | "result">("lobby"); const [socket, setSocket] = useState(null); const [result, setResult] = useState<{ resultLabel: string; winnerId: string; payout: number; serverSeed: string } | null>(null); const [myRoomId, setMyRoomId] = useState(null); useEffect(() => { fetchRooms(); }, []); async function fetchRooms() { const r = await fetch("/api/games/rooms?gameType=COIN_FLIP"); if (r.ok) { const d = await r.json(); setRooms(d.rooms); } } function connect(roomId: string) { const s = io("/coin-flip", { path: "/api/socket" }); setSocket(s); s.emit("join_room", { roomId, userId }); s.on("waiting", () => setPhase("waiting")); s.on("game_start", () => setPhase("waiting")); s.on("result", (data) => { setResult(data); setPhase("result"); s.disconnect(); }); s.on("error", (msg: string) => { alert(msg); s.disconnect(); setPhase("lobby"); }); } async function createRoom() { const res = await fetch("/api/games/rooms", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ gameType: "COIN_FLIP", wageBLW: wager }), }); if (!res.ok) { const e = await res.json(); alert(e.error); return; } const { room } = await res.json(); setMyRoomId(room.id); connect(room.id); setPhase("waiting"); } if (phase === "waiting") { return (
🪙

Waiting for opponent…

Room ID: {myRoomId}

Share this with a friend to flip instantly!

); } if (phase === "result" && result) { const won = result.winnerId === userId; return (
{result.resultLabel === "heads" ? "🦅" : "🔵"}

{result.resultLabel.toUpperCase()}

{won ? `You win! +${result.payout} ${T}` : "You lose!"}

Seed: {result.serverSeed}

); } return (

Create a Room

setWager(Math.max(1, parseInt(e.target.value) || 1))} className="w-full rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-white focus:outline-none focus:border-sky-500" />

Open Rooms

{rooms.length === 0 ? (

No open rooms — create one!

) : ( rooms.map(room => (

{room.wageBLW} {T}

{room.id.slice(0, 8)}…

)) )}
); }