All files / web/src/components/nav AddPlayerButton.tsx

71.92% Statements 246/342
89.74% Branches 35/39
35.29% Functions 6/17
71.92% Lines 246/342

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 3431x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x                                                   15x 15x 15x                                                         15x 15x 15x 9x         9x 9x 4x 4x 4x 15x 15x 15x 1x 1x 1x 15x 15x     15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 10x 5x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 10x 5x 15x 15x 15x               15x                 15x 15x 15x 15x 15x 15x 15x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x         10x         10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x         10x         10x 10x 10x 10x 10x 10x 10x 10x 5x 5x 5x 5x 5x 5x 5x 5x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x     7x     7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 5x 5x 10x 10x 10x 5x 5x     10x 10x 10x 15x 15x 15x 15x  
import React from 'react'
import { useRouter } from 'next/navigation'
import { useToast } from '@/components/common/ToastContext'
import { InvitePlayersTab } from './InvitePlayersTab'
import { PlayOnlineTab } from './PlayOnlineTab'
import { addToRecentRooms } from './RecentRoomsList'
import { useCreateRoom, useGetRoomByCode, useJoinRoom } from '@/hooks/useRoomData'
 
interface Player {
  id: string
  name: string
  emoji: string
}
 
export type TabType = 'add' | 'invite'
 
interface AddPlayerButtonProps {
  inactivePlayers: Player[]
  shouldEmphasize: boolean
  onAddPlayer: (playerId: string) => void
  // Lifted state from PageWithNav
  showPopover?: boolean
  setShowPopover?: (show: boolean) => void
  activeTab?: TabType
  setActiveTab?: (tab: TabType) => void
  // Context-aware: show different content based on room state
  isInRoom?: boolean
  // Game info for room creation
  gameName?: string | null
}
 
