import React, { useState } from "react";

import styles from "./StarterGridGame.module.css";

const boardSize = 8;
const initialPlayer = { x: 1, y: 1 };
const target = { x: 6, y: 5 };

export function StarterGridGame() {
  const [player, setPlayer] = useState(initialPlayer);
  const [score, setScore] = useState(0);

  function move(dx: number, dy: number) {
    setPlayer((current) => {
      const next = {
        x: clamp(current.x + dx, 0, boardSize - 1),
        y: clamp(current.y + dy, 0, boardSize - 1),
      };

      if (next.x === target.x && next.y === target.y) {
        setScore((currentScore) => currentScore + 1);
        return initialPlayer;
      }

      return next;
    });
  }

  return (
    <section className={styles.game}>
      <div className={styles.board} aria-label="Starter game board">
        {Array.from({ length: boardSize * boardSize }).map((_, index) => {
          const x = index % boardSize;
          const y = Math.floor(index / boardSize);
          const isPlayer = player.x === x && player.y === y;
          const isTarget = target.x === x && target.y === y;

          return (
            <div className={styles.cell} key={`${x}-${y}`}>
              {isTarget && <span className={styles.target} />}
              {isPlayer && <span className={styles.player} />}
            </div>
          );
        })}
      </div>
      <aside className={styles.panel}>
        <p className={styles.score}>Score: {score}</p>
        <p className={styles.status}>Move the blue square to the green dot.</p>
        <div className={styles.buttons} aria-label="Move player">
          <button onClick={() => move(0, -1)} aria-label="Move up">
            Up
          </button>
          <button onClick={() => move(-1, 0)} aria-label="Move left">
            Left
          </button>
          <button onClick={() => move(1, 0)} aria-label="Move right">
            Right
          </button>
          <button onClick={() => move(0, 1)} aria-label="Move down">
            Down
          </button>
        </div>
      </aside>
    </section>
  );
}

function clamp(value: number, min: number, max: number) {
  return Math.min(Math.max(value, min), max);
}
