-- wheredoigetit.lua
-- Compact data + icon support + Command Central

local ADDON_NAME, WDIGI = ...

-- Ensure global command table exists
WDIGI.Commands = WDIGI.Commands or {}

------------------------------------------------------------
-- INITIALIZATION
------------------------------------------------------------
local eventFrame = CreateFrame("Frame")
eventFrame:RegisterEvent("ADDON_LOADED")

eventFrame:SetScript("OnEvent", function(self, event, addon)
    if addon == ADDON_NAME then
        WDIGI:Initialize()
        self:UnregisterEvent("ADDON_LOADED")
    end
end)

function WDIGI:Initialize()
    print("|cff00ffffWhere Do I Get It?|r " .. (WDIGI.VERSION or "") .. " loaded.")

    -- 1. Initialize modern Tooltip hooks (Retail/2026 support)
    if TooltipDataProcessor and TooltipDataProcessor.AddTooltipPostCall then
        TooltipDataProcessor.AddTooltipPostCall(Enum.TooltipDataType.Item, function(tooltip)
             if WDIGI.Tooltip and WDIGI.Tooltip.Update then
                WDIGI.Tooltip.Update(tooltip)
             end
        end)
    else
        -- Fallback for classic or older API versions
        GameTooltip:HookScript("OnTooltipSetItem", WDIGI.Tooltip.Update)
        ItemRefTooltip:HookScript("OnTooltipSetItem", WDIGI.Tooltip.Update)
    end

    -- 2. Cleanup GUIDs on hide
    local function ClearGUID() WDIGI.Tooltip.lastItemGUID = nil end
    GameTooltip:HookScript("OnHide", ClearGUID)
    ItemRefTooltip:HookScript("OnHide", ClearGUID)
    
    -- 3. Minimap Button Creation (Dashboard Entry)
    if WDIGI.Compendium and WDIGI.Compendium.CreateMinimapButton then
        WDIGI.Compendium:CreateMinimapButton()
    end
    
    WDIGI.Utils.Debug("WDIGI Initialized and Hooks set.")
end

------------------------------------------------------------
-- ITEM CLICK HANDLER (CTRL+SHIFT+LCLICK Pin)
------------------------------------------------------------
hooksecurefunc("HandleModifiedItemClick", function(itemLink)
    -- Only trigger if the specific modifiers are held
    if IsControlKeyDown() and IsShiftKeyDown() then
        if WDIGI.Tooltip.bestLocation then
            WDIGI.Utils.Debug("Modifier Click: Triggering WDIGI.Commands.Pin")
            WDIGI.Commands.Pin()
        else
            WDIGI.Utils.Warn("Modifier Click: No location data found in tooltip.")
        end
    end
end)

------------------------------------------------------------
-- CORE COMMANDS
------------------------------------------------------------
function WDIGI.Commands.Pin()
    local best = WDIGI.Tooltip.bestLocation

    if not best then
        WDIGI.Utils.Warn("Commands.Pin: bestLocation is NIL")
        print("|cffff0000WDIGI:|r Hover over an item with location data first.")
        return
    end

    WDIGI.Utils.Debug(string.format("  -> Pinning: %s at %s (%s, %s)",
        tostring(best.vendorName), tostring(best.zID), tostring(best.tx), tostring(best.ty)))

    local vendorIcon = WDIGI.Data.VENDOR_ICONS[best.vendorType]

    WDIGI.Navigation.SetPin(
        best.zID,
        best.tx,
        best.ty,
        best.vendorName,
        WDIGI.Tooltip.lastItemName,
        best.cost,
        best.header,
        WDIGI.Tooltip.lastItemIcon,
        vendorIcon
    )
end

function WDIGI.Commands.NavOff()
    if WDIGI.Navigation and WDIGI.Navigation.HUD then
        WDIGI.Navigation.HUD:Hide()
    end
    C_Map.ClearUserWaypoint()
    print("|cff00ffffWDIGI:|r Navigation cleared.")
end

function WDIGI.Commands.ClearCache()
    WDIGI.Data.Parsed = {}
    print("|cff00ffffWDIGI:|r Data cache cleared.")
end

