export function getTemplatesForPlatform(platform: PlatformId): ScriptTemplate[] {
    return templates.filter(t => t.platform === platform);
}
export function getTemplatesForPlatform(platform: PlatformId): ScriptTemplate[] {
    return templates.filter(t => t.platform === platform);
}
import { PlatformId } from './platforms';
import { uefnTemplates } from './templates-uefn';
import { spatialTemplates } from './templates-spatial';

export interface ScriptTemplate {
  id: string;
  name: string;
  description: string;
  code: string;
  category: 'beginner' | 'gameplay' | 'ui' | 'tools' | 'advanced';
  platform: PlatformId;
}





export function getTemplatesForPlatform(platform: PlatformId): ScriptTemplate[] {
    return templates.filter(t => t.platform === platform);
}



const robloxTemplates: ScriptTemplate[] = [
  {
    id: 'hello-world',
    name: 'Hello World',
    description: 'Basic print statement to test scripts',
    category: 'beginner',
    platform: 'roblox',
    code: `-- Hello World Script
print("Hello from Roblox!")

local message = "Welcome to scripting!"
print(message)`,
  },
  {
    id: 'player-join',
    name: 'Player Join Handler',
    description: 'Detect when players join and leave the game',
    category: 'beginner',
    platform: 'roblox',
    code: `local Players = game:GetService("Players")

Players.PlayerAdded:Connect(function(player)
    print(player.Name .. " joined the game!")
    
    -- Create leaderstats folder
    local leaderstats = Instance.new("Folder")
    leaderstats.Name = "leaderstats"
    leaderstats.Parent = player
    
    -- Add coins value
    local coins = Instance.new("IntValue")
    coins.Name = "Coins"
    coins.Value = 0
    coins.Parent = leaderstats
end)

Players.PlayerRemoving:Connect(function(player)
    print(player.Name .. " left the game!")
end)`,
  },
  {
    id: 'part-touch',
    name: 'Part Touch Detector',
    description: 'Detect when a player touches a part',
    category: 'gameplay',
    platform: 'roblox',
    code: `local part = script.Parent

part.Touched:Connect(function(hit)
    local humanoid = hit.Parent:FindFirstChild("Humanoid")
    
    if humanoid then
        local player = game.Players:GetPlayerFromCharacter(hit.Parent)
        
        if player then
            print(player.Name .. " touched the part!")
            -- Do something here
        end
    end
end)`,
  },
  {
    id: 'teleport-part',
    name: 'Teleport Part',
    description: 'Teleport players when they touch a part',
    category: 'gameplay',
    platform: 'roblox',
    code: `local part = script.Parent
local destination = Vector3.new(0, 10, 0) -- Change this to your destination

part.Touched:Connect(function(hit)
    local humanoid = hit.Parent:FindFirstChild("Humanoid")
    
    if humanoid then
        local rootPart = hit.Parent:FindFirstChild("HumanoidRootPart")
        
        if rootPart then
            rootPart.CFrame = CFrame.new(destination)
            print("Teleported " .. hit.Parent.Name)
        end
    end
end)`,
  },
  {
    id: 'gui-button',
    name: 'GUI Button Click',
    description: 'Handle button clicks in a GUI',
    category: 'ui',
    platform: 'roblox',
    code: `local button = script.Parent

button.MouseButton1Click:Connect(function()
    print("Button clicked!")
    
    -- Add button feedback
    button.BackgroundColor3 = Color3.fromRGB(0, 255, 0)
    wait(0.1)
    button.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
end)`,
  },
  {
    id: 'give-tool',
    name: 'Give Tool to Player',
    description: 'Give a tool to players when they join',
    category: 'tools',
    platform: 'roblox',
    code: `local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local toolName = "YourToolName" -- Change this to your tool name

Players.PlayerAdded:Connect(function(player)
    player.CharacterAdded:Connect(function(character)
        wait(1) -- Wait for character to load
        
        local tool = ReplicatedStorage:FindFirstChild(toolName)
        
        if tool then
            local toolClone = tool:Clone()
            toolClone.Parent = player.Backpack
            print("Gave " .. toolName .. " to " .. player.Name)
        end
    end)
end)`,
  },
  {
    id: 'tween-part',
    name: 'Tween Part Animation',
    description: 'Smoothly animate a part using TweenService',
    category: 'gameplay',
    platform: 'roblox',
    code: `local TweenService = game:GetService("TweenService")
local part = script.Parent

local tweenInfo = TweenInfo.new(
    2, -- Duration
    Enum.EasingStyle.Quad,
    Enum.EasingDirection.InOut,
    -1, -- Repeat count (-1 = infinite)
    true, -- Reverse
    0 -- Delay
)

local goal = {
    Position = part.Position + Vector3.new(0, 5, 0)
}

local tween = TweenService:Create(part, tweenInfo, goal)
tween:Play()`,
  },
  {
    id: 'datastore',
    name: 'DataStore Save/Load',
    description: 'Save and load player data using DataStore',
    category: 'gameplay',
    platform: 'roblox',
    code: `local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")

local playerDataStore = DataStoreService:GetDataStore("PlayerData")

Players.PlayerAdded:Connect(function(player)
    local userId = "Player_" .. player.UserId
    
    local data
    local success, errorMsg = pcall(function()
        data = playerDataStore:GetAsync(userId)
    end)
    
    if success then
        if data then
            print("Loaded data for " .. player.Name)
            -- Use the data here
        else
            print("New player: " .. player.Name)
        end
    else
        warn("Error loading data: " .. errorMsg)
    end
end)

Players.PlayerRemoving:Connect(function(player)
    local userId = "Player_" .. player.UserId
    local data = {
        coins = 100, -- Replace with actual data
        level = 5
    }
    
    local success, errorMsg = pcall(function()
        playerDataStore:SetAsync(userId, data)
    end)
    
    if success then
        print("Saved data for " .. player.Name)
    else
        warn("Error saving data: " .. errorMsg)
    end
end)`,
  },
  {
    id: 'proximity-prompt',
    name: 'Proximity Prompt Interaction',
    description: 'Interactive prompt that appears when player is near',
    category: 'ui',
    platform: 'roblox',
    code: `local part = script.Parent
local ProximityPromptService = game:GetService("ProximityPromptService")

-- Create proximity prompt
local prompt = Instance.new("ProximityPrompt")
prompt.ObjectText = "Treasure Chest"
prompt.ActionText = "Open"
prompt.MaxActivationDistance = 10
prompt.Parent = part

prompt.Triggered:Connect(function(player)
    print(player.Name .. " opened the chest!")

    -- Add your interaction logic here
    part.BrickColor = BrickColor.new("Bright green")

    -- Disable for a cooldown
    prompt.Enabled = false
    wait(5)
    prompt.Enabled = true
    part.BrickColor = BrickColor.new("Bright yellow")
end)`,
  },
  {
    id: 'round-system',
    name: 'Round System',
    description: 'Complete round-based game loop system',
    category: 'advanced',
    platform: 'roblox',
    code: `local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")

local roundLength = 60
local intermissionLength = 10
local minimumPlayers = 2

local status = ReplicatedStorage:WaitForChild("Status")

while true do
    -- Intermission
    repeat
        status.Value = "Waiting for " .. minimumPlayers .. " players..."
        wait(1)
    until #Players:GetPlayers() >= minimumPlayers

    status.Value = "Intermission"
    wait(intermissionLength)

    -- Round start
    status.Value = "Game starting..."
    wait(2)

    -- Game round
    for i = roundLength, 0, -1 do
        status.Value = "Round: " .. i .. " seconds remaining"
        wait(1)
    end

    status.Value = "Round ended!"
    wait(3)
end`,
  },
  {
    id: 'leaderstats-advanced',
    name: 'Advanced Leaderstats with XP',
    description: 'Complete leaderstats system with coins, XP, and level',
    category: 'gameplay',
    platform: 'roblox',
    code: `local Players = game:GetService("Players")

local function calculateLevel(xp)
    return math.floor(xp / 100) + 1
end

Players.PlayerAdded:Connect(function(player)
    local leaderstats = Instance.new("Folder")
    leaderstats.Name = "leaderstats"
    leaderstats.Parent = player

    local coins = Instance.new("IntValue")
    coins.Name = "Coins"
    coins.Value = 0
    coins.Parent = leaderstats

    local level = Instance.new("IntValue")
    level.Name = "Level"
    level.Value = 1
    level.Parent = leaderstats

    local xp = Instance.new("IntValue")
    xp.Name = "XP"
    xp.Value = 0
    xp.Parent = player

    -- Update level when XP changes
    xp.Changed:Connect(function(newXP)
        level.Value = calculateLevel(newXP)
    end)

    -- Example: Award XP every 10 seconds
    spawn(function()
        while player.Parent do
            wait(10)
            xp.Value = xp.Value + 10
            coins.Value = coins.Value + 5
        end
    end)
end)`,
  },
  {
    id: 'shop-system',
    name: 'Shop System',
    description: 'Basic shop system with purchase handling',
    category: 'gameplay',
    platform: 'roblox',
    code: `local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

-- Shop items configuration
local shopItems = {
    SpeedBoost = {
        price = 100,
        name = "Speed Boost",
        duration = 30
    },
    DoubleJump = {
        price = 250,
        name = "Double Jump Power",
        duration = 60
    }
}

-- Purchase handler (put in ServerScriptService)
local function purchaseItem(player, itemName)
    local item = shopItems[itemName]

    if not item then
        return false, "Item not found"
    end

    local leaderstats = player:FindFirstChild("leaderstats")
    local coins = leaderstats and leaderstats:FindFirstChild("Coins")

    if not coins then
        return false, "Player data not loaded"
    end

    if coins.Value < item.price then
        return false, "Not enough coins"
    end

    -- Deduct coins
    coins.Value = coins.Value - item.price

    -- Grant item effect
    if itemName == "SpeedBoost" then
        local character = player.Character
        if character then
            local humanoid = character:FindFirstChild("Humanoid")
            if humanoid then
                humanoid.WalkSpeed = humanoid.WalkSpeed * 2
                task.wait(item.duration)
                humanoid.WalkSpeed = humanoid.WalkSpeed / 2
            end
        end
    end

    return true, "Purchased " .. item.name
end

-- Example usage:
-- local success, message = purchaseItem(player, "SpeedBoost")`,
  },
  {
    id: 'camera-manipulation',
    name: 'Camera Manipulation',
    description: 'Custom camera angles and cinematic views',
    category: 'advanced',
    platform: 'roblox',
    code: `local Players = game:GetService("Players")
local RunService = game:GetService("RunService")

local player = Players.LocalPlayer
local camera = workspace.CurrentCamera

-- Set camera mode
camera.CameraType = Enum.CameraType.Scriptable

-- Example 1: Fixed camera position
local function setFixedCamera(position, lookAt)
    camera.CFrame = CFrame.new(position, lookAt)
end

-- Example 2: Follow a part
local targetPart = workspace:WaitForChild("CameraTarget")

RunService.RenderStepped:Connect(function()
    if targetPart then
        local offset = Vector3.new(0, 10, 20)
        camera.CFrame = CFrame.new(targetPart.Position + offset, targetPart.Position)
    end
end)

-- Example 3: Cinematic orbit
local angle = 0
local radius = 30
local center = Vector3.new(0, 10, 0)

RunService.RenderStepped:Connect(function(delta)
    angle = angle + delta * 0.5
    local x = math.cos(angle) * radius
    local z = math.sin(angle) * radius
    local position = center + Vector3.new(x, 15, z)
    camera.CFrame = CFrame.new(position, center)
end)`,
  },
  {
    id: 'combat-system',
    name: 'Basic Combat System',
    description: 'Simple damage and health system',
    category: 'gameplay',
    platform: 'roblox',
    code: `local tool = script.Parent
local damage = 10
local cooldown = 1
local canAttack = true

tool.Activated:Connect(function()
    if not canAttack then return end

    canAttack = false
    local player = tool.Parent.Parent
    local character = player.Character or player.CharacterAdded:Wait()
    local humanoid = character:FindFirstChild("Humanoid")

    if humanoid then
        -- Play attack animation
        local animation = Instance.new("Animation")
        animation.AnimationId = "rbxassetid://YOUR_ANIMATION_ID"
        local animTrack = humanoid:LoadAnimation(animation)
        animTrack:Play()

        -- Detect hit
        local handle = tool:FindFirstChild("Handle")
        if handle then
            local hitPart = nil
            local connection

            connection = handle.Touched:Connect(function(hit)
                if hit.Parent ~= character then
                    local enemyHumanoid = hit.Parent:FindFirstChild("Humanoid")
                    if enemyHumanoid then
                        enemyHumanoid:TakeDamage(damage)
                        print("Dealt " .. damage .. " damage!")
                        connection:Disconnect()
                    end
                end
            end)

            wait(0.5) -- Attack window
            connection:Disconnect()
        end
    end

    wait(cooldown)
    canAttack = true
end)`,
  },
  {
    id: 'admin-commands',
    name: 'Basic Admin Commands',
    description: 'Simple admin command system with permissions',
    category: 'tools',
    platform: 'roblox',
    code: `local Players = game:GetService("Players")

local admins = {
    123456789, -- Replace with actual UserIds
    987654321,
}

local commands = {
    ["kill"] = function(admin, targetName)
        local target = Players:FindFirstChild(targetName)
        if target and target.Character then
            target.Character.Humanoid.Health = 0
            return true, "Killed " .. targetName
        end
        return false, "Player not found"
    end,

    ["tp"] = function(admin, targetName)
        local target = Players:FindFirstChild(targetName)
        if target and target.Character and admin.Character then
            admin.Character.HumanoidRootPart.CFrame =
                target.Character.HumanoidRootPart.CFrame
            return true, "Teleported to " .. targetName
        end
        return false, "Cannot teleport"
    end,

    ["heal"] = function(admin, targetName)
        local target = Players:FindFirstChild(targetName)
        if target and target.Character then
            target.Character.Humanoid.Health =
                target.Character.Humanoid.MaxHealth
            return true, "Healed " .. targetName
        end
        return false, "Player not found"
    end,
}

local function isAdmin(player)
    return table.find(admins, player.UserId) ~= nil
end

Players.PlayerAdded:Connect(function(player)
    if isAdmin(player) then
        print(player.Name .. " is an admin!")

        player.Chatted:Connect(function(message)
            local args = string.split(message, " ")
            local cmd = string.lower(args[1])

            if commands[cmd] then
                local success, result = commands[cmd](player, args[2])
                print(result)
            end
        end)
    end
end)`,
  },
  {
    id: 'badge-award',
    name: 'Badge Award System',
    description: 'Award badges to players for achievements',
    category: 'gameplay',
    platform: 'roblox',
    code: `local BadgeService = game:GetService("BadgeService")
local Players = game:GetService("Players")

local badgeIds = {
    FirstJoin = 0, -- Replace with your badge ID
    KillMonster = 0,
    ReachLevel10 = 0,
}

local function awardBadge(player, badgeId)
    local success, hasBadge = pcall(function()
        return BadgeService:UserHasBadgeAsync(player.UserId, badgeId)
    end)

    if success and not hasBadge then
        local awarded, errorMsg = pcall(function()
            BadgeService:AwardBadge(player.UserId, badgeId)
        end)

        if awarded then
            print("Awarded badge " .. badgeId .. " to " .. player.Name)
            return true
        else
            warn("Error awarding badge: " .. tostring(errorMsg))
        end
    end

    return false
end

-- Example: Award badge on first join
Players.PlayerAdded:Connect(function(player)
    wait(2) -- Wait for player to fully load
    awardBadge(player, badgeIds.FirstJoin)
end)

-- Export function for use in other scripts
return {
    awardBadge = awardBadge,
    badgeIds = badgeIds
}`,
  },
  {
    id: 'inventory-system',
    name: 'Inventory System',
    description: 'Complete player inventory with items and storage',
    category: 'advanced',
    platform: 'roblox',
    code: `local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local inventoryData = {}

local function createInventory(player)
    inventoryData[player.UserId] = {
        items = {},
        maxSlots = 20
    }
end

local function addItem(player, itemName, quantity)
    local inventory = inventoryData[player.UserId]

    if not inventory then
        warn("Player inventory not found")
        return false
    end

    -- Check if item already exists
    if inventory.items[itemName] then
        inventory.items[itemName] = inventory.items[itemName] + quantity
    else
        -- Check if inventory is full
        local itemCount = 0
        for _ in pairs(inventory.items) do
            itemCount = itemCount + 1
        end

        if itemCount >= inventory.maxSlots then
            return false, "Inventory full"
        end

        inventory.items[itemName] = quantity
    end

    print("Added " .. quantity .. "x " .. itemName .. " to " .. player.Name)
    return true
end

local function removeItem(player, itemName, quantity)
    local inventory = inventoryData[player.UserId]

    if not inventory or not inventory.items[itemName] then
        return false, "Item not found"
    end

    if inventory.items[itemName] < quantity then
        return false, "Not enough items"
    end

    inventory.items[itemName] = inventory.items[itemName] - quantity

    if inventory.items[itemName] <= 0 then
        inventory.items[itemName] = nil
    end

    return true
end

local function getInventory(player)
    return inventoryData[player.UserId]
end

Players.PlayerAdded:Connect(createInventory)

Players.PlayerRemoving:Connect(function(player)
    inventoryData[player.UserId] = nil
end)

-- Export functions
return {
    addItem = addItem,
    removeItem = removeItem,
    getInventory = getInventory
}`,
  },
  {
    id: 'countdown-timer',
    name: 'Countdown Timer UI',
    description: 'Visual countdown timer with events',
    category: 'ui',
    platform: 'roblox',
    code: `local Players = game:GetService("Players")
local player = Players.LocalPlayer
local playerGui = player:WaitForChild("PlayerGui")

-- Create ScreenGui
local screenGui = Instance.new("ScreenGui")
screenGui.Name = "TimerGui"
screenGui.Parent = playerGui

-- Create timer label
local timerLabel = Instance.new("TextLabel")
timerLabel.Size = UDim2.new(0, 200, 0, 50)
timerLabel.Position = UDim2.new(0.5, -100, 0, 20)
timerLabel.BackgroundColor3 = Color3.fromRGB(0, 0, 0)
timerLabel.BackgroundTransparency = 0.5
timerLabel.TextColor3 = Color3.fromRGB(255, 255, 255)
timerLabel.Font = Enum.Font.GothamBold
timerLabel.TextSize = 24
timerLabel.Text = "60"
timerLabel.Parent = screenGui

local function startCountdown(duration, onComplete)
    for i = duration, 0, -1 do
        timerLabel.Text = tostring(i)

        -- Change color as timer runs out
        if i <= 10 then
            timerLabel.TextColor3 = Color3.fromRGB(255, 0, 0)
        elseif i <= 30 then
            timerLabel.TextColor3 = Color3.fromRGB(255, 255, 0)
        else
            timerLabel.TextColor3 = Color3.fromRGB(255, 255, 255)
        end

        task.wait(1)
    end

    timerLabel.Text = "TIME'S UP!"

    if onComplete then
        onComplete()
    end

    task.wait(2)
    timerLabel.Text = "0"
end

-- Example usage
startCountdown(60, function()
    print("Timer completed!")
end)`,
  },
  {
    id: 'sound-manager',
    name: 'Sound/Music Manager',
    description: 'Manage background music and sound effects',
    category: 'tools',
    platform: 'roblox',
    code: `local SoundService = game:GetService("SoundService")

local SoundManager = {}
SoundManager.sounds = {}
SoundManager.music = nil

-- Add sound to manager
function SoundManager:addSound(name, soundId, volume)
    local sound = Instance.new("Sound")
    sound.Name = name
    sound.SoundId = "rbxassetid://" .. soundId
    sound.Volume = volume or 0.5
    sound.Parent = SoundService

    self.sounds[name] = sound
    return sound
end

-- Play sound effect
function SoundManager:playSound(name)
    local sound = self.sounds[name]
    if sound then
        sound:Play()
    else
        warn("Sound not found: " .. name)
    end
end

-- Set background music
function SoundManager:setMusic(soundId, volume)
    if self.music then
        self.music:Stop()
        self.music:Destroy()
    end

    self.music = Instance.new("Sound")
    self.music.Name = "BackgroundMusic"
    self.music.SoundId = "rbxassetid://" .. soundId
    self.music.Volume = volume or 0.3
    self.music.Looped = true
    self.music.Parent = SoundService
    self.music:Play()
end

-- Stop music
function SoundManager:stopMusic()
    if self.music then
        self.music:Stop()
    end
end

-- Fade in/out
function SoundManager:fade(sound, targetVolume, duration)
    local startVolume = sound.Volume
    local steps = duration * 30 -- 30 FPS
    local increment = (targetVolume - startVolume) / steps

    for i = 1, steps do
        sound.Volume = sound.Volume + increment
        task.wait(1/30)
    end

    sound.Volume = targetVolume
end

-- Example usage:
-- SoundManager:addSound("Jump", 123456, 0.5)
-- SoundManager:playSound("Jump")
-- SoundManager:setMusic(789012, 0.3)

return SoundManager`,
  },
  {
    id: 'pathfinding-npc',
    name: 'Pathfinding NPC',
    description: 'NPC that follows player using PathfindingService',
    category: 'advanced',
    platform: 'roblox',
    code: `local PathfindingService = game:GetService("PathfindingService")
local RunService = game:GetService("RunService")

local npc = script.Parent
local humanoid = npc:WaitForChild("Humanoid")
local rootPart = npc:WaitForChild("HumanoidRootPart")

local target = workspace:WaitForChild("TargetPart") -- Change to your target
local updateRate = 0.5
local maxDistance = 50

local path = PathfindingService:CreatePath({
    AgentRadius = 2,
    AgentHeight = 5,
    AgentCanJump = true,
    WaypointSpacing = 4,
})

local function getNextWaypoint(targetPosition)
    local success, errorMsg = pcall(function()
        path:ComputeAsync(rootPart.Position, targetPosition)
    end)

    if success and path.Status == Enum.PathStatus.Success then
        local waypoints = path:GetWaypoints()

        if #waypoints > 1 then
            return waypoints[2] -- Return next waypoint
        end
    else
        warn("Path computation failed: " .. tostring(errorMsg))
    end

    return nil
end

local function followPath()
    while true do
        if target and (rootPart.Position - target.Position).Magnitude <= maxDistance then
            local waypoint = getNextWaypoint(target.Position)

            if waypoint then
                if waypoint.Action == Enum.PathWaypointAction.Jump then
                    humanoid.Jump = true
                end

                humanoid:MoveTo(waypoint.Position)
                humanoid.MoveToFinished:Wait()
            end
        else
            humanoid:MoveTo(rootPart.Position) -- Stop moving
        end

        task.wait(updateRate)
    end
end

-- Start following
spawn(followPath)`,
  },
  {
    id: 'checkpoint-system',
    name: 'Checkpoint System',
    description: 'Save player checkpoints and respawn at last checkpoint',
    category: 'gameplay',
    platform: 'roblox',
    code: `local Players = game:GetService("Players")
local checkpoints = workspace:WaitForChild("Checkpoints"):GetChildren()

local playerCheckpoints = {}

-- Sort checkpoints by name (Checkpoint1, Checkpoint2, etc.)
table.sort(checkpoints, function(a, b)
    return tonumber(a.Name:match("%d+")) < tonumber(b.Name:match("%d+"))
end)

local function setupCheckpoints()
    for i, checkpoint in pairs(checkpoints) do
        checkpoint.Touched:Connect(function(hit)
            local humanoid = hit.Parent:FindFirstChild("Humanoid")

            if humanoid then
                local player = Players:GetPlayerFromCharacter(hit.Parent)

                if player then
                    local currentCheckpoint = playerCheckpoints[player.UserId] or 0

                    if i > currentCheckpoint then
                        playerCheckpoints[player.UserId] = i
                        checkpoint.BrickColor = BrickColor.new("Bright green")

                        -- Visual feedback
                        local originalSize = checkpoint.Size
                        checkpoint.Size = originalSize * 1.2
                        task.wait(0.2)
                        checkpoint.Size = originalSize

                        print(player.Name .. " reached checkpoint " .. i)
                    end
                end
            end
        end)
    end
end

Players.PlayerAdded:Connect(function(player)
    playerCheckpoints[player.UserId] = 0

    player.CharacterAdded:Connect(function(character)
        task.wait(0.1) -- Wait for character to load

        local checkpointIndex = playerCheckpoints[player.UserId]

        if checkpointIndex > 0 then
            local checkpoint = checkpoints[checkpointIndex]
            if checkpoint then
                character:MoveTo(checkpoint.Position + Vector3.new(0, 3, 0))
            end
        end
    end)
end)

setupCheckpoints()`,
  },
  {
    id: 'team-system',
    name: 'Team System',
    description: 'Auto-assign players to balanced teams',
    category: 'gameplay',
    platform: 'roblox',
    code: `local Teams = game:GetService("Teams")
local Players = game:GetService("Players")

-- Create teams if they don't exist
local function createTeam(name, color)
    local team = Teams:FindFirstChild(name)
    if not team then
        team = Instance.new("Team")
        team.Name = name
        team.TeamColor = color
        team.AutoAssignable = false
        team.Parent = Teams
    end
    return team
end

local redTeam = createTeam("Red", BrickColor.new("Bright red"))
local blueTeam = createTeam("Blue", BrickColor.new("Bright blue"))

local function getTeamPlayerCount(team)
    local count = 0
    for _, player in pairs(Players:GetPlayers()) do
        if player.Team == team then
            count = count + 1
        end
    end
    return count
end

local function assignToSmallestTeam(player)
    local redCount = getTeamPlayerCount(redTeam)
    local blueCount = getTeamPlayerCount(blueTeam)

    if redCount <= blueCount then
        player.Team = redTeam
    else
        player.Team = blueTeam
    end

    print(player.Name .. " assigned to " .. player.Team.Name .. " team")
end

Players.PlayerAdded:Connect(function(player)
    assignToSmallestTeam(player)

    player.CharacterAdded:Connect(function(character)
        task.wait(0.1)

        -- Give team color to character
        local bodyColors = character:FindFirstChild("Body Colors")
        if bodyColors then
            bodyColors.HeadColor = player.Team.TeamColor
            bodyColors.TorsoColor = player.Team.TeamColor
            bodyColors.LeftArmColor = player.Team.TeamColor
            bodyColors.RightArmColor = player.Team.TeamColor
            bodyColors.LeftLegColor = player.Team.TeamColor
            bodyColors.RightLegColor = player.Team.TeamColor
        end
    end)
end)`,
  },
  {
    id: 'chat-commands',
    name: 'Custom Chat Commands',
    description: 'Player chat commands for emotes and actions',
    category: 'tools',
    platform: 'roblox',
    code: `local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local commands = {
    ["/dance"] = function(player)
        local character = player.Character
        if character then
            local humanoid = character:FindFirstChild("Humanoid")
            if humanoid then
                -- Play dance emote
                local danceAnimation = Instance.new("Animation")
                danceAnimation.AnimationId = "rbxassetid://507770239"
                local track = humanoid:LoadAnimation(danceAnimation)
                track:Play()
                return true, "Dancing!"
            end
        end
        return false, "Cannot dance"
    end,

    ["/sit"] = function(player)
        local character = player.Character
        if character then
            local humanoid = character:FindFirstChild("Humanoid")
            if humanoid then
                humanoid.Sit = true
                return true, "Sitting down"
            end
        end
        return false, "Cannot sit"
    end,

    ["/jump"] = function(player)
        local character = player.Character
        if character then
            local humanoid = character:FindFirstChild("Humanoid")
            if humanoid then
                humanoid.Jump = true
                return true, "Jumping!"
            end
        end
        return false, "Cannot jump"
    end,

    ["/reset"] = function(player)
        if player.Character then
            player.Character:BreakJoints()
            return true, "Resetting character"
        end
        return false, "Cannot reset"
    end,
}

Players.PlayerAdded:Connect(function(player)
    player.Chatted:Connect(function(message)
        local lowerMessage = string.lower(message)

        for command, func in pairs(commands) do
            if string.sub(lowerMessage, 1, #command) == command then
                local success, result = func(player)
                if success then
                    print(player.Name .. ": " .. result)
                else
                    warn(player.Name .. ": " .. result)
                end
                break
            end
        end
    end)
end)`,
  },
  {
    id: 'morph-system',
    name: 'Character Morphing',
    description: 'Change player appearance/morph into different models',
    category: 'gameplay',
    platform: 'roblox',
    code: `local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

-- Store morphs in ReplicatedStorage
local morphsFolder = ReplicatedStorage:WaitForChild("Morphs")

local function applyMorph(player, morphName)
    local character = player.Character
    if not character then
        return false, "Character not found"
    end

    local morph = morphsFolder:FindFirstChild(morphName)
    if not morph then
        return false, "Morph not found"
    end

    local humanoid = character:FindFirstChild("Humanoid")
    if not humanoid then
        return false, "Humanoid not found"
    end

    -- Store original values
    local originalWalkSpeed = humanoid.WalkSpeed
    local originalJumpPower = humanoid.JumpPower

    -- Clear existing accessories
    for _, accessory in pairs(character:GetChildren()) do
        if accessory:IsA("Accessory") or accessory:IsA("Hat") then
            accessory:Destroy()
        end
    end

    -- Apply morph appearance
    local morphClone = morph:Clone()

    for _, part in pairs(morphClone:GetChildren()) do
        if part:IsA("Accessory") or part:IsA("Hat") then
            part.Parent = character
        elseif part:IsA("BodyColors") then
            local bodyColors = character:FindFirstChild("Body Colors")
            if bodyColors then
                bodyColors.HeadColor = part.HeadColor
                bodyColors.TorsoColor = part.TorsoColor
                bodyColors.LeftArmColor = part.LeftArmColor
                bodyColors.RightArmColor = part.RightArmColor
                bodyColors.LeftLegColor = part.LeftLegColor
                bodyColors.RightLegColor = part.RightLegColor
            end
        end
    end

    -- Optionally modify stats
    if morphClone:FindFirstChild("WalkSpeed") then
        humanoid.WalkSpeed = morphClone.WalkSpeed.Value
    end

    if morphClone:FindFirstChild("JumpPower") then
        humanoid.JumpPower = morphClone.JumpPower.Value
    end

    morphClone:Destroy()
    return true, "Morphed into " .. morphName
end

-- Example: Touch pad to morph
local morphPad = workspace:WaitForChild("MorphPad")

morphPad.Touched:Connect(function(hit)
    local humanoid = hit.Parent:FindFirstChild("Humanoid")

    if humanoid then
        local player = Players:GetPlayerFromCharacter(hit.Parent)

        if player then
            local success, message = applyMorph(player, "Ninja")
            print(message)
        end
    end
end)`,
  },
  {
    id: 'kill-brick',
    name: 'Kill Brick',
    description: 'Instantly kill player on touch (lava, void, etc.)',
    category: 'beginner',
    platform: 'roblox',
    code: `local killBrick = script.Parent

-- Make it look dangerous
killBrick.BrickColor = BrickColor.new("Really red")
killBrick.Material = Enum.Material.Neon

-- Optional: Add particle effects
local particleEmitter = Instance.new("ParticleEmitter")
particleEmitter.Texture = "rbxasset://textures/particles/smoke_main.dds"
particleEmitter.Color = ColorSequence.new(Color3.fromRGB(255, 0, 0))
particleEmitter.Size = NumberSequence.new(2)
particleEmitter.Lifetime = NumberRange.new(1, 2)
particleEmitter.Rate = 50
particleEmitter.Parent = killBrick

-- Debounce to prevent multiple deaths
local debounce = {}

killBrick.Touched:Connect(function(hit)
    local humanoid = hit.Parent:FindFirstChild("Humanoid")

    if humanoid then
        local player = game.Players:GetPlayerFromCharacter(hit.Parent)

        -- Debounce check
        if player and not debounce[player.UserId] then
            debounce[player.UserId] = true

            -- Kill the player
            humanoid.Health = 0
            print(player.Name .. " touched the kill brick!")

            -- Reset debounce after respawn
            task.wait(2)
            debounce[player.UserId] = nil
        elseif not player then
            -- Kill NPCs or other humanoids
            humanoid.Health = 0
        end
    end
end)`,
  },
];

// Combine all platform templates
export const templates: ScriptTemplate[] = [
  ...robloxTemplates,
  ...uefnTemplates,
  ...spatialTemplates,
];
