-- layout/home3.lua
local renderList
local showLoading
local showLoadingInto

showLoadingInto = function(ctx, container, msg)
    if not container then return end
    local tv = TextView(ctx.activity)
    tv.setText(msg or "暂无数据")
    tv.setTextColor(ctx.getColors().TEXT_SUB)
    tv.setTextSize(14)
    tv.setGravity(Gravity.CENTER)
    tv.setPadding(0, ctx.dp(36), 0, ctx.dp(36))
    container.addView(tv)
    ctx.fadeInView(tv, 220, 0)
end

showLoading = function(ctx, msg)
    showLoadingInto(ctx, ctx.contentLayout, msg)
end

renderList = function(ctx, catId)
    local contentLayout = ctx.contentLayout
    local state = ctx.state

    local items = state.dataCache[catId]

    ctx.recycleAllCards()
    contentLayout.removeAllViews()

    local sec = ctx.makeSectionTitle("资源 · 全部")
    contentLayout.addView(sec)
    ctx.fadeInView(sec, 220, 0)

    if not items or #items == 0 then
        showLoading(ctx, "暂无资源")
        return
    end

    for i = 1, #items do
        local item = items[i]
        local rawName = (item.name or "未命名"):gsub("%.zip$", "")
        local prefix = item.pinned and "📌 " or ""
        local sub = tostring(item.time or "")
        if item.today then sub = "今日 · " .. sub end

        local card = ctx.makeCard(prefix .. rawName, sub, function()
            ctx.showDetailDialog(ctx, item)
        end)
        contentLayout.addView(card)
        ctx.slideUpFadeIn(card, 240, math.min(40 + i * 30, 500))
    end
end

return function(ctx)
    local contentLayout = ctx.contentLayout
    local state = ctx.state

    if not ctx.isActivityAlive() then return end

    local catId = "ziyuan"
    state.currentCategory = catId
    state.searchQuery = nil
    state.searchResults = nil
    state.searchLoading = false

    ctx.backBtn.setVisibility(View.GONE)
    ctx.setTitleVisible(true)
    ctx.titleText.setText("资源")

    if state.dataCache[catId] then
        renderList(ctx, catId)
        return
    end

    if state.isLoading[catId] then
        ctx.recycleAllCards()
        contentLayout.removeAllViews()
        showLoading(ctx, "正在加载...")
        return
    end
    state.isLoading[catId] = true

    ctx.recycleAllCards()
    contentLayout.removeAllViews()
    showLoading(ctx, "正在加载...")

    ctx.runAsync(function()
        local ok, result = pcall(ctx.fetchListData, catId)
        ctx.postUi(function()
            state.isLoading[catId] = false
            if not ctx.isActivityAlive() then return end
            if state.currentTab ~= ctx.TAB_ZIYUAN then return end

            if ok and result then
                state.dataCache[catId] = result
                renderList(ctx, catId)
            else
                contentLayout.removeAllViews()
                showLoading(ctx, "加载失败，请检查网络或切换线路")
            end
        end)
    end)
end