local PT = AhUI
if not PT then return end

PT.FarmTracker = PT.FarmTracker or {}
local FT = PT.FarmTracker
local L = PT.L or {}

FT.Data   = FT.Data   or {}
FT.Events = FT.Events or {}
FT.Prices = FT.Prices or {}
FT.UI     = FT.UI     or {}

local function PrintMsg(msg)
    if DEFAULT_CHAT_FRAME and DEFAULT_CHAT_FRAME.AddMessage then
        DEFAULT_CHAT_FRAME:AddMessage("|cff33ccffAhUI|r |cff88ff88FarmTracker:|r " .. tostring(msg or ""))
    end
end

FT.Print = PrintMsg

function FT:GetCurrentCharKey()
    local name = UnitName("player")
    local realm = GetNormalizedRealmName() or GetRealmName() or ""
    if not name then return nil end
    return name .. "-" .. realm
end

function FT:GetCurrentZoneInfo()
    local mapID = C_Map.GetBestMapForUnit("player")
    local zone = GetRealZoneText()
    if mapID then
        local info = C_Map.GetMapInfo(mapID)
        if info and info.name and info.name ~= "" then
            zone = info.name
        end
    end
    return zone or UNKNOWN, mapID
end

function FT:RefreshUI(immediate)
    if not FT.UI or not FT.UI.Refresh then return end

    if immediate then
        FT._refreshToken = (FT._refreshToken or 0) + 1
        FT._refreshQueued = false
        FT.UI:Refresh()
        return
    end

    if FT._refreshQueued then return end
    FT._refreshQueued = true
    FT._refreshToken = (FT._refreshToken or 0) + 1
    local token = FT._refreshToken

    C_Timer.After(0.08, function()
        if token ~= FT._refreshToken then return end
        FT._refreshQueued = false

        if FT.UI and FT.UI.Refresh then
            FT.UI:Refresh()
        end
    end)
end

function FT:Open()
    if FT.UI and FT.UI.Show then
        FT.UI:Show()
    end
end

function FT:Close()
    if FT.UI and FT.UI.Hide then
        FT.UI:Hide()
    end
end

function FT:ToggleVisibility()
    if FT.UI and FT.UI.ToggleVisibility then
        FT.UI:ToggleVisibility()
    end
end

function FT:Toggle()
    if FT.UI and FT.UI.Toggle then
        FT.UI:Toggle()
    end
end

function FT:GetPriceSource()
    local db = FT.Data:GetDB()
    return db and db.config and db.config.priceSource or "AUCTIONATOR"
end

function FT:GetItemPrice(itemID, itemLink)
    if FT.Prices and FT.Prices.GetItemPrice then
        return FT.Prices:GetItemPrice(itemID, itemLink)
    end
    return 0, "VENDOR"
end

function FT:IsEnabled()
    return FT.Data and FT.Data.IsEnabled and FT.Data:IsEnabled() or false
end

function FT:ApplyEnabledState()
    local cdb = FT.Data:GetCharDB()

    if self:IsEnabled() then
        cdb.ui.collapsed = true

        if FT.UI and FT.UI.Show then
            FT.UI:Show()
        end
    else
        if FT.UI and FT.UI.Hide then
            FT.UI:Hide(true)
        end
    end
end

function FT:InitSlash()
    local old = SlashCmdList["AHUI"]
    SlashCmdList["AHUI"] = function(msg)
        local text = tostring(msg or "")
        local cmd, rest = text:match("^(%S+)%s*(.-)$")
        cmd = cmd and cmd:lower() or ""

        if cmd == "farm" or cmd == "ft" then
            local sub = (rest or ""):lower()
            if sub == "" then
                FT:Toggle()
                return
            elseif sub == "start" then
                FT:StartSession()
                return
            elseif sub == "pause" then
                FT:PauseSession()
                return
            elseif sub == "resume" then
                FT:ResumeSession()
                return
            elseif sub == "stop" then
                FT:StopSession()
                return
            elseif sub == "reset" then
                FT:ResetSession()
                return
            elseif sub == "history" then
                FT:Open()
                if FT.UI and FT.UI.ShowTab then
                    FT.UI:ShowTab("history")
                end
                return
            end
        end

        if old then
            old(msg)
        elseif PT.Settings and PT.Settings.category then
            Settings.OpenToCategory(PT.Settings.category:GetID())
        end
    end
end

function FT:Init()
    if FT._initialized then return end
    FT._initialized = true

    if FT.Data and FT.Data.Init then
        FT.Data:Init()
    end

    if FT.Prices and FT.Prices.Init then
        FT.Prices:Init()
    end

    if FT.UI and FT.UI.Create then
        FT.UI:Create()
    end

    if FT.Events and FT.Events.Register then
        FT.Events:Register()
        if FT.Events.OnLogin then
            FT.Events:OnLogin()
        end
    end

    FT:InitSlash()
    FT:ApplyEnabledState()
end

local ev = CreateFrame("Frame")
ev:RegisterEvent("PLAYER_LOGIN")
ev:SetScript("OnEvent", function()
    FT:Init()
end)
