local addonName, privateDB = ...
local L = HDG_L or {}

-- ============================================================================
-- MINIMAP BUTTON (LibDBIcon) & ADDON COMPARTMENT
-- ============================================================================

local HDG_Minimap = {}

-- ============================================================================
-- STORE HELPERS
-- ============================================================================

local function GetStore()
    local HDG = _G.HousingDecorGuide
    return HDG and HDG.Store
end

local function GetState()
    local store = GetStore()
    return store and store:GetState()
end

local function Dispatch(action, payload)
    local store = GetStore()
    if store then
        store:Dispatch(action, payload)
    end
end

local function GetMinimap(key)
    local state = GetState()
    return state and state.minimap and state.minimap[key]
end

local function SetMinimap(key, value)
    Dispatch("SET_MINIMAP", { key = key, value = value })
end
privateDB.HDG_Minimap = HDG_Minimap

local launcher -- LDB data object
local DBIcon   -- LibDBIcon reference

local ADDON_KEY = "HousingDecorGuide"
local ICON_PATH = "Interface/AddOns/HousingDecorGuide/textures/HousingDecorIcon"

-- Right-click context menu
local function ShowContextMenu(owner)
    MenuUtil.CreateContextMenu(owner, function(_, rootDescription)
        rootDescription:CreateTitle("Housing Decor Guide")
        rootDescription:CreateButton("Lumber Tracker", function()
            HDG_LumberTracker.TogglePinned()
        end)
        rootDescription:CreateButton(L["HEADER_SHOPPING_LIST"] or "Shopping List", function()
            HDG_VendorShoppingList.Toggle()
        end)
        rootDescription:CreateButton("Materials List", function()
            HDG_MaterialsList.Toggle()
        end)
        rootDescription:CreateButton("Zone Scanner", function()
            HDG_ZoneMode.ShowPopup()
        end)
    end)
end

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

function HDG_Minimap.Initialize()
    if not LibStub then return end

    -- Create the LDB data object (feeds both LibDBIcon and external LDB hosts)
    local LDB = LibStub("LibDataBroker-1.1", true)
    if not LDB then return end

    launcher = LDB:NewDataObject(ADDON_KEY, {
        type = "launcher",
        icon = ICON_PATH,
        label = "Housing Decor Guide",
        OnClick = function(frame, button)
            if button == "LeftButton" then
                HDG_UI.Toggle()
            elseif button == "RightButton" then
                ShowContextMenu(frame)
            end
        end,
        OnTooltipShow = function(tooltip)
            tooltip:AddLine("|cFFfcd34dHousing Decor Guide|r")
            tooltip:AddLine(L["TIP_MINIMAP_LEFTCLICK"] or "|cFFFFFFFFLeft-click:|r Toggle addon", 0.7, 0.7, 0.7)
            tooltip:AddLine(L["TIP_MINIMAP_RIGHTCLICK"] or "|cFFFFFFFFRight-click:|r Menu", 0.7, 0.7, 0.7)
            tooltip:AddLine(L["TIP_MINIMAP_DRAG"] or "|cFFFFFFFFDrag:|r Move button", 0.7, 0.7, 0.7)
        end,
    })

    -- Register with LibDBIcon (handles all positioning, shape detection, drag)
    DBIcon = LibStub("LibDBIcon-1.0", true)
    if DBIcon then
        local state = GetState()
        local minimapDB = state and state.minimap
        if minimapDB then
            -- LibDBIcon reads/writes minimapPos, hide, lock directly on this table
            DBIcon:Register(ADDON_KEY, launcher, minimapDB)

            -- Apply initial visibility from saved state
            HDG_Minimap.UpdateVisibility()
        end
    end

    -- Register with addon compartment (Blizzard's minimap drawer, via TOC directives)
    -- Note: Compartment is registered via TOC AddonCompartmentFunc directives, not here
end

-- ============================================================================
-- VISIBILITY CONTROLS
-- ============================================================================

function HDG_Minimap.UpdateVisibility()
    if not DBIcon or not DBIcon:IsRegistered(ADDON_KEY) then return end

    local showButton = GetMinimap("showMinimapButton")
    if showButton == nil then showButton = true end
    -- Sync LibDBIcon's hide field so its PLAYER_LOGIN handler stays consistent
    local state = GetState()
    if state and state.minimap then
        state.minimap.hide = not showButton
    end

    if showButton then
        DBIcon:Show(ADDON_KEY)
    else
        DBIcon:Hide(ADDON_KEY)
    end
end

function HDG_Minimap.Show()
    SetMinimap("showMinimapButton", true)
    HDG_Minimap.UpdateVisibility()
end

function HDG_Minimap.Hide()
    SetMinimap("showMinimapButton", false)
    HDG_Minimap.UpdateVisibility()
end

function HDG_Minimap.Toggle()
    if DBIcon and DBIcon:IsRegistered(ADDON_KEY) then
        local button = DBIcon:GetMinimapButton(ADDON_KEY)
        if button and button:IsShown() then
            HDG_Minimap.Hide()
        else
            HDG_Minimap.Show()
        end
    end
end

function HDG_Minimap.SetIcon(iconName)
    if not launcher then return end

    local iconPath
    if iconName:match("^Interface") or iconName:match("^\\") then
        iconPath = iconName
    else
        iconPath = "Interface\\Icons\\" .. iconName
    end

    launcher.icon = iconPath
    SetMinimap("icon", iconPath)
    print("|cFFfcd34d[HDG]|r Minimap icon changed to: " .. iconPath)
end

-- Set minimap button visibility
function HDG_Minimap.SetShowMinimapButton(show)
    SetMinimap("showMinimapButton", show)
    HDG_Minimap.UpdateVisibility()
end

-- Set compartment visibility (requires reload to take effect for registration)
function HDG_Minimap.SetShowInCompartment(show)
    SetMinimap("showInCompartment", show)
end

-- Check if compartment is available
function HDG_Minimap.IsCompartmentAvailable()
    return AddonCompartmentFrame and AddonCompartmentFrame.RegisterAddon
end

-- Compat: UpdatePosition is now a no-op (LibDBIcon owns positioning)
function HDG_Minimap.UpdatePosition()
    if DBIcon and DBIcon:IsRegistered(ADDON_KEY) then
        DBIcon:Refresh(ADDON_KEY)
    end
end

-- ============================================================================
-- ADDON COMPARTMENT (Minimap Drawer) - Registered via TOC directives
-- These global functions are referenced by the TOC AddonCompartmentFunc headers
-- ============================================================================

-- RegisterCompartment kept as no-op for any callers (compartment is now TOC-only)
function HDG_Minimap.RegisterCompartment() end

-- RegisterLDB kept as no-op (LDB object is now created in Initialize)
function HDG_Minimap.RegisterLDB() end

-- Don't initialize here - will be called after ADDON_LOADED event
