local PT = AhUI
if not PT then return end

local L = PT.L or {}
local UI = PT.Settings
if not UI then return end

local panel = CreateFrame("Frame", "AhUIFarmTrackerSettingsPanel", UIParent)
panel:SetSize(700, 520)

local title = panel:CreateFontString(nil, "OVERLAY", "GameFontHighlightLarge")
title:SetPoint("TOPLEFT", 16, -16)
title:SetText(L["FT_SettingsTitle"] or "AhUI — Farm Tracker")

local function MakeCheck(anchor, offsetY, text, getter, setter)
    local cb = CreateFrame("CheckButton", nil, panel, "UICheckButtonTemplate")
    cb:SetPoint("TOPLEFT", anchor, "BOTTOMLEFT", 0, offsetY)
    cb.text:SetText(text)
    cb.GetValue = getter
    cb:SetChecked(getter())
    cb:SetScript("OnClick", function(self)
        setter(self:GetChecked() == true)
        cb:SetChecked(getter())

        if PT.FarmTracker and PT.FarmTracker.RefreshUI then
            PT.FarmTracker:RefreshUI()
        end

        if PT.WelcomeUI and PT.WelcomeUI.Refresh then
            PT.WelcomeUI:Refresh()
        end
    end)
    return cb
end

local function MakeSection(anchor, offsetY, text)
    local fs = panel:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
    fs:SetPoint("TOPLEFT", anchor, "BOTTOMLEFT", 0, offsetY)
    fs:SetText(text)
    return fs
end

local db = function() return PT.FarmTracker and PT.FarmTracker.Data and PT.FarmTracker.Data:GetDB() end
local cdb = function() return PT.FarmTracker and PT.FarmTracker.Data and PT.FarmTracker.Data:GetCharDB() end

local general = MakeSection(title, -20, L["FT_SettingsGeneral"] or "General")
local cbEnable = MakeCheck(general, -8, L["FT_EnableModule"] or "Enable module",
    function() return db().config.enabled == true end,
    function(v)
        db().config.enabled = (v == true)

        if PT.FarmTracker and PT.FarmTracker.ApplyEnabledState then
            PT.FarmTracker:ApplyEnabledState()
        elseif PT.FarmTracker and PT.FarmTracker.RefreshUI then
            PT.FarmTracker:RefreshUI()
        end
    end)

local cbAuto = MakeCheck(cbEnable, -10, L["FT_AutoStartOnLoot"] or "Auto start on first loot",
    function() return db().config.autoStartOnLoot == true end,
    function(v) db().config.autoStartOnLoot = v end)

local cbResume = MakeCheck(cbAuto, -10, L["FT_ResumeOnLogin"] or "Resume unfinished session on login",
    function() return db().config.resumeUnfinishedSession ~= false end,
    function(v) db().config.resumeUnfinishedSession = v end)
local sourcesSec = MakeSection(cbResume, -26, L["FT_SettingsSources"] or "Tracked sources")

local cbSourceLoot = MakeCheck(sourcesSec, -8, L["FT_SourceLoot"] or "Loot",
    function() return db().config.sources and db().config.sources.loot ~= false end,
    function(v) db().config.sources.loot = v end)

local cbSourceCrafting = MakeCheck(cbSourceLoot, -10, L["FT_SourceCrafting"] or "Crafting",
    function() return db().config.sources and db().config.sources.crafting ~= false end,
    function(v) db().config.sources.crafting = v end)

local cbSourceMoney = MakeCheck(cbSourceCrafting, -10, L["FT_SourceMoney"] or "Money",
    function() return db().config.sources and db().config.sources.money ~= false end,
    function(v) db().config.sources.money = v end)

local cbSourceMailItems = MakeCheck(cbSourceMoney, -10, L["FT_SourceMailItems"] or "Mail items",
    function() return db().config.sources and db().config.sources.mailItems == true end,
    function(v) db().config.sources.mailItems = v end)

local cbSourceMailMoney = MakeCheck(cbSourceMailItems, -10, L["FT_SourceMailMoney"] or "Mail money",
    function() return db().config.sources and db().config.sources.mailMoney == true end,
    function(v) db().config.sources.mailMoney = v end)

local qualitySec = MakeSection(cbSourceMailMoney, -26, L["FT_SettingsQualityFilter"] or "Item quality filter")

local function MakeCheckPoint(anchor, point, relPoint, x, y, text, getter, setter)
    local cb = CreateFrame("CheckButton", nil, panel, "UICheckButtonTemplate")
    cb:SetPoint(point, anchor, relPoint, x, y)
    cb.text:SetText(text)
    cb.GetValue = getter
    cb:SetChecked(getter())
    cb:SetScript("OnClick", function(self)
        setter(self:GetChecked() == true)
        cb:SetChecked(getter())

        if PT.FarmTracker and PT.FarmTracker.RefreshUI then
            PT.FarmTracker:RefreshUI()
        end

        if PT.WelcomeUI and PT.WelcomeUI.Refresh then
            PT.WelcomeUI:Refresh()
        end
    end)
    return cb
