import { type CSSProperties, type KeyboardEvent, type RefObject } from 'react'
import styles from '../../pages/EndOfGamePage.module.css'

type ArcadeNameInputProps = {
  maxLength: number
  username: string
  inputRef: RefObject<HTMLInputElement | null>
  style: CSSProperties
  onNameChange: (value: string) => void
}

export function ArcadeNameInput({
  maxLength,
  username,
  inputRef,
  style,
  onNameChange,
}: ArcadeNameInputProps) {
  function focusNameInput() {
    inputRef.current?.focus()
  }

  function handleKeyDown(e: KeyboardEvent<HTMLDivElement>) {
    if (e.key === 'Enter' || e.key === ' ') {
      e.preventDefault()
      focusNameInput()
    }
  }

  return (
    <section className={styles.nameBar} style={style}>
      <div className={styles.nameBarHeader}>
        <label className={`${styles.nameBarTitle} font-title`} htmlFor="arcade-name-input">
          ENTER YOUR NAME
        </label>
        <span className={`${styles.nameBarSub} font-caption`} id="arcade-name-hint">
          KEYBOARD · {maxLength} CHARS MAX
        </span>
      </div>

      <input
        ref={inputRef}
        id="arcade-name-input"
        className={styles.nameInputHidden}
        type="text"
        name="username"
        autoComplete="off"
        autoCapitalize="characters"
        spellCheck={false}
        maxLength={maxLength}
        value={username}
        onChange={(e) => onNameChange(e.target.value)}
        aria-describedby="arcade-name-hint"
      />

      <div
        className={styles.nameSlots}
        role="presentation"
        onClick={focusNameInput}
        onKeyDown={handleKeyDown}
        tabIndex={-1}
      >
        {Array.from({ length: maxLength }).map((_, i) => {
          const ch = username[i]
          const showCaret = i === username.length && username.length < maxLength
          return (
            <span
              key={i}
              className={`${styles.nameSlot} font-display${showCaret ? ` ${styles.nameSlotActive}` : ''}`}
            >
              {ch ?? '\u00A0'}
              {showCaret ? <span className={styles.nameCaret} /> : null}
            </span>
          )
        })}
      </div>
    </section>
  )
}
