-------------------------
-- AiB Minimap Button (Hybrid Snap/Free-Form System)
-- MUST load EARLY for button collectors to detect!
-------------------------

-- Initialize Settings early
AiB_Settings = AiB_Settings or {}

-- Migrate from old angle-only format or initialize defaults
local function InitMinimapDB()
    -- Migrate: if old angle-based data exists, convert to x,y
    if AiB_Settings.minimap_position and not AiB_Settings.minimap_x then
        local angle = AiB_Settings.minimap_position
        local radius = 80
        AiB_Settings.minimap_x = math.cos(angle) * radius
        AiB_Settings.minimap_y = math.sin(angle) * radius
        AiB_Settings.minimap_position = nil  -- Remove old format
    end
    
    -- Default position: bottom-left of minimap (equivalent to old -0.5 radians)
    if not AiB_Settings.minimap_x then
        local angle = -0.5  -- Old default
        local radius = 80
        AiB_Settings.minimap_x = math.cos(angle) * radius
        AiB_Settings.minimap_y = math.sin(angle) * radius
    end
end

-- Update button position based on saved x,y offset
local function UpdateMinimapPosition()
    if not AiBMinimapButton then return end
    local x = AiB_Settings.minimap_x or 0
    local y = AiB_Settings.minimap_y or 0
    AiBMinimapButton:ClearAllPoints()
    AiBMinimapButton:SetPoint("CENTER", Minimap, "CENTER", x, y)
end

-- Create Minimap Button EARLY
local function CreateMinimapButton()
    -- Don't create if hidden
    if AiB_Settings.minimap_button_enabled == false then
        return
    end
    
    -- Don't create twice
    if AiBMinimapButton then
        UpdateMinimapPosition()
        return
    end
    
    AiBMinimapButton = CreateFrame("Button", "AiBMinimapButton", Minimap)
    AiBMinimapButton:SetSize(32, 32)
    AiBMinimapButton:SetFrameStrata("MEDIUM")
    AiBMinimapButton:SetFrameLevel(8)
    AiBMinimapButton:SetHighlightTexture("Interface\\Minimap\\UI-Minimap-ZoomButton-Highlight")
    AiBMinimapButton:SetMovable(true)
    AiBMinimapButton:EnableMouse(true)
    AiBMinimapButton:SetClampedToScreen(true)
    
    -- Addon Metadata für Minimap-Button-Sammler (z.B. MBB, Bazooka, SexyMap)
    AiBMinimapButton.IsMinimapButton = true
    AiBMinimapButton.icon = "Interface\\AddOns\\aib\\textures\\aib_icon.tga"
    AiBMinimapButton.tooltip = "AiB - All into Boss"
    AiBMinimapButton.tooltipText = "AiB - All into Boss"
    AiBMinimapButton.name = "AiB"
    
    -- Icon
    local icon = AiBMinimapButton:CreateTexture(nil, "BACKGROUND")
    icon:SetSize(20, 20)
    icon:SetPoint("CENTER", 0, 1)
    icon:SetTexture("Interface\\AddOns\\aib\\textures\\aib_icon.tga")
    
    -- Border
    local overlay = AiBMinimapButton:CreateTexture(nil, "OVERLAY")
    overlay:SetSize(53, 53)
    overlay:SetTexture("Interface\\Minimap\\MiniMap-TrackingBorder")
    overlay:SetPoint("TOPLEFT")
    
    -- Tooltip (simplified - will be enhanced later by main addon)
    AiBMinimapButton:SetScript("OnEnter", function(self)
        GameTooltip:SetOwner(self, "ANCHOR_LEFT")
        GameTooltip:AddLine("|cFFFF0000AiB|r - All into Boss", 1, 1, 1)
        GameTooltip:AddLine("Links-Klick: Öffnen", 0.8, 0.8, 0.8)
        GameTooltip:AddLine("Rechts-Klick: Settings", 0.8, 0.8, 0.8)
        GameTooltip:AddLine("Ziehen: Verschieben", 0.8, 0.8, 0.8)
        GameTooltip:Show()
    end)
    
    AiBMinimapButton:SetScript("OnLeave", function(self)
        GameTooltip:Hide()
    end)
    
    -- Click Handler (simple for now - will be enhanced by main addon)
    AiBMinimapButton:RegisterForClicks("LeftButtonUp", "RightButtonUp")
    
    -- Drag with Hybrid Snap/Free-Form System
    AiBMinimapButton:RegisterForDrag("LeftButton")
    AiBMinimapButton:SetScript("OnDragStart", function(self)
        self.isDragging = true
        self:SetScript("OnUpdate", function(self)
            local minimap = Minimap
            local mx, my = minimap:GetCenter()
            local scale = minimap:GetEffectiveScale()
            local cx, cy = GetCursorPosition()
            cx, cy = cx / scale, cy / scale
            local dx, dy = cx - mx, cy - my
            local dist = (dx * dx + dy * dy) ^ 0.5
            
            -- Snap zone configuration
            local RADIUS_ADJUST = -5  -- Tighter snap zone
            local edgeRadius = (minimap:GetWidth() + self:GetWidth()) / 2
            local radSnap = edgeRadius + RADIUS_ADJUST
            local radPull = edgeRadius + self:GetWidth() * 0.2
            local radFree = edgeRadius + self:GetWidth() * 0.7
            local radClamp
            
            -- Snapping logic (works with round AND square minimaps!)
            if dist <= radSnap then
                self.snapped = true
                radClamp = radSnap
            elseif dist < radPull and self.snapped then
                radClamp = radSnap
            elseif dist < radFree and self.snapped then
                radClamp = radSnap + (dist - radPull) / 2
            else
                self.snapped = false
            end
            
            -- Apply final position
            if radClamp and dist > 0 then
                local factor = radClamp / dist
                dx = dx * factor
                dy = dy * factor
            end
            
            AiB_Settings.minimap_x = dx
            AiB_Settings.minimap_y = dy
            self:ClearAllPoints()
            self:SetPoint("CENTER", minimap, "CENTER", dx, dy)
        end)
    end)
    
    AiBMinimapButton:SetScript("OnDragStop", function(self)
        self.isDragging = false
        self:SetScript("OnUpdate", nil)
    end)
    
    -- Initialize DB and position
    InitMinimapDB()
    
    -- Determine initial snap state
    local edgeRadius = (Minimap:GetWidth() + AiBMinimapButton:GetWidth()) / 2
    local savedDist = ((AiB_Settings.minimap_x or 0) ^ 2 + (AiB_Settings.minimap_y or 0) ^ 2) ^ 0.5
    AiBMinimapButton.snapped = (savedDist <= edgeRadius + AiBMinimapButton:GetWidth() * 0.3)
    
    UpdateMinimapPosition()
    
    -- Show button
    AiBMinimapButton:Show()
end

-- Init on ADDON_LOADED (EARLY!)
local initFrame = CreateFrame("Frame")
initFrame:RegisterEvent("ADDON_LOADED")
initFrame:SetScript("OnEvent", function(self, event, addonName)
    if addonName == "AiB" then
        CreateMinimapButton()
        self:UnregisterEvent("ADDON_LOADED")
    end
end)
