-- DynamicTooltips: Minimap Button Module
-- Inspired by Cell addon patterns for proper show/hide and backdrop handling

local addonName, DT = ...

DT.Minimap = {}

-- ============================================================================
-- STYLE FRAME FUNCTION (Cell-style backdrop)
-- ============================================================================

local function StylizeFrame(frame, bgColor, borderColor)
    if not bgColor then bgColor = {0.0, 0.0, 0.0, 0.85} end
    if not borderColor then borderColor = {1.0, 1.0, 1.0, 1.0} end
    
    frame:SetBackdrop({
        bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
        edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
        tile = true,
        tileSize = 32,
        edgeSize = 16,
        insets = { left = 4, right = 4, top = 4, bottom = 4 }
    })
    frame:SetBackdropColor(unpack(bgColor))
    frame:SetBackdropBorderColor(unpack(borderColor))
end

-- ============================================================================
-- LOCAL REFERENCES
-- ============================================================================

local minimapButton = nil
local optionsPanel = nil
local optionsPanelInitialized = false
local isDragging = false

-- Page definitions: each page has a title and a list of checkboxes
local pageDefs = {
    {
        id = "display",
        title = "Display",
        checkboxes = {
            { key = "enabled",              label = "Enable DynamicTooltips", tip = "Show enhanced tooltips with scaling info" },
            { key = "showCoefficients",     label = "Show Coefficients",     tip = "Display spell power/weapon damage coefficients" },
            { key = "showBaseDamage",       label = "Base Damage",           tip = "Show base damage/healing before spell power (uncheck to only see totals)" },
            { key = "showTotal",            label = "Show Total Damage",     tip = "Calculate and display total damage/healing" },
            { key = "showDPS",              label = "Show DPS/HPS",          tip = "Display damage/healing per second for DoTs/HoTs" },
            { key = "showMana",             label = "Show Mana Cost",        tip = "Display mana cost in tooltips" },
            { key = "showSpellID",          label = "Show Spell ID",         tip = "Display spell ID in tooltip footer" },
            { key = "showRankComparisons",  label = "Rank Comparisons",      tip = "Show comparisons between spell ranks" },
            { key = "showTalentModifiers",  label = "Talent Modifiers",      tip = "Show talent-modified values in tooltips" },
            { key = "showThreat",           label = "Threat Values",         tip = "Show bonus threat for high-threat abilities" },
            { key = "showDuration",         label = "Duration",              tip = "Show spell duration information" },
            -- Advanced
            { key = "showOptimization",     label = "Optimization Advice",   tip = "Show tips for spell optimization" },
            { key = "showManaEfficiency",   label = "Mana & Efficiency",     tip = "Show damage/healing per mana spent" },
            { key = "showDownrankPenalty",   label = "Downrank Penalty",      tip = "Warn about coefficient reduction for low ranks" },
        },
    },
    {
        id = "style",
        title = "Style",
        checkboxes = {},
        hasThemes = true,  -- this page gets the theme grid and font dropdown
    },
}

-- Theme definitions
local themeDefs = {
    { id = "default",         label = "Default" },
    { id = "medieval",        label = "Medieval" },
    { id = "cyberpunk",       label = "Cyberpunk" },
    { id = "nature",          label = "Nature" },
    { id = "fire",            label = "Fire" },
    { id = "minimal",         label = "Minimal" },
    { id = "void",            label = "Void" },
    { id = "frost",           label = "Frost" },
    { id = "fel",             label = "Fel" },
}

-- Runtime storage for dynamically created widgets
local createdCheckboxes = {}   -- key => CheckButton reference
local createdThemeButtons = {} -- id => Button reference
local tabButtons = {}          -- ordered list of tab buttons
local tabPages = {}            -- id => page frame
local activeTab = nil          -- currently active tab id

-- ============================================================================
-- POSITION MANAGEMENT
-- ============================================================================

local function GetMinimapButtonPosition()
    if DynamicTooltipsDB and DynamicTooltipsDB.minimapPos then
        return DynamicTooltipsDB.minimapPos
    end
    return 225  -- Default angle
