-- layout/home4.lua
local showServerDialog
local showThemeDialog
local showAboutDialog

local SPONSOR_URL = "https://pay.rliyun.cn/cashier/2a98fe835d822a1ac5"

-- ==================== 服务器线路弹窗 ====================
showServerDialog = function(ctx)
    local activity = ctx.activity
    local dp = ctx.dp
    local C = ctx.getColors()
    local state = ctx.state

    if not ctx.isActivityAlive() then return end

    local dialogLayout = LinearLayout(activity)
    dialogLayout.setOrientation(LinearLayout.VERTICAL)
    dialogLayout.setPadding(dp(22), dp(22), dp(22), dp(18))
    dialogLayout.setBackground(ctx.cachedRoundedBg(C.CARD, 18))

    local title = TextView(activity)
    title.setText("选择服务器线路")
    title.setTextColor(C.TEXT)
    title.setTextSize(16)
    ctx.setTextBold(title, true)
    dialogLayout.addView(title)

    local serverDialog

    local function doSwitch(key)
        if state.SERVER_LINE == key then
            ctx.safeDismiss(serverDialog)
            return
        end
        state.SERVER_LINE = key
        ctx.writeServerPref(key)
        state.bannerData = nil
        state.noticeData = nil
        state.dataCache = {}
        state.isLoading = {}
        state.currentCategory = nil
        state.searchQuery = nil
        state.searchResults = nil

        ctx.safeDismiss(serverDialog)
        ctx.reloadCurrentTab()
        ctx.toast("已切换为：" .. ctx.getServerLabel(key))
    end

    for _, line in ipairs(ctx.SERVER_LINES) do
        local isCurrent = (state.SERVER_LINE == line.key)
        local btn = LinearLayout(activity)
        btn.setOrientation(LinearLayout.HORIZONTAL)
        btn.setGravity(Gravity.CENTER_VERTICAL)
        btn.setPadding(dp(16), dp(14), dp(16), dp(14))
        btn.setBackground(ctx.cachedRoundedBgStroke(
            isCurrent and C.ACCENT_SOFT_BG or 0x00000000,
            isCurrent and C.ACCENT_SOFT_BORDER or C.CARD_STROKE, 10, 1))
        local lp = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT)
        lp.setMargins(0, dp(10), 0, 0)
        btn.setLayoutParams(lp)

        local labelTv = TextView(activity)
        labelTv.setText(line.label)
        labelTv.setTextColor(C.TEXT)
        labelTv.setTextSize(14)
        ctx.setTextBold(labelTv, isCurrent)
        labelTv.setLayoutParams(LinearLayout.LayoutParams(0,
            LinearLayout.LayoutParams.WRAP_CONTENT, 1.0))
        btn.addView(labelTv)

        if isCurrent then
            local checkTv = TextView(activity)
            checkTv.setText("✓")
            checkTv.setTextColor(C.ACCENT)
            checkTv.setTextSize(16)
            ctx.setTextBold(checkTv, true)
            btn.addView(checkTv)
        end

        ctx.setOnClick(btn, function()
            doSwitch(line.key)
        end)
        dialogLayout.addView(btn)
    end

    local cancelBtn = TextView(activity)
    cancelBtn.setText("取消")
    cancelBtn.setTextColor(C.TEXT)
    cancelBtn.setTextSize(14)
    cancelBtn.setGravity(Gravity.CENTER)
    cancelBtn.setPadding(0, dp(12), 0, dp(12))
    cancelBtn.setBackground(ctx.cachedRoundedBgStroke(0x00000000, C.CARD_STROKE, 11, 1))
    local cLp = LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.MATCH_PARENT,
        LinearLayout.LayoutParams.WRAP_CONTENT)
    cLp.setMargins(0, dp(16), 0, 0)
    cancelBtn.setLayoutParams(cLp)
    dialogLayout.addView(cancelBtn)

    serverDialog = ctx.newDialog(dialogLayout, 40, true)
    if not serverDialog then return end
    ctx.setOnClick(cancelBtn, function()
        ctx.safeDismiss(serverDialog)
    end)
    serverDialog.show()
end

