<template>
	<div class="flex flex-col gap-14">
		<PlayerCards v-for="playerId in reorderedPlayerIds" :key="playerId" :player-id="playerId"/>
		<div class="flex gap-5 justify-end items-center transform transition ease duration-500">
			<template v-if="game.state.phase === 'end'">
				<BigButton
					class="bg-gradient-to-br from-green-700 to-green-800"
					v-if="game.isOwnGame"
					@click="game.newRound()"
				>
					New round
				</BigButton>
			</template>
			<template v-else>
				<div class="font-fat opacity-20 text-3xl pr-2">
					<template v-if="isBust">You are bust.</template>
				</div>
				<BigButton
					class="bg-gradient-to-br from-red-800 to-red-900 uppercase"
					:disabled="!isYourTurn || isBust"
					@click="game.hit()"
				>
					Hit
				</BigButton>
				<BigButton
					class="bg-gradient-to-br from-blue-800 to-blue-900 uppercase"
					:disabled="!isYourTurn"
					@click="game.stay()"
				>
					Stay
				</BigButton>
			</template>
		</div>
		<GameEndModal/>
	</div>
</template>

<style module lang="scss">

</style>

<script setup lang="ts">
	import { useGame } from "../clientGame"
	import PlayerCards from "./PlayerCards.vue"
	import BigButton from "./BigButton.vue"
	import { computed } from "vue"
	import { useAuth } from "../auth"
	import { getNumberCardsSum } from "../shared/game/state"
	import GameEndModal from "./GameEndModal.vue"

	const game = useGame()
	const auth = useAuth()
	const isYourTurn = computed(() => game.state.activePlayerId === auth.requiredUser.id)
	const isBust = computed(() => getNumberCardsSum(game.state.players.find(p => p.id === auth.requiredUser.id)!.numberCards) > game.state.targetSum)

	const reorderedPlayerIds = computed(() => {
		const ids = game.state.players.map(p => p.id)
		const selfIndex = ids.findIndex(id => id === auth.requiredUser.id)
		let before = ids.slice(0, selfIndex)
		let rest = ids.slice(selfIndex)
		return [...rest, ...before]
	})
</script>