import { createGrid, checkLine, clearAndEvolve, animals, Grid } from "./grid";

const gridElement = document.getElementById("grid")!;
const celebrationModal = document.getElementById("celebration-modal")!;
let grid = createGrid();

function renderGrid() {
  gridElement.innerHTML = ""; // Clear the grid
  grid.forEach((row, rowIndex) => {
    row.forEach((cell, colIndex) => {
      const cellElement = document.createElement("div");
      cellElement.classList.add("cell");
      if (cell) {
        cellElement.textContent = cell;
        cellElement.classList.add("occupied");
      }
      cellElement.addEventListener("click", () => handleCellClick(rowIndex, colIndex));
      gridElement.appendChild(cellElement);
    });
  });
}

function handleCellClick(row: number, col: number) {
  if (grid[row][col]) return; // Ignore clicks on occupied cells

  grid[row][col] = animals[0]; // Place a worm
  let needCheck = true
  while (needCheck) {
    const animal = grid[row][col];
    if (animals.indexOf(animal) !== animals.length - 1) {
      if (checkLine(grid, row, col, 3)) {
        clearAndEvolve(grid, row, col, 3);
      } else {
        needCheck = false
      }
    } else {
      needCheck = false
    }
  }
  checkUnicornCelebration(); // Check if 3+ unicorns aligned
  renderGrid();
}

function checkUnicornCelebration() {
  for (let row = 0; row < grid.length; row++) {
    for (let col = 0; col < grid[row].length; col++) {
      if (grid[row][col] === "🦄" && checkLine(grid, row, col, 3)) {
        triggerCelebration();
        return;
      }
    }
  }
}

function triggerCelebration() {
  // Show confetti
  confetti({
    particleCount: 100,
    spread: 70,
    origin: { y: 0.6 },
  });

  // Show celebration modal
  celebrationModal.classList.remove("hidden");

  // Hide modal after a few seconds
  setTimeout(() => {
    celebrationModal.classList.add("hidden");
  }, 3000);
}

// Initialize the game
renderGrid();