end

local function SaveMinimapButtonPosition(angle)
    if not DynamicTooltipsDB then
        DynamicTooltipsDB = {}
    end
    DynamicTooltipsDB.minimapPos = angle
end

local function UpdateMinimapButtonPosition(button, angle)
    local radius = 80
    local x = math.cos(math.rad(angle)) * radius
    local y = math.sin(math.rad(angle)) * radius
    button:ClearAllPoints()
    button:SetPoint("CENTER", Minimap, "CENTER", x, y)
end

-- ============================================================================
-- DRAGGING LOGIC
-- ============================================================================

local function OnDragStart(self)
    isDragging = true
    self:LockHighlight()
end

local function OnDragStop(self)
    isDragging = false
    self:UnlockHighlight()
    
    -- Calculate angle from minimap center
    local mx, my = Minimap:GetCenter()
    local px, py = GetCursorPosition()
    local scale = UIParent:GetEffectiveScale()
    px, py = px / scale, py / scale
    
    local angle = math.deg(math.atan2(py - my, px - mx))
    SaveMinimapButtonPosition(angle)
    UpdateMinimapButtonPosition(self, angle)
end

local function OnUpdate(self)
    if isDragging then
        local mx, my = Minimap:GetCenter()
        local px, py = GetCursorPosition()
        local scale = UIParent:GetEffectiveScale()
        px, py = px / scale, py / scale
        
        local angle = math.deg(math.atan2(py - my, px - mx))
        UpdateMinimapButtonPosition(self, angle)
    end
end

-- ============================================================================
-- TAB-PAGED OPTIONS PANEL (Cell-style)
-- ============================================================================

-- Heights for each tab page
local CHECKBOX_H = 20              -- compact row height
local DISPLAY_VISIBLE_ROWS = 10    -- how many rows visible before scrolling
local DISPLAY_SCROLL_H = DISPLAY_VISIBLE_ROWS * CHECKBOX_H + 8
local TAB_HEIGHTS = {
    display  = 34 + 24 + DISPLAY_SCROLL_H + 24,  -- title + tabs + scroll area + footer
    style    = 34 + 24 + 12 + (3 * 24 + 12) + 44 + 24, -- theme grid (3 rows for 9 themes) + font dropdown + footer
}

-- Creates a single checkbox inside a parent frame
local function CreateOptionCheckbox(parent, config, yOffset)
    local cb = CreateFrame("CheckButton", nil, parent, "DT_CheckButtonTemplate")
    cb:SetPoint("TOPLEFT", parent, "TOPLEFT", 4, yOffset)

    -- The template already creates $parentText FontString and OnEnter/OnLeave
    local regions = { cb:GetRegions() }
    for _, region in ipairs(regions) do
        if region:IsObjectType("FontString") then
            region:SetText(config.label)
            break
        end
    end

    cb.tooltipText = config.tip
    cb.dbKey = config.key

    cb:SetScript("OnClick", function(self)
        if DT.DB then
            DT.DB[self.dbKey] = (self:GetChecked() == true) or (self:GetChecked() == 1)
        end
        PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON or 856)
    end)

    createdCheckboxes[config.key] = cb
    return cb
end

-- Refresh all checkboxes from saved variables
local function RefreshCheckboxes()
    for key, cb in pairs(createdCheckboxes) do
        if DT.DB then
            local value = DT.DB[key]
            if value == nil then value = true end
            cb:SetChecked(value)
        end
    end
end

-- Update theme button highlights
local function UpdateThemeButtonHighlights()
    local currentTheme = DT.DB and DT.DB.currentTheme or "medieval"
    for id, btn in pairs(createdThemeButtons) do
        if id == currentTheme then
            btn:SetAlpha(1.0)
            btn:GetFontString():SetTextColor(1.0, 0.82, 0.0)
            if not btn.activeBorder then
                btn.activeBorder = btn:CreateTexture(nil, "OVERLAY")
                btn.activeBorder:SetPoint("TOPLEFT", 3, -3)
                btn.activeBorder:SetPoint("BOTTOMRIGHT", -3, 3)
                btn.activeBorder:SetColorTexture(0.85, 0.65, 0.15, 0.35)
            end
            btn.activeBorder:Show()
        else
            btn:SetAlpha(0.75)
            btn:GetFontString():SetTextColor(0.7, 0.6, 0.45)
            if btn.activeBorder then btn.activeBorder:Hide() end
        end
    end
