<script lang="ts">
  import { fade } from "svelte/transition";
  import { getBookById, toOrdinal, getNextGradeMessage } from "$lib/utils/game";
  import { onMount } from "svelte";

  interface StatsData {
    solveRank: number;
    guessRank: number;
    totalSolves: number;
    averageGuesses: number;
  }

  interface WeightedMessage {
    text: string;
    weight: number;
  }

  let {
    grade,
    statsData,
    correctBookId,
    handleShare,
    copyToClipboard,
    copied = $bindable(false),
    statsSubmitted,
    guessCount,
  } = $props();

  let bookName = $derived(getBookById(correctBookId)?.name ?? "");
  let hasWebShare = $derived(
    typeof navigator !== "undefined" && "share" in navigator
  );
  let copySuccess = $state(false);

  // List of congratulations messages with weights
  const congratulationsMessages: WeightedMessage[] = [
    { text: "Congratulations!", weight: 10 },
    { text: "You got it!", weight: 1000 },
    { text: "Yup,", weight: 100 },
    { text: "Very nice!", weight: 1 },
  ];

  // Function to select a random message based on weights
  function getRandomCongratulationsMessage(): string {
    // Special case for first try success
    if (guessCount === 1) {
      const n = Math.random();
      if (n < 0.99) {
        return "🌟 First try! 🌟";
      } else {
        return "🗣️ Axios! 🗣️";
      }
    }

    const totalWeight = congratulationsMessages.reduce(
      (sum, msg) => sum + msg.weight,
      0
    );
    let random = Math.random() * totalWeight;

    for (const message of congratulationsMessages) {
      random -= message.weight;
      if (random <= 0) {
        return message.text;
      }
    }

    // Fallback to first message if something goes wrong
    return congratulationsMessages[0].text;
  }

  // Generate the congratulations message
  let congratulationsMessage = $derived(getRandomCongratulationsMessage());
</script>

<div
  class="p-8 sm:p-12 w-full bg-linear-to-r from-green-400 to-green-600 text-white rounded-2xl shadow-2xl text-center fade-in"
>
  <!-- <h2 class="text-2xl sm:text-4xl font-black mb-4 drop-shadow-lg">
    {congratulationsMessage}
  </h2> -->
  <p class="text-xl sm:text-3xl md:text-4xl">
    {congratulationsMessage} The verse is from
    <span class="font-black text-xl sm:text-2xl md:text-3xl">{bookName}</span>.
  </p>
  <p
    class="text-2xl font-bold mt-6 p-2 mx-2 bg-black/20 rounded-lg inline-block"
  >
    Your grade: {grade}
  </p>

  {#if hasWebShare}
    <button
      onclick={handleShare}
      data-umami-event="Share"
      class="mt-4 text-2xl font-bold p-2 bg-white/20 hover:bg-white/30 rounded-lg inline-block transition-all shadow-lg mx-2 cursor-pointer border-none appearance-none"
    >
      📤 Share
    </button>
    <button
      onclick={() => {
        copyToClipboard();
        copySuccess = true;
        setTimeout(() => {
          copySuccess = false;
        }, 3000);
      }}
      data-umami-event="Copy to Clipboard"
      class={`mt-4 text-2xl font-bold p-2 rounded-lg inline-block transition-all shadow-lg mx-2 cursor-pointer border-none appearance-none ${
        copySuccess
          ? "bg-green-400/50 hover:bg-green-500/60"
          : "bg-white/20 hover:bg-white/30"
      }`}
    >
      {copySuccess ? "✅ Copied!" : "📋 Copy to clipboard"}
    </button>
  {:else}
    <button
      onclick={handleShare}
      data-umami-event="Share"
      class={`mt-4 text-2xl font-bold p-2 ${
        copied
          ? "bg-green-400/50 hover:bg-green-500/60"
          : "bg-white/20 hover:bg-white/30"
      } rounded-lg inline-block transition-all shadow-lg mx-2 cursor-pointer border-none appearance-none`}
    >
      {copied ? "Copied to clipboard!" : "📤 Share"}
    </button>
  {/if}

  <p class="pt-6 big-text text-gray-100!">
    {getNextGradeMessage(guessCount)}
  </p>

  <!-- Statistics Display -->
  {#if statsData}
    <div class="mt-6" in:fade={{ delay: 800 }}>
      <div class="grid grid-cols-3 gap-4 gap-x-8 text-center">
        <!-- Solve Rank Column -->
        <div class="flex flex-col">
          <div class="text-3xl sm:text-4xl font-black">
            #{statsData.solveRank}
          </div>
          <div class="text-xs sm:text-sm opacity-90 mt-1">
            You were the {toOrdinal(statsData.solveRank)} person to solve today
          </div>
        </div>

        <!-- Guess Rank Column -->
        <div class="flex flex-col">
          <div class="text-3xl sm:text-4xl font-black">
            {Math.round(
              ((statsData.totalSolves - statsData.guessRank + 1) /
                statsData.totalSolves) *
                100
            )}%
          </div>
          <div class="text-xs sm:text-sm opacity-90 mt-1">
            You ranked {toOrdinal(statsData.guessRank)} of {statsData.totalSolves}
            total solves
          </div>
        </div>

        <!-- Average Column -->
        <div class="flex flex-col">
          <div class="text-3xl sm:text-4xl font-black">
            {statsData.averageGuesses}
          </div>
          <div class="text-xs sm:text-sm opacity-90 mt-1">
            People guessed correctly after {statsData.averageGuesses}
            {statsData.averageGuesses === 1 ? "guess" : "guesses"} on average
          </div>
        </div>
      </div>
    </div>
  {:else if !statsSubmitted}
    <div class="mt-6 text-sm opacity-80">Submitting stats...</div>
  {/if}
</div>

<style>
  @keyframes fadeIn {
    from {
      opacity: 0;
      transform: translateY(-10px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }

  .fade-in {
    animation: fadeIn 0.5s ease-out;
  }
</style>
