<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Elemental Awareness Game</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
      .animate-scale {
        animation: scale-up 0.3s ease-in-out;
      }
      @keyframes scale-up {
        0% {
          transform: scale(1);
        }
        50% {
          transform: scale(1.1);
        }
        100% {
          transform: scale(1);
        }
      }

      .progress-bar {
        height: 10px;
        border-radius: 5px;
      }

      /* Flexbox for two sections */
      .game-layout {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .game-content {
        flex: 1;
        padding: 16px;
        text-align: center;
      }

      .game-image {
        flex: 1;
        padding: 16px;
        display: flex;
        justify-content: center;
      }

      .game-image img {
        max-width: 100%;
        height: auto;
      }

      .sprite-container {
        width: 532px; /* Tentukan ukuran gambar */
        height: 532px; /* Sesuaikan dengan tinggi gambar */
        overflow: hidden;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
      }

      .sprite {
        width: 140px; /* Lebar gambar */
        height: 527px; /* Tinggi gambar */
        background-image: url("./images/sprites.jpg"); /* Lokasi gambar sprite */
        background-size: auto;
        animation: moveBackground 27s linear forwards;
      }

      .barometer {
        position: relative;
        width: 30px;
        height: 300px;
        background-color: #f0f0f0;
        border-radius: 15px;
        overflow: hidden;
        margin: 20px auto;
      }
      .barometer-fill {
        width: 100%;
        background: linear-gradient(180deg, rgba(255,173,0,1) 0%, rgba(173,0,255,1) 100%);
        height: 0%;
        transition: height 0.5s ease;
        position: absolute;
        border-radius: 15px;
        bottom: 0;
      }
      .barometer-text {
        background: radial-gradient(circle, rgba(255,173,0,1) 0%, rgba(255,0,120,1) 33%, rgba(173,0,255,1) 75%, rgba(57,2,83,1) 96%);
        display: flex;
        justify-content: center;
        padding: 4px 0px;
        border-radius: 50px;
        font-weight: bold;
        color: white;
      }

      @keyframes moveBackground {
        0% {
          background-position: 0px;
        }
        33.33% {
          background-position: -130px;
        }
        66.66% {
          background-position: -260px;
        }
        100% {
          background-position: -400px;
        }
      }

      .trimester-step-container {
        position: relative;
        width: 100%; /* Ukuran gambar */
        height: 100px; /* Ukuran gambar */
        overflow: hidden;
      }
      .trimester-step {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: url('./images/trimester\ steps.png') no-repeat center/contain;
        clip-path: inset(0 100% 0 0); /* Menyembunyikan seluruh gambar kecuali sisi kiri */
        transition: clip-path 15s linear;
      }
      .treshold {
        width: 100%;
        background: #c3c3c3;
        height: 40%;
        transition: height 0.5s ease;
        position: absolute;
        bottom: 0;
        border-radius: 15px;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .treshold p {
        writing-mode: vertical-rl;
        font-weight: bold;
        font-size: 15px;
      }
    </style>
  </head>
  <body class="bg-gray-100 text-gray-800">
    <div class="container mx-auto p-8">
      <h1 class="text-xl sm:text-4xl font-bold mb-2 sm:mb-6 text-center">
        Let's Fight Pre-eclampsia
      </h1>
      <p class="text-sm sm:text-lg mb-4 text-center">
        Choose the right calcium product to prevent preeclampsia!
      </p>

      <!-- Timer and Progress Bar -->
      <div class="mb-4">
        <div
          id="timer"
          class="text-sm sm:text-xl font-semibold text-red-600 mb-2 text-center"
        >
          Time Left: <span id="time">15</span>s
        </div>
        <progress
          id="progress-bar"
          class="progress-bar w-full"
          value="0"
          max="100"
        ></progress>
      </div>

      <!-- Game Layout -->
      <div class="game-layout flex-col-reverse sm:flex-row">
        <!-- Game Content Section (Right side) -->
        <div class="flex-1 sm:p-[16px] text-center">
          <div id="game-container" class="bg-white p-6 rounded-lg shadow-md">
            <h2 class=" text-xl sm:text-2xl font-semibold mb-4">Choose your weapon!</h2>
            <div id="options" class="grid grid-cols-2 gap-4">
              <!-- Options will be dynamically inserted here -->
            </div>
          </div>

          <!-- Result Message -->
          <div id="result-container" class="mt-6 hidden">
            <h2 id="result-message" class="text-3xl font-bold"></h2>
            <p id="result-choices" class="text-lg mt-4"></p>
            <button
              id="restart-btn"
              class="bg-green-500 text-white px-4 py-2 rounded-lg mt-4"
            >
              Restart
            </button>
          </div>
        </div>

        <div class="absolute right-0 sm:pr-4 sm:relative sm:pr-0 top-[35%] sm:top-0">
          <div class="barometer">
            <div class="treshold">
              <p>Pre-eclampsia</p>
            </div>
            <div class="barometer-fill" id="barometer-fill">
              <p class="barometer-text
              ">Ca</p>
            </div>
          </div>
        </div>

        <!-- Game Image Section (Left side) -->
        <div class="flex-1 sm:p-[16px] flex justify-center items-center">
          <!-- <img src="https://i.pinimg.com/originals/0e/24/87/0e248740ea773e318d9c74e903cf09eb.gif" alt="Game Animation"> -->
          <div id="ongame-image" class="sm:w-[532px] sm:h-[532px] overflow-hidden flex justify-center items-center flex-col">
            <!-- <div class="sprite"></div>walaweee -->
            <video id="illustration-video" autoplay muted playsinline>
              <source src="./illustration.mp4" type="video/mp4">
              Your browser does not support the video tag.
            </video>
            <div class="trimester-step-container">
              <div class="trimester-step" id="trimester-step"></div>
            </div>
          </div>
          <div id="end-image" class="hidden">
            <img id="end-img" src="./images/pregnant-failed.avif" />
          </div>
        </div>
      </div>
    </div>

    <audio id="audio-benar" src="./benar.wav"></audio>
    <audio id="audio-salah" src="./salah.wav"></audio>
    <script>
      const video = document.getElementById('illustration-video');
      video.playbackRate = 2;

      document.addEventListener("DOMContentLoaded", () => {
        const totalTime = 15; // Total time in seconds
        let timeLeft = totalTime;
        let timer;
        let gameOver = false; // Flag to indicate if game is over
        const progressBar = document.getElementById("progress-bar");
        const timerElement = document.getElementById("time");
        const gameContainer = document.getElementById("game-container");
        const resultContainer = document.getElementById("result-container");
        const resultMessage = document.getElementById("result-message");
        const resultChoices = document.getElementById("result-choices");
        const restartButton = document.getElementById("restart-btn");
        const optionsContainer = document.getElementById("options");
        const endImage = document.getElementById("end-image");
        const endImg = document.getElementById("end-img");
        const ongameImage = document.getElementById("ongame-image");
        let calciumLevel = 0; // Nilai awal kadar kalsium
        const maxCalcium = 70; // Batas maksimum barometer
        const minimumFormicalSelected = 4; // Jumlah minimum Formical-B yang harus dipilih
        let formicalSelected = 0; // Jumlah Formical-B yang sudah dipilih
        const barometerFill = document.getElementById("barometer-fill");

        const options = [
          {
            id: "formical",
            name: "Formical-B",
            color: "bg-blue-100",
            textColor: "text-blue-600",
            description: "Boost Calcium levels 7x more than Coral Calcium",
            image: "./images/formical-b.png",
          },
          {
            id: "coral",
            name: "Generic Calcium",
            color: "bg-red-100",
            textColor: "text-red-600",
            description: "Contains standard Calcium, with less elemental Calcium",
            image: "./images/generic-calcium.png",
          },
          {
            id: "cal95",
            name: "Coral Calcium",
            color: "bg-green-100",
            textColor: "text-green-600",
            description: "Contains Coral Calcium, with less elemental Calcium",
            image: "./images/cal-95.png",
          },
          {
            id: "cavit",
            name: "Phosphate Calcium",
            color: "bg-yellow-100",
            textColor: "text-yellow-600",
            description:
              "Contains Phosphate Calcium, with less elemental Calcium",
            image: "./images/cavit-d3.png",
          },
        ];

        let selectedOption = null;
        let incorrectChoice = false; // Track if the player made an incorrect choice
        let correctChoices = 0; // Track the number of correct choices
        let totalChoices = 0; // Track the total number of choices

        // Track number of choices for each option
        let optionChoices = {
          formical: 0,
          coral: 0,
          cal95: 0,
          cavit: 0,
        };

        function startCountdown() {
          timer = setInterval(() => {
            if (gameOver) return;

            timeLeft--;
            timerElement.textContent = timeLeft;
            progressBar.value = ((totalTime - timeLeft) / totalTime) * 100;

            if (timeLeft <= 0) {
              clearInterval(timer);
              if (incorrectChoice || totalChoices === 0 || formicalSelected < minimumFormicalSelected) {
                endGame(false, "Oh no! You failed to prevent preeclampsia.");
              } else {
                endGame(
                  true,
                  "Great! You successfully prevented preeclampsia."
                );
              }
            }
          }, 1000);
        }

        function endGame(win, message) {
          clearInterval(timer);
          gameContainer.classList.add("hidden");
          resultContainer.classList.remove("hidden");
          resultMessage.textContent = message;
          resultMessage.classList.add(win ? "text-green-600" : "text-red-600");
          endImage.classList.remove("hidden");
          ongameImage.classList.add("hidden");

          if (win) {
            endImg.src = "./images/happy.png";
          } else {
            endImg.src = "./images/pregnant-failed.png";
          }

          gameOver = true;
        }

        function shuffleOptions(options) {
          // Shuffle the options array
          for (let i = options.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [options[i], options[j]] = [options[j], options[i]];
          }
          return options;
        }

        function displayOptions() {
          // Shuffle options and display them
          const shuffledOptions = shuffleOptions([...options]);
          optionsContainer.innerHTML = "";

          shuffledOptions.forEach((option) => {
            const optionElement = document.createElement("div");
            optionElement.id = option.id;
            optionElement.classList.add(
              "p-4",
              "rounded-lg",
              "shadow-md",
              "cursor-pointer",
              "hover:bg-opacity-80",
              "transition-all",
              "animate-scale",
              // "hover:border-2",
              // `hover:border-black`,
              option.color
            );
            optionElement.innerHTML = `
                        <img src="${option.image}" alt="${option.name}" class="mx-auto mb-2 h-[50px] sm:h-[100px]">
                        <p class="text-sm sm:text-md font-semibold ${option.textColor}">${option.name}</p>
                        <p class="text-xs sm:text-sm">${option.description}</p>
                    `;
            optionsContainer.appendChild(optionElement);
          });
        }

        function addBarometer(calcium) {
          calciumLevel = Math.min(calciumLevel + calcium, maxCalcium);

          // Update UI barometer
          const percentage = (calciumLevel / maxCalcium) * 100;
          barometerFill.style.height = `${percentage}%`;

          // Check if calcium level is full
          if (calciumLevel >= maxCalcium) {
            clearInterval(timer);
            if (incorrectChoice || totalChoices === 0 || formicalSelected < minimumFormicalSelected) {
                endGame(false, "Oh no! You failed to prevent preeclampsia.");
              } else {
                endGame(
                  true,
                  "Great! You successfully prevented preeclampsia."
                );
              }
          }
        }

        // Event listener for dynamic options
        optionsContainer.addEventListener("click", (event) => {
          if (event.target.closest(".cursor-pointer")) {
            const selected = event.target.closest(".cursor-pointer");
            const selectedId = selected.id;

            // Track total choices
            totalChoices++;

            // Track choice for each option
            optionChoices[selectedId]++;

            // If the selected option is Formical-B, increment correctChoices
            if (selectedId === "formical") {
              document.getElementById('audio-benar').play();
              correctChoices++;
              formicalSelected++;
              addBarometer(7);
            } else {
              document.getElementById('audio-salah').play();
              incorrectChoice = true;
              if (selectedId === "cal95") {
                addBarometer(1);
              } else if (selectedId === "cavit") {
                addBarometer(3);
              } else {
                addBarometer(1);
              }
            }

            // Shuffle options and continue the game
            displayOptions();
          }
        });

        // Restart button
        restartButton.addEventListener("click", () => {
          window.location = "/";
        });

        // Start the game
        displayOptions();
        startCountdown();
      });

      window.onload = () => {
        const image = document.getElementById('trimester-step');
        // Mulai efek terisi
        image.style.clipPath = 'inset(0 0 0 0)';
      };
    </script>
  </body>
</html>
