-------------------------
-- AiB Utility Functions
-------------------------

AiB = AiB or {}
AiB.Utils = {}

-------------------------
-- STRING UTILITIES
-------------------------
function AiB.Utils:ColorText(text, color)
    if type(color) == "table" then
        local r = math.floor((color[1] or 1) * 255)
        local g = math.floor((color[2] or 1) * 255)
        local b = math.floor((color[3] or 1) * 255)
        return string.format("|cFF%02X%02X%02X%s|r", r, g, b, text)
    elseif type(color) == "string" then
        return "|c" .. color .. text .. "|r"
    end
    return text
end

function AiB.Utils:TruncateString(str, maxLength)
    if #str <= maxLength then
        return str
    end
    return str:sub(1, maxLength - 3) .. "..."
end

function AiB.Utils:FormatNumber(num)
    if num >= 1000000 then
        return string.format("%.1fM", num / 1000000)
    elseif num >= 1000 then
        return string.format("%.1fK", num / 1000)
    end
    return tostring(num)
end

-------------------------
-- TABLE UTILITIES
-------------------------
function AiB.Utils:TableCopy(orig)
    local copy
    if type(orig) == 'table' then
        copy = {}
        for k, v in pairs(orig) do
            copy[k] = self:TableCopy(v)
        end
    else
        copy = orig
    end
    return copy
end

function AiB.Utils:TableMerge(t1, t2)
    for k, v in pairs(t2) do
        if type(v) == "table" and type(t1[k]) == "table" then
            self:TableMerge(t1[k], v)
        else
            t1[k] = v
        end
    end
    return t1
end

function AiB.Utils:TableContains(table, value)
    for _, v in pairs(table) do
        if v == value then
            return true
        end
    end
    return false
end

-------------------------
-- UI UTILITIES
-------------------------
function AiB.Utils:CreateBackdrop(parent, bgFile, edgeFile, edgeSize)
    bgFile = bgFile or "Interface\\Buttons\\WHITE8x8"
    edgeFile = edgeFile or "Interface\\Buttons\\WHITE8x8"
    edgeSize = edgeSize or 2
    
    return {
        bgFile = bgFile,
        edgeFile = edgeFile,
        edgeSize = edgeSize,
        insets = { left = edgeSize, right = edgeSize, top = edgeSize, bottom = edgeSize }
    }
end

function AiB.Utils:CreateButton(parent, width, height, text, onClick)
    local button = CreateFrame("Button", nil, parent, "UIPanelButtonTemplate")
    button:SetSize(width, height)
    button:SetText(text or "")
    
    if onClick then
        button:SetScript("OnClick", onClick)
    end
    
    -- Apply theme
    if AiB.Themes then
        local bg = button:CreateTexture(nil, "BACKGROUND")
        bg:SetAllPoints()
        AiB.Themes:ApplyToTexture(bg, "button_normal")
        button:SetNormalTexture(bg)
        
        local fs = button:GetFontString()
        if fs then
            AiB.Themes:ApplyToText(fs, "text_primary")
        end
    end
    
    -- Add hover effect
    if AiB.Animations then
        AiB.Animations:AddHoverEffect(button, 1.05)
    end
    
    return button
end

function AiB.Utils:CreateCheckbox(parent, text, default, onChange)
    local checkbox = CreateFrame("CheckButton", nil, parent, "UICheckButtonTemplate")
    checkbox:SetSize(24, 24)
    checkbox:SetChecked(default or false)
    
    if text then
        checkbox.text = checkbox:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        checkbox.text:SetPoint("LEFT", checkbox, "RIGHT", 5, 0)
        checkbox.text:SetText(text)
        
        if AiB.Themes then
            AiB.Themes:ApplyToText(checkbox.text, "text_primary")
        end
    end
    
    if onChange then
        checkbox:SetScript("OnClick", function(self)
            onChange(self:GetChecked())
        end)
    end
    
    return checkbox
end

