/** 방: 대기실 ↔ 게임 ↔ 결과를 한 주소에서 전환 (docs/06 §5–§9). */ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react'; import { Link, useNavigate, useParams } from 'react-router'; import { BOT_BANDS, BOT_PICKS, BOT_PICK_LABEL, bandOf, botChatRequired, botsAllowed, formatRoomCode, isBotId, luckLabel, type PublicUser, type RoomView } from '@bg/shared/lite'; import { Avatar, CodeLabel, ConfirmSheet, CopyButton, ShareButton, Sheet, TopBar } from '../components/ui'; import { GuestWarning, NicknameForm } from '../components/NicknameForm'; import { GameNotice, gameName } from '../components/GameNotice'; import { QrModal } from '../components/QrModal'; import { SettingsPopup } from '../components/SettingsPopup'; import { api, type RoomPreview } from '../net/api'; import { socket, useRoom } from '../net/socket'; import { useSession } from '../store/session'; import { OptionSync, withLocks } from '../lib/option-sync'; import { loadGameUI } from '../games/registry'; import type { GameUI } from '../games/types'; import { sounds, useChatSound } from '../lib/feedback'; import { ChatPanel, EmoteBubbles, useChatSeen } from '../components/ChatPanel'; import { BotActivity } from '../components/BotActivity'; import { VolumeControl } from '../components/VolumeControl'; import { useWide } from '../lib/media'; import { GameHelp } from '../components/GameHelp'; import { PlayerName } from '../components/PlayerCard'; import { useMotionScope } from '../lib/motion'; export default function RoomPage() { const { code = '' } = useParams(); const me = useSession((s) => s.me); const nav = useNavigate(); const [preview, setPreview] = useState(null); const [previewError, setPreviewError] = useState(null); useEffect(() => { if (!/^\d{6}$/.test(code)) { setPreviewError('방 코드가 올바르지 않아요.'); return; } if (!me) api.room(code).then(setPreview, (e) => setPreviewError((e as Error).message)); }, [code, me]); useEffect(() => { if (!me || !/^\d{6}$/.test(code)) return; socket.join(code); return () => socket.detach(code); }, [code, me]); if (!me) { return ( <> nav('/')} />
{previewError ? ( ) : (
{preview ? ( <>

{gameName(preview.gameId)} 방에 초대받았어요

방장 {preview.host} · {preview.seated}/{preview.maxPlayers}명 · 코드 {preview.codeLabel}

) : (

방 정보를 불러오는 중…

)}
)}
); } return ; } function RoomGone({ message }: { message: string }) { const nav = useNavigate(); return (

{message}

); } function Room({ code, me }: { code: string; me: PublicUser }) { const nav = useNavigate(); const { room, game, result, status, joinError, pending, slow } = useRoom(); const [ui, setUi] = useState(null); const [leaveAsk, setLeaveAsk] = useState(false); const [chatOpen, setChatOpen] = useState(false); // Under 1100px there is no chat column (Lobby/GameView), so the bar carries a 💬 button — phones and narrowed PC windows alike. const wide = useWide(); // 설정 opens as a popup over the room: going to /me would unmount the room and detach from it. const [settingsOpen, setSettingsOpen] = useState(false); const closeSettings = useCallback(() => setSettingsOpen(false), []); // 규칙 too: going to /rules would leave the room page (and, alone in a lobby, the room itself). const [rulesOpen, setRulesOpen] = useState(false); // [한 판 더] takes me back to this room's lobby after game N (kept per tab so a reload stays there). const lobbyKey = `bg:lobby:${code}`; const [lobbyAfter, setLobbyAfter] = useState(() => Number(sessionStorage.getItem(lobbyKey)) || null); const gameId = room?.gameId; useEffect(() => { if (gameId) loadGameUI(gameId).then(setUi); }, [gameId]); const players = useMemo(() => { const map: Record = {}; for (const s of room?.seats ?? []) if (s) map[s.user.id] = s.user; for (const u of room?.spectators ?? []) map[u.id] = u; return map; }, [room]); useTurnTitle(ui, game?.view, me.id); // Every new room chat line (mine too, like StarCraft) plays the chat sound; history resent on joining does not. const lastLiveChat = useRoom((s) => { const l = s.chat.at(-1); return l?.live ? l.id : undefined; }); useChatSound(lastLiveChat); // Inside a room the room bar replaces the site header, so the board gets that height back. useEffect(() => { document.documentElement.classList.add('in-room'); return () => document.documentElement.classList.remove('in-room'); }, []); if (status === 'replaced') { return (

다른 창에서 이 방을 열었어요

한 번에 한 창에서만 할 수 있어요.

); } if (joinError) { return ( <> nav('/')} />
); } if (!room || room.code !== code || !ui) { return ( <> nav('/')} />
방에 들어가는 중…
); } const g = { nameKo: gameName(room.gameId) }; const backInLobby = room.status === 'finished' && lobbyAfter === room.gameNo; const inGame = room.status === 'playing' || room.status === 'paused' || (room.status === 'finished' && !!game && !backInLobby); const toLobby = () => { sessionStorage.setItem(lobbyKey, String(room.gameNo)); setLobbyAfter(room.gameNo); // Seated people come back ready, so the host sees who wants another game. const seat = room.seats.find((s) => s?.user.id === me.id); if (seat && room.hostId !== me.id && !seat.ready) socket.send({ t: 'ready', ready: true }); }; // Games with their own chat channels (마피아) close the room chat while playing (the server refuses it too). const roomChatClosed = !!ui.ownChat && (room.status === 'playing' || room.status === 'paused'); const doLeave = () => { socket.leave(); nav('/'); }; // Leaving mid-game forfeits, so only that case asks first; otherwise one tap leaves. const forfeits = room.status === 'playing' && room.seats.some((s) => s?.user.id === me.id); const askLeave = () => (forfeits ? setLeaveAsk(true) : doLeave()); return ( <> {inGame && game ? ( ) : ( )} {room.status === 'finished' && result && game && !backInLobby && } {chatOpen && !roomChatClosed && !wide && ( setChatOpen(false)} label="채팅"> )} {settingsOpen && } {rulesOpen && ( setRulesOpen(false)} label={`${gameName(room.gameId)} 규칙`}>

{gameName(room.gameId)} 규칙

{ui ? :

불러오는 중…

}
)} {leaveAsk && ( setLeaveAsk(false)} /> )} ); } /** Blink the tab title when it's my turn and the tab is hidden (docs/07 §6). */ function useTurnTitle(ui: GameUI | null, view: unknown, me: string) { const myTurn = !!ui && !!view && ui.isMyTurn(view, me); const prev = useRef(false); useEffect(() => { if (myTurn && !prev.current && document.visibilityState === 'hidden') sounds.myTurn(); prev.current = myTurn; if (!myTurn) return; const base = document.title; let on = false; const t = setInterval(() => { if (document.visibilityState === 'visible') { document.title = base; return; } on = !on; document.title = on ? '● 내 차례예요' : base; }, 1000); return () => { clearInterval(t); document.title = base; }; }, [myTurn]); } // ---------------------------------------------------------------- lobby function Lobby({ room, ui, me }: { room: RoomView; ui: GameUI; me: PublicUser }) { const [qr, setQr] = useState(false); const [settings, setSettings] = useState(false); const isHost = room.hostId === me.id; const mySeat = room.seats.findIndex((s) => s?.user.id === me.id); const seated = room.seats.filter(Boolean).length; const need = Math.max(0, room.minPlayers - seated); const url = `${location.origin}/r/${room.code}`; const gName = gameName(room.gameId); const host = room.seats.find((s) => s?.user.id === room.hostId)?.user.nickname ?? me.nickname; const shareText = `${host}님이 ${gName} 방에 초대했어요! 코드 ${formatRoomCode(room.code)}`; const notReady = room.seats.filter((s) => s && !s.ready && s.user.id !== room.hostId).length; const [askStart, setAskStart] = useState(false); // Computer players (docs/06 §12): the host fills empty seats; a room with them is a practice room. const canAddBot = isHost && botsAllowed(room.gameId); const practice = room.seats.some((s) => s && isBotId(s.user.id)); // Offered on the first empty seat only, so big rooms don't show a column of the same button. const firstEmpty = room.seats.findIndex((s) => s === null); const wide = useWide(); // Only while a seat is empty: once everyone is in, the room bar's link button is enough. const invite = firstEmpty >= 0 && (