-- ==================== 主题弹窗 ====================
showThemeDialog = function(ctx)
    local activity = ctx.activity
    local dp = ctx.dp
    local C = ctx.getColors()
    local state = ctx.state

    if not ctx.isActivityAlive() then return end

    local dialogLayout = LinearLayout(activity)
    dialogLayout.setOrientation(LinearLayout.VERTICAL)
    dialogLayout.setPadding(dp(22), dp(22), dp(22), dp(18))
    dialogLayout.setBackground(ctx.cachedRoundedBg(C.CARD, 18))

    local title = TextView(activity)
    title.setText("选择主题")
    title.setTextColor(C.TEXT)
    title.setTextSize(16)
    ctx.setTextBold(title, true)
    dialogLayout.addView(title)

    local themeDialog
    local options = {
        { key = "default", label = "默认（跟随系统）" },
        { key = "light", label = "浅色" },
        { key = "dark", label = "深色" },
    }

    for _, opt in ipairs(options) do
        local isCurrent = (state.THEME_MODE == opt.key)
        local btn = LinearLayout(activity)
        btn.setOrientation(LinearLayout.HORIZONTAL)
        btn.setGravity(Gravity.CENTER_VERTICAL)
        btn.setPadding(dp(16), dp(14), dp(16), dp(14))
        btn.setBackground(ctx.cachedRoundedBgStroke(
            isCurrent and C.ACCENT_SOFT_BG or 0x00000000,
            isCurrent and C.ACCENT_SOFT_BORDER or C.CARD_STROKE, 10, 1))
        local lp = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT)
        lp.setMargins(0, dp(10), 0, 0)
        btn.setLayoutParams(lp)

        local labelTv = TextView(activity)
        labelTv.setText(opt.label)
        labelTv.setTextColor(C.TEXT)
        labelTv.setTextSize(14)
        ctx.setTextBold(labelTv, isCurrent)
        labelTv.setLayoutParams(LinearLayout.LayoutParams(0,
            LinearLayout.LayoutParams.WRAP_CONTENT, 1.0))
        btn.addView(labelTv)

        if isCurrent then
            local checkTv = TextView(activity)
            checkTv.setText("✓")
            checkTv.setTextColor(C.ACCENT)
            checkTv.setTextSize(16)
            ctx.setTextBold(checkTv, true)
            btn.addView(checkTv)
        end

        ctx.setOnClick(btn, function()
            state.THEME_MODE = opt.key
            ctx.applyThemeToUI()
            ctx.safeDismiss(themeDialog)
            ctx.reloadCurrentTab()
            ctx.toast("已切换为：" .. opt.label)
        end)
        dialogLayout.addView(btn)
    end

    local cancelBtn = TextView(activity)
    cancelBtn.setText("取消")
    cancelBtn.setTextColor(C.TEXT)
    cancelBtn.setTextSize(14)
    cancelBtn.setGravity(Gravity.CENTER)
    cancelBtn.setPadding(0, dp(12), 0, dp(12))
    cancelBtn.setBackground(ctx.cachedRoundedBgStroke(0x00000000, C.CARD_STROKE, 11, 1))
    local cLp = LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.MATCH_PARENT,
        LinearLayout.LayoutParams.WRAP_CONTENT)
    cLp.setMargins(0, dp(16), 0, 0)
    cancelBtn.setLayoutParams(cLp)
    dialogLayout.addView(cancelBtn)

    themeDialog = ctx.newDialog(dialogLayout, 40, true)
    if not themeDialog then return end
    ctx.setOnClick(cancelBtn, function()
        ctx.safeDismiss(themeDialog)
    end)
    themeDialog.show()
end

