ENT.Base = "base_gmodentity"
ENT.Type = "anim"
ENT.PrintName = "Recon Drone"
ENT.Spawnable = true 
ENT.AutomaticFrameAdvance = true

ENT.BatteryCount = 600
ENT.HealthCount = 20

if CLIENT then

    ---------------------------------------------------------
    -- ВСПОМОГАТЕЛЬНЫЕ ФУНКЦИИ HUD
    ---------------------------------------------------------

    local function DrawScanlines(sw, sh, intensity)
        surface.SetDrawColor(0, 0, 0, intensity * 15)
        for i = 0, sh, 4 do
            surface.DrawRect(0, i, sw, 1)
        end
    end
    
    local function DrawGlitchNoise(sw, sh, intensity)
        if intensity < 0.3 then return end
        local glitchCount = math.floor((1 - intensity) * 50)
        surface.SetDrawColor(255, 255, 255, (1 - intensity) * 100)
        for i = 1, glitchCount do
            local x = math.random(0, sw)
            local y = math.random(0, sh)
            local w = math.random(20, 200)
            surface.DrawRect(x, y, w, 2)
        end
    end

    local function DrawCornerBrackets(x, y, w, h, size, thickness, col)
        surface.SetDrawColor(col)
        surface.DrawRect(x, y, size, thickness)
        surface.DrawRect(x, y, thickness, size)
        surface.DrawRect(x + w - size, y, size, thickness)
        surface.DrawRect(x + w - thickness, y, thickness, size)
        surface.DrawRect(x, y + h - thickness, size, thickness)
        surface.DrawRect(x, y + h - size, thickness, size)
        surface.DrawRect(x + w - size, y + h - thickness, size, thickness)
        surface.DrawRect(x + w - thickness, y + h - size, thickness, size)
    end

    local function DrawCrosshair(cx, cy, size, gap, thickness, col)
        surface.SetDrawColor(col)
        surface.DrawRect(cx - size, cy - thickness/2, size - gap, thickness)
        surface.DrawRect(cx + gap, cy - thickness/2, size - gap, thickness)
        surface.DrawRect(cx - thickness/2, cy - size, thickness, size - gap)
        surface.DrawRect(cx - thickness/2, cy + gap, thickness, size - gap)
    end

    local function DrawArcSegment(cx, cy, radius, startAng, endAng, thickness, segments, col)
        surface.SetDrawColor(col)
        local step = (endAng - startAng) / segments
        for i = 0, segments - 1 do
            local a1 = math.rad(startAng + i * step)
            local a2 = math.rad(startAng + (i + 1) * step)
            local x1 = cx + math.cos(a1) * radius
            local y1 = cy + math.sin(a1) * radius
            local x2 = cx + math.cos(a2) * radius
            local y2 = cy + math.sin(a2) * radius
            surface.DrawLine(x1, y1, x2, y2)
        end
    end

    ---------------------------------------------------------
    -- РЕНДЕР ПОСЛЕДНЕГО КАДРА
    ---------------------------------------------------------

    local function GetDroneRT()
        local name = "MuR_Drone_LastFrame"
        return GetRenderTarget(name, ScrW(), ScrH())
    end

    local lastFrameMat = CreateMaterial("MuR_Drone_LastFrame_Mat", "UnlitGeneric", {
        ["$basetexture"] = "MuR_Drone_LastFrame",
        ["$ignorez"] = 1,
        ["$vertexcolor"] = 1,
        ["$vertexalpha"] = 1
    })

    ---------------------------------------------------------
    -- МОЩНЫЕ ПОМЕХИ
    ---------------------------------------------------------

    local function DrawHeavySignalNoise(strength)
        if not strength then return end
        if strength > 0.9 then return end

        local sw, sh = ScrW(), ScrH()

        local noiseCount = (1 - strength) * 400
        for i = 1, noiseCount do
            surface.SetDrawColor(255, 255, 255, math.random(10, 60))
            surface.DrawRect(math.random(0, sw), math.random(0, sh), 1, 1)
        end

        local lineCount = (1 - strength) * 60
        for i = 1, lineCount do
            local y = math.random(0, sh)
            local w = math.random(sw * 0.2, sw)
            local x = math.random(0, sw - w)
            surface.SetDrawColor(255, 255, 255, math.random(20, 80))
            surface.DrawRect(x, y, w, math.random(1, 3))
        end

        if strength < 0.4 then
            local shift = math.random(-8, 8) * (1 - strength)
            surface.SetDrawColor(255, 255, 255, 40)
            surface.DrawRect(shift, 0, sw, sh)
        end

        if strength < 0.3 then
            for i = 1, 10 do
                local x = math.random(0, sw)
                surface.SetDrawColor(255, 255, 255, math.random(30, 80))
                surface.DrawRect(x, 0, math.random(2, 6), sh)
            end
        end

        if strength < 0.2 then
            local shake = (0.2 - strength) * 6
            surface.SetDrawColor(255, 255, 255, 25)
            surface.DrawRect(
                math.random(-shake, shake),
                math.random(-shake, shake),
                sw, sh
            )
        end
    end

    ---------------------------------------------------------
    -- ПЕРЕМЕННЫЕ КАМЕРЫ / FLIR
    ---------------------------------------------------------

    local DRONE = nil
    local Thermal = false
    local ThermalKeyHeld = false
    local Zoom = 1

    local FPV_Yaw = 0
    local FPV_Pitch = 0

    local DefMats = {}
    local DefClrs = {}
    local DoXRay = false

    local FLIR = {
        ["$pp_colour_addr"]       = -.3,
        ["$pp_colour_addg"]       = -.4,
        ["$pp_colour_addb"]       = -.4,
        ["$pp_colour_brightness"] = .1,
        ["$pp_colour_contrast"]   = 1,
        ["$pp_colour_colour"]     = 0,
        ["$pp_colour_mulr"]       = 0,
        ["$pp_colour_mulg"]       = 0,
        ["$pp_colour_mulb"]       = 0,
    }

    ---------------------------------------------------------
    -- X-RAY ДЛЯ FLIR
    ---------------------------------------------------------

    local function ApplyXRay()
        for _, v in ipairs(ents.GetAll()) do
            if not v:GetModel() then continue end
            if string.sub(v:GetModel(), -3) ~= "mdl" then continue end

            if v:IsPlayer() then
            elseif v:IsNPC() then
            elseif v.LVS or v.LFS then
            else
                continue
            end

            local col = v:GetColor()
            if col.a <= 0 then continue end

            if not DefClrs[v] then
                DefClrs[v] = Color(col.r, col.g, col.b, col.a)
            end

            local entmat = v:GetMaterial()
            if not DefMats[v] then
                DefMats[v] = entmat
            end

            v:SetColor(Color(255,255,255,255))
            v:SetMaterial("xray/living")
        end
    end

    local function RestoreXRayMaterials()
        for ent2, mat in pairs(DefMats) do
            if IsValid(ent2) then ent2:SetMaterial(mat) end
        end
        for ent2, clr in pairs(DefClrs) do
            if IsValid(ent2) then
                ent2:SetRenderMode(RENDERMODE_TRANSALPHA)
                ent2:SetColor(Color(clr.r, clr.g, clr.b, clr.a))
            end
        end
        DefMats = {}
        DefClrs = {}
        DoXRay = false
    end

    local function RenderFLIR()
        DrawColorModify(FLIR)
        DrawBloom(0,1,1,1,0,0,0,0,0)
        DrawMotionBlur(FrameTime() * 50, 0.5, 0.05)
        DrawBokehDOF(0.15, 1, 12)
    end

    ---------------------------------------------------------
    -- ЭКРАН ПОТЕРИ СВЯЗИ
    ---------------------------------------------------------

    local function LoseDrone()
        surface.PlaySound("ambient/levels/prison/radio_random"..math.random(1,15)..".wav")

        local startTime = CurTime()
        lastFrameMat:SetTexture("$basetexture", GetDroneRT())

        hook.Add("HUDPaint", "Spy_DroneCamLost", function()
            local sw, sh = ScrW(), ScrH()
            local elapsed = CurTime() - startTime
            local flicker = math.sin(elapsed * 30) > 0

            surface.SetDrawColor(0, 0, 0, 255)
            surface.DrawRect(0, 0, sw, sh)

            surface.SetDrawColor(255, 255, 255, 255)
            surface.SetMaterial(lastFrameMat)
            surface.DrawTexturedRect(0, 0, sw, sh)

            surface.SetDrawColor(0, 0, 0, math.min(elapsed * 100, 200))
            surface.DrawRect(0, 0, sw, sh)

            for i = 1, 150 do
                local px = math.random(0, sw)
                local py = math.random(0, sh)
                local ps = math.random(2, 8)
                local c = math.random(30, 80)
                surface.SetDrawColor(c, c, c, 255)
                surface.DrawRect(px, py, ps, ps)
            end

            DrawScanlines(sw, sh, 3)

            for i = 1, 20 do
                local y = math.random(0, sh)
                local w = math.random(sw * 0.3, sw)
                local x = math.random(0, sw - w)
                surface.SetDrawColor(40, 40, 45, 200)
                surface.DrawRect(x, y, w, math.random(1, 5))
            end

            local textCol = flicker and Color(255, 50, 50, 255) or Color(200, 40, 40, 200)
            draw.SimpleText("▌▌ СОЕДИНЕНИЕ ПОТЕРЯНО ▐▐", "MuR_Font5", sw/2, sh/2 - 30, textCol, TEXT_ALIGN_CENTER)
            draw.SimpleText("СВЯЗЬ ПРЕКРАЩЕНА", "MuR_Font2", sw/2, sh/2 + 30, Color(150,150,150,200), TEXT_ALIGN_CENTER)

            DrawHeavySignalNoise(0.05)
        end)

        timer.Simple(2, function()
            hook.Remove("HUDPaint", "Spy_DroneCamLost")
        end)
    end

    net.Receive("MuR_DroneLost_Spy", LoseDrone)

    ---------------------------------------------------------
    -- Синхронизация состояния тепловизора от сервера
    -- (перенесено сюда чтобы менять локальную переменную Thermal)
    ---------------------------------------------------------
    net.Receive("MuR_ThermalState_Spy", function()
        local state = net.ReadBool()
        Thermal = state

        if not Thermal then
            -- гарантированный сброс XRay и возврат материалов
            if DoXRay then
                RestoreXRayMaterials()
            end
        end
    end)

    ---------------------------------------------------------
    -- ПОЛУЧЕНИЕ ДРОНА / ОСНОВНОЙ HUD
    ---------------------------------------------------------

    net.Receive("MuR_DroneCam_Spy", function()
        local ent = net.ReadEntity()
        DRONE = ent
        Thermal = false
        Zoom = 1

        if IsValid(ent) then
            FPV_Yaw = ent:GetAngles().y
            FPV_Pitch = 0
        end

        local pulseAlpha = 0
        local pulseDir = 1
        local startTime = CurTime()
        local smoothBatt = 1
        local smoothHP = 1

        local ppTab = {
            ["$pp_colour_addr"] = 0,
            ["$pp_colour_addg"] = 0.02,
            ["$pp_colour_addb"] = 0.05,
            ["$pp_colour_brightness"] = -0.01,
            ["$pp_colour_contrast"] = 1.1,
            ["$pp_colour_colour"] = 0.6,
            ["$pp_colour_mulr"] = 0,
            ["$pp_colour_mulg"] = 0.05,
            ["$pp_colour_mulb"] = 0.05
        }

        hook.Add("RenderScreenspaceEffects", "Spy_DroneCam", function()
            if not IsValid(ent) then return end

            local rt = GetDroneRT()
            render.CopyRenderTargetToTexture(rt)

            local timeLeft = math.max(ent:GetNW2Float("RemoveTime") - CurTime(), 0)
            local battFrac = math.Clamp(timeLeft / ent.BatteryCount, 0, 1)

            if battFrac < 0.2 then
                ppTab["$pp_colour_addr"] = 0.1 * (1 - battFrac / 0.2)
                ppTab["$pp_colour_contrast"] = 1.15 + 0.2 * (1 - battFrac / 0.2)
            else
                ppTab["$pp_colour_addr"] = 0
                ppTab["$pp_colour_contrast"] = 1.15
            end

            DrawColorModify(ppTab)
            DrawSharpen(0.8, 0.8)
        end)

        -----------------------------------------------------
        -- FLIR / X-RAY
        -----------------------------------------------------

        hook.Add("RenderScene", "spy_drone_FLIR_Apply", function()
            if not IsValid(DRONE) then return end
            if DRONE:GetClass() ~= "mur_drone_spy" then return end

            if not Thermal then return end
            if not DRONE:GetNW2Bool("ThermalActive") then return end

            if not DoXRay then
                DoXRay = true
                ApplyXRay()
            end
        end)

        hook.Add("HUDPaintBackground", "spy_drone_FLIR_Effects", function()
            if not Thermal then return end
            if not IsValid(DRONE) then return end
            if DRONE:GetClass() ~= "mur_drone_spy" then return end

            RenderFLIR()
        end)

        hook.Add("Think", "spy_drone_FLIR_AutoOff", function()
            -- если тепловизор включён и дрон валиден — ничего не делаем
            if Thermal and IsValid(DRONE) then return end

            -- иначе — сбрасываем XRay и возвращаем материалы
            if DoXRay then
                DoXRay = false

                for ent2, mat in pairs(DefMats) do
                    if IsValid(ent2) then ent2:SetMaterial(mat) end
                end
                for ent2, clr in pairs(DefClrs) do
                    if IsValid(ent2) then
                        ent2:SetRenderMode(RENDERMODE_TRANSALPHA)
                        ent2:SetColor(Color(clr.r, clr.g, clr.b, clr.a))
                    end
                end

                DefMats = {}
                DefClrs = {}
            end
        end)

        ---------------------------------------------------------
        -- HUD КАМЕРЫ (ОСНОВНОЙ)
        ---------------------------------------------------------

        hook.Add("HUDPaint", "Spy_DroneCam", function()
            if not IsValid(ent) then return end

            local sw, sh = ScrW(), ScrH()
            local cx, cy = sw / 2, sh / 2
            local time = CurTime()
            local elapsed = time - startTime

            pulseAlpha = pulseAlpha + pulseDir * FrameTime() * 400
            if pulseAlpha >= 255 then pulseDir = -1 pulseAlpha = 255
            elseif pulseAlpha <= 100 then pulseDir = 1 pulseAlpha = 100 end

            local timeLeft = math.max(ent:GetNW2Float("RemoveTime") - CurTime(), 0)
            local battFrac = math.Clamp(timeLeft / ent.BatteryCount, 0, 1)
            local hpFrac = math.Clamp(ent:Health() / ent.HealthCount, 0, 1)

            smoothBatt = Lerp(FrameTime() * 3, smoothBatt, battFrac)
            smoothHP   = Lerp(FrameTime() * 5, smoothHP, hpFrac)

            local vel = ent:GetVelocity():Length()
            local spd = math.Round(vel * 0.068)

            local tr = util.TraceLine({
                start = ent:GetPos(),
                endpos = ent:GetPos() - Vector(0,0,10000),
                filter = ent
            })

            local agl = math.Round(ent:GetPos().z - tr.HitPos.z)

            local dist2 = LocalPlayer():GetPos():DistToSqr(ent:GetPos())
            local signal = math.Clamp(1 - (dist2 / (8000 * 8000)), 0, 1)


            local killTime = ent:GetNWFloat("EmergencyCountdown", 0)

            DrawScanlines(sw, sh, 20)
            DrawGlitchNoise(sw, sh, signal)

            local frameCol = Color(100, 200, 255, 120)
            DrawCornerBrackets(40, 40, sw - 80, sh - 80, 60, 3, frameCol)

            local crossCol = Color(100, 200, 255, pulseAlpha)
            DrawCrosshair(cx, cy, 25, 8, 2, crossCol)

            surface.SetDrawColor(100, 200, 255, 60)
            DrawArcSegment(cx, cy, 45, 0, 360, 1, 64, Color(100,200,255,40))

            draw.SimpleText("◈ РАЗВЕДЫВАТЕЛЬНЫЙ ДРОН", "MuR_Font3", 80, 60, Color(100,200,255), TEXT_ALIGN_LEFT)
            draw.SimpleText(string.format("ВРЕМЯ РАБОТЫ %.1fs", elapsed), "MuR_Font1", 80, 95, Color(150,150,150), TEXT_ALIGN_LEFT)
            draw.SimpleText(os.date("%H:%M:%S"), "MuR_Font1", 80, 115, Color(150,150,150), TEXT_ALIGN_LEFT)

            local telemX = sw - 80
            local spdCol = spd > 100 and Color(255, 200, 60) or Color(100, 200, 255)
            draw.SimpleText(string.format("%03d km/h", spd), "MuR_Font3", telemX, 60, spdCol, TEXT_ALIGN_RIGHT)
            draw.SimpleText("СКОР", "MuR_Font1", telemX, 95, Color(100,100,100), TEXT_ALIGN_RIGHT)

            draw.SimpleText(string.format("%04d m", agl), "MuR_Font3", telemX, 120, Color(100,200,255), TEXT_ALIGN_RIGHT)
            draw.SimpleText("ВЫС", "MuR_Font1", telemX, 155, Color(100,100,100), TEXT_ALIGN_RIGHT)

            local sigCol = signal < 0.25 and Color(255, 60, 60)
                or (signal < 0.5 and Color(255, 200, 60) or Color(100, 200, 255))
            local sigBars = math.floor(signal * 5)
            local sigStr = string.rep("▮", sigBars) .. string.rep("▯", 5 - sigBars)
            draw.SimpleText(sigStr, "MuR_Font2", telemX, 180, sigCol, TEXT_ALIGN_RIGHT)
            draw.SimpleText(string.format("%d%%", math.Round(signal * 100)), "MuR_Font1", telemX, 210, sigCol, TEXT_ALIGN_RIGHT)

            local barW, barH = 250, 12
            local barX, barY = 80, sh - 180

            local battCol = smoothBatt < 0.2 and Color(255,60,60)
                or (smoothBatt < 0.4 and Color(255,200,60) or Color(100,200,255))
            surface.SetDrawColor(30,30,30,200)
            surface.DrawRect(barX, barY, barW, barH)
            surface.SetDrawColor(battCol.r, battCol.g, battCol.b, 255)
            surface.DrawRect(barX + 2, barY + 2, (barW - 4) * smoothBatt, barH - 4)
            surface.SetDrawColor(battCol.r, battCol.g, battCol.b, 100)
            surface.DrawOutlinedRect(barX, barY, barW, barH, 1)
            draw.SimpleText(string.format("ЗАРЯД %d%%", math.Round(smoothBatt * 100)), "MuR_Font1", barX, barY - 20, battCol, TEXT_ALIGN_LEFT)
            draw.SimpleText(string.format("%.0fs", timeLeft), "MuR_Font1", barX + barW, barY - 20, Color(150,150,150), TEXT_ALIGN_RIGHT)

            barY = sh - 130
            local hpCol = smoothHP < 0.3 and Color(255,60,60)
                or (smoothHP < 0.6 and Color(255,200,60) or Color(100,200,255))
            surface.SetDrawColor(30,30,30,200)
            surface.DrawRect(barX, barY, barW, barH)
            surface.SetDrawColor(hpCol.r, hpCol.g, hpCol.b, 255)
            surface.DrawRect(barX + 2, barY + 2, (barW - 4) * smoothHP, barH - 4)
            surface.SetDrawColor(hpCol.r, hpCol.g, hpCol.b, 100)
            surface.DrawOutlinedRect(barX, barY, barW, barH, 1)
            draw.SimpleText(string.format("ПРОЧНОСТЬ %d%%", math.Round(smoothHP * 100)), "MuR_Font1", barX, barY - 20, hpCol, TEXT_ALIGN_LEFT)

            -- Блок управления
            local ctrlX, ctrlY = sw - 80, sh - 200
            local ctrlCol = Color(150,150,150,200)
            draw.SimpleText("▶ [J] САМОУНИЧТОЖЕНИЕ", "MuR_Font1", ctrlX, ctrlY, Color(255,80,80,200), TEXT_ALIGN_RIGHT)
            draw.SimpleText("▲ [SHIFT] ВВЕРХ", "MuR_Font1", ctrlX, ctrlY + 22, ctrlCol, TEXT_ALIGN_RIGHT)
            draw.SimpleText("▼ [CTRL] ВНИЗ", "MuR_Font1", ctrlX, ctrlY + 44, ctrlCol, TEXT_ALIGN_RIGHT)
            draw.SimpleText("▶ [ALT] ТЕПЛОВИЗОР", "MuR_Font1", ctrlX, ctrlY + 66, Color(100,200,255), TEXT_ALIGN_RIGHT)

            if smoothBatt < 0.15 then
                local warnFlash = math.sin(time * 8) > 0 and 255 or 100
                draw.SimpleText("⚠ НИЗКИЙ ЗАРЯД ⚠", "MuR_Font4", cx, 80, Color(255,60,60,warnFlash), TEXT_ALIGN_CENTER)
            end

            if smoothHP < 0.25 then
                local dmgFlash = math.sin(time * 6) > 0 and 255 or 100
                draw.SimpleText("⚠ КРИТИЧЕСКИЕ ПОВРЕЖДЕНИЯ ⚠", "MuR_Font3", cx, 130, Color(255,120,60,dmgFlash), TEXT_ALIGN_CENTER)
            end

            if signal < 0.2 then
                local sigFlash = math.sin(time * 10) > 0 and 255 or 100
                draw.SimpleText("◢◤ СЛАБЫЙ СИГНАЛ ◢◤", "MuR_Font3", cx, 180, Color(255, 80, 60, sigFlash), TEXT_ALIGN_CENTER)
            end
            DrawGlitchNoise(sw, sh, signal)
            if ent:GetNWBool("Jammed") then
                local jamStrength = ent:GetNWFloat("JamStrength", 1)

                DrawHeavySignalNoise(jamStrength)

                local jamFlash = math.sin(time * 8) > 0 and 255 or 120
                draw.SimpleText(
                    "◢◤ ОБНАРУЖЕНЫ ПОМЕХИ ◢◤",
                    "MuR_Font3",
                    cx,
                    220,
                    Color(255, 80, 60, jamFlash),
                    TEXT_ALIGN_CENTER
                )
            end

            -- Обратный отсчёт самоуничтожения
            if killTime > CurTime() then
                local left = math.max(0, killTime - CurTime())
                local flash = math.sin(CurTime() * 10) > 0 and 255 or 120

                draw.SimpleText(
                    string.format("САМОУНИЧТОЖЕНИЕ: %.1f", left),
                    "MuR_Font3",
                    cx,
                    260,
                    Color(255, 50, 50, flash),
                    TEXT_ALIGN_CENTER
                )
            end

            DrawHeavySignalNoise(signal)
        end)
        hook.Add("CreateMove", "Spy_Drone_BlockWeapons", function(cmd)
            if not IsValid(DRONE) then return end
            if DRONE:GetClass() ~= "mur_drone_spy" then return end

            cmd:RemoveKey(IN_ATTACK)
            cmd:RemoveKey(IN_ATTACK2)
            cmd:RemoveKey(IN_RELOAD)
            cmd:RemoveKey(IN_USE)
            cmd:SetImpulse(0)
        end)
    end)

    ---------------------------------------------------------
    -- КАМЕРА (CalcView)
    ---------------------------------------------------------

    hook.Add("CalcView", "Spy_DroneCam_Global", function(ply, pos, angles, fov)
        if not IsValid(DRONE) then return end
        if DRONE:GetClass() ~= "mur_drone_spy" then return end

        local dPos = DRONE:GetPos()
        local vel  = DRONE:GetVelocity():Length()

        local offset = Vector(-8 - math.Clamp(vel * 0.015, 0, 5), 0, -2)
        local camPos = dPos + DRONE:GetForward() * offset.x + DRONE:GetUp() * offset.z

        local camAng = Angle(FPV_Pitch, FPV_Yaw, 0)

        local baseFov = 60
        local speedBoost = math.Clamp(vel * 0.025, 0, 15)
        local dynFov = baseFov + speedBoost
        dynFov = Lerp(Zoom, 20, dynFov)

        dynFov = Lerp(Zoom, 20, dynFov)

        return {
            origin = camPos,
            angles = camAng,
            fov = math.Clamp(dynFov, 20, 120),
            drawviewer = true
        }
    end)

    hook.Add("Think", "spy_drone_Zoom", function()
        if not IsValid(DRONE) then return end
        if DRONE:GetClass() ~= "mur_drone_spy" then return end

        local delta = input.GetAnalogValue(ANALOG_MOUSE_WHEEL)
        if delta ~= 0 then
            Zoom = Zoom - delta * 0.05
            Zoom = math.Clamp(Zoom, 0, 1)
        end
    end)

    -- Перехват invprev/invnext чтобы колесо и кнопки не переключали оружие
    hook.Add("PlayerBindPress", "spy_drone_ZoomBlock", function(ply, bind, pressed)
        if not IsValid(DRONE) then return end
        if DRONE:GetClass() ~= "mur_drone_spy" then return end

        if bind == "invprev" then
            Zoom = math.Clamp(Zoom - 0.1, 0, 1)
            return true
        end

        if bind == "invnext" then
            Zoom = math.Clamp(Zoom + 0.1, 0, 1)
            return true
        end
    end)

    ---------------------------------------------------------
    -- ТЕПЛОВИЗОР (кнопка)
    ---------------------------------------------------------

    hook.Add("Think", "spy_drone_ThermalToggle", function()
        if not IsValid(DRONE) then return end
        if DRONE:GetClass() ~= "mur_drone_spy" then return end

        if input.IsKeyDown(KEY_LALT) and not ThermalKeyHeld then
            ThermalKeyHeld = true
            Thermal = not Thermal

            surface.PlaySound(Thermal and "sw/misc/nv_on.wav" or "sw/misc/nv_off.wav")

            net.Start("MuR_ThermalState_Spy")
            net.WriteBool(Thermal)
            net.SendToServer()
        end

        if not input.IsKeyDown(KEY_LALT) then
            ThermalKeyHeld = false
        end
    end)

    ---------------------------------------------------------
    -- FPV МЫШЬ
    ---------------------------------------------------------

    hook.Add("CreateMove", "Spy_Drone_FPV_Mouse", function(cmd)
        if not IsValid(DRONE) then return end
        if DRONE:GetClass() ~= "mur_drone_spy" then return end

        local mx = cmd:GetMouseX()
        local my = cmd:GetMouseY()

        FPV_Yaw   = FPV_Yaw   - mx * 0.03
        FPV_Pitch = FPV_Pitch + my * 0.03
        FPV_Pitch = math.Clamp(FPV_Pitch, -45, 45)

        cmd:SetMouseX(0)
        cmd:SetMouseY(0)
        cmd:SetForwardMove(0)
        cmd:SetSideMove(0)

        DRONE:SetNW2Float("FPV_Yaw", FPV_Yaw)
        DRONE:SetNW2Float("FPV_Pitch", FPV_Pitch)
    end)

    ---------------------------------------------------------
    -- КЛАВИША G ДЛЯ САМОУНИЧТОЖЕНИЯ
    ---------------------------------------------------------

    hook.Add("Think", "spy_drone_EmergencyKey", function()
        if not IsValid(DRONE) then return end
        if DRONE:GetClass() ~= "mur_drone_spy" then return end

        DRONE._KillKeyHeld = DRONE._KillKeyHeld or false

        if input.IsKeyDown(KEY_J) and not DRONE._KillKeyHeld then
            DRONE._KillKeyHeld = true

            net.Start("MuR_DroneEmergency_Spy")
            net.SendToServer()
        end

        if not input.IsKeyDown(KEY_J) then
            DRONE._KillKeyHeld = false
        end
    end)

    -- Подстраховка: если дрон удалён — вернуть материалы и очистить переменные
    hook.Add("Think", "spy_drone_cleanup_on_remove", function()
        if DRONE and not IsValid(DRONE) then
            DRONE = nil
            Thermal = false
            RestoreXRayMaterials()
        end
    end)

end