function AiB.Utils:CreateSlider(parent, minVal, maxVal, step, default, onChange)
    local slider = CreateFrame("Slider", nil, parent, "OptionsSliderTemplate")
    slider:SetMinMaxValues(minVal, maxVal)
    slider:SetValueStep(step)
    slider:SetValue(default or minVal)
    slider:SetObeyStepOnDrag(true)
    
    if onChange then
        slider:SetScript("OnValueChanged", function(self, value)
            onChange(value)
        end)
    end
    
    return slider
end

function AiB.Utils:CreateDropdown(parent, width, items, default, onChange)
    local dropdown = CreateFrame("Frame", nil, parent, "UIDropDownMenuTemplate")
    dropdown:SetWidth(width or 150)
    
    UIDropDownMenu_SetWidth(dropdown, width or 150)
    
    local function OnClick(self)
        UIDropDownMenu_SetSelectedID(dropdown, self:GetID())
        if onChange then
            onChange(self.value)
        end
    end
    
    local function Initialize(self, level)
        local info = UIDropDownMenu_CreateInfo()
        for i, item in ipairs(items) do
            info.text = item.text or item
            info.value = item.value or item
            info.func = OnClick
            UIDropDownMenu_AddButton(info)
        end
    end
    
    UIDropDownMenu_Initialize(dropdown, Initialize)
    UIDropDownMenu_SetSelectedID(dropdown, default or 1)
    
    return dropdown
end

-------------------------
-- ICON UTILITIES
-------------------------
function AiB.Utils:CreateIcon(parent, size, texture, point)
    local icon = parent:CreateTexture(nil, "ARTWORK")
    icon:SetSize(size, size)
    
    if point then
        icon:SetPoint(unpack(point))
    end
    
    if texture then
        icon:SetTexture(texture)
    end
    
    icon:SetTexCoord(0.08, 0.92, 0.08, 0.92) -- Rounded corners
    
    return icon
end

function AiB.Utils:AddIconBorder(icon, color)
    if icon.border then return icon.border end
    
    local border = icon:GetParent():CreateTexture(nil, "OVERLAY")
    border:SetPoint("TOPLEFT", icon, "TOPLEFT", -1, 1)
    border:SetPoint("BOTTOMRIGHT", icon, "BOTTOMRIGHT", 1, -1)
    border:SetColorTexture(unpack(color or {1, 1, 1, 1}))
    
    icon.border = border
    return border
end

-------------------------
-- TOOLTIP UTILITIES
-------------------------
function AiB.Utils:AddTooltip(frame, title, text, anchor)
    anchor = anchor or "ANCHOR_RIGHT"
    
    frame:SetScript("OnEnter", function(self)
        GameTooltip:SetOwner(self, anchor)
        
        if title then
            GameTooltip:AddLine(title, 1, 1, 1)
        end
        
        if text then
            GameTooltip:AddLine(text, 0.8, 0.8, 0.8, true)
        end
        
        GameTooltip:Show()
    end)
    
    frame:SetScript("OnLeave", function()
        GameTooltip:Hide()
    end)
end

function AiB.Utils:AddDetailedTooltip(frame, data, anchor)
    anchor = anchor or "ANCHOR_RIGHT"
    
    frame:SetScript("OnEnter", function(self)
        GameTooltip:SetOwner(self, anchor)
        
        if data.title then
            GameTooltip:AddLine(data.title, 1, 1, 1)
        end
        
        if data.subtitle then
            GameTooltip:AddLine(data.subtitle, 0.7, 0.7, 0.7)
        end
        
        if data.lines then
            GameTooltip:AddLine(" ")
            for _, line in ipairs(data.lines) do
                local color = line.color or {1, 1, 1}
                GameTooltip:AddLine(line.text, color[1], color[2], color[3])
            end
        end
        
        if data.footer then
            GameTooltip:AddLine(" ")
            GameTooltip:AddLine(data.footer, 0.5, 0.5, 0.5)
        end
        
        GameTooltip:Show()
    end)
    
    frame:SetScript("OnLeave", function()
        GameTooltip:Hide()
    end)
