local _, ns = ...

ns.Commands = {}

local function normalize(msg)
    return string.lower((msg or ""):gsub("^%s+", ""):gsub("%s+$", ""))
end

local function showHelp()
    ns.Utils:Print("Commands: /aa, /angler reset, /angler session, /angler export, /angler void, /angler compact, /angler watcher, /angler atlas, /angler equipment, /angler tackle, /angler gear, /angler restore, /angler sleep, /angler wake, /angler lure next, /angler lure prev, /angler mini, /angler nearby, /angler nearby map, /angler nearby ping, /angler debug, /angler debug clear, /angler options")
end

function ns.Commands:Handle(msg)
    msg = normalize(msg)
    if msg == "" then ns.UI:ToggleMain() return end
    if msg == "reset" then ns.Session:Reset() ns.Utils:Print("Current session reset.") return end
    if msg == "compact" then ns.UI:ToggleCompact() return end
    if msg == "debug" then ns.UI:ToggleDebug() return end
    if msg == "debug clear" then
        if ns.Debug and ns.Debug.Clear then ns.Debug:Clear() end
        if ns.UI and ns.UI.RefreshDebug then ns.UI:RefreshDebug() end
        ns.Utils:Print("Debug log cleared.")
        return
    end
    if msg == "watcher" then ns.UI:Open("Watcher") return end
    if msg == "atlas" or msg == "zone" then ns.UI:Open("Atlas") return end
    if msg == "equipment" or msg == "equip" then ns.UI:Open("Equipment") return end
    if msg == "tackle" or msg == "lure" then ns.UI:Open("Tackle") return end
    if msg == "lure next" then
        if ns.Fishing and ns.Fishing.CyclePreferredLure then
            local lure = ns.Fishing:CyclePreferredLure(1)
            if lure then ns.Utils:Print("Selected lure: " .. tostring(lure.name)) end
        end
        return
    end
    if msg == "lure prev" then
        if ns.Fishing and ns.Fishing.CyclePreferredLure then
            local lure = ns.Fishing:CyclePreferredLure(-1)
            if lure then ns.Utils:Print("Selected lure: " .. tostring(lure.name)) end
        end
        return
    end
    if msg == "mini" or msg == "minimap" then
        if ns.Minimap and ns.Minimap.ToggleVisibility then ns.Minimap:ToggleVisibility() end
        return
    end
    if msg == "nearby" then
        if ns.Nearby and ns.Nearby.ToggleEnabled then
            ns.Nearby:ToggleEnabled()
        else
            ns.Utils:Print("Nearby module is unavailable.")
        end
        return
    end
    if msg == "nearby map" then
        if ns.Nearby and ns.Nearby.ToggleMinimapMarkers then
            ns.Nearby:ToggleMinimapMarkers()
        else
            ns.Utils:Print("Nearby module is unavailable.")
        end
        return
    end
    if msg == "nearby ping" then
        if ns.Nearby and ns.Nearby.BroadcastPing then
            if ns.Nearby:BroadcastPing() then
                ns.Utils:Print("Nearby ping sent.")
            else
                ns.Utils:Print("Nearby ping failed. Try again in a moment.")
            end
        else
            ns.Utils:Print("Nearby module is unavailable.")
        end
        return
    end
    if msg == "sleep" then
        if ns.Fishing and ns.Fishing.SetSleeping then ns.Fishing:SetSleeping(true, "command") end
        return
    end
    if msg == "wake" then
        if ns.Fishing and ns.Fishing.SetSleeping then ns.Fishing:SetSleeping(false, "command") end
        return
    end
    if msg == "gear" then ns.Fishing:EquipPreferredSet() return end
    if msg == "restore" then ns.Fishing:RestorePreviousSet() return end
    if msg == "export" then
        local current = ns.DB.currentSession
        local top = ns.Tracking.GetSessionTopItems and ns.Tracking:GetSessionTopItems(5) or {}
        local elapsed = ns.Session.GetElapsed and ns.Session:GetElapsed() or 0
        local lines = {
            "=== Azeroth Angler Export ===",
            "Zone: " .. tostring(current.zone or "Unknown"),
            "Elapsed: " .. ns.Utils:FormatDuration(elapsed),
            "Casts: " .. tostring(current.casts or 0),
            "Catches: " .. tostring(current.catches or 0) .. " (" .. ns.Utils:GetSuccessRate(current.catches, current.casts) .. ")",
            "Pool: " .. tostring(current.poolCatches or 0) .. "  /  Open Water: " .. tostring(current.openWaterCatches or 0),
            "Rare Catches: " .. tostring(current.rareCatches or 0),
        }
        if #top > 0 then
            lines[#lines+1] = "Top Catches:"
            for i, row in ipairs(top) do
                lines[#lines+1] = string.format("  %d. %s x%d", i, tostring(row.display or row.name or "?"), row.count or 0)
            end
        end
        local text = table.concat(lines, "\n")
        if C_Clipboard and C_Clipboard.SetClipboardText then
            C_Clipboard.SetClipboardText(text)
            ns.Utils:Print("Session exported to clipboard.")
        else
            for _, line in ipairs(lines) do ns.Utils:Print(line) end
        end
        return
    end
    if msg == "void" then
        if ns.Fishing and ns.Fishing.GetVoidFinderButton then
            if InCombatLockdown() then
                ns.Utils:Print("Cannot use Void Finder in combat.")
                return
            end
            local btn = ns.Fishing:GetVoidFinderButton()
            if btn and btn.Click then
                btn:Click()
                ns.Utils:Print("|cff9966FFVoid Finder:|r Scanning for Hyper-Compressed vortex...")
            end
        end
        return
    end
    if msg == "session" then
        if ns.DB.currentSession.active then ns.Session:Stop(true) ns.Utils:Print("Session ended and saved.") else ns.Session:Start() ns.Utils:Print("Session started.") end
        return
    end
    if msg == "options" then
        if Settings and Settings.OpenToCategory and ns.Settings and ns.Settings.categoryID then
            Settings.OpenToCategory(ns.Settings.categoryID)
            Settings.OpenToCategory(ns.Settings.categoryID)
            return
        end
    end
    showHelp()
end

SLASH_AZEROTHANGLER1 = "/aa"
SLASH_AZEROTHANGLER2 = "/angler"
SLASH_AZEROTHANGLER3 = "/azerothangler"
SlashCmdList["AZEROTHANGLER"] = function(msg) ns.Commands:Handle(msg) end
