<template>
  <div>
    <h2>Add players</h2>
    <div class="row">
      <input v-model="playerInput" type="text" placeholder="Enter player name" @keydown.enter="addPlayer" />
      <button @click="addPlayer" type="button">Add</button>
    </div>
    <ul class="player-list">
      <li v-for="(player, index) in playersStore.players" :key="index" class="player-item">
        <span class="player-name">{{ player }}</span>
        <button class="delete-btn" @click="deletePlayer(index)" title="Delete player">
          <svg class="trash-icon" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
            <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-9l-1 1H5v2h14V4z"
              fill="currentColor" />
          </svg>
        </button>
      </li>
    </ul>
    <div class="players-actions">
      <button @click="clearAll" type="button" class="btn-secondary">Clear All</button>
      <button @click="finished" type="button" class="btn-primary">Finished</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { usePlayersStore } from '../stores/players'

const playerInput = ref<string>('')
const playersStore = usePlayersStore()

function addPlayer(): void {
  playersStore.addPlayer(playerInput.value)
  playerInput.value = ''
}

function deletePlayer(index: number): void {
  playersStore.deletePlayer(index)
}

function clearAll(): void {
  if (confirm('Are you sure you want to delete all players?')) {
    playersStore.clearAllPlayers()
  }
}

function finished(): void {
  router.push('/start')
}
</script>
