local PLUGIN = PLUGIN

local storageData = {}

net.Receive("ixStorageSync", function()
    storageData = net.ReadTable()
    
    if (IsValid(ix.gui.personalStorage)) then
        ix.gui.personalStorage:UpdateStorage(storageData)
        ix.gui.personalStorage:UpdatePlayerItems()
    else
        PLUGIN:OpenUI()
    end
end)

function PLUGIN:OpenUI()
    if (IsValid(ix.gui.personalStorage)) then
        ix.gui.personalStorage:Remove()
    end

    local frame = vgui.Create("DFrame")
    frame:SetSize(800, 600)
    frame:Center()
    frame:SetTitle("ПЕРСОНАЛЬНЫЙ СКЛАД")
    frame:MakePopup()
    ix.gui.personalStorage = frame

    frame.Paint = function(self, w, h)
        surface.SetDrawColor(30, 30, 30, 240)
        surface.DrawRect(0, 0, w, h)
        local accent = ix.config.Get("color") or Color(100, 150, 100)
        surface.SetDrawColor(accent)
        surface.DrawOutlinedRect(0, 0, w, h)
        
        surface.SetDrawColor(accent.r, accent.g, accent.b, 50)
        surface.DrawRect(0, 0, w, 24)
    end

    local leftPanel = frame:Add("DPanel")
    leftPanel:Dock(LEFT)
    leftPanel:SetWide(385)
    leftPanel:DockMargin(10, 30, 5, 10)
    leftPanel.Paint = function(self, w, h)
        surface.SetDrawColor(0, 0, 0, 100)
        surface.DrawRect(0, 0, w, h)
    end

    local rightPanel = frame:Add("DPanel")
    rightPanel:Dock(RIGHT)
    rightPanel:SetWide(385)
    rightPanel:DockMargin(5, 30, 10, 10)
    rightPanel.Paint = function(self, w, h)
        surface.SetDrawColor(0, 0, 0, 100)
        surface.DrawRect(0, 0, w, h)
    end

    local pScroll = leftPanel:Add("DScrollPanel")
    pScroll:Dock(FILL)
    pScroll:DockMargin(5, 5, 5, 5)

    function frame:UpdatePlayerItems()
        pScroll:Clear()
        
        local wepHeader = pScroll:Add("DLabel")
        wepHeader:SetText("ОРУЖИЕ В РУКАХ")
        wepHeader:SetFont("ixSmallFont")
        wepHeader:Dock(TOP)
        wepHeader:SetContentAlignment(5)
        wepHeader:SetTall(25)
        wepHeader:SetTextColor(ix.config.Get("color"))

        for _, wep in pairs(LocalPlayer():GetWeapons()) do
            if (!IsValid(wep)) then continue end
            
            local wepName = wep:GetPrintName()
            local class = wep:GetClass()

            local btn = pScroll:Add("ixMenuButton")
            btn:Dock(TOP)
            btn:SetTall(35)
            btn:SetText(wepName)
            btn.DoClick = function()
                if (frame.nextClick and frame.nextClick > CurTime()) then return end
                frame.nextClick = CurTime() + 1.0 -- Increase cooldown for safety

                net.Start("ixStorageDeposit")
                net.WriteString("weapon")
                net.WriteString(class)
                net.SendToServer()
                
                btn:SetEnabled(false)
                btn:SetText("ОЖИДАНИЕ...")
                
                -- Fail-safe to re-enable UI if server doesn't respond
                timer.Simple(2, function()
                    if (IsValid(btn) and !btn:IsEnabled()) then
                        btn:SetEnabled(true)
                        btn:SetText(wepName)
                    end
                end)
            end
        end

        local invHeader = pScroll:Add("DLabel")
        invHeader:SetText("ПРЕДМЕТЫ В ИНВЕНТАРЕ")
        invHeader:SetFont("ixSmallFont")
        invHeader:Dock(TOP)
        invHeader:SetContentAlignment(5)
        invHeader:SetTall(25)
        invHeader:DockMargin(0, 10, 0, 0)
        invHeader:SetTextColor(ix.config.Get("color"))

        local char = LocalPlayer():GetCharacter()
        if (char) then
            local inv = char:GetInventory()
            if (inv) then
                for _, item in pairs(inv:GetItems()) do
                    local btn = pScroll:Add("ixMenuButton")
                    btn:Dock(TOP)
                    btn:SetTall(35)
                    btn:SetText(item:GetName())
                    local originalText = item:GetName()
                    btn.DoClick = function()
                        if (frame.nextClick and frame.nextClick > CurTime()) then return end
                        frame.nextClick = CurTime() + 1.0

                        net.Start("ixStorageDeposit")
                        net.WriteString("item")
                        net.WriteString(tostring(item:GetID()))
                        net.SendToServer()
                        
                        btn:SetEnabled(false)
                        btn:SetText("ОЖИДАНИЕ...")

                        timer.Simple(2, function()
                            if (IsValid(btn) and !btn:IsEnabled()) then
                                btn:SetEnabled(true)
                                btn:SetText(originalText)
                            end
                        end)
                    end
                end
            end
        end
    end
    frame:UpdatePlayerItems()

    local sScroll = rightPanel:Add("DScrollPanel")
    sScroll:Dock(FILL)
    sScroll:DockMargin(5, 5, 5, 5)

    local storageHeader = sScroll:Add("DLabel")
    storageHeader:SetText("СОДЕРЖИМОЕ ХРАНИЛИЩА")
    storageHeader:SetFont("ixSmallFont")
    storageHeader:Dock(TOP)
    storageHeader:SetContentAlignment(5)
    storageHeader:SetTall(25)
    storageHeader:SetTextColor(ix.config.Get("color"))

    local grid = sScroll:Add("DIconLayout")
    grid:Dock(TOP)
    grid:SetSpaceX(5)
    grid:SetSpaceY(5)

    function frame:UpdateStorage(data)
        grid:Clear()
        
        for i, entry in ipairs(data) do
            if (!istable(entry)) then continue end
            
            local icon = grid:Add("SpawnIcon")
            
            local model = "models/error.mdl"
            if (entry.type == "weapon" and entry.class) then
                local wepTable = weapons.Get(entry.class)
                model = (wepTable and wepTable.WorldModel) or "models/weapons/w_pistol.mdl"
            elseif (entry.type == "item" and entry.uniqueID) then
                local itemTable = ix.item.list[entry.uniqueID]
                model = (itemTable and itemTable.model) or "models/props_junk/garbage_bag001a.mdl"
            end

            icon:SetModel(model)
            icon:SetSize(64, 64)
            icon:SetTooltip(entry.name or entry.class or entry.uniqueID or "Неизвестный предмет")
            icon.DoClick = function()
                if (frame.nextClick and frame.nextClick > CurTime()) then return end
                frame.nextClick = CurTime() + 1.0

                net.Start("ixStorageWithdraw")
                net.WriteUInt(i, 8)
                net.SendToServer()
                
                icon:SetAlpha(100)
                
                timer.Simple(2, function()
                    if (IsValid(icon)) then icon:SetAlpha(255) end
                end)
            end
        end
    end
    frame:UpdateStorage(storageData)
end