export function AddPlayerButton({
  inactivePlayers,
  shouldEmphasize,
  onAddPlayer,
  showPopover: showPopoverProp,
  setShowPopover: setShowPopoverProp,
  activeTab: activeTabProp,
  setActiveTab: setActiveTabProp,
  isInRoom = false,
  gameName = null,
}: AddPlayerButtonProps) {
  const popoverRef = React.useRef<HTMLDivElement>(null)
  const router = useRouter()
  const { showError } = useToast()
 
  // Use lifted state if provided, otherwise fallback to internal state
  const [internalShowPopover, setInternalShowPopover] = React.useState(false)
  const [internalActiveTab, setInternalActiveTab] = React.useState<TabType>('add')
 
  const showPopover = showPopoverProp ?? internalShowPopover
  const setShowPopover = setShowPopoverProp ?? setInternalShowPopover
  const activeTab = activeTabProp ?? internalActiveTab
  const setActiveTab = setActiveTabProp ?? setInternalActiveTab
 
  // Context-aware tab label
  const secondTabLabel = isInRoom ? '📨 Invite More' : '🌐 Play Online'
  const secondTabColor = isInRoom ? '#8b5cf6' : '#3b82f6'
 
  // Room creation and joining hooks
  const { mutate: createRoom } = useCreateRoom()
  const { mutate: joinRoom } = useJoinRoom()
  const { mutateAsync: getRoomByCode } = useGetRoomByCode()
 
  // Handler for creating a new room (without a game - game will be selected in room)
  const handleCreateRoom = () => {
    createRoom(
      {
        name: null, // Auto-generated from code
        gameName: null, // No game selected yet - will be chosen in room
        creatorName: 'Player',
      },
      {
        onSuccess: (result) => {
          // Add to recent rooms
          addToRecentRooms({
            code: result.room.code,
            name: result.room.name,
            gameName: result.room.gameName,
          })
          // Close popover and navigate to room to choose game
          setShowPopover(false)
          router.push('/arcade')
        },
        onError: (error) => {
          console.error('Failed to create room:', error)
          showError('Failed to create room', error.message)
        },
      }
    )
  }
 
  // Handler for joining a room
  const handleJoinRoom = async (code: string) => {
    try {
      // First, get the room by code to get the roomId
      const room = await getRoomByCode(code)

      // Then join the room by ID
      joinRoom(
        { roomId: room.id, displayName: 'Player' },
        {
          onSuccess: (data) => {
            // Add to recent rooms
            if (data.room) {
              addToRecentRooms({
                code: data.room.code,
                name: data.room.name,
                gameName: data.room.gameName,
              })
            }
            // Close popover and navigate to room
            setShowPopover(false)
            router.push('/arcade')
          },
        }
      )
    } catch (error) {
      console.error('Failed to join room:', error)
      // Error will be shown by JoinRoomInput validation
    }
  }
 
  // Close popover when clicking outside
  React.useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (popoverRef.current && !popoverRef.current.contains(event.target as Node)) {
        setShowPopover(false)
      }
    }
 
    if (showPopover) {
      document.addEventListener('mousedown', handleClickOutside)
      return () => document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [showPopover, setShowPopover])
 
  const handleAddPlayerClick = (playerId: string) => {
    onAddPlayer(playerId)
    setShowPopover(false)
  }
 
  if (!shouldEmphasize || inactivePlayers.length === 0) {
    return null
  }
 
  return (
    <div style={{ position: 'relative' }} ref={popoverRef}>
      <button
        type="button"
        onClick={() => setShowPopover(!showPopover)}
        style={{
          fontSize: '36px',
          width: '56px',
          height: '56px',
          borderRadius: '50%',
          border: '3px solid #10b981',
          background: showPopover
            ? 'linear-gradient(135deg, #10b981, #059669)'
            : 'linear-gradient(135deg, rgba(16, 185, 129, 0.15), rgba(16, 185, 129, 0.1))',
          color: showPopover ? 'white' : '#10b981',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          cursor: 'pointer',
          transition: 'all 0.3s ease',
          padding: 0,
          lineHeight: 1,
          fontWeight: 'bold',
          boxShadow: showPopover
            ? '0 6px 16px rgba(16, 185, 129, 0.5)'
            : '0 6px 12px rgba(0,0,0,0.3)',
          flexShrink: 0,
        }}
        onMouseEnter={(e) => {
          if (!showPopover) {
            e.currentTarget.style.background = 'linear-gradient(135deg, #10b981, #059669)'
            e.currentTarget.style.color = 'white'
            e.currentTarget.style.transform = 'scale(1.08)'
            e.currentTarget.style.boxShadow = '0 6px 16px rgba(16, 185, 129, 0.5)'
          }
        }}
        onMouseLeave={(e) => {
          if (!showPopover) {
            e.currentTarget.style.background =
              'linear-gradient(135deg, rgba(16, 185, 129, 0.15), rgba(16, 185, 129, 0.1))'
            e.currentTarget.style.color = '#10b981'
            e.currentTarget.style.transform = 'scale(1)'
            e.currentTarget.style.boxShadow = '0 6px 12px rgba(0,0,0,0.3)'
          }
        }}
        title="Add player"
      >
        +
      </button>
 
      {/* Add Player / Invite Players Popover */}
      {showPopover && (
        <div
          style={{
            position: 'absolute',
            top: 'calc(100% + 12px)',
            right: 0,
            background: 'white',
            borderRadius: '12px',
            boxShadow: '0 10px 40px rgba(0, 0, 0, 0.2)',
            border: '2px solid #e5e7eb',
            minWidth: '240px',
            zIndex: 1000,
            animation: 'fadeIn 0.2s ease',
            overflow: 'hidden',
          }}
        >
          {/* Tab Headers */}
          <div
            style={{
              display: 'flex',
              borderBottom: '2px solid #e5e7eb',
              background: '#f9fafb',
            }}
          >
            <button
              type="button"
              onClick={() => setActiveTab('add')}
              style={{
                flex: 1,
                padding: '10px 16px',
                background: activeTab === 'add' ? 'white' : 'transparent',
                border: 'none',
                borderBottom: activeTab === 'add' ? '2px solid #10b981' : '2px solid transparent',
                color: activeTab === 'add' ? '#10b981' : '#6b7280',
                fontSize: '13px',
                fontWeight: activeTab === 'add' ? '700' : '600',
                cursor: 'pointer',
                transition: 'all 0.2s ease',
                marginBottom: '-2px',
              }}
              onMouseEnter={(e) => {
                if (activeTab !== 'add') {
                  e.currentTarget.style.color = '#374151'
                }
              }}
              onMouseLeave={(e) => {
                if (activeTab !== 'add') {
                  e.currentTarget.style.color = '#6b7280'
                }
              }}
            >
              Add Player
            </button>
            <button
              type="button"
              onClick={() => setActiveTab('invite')}
              style={{
                flex: 1,
                padding: '10px 16px',
                background: activeTab === 'invite' ? 'white' : 'transparent',
                border: 'none',
                borderBottom:
                  activeTab === 'invite' ? `2px solid ${secondTabColor}` : '2px solid transparent',
                color: activeTab === 'invite' ? secondTabColor : '#6b7280',
                fontSize: '13px',
                fontWeight: activeTab === 'invite' ? '700' : '600',
                cursor: 'pointer',
                transition: 'all 0.2s ease',
                marginBottom: '-2px',
              }}
              onMouseEnter={(e) => {
                if (activeTab !== 'invite') {
                  e.currentTarget.style.color = '#374151'
                }
              }}
              onMouseLeave={(e) => {
                if (activeTab !== 'invite') {
                  e.currentTarget.style.color = '#6b7280'
                }
              }}
            >
              {secondTabLabel}
            </button>
          </div>
 
          {/* Tab Content */}
          <div style={{ padding: '12px' }}>
            {activeTab === 'add' && (
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  gap: '4px',
                }}
              >
                {inactivePlayers.map((player) => (
                  <button
                    key={player.id}
                    onClick={() => handleAddPlayerClick(player.id)}
                    style={{
                      display: 'flex',
                      alignItems: 'center',
                      gap: '12px',
                      padding: '8px 12px',
                      background: 'transparent',
                      border: 'none',
                      borderRadius: '8px',
                      cursor: 'pointer',
                      transition: 'all 0.2s ease',
                      textAlign: 'left',
                    }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.background = '#f3f4f6'
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.background = 'transparent'
                    }}
                  >
                    <span style={{ fontSize: '24px', lineHeight: 1 }}>{player.emoji}</span>
                    <span
                      style={{
                        fontSize: '14px',
                        fontWeight: 500,
                        color: '#1f2937',
                      }}
                    >
                      {player.name}
                    </span>
                  </button>
                ))}
              </div>
            )}
 
            {activeTab === 'invite' &&
              (isInRoom ? (
                <InvitePlayersTab />
              ) : (
                <PlayOnlineTab onCreateRoom={handleCreateRoom} onJoinRoom={handleJoinRoom} />
              ))}
          </div>
        </div>
      )}
    </div>
  )
}