All files / web/src/components/toys/number-line/findTheNumber FindTheNumberBar.tsx

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

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
'use client'

import { useState, useCallback, useRef, useEffect } from 'react'
import { parseTargetNumber } from './parseTargetNumber'

const PRESET_EMOJIS = ['⭐', 'πŸš€', 'πŸ’Ž', 'πŸ¦„', '🌈', '🎯', 'πŸ”₯', '🌸', 'πŸ™', 'πŸ•', 'πŸŽͺ', 'πŸͺ']

export type FindTheNumberGameState = 'idle' | 'active' | 'found'

interface FindTheNumberBarProps {
  onStart: (target: number, emoji: string) => void
  onGiveUp: () => void
  gameState: FindTheNumberGameState
  isDark: boolean
  /** When true, hide the target number (voice model gives clues instead) */
  hideTarget?: boolean
}

function getRandomEmoji(): string {
  return PRESET_EMOJIS[Math.floor(Math.random() * PRESET_EMOJIS.length)]
}

function formatNumber(val: number): string {
  const str = val.toString()
  if (str.includes('.') && str.split('.')[1].length > 3) {
    return val.toFixed(6).replace(/0+$/, '').replace(/\.$/, '')
  }
  return str
}

export function FindTheNumberBar({
  onStart,
  onGiveUp,
  gameState,
  isDark,
  hideTarget = false,
}: FindTheNumberBarProps) {
  const [isEditing, setIsEditing] = useState(false)
  const [inputValue, setInputValue] = useState('')
  const [displayNumber, setDisplayNumber] = useState<number | null>(null)
  const [displayEmoji, setDisplayEmoji] = useState(PRESET_EMOJIS[0])
  const inputRef = useRef<HTMLInputElement>(null)
  const numberRef = useRef<HTMLDivElement>(null)
  const prevGameStateRef = useRef(gameState)

  // Randomize emoji after mount to avoid hydration mismatch
  const didMount = useRef(false)
  useEffect(() => {
    if (!didMount.current) {
      didMount.current = true
      setDisplayEmoji(getRandomEmoji())
    }
  }, [])

  // Celebration animation when found
  useEffect(() => {
    if (gameState === 'found' && prevGameStateRef.current === 'active' && numberRef.current) {
      numberRef.current.animate(
        [
          { transform: 'scale(1)', color: isDark ? '#e5e7eb' : '#1f2937' },
          { transform: 'scale(1.15)', color: '#10b981' },
          { transform: 'scale(1)', color: '#10b981' },
        ],
        { duration: 500, easing: 'ease-out', fill: 'forwards' }
      )
    }
    prevGameStateRef.current = gameState
  }, [gameState, isDark])

  // Focus input when entering edit mode
  useEffect(() => {
    if (isEditing) {
      // Small delay to ensure the input is rendered
      requestAnimationFrame(() => inputRef.current?.focus())
    }
  }, [isEditing])

  const commitInput = useCallback(() => {
    const trimmed = inputValue.trim()
    if (!trimmed) {
      // Empty input β†’ return to idle
      setIsEditing(false)
      setInputValue('')
      return
    }
    const parsed = parseTargetNumber(trimmed)
    if (parsed !== null) {
      const emoji = getRandomEmoji()
      setDisplayNumber(parsed)
      setDisplayEmoji(emoji)
      setIsEditing(false)
      setInputValue('')
      onStart(parsed, emoji)
    }
    // Invalid input: stay in editing mode (let user fix it)
  }, [inputValue, onStart])

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === 'Enter') {
        e.preventDefault()
        commitInput()
      } else if (e.key === 'Escape') {
        setIsEditing(false)
        setInputValue('')
      }
    },
    [commitInput]
  )

  const handleTapNumber = useCallback(() => {
    onGiveUp()
    setDisplayNumber(null)
    setIsEditing(true)
    setInputValue('')
  }, [onGiveUp])

  const handleTapPlaceholder = useCallback(() => {
    setIsEditing(true)
    setInputValue('')
  }, [])

  const textColor = isDark ? '#e5e7eb' : '#1f2937'
  const mutedColor = isDark ? 'rgba(156, 163, 175, 0.7)' : 'rgba(107, 114, 128, 0.7)'
  const borderColor = isDark ? 'rgba(75, 85, 99, 0.5)' : 'rgba(209, 213, 219, 0.8)'

  // Parse live for validation hint
  const parsed = inputValue.trim() ? parseTargetNumber(inputValue) : undefined
  const showInvalid = inputValue.trim().length > 0 && parsed === null

  return (
    <div
      data-component="find-the-number-bar"
      style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        minHeight: 56,
        padding: '8px 16px',
        borderBottom: `1px solid ${borderColor}`,
        userSelect: 'none',
        WebkitUserSelect: 'none',
      }}
    >
      {isEditing ? (
        /* --- Editing: inline input --- */
        <div
          data-element="edit-container"
          style={{
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            gap: 2,
            width: '100%',
            maxWidth: 280,
          }}
        >
          <input
            ref={inputRef}
            data-element="number-input"
            type="text"
            inputMode="text"
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            onBlur={commitInput}
            onKeyDown={handleKeyDown}
            placeholder="type a number…"
            style={{
              width: '100%',
              textAlign: 'center',
              fontSize: '1.5rem',
              fontWeight: 700,
              color: showInvalid ? '#ef4444' : textColor,
              background: 'transparent',
              border: 'none',
              borderBottom: `2px solid ${showInvalid ? '#ef4444' : isDark ? 'rgba(99, 102, 241, 0.6)' : 'rgba(79, 70, 229, 0.5)'}`,
              outline: 'none',
              padding: '4px 0',
              caretColor: isDark ? '#818cf8' : '#4f46e5',
            }}
          />
          {showInvalid && (
            <span style={{ fontSize: '0.75rem', color: '#ef4444' }}>try 3.14 or 1/3</span>
          )}
        </div>
      ) : displayNumber !== null ? (
        /* --- Active / Found: tappable number display --- */
        <div
          ref={numberRef}
          data-element="number-display"
          data-action="tap-to-reset"
          onClick={handleTapNumber}
          style={{
            fontSize: '1.75rem',
            fontWeight: 800,
            color: gameState === 'found' ? '#10b981' : textColor,
            cursor: 'pointer',
            padding: '4px 16px',
            borderRadius: 12,
            transition: 'background 0.15s ease',
            WebkitTapHighlightColor: 'transparent',
          }}
          onPointerEnter={(e) => {
            ;(e.currentTarget as HTMLElement).style.background = isDark
              ? 'rgba(255,255,255,0.06)'
              : 'rgba(0,0,0,0.04)'
          }}
          onPointerLeave={(e) => {
            ;(e.currentTarget as HTMLElement).style.background = ''
          }}
        >
          {hideTarget && gameState !== 'found'
            ? `πŸ” Find the mystery number!`
            : `${displayEmoji} ${formatNumber(displayNumber)}`}
        </div>
      ) : (
        /* --- Idle: tappable placeholder --- */
        <div
          data-element="placeholder"
          data-action="tap-to-start"
          onClick={handleTapPlaceholder}
          style={{
            fontSize: '1.1rem',
            fontWeight: 500,
            color: mutedColor,
            cursor: 'pointer',
            padding: '8px 16px',
            borderRadius: 12,
            transition: 'background 0.15s ease',
            WebkitTapHighlightColor: 'transparent',
          }}
          onPointerEnter={(e) => {
            ;(e.currentTarget as HTMLElement).style.background = isDark
              ? 'rgba(255,255,255,0.06)'
              : 'rgba(0,0,0,0.04)'
          }}
          onPointerLeave={(e) => {
            ;(e.currentTarget as HTMLElement).style.background = ''
          }}
        >
          {displayEmoji} tap to pick a number
        </div>
      )}
    </div>
  )
}