-- =============================================================================
-- EditMode_DR.lua - DR Icons Edit Mode Support (Clean Rebuild)
-- =============================================================================
-- This module makes DR icons draggable in Edit Mode by creating wrapper frames
-- that cover the DR icon area and forward drag events to the containers.
-- =============================================================================

local AddonName, _ns = ...
if type(_G.ArenaCore) ~= "table" then _G.ArenaCore = {} end
local AC = _G.ArenaCore

if not AC.EditMode then
    print("|cffFF0000ArenaCore DR Edit Mode:|r Edit Mode not loaded!")
    return
end

local EM = AC.EditMode

-- Store DR drag wrappers so we can clean them up
local drWrappers = {}

-- Create a draggable wrapper frame that covers the DR icon area
local function CreateDRWrapper(drContainer, arenaIndex)
    -- Get DR settings to position the wrapper correctly
    local db = AC.DB and AC.DB.profile and AC.DB.profile.diminishingReturns
    if not db then return nil end
    
    local pos = db.positioning or {}
    local sizing = db.sizing or {}
    local rows = db.rows or {}
    local iconSize = tonumber(sizing.size) or 33
    local spacing = tonumber(pos.spacing) or 3
    -- CRITICAL FIX: Read from rows.growthDirection (number), not positioning.growthDirection (string)
    local growthNum = rows.growthDirection or 4 -- 1=Up, 2=Down, 3=Left, 4=Right
    local growthMap = {[1]="Up", [2]="Down", [3]="Left", [4]="Right"}
    local growth = growthMap[growthNum] or "Right"
    
    -- Calculate wrapper size (covers all 7 DR categories)
    local maxIcons = 7
    local wrapperWidth, wrapperHeight
    
    if growth == "Right" or growth == "Left" then
        wrapperWidth = (iconSize * maxIcons) + (spacing * (maxIcons - 1))
        wrapperHeight = iconSize
    else
        wrapperWidth = iconSize
        wrapperHeight = (iconSize * maxIcons) + (spacing * (maxIcons - 1))
    end
    
    -- Create wrapper frame parented to the arena frame (not the container)
    local arenaFrame = drContainer:GetParent()
    local wrapper = CreateFrame("Frame", nil, arenaFrame)
    wrapper:SetSize(wrapperWidth, wrapperHeight)
    wrapper:SetFrameStrata("HIGH")
    wrapper:SetFrameLevel(200)  -- Above everything
    
    -- CRITICAL FIX: Position wrapper to match actual DR icon positioning
    -- DR icons use CENTER anchor (see DR.lua line 334), so wrapper must too
    local baseX = pos.horizontal or 0
    local baseY = pos.vertical or 0
    
    -- FINE-TUNING: Account for icon being centered at the anchor point
    -- The first icon's CENTER is at baseX/baseY, so we need to offset by half icon size
    local halfIcon = iconSize / 2
    
    -- Wrapper uses CENTER anchor to match where first DR icon is positioned
    -- Then offset based on growth direction to cover the icon group
    if growth == "Right" then
        -- Icons grow left from center, wrapper RIGHT edge at center + half icon
        wrapper:SetPoint("RIGHT", arenaFrame, "CENTER", baseX + halfIcon, baseY)
    elseif growth == "Left" then
        -- Icons grow right from center, wrapper LEFT edge at center - half icon
        wrapper:SetPoint("LEFT", arenaFrame, "CENTER", baseX - halfIcon, baseY)
    elseif growth == "Up" then
        -- Icons grow down from center, wrapper BOTTOM edge at center - half icon
        wrapper:SetPoint("BOTTOM", arenaFrame, "CENTER", baseX, baseY - halfIcon)
    elseif growth == "Down" then
        -- Icons grow up from center, wrapper TOP edge at center + half icon
        wrapper:SetPoint("TOP", arenaFrame, "CENTER", baseX, baseY + halfIcon)
    end
    
    -- Store reference to the container we're controlling
    wrapper.drContainer = drContainer
    wrapper.arenaIndex = arenaIndex
    
    return wrapper
end

-- Register DR Icons as an Edit Mode group
C_Timer.After(0.5, function()
    if not EM.ELEMENT_GROUPS then
        print("|cffFF0000ArenaCore DR Edit Mode:|r ELEMENT_GROUPS not found!")
        return
    end

    -- Clean approach: Return wrapper frames that are properly positioned and sized
    EM.ELEMENT_GROUPS.drIcons = {
        dbPath = "diminishingReturns.positioning",
        refreshFunc = "RefreshDRLayout",
        selector = function()
            -- Reuse existing wrappers if they exist, otherwise create new ones
            if #drWrappers == 0 then
                -- Create new wrappers for each arena frame
                local arenaFrames = AC.FrameManager and AC.FrameManager:GetFrames()
                if arenaFrames then
                    for i = 1, 3 do
                        local f = arenaFrames[i]
                        if f and f.drContainer then
                            local wrapper = CreateDRWrapper(f.drContainer, i)
                            if wrapper then
                                table.insert(drWrappers, wrapper)
                            end
                        end
                    end
                end
            else
                -- Reposition existing wrappers (in case DR layout changed)
                for i, wrapper in ipairs(drWrappers) do
                    if wrapper and wrapper.drContainer then
                        -- Update wrapper position based on current DR settings
                        local db = AC.DB and AC.DB.profile and AC.DB.profile.diminishingReturns
                        if db then
                            local pos = db.positioning or {}
                            local sizing = db.sizing or {}
                            local rows = db.rows or {}
                            local baseX = pos.horizontal or 0
                            local baseY = pos.vertical or 0
                            local iconSize = tonumber(sizing.size) or 33
                            local halfIcon = iconSize / 2
                            -- CRITICAL FIX: Read from rows.growthDirection (number), not positioning.growthDirection (string)
                            local growthNum = rows.growthDirection or 4
                            local growthMap = {[1]="Up", [2]="Down", [3]="Left", [4]="Right"}
                            local growth = growthMap[growthNum] or "Right"
                            local arenaFrame = wrapper.drContainer:GetParent()
                            
                            wrapper:ClearAllPoints()
                            -- CRITICAL FIX: Use CENTER anchor with half-icon offset for perfect alignment
                            if growth == "Right" then
                                wrapper:SetPoint("RIGHT", arenaFrame, "CENTER", baseX + halfIcon, baseY)
                            elseif growth == "Left" then
                                wrapper:SetPoint("LEFT", arenaFrame, "CENTER", baseX - halfIcon, baseY)
                            elseif growth == "Up" then
                                wrapper:SetPoint("BOTTOM", arenaFrame, "CENTER", baseX, baseY - halfIcon)
                            elseif growth == "Down" then
                                wrapper:SetPoint("TOP", arenaFrame, "CENTER", baseX, baseY + halfIcon)
                            end
                        end
                    end
                end
            end
            
            return drWrappers
        end
    }

    -- Hook into Disable to clean up wrappers
    local originalDisable = EM.Disable
    EM.Disable = function(self)
        -- Clear wrappers when Edit Mode is disabled
        for i, wrapper in ipairs(drWrappers) do
            if wrapper then
                wrapper:Hide()
                wrapper:SetParent(nil)
            end
        end
        drWrappers = {}
        
        -- Call original Disable
        originalDisable(self)
    end

    -- DR Icons Edit Mode support loaded (debug removed for clean chat output)
end)
