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

local ADDON_NAME, WDIGI = ...

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

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

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

    if TooltipDataProcessor then
        TooltipDataProcessor.AddTooltipPostCall(Enum.TooltipDataType.Item, WDIGI.Tooltip.Update)
    else
        GameTooltip:HookScript("OnTooltipSetItem", WDIGI.Tooltip.Update)
    end

    GameTooltip:HookScript("OnHide", function() WDIGI.Tooltip.lastItemGUID = nil end)
    ItemRefTooltip:HookScript("OnHide", function() WDIGI.Tooltip.lastItemGUID = nil end)
end

------------------------------------------------------------
-- ITEM CLICK HANDLER
------------------------------------------------------------
local original_HandleModifiedItemClick = HandleModifiedItemClick

------------------------------------------------------------
-- CTRL-SHFT-LCLICK pin
------------------------------------------------------------
function HandleModifiedItemClick(itemLink)
    if original_HandleModifiedItemClick then
        original_HandleModifiedItemClick(itemLink)
    end

    -- If the user is holding Control + Shift, trigger OUR pin
    if IsControlKeyDown() and IsShiftKeyDown() then
        -- Check if we have tooltip data ready to go
        if WDIGI.Tooltip.bestLocation then
            WDIGI.Utils.Debug("Modifier Click: Triggering WDIGI.Commands.Pin")
            WDIGI.Commands.Pin()
        else
            -- If we don't have a hover-best, try to get the fallback
            -- but let's stick to the Command for consistency
            WDIGI.Commands.Pin()
        end
    end
end

------------------------------------------------------------
-- /wdigi pin
------------------------------------------------------------
function WDIGI.Commands.Pin()
    local best = WDIGI.Tooltip.bestLocation

    -- DEBUG: Trace what the tooltip is holding
    WDIGI.Utils.Debug("Commands.Pin Triggered")
    if not best then
        WDIGI.Utils.Warn("Commands.Pin: WDIGI.Tooltip.bestLocation is NIL")
        print("|cffff0000WDIGI:|r Hover over an item with location data first.")
        return
    end

    WDIGI.Utils.Debug(string.format("  -> Tooltip Best: %s | zID: %s | Coords: %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

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

-- Replace your DebugLevel function with this single, clean version:
function WDIGI.Commands.DebugLevel(level)
    level = level:upper()
    -- Match the table name you defined in debuglevels.lua
    if WDIGI.DebugLevels[level] then
        WDIGI.CurrentDebugLevel = WDIGI.DebugLevels[level]
        print("|cff00ffffWDIGI:|r Debug level set to " .. level)
    else
        print("|cff00ffffWDIGI:|r Invalid level: " .. level)
    end
end

function WDIGI.Commands.Test()
    WDIGI.Utils.Debug("Test command fired!")
    print("|cff00ffffWDIGI:|r Test successful.")
end

function WDIGI.Commands.Reload()
    ReloadUI()
end

------------------------------------------------------------
-- /wdigi show / hide / version / nav off / clearcache
------------------------------------------------------------
function WDIGI.Commands.Show()
    if WDIGI.MainFrame then WDIGI.MainFrame:Show() end
end

function WDIGI.Commands.Hide()
    if WDIGI.MainFrame then WDIGI.MainFrame:Hide() end
end

function WDIGI.Commands.Version()
    print("|cff00ffffWDIGI Version:|r " .. WDIGI.VERSION)
end

function WDIGI.Commands.NavOff()
    if WDIGI.Navigation.HUD then
        WDIGI.Navigation.HUD:Hide()
    end
    C_Map.ClearUserWaypoint()
end

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

------------------------------------------------------------
-- DEBUG LEVEL
------------------------------------------------------------
function WDIGI.Commands.DebugLevel(level)
    level = level:upper()

    if WDIGI.Constants and WDIGI.Constants.LEVEL_ORDER and WDIGI.Constants.LEVEL_ORDER[level] then
        WDIGI.DebugLevel = level
        print("|cff00ffffWDIGI:|r Debug level set to " .. level)
    else
        print("|cffff0000WDIGI:|r Invalid level. Use: trace, debug, warn, error")
    end
end

------------------------------------------------------------
-- DEBUG CONSOLE
------------------------------------------------------------
function WDIGI.Commands.DebugConsole()
    WDIGI.Utils.ShowDebugConsole()
end

------------------------------------------------------------
-- SAVE LOG TO SAVEDVARIABLES
------------------------------------------------------------
function WDIGI.Commands.DebugSave()
    WDIGI_APP_SETTINGS.DebugLog = WDIGI.DebugLog
    print("|cff00ffffWDIGI:|r Debug log saved to SavedVariables.")
end

------------------------------------------------------------
-- SLASH COMMAND PARSER (Corrected Order)
------------------------------------------------------------
function WDIGI.Commands.Reload()
    ReloadUI()
end

function WDIGI.Commands.Test()
    WDIGI.Utils.Info("Running WDIGI Test...")
    -- Add any test logic here, like a fake tooltip update
    print("|cff00ffffWDIGI:|r Test command executed successfully.")
end

local function WDIGI_SlashHandler(msg)
    msg = msg:lower() or ""

    if msg == "" or msg == "show" then
        WDIGI.Commands.Show()

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

    elseif msg == "version" then
        WDIGI.Commands.Version()

    elseif msg == "pin" then
        WDIGI.Commands.Pin()

    elseif msg == "nav off" then
        WDIGI.Commands.NavOff()

    elseif msg == "clearcache" then
        WDIGI.Commands.ClearCache()

    --------------------------------------------------------
    -- DEBUG LEVEL (must come BEFORE debug on/off)
    --------------------------------------------------------
    elseif msg:match("^debug level") then
        local lvl = msg:match("debug level%s+(%S+)")
        WDIGI.Commands.DebugLevel(lvl)

    --------------------------------------------------------
    -- DEBUG CONSOLE
    --------------------------------------------------------
    elseif msg == "debug console" then
        WDIGI.Commands.DebugConsole()

    --------------------------------------------------------
    -- DEBUG SAVE
    --------------------------------------------------------
    elseif msg == "debug save" then
        WDIGI.Commands.DebugSave()

    --------------------------------------------------------
    -- DEBUG ON/OFF (must come AFTER debug level)
    --------------------------------------------------------
    elseif msg:sub(1,5) == "debug" then
        local arg = msg:match("debug%s+(%S+)")
        WDIGI.Commands.Debug(arg)

    elseif msg == "reload" then
        WDIGI.Commands.Reload()

    elseif msg == "test" then
        WDIGI.Commands.Test()

    else
        print("|cff00ffffWDIGI Commands:|r")
        print("  /wdigi show        - Show main window")
        print("  /wdigi hide        - Hide main window")
        print("  /wdigi pin         - Set pin from hovered tooltip")
        print("  /wdigi nav off     - Hide navigation HUD")
        print("  /wdigi version     - Show version")
        print("  /wdigi clearcache  - Clear parsed data cache")
        print("  /wdigi debug on/off")
        print("  /wdigi debug level trace|debug|warn|error")
        print("  /wdigi debug console")
        print("  /wdigi debug save")
        print("  /wdigi reload")
        print("  /wdigi test")
    end
end

SLASH_WDIGI1 = "/wdigi"
SLASH_WDIGI2 = "/wd"
SLASH_WDIGI3 = "/wheredoi"
SLASH_WDIGI4 = "/wheredoigetit"
SlashCmdList["WDIGI"] = WDIGI_SlashHandler