------------------------------------------------------------
-- DEBUG SYSTEM COMMANDS
------------------------------------------------------------
function WDIGI.Commands.Debug(arg)
    if arg == "on" then
        WDIGI.CurrentDebugLevel = WDIGI.DebugLevels.DEBUG
        print("|cff00ffffWDIGI:|r Debug mode ON")
    elseif arg == "off" then
        WDIGI.CurrentDebugLevel = WDIGI.DebugLevels.ERROR
        print("|cff00ffffWDIGI:|r Debug mode OFF")
    else
        print("|cff00ffffWDIGI:|r Usage: /wd debug on|off")
    end
end

function WDIGI.Commands.DebugLevel(level)
    if not level then return end
    level = level:upper()

    if WDIGI.DebugLevels and WDIGI.DebugLevels[level] then
        WDIGI.CurrentDebugLevel = WDIGI.DebugLevels[level]
        print("|cff00ffffWDIGI:|r Debug level set to " .. level)
    else
        print("|cffff0000WDIGI:|r Invalid level. Use: TRACE, DEBUG, WARN, ERROR")
    end
end

function WDIGI.Commands.DebugSave()
    if WDIGI_APP_SETTINGS then
        WDIGI_APP_SETTINGS.DebugLog = WDIGI.DebugLog
        print("|cff00ffffWDIGI:|r Debug log saved to SavedVariables.")
    end
end

------------------------------------------------------------
-- UTILITY COMMANDS
------------------------------------------------------------
function WDIGI.Commands.Reload() ReloadUI() end

function WDIGI.Commands.Version()
    print("|cff00ffffWhere Do I Get It?|r Version: " .. (WDIGI.VERSION or "Unknown"))
end

function WDIGI.Commands.Show() 
    if WDIGI.Compendium then WDIGI.Compendium:Toggle() end 
end

function WDIGI.Commands.Hide() 
    if WDIGI.Compendium and WDIGI.Compendium.Frame then WDIGI.Compendium.Frame:Hide() end 
end

------------------------------------------------------------
-- SLASH COMMAND HANDLER (Updated for Experimental Toggle)
------------------------------------------------------------
local function WDIGI_SlashHandler(msg)
    msg = msg:lower():trim()
    local cmd, arg = msg:match("^(%S*)%s*(.-)$")

    -- Check if Compendium is actually enabled in Settings
    local compEnabled = WDIGI.Settings.Get("WDIGI_EnableCompendium_Experimental")

    -- 1. Compendium Commands (Now requires specific 'comp' or 'search' or 'show' call)
    if cmd == "comp" or cmd == "search" or cmd == "show" then
        if compEnabled then
            WDIGI.Commands.Show()
        else
            print("|cff00ffffWDIGI:|r The Search Compendium is currently disabled in settings (Experimental).")
        end

    elseif cmd == "hide" then
        WDIGI.Commands.Hide()

    -- 2. Navigation Commands
    elseif cmd == "pin" then
        WDIGI.Commands.Pin()
    elseif cmd == "nav" and arg == "off" then
        WDIGI.Commands.NavOff()

    -- 3. System & Debug
    elseif cmd == "about" then
        WDIGI.MainFrame:ShowAbout()
    elseif cmd == "clearcache" then
        WDIGI.Commands.ClearCache()
    elseif cmd == "debug" then
        if arg:find("level") then
            local lvl = arg:match("level%s+(%S+)")
            WDIGI.Commands.DebugLevel(lvl)
        elseif arg == "console" then
            WDIGI.Utils.ShowDebugConsole()
        elseif arg == "save" then
            WDIGI.Commands.DebugSave()
        else
            WDIGI.Commands.Debug(arg)
        end
    elseif cmd == "reload" then
        WDIGI.Commands.Reload()
    elseif cmd == "version" then
        WDIGI.Commands.Version()

    -- 4. Default / Help (This is what /wd or /wdigi now shows)
    else
        print("|cff00ffffWhere Do I Get It?|r")
        print("  /wd pin - Set waypoint to current tooltip item")
        print("  /wd nav off - Clear navigation HUD")
        
        if compEnabled then
            print("  /wd comp - Open Experimental Search Compendium")
        end
        
        print("  /wd about - Show Addon Info & Credits")
        print("  /wd reload - Reload UI")
        print("  /wd version - Show current version")
        print("  /wd debug on|off - Toggle debug logs")
    end
end

-- Unified Slash Commands
SLASH_WDIGI1 = "/wdigi"
SLASH_WDIGI2 = "/wd"
SLASH_WDIGI3 = "/comp"
SlashCmdList["WDIGI"] = WDIGI_SlashHandler