친구에게 이 코드를 알려 주세요

{/* QR lives on the empty seat button ("+ 빈자리 · QR로 초대"), so this row stays two buttons. */}
); const seats = (

자리 ({seated}/{room.maxPlayers})

{/* PC: seats are the main column of the lobby, two or three cards per row. */}
4 ? 3 : 2}, minmax(0, 1fr))` : '1fr', gap: 10 }}> {room.seats.map((s, i) => s && isBotId(s.user.id) ? (
{s.user.nickname}
🤖 컴퓨터 {!isHost && 난이도 {BOT_PICK_LABEL[room.botPicks?.[s.user.id] ?? 'random']}}
{isHost && ( )}
{/* docs/06 §12: 랜덤 = any level 1~60; a band = a random level inside it. The level shows after the game. */} {isHost && (
{BOT_PICKS.map((p) => ( ))}
)}
) : s ? (
{room.hostId === s.user.id && 👑 } {s.user.id === me.id && (나)}
{s.connected ? '접속 중' : s.away ? '자리 비움' : '연결 끊김'} {room.hostId !== s.user.id && (s.ready ? 준비 완료 : 준비 중)}
{isHost && s.user.id !== me.id && }
) : (
{canAddBot && i === firstEmpty && !wide && ( )}
), )}
{room.spectators.length > 0 && (

관전 {room.spectators.length}명:{' '} {room.spectators.map((u, i) => ( {i > 0 && ', '} ))}

)} {((wide && canAddBot && firstEmpty >= 0) || (mySeat >= 0 && room.allowSpectators)) && (
{wide && canAddBot && firstEmpty >= 0 && ( )} {mySeat >= 0 && room.allowSpectators && ( )}
)}
); const settingsCard = (

게임 설정

{ui.optionsSummary(room.options)}

{!wide && ( )}
{!isHost &&

👑 설정은 방장만 바꿀 수 있어요. 여기서는 볼 수만 있어요.

} {practice &&

🤖 연습 게임이에요. 기록에는 남지 않아요.

} {room.lockedOptions.length > 0 &&

🔒 일부 규칙은 관리자가 정해 두어서 바꿀 수 없어요.

} {wide && }
); const guestLine = me.kind === 'guest' && !practice && ; const action = (
{isHost ? ( ) : mySeat >= 0 ? ( room.seats[mySeat]!.ready ? ( ) : ( ) ) : ( )}
); return (
{/* PC: invite → seats → start → chat down the main column (the people), game settings on the side. */}
{invite} {seats} {wide ? action : settingsCard} {wide && guestLine} {wide && }
{wide ? settingsCard : action} {!wide && guestLine}
{qr && setQr(false)} />} {settings && setSettings(false)} />} {askStart && ( socket.send({ t: 'start' })} onClose={() => setAskStart(false)} /> )}
); } function HostMenu({ room, target }: { room: RoomView; target: PublicUser }) { const [open, setOpen] = useState(false); const [kick, setKick] = useState(false); void room; return ( <> {open && ( setOpen(false)} label={`${target.nickname} 관리`}>

{target.nickname}

)} {kick && ( socket.send({ t: 'kick', userId: target.id })} onClose={() => setKick(false)} /> )} ); } function SettingsSheet({ room, ui, readOnly, onClose }: { room: RoomView; ui: GameUI; readOnly: boolean; onClose: () => void }) { return (

게임 설정

{readOnly &&

👑 설정은 방장만 바꿀 수 있어요.

}
); } /** * Game options + room options. Inline on PC, in a sheet on narrow screens. * Host: every change is sent right away, so [게임 시작] always uses what is on screen. * Everyone else (`readOnly`): the same form showing the room's current options, with every control locked * (only "▼ 자세한 설정" still opens, so the hidden rules can be read too). The server refuses non-host config anyway. */ function SettingsForm({ room, ui, inline, readOnly, onDone }: { room: RoomView; ui: GameUI; inline?: boolean; readOnly?: boolean; onDone?: () => void }) { const [options, setOptions] = useState(room.options); const sync = useRef(new OptionSync()); useEffect(() => { if (sync.current.received(room.options)) setOptions(room.options); }, [room.options]); const changeOptions = (next: typeof options) => { // Admin-locked rules keep the room's value, exactly as the server will (so the echo matches). const out = withLocks(next, room.options, room.lockedOptions); sync.current.sent(room.options, out); setOptions(out); socket.send({ t: 'config', options: out }); }; const seg = (value: boolean, set: (v: boolean) => void, on: string, off: string) => (
); return (
{!readOnly && room.lockedOptions.length > 0 &&

🔒 관리자가 고정한 규칙은 바꿔도 저장되지 않아요.

} {readOnly ? ( {}} /> ) : ( )}
관전 {readOnly ? {seg(room.allowSpectators, () => {}, '허용', '안 됨')} : seg(room.allowSpectators, (allowSpectators) => socket.send({ t: 'config', allowSpectators }), '허용', '안 됨')}
채팅 {readOnly ? {seg(room.chatEnabled, () => {}, '켜기', '끄기')} : seg(room.chatEnabled, (chatEnabled) => socket.send({ t: 'config', chatEnabled }), '켜기', '끄기')}
{botsAllowed(room.gameId) && (
컴퓨터 채팅 {botChatRequired(room.gameId) ? (

항상 켜짐 · 이 게임은 컴퓨터도 말해야 할 수 있어요

) : readOnly ? ( {seg(room.botChat, () => {}, '켜기', '끄기')} ) : ( seg(room.botChat, (botChat) => socket.send({ t: 'config', botChat }), '켜기', '끄기') )} {!botChatRequired(room.gameId) && 켜면 컴퓨터가 게임하면서 먼저 말을 걸고, 채팅에 대답해요.}
)}
{!inline && ( )}
); } /** * Locks every control inside (each game's options form has its own buttons, selects and inputs), except * disclosure toggles (`aria-expanded`, e.g. "▼ 자세한 설정") so hidden rules can still be opened and read. * Re-locks whatever the form renders later (opening "자세한 설정" adds new controls). */ function ReadOnlyControls({ children }: { children: ReactNode }) { const ref = useRef(null); useLayoutEffect(() => { const root = ref.current!; const lock = () => { root.querySelectorAll('button:not([aria-expanded]), input, select, textarea').forEach((el) => { if (!el.disabled) el.disabled = true; }); }; lock(); const mo = new MutationObserver(lock); mo.observe(root, { childList: true, subtree: true, attributes: true, attributeFilter: ['disabled'] }); return () => mo.disconnect(); }, []); return (
{children}
); } // ---------------------------------------------------------------- game function GameView({ room, ui, me, players, pending, slow }: { room: RoomView; ui: GameUI; me: PublicUser; players: Record; pending: boolean; slow: boolean }) { const game = useRoom((s) => s.game)!; const tapConfirm = useSession((s) => s.settings.tapConfirm); const wide = useWide(); const layout = useRef(null); useMotionScope(layout); const myTurn = ui.isMyTurn(game.view, me.id); const isPlayer = room.seats.some((s) => s?.user.id === me.id) && game.active !== undefined; const props = { view: game.view, me: me.id, players, act: (a: unknown) => socket.act(a), pending, deadline: game.deadline, active: game.active, tapConfirm, }; const status = (
{room.status === 'paused' ? '오류로 게임이 멈췄어요. 방장이 끝낼 수 있어요.' : ui.statusText(game.view, me.id, players)} {slow && · 연결 확인 중…} {!isPlayer && ( 관전 중 )}
); // [?] 지금 할 수 있는 것 sits right next to the turn status (docs/07 §5). // The host's way out of a game stopped by an error sits right under the status that explains it. const statusRow = ( <>
{status}
{room.status === 'paused' && room.hostId === me.id && ( )} ); return (
{!wide && statusRow}
); } function ResultPanel({ room, me, players, onLeave, onAgain }: { room: RoomView; me: PublicUser; players: Record; onLeave: () => void; onAgain: () => void }) { const result = useRoom((s) => s.result)!; const [hidden, setHidden] = useState(false); const played = useRef(false); const seatedAll = room.seats.filter(Boolean).map((s) => s!.user.id); const seated = seatedAll.filter((u) => !isBotId(u)); // Solo games (e.g. 요트 다이스) have one ranked player: neither a draw nor a win. const solo = result.ranking.flat().length === 1; const allFirst = !solo && result.ranking.length === 1; const won = !solo && !allFirst && result.ranking[0]?.includes(me.id); const lost = !solo && !allFirst && !won && result.ranking.some((g) => g.includes(me.id)); useEffect(() => { if (played.current) return; played.current = true; if (won) sounds.win(); else if (lost) sounds.lose(); }, [won, lost]); if (hidden) { return (
); } return ( setHidden(true)} label="게임 결과">

{allFirst ? '무승부예요' : won ? '🎉 이겼어요!' : lost ? '아쉽게 졌어요' : '게임이 끝났어요'}

{result.summary}

{seatedAll.length > seated.length &&

🤖 연습 게임이라 기록에는 남지 않아요.

}
{result.ranking.map((group, i) => group.map((u) => (
{i + 1}등 {players[u] && } {players[u] ? : '나간 사람'} {/* Final score of this game, in the game's own words (35점, +1,200칩, 카드 12장). */} {result.scoreText?.[u] && ( {result.scoreText[u]} )} 이 방에서 {room.sessionStats[u]?.wins ?? 0}승 / {room.sessionStats[u]?.played ?? 0}판
)), )}
{/* Back to this room's lobby: seats, computers and settings can change before the host starts again. */} {/* One primary action (한 판 더); the rest share one quieter row. */}
{room.lastGamePk && result.ranking.some((g) => g.includes(me.id)) && ( ▶ 다시 보기 )}
{room.lastSeed && ( )}
); } /** * docs/04 §5: the seed's SHA-256 was published when the game started; the seed is revealed at the end. * The browser recomputes the hash itself so players don't have to trust the server's word. */ function FairnessCheck({ seedHash, seed, bots, shuffles, players, }: { seedHash: string | null; seed: string; bots?: RoomView['lastBots']; shuffles?: number; players: Record; }) { const [verdict, setVerdict] = useState(null); const check = async () => { const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(seed)); const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join(''); setVerdict(hex === seedHash); }; return (
공정성 확인 {/* docs/09 §9.1: each computer's level (1~60) and luck in this game; docs/04 §5.1: shuffles tried for luck. */} {bots && Object.keys(bots).length > 0 && (
{Object.entries(bots).map(([id, b]) => (

🤖 {players[id]?.nickname ?? '컴퓨터'}: 난이도 {b.level}단계 ({BOT_PICK_LABEL[bandOf(b.level)]}) · 운 {luckLabel(b.luck)}

))} {(shuffles ?? 1) > 1 &&

이번 판은 컴퓨터의 운에 맞춰, 미리 섞어 본 {shuffles}가지 중 하나로 시작했어요. 고른 결과는 시작할 때 아래 값으로 공개했어요.

}
)}

시작할 때 공개한 값(SHA-256): {seedHash ?? '-'}

끝나고 공개한 난수 씨앗: {seed}

{verdict !== null && (

{verdict ? '✓ 일치해요. 게임 도중 카드 순서나 난수가 바뀌지 않았어요.' : '✗ 일치하지 않아요. 관리자에게 알려 주세요.'}

)}
); } // ---------------------------------------------------------------- chat function ChatButton({ onOpen }: { onOpen: () => void }) { const seen = useChatSeen((s) => s.seen); const unread = useRoom((s) => s.chat.filter((m) => m.id > seen).length); return ( ); }