local addonName, FN = ...

FavoriteNeighborhood = FavoriteNeighborhood or {}
FN = FN or FavoriteNeighborhood
FavoriteNeighborhood = FN

local L = FN.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

FN.TEX_MINIMAP = "Interface\\AddOns\\FavoriteNeighborhood\\Images\\Minimap\\FavoriteNeighborhoodIcon.tga"

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

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

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

    FN_DB.minimap.showInCompartment = false
    return FN_DB.minimap
end

local launcher = LDB:NewDataObject(addonName, {
    type = "launcher",
    text = L["Favorite Neighborhood"],
    icon = FN.TEX_MINIMAP,

    OnClick = function(_, button)
        if button == "LeftButton" then
            if FN.ToggleOptionsFrame then
                FN.ToggleOptionsFrame()
            elseif FavoriteNeighborhood and FavoriteNeighborhood.ToggleOptionsFrame then
                FavoriteNeighborhood.ToggleOptionsFrame()
            elseif SlashCmdList and SlashCmdList["FAVORITENEIGHBORHOOD"] then
                SlashCmdList["FAVORITENEIGHBORHOOD"]("")
            elseif FN.Msg then
                FN.Msg("toggle function not ready.")
            else
                DEFAULT_CHAT_FRAME:AddMessage("|cff00ff98FavoriteNeighborhood:|r " .. L["toggle function not ready."])
            end
        end
    end,

    OnTooltipShow = function(tt)
        if not tt then return end
        tt:AddLine(L["Favorite Neighborhood"], 1, 1, 0)
        tt:AddLine("Left Click: Open/close options", 0.7, 0.7, 0.7)
    end,
})

local function RegisterMinimapIcon()
    local minimapDB = EnsureMinimapDB()

    launcher.icon = FN.TEX_MINIMAP
    launcher.text = L["Favorite Neighborhood"]
    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)
