import { useEffect, useRef, useState } from 'react';

const API = import.meta.env.VITE_API_URL;
const USERNAME_RE = /^[a-zA-Z0-9_]{3,20}$/;

export default function UsernameModal({ token, current, onClose, onSave }) {
  const [value, setValue]   = useState(current ?? '');
  const [error, setError]   = useState(null);
  const [saving, setSaving] = useState(false);
  const inputRef            = useRef(null);

  useEffect(() => {
    inputRef.current?.focus();
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  async function handleSave() {
    const trimmed = value.trim();
    if (!trimmed) return;
    if (!USERNAME_RE.test(trimmed)) {
      setError('3\u201320 characters, letters, numbers, and underscores only.');
      return;
    }
    setSaving(true);
    setError(null);
    try {
      const res = await fetch(`${API}/me/username`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
        body: JSON.stringify({ username: trimmed }),
      });
      const data = await res.json();
      if (res.ok) { onSave(data.username); onClose(); }
      else if (data.error === 'taken') setError('Username already taken \u2014 try another.');
      else setError('Something went wrong. Try again.');
    } catch {
      setError('Could not save. Check your connection.');
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="uname-overlay" onMouseDown={onClose}>
      <div className="uname-modal" onMouseDown={e => e.stopPropagation()}>
        <h3 className="uname-modal__title">Set username</h3>
        <p className="uname-modal__hint">3–20 chars · letters, numbers, underscores</p>
        <input
          ref={inputRef}
          className="uname-input"
          value={value}
          onChange={e => { setValue(e.target.value); setError(null); }}
          onKeyDown={e => e.key === 'Enter' && handleSave()}
          placeholder="e.g. player_one"
          maxLength={20}
        />
        {error && <p className="uname-error">{error}</p>}
        <div className="uname-actions">
          <button className="uname-btn uname-btn--cancel" onClick={onClose}>Cancel</button>
          <button className="uname-btn uname-btn--save" onClick={handleSave} disabled={saving}>
            {saving ? 'Saving\u2026' : 'Save'}
          </button>
        </div>
      </div>
    </div>
  );
}