end

-------------------------
-- SOUND UTILITIES
-------------------------
function AiB.Utils:PlaySound(soundID)
    if soundID then
        PlaySound(soundID)
    end
end

-- Common UI Sounds
AiB.Utils.Sounds = {
    CLICK = SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON,
    HOVER = SOUNDKIT.IG_MAINMENU_OPTION,
    OPEN = SOUNDKIT.IG_CHARACTER_INFO_OPEN,
    CLOSE = SOUNDKIT.IG_CHARACTER_INFO_CLOSE,
    TAB = SOUNDKIT.IG_CHARACTER_INFO_TAB,
    ERROR = SOUNDKIT.IG_QUEST_LOG_ABANDON_QUEST,
}

-------------------------
-- SCROLL FRAME UTILITY
-------------------------
function AiB.Utils:CreateScrollFrame(parent, width, height)
    local scrollFrame = CreateFrame("ScrollFrame", nil, parent, "UIPanelScrollFrameTemplate")
    scrollFrame:SetSize(width, height)
    
    local scrollChild = CreateFrame("Frame", nil, scrollFrame)
    scrollChild:SetSize(width, height)
    scrollFrame:SetScrollChild(scrollChild)
    
    -- Style scrollbar
    if AiB.Themes then
        local scrollBar = scrollFrame.ScrollBar
        if scrollBar then
            scrollBar:GetThumbTexture():SetColorTexture(AiB.Themes:GetColor("border_accent"))
        end
    end
    
    return scrollFrame, scrollChild
end

-------------------------
-- POSITION UTILITIES
-------------------------
function AiB.Utils:CenterFrame(frame, offsetX, offsetY)
    frame:ClearAllPoints()
    frame:SetPoint("CENTER", UIParent, "CENTER", offsetX or 0, offsetY or 0)
end

-- v2.1.0.0: AiB_Settings ist Alias auf AiB.db.profile.settings (AceDB)
-- SavePosition/LoadPosition speichern im Profil (geteilt via Profil-System).
function AiB.Utils:SavePosition(frame, saveName)
    local point, relativeTo, relativePoint, xOfs, yOfs = frame:GetPoint()
    
    AiB_Settings = AiB_Settings or {}
    AiB_Settings.positions = AiB_Settings.positions or {}
    AiB_Settings.positions[saveName] = {
        point = point,
        relativePoint = relativePoint,
        x = xOfs,
        y = yOfs
    }
end

function AiB.Utils:LoadPosition(frame, saveName)
    if not AiB_Settings or not AiB_Settings.positions or not AiB_Settings.positions[saveName] then
        return false
    end
    
    local pos = AiB_Settings.positions[saveName]
    frame:ClearAllPoints()
    frame:SetPoint(pos.point, UIParent, pos.relativePoint, pos.x, pos.y)
    return true
end

-------------------------
-- DEBUG UTILITIES
-------------------------
function AiB.Utils:DumpTable(tbl, depth)
    depth = depth or 0
    if depth > 3 then return end
    
    local indent = string.rep("  ", depth)
    
    for k, v in pairs(tbl) do
        if type(v) == "table" then
            print(indent .. tostring(k) .. " = {")
            self:DumpTable(v, depth + 1)
            print(indent .. "}")
        else
            print(indent .. tostring(k) .. " = " .. tostring(v))
        end
    end
end

function AiB.Utils:PrintMemoryUsage()
    UpdateAddOnMemoryUsage()
    local mem = GetAddOnMemoryUsage("aib")
    print("|cFF00FF00AiB Memory Usage:|r " .. string.format("%.2f KB", mem))
end

-------------------------
-- VALIDATION UTILITIES
-------------------------
function AiB.Utils:ValidateSettings()
    AiB_Settings = AiB_Settings or {}
    
    -- Merge with defaults
    for key, value in pairs(AiB.Config.DEFAULTS) do
        if AiB_Settings[key] == nil then
            AiB_Settings[key] = value
        end
    end
    
    return true
end


