const canvas = document.getElementById("board");
const ctx = canvas.getContext("2d");
const scoreEl = document.getElementById("score");
const highEl = document.getElementById("high");
const SIZE = 20, COLS = canvas.width / SIZE;
let snake, dir, food, score, gameOver;
let high = Number(localStorage.getItem("snake_high") || 0);
highEl.textContent = high;

function reset() {
  snake = [{ x: 10, y: 10 }];
  dir = { x: 1, y: 0 };
  score = 0;
  gameOver = false;
  placeFood();
  scoreEl.textContent = score;
}

function placeFood() {
  do { food = { x: Math.floor(Math.random()*COLS), y: Math.floor(Math.random()*COLS) }; }
  while (snake.some(s => s.x === food.x && s.y === food.y));
}

function tick() {
  if (gameOver) return;
  const head = { x: snake[0].x + dir.x, y: snake[0].y + dir.y };
  if (head.x < 0 || head.x >= COLS || head.y < 0 || head.y >= COLS || snake.some(s => s.x === head.x && s.y === head.y)) {
    gameOver = true;
    if (score > high) { high = score; localStorage.setItem("snake_high", high); highEl.textContent = high; }
    alert(`Game Over! Score: ${score}`);
    reset();
    return;
  }
  snake.unshift(head);
  if (head.x === food.x && head.y === food.y) { score++; scoreEl.textContent = score; placeFood(); }
  else snake.pop();
  draw();
}

function draw() {
  ctx.fillStyle = "#0f172a";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "#ef4444";
  ctx.fillRect(food.x * SIZE, food.y * SIZE, SIZE - 1, SIZE - 1);
  snake.forEach((s, i) => {
    ctx.fillStyle = i === 0 ? "#22c55e" : "#16a34a";
    ctx.fillRect(s.x * SIZE, s.y * SIZE, SIZE - 1, SIZE - 1);
  });
}

document.addEventListener("keydown", (e) => {
  const k = e.key.toLowerCase();
  if ((k === "arrowup" || k === "w") && dir.y !== 1) dir = { x: 0, y: -1 };
  else if ((k === "arrowdown" || k === "s") && dir.y !== -1) dir = { x: 0, y: 1 };
  else if ((k === "arrowleft" || k === "a") && dir.x !== 1) dir = { x: -1, y: 0 };
  else if ((k === "arrowright" || k === "d") && dir.x !== -1) dir = { x: 1, y: 0 };
});

reset();
setInterval(tick, 120);