Road placement system doesnt work like i want it to

First i tried scripting it by myself and could not make it work. Then i used AI which made it work somewhat. But right now the snapping is buggy and for some reason only curved roads can snap onto other roads. If i try to snap a straight road onto another straight road it just wont let me.

All this is in a client script.

Here are the roadObjects. They all have 2 or more attachments on the edges of the road. Each attachment has an attribute named SnapType and they’re either “End” or “Side” to determine in the script what side its snapping to. I’ve lost track of what even happens in this script cuz ive had an AI redo it so many times and it just doesnt ever work exactly how i like it to.

Function LocalScript

local player = game.Players.LocalPlayer
local runService = game:GetService("RunService")
local uis = game:GetService("UserInputService")
local repStorage = game:GetService("ReplicatedStorage")
local camera = workspace.CurrentCamera

local roadBuildingFrame = script.Parent
local straightButton = roadBuildingFrame:FindFirstChild("StraightRoad")
local deg90Button = roadBuildingFrame:FindFirstChild("90DegreeRoad")
local deg45Button = roadBuildingFrame:FindFirstChild("45DegreeRoad")
local sCurveButton = roadBuildingFrame:FindFirstChild("sCurveRoad")

local roadStorage = repStorage:WaitForChild("RoadObjects")
local straightRoad = roadStorage:WaitForChild("StraightRoad")
local deg90Road = roadStorage:WaitForChild("90DegreesRoad")
local deg45Road = roadStorage:WaitForChild("45DegreesRoad")
local sCurveRoad = roadStorage:WaitForChild("sCurveRoad")

local placing = false
local ghost = nil
local placedRoads = {}
local selectedRoad = straightRoad
local currentRotation = 0
local snapThreshold = 3
local maxHeight = 50
local lastSelectedRoad = nil

local function collectAttachments(obj)
	local out = {}
	if obj:IsA("BasePart") then
		for _, child in ipairs(obj:GetChildren()) do
			if child:IsA("Attachment") then table.insert(out, child) end
		end
	else
		for _, descendant in ipairs(obj:GetDescendants()) do
			if descendant:IsA("Attachment") then table.insert(out, descendant) end
		end
	end
	return out
end

local function getAttachmentWorldCFrame(att)
	if not att or not att.Parent then return nil end
	if att.Parent:IsA("BasePart") then
		return att.Parent.CFrame * att.CFrame
	end
	if att.WorldPosition then
		return CFrame.new(att.WorldPosition)
	end
	return nil
end

local function screenRaycastFromMouse(ignoreInstances, maxDistance)
	local cam = workspace.CurrentCamera or camera
	local mouseLocation = uis:GetMouseLocation()
	local ray = cam:ScreenPointToRay(mouseLocation.X, mouseLocation.Y)
	local origin = ray.Origin
	local direction = ray.Direction
	local rayDir = direction * (maxDistance or 500)
	local params = RaycastParams.new()
	params.FilterType = Enum.RaycastFilterType.Exclude
	params.FilterDescendantsInstances = ignoreInstances or {}
	params.IgnoreWater = false
	return workspace:Raycast(origin, rayDir, params)
end

-- Stable snapping logic for Parts/Unions, including End→End for straight roads
local function computeSnapCandidate(ghost, mousePos)
	if not ghost then return nil end
	local ghostAtts = collectAttachments(ghost)
	if #ghostAtts == 0 then return nil end

	-- Find ghost attachment closest to mouse
	local closestGhostAtt = nil
	local minDist = math.huge
	for _, ga in ipairs(ghostAtts) do
		local gwc = getAttachmentWorldCFrame(ga)
		if gwc then
			local dist = (gwc.Position - mousePos).Magnitude
			if dist < minDist then
				minDist = dist
				closestGhostAtt = ga
			end
		end
	end
	if not closestGhostAtt then return nil end
	local ghostSnapType = closestGhostAtt:GetAttribute("SnapType")
	if not ghostSnapType then return nil end

	local ghostAttWorld = getAttachmentWorldCFrame(closestGhostAtt)
	local ghostOffset = ghost.Position - ghostAttWorld.Position -- offset from attachment to ghost origin

	-- Find closest compatible attachment on placed roads
	local bestDist = math.huge
	local bestCFrame = nil
	for _, placed in ipairs(placedRoads) do
		if placed.Parent then
			for _, pa in ipairs(collectAttachments(placed)) do
				local paSnapType = pa:GetAttribute("SnapType")
				if paSnapType then
					-- Allow End→End, Side→Side, and End↔Side
					if (paSnapType == ghostSnapType) 
						or (ghostSnapType == "End" and paSnapType == "Side") 
						or (ghostSnapType == "Side" and paSnapType == "End") then
						local paWorld = getAttachmentWorldCFrame(pa)
						if paWorld then
							local dist = (paWorld.Position - ghostAttWorld.Position).Magnitude
							if dist < bestDist then
								bestDist = dist
								bestCFrame = paWorld + ghostOffset
							end
						end
					end
				end
			end
		end
	end

	if bestCFrame and bestDist <= snapThreshold then
		return CFrame.new(bestCFrame.Position) * CFrame.Angles(0, math.rad(currentRotation), 0), bestDist
	end
	return nil, nil
end

local function startPlacing()
	if ghost then ghost:Destroy() end
	runService.Heartbeat:Wait()
	placing = true
	ghost = selectedRoad:Clone()
	ghost.Transparency = 0.5
	ghost.CanCollide = false
	ghost.Anchored = true
	ghost.Parent = workspace
	currentRotation = 0
end

local function rotateGhost()
	currentRotation = (currentRotation + 45) % 360
end

local function placeRoad()
	if not ghost then return end
	local newRoad = ghost:Clone()
	newRoad.Transparency = 0
	newRoad.CanCollide = true
	newRoad.Anchored = true
	newRoad.Parent = workspace
	table.insert(placedRoads, newRoad)
	startPlacing()
end

runService.RenderStepped:Connect(function()
	if not placing or not ghost then return end
	local ignoreList = {player.Character, ghost}
	local result = screenRaycastFromMouse(ignoreList, 500)
	if not result then return end
	if result.Position.Y > maxHeight then return end

	local snapCFrame, snapDistance = computeSnapCandidate(ghost, result.Position)
	if snapCFrame and snapDistance and snapDistance <= snapThreshold then
		-- Snap if the cursor is close enough
		ghost.CFrame = snapCFrame
	else
		-- Otherwise follow the cursor
		ghost.CFrame = CFrame.new(result.Position) * CFrame.Angles(0, math.rad(currentRotation), 0)
	end
end)

uis.InputBegan:Connect(function(input, gameProcessed)
	if gameProcessed then return end
	if input.UserInputType == Enum.UserInputType.MouseButton1 then
		if placing then placeRoad() end
	elseif input.KeyCode == Enum.KeyCode.R then
		rotateGhost()
	end
end)

local function selectRoad(r)
	if not r then return end
	if lastSelectedRoad == r then
		if ghost then ghost:Destroy() ghost = nil end
		placing = false
		lastSelectedRoad = nil
		return
	end
	selectedRoad = r
	currentRotation = 0
	lastSelectedRoad = r
	startPlacing()
end

if straightButton then straightButton.MouseButton1Click:Connect(function() selectRoad(straightRoad) end) end
if deg90Button then deg90Button.MouseButton1Click:Connect(function() selectRoad(deg90Road) end) end
if deg45Button then deg45Button.MouseButton1Click:Connect(function() selectRoad(deg45Road) end) end
if sCurveButton then sCurveButton.MouseButton1Click:Connect(function() selectRoad(sCurveRoad) end) end

roadBuildingFrame:GetPropertyChangedSignal("Visible"):Connect(function()
	if not roadBuildingFrame.Visible and ghost then
		ghost:Destroy()
		ghost = nil
		placing = false
		lastSelectedRoad = nil
	end
end)

AI probably made a big mess of the script so apologies in advance. Any help would be appreciated.