REInteREInterfaceWeight = REInterfaceWeight or {}

-------------------------------------------------
-- 1) Apply custom base carry weight (sandbox)
-------------------------------------------------
local function applyREWeight(player)
    if not player then return end

    local sv = SandboxVars.REInterfaceWeight or {}

    local vanillaBase = player:getMaxWeightBase()
    local baseCap     = vanillaBase

    if sv.UseCustomStartWeight == true then
        if sv.BaseCapacity and sv.BaseCapacity ~= 12 then
            baseCap = sv.BaseCapacity
        end
    end

    player:setMaxWeightBase(baseCap)
    player:setMaxWeight(baseCap)
end

local function onGameLoaded()
    local p = getPlayer()
    if p then applyREWeight(p) end
end

Events.OnCreatePlayer.Add(function(pid, player)
    applyREWeight(player)
end)
Events.OnLoad.Add(onGameLoaded)
Events.OnGameStart.Add(onGameLoaded)

-------------------------------------------------
-- 2) Patch ONLY the player-inventory title bar
--    so it uses Tetris / player inventory weight
-------------------------------------------------
local function REI_PatchInventoryTitleWeight()
    if not ISInventoryPage then return end
    if ISInventoryPage.REI_WeightPatched then return end
    ISInventoryPage.REI_WeightPatched = true

    local oldLoadWeight = ISInventoryPage.loadWeight

    -- This is called by ISInventoryPage:render()
    -- to get the number drawn as "X / Y" in the
    -- inventory window title bar.
    function ISInventoryPage.loadWeight(inv)
        if inv then
            -- Check all active players and see if this
            -- ItemContainer *is* one of their main inventories.
            local numPlayers = getNumActivePlayers() or 1
            for i = 0, numPlayers - 1 do
                local player = getSpecificPlayer(i)
                if player and inv == player:getInventory() then
                    -- Use the same weight that Tetris uses
                    -- for the player: inventory-only weight.
                    return player:getInventoryWeight()
                end
            end
        end

        -- Anything that isn't a player main inventory
        -- stays completely vanilla (backpacks, ground, etc).
        return oldLoadWeight(inv)
    end

    print("[REInterface] ISInventoryPage.loadWeight patched → player title uses inventory weight only.")
end

Events.OnGameStart.Add(REI_PatchInventoryTitleWeight)
Events.OnLoad.Add(REI_PatchInventoryTitleWeight)