end

-- Show a specific tab page, hide all others, update button highlights
local function ShowTab(tabId)
    if activeTab == tabId then return end
    activeTab = tabId

    -- Show/hide pages
    for id, page in pairs(tabPages) do
        if id == tabId then
            page:Show()
        else
            page:Hide()
        end
    end

    -- Update tab button styling
    for _, btn in ipairs(tabButtons) do
        if btn.tabId == tabId then
            btn:SetBackdropColor(0.12, 0.08, 0.02, 1.0)
            btn:SetBackdropBorderColor(0.85, 0.70, 0.35, 0.9)
            btn:GetFontString():SetTextColor(1.0, 0.82, 0.0)
        else
            btn:SetBackdropColor(0.05, 0.03, 0.0, 0.85)
            btn:SetBackdropBorderColor(0.6, 0.5, 0.35, 0.5)
            btn:GetFontString():SetTextColor(0.7, 0.6, 0.45)
        end
    end

    -- Resize panel for this tab
    if optionsPanel and TAB_HEIGHTS[tabId] then
        optionsPanel:SetHeight(TAB_HEIGHTS[tabId])
    end
end

-- Create a tab button (Cell-style)
local function CreateTabButton(parent, label, tabId, anchorFrame, anchorPoint, anchorOffX)
    local btn = CreateFrame("Button", nil, parent, "BackdropTemplate")
    btn:SetSize(70, 22)
    btn:SetPoint("BOTTOMLEFT", anchorFrame, anchorPoint, anchorOffX or 0, 0)

    btn:SetBackdrop({
        bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
        edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
        tile = true, tileSize = 32, edgeSize = 12,
        insets = { left = 3, right = 3, top = 3, bottom = 3 },
    })
    btn:SetBackdropColor(0.05, 0.03, 0.0, 0.85)
    btn:SetBackdropBorderColor(0.6, 0.5, 0.35, 0.7)

    local text = btn:CreateFontString(nil, "ARTWORK", "DT_Font_Description")
    text:SetPoint("CENTER")
    text:SetText(label)
    btn:SetFontString(text)

    btn.tabId = tabId
    btn:SetScript("OnClick", function()
        ShowTab(tabId)
        PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON or 856)
    end)

    -- Drag to move the whole panel (Cell pattern)
    btn:RegisterForDrag("LeftButton")
    btn:SetScript("OnDragStart", function() optionsPanel:StartMoving() end)
    btn:SetScript("OnDragStop", function() optionsPanel:StopMovingOrSizing() end)

    table.insert(tabButtons, btn)
    return btn
end

-- Create a page frame (hidden by default)
local function CreatePage(parent, tabId)
    local page = CreateFrame("Frame", nil, parent)
    page:SetAllPoints(parent)
    page:SetFrameLevel(parent:GetFrameLevel() + 1)
    page:Hide()
    tabPages[tabId] = page
    return page
end

-- ============================================================================
-- FONT DROPDOWN (inside Style tab)
-- ============================================================================

local fontDropdownButton = nil  -- reference to the dropdown button
local fontDropdownMenu = nil    -- the dropdown frame with options

local function UpdateFontDropdownText()
    if not fontDropdownButton then return end
    local _, data = DT.Fonts:GetCurrent()
    if data then
        fontDropdownButton.label:SetText(data.name)
    end
end

