<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Tic-Tac-Toe</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <style>
    /* Animasi untuk pemenang */
    .win-highlight {
      animation: highlight 1s ease-in-out infinite alternate;
    }
    @keyframes highlight {
      from {
        background-color: #4ade80;
      }
      to {
        background-color: #22c55e;
      }
    }
  </style>
</head>
<body class="bg-gradient-to-r from-purple-600 to-pink-600 text-white min-h-screen flex flex-col items-center justify-center">
  <h1 class="text-5xl font-bold mb-6">❌ Tic-Tac-Toe ⭕</h1>

  <!-- Level Selection -->
  <div id="levelSelector" class="text-center mb-6">
    <p class="text-xl mb-4">Pilih tingkat kesulitan:</p>
    <button onclick="startGame('normal')" class="bg-blue-500 hover:bg-blue-700 text-white py-2 px-4 rounded mx-2">Normal</button>
    <button onclick="startGame('medium')" class="bg-yellow-500 hover:bg-yellow-700 text-white py-2 px-4 rounded mx-2">Medium</button>
    <button onclick="startGame('extreme')" class="bg-red-500 hover:bg-red-700 text-white py-2 px-4 rounded mx-2">Extreme</button>
  </div>

  <!-- Game Board -->
  <div id="gameBoard" class="grid grid-cols-3 gap-2 w-72 h-72 hidden">
    <!-- Sel akan diisi dengan JavaScript -->
  </div>

  <!-- Status -->
  <div id="status" class="text-center text-lg font-medium mt-4 hidden"></div>
  <button onclick="resetGame()" id="resetButton" class="hidden mt-4 bg-blue-600 hover:bg-blue-800 text-white py-2 px-4 rounded">Main Lagi</button>

  <a href="index.html" class="mt-6 text-blue-300 hover:underline">Kembali ke Beranda</a>

  <script>
    let board = ["", "", "", "", "", "", "", "", ""];
    let currentPlayer = "❌";
    let botLevel = "normal"; // Default level
    let gameActive = true;
    const gameBoard = document.getElementById("gameBoard");
    const statusText = document.getElementById("status");
    const levelSelector = document.getElementById("levelSelector");
    const resetButton = document.getElementById("resetButton");

    // Mulai permainan
    function startGame(level) {
      botLevel = level;
      levelSelector.classList.add("hidden");
      gameBoard.classList.remove("hidden");
      resetButton.classList.remove("hidden");
      statusText.classList.remove("hidden");
      initializeBoard();
      statusText.textContent = `Giliran: ${currentPlayer}`;
    }

    // Inisialisasi papan
    function initializeBoard() {
      gameBoard.innerHTML = "";
      board = ["", "", "", "", "", "", "", "", ""];
      currentPlayer = "❌";
      gameActive = true;

      board.forEach((_, index) => {
        const cell = document.createElement("div");
        cell.className = "flex items-center justify-center bg-white text-black text-3xl font-bold border border-gray-300 cursor-pointer transition duration-200 transform hover:scale-105";
        cell.dataset.index = index;
        cell.addEventListener("click", handlePlayerMove);
        gameBoard.appendChild(cell);
      });
    }

    // Logika klik pemain
    function handlePlayerMove(event) {
      const cellIndex = event.target.dataset.index;

      if (board[cellIndex] !== "" || !gameActive || currentPlayer !== "❌") return;

      board[cellIndex] = currentPlayer;
      event.target.textContent = currentPlayer;

      if (checkWin()) return endGame(`${currentPlayer} Menang!`);
      if (board.every(cell => cell !== "")) return endGame("Seri!");

      currentPlayer = "⭕";
      statusText.textContent = `Giliran: ${currentPlayer}`;
      setTimeout(botMove, 500);
    }

    // Logika bot
    function botMove() {
      if (!gameActive) return;

      let move;

      if (botLevel === "normal") {
        move = randomMove();
      } else if (botLevel === "medium") {
        move = strategicMove() || randomMove();
      } else if (botLevel === "extreme") {
        move = minimax(board, "⭕").index;
      }

      board[move] = "⭕";
      const cell = gameBoard.children[move];
      cell.textContent = "⭕";

      if (checkWin()) return endGame(`${currentPlayer} Menang!`);
      if (board.every(cell => cell !== "")) return endGame("Seri!");

      currentPlayer = "❌";
      statusText.textContent = `Giliran: ${currentPlayer}`;
    }

    // Random move untuk level normal
    function randomMove() {
      const available = board.map((cell, index) => (cell === "" ? index : null)).filter(index => index !== null);
      return available[Math.floor(Math.random() * available.length)];
    }

    // Strategi bot untuk medium (menang jika bisa, blokir jika perlu)
    function strategicMove() {
      const winPatterns = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6],
      ];

      for (let pattern of winPatterns) {
        const [a, b, c] = pattern;
        if (board[a] === "⭕" && board[b] === "⭕" && board[c] === "") return c;
        if (board[a] === "⭕" && board[c] === "⭕" && board[b] === "") return b;
        if (board[b] === "⭕" && board[c] === "⭕" && board[a] === "") return a;
      }

      for (let pattern of winPatterns) {
        const [a, b, c] = pattern;
        if (board[a] === "❌" && board[b] === "❌" && board[c] === "") return c;
        if (board[a] === "❌" && board[c] === "❌" && board[b] === "") return b;
        if (board[b] === "❌" && board[c] === "❌" && board[a] === "") return a;
      }

      return null;
    }

    // Algoritma Minimax untuk level extreme
    function minimax(newBoard, player) {
      const availableSpots = board.map((cell, index) => (cell === "" ? index : null)).filter(index => index !== null);

      if (checkWinFor(newBoard, "❌")) return { score: -10 };
      if (checkWinFor(newBoard, "⭕")) return { score: 10 };
      if (availableSpots.length === 0) return { score: 0 };

      const moves = [];
      for (let spot of availableSpots) {
        const move = {};
        move.index = spot;
        newBoard[spot] = player;

        if (player === "⭕") {
          move.score = minimax(newBoard, "❌").score;
        } else {
          move.score = minimax(newBoard, "⭕").score;
        }

        newBoard[spot] = "";
        moves.push(move);
      }

      let bestMove;
      if (player === "⭕") {
        bestMove = moves.reduce((a, b) => (a.score > b.score ? a : b));
      } else {
        bestMove = moves.reduce((a, b) => (a.score < b.score ? a : b));
      }

      return bestMove;
    }

    // Cek kemenangan
    function checkWin() {
      const winPatterns = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6],
      ];

      for (let pattern of winPatterns) {
        const [a, b, c] = pattern;
        if (board[a] && board[a] === board[b] && board[a] === board[c]) {
          pattern.forEach(index => gameBoard.children[index].classList.add("win-highlight"));
          return true;
        }
      }

      return false;
    }

    // Cek kemenangan khusus Minimax
    function checkWinFor(newBoard, player) {
      const winPatterns = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6],
      ];

      return winPatterns.some(pattern => {
        const [a, b, c] = pattern;
        return newBoard[a] === player && newBoard[a] === newBoard[b] && newBoard[a] === newBoard[c];
      });
    }

    // Akhiri permainan
    function endGame(message) {
      statusText.textContent = message;
      gameActive = false;
    }

    // Reset permainan
    function resetGame() {
      initializeBoard();
      statusText.textContent = `Giliran: ❌`;
      gameActive = true;
      currentPlayer = "❌";
    }
  </script>
</body>
</html>