local M = {}

local normalRevLimiterAV = 6200
local normalRevLimiterAVDrop = 100
local revlimiterAVDecreaseRate = 0.007
local revlimiterAVDropIncreaseRate = 0.12
local revlimiterAVLow = 620
local revlimiterAVDropLow = 10
local lastThrottleState = 0
local throttleTimer = 0
local releaseTimer = 0
local isThrottleHigh = false

local function init()
    lastThrottleState = 0
    throttleTimer = 0
    releaseTimer = 0
    isThrottleHigh = false
end

local function updateGFX(dt)
    local throttle = electrics.values.throttle or 0
    local engine = powertrain.getDevice("mainEngine")
    local gear = electrics.values.gearIndex or 0
    local clutch = electrics.values.clutch or 0
    
    if engine then
        if throttle >= 0.9 and (gear == 0 or clutch >= 1) then
            if not isThrottleHigh then
                throttleTimer = 0
                isThrottleHigh = true
            end
            throttleTimer = throttleTimer + dt

            if throttleTimer >= 2 then
                engine.revLimiterAV = engine.revLimiterAV * (1 - revlimiterAVDecreaseRate)
                engine.revLimiterAVDrop = engine.revLimiterAVDrop * (1 + revlimiterAVDropIncreaseRate)
                throttleTimer = 0
            end
            releaseTimer = 0 -- Reset release timer when throttle is high
        elseif throttle < 0.9 then
            if isThrottleHigh then
                releaseTimer = releaseTimer + dt
                if releaseTimer >= 1.5 then
                    engine.revLimiterAV = revlimiterAVLow
                    engine.revLimiterAVDrop = revlimiterAVDropLow
                    isThrottleHigh = false
                    releaseTimer = 0
                end
            end
        end
    end
end

M.init = init
M.updateGFX = updateGFX

return M