local _, ns = ...
local L = ns.L or {}

local function safeCopyTable(source)
    local copy = {}
    if type(source) ~= "table" then
        return copy
    end

    for key, value in pairs(source) do
        copy[key] = value
    end

    return copy
end

local function getWeeklyResetInfo()
    local secondsUntilReset = 0
    if C_DateAndTime and type(C_DateAndTime.GetSecondsUntilWeeklyReset) == "function" then
        secondsUntilReset = math.max(0, tonumber(C_DateAndTime.GetSecondsUntilWeeklyReset()) or 0)
    end

    local now = time()
    return secondsUntilReset, now + secondsUntilReset
end

local function getDelimitedText(template, count)
    if type(template) ~= "string" or template == "" then
        return tostring(count or 0)
    end

    return string.format(template, tonumber(count) or 0)
end

local function formatDurationShort(seconds)
    seconds = math.max(0, math.floor(tonumber(seconds) or 0))

    local days = math.floor(seconds / 86400)
    local hours = math.floor((seconds % 86400) / 3600)
    local minutes = math.floor((seconds % 3600) / 60)

    if days > 0 then
        return string.format(L.TIME_DAY_HOUR or "%d d %d h", days, hours)
    end
    if hours > 0 then
        return string.format(L.TIME_HOUR_MIN or "%d h %d m", hours, minutes)
    end
    if minutes > 0 then
        return string.format(L.TIME_MIN or "%d m", minutes)
    end

    return L.TIME_JUST_NOW or "just now"
end

local function normalizeText(text)
    return string.lower(tostring(text or ""))
end

local function containsPattern(text, patterns)
    local haystack = normalizeText(text)
    for _, pattern in ipairs(patterns or {}) do
        if type(pattern) == "string" and pattern ~= "" and haystack:find(pattern) then
            return true
        end
    end

    return false
end

local function stringContainsAnyPattern(text, patterns)
    if type(text) ~= "string" or text == "" then
        return false
    end

    local haystack = string.lower(text)
    for _, pattern in ipairs(patterns or {}) do
        if type(pattern) == "string" and pattern ~= "" and haystack:find(string.lower(pattern), 1, true) then
            return true
        end
    end

    return false
end

local Util = ns.Util or {}
ns.Util = Util

Util.SafeCopyTable = safeCopyTable
Util.GetWeeklyResetInfo = getWeeklyResetInfo
Util.GetDelimitedText = getDelimitedText
Util.FormatDurationShort = formatDurationShort
Util.NormalizeText = normalizeText
Util.ContainsPattern = containsPattern
Util.StringContainsAnyPattern = stringContainsAnyPattern
