-- REAsoilTracks.lua
-- erzeugt sichtbare Boden- / Matschspuren abhängig von REAwheels Sink + Slip

REAsoilTracks = {}
local function tPrint(msg) print(("REAsoilTracks: %s"):format(tostring(msg))) end

function REAsoilTracks.prerequisitesPresent(specializations)
    return true
end

function REAsoilTracks.registerEventListeners(vehicleType)
    SpecializationUtil.registerEventListener(vehicleType, "onUpdate", REAsoilTracks)
end

function REAsoilTracks:onUpdate(dt)
    local wheels = self.spec_wheels and self.spec_wheels.wheels
    local specW = self.spec_REAwheels

    if wheels == nil or specW == nil or not specW.active then return end

    -- Spur nur erstellen wenn realer Kontakt
    if specW.sink <= 0.001 or specW.slip < 0.01 then return end

    local trackIntensity = math.min(specW.sink * 4, 1.0) -- 0..1
    local slipFactor = math.min(specW.slip * 3, 1.0)

    for _, w in ipairs(wheels) do
        if w.driveGroundContact and w.isDriveWheel then
            local x, y, z = getWorldTranslation(w.node)

            local width = (w.width or 0.4) * (0.6 + trackIntensity)
            local depth = specW.sink * 0.08 -- wie tief die Spur gezeichnet wird

            -- Giants FS25 API: TerrainDecalManager
            local decalType = TerrainDecalManager.DEDECAL_SOIL
            if slipFactor > 0.6 then
                decalType = TerrainDecalManager.DEDECAL_MUD
            end

            TerrainDecalManager.addTrack(x, y, z, w.lastWheelDamping or 0.1, width, depth, decalType)
        end
    end
end

tPrint("REAsoilTracks aktiviert")
