"use client";

import * as React from "react";
import { Bot, Flag, Star } from "lucide-react";
import { cn } from "@/lib/utils";
import { DIRECTION_LABELS, type Direction, type GridPoint } from "@/lib/simulator";

export interface GridSpec {
  width: number;
  height: number;
  walls: [number, number][];
  stars: [number, number][];
  goal: { x: number; y: number };
}

/**
 * Render the robot's world.
 *
 * Purely presentational — it takes a *frame* (position, heading, collected
 * stars) and draws it. Animation is the caller's job, which keeps this
 * component usable both for the static starting position and for stepping
 * through a recorded trace.
 */
export function SimulatorGrid({
  spec,
  x,
  y,
  dir,
  collected,
  blocked = false,
  cellSize = 44,
  className,
}: {
  spec: GridSpec;
  x: number;
  y: number;
  dir: Direction;
  collected: GridPoint[];
  blocked?: boolean;
  cellSize?: number;
  className?: string;
}) {
  const wallKeys = React.useMemo(
    () => new Set(spec.walls.map(([wx, wy]) => `${wx},${wy}`)),
    [spec.walls]
  );
  const starKeys = React.useMemo(
    () => new Set(spec.stars.map(([sx, sy]) => `${sx},${sy}`)),
    [spec.stars]
  );
  const collectedKeys = React.useMemo(
    () => new Set(collected.map((point) => `${point.x},${point.y}`)),
    [collected]
  );

  // Rotate the robot glyph so its "nose" points along the heading.
  const rotation = { north: -90, east: 0, south: 90, west: 180 }[dir];

  return (
    <div
      className={cn("inline-block overflow-hidden rounded-lg border border-line bg-sunken p-2", className)}
    >
      <div
        className="relative grid gap-px"
        style={{
          gridTemplateColumns: `repeat(${spec.width}, ${cellSize}px)`,
          gridTemplateRows: `repeat(${spec.height}, ${cellSize}px)`,
        }}
        role="img"
        aria-label={`Grid ${spec.width} kali ${spec.height}. Robot di (${x}, ${y}) menghadap ${DIRECTION_LABELS[dir]}.`}
      >
        {Array.from({ length: spec.height }).flatMap((_, row) =>
          Array.from({ length: spec.width }).map((__, column) => {
            const key = `${column},${row}`;
            const isWall = wallKeys.has(key);
            const isStar = starKeys.has(key) && !collectedKeys.has(key);
            const isGoal = spec.goal.x === column && spec.goal.y === row;
            const isRobot = x === column && y === row;

            return (
              <div
                key={key}
                className={cn(
                  "relative flex items-center justify-center",
                  isWall
                    ? "bg-brand-500 dark:bg-brand-400"
                    : "bg-surface",
                  !isWall && (column + row) % 2 === 0 && "bg-sunken"
                )}
              >
                {isStar ? (
                  <Star className="size-5 fill-warning-400 text-warning-500" aria-hidden="true" />
                ) : null}

                {isGoal && !isWall ? (
                  <Flag className="size-5 text-success-600 dark:text-success-500" aria-hidden="true" />
                ) : null}

                {isRobot ? (
                  <span
                    className={cn(
                      "absolute inset-1 flex items-center justify-center text-inverse transition-transform",
                      blocked ? "bg-danger-600" : "bg-brand-600"
                    )}
                    style={{ transform: `rotate(${rotation}deg)` }}
                  >
                    <Bot className="size-5" aria-hidden="true" />
                  </span>
                ) : null}
              </div>
            );
          })
        )}
      </div>
    </div>
  );
}