end

local cbQualityPoor = MakeCheckPoint(
    qualitySec, "TOPLEFT", "BOTTOMLEFT", 0, -8,
    L["FT_QualityPoor"] or "Poor",
    function() return db().config.qualityFilter and db().config.qualityFilter[0] ~= false end,
    function(v) db().config.qualityFilter[0] = v end
)

local cbQualityCommon = MakeCheckPoint(
    cbQualityPoor, "TOPLEFT", "BOTTOMLEFT", 0, -10,
    L["FT_QualityCommon"] or "Common",
    function() return db().config.qualityFilter and db().config.qualityFilter[1] ~= false end,
    function(v) db().config.qualityFilter[1] = v end
)

local cbQualityUncommon = MakeCheckPoint(
    cbQualityCommon, "TOPLEFT", "BOTTOMLEFT", 0, -10,
    L["FT_QualityUncommon"] or "Uncommon",
    function() return db().config.qualityFilter and db().config.qualityFilter[2] ~= false end,
    function(v) db().config.qualityFilter[2] = v end
)

local cbQualityRare = MakeCheckPoint(
    cbQualityPoor, "TOPLEFT", "TOPRIGHT", 100, 0,
    L["FT_QualityRare"] or "Rare",
    function() return db().config.qualityFilter and db().config.qualityFilter[3] ~= false end,
    function(v) db().config.qualityFilter[3] = v end
)

local cbQualityEpic = MakeCheckPoint(
    cbQualityRare, "TOPLEFT", "BOTTOMLEFT", 0, -10,
    L["FT_QualityEpic"] or "Epic",
    function() return db().config.qualityFilter and db().config.qualityFilter[4] ~= false end,
    function(v) db().config.qualityFilter[4] = v end
)

local cbQualityLegendary = MakeCheckPoint(
    cbQualityEpic, "TOPLEFT", "BOTTOMLEFT", 0, -10,
    L["FT_QualityLegendary"] or "Legendary",
    function() return db().config.qualityFilter and db().config.qualityFilter[5] ~= false end,
    function(v) db().config.qualityFilter[5] = v end
)

local pricing = panel:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
pricing:SetPoint("TOPLEFT", general, "TOPRIGHT", 240, 0)
pricing:SetText(L["FT_SettingsPricing"] or "Pricing")

local priceLabel = panel:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
priceLabel:SetPoint("TOPLEFT", pricing, "BOTTOMLEFT", 0, -10)
priceLabel:SetText(L["FT_PriceSource"] or "Price source")

local dd = CreateFrame("Frame", "AhUIFarmTrackerPriceDropdown", panel, "UIDropDownMenuTemplate")
dd:SetPoint("TOPLEFT", priceLabel, "BOTTOMLEFT", -16, -2)
UIDropDownMenu_SetWidth(dd, 180)

local function RefreshDropdown()
    local current = db().config.priceSource or "AUCTIONATOR"
    local names = {
        AUTO = "Auto",
        AUCTIONATOR = "Auctionator",
        TSM = "TSM",
        VENDOR = "Vendor",
    }
    UIDropDownMenu_SetText(dd, names[current] or current)
end

UIDropDownMenu_Initialize(dd, function(self, level)
    local info = UIDropDownMenu_CreateInfo()
    local entries = {
        { value = "AUCTIONATOR", text = "Auctionator" },
        { value = "TSM", text = "TSM" },
        { value = "VENDOR", text = "Vendor" },
        { value = "AUTO", text = "Auto" },
    }
    for _, entry in ipairs(entries) do
        info.text = entry.text
        info.checked = db().config.priceSource == entry.value
        info.func = function()
            db().config.priceSource = entry.value
            RefreshDropdown()

            if PT.FarmTracker then
                PT.FarmTracker:RecalculateSessionTotals()
                PT.FarmTracker:RefreshUI()
            end

            if PT.WelcomeUI and PT.WelcomeUI.Refresh then
                PT.WelcomeUI:Refresh()
            end
        end
        UIDropDownMenu_AddButton(info, level)
    end
end)

RefreshDropdown()

local cbFallback = MakeCheck(priceLabel, -54, L["FT_UseFallback"] or "Use fallback automatically",
    function() return db().config.autoFallback ~= false end,
    function(v) db().config.autoFallback = v end)

