<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import type { Player } from '../models/public';
import axios from 'axios';
import router from '../router/router';
import { useRoute } from 'vue-router';
import confetti from 'canvas-confetti';

const route = useRoute();
const backendUrl = import.meta.env.VITE_BACKEND_URL;
const lobbyCode = ref<string | string[]>(route.params.code);
const players = ref<Player[]>([]);

function celebrateWinner() {
  const colors = ['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#ff00ff', '#00ffff', '#ffffff', '#ffcc00', '#ff69b4'];

  confetti({
    particleCount: 600,
    spread: 180,
    origin: { x: 0.5, y: 0.8 },
    colors: colors,
    startVelocity: 60,
    gravity: 0.9,
    shapes: ['square', 'circle'],
    ticks: 200,
    disableForReducedMotion: true,
    scalar: 1.2
  });

  setTimeout(() => {
    confetti({
      particleCount: 500,
      spread: 180,
      origin: { x: 0.5, y: 0.5 },
      colors: colors,
      startVelocity: 60,
      gravity: 0.9,
      shapes: ['square', 'circle'],
      ticks: 200,
      disableForReducedMotion: true,
      scalar: 1.2
    });
  }, 50);
}

function goHome(): void {
  router.push('/lobbies');
}

function getFromLocalStorage(key: string): string | null {
  if (typeof window !== 'undefined' && window.localStorage) {
    return localStorage.getItem(key);
  }
  return null;
}

async function fetchScoreboard() {
  try {
    const response = await axios.get(`${backendUrl}/game/${lobbyCode.value}/players`);

    if (!response.data || !Array.isArray(response.data)) {
      return;
    }

    const processedPlayers = response.data.map((player: any) => ({
      ...player,
      id: player.id.toString(),
      score: player.score || 0,
    }));

    players.value = processedPlayers.sort((a: Player, b: Player) => b.score - a.score);
  } catch (error) {
    console.error('Error fetching scoreboard:', error);
  }
}

onMounted(async () => {
  try {
    await fetchScoreboard();
    celebrateWinner();
  } catch (error) {
    console.error('Error during game initialization:', error);
  }
});

const sortedPlayers = computed(() => [...players.value].sort((a, b) => b.score - a.score));
</script>

<template>
  <div
    class="scoreboard-container bg-gradient-to-br from-gray-700 via-gray-800 to-gray-900 min-h-screen text-white flex flex-col items-center justify-center px-2 py-3"
  >
    <div
      class="winner-card relative overflow-hidden bg-gradient-to-r from-yellow-700 via-yellow-600 to-yellow-500 text-white rounded-2xl shadow-2xl p-8 mb-8 text-center transform"
    >
      <div class="absolute -top-12 -left-12 w-40 h-40 bg-yellow-300/20 rounded-full blur-3xl" />
      <div class="absolute -bottom-12 -right-12 w-40 h-40 bg-yellow-300/20 rounded-full blur-3xl" />
      <div class="mb-2 text-yellow-300 font-bold tracking-wider uppercase">
        Winner
      </div>
      <h1 class="relative text-5xl sm:text-6xl font-extrabold mb-3 tracking-tight">
        <span class="bg-clip-text text-transparent bg-gradient-to-r from-white to-yellow-200">
          {{ sortedPlayers[0]?.name || 'Unknown' }}
        </span>
      </h1>

      <div class="mt-6 inline-block bg-black/30 rounded-full px-6 py-2 border border-yellow-500/30">
        <p class="text-xl font-medium">
          <span class="text-yellow-300 font-bold">{{ sortedPlayers[0]?.score }}</span>
          <span class="text-yellow-100 ml-1">points</span>
        </p>
      </div>
    </div>

    <div class="final-scores w-full max-w-3xl rounded-xl p-4">
      <h2 class="text-3xl font-bold text-center mb-6 mt-5">
        Ranking
      </h2>
      <div
        v-for="(player, index) in players"
        :key="player.id"
        class="player-score flex items-center justify-between p-3 mb-2 rounded-lg transition-all duration-300"
        :class="{
          'from-yellow-600/50 to-yellow-500/30 bg-gradient-to-r border-l-4 border-yellow-400': index === 0,
          'from-gray-500/50 to-gray-400/30 bg-gradient-to-r border-l-4 border-gray-400': index === 1,
          'from-amber-800/50 to-amber-700/30 bg-gradient-to-r border-l-4 border-amber-700': index === 2,
          'from-gray-700/50 to-gray-600/30 bg-gradient-to-r border-l-4 border-gray-600': index >= 3,
        }"
      >
        <div class="flex items-center gap-3">
          <div class="rank flex items-center justify-center w-8 h-8 rounded-full bg-gray-900/60 text-lg font-bold">
            {{ index === 0 ? '🥇' : index === 1 ? '🥈' : index === 2 ? '🥉' : index + 1 }}
          </div>
          <div class="player-name text-bold text-base md:text-lg flex items-center">
            <span class="truncate max-w-[120px]">{{ player.name }}</span>
            <span
              v-if="player.id == getFromLocalStorage('playerId')"
              class="ml-2 text-xs text-blue-300"
            >(You)</span>
          </div>
        </div>
        <div class="player-points relative bg-gray-900/60 rounded-full px-4 py-1 text-lg font-bold">
          <span :class="{ 'text-yellow-300': index === 0, 'text-gray-300': index === 1, 'text-amber-600': index === 2 }">
            {{ player.score || 0 }}
          </span>
          <span class="text-sm text-gray-400 ml-0.5">pts</span>
        </div>
      </div>
    </div>

    <button
      class="mt-10 py-3 px-8 bg-blue-600 hover:bg-blue-700 text-white font-bold rounded-xl transition-colors duration-200"
      @click="goHome"
    >
      Go to Home
    </button>
  </div>
</template>
