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

4.52% Statements 9/199
100% Branches 0/0
0% Functions 0/1
4.52% Lines 9/199

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 2001x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                                                                                                                                                                                                                                                                                                              
import React from 'react'
 
interface JoinRoomInputProps {
  onJoin: (code: string) => void
}
 
type ValidationState = 'idle' | 'checking' | 'valid' | 'invalid'
 
export function JoinRoomInput({ onJoin }: JoinRoomInputProps) {
  const [code, setCode] = React.useState('')
  const [validationState, setValidationState] = React.useState<ValidationState>('idle')
  const [error, setError] = React.useState<string>('')
  const inputRef = React.useRef<HTMLInputElement>(null)

  // Format code as user types: ABC123 → ABC-123
  const formatCode = (value: string): string => {
    const cleaned = value.toUpperCase().replace(/[^A-Z0-9]/g, '')
    if (cleaned.length <= 3) return cleaned
    return `${cleaned.slice(0, 3)}-${cleaned.slice(3, 6)}`
  }

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const formatted = formatCode(e.target.value)
    setCode(formatted)
    setError('')

    // Reset validation when user types
    if (validationState !== 'idle') {
      setValidationState('idle')
    }

    // Auto-validate when 6 characters entered
    const cleanCode = formatted.replace('-', '')
    if (cleanCode.length === 6) {
      validateCode(cleanCode)
    }
  }

  const validateCode = async (codeToValidate: string) => {
    setValidationState('checking')

    try {
      // Check if room exists via API
      const response = await fetch(`/api/arcade/rooms/code/${codeToValidate}`)

      if (response.ok) {
        setValidationState('valid')
      } else {
        setValidationState('invalid')
        setError('Room not found')
      }
    } catch (err) {
      setValidationState('invalid')
      setError('Unable to validate code')
    }
  }

  const handleJoin = () => {
    const cleanCode = code.replace('-', '')
    if (cleanCode.length === 6 && validationState === 'valid') {
      onJoin(cleanCode)
    }
  }

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && validationState === 'valid') {
      handleJoin()
    }
  }

  // Visual state colors
  const getBorderColor = () => {
    switch (validationState) {
      case 'valid':
        return '#10b981'
      case 'invalid':
        return '#ef4444'
      case 'checking':
        return '#3b82f6'
      default:
        return '#e5e7eb'
    }
  }

  const getIcon = () => {
    switch (validationState) {
      case 'valid':
        return '✅'
      case 'invalid':
        return '❌'
      case 'checking':
        return '🔄'
      default:
        return ''
    }
  }

  return (
    <div>
      <div style={{ position: 'relative' }}>
        <input
          ref={inputRef}
          type="text"
          value={code}
          onChange={handleChange}
          onKeyPress={handleKeyPress}
          placeholder="ABC-123"
          maxLength={7} // ABC-123
          style={{
            width: '100%',
            padding: '12px 40px 12px 12px',
            fontSize: '16px',
            fontWeight: 600,
            letterSpacing: '2px',
            textAlign: 'center',
            border: `2px solid ${getBorderColor()}`,
            borderRadius: '8px',
            outline: 'none',
            transition: 'all 0.2s ease',
            fontFamily: 'monospace',
          }}
        />

        {/* Validation Icon */}
        {validationState !== 'idle' && (
          <div
            style={{
              position: 'absolute',
              right: '12px',
              top: '50%',
              transform: 'translateY(-50%)',
              fontSize: '18px',
              animation: validationState === 'checking' ? 'spin 1s linear infinite' : 'none',
            }}
          >
            {getIcon()}
          </div>
        )}
      </div>

      {/* Error message */}
      {error && (
        <div
          style={{
            marginTop: '6px',
            fontSize: '12px',
            color: '#ef4444',
            textAlign: 'center',
          }}
        >
          {error}
        </div>
      )}

      {/* Join button */}
      {validationState === 'valid' && (
        <button
          type="button"
          onClick={handleJoin}
          style={{
            width: '100%',
            marginTop: '8px',
            padding: '10px 16px',
            background: 'linear-gradient(135deg, #3b82f6, #2563eb)',
            border: 'none',
            borderRadius: '8px',
            color: 'white',
            fontSize: '14px',
            fontWeight: 600,
            cursor: 'pointer',
            transition: 'all 0.2s ease',
            boxShadow: '0 2px 4px rgba(59, 130, 246, 0.3)',
          }}
          onMouseEnter={(e) => {
            e.currentTarget.style.transform = 'translateY(-1px)'
            e.currentTarget.style.boxShadow = '0 4px 8px rgba(59, 130, 246, 0.4)'
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.transform = 'translateY(0)'
            e.currentTarget.style.boxShadow = '0 2px 4px rgba(59, 130, 246, 0.3)'
          }}
        >
          🚀 Join Room
        </button>
      )}

      <style
        dangerouslySetInnerHTML={{
          __html: `
            @keyframes spin {
              from { transform: translateY(-50%) rotate(0deg); }
              to { transform: translateY(-50%) rotate(360deg); }
            }
          `,
        }}
      />
    </div>
  )
}