-- layout/home2.lua
local renderCategoryGrid
local openCategory
local renderList
local showLoading
local showLoadingInto

local activeCat = nil
local catReqGen = {}

_G.__home2_resetActiveCat = function()
    activeCat = nil
end

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

renderCategoryGrid = function(ctx)
    local activity = ctx.activity
    local dp = ctx.dp
    local C = ctx.getColors()
    local contentLayout = ctx.contentLayout

    activeCat = nil
    ctx.recycleAllCards()
    contentLayout.removeAllViews()

    local hint = TextView(activity)
    hint.setText("选择分类")
    hint.setTextColor(C.TEXT_SUB)
    hint.setTextSize(12)
    local hintLp = LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.MATCH_PARENT,
        LinearLayout.LayoutParams.WRAP_CONTENT)
    hintLp.setMargins(dp(4), 0, 0, dp(10))
    hint.setLayoutParams(hintLp)
    contentLayout.addView(hint)

    local idx = 0
    for _, cat in ipairs(ctx.CATEGORY_LIST) do
        if cat.id ~= "ziyuan" then
            idx = idx + 1
            local card = LinearLayout(activity)
            card.setOrientation(LinearLayout.HORIZONTAL)
            card.setGravity(Gravity.CENTER_VERTICAL)
            card.setBackground(ctx.cachedRoundedBgStroke(C.CARD, C.CARD_STROKE, 14, 1))
            card.setPadding(dp(20), dp(18), dp(16), dp(18))
            local lp = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT)
            lp.setMargins(0, 0, 0, dp(10))
            card.setLayoutParams(lp)

            local titleTv = TextView(activity)
            titleTv.setText(cat.name)
            titleTv.setTextColor(C.TEXT)
            titleTv.setTextSize(16)
            titleTv.setLayoutParams(LinearLayout.LayoutParams(0,
                LinearLayout.LayoutParams.WRAP_CONTENT, 1.0))
            titleTv.setMaxLines(1); titleTv.setSingleLine(true)
            titleTv.setEllipsize(TextUtils.TruncateAt.END)
            card.addView(titleTv)

            local arrowTv = TextView(activity)
            arrowTv.setText("›")
            arrowTv.setTextSize(22)
            arrowTv.setTextColor(C.TEXT_SUB)
            card.addView(arrowTv)

            ctx.setOnClick(card, function()
                openCategory(ctx, cat.id, cat.name, true)
            end)

            contentLayout.addView(card)
            ctx.slideUpFadeIn(card, 240, idx * 40)
        end
    end
end

openCategory = function(ctx, catId, catName, showBack)
    local contentLayout = ctx.contentLayout
    local state = ctx.state

    if not ctx.isActivityAlive() then return end
    if showBack == nil then showBack = true end

    activeCat = catId
    state.searchQuery = nil
    state.searchResults = nil
    state.searchLoading = false

    ctx.backBtn.setVisibility(showBack and View.VISIBLE or View.GONE)
    ctx.setTitleVisible(true)
    ctx.titleText.setText(catName or ctx.findCatName(catId) or "列表")

    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
    catReqGen[catId] = (catReqGen[catId] or 0) + 1
    local myGen = catReqGen[catId]

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

    ctx.runAsync(function()
        local ok, result = pcall(ctx.fetchListData, catId)
        ctx.postUi(function()
            if catReqGen[catId] ~= myGen then return end
            state.isLoading[catId] = false
            if not ctx.isActivityAlive() then return end
            if ok and result then
                state.dataCache[catId] = result
                if activeCat == catId
                    and state.currentTab == ctx.TAB_FILES then
                    renderList(ctx, catId)
                end
            else
                if activeCat == catId
                    and state.currentTab == ctx.TAB_FILES then
                    contentLayout.removeAllViews()
                    showLoading(ctx, "加载失败，请检查网络或切换线路")
                end
            end
        end)
    end)
end

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

    local items = state.dataCache[catId]
    if not ctx.isActivityAlive() then return end
    if not contentLayout then return end

    ctx.recycleAllCards()
    contentLayout.removeAllViews()

    local catName = ctx.findCatName(catId)
    if catName ~= "" then
        local sec = ctx.makeSectionTitle(catName .. " · 全部")
        contentLayout.addView(sec)
        ctx.fadeInView(sec, 220, 0)
    end

    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)
    if not ctx.isActivityAlive() then return end

    if activeCat == nil then
        renderCategoryGrid(ctx)
    else
        renderList(ctx, activeCat)
    end
end