--[[ CriaJogo IA — plugin do Roblox Studio
(números com vírgula escritos como fração de propósito: o Studio em português às vezes não lê "0.5")
Como instalar: no Studio, aba PLUGINS → "Plugins Folder" → coloque este arquivo lá → feche e abra o Studio.
Como usar: clique no botão "CriaJogo", cole o CÓDIGO que aparece no site e clique em "Criar no meu jogo".
O plugin monta o obby com peças prontas e testadas. Dá pra desfazer com Ctrl+Z. ]]

local SITE = "https://criajogo.pages.dev"
local HttpService = game:GetService("HttpService")
local CollectionService = game:GetService("CollectionService")
local Lighting = game:GetService("Lighting")
local ServerScriptService = game:GetService("ServerScriptService")

---------------------------------------------------------------------------------------------------
-- MOTOR (vai pro jogo): checkpoints, lava, plataformas que somem, trampolim, barras girando, vitória
---------------------------------------------------------------------------------------------------
local MOTOR = [==[
local CS = game:GetService("CollectionService")
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local salvo = {}

local function jogadorDe(hit)
	local m = hit and hit:FindFirstAncestorOfClass("Model")
	return m and Players:GetPlayerFromCharacter(m), m
end
local function liga(tag, fn)
	for _, x in CS:GetTagged(tag) do task.spawn(fn, x) end
	CS:GetInstanceAddedSignal(tag):Connect(fn)
end

Players.PlayerAdded:Connect(function(p)
	local ls = Instance.new("Folder"); ls.Name = "leaderstats"; ls.Parent = p
	local f = Instance.new("IntValue"); f.Name = "Fase"; f.Value = 0; f.Parent = ls
	p.CharacterAdded:Connect(function(c)
		local cp = salvo[p]
		if cp then
			local hrp = c:WaitForChild("HumanoidRootPart")
			task.wait((1/10))
			hrp.CFrame = cp.CFrame + Vector3.new(0, 5, 0)
		end
	end)
end)
Players.PlayerRemoving:Connect(function(p) salvo[p] = nil end)

liga("CJ_Lava", function(x)
	x.Touched:Connect(function(h)
		local _, m = jogadorDe(h)
		local hum = m and m:FindFirstChildOfClass("Humanoid")
		if hum then hum.Health = 0 end
	end)
end)

liga("CJ_Checkpoint", function(x)
	x.Touched:Connect(function(h)
		local p = jogadorDe(h)
		if not p then return end
		local n = x:GetAttribute("Fase") or 0
		local ls = p:FindFirstChild("leaderstats")
		if ls and ls.Fase.Value < n then ls.Fase.Value = n; salvo[p] = x end
	end)
end)

liga("CJ_Some", function(x)
	local ocupado = false
	x.Touched:Connect(function(h)
		if ocupado or not jogadorDe(h) then return end
		ocupado = true
		task.wait((6/10))
		x.Transparency = (85/100); x.CanCollide = false
		task.wait((25/10))
		x.Transparency = 0; x.CanCollide = true
		ocupado = false
	end)
end)

liga("CJ_Trampolim", function(x)
	local forca = x:GetAttribute("Forca") or 120
	local ultimo = {}
	x.Touched:Connect(function(h)
		local p, m = jogadorDe(h)
		if not p or (ultimo[p] and os.clock() - ultimo[p] < (5/10)) then return end
		ultimo[p] = os.clock()
		local hrp = m:FindFirstChild("HumanoidRootPart")
		if hrp then
			local v = hrp.AssemblyLinearVelocity
			hrp.AssemblyLinearVelocity = Vector3.new(v.X, forca, v.Z)
		end
	end)
end)

local girando = {}
liga("CJ_Gira", function(x) table.insert(girando, x) end)
RunService.Heartbeat:Connect(function(dt)
	for _, x in girando do
		if x.Parent then x.CFrame = x.CFrame * CFrame.Angles(0, (x:GetAttribute("Vel") or (15/10)) * dt, 0) end
	end
end)

liga("CJ_Vitoria", function(x)
	local ja = {}
	x.Touched:Connect(function(h)
		local p = jogadorDe(h)
		if not p or ja[p] then return end
		ja[p] = true
		local ls = p:FindFirstChild("leaderstats")
		if ls then ls.Fase.Value = x:GetAttribute("Fase") or ls.Fase.Value end
		local g = Instance.new("ScreenGui"); g.Name = "CJ_Venceu"; g.ResetOnSpawn = false
		local t = Instance.new("TextLabel")
		t.Size = UDim2.fromScale((8/10), (18/100)); t.Position = UDim2.fromScale((1/10), (12/100))
		t.BackgroundColor3 = Color3.fromRGB(250, 204, 21); t.TextColor3 = Color3.fromRGB(40, 20, 0)
		t.Font = Enum.Font.FredokaOne; t.TextScaled = true
		t.Text = x:GetAttribute("Premio") or "Você zerou!"
		Instance.new("UICorner", t).CornerRadius = UDim.new(0, 18)
		t.Parent = g; g.Parent = p:WaitForChild("PlayerGui")
		task.delay(6, function() g:Destroy() end)
	end)
end)
]==]

