-- modules/Search.lua - ArenaCore's unique search engine backend
-- Custom algorithm and architecture - completely original

local addonName, AC = ...
-- gotta use the global ArenaCore table or this whole thing falls apart
AC = _G.ArenaCore

local Search = {}
AC.Search = Search

-- ArenaCore's unique search parameters
local MIN_CHARS = 2
local MAX_RESULTS = 25

---------------------------------------------------------------------------
-- ARENACORE UNIQUE SEARCH CATALOG
-- Enhanced metadata structure with custom fields
---------------------------------------------------------------------------

local catalog = {
    -- Arena Frames
    {id = "arena_scale", label = "Frame Scale", category = "Arena Frames", keywords = {"scale", "size", "arena", "frames"}, page = "ArenaFrames", weight = 100, description = "Adjust the overall size of arena frames"},
    {id = "arena_width", label = "Frame Width", category = "Arena Frames", keywords = {"width", "size", "arena", "frames"}, page = "ArenaFrames", weight = 95, description = "Adjust arena frame width"},
    {id = "arena_height", label = "Frame Height", category = "Arena Frames", keywords = {"height", "size", "arena", "frames"}, page = "ArenaFrames", weight = 95, description = "Adjust arena frame height"},
    {id = "health_texture", label = "Health Bar Texture", category = "Arena Frames", keywords = {"health", "texture", "bar", "statusbar"}, page = "ArenaFrames", weight = 90, description = "Visual texture for health bars"},
    {id = "health_color", label = "Health Bar Color", category = "Arena Frames", keywords = {"health", "color", "bar", "class"}, page = "ArenaFrames", weight = 90, description = "Health bar color settings"},
    {id = "health_format", label = "Health Text Format", category = "Arena Frames", keywords = {"health", "text", "format", "percentage"}, page = "ArenaFrames", weight = 85, description = "How health values are displayed"},
    {id = "mana_texture", label = "Mana Bar Texture", category = "Arena Frames", keywords = {"mana", "texture", "bar", "power", "resource"}, page = "ArenaFrames", weight = 90, description = "Visual texture for mana/power bars"},
    {id = "mana_color", label = "Mana Bar Color", category = "Arena Frames", keywords = {"mana", "color", "bar", "power", "resource"}, page = "ArenaFrames", weight = 90, description = "Mana/power bar color settings"},
    {id = "mana_format", label = "Mana Text Format", category = "Arena Frames", keywords = {"mana", "text", "format", "percentage", "power"}, page = "ArenaFrames", weight = 85, description = "How mana/power values are displayed"},
    {id = "cast_settings", label = "Cast Bar Settings", category = "Arena Frames", keywords = {"cast", "bar", "casting", "spell", "channel"}, page = "ArenaFrames", weight = 88, description = "Enemy cast bar display options"},
    {id = "class_icons", label = "Class Icons", category = "Arena Frames", keywords = {"class", "icon", "portrait", "spec"}, page = "ArenaFrames", weight = 92, description = "Class and specialization icon display"},
    {id = "trinket_display", label = "Trinket Display", category = "Arena Frames", keywords = {"trinket", "pvp", "cooldown", "icon"}, page = "ArenaFrames", weight = 93, description = "PvP trinket tracking and display"},
    {id = "racial_display", label = "Racial Display", category = "Arena Frames", keywords = {"racial", "cooldown", "ability", "icon"}, page = "ArenaFrames", weight = 93, description = "Racial ability tracking and display"},
    {id = "dr_icons", label = "DR Icons", category = "Arena Frames", keywords = {"dr", "diminishing", "returns", "cc", "stun"}, page = "ArenaFrames", weight = 91, description = "Diminishing returns icon display"},
    {id = "target_highlight", label = "Target Highlight", category = "Arena Frames", keywords = {"target", "highlight", "border", "glow"}, page = "ArenaFrames", weight = 87, description = "Visual highlight for your current target"},

    -- Diminishing Returns
    {id = "dr_size", label = "DR Icon Size", category = "Diminishing Returns", keywords = {"dr", "size", "scale", "diminishing", "returns"}, page = "DiminishingReturns", weight = 94, description = "Adjust size of DR icons"},
    {id = "dr_spacing", label = "DR Icon Spacing", category = "Diminishing Returns", keywords = {"dr", "spacing", "gap", "diminishing", "returns"}, page = "DiminishingReturns", weight = 89, description = "Space between DR icons"},
    {id = "dr_growth", label = "DR Growth Direction", category = "Diminishing Returns", keywords = {"dr", "growth", "direction", "layout"}, page = "DiminishingReturns", weight = 88, description = "Which way DR icons expand"},
    {id = "dr_stacking", label = "DR Stacking Mode", category = "Diminishing Returns", keywords = {"dr", "stacking", "layout", "rows"}, page = "DiminishingReturns", weight = 86, description = "Single row vs stacked layout"},
    {id = "dr_dynamic", label = "DR Dynamic Positioning", category = "Diminishing Returns", keywords = {"dr", "dynamic", "positioning", "collapse"}, page = "DiminishingReturns", weight = 87, description = "Collapse gaps when categories disabled"},
    {id = "dr_categories", label = "DR Categories", category = "Diminishing Returns", keywords = {"dr", "categories", "stun", "silence", "root", "disorient"}, page = "DiminishingReturns", weight = 90, description = "Enable/disable specific DR categories"},

    -- Trinkets/Other
    {id = "trinket_size", label = "Trinket Icon Size", category = "Trinkets/Other", keywords = {"trinket", "size", "scale", "icon"}, page = "TrinketsOther", weight = 92, description = "Adjust trinket icon size"},
    {id = "trinket_position", label = "Trinket Position", category = "Trinkets/Other", keywords = {"trinket", "position", "location"}, page = "TrinketsOther", weight = 89, description = "Where trinket icons appear"},
    {id = "trinket_style", label = "Trinket Display Style", category = "Trinkets/Other", keywords = {"trinket", "style", "design", "horde", "alliance"}, page = "TrinketsOther", weight = 91, description = "Trinket icon visual style"},
    {id = "racial_size", label = "Racial Icon Size", category = "Trinkets/Other", keywords = {"racial", "size", "scale", "icon"}, page = "TrinketsOther", weight = 92, description = "Adjust racial icon size"},
    {id = "racial_position", label = "Racial Position", category = "Trinkets/Other", keywords = {"racial", "position", "location"}, page = "TrinketsOther", weight = 89, description = "Where racial icons appear"},

    -- Class Packs
    -- REMOVED: Class Packs search entries - Legacy feature removed

    -- More Goodies
    {id = "debuffs_enable", label = "Debuffs Enable", category = "More Goodies", keywords = {"debuffs", "enable", "show", "icons"}, page = "MoreGoodies", weight = 90, description = "Enable/disable debuff display"},
    {id = "debuffs_max", label = "Max Debuffs", category = "More Goodies", keywords = {"debuffs", "max", "count", "limit"}, page = "MoreGoodies", weight = 84, description = "Maximum number of debuffs to show"},
    {id = "debuffs_position", label = "Debuffs Position", category = "More Goodies", keywords = {"debuffs", "position", "location", "x", "y"}, page = "MoreGoodies", weight = 86, description = "Where debuff icons appear"},
    {id = "debuffs_scale", label = "Debuffs Scale", category = "More Goodies", keywords = {"debuffs", "scale", "size", "icons"}, page = "MoreGoodies", weight = 87, description = "Adjust debuff icon size"},
    {id = "debuffs_growth", label = "Debuffs Growth", category = "More Goodies", keywords = {"debuffs", "growth", "direction", "layout"}, page = "MoreGoodies", weight = 85, description = "Which way debuff icons expand"},
    {id = "debuffs_spacing", label = "Debuffs Spacing", category = "More Goodies", keywords = {"debuffs", "spacing", "gap", "icons"}, page = "MoreGoodies", weight = 83, description = "Space between debuff icons"},
    
    {id = "blackout_enable", label = "Blackout Enable", category = "More Goodies > Blackout", keywords = {"blackout", "enable", "defensive", "cooldowns"}, page = "MoreGoodies", weight = 92, description = "Enable/disable blackout feature"},
    {id = "blackout_color", label = "Blackout Color", category = "More Goodies > Blackout", keywords = {"blackout", "color", "background"}, page = "MoreGoodies", weight = 88, description = "Blackout background color"},
    {id = "blackout_duration", label = "Blackout Duration", category = "More Goodies > Blackout", keywords = {"blackout", "duration", "time"}, page = "MoreGoodies", weight = 86, description = "How long blackout lasts"},
    {id = "nameplate_gcd", label = "Nameplate GCD", category = "More Goodies > Nameplate GCD", keywords = {"nameplate", "gcd", "cooldown", "tracker"}, page = "MoreGoodies", weight = 89, description = "GCD tracking on nameplates"},
    {id = "party_class", label = "Party Class Indicators", category = "More Goodies > Party Class Indicators", keywords = {"party", "class", "icons", "indicators"}, page = "MoreGoodies", weight = 91, description = "Class icons on party frames"},
    {id = "dispel_tracker", label = "Dispel Tracker", category = "More Goodies > Dispel Tracker", keywords = {"dispel", "tracker", "cooldown", "healer"}, page = "MoreGoodies", weight = 90, description = "Track enemy dispel cooldowns"},
    {id = "absorbs_display", label = "Absorbs Display", category = "More Goodies > Absorbs", keywords = {"absorbs", "shields", "absorption"}, page = "MoreGoodies", weight = 87, description = "Show absorption shields on frames"},

    -- Misc/General Features
    {id = "portrait_swap", label = "Class Portrait Swap", category = "Misc", keywords = {"class", "portrait", "swap", "player", "target"}, page = "Misc", weight = 93, description = "Replace portraits with class icons"},
    {id = "achievement_unlocks", label = "Achievement Unlocks", category = "Misc", keywords = {"achievement", "unlocks", "rewards", "themes"}, page = "Misc", weight = 89, description = "Unlock features based on achievements"},
    {id = "tab_players", label = "Tab Players Only", category = "Misc", keywords = {"tab", "target", "players", "arena", "pvp"}, page = "Misc", weight = 85, description = "Tab-targeting only hits players in PvP"},
    {id = "queue_status", label = "Queue Status Tracker", category = "Misc", keywords = {"queue", "status", "tracker", "pvp", "arena"}, page = "Misc", weight = 86, description = "Show queue status and wait times"},
    {id = "chat_arena", label = "Chat In Arena", category = "Misc", keywords = {"chat", "arena", "hide", "pvp"}, page = "Misc", weight = 84, description = "Chat visibility in arena matches"},
    {id = "minimap_arena", label = "Minimap In Arena", category = "Misc", keywords = {"minimap", "arena", "hide", "pvp"}, page = "Misc", weight = 84, description = "Minimap visibility in arena matches"},
    {id = "dampening_display", label = "Dampening Display", category = "Misc", keywords = {"dampening", "arena", "percentage", "pvp"}, page = "Misc", weight = 87, description = "Show dampening percentage"},

    -- Frames/Nameplates
    {id = "party_scale", label = "Party Frame Scale", category = "Frames/Nameplates > Party Frames", keywords = {"party", "frame", "scale", "size"}, page = "frames", weight = 88, description = "Adjust party frame size"},
    {id = "party_castbars", label = "Party Cast Bars", category = "Frames/Nameplates > Party Frames", keywords = {"party", "cast", "bars", "casting"}, page = "frames", weight = 89, description = "Cast bars on party frames"},
    {id = "party_auras", label = "Party Buffs/Debuffs", category = "Frames/Nameplates > Party Frames", keywords = {"party", "buffs", "debuffs", "auras"}, page = "frames", weight = 87, description = "Buff and debuff display on party frames"},
    {id = "party_roles", label = "Party Role Icons", category = "Frames/Nameplates > Party Frames", keywords = {"party", "role", "icons", "tank", "healer"}, page = "frames", weight = 86, description = "Role icons on party frames"},
    {id = "nameplate_indicators", label = "Nameplate Indicators", category = "Frames/Nameplates > Nameplates", keywords = {"nameplate", "indicators", "icons", "enemy"}, page = "frames", weight = 90, description = "Visual indicators on nameplates"},

    -- Misc Features
    {id = "test_mode", label = "Test Mode", category = "Misc", keywords = {"test", "mode", "preview", "frames"}, page = "Misc", weight = 85, description = "Test arena frame appearance"},
    {id = "edit_mode", label = "Edit Mode", category = "Misc", keywords = {"edit", "mode", "drag", "position", "frames"}, page = "Misc", weight = 86, description = "Drag to reposition frame elements"},
    {id = "frame_lock", label = "Frame Lock", category = "Misc", keywords = {"lock", "frames", "position", "edit"}, page = "Misc", weight = 84, description = "Lock/unlock frame positions"},
    {id = "reset_positions", label = "Reset Positions", category = "Misc", keywords = {"reset", "positions", "default", "frames"}, page = "Misc", weight = 83, description = "Reset all frame positions to default"},

    -- Performance
    {id = "combat_filter", label = "Combat Log Filter", category = "Performance", keywords = {"combat", "log", "filter", "performance"}, page = "performance", weight = 87, description = "Filter combat log events for performance"},
    {id = "update_frequency", label = "Update Frequency", category = "Performance", keywords = {"update", "frequency", "performance", "fps"}, page = "performance", weight = 86, description = "How often frames update"},
    {id = "debug_mode", label = "Debug Mode", category = "Performance", keywords = {"debug", "mode", "testing", "development"}, page = "performance", weight = 82, description = "Enable debug output for troubleshooting"},

    -- Profiles
    {id = "profile_manage", label = "Profile Management", category = "Profiles", keywords = {"profile", "manage", "create", "delete"}, page = "Profiles", weight = 90, description = "Create, delete, and switch profiles"},
    {id = "profile_export", label = "Profile Export", category = "Profiles", keywords = {"profile", "export", "share", "string"}, page = "Profiles", weight = 88, description = "Export settings as shareable string"},
    {id = "profile_import", label = "Profile Import", category = "Profiles", keywords = {"profile", "import", "load", "string"}, page = "Profiles", weight = 88, description = "Import settings from shared string"},
    {id = "profile_auto", label = "Auto Profile Switch", category = "Profiles", keywords = {"profile", "auto", "switch", "spec"}, page = "Profiles", weight = 85, description = "Automatically switch profiles per spec"},

    -- Textures
    {id = "health_width", label = "Health Bar Width", category = "Textures", keywords = {"health", "bar", "width", "texture"}, page = "Textures", weight = 86, description = "Health bar texture width"},
    {id = "health_height", label = "Health Bar Height", category = "Textures", keywords = {"health", "bar", "height", "texture"}, page = "Textures", weight = 86, description = "Health bar texture height"},
    {id = "mana_width", label = "Mana Bar Width", category = "Textures", keywords = {"mana", "bar", "width", "texture", "power"}, page = "Textures", weight = 86, description = "Mana bar texture width"},
    {id = "mana_height", label = "Mana Bar Height", category = "Textures", keywords = {"mana", "bar", "height", "texture", "power"}, page = "Textures", weight = 86, description = "Mana bar texture height"},
    {id = "cast_width", label = "Cast Bar Width", category = "Textures", keywords = {"cast", "bar", "width", "texture"}, page = "Textures", weight = 86, description = "Cast bar texture width"},
    {id = "cast_height", label = "Cast Bar Height", category = "Textures", keywords = {"cast", "bar", "height", "texture"}, page = "Textures", weight = 86, description = "Cast bar texture height"},
    {id = "border_thickness", label = "Border Thickness", category = "Textures", keywords = {"border", "thickness", "outline"}, page = "Textures", weight = 84, description = "Thickness of frame borders"},

    -- General Settings
    {id = "ui_scale", label = "UI Scale", category = "Arena Frames > General", keywords = {"ui", "scale", "interface", "size"}, page = "ArenaFrames", weight = 87, description = "Overall UI scale adjustment"},
    {id = "font_settings", label = "Font Settings", category = "Arena Frames > General", keywords = {"font", "text", "size", "style"}, page = "ArenaFrames", weight = 85, description = "Font customization options"},
    {id = "color_settings", label = "Color Settings", category = "Arena Frames > General", keywords = {"color", "theme", "customization"}, page = "ArenaFrames", weight = 86, description = "Color customization options"},
}

