local addonName, LRH = ...

LRH = LRH or {}
local L = LRH.L or {}

local LibStub = _G.LibStub
if not LibStub then return end

local LDB = LibStub:GetLibrary("LibDataBroker-1.1", true)
local DBIcon = LibStub:GetLibrary("LibDBIcon-1.0", true)
if not LDB or not DBIcon then return end

local function EnsureMinimapDB()
    LeftRightDB = LeftRightDB or {}
    LeftRightDB.minimap = LeftRightDB.minimap or {}

    if LeftRightDB.minimap.hide == nil then
        LeftRightDB.minimap.hide = false
    end

    if LeftRightDB.minimap.minimapPos == nil then
        LeftRightDB.minimap.minimapPos = 220
    end

    LeftRightDB.minimap.showInCompartment = false

    return LeftRightDB.minimap
end

local launcher = LDB:NewDataObject(addonName, {
    type = "launcher",
    text = L.ADDON_NAME or "Left Right Helper",
    icon = LRH.TEX_MINIMAP,

    OnClick = function(_, button)
        LeftRightDB = LeftRightDB or {}

        if button == "LeftButton" then
            if LRH.SetDragMode then
                LRH:SetDragMode(not (LeftRightDB.dragEnabled == true))
            end
        elseif button == "RightButton" then
            LeftRightDB.enabled = (LeftRightDB.enabled ~= false)
            LeftRightDB.enabled = not LeftRightDB.enabled

            if LRH.UpdateVisibility then
                LRH:UpdateVisibility()
            end

            print(
                "|cFFFFFF00"
                .. (L.ADDON_NAME or "Left Right Helper")
                .. ": "
                .. (LeftRightDB.enabled and (L.SHOWN or "shown") or (L.HIDDEN or "hidden"))
                .. "|r"
            )
        end
    end,

    OnTooltipShow = function(tt)
        if not tt then return end

        tt:AddLine(L.ADDON_NAME or "Left Right Helper", 1, 1, 0)
        tt:AddLine(L.MINIMAP_LEFT or "Left Click: Toggle drag mode", 0.7, 0.7, 0.7)
        tt:AddLine(L.MINIMAP_RIGHT or "Right Click: Show/Hide addon", 0.7, 0.7, 0.7)
    end,
})

local function RegisterMinimapIcon()
    local minimapDB = EnsureMinimapDB()

    launcher.icon = LRH.TEX_MINIMAP
    launcher.text = L.ADDON_NAME or "Left Right Helper"
    minimapDB.showInCompartment = false

    if not DBIcon:IsRegistered(addonName) then
        DBIcon:Register(addonName, launcher, minimapDB)
    end

    if DBIcon.RemoveButtonFromCompartment then
        DBIcon:RemoveButtonFromCompartment(addonName)
    end

    if minimapDB.hide then
        DBIcon:Hide(addonName)
    else
        DBIcon:Show(addonName)
    end
end

local f = CreateFrame("Frame")
f:RegisterEvent("PLAYER_LOGIN")
f:SetScript("OnEvent", function(_, event)
    if event == "PLAYER_LOGIN" then
        RegisterMinimapIcon()
    end
end)