-- Build the dropdown button + flyout menu
local function BuildFontDropdown(parent, yOffset)
    -- Main dropdown button (styled like theme buttons)
    local btn = CreateFrame("Button", nil, parent, "BackdropTemplate")
    btn:SetSize(160, 22)
    btn:SetPoint("TOPLEFT", parent, "TOPLEFT", 8, yOffset)

    btn:SetBackdrop({
        bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
        edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
        tile = true, tileSize = 32, edgeSize = 10,
        insets = { left = 2, right = 2, top = 2, bottom = 2 },
    })
    btn:SetBackdropColor(0.05, 0.03, 0.0, 0.9)
    btn:SetBackdropBorderColor(0.6, 0.5, 0.35, 0.6)

    -- Current font name label
    local label = btn:CreateFontString(nil, "ARTWORK", "DT_Font_Footer")
    label:SetPoint("LEFT", 6, 0)
    btn.label = label

    -- Arrow indicator
    local arrow = btn:CreateFontString(nil, "ARTWORK", "DT_Font_Footer")
    arrow:SetPoint("RIGHT", -4, 0)
    arrow:SetText("|cffdaa520v|r")

    fontDropdownButton = btn

    -- Build the flyout menu (initially hidden)
    local fonts = DT.Fonts:GetList()
    local ITEM_H = 20
    local menuHeight = #fonts * ITEM_H + 4

    local menu = CreateFrame("Frame", nil, btn, "BackdropTemplate")
    menu:SetSize(160, menuHeight)
    menu:SetPoint("TOPLEFT", btn, "BOTTOMLEFT", 0, -1)
    menu:SetBackdrop({
        bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
        edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
        tile = true, tileSize = 32, edgeSize = 10,
        insets = { left = 2, right = 2, top = 2, bottom = 2 },
    })
    menu:SetBackdropColor(0.02, 0.01, 0.0, 0.97)
    menu:SetBackdropBorderColor(0.6, 0.5, 0.35, 0.7)
    menu:SetFrameLevel(btn:GetFrameLevel() + 10)
    menu:Hide()
    fontDropdownMenu = menu

    -- Create one button per font
    for i, fontInfo in ipairs(fonts) do
        local item = CreateFrame("Button", nil, menu)
        item:SetSize(156, ITEM_H)
        item:SetPoint("TOPLEFT", menu, "TOPLEFT", 2, -((i - 1) * ITEM_H + 2))

        -- Use the actual font for the label so user previews it
        local itemLabel = item:CreateFontString(nil, "ARTWORK")
        itemLabel:SetPoint("LEFT", 6, 0)
        itemLabel:SetFont(fontInfo.path, 12, "OUTLINE")
        itemLabel:SetText(fontInfo.name)
        itemLabel:SetTextColor(0.85, 0.75, 0.55)
        item:SetFontString(itemLabel)

        -- Highlight on hover
        local hl = item:CreateTexture(nil, "HIGHLIGHT")
        hl:SetAllPoints()
        hl:SetColorTexture(0.6, 0.5, 0.2, 0.2)

        item:SetScript("OnClick", function()
            DT.Fonts:Set(fontInfo.id)
            UpdateFontDropdownText()
            menu:Hide()
            PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON or 856)
            print("|cff66ccffDynamicTooltips|r: Font changed to |cffffffff" .. fontInfo.name .. "|r")
        end)
    end

    -- Toggle menu on click
    btn:SetScript("OnClick", function()
        if menu:IsShown() then
            menu:Hide()
        else
            menu:Show()
        end
        PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON or 856)
    end)

    -- Close menu when clicking elsewhere
    menu:SetScript("OnShow", function(self)
        self:SetPropagateKeyboardInput(true)
    end)

    -- Set initial text
    UpdateFontDropdownText()
end

