local GC = select(2, ...)

local MinimapIcon = {}
GC.MinimapIcon = MinimapIcon

-- Wow APIs
local IsShiftKeyDown, SecondsToTime, time, pairs = IsShiftKeyDown,
                                                   SecondsToTime, time, pairs

local private = {}

--[[------------------------------------------------------------------------
    Tooltip drawing (shared between minimap icon and addon compartment)
--------------------------------------------------------------------------]]
local function tooltip_draw(isAddonCompartment, blizzardTooltip)
    local tooltip
    if isAddonCompartment then
        tooltip = blizzardTooltip
    else
        tooltip = GameTooltip
    end

    tooltip:AddDoubleLine(GC.CONST.METADATA.NAME, GC.CONST.METADATA.VERSION)
    tooltip:AddLine(" ")
    tooltip:AddLine("|cffff8040Left-Click|r to open the main window")
    tooltip:AddLine("|cffff8040Right-Click|r to open options window")
    tooltip:Show()
end

GC.GenerateTooltip = tooltip_draw

--[[------------------------------------------------------------------------
    Handle click actions (shared between all icon sources)
--------------------------------------------------------------------------]]
function private.HandleLeftClick()
    GC.Debug.Log("MinimapIcon: LeftClick - Toggle UI")
    if GC.UI and GC.UI.ToggleMainWindow then
        GC.UI.ToggleMainWindow()
    end
end

function private.HandleRightClick()
    GC.Debug.Log("MinimapIcon: RightClick - Open Options")
    local isShiftKeyDown = IsShiftKeyDown()
    if isShiftKeyDown then
        local callback = private.GetModuleCallback("RightButton", "Shift")
        if callback then callback() end
    else
        local category = GC.settingsCategoryID
        local categoryID = category and (type(category) == "table" and category.name or category) or GC.CONST.METADATA.NAME
        GC.Debug.Log("MinimapIcon: Opening category: " .. tostring(categoryID))
        
        if Settings and Settings.OpenToCategory then
            Settings.OpenToCategory(categoryID)
        else
            -- Classic / Older API fallback
            InterfaceOptionsFrame_OpenToCategory(categoryID)
        end
    end
end

function private.HandleClick(button)
    if button == "LeftButton" then
        private.HandleLeftClick()
    elseif button == "RightButton" then
        private.HandleRightClick()
    end
end

--[[------------------------------------------------------------------------
    Get module callback for icon actions
--------------------------------------------------------------------------]]
function private.GetModuleCallback(button, modifier)
    local modules = GC.GetModules()
    if not modules then return end

    for _, module in pairs(modules) do
        if module.icon and module.icon.action then
            for _, action in pairs(module.icon.action) do
                if action.button == button and action.modifier == modifier then
                    return action.callback
                end
            end
        end
    end
end

--[[------------------------------------------------------------------------
    DataBroker: "LootedItemValue" data source (for ElvUI support / datatexts)
--------------------------------------------------------------------------]]
function MinimapIcon.SetupDataBroker()
    local ldb = LibStub("LibDataBroker-1.1")

    ldb:NewDataObject("LootedItemValue", {
        type = "data source",
        text = "0g",
        label = "Looted Item Value",

        OnClick = function(self, button, _down)
            private.HandleClick(button)
        end
    })

    -- Periodic update frame for data text
    local UPDATEPERIOD, elapsed = 1, 0
    local f = CreateFrame("Frame")
    f:SetScript("OnUpdate", function(self, elap)
        elapsed = elapsed + elap
        if elapsed < UPDATEPERIOD then return end
        elapsed = 0

        local lootedItemValue = 0
        local currentSession = GC.Session.GetCurrentSession()
        if currentSession ~= nil then
            lootedItemValue = currentSession["liv"] or 0
        end

        -- Update the data object text
        local dataobj = ldb:GetDataObjectByName("LootedItemValue")
        if dataobj then
            dataobj.text = GC.Util.MoneyToString(lootedItemValue)
        end
    end)
end

--[[------------------------------------------------------------------------
    Minimap icon setup (LibDBIcon)
--------------------------------------------------------------------------]]
function MinimapIcon.SetupMinimapIcon()
    GC.icon = LibStub("LibDBIcon-1.0")
    GC.LibDataBroker = LibStub("LibDataBroker-1.1"):NewDataObject(GC.CONST
                                                                      .METADATA
                                                                      .NAME, {
        type = "launcher",
        text = GC.CONST.METADATA.NAME,
        icon = "Interface\\AddOns\\GallywixCoins\\Media\\logo.tga",

        OnClick = function(self, button, _down)
            private.HandleClick(button)
        end,

        OnTooltipShow = function(tooltip)
            tooltip:SetText("|TInterface\\AddOns\\GallywixCoins\\Media\\logo.tga:16:16:0:0|t |cffffd100GallywixCoins|r")
            tooltip:AddLine("Track your wealth like a Trade Prince.\nTime is money, friend!", 1, 0.82, 0)
            tooltip:AddLine(" ")
            tooltip:AddLine("|cFFCFCFCFLeft-Click:|r Toggle Main Window", 1, 1, 1)
            tooltip:AddLine("|cFFCFCFCFRight-Click:|r Open Options Menu", 1, 1, 1)
            tooltip:AddLine("|cFFCFCFCFDrag:|r Move this button", 1, 1, 1)
            tooltip:AddLine(" ")

            if GC.Session.IsRunning() then
                local offset = GC.Session.GetPauseStart() or time()
                local delta = offset - GC.Session.GetCurrentSession("start") -
                                  GC.Session.GetSessionPause()

                local noSeconds = delta > 3600

                local text = "Session is "
                if GC.Session.IsPaused() then
                    text = text .. "paused: "
                else
                    text = text .. "running: "
                end

                tooltip:AddDoubleLine(text,
                                      SecondsToTime(delta, noSeconds, false))
            else
                tooltip:AddLine("Session is not running")
            end

            -- Module tooltip lines
            local modules = GC.GetModules()
            if modules then
                for _, module in pairs(modules) do
                    if module.icon and module.icon.tooltip then
                        tooltip:AddLine(" ")
                        for _, line in pairs(module.icon.tooltip) do
                            tooltip:AddLine(line)
                        end
                    end
                end
            end
        end
    })

    GC.icon:Register(GC.CONST.METADATA.NAME, GC.LibDataBroker,
                     GC.db.profile.minimapIcon)

    if GC.db.profile.minimapIcon.hide == true then
        GC.icon:Show(GC.CONST.METADATA.NAME)
    else
        GC.icon:Hide(GC.CONST.METADATA.NAME)
    end
end

--[[------------------------------------------------------------------------
    Addon Compartment (retail 10.x+)
--------------------------------------------------------------------------]]
function MinimapIcon.SetupAddonCompartment()
    if not GC.Util.IsModern then return end

    AddonCompartmentFrame:RegisterAddon({
        text = GC.CONST.METADATA.NAME,
        icon = "Interface\\Icons\\inv_scroll_11",
        registerForAnyClick = true,
        notCheckable = true,
        func = function(_button, menuInputData, _menu)
            private.HandleClick(menuInputData.buttonName)
        end,
        funcOnEnter = function(button)
            MenuUtil.ShowTooltip(button, function(tooltip)
                GC.GenerateTooltip(true, tooltip)
            end)
        end,
        funcOnLeave = function(button) MenuUtil.HideTooltip(button) end
    })
end

