local BFH = _G.BlightfallHelper
if not BFH then return end

local function PositionButton(button, angle)
    if not Minimap then return end
    local radius = 80
    local r = math.rad(angle or 225)
    button:ClearAllPoints()
    button:SetPoint("CENTER", Minimap, "CENTER", math.cos(r) * radius, math.sin(r) * radius)
end

function BFH:InitializeMinimapButton()
    if not Minimap then return end

    local b = CreateFrame("Button", "BlightfallHelperMinimapButton", Minimap, "BackdropTemplate")
    b:SetSize(32, 32)
    b:SetFrameStrata("MEDIUM")
    b:SetClampedToScreen(true)
    b:RegisterForClicks("LeftButtonUp")
    b:RegisterForDrag("LeftButton")

    b:SetBackdrop({
        bgFile = "Interface\\Buttons\\WHITE8X8",
        edgeFile = "Interface\\Buttons\\WHITE8X8",
        edgeSize = 2,
    })
    b:SetBackdropColor(0.02, 0.02, 0.025, 1)
    b:SetBackdropBorderColor(0.62, 0.11, 1, 1)

    local texture = b:CreateTexture(nil, "ARTWORK")
    texture:SetPoint("TOPLEFT", 3, -3)
    texture:SetPoint("BOTTOMRIGHT", -3, 3)
    texture:SetTexture(self:GetSpellTexture(self.SPELL.BLIGHTFALL))
    texture:SetTexCoord(0.08, 0.92, 0.08, 0.92)

    local highlight = b:CreateTexture(nil, "HIGHLIGHT")
    highlight:SetAllPoints(texture)
    highlight:SetColorTexture(1, 1, 1, 0.12)

    b:SetScript("OnEnter", function(self)
        GameTooltip:SetOwner(self, "ANCHOR_LEFT")
        GameTooltip:AddLine("BlightfallHelper", 0.78, 0.38, 1)
        GameTooltip:AddLine("Left-click: Open settings", 1, 1, 1)
        GameTooltip:AddLine("Drag: Move around the minimap", 0.72, 0.75, 0.82)
        GameTooltip:Show()
    end)

    b:SetScript("OnLeave", function() GameTooltip:Hide() end)

    b:SetScript("OnClick", function()
        BFH:ToggleConfig()
    end)

    b:SetScript("OnDragStart", function(self)
        self:SetScript("OnUpdate", function()
            local mx, my = Minimap:GetCenter()
            local scale = Minimap:GetEffectiveScale()
            local cx, cy = GetCursorPosition()
            cx, cy = cx / scale, cy / scale
            local angle = math.deg(math.atan2(cy - my, cx - mx))
            BFH.db.minimapAngle = angle
            PositionButton(self, angle)
        end)
    end)

    b:SetScript("OnDragStop", function(self)
        self:SetScript("OnUpdate", nil)
    end)

    self.minimapButton = b
    PositionButton(b, self.db.minimapAngle)
    self:UpdateMinimapButton()
end

function BFH:UpdateMinimapButton()
    if not self.minimapButton or not self.db then return end
    self.minimapButton:SetShown(self.db.showMinimapButton ~= false)
    PositionButton(self.minimapButton, self.db.minimapAngle)
end