-- Build the Themes page (grid of 8 buttons)
local function BuildThemesPage(parent)
    local COLS = 4
    local BTN_W = 66
    local BTN_H = 22
    local PAD_X = 2
    local PAD_Y = 2

    for i, def in ipairs(themeDefs) do
        local col = (i - 1) % COLS
        local row = math.floor((i - 1) / COLS)

        local btn = CreateFrame("Button", nil, parent, "BackdropTemplate")
        btn:SetSize(BTN_W, BTN_H)
        btn:SetPoint("TOPLEFT", parent, "TOPLEFT", 6 + col * (BTN_W + PAD_X), -(6 + row * (BTN_H + PAD_Y)))

        btn:SetBackdrop({
            bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
            edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
            tile = true, tileSize = 32, edgeSize = 10,
            insets = { left = 2, right = 2, top = 2, bottom = 2 },
        })
        btn:SetBackdropColor(0.05, 0.03, 0.0, 0.9)
        btn:SetBackdropBorderColor(0.6, 0.5, 0.35, 0.6)

        local text = btn:CreateFontString(nil, "ARTWORK", "DT_Font_Footer")
        text:SetPoint("CENTER")
        text:SetText(def.label)
        btn:SetFontString(text)

        btn.themeId = def.id
        btn:SetScript("OnClick", function(self)
            if DT.Themes then
                DT.Themes.Set(self.themeId)
                if DT.DB then DT.DB.currentTheme = self.themeId end
                UpdateThemeButtonHighlights()
                local footerText = _G["DynamicTooltipsOptionsPanelFooterVersionText"]
                if footerText then
                    local theme = DT.Themes.GetCurrent()
                    footerText:SetText("DynamicTooltips v" .. (DT.version or "1.0.0") .. " | " .. theme.name .. " Theme")
                end
                print("|cff66ccffDynamicTooltips|r: Theme changed to |cffffffff" .. def.label .. "|r")
            end
            PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON or 856)
        end)
        btn:SetScript("OnEnter", function(self)
            GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
            local theme = DT.Themes and DT.Themes.List[self.themeId]
            if theme then
                GameTooltip:SetText(theme.name, 0.902, 0.953, 1.0)
                GameTooltip:AddLine(theme.description, 0.7, 0.8, 0.9, true)
            else
                GameTooltip:SetText(def.label, 0.902, 0.953, 1.0)
            end
            GameTooltip:Show()
        end)
        btn:SetScript("OnLeave", function() GameTooltip:Hide() end)

        createdThemeButtons[def.id] = btn
    end
end

-- ============================================================================
-- INITIALIZE OPTIONS PANEL
-- ============================================================================