local cbVendor = MakeCheck(cbFallback, -10, L["FT_UseVendorFallback"] or "Use vendor fallback",
    function() return db().config.includeVendorFallback ~= false end,
    function(v) db().config.includeVendorFallback = v end)

local history = MakeSection(cbVendor, -26, L["FT_SettingsHistory"] or "History")

local maxLabel = panel:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
maxLabel:SetPoint("TOPLEFT", history, "BOTTOMLEFT", 0, -10)
maxLabel:SetText(L["FT_MaxHistory"] or "Max stored sessions")

local maxBox = CreateFrame("EditBox", nil, panel, "InputBoxTemplate")
maxBox:SetSize(60, 24)
maxBox:SetAutoFocus(false)
maxBox:SetPoint("LEFT", maxLabel, "RIGHT", 12, 0)
maxBox:SetNumeric(true)
maxBox:SetText(tostring(db().config.maxHistory or 100))
maxBox:SetScript("OnEnterPressed", function(self)
    local v = tonumber(self:GetText()) or 100
    if v < 1 then v = 1 end
    if v > 500 then v = 500 end
    db().config.maxHistory = v
    self:SetText(v)
    if PT.FarmTracker and PT.FarmTracker.Data then
        PT.FarmTracker.Data:TrimHistory()
        PT.FarmTracker:RefreshUI()
    end
    self:ClearFocus()
end)

local uiSec = MakeSection(maxLabel, -28, L["FT_SettingsUI"] or "UI")
local cbShift = MakeCheck(uiSec, -8, L["FT_MinimapShift"] or "Shift + Left Click on minimap icon opens Farm Tracker",
    function() return db().config.minimapShiftOpen ~= false end,
    function(v) db().config.minimapShiftOpen = v end)

local cbDefaultFilter = MakeCheck(cbShift, -10, L["FT_DefaultHistoryCurrent"] or "Default history filter: current character",
    function() return db().config.defaultHistoryFilter ~= "all" end,
    function(v)
        db().config.defaultHistoryFilter = v and "current" or "all"
        cdb().ui.historyFilter = db().config.defaultHistoryFilter

        if PT.FarmTracker and PT.FarmTracker.RefreshUI then
            PT.FarmTracker:RefreshUI()
        end
    end)

local function RefreshUI()
    local d = db()
    local cd = cdb()
    if not d or not d.config or not cd or not cd.ui then return end

    cbEnable:SetChecked(d.config.enabled == true)
    cbAuto:SetChecked(d.config.autoStartOnLoot == true)
    cbResume:SetChecked(d.config.resumeUnfinishedSession ~= false)
    cbSourceLoot:SetChecked(d.config.sources and d.config.sources.loot ~= false)
    cbSourceCrafting:SetChecked(d.config.sources and d.config.sources.crafting ~= false)
    cbSourceMoney:SetChecked(d.config.sources and d.config.sources.money ~= false)
    cbSourceMailItems:SetChecked(d.config.sources and d.config.sources.mailItems == true)
    cbSourceMailMoney:SetChecked(d.config.sources and d.config.sources.mailMoney == true)
    cbQualityPoor:SetChecked(d.config.qualityFilter and d.config.qualityFilter[0] ~= false)
    cbQualityCommon:SetChecked(d.config.qualityFilter and d.config.qualityFilter[1] ~= false)
    cbQualityUncommon:SetChecked(d.config.qualityFilter and d.config.qualityFilter[2] ~= false)
    cbQualityRare:SetChecked(d.config.qualityFilter and d.config.qualityFilter[3] ~= false)
    cbQualityEpic:SetChecked(d.config.qualityFilter and d.config.qualityFilter[4] ~= false)
    cbQualityLegendary:SetChecked(d.config.qualityFilter and d.config.qualityFilter[5] ~= false)
    cbFallback:SetChecked(d.config.autoFallback ~= false)
    cbVendor:SetChecked(d.config.includeVendorFallback ~= false)
    cbShift:SetChecked(d.config.minimapShiftOpen ~= false)
    cbDefaultFilter:SetChecked(d.config.defaultHistoryFilter ~= "all")
    maxBox:SetText(tostring(d.config.maxHistory or 100))
    RefreshDropdown()
end

function UI:RegisterFarmTrackerSubcategory()
    if self.farmTrackerSubcategory then return end
    if not self.category then return end

    local sub = Settings.RegisterCanvasLayoutSubcategory(
        self.category,
        panel,
        L["FT_Title"] or "Farm Tracker"
    )

    if sub and sub.SetOnRefresh then
        sub:SetOnRefresh(RefreshUI)
    else
        sub.OnRefresh = RefreshUI
    end

    self.farmTrackerSubcategory = sub
    RefreshUI()
end
