--[[
============================================================================
ETB v10.0 - MinimapButton.lua
============================================================================
Minimap button for quick access.
============================================================================
]]--

local ADDON_NAME, NS = ...
local ETB = NS.ETB

ETB.MinimapButton = {
    frame = nil,
    dragging = false,
}

local MMB = ETB.MinimapButton

-- =============================================================================
-- CREATE
-- =============================================================================

function MMB:Create()
    if self.frame then return self.frame end
    
    local f = CreateFrame("Button", "ETBMinimapButton", Minimap)
    f:SetSize(31, 31)
    f:SetFrameStrata("MEDIUM")
    f:SetFrameLevel(8)
    f:SetHighlightTexture("Interface\\Minimap\\UI-Minimap-ZoomButton-Highlight")
    
    local overlay = f:CreateTexture(nil, "OVERLAY")
    overlay:SetSize(53, 53)
    overlay:SetPoint("TOPLEFT")
    overlay:SetTexture("Interface\\Minimap\\MiniMap-TrackingBorder")
    
    local icon = f:CreateTexture(nil, "BACKGROUND")
    icon:SetSize(20, 20)
    icon:SetPoint("CENTER", 0, 0)
    icon:SetTexture("Interface\\Icons\\INV_Chest_Cloth_17")
    icon:SetTexCoord(0.08, 0.92, 0.08, 0.92)
    f.icon = icon
    
    -- Tooltip
    f:SetScript("OnEnter", function(self)
        GameTooltip:SetOwner(self, "ANCHOR_LEFT")
        GameTooltip:SetText("Enhanced Transmog Browser", 1, 1, 1)
        GameTooltip:AddLine("Left-click: Open Launcher", 0.8, 0.8, 0.8)
        GameTooltip:AddLine("Right-click: Quick open Browser", 0.8, 0.8, 0.8)
        GameTooltip:AddLine("Shift+click: Quick open TransmogUI", 0.8, 0.8, 0.8)
        GameTooltip:AddLine("Ctrl+click: |cff00ccffRaid BiS Browser|r", 0.8, 0.8, 0.8)
        GameTooltip:AddLine("Drag: Move button", 0.5, 0.5, 0.5)
        
        local stats = ETB.BlizzardData:GetAllStats()
        if stats.total > 0 then
            GameTooltip:AddLine(" ")
            GameTooltip:AddLine(string.format("Collection: %s/%s (%.0f%%)",
                ETB:FormatNumber(stats.collected),
                ETB:FormatNumber(stats.total),
                stats.percent), 0, 1, 0)
        end
        
        -- ERB status line
        local ERB = ETB.ERB
        if ERB and ERB.DataBridge and ERB.DataBridge.playerSpecName then
            local info = ERB:GetPlayerInfo()
            GameTooltip:AddLine(string.format("|cff00ccff[Raid BiS]|r %s — %d items (%s)",
                ERB.DataBridge.playerSpecName,
                ERB.DataBridge.itemCount or 0,
                ERB.DataBridge:GetSourceLabel(ERB.DataBridge.activeSource) or "?"), 0.5, 0.8, 1)
        end
        
        GameTooltip:Show()
    end)
    f:SetScript("OnLeave", function() GameTooltip:Hide() end)
    
    -- Click
    f:SetScript("OnClick", function(self, button)
        if button == "LeftButton" then
            if IsControlKeyDown() then
                -- Open ERB Raid BiS Browser (triggers LoadAddOn on first click)
                local ERB = ETB:GetERB()
                if ERB and ERB.MainFrame then
                    ERB.MainFrame:Toggle()
                end
            elseif IsShiftKeyDown() then
                -- Quick open TransmogUI
                if ETB.TransmogUI and ETB.TransmogUI.Show then
                    ETB.TransmogUI:Show()
                elseif ETB.TransmogUI and ETB.TransmogUI.frame then
                    ETB.TransmogUI.frame:Show()
                end
            else
                -- Open launcher panel
                if ETB.LauncherPanel then
                    ETB.LauncherPanel:Toggle()
                else
                    ETB.MainFrame:Toggle()
                end
            end
        elseif button == "RightButton" then
            -- Quick open browser directly
            ETB.MainFrame:Toggle()
        elseif button == "MiddleButton" then
            -- Middle-click also opens ERB (triggers LoadAddOn on first click)
            local ERB = ETB:GetERB()
            if ERB and ERB.MainFrame then
                ERB.MainFrame:Toggle()
            end
        end
    end)
    
    -- Dragging
    f:RegisterForDrag("LeftButton")
    -- v15.8.8: bind OnUpdate only while dragging. The minimap button is
    -- always shown so this OnUpdate was firing 60 fps × 60s × 60min ~=
    -- 216,000 wasted calls per hour just to check the dragging flag.
    -- Install/uninstall via OnDragStart/OnDragStop instead.
    local function onUpdateDrag(self)
        local mx, my = Minimap:GetCenter()
        local px, py = GetCursorPosition()
        local scale = Minimap:GetEffectiveScale()
        px, py = px / scale, py / scale
        local angle = math.atan2(py - my, px - mx)
        MMB:SetPosition(math.deg(angle))
    end
    f:SetScript("OnDragStart", function(self)
        self:SetScript("OnUpdate", onUpdateDrag)
    end)
    f:SetScript("OnDragStop", function(self)
        self:SetScript("OnUpdate", nil)
        MMB:SavePosition()
    end)
    
    f:RegisterForClicks("LeftButtonUp", "RightButtonUp", "MiddleButtonUp")
    
    self.frame = f
    return f
end

-- =============================================================================
-- POSITION
-- =============================================================================

function MMB:SetPosition(angle)
    if not self.frame then return end
    
    local radius = 80
    local rads = math.rad(angle)
    local x = math.cos(rads) * radius
    local y = math.sin(rads) * radius
    
    self.frame:ClearAllPoints()
    self.frame:SetPoint("CENTER", Minimap, "CENTER", x, y)
    
    ETB_MinimapSettings = ETB_MinimapSettings or {}
    ETB_MinimapSettings.position = angle
end

function MMB:SavePosition()
    ETB_MinimapSettings = ETB_MinimapSettings or {}
    -- Position already saved in SetPosition
end

-- =============================================================================
-- INITIALIZE
-- =============================================================================

function MMB:Initialize()
    if not self.frame then self:Create() end
    
    ETB_MinimapSettings = ETB_MinimapSettings or { show = true, position = 195 }
    
    if ETB_MinimapSettings.show then
        self:SetPosition(ETB_MinimapSettings.position or 195)
        self.frame:Show()
    else
        self.frame:Hide()
    end
end

function MMB:Show()
    if not self.frame then self:Create() end
    self.frame:Show()
    ETB_MinimapSettings = ETB_MinimapSettings or {}
    ETB_MinimapSettings.show = true
end

function MMB:Hide()
    if self.frame then self.frame:Hide() end
    ETB_MinimapSettings = ETB_MinimapSettings or {}
    ETB_MinimapSettings.show = false
end

function MMB:Toggle()
    if self.frame and self.frame:IsShown() then
        self:Hide()
    else
        self:Show()
    end
end

ETB:Debug("MinimapButton", "MinimapButton.lua loaded")