local function InitOptionsPanel()
    if optionsPanelInitialized then return end
    optionsPanelInitialized = true

    optionsPanel = _G["DynamicTooltipsOptionsPanel"]
    if not optionsPanel then return end

    -- Apply backdrop
    StylizeFrame(optionsPanel, {0.0, 0.0, 0.0, 0.85}, {1.0, 1.0, 1.0, 1.0})

    local titleBar = _G["DynamicTooltipsOptionsPanelTitleBar"]
    if titleBar then
        StylizeFrame(titleBar, {0.05, 0.03, 0.0, 0.95}, {1.0, 1.0, 1.0, 1.0})
        titleBar:SetFrameLevel(optionsPanel:GetFrameLevel() + 5)
    end

    -- Raise close button above everything so it's clickable
    local closeButton = _G["DynamicTooltipsOptionsPanelCloseButton"]
    if closeButton then
        closeButton:SetFrameLevel(optionsPanel:GetFrameLevel() + 10)
    end

    local content = _G["DynamicTooltipsOptionsPanelContent"]
    if not content then return end

    -- Raise content above the BackdropTemplate's internal backdrop frame
    content:SetFrameLevel(optionsPanel:GetFrameLevel() + 5)

    -- Raise footer too
    local footer = _G["DynamicTooltipsOptionsPanelFooter"]
    if footer then
        footer:SetFrameLevel(optionsPanel:GetFrameLevel() + 5)
    end

    -- ----------------------------------------------------------------
    -- Create tab buttons above the title bar (Cell-style)
    -- ----------------------------------------------------------------
    local tab1 = CreateTabButton(optionsPanel, "Display",  "display",  optionsPanel, "TOPLEFT",  0)
    local tab2 = CreateTabButton(optionsPanel, "Style",    "style",    tab1,         "BOTTOMRIGHT", -1)

    -- Raise tab buttons
    for _, tb in ipairs(tabButtons) do
        tb:SetFrameLevel(optionsPanel:GetFrameLevel() + 6)
    end

    -- ----------------------------------------------------------------
    -- Create page frames inside content
    -- ----------------------------------------------------------------
    for _, def in ipairs(pageDefs) do
        local page = CreatePage(content, def.id)

        -- Display tab: wrap checkboxes in a scroll frame
        if def.id == "display" and #def.checkboxes > DISPLAY_VISIBLE_ROWS then
            -- ScrollFrame container
            local sf = CreateFrame("ScrollFrame", nil, page, "UIPanelScrollFrameTemplate")
            sf:SetPoint("TOPLEFT", page, "TOPLEFT", 0, -2)
            sf:SetPoint("BOTTOMRIGHT", page, "BOTTOMRIGHT", -24, 2)
            sf:SetFrameLevel(page:GetFrameLevel() + 1)
            sf:SetSize(page:GetWidth() or 260, DISPLAY_SCROLL_H)

            -- Scroll child (tall enough for all checkboxes)
            local child = CreateFrame("Frame", nil, sf)
            child:SetWidth(sf:GetWidth() or 260)
            child:SetHeight(#def.checkboxes * CHECKBOX_H + 8)
            sf:SetScrollChild(child)

            -- Enable mouse wheel scrolling
            sf:EnableMouseWheel(true)
            sf:SetScript("OnMouseWheel", function(self, delta)
                local scrollBar = self.ScrollBar or _G[self:GetName() .. "ScrollBar"]
                if scrollBar then
                    local cur = scrollBar:GetValue()
                    local minV, maxV = scrollBar:GetMinMaxValues()
                    local step = CHECKBOX_H * 3
                    scrollBar:SetValue(math.max(minV, math.min(maxV, cur - delta * step)))
                end
            end)

            for idx, cbDef in ipairs(def.checkboxes) do
                CreateOptionCheckbox(child, cbDef, -((idx - 1) * CHECKBOX_H) - 4)
            end
        else
            for idx, cbDef in ipairs(def.checkboxes) do
                CreateOptionCheckbox(page, cbDef, -((idx - 1) * CHECKBOX_H) - 4)
            end
        end

        -- If this page also has theme buttons, add them below checkboxes
        if def.hasThemes then
            local themeAnchorY = -(#def.checkboxes * CHECKBOX_H + 12)
            -- Section label
            local label = page:CreateFontString(nil, "ARTWORK", "DT_Font_Title")
            label:SetPoint("TOPLEFT", page, "TOPLEFT", 8, themeAnchorY)
            label:SetText("|cffdaa520Themes|r")
            -- Theme grid offset below the label
            local themeFrame = CreateFrame("Frame", nil, page)
            themeFrame:SetPoint("TOPLEFT", page, "TOPLEFT", 0, themeAnchorY - 16)
            themeFrame:SetPoint("TOPRIGHT", page, "TOPRIGHT", 0, themeAnchorY - 16)
            themeFrame:SetHeight(76)
            BuildThemesPage(themeFrame)

            -- Font dropdown below theme grid
            local fontAnchorY = themeAnchorY - 16 - 76  -- below theme grid
            local fontLabel = page:CreateFontString(nil, "ARTWORK", "DT_Font_Title")
            fontLabel:SetPoint("TOPLEFT", page, "TOPLEFT", 8, fontAnchorY)
            fontLabel:SetText("|cffdaa520Font|r")

            BuildFontDropdown(page, fontAnchorY - 16)
        end
    end

    -- Show first tab by default
    ShowTab("display")
    RefreshCheckboxes()
    UpdateThemeButtonHighlights()
end

local function ShowOptions()
    -- Initialize panel if not done
    InitOptionsPanel()
    
    if not optionsPanel then
        optionsPanel = _G["DynamicTooltipsOptionsPanel"]
    end
    
    if optionsPanel then
        -- Toggle if already shown (Cell pattern)
        if optionsPanel:IsShown() then
            optionsPanel:Hide()
            return
        end
        
        RefreshCheckboxes()
        UpdateThemeButtonHighlights()
        if activeTab then ShowTab(activeTab) end
        optionsPanel:Show()
    end
end

local function ToggleEnabled()
    if not DT.DB then DT.DB = {} end
    DT.DB.enabled = not (DT.DB.enabled ~= false)
    
    local status = DT.DB.enabled and "|cff00ff00Enabled|r" or "|cffff0000Disabled|r"
    print("|cff66ccffDynamicTooltips|r: " .. status)
    
    -- Update checkbox if it exists
    local cb = createdCheckboxes["enabled"]
    if cb then
        cb:SetChecked(DT.DB.enabled)
    end
end

-- ============================================================================
-- MINIMAP BUTTON HANDLERS
-- ============================================================================

local function OnMinimapClick(self, button)
    if button == "LeftButton" then
        ShowOptions()
    elseif button == "RightButton" then
        ToggleEnabled()
    end
end

-- ============================================================================
-- INITIALIZATION
-- ============================================================================

function DT.Minimap:Initialize()
    -- Get reference to XML-defined minimap button
    minimapButton = _G["DynamicTooltipsMinimapButtonFrame"]
    
    if minimapButton then
        -- Set up event handlers
        minimapButton:SetScript("OnClick", OnMinimapClick)
        minimapButton:SetScript("OnDragStart", OnDragStart)
        minimapButton:SetScript("OnDragStop", OnDragStop)
        minimapButton:SetScript("OnUpdate", OnUpdate)
        
        -- Load saved position
        local angle = GetMinimapButtonPosition()
        UpdateMinimapButtonPosition(minimapButton, angle)
        
        -- Check if should be hidden
        if DynamicTooltipsDB and DynamicTooltipsDB.hideMinimapButton then
            minimapButton:Hide()
        end
    end
    
    -- Get reference to options panel
    optionsPanel = _G["DynamicTooltipsOptionsPanel"]
    
    if optionsPanel then
        optionsPanel:SetScript("OnShow", function(self)
            RefreshCheckboxes()
            UpdateThemeButtonHighlights()
            if activeTab then ShowTab(activeTab) end
            local footerText = _G["DynamicTooltipsOptionsPanelFooterVersionText"]
            if footerText then
                local themeName = DT.Themes and DT.Themes.GetCurrent().name or "Medieval"
                footerText:SetText("DynamicTooltips v" .. (DT.version or "1.0.0") .. " | " .. themeName .. " Theme")
            end
            PlaySound(SOUNDKIT.IG_CHARACTER_INFO_OPEN or 839)
        end)
        
        optionsPanel:SetScript("OnHide", function(self)
            PlaySound(SOUNDKIT.IG_CHARACTER_INFO_CLOSE or 840)
            if not InCombatLockdown() and not UnitAffectingCombat("player") then
                collectgarbage("collect")
            end
        end)
        
        local closeButton = _G["DynamicTooltipsOptionsPanelCloseButton"]
        if closeButton then
            closeButton:SetScript("OnClick", function()
                optionsPanel:Hide()
            end)
        end
    end
    
    -- Initialize checkboxes and theme buttons
    InitOptionsPanel()
end

function DT.Minimap:Show()
    if minimapButton then
        minimapButton:Show()
    end
end

function DT.Minimap:Hide()
    if minimapButton then
        minimapButton:Hide()
    end
end

function DT.Minimap:Toggle()
    if minimapButton then
        if minimapButton:IsShown() then
            minimapButton:Hide()
            if DT.DB then DT.DB.hideMinimapButton = true end
        else
            minimapButton:Show()
            if DT.DB then DT.DB.hideMinimapButton = false end
        end
    end
end

function DT.Minimap:ShowOptions()
    ShowOptions()
end

function DT.Minimap:RefreshOptions()
    RefreshCheckboxes()
end

-- Export
_G.DynamicTooltipsMinimap = DT.Minimap