---------------------------------------------------------------------------------------------------
-- CONSTRUTOR: lê a config e monta as fases no Workspace
---------------------------------------------------------------------------------------------------
local function cor(h, padrao)
	local ok, c = pcall(Color3.fromHex, h or "")
	return ok and c or padrao
end

local function construir(cfg)
	local velho = workspace:FindFirstChild("CriaJogo")
	if velho then velho:Destroy() end
	local velhoMotor = ServerScriptService:FindFirstChild("CriaJogoMotor")
	if velhoMotor then velhoMotor:Destroy() end

	local pasta = Instance.new("Folder"); pasta.Name = "CriaJogo"
	local tema = cor(cfg.corTema, Color3.fromRGB(139, 92, 246))
	local LAVA = Color3.fromRGB(255, 70, 20)
	local ALTURA_BASE = 30
	local z, y = 0, ALTURA_BASE

	local function bloco(nome, tam, pos, c, mat, pai)
		local p = Instance.new("Part")
		p.Name = nome; p.Size = tam; p.Anchored = true
		p.CFrame = CFrame.new(pos); p.Color = c
		p.Material = mat or Enum.Material.SmoothPlastic
		p.TopSurface = Enum.SurfaceType.Smooth; p.BottomSurface = Enum.SurfaceType.Smooth
		p.Parent = pai or pasta
		return p
	end
	local function tag(p, t) CollectionService:AddTag(p, t); return p end
	local function lava(nome, tam, pos, pai)
		return tag(bloco(nome, tam, pos, LAVA, Enum.Material.Neon, pai), "CJ_Lava")
	end
	local function placa(parte, texto, corTexto)
		local b = Instance.new("BillboardGui")
		b.Size = UDim2.fromOffset(420, 90); b.StudsOffset = Vector3.new(0, 7, 0); b.AlwaysOnTop = false
		b.MaxDistance = 120
		local t = Instance.new("TextLabel")
		t.Size = UDim2.fromScale(1, 1); t.BackgroundTransparency = 1; t.TextScaled = true
		t.Font = Enum.Font.FredokaOne; t.Text = texto; t.TextColor3 = corTexto or Color3.new(1, 1, 1)
		t.TextStrokeTransparency = (2/10)
		t.Parent = b; b.Parent = parte
	end

	-- início
	local spawn = Instance.new("SpawnLocation")
	spawn.Name = "Inicio"; spawn.Size = Vector3.new(16, 1, 16); spawn.Anchored = true
	spawn.CFrame = CFrame.new(0, y, z); spawn.Color = tema; spawn.Material = Enum.Material.SmoothPlastic
	spawn.Duration = 0; spawn.Neutral = true; spawn.Parent = pasta
	placa(spawn, (cfg.nome or "Meu Obby"), Color3.new(1, 1, 1))
	local boasVindas = bloco("Boas-vindas", Vector3.new(1, 1, 1), Vector3.new(0, y + 6, z - 6), tema)
	boasVindas.Transparency = 1; boasVindas.CanCollide = false
	placa(boasVindas, cfg.mensagemInicio or "", Color3.fromRGB(255, 240, 160))
	z += 8

	-- cada tipo de fase recebe (pasta da fase, cor, dificuldade) e avança z/y
	local FASES = {}

	FASES.pulos = function(f, c, d)
		local n, vao = 4 + d * 2, 5 + d * (15/10)
		for i = 1, n do
			z += vao
			local tam = 5 - d
			bloco("Pulo" .. i, Vector3.new(tam, 1, tam), Vector3.new(((i % 2) * 2 - 1) * 2, y + ((i % 3) - 1) * (12/10), z), c, nil, f)
		end
		z += 3
	end

	FASES.lava = function(f, c, d)
		local n, faixa = 4 + d, (25/10) + d
		for i = 1, n do
			z += 3
			bloco("Chao" .. i, Vector3.new(10, 1, 6), Vector3.new(0, y, z), c, nil, f)
			z += 3 + faixa / 2
			lava("Lava" .. i, Vector3.new(10, (12/10), faixa), Vector3.new(0, y, z), f)
			z += faixa / 2
		end
		z += 3
		bloco("ChaoFim", Vector3.new(10, 1, 6), Vector3.new(0, y, z), c, nil, f)
		z += 3
	end

	FASES.giratorio = function(f, c, d)
		local raio = 14
		z += raio + 2
		local base = bloco("Roda", Vector3.new(1, raio * 2 + 4, raio * 2 + 4), Vector3.new(0, y, z), c, nil, f)
		base.Shape = Enum.PartType.Cylinder
		base.CFrame = CFrame.new(0, y, z) * CFrame.Angles(0, 0, math.rad(90))
		local barras = d >= 3 and 2 or 1
		for i = 1, barras do
			local b = lava("Barra" .. i, Vector3.new(raio * 2 + 2, (12/10), (12/10)), Vector3.new(0, y + (16/10), z), f)
			b.CFrame = CFrame.new(0, y + (16/10), z) * CFrame.Angles(0, math.rad(90 * (i - 1)), 0)
			tag(b, "CJ_Gira"); b:SetAttribute("Vel", 1 + d * (6/10))
		end
		z += raio + 2
	end

	FASES.sumir = function(f, c, d)
		local n = 5 + d
		for i = 1, n do
			z += 6 + d * (5/10)
			tag(bloco("Some" .. i, Vector3.new(5, 1, 5), Vector3.new(0, y, z), c, Enum.Material.Glass, f), "CJ_Some")
		end
		z += 3
	end

	FASES.trampolim = function(f, c, d)
		z += 7
		local t = tag(bloco("Trampolim", Vector3.new(6, 1, 6), Vector3.new(0, y, z), c, Enum.Material.Neon, f), "CJ_Trampolim")
		t:SetAttribute("Forca", 95 + d * 10)
		local sobe = 12 + d * 4
		y += sobe
		z += 9
		bloco("Topo", Vector3.new(8, 1, 8), Vector3.new(0, y, z), c, nil, f)
		z += 4
	end

	FASES.estreito = function(f, c, d)
		local n, larg = 4 + d, (16/10) - d * (3/10)
		local x = 0
		for i = 1, n do
			local nx = (i % 2 == 1) and 6 or -6
			local meio = Vector3.new((x + nx) / 2, y, z + 5)
			local dist = (Vector3.new(nx, y, z + 10) - Vector3.new(x, y, z)).Magnitude
			local v = bloco("Viga" .. i, Vector3.new(larg, 1, dist), meio, c, Enum.Material.Wood, f)
			v.CFrame = CFrame.lookAt(meio, Vector3.new(nx, y, z + 10))
			x = nx; z += 10
		end
		z += 3
		bloco("Fim", Vector3.new(14, 1, 6), Vector3.new(0, y, z), c, nil, f)
		z += 3
	end

	local fases = cfg.fases or {}
	for i, fase in fases do
		local f = Instance.new("Folder"); f.Name = string.format("Fase %02d - %s", i, fase.tipo or "?"); f.Parent = pasta
		local construtor = FASES[fase.tipo] or FASES.pulos
		construtor(f, cor(fase.cor, tema), math.clamp(tonumber(fase.dificuldade) or 1, 1, 3))
		z += 7
		local cp = tag(bloco("Checkpoint", Vector3.new(10, 1, 10), Vector3.new(0, y, z), Color3.fromRGB(34, 197, 94), Enum.Material.Neon, f), "CJ_Checkpoint")
		cp:SetAttribute("Fase", i)
		placa(cp, "Fase " .. i .. " ✔", Color3.fromRGB(190, 255, 190))
		z += 5
	end

	-- final
	z += 8
	local fim = tag(bloco("Vitoria", Vector3.new(18, 1, 18), Vector3.new(0, y, z), Color3.fromRGB(250, 204, 21), Enum.Material.Neon), "CJ_Vitoria")
	fim:SetAttribute("Premio", cfg.premioFinal or "Você zerou!")
	fim:SetAttribute("Fase", #fases + 1)
	placa(fim, "🏆 FIM 🏆", Color3.fromRGB(255, 230, 120))

	-- chão de lava embaixo de tudo (cair = voltar pro checkpoint)
	local comp = z + 40
	lava("ChaoDeLava", Vector3.new(90, 2, comp + 60), Vector3.new(0, ALTURA_BASE - 25, comp / 2 - 20))

	-- céu
	local ceu = cfg.ceu or "dia"
	Lighting.ClockTime = (ceu == "noite" and 0) or (ceu == "por-do-sol" and (176/10)) or 14
	pasta.Parent = workspace

	local motor = Instance.new("Script"); motor.Name = "CriaJogoMotor"; motor.Source = MOTOR
	motor.Parent = ServerScriptService
	return #fases
end

--[[UI]]
---------------------------------------------------------------------------------------------------
-- JANELA DO PLUGIN
---------------------------------------------------------------------------------------------------
if not plugin then return construir end
local ChangeHistoryService = game:GetService("ChangeHistoryService")
local barra = plugin:CreateToolbar("CriaJogo IA")
local botao = barra:CreateButton("CriaJogo", "Montar o obby que você criou no site", "")
local info = DockWidgetPluginGuiInfo.new(Enum.InitialDockState.Float, false, false, 320, 230, 280, 200)
local janela = plugin:CreateDockWidgetPluginGui("CriaJogoIA", info)
janela.Title = "CriaJogo IA"

local fundo = Instance.new("Frame"); fundo.Size = UDim2.fromScale(1, 1)
fundo.BackgroundColor3 = Color3.fromRGB(30, 22, 52); fundo.Parent = janela
local lista = Instance.new("UIListLayout"); lista.Padding = UDim.new(0, 10)
lista.HorizontalAlignment = Enum.HorizontalAlignment.Center; lista.Parent = fundo
local pad = Instance.new("UIPadding"); pad.PaddingTop = UDim.new(0, 14); pad.Parent = fundo

local function rotulo(t, tam)
	local l = Instance.new("TextLabel"); l.Size = UDim2.new((9/10), 0, 0, tam or 22)
	l.BackgroundTransparency = 1; l.TextColor3 = Color3.new(1, 1, 1); l.Font = Enum.Font.GothamBold
	l.TextScaled = false; l.TextSize = 15; l.TextWrapped = true; l.Text = t; l.Parent = fundo
	return l
end
rotulo("Cole o código do site:")
local caixa = Instance.new("TextBox"); caixa.Size = UDim2.new((9/10), 0, 0, 40)
caixa.PlaceholderText = "EX: K7P2QX"; caixa.Text = ""; caixa.Font = Enum.Font.GothamBlack; caixa.TextSize = 22
caixa.BackgroundColor3 = Color3.new(1, 1, 1); caixa.TextColor3 = Color3.fromRGB(30, 22, 52); caixa.ClearTextOnFocus = false
Instance.new("UICorner", caixa).CornerRadius = UDim.new(0, 10); caixa.Parent = fundo
local criar = Instance.new("TextButton"); criar.Size = UDim2.new((9/10), 0, 0, 44)
criar.BackgroundColor3 = Color3.fromRGB(88, 204, 2); criar.TextColor3 = Color3.new(1, 1, 1)
criar.Font = Enum.Font.GothamBlack; criar.TextSize = 18; criar.Text = "CRIAR NO MEU JOGO"
Instance.new("UICorner", criar).CornerRadius = UDim.new(0, 12); criar.Parent = fundo
local status = rotulo("", 50); status.TextColor3 = Color3.fromRGB(200, 190, 255); status.TextSize = 13

botao.Click:Connect(function() janela.Enabled = not janela.Enabled end)

local ocupado = false
criar.MouseButton1Click:Connect(function()
	if ocupado then return end
	local codigo = caixa.Text:upper():gsub("[^A-Z0-9]", "")
	if #codigo < 4 then status.Text = "Cole o código que aparece no site 🙂"; return end
	ocupado = true; status.Text = "Buscando seu obby..."
	local ok, resp = pcall(function() return HttpService:GetAsync(SITE .. "/api/projeto/" .. codigo, true) end)
	if not ok then
		if tostring(resp):find("404") then status.Text = "Código não encontrado. Confere no site!"
		else status.Text = "Não consegui falar com o site. Se o Studio perguntar, clique em PERMITIR. (" .. tostring(resp):sub(1, 60) .. ")" end
		ocupado = false; return
	end
	local okj, dados = pcall(function() return HttpService:JSONDecode(resp) end)
	if not okj or not dados.config then status.Text = "Código não encontrado. Confere no site!"; ocupado = false; return end
	local gravacao = ChangeHistoryService:TryBeginRecording("CriaJogo: montar obby")
	local okc, n = pcall(construir, dados.config)
	if gravacao then ChangeHistoryService:FinishRecording(gravacao, Enum.FinishRecordingOperation.Commit) end
	if okc then
		status.Text = "✅ Obby \"" .. (dados.config.nome or "") .. "\" com " .. n .. " fases montado! Aperte PLAY pra testar."
	else
		status.Text = "Deu erro ao montar: " .. tostring(n):sub(1, 80)
	end
	ocupado = false
end)
