local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Workspace = game:GetService("Workspace")

local remotes = ReplicatedStorage:WaitForChild("Remotes")
local stateSync = remotes:WaitForChild("StateSync") :: RemoteEvent

local root = Workspace:FindFirstChild("BuildAZooClientView")
if root == nil then
	root = Instance.new("Folder")
	root.Name = "BuildAZooClientView"
	root.Parent = Workspace
end

local gridFolder = Instance.new("Folder")
gridFolder.Name = "Grid"
gridFolder.Parent = root

local cellsFolder = Instance.new("Folder")
cellsFolder.Name = "Cells"
cellsFolder.Parent = root

local function clearFolder(folder)
	for _, child in ipairs(folder:GetChildren()) do
		child:Destroy()
	end
end

local function makeTile(x, y)
	local part = Instance.new("Part")
	part.Name = string.format("Tile_%d_%d", x, y)
	part.Size = Vector3.new(4, 0.2, 4)
	part.Anchored = true
	part.Position = Vector3.new(x * 4, 0, y * 4)
	part.Material = Enum.Material.SmoothPlastic
	part.Color = Color3.fromRGB(80, 120, 80)
	part.Parent = gridFolder
end

local function makeCellPart(key, cell)
	local xText, yText = string.match(key, "^(%d+)_(%d+)$")
	if xText == nil or yText == nil then
		return
	end
	local x = tonumber(xText)
	local y = tonumber(yText)

	local part = Instance.new("Part")
	part.Name = "Cell_" .. key
	part.Anchored = true
	part.Size = Vector3.new(3.2, 2.5, 3.2)
	part.Position = Vector3.new(x * 4, 1.3, y * 4)
	if cell.kind == "egg" then
		part.Shape = Enum.PartType.Ball
		part.Color = Color3.fromRGB(240, 230, 120)
	else
		part.Shape = Enum.PartType.Block
		part.Color = Color3.fromRGB(130, 180, 240)
	end
	part.Parent = cellsFolder
end

local function renderState(payload)
	if payload.grid == nil then
		return
	end

	clearFolder(gridFolder)
	clearFolder(cellsFolder)

	for x = 1, payload.grid.width do
		for y = 1, payload.grid.height do
			makeTile(x, y)
		end
	end

	for key, cell in pairs(payload.grid.cells) do
		makeCellPart(key, cell)
	end
end

stateSync.OnClientEvent:Connect(function(payload)
	if payload.error then
		return
	end
	renderState(payload)
end)
