-- =========================================================
-- ExwindVirtualList.lua - 事件驱动的可复用虚拟列表
-- =========================================================

local ExwindTools = _G.ExwindTools
if not ExwindTools then return end

local VirtualList = {}
ExwindTools.VirtualList = VirtualList
_G.ExwindVirtualList = VirtualList

local function Clamp(value, minValue, maxValue)
    value = tonumber(value) or minValue
    if value < minValue then return minValue end
    if value > maxValue then return maxValue end
    return value
end

local function GetSlotCount(list)
    local height = math.max(1, list:GetHeight() or 1)
    local count = math.max(1, math.ceil(height / list.rowHeight) + list.overscan)
    if list.maxRows then
        count = math.min(count, list.maxRows)
    end
    return count
end

function VirtualList:Create(parent, options)
    options = type(options) == "table" and options or {}
    local list = CreateFrame("Frame", nil, parent, "BackdropTemplate")
    list.rowHeight = math.max(20, tonumber(options.rowHeight) or 42)
    list.overscan = math.max(0, math.floor(tonumber(options.overscan) or 1))
    list.maxRows = tonumber(options.maxRows)
    if list.maxRows then list.maxRows = math.max(1, math.floor(list.maxRows)) end
    list.createRow = options.createRow
    list.bindRow = options.bindRow
    list.rows = {}
    list.items = {}
    list.offset = 0
    list.context = nil
    list:EnableMouseWheel(true)

    list.scrollBar = CreateFrame("Slider", nil, list, "UIPanelScrollBarTemplate")
    list.scrollBar:SetPoint("TOPRIGHT", list, "TOPRIGHT", -1, -16)
    list.scrollBar:SetPoint("BOTTOMRIGHT", list, "BOTTOMRIGHT", -1, 16)
    list.scrollBar:SetWidth(16)
    list.scrollBar:SetMinMaxValues(0, 0)
    list.scrollBar:SetValueStep(1)
    list.scrollBar:SetObeyStepOnDrag(true)

    function list:EnsureRows()
        local wanted = GetSlotCount(self)
        while #self.rows < wanted do
            local row = type(self.createRow) == "function" and self.createRow(self) or CreateFrame("Frame", nil, self)
            row:SetParent(self)
            row:ClearAllPoints()
            row:SetPoint("TOPLEFT", self, "TOPLEFT", 0, -((#self.rows) * self.rowHeight))
            row:SetPoint("TOPRIGHT", self, "TOPRIGHT", -22, -((#self.rows) * self.rowHeight))
            row:SetHeight(self.rowHeight)
            -- 鼠标落在实际行上时也交给列表滚动，避免子控件吞掉滚轮事件。
            if row.EnableMouseWheel then row:EnableMouseWheel(true) end
            row:SetScript("OnMouseWheel", function(_, delta)
                self:SetOffset(self.offset - (tonumber(delta) or 0))
            end)
            self.rows[#self.rows + 1] = row
        end
    end

    function list:GetMaxOffset()
        return math.max(0, #self.items - GetSlotCount(self))
    end

    function list:Refresh()
        -- 在 custom host 完成最终尺寸前，列表会经历若干次 SizeChanged。
        -- 空数据不应预创建行/复合控件，否则首次打开会产生无效分配和闪动。
        if #self.items == 0 then
            self.offset = 0
            self.scrollBar:SetMinMaxValues(0, 0)
            self.scrollBar:SetValue(0)
            self.scrollBar:Hide()
            for _, row in ipairs(self.rows) do row:Hide() end
            return
        end

        self:EnsureRows()
        local maxOffset = self:GetMaxOffset()
        self.offset = math.floor(Clamp(self.offset, 0, maxOffset) + 0.5)
        self.scrollBar:SetMinMaxValues(0, maxOffset)
        self.scrollBar:SetValue(self.offset)
        self.scrollBar:SetShown(maxOffset > 0)
        for slot, row in ipairs(self.rows) do
            local index = self.offset + slot
            local item = self.items[index]
            if item then
                row:SetShown(true)
                if type(self.bindRow) == "function" then
                    self.bindRow(row, item, index, self.context, self)
                end
            else
                if type(self.bindRow) == "function" then
                    self.bindRow(row, nil, nil, nil, self)
                end
                row:Hide()
            end
        end
    end

    function list:SetData(items, context)
        self.items = type(items) == "table" and items or {}
        self.context = context
        self.offset = 0
        self:Refresh()
    end

    function list:SetOffset(offset)
        self.offset = math.floor(Clamp(offset, 0, self:GetMaxOffset()) + 0.5)
        self:Refresh()
    end

    function list:ReleaseData()
        self:SetData({}, nil)
        self:Hide()
    end

    list.scrollBar:SetScript("OnValueChanged", function(_, value)
        local offset = math.floor((tonumber(value) or 0) + 0.5)
        if offset ~= list.offset then
            list.offset = offset
            list:Refresh()
        end
    end)
    list:SetScript("OnMouseWheel", function(_, delta)
        list:SetOffset(list.offset - (tonumber(delta) or 0))
    end)
    list:SetScript("OnSizeChanged", function()
        list:Refresh()
    end)

    return list
end