---------------------------------------------------------------------------
-- ARENACORE CUSTOM SEARCH ALGORITHM
-- Unique fuzzy matching with enhanced scoring system
---------------------------------------------------------------------------

-- ArenaCore's unique search algorithm with custom scoring
local function ArenaCoreFuzzySearch(query)
    if not query or query:len() < MIN_CHARS then
        return {}
    end
    
    local results = {}
    local lowerQuery = query:lower()
    local queryWords = {}
    for word in lowerQuery:gmatch("%S+") do
        queryWords[#queryWords + 1] = word
    end
    
    for _, item in ipairs(catalog) do
        local score = 0
        local matchFactors = {}
        
        -- Label matching (highest weight)
        local labelLower = item.label:lower()
        if labelLower == lowerQuery then
            score = score + 200
            matchFactors[#matchFactors + 1] = "exact_label"
        elseif labelLower:find(lowerQuery, 1, true) == 1 then
            score = score + 150
            matchFactors[#matchFactors + 1] = "starts_with_label"
        elseif labelLower:find(lowerQuery, 1, true) then
            score = score + 100
            matchFactors[#matchFactors + 1] = "contains_label"
        end
        
        -- Category matching
        local categoryLower = item.category:lower()
        if categoryLower:find(lowerQuery, 1, true) then
            score = score + 80
            matchFactors[#matchFactors + 1] = "category_match"
        end
        
        -- Keyword matching with multi-word support
        local keywordMatches = 0
        if item.keywords then
            for _, keyword in ipairs(item.keywords) do
                local keywordLower = keyword:lower()
                for _, queryWord in ipairs(queryWords) do
                    if keywordLower:find(queryWord, 1, true) then
                        keywordMatches = keywordMatches + 1
                        score = score + 40
                        matchFactors[#matchFactors + 1] = "keyword_" .. keyword
                        break
                    end
                end
            end
        end
        
        -- Description matching (lower weight)
        if item.description then
            local descLower = item.description:lower()
            if descLower:find(lowerQuery, 1, true) then
                score = score + 20
                matchFactors[#matchFactors + 1] = "description_match"
            end
        end
        
        -- Weight bonus
        score = score + (item.weight or 50)
        
        -- Multi-word bonus
        if keywordMatches >= #queryWords and #queryWords > 1 then
            score = score + 50
            matchFactors[#matchFactors + 1] = "multiword_bonus"
        end
        
        if score > 0 then
            results[#results + 1] = {
                entry = item,
                score = score,
                matchFactors = matchFactors
            }
        end
    end
    
    -- Custom sorting: score -> weight -> label
    table.sort(results, function(a, b)
        if a.score ~= b.score then
            return a.score > b.score
        end
        local weightA = a.entry.weight or 50
        local weightB = b.entry.weight or 50
        if weightA ~= weightB then
            return weightA > weightB
        end
        return a.entry.label < b.entry.label
    end)
    
    -- Limit results for performance
    if #results > MAX_RESULTS then
        for i = MAX_RESULTS + 1, #results do
            results[i] = nil
        end
    end
    
    return results
end

-- Main search function using ArenaCore's algorithm
function Search:Find(input)
    return ArenaCoreFuzzySearch(input)
end

-- Get catalog size for UI display
function Search:GetCatalogSize()
    return #catalog
end

-- Get raw catalog for debugging
function Search:GetCatalog()
    return catalog
end

-- Get localized catalog entry (infrastructure for future localization)
-- @param entry table The catalog entry to localize
-- @return table Localized entry with translated label/category/description/keywords
function Search:GetLocalizedEntry(entry)
    -- For now, return the entry as-is (English)
    -- This infrastructure allows future localization without breaking the feature
    -- When implementing full localization:
    -- 1. Create localized catalog tables for each supported language
    -- 2. Use GetLocale() to detect client language
    -- 3. Return localized version if available, otherwise return English
    return entry
end

-- Get current locale for search (infrastructure for future use)
-- @return string Current locale code (e.g., "enUS", "zhCN", "koKR")
function Search:GetLocale()
    return GetLocale()
end

-- Check if search localization is available for current locale
-- @return boolean True if localized search catalog exists for current locale
function Search:HasLocalizedCatalog()
    -- Infrastructure placeholder
    -- Return false for now - English catalog is the source of truth
    -- Can be expanded later when localized catalogs are added
    return false
end