-- ==================== 关于弹窗（兜底用） ====================
showAboutDialog = function(ctx)
    local activity = ctx.activity
    local dp = ctx.dp
    local C = ctx.getColors()

    if not ctx.isActivityAlive() then return end

    local dialogLayout = LinearLayout(activity)
    dialogLayout.setOrientation(LinearLayout.VERTICAL)
    dialogLayout.setPadding(dp(22), dp(22), dp(22), dp(18))
    dialogLayout.setBackground(ctx.cachedRoundedBg(C.CARD, 18))

    local nameTv = TextView(activity)
    nameTv.setText("辉少工具箱")
    nameTv.setTextColor(C.TEXT)
    nameTv.setTextSize(18)
    ctx.setTextBold(nameTv, true)
    dialogLayout.addView(nameTv)

    local verStr = "1.2.0"
    if ctx.getAppVersionName then
        local ok, v = pcall(ctx.getAppVersionName)
        if ok and v and v ~= "" then verStr = v end
    end

    local verTv = TextView(activity)
    verTv.setText("v" .. verStr)
    verTv.setTextColor(C.TEXT_SUB)
    verTv.setTextSize(11)
    local verLp = LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.WRAP_CONTENT,
        LinearLayout.LayoutParams.WRAP_CONTENT)
    verLp.setMargins(0, dp(4), 0, dp(16))
    verTv.setLayoutParams(verLp)
    dialogLayout.addView(verTv)

    local closeBtn = TextView(activity)
    closeBtn.setText("关闭")
    closeBtn.setTextColor(C.TEXT)
    closeBtn.setTextSize(14)
    closeBtn.setGravity(Gravity.CENTER)
    closeBtn.setPadding(0, dp(12), 0, dp(12))
    closeBtn.setBackground(ctx.cachedRoundedBgStroke(0x00000000, C.CARD_STROKE, 11, 1))
    dialogLayout.addView(closeBtn)

    local dlg = ctx.newDialog(dialogLayout, 40, true)
    if not dlg then return end
    ctx.setOnClick(closeBtn, function()
        ctx.safeDismiss(dlg)
    end)
    dlg.show()
end

-- ==================== 设置页入口 ====================
return function(ctx)
    local activity = ctx.activity
    local dp = ctx.dp
    local C = ctx.getColors()
    local contentLayout = ctx.contentLayout
    local state = ctx.state

    if not ctx.isActivityAlive() then return end

    -- ★ 清空内容 + 卡片池，防止残留
    ctx.recycleAllCards()
    contentLayout.removeAllViews()

    -- ★ 进入设置页时清除子页面标记
    if state then state.subPage = nil end

    -- ★ FIX-4: 恢复默认 padding（从 home6 返回时能正确恢复）
    contentLayout.setPadding(dp(18), dp(8), dp(18), dp(120))

    ctx.backBtn.setVisibility(View.GONE)
    ctx.setTitleVisible(true)
    ctx.titleText.setText("设置")

    local function subtitle(text)
        local tv = TextView(activity)
        tv.setText(tostring(text))
        tv.setTextColor(C.TEXT_SUB)
        tv.setTextSize(11)
        tv.setPadding(dp(8), dp(14), 0, dp(6))
        contentLayout.addView(tv)
    end

    subtitle("网络")
    contentLayout.addView(ctx.makeCard("服务器线路",
        ctx.getServerLabel(),
        function()
            showServerDialog(ctx)
        end))

    subtitle("外观")
    local themeLabelMap = {
        ["default"] = "默认（跟随系统）",
        ["light"] = "浅色",
        ["dark"] = "深色",
    }
    contentLayout.addView(ctx.makeCard("主题切换",
        themeLabelMap[state.THEME_MODE] or "默认（自动）",
        function()
            showThemeDialog(ctx)
        end))

    subtitle("其他")
    contentLayout.addView(ctx.makeCard("官方网站", "访问官网了解更多",
        function()
            ctx.openExternalUrl(ctx.OFFICIAL_WEBSITE_URL)
        end))

    contentLayout.addView(ctx.makeCard("赞助支持", "微信 / 支付宝",
        function()
            ctx.openExternalUrl(SPONSOR_URL)
        end))

    subtitle("系统")
    contentLayout.addView(ctx.makeCard("检查更新",
        "当前版本 v" .. ctx.getAppVersionName(),
        function()
            ctx.checkUpdate(true)
        end))

    local aboutVer = "1.2.0"
    if ctx.getAppVersionName then
        local ok, v = pcall(ctx.getAppVersionName)
        if ok and v and v ~= "" then aboutVer = v end
    end

    contentLayout.addView(ctx.makeCard("关于软件", "v" .. aboutVer,
        function()
            if ctx.renderHome6 and state then
                ctx.recycleAllCards()
                state.subPage = "home6"
                ctx.renderHome6()
            else
                showAboutDialog(ctx)
            end
        end))

    -- ★ FIX: tag 兼容 Java String，恢复卡片入场动画
    local idx = 0
    for i = 0, contentLayout.getChildCount() - 1 do
        local v = contentLayout.getChildAt(i)
        if v then
            local tag = nil
            pcall(function() tag = tostring(v.getTag()) end)
            if tag == "card" then
                ctx.slideUpFadeIn(v, 220, 60 + idx * 40)
                idx = idx + 1
            end
        end
    end
end