<script setup lang="ts">
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import type { Player } from '../models/public';

const playerName = ref('');
const router = useRouter();

async function confirmName(): Promise<void> {
  if (!playerName.value) return;

  try {
    const { data: player } = await axios.post<Player>(
      `${import.meta.env.VITE_BACKEND_URL}/player/${playerName.value}`
    );    
    
    localStorage.setItem('playerName', player.name);
    localStorage.setItem('playerId', player.id);
    window.dispatchEvent(new Event('player-name-changed'));
    router.push('/lobbies');
  } catch (error) {
    console.error('Failed to confirm player name:', error);
  }
}
</script>

<template>
  <div
    class="bg-gradient-to-br from-gray-900 via-gray-700 to-gray-800 flex flex-col items-center justify-center text-white px-4 py-6"
  >
    <div class="max-w-xl w-full text-center">
      <div class="mb-5 flex justify-center">
        <img
          src="../assets/logo.png"
          alt="SmolBrainDuel Logo"
          class="h-48 w-48 object-contain rounded-full shadow-xl ring-4 ring-blue-500"
        >
      </div>

      <p class="text-gray-400 text-lg mb-1 tracking-wide">
        👋 Welcome to
      </p>
      <h1 class="text-3xl md:text-6xl font-black mb-3 tracking-tight">
        <span class="text-blue-500">SmolBrainDuel</span>
      </h1>
      <p class="text-gray-400 text-sm md:text-base mb-5 max-w-md mx-auto">
        A fast-paced trivia showdown to test your wits and dominate the leaderboard.
      </p>
    </div>

    <div class="bg-gray-800 rounded-2xl shadow-2xl p-5 w-full max-w-md">
      <h2 class="text-xl font-semibold text-center mb-5">
        Enter Your Name to Begin
      </h2>
      <input
        v-model="playerName"
        type="text"
        placeholder="e.g. Brainiac123"
        class="w-full mb-4 px-5 py-3 rounded-lg text-gray-900 bg-white text-base border border-gray-300 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent shadow-sm"
        @keydown.enter="confirmName"
      >

      <button
        :disabled="!playerName"
        class="w-full bg-blue-600 hover:bg-blue-700 disabled:opacity-50 text-white font-semibold py-3 rounded-lg transition-all duration-300 ease-in-out"
        @click="confirmName"
      >
        🚀 Start the Duel
      </button>
    </div>
  </div>
</template>
