<template>
  <div class="playground__container">
    <div class="playground__area">
      <div class="playground__sources">
        <SourceCard v-for="source in sources" :key="source.id" :source="source" :selectable="selectable"
          :selected="selection == source.id" @click="selectSource(source)" :badge="badgeMap[source.id]"
          :disabled="disabledMap[source.id]" />
      </div>
      <div class="playground__spacer" />
      <div class="playground__quote">
        <QuoteCard :quote="quote" />
      </div>
    </div>
    <div class="playground__players-list">
      <PlayerList :show-score="true" :show-checkbox="playerListShowCheckbox" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import type { Quote, Source, Sources } from '@/composables/engine.d'
import { useRoundStore } from '@/stores/RoundStore'
import useEngine from '@/composables/useEngine'
import { useGameinfoStore } from "@/stores/GameinfoStore"
import { useUserinfoStore } from "@/stores/UserinfoStore"

const { round } = useRoundStore()
const quote = { quote: round.quote } as Quote
const sources = round.sources as Sources

const { saveSelection } = useEngine()
const selection = ref('')
const selectable = computed(() => game.phase === 'select-quote' && !selection.value && !round.selections[useUserinfoStore().id])
const selectSource = async (source: Source): Promise<void> => {
  if (selectable.value) {
    await saveSelection(source.id)
    selection.value = source.id
  }
}

const game = useGameinfoStore()
const playerListShowCheckbox = computed(() => game.state === 'play' && game.phase === 'select-quote')
const badgeMap = computed(() => {
  const badgeMap = {}
  if (game.phase === 'reveal-show-count') {
    for (const id in round.revelation.votes) {
      badgeMap[id] = round.revelation.votes[id].length
    }
  }
  return badgeMap
})

const disabledMap = computed(() => {
  const disabledMap = {}
  if (game.phase === 'reveal-source') {
    for (const id in round.revelation.sources) {
      disabledMap[id] = !round.revelation.sources[id]
    }
  }

  return disabledMap
})
</script>

<style lang="scss">
.playground {
  &__container {
    display: flex;
    width: 100%;
    height: 100%;
  }

  &__area {
    display: flex;
    flex-direction: column;
    flex-grow: 1;
    margin: 40px;
  }

  &__sources {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    gap: 24px 36px;
  }

  &__spacer {
    flex-grow: 3;
  }

  &__quote {
    display: flex;
    justify-content: center;
    flex-grow: 4;
  }

  &__players-list {
    width: 200px;
    margin: 16px 16px 0 64px;
  }
}
</style>