All files / web/src/app/arcade-rooms page.tsx

0% Statements 0/573
0% Branches 0/1
0% Functions 0/1
0% Lines 0/573

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { css } from '../../../styled-system/css'
import { useToast } from '@/components/common/ToastContext'
import { PageWithNav } from '@/components/PageWithNav'
import { getRoomDisplayWithEmoji } from '@/utils/room-display'

interface Room {
  id: string
  code: string
  name: string | null
  gameName: string
  status: 'lobby' | 'playing' | 'finished'
  createdAt: Date
  creatorName: string
  isLocked: boolean
  accessMode: 'open' | 'password' | 'approval-only' | 'restricted' | 'locked' | 'retired'
  memberCount?: number
  playerCount?: number
  isMember?: boolean
}

export default function RoomBrowserPage() {
  const router = useRouter()
  const { showError, showInfo } = useToast()
  const [rooms, setRooms] = useState<Room[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [showCreateModal, setShowCreateModal] = useState(false)

  useEffect(() => {
    fetchRooms()
  }, [])

  const fetchRooms = async () => {
    try {
      setLoading(true)
      const response = await fetch('/api/arcade/rooms')
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`)
      }
      const data = await response.json()
      setRooms(data.rooms)
      setError(null)
    } catch (err) {
      console.error('Failed to fetch rooms:', err)
      setError('Failed to load rooms')
    } finally {
      setLoading(false)
    }
  }

  const createRoom = async (name: string | null, gameName: string) => {
    try {
      const response = await fetch('/api/arcade/rooms', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name,
          gameName,
          creatorName: 'Player',
          gameConfig: { difficulty: 6 },
        }),
      })

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`)
      }

      const data = await response.json()
      router.push(`/join/${data.room.code}`)
    } catch (err) {
      console.error('Failed to create room:', err)
      showError('Failed to create room', err instanceof Error ? err.message : undefined)
    }
  }

  const joinRoom = async (room: Room) => {
    try {
      // Check access mode
      if (room.accessMode === 'password') {
        const password = prompt(`Enter password for ${room.name || `Room ${room.code}`}:`)
        if (!password) return // User cancelled

        const response = await fetch(`/api/arcade/rooms/${room.id}/join`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ displayName: 'Player', password }),
        })

        if (!response.ok) {
          const errorData = await response.json()
          showError('Failed to join room', errorData.error)
          return
        }

        router.push(`/arcade-rooms/${room.id}`)
        return
      }

      if (room.accessMode === 'approval-only') {
        showInfo(
          'Approval Required',
          'This room requires host approval. Please use the Join Room modal to request access.'
        )
        return
      }

      if (room.accessMode === 'restricted') {
        showInfo(
          'Invitation Only',
          'This room is invitation-only. Please ask the host for an invitation.'
        )
        return
      }

      // For open rooms
      const response = await fetch(`/api/arcade/rooms/${room.id}/join`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ displayName: 'Player' }),
      })

      if (!response.ok) {
        const errorData = await response.json()

        // Handle specific room membership conflict
        if (errorData.code === 'ROOM_MEMBERSHIP_CONFLICT') {
          showError('Already in Another Room', errorData.userMessage || errorData.message)
          // Refresh the page to update room list state
          await fetchRooms()
          return
        }

        throw new Error(errorData.error || `HTTP ${response.status}`)
      }

      const data = await response.json()

      // Show notification if user was auto-removed from other rooms
      if (data.autoLeave) {
        console.log(`[Room Join] ${data.autoLeave.message}`)
        // Could show a toast notification here in the future
      }

      router.push(`/arcade-rooms/${room.id}`)
    } catch (err) {
      console.error('Failed to join room:', err)
      showError('Failed to join room', err instanceof Error ? err.message : undefined)
    }
  }

  return (
    <PageWithNav>
      <div
        className={css({
          minH: 'calc(100vh - 80px)',
          bg: 'linear-gradient(135deg, #0f0f23 0%, #1a1a3a 50%, #2d1b69 100%)',
          p: '8',
        })}
      >
        <div className={css({ maxW: '1200px', mx: 'auto' })}>
          {/* Header */}
          <div className={css({ mb: '8', textAlign: 'center' })}>
            <h1
              className={css({
                fontSize: '4xl',
                fontWeight: 'bold',
                color: 'white',
                mb: '4',
              })}
            >
              🎮 Multiplayer Rooms
            </h1>
            <p className={css({ color: '#a0a0ff', fontSize: 'lg', mb: '6' })}>
              Join a room or create your own to play with friends
            </p>
            <button
              onClick={() => setShowCreateModal(true)}
              className={css({
                px: '6',
                py: '3',
                bg: '#10b981',
                color: 'white',
                rounded: 'lg',
                fontSize: 'lg',
                fontWeight: 600,
                cursor: 'pointer',
                _hover: { bg: '#059669' },
                transition: 'all 0.2s',
              })}
            >
              + Create New Room
            </button>
          </div>

          {/* Room List */}
          {loading && (
            <div className={css({ textAlign: 'center', color: 'white', py: '12' })}>
              Loading rooms...
            </div>
          )}

          {error && (
            <div
              className={css({
                bg: '#fef2f2',
                border: '1px solid #fecaca',
                color: '#991b1b',
                p: '4',
                rounded: 'lg',
                textAlign: 'center',
              })}
            >
              {error}
            </div>
          )}

          {!loading && !error && rooms.length === 0 && (
            <div
              className={css({
                bg: 'rgba(255, 255, 255, 0.05)',
                backdropFilter: 'blur(10px)',
                border: '1px solid rgba(255, 255, 255, 0.1)',
                rounded: 'lg',
                p: '12',
                textAlign: 'center',
                color: 'white',
              })}
            >
              <p className={css({ fontSize: 'xl', mb: '2' })}>No rooms available</p>
              <p className={css({ color: '#a0a0ff' })}>Be the first to create one!</p>
            </div>
          )}

          {!loading && !error && rooms.length > 0 && (
            <div className={css({ display: 'grid', gap: '4' })}>
              {rooms.map((room) => (
                <div
                  key={room.id}
                  className={css({
                    bg: 'rgba(255, 255, 255, 0.05)',
                    backdropFilter: 'blur(10px)',
                    border: '1px solid rgba(255, 255, 255, 0.1)',
                    rounded: 'lg',
                    p: '6',
                    transition: 'all 0.2s',
                    _hover: {
                      bg: 'rgba(255, 255, 255, 0.08)',
                      borderColor: 'rgba(255, 255, 255, 0.2)',
                    },
                  })}
                >
                  <div
                    className={css({
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'center',
                    })}
                  >
                    <div
                      onClick={() => router.push(`/arcade-rooms/${room.id}`)}
                      className={css({ flex: 1, cursor: 'pointer' })}
                    >
                      <div
                        className={css({
                          display: 'flex',
                          alignItems: 'center',
                          gap: '3',
                          mb: '2',
                        })}
                      >
                        <h3
                          className={css({
                            fontSize: '2xl',
                            fontWeight: 'bold',
                            color: 'white',
                          })}
                        >
                          {getRoomDisplayWithEmoji({
                            name: room.name,
                            code: room.code,
                            gameName: room.gameName,
                          })}
                        </h3>
                        <span
                          className={css({
                            px: '3',
                            py: '1',
                            bg: 'rgba(255, 255, 255, 0.1)',
                            color: '#fbbf24',
                            rounded: 'full',
                            fontSize: 'sm',
                            fontWeight: 600,
                            fontFamily: 'monospace',
                          })}
                        >
                          {room.code}
                        </span>
                        {room.isLocked && (
                          <span
                            className={css({
                              color: '#f87171',
                              fontSize: 'sm',
                            })}
                          >
                            🔒 Locked
                          </span>
                        )}
                      </div>
                      <div
                        className={css({
                          display: 'flex',
                          gap: '4',
                          color: '#a0a0ff',
                          fontSize: 'sm',
                          flexWrap: 'wrap',
                        })}
                      >
                        <span>👤 Host: {room.creatorName}</span>
                        <span>🎮 {room.gameName}</span>
                        {room.memberCount !== undefined && (
                          <span>
                            👥 {room.memberCount} member
                            {room.memberCount !== 1 ? 's' : ''}
                          </span>
                        )}
                        {room.playerCount !== undefined && room.playerCount > 0 && (
                          <span>
                            🎯 {room.playerCount} player
                            {room.playerCount !== 1 ? 's' : ''}
                          </span>
                        )}
                        <span
                          className={css({
                            color:
                              room.status === 'lobby'
                                ? '#10b981'
                                : room.status === 'playing'
                                  ? '#fbbf24'
                                  : '#6b7280',
                          })}
                        >
                          {room.status === 'lobby'
                            ? '⏳ Waiting'
                            : room.status === 'playing'
                              ? '🎮 Playing'
                              : '✓ Finished'}
                        </span>
                      </div>
                    </div>
                    {room.isMember ? (
                      <div
                        className={css({
                          px: '6',
                          py: '3',
                          bg: '#10b981',
                          color: 'white',
                          rounded: 'lg',
                          fontWeight: 600,
                          display: 'flex',
                          alignItems: 'center',
                          gap: '2',
                        })}
                      >
                        ✓ Joined
                      </div>
                    ) : (
                      <button
                        onClick={(e) => {
                          e.stopPropagation()
                          joinRoom(room)
                        }}
                        disabled={
                          room.isLocked ||
                          room.accessMode === 'locked' ||
                          room.accessMode === 'retired'
                        }
                        className={css({
                          px: '6',
                          py: '3',
                          bg:
                            room.isLocked ||
                            room.accessMode === 'locked' ||
                            room.accessMode === 'retired'
                              ? '#6b7280'
                              : room.accessMode === 'password'
                                ? '#f59e0b'
                                : '#3b82f6',
                          color: 'white',
                          rounded: 'lg',
                          fontWeight: 600,
                          cursor:
                            room.isLocked ||
                            room.accessMode === 'locked' ||
                            room.accessMode === 'retired'
                              ? 'not-allowed'
                              : 'pointer',
                          opacity:
                            room.isLocked ||
                            room.accessMode === 'locked' ||
                            room.accessMode === 'retired'
                              ? 0.5
                              : 1,
                          _hover:
                            room.isLocked ||
                            room.accessMode === 'locked' ||
                            room.accessMode === 'retired'
                              ? {}
                              : room.accessMode === 'password'
                                ? { bg: '#d97706' }
                                : { bg: '#2563eb' },
                          transition: 'all 0.2s',
                        })}
                      >
                        {room.accessMode === 'password' ? '🔑 Join with Password' : 'Join Room'}
                      </button>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Create Room Modal */}
        {showCreateModal && (
          <div
            className={css({
              position: 'fixed',
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
              bg: 'rgba(0, 0, 0, 0.7)',
              backdropFilter: 'blur(4px)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              zIndex: 50,
            })}
            onClick={() => setShowCreateModal(false)}
          >
            <div
              className={css({
                bg: 'white',
                rounded: 'xl',
                p: '8',
                maxW: '500px',
                w: 'full',
                mx: '4',
              })}
              onClick={(e) => e.stopPropagation()}
            >
              <h2
                className={css({
                  fontSize: '2xl',
                  fontWeight: 'bold',
                  mb: '6',
                })}
              >
                Create New Room
              </h2>
              <form
                onSubmit={(e) => {
                  e.preventDefault()
                  const formData = new FormData(e.currentTarget)
                  const nameValue = formData.get('name') as string
                  const gameName = formData.get('gameName') as string
                  // Treat empty name as null
                  const name = nameValue?.trim() || null
                  if (gameName) {
                    createRoom(name, gameName)
                  }
                }}
              >
                <div className={css({ mb: '4' })}>
                  <label
                    className={css({
                      display: 'block',
                      mb: '2',
                      fontWeight: 600,
                    })}
                  >
                    Room Name{' '}
                    <span className={css({ fontWeight: 400, color: '#9ca3af' })}>(optional)</span>
                  </label>
                  <input
                    name="name"
                    type="text"
                    placeholder="e.g., Friday Night Games (defaults to: 🎮 CODE)"
                    className={css({
                      w: 'full',
                      px: '4',
                      py: '3',
                      border: '1px solid #d1d5db',
                      rounded: 'lg',
                      _focus: { outline: 'none', borderColor: '#3b82f6' },
                    })}
                  />
                </div>
                <div className={css({ mb: '6' })}>
                  <label
                    className={css({
                      display: 'block',
                      mb: '2',
                      fontWeight: 600,
                    })}
                  >
                    Game
                  </label>
                  <select
                    name="gameName"
                    required
                    className={css({
                      w: 'full',
                      px: '4',
                      py: '3',
                      border: '1px solid #d1d5db',
                      rounded: 'lg',
                      _focus: { outline: 'none', borderColor: '#3b82f6' },
                    })}
                  >
                    <option value="matching">Memory Matching</option>
                    <option value="memory-quiz">Memory Quiz</option>
                    <option value="complement-race">Complement Race</option>
                  </select>
                </div>
                <div className={css({ display: 'flex', gap: '3' })}>
                  <button
                    type="button"
                    onClick={() => setShowCreateModal(false)}
                    className={css({
                      flex: 1,
                      px: '6',
                      py: '3',
                      bg: '#e5e7eb',
                      color: '#374151',
                      rounded: 'lg',
                      fontWeight: 600,
                      cursor: 'pointer',
                      _hover: { bg: '#d1d5db' },
                    })}
                  >
                    Cancel
                  </button>
                  <button
                    type="submit"
                    className={css({
                      flex: 1,
                      px: '6',
                      py: '3',
                      bg: '#10b981',
                      color: 'white',
                      rounded: 'lg',
                      fontWeight: 600,
                      cursor: 'pointer',
                      _hover: { bg: '#059669' },
                    })}
                  >
                    Create Room
                  </button>
                </div>
              </form>
            </div>
          </div>
        )}
      </div>
    </PageWithNav>
  )
}