import { useEffect, useState } from 'react';
import { useGameStore } from '../store/gameStore';
import { emit } from '../lib/socket';

interface Props {
  onClose: () => void;
}

/** Prompt for a new game's name. Identity is taken from the logged-in session,
 *  so no player name is asked here. */
export default function NameModal({ onClose }: Props) {
  const [name, setName] = useState('');
  const myPlayer = useGameStore((s) => s.myPlayer);

  // Close once we've joined the just-created game (create → register chain done).
  useEffect(() => {
    if (myPlayer) onClose();
  }, [myPlayer, onClose]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const trimmed = name.trim();
    if (!trimmed) return;
    // Stores the name; the socket listener auto-chains register_player.
    emit.createGame(trimmed);
  };

  return (
    <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-40 p-4">
      <div className="bg-header border border-[#142018] rounded-2xl p-6 w-full max-w-sm shadow-[0_28px_88px_rgba(0,0,0,.65)]">
        <h2 className="font-serif text-xl mb-4 text-gold">Názov hry</h2>
        <form onSubmit={handleSubmit} className="flex flex-col gap-4">
          <input
            autoFocus
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            maxLength={30}
            placeholder="Napr. Večerná partia"
            className="bg-circle text-green-score rounded-lg px-4 py-2 border border-gold/20 outline-none focus:border-gold/60 focus:ring-1 focus:ring-gold/30 placeholder:text-green-dim/60"
          />
          <div className="flex gap-2 justify-end">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 rounded-lg text-green-dim hover:text-gold"
            >
              Zrušiť
            </button>
            <button
              type="submit"
              disabled={!name.trim()}
              className="px-4 py-2 rounded-lg bg-gold text-table font-serif font-semibold disabled:opacity-40 hover:bg-gold-bright transition-colors"
            >
              Vytvoriť
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
