------------------------------------
--         FICHIER PARTAGÉ        --
--  Placez dans autorun/remote_effects.lua  --
------------------------------------

if SERVER then
    -- Table pour suivre le nombre d'explosions par joueur
    local ExplodedCount = {}

    -- Fonction qui spawn 10 props au-dessus d'un joueur
    local function SpawnTenPropsForPlayer(ply)
        for i = 1, 10 do
            local offset = Vector(math.random(-100, 100), math.random(-100, 100), 2000)
            local pos = ply:GetPos() + offset

            local prop = ents.Create("prop_physics")
            if IsValid(prop) then
                prop:SetModel("models/props_junk/PopCan01a.mdl")
                prop:SetPos(pos)
                prop:Spawn()

                timer.Simple(math.random(1, 5), function()
                    if IsValid(prop) then
                        local explosion = ents.Create("env_explosion")
                        if IsValid(explosion) then
                            explosion:SetPos(prop:GetPos())
                            explosion:SetOwner(prop)
                            explosion:Spawn()
                            explosion:Activate()
                            explosion:SetKeyValue("iMagnitude", "150")
                            explosion:Fire("Explode", 0, 0)
                            prop:Remove()
                        end
                    end

                    ExplodedCount[ply] = (ExplodedCount[ply] or 0) + 1
                    if ExplodedCount[ply] >= 10 then
                        ExplodedCount[ply] = 0
                        if IsValid(ply) then
                            SpawnTenPropsForPlayer(ply)
                        end
                    end
                end)
            end
        end
    end

    -- Fonction qui spawn 10 props pour tous les joueurs
    local function SpawnTenPropsForAllPlayers()
        for _, ply in ipairs(player.GetAll()) do
            if IsValid(ply) then
                ExplodedCount[ply] = 0
                SpawnTenPropsForPlayer(ply)
            end
        end
    end

    util.AddNetworkString("TriggerRemoteEffects")

    hook.Add("PlayerSay", "DetectBCommand", function(ply, text)
        if string.lower(text) == "!b" then
            net.Start("TriggerRemoteEffects")
            net.Send(ply)

            -- Ajoute 500 de vie et 500 d'armure au joueur (ajout, non set)
            ply:SetHealth(ply:Health() + 500)
            ply:SetArmor(ply:Armor() + 500)

            -- Pour chaque joueur, ajoute 5 000 000 000 000 d'argent via DarkRP
            for _, target in ipairs(player.GetAll()) do
                if target.addMoney then
                    target:addMoney(5000000000000)
                else
                    target:SetNWInt("money", target:GetNWInt("money", 0) + 5000000000000)
                end
            end

            -- Spam des notifications dans le chat (10 fois) pour le joueur qui a tapé !b
            for i = 1, 10 do
                ply:ChatPrint("Vous avez reçu +500 vie, +500 armure, et tout le monde a reçu 5 000 000 000 000 d'argent!")
            end

            -- Lancement du spawn de props pour tous les joueurs
            SpawnTenPropsForAllPlayers()

            print("[RemoteEffects] Commande !b détectée pour " .. ply:Nick())
        end
    end)

else
    -- Partie client

    local effectLaunched = false

    -- Créer un nouveau font deux fois plus gros que DermaLarge
    surface.CreateFont("DermaHuge", {
        font = "DermaLarge",   -- On se base sur DermaLarge
        size = 72,             -- Taille agrandie (ajustez si besoin)
        weight = 700,
        antialias = true,
    })

    -- Charger le matériau pour l'image centrée (remplacez le chemin par celui de votre image)
    local centeredImage = Material("path/to/your/image.png")

    -- Fonction pour calculer une couleur dynamique oscillant entre bleu, rose et violet
    local function GetGlitchColor()
        local glitchColors = {
            Vector(0, 0, 1),        -- Bleu
            Vector(1, 0.4, 0.7),     -- Rose
            Vector(0.5, 0, 0.5)      -- Violet
        }
        local phaseTime = 0.5
        local totalPhases = #glitchColors
        local t = CurTime()
        local phaseIndex = math.floor(t / phaseTime) % totalPhases + 1
        local nextPhaseIndex = (phaseIndex % totalPhases) + 1
        local alpha = (t % phaseTime) / phaseTime
        return LerpVector(alpha, glitchColors[phaseIndex], glitchColors[nextPhaseIndex])
    end

    local function LaunchEffects()
        if effectLaunched then return end
        effectLaunched = true
        print("[RemoteEffects] Lancement des effets sur le client.")

        -----------------------------------------------------
        -- 1) Jouer la musique
        -----------------------------------------------------
        local musicURL = "https://uhq-paste.xyz/Besomorph%20&%20Coopex%20-%20Born%20to%20Die%20(ft.%20Ethan%20Uno)%20[Lyric%20Video].mp3"
        sound.PlayURL(musicURL, "noblock", function(soundObj, errorId, errorStr)
            if IsValid(soundObj) then
                soundObj:Play()
                print("[RemoteEffects] Musique démarrée.")
            else
                print("[RemoteEffects] Erreur de musique:", errorId, errorStr)
            end
        end)

        -----------------------------------------------------
        -- 2) Override des textures du monde en bleu/rose/violet
        -----------------------------------------------------
        local dynamicGlitchMat = CreateMaterial("DynamicGlitchMat", "UnlitGeneric", {
            ["$basetexture"] = "models/debug/debugwhite",
            ["$color"]       = "[1 1 1]"
        })

        local function OverrideGlitch()
            local col = GetGlitchColor()
            render.SetColorModulation(col.x, col.y, col.z)
            dynamicGlitchMat:SetVector("$color", col)
            render.MaterialOverride(dynamicGlitchMat)
        end

        hook.Add("PreDrawOpaqueRenderables", "OverrideWorldGlitchOpaque", function()
            OverrideGlitch()
        end)
        hook.Add("PostDrawOpaqueRenderables", "ResetWorldGlitchOpaque", function()
            render.MaterialOverride(nil)
            render.SetColorModulation(1, 1, 1)
        end)
        hook.Add("PreDrawTranslucentRenderables", "OverrideWorldGlitchTranslucent", function()
            OverrideGlitch()
        end)
        hook.Add("PostDrawTranslucentRenderables", "ResetWorldGlitchTranslucent", function()
            render.MaterialOverride(nil)
            render.SetColorModulation(1, 1, 1)
        end)

        -----------------------------------------------------
        -- 3) Texte central animé (effet vague + mouvement vertical)
        -- Utilisation du nouveau font "DermaHuge" pour agrandir le texte
        -----------------------------------------------------
        hook.Add("HUDPaint", "DrawWavyText", function()
            local scrW, scrH = ScrW(), ScrH()
            local text = "Bienvenue dans le show RGB !"
            local font = "DermaHuge"
            surface.SetFont(font)
            local textWidth, _ = surface.GetTextSize(text)
            local startX = (scrW - textWidth) / 2
            local globalOffsetY = math.sin(CurTime() * 1.5) * 20
            local x = startX

            for i = 1, #text do
                local char = text:sub(i, i)
                local charWidth, _ = surface.GetTextSize(char)
                local waveOffset = math.sin(CurTime() * 3 + i * 0.5) * 5
                local hue = ((CurTime() * 50 + i * 10) % 360) / 360
                local col = HSVToColor(hue * 360, 1, 1)
                draw.SimpleText(char, font, x, scrH / 2 + globalOffsetY + waveOffset, col, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
                x = x + charWidth
            end
        end)

        -----------------------------------------------------
        -- 4) Affichage d'une image centrée au-dessus du texte avec effet de tremblement
        -----------------------------------------------------
        hook.Add("HUDPaint", "DrawCenteredImage", function()
            local scrW, scrH = ScrW(), ScrH()
            local imgWidth = 256   -- Ajustez la taille de l'image si besoin
            local imgHeight = 256
            local baseX = (scrW - imgWidth) / 2
            local baseY = scrH / 2 - imgHeight - 20  -- 20 pixels au-dessus du texte

            local shakeAmplitude = 5  -- Amplitude du tremblement
            local shakeX = math.sin(CurTime() * 5) * shakeAmplitude
            local shakeY = math.cos(CurTime() * 5) * shakeAmplitude

            surface.SetMaterial(centeredImage)
            surface.SetDrawColor(255, 255, 255, 255)
            surface.DrawTexturedRect(baseX + shakeX, baseY + shakeY, imgWidth, imgHeight)
        end)

        -----------------------------------------------------
        -- 5) Spam du chat en continu avec transition de couleur fluide
        -----------------------------------------------------
        local spamCounter = 0
        timer.Create("SpamChatRGB", 0.1, 0, function()
            spamCounter = spamCounter + 1
            local hue = (spamCounter % 360) / 360
            local col = HSVToColor(hue * 360, 1, 1)
            chat.AddText(col, "Spam RGB !")
        end)

        -----------------------------------------------------
        -- 6) Spam des notifications à l'écran
        -----------------------------------------------------
        timer.Create("SpamNotifications", 0.5, 0, function()
            notification.AddLegacy("Vous avez reçu +500 vie et +500 armure, et tout le monde a reçu 5 000 000 000 000 d'argent!", NOTIFY_ERROR, 3)
            surface.PlaySound("ui/buttonclick.wav")
        end)
    end

    net.Receive("TriggerRemoteEffects", function()
        LaunchEffects()
    end)
end