BTtow = {}
BTtow.Create = {}
BTtow.Init = {}

local TowbarVariantSize = 24
local TowbarNormalStart = 0
local TowbarLargeStart = 24
local TowbarMaxIndex = TowbarVariantSize - 1

local function getVehicleModelScale(script)
    if not script then return nil end

    local ok, result = pcall(function()
        return script:getModelScale()
    end)
    if ok and type(result) == "number" then
        return result
    end

    ok, result = pcall(function()
        local model = script:getModel()
        if model then
            return model:getScale()
        end
        return nil
    end)
    if ok and type(result) == "number" then
        return result
    end

    return nil
end

local function shouldUseLargeTowbarModel(script)
    local modelScale = getVehicleModelScale(script)
    if modelScale == nil then
        return false
    end

    local configuredThreshold = TowBarMod and TowBarMod.Config and tonumber(TowBarMod.Config.largeTowbarModelScaleThreshold)
    local threshold = configuredThreshold or 1.2
    return modelScale < threshold
end

local function getTowbarModelSlot(script)
    local chassisZ = script:getPhysicsChassisShape():z()
    local index = 0
    if chassisZ > 3.0 then
        local halfZ = chassisZ / 2
        index = math.floor((halfZ - 1.0) * 16 - 1)
    end
    index = math.max(0, math.min(TowbarMaxIndex, index))

    local slotStart = shouldUseLargeTowbarModel(script) and TowbarLargeStart or TowbarNormalStart
    return slotStart + index
end

function BTtow.Create.towbar(vehicle, part)  
    if part == nil then return end
    for j=0, (TowbarVariantSize * 2) - 1 do
        part:setModelVisible("towbar" .. j, false)        
    end
end

function BTtow.Init.towbar(vehicle, part)
    if part == nil then return end
    for j=0, (TowbarVariantSize * 2) - 1 do
        part:setModelVisible("towbar" .. j, false)
    end
    if vehicle:getModData()["isTowingByTowBar"] and vehicle:getModData()["towed"] then
        local script = vehicle:getScript()
        if script then
            local slot = getTowbarModelSlot(script)
            part:setModelVisible("towbar" .. slot, true)
        end
    end
end
