<script setup lang="ts">
import { useHead } from '@vueuse/head'
import { useRouter } from 'vue-router'
import useRaffle from '../composables/useRaffle'

useHead({
  title: 'Welcome',
})

const {
  raffleStore,
  newRaffle,
  newParticipant,
  addParticipant,
  removeParticipant,
  readyToRaffle,
} = useRaffle()

const showNewRaffleForm = $ref(false)

function startRaffle() {
  if (!readyToRaffle) return

  raffleStore.value.push(newRaffle.value)
  const router = useRouter()
  router.push(`/raffle/${newRaffle.value.id}`)
}
</script>

<template>
  <header>
    <h1 class="text-4xl">Raffle Me That!</h1>

    <div class="mt-8" v-if="raffleStore.length">
      <strong>Select Existing:</strong>
      <ul>
        <li v-for="raffle in raffleStore">
          <router-link :to="`/raffle/${raffle.id}`">
            {{ raffle.title }}
          </router-link>
        </li>
      </ul>
    </div>
  </header>

  <main>
    <div class="text-xl" v-if="showNewRaffleForm">

      <input
        class="w-full mb-16"
        placeholder="Amazing Raffle Title"
        :class="{ 'border-transparent': newRaffle.title.length }"
        v-model="newRaffle.title"
      />

      <section>
        <ul>
          <li class="flex justify-between items-center mb-1" v-for="(p, i) in newRaffle.participants">
            <input class="w-5/6 border-transparent outline-none" v-model="newRaffle.participants[i]" />
            <button class="w-1/6" @click="removeParticipant(i)" v-if="p.length">x</button>
          </li>
        </ul>

        <input
          class="w-5/6 rounded-r-none"
          v-model="newParticipant"
          @keypress.enter="addParticipant"
        />
        <button class="w-1/6 border-l-0 rounded-l-none font-bold" @click="addParticipant">+</button>
        <button class="w-full mt-16 disabled:opacity-50" :disabled="!readyToRaffle" @click="startRaffle">Start!</button>
      </section>
    </div>
    <button @click="showNewRaffleForm = true" v-else>Create New Raffle</button>
  </main>
</template>
