-- 1. Ensure the main table & defaults exist
if not EasyCursorTrails then
    EasyCursorTrails = {}
end

EasyCursorTrails.debugMode = false
-- At top of your addon:
EasyCursorTrails.lastArcTime = {}

--Reset Button default profile
EasyCursorTrails.defaults = {
     verticalScale = 2,
    trailColor = { r = 1, g = 1, b = 1, a = 1 },
    enableStaticArc = true,
    cursorColorEffect = 2,
    minimapPosition = { x = 0, y = 0 },
    horizontalScale = 1,
    enableStaticArcs = true,
    glowAboveCursor = false,
    randomLightningSparkColor = false,
    glowRadius = 0.1,
    glowColor = { r = 0.7176470588235294, g = 0.4196078431372549, b = 0.9568627450980393, a = 1 },
    numGlows = 30,
    trailRadius = 20,
    cursorOffsetX = 0,
    enableTrailShadows = true,
    glowThickness = 0.8,
    trailColorEffect = 11,
    pulsingSpeed = 10,
    trailDelay = 0,
    chainSegment = 10,
    disableGlowPulsing = false,
    cursorTexture = 32,
    enableStars = true,
    selectedCursorTextureName = "Yin_Yang_1",
    randomEmberColor = false,
    staticArcColor = { r = 1, g = 1, b = 1, a = 1 },
    enableTwinkleStars = false,
    enableSmokeEffect = true,
    patternGlowCount = 29,
    cursorFrameStrata = "HIGH",
    trailTexture = 1,
    cursorSize = 40,
    glowIntensity = 1,
    randomFireColor = false,
    randomStaticArcColor = true,
    randomStarColor = true,
    shadowTrailColor = { r = 0, g = 0, b = 0, a = 0.4 },
    glowHollowness = 0,
    trailCount = 35,
    trailSpacing = 10,
    glowBelow = false,
    enableEmbers = false,
    randomSpringSeasonColor = false,
    cursorColor = { r = 0.5411764705882353, g = 0.9921568627450981, b = 1, a = 1 },
    trailFrameStrata = "HIGH",
    trailMovementEffect = 1,
    trailInitialSeparation = 30,
    glowPulsingIntensity = 0.5,
    trailIntensity = 0.5,
    enableDirectionalOffset = true,
    connectTrails = true,
    trailSizeStart = 15,
    trailUpdateMultiplier = 100,
    menuPosition = {
        x = 250.1666412353516,
        y = -87.33332061767578,
        point = "TOP",
        relativePoint = "TOP",
    },
    additionalEffects = 1,
    pulseMin = 0.3,
    glowIntensityFactor = 0.2999999821186066,
    enableSmoke = true,
    trailLayerSpacing = 0,
    selectedGlowEffect = 5,
    numTrails = 10,
    enableFire = false,
    trailOffsetY = 1,
    cursorOffsetY = 0,
    trailSizeEnd = 1,
    trailOffsetX = -33,
    randomShadowColor = false,
    enableTrails = true,
    enableStarEmbers = true,
    enableSmokeTrails = true,
    enableLightningSparks = false,
    enableSpringSeason = false,
    enableSpringSeasonTrails = false,
    enableFireTrails = false,
    randomSmokeColor = true,
    randomTwinkleStarsColor = false,
    trailGlowIntensity = 1,
    chainSpacing = 1,
    trailLayerCount = 1,
    twinkleStarsColor = { r = 0.9, g = 0.95, b = 1, a = 1 },
    glowSize = 0.5


    }


function EasyCursorTrails:MergeDefaults(target, defaults)
    for key, value in pairs(defaults) do
        if type(value) == "table" then
            if type(target[key]) ~= "table" then
                target[key] = {}
            end
            -- Only merge if target[key] is not already populated
            self:MergeDefaults(target[key], value)
        elseif target[key] == nil then
            target[key] = value
        end
    end
end



------------------------------------------------------------------------------
-- Basic error handler
------------------------------------------------------------------------------
function EasyCursorTrails.HandleError(msg)
    --print("EasyCursorTrails Error: " .. tostring(msg))
end

------------------------------------------------------------------------------
-- Initialize or fix up EasyCursorTrailsDB
------------------------------------------------------------------------------
function EasyCursorTrails.InitializeEasyCursorTrailsDB()
    if not EasyCursorTrails.defaults then
        EasyCursorTrails.HandleError("InitializeEasyCursorTrailsDB: Defaults not defined.")
        return
    end

    -- Ensure the global saved variable
    if not EasyCursorTrailsDB then
        EasyCursorTrailsDB = { profiles = {} }
        --print("EasyCursorTrails: Created a fresh EasyCursorTrailsDB.")
    else
        EasyCursorTrailsDB.profiles = EasyCursorTrailsDB.profiles or {}
    end

    -- Ensure 'Default' profile exists
    if not EasyCursorTrailsDB.profiles["Default"] then
        EasyCursorTrailsDB.profiles["Default"] = {}
        for key, val in pairs(EasyCursorTrails.defaults) do
            EasyCursorTrailsDB.profiles["Default"][key] = val
        end

        --print("EasyCursorTrails: 'Default' profile created with defaults.")
    end

    -- Pick a valid currentProfile if needed
    local cp = EasyCursorTrailsDB.currentProfile
    if not cp or not EasyCursorTrailsDB.profiles[cp] then
        cp = "Default"
        EasyCursorTrailsDB.currentProfile = "Default"
        --print("EasyCursorTrails: Using 'Default' profile since current was invalid.")
    end

    -- Also ensure lastSelectedProfile is valid
    local lsp = EasyCursorTrailsDB.lastSelectedProfile
    if not lsp or not EasyCursorTrailsDB.profiles[lsp] then
        EasyCursorTrailsDB.lastSelectedProfile = "Default"
    end
    -- We do NOT call Load/Refresh/Rebuild here to avoid double merges
end


------------------------------------------------------------------------------
-- InitializeProfile
-----------------------
function EasyCursorTrails.InitializeProfile()
    local cp = EasyCursorTrailsDB.currentProfile or "Default"
    local prof = EasyCursorTrailsDB.profiles[cp]
    if not prof then
        cp = "Default"
        EasyCursorTrailsDB.currentProfile = cp
        prof = EasyCursorTrailsDB.profiles[cp]
        if not prof then
            EasyCursorTrails.HandleError("InitializeProfile: Missing 'Default' profile.")
            return
        end
    end
  
    EasyCursorTrails.currentProfileTable = prof
    
end

------------------------------------------------------------------------------
-- LoadCurrentProfile
--
-- Usually called after switching profile or reset. 
-- Ensures currentProfileTable is valid and merges defaults if needed.
------------------------------------------------------------------------------
function EasyCursorTrails.LoadCurrentProfile()
    -- 🗝️ Step 1: Identify profile key
    local cp = EasyCursorTrailsDB.currentProfile or "Default"
    local prof = EasyCursorTrailsDB.profiles[cp]

    -- 🧯 Step 2: Fallback if profile is missing
    if not prof then
        EasyCursorTrails.HandleError("LoadCurrentProfile: Profile '" .. cp .. "' not found; using 'Default'.")
        cp = "Default"
        EasyCursorTrailsDB.currentProfile = cp
        prof = EasyCursorTrailsDB.profiles[cp]
        if not prof then
            EasyCursorTrails.HandleError("LoadCurrentProfile: 'Default' profile missing; cannot load.")
            return
        end
    end

    -- 🛠️ Step 3: Merge missing fields from defaults
    if EasyCursorTrails.defaults then
        EasyCursorTrails:MergeDefaults(prof, EasyCursorTrails.defaults)
    end

    -- 🎯 Step 4: Set current profile reference
    EasyCursorTrails.currentProfileTable = prof
    EasyCursorTrails.profile = prof

    -- 🧪 Step 5: Validate profile if possible
    if EasyCursorTrails.ValidateProfile then
        EasyCursorTrails.ValidateProfile(prof)
    end

    -- 📶 Step 6: Normalize cursor strata string
    local strataMap = {
        "BACKGROUND", "LOW", "MEDIUM", "HIGH", "DIALOG",
        "FULLSCREEN", "FULLSCREEN_DIALOG", "TOOLTIP"
    }
    local storedStrata = prof.cursorFrameStrata
    if type(storedStrata) ~= "string" then
        prof.cursorFrameStrata = strataMap[tonumber(storedStrata)] or "MEDIUM"
    end

    -- 🔢 Step 7: Ensure trail layer count is sensible
    local storedLayerCount = tonumber(prof.trailLayerCount)
    if (not storedLayerCount) or (storedLayerCount < 2) then
        storedLayerCount = tonumber(EasyCursorTrails.defaults.trailLayerCount) or 14
    end
    prof.trailLayerCount = math.floor(storedLayerCount)

    -- 🧹 Step 8: Clear lingering visual effects (e.g. sparkles)
    if EasyCursorTrails.ClearActiveGlows then
        EasyCursorTrails.ClearActiveGlows()
    end

    -- 🖱️ Step 9: Rebuild cursor and trails
    if EasyCursorTrails.InitializeCustomCursor then
        EasyCursorTrails.InitializeCustomCursor()
    end
    if EasyCursorTrails.RebuildTrails then
        EasyCursorTrails.RebuildTrails()
    end
end







------------------------------------------------------------------------------
-- SaveToCurrentProfile
--
-- Writes a single key/value pair to whatever profile is in EasyCursorTrailsDB.currentProfile
------------------------------------------------------------------------------
function EasyCursorTrails.SaveToCurrentProfile(key, value)
    if not EasyCursorTrailsDB or not EasyCursorTrailsDB.profiles then
        EasyCursorTrails.HandleError("SaveToCurrentProfile: DB or DB.profiles is nil.")
        return
    end

    if type(key) ~= "string" then
        EasyCursorTrails.HandleError("SaveToCurrentProfile: Key must be a string.")
        return
    end

    local cp = EasyCursorTrailsDB.currentProfile or "Default"
    local prof = EasyCursorTrailsDB.profiles[cp]
    if not prof then
        EasyCursorTrails.HandleError(("SaveToCurrentProfile: Profile '%s' not found."):format(cp))
        return
    end

    -- 🧼 Sanitize special cases
    if key == "trailLayerCount" then
        value = math.floor(value or 1)
    end

    -- 🛡️ Prevent accidental overwrites
    if type(value) == "table" then
        value = CopyTable(value) -- Ensure table fields aren't shared references
    end

    prof[key] = value

    -- 🧠 Optional: Log update for debugging
    if EasyCursorTrails.debugSave then
        print(("[EasyCursorTrails] Profile '%s': Saved key '%s' → %s"):format(cp, key, tostring(value)))
    end
end

------------------------------------------------------------------------------
-- SaveLastSelectedProfile
------------------------------------------------------------------------------
function EasyCursorTrails.SaveLastSelectedProfile(profileName)
    if (not profileName) or (not EasyCursorTrailsDB.profiles[profileName]) then
        return
    end
    EasyCursorTrailsDB.lastSelectedProfile = profileName
end


function EasyCursorTrails.DeepCopyDefaults(defaults, overrides)
    if type(defaults) ~= "table" then
        return {}
    end

    local copy = {}

    for key, value in pairs(defaults) do
        if type(value) == "table" then
            -- ⚙ Recursively merge nested tables with overrides if available
            local subOverride = type(overrides) == "table" and overrides[key]
            if type(subOverride) == "table" then
                copy[key] = EasyCursorTrails.DeepCopyDefaults(value, subOverride)
            else
                copy[key] = EasyCursorTrails.DeepCopyDefaults(value)
            end
        else
            copy[key] = value
        end
    end

    -- 🧩 Apply remaining overrides (non-nested or new keys)
    if type(overrides) == "table" then
        for k, v in pairs(overrides) do
            if type(v) ~= "table" or type(copy[k]) ~= "table" then
                copy[k] = v
            end
        end
    end

    return copy
end




-------------------------
-- Custom Cursors
-------------------------
EasyCursorTrails.customCursorTextures = {
    {
        name = "Pearl (Use Custom + Glow Effect)",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Pearl",
        animated = false,
    },
    {
        name = "Alien",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Alien3",
        animated = false,
    },
    {
        name = "Broom Stick",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\BroomStick1",
        animated = false,
    },
    {
        name = "Bullet",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Bullet1",
        animated = false,
    },
    {
        name = "Vibrant Sniper Scope",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\vibrant_sniper_scope",
        animated = false,
    },
    {
        name = "Sniper Scope",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\sniper_scope",
        animated = false,
    },
    {
        name = "Sniper Scope 4",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\sniper_scope4",
        animated = false,
    },
    {
        name = "Dirty Lens",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\dirty_lens",
        animated = false,
    },

    {
        name = "Circle 1",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Circle1",
        animated = false,
    },
    {
        name = "Circle 2",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Circle2",
        animated = false,
    },
    {
        name = "Circle 3",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Circle3",
        animated = false,
    },
    {
        name = "Circle 4",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Circle4",
        animated = false,
    },
    {
        name = "Circle 5",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Circle5",
        animated = false,
    },
    {
        name = "Circle_thin_mid",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Circle_thin_mid",
        animated = false,
    },
    {
        name = "Circle White",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Circle_White",
        animated = false,
    },
    {
        name = "2 Semi Circle 2",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\2_Semi_Circle_2",
        animated = false,
    },
    {
        name = "2 Semi Circle 5",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\2_Semi_Circle_5",
        animated = false,
    },
    {
        name = "Diamond Left",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Diamond_Left",
        animated = false,
    },
    {
        name = "Diamond Cystal",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Diamond_Crystal",
        animated = false,
    },
    {
        name = "Glass 1",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Glass1",
        animated = false,
    },
    {
        name = "Glass 2",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Glass2",
        animated = false,
    },
    {
        name = "Cursor 1",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\cursor1",
        animated = false,
    },
    {
        name = "Cursor 2",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\cursor2",
        animated = false,
    },
    {
        name = "Golden Ring",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Golden_Ring",
        animated = false,
    },
    {
        name = "Golden Heart",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Golden_Heart",
        animated = false,
    },

    {
        name = "Heart 1",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Heart_White",
        animated = false,
    },
    {
        name = "Heart 2",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Heart3",
        animated = false,
    },
    {
        name = "Heart 3",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Heart5",
        animated = false,
    },
    {
        name = "Heart 4",
        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Heart7",
        animated = false,
    },

    -- Animated Example
    {
        name = "RGB Rotate",
        textures = {
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\RGB\\RGB_Rotate_1.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\RGB\\RGB_Rotate_2.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\RGB\\RGB_Rotate_3.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\RGB\\RGB_Rotate_4.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\RGB\\RGB_Rotate_5.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\RGB\\RGB_Rotate_6.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\RGB\\RGB_Rotate_7.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\RGB\\RGB_Rotate_8.blp",
        },
        animated = true,
        totalFrames = 8,
        animationDuration = 0.8,
    },
    {
        name = "Yin and Yang v2",
        textures = {
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Yin_Yang\\Yin_Yang_v1.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Yin_Yang\\Yin_Yang_v2.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Yin_Yang\\Yin_Yang_v3.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Yin_Yang\\Yin_Yang_v4.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Yin_Yang\\Yin_Yang_v5.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Yin_Yang\\Yin_Yang_v6.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Yin_Yang\\Yin_Yang_v7.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Yin_Yang\\Yin_Yang_v8.blp",
        },
        animated = true,
        totalFrames = 8,
        animationDuration = 0.6,
    },
    {
        name = "Yin and Yang",
        textures = {
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Yin_Yang\\Yin_Yang_1.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Yin_Yang\\Yin_Yang_2.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Yin_Yang\\Yin_Yang_3.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Yin_Yang\\Yin_Yang_4.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Yin_Yang\\Yin_Yang_5.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Yin_Yang\\Yin_Yang_6.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Yin_Yang\\Yin_Yang_7.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Yin_Yang\\Yin_Yang_8.blp",
        },
        animated = true,
        totalFrames = 8,
        animationDuration = 0.6,
    },
    {
        name = "Radar",
        textures = {
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Radar\\Radar_1.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Radar\\Radar_2.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Radar\\Radar_3.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Radar\\Radar_4.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Radar\\Radar_5.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Radar\\Radar_6.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Radar\\Radar_7.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Radar\\Radar_8.blp",
        },
        animated = true,
        totalFrames = 8,
        animationDuration = 2.5,
    },
    {
        name = "Circle",
        textures = {
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Circle\\Circle_1_Hovering.tga",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Circle\\Circle_2_Hovering.tga",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Circle\\Circle_3_Hovering.tga",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Circle\\Circle_4_Hovering.tga",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Circle\\Circle_5_Hovering.tga",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Circle\\Circle_6_Hovering.tga",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Circle\\Circle_7_Hovering.tga",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Circle\\Circle_8_Hovering.tga",
        },
        animated = true,
        totalFrames = 8,
        animationDuration = 0.5,
    },
    {
        name = "Circle_focus",
        textures = {
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Circle\\Circle_focus_1.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Circle\\Circle_focus_2.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Circle\\Circle_focus_3.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Circle\\CCircle_focus_4.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Circle\\Circle_focus_5.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Circle\\Circle_focus_6.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Circle\\Circle_focus_7.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Circle\\Circle_focus_8.blp",
        },
        animated = true,
        totalFrames = 8,
        animationDuration = 0.5,
    },
    {
        name = "Butterfly Hovering",
        textures = {
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Butterfly\\Butterfly_1.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Butterfly\\Butterfly_2.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Butterfly\\Butterfly_3.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Butterfly\\Butterfly_4.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Butterfly\\Butterfly_5.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Butterfly\\Butterfly_6.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Butterfly\\Butterfly_7.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Butterfly\\Butterfly_8.blp",
        },
        animated = true,
        totalFrames = 8,
        animationDuration = 0.6,
    },
    {
        name = "Fairy Hovering",
        textures = {
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Fairy\\Fairy_Left_1_Hovering.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Fairy\\Fairy_Left_2_Hovering.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Fairy\\Fairy_Left_3_Hovering.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Fairy\\Fairy_Left_4_Hovering.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Fairy\\Fairy_Left_5_Hovering.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Fairy\\Fairy_Left_6_Hovering.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Fairy\\Fairy_Left_7_Hovering.blp",
            "Interface\\AddOns\\EasyCursorTrails\\Textures\\Cursors\\Fairy\\Fairy_Left_8_Hovering.blp",
        },
        animated = true,
        totalFrames = 8,
        animationDuration = 0.3,
    },
}



---------------------------------------------------------------------------
-- dynamicPatterns: shape generation for glows with adjustable positioning
---------------------------------------------------------------------------
EasyCursorTrails.dynamicPatterns = EasyCursorTrails.dynamicPatterns or {}

-- Helper function to generate a single "V" shape
local function generateVShape(rotationAngle, xOffset, yOffset, length, width)
    local points = {}
    
    -- Convert rotation angle from degrees to radians
    local radians = math.rad(rotationAngle or 0)
    
    -- Define the three points of the "V"
    local baseLeft = {
        x = -width,
        y = -0
    }
    local tip = {
        x = 0,
        y = length
    }
    local baseRight = {
        x = width,
        y = 0
    }
    
    -- Function to rotate a point around the origin
    local function rotatePoint(point, radians)
        return {
            x = point.x * math.cos(radians) - point.y * math.sin(radians),
            y = point.x * math.sin(radians) + point.y * math.cos(radians)
        }
    end
    
    -- Rotate points
    local rotatedBaseLeft = rotatePoint(baseLeft, radians)
    local rotatedTip = rotatePoint(tip, radians)
    local rotatedBaseRight = rotatePoint(baseRight, radians)
    
    -- Apply offsets
    rotatedBaseLeft.x = rotatedBaseLeft.x + xOffset
    rotatedBaseLeft.y = rotatedBaseLeft.y + yOffset
    rotatedTip.x = rotatedTip.x + xOffset
    rotatedTip.y = rotatedTip.y + yOffset
    rotatedBaseRight.x = rotatedBaseRight.x + xOffset
    rotatedBaseRight.y = rotatedBaseRight.y + yOffset
    
    -- Insert points into the table
    table.insert(points, rotatedBaseLeft)
    table.insert(points, rotatedTip)
    table.insert(points, rotatedBaseRight)
    
    return points
end



-- 1. Helper function to generate points between two points
local function generateLinePoints(startPoint, endPoint, numPoints)
    local points = {}
    if numPoints < 2 then numPoints = 2 end -- Ensure at least two points
    for i = 0, numPoints - 1 do
        local ratio = i / (numPoints - 1)
        local x = startPoint.x + (endPoint.x - startPoint.x) * ratio
        local y = startPoint.y + (endPoint.y - startPoint.y) * ratio
        table.insert(points, { x = x, y = y })
    end
    return points
end

-- 2. Helper function to generate points for a single "V" shape
local function generateArrowHead(numPoints, direction, rotationAngle, xOffset, yOffset, length, width)
    local points = {}
    
    -- Convert rotation angle from degrees to radians
    local radians = math.rad(rotationAngle or 0)
    
    -- Define the three points of the "V"
    local baseLeft = { x = -width * direction.leftOrRight, y = 0 }
    local tip = { x = 0, y = length * direction.upOrDown }
    local baseRight = { x = width * direction.leftOrRight, y = 0 }
    
    -- Function to rotate a point around the origin and apply offsets
    local function rotatePoint(point, radians)
        return {
            x = point.x * math.cos(radians) - point.y * math.sin(radians) + xOffset,
            y = point.x * math.sin(radians) + point.y * math.cos(radians) + yOffset
        }
    end
    
    -- Rotate points
    local rotatedBaseLeft = rotatePoint(baseLeft, radians)
    local rotatedTip = rotatePoint(tip, radians)
    local rotatedBaseRight = rotatePoint(baseRight, radians)
    
    -- Generate points for left side of "V"
    local leftPoints = generateLinePoints(rotatedBaseLeft, rotatedTip, math.ceil(numPoints / 2))
    
    -- Generate points for right side of "V"
    local rightPoints = generateLinePoints(rotatedTip, rotatedBaseRight, math.floor(numPoints / 2))
    
    -- Combine points
    for _, point in ipairs(leftPoints) do
        table.insert(points, point)
    end
    for _, point in ipairs(rightPoints) do
        table.insert(points, point)
    end
    
    return points
end


-- 2. Helper function to generate points for a single "U" shape
local function generateUShape(numPoints, direction, rotationAngle, xOffset, yOffset, length, width)
    local points = {}
    
    -- Convert rotation angle from degrees to radians
    local radians = math.rad(rotationAngle or 0)
    
    -- Define the key points of the "U"
    local topLeft = { x = -width, y = 0 }
    local bottomLeft = { x = -width, y = -length }
    local bottomRight = { x = width, y = -length }
    local topRight = { x = width, y = 0 }
    
    -- Function to rotate a point around the origin and apply offsets
    local function rotatePoint(point, radians)
        return {
            x = point.x * math.cos(radians) - point.y * math.sin(radians) + xOffset,
            y = point.x * math.sin(radians) + point.y * math.cos(radians) + yOffset
        }
    end
    
    -- Rotate and offset points
    local rotatedTopLeft = rotatePoint(topLeft, radians)
    local rotatedBottomLeft = rotatePoint(bottomLeft, radians)
    local rotatedBottomRight = rotatePoint(bottomRight, radians)
    local rotatedTopRight = rotatePoint(topRight, radians)
    
    -- Allocate points to each segment
    -- Ensure the curved segment has a sufficient number of points for smoothness
    local minCurvePoints = 10
    local curvePoints = math.max(minCurvePoints, math.floor(numPoints * 0.6))
    local remainingPoints = numPoints - curvePoints
    local pointsPerVertical = math.floor(remainingPoints / 2)
    
    -- Ensure pointsPerVertical is at least 2 for smooth vertical lines
    pointsPerVertical = math.max(2, pointsPerVertical)
    
    -- Generate points for left vertical line
    local leftPoints = generateLinePoints(rotatedTopLeft, rotatedBottomLeft, pointsPerVertical)
    
    -- Generate points for the bottom curve (semi-circle)
    local curvePointsList = {}
    for i = 0, curvePoints - 1 do
        local angle = math.pi + (i / (curvePoints - 1)) * math.pi -- from pi to 2pi
        local x = width * math.cos(angle)
        local y = -length * math.sin(angle)
        local rotatedX = x * math.cos(radians) - y * math.sin(radians) + xOffset
        local rotatedY = x * math.sin(radians) + y * math.cos(radians) + yOffset
        table.insert(curvePointsList, {x = rotatedX, y = rotatedY})
    end
    
    -- Generate points for right vertical line
    local rightPoints = generateLinePoints(rotatedBottomRight, rotatedTopRight, pointsPerVertical)
    
    -- Combine all points
    for _, point in ipairs(leftPoints) do
        table.insert(points, point)
    end
    for _, point in ipairs(curvePointsList) do
        table.insert(points, point)
    end
    for _, point in ipairs(rightPoints) do
        table.insert(points, point)
    end
    

    return points
end



-- 2. Helper function to generate points along an ellipse
local function generateEllipsePoints(a, b, numPoints, rotationAngle, xOffset, yOffset)
    local points = {}
    local radians = math.rad(rotationAngle or 0) -- Convert rotation angle to radians
    
    for i = 0, numPoints - 1 do
        local t = (i / numPoints) * 2 * math.pi
        local x = a * math.cos(t)
        local y = b * math.sin(t)
        
        -- Apply rotation
        local rotatedX = x * math.cos(radians) - y * math.sin(radians)
        local rotatedY = x * math.sin(radians) + y * math.cos(radians)
        
        -- Apply offsets
        rotatedX = rotatedX + xOffset
        rotatedY = rotatedY + yOffset
        
        table.insert(points, {x = rotatedX, y = rotatedY})
    end
    

    return points
end

-- 3. Oval Pattern Function
EasyCursorTrails.dynamicPatterns.OvalPattern = function(N)
    local points = {}
    
    -- Define parameters
    local a = 35 -- Horizontal radius; adjust for wider or narrower oval
    local b = 20 -- Vertical radius; adjust for taller or shorter oval
    local rotationAngle = 0 -- Degrees; rotate the oval if desired
    local xOffset = 0 -- Center the oval horizontally
    local yOffset = 0 -- Center the oval vertically
    
    -- Generate points along the ellipse
    points = generateEllipsePoints(a, b, N, rotationAngle, xOffset, yOffset)
    
    return points
end


    -- Helper function to determine the sign of a number
    local function sign(x)
        if x > 0 then
            return 1
        elseif x < 0 then
            return -1
        else
            return 0
        end
    end
    
EasyCursorTrails.dynamicPatterns = {
    -- Circle Pattern
    Circle_White = function(N)
        local points = {}
        local angleStep = (2 * math.pi) / N

        -- Position Offsets (Adjust these to move the circle)
        local xOffset = 0    -- Horizontal offset
        local yOffset = 0    -- Vertical offset

        for i = 1, N do
            local angle = (i - 1) * angleStep
            local x = math.cos(angle) * 20 + xOffset
            local y = math.sin(angle) * 20 + yOffset
            table.insert(points, { x = x, y = y })
        end
        return points
    end,

    -- Heart Pattern
    Heart_1 = function(N)
        local points = {}
        local tStep = (2 * math.pi) / N
        local scale = 0.7

        -- Position Offsets (Adjust these to move the heart)
        local xOffset = 0    -- Horizontal offset
        local yOffset = 1   -- Vertical offset (e.g., moving the heart up)

        for i = 1, N do
            local t = (i - 1) * tStep
            local x = scale * (16 * math.sin(t)^3) + xOffset
            local y = scale * (
                12 * math.cos(t)
                - 5 * math.cos(2 * t)
                - 2 * math.cos(3 * t)
                - math.cos(4 * t)
            ) + yOffset
            table.insert(points, { x = x, y = y })
        end
        return points
    end,

    -- Star Cursor Pattern
    Star_Cursor = function(N)
        local points = {}
        local angleStep = (2 * math.pi) / N

        -- Position Offsets (Adjust these to move the star)
        local xOffset = 0    -- Horizontal offset
        local yOffset = 0    -- Vertical offset

        for i = 1, N do
            local angle = (i - 1) * angleStep
            local radius = (i % 2 == 1) and 30 or 15
            local x = math.cos(angle) * radius + xOffset
            local y = math.sin(angle) * radius + yOffset
            table.insert(points, { x = x, y = y })
        end
        return points
    end,



    -- Yin and Yang Pattern
    Yin_Yang_Pattern = function(N)
        local points = {}
        local angleStep = (2 * math.pi) / N

        -- Position Offsets (Adjust these to move the Yin-Yang)
        local xOffset = 0    -- Horizontal offset
        local yOffset = 0    -- Vertical offset

        for i = 1, N do
            local angle = (i - 1) * angleStep
            -- Simplified circular pattern for Yin and Yang
            local x = math.cos(angle) * 20 + xOffset
            local y = math.sin(angle) * 20 + yOffset
            table.insert(points, { x = x, y = y })
        end
        return points
    end,

    -- Butterfly Pattern
    Butterfly_Pattern = function(N)
        local points = {}
        local angleStep = (2 * math.pi) / N

        -- Position Offsets (Adjust these to move the butterfly)
        local xOffset = 0    -- Horizontal offset
        local yOffset = 0    -- Vertical offset

        for i = 1, N do
            local angle = (i - 1) * angleStep
            -- Define a butterfly-like pattern with symmetric wings
            local x = math.cos(angle) * (25 + 10 * math.sin(2 * angle)) + xOffset
            local y = math.sin(angle) * (25 + 10 * math.sin(2 * angle)) + yOffset
            table.insert(points, { x = x, y = y })
        end
        return points
    end,


    Bullet1 = function(N)
        local points = {}
        
        -- Define parameters
        local FIXED_ROTATION_ANGLE = 42    -- Degrees: Adjust as desired
        local xOffset = 2                 -- Horizontal offset (positive moves right, negative moves left)
        local yOffset = -10                 -- Vertical offset (positive moves up, negative moves down)
        local arrowHeadLength = 20          -- Length of the arrowhead sides
        local arrowHeadWidth = 1         -- Width of the arrowhead base (positive value)
        
        -- Define manual offset parameters for each "U"
        local direction1yoffset = 5         -- Manual Y offset for first "U"
        local direction1xoffset = 2         -- Manual X offset for first "U"
        local direction2yoffset = 2         -- Manual Y offset for second "U"
        local direction2xoffset = 5         -- Manual X offset for second "U"
        
        -- Define direction multipliers for two "U" shapes
        -- First "U" pointing down and to the right
        local direction1 = {
            upOrDown = -1,       -- -1 for "Down", 1 for "Up"
            leftOrRight = 1      -- 1 for "Right", -1 for "Left"
        }
        
        -- Second "U" pointing up and to the left (mirrored)
        local direction2 = {
            upOrDown = 1,        -- 1 for "Up", -1 for "Down"
            leftOrRight = -1     -- -1 for "Left", 1 for "Right"
        }
        
        -- Ensure N is a multiple of 6 for symmetry (since each "U" has three segments)
        if N % 6 ~= 0 then
            N = math.floor(N / 6) * 6
            if N < 6 then
                N = 6
            end
        end
        
        -- Number of points per "U" shape
        local pointsPerU = math.floor(N / 2) -- Each "U" has two curves: left and right
        pointsPerU = math.max(6, pointsPerU) -- At least 6 points per "U" for smoothness
        
        -- Generate first "U" shape (pointing down and to the right) with manual offsets
        local U1Points = generateUShape(
            pointsPerU,
            direction1,
            FIXED_ROTATION_ANGLE,
            xOffset + direction1xoffset,    -- Apply manual X offset
            yOffset + direction1yoffset,    -- Apply manual Y offset
            arrowHeadLength,
            arrowHeadWidth
        )
        
        -- Generate second "U" shape (pointing up and to the left) with manual offsets and rotation
        local U2Points = generateUShape(
            pointsPerU,
            direction2,
            FIXED_ROTATION_ANGLE + 180,   -- Rotate by 180 degrees to mirror
            xOffset + direction2xoffset,    -- Apply manual X offset
            yOffset + direction2yoffset,    -- Apply manual Y offset
            arrowHeadLength,
            arrowHeadWidth
        )
        
        -- Combine points from both "U" shapes to form a diamond
        for _, point in ipairs(U1Points) do
            table.insert(points, point)
        end
        
        for _, point in ipairs(U2Points) do
            table.insert(points, point)
        end
        
        return points
    end,


    -- Cursor (Arrow) Pattern with Fixed Angle, Direction Controls, and Position Offsets
Cursor_Arrow_Pattern = function(N)
    local points = {}
 
    local arrowUpOrDown = 1          -- Positive for "Up", Negative for "Down"
    local arrowLeftOrRight = 1       -- Positive for "Right", Negative for "Left"
  
    local FIXED_ROTATION_ANGLE = 42   -- Adjust this value to rotate the cursor pattern as desired

    local xOffset = 12                -- Horizontal offset (positive moves right, negative moves left)
    local yOffset = -15               -- Vertical offset (positive moves up, negative moves down)

    local shaftLength = 10           -- Increased for visibility
    
    local shaftWidth = 10              -- Currently not directly used but can influence visual spacing
    
    local arrowHeadLength = 30        -- Increase for longer arrowhead sides; decrease for shorter sides
    
    local arrowHeadWidth = 19         -- Increase for a wider arrowhead base; decrease for a narrower base
    
    local verticalMultiplier = sign(arrowUpOrDown)

    local horizontalMultiplier = sign(arrowLeftOrRight)
    
    local radiansOffset = math.rad(FIXED_ROTATION_ANGLE or 45) -- Defaults to 45° if not defined

    local shaftPoints = math.floor(N * 0.6)
    
    local arrowHeadPoints = math.floor((N - shaftPoints) / 2)

    shaftPoints = math.max(1, shaftPoints)
    arrowHeadPoints = math.max(1, arrowHeadPoints)

    for i = 1, shaftPoints do
        -- Calculate the Y-coordinate based on the current point's position along the shaft
        local y = (i / shaftPoints) * shaftLength * verticalMultiplier
        
        -- The X-coordinate remains 0 as the shaft is centered vertically
        local x = 0
        
        -- Apply rotation to the (x, y) point
        local rotatedX = x * math.cos(radiansOffset) - y * math.sin(radiansOffset)
        local rotatedY = x * math.sin(radiansOffset) + y * math.cos(radiansOffset)
        
        -- Apply position offsets to shift the entire pattern
        rotatedX = rotatedX + xOffset
        rotatedY = rotatedY + yOffset

        table.insert(points, { x = rotatedX, y = rotatedY })
    end

    for i = 1, arrowHeadPoints do
        -- Calculate the ratio of the current point's position within the arrowhead
        local ratio = i / arrowHeadPoints
        
        -- Calculate the X and Y coordinates for the left side of the arrowhead
        local x = -arrowHeadWidth * (1 - ratio) * horizontalMultiplier
        local y = (shaftLength + arrowHeadLength * ratio) * verticalMultiplier
        
        -- Apply rotation to the (x, y) point
        local rotatedX = x * math.cos(radiansOffset) - y * math.sin(radiansOffset)
        local rotatedY = x * math.sin(radiansOffset) + y * math.cos(radiansOffset)
        
        -- Apply position offsets to shift the entire pattern
        rotatedX = rotatedX + xOffset
        rotatedY = rotatedY + yOffset
        
        -- Insert the rotated and offset point into the points table
        table.insert(points, { x = rotatedX, y = rotatedY })
    end
    
 
    for i = 1, arrowHeadPoints do
        -- Calculate the ratio of the current point's position within the arrowhead
        local ratio = i / arrowHeadPoints
        
        -- Calculate the X and Y coordinates for the right side of the arrowhead
        local x = arrowHeadWidth * (1 - ratio) * horizontalMultiplier
        local y = (shaftLength + arrowHeadLength * ratio) * verticalMultiplier
        
        -- Apply rotation to the (x, y) point
        local rotatedX = x * math.cos(radiansOffset) - y * math.sin(radiansOffset)
        local rotatedY = x * math.sin(radiansOffset) + y * math.cos(radiansOffset)
        
        -- Apply position offsets to shift the entire pattern
        rotatedX = rotatedX + xOffset
        rotatedY = rotatedY + yOffset
        

        table.insert(points, { x = rotatedX, y = rotatedY })
    end
    

    return points
end,


Diamond = function(N)
    local points = {}
    
    -- Define parameters
    local FIXED_ROTATION_ANGLE = 45    -- Degrees: Adjust as desired
    local xOffset = -10                  -- Horizontal offset (positive moves right, negative moves left)
    local yOffset = -40                 -- Vertical offset (positive moves up, negative moves down)
    local arrowHeadLength = 10         -- Length of the arrowhead sides
    local arrowHeadWidth = 8          -- Width of the arrowhead base (positive value)
    
    -- Define manual offset parameters for each direction
    local direction1yoffset = 40        -- Manual Y offset for first "V"
    local direction1xoffset = 10         -- Manual X offset for first "V"
    local direction2yoffset = 30         -- Manual Y offset for second "V"
    local direction2xoffset = 10         -- Manual X offset for second "V"
    
    -- Define direction multipliers for two arrowheads
    -- First arrow pointing down and to the right
    local direction1 = {
        upOrDown = 1,       -- -1 for "Down", 1 for "Up"
        leftOrRight = 1      -- 1 for "Right", -1 for "Left"
    }
    
    -- Second arrow pointing up and to the left (mirrored)
    local direction2 = {
        upOrDown = 1,        -- 1 for "Up", -1 for "Down"
        leftOrRight = -1     -- -1 for "Left", 1 for "Right"
    }
    
    -- Ensure N is a multiple of 4 for symmetry
    if N % 4 ~= 0 then
        N = math.floor(N / 4) * 4
        if N < 4 then
            N = 4
        end
    end
    
    -- Number of points per arrowhead side
    local pointsPerArrow = math.floor(N / 4) -- Each arrow has two sides: left and right
    pointsPerArrow = math.max(1, pointsPerArrow)
    
    -- Generate first arrowhead (pointing down and to the right) with manual offsets
    local arrow1Points = generateArrowHead(
        pointsPerArrow * 2,
        direction1,
        FIXED_ROTATION_ANGLE,
        xOffset + direction1xoffset,    -- Apply manual X offset
        yOffset + direction1yoffset,    -- Apply manual Y offset
        arrowHeadLength,
        arrowHeadWidth
    )
    
    -- Compute yOffset for the second arrowhead (pointing up and to the left)
    local yOffset2 = yOffset + (arrowHeadLength * direction1.upOrDown) + direction2yoffset
    
    -- Compute xOffset for the second arrowhead
    local xOffset2 = xOffset + direction2xoffset
    
    -- Generate second arrowhead (mirrored, pointing up and to the left) with manual offsets
    local arrow2Points = generateArrowHead(
        pointsPerArrow * 2,
        direction2,
        FIXED_ROTATION_ANGLE + 180,   -- Rotate by 180 degrees to mirror
        xOffset2,                      -- Apply manual X offset
        yOffset2,                      -- Apply manual Y offset
        arrowHeadLength,
        arrowHeadWidth
    )
    
    -- Combine points from both arrowheads to form a diamond
    for _, point in ipairs(arrow1Points) do
        table.insert(points, point)
    end
    
    for _, point in ipairs(arrow2Points) do
        table.insert(points, point)
    end
    
    return points
end,


U_Shape = function(N)
    local points = {}
    
    -- Define parameters
    local FIXED_ROTATION_ANGLE = 41    -- Degrees: Adjust as desired
    local xOffset = 15                  -- Horizontal offset (positive moves right, negative moves left)
    local yOffset = -15                 -- Vertical offset (positive moves up, negative moves down)
    local arrowHeadLength = 4       -- Length of the arrowhead sides
    local arrowHeadWidth = 6           -- Width of the arrowhead base (positive value)
    
    -- Define manual offset parameters for each "U"
    local direction1yoffset = 20         -- Manual Y offset for first "U"
    local direction1xoffset = -20         -- Manual X offset for first "U"
    local direction2yoffset = 10         -- Manual Y offset for second "U"
    local direction2xoffset = -10         -- Manual X offset for second "U"
    
    -- Define direction multipliers for two "U" shapes
    -- First "U" pointing down and to the right
    local direction1 = {
        upOrDown = 1,       -- -1 for "Down", 1 for "Up"
        leftOrRight = 1      -- 1 for "Right", -1 for "Left"
    }
    
    -- Second "U" pointing up and to the left (mirrored)
    local direction2 = {
        upOrDown = 1,        -- 1 for "Up", -1 for "Down"
        leftOrRight = 1     -- -1 for "Left", 1 for "Right"
    }

        
    -- Ensure N is a multiple of 6 for symmetry (since each "U" has three segments)
    if N % 4 ~= 0 then
        N = math.floor(N / 4) * 4
        if N < 4 then
            N = 4
        end
    end

    -- Number of points per "U" shape
    local pointsPerU = math.floor(N / 2) -- Each "U" has two "U" segments (left and right)
    pointsPerU = math.max(6, pointsPerU) -- Ensure enough points for smoothness (minimum 20)
    
    -- Generate first "U" shape (pointing down and to the right) with manual offsets
    local U1Points = generateUShape(
        pointsPerU,
        direction1,
        FIXED_ROTATION_ANGLE,
        xOffset + direction1xoffset,    -- Apply manual X offset
        yOffset + direction1yoffset,    -- Apply manual Y offset
        arrowHeadLength,
        arrowHeadWidth
    )
    
    -- Generate second "U" shape (pointing up and to the left) with manual offsets and rotation
    local U2Points = generateUShape(
        pointsPerU,
        direction2,
        FIXED_ROTATION_ANGLE + 180,   -- Rotate by 180 degrees to mirror
        xOffset + direction2xoffset,    -- Apply manual X offset
        yOffset + direction2yoffset,    -- Apply manual Y offset
        arrowHeadLength,
        arrowHeadWidth
    )
    
    -- Combine points from both "U" shapes to form a diamond
    for _, point in ipairs(U1Points) do
        table.insert(points, point)
    end
    
    for _, point in ipairs(U2Points) do
        table.insert(points, point)
    end
    
    return points
end,


Diamond_Crystal = function(N)
    local points = {}
    
    -- Define parameters
    local FIXED_ROTATION_ANGLE = 32    -- Degrees: Adjust as desired
    local xOffset = -10                 -- Horizontal offset (positive moves right, negative moves left)
    local yOffset = -40                 -- Vertical offset (positive moves up, negative moves down)
    local arrowHeadLength = 10         -- Length of the arrowhead sides
    local arrowHeadWidth = 5        -- Width of the arrowhead base (positive value)
    
    -- Define manual offset parameters for each direction
    local direction1yoffset = 40        -- Manual Y offset for first "V"
    local direction1xoffset = 10         -- Manual X offset for first "V"
    local direction2yoffset = 30         -- Manual Y offset for second "V"
    local direction2xoffset = 10         -- Manual X offset for second "V"
    
    -- Define direction multipliers for two arrowheads
    -- First arrow pointing down and to the right
    local direction1 = {
        upOrDown = 1,       -- -1 for "Down", 1 for "Up"
        leftOrRight = 1      -- 1 for "Right", -1 for "Left"
    }
    
    -- Second arrow pointing up and to the left (mirrored)
    local direction2 = {
        upOrDown = 1,        -- 1 for "Up", -1 for "Down"
        leftOrRight = -1     -- -1 for "Left", 1 for "Right"
    }
    
    -- Ensure N is a multiple of 4 for symmetry
    if N % 4 ~= 0 then
        N = math.floor(N / 4) * 4
        if N < 4 then
            N = 4
        end
    end
    
    -- Number of points per arrowhead side
    local pointsPerArrow = math.floor(N / 4) -- Each arrow has two sides: left and right
    pointsPerArrow = math.max(1, pointsPerArrow)
    
    -- Generate first arrowhead (pointing down and to the right) with manual offsets
    local arrow1Points = generateArrowHead(
        pointsPerArrow * 2,
        direction1,
        FIXED_ROTATION_ANGLE,
        xOffset + direction1xoffset,    -- Apply manual X offset
        yOffset + direction1yoffset,    -- Apply manual Y offset
        arrowHeadLength,
        arrowHeadWidth
    )
    
    -- Compute yOffset for the second arrowhead (pointing up and to the left)
    local yOffset2 = yOffset + (arrowHeadLength * direction1.upOrDown) + direction2yoffset
    
    -- Compute xOffset for the second arrowhead
    local xOffset2 = xOffset + direction2xoffset
    
    -- Generate second arrowhead (mirrored, pointing up and to the left) with manual offsets
    local arrow2Points = generateArrowHead(
        pointsPerArrow * 2,
        direction2,
        FIXED_ROTATION_ANGLE + 180,   -- Rotate by 180 degrees to mirror
        xOffset2,                      -- Apply manual X offset
        yOffset2,                      -- Apply manual Y offset
        arrowHeadLength,
        arrowHeadWidth
    )
    
    -- Combine points from both arrowheads to form a diamond
    for _, point in ipairs(arrow1Points) do
        table.insert(points, point)
    end
    
    for _, point in ipairs(arrow2Points) do
        table.insert(points, point)
    end
    
    return points
end,


    -- Star Cursor Pattern
    Vibrant_Cursor = function(N)
        local points = {}
        local angleStep = (2 * math.pi) / N

        -- Position Offsets (Adjust these to move the star)
        local xOffset = 1    -- Horizontal offset
        local yOffset = -10    -- Vertical offset

        for i = 1, N do
            local angle = (i - 1) * angleStep
            local radius = (i % 2 == 1) and 2 or 4
            local x = math.cos(angle) * radius + xOffset
            local y = math.sin(angle) * radius + yOffset
            table.insert(points, { x = x, y = y })
        end
        return points
    end,

    
 -- Cursor (Arrow) Pattern with Fixed Angle, Direction Controls, and Position Offsets
 Broom = function(N)
    local points = {}
 
    local arrowUpOrDown = 1          -- Positive for "Up", Negative for "Down"
    local arrowLeftOrRight = 1       -- Positive for "Right", Negative for "Left"
  
    local FIXED_ROTATION_ANGLE = 49   -- Adjust this value to rotate the cursor pattern as desired

    local xOffset = 21                -- Horizontal offset (positive moves right, negative moves left)
    local yOffset = -15               -- Vertical offset (positive moves up, negative moves down)

    local shaftLength = 20          -- Increased for visibility
    
    local shaftWidth = 10              -- Currently not directly used but can influence visual spacing
    
    local arrowHeadLength = 30        -- Increase for longer arrowhead sides; decrease for shorter sides
    
    local arrowHeadWidth = 1         -- Increase for a wider arrowhead base; decrease for a narrower base
    
    local verticalMultiplier = sign(arrowUpOrDown)

    local horizontalMultiplier = sign(arrowLeftOrRight)
    
    local radiansOffset = math.rad(FIXED_ROTATION_ANGLE or 45) -- Defaults to 45° if not defined

    local shaftPoints = math.floor(N * 0.6)
    
    local arrowHeadPoints = math.floor((N - shaftPoints) / 2)

    shaftPoints = math.max(1, shaftPoints)
    arrowHeadPoints = math.max(1, arrowHeadPoints)

    for i = 1, shaftPoints do
        -- Calculate the Y-coordinate based on the current point's position along the shaft
        local y = (i / shaftPoints) * shaftLength * verticalMultiplier
        
        -- The X-coordinate remains 0 as the shaft is centered vertically
        local x = 0
        
        -- Apply rotation to the (x, y) point
        local rotatedX = x * math.cos(radiansOffset) - y * math.sin(radiansOffset)
        local rotatedY = x * math.sin(radiansOffset) + y * math.cos(radiansOffset)
        
        -- Apply position offsets to shift the entire pattern
        rotatedX = rotatedX + xOffset
        rotatedY = rotatedY + yOffset

        table.insert(points, { x = rotatedX, y = rotatedY })
    end

    for i = 1, arrowHeadPoints do
        -- Calculate the ratio of the current point's position within the arrowhead
        local ratio = i / arrowHeadPoints
        
        -- Calculate the X and Y coordinates for the left side of the arrowhead
        local x = -arrowHeadWidth * (1 - ratio) * horizontalMultiplier
        local y = (shaftLength + arrowHeadLength * ratio) * verticalMultiplier
        
        -- Apply rotation to the (x, y) point
        local rotatedX = x * math.cos(radiansOffset) - y * math.sin(radiansOffset)
        local rotatedY = x * math.sin(radiansOffset) + y * math.cos(radiansOffset)
        
        -- Apply position offsets to shift the entire pattern
        rotatedX = rotatedX + xOffset
        rotatedY = rotatedY + yOffset
        
        -- Insert the rotated and offset point into the points table
        table.insert(points, { x = rotatedX, y = rotatedY })
    end
    
 
    for i = 1, arrowHeadPoints do
        -- Calculate the ratio of the current point's position within the arrowhead
        local ratio = i / arrowHeadPoints
        
        -- Calculate the X and Y coordinates for the right side of the arrowhead
        local x = arrowHeadWidth * (1 - ratio) * horizontalMultiplier
        local y = (shaftLength + arrowHeadLength * ratio) * verticalMultiplier
        
        -- Apply rotation to the (x, y) point
        local rotatedX = x * math.cos(radiansOffset) - y * math.sin(radiansOffset)
        local rotatedY = x * math.sin(radiansOffset) + y * math.cos(radiansOffset)
        
        -- Apply position offsets to shift the entire pattern
        rotatedX = rotatedX + xOffset
        rotatedY = rotatedY + yOffset
        

        table.insert(points, { x = rotatedX, y = rotatedY })
    end
    

    return points
end,


    -- Custom Star Pattern for Unique Shapes
    Custom_Star_Pattern = function(N)
        local points = {}
        local angleStep = (2 * math.pi) / N

        -- Position Offsets (Adjust these to move the custom star)
        local xOffset = 0    -- Horizontal offset
        local yOffset = 0    -- Vertical offset

        for i = 1, N do
            local angle = (i - 1) * angleStep
            local radius = (i % 2 == 1) and 30 or 15
            local x = math.cos(angle) * radius + xOffset
            local y = math.sin(angle) * radius + yOffset
            table.insert(points, { x = x, y = y })
        end
        return points
    end,
}

-- For safety, unify references:
EasyCursorTrails.glowPatterns = EasyCursorTrails.dynamicPatterns



---------------------------------------------------------------------------
-- Mapping short texture names -> pattern key
---------------------------------------------------------------------------
-- Mapping short texture names -> pattern key
EasyCursorTrails.cursorGlowMapping = {
    ["Pearl"]                 = "",
    ["Alien3"]                = "Star_Cursor",
    ["BroomStick1"]           = "Broom",
    ["Bullet1"]               = "Bullet1",
    ["vibrant_sniper_scope"]  = "Circle_White",
    ["sniper_scope"]          = "Circle_White",
    ["sniper_scope4"]        = "Circle_White",
    ["dirty_lens"]            = "Circle_White",
    ["Circle1"]              = "Circle_White",
    ["Circle2"]              = "Circle_White",
    ["Circle3"]              = "Circle_White",
    ["Circle4"]              = "Circle_White",
    ["Circle5"]              = "Circle_White",
    ["Circle_thin_mid"]       = "Circle_White",
    ["Circle_White"]          = "Circle_White",
    ["2_Semi_Circle_2"]       = "U_Shape",
    ["2_Semi_Circle_5"]       = "U_Shape",
    ["Diamond_Left"]          = "Diamond",
    ["Diamond_Crystal"]        = "Diamond_Crystal",
    ["Glass1"]               = "Circle_White",
    ["Glass2"]               = "Circle_White",
    ["cursor1"]              = "Cursor_Arrow_Pattern",
    ["cursor2"]              = "Vibrant_Cursor",
    ["Golden_Ring"]          = "Circle_White",
    ["Golden_Heart"]          = "Heart_1",
    ["Heart_White"]           = "Heart_1",
    ["Heart3"]               = "Heart_1",
    ["Heart5"]               = "Heart_1",
    ["Heart7"]               = "Heart_1",
    ["RGB_Rotate_1"]          = "Circle_White",
    ["Yin_Yang_v1"]          = "Circle_White",
    ["Yin_Yang_1"]          = "Circle_White",
    ["Radar_1"]                 = "Circle_White",
    ["Circle_1_Hovering"]     = "Circle_White",
    ["Circle_focus_1"]          = "Circle_White",
    ["Butterfly_1"]          = "Star_Cursor",
    ["Fairy_Left_1_Hovering"]       = "Star_Cursor",
}



-- Select trail “Effect” categories
local trailEffects = {
    "Star",
    "Shapes",
    "Bubble",
    "Circle",
    "Fantasy",
    "Heart",
    "Magic",
    "Nature",
    "Military",
    "ALL",
}


---------------------------------------------------------------------------
-- Trail Textures
---------------------------------------------------------------------------
EasyCursorTrails.trailTextures = {
    { name = "Dragon_Scale",         texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Fantasy\\Dragon_Scale.blp" },
    { name = "Alien",                texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Fantasy\\Alien3.blp" },
    { name = "Bubble1",             texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Bubble\\Bubble1.tga" },
    { name = "Bubble2",              texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Bubble\\Bubble2.tga" },
    { name = "Bubble3",              texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Bubble\\Bubble3.tga" },
    { name = "Bubble4",              texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Bubble\\Bubble4.tga" },
    { name = "Bubble5",              texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Bubble\\Bubble5.tga" },
    { name = "Bullet Sparks",        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Military\\Bullet_Sparks.tga" },
    { name = "Bullet",               texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Military\\Bullet1.blp" },
    { name = "Circle1",              texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Circle\\Circle1.tga" },
    { name = "Circle1_Trail",        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Circle\\Circle1_Trail.tga" },
    { name = "Circle2",              texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Circle\\Circle2.tga" },
    { name = "Circle2_Trail",        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Circle\\Circle2_Trail.tga" },
    { name = "Circle3",              texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Circle\\Circle3.tga" },
    { name = "Circle3_Trail",        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Circle\\Circle3_Trail.tga" },
    { name = "Circle4",              texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Circle\\Circle4.tga" },
    { name = "Circle5",              texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Circle\\Circle5.tga" },
    { name = "Dragon_Scale",         texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Fantasy\\Dragon_Scale.blp" },
    { name = "Dust_Magic",           texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Magic\\Bright_Dust.blp" },
    { name = "Fairies",              texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Fantasy\\Faries1.blp" },
    { name = "Fairies1_Trail",       texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Fantasy\\Fairies1_Trail.tga" },
    { name = "Fairy",                texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Fantasy\\Fairy_Trail.blp" },
    { name = "Fire1_Fantasy",        texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Fantasy\\Fire1.tga" },
    { name = "Fire1_Magic",          texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Magic\\Fire1.tga" },
    { name = "Flames",               texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Magic\\Flames.tga" },
    { name = "Glitter",              texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Star\\Glitter.tga" },
    { name = "Ghost",                texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Fantasy\\ghost.tga" },
    { name = "Heart1_Trail",         texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Heart\\Heart1_Trail.tga" },
    { name = "Heart4_Trail",         texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Heart\\Heart4_Trail.tga" },
    { name = "Leaf1",                texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Nature\\Leaf1.tga" },
    { name = "Leaf2",                texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Nature\\Leaf2.tga" },
    { name = "Leaf3",                texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Nature\\Leaf3.tga" },
    { name = "Lines",                texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Star\\lines_trail.tga" },
    { name = "Magic_Ball_Trail",     texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Magic\\Magic_Ball_Trail.tga" },
    { name = "Rain",                 texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Nature\\Rain.tga" },
    { name = "Seeds_Circle",         texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Circle\\Seeds.tga" },
    { name = "Star1",                texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Star\\Star1.tga" },
    { name = "Rigth_Arrow",          texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Shapes\\White_Arrow.blp" },
    { name = "Hexagon",              texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Shapes\\Hexagon.blp" },
    { name = "Capsule",              texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Shapes\\Capsule.blp" },
    { name = "Diamond",              texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Shapes\\Diamond.blp" },
    { name = "Star",                 texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Shapes\\Star.blp" },
    { name = "Cross",                texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Shapes\\Cross.blp" },
    { name = "Arrow",                texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Shapes\\Arrow.blp" },
    { name = "snake_scale",          texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Fantasy\\snake_scale.blp" },
    { name = "Chain",                texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Fantasy\\Chain_800_500.blp" },
    { name = "Smiley",               texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Fantasy\\Smiley.blp" },
    { name = "DNA",                  texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Fantasy\\DNA_800_500.blp" },
    { name = "feather",              texture = "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Fantasy\\feather.blp" },
   
}

local function OnTrailTextureSelected(newIndex)
    -- Save the selected texture index to the active profile
    EasyCursorTrails.SaveToCurrentProfile("trailTexture", newIndex)

    -- Rebuild trails to apply the new texture
    if EasyCursorTrails.RebuildTrails then
        EasyCursorTrails.RebuildTrails()
    end
end

function EasyCursorTrails.PopulateTrailTextureDropdown()
    local MAX_PER_LEVEL = 30

    -- Ensure trailTextures exist before proceeding
    if not EasyCursorTrails.trailTextures or #EasyCursorTrails.trailTextures == 0 then
        EasyCursorTrails.trailTextures = {
            { name = "Default Texture", texture = "Interface\\CURSOR\\Arrow" }
        }
    end

    -- Retrieve active profile
    local currentProfileName = EasyCursorTrailsDB.currentProfile or "Default"
    local currentProfile = EasyCursorTrailsDB.profiles[currentProfileName] or {}
    local defaults = EasyCursorTrails.defaults or {}

    -- Get saved trail texture index
    local storedIndex = currentProfile.trailTexture or defaults.trailTexture or 1

    -- Validate stored index before applying
    if storedIndex < 1 or storedIndex > #EasyCursorTrails.trailTextures then
        storedIndex = 1
        EasyCursorTrailsDB.trailTexture = 1
        EasyCursorTrails.SaveToCurrentProfile("trailTexture", 1)
    end

    -- Create dropdown options
    local textureOptions = {}
    for i, textureInfo in ipairs(EasyCursorTrails.trailTextures) do
        table.insert(textureOptions, {
            text = textureInfo.name,
            icon = textureInfo.texture
        })
    end

    -- Initialize dropdown
    UIDropDownMenu_Initialize(EasyCursorTrails.trailTextureDropdown, function(self, level, menuList)
        if not level then return end

        if level == 1 then
            -- Populate main level dropdown
            for i, option in ipairs(textureOptions) do
                if i > MAX_PER_LEVEL then break end

                local info = UIDropDownMenu_CreateInfo()
                info.text = option.text
                if option.icon then
                    info.icon = option.icon
                    info.iconTexCoord = {0, 1, 0, 1}
                    info.iconWidth = 16
                    info.iconHeight = 16
                end
                info.func = function()
                    UIDropDownMenu_SetSelectedID(EasyCursorTrails.profileDropdown, name)
                    UIDropDownMenu_SetText(EasyCursorTrails.profileDropdown, name)
                
                    -- Apply selection
                    EasyCursorTrailsDB.currentProfile = name
                    EasyCursorTrails.settingsChanged = true
                    EasyCursorTrails.SaveToCurrentProfile("currentProfile", name)
                
                    -- Refresh settings
                    if EasyCursorTrails.RefreshSettingsUI then
                        EasyCursorTrails.RefreshSettingsUI()
                    end
                
                    CloseDropDownMenus()
                end
                
                
                UIDropDownMenu_AddButton(info, level)
            end

            -- Add "More..." submenu if options exceed MAX_PER_LEVEL
            if #textureOptions > MAX_PER_LEVEL then
                local info = UIDropDownMenu_CreateInfo()
                info.text = "More..."
                info.hasArrow = true
                info.notCheckable = true
                info.menuList = "TrailTextureDropdown_EXTRA_OPTIONS"
                UIDropDownMenu_AddButton(info, level)
            end

        elseif level == 2 and menuList == "TrailTextureDropdown_EXTRA_OPTIONS" then
            -- Populate second-level menu
            for i, option in ipairs(textureOptions) do
                if i > MAX_PER_LEVEL then
                    local info = UIDropDownMenu_CreateInfo()
                    info.text = option.text
                    if option.icon then
                        info.icon = option.icon
                        info.iconTexCoord = {0, 1, 0, 1}
                        info.iconWidth = 16
                        info.iconHeight = 16
                    end
                    info.func = function()
                        -- Save selected trail texture
                        OnTrailTextureSelected(i)

                        -- Update dropdown UI
                        UIDropDownMenu_SetSelectedID(EasyCursorTrails.trailTextureDropdown, i)
                        UIDropDownMenu_SetText(EasyCursorTrails.trailTextureDropdown, option.text)

                        CloseDropDownMenus()
                    end
                    UIDropDownMenu_AddButton(info, level)
                end
            end
        end
    end)

    -- Ensure dropdown loads saved texture selection
    UIDropDownMenu_SetSelectedID(EasyCursorTrails.trailTextureDropdown, storedIndex)
    UIDropDownMenu_SetText(EasyCursorTrails.trailTextureDropdown, textureOptions[storedIndex].text or "Unknown")
  
end

function EasyCursorTrails.GetRandomTwinkleColor()
    local hue = math.random()
    local saturation = 0.7 + math.random() * 0.3
    local value = 0.8 + math.random() * 0.2

    -- HSV to RGB conversion
    local i = math.floor(hue * 6)
    local f = hue * 6 - i
    local p = value * (1 - saturation)
    local q = value * (1 - f * saturation)
    local t = value * (1 - (1 - f) * saturation)

    local r, g, b
    if i % 6 == 0 then r, g, b = value, t, p
    elseif i == 1 then r, g, b = q, value, p
    elseif i == 2 then r, g, b = p, value, t
    elseif i == 3 then r, g, b = p, q, value
    elseif i == 4 then r, g, b = t, p, value
    elseif i == 5 then r, g, b = value, p, q end

    return { r = r, g = g, b = b, a = 1 }
end


function EasyCursorTrails.GetTwinkleStarsColor(profile)
    if not profile then
        return { r = 1, g = 1, b = 1, a = 1 } -- default white sparkle
    end

    if profile.randomTwinkleStarsColor then
        return {
            r = math.random(),
            g = math.random(),
            b = math.random(),
            a = profile.twinkleStarsAlpha or 1
        }
    else
        return profile.twinkleStarsColor or { r = 1, g = 1, b = 1, a = 1 }
    end
end



function EasyCursorTrails.ApplyTwinkleStarsEffect(trail, index, intensity)
    if not trail then return end

    -- Expanded sparkle container
    local expansion = 1.5
    trail.twinkleSpark = trail.twinkleSpark or CreateFrame("Frame", nil, trail)
    trail.twinkleSpark:SetSize(trail:GetWidth() * expansion, trail:GetHeight() * expansion)
    trail.twinkleSpark:SetPoint("CENTER", trail, "CENTER")

    -- ✨ Retrieve color from profile or fallback to defaults
    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile] or {}
    local defaultColor = EasyCursorTrails.defaults and EasyCursorTrails.defaults.twinkleStarsColor or { r = 0.9, g = 0.95, b = 1, a = 1 }
    local color = profile.twinkleStarsRandomColor and EasyCursorTrails.GetRandomTwinkleColor()
    or profile.twinkleStarsColor
    or { r = 1, g = 1, b = 1, a = 1 }


    local tex = trail.twinkleSpark.texture
    if not tex then
        tex = trail.twinkleSpark:CreateTexture(nil, "OVERLAY")
        trail.twinkleSpark.texture = tex
        tex:SetTexture("Interface\\Cooldown\\star4")
        tex:SetBlendMode("ADD")
        tex:SetAllPoints()
    end


    if trail.twinkleSpark.ag then
        trail.twinkleSpark.ag:Stop()
    end

    local ag = trail.twinkleSpark:CreateAnimationGroup()
    trail.twinkleSpark.ag = ag

    local angle = math.random() * 360
    local dist = 6 + math.random() * 16
    local dx = math.cos(math.rad(angle)) * dist
    local dy = math.sin(math.rad(angle)) * dist

    local t = ag:CreateAnimation("Translation")
    t:SetOffset(dx, dy)
    t:SetDuration(0.10)
    t:SetOrder(1)

    local a = ag:CreateAnimation("Alpha")
    a:SetFromAlpha(0.90)
    a:SetToAlpha(0)
    a:SetDuration(0.1)
    a:SetOrder(1)

    ag:SetScript("OnFinished", function()
        C_Timer.After(math.random(20, 80) / 1000, function()
            EasyCursorTrails.ApplyTwinkleStarsEffect(trail, index, intensity)
        end)
    end)

    ag:SetLooping("NONE")
    ag:Play()
end

--==========================================================================================

function EasyCursorTrails.ClearStaticArcEffect(trail)
  if not trail then return end

  -- Stop animation if active
  if trail.arcEmitter and trail.arcEmitter.ag then
    trail.arcEmitter.ag:Stop()
  end

  -- Hide and detach emitter safely
  if trail.arcEmitter then
    trail.arcEmitter:Hide()
    trail.arcEmitter:SetParent(nil)

    -- Clear vertex color and texture if applicable
    if trail.arcEmitter.SetVertexColor then
      trail.arcEmitter:SetVertexColor(0, 0, 0, 0)
    end
    if trail.arcEmitter.SetTexture then
      trail.arcEmitter:SetTexture(nil)
    end

    trail.arcEmitter = nil
  end

  -- Optional: Remove arcEmitter reference from trail frame if it still exists
  if rawget(trail, "arcEmitter") then
    rawset(trail, "arcEmitter", nil)
  end
end

-- Clamp helper (define once at top of file)
if not math.clamp then
    function math.clamp(val, min, max)
        return math.max(min, math.min(max, val))
    end
end

-- Create overlay container if needed
if not EasyCursorTrails.arcOverlay then
    EasyCursorTrails.arcOverlay = CreateFrame("Frame", nil, UIParent)
    EasyCursorTrails.arcOverlay:SetAllPoints(UIParent)
    EasyCursorTrails.arcOverlay:SetFrameStrata("TOOLTIP")
end



function EasyCursorTrails.ApplyStaticArcEffect(trail, index, color)
    if not trail then return end

    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile] or {}
    local defaultColor = EasyCursorTrails.defaults and EasyCursorTrails.defaults.staticArcColor or { r = 1, g = 1, b = 1, a = 1 }

    -- 🌀 Respect randomStaticArcColor from profile
    local useRandom = profile.randomStaticArcColor
    color = useRandom and EasyCursorTrails.GetRandomTwinkleColor()
        or color
        or profile.staticArcColor
        or defaultColor

    if not trail.arcEmitter then
        local emitter = CreateFrame("Frame", nil, trail)
        emitter:SetSize(trail:GetWidth() * 2.0, trail:GetHeight() * 2.0)
        emitter:SetPoint("CENTER", trail)
        emitter:Show()

        local tex = emitter:CreateTexture(nil, "OVERLAY")
        emitter.texture = tex
        tex:SetTexture("Interface\\Cooldown\\star4")
        tex:SetBlendMode("ADD")
        tex:SetAllPoints()

        -- ✨ Slight randomized hue variation
        tex:SetVertexColor(
            (color.r or 1) * (0.95 + math.random() * 0.1),
            (color.g or 1) * (0.95 + math.random() * 0.1),
            (color.b or 1),
            color.a or 0.6
        )
        tex:SetRotation(math.random() * 6.28)

        local ag = emitter:CreateAnimationGroup()
        emitter.ag = ag

        local flick = ag:CreateAnimation("Alpha")
        flick:SetFromAlpha(0.1)
        flick:SetToAlpha(0.7)
        flick:SetDuration(0.05)
        flick:SetSmoothing("IN_OUT")
        flick:SetOrder(1)

        local scale = ag:CreateAnimation("Scale")
        scale:SetScale(1.3 + math.random() * 0.4, 1.2)
        scale:SetOrigin("CENTER", 0, 0)
        scale:SetDuration(0.05)
        scale:SetSmoothing("OUT")
        scale:SetOrder(1)

        local drift = ag:CreateAnimation("Translation")
        drift:SetOffset(math.random(-10, 10), math.random(-10, 10))
        drift:SetDuration(0.08)
        drift:SetSmoothing("IN_OUT")
        drift:SetOrder(2)

        local fade = ag:CreateAnimation("Alpha")
        fade:SetFromAlpha(0.6)
        fade:SetToAlpha(0.1)
        fade:SetDuration(0.06)
        fade:SetOrder(3)

        ag:SetLooping("REPEAT")
        ag:Play()

        trail.arcEmitter = emitter
    end
end

--===================================================================================================
function EasyCursorTrails.StartLightningSparkEffect()
    EasyCursorTrails.StopLightningSparkEffect()

    EasyCursorTrails.lightningSparkTicker = C_Timer.NewTicker(0.05, function()
        local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
        if not (profile and profile.enableLightningSparks) then return end

        local pool = EasyCursorTrails.trailPool
        if not pool or #pool == 0 then return end

        local mode = math.random(1, 4)

        local function getTrailByMode()
            -- ✅ Pick a random layer safely
            local layerIndex = math.random(1, #pool)
            local layer = pool[layerIndex]
            if not layer or #layer == 0 then return nil end

            local count = #layer

            -- ✅ Mode 1: pick from second half
            if mode == 1 and count >= 2 then
                local startIndex = math.max(1, math.floor(count / 2))
                return layer[math.random(startIndex, count)]

            -- ✅ Mode 2: pick from first half
            elseif mode == 2 and count >= 2 then
                local endIndex = math.max(1, math.floor(count / 2))
                return layer[math.random(1, endIndex)]

            -- ✅ Mode 3: pick topmost visible trail with decent size
            elseif mode == 3 then
                local sortedLayer = {}
                for _, trail in ipairs(layer) do
                    if trail:IsVisible() and trail.texture then
                        local w, h = trail.texture:GetSize()
                        if w > 4 and h > 4 then
                            table.insert(sortedLayer, trail)
                        end
                    end
                end

                table.sort(sortedLayer, function(a, b)
                    return (a:GetTop() or 0) > (b:GetTop() or 0)
                end)

                return sortedLayer[1] -- topmost valid trail or nil

            -- ✅ Mode 4 (fallback): pick any
            else
                return layer[math.random(1, count)]
            end
        end

        local trail = getTrailByMode()
        if trail and trail:IsVisible() then
            EasyCursorTrails.ApplyLightningSparkEffect(trail)
        end
    end)
end


function EasyCursorTrails.StopLightningSparkEffect()
    if EasyCursorTrails.lightningSparkTicker then
        EasyCursorTrails.lightningSparkTicker:Cancel()
        EasyCursorTrails.lightningSparkTicker = nil
    end

    if EasyCursorTrails.trailPool then
        for _, layer in ipairs(EasyCursorTrails.trailPool) do
            for _, trail in ipairs(layer) do
                EasyCursorTrails.ClearLightningSparkEffect(trail)
            end
        end
    end
end


function EasyCursorTrails.ResetTrailTexture(trail)
    if not trail or not trail.texture then return end

    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    local startSize = tonumber(profile and profile.trailSizeStart) or EasyCursorTrails.defaults.trailSizeStart or 32

    local nativeW = trail.texture:GetWidth()
    local nativeH = trail.texture:GetHeight()

    -- 🛡️ Skip malformed or uninitialized textures
    if nativeW < 4 or nativeH < 4 then return end

    local scaleFactor = startSize / math.max(nativeW, nativeH)
    scaleFactor = math.min(math.max(scaleFactor, 0.5), 2.0) -- optional clamping

    trail.texture:SetTexCoord(0, 1, 0, 1)
    trail.texture:SetSize(nativeW, nativeH)

    -- 🧠 Only apply scale if it changed
    if trail._lastResetScale ~= scaleFactor then
        trail.texture:SetScale(scaleFactor)
        trail._lastResetScale = scaleFactor
    end

    trail.texture:ClearAllPoints()
    trail.texture:SetPoint("CENTER", trail, "CENTER")
end




function EasyCursorTrails.ClearLightningSparkEffect(trail)
    if not trail or not trail.lightningSpark then return end

    if trail.lightningSpark.ag then
        trail.lightningSpark.ag:Stop()
    end

    trail.lightningSpark:Hide()
    trail.lightningSpark:SetParent(nil)
    trail.lightningSpark = nil
end


function EasyCursorTrails.ApplyLightningSparkEffect(trail)
    if not trail or not trail.texture or not trail:IsVisible() then return end

    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    if not profile then return end

    -- 🔧 Get start and end sizes from profile or fallback
    local startSize = tonumber(profile.trailSizeStart) or EasyCursorTrails.defaults.trailSizeStart or 32
    local endSize = tonumber(profile.trailSizeEnd) or EasyCursorTrails.defaults.trailSizeEnd or 48

    -- 🧼 Reset trail texture to start size
    trail.texture:SetTexCoord(0, 1, 0, 1)
    local nativeW = trail.texture:GetWidth()
    local nativeH = trail.texture:GetHeight()
    local scaleFactor = (tonumber(profile.trailSizeStart) or EasyCursorTrails.defaults.trailSizeStart or 32) / math.max(nativeW, nativeH)

    trail.texture:SetSize(nativeW, nativeH)
    trail.texture:SetScale(scaleFactor)

    trail.texture:ClearAllPoints()
    trail.texture:SetPoint("CENTER", trail, "CENTER")

    -- 🎨 Color logic
    local rawColor = profile.randomLightningSparkColor and EasyCursorTrails.GetRandomVibrantColor()
        or profile.lightningSparkColor or { r = 0.8, g = 0.9, b = 1, a = 1 }

    local function sanitizeColor(c)
        return {
            r = tonumber(c.r) or 1,
            g = tonumber(c.g) or 1,
            b = tonumber(c.b) or 1,
            a = tonumber(c.a) or 0.8
        }
    end
    local color = sanitizeColor(rawColor)

    -- ⏱ Spark timing
    trail._nextSparkDelay = trail._nextSparkDelay or 0
    if GetTime() < (trail.lastSparkTime or 0) + trail._nextSparkDelay then return end
    trail.lastSparkTime = GetTime()
    trail._nextSparkDelay = math.random(10, 50) / 100

    -- ⚡ Spark geometry based on end size
    local baseScale = endSize * 0.50
    local segmentLength = baseScale * 0.40
    local segmentCount = 10
    local angleSpread = 0.15
    local rootAngle = math.random() * 2 * math.pi

    for i = 1, segmentCount do
        local t = i / segmentCount
        local theta = rootAngle + (math.random() - 0.5) * angleSpread
        local dist = segmentLength * i
        local x = math.cos(theta) * dist
        local y = math.sin(theta) * dist
        local alpha = math.max(color.a * (1.0 - math.abs(t - 0.5) * 1.4), 0.6)
        local duration = math.random(15, 60) / 100

        local glow = CreateFrame("Frame", nil, trail)
        glow:SetSize(baseScale, baseScale)
        glow:SetPoint("CENTER", trail, "CENTER", x, y)
        glow:SetFrameStrata("HIGH")
        glow:SetFrameLevel(trail:GetFrameLevel() + 6)

        local tex = glow:CreateTexture(nil, "OVERLAY")
        tex:SetAllPoints()
        tex:SetTexture("Interface\\GLUES\\MODELS\\UI_Draenei\\GenericGlow64")
        tex:SetBlendMode("ADD")
        tex:SetRotation(theta)
        tex:SetTexCoord(0, 1, 0, 1)
        tex:SetVertexColor(color.r, color.g, color.b, alpha)

        local ag = glow:CreateAnimationGroup()
        ag:SetLooping("NONE")
        ag:SetScript("OnFinished", function()
            glow:Hide()
            tex:SetTexture(nil)
            tex:SetParent(nil)
            glow:SetParent(nil)
        end)

        local fade = ag:CreateAnimation("Alpha")
        fade:SetFromAlpha(1)
        fade:SetToAlpha(0)
        fade:SetDuration(duration)
        fade:SetOrder(1)
        ag:Play()

        -- 🌩 Branching logic
        if math.random() < 0.10 then
            local branchAngle = theta + ((math.random() - 0.5) * math.pi)
            local branchCount = math.random(2, 3)
            local branchFactor = math.random(1.0, 1.4)

            for j = 1, branchCount do
                local bDist = segmentLength * j * branchFactor
                local bx = x + math.cos(branchAngle) * bDist
                local by = y + math.sin(branchAngle) * bDist
                local bAlpha = alpha * (1 - j / branchCount) ^ 1.3
                local branchDuration = duration + j * 0.08

                local branch = CreateFrame("Frame", nil, trail)
                branch:SetSize(baseScale * 0.15, baseScale * 0.15)
                branch:SetPoint("CENTER", trail, "CENTER", bx, by)
                branch:SetFrameStrata("HIGH")
                branch:SetFrameLevel(trail:GetFrameLevel() + 5)

                local branchTex = branch:CreateTexture(nil, "OVERLAY")
                branchTex:SetAllPoints()
                branchTex:SetTexture("Interface\\GLUES\\MODELS\\UI_Draenei\\GenericGlow64")
                branchTex:SetBlendMode("ADD")
                branchTex:SetRotation(branchAngle)
                branchTex:SetTexCoord(0, 1, 0, 1)
                branchTex:SetVertexColor(color.r, color.g, color.b, bAlpha)

                local bag = branch:CreateAnimationGroup()
                bag:SetLooping("NONE")
                bag:SetScript("OnFinished", function()
                    branch:Hide()
                    branchTex:SetTexture(nil)
                    branchTex:SetParent(nil)
                    branch:SetParent(nil)
                end)

                local bfade = bag:CreateAnimation("Alpha")
                bfade:SetFromAlpha(1)
                bfade:SetToAlpha(0)
                bfade:SetDuration(branchDuration)
                bfade:SetOrder(1)
                bag:Play()
            end

            -- 🌊 Ripple-style discharge
            if math.random() < 0.6 then
                local ripple = CreateFrame("Frame", nil, UIParent)
                ripple:SetSize(32, 32)
                ripple:SetPoint("CENTER", trail, "CENTER", 0, 0)
                ripple:SetFrameStrata("HIGH")
                ripple:SetFrameLevel(trail:GetFrameLevel() + 7)

                local tex = ripple:CreateTexture(nil, "OVERLAY")
                tex:SetAllPoints()
                tex:SetTexture("Interface\\Cooldown\\ping4")
                tex:SetBlendMode("ADD")
                tex:SetTexCoord(0, 1, 0, 1)
                tex:SetVertexColor(color.r, color.g, color.b, color.a)

                local ag = ripple:CreateAnimationGroup()
                ag:SetLooping("NONE")

                local scale = ag:CreateAnimation("Scale")
                scale:SetScaleFrom(1, 1)
                scale:SetScaleTo(2.0, 2.0)
                scale:SetDuration(0.5)
                scale:SetOrder(1)

                local fade = ag:CreateAnimation("Alpha")
                fade:SetFromAlpha(1)
                fade:SetToAlpha(0)
                fade:SetDuration(0.4)
                fade:SetOrder(2)

                ag:SetScript("OnFinished", function()
                    ripple:Hide()
                    tex:SetTexture(nil)
                    tex:SetParent(nil)
                    ripple:SetParent(nil)
                end)

                ag:Play()
            end

        end
    end
end





--=========================================================================================================
function EasyCursorTrails.GetRandomVibrantColor()
    local colors = {
        { r = 1, g = 0.5, b = 0.5, a = 0.6 }, -- soft red
        { r = 0.5, g = 1, b = 0.5, a = 0.6 }, -- soft green
        { r = 0.5, g = 0.5, b = 1, a = 0.6 }, -- soft blue
        { r = 1, g = 1, b = 0.5, a = 0.6 }, -- yellowish
        { r = 0.8, g = 0.5, b = 1, a = 0.6 }, -- purple
    }
    return colors[math.random(#colors)]
end





function EasyCursorTrails.HSVtoRGB(h, s, v, a)
    local r, g, b
    local i = math.floor(h * 6)
    local f = h * 6 - i
    local p = v * (1 - s)
    local q = v * (1 - f * s)
    local t = v * (1 - (1 - f) * s)
    i = i % 6
    if i == 0 then r, g, b = v, t, p
    elseif i == 1 then r, g, b = q, v, p
    elseif i == 2 then r, g, b = p, v, t
    elseif i == 3 then r, g, b = p, q, v
    elseif i == 4 then r, g, b = t, p, v
    elseif i == 5 then r, g, b = v, p, q end
    return { r = r, g = g, b = b, a = a or 1 }
end

--==========================================================================================
function EasyCursorTrails.StartStarTicker()
    EasyCursorTrails.StopStarTicker()

    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    if not profile then return end

    EasyCursorTrails.SaveToCurrentProfile("enableStarEmbers", true)

    EasyCursorTrails.starTicker = C_Timer.NewTicker(math.random(22, 30) / 100, function()
        if not profile.enableStarEmbers then return end

        for _, pool in pairs(EasyCursorTrails.trailPool or {}) do
            for _, trail in ipairs(pool) do
                if trail:IsVisible() then
                    EasyCursorTrails.SpawnSparkles(trail)
                end
            end
        end
    end)
end

function EasyCursorTrails.StopStarTicker()
    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    if profile then
        EasyCursorTrails.SaveToCurrentProfile("enableStarEmbers", false)
    end

    if EasyCursorTrails.starTicker then
        EasyCursorTrails.starTicker:Cancel()
        EasyCursorTrails.starTicker = nil
    end
end

function EasyCursorTrails.SpawnSparkles(trail)
    if not trail or not trail:IsVisible() then return end

    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    if not profile or not profile.enableStarEmbers then return end

    local trailSize = trail:GetWidth() or 15
    local baseScale = trailSize * 1.2
    local trailX, trailY = trail:GetCenter()
    if not trailX or not trailY then return end

    for _ = 1, math.random(1, 2) do
        local offsetX = (math.random() - 0.5) * trailSize
        local offsetY = (math.random() - 0.5) * trailSize
        local sparkleX = trailX + offsetX
        local sparkleY = trailY + offsetY

        local scaleMult = math.random(30, 95) / 100
        local sparkleSize = baseScale * scaleMult
        local alpha = math.min(0.6 + scaleMult * 0.4, 1)

        local sparkle = CreateFrame("Frame", nil, UIParent)
        sparkle:SetPoint("CENTER", UIParent, "BOTTOMLEFT", sparkleX, sparkleY)
        sparkle:SetSize(sparkleSize, sparkleSize)
        sparkle:SetFrameStrata("MEDIUM")
        sparkle:SetFrameLevel((trail:GetFrameLevel() or 2) + 2)

        local tex = sparkle:CreateTexture(nil, "OVERLAY")
        tex:SetAllPoints()
        tex:SetBlendMode("ADD")
        tex:SetTexture("Interface\\Cooldown\\star4")
        tex:SetTexCoord(0.2, 0.8, 0.2, 0.8) -- Crop edges to reduce square feel
        tex:SetRotation(math.random() * 6.28)

        local color = profile.randomStarColor and EasyCursorTrails.GetRandomVibrantColor()
            or profile.starColor
            or { r = 1, g = 0.4, b = 0.1, a = 1 }

        tex:SetVertexColor(color.r, color.g, color.b, alpha)

        local driftAg = sparkle:CreateAnimationGroup()
        driftAg:SetLooping("NONE")
        driftAg:SetScript("OnFinished", function()
            sparkle:Hide()
            tex:SetTexture(nil)
            tex:SetParent(nil)
            sparkle:SetParent(nil)
            sparkle:ClearAllPoints()
        end)

        local driftAngle = math.random() * 2 * math.pi
        local driftDist = math.random(14, 20)
        local driftX = math.cos(driftAngle) * driftDist
        local driftY = math.sin(driftAngle) * driftDist
        local driftDur = math.min(1.0 + scaleMult * 0.10, 1.0)

        local drift = driftAg:CreateAnimation("Translation")
        drift:SetOffset(driftX, driftY)
        drift:SetDuration(driftDur)
        drift:SetOrder(1)
        drift:SetSmoothing("IN_OUT")

        local rotate = driftAg:CreateAnimation("Rotation")
        rotate:SetDegrees(math.random(-25, 25))
        rotate:SetDuration(driftDur)
        rotate:SetOrder(1)
        rotate:SetSmoothing("IN_OUT")

        local fade = driftAg:CreateAnimation("Alpha")
        fade:SetFromAlpha(alpha * 0.2)
        fade:SetToAlpha(0)
        fade:SetDuration(0.2)
        fade:SetOrder(2)
        fade:SetSmoothing("OUT")

        driftAg:Play()

        local sparkleAg = tex:CreateAnimationGroup()
        sparkleAg:SetLooping("REPEAT")

        local twinkle = sparkleAg:CreateAnimation("Alpha")
        twinkle:SetFromAlpha(alpha * math.random(0.4, 0.6))
        twinkle:SetToAlpha(alpha)
        twinkle:SetDuration(math.random(0.3, 0.5))
        twinkle:SetSmoothing("IN_OUT")
        twinkle:SetOrder(1)
        twinkle:SetStartDelay(math.random(0, 40) / 100)

        local dim = sparkleAg:CreateAnimation("Alpha")
        dim:SetFromAlpha(alpha)
        dim:SetToAlpha(alpha * math.random(0.4, 0.6))
        dim:SetDuration(math.random(0.3, 0.5))
        dim:SetSmoothing("IN_OUT")
        dim:SetOrder(2)

        sparkleAg:Play()
    end
end



--==========================================================================================
function EasyCursorTrails.StartNatureTicker()
   --test")
    if EasyCursorTrails.lightningTicker then
      
        EasyCursorTrails.lightningTicker:Cancel()
    end

    EasyCursorTrails.lightningTicker = C_Timer.NewTicker(0.25, function()
        local profile = EasyCursorTrails.currentProfileTable 
                     or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
        if not profile or not profile.enableSpringSeasonTrails then return end


        for _, pool in pairs(EasyCursorTrails.trailPool or {}) do
            for _, trail in ipairs(pool) do
                if trail:IsVisible() then
                    local nowX, nowY = trail:GetCenter()
                    local last = trail._lastPos or { x = nowX, y = nowY }

                    if nowX and nowY and (math.abs(nowX - last.x) > 0.5 or math.abs(nowY - last.y) > 0.5) then
                        EasyCursorTrails.SpawnNatureEmbersAt(last.x, last.y, trail:GetWidth())
                    end

                    trail._lastPos = { x = nowX, y = nowY }
                end
            end
        end
    end)
end


function EasyCursorTrails.SpawnNatureEmbersAt(centerX, centerY, baseScale)
    local mockTrail = {
        GetCenter = function() return centerX, centerY end,
        IsVisible = function() return true end
    }
   EasyCursorTrails.SpawnNatureEmbers(
    baseScale,
    centerX,
    centerY,
    0,    -- offsetX
    0     -- offsetY
)

end


function EasyCursorTrails.StopNatureTicker()
  
    if EasyCursorTrails.lightningTicker then
        EasyCursorTrails.lightningTicker:Cancel()
        EasyCursorTrails.lightningTicker = nil
    end
end

function EasyCursorTrails.SpawnNatureEmbers(baseScale, baseX, baseY, offsetX, offsetY)
    local profile = EasyCursorTrails.currentProfileTable
                 or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    if not profile then return end

    local color = profile.randomLightningColor and EasyCursorTrails.GetRandomVibrantColor()
               or profile.lightningEmberColor or { r = 0.8, g = 0.9, b = 1, a = 0.8 }

    local emberX = baseX + offsetX + (math.random() - 0.5) * 10
    local emberY = baseY + offsetY + (math.random() - 0.5) * 8

    for _ = 1, math.random(1, 2) do
        if math.random() < 0.3 then
            local sizeMult = math.random(30, 60) / 100
            local emberLength = baseScale * sizeMult * 2.5
            local emberWidth  = baseScale * sizeMult * 2.5
            local alpha = math.min(0.7 + sizeMult * 0.6, 1.0)


            local spark = CreateFrame("Frame", nil, UIParent)
            spark:SetPoint("CENTER", UIParent, "BOTTOMLEFT", emberX, emberY)
            spark:SetSize(emberLength, emberWidth)
            spark:SetFrameStrata("TOOLTIP")
            spark:SetFrameLevel(20)
            spark:Show()

            local tex = spark:CreateTexture(nil, "OVERLAY")
            tex:SetAllPoints()
            local leafTextures = {
                "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Nature\\Petal.blp",
                "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Nature\\Petal2.blp",
                "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Nature\\Red_Rose.blp",
                "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Nature\\Leaf1.tga",
                "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Nature\\Leaf3.tga",
                "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Nature\\Dandelion.blp",
                "Interface\\AddOns\\EasyCursorTrails\\Textures\\Trails\\Nature\\flower1.blp"
            }
            tex:SetTexture(leafTextures[math.random(#leafTextures)])
            tex:SetBlendMode("ADD")
            tex:SetVertexColor(color.r * 1.2, color.g * 1.2, color.b * 1.2, alpha)

            tex:SetRotation(math.random() * 2 * math.pi)

            local ag = spark:CreateAnimationGroup()
            ag:SetLooping("NONE")
            ag:SetScript("OnFinished", function()
                spark:Hide()
                tex:SetTexture(nil)
                tex:SetParent(nil)
                spark:SetParent(nil)
            end)

            local driftAngle = math.random() * 2 * math.pi
            local driftDist = math.random(24, 56)
            local driftX = math.cos(driftAngle) * driftDist
            local driftY = math.sin(driftAngle) * driftDist

            -- 🧩 Fade and drift together
            local drift = ag:CreateAnimation("Translation")
            drift:SetOffset(driftX, driftY)
            drift:SetDuration(2.0)
            drift:SetOrder(1)
            drift:SetSmoothing("IN_OUT")

            local fade = ag:CreateAnimation("Alpha")
            fade:SetFromAlpha(alpha)
            fade:SetToAlpha(0)
            fade:SetDuration(2.0)
            fade:SetOrder(1)
            fade:SetSmoothing("IN_OUT")

            -- 🌪️ Leaf flutter wobble
            local rotate = ag:CreateAnimation("Rotation")
            rotate:SetDegrees((math.random() - 0.5) * 80)
            rotate:SetDuration(2.0)
            rotate:SetOrder(1)
            rotate:SetSmoothing("IN_OUT")

            -- 🫧 Gentle bounce pulse
            local pulse = ag:CreateAnimation("Scale")
            pulse:SetScaleFrom(1.0, 1.0)
            pulse:SetScaleTo(1.05, 0.95)
            pulse:SetDuration(0.4)
            pulse:SetOrder(1)
            pulse:SetSmoothing("IN_OUT")

            ag:Play()
        end
    end
end





--==========================================================================================


--==========================================================================================



function EasyCursorTrails.SpawnTrailShadow(trail)
    if not trail or not trail.texture then return end

    local profile = EasyCursorTrails.currentProfileTable
        or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    if not profile or not profile.enableTrailShadows then return end

    if not trail.shadowFrame then
        local frame = CreateFrame("Frame", nil, UIParent)
        frame:SetSize(trail:GetWidth(), trail:GetHeight())
        frame:SetFrameStrata("BACKGROUND")
        frame:SetFrameLevel(0)

        local offsetTex = frame:CreateTexture(nil, "BACKGROUND")
        offsetTex:SetPoint("CENTER", frame, "CENTER")
        offsetTex:SetTexture(trail.texture:GetTexture())
        offsetTex:SetBlendMode("BLEND")

        local glowTex = frame:CreateTexture(nil, "BACKGROUND")
        glowTex:SetPoint("CENTER", frame, "CENTER")
        glowTex:SetTexture(trail.texture:GetTexture())
        glowTex:SetBlendMode("ADD")

        frame.offsetTex = offsetTex
        frame.glowTex = glowTex

        trail.shadowFrame = frame
        trail._lastShadowPos = { x = 0, y = 0 }
        trail._shadowIdleTime = 0
        trail._lastShadowScale = trail:GetScale()
    end

    trail:SetScript("OnUpdate", function(self, elapsed)
        local shadow = self.shadowFrame
        if not shadow or not shadow.offsetTex or not shadow.glowTex then return end

        local profile = EasyCursorTrails.currentProfileTable
            or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
        if not profile or not profile.enableTrailShadows then
            shadow:Hide()
            return
        end

        if not self:IsVisible() or (self.texture:GetAlpha() or 0) <= 0.01 then
            shadow:Hide()
            return
        end

        local trailX, trailY = self:GetCenter()
        if not trailX or not trailY then return end

        local last = self._lastShadowPos or { x = trailX, y = trailY }
        self._shadowIdleTime = (self._shadowIdleTime or 0) + elapsed

        local dx = trailX - last.x
        local dy = trailY - last.y
        local moved = math.abs(dx) > 0.5 or math.abs(dy) > 0.5
        local idleFadeFactor = moved and 1 or math.max(0, 1 - self._shadowIdleTime * 1.8)

        if moved then
            self._lastShadowPos = { x = trailX, y = trailY }
            self._shadowIdleTime = 0
        end

        local angle = math.atan2(dy, dx)
        shadow.offsetTex:SetRotation(angle)
        shadow.glowTex:SetRotation(angle)

        local screenHeight = UIParent:GetHeight()
        local trailYRatio = math.max(0, math.min(1, trailY / screenHeight))
        local dropOffset = math.max(0, math.min(350, trailYRatio * 350))
        local baseOffset = 5

        local isTilting = IsMouseButtonDown("RightButton")
        local tiltFade = isTilting and 0.5 or 1.0
        local shadowDarknessFactor = 1 - trailYRatio
        local alphaBoost = 1.0 + shadowDarknessFactor * 0.5
        local offsetAlpha = 0.13 * idleFadeFactor * tiltFade * alphaBoost
        local glowAlpha   = 0.18 * idleFadeFactor * tiltFade * alphaBoost

        -- Smooth interpolation helper
        local function Lerp(a, b, t)
            return a + (b - a) * t
        end

        local trailScale = self:GetScale() or 1
        local shrinkFactor = 1 - (1 - idleFadeFactor) * 0.3
        local upwardBoost = (dy > 1) and (1 + 0.6 * trailYRatio) or 1.0
        local targetScale = trailScale * shrinkFactor

        if dy < -1 then
            -- Smoothly shrink when descending
            self._lastShadowScale = Lerp(self._lastShadowScale or trailScale, targetScale, math.min(1, elapsed * 6))
        else
            -- Snap or expand upward
            self._lastShadowScale = trailScale * shrinkFactor * upwardBoost
        end

        local maxShadowScale = self._lastShadowScale or trailScale

        local w, h = trail:GetWidth(), trail:GetHeight()
        shadow.offsetTex:SetSize(w * maxShadowScale, h * maxShadowScale)
        shadow.glowTex:SetSize(w * maxShadowScale, h * maxShadowScale)

        local color = profile.randomShadowColor and EasyCursorTrails.GetRandomVibrantColor()
            or profile.shadowTrailColor or { r = 0, g = 0, b = 0, a = 0.4 }
        shadow.offsetTex:SetVertexColor(color.r * 0.5, color.g * 0.5, color.b * 0.5, offsetAlpha)
        shadow.glowTex:SetVertexColor(color.r * 1.1, color.g * 1.1, color.b * 1.1, glowAlpha)

        shadow:SetPoint("CENTER", UIParent, "BOTTOMLEFT", trailX - baseOffset, trailY - (baseOffset + dropOffset))

        shadow:Show()
    end)
end

--==========================================================================================

function EasyCursorTrails.StartEmberTicker()
    if EasyCursorTrails.emberTicker then
        EasyCursorTrails.emberTicker:Cancel()
    end

    EasyCursorTrails.emberTicker = C_Timer.NewTicker(0.25, function()
        local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
        if not profile or not profile.enableEmbers then return end

        for _, pool in pairs(EasyCursorTrails.trailPool or {}) do
            for _, trail in ipairs(pool) do
                if trail:IsVisible() then
                    EasyCursorTrails.SpawnEmberEffect(trail)
                end
            end
        end
    end)
end


function EasyCursorTrails.StopEmberTicker()
    if EasyCursorTrails.emberTicker then
        EasyCursorTrails.emberTicker:Cancel()
        EasyCursorTrails.emberTicker = nil
    end
end


function EasyCursorTrails.SpawnEmberEffect(trail)
    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    if not profile then return end

    -- 🧯 Stop early if embers are disabled or trail isn't visible enough
    if not profile.enableEmbers or not trail:IsVisible() or trail:GetAlpha() < 0.1 then return end

    -- 🎯 Gather trail dimensions and position
    local trailSize = trail:GetWidth() or 15
    local baseScale = trailSize * 0.9

    local trailX, trailY = trail:GetCenter()
    if not trailX or not trailY then return end -- 🛡️ Prevent nil crash

    -- 🌠 Randomized ember offset
    local offsetX = (math.random() - 0.5) * trailSize * 0.4
    local offsetY = (math.random() - 0.5) * trailSize * 0.4

    local baseX = trailX
    local baseY = trailY

    -- 🧪 Optional debugging: Log spawn origin
    -- print("Spawning Ember at:", baseX + offsetX, baseY + offsetY)

    EasyCursorTrails.SpawnEmbers(trail, baseScale, baseX, baseY, offsetX, offsetY)
end


function EasyCursorTrails.SpawnEmbers(trail, baseScale, baseX, baseY, offsetX, offsetY)
    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    if not profile then return end

    local color = profile.randomEmberColor and EasyCursorTrails.GetRandomVibrantColor()
        or profile.emberColor
        or { r = 1, g = 0.4, b = 0.1, a = 0.8 }

    local emberX = baseX + offsetX + (math.random() - 0.5) * 16
    local emberY = baseY + offsetY + (math.random() - 0.5) * 12


    for _ = 1, math.random(1, 2) do
        if math.random() < 0.3 then
            local sizeMult = math.random(20, 50) / 100
            local emberSize = baseScale * sizeMult
            local alpha = math.min(0.9 + sizeMult * 0.5, 0.8)

            local ember = CreateFrame("Frame", nil, UIParent)
            ember:SetPoint("CENTER", UIParent, "BOTTOMLEFT", emberX, emberY)
            ember:SetSize(emberSize, emberSize)
            ember:SetFrameStrata("BACKGROUND")
            ember:SetFrameLevel(1)

            local tex = ember:CreateTexture(nil, "OVERLAY")
            tex:SetAllPoints()
            tex:SetTexture("Interface\\GLUES\\MODELS\\UI_Draenei\\GenericGlow64")
            tex:SetBlendMode("ADD")
            tex:SetVertexColor(color.r, color.g, color.b, alpha)

            local ag = ember:CreateAnimationGroup()
            ag:SetLooping("NONE")
            ag:SetScript("OnFinished", function()
                ember:Hide()
                tex:SetTexture(nil)
                tex:SetParent(nil)
                ember:SetParent(nil)
            end)

            local driftAngle = math.random() * 2 * math.pi
            local driftDistance = math.random(8, 50)
            local driftX = math.cos(driftAngle) * driftDistance
            local driftY = math.sin(driftAngle) * driftDistance

            local drift = ag:CreateAnimation("Translation")
            drift:SetOffset(driftX, driftY)
            drift:SetDuration(2.0)
            drift:SetOrder(1)
            drift:SetSmoothing("OUT")

            local fade = ag:CreateAnimation("Alpha")
            fade:SetFromAlpha(alpha)
            fade:SetToAlpha(0)
            fade:SetDuration(0.3)
            fade:SetOrder(2)
            fade:SetSmoothing("IN")

            local rotate = ag:CreateAnimation("Rotation")
            rotate:SetDegrees((math.random() - 0.5) * 90)
            rotate:SetDuration(0.3)
            rotate:SetOrder(3)
            rotate:SetSmoothing("OUT")

            ag:Play()
        end
    end
end


--===============================================================================================
function EasyCursorTrails.IsFireEnabled()
    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    return profile and profile.enableFire == true
end


function EasyCursorTrails.StartFireTicker()
    if not EasyCursorTrails.IsFireEnabled() then return end

    if EasyCursorTrails.fireEffectTicker then
        EasyCursorTrails.fireEffectTicker:Cancel()
    end

    local profile = EasyCursorTrails.currentProfileTable
    EasyCursorTrails.fireEffectTicker = C_Timer.NewTicker(0.2, function()
        for _, layerPool in pairs(EasyCursorTrails.trailPool or {}) do
            for _, trail in ipairs(layerPool) do
                if trail:IsVisible() then
                    local color = profile.randomFireColor and EasyCursorTrails.GetRandomVibrantColor()
                                or profile.fireColor or { r = 1, g = 0.5, b = 0.1, a = 0.8 }
                    EasyCursorTrails.SpawnFireGlow(trail, color)
                end
            end
        end
    end)
end



function EasyCursorTrails.ClearFireGlow(trail)
    if not trail then return end
    for _, region in pairs({ trail:GetChildren() }) do
        local tex = region:GetRegions()
        if tex and tex:GetTexture() == "Interface\\GLUES\\MODELS\\UI_Draenei\\GenericGlow64" then
            region:Hide()
            tex:SetTexture(nil)
            tex:SetParent(nil)
            region:SetParent(nil)
        end
    end
end

function EasyCursorTrails.StopFireTicker()
    if EasyCursorTrails.fireEffectTicker then
        EasyCursorTrails.fireEffectTicker:Cancel()
        EasyCursorTrails.fireEffectTicker = nil
    end

    for _, pool in pairs(EasyCursorTrails.trailPool or {}) do
        for _, trail in ipairs(pool) do
            EasyCursorTrails.ClearFireGlow(trail)
        end
    end
end



function EasyCursorTrails.SpawnFireGlow(trail)
    if not trail or not trail.texture or not trail:IsVisible() then return end

    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    if not profile then return end

    -- 🎲 Choose color based on profile flag
    local finalColor
    if profile.randomFireColor then
        finalColor = EasyCursorTrails.GetRandomVibrantColor()
    else
        finalColor = profile.fireColor or { r = 1, g = 0.5, b = 0.1, a = 0.8 }
    end

    -- 🧪 Optional debug
    -- print(string.format("FireGlow color = %.2f, %.2f, %.2f", finalColor.r, finalColor.g, finalColor.b))

    local trailX, trailY = trail:GetCenter()
    if not trailX or not trailY then return end

    local dx = trail:GetLeft() - (trail.lastX or trail:GetLeft())
    local dy = trail:GetTop() - (trail.lastY or trail:GetTop())
    trail.lastX, trail.lastY = trail:GetLeft(), trail:GetTop()
    local angle = math.atan2(dy, dx)

    local trailSize = math.max(trail:GetWidth() or 0, 1)
    local baseScale = trailSize * 1.1
    local offsetX = -math.cos(angle) * trailSize * 0.4 + (math.random() - 0.5) * trailSize * 0.1
    local offsetY = -math.sin(angle) * trailSize * 0.4 + (math.random() - 0.5) * trailSize * 0.1

    EasyCursorTrails.SpawnFireBurst(trail, baseScale, offsetX, offsetY, finalColor)
end


function EasyCursorTrails.SpawnFireBurst(trail, baseScale, offsetX, offsetY, color)
    for i = 1, 3 do -- 🔥 Stack vertical flame layers
        local flame = CreateFrame("Frame", nil, trail)
        local scaleFactor = baseScale * (1.0 + i * 0.2)
        flame:SetSize(scaleFactor * 1.1, scaleFactor * 0.6) -- Elongated for vertical flame
        flame:SetPoint("CENTER", trail, "CENTER", offsetX, offsetY + (i - 2) * baseScale * 0.5)
        flame:SetFrameStrata("HIGH")
        flame:SetFrameLevel(trail:GetFrameLevel() + 8 + i)

        local tex = flame:CreateTexture(nil, "OVERLAY")
        tex:SetAllPoints()
        tex:SetTexture("Interface\\GLUES\\MODELS\\UI_Draenei\\GenericGlow64")
        tex:SetBlendMode("ADD")
        tex:SetVertexColor(color.r, color.g, color.b, color.a * (1 - (i - 1) * 0.25)) -- Diminishing alpha per layer

        -- 🔥 Flame shaping via TexCoord cropping
        tex:SetTexCoord(0.3, 0.7, 0, 1) -- Focus on middle band

        local group = flame:CreateAnimationGroup()
        group:SetLooping("NONE")
        group:SetScript("OnFinished", function()
            tex:SetTexture(nil)
            tex:SetParent(nil)
            flame:SetParent(nil)
        end)

        local drift = group:CreateAnimation("Translation")
    
        drift:SetOffset((math.random() - 0.5) * 10, math.random(10, 18)) -- 💡 Less dramatic rise

        drift:SetDuration(0.4 + i * 0.1)
        drift:SetOrder(1)

        local fade = group:CreateAnimation("Alpha")
        fade:SetFromAlpha(1)
        fade:SetToAlpha(0)
        fade:SetDuration(0.5 + i * 0.1)
        fade:SetOrder(2)

        group:Play()
    end
end

--===============================================================================================

--=======================================================================================================
function EasyCursorTrails.StartSmokeTicker()
    if EasyCursorTrails.smokeTicker then
        EasyCursorTrails.smokeTicker:Cancel()
    end

    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]

    EasyCursorTrails.smokeTicker = C_Timer.NewTicker(0.15, function()
        if not profile or not profile.enableSmokeEffect then return end

        for _, pool in pairs(EasyCursorTrails.trailPool or {}) do
            for _, trail in ipairs(pool) do
                if trail:IsVisible() then
                    EasyCursorTrails.SpawnSmokeTrail(trail)
                end
            end
        end
    end)
end

function EasyCursorTrails.StopSmokeTicker()
    if EasyCursorTrails.smokeTicker then
        EasyCursorTrails.smokeTicker:Cancel()
        EasyCursorTrails.smokeTicker = nil
    end
end

function EasyCursorTrails.SpawnSmokeTrail(trail)
    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    if not profile or not profile.enableSmokeEffect or not trail:IsVisible() then return end

    local trailSize = trail:GetWidth() or 15
    local baseScale = trailSize * 0.70
    local trailX, trailY = trail:GetCenter()
    if not trailX or not trailY then return end

    local offsetX = (math.random() - 0.5) * trailSize * 0.3
    local offsetY = (math.random() - 0.5) * trailSize * 0.3

    EasyCursorTrails.SpawnSmokeEffect(trail, baseScale, trailX, trailY, offsetX, offsetY)
end


function EasyCursorTrails.SpawnSmokeEffect(trail, baseScale, baseX, baseY, offsetX, offsetY)
    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    if not profile then return end

    local color = profile.randomSmokeColor and EasyCursorTrails.GetRandomVibrantColor()
    or profile.smokeColor or { r = 0.129, g = 0.121, b = 0.117, a = 0.45 }

    if not (color.r and color.g and color.b and color.a) then
        EasyCursorTrails.HandleError("SmokeEffect: Invalid color format.")
        return
    end

   local puffCount = math.random(3, 5)
for layer = 1, 2 do
    for i = 1, puffCount do
        local smokeX = baseX + offsetX + (math.random() - 0.5) * 10 + (layer - 1) * 4
        local smokeY = baseY + offsetY + (math.random() - 0.5) * 10 + (layer - 1) * 4
        local puffSize = baseScale * math.random(1.4, 2.4) * (1 + layer * 0.1)

        local puff = CreateFrame("Frame", nil, UIParent)
        puff:SetPoint("CENTER", UIParent, "BOTTOMLEFT", smokeX, smokeY)
        puff:SetSize(puffSize, puffSize)
        puff:SetFrameStrata("MEDIUM")
        puff:SetFrameLevel(2)

        local tex = puff:CreateTexture(nil, "OVERLAY")
        tex:SetAllPoints()
        tex:SetTexture("Interface\\GLUES\\MODELS\\UI_Draenei\\GenericGlow64")
        tex:SetBlendMode("BLEND")
        tex:SetVertexColor(color.r, color.g, color.b, color.a)
        tex:SetRotation(math.rad(math.random(0, 360)))
        tex:SetTexCoord(0, 1, 0, 1)

        local ag = puff:CreateAnimationGroup()
        ag:SetLooping("NONE")
        ag:SetScript("OnFinished", function()
            puff:Hide()
            tex:SetTexture(nil)
            tex:SetParent(nil)
            puff:SetParent(nil)
        end)

        local driftAngle = math.random() * 2 * math.pi
        local driftDistance = math.random(8, 24)
        local driftX = math.cos(driftAngle) * driftDistance
        local driftY = math.sin(driftAngle) * driftDistance + 10

        local duration = math.random(1.1, 1.4)

        local move = ag:CreateAnimation("Translation")
        move:SetOffset(driftX, driftY)
        move:SetDuration(duration)
        move:SetOrder(1)

        local fade = ag:CreateAnimation("Alpha")
        fade:SetFromAlpha(color.a)
        fade:SetToAlpha(0)
        fade:SetDuration(duration)
        fade:SetOrder(1)

        local rotate = ag:CreateAnimation("Rotation")
        rotate:SetDegrees((math.random() - 0.5) * 30)
        rotate:SetDuration(duration)
        rotate:SetOrder(1)

        local grow = ag:CreateAnimation("Scale")
        grow:SetScale(1.3, 1.3)
        grow:SetDuration(duration)
        grow:SetOrder(1)

        ag:Play()
    end
end
end



--=================================================================================================

-- Color Effects Options (for the cursor, simplified):
local colorEffects = {
    { text = "None" },
    { text = "Rainbow" },
    { text = "Pulsing" },
    { text = "Rainbow + Pulsing" },
    { text = "Custom Color Only" },
    { text = "Custom + Pulsing" },
}

---------------------------------------------
-- 24 color effects for the trail
---------------------------------------------
local TrailcolorEffects = {
    { text = "None" },                     -- 1
    { text = "Rainbow" },                  -- 2
    { text = "Pulsing" },                  -- 3
    { text = "Glow" },                     -- 4
    { text = "Rainbow + Pulsing" },        -- 5
    { text = "Glow + Rainbow + Pulsing" }, -- 6
    { text = "Custom Color Only" },        -- 7
    { text = "Custom + Pulsing" },         -- 8
    { text = "Custom + Glow" },            -- 9
    { text = "Custom + Glow + Pulsing" },  -- 10
    { text = "Code-based Magic" },         -- 11
    { text = "Nebula Swirl" },             -- 12
    { text = "Galactic Plasma" },          -- 13
    { text = "Stardust Explosion" },       -- 14
    { text = "Dark Matter" },              -- 15
    { text = "Aurora Borealis" },          -- 16
    { text = "Crackling Electricity" },    -- 17
    { text = "Psychedelic Spiral" },       -- 18
    { text = "Inferno Pulse" },            -- 19
    { text = "Heavenly Glow" },            -- 20
    { text = "Midnight Spark" },           -- 21
}


local trailMovementEffectOptions = {
    { text = "No Effect" },              -- Index 1
    { text = "Linear Separation" },      -- Index 2
    { text = "Spiral Expansion" },       -- Index 3
    { text = "Zig-Zag" },                -- Index 4
    { text = "Wave Oscillation" },       -- Index 5
    { text = "Galactic Orbit" },         -- Index 6
    { text = "Firestorm" },              -- Index 7
    { text = "Wind Spiral" },            -- Index 8
    { text = "Spiral" },                 -- Index 9
    { text = "Radial Burst" },                 -- Index 10
    { text = "Vortex Spiral" },                 -- Index 11
    { text = "Oscillating Swirl" },                 -- Index 12
    { text = "Drifting Fog" },                 -- Index 13
    { text = "Counter Wave" },                 -- Index 14
    { text = "Chaotic Jab" },                 -- Index 15
    { text = "Heartbeat Pulse" },                 -- Index 16
    { text = "Pendulum Swing" },                 -- Index 17
    { text = "Elliptical Orbit" },                 -- Index 18
    { text = "Rising Spiral" },                 -- Index 19
    { text = "Cosmic Ripple" },                 -- Index 20
   
}

StaticPopupDialogs["EASYCURSORTRAILS_TEXT_INPUT"] = {
    text = "Enter new profile name:",
    button1 = "OK",
    button2 = "Cancel",
    hasEditBox = true,
    maxLetters = 100,
    timeout = 0,
    whileDead = true,
    hideOnEscape = true,
    preferredIndex = 3,

    OnAccept = function(self)
        local popupName = self:GetName()  -- e.g., "StaticPopup1"
        local editBox = _G[popupName .. "EditBox"]
        local text = editBox and editBox:GetText() or ""

        if EasyCursorTrails._onTextInputAccept then
            EasyCursorTrails._onTextInputAccept(text)
            EasyCursorTrails._onTextInputAccept = nil
        end
    end,

    EditBoxOnEnterPressed = function(self)
        local parent = self:GetParent()
        local text = self:GetText()

        if EasyCursorTrails._onTextInputAccept then
            EasyCursorTrails._onTextInputAccept(text)
            EasyCursorTrails._onTextInputAccept = nil
        end

        parent:Hide()
    end,

    EditBoxOnEscapePressed = function(self)
        self:GetParent():Hide()
    end,
}


-- A small helper to get a profile value or default
local function getValueOrDefault(profileTable, key, defaultsTable)
    local val = profileTable[key]
    if val == nil then
        val = defaultsTable[key]
        --print(("EasyCursorTrails: '%s' not found in profile. Using default value."):format(key))
    end
    return val
end


function EasyCursorTrails.ValidateProfile(profile)
    local expectedFlags = {
        "enableTrailShadows",
        "randomShadowColor",
        "enableTwinkleStars",
        "randomTwinkleStarsColor",
        "enableStarEmbers",
        "randomStarColor",
        "enableEmbers",
        "randomEmberColor",
        "enableFireTrails",
        "randomFireColor",
        "enableSmokeTrails",
        "randomSmokeColor",
        "enableLightningSparks",
        "randomLightningSparkColor",
        "enableStaticArcs",
        "randomStaticArcColor",
        "enableSpringSeasonTrails",
        "randomSpringSeasonColor"
    }

    for _, flag in ipairs(expectedFlags) do
        if profile[flag] == nil then
            print("🛑 Missing profile flag:", flag)
            -- Optional auto-correction:
            -- profile[flag] = false
        end
    end
end

function EasyCursorTrails.ApplyActiveEffectsFromProfile(profileSettings)
    if profileSettings.enableTrailShadows and EasyCursorTrails.RefreshAllTrailShadows then
        EasyCursorTrails.RefreshAllTrailShadows()
    end

    if profileSettings.enableFireTrails and EasyCursorTrails.RefreshAllFireEffects then
        EasyCursorTrails.RefreshAllFireEffects()
    end

    if profileSettings.enableSpringSeasonTrails and EasyCursorTrails.RefreshSpringSeasonEffects then
        EasyCursorTrails.RefreshSpringSeasonEffects()
    end

    if profileSettings.enableLightningSparks and EasyCursorTrails.RefreshLightningSparks then
        EasyCursorTrails.RefreshLightningSparks()
    end

    if profileSettings.enableSmokeTrails and EasyCursorTrails.RefreshSmokeTrails then
        EasyCursorTrails.RefreshSmokeTrails()
    end

    if profileSettings.enableStaticArc and EasyCursorTrails.RefreshStaticArcTrails then
        EasyCursorTrails.RefreshStaticArcTrails()
    end

    if profileSettings.enableEmberTrails and EasyCursorTrails.RefreshEmberTrails then
        EasyCursorTrails.RefreshEmberTrails()
    end

    if profileSettings.enableTwinkleStars and EasyCursorTrails.RefreshTwinkleStarsEffects then
        EasyCursorTrails.RefreshTwinkleStarsEffects()
    end

    if profileSettings.enableStarTrails and EasyCursorTrails.RefreshStarTrails then
        EasyCursorTrails.RefreshStarTrails()
    end

    if profileSettings.enableGlowFrames and EasyCursorTrails.UpdateGlowFrames then
        EasyCursorTrails.UpdateGlowFrames()
    end

    if profileSettings.enableSelectedGlowEffect and EasyCursorTrails.ApplySelectedGlowEffect then
        EasyCursorTrails.ApplySelectedGlowEffect()
    end
end

function EasyCursorTrails.SanitizeProfileState(profile)
    if not profile or type(profile) ~= "table" then return end

    local defaults = EasyCursorTrails.defaults or {}
    local missingKeys = {}

    for key, defaultValue in pairs(defaults) do
        if profile[key] == nil then
            profile[key] = defaultValue
            table.insert(missingKeys, key)
        end
    end

    if #missingKeys > 0 then
        --SanitizeProfileState: Initialized missing keys →", table.concat(missingKeys, ", "))
    end
end

-- 🔧 SyncDropdown Utility
local function SyncDropdown(dropdown, options, index, defaultText)
    if not dropdown or type(options) ~= "table" then
        EasyCursorTrails.HandleError("SyncDropdown: Invalid dropdown or options table.")
        return
    end
    if not options[index] then
        EasyCursorTrails.HandleError("SyncDropdown: Index " .. tostring(index) .. " not found in options.")
        index = 1
    end
    UIDropDownMenu_SetSelectedID(dropdown, index)
    UIDropDownMenu_SetText(dropdown, options[index].text or defaultText)
end


function EasyCursorTrails.RefreshSettingsUI()
    if not EasyCursorTrails.menuInitialized then return end

    local profileName = EasyCursorTrailsDB.currentProfile or "Default"
    local profileSettings = EasyCursorTrailsDB.profiles[profileName]
    local defaults = EasyCursorTrails.defaults

    if not profileSettings then
        EasyCursorTrails.HandleError("RefreshSettingsUI: Profile '" .. profileName .. "' not found. Using defaults.")
        profileSettings = defaults
    end

    EasyCursorTrails.SanitizeProfileState(profileSettings)
    EasyCursorTrails.currentProfileTable = profileSettings

    ----------------------------------------------------------------
    -- ✅ Sync sliders
    ----------------------------------------------------------------
    local sliders = {
        { ref = EasyCursorTrails.trailFollowSpeedSlider, key = "trailUpdateMultiplier" },
        { ref = EasyCursorTrails.chainSegmentSlider, key = "chainSegment" },
        { ref = EasyCursorTrails.cursorSizeSlider, key = "cursorSize" },
        { ref = EasyCursorTrails.trailSizeStartSlider, key = "trailSizeStart" },
        { ref = EasyCursorTrails.trailSizeEndSlider, key = "trailSizeEnd" },
        { ref = EasyCursorTrails.trailCountSlider, key = "trailCount" },
        { ref = EasyCursorTrails.trailLengthSlider, key = "trailLayerCount", roundToInt = true },
        { ref = EasyCursorTrails.trailLayerSpacingSlider, key = "trailLayerSpacing" },
        { ref = EasyCursorTrails.trailInitialSeparationSlider, key = "trailInitialSeparation" },
        { ref = EasyCursorTrails.glowIntensitySlider, key = "glowIntensity" },
        { ref = EasyCursorTrails.trailIntensitySlider, key = "trailIntensity" },
        { ref = EasyCursorTrails.trailSpacingSlider, key = "trailSpacing" },
        { ref = EasyCursorTrails.trailOffsetXSlider, key = "trailOffsetX" },
        { ref = EasyCursorTrails.trailOffsetYSlider, key = "trailOffsetY" },
        { ref = EasyCursorTrails.trailOffsetMagnitudeSlider, key = "trailOffsetMagnitude" },
        { ref = EasyCursorTrails.trailTextureOpacitySlider, key = "trailTextureOpacity" },
        { ref = EasyCursorTrails.glowFactorSlider, key = "glowIntensityFactor" },
        { ref = EasyCursorTrails.numGlowsSlider, key = "numGlows", roundToInt = true },
        { ref = EasyCursorTrails.patternGlowCountSlider, key = "patternGlowCount", roundToInt = true },
        { ref = EasyCursorTrails.glowRadiusSlider, key = "glowRadius" },
        { ref = EasyCursorTrails.glowSizeSlider, key = "glowSize" },
        { ref = EasyCursorTrails.glowThicknessSlider, key = "glowThickness" },
        { ref = EasyCursorTrails.cursorOffsetXSlider, key = "cursorOffsetX" },
        { ref = EasyCursorTrails.cursorOffsetYSlider, key = "cursorOffsetY" },
    }

    for _, info in ipairs(sliders) do
        local slider = info.ref
        local key = info.key
        local roundToInt = info.roundToInt or false
        if slider and slider.SetValue then
            local value = profileSettings[key] or defaults[key] or 1
            value = tonumber(value) or 1
            local displayValue = roundToInt and math.floor(value) or value
            slider:SetValue(displayValue)
            if slider.editBox then
                slider.editBox:SetText(roundToInt and tostring(displayValue) or string.format("%.2f", displayValue))
            elseif slider.valueText then
                slider.valueText:SetText(tostring(displayValue))
            end
        else
            EasyCursorTrails.HandleError("RefreshSettingsUI: Missing slider for key '" .. tostring(key) .. "'")
        end
    end

    ----------------------------------------------------------------
    -- ✅ Sync checkboxes
    ----------------------------------------------------------------
    local checkboxMap = {
        enableTrailsCheckbox = "enableTrails",
        shadowEffectCheckbox = "enableTrailShadows",
        staticArcEffectCheckbox = "enableStaticArcs",
        emberCheckbox = "enableEmbers",
        fireEffectCheckbox = "enableFire",
        smokeEffectCheckbox = "enableSmoke",
        lightningSparkCheckbox = "enableLightningSparks",
        twinkleStarsCheckbox = "enableTwinkleStars",
        starTrailCheckbox = "enableStars",
        springSeasonCheckbox = "enableSpringSeason",
        connectTrailsCheckbox = "connectTrails",
        shadowRandomColorCheckbox = "randomShadowColor",
        fireRandomColorCheckbox = "randomFireColor",
        smokeRandomColorCheckbox = "randomSmokeColor",
        lightningSparkRandomColorCheckbox = "randomLightningSparkColor",
        staticArcRandomColorCheckbox = "randomStaticArcColor",
        starRandomColorCheckbox = "randomStarColor",
        springSeasonRandomColorCheckbox = "randomSpringSeasonColor",
        emberRandomColorCheckbox = "randomEmberColor",
        twinkleStarsRandomColorCheckbox = "randomTwinkleStarsColor",
        fireTrailCheckbox = "enableFireTrails",
        smokeTrailCheckbox = "enableSmokeTrails",
        starEmberCheckbox = "enableStarEmbers",
        springSeasonTrailCheckbox = "enableSpringSeasonTrails",
        directionalOffsetCheckbox = "enableDirectionalOffset"
    }

    for uiKey, flagKey in pairs(checkboxMap) do
        local checkbox = EasyCursorTrails[uiKey]
        if checkbox and profileSettings[flagKey] ~= nil then
            checkbox:SetChecked(profileSettings[flagKey] == true)
        end
    end

    ----------------------------------------------------------------
    -- ✅ Dropdown sync helper
    ----------------------------------------------------------------
    local function SyncDropdown(dropdown, options, index, defaultText)
        if not dropdown or type(options) ~= "table" then
            EasyCursorTrails.HandleError("SyncDropdown: Invalid dropdown or options table.")
            return
        end
        if not options[index] then index = 1 end
        UIDropDownMenu_SetSelectedID(dropdown, index)
        UIDropDownMenu_SetText(dropdown, options[index].text or defaultText)
    end

    ----------------------------------------------------------------
    -- ✅ Build dropdown options
    ----------------------------------------------------------------
    EasyCursorTrails.trailColorEffectOptions = {}
    for _, effect in ipairs(TrailcolorEffects or {}) do
        table.insert(EasyCursorTrails.trailColorEffectOptions, {
            text = effect.text or "Unnamed Effect",
            value = effect.value
        })
    end

    EasyCursorTrails.cursorColorEffectOptions = {}
    for _, effect in ipairs(colorEffects or {}) do
        table.insert(EasyCursorTrails.cursorColorEffectOptions, {
            text = effect.text or "Unnamed Effect",
            value = effect.value
        })
    end

    EasyCursorTrails.trailMovementEffectOptions = {}
    for _, effect in ipairs(trailMovementEffectOptions or {}) do
        table.insert(EasyCursorTrails.trailMovementEffectOptions, {
            text = effect.text or "Unnamed Movement",
            value = effect.value
        })
    end

    ----------------------------------------------------------------
    -- ✅ Sync dropdowns
    ----------------------------------------------------------------
    EasyCursorTrails.RefreshTrailDropdowns()
    EasyCursorTrails.PopulateTrailTextureDropdown()

    SyncDropdown(EasyCursorTrails.trailColorEffectDropdown, EasyCursorTrails.trailColorEffectOptions, tonumber(profileSettings.trailColorEffect) or 1, "Custom Color")
    SyncDropdown(EasyCursorTrails.cursorColorEffectDropdown, EasyCursorTrails.cursorColorEffectOptions, tonumber(profileSettings.cursorColorEffect) or 1, "Default")
    SyncDropdown(EasyCursorTrails.glowEffectDropdown, EasyCursorTrails.glowEffectOptions, tonumber(profileSettings.selectedGlowEffect) or 1, "Custom Glow")
    SyncDropdown(EasyCursorTrails.trailMovementEffectDropdown, EasyCursorTrails.trailMovementEffectOptions, tonumber(profileSettings.trailMovementEffect) or 1, "No Effect")

    if EasyCursorTrails.cursorFrameStrataDropdown then
        local index = EasyCursorTrails.GetStrataIndex(profileSettings.cursorFrameStrata or "HIGH")
        SyncDropdown(EasyCursorTrails.cursorFrameStrataDropdown, EasyCursorTrails.frameStrataOptions, index, "HIGH")
    end

    -- Build cursor texture options
    EasyCursorTrails.cursorTextureOptions = {}
    if EasyCursorTrails.customCursorTextures then
        for _, data in ipairs(EasyCursorTrails.customCursorTextures) do
            local name = data.name or "Unknown"
            if data.animated then name = name .. " (Animated)" end
            table.insert(EasyCursorTrails.cursorTextureOptions, { text = name, icon = data.texture })
        end
    end

    C_Timer.After(0.1, function()
                local index = tonumber(profileSettings.cursorTexture) or 1
        if index > #EasyCursorTrails.cursorTextureOptions then index = 1 end
        SyncDropdown(EasyCursorTrails.cursorTextureDropdown, EasyCursorTrails.cursorTextureOptions, index, "Default")
    end)
    


    ----------------------------------------------------------------
    -- ✅ Sync color pickers
    ----------------------------------------------------------------
    local function SetColor(editBox, color)
        if editBox and color and type(RGBToHex) == "function" then
            editBox:SetText(RGBToHex(color.r, color.g, color.b))
        end
    end

    SetColor(EasyCursorTrails.cursorColorEditBox, profileSettings.cursorColor or defaults.cursorColor)
    SetColor(EasyCursorTrails.glowColorEditBox, profileSettings.glowColor or defaults.glowColor)

      if EasyCursorTrails.shadowColorPicker and type(EasyCursorTrails.shadowColorPicker.SetColorRGBA) == "function" then
        local shadowColor = profileSettings.shadowTrailColor or defaults.shadowTrailColor or { r = 0, g = 0, b = 0, a = 0.4 }
        EasyCursorTrails.shadowColorPicker:SetColorRGBA(shadowColor.r, shadowColor.g, shadowColor.b, shadowColor.a)
    end

    ----------------------------------------------------------------
    -- ✅ Apply effects and toggles
    ----------------------------------------------------------------
    EasyCursorTrails.ApplyActiveEffectsFromProfile(profileSettings)

    EasyCursorTrails.SyncToggleState(
        "enableEmbers",
        EasyCursorTrails.emberCheckbox,
        EasyCursorTrails.StartEmberTicker,
        EasyCursorTrails.StopEmberTicker
    )

    EasyCursorTrails.SyncToggleState(
        "enableFire",
        EasyCursorTrails.fireEffectCheckbox,
        EasyCursorTrails.StartFireTicker,
        EasyCursorTrails.StopFireTicker
    )

    -- 🔄 Reapply glow effects if supported
    if EasyCursorTrails.UpdateGlowFrames then
        EasyCursorTrails.UpdateGlowFrames()
    end

    if EasyCursorTrails.ApplySelectedGlowEffect then
        EasyCursorTrails.ApplySelectedGlowEffect()
    end

    -- ✅ Rebuild trails if needed
    if EasyCursorTrails.RebuildTrails then
        local success, err = pcall(EasyCursorTrails.RebuildTrails)
        if not success then
            EasyCursorTrails.HandleError("RefreshSettingsUI: Failed to rebuild trails. Error: " .. tostring(err))
        end
    end
end




function EasyCursorTrails.SyncToggleState(profileKey, checkbox, startFunc, stopFunc)
    local profile = EasyCursorTrails.currentProfileTable
    if not profile then
        EasyCursorTrails.HandleError("SyncToggleState: Profile not available.")
        return
    end

    local state = profile[profileKey]
    if type(state) ~= "boolean" then
        EasyCursorTrails.HandleError("SyncToggleState: Invalid state for '" .. profileKey .. "' — expected boolean, got " .. type(state))
        return
    end

    if checkbox then
        checkbox:SetChecked(state)
    end

    if state then
        if type(startFunc) == "function" then startFunc() end
    else
        if type(stopFunc) == "function" then stopFunc() end
    end
end


function EasyCursorTrails.SaveCurrentProfile()
    local profileName = EasyCursorTrailsDB.currentProfile
    if not profileName then return end

    local profileSettings = EasyCursorTrailsDB.profiles[profileName]
    if not profileSettings then return end

    local defaults = EasyCursorTrails.defaults or {}

    -- 🧭 Save sliders
    local sliders = {
        { ref = EasyCursorTrails.cursorSizeSlider,            key = "cursorSize" },
        { ref = EasyCursorTrails.trailSizeStartSlider,        key = "trailSizeStart" },
        { ref = EasyCursorTrails.trailSizeEndSlider,          key = "trailSizeEnd" },
        { ref = EasyCursorTrails.trailCountSlider,            key = "trailCount" },
        { ref = EasyCursorTrails.trailLengthSlider,           key = "trailLayerCount", roundToInt = true },
        { ref = EasyCursorTrails.glowIntensitySlider,         key = "glowIntensity" },
        { ref = EasyCursorTrails.glowRadiusSlider,            key = "glowRadius" },
        { ref = EasyCursorTrails.trailIntensitySlider,        key = "trailGlowIntensity" },
        { ref = EasyCursorTrails.trailSpacingSlider,          key = "trailSpacing" },
        { ref = EasyCursorTrails.horizontalScaleSlider,       key = "horizontalScale" },
        { ref = EasyCursorTrails.verticalScaleSlider,         key = "verticalScale" },
        { ref = EasyCursorTrails.cursorOffsetXSlider,         key = "cursorOffsetX" },
        { ref = EasyCursorTrails.cursorOffsetYSlider,         key = "cursorOffsetY" },
        { ref = EasyCursorTrails.trailOffsetXSlider,          key = "trailOffsetX" },
        { ref = EasyCursorTrails.trailOffsetYSlider,          key = "trailOffsetY" },
    }

    for _, info in ipairs(sliders) do
        EasyCursorTrails.SaveSliderValue(info.ref, info.key, info.roundToInt)
    end

    -- 🎛️ Save dropdowns
    local dropdowns = {
        { dropdown = EasyCursorTrails.trailTextureDropdown, key = "trailTexture" },
        -- Add more dropdowns if needed
    }

    for _, info in ipairs(dropdowns) do
        EasyCursorTrails.SaveDropdownValue(info.dropdown, info.key)
    end

    -- ✅ Save checkboxes
    local checkboxes = {
        { checkbox = EasyCursorTrails.enableTrailsCheckbox, key = "enableTrails" },
        { checkbox = EasyCursorTrails.emberCheckbox, key = "enableEmbers" },
        { checkbox = EasyCursorTrails.staticArcEffectCheckbox, key = "enableStaticArcs" },
        { checkbox = EasyCursorTrails.shadowEffectCheckbox, key = "enableTrailShadows" },
        { checkbox = EasyCursorTrails.fireEffectCheckbox, key = "enableFire" },
        { checkbox = EasyCursorTrails.smokeEffectCheckbox, key = "enableSmoke" },
        { checkbox = EasyCursorTrails.lightningSparkCheckbox, key = "enableLightningSparks" },
        { checkbox = EasyCursorTrails.twinkleStarsCheckbox, key = "enableTwinkleStars" },
        { checkbox = EasyCursorTrails.starTrailCheckbox, key = "enableStars" },
        { checkbox = EasyCursorTrails.springSeasonCheckbox, key = "enableSpringSeason" },
        { checkbox = EasyCursorTrails.connectTrailsCheckbox, key = "connectTrails" },
    }

    for _, info in ipairs(checkboxes) do
        EasyCursorTrails.SaveCheckboxValue(info.checkbox, info.key)
    end

    -- 🌈 Save random color flags
    local randomColorCheckboxes = {
        { checkbox = EasyCursorTrails.randomEmberColorCheckbox, key = "randomEmberColor" },
        { checkbox = EasyCursorTrails.randomShadowColorCheckbox, key = "randomShadowColor" },
        { checkbox = EasyCursorTrails.randomSmokeColorCheckbox, key = "randomSmokeColor" },
        { checkbox = EasyCursorTrails.randomFireColorCheckbox, key = "randomFireColor" },
        { checkbox = EasyCursorTrails.randomLightningSparkColorCheckbox, key = "randomLightningSparkColor" },
        { checkbox = EasyCursorTrails.randomStaticArcColorCheckbox, key = "randomStaticArcColor" },
        { checkbox = EasyCursorTrails.randomStarColorCheckbox, key = "randomStarColor" },
        { checkbox = EasyCursorTrails.randomSpringSeasonColorCheckbox, key = "randomSpringSeasonColor" },
        { checkbox = EasyCursorTrails.randomTwinkleStarsColorCheckbox, key = "randomTwinkleStarsColor" },
    }

    for _, info in ipairs(randomColorCheckboxes) do
        EasyCursorTrails.SaveCheckboxValue(info.checkbox, info.key)
    end
end




function EasyCursorTrails.SaveSliderValue(slider, key, roundToInt)
    if EasyCursorTrails.isSyncingUI then return end
    if slider and type(slider.GetValue) == "function" then
        local value = tonumber(slider:GetValue()) or 1
        if roundToInt then value = math.floor(value) end
        EasyCursorTrails.currentProfileTable[key] = value
    end
end


function EasyCursorTrails.SaveDropdownValue(dropdown, key)
    if EasyCursorTrails.isSyncingUI then return end
    if dropdown and UIDropDownMenu_GetSelectedID then
        local selectedID = UIDropDownMenu_GetSelectedID(dropdown)
        EasyCursorTrails.currentProfileTable[key] = selectedID
    end
end


function EasyCursorTrails.SaveCheckboxValue(checkbox, key)
    if EasyCursorTrails.isSyncingUI then return end
    if checkbox and type(checkbox.GetChecked) == "function" then
        local checked = checkbox:GetChecked()
        EasyCursorTrails.currentProfileTable[key] = checked == true
    end
end




-- Populate the Profile Dropdown
function EasyCursorTrails.PopulateProfileDropdownAndSelectCurrent()
    if not EasyCursorTrails.profileDropdown or not EasyCursorTrailsDB or not EasyCursorTrailsDB.profiles then
        return
    end

    local currentProfile = EasyCursorTrailsDB.currentProfile or "Default"
    if not EasyCursorTrailsDB.profiles[currentProfile] then
        currentProfile = "Default"
        EasyCursorTrailsDB.currentProfile = currentProfile
    end

    UIDropDownMenu_Initialize(EasyCursorTrails.profileDropdown, function(self, level)
        if not level or level ~= 1 then return end

        -- Sort profile names alphabetically
        local profileNames = {}
        for name in pairs(EasyCursorTrailsDB.profiles) do
            table.insert(profileNames, name)
        end
        table.sort(profileNames)

        for _, name in ipairs(profileNames) do
            local info = UIDropDownMenu_CreateInfo()
            info.text = name
            info.checked = (name == currentProfile)
            info.func = function()
                UIDropDownMenu_SetSelectedID(EasyCursorTrails.trailTextureDropdown, i)
                UIDropDownMenu_SetText(EasyCursorTrails.trailTextureDropdown, option.text)
            
                if EasyCursorTrails.trailTextureDropdown.onSelect then
                    EasyCursorTrails.trailTextureDropdown.onSelect(i)
                end
                CloseDropDownMenus()
            end
            
            UIDropDownMenu_AddButton(info, level)
        end
    end)

    UIDropDownMenu_SetText(EasyCursorTrails.profileDropdown, currentProfile)
end



function EasyCursorTrails.SaveAllSettingsToProfile()
    local profileName = EasyCursorTrailsDB.currentProfile or "Default"
    if not profileName then
        EasyCursorTrails.HandleError("SaveAllSettingsToProfile: No profile name found.")
        return
    end

    -- Ensure profile table exists
    EasyCursorTrailsDB.profiles[profileName] = EasyCursorTrailsDB.profiles[profileName] or {}
    local profile = EasyCursorTrailsDB.profiles[profileName]

    ----------------------------------------------------------------------
    -- 🔧 Save slider values
    ----------------------------------------------------------------------
    local sliders = {
        { EasyCursorTrails.cursorSizeSlider,            "cursorSize" },
        { EasyCursorTrails.trailSizeStartSlider,        "trailSizeStart" },
        { EasyCursorTrails.trailSizeEndSlider,          "trailSizeEnd" },
        { EasyCursorTrails.trailCountSlider,            "trailCount" },
        { EasyCursorTrails.trailLengthSlider,           "trailLayerCount", true },
        { EasyCursorTrails.glowIntensitySlider,         "glowIntensity" },
        { EasyCursorTrails.glowRadiusSlider,            "glowRadius" },
        { EasyCursorTrails.trailIntensitySlider,        "trailIntensity" },
        { EasyCursorTrails.trailSpacingSlider,          "trailSpacing" },
        { EasyCursorTrails.horizontalScaleSlider,       "horizontalScale" },
        { EasyCursorTrails.verticalScaleSlider,         "verticalScale" },
        { EasyCursorTrails.cursorOffsetXSlider,         "cursorOffsetX" },
        { EasyCursorTrails.cursorOffsetYSlider,         "cursorOffsetY" },
        { EasyCursorTrails.trailOffsetXSlider,          "trailOffsetX" },
        { EasyCursorTrails.trailOffsetYSlider,          "trailOffsetY" },
    }

    for _, sliderInfo in ipairs(sliders) do
        local slider, key, round = unpack(sliderInfo)
        if slider and key then
            local val = slider:GetValue()
            profile[key] = round and math.floor(val) or val
        end
    end

    ----------------------------------------------------------------------
    -- 🎛️ Save dropdown selections
    ----------------------------------------------------------------------
    local dropdowns = {
        { EasyCursorTrails.trailTextureDropdown,       "trailTexture" },
        { EasyCursorTrails.trailColorEffectDropdown,   "trailColorEffect" },
        { EasyCursorTrails.cursorFrameStrataDropdown,  "cursorFrameStrata" },
        { EasyCursorTrails.glowEffectDropdown,         "selectedGlowEffect" },
        { EasyCursorTrails.cursorTextureDropdown,      "cursorTexture" },
    }

    for _, dropdownInfo in ipairs(dropdowns) do
        local dropdown, key = unpack(dropdownInfo)
        if dropdown and key then
            profile[key] = UIDropDownMenu_GetSelectedID(dropdown)
        end
    end

    ----------------------------------------------------------------------
    -- ☑ Save effect checkboxes
    ----------------------------------------------------------------------
    local effectCheckboxes = {
        { EasyCursorTrails.enableTrailsCheckbox,       "enableTrails" },
        { EasyCursorTrails.shadowEffectCheckbox,       "enableTrailShadows" },
        { EasyCursorTrails.twinkleStarsCheckbox,       "enableTwinkleStars" },
        { EasyCursorTrails.starTrailCheckbox,          "enableStars" },
        { EasyCursorTrails.emberCheckbox,              "enableEmbers" },
        { EasyCursorTrails.fireEffectCheckbox,         "enableFire" },
        { EasyCursorTrails.smokeEffectCheckbox,        "enableSmoke" },
        { EasyCursorTrails.lightningSparkCheckbox,     "enableLightningSparks" },
        { EasyCursorTrails.staticArcEffectCheckbox,    "enableStaticArcs" },
        { EasyCursorTrails.springSeasonCheckbox,       "enableSpringSeason" },
        { EasyCursorTrails.connectTrailsCheckbox,      "connectTrails" },
    }

    for _, checkboxInfo in ipairs(effectCheckboxes) do
        local checkbox, key = unpack(checkboxInfo)
        if checkbox and key and checkbox:IsObjectType("CheckButton") then
            profile[key] = checkbox:GetChecked()
        end
    end

    ----------------------------------------------------------------------
    -- ☑ Save random color toggles
    ----------------------------------------------------------------------
    local randomCheckboxes = {
        { EasyCursorTrails.shadowRandomColorCheckbox,         "randomShadowColor" },
        { EasyCursorTrails.twinkleStarsRandomColorCheckbox,   "randomTwinkleStarsColor" },
        { EasyCursorTrails.starRandomColorCheckbox,           "randomStarColor" },
        { EasyCursorTrails.emberRandomColorCheckbox,          "randomEmberColor" },
        { EasyCursorTrails.fireRandomColorCheckbox,           "randomFireColor" },
        { EasyCursorTrails.smokeRandomColorCheckbox,          "randomSmokeColor" },
        { EasyCursorTrails.lightningSparkRandomColorCheckbox, "randomLightningSparkColor" },
        { EasyCursorTrails.staticArcRandomColorCheckbox,      "randomStaticArcColor" },
        { EasyCursorTrails.springSeasonRandomColorCheckbox,   "randomSpringSeasonColor" },
    }

    for _, checkboxInfo in ipairs(randomCheckboxes) do
        local checkbox, key = unpack(checkboxInfo)
        if checkbox and key and checkbox:IsObjectType("CheckButton") then
            profile[key] = checkbox:GetChecked()
        end
    end

    ----------------------------------------------------------------------
    -- 🎨 Save color pickers and edit boxes
    ----------------------------------------------------------------------
    if EasyCursorTrails.cursorColorEditBox then
        local r, g, b, a = HexToRGB(EasyCursorTrails.cursorColorEditBox:GetText())
        profile.cursorColor = { r = r, g = g, b = b, a = a }
    end

    if EasyCursorTrails.glowColorEditBox then
        local r, g, b, a = HexToRGB(EasyCursorTrails.glowColorEditBox:GetText())
        profile.glowColor = { r = r, g = g, b = b, a = a }
    end

    if EasyCursorTrails.shadowColorPicker and type(EasyCursorTrails.shadowColorPicker.GetColorRGBA) == "function" then
        local r, g, b, a = EasyCursorTrails.shadowColorPicker:GetColorRGBA()
        profile.shadowTrailColor = { r = r, g = g, b = b, a = a }
    end

    ----------------------------------------------------------------------
    -- 🔁 Update in-memory reference
    ----------------------------------------------------------------------
    EasyCursorTrails.currentProfileName = profileName
    EasyCursorTrails.currentProfileTable = profile
end




function CreateSlider(name, parent, label, min, max, step, initialValue, onValueChanged, numDecimals)
    local slider = CreateFrame("Slider", name, parent, "OptionsSliderTemplate")
    slider:SetMinMaxValues(min, max)
    slider:SetValueStep(step)
    slider:SetWidth(150)
    slider:SetHeight(20)

    local decimals = numDecimals or 2

    -- 🏷️ Label
    slider.labelText = slider:CreateFontString(nil, "OVERLAY", "GameFontHighlight")

    slider.labelText:SetPoint("BOTTOM", slider, "TOP", 0, 6)
    slider.labelText:SetText(label)
    slider.labelText:SetTextColor(1, 0.85, 0.1)  -- Gold-ish for visibility

    -- 🧮 Value formatting
    local function formatValue(val)
        local fmt = "%." .. decimals .. "f"
        return string.format(fmt, val)
    end

    -- 🔁 Sync helper
    local function UpdateEditBox(val)
        slider.editBox:SetText(formatValue(val))
    end

    -- 📝 EditBox for precise input
    slider.editBox = CreateFrame("EditBox", nil, slider, "InputBoxTemplate")
    slider.editBox:SetSize(45, 20)
    slider.editBox:SetPoint("LEFT", slider, "RIGHT", 10, 0)
    slider.editBox:SetAutoFocus(false)
    slider.editBox:SetFontObject("GameFontHighlight")
    slider.editBox:SetTextColor(1, 1, 1)

    -- 🎨 Add background texture for visibility
    local bg = slider.editBox:CreateTexture(nil, "BACKGROUND")
    bg:SetColorTexture(0, 0, 0, 0.6)  -- Semi-transparent black
    bg:SetAllPoints(slider.editBox)
    slider.editBox.bg = bg

    -- 🧼 Apply initial value
    local initial = initialValue or min
    slider:SetValue(initial)
    UpdateEditBox(initial)

    -- 🧠 EditBox input handler
    slider.editBox:SetScript("OnEnterPressed", function(self)
        local entered = tonumber(self:GetText())
        if entered then
            local clamped = math.max(min, math.min(max, entered))
            slider:SetValue(clamped)
            UpdateEditBox(clamped)
        else
            UpdateEditBox(slider:GetValue())
        end
        self:ClearFocus()
    end)

    -- 🔄 Slider movement handler
    slider:SetScript("OnValueChanged", function(self, newValue)
        local val = tonumber(newValue)
        UpdateEditBox(val)

        if onValueChanged then
            onValueChanged(self, val)
        end

        -- ✨ Optional: live glow update
        if EasyCursorTrails and EasyCursorTrails.UpdateGlowFrames and EasyCursorTrails.ApplySelectedGlowEffect then
            EasyCursorTrails.UpdateGlowFrames()
            EasyCursorTrails.ApplySelectedGlowEffect()
        end
    end)

    return slider
end



local function AutoAdjustDropdownWidth(dropdown, options)
    -- Create a temporary FontString for measurement.
    local fontString = dropdown:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    local maxWidth = 0

    for i, option in ipairs(options) do
        local text = (type(option) == "table" and option.text) 
                     or (type(option) == "string" and option) 
                     or ("Option " .. i)
        fontString:SetText(text)
        local width = fontString:GetStringWidth()
        if width > maxWidth then
            maxWidth = width
        end
    end

    -- Add padding to account for the drop-down arrow, icons, etc.
    local padding = 10
    local newWidth = maxWidth + padding

    UIDropDownMenu_SetWidth(dropdown, newWidth)

    -- Adjust the internal text field width (if available).
    local dropdownText = _G[dropdown:GetName() .. "Text"]
    if dropdownText then
        dropdownText:SetWidth(newWidth - 10)  -- reduce further by some padding if needed
    end

    fontString:Hide()  -- Cleanup our temporary FontString
end

local function CreateDropdown(name, parent, label, options, selectedIndex, onSelect)
    -- Ensure `options` is valid
    if not options or type(options) ~= "table" or #options == 0 then
        options = { { text = "Default Option" } } -- Fallback default option
    end

    -- Create the dropdown frame using Blizzard's template.
    local dropdown = CreateFrame("Frame", name, parent, "UIDropDownMenuTemplate")
    dropdown:SetPoint("TOPLEFT", parent, "BOTTOMLEFT", 0, -10) -- Adjust positioning as needed

    -- Set up the label for the dropdown.
    local dropdownLabel = parent:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    dropdownLabel:SetPoint("BOTTOM", dropdown, "TOP", 0, 0)
    dropdownLabel:SetText(label or "Dropdown")

    -- Initialize the dropdown options
    UIDropDownMenu_Initialize(dropdown, function(self, level, menuList)
        if not level or level ~= 1 then return end

        -- Create list items for the dropdown.
        for i, option in ipairs(options) do
            local info = UIDropDownMenu_CreateInfo()
            local text = (type(option) == "table" and option.text)
                         or (type(option) == "string" and option)
                         or ("Option " .. i)
            info.text = text

            -- Provide an icon if one exists.
            if type(option) == "table" and option.icon then
                info.icon = option.icon
                info.iconTexCoord = {0, 1, 0, 1}
                info.iconWidth = 50
                info.iconHeight = 20
            end

            info.checked = (UIDropDownMenu_GetSelectedID(dropdown) == i)

            info.func = function()
                UIDropDownMenu_SetSelectedID(dropdown, i)
                UIDropDownMenu_SetText(dropdown, text)
                if onSelect and type(onSelect) == "function" then
                    onSelect(i)
                end
                CloseDropDownMenus()
            end

            UIDropDownMenu_AddButton(info, level)
        end
    end)

    -- Clamp the selected index
    local clampedIndex = math.max(1, math.min(selectedIndex or 1, #options))
    UIDropDownMenu_SetSelectedID(dropdown, clampedIndex)
    local initialOpt = options[clampedIndex]
    local initialText = (type(initialOpt) == "table" and initialOpt.text)
                        or (type(initialOpt) == "string" and initialOpt)
                        or "Default Option"
    UIDropDownMenu_SetText(dropdown, initialText)

    -- Automatically adjust the width of the dropdown box based on options.
    AutoAdjustDropdownWidth(dropdown, options)

    return dropdown
end



    EasyCursorTrails.DebugPrint = function(message)
        if EasyCursorTrailsDB.debugMode then
           -- -- ----print("|cff00ff00EasyCursorTrails Debug:|r " .. tostring(message))
        end
    end
    
    EasyCursorTrails.HandleError = function(message)
      --  -- ----print("|cffff0000EasyCursorTrails Error:|r " .. tostring(message))
    end

 -------------------------
-- Color Picker
-------------------------
function EasyCursorTrails.OpenColorPicker(initialColor, callback)
    local function ColorPickerCallback(restore)
        local newR, newG, newB, newA
        if restore then
            newR, newG, newB, newA = unpack(restore)
        else
            newR, newG, newB = ColorPickerFrame:GetColorRGB()
            if ColorPickerFrame.hasOpacity then
                if ColorPickerFrame.opacity then
                    newA = 1 - (ColorPickerFrame.opacity or 0)
                else
                    newA = 1
                end
            else
                newA = 1
            end
        end
        callback({ r = newR, g = newG, b = newB, a = newA })
    end

    ColorPickerFrame.func = ColorPickerCallback
    ColorPickerFrame.opacityFunc = ColorPickerCallback
    ColorPickerFrame.cancelFunc = ColorPickerCallback
    ColorPickerFrame.swatchFunc = ColorPickerCallback

    ColorPickerFrame.hasOpacity = true
    ColorPickerFrame.opacity = 1 - (initialColor.a or 1)
    ColorPickerFrame.previousValues = { initialColor.r, initialColor.g, initialColor.b, initialColor.a }

    if ColorPickerFrame.SetColorRGB then
        ColorPickerFrame:SetColorRGB(initialColor.r, initialColor.g, initialColor.b)
    else
        ColorPickerFrame.red = initialColor.r
        ColorPickerFrame.green = initialColor.g
        ColorPickerFrame.blue = initialColor.b
    end

    ColorPickerFrame:Hide()
    ColorPickerFrame:Show()
end


function EasyCursorTrails.HSVToRGB(h, s, v)
    local c = v * s
    local x = c * (1 - math.abs((h / 60) % 2 - 1))
    local m = v - c
    local r, g, b

    if h >= 0 and h < 60 then
        r, g, b = c, x, 0
    elseif h >= 60 and h < 120 then
        r, g, b = x, c, 0
    elseif h >= 120 and h < 180 then
        r, g, b = 0, c, x
    elseif h >= 180 and h < 240 then
        r, g, b = 0, x, c
    elseif h >= 240 and h < 300 then
        r, g, b = x, 0, c
    elseif h >= 300 and h < 360 then
        r, g, b = c, 0, x
    else
        r, g, b = 0, 0, 0
    end

    return r + m, g + m, b + m
end

-------------------------
-- Pulsing Logic
-------------------------
function EasyCursorTrails.UpdatePulseValue()
    -- Retrieve the number of trails (fallback to 70 if missing)
    local numTrails = EasyCursorTrails.currentProfileTable and EasyCursorTrails.currentProfileTable.trailCount 
                      or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile].trailCount 
                      or 70

    -- Base pulse step, adjust dynamically based on trail count.
    local basePulseStep = EasyCursorTrailsDB.pulseStep or 0.02
    local adjustedPulseStep = basePulseStep * (70 / math.max(numTrails, 70))

    EasyCursorTrails.pulseValueTrail = (EasyCursorTrails.pulseValueTrail or 0.5) 
                                        + (EasyCursorTrails.pulseDirectionTrail or 1) * adjustedPulseStep

    local pulseMin = EasyCursorTrailsDB.pulseMin or 0.3
    local pulseMax = EasyCursorTrailsDB.pulseMax or 1.0

    if EasyCursorTrails.pulseValueTrail >= pulseMax then
        EasyCursorTrails.pulseValueTrail = pulseMax
        EasyCursorTrails.pulseDirectionTrail = -1
    elseif EasyCursorTrails.pulseValueTrail <= pulseMin then
        EasyCursorTrails.pulseValueTrail = pulseMin
        EasyCursorTrails.pulseDirectionTrail = 1
    end

   -- print("DEBUG: Pulse updated with adjustedPulseStep:", adjustedPulseStep, "NumTrails:", numTrails)
end

-------------------------
-- Glow Animation
-------------------------
function EasyCursorTrails.AnimateGlow(glowLayer)
    if not glowLayer.animation then
        glowLayer.animation = glowLayer:CreateAnimationGroup()
        glowLayer.animation:SetLooping("BOUNCE")

        local alphaAnim = glowLayer.animation:CreateAnimation("Alpha")
        alphaAnim:SetFromAlpha((EasyCursorTrailsDB.glowIntensityFactor or 0.8) * 0.5)
        alphaAnim:SetToAlpha(EasyCursorTrailsDB.glowIntensityFactor or 0.8)
        alphaAnim:SetDuration(1)
        glowLayer.animation:AddAnimation(alphaAnim)
    end

    glowLayer.animation:Play()
end

function EasyCursorTrails.ToggleGlow(glow, show)
    if show and glow and glow.texture then
        glow.texture:SetVertexColor(EasyCursorTrailsDB.glowColor.r, EasyCursorTrailsDB.glowColor.g, EasyCursorTrailsDB.glowColor.b, EasyCursorTrailsDB.glowColor.a)
        glow:Show()
        EasyCursorTrails.AnimateGlow(glow)
    else
        if glow and glow.texture then
            glow:Hide()
        end
    end
end

-------------------------
-- Rainbow Color Update
-------------------------
function EasyCursorTrails.UpdateRainbowColor(indexOffset)
    local offset = indexOffset or 0
    local hue = (EasyCursorTrails.colorIndexTrail or 0) + 0.05 + offset

    local rr = 0.5 + 0.5 * math.sin(hue)
    local gg = 0.5 + 0.5 * math.sin(hue + 2)
    local bb = 0.5 + 0.5 * math.sin(hue + 4)

    return rr, gg, bb
end


local function SanitizeColor(c)
    if type(c) ~= "table" or type(c.r) ~= "number" or type(c.g) ~= "number" or type(c.b) ~= "number" then
        return { r = 1, g = 1, b = 1, a = 1 }
    end
    c.a = type(c.a) == "number" and c.a or 1
    return c
end


function EasyCursorTrails.ApplyColorEffectTrail(trail, index)

    ---------------------------------------------------------------
    -- 1) Basic safety checks
    ---------------------------------------------------------------
    if not (trail and trail.texture) then
        EasyCursorTrails.HandleError("ApplyColorEffectTrail: 'trail' or 'trail.texture' is nil.")
        return
    end

    ---------------------------------------------------------------
    -- 2) Retrieve the current profile & defaults
    ---------------------------------------------------------------
    local currentProfileName = EasyCursorTrailsDB.currentProfile or "Default"
    local profile = EasyCursorTrailsDB.profiles[currentProfileName]
    if not profile then
        profile = {}
        EasyCursorTrails.HandleError("ApplyColorEffectTrail: Missing profile '" .. currentProfileName .. "', using empty.")
    end

    local defaults = EasyCursorTrails.defaults or {}

    -- 🧰 Helper to fetch value from profile or default
    local function getVal(key)
        return profile[key] ~= nil and profile[key] or defaults[key]
    end

    ---------------------------------------------------------------
    -- 3) Twinkle Stars
    ---------------------------------------------------------------
if profile.enableTwinkleStars and trail.twinkleSpark and trail.twinkleSpark.texture then
    local color = EasyCursorTrails.GetTwinkleStarsColor(profile)

    -- Slightly randomize rotation
    trail.twinkleSpark.texture:SetRotation(math.rad(math.random(-20, 20)))

    -- Randomize alpha (90% to 100% of original)
    local alpha = color.a * (math.random(90, 100) / 100)

    -- Apply color with randomized alpha
    trail.twinkleSpark.texture:SetVertexColor(color.r, color.g, color.b, alpha)

    -- Randomize sparkle scale (between 0.9 and 1.1)
    trail.twinkleSpark:SetScale(0.9 + math.random() * 0.2)

    trail.twinkleSpark:Show()
end

    ---------------------------------------------------------------
    -- 4) Static Arc
    ---------------------------------------------------------------
    if profile.enableStaticArc and trail.staticArc and trail.staticArc.texture then
        local color = profile.randomStaticArcColor and EasyCursorTrails.GetRandomVibrantColor()
            or getVal("staticArcColor") or { r = 1, g = 1, b = 0.3, a = 1 }

        trail.staticArc.texture:SetVertexColor(color.r, color.g, color.b, color.a)
        trail.staticArc:Show()
    end

    ---------------------------------------------------------------
    -- 5) Lightning Embers
    ---------------------------------------------------------------
    if profile.enableLightningEmbers and trail.lightningEmber and trail.lightningEmber.texture then
        local color = profile.randomLightningColor and EasyCursorTrails.GetRandomVibrantColor()
            or getVal("lightningColor") or { r = 0.5, g = 0.7, b = 1, a = 0.9 }

        trail.lightningEmber.texture:SetVertexColor(color.r, color.g, color.b, color.a)
        trail.lightningEmber:Show()
    end

    ---------------------------------------------------------------
    -- 6) Burning FireGlow
    ---------------------------------------------------------------
    if profile.enableFireEffect and trail.fireGlow and trail.fireGlow.texture then
        local color = profile.randomFireColor and EasyCursorTrails.GetRandomVibrantColor()
            or getVal("fireColor") or { r = 1, g = 0.4, b = 0.1, a = 0.8 }

        trail.fireGlow.texture:SetVertexColor(color.r, color.g, color.b, color.a)
        trail.fireGlow:Show()
    end

    ---------------------------------------------------------------
    -- 7) Lightning Spark
    ---------------------------------------------------------------
    if profile.enableLightningSpark and trail.lightningSpark and trail.lightningSpark.texture then
    local color = profile.randomLightningSparkColor and EasyCursorTrails.GetRandomVibrantColor()
        or getVal("lightningSparkColor") or { r = 0.8, g = 0.8, b = 1, a = 1 }

    trail.lightningSpark.texture:SetVertexColor(color.r, color.g, color.b, color.a)

    -- Optional: Add flicker or pulse animation here
    trail.lightningSpark:SetScale(1.0 + math.random() * 0.2)
    trail.lightningSpark:Show()
    end

    ---------------------------------------------------------------
    -- 8) Star Embers
    ---------------------------------------------------------------

    if profile.enableStarEmbers and trail.starEmbers and trail.starEmbers.texture then
    local color = getVal("starColor") or { r = 1, g = 1, b = 1, a = 1 }

    trail.starEmbers.texture:SetVertexColor(color.r, color.g, color.b, color.a)
    trail.starEmbers:SetScale(0.8 + math.random() * 0.4)
    trail.starEmbers:Show()
    end

    ---------------------------------------------------------------
    -- 9) Smokes
    ---------------------------------------------------------------

    if profile.enableSmokeEffect and trail.smokeEffect and trail.smokeEffect.texture then
    local color = getVal("smokeColor") or { r = 0.4, g = 0.4, b = 0.4, a = 0.4 }

    trail.smokeEffect.texture:SetVertexColor(color.r, color.g, color.b, color.a)
    trail.smokeEffect:SetAlpha(color.a * (0.8 + math.random() * 0.4))
    trail.smokeEffect:Show()
    end


    ---------------------------------------------------------------
    -- 9) Spring Season
    ---------------------------------------------------------------

    if profile.enableSpringSeason and trail.springSeason and trail.springSeason.texture then
        local color = getVal("springSeasonColor") or { r = 0.5, g = 1, b = 0.5, a = 1 }

        trail.springSeason.texture:SetVertexColor(color.r, color.g, color.b, color.a)
        trail.springSeason:SetScale(0.9 + math.random() * 0.3)
        trail.springSeason:Show()
    end



    ---------------------------------------------------------------
    -- 3) Gather config values from profile (or defaults)
    ---------------------------------------------------------------
    -- glowColor, glowIntensity, customGlowTex might originally be stored in the profile,
    -- or might still be top-level in EasyCursorTrailsDB. Ideally unify them into the profile:
    local glowColor    = getVal("glowColor")    or { r=1, g=1, b=1, a=1 }
    local glowIntensity= getVal("glowIntensity") or 1
    local customGlowTex= getVal("customGlowTexture")
                       or "Interface\\GLUES\\MODELS\\UI_Draenei\\GenericGlow64"

    -- The user-chosen "textureOpacity" from a slider, or fallback 1
    local textureOpacity      = getVal("trailTextureOpacity")    or 1
    local glowIntensityFactor = getVal("glowIntensityFactor")    or 0.8

    -- The color effect index
    local effect      = getVal("trailColorEffect") or 1
    -- The user's chosen color
    local trailColor  = getVal("trailColor")       or { r=1, g=1, b=1, a=1 }
---------------------------------------------------------------
-- 4) Initialize dynamic values
---------------------------------------------------------------
EasyCursorTrails.colorIndexTrail = EasyCursorTrails.colorIndexTrail or 0
EasyCursorTrails.pulseValueTrail = EasyCursorTrails.pulseValueTrail or 0.5
index = index or 1

local r, g, b, a = 1, 1, 1, 1
local showGlow = false

-- Pulse updater
local function UpdatePulse()
    if EasyCursorTrails.UpdatePulseValue then
        EasyCursorTrails.UpdatePulseValue()
    else
        EasyCursorTrails.HandleError("ApplyColorEffectTrail: Missing UpdatePulseValue function.")
    end
end

-- Rainbow hue generator
local function GetRainbowHue(offset)
    offset = offset or 0
    local hue = (EasyCursorTrails.colorIndexTrail + (index * 15) + offset) % 360
    return EasyCursorTrails.HSVToRGB(hue, 1, 1)
end

---------------------------------------------------------------
-- 5) Color effect logic
---------------------------------------------------------------
if effect == 1 then
    r, g, b, a = 1, 1, 1, 1
elseif effect == 2 then
    r, g, b = GetRainbowHue()
    a = 1
elseif effect == 3 then
    UpdatePulse()
    r = EasyCursorTrails.pulseValueTrail
    g = EasyCursorTrails.pulseValueTrail
    b = EasyCursorTrails.pulseValueTrail
    a = 1
elseif effect == 4 then
    r, g, b, a = 1, 1, 1, 0.9
    showGlow = true
elseif effect == 5 then
    UpdatePulse()
    local rr, gg, bb = GetRainbowHue()
    r = rr * EasyCursorTrails.pulseValueTrail
    g = gg * EasyCursorTrails.pulseValueTrail
    b = bb * EasyCursorTrails.pulseValueTrail
    a = 1
elseif effect == 6 then
    UpdatePulse()
    local rr, gg, bb = GetRainbowHue()
    r = rr * EasyCursorTrails.pulseValueTrail
    g = gg * EasyCursorTrails.pulseValueTrail
    b = bb * EasyCursorTrails.pulseValueTrail
    a = 1
    showGlow = true
elseif effect == 7 then
    r, g, b, a = trailColor.r, trailColor.g, trailColor.b, trailColor.a
elseif effect == 8 then
    UpdatePulse()
    r = trailColor.r * EasyCursorTrails.pulseValueTrail
    g = trailColor.g * EasyCursorTrails.pulseValueTrail
    b = trailColor.b * EasyCursorTrails.pulseValueTrail
    a = trailColor.a
elseif effect == 9 then
    r, g, b, a = trailColor.r, trailColor.g, trailColor.b, 0.8
    showGlow = true
elseif effect == 10 then
    UpdatePulse()
    r = trailColor.r * EasyCursorTrails.pulseValueTrail
    g = trailColor.g * EasyCursorTrails.pulseValueTrail
    b = trailColor.b * EasyCursorTrails.pulseValueTrail
    a = trailColor.a
    showGlow = true
elseif effect == 11 then
    r, g, b = GetRainbowHue()
    a = 1
    showGlow = true
elseif effect == 12 then
    r, g, b, a = 0.5, 0.7, 1, 0.8
    showGlow = true
elseif effect == 13 then
    UpdatePulse()
    r, g, b = GetRainbowHue()
    a = 0.9
    showGlow = true
elseif effect == 14 then
    UpdatePulse()
    r = 0.5 + 0.5 * math.sin(EasyCursorTrails.colorIndexTrail)
    g = 0.5 + 0.5 * math.cos(EasyCursorTrails.colorIndexTrail + 1)
    b = 0.5 + 0.5 * math.sin(EasyCursorTrails.colorIndexTrail + 2)
    a = EasyCursorTrails.pulseValueTrail
elseif effect == 15 then
    r, g, b, a = 0.2, 0.1, 0.3, 0.7
    showGlow = true
elseif effect == 16 then
    UpdatePulse()
    r, g, b, a = 0, 0.7 * EasyCursorTrails.pulseValueTrail, 0.6, 1
    showGlow = true
elseif effect == 17 then
    UpdatePulse()
    r = 0.8 + 0.2 * EasyCursorTrails.pulseValueTrail
    g = 0.8 + 0.2 * EasyCursorTrails.pulseValueTrail
    b = 1
    a = 1
    showGlow = true
elseif effect == 18 then
    UpdatePulse()
    local hueOffset = EasyCursorTrails.colorIndexTrail * 3
    r, g, b = EasyCursorTrails.HSVToRGB(hueOffset % 360, 1, 1)
    a = 0.9
    showGlow = true
elseif effect == 19 then
    UpdatePulse()
    r, g, b, a = 1, 0.4 + 0.4 * EasyCursorTrails.pulseValueTrail, 0.2, 1
    showGlow = true
elseif effect == 20 then
    r, g, b, a = 1, 1, 0.8, 0.9
    showGlow = true
elseif effect == 21 then
    UpdatePulse()
    r, g, b, a = 0.3, 0.3, 0.7, EasyCursorTrails.pulseValueTrail
elseif effect == 22 then
    r, g, b, a = 0.8, 0.9, 1, 1
    trail.texture:SetVertexColor(r, g, b, a * textureOpacity)
    EasyCursorTrails.ApplyTwinkleStarsEffect(trail, index, glowIntensityFactor)
else
    r, g, b, a = 1, 1, 1, 1
end

---------------------------------------------------------------
-- 6) Apply final color and overlays
---------------------------------------------------------------
local finalA = a * textureOpacity
trail.texture:SetVertexColor(r, g, b, finalA)

if profile.enableTwinkleStars then
    EasyCursorTrails.ApplyTwinkleStarsEffect(trail, index, profile.glowIntensityFactor or 1)
end

if profile.enableStaticArc then
    EasyCursorTrails.ApplyStaticArcEffect(trail, index, profile.staticArcColor or EasyCursorTrails.defaults.staticArcColor)
else
    EasyCursorTrails.ClearStaticArcEffect(trail)
end
---------------------------------------------------------------
-- 7) Glow Layers: radiant glow behind trail (enhanced)
---------------------------------------------------------------
if showGlow then
    local glowFactor = (EasyCursorTrails.glowFactorSlider and EasyCursorTrails.glowFactorSlider:GetValue())
        or (EasyCursorTrails.currentProfileTable and EasyCursorTrails.currentProfileTable.glowIntensityFactor)
        or 0.8

    -- Clamp alpha and brightness for stronger glow
    local safeAlpha   = math.max(math.min(glowFactor, 1.0), 0.6)
    local brightness  = math.min(glowFactor * 1.5, 3.0)
    local baseW       = math.max(trail:GetWidth() or 0, 1)
    local baseH       = math.max(trail:GetHeight() or 0, 1)
    local minGlowSize = 24

    -- Optional: pulsing glow effect
    local pulse = 0.9 + 0.1 * math.sin(GetTime() * 3)
    local adaptiveAlpha = math.min(safeAlpha * pulse, 1)

    -- Create 3 glow layers if not already present
    if not trail.glowLayers then
        trail.glowLayers = {}
        for i = 1, 3 do
            local glowFrame = CreateFrame("Frame", nil, trail)
            glowFrame:SetFrameLevel(math.max(trail:GetFrameLevel() - 5 - i, 0))
            glowFrame:SetPoint("CENTER", trail, "CENTER")

            local glowTex = glowFrame:CreateTexture(nil, "OVERLAY")
            glowTex:SetTexture(customGlowTex)
            glowTex:SetBlendMode("ADD")
            glowTex:SetAllPoints(true)
            glowFrame.texture = glowTex

            glowFrame:Hide()
            table.insert(trail.glowLayers, glowFrame)
        end
    end

    -- Update each glow layer
    for i, glowLayer in ipairs(trail.glowLayers) do
        local expansion = 14 + (i * 12)  -- Larger expansion for stronger aura
        local glowW = math.max(baseW + expansion, minGlowSize)
        local glowH = math.max(baseH + expansion, minGlowSize)
        glowLayer:SetSize(glowW, glowH)

        glowLayer.texture:SetVertexColor(
            r * brightness,
            g * brightness,
            b * brightness,
            adaptiveAlpha
        )

        if adaptiveAlpha > 0.01 then
            glowLayer:Show()
        else
            glowLayer:Hide()
        end
    end
end

end



function EasyCursorTrails.ApplyColorEffectCursor(elapsed)
    -------------------------------------------------------
    -- 1) Validate customCursor
    -------------------------------------------------------
    if not customCursor or not customCursor.texture then
        EasyCursorTrails.HandleError("ApplyColorEffectCursor: 'customCursor' or 'customCursor.texture' not initialized.")
        return
    end

    -------------------------------------------------------
    -- 2) Retrieve the current profile and defaults
    -------------------------------------------------------
    local currentProfileName = EasyCursorTrailsDB.currentProfile or "Default"
    local profile = EasyCursorTrailsDB.profiles[currentProfileName]
    if not profile then
        profile = {}
        EasyCursorTrails.HandleError("ApplyColorEffectCursor: Missing profile '" .. currentProfileName .. "', using empty fallback.")
    end

    local defaults = EasyCursorTrails.defaults or {}

    -- Helper to get a profile value, or fallback to defaults
    local function getVal(key)
        local val = profile[key]
        if val == nil then
            val = defaults[key]
        end
        return val
    end

    -------------------------------------------------------
    -- 3) Gather the config we need
    -------------------------------------------------------
    local glowColor       = getVal("glowColor")       or { r=1, g=1, b=1, a=1 }
    local glowIntensity   = getVal("glowIntensity")   or 1
    local effect          = getVal("cursorColorEffect") or 1
    local cursorColor     = getVal("cursorColor")     or { r=1, g=1, b=1, a=1 }

    -------------------------------------------------------
    -- 4) Blend Mode
    -------------------------------------------------------
    customCursor.texture:SetBlendMode("ADD")

    -------------------------------------------------------
    -- 5) Effect Logic
    --
    --   We override the texture color based on effect index.
    --   If the user wants some "default glow" behind the effect,
    --   you can set that first, but be sure not to override
    --   after you apply the chosen effect.
    -------------------------------------------------------
    if effect == 1 then
        -- (1) Static White
        customCursor.texture:SetVertexColor(1, 1, 1, 1)

    elseif effect == 2 then
        -- (2) Rainbow Effect
        customCursor.colorIndexCursor = (customCursor.colorIndexCursor or 0) + (elapsed or 0.05)*60
        customCursor.colorIndexCursor = customCursor.colorIndexCursor % 360
        local hue = customCursor.colorIndexCursor
        local r, g, b = EasyCursorTrails.HSVToRGB(hue, 1, 1)
        customCursor.texture:SetVertexColor(r, g, b, cursorColor.a)

    elseif effect == 3 then
        -- (3) Pulsing White
        EasyCursorTrails.ApplyPulsingEffect(cursorColor, elapsed)

    elseif effect == 4 then
        -- (4) Rainbow + Pulsing
        EasyCursorTrails.ApplyRainbowPulsingEffect(cursorColor, elapsed)

    elseif effect == 5 then
        -- (5) Static Custom Color
        customCursor.texture:SetVertexColor(cursorColor.r, cursorColor.g, cursorColor.b, cursorColor.a)

    elseif effect == 6 then
        -- (6) Pulsing with Static Color
        EasyCursorTrails.ApplyPulsingEffect(cursorColor, elapsed)

    elseif effect == 7 then
        -- (7) Some "Glow" effect
        EasyCursorTrails.ApplyGlowEffect(cursorColor, elapsed)

    else
        -- Fallback => white
        customCursor.texture:SetVertexColor(1, 1, 1, 1)
    end

  
end


-- Helper: Apply Pulsing Effect
function EasyCursorTrails.ApplyPulsingEffect(cursorColor, elapsed)
    local pulseValue = (customCursor.pulseValueCursor or 0.5)
                     + (customCursor.pulseDirectionCursor or -1) * (elapsed or 0.05) * 0.5
    if pulseValue > 1 then
        pulseValue = 1
        customCursor.pulseDirectionCursor = -1
    elseif pulseValue < 0.5 then
        pulseValue = 0.5
        customCursor.pulseDirectionCursor = 1
    end
    customCursor.pulseValueCursor = pulseValue
    customCursor.texture:SetVertexColor(
        cursorColor.r * pulseValue,
        cursorColor.g * pulseValue,
        cursorColor.b * pulseValue,
        cursorColor.a
    )
end

-- Helper: Apply Rainbow + Pulsing Effect
function EasyCursorTrails.ApplyRainbowPulsingEffect(cursorColor, elapsed)
    customCursor.colorIndexCursor = (customCursor.colorIndexCursor or 0) + (elapsed or 0.05) * 60
    customCursor.colorIndexCursor = customCursor.colorIndexCursor % 360
    local hue = customCursor.colorIndexCursor / 360
    local baseR, baseG, baseB = EasyCursorTrails.HSVToRGB(hue * 360, 1, 1)

    local pulseValue = (customCursor.pulseValueCursor or 0.5)
                     + (customCursor.pulseDirectionCursor or 1) * (elapsed or 0.05) * 0.5
    if pulseValue > 1 then
        pulseValue = 1
        customCursor.pulseDirectionCursor = -1
    elseif pulseValue < 0.1 then
        pulseValue = 0.2
        customCursor.pulseDirectionCursor = 1
    end
    customCursor.pulseValueCursor = pulseValue

    customCursor.texture:SetVertexColor(
        baseR * pulseValue,
        baseG * pulseValue,
        baseB * pulseValue,
        cursorColor.a
    )
end

-- Helper: Apply Glow Effect
function EasyCursorTrails.ApplyGlowEffect(cursorColor, elapsed)
    -- Smooth pulsing alpha logic
    local alpha = (customCursor.glowAlpha or 0.8)
                + (customCursor.glowDir or 1) * (elapsed or 0.05) * 0.5

    if alpha > 1 then
        alpha = 1
        customCursor.glowDir = -1
    elseif alpha < 0.8 then
        alpha = 0.8
        customCursor.glowDir = 1
    end
    customCursor.glowAlpha = alpha

    -- Adjust alpha if trail size is too small for glow visibility
    local trailSize = customCursor:GetWidth() or 0
    if trailSize < 15 then
        -- Boost alpha slightly to ensure glow remains visible
        alpha = math.max(alpha, 0.9)
    end

    -- Apply glow color with adjusted alpha
    customCursor.texture:SetVertexColor(cursorColor.r, cursorColor.g, cursorColor.b, alpha)
end






-- Function to update glow effects based on saved or selected state
function EasyCursorTrails.UpdateGlowBelowCursor()
    if not customCursor or not customCursor.glowEffects then
         ----print("EasyCursorTrails Error: customCursor or glowEffects not initialized.")
        return
    end

    -- Apply the appropriate frame strata to glow effects
    for _, glow in ipairs(customCursor.glowEffects) do
        if EasyCursorTrailsDB.glowBelow then
            glow:SetFrameStrata("LOW")
        else
            glow:SetFrameStrata("HIGH")
        end
    end
end




function EasyCursorTrails.InitializeSettingsMenu()
    if EasyCursorTrails.menuInitialized then
        return
    end
    EasyCursorTrails.menuInitialized = true
   
    -- Reset settingsChanged flag
    EasyCursorTrails.settingsChanged = false

    -- Create the settings menu frame
    local menu = CreateFrame("Frame", "EasyCursorTrailsMenu", UIParent, "BasicFrameTemplateWithInset")
    menu:SetSize(920, 830)
    menu:SetPoint("CENTER", UIParent, "CENTER")
    menu:SetMovable(true)
    menu:EnableMouse(true)
    menu:RegisterForDrag("LeftButton")
    menu:SetScript("OnDragStart", menu.StartMoving)
    menu:SetScript("OnDragStop", function(self)
        self:StopMovingOrSizing()
        local point, _, relativePoint, x, y = self:GetPoint()
        EasyCursorTrailsDB.menuPosition = { point = point, relativePoint = relativePoint, x = x, y = y }
        EasyCursorTrails.SaveToCurrentProfile("menuPosition", EasyCursorTrailsDB.menuPosition)
    end)
    menu:Hide()

-- Restore saved menu position
if EasyCursorTrailsDB.menuPosition then
    menu:ClearAllPoints()
    menu:SetPoint(
        EasyCursorTrailsDB.menuPosition.point,
        UIParent,
        EasyCursorTrailsDB.menuPosition.relativePoint,
        EasyCursorTrailsDB.menuPosition.x,
        EasyCursorTrailsDB.menuPosition.y
    )
end


    -- Reset menu position button
    local resetPositionButton = CreateFrame("Button", "ResetMenuPositionButton", menu, "UIPanelButtonTemplate")
    resetPositionButton:SetSize(150, 25)
    resetPositionButton:SetText("Reset Menu Position")
    resetPositionButton:SetPoint("BOTTOM", menu, "BOTTOM", 250, 90)
    resetPositionButton:SetScript("OnClick", function()
        menu:ClearAllPoints()
        menu:SetPoint("CENTER", UIParent, "CENTER")
        EasyCursorTrailsDB.menuPosition = { point = "CENTER", relativePoint = "CENTER", x = 0, y = 0 }
        EasyCursorTrails.SaveToCurrentProfile("menuPosition", EasyCursorTrailsDB.menuPosition)
        -- ----print("EasyCursorTrails: Menu position reset to default.")
    end)


   -- A text note (two lines) in a larger font
local reloadNote = menu:CreateFontString(nil, "OVERLAY", "GameFontNormal")
reloadNote:SetPoint("TOP", resetPositionButton, "BOTTOM", 0, -20)
reloadNote:SetText("Hint:\nDon’t forget to save after updates or profile changes\n Effects will look much better on reload!")


    -- UI Elements
    local menuTitle = menu:CreateFontString(nil, "OVERLAY", "GameFontHighlightLarge")
    menuTitle:SetPoint("TOP", menu, "TOP", 0, -3)
    menuTitle:SetText("Easy Cursor Trails Settings")


    -- ============================
-- 1) Enable Trails Checkbox
-- ============================
local enableTrailsCheckbox = CreateFrame("CheckButton", "EnableTrailsCheckbox", menu, "UICheckButtonTemplate")
enableTrailsCheckbox:SetPoint("TOPLEFT", menuTitle, "BOTTOMLEFT", -50, -50)

-- Create and position the label for the checkbox
enableTrailsCheckbox.text = enableTrailsCheckbox:CreateFontString(nil, "OVERLAY", "GameFontNormal")
enableTrailsCheckbox.text:SetPoint("LEFT", enableTrailsCheckbox, "RIGHT", 5, 0)
enableTrailsCheckbox.text:SetText("Enable Trails")

-- Set the initial checked state based on the current profile
local currentProfileName = EasyCursorTrailsDB.currentProfile or "Default"
local currentProfile = EasyCursorTrailsDB.profiles[currentProfileName]
enableTrailsCheckbox:SetChecked(currentProfile and currentProfile.enableTrails or false)

enableTrailsCheckbox:SetScript("OnClick", function(self)
    local isEnabled = self:GetChecked()

    -- ✅ Force sync immediately into both DB and runtime table
    local profileName = EasyCursorTrailsDB.currentProfile or "Default"
    local profile = EasyCursorTrailsDB.profiles[profileName]
    if profile then
        profile.enableTrails = isEnabled
        EasyCursorTrails.currentProfileTable.enableTrails = isEnabled
    end

    -- 🌀 Apply changes
    if isEnabled then
        if EasyCursorTrails.RebuildTrails then
            EasyCursorTrails.RebuildTrails()
        end
    else
        if EasyCursorTrails.trailPool then
            for _, layerPool in pairs(EasyCursorTrails.trailPool) do
                for _, trail in ipairs(layerPool) do
                    if trail then trail:Hide() end
                end
            end
        end
    end

    -- 🔁 Delay refresh to avoid race condition
    C_Timer.After(0.1, function()
        if EasyCursorTrails.RefreshSettingsUI then
            EasyCursorTrails.RefreshSettingsUI()
            -- ✅ Re-sync UI state AFTER everything else
            enableTrailsCheckbox:SetChecked(EasyCursorTrails.currentProfileTable.enableTrails)
        end
    end)
end)


-- Assign the checkbox to the namespace for easy access elsewhere
EasyCursorTrails.enableTrailsCheckbox = enableTrailsCheckbox


    -- Cursor Settings
    local cursorHeading = menu:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    cursorHeading:SetPoint("TOPLEFT", menuTitle, "BOTTOMLEFT", -300, -20)
    cursorHeading:SetText("Cursor Settings")
    
-- Glow Below Cursor Checkbox
local glowBelowCheckbox = CreateFrame("CheckButton", "GlowBelowCursorCheckbox", menu, "UICheckButtonTemplate")
glowBelowCheckbox:SetPoint("TOPLEFT", cursorHeading, "BOTTOMLEFT", -20, -15)

-- Add label text
glowBelowCheckbox.text = glowBelowCheckbox:CreateFontString(nil, "OVERLAY", "GameFontNormal")
glowBelowCheckbox.text:SetPoint("LEFT", glowBelowCheckbox, "RIGHT", 5, 0)
glowBelowCheckbox.text:SetText("Glow behind the frame")

-- Initialize checkbox state from the saved database or default
glowBelowCheckbox:SetChecked(EasyCursorTrailsDB.glowBelow or false)

-- OnClick event to handle user interaction
glowBelowCheckbox:SetScript("OnClick", function(self)
    -- Update the database with the new state
    EasyCursorTrailsDB.glowBelow = self:GetChecked()
    EasyCursorTrails.SaveToCurrentProfile("glowBelow", EasyCursorTrailsDB.glowBelow)

    -- Dynamically update the glow effect
    EasyCursorTrails.UpdateGlowBelowCursor()
end)

-- 🧠 Debounce logic to prevent rebuild spam
local debounceTimer
local function DebouncedRebuild()
    if debounceTimer then
        debounceTimer:Cancel()
    end
    debounceTimer = C_Timer.NewTimer(0.2, function()
        EasyCursorTrails.RebuildTrails()
    end)
end

-- 🛠 Trail Size Start Slider
local trailSizeStartSlider = CreateSlider(
    "TrailSizeStartSlider",
    menu,
    "Trail Size Start",
    1,
    100,
    1,
    EasyCursorTrailsDB.trailSizeStart or EasyCursorTrails.defaults.trailSizeStart,
    function(slider, value)
    EasyCursorTrailsDB.trailSizeStart = value
    EasyCursorTrails.SaveToCurrentProfile("trailSizeStart", value)

   
    -- Instant visual update
    EasyCursorTrails.RebuildTrails()

    -- Debounced rebuild for safety (optional)
    DebouncedRebuild()

end

)

-- Position and store reference
trailSizeStartSlider:SetPoint("TOPLEFT", enableTrailsCheckbox, "BOTTOMLEFT", 0, -30)
EasyCursorTrails.trailSizeStartSlider = trailSizeStartSlider

-- 🛠 Trail Size End Slider
local trailSizeEndSlider = CreateSlider(
    "TrailSizeEndSlider",
    menu,
    "Trail Size End",
    1,
    100,
    1,
    EasyCursorTrailsDB.trailSizeEnd or EasyCursorTrails.defaults.trailSizeEnd,
   function(slider, value)
    EasyCursorTrailsDB.trailSizeEnd = value
    EasyCursorTrails.settingsChanged = true
    EasyCursorTrails.SaveToCurrentProfile("trailSizeEnd", value)

   
    -- Instant visual update
    EasyCursorTrails.RebuildTrails()

    -- Debounced rebuild for safety (optional)
    DebouncedRebuild()
end

)

-- Position and store reference
trailSizeEndSlider:SetPoint("TOPLEFT", trailSizeStartSlider, "BOTTOMLEFT", 0, -30)
EasyCursorTrails.trailSizeEndSlider = trailSizeEndSlider




-- 🛠 Trail Count Slider
local trailCountSlider = CreateSlider(
    "TrailCountSlider",
    menu,
    "Trail Length",
    1, -- Avoid 0 if your code doesn’t handle zero trails well
    200,
    1,
    EasyCursorTrailsDB.trailCount or EasyCursorTrails.defaults.trailCount,
    function(slider, value)
        EasyCursorTrailsDB.trailCount = value
        EasyCursorTrails.settingsChanged = true
        EasyCursorTrails.SaveToCurrentProfile("trailCount", value)
        

   
    -- Instant visual update
    EasyCursorTrails.RebuildTrails()

    -- Debounced rebuild for safety (optional)
    DebouncedRebuild()
    end
)
trailCountSlider:SetPoint("TOPLEFT", trailSizeEndSlider, "BOTTOMLEFT", 0, -30)
EasyCursorTrails.trailCountSlider = trailCountSlider

-- 🛠 Trail Duplicate Slider
local trailDuplicatesSlider = CreateSlider(
    "trailDuplicatesSlider",
    menu,
    "Trail Duplicate",
    1,      -- Minimum value
    20,     -- Maximum value
    1,      -- Step size
    EasyCursorTrails.currentProfileTable and EasyCursorTrails.currentProfileTable.trailLayerCount
        or EasyCursorTrails.defaults.trailLayerCount
        or 14,
    function(slider, value)
        local newValue = math.floor(value)
        EasyCursorTrailsDB.trailLayerCount = newValue
        EasyCursorTrails.settingsChanged = true
        EasyCursorTrails.SaveToCurrentProfile("trailLayerCount", newValue)
        
 
   
    -- Instant visual update
    EasyCursorTrails.RebuildTrails()

    -- Debounced rebuild for safety (optional)
    DebouncedRebuild()
    end, 2
    
)
trailDuplicatesSlider:SetPoint("TOPLEFT", trailCountSlider, "BOTTOMLEFT", 0, -30)
EasyCursorTrails.trailDuplicatesSlider = trailDuplicatesSlider

-- 🧼 Ensure defaults table and chainSegment default exist
EasyCursorTrails.defaults = EasyCursorTrails.defaults or {}
EasyCursorTrails.defaults.chainSegment = EasyCursorTrails.defaults.chainSegment or 10

-- 🔍 Determine current profile
local currentProfileName = EasyCursorTrailsDB.currentProfile or "Default"
local currentProfile = EasyCursorTrailsDB.profiles[currentProfileName] or {}
EasyCursorTrails.currentProfileTable = currentProfile

-- 🧪 Sanitize stored value
local storedVal = currentProfile.chainSegment
if type(storedVal) == "table" then
    storedVal = EasyCursorTrails.defaults.chainSegment
    currentProfile.chainSegment = storedVal
    EasyCursorTrails.SaveToCurrentProfile("chainSegment", storedVal)
end
local chainSegmentInitial = tonumber(storedVal) or EasyCursorTrails.defaults.chainSegment

-- 🔢 Optional multiplier (preserved for future scaling)
local CHAIN_GAP_FACTOR = 1
local chainSegmentInitialEffective = chainSegmentInitial * CHAIN_GAP_FACTOR


-- 🛠 Create Chain Segment Slider
local chainSegmentSlider = CreateSlider(
    "ChainSegmentSlider",
    menu,
    "Trail Segment Distance",
    10,
    100,
    1,
    chainSegmentInitial,
    function(slider, value)
        local effectiveGap = value * CHAIN_GAP_FACTOR
        currentProfile.chainSegment = effectiveGap
        EasyCursorTrails.settingsChanged = true
        EasyCursorTrails.SaveToCurrentProfile("chainSegment", effectiveGap)

        if slider.editBox then
            slider.editBox:SetText(string.format("%.0f", effectiveGap))
        end

    -- Instant visual update
    EasyCursorTrails.RebuildTrails()

    -- Debounced rebuild for safety (optional)
    DebouncedRebuild()
    end, 2
)
chainSegmentSlider:SetPoint("TOPLEFT", trailDuplicatesSlider, "BOTTOMLEFT", 0, -30)
EasyCursorTrails.chainSegmentSlider = chainSegmentSlider

-- 🖊️ Initialize edit box display
if chainSegmentSlider.editBox then
    chainSegmentSlider.editBox:SetText(string.format("%.0f", chainSegmentInitialEffective))
end


-- 🧼 Ensure defaults table and fallback value
EasyCursorTrails.defaults = EasyCursorTrails.defaults or {}
EasyCursorTrails.defaults.trailInitialSeparation = EasyCursorTrails.defaults.trailInitialSeparation or 50

-- 🛠 Create Trail Layer Separation Slider
local trailInitialSeparationSlider = CreateSlider(
    "TrailInitialSeparationSlider",
    menu,
    "Trail Layer Separation",
    1,
    500,
    1,
    EasyCursorTrailsDB.trailInitialSeparation or EasyCursorTrails.defaults.trailInitialSeparation,
    function(slider, value)
        EasyCursorTrailsDB.trailInitialSeparation = value
        EasyCursorTrails.settingsChanged = true
        EasyCursorTrails.SaveToCurrentProfile("trailInitialSeparation", value)
        
    -- Instant visual update
    EasyCursorTrails.RebuildTrails()

    -- Debounced rebuild for safety (optional)
    DebouncedRebuild()
    end, 2
)
trailInitialSeparationSlider:SetPoint("TOPLEFT", chainSegmentSlider, "BOTTOMLEFT", 0, -30)
EasyCursorTrails.trailInitialSeparationSlider = trailInitialSeparationSlider

-- 🛠️ Trail Texture Opacity Slider Setup (Lag-Free)
local currentProfileName = EasyCursorTrailsDB.currentProfile or "Default"
local currentProfile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[currentProfileName]

local initialOpacity = (currentProfile and currentProfile.trailTextureOpacity)
    or EasyCursorTrails.defaults.trailTextureOpacity
    or 1.0

local trailTextureOpacitySlider = CreateSlider(
    "trailTextureOpacity",
    menu,
    "Trail Texture Opacity",
    0.0,    -- Min
    1.0,    -- Max
    0.01,   -- Step
    initialOpacity,
    function(slider, value)
        -- 🔄 Save to profile
        local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[currentProfileName]
        if not profile then
            EasyCursorTrails.HandleError("trailTextureOpacitySlider: current profile not found.")
            return
        end

        profile.trailTextureOpacity = value
        EasyCursorTrails.SaveToCurrentProfile("trailTextureOpacity", value)

        -- 🎨 Lightweight visual update (no full rebuild)
        if EasyCursorTrails.trailPool then
            for _, layerPool in pairs(EasyCursorTrails.trailPool) do
                for _, trail in ipairs(layerPool) do
                    if trail and trail.texture then
                        trail.texture:SetVertexColor(1, 1, 1, value)
                    end
                end
            end
        end

        -- 🧪 Preview update
        if EasyCursorTrails.TrailPreview and EasyCursorTrails.TrailPreview.texture then
            EasyCursorTrails.TrailPreview.texture:SetVertexColor(1, 1, 1, value)
        end

        -- 🕒 Debounced rebuild (only if needed)
        DebouncedRebuild()
    end,
    2  -- Display precision: 2 decimal places
)

-- 📍 Positioning
trailTextureOpacitySlider:SetPoint("TOPLEFT", trailInitialSeparationSlider, "CENTER", -75, -145)
EasyCursorTrails.trailTextureOpacitySlider = trailTextureOpacitySlider


-- 🧼 Ensure defaults table and fallback value
EasyCursorTrails.defaults = EasyCursorTrails.defaults or {}
EasyCursorTrails.defaults.glowIntensityFactor = EasyCursorTrails.defaults.glowIntensityFactor or 0.8

-- 🔍 Determine initial value
local currentProfileName = EasyCursorTrailsDB.currentProfile or "Default"
local currentProfile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[currentProfileName] or {}
local initialGlowFactor = currentProfile.glowIntensityFactor or EasyCursorTrails.defaults.glowIntensityFactor

-- 🌟 Create Glow Factor Slider
local glowFactorSlider = CreateSlider(
    "GlowFactorSlider",
    menu,
    "Trail Glow Intensity Factor",
    0.10,
    1.00,
    0.01,
    initialGlowFactor,
    function(slider, value)
        local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[currentProfileName]
        if not profile then
            EasyCursorTrails.HandleError("glowFactorSlider: Current profile not found.")
            return
        end

        profile.glowIntensityFactor = value
        EasyCursorTrails.settingsChanged = true
        EasyCursorTrails.SaveToCurrentProfile("glowIntensityFactor", value)

        -- 🔄 Update trail glow layers
        if EasyCursorTrails.trailPool then
            for _, layerPool in pairs(EasyCursorTrails.trailPool) do
                for _, trail in ipairs(layerPool) do
                    if trail.glowLayers then
                        for _, glowLayer in ipairs(trail.glowLayers) do
                            local tex = glowLayer.texture
                            if tex then
                                local r, g, b, a = tex:GetVertexColor()
                                tex:SetVertexColor(r * value, g * value, b * value, value == 0 and 0 or a * value)
                            end
                        end
                    end
                end
            end
        end

         -- Instant visual update
    EasyCursorTrails.RebuildTrails()

    -- Debounced rebuild for safety (optional)
    DebouncedRebuild()
    end,
    2
)

glowFactorSlider:SetPoint("TOPLEFT", trailTextureOpacitySlider, "BOTTOMLEFT", 0, -30)
EasyCursorTrails.glowFactorSlider = glowFactorSlider


-- 🧼 Ensure defaults table and fallback value
EasyCursorTrails.defaults = EasyCursorTrails.defaults or {}
EasyCursorTrails.defaults.trailUpdateMultiplier = EasyCursorTrails.defaults.trailUpdateMultiplier or 1

-- 🔍 Determine initial value
local currentProfileName = EasyCursorTrailsDB.currentProfile or "Default"
local currentProfile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[currentProfileName] or {}
local initialFollowSpeed = currentProfile.trailUpdateMultiplier or EasyCursorTrails.defaults.trailUpdateMultiplier

-- 🛠 Create Trail Follow Speed Slider
local trailFollowSpeedSlider = CreateSlider(
    "TrailFollowSpeedSlider",
    menu,
    "Trail Follow Speed",
    1,
    100,
    1,
    initialFollowSpeed,
    function(slider, value)
        local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[currentProfileName]
        if not profile then
            EasyCursorTrails.HandleError("trailFollowSpeedSlider: Current profile not found.")
            return
        end

        profile.trailUpdateMultiplier = value
        EasyCursorTrails.settingsChanged = true
        EasyCursorTrails.SaveToCurrentProfile("trailUpdateMultiplier", value)
            -- Instant visual update
            EasyCursorTrails.RebuildTrails()

            -- Debounced rebuild for safety (optional)
            DebouncedRebuild()
    end
)
trailFollowSpeedSlider:SetPoint("TOPLEFT", glowFactorSlider, "BOTTOMLEFT", 0, -30)
EasyCursorTrails.trailFollowSpeedSlider = trailFollowSpeedSlider


if trailFollowSpeedSlider.editBox then
    trailFollowSpeedSlider.editBox:SetText(string.format("%.0f", initialFollowSpeed))
    trailFollowSpeedSlider.editBox:SetScript("OnEnterPressed", function(self)
        local text = self:GetText()
        local num = tonumber(text)
        if num then
            trailFollowSpeedSlider:SetValue(num, true)
            local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[currentProfileName]
            if profile then
                profile.trailUpdateMultiplier = num
                EasyCursorTrails.SaveToCurrentProfile("trailUpdateMultiplier", num)
                
                            -- Instant visual update
                EasyCursorTrails.RebuildTrails()

                -- Debounced rebuild for safety (optional)
                DebouncedRebuild()
            end
        end
        self:ClearFocus()
    end)
end


function EasyCursorTrails.UpdateTrailOffsets()
    local db = EasyCursorTrailsDB
    local defaults = EasyCursorTrails.defaults or {}
    local profile = db.profiles[db.currentProfile or "Default"]
    if not profile then return end

    local trailOffsetX = tonumber(profile.trailOffsetX) or tonumber(defaults.trailOffsetX) or 0
    local trailOffsetY = tonumber(profile.trailOffsetY) or tonumber(defaults.trailOffsetY) or 0
    local maxOffset     = tonumber(profile.trailLayerSpacingSlider) or 30
    local initialSep    = tonumber(profile.trailInitialSeparation) or 30
    local chainSegment  = tonumber(profile.chainSegment) or tonumber(defaults.chainSegment) or 10
    local bufferSize    = tonumber(EasyCursorTrails.bufferSize) or 100

    local trailPool = EasyCursorTrails.trailPool
    if not trailPool or not trailPool[1] or #trailPool[1] < 1 then return end
    local firstTrail = trailPool[1][1]

    -- 🧠 Use ring buffer position or fallback to cursor
    local posIndex = EasyCursorTrails.headIndex - 1
    if posIndex < 1 then posIndex = posIndex + bufferSize end
    local history = EasyCursorTrails.cursorHistory
    local basePos = history and history[posIndex]

    if not basePos then
        local scale = UIParent:GetEffectiveScale()
        local x, y = GetCursorPosition()
        basePos = { x = x / scale, y = y / scale }
    end

    -- 🌀 Compute dynamic offset
    local angle = 0
    local frac = 0
    local distance = initialSep + frac * (maxOffset - initialSep)
    local effectIndex = profile.trailMovementEffect or 1
    local movementFunc = EasyCursorTrails.movementEffects and EasyCursorTrails.movementEffects[effectIndex]
                        or function() return {0, 0} end
    local offset = movementFunc(angle, frac, distance, profile, 1, 0, maxOffset)
    local dx = (offset[1] or 0) + distance * math.cos(angle)
    local dy = (offset[2] or 0) + distance * math.sin(angle)

    -- 🎯 Final position
    local finalX = basePos.x + trailOffsetX + dx
    local finalY = basePos.y + trailOffsetY + dy

    firstTrail:ClearAllPoints()
    firstTrail:SetPoint("CENTER", UIParent, "BOTTOMLEFT", finalX, finalY)
    firstTrail:Show()

    -- 🧼 Hide other preview trails
    for i = 2, #trailPool[1] do
        local trail = trailPool[1][i]
        if trail and trail:IsShown() then trail:Hide() end
    end

    -- ✨ Update glow frames
    if EasyCursorTrails.UpdateGlowFrames then
        EasyCursorTrails.UpdateGlowFrames()
    else
        EasyCursorTrails.HandleError("UpdateTrailOffsets: UpdateGlowFrames function is missing.")
    end
end



--------------------------------------------
-- 6) Trail Offset X Slider
--------------------------------------------
local trailOffsetXSlider = CreateSlider(
    "TrailOffsetXSlider",
    menu,
    "Trail Offset X",
    -100,
    100,
    1,
    EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile].trailOffsetX or EasyCursorTrails.defaults.trailOffsetX,
    function(slider, value)
        EasyCursorTrails.SaveToCurrentProfile("trailOffsetX", value)
        EasyCursorTrails.RebuildTrails()
        if EasyCursorTrails.UpdateTrailOffsets then
            EasyCursorTrails.UpdateTrailOffsets()
        end
    end
)
trailOffsetXSlider:SetPoint("TOPLEFT", trailInitialSeparationSlider, "BOTTOMLEFT", 0, -30)
EasyCursorTrails.trailOffsetXSlider = trailOffsetXSlider

--------------------------------------------
-- 7) Trail Offset Y Slider
--------------------------------------------
local trailOffsetYSlider = CreateSlider(
    "TrailOffsetYSlider",
    menu,
    "Trail Offset Y",
    -100,
    100,
    1,
    EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile].trailOffsetY or EasyCursorTrails.defaults.trailOffsetY,
    function(slider, value)
        EasyCursorTrails.SaveToCurrentProfile("trailOffsetY", value)
        EasyCursorTrails.RebuildTrails()
        if EasyCursorTrails.UpdateTrailOffsets then
            EasyCursorTrails.UpdateTrailOffsets()
        end
    end
)
trailOffsetYSlider:SetPoint("TOPLEFT", trailOffsetXSlider, "BOTTOMLEFT", 0, -30)
EasyCursorTrails.trailOffsetYSlider = trailOffsetYSlider


-------------------------------
-- Effects Settings Section
-------------------------------
local effectsSettingsHeader = menu:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
effectsSettingsHeader:SetPoint("TOPLEFT", menu, "CENTER", -150, 375)
effectsSettingsHeader:SetText("Trail Effects Settings")


function EasyCursorTrails.CreateValidatedDropdown(name, parent, label, options, selectedIndex, onSelect, maxPerLevel)
    maxPerLevel = maxPerLevel or 30 -- Default to 30 for flat lists

    local dropdown = CreateFrame("Frame", name, parent, "UIDropDownMenuTemplate")
    dropdown:SetPoint("TOPLEFT", parent, "BOTTOMLEFT", 30, 20) -- Adjust positioning as needed

    -- Create a label for the dropdown
    local dropdownLabel = parent:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    dropdownLabel:SetPoint("BOTTOM", dropdown, "TOP", 50, 5)
    dropdownLabel:SetText(label)


    -- Initialize the dropdown
    UIDropDownMenu_Initialize(dropdown, function(self, level, menuList)
        if level == 1 then
            for i, option in ipairs(options) do
                local info = UIDropDownMenu_CreateInfo()
                info.text = option.text
                info.arg1 = i
                info.func = function(_, arg1)
                    onSelect(arg1)
                    UIDropDownMenu_SetSelectedID(dropdown, arg1)
                    UIDropDownMenu_SetText(dropdown, options[arg1].text)
                
                end
                UIDropDownMenu_AddButton(info, level)
            end
        end
    end)

    -- Set the selected option based on selectedIndex
    if selectedIndex and selectedIndex <= #options then
        UIDropDownMenu_SetSelectedID(dropdown, selectedIndex)
        UIDropDownMenu_SetText(dropdown, options[selectedIndex].text)
    elseif #options > 0 then
        UIDropDownMenu_SetSelectedID(dropdown, 1)
        UIDropDownMenu_SetText(dropdown, options[1].text)
    else
        UIDropDownMenu_SetSelectedID(dropdown, 0)
        UIDropDownMenu_SetText(dropdown, "None")
    end

    -- Store onSelect as a property for later reference
    dropdown.onSelect = onSelect

    return dropdown
end


function EasyCursorTrails.PopulateTrailTextureDropdown()
    local MAX_PER_LEVEL = 30

    -- Ensure trailTextures exist before proceeding
    if not EasyCursorTrails.trailTextures or #EasyCursorTrails.trailTextures == 0 then
        EasyCursorTrails.trailTextures = {
            { name = "Default Texture", texture = "Interface\\CURSOR\\Arrow" }
        }
    end

    -- Retrieve active profile
    local profileName = EasyCursorTrailsDB.currentProfile or "Default"
    local profileSettings = EasyCursorTrailsDB.profiles[profileName] or {}
    local defaults = EasyCursorTrails.defaults or {}

    -- Get saved trail texture index
    local storedIndex = profileSettings.trailTexture or defaults.trailTexture or 1

    -- Validate stored index before applying
    if not EasyCursorTrails.trailTextures[storedIndex] then
        storedIndex = 1
        EasyCursorTrailsDB.trailTexture = 1
        EasyCursorTrails.SaveToCurrentProfile("trailTexture", 1)
    end

    -- Create dropdown options
    local textureOptions = {}
    for i, textureInfo in ipairs(EasyCursorTrails.trailTextures) do
        table.insert(textureOptions, {
            text = textureInfo.name,
            icon = textureInfo.texture
        })
    end

    -- Ensure dropdown is created before initializing
    if not EasyCursorTrails.trailTextureDropdown then
       -- print("Error: trailTextureDropdown is nil! Ensure it is initialized before calling PopulateTrailTextureDropdown.")
        return
    end

    -- Initialize dropdown
    UIDropDownMenu_Initialize(EasyCursorTrails.trailTextureDropdown, function(self, level, menuList)
        if not level then return end

        if level == 1 then
            -- Populate main level dropdown
            for i, option in ipairs(textureOptions) do
                if i > MAX_PER_LEVEL then break end

                local info = UIDropDownMenu_CreateInfo()
                info.text = option.text
                if option.icon then
                    info.icon = option.icon
                    info.iconTexCoord = {0, 1, 0, 1}
                    info.iconWidth = 16
                    info.iconHeight = 16
                end
                info.func = function()
                    -- ✅ Save selected trail texture
                    EasyCursorTrailsDB.trailTexture = i
                    EasyCursorTrails.settingsChanged = true
                    EasyCursorTrails.SaveToCurrentProfile("trailTexture", i)

                    -- ✅ Sync in-memory profile
                    if EasyCursorTrails.currentProfileTable then
                        EasyCursorTrails.currentProfileTable.trailTexture = i
                    end

                    -- ✅ Rebuild trails with new texture
                    EasyCursorTrails.RebuildTrails()

                    -- ✅ Refresh UI settings
                    if EasyCursorTrails.RefreshSettingsUI then
                        EasyCursorTrails.RefreshSettingsUI()
                    end

                    -- ✅ Update dropdown UI
                    UIDropDownMenu_SetSelectedID(EasyCursorTrails.trailTextureDropdown, i)
                    UIDropDownMenu_SetText(EasyCursorTrails.trailTextureDropdown, option.text)

                    CloseDropDownMenus()
                end


                UIDropDownMenu_AddButton(info, level)
            end

            -- Add "More..." submenu if options exceed MAX_PER_LEVEL
            if #textureOptions > MAX_PER_LEVEL then
                local info = UIDropDownMenu_CreateInfo()
                info.text = "More..."
                info.hasArrow = true
                info.notCheckable = true
                info.menuList = "TrailTextureDropdown_EXTRA_OPTIONS"
                UIDropDownMenu_AddButton(info, level)
            end

        elseif level == 2 and menuList == "TrailTextureDropdown_EXTRA_OPTIONS" then
            -- Populate second-level menu
            for i = MAX_PER_LEVEL + 1, #textureOptions do
                local option = textureOptions[i]
                local info = UIDropDownMenu_CreateInfo()
                info.text = option.text
                if option.icon then
                    info.icon = option.icon
                    info.iconTexCoord = {0, 1, 0, 1}
                    info.iconWidth = 16
                    info.iconHeight = 16
                end
                info.func = function()
                    -- ✅ Save selected trail texture
                    EasyCursorTrailsDB.trailTexture = i
                    EasyCursorTrails.settingsChanged = true
                    EasyCursorTrails.SaveToCurrentProfile("trailTexture", i)

                    -- ✅ Refresh UI settings
                    if EasyCursorTrails.RefreshSettingsUI then
                        EasyCursorTrails.RefreshSettingsUI()
                    end

                    -- ✅ Update dropdown UI
                    UIDropDownMenu_SetSelectedID(EasyCursorTrails.trailTextureDropdown, i)
                    UIDropDownMenu_SetText(EasyCursorTrails.trailTextureDropdown, option.text)

                    CloseDropDownMenus()
                end
                UIDropDownMenu_AddButton(info, level)
            end
        end
    end)

    -- ✅ Ensure dropdown reflects saved selection
    UIDropDownMenu_SetSelectedID(EasyCursorTrails.trailTextureDropdown, storedIndex)
    UIDropDownMenu_SetText(EasyCursorTrails.trailTextureDropdown, textureOptions[storedIndex].text or "Unknown")
end


function EasyCursorTrails.RefreshTrailDropdowns()
    local profileName = EasyCursorTrailsDB.currentProfile or "Default"
    local profileSettings = EasyCursorTrailsDB.profiles[profileName] or {}
    local defaults = EasyCursorTrails.defaults or {}

    -------------------------------
    -- Refresh Trail Texture Dropdown
    -------------------------------
    local textureIndex = profileSettings.trailTexture or defaults.trailTexture or 1
    if EasyCursorTrails.trailTextureDropdown and EasyCursorTrails.trailTextures then
        if not EasyCursorTrails.trailTextures[textureIndex] then
            textureIndex = 1
        end
        UIDropDownMenu_SetSelectedID(EasyCursorTrails.trailTextureDropdown, textureIndex)
        local selectedTextureName = EasyCursorTrails.trailTextures[textureIndex].name or "Unknown"
        UIDropDownMenu_SetText(EasyCursorTrails.trailTextureDropdown, selectedTextureName)
    else
       -- print("Error: trailTextureDropdown or trailTextures is nil!")
    end

    -------------------------------
    -- Refresh Trail Movement Effects Dropdown
    -------------------------------
    local movementIndex = profileSettings.trailMovementEffect or defaults.trailMovementEffect or 1
    if EasyCursorTrails.trailMovementEffectDropdown and EasyCursorTrails.trailMovementEffectOptions then
        if not EasyCursorTrails.trailMovementEffectOptions[movementIndex] then
            movementIndex = 1
        end
        UIDropDownMenu_SetSelectedID(EasyCursorTrails.trailMovementEffectDropdown, movementIndex)
        local selectedMovementText = EasyCursorTrails.trailMovementEffectOptions[movementIndex].text or "Custom Movement Effect"
        UIDropDownMenu_SetText(EasyCursorTrails.trailMovementEffectDropdown, selectedMovementText)
    else
       -- print("Error: trailMovementEffectDropdown or trailMovementEffectOptions is nil!")
    end
end



-- Function to retrieve saved trail texture index with fallbacks
function EasyCursorTrails.GetSavedTrailTextureIndex()
    local profileName = EasyCursorTrailsDB.currentProfile or "Default"
    local profileSettings = EasyCursorTrailsDB.profiles[profileName] or {}
    local defaultSettings = EasyCursorTrails.defaults or {}

    local savedIndex = profileSettings.trailTexture or defaultSettings.trailTexture or 1

    -- Validate Index
    if not EasyCursorTrails.trailTextures or not EasyCursorTrails.trailTextures[savedIndex] then
        savedIndex = 1 -- Default if invalid
    end

    return savedIndex
end


-- 🧼 Ensure profile access
local currentProfileName = EasyCursorTrailsDB.currentProfile or "Default"
local currentProfile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[currentProfileName] or {}
EasyCursorTrails.currentProfileTable = currentProfile

-- 🛠 Create Trail Texture Dropdown
EasyCursorTrails.trailTextureDropdown = EasyCursorTrails.CreateValidatedDropdown(
    "TrailTextureDropdown", 
    menu,
    "Trail Textures",
    EasyCursorTrails.trailTextures,  -- Available textures
    EasyCursorTrails.GetSavedTrailTextureIndex(), -- Saved index
    function(textureIndex)
        currentProfile.trailTexture = textureIndex
        EasyCursorTrails.SaveToCurrentProfile("trailTexture", textureIndex)
        
       -- Instant visual update
    EasyCursorTrails.RebuildTrails()

    -- Debounced rebuild for safety (optional)
    DebouncedRebuild()
    end
)

EasyCursorTrails.trailTextureDropdown:SetPoint("TOPLEFT", EasyCursorTrails.trailFollowSpeedSlider, "BOTTOMLEFT", 120, -45)

-- Populate textures **before** updating the selection
EasyCursorTrails.PopulateTrailTextureDropdown()

function EasyCursorTrails.CreateCheckbox(name, parent, label, checked, onClick)
    local checkbox = CreateFrame("CheckButton", name, parent, "InterfaceOptionsCheckButtonTemplate")
    checkbox:SetChecked(checked)
    checkbox.Text:SetText(label)

    checkbox:SetScript("OnClick", function(self)
        local isChecked = self:GetChecked()
        PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON)
        onClick(isChecked)
    end)

    return checkbox
end

function EasyCursorTrails.CreateColorPicker(name, parent, label, initialColor, onColorChanged)
    -- 🛡️ Sanitize initial color input
    local function sanitizeColor(c)
        if type(c) ~= "table" or type(c.r) ~= "number" or type(c.g) ~= "number" or type(c.b) ~= "number" then
            return { r = 1, g = 1, b = 1, a = 1 }
        end
        c.a = type(c.a) == "number" and c.a or 1
        return c
    end
    initialColor = sanitizeColor(initialColor)

    local picker = CreateFrame("Button", name, parent, "UIPanelButtonTemplate")
    picker:SetSize(24, 24)
    picker:SetFrameStrata("MEDIUM")
    picker:EnableMouse(true)

    -- 🎨 Swatch texture
    local swatch = picker:CreateTexture(nil, "ARTWORK")
    swatch:SetAllPoints()
    swatch:SetColorTexture(initialColor.r, initialColor.g, initialColor.b, initialColor.a)
    picker.swatch = swatch

    -- 🎀 Border
    local border = picker:CreateTexture(nil, "OVERLAY")
    border:SetTexture("Interface\\Common\\WhiteIconFrame")
    border:SetAllPoints()
    border:SetVertexColor(1, 0.82, 0)
    picker.border = border

    -- 🏷️ Optional label
    if label and label ~= "" then
        local labelText = picker:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        labelText:SetPoint("LEFT", picker, "RIGHT", 8, 1)
        labelText:SetText(label)
        picker.label = labelText
    end

    -- 🖱️ Tooltip
    picker:SetScript("OnEnter", function(self)
        GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
        GameTooltip:SetText("Click to pick a color.", 1, 1, 1)
        GameTooltip:Show()
    end)
    picker:SetScript("OnLeave", GameTooltip_Hide)

    -- 🖌️ Click to open color picker
    picker:SetScript("OnClick", function()
        local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
        local color = sanitizeColor(profile and profile[name .. "Color"] or initialColor)

        local r, g, b, a = color.r, color.g, color.b, color.a

        ColorPickerFrame:Hide()
        ColorPickerFrame.r = r
        ColorPickerFrame.g = g
        ColorPickerFrame.b = b
        ColorPickerFrame.opacity = 1 - a
        ColorPickerFrame.hasOpacity = true
        ColorPickerFrame.previousValues = { r, g, b, a }

        local function apply()
            local nr, ng, nb = ColorPickerFrame:GetColorRGB()
            local na = 1 - (ColorPickerFrame.opacity or 0)
            if type(onColorChanged) == "function" then
                onColorChanged(nr, ng, nb, na)
            end
            swatch:SetColorTexture(nr, ng, nb, na)
        end

        local function cancel()
            local pv = ColorPickerFrame.previousValues
            if pv and type(onColorChanged) == "function" then
                onColorChanged(pv[1], pv[2], pv[3], pv[4])
                swatch:SetColorTexture(pv[1], pv[2], pv[3], pv[4])
            end
        end

        ColorPickerFrame.func = apply
        ColorPickerFrame.swatchFunc = apply
        ColorPickerFrame.opacityFunc = apply
        ColorPickerFrame.cancelFunc = cancel

        ColorPickerFrame:Show()
    end)

    -- 🧭 Store reference for external access (e.g., in ResetColorFeature)
    EasyCursorTrails[name .. "ColorPicker"] = picker

    return picker
end

function EasyCursorTrails.GetDefaultColor(name)
  if not name then return nil end

  local defaults = EasyCursorTrails.defaults or {}
  return defaults[name] or nil
end


--==============================================================================================================
-- 🧩 Section Header: Trail Effects
local trailEffectsHeader = menu:CreateFontString(nil, "OVERLAY", "GameFontNormal")
trailEffectsHeader:SetPoint("TOPLEFT", EasyCursorTrails.trailSizeStartSlider, "TOPRIGHT", 130, -50)
trailEffectsHeader:SetText("Trail Effects")

-- 🧩 Section Header: Trail Effects
local trailColorEffectsHeader = menu:CreateFontString(nil, "OVERLAY", "GameFontNormal")
trailColorEffectsHeader:SetPoint("TOPLEFT", EasyCursorTrails.trailSizeStartSlider, "TOPRIGHT", 260, -50)
trailColorEffectsHeader:SetText("Pick a Color")

--============================================================================================================
local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]

function EasyCursorTrails.UpdateTwinkleTrailColors()
  local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
  if not profile or not profile.enableTwinkleStars then return end

  for _, pool in pairs(EasyCursorTrails.trailPool or {}) do
    for _, trail in ipairs(pool) do
      if trail.twinkleSpark and trail.twinkleSpark.texture then
        local color = profile.randomTwinkleStarsColor and EasyCursorTrails.GetRandomVibrantColor()
                    or profile.twinkleStarsColor or { r = 1, g = 1, b = 1, a = 1 }

        trail.twinkleSpark.texture:SetVertexColor(color.r, color.g, color.b, color.a)
        trail.twinkleSpark:Show()
      end
    end
  end
end

-- 🟨 Twinkle Stars Checkbox
local twinkleStarsCheckbox = EasyCursorTrails.CreateCheckbox(
  "EnableTwinkleStars",
  menu,
  "Sparkles",
  EasyCursorTrails.currentProfileTable and EasyCursorTrails.currentProfileTable.enableTwinkleStars,
  function(checked)
    local profile = EasyCursorTrails.currentProfileTable
    if not profile then return end

    profile.enableTwinkleStars = checked
    EasyCursorTrails.SaveToCurrentProfile("enableTwinkleStars", checked)

    for _, pool in pairs(EasyCursorTrails.trailPool or {}) do
      for i, trail in ipairs(pool) do
        if not checked then
          if trail.twinkleSpark then
            if trail.twinkleSpark.ag then trail.twinkleSpark.ag:Stop() end
            trail.twinkleSpark:Hide()
          end
          trail.twinkleSpark = nil
        else
          EasyCursorTrails.ApplyColorEffectTrail(trail, i)
        end
      end
    end
  end
)

-- ✅ Resize checkbox to 28x28
twinkleStarsCheckbox:SetSize(28, 28)
-- ✅ Store reference
EasyCursorTrails.twinkleStarsCheckbox = twinkleStarsCheckbox

EasyCursorTrails.twinkleStarsCheckbox:SetPoint("TOPLEFT", trailEffectsHeader, "TOPRIGHT", -70, -15)


-- 🎨 Twinkle Stars Color Picker
EasyCursorTrails.twinkleStarsColorPicker = EasyCursorTrails.CreateColorPicker(
  "TwinkleStarsColor",
  menu,
  "",
  profile.twinkleStarsColor or EasyCursorTrails.defaults.twinkleStarsColor,
  function(r, g, b, a)
    profile.twinkleStarsColor = { r = r, g = g, b = b, a = a }
    EasyCursorTrails.SaveToCurrentProfile("twinkleStarsColor", profile.twinkleStarsColor)

    if profile.enableTwinkleStars then
      for _, pool in pairs(EasyCursorTrails.trailPool or {}) do
        for i, trail in ipairs(pool) do
          EasyCursorTrails.ClearStaticArcEffect(trail)
          EasyCursorTrails.ApplyColorEffectTrail(trail, i)
        end
      end
    end
  end
)


EasyCursorTrails.twinkleStarsColorPicker:SetPoint("TOPLEFT", EasyCursorTrails.twinkleStarsCheckbox, "BOTTOMLEFT", 130, 25)
EasyCursorTrails.twinkleStarsColorPicker:SetScript("OnEnter", function(self)
  GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
  GameTooltip:SetText("Click to pick star sparkle color", 1, 1, 1)
  GameTooltip:Show()
end)
EasyCursorTrails.twinkleStarsColorPicker:SetScript("OnLeave", GameTooltip_Hide)

-- 🎲 Random Sparkle Checkbox
local twinkleStarsRandomCheckbox = CreateFrame("CheckButton", "EasyCursorTrails_TwinkleStarsRandomColorToggle", menu, "ChatConfigCheckButtonTemplate")
twinkleStarsRandomCheckbox:SetSize(28, 28)
twinkleStarsRandomCheckbox:SetPoint("LEFT", EasyCursorTrails.twinkleStarsColorPicker, "RIGHT", 20, 0)
twinkleStarsRandomCheckbox:SetHitRectInsets(0, 0, 0, 0)
EasyCursorTrails.twinkleStarsRandomColorCheckbox = twinkleStarsRandomCheckbox

local twinkleRandLabel = menu:CreateFontString(nil, "ARTWORK", "GameFontNormal")
twinkleRandLabel:SetPoint("LEFT", twinkleStarsRandomCheckbox, "RIGHT", 4, 1)
twinkleRandLabel:SetText("Random")
twinkleRandLabel:SetTextColor(1, 0.82, 0)

twinkleStarsRandomCheckbox:SetChecked(profile.randomTwinkleStarsColor == true)
twinkleStarsRandomCheckbox:SetScript("OnClick", function(self)
  profile.randomTwinkleStarsColor = self:GetChecked()
  EasyCursorTrails.SaveToCurrentProfile("randomTwinkleStarsColor", profile.randomTwinkleStarsColor)

  if profile.enableTwinkleStars then
    for _, pool in pairs(EasyCursorTrails.trailPool or {}) do
      for _, trail in ipairs(pool) do
        if trail.twinkleSpark and trail.twinkleSpark.texture then
          local color = profile.randomTwinkleStarsColor and EasyCursorTrails.GetRandomVibrantColor()
                      or profile.twinkleStarsColor or { r = 1, g = 1, b = 1, a = 1 }
          trail.twinkleSpark.texture:SetVertexColor(color.r, color.g, color.b, color.a)
          trail.twinkleSpark:Show()
        end
      end
    end   
  end
end)
-- ✅ Resize checkbox to 28x28
twinkleStarsRandomCheckbox:SetSize(28, 28)

-- ✅ Store reference
EasyCursorTrails.twinkleStarsRandomCheckbox = twinkleStarsRandomCheckbox

-- ♻️ Twinkle Stars Reset Button
EasyCursorTrails.resetTwinkleStarsBtn = CreateFrame("Button", "EasyCursorTrails_ResetTwinkleStarsBtn", menu, "UIPanelButtonTemplate")
local resetBtn = EasyCursorTrails.resetTwinkleStarsBtn
resetBtn:SetSize(48, 24)
resetBtn:SetText("Reset")
resetBtn:SetPoint("LEFT", twinkleRandLabel, "RIGHT", 12, 0)
resetBtn:SetScript("OnClick", function()
  profile.enableTwinkleStars = false
  profile.randomTwinkleStarsColor = false
  profile.twinkleStarsColor = CopyTable(EasyCursorTrails.GetDefaultColor("twinkleStarsColor") or { r = 1, g = 1, b = 1, a = 1 })

  EasyCursorTrails.SaveToCurrentProfile("enableTwinkleStars", false)
  EasyCursorTrails.SaveToCurrentProfile("randomTwinkleStarsColor", false)
  EasyCursorTrails.SaveToCurrentProfile("twinkleStarsColor", profile.twinkleStarsColor)

  if EasyCursorTrails.twinkleStarsCheckbox then
    EasyCursorTrails.twinkleStarsCheckbox:SetChecked(false)
  end
  if EasyCursorTrails.twinkleStarsRandomColorCheckbox then
    EasyCursorTrails.twinkleStarsRandomColorCheckbox:SetChecked(false)
  end

  local picker = EasyCursorTrails.twinkleStarsColorPicker
  if picker then
    if picker.SetColorRGBA then
      picker:SetColorRGBA(profile.twinkleStarsColor.r, profile.twinkleStarsColor.g, profile.twinkleStarsColor.b, profile.twinkleStarsColor.a)
    elseif picker.swatch then
      picker.swatch:SetColorTexture(profile.twinkleStarsColor.r, profile.twinkleStarsColor.g, profile.twinkleStarsColor.b, profile.twinkleStarsColor.a)
    end
  end

  for _, pool in pairs(EasyCursorTrails.trailPool or {}) do
    for _, trail in ipairs(pool) do
      if trail.twinkleSpark then
        if trail.twinkleSpark.ag then trail.twinkleSpark.ag:Stop() end
        trail.twinkleSpark:Hide()
      end
      trail.twinkleSpark = nil
    end
  end

  EasyCursorTrails.RebuildTrails()
  --|cff99ccffEasyCursorTrails:|r Twinkle Stars reset to default and disabled.")
end)

resetBtn:SetScript("OnEnter", function(self)
  GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
  GameTooltip:SetText("Reset sparkle color and disable effect", 1, 1, 1)
  GameTooltip:Show()
end)
resetBtn:SetScript("OnLeave", GameTooltip_Hide)


--===================================================================================================================
-- Fetch current profile
local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]

-- 🔌 Static Arc Toggle Checkbox
local staticArcEffectCheckbox = EasyCursorTrails.CreateCheckbox(
  "EnableStaticArc",
  menu,
  "Static Sparkles",
  EasyCursorTrails.currentProfileTable and EasyCursorTrails.currentProfileTable.enableStaticArc,
  function(checked)
    local profile = EasyCursorTrails.currentProfileTable
    if not profile then return end

    profile.enableStaticArc = checked
    EasyCursorTrails.SaveToCurrentProfile("enableStaticArc", checked)

    -- Modular effect refresh (no rebuild)
    for _, pool in pairs(EasyCursorTrails.trailPool or {}) do
      for i, trail in ipairs(pool) do
        if checked then
          EasyCursorTrails.ApplyStaticArcEffect(trail, i, profile.staticArcColor)
        else
          EasyCursorTrails.ClearStaticArcEffect(trail)
        end
      end
    end
  end
)

-- ✅ Resize checkbox to 28x28
staticArcEffectCheckbox:SetSize(28, 28)

-- ✅ Store reference
EasyCursorTrails.staticArcEffectCheckbox = staticArcEffectCheckbox

-- ✅ Position relative to previous checkbox
EasyCursorTrails.staticArcEffectCheckbox:SetPoint("TOPLEFT", EasyCursorTrails.twinkleStarsCheckbox, "BOTTOMLEFT", 0, -20)

-- 🎨 Static Arc Color Picker
EasyCursorTrails.staticArcColorPicker = EasyCursorTrails.CreateColorPicker(
  "StaticArcColor", menu, "", profile.staticArcColor or EasyCursorTrails.defaults.staticArcColor,
  function(r, g, b, a)
    if not profile then return end
    profile.staticArcColor = { r = r, g = g, b = b, a = a }
    EasyCursorTrails.SaveToCurrentProfile("staticArcColor", profile.staticArcColor)

    if profile.enableStaticArc then
      for _, pool in pairs(EasyCursorTrails.trailPool or {}) do
        for i, trail in ipairs(pool) do
          EasyCursorTrails.ClearStaticArcEffect(trail)
          EasyCursorTrails.ApplyStaticArcEffect(trail, i, profile.staticArcColor)
        end
      end
    end
  end
)
EasyCursorTrails.staticArcColorPicker:SetPoint("LEFT", EasyCursorTrails.staticArcEffectCheckbox, "RIGHT", 104, 0)
EasyCursorTrails.staticArcColorPicker:SetScript("OnEnter", function(self)
  GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
  GameTooltip:SetText("Click to pick a color.", 1, 1, 1)
  GameTooltip:Show()
end)
EasyCursorTrails.staticArcColorPicker:SetScript("OnLeave", GameTooltip_Hide)

-- 🎲 Random Static Arc Checkbox
local staticRandCheck = CreateFrame("CheckButton", "EasyCursorTrails_StaticArcRandomColorToggle", menu, "ChatConfigCheckButtonTemplate")
staticRandCheck:SetSize(28, 28)
staticRandCheck:SetPoint("LEFT", EasyCursorTrails.staticArcColorPicker, "RIGHT", 20, 0)
staticRandCheck:SetHitRectInsets(0, 0, 0, 0) -- Precise clickable zone
EasyCursorTrails.staticArcRandomColorCheckbox = staticRandCheck

-- 🏷️ Label
local staticRandLabel = menu:CreateFontString(nil, "ARTWORK", "GameFontNormal")
staticRandLabel:SetText("Random")
staticRandLabel:SetTextColor(1, 0.82, 0)
staticRandLabel:SetPoint("LEFT", staticRandCheck, "RIGHT", 4, 1) -- slight Y offset for vertical centering

staticRandCheck:SetChecked(profile.randomStaticArcColor == true)
staticRandCheck:SetScript("OnClick", function(self)
  if not profile then return end
  profile.randomStaticArcColor = self:GetChecked()
  EasyCursorTrails.SaveToCurrentProfile("randomStaticArcColor", profile.randomStaticArcColor)

  if profile.enableStaticArc then
    EasyCursorTrails.RebuildTrails()
  end
end)

-- 🔄 Reset Button (precise spacing, vertical alignment)
EasyCursorTrails.resetStaticArcRandomBtn = CreateFrame("Button", "EasyCursorTrails_ResetStaticArcRandomBtn", menu, "UIPanelButtonTemplate")
local resetBtn = EasyCursorTrails.resetStaticArcRandomBtn
resetBtn:SetSize(48, 24)
resetBtn:SetText("Reset")
resetBtn:SetPoint("LEFT", EasyCursorTrails.resetTwinkleStarsBtn, "RIGHT", -48, -45) -- horizontal + vertical offset to avoid hitbox overlap

resetBtn:SetScript("OnClick", function()
  if not profile then return end

  -- 🚫 Disable both static arc effects
  profile.enableStaticArc = false
  profile.randomStaticArcColor = false
  EasyCursorTrails.SaveToCurrentProfile("enableStaticArc", false)
  EasyCursorTrails.SaveToCurrentProfile("randomStaticArcColor", false)

  -- 🔘 Uncheck both boxes visually
  if EasyCursorTrails.staticArcEffectCheckbox then
    EasyCursorTrails.staticArcEffectCheckbox:SetChecked(false)
  end
  if EasyCursorTrails.staticArcRandomColorCheckbox then
    EasyCursorTrails.staticArcRandomColorCheckbox:SetChecked(false)
  end

  -- 🎨 Reset color to default
  local defaultColor = EasyCursorTrails.GetDefaultColor("staticArcColor") or { r = 1, g = 1, b = 1, a = 0.8 }
  profile.staticArcColor = CopyTable(defaultColor)
  EasyCursorTrails.SaveToCurrentProfile("staticArcColor", profile.staticArcColor)

  -- 🎛️ Refresh color picker display
  local picker = EasyCursorTrails.staticArcColorPicker
  if picker then
    if picker.SetColorRGBA then
      picker:SetColorRGBA(defaultColor.r, defaultColor.g, defaultColor.b, defaultColor.a)
    elseif picker.swatch then
      picker.swatch:SetColorTexture(defaultColor.r, defaultColor.g, defaultColor.b, defaultColor.a)
    end
  end

  -- 💨 Remove active effects
  for _, pool in pairs(EasyCursorTrails.trailPool or {}) do
    for _, trail in ipairs(pool) do
      EasyCursorTrails.ClearStaticArcEffect(trail)
    end
  end

  -- 🔃 Final visual sync
  EasyCursorTrails.RebuildTrails()
  --|cff99ccffEasyCursorTrails:|r Static Arc reset to default and disabled.")
end)

-- 🧠 Tooltip for clarity
resetBtn:SetScript("OnEnter", function(self)
  GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
  GameTooltip:SetText("Reset Static Arc color, disable the effect, and turn off randomization", 1, 1, 1)
  GameTooltip:Show()
end)
resetBtn:SetScript("OnLeave", GameTooltip_Hide)


--===================================================================================================================
function EasyCursorTrails.ResetLightningEffect()
  local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
  if not profile then
    --⚠️ No profile found during lightning reset")
    return
  end

  -- 🛑 Stop ticker
  if EasyCursorTrails.lightningSparkTicker then
    EasyCursorTrails.lightningSparkTicker:Cancel()
    EasyCursorTrails.lightningSparkTicker = nil
  end

  -- ❌ Disable spark and random toggle
  profile.enableLightningSpark = false
  profile.randomLightningSparkColor = false
  EasyCursorTrails.SaveToCurrentProfile("enableLightningSpark", false)
  EasyCursorTrails.SaveToCurrentProfile("randomLightningSparkColor", false)

  -- 🌈 Reset to default color
  local defaultColor = EasyCursorTrails.GetDefaultColor("lightningSparkColor") or { r = 0.8, g = 0.9, b = 1, a = 1 }
  profile.lightningSparkColor = CopyTable(defaultColor)
  EasyCursorTrails.SaveToCurrentProfile("lightningSparkColor", profile.lightningSparkColor)

  -- 🔘 Uncheck checkboxes
  if EasyCursorTrails.lightningSparkCheckbox then
    EasyCursorTrails.lightningSparkCheckbox:SetChecked(false)
  end
  if EasyCursorTrails.lightningSparkRandomColorCheckbox then
    EasyCursorTrails.lightningSparkRandomColorCheckbox:SetChecked(false)
  end

  -- 🎨 Update color picker display
  local picker = EasyCursorTrails.lightningSparkColorPicker
  if picker then
    if picker.SetColorRGBA then
      picker:SetColorRGBA(defaultColor.r, defaultColor.g, defaultColor.b, defaultColor.a)
    elseif picker.swatch then
      picker.swatch:SetColorTexture(defaultColor.r, defaultColor.g, defaultColor.b, defaultColor.a)
    end
  end

  -- 🧼 Clear spark visuals
  for _, pool in pairs(EasyCursorTrails.trailPool or {}) do
    for _, trail in ipairs(pool) do
      EasyCursorTrails.ClearLightningSparkEffect(trail)
    end
  end

  -- 🔁 Rebuild cursor visuals
  if EasyCursorTrails.RebuildTrails then
    EasyCursorTrails.RebuildTrails()
  end

  --|cff99ccffEasyCursorTrails:|r Lightning Spark reset complete.")
end


-- ⚡ Lightning Spark Checkbox
local lightningSparkCheckbox = EasyCursorTrails.CreateCheckbox(
  "EnableLightningSpark",
  menu,
  "Lightnings",
  EasyCursorTrails.currentProfileTable and EasyCursorTrails.currentProfileTable.enableLightningSpark,
  function(checked)
    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    if not profile then return end

    profile.enableLightningSpark = checked
    EasyCursorTrails.SaveToCurrentProfile("enableLightningSpark", checked)

    -- 🔁 Cancel existing ticker
    if EasyCursorTrails.lightningSparkTicker then
      EasyCursorTrails.lightningSparkTicker:Cancel()
      EasyCursorTrails.lightningSparkTicker = nil
    end

    if checked then
      -- ⚡ Start ticker for lightning sparks
      EasyCursorTrails.lightningSparkTicker = C_Timer.NewTicker(0.25, function()
        local liveProfile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
        if not liveProfile or not liveProfile.enableLightningSpark then return end

        for _, layerPool in pairs(EasyCursorTrails.trailPool or {}) do
          for _, trail in ipairs(layerPool) do
            if trail:IsVisible() then
              EasyCursorTrails.ApplyLightningSparkEffect(trail)
            end
          end
        end
      end)
    else
      -- 🧼 Clear visuals immediately
      for _, pool in pairs(EasyCursorTrails.trailPool or {}) do
        for _, trail in ipairs(pool) do
          EasyCursorTrails.ClearLightningSparkEffect(trail)
        end
      end
    end
  end
)

-- ✅ Resize checkbox to 28x28
lightningSparkCheckbox:SetSize(28, 28)

-- ✅ Store reference
EasyCursorTrails.lightningSparkCheckbox = lightningSparkCheckbox

-- ✅ Position relative to Static Arc checkbox
EasyCursorTrails.lightningSparkCheckbox:SetPoint("TOPLEFT", EasyCursorTrails.staticArcEffectCheckbox, "BOTTOMLEFT", 0, -20)


-- 🎨 Lightning Spark Color Picker
EasyCursorTrails.lightningSparkColorPicker = EasyCursorTrails.CreateColorPicker(
  "LightningSparkColor",
  menu,
  "",
  EasyCursorTrails.currentProfileTable and EasyCursorTrails.currentProfileTable.lightningSparkColor
    or { r = 0.8, g = 0.9, b = 1, a = 1 },
  function(r, g, b, a)
    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    if not profile then return end
    profile.lightningSparkColor = { r = r, g = g, b = b, a = a }
    EasyCursorTrails.SaveToCurrentProfile("lightningSparkColor", profile.lightningSparkColor)
  end
)
EasyCursorTrails.lightningSparkColorPicker:SetPoint("LEFT", EasyCursorTrails.lightningSparkCheckbox, "RIGHT", 104, 0)
EasyCursorTrails.lightningSparkColorPicker:SetScript("OnEnter", function(self)
  GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
  GameTooltip:SetText("Click to pick lightning color.", 1, 1, 1)
  GameTooltip:Show()
end)
EasyCursorTrails.lightningSparkColorPicker:SetScript("OnLeave", function()
  GameTooltip:Hide()
end)
-- ⚡ Random Lightning Spark Color Checkbox
local lightningSparkRandomCheckbox = CreateFrame(
  "CheckButton",
  "EasyCursorTrails_LightningSparkRandomColorToggle",
  menu,
  "ChatConfigCheckButtonTemplate"
)
lightningSparkRandomCheckbox:SetPoint("LEFT", EasyCursorTrails.lightningSparkColorPicker, "RIGHT", 20, 0)
lightningSparkRandomCheckbox:SetSize(28, 28)
lightningSparkRandomCheckbox:SetHitRectInsets(6, 6, 6, 6) -- Shrinks hitbox to avoid overlap
EasyCursorTrails.lightningSparkRandomColorCheckbox = lightningSparkRandomCheckbox

local lightningRandLabel = menu:CreateFontString(nil, "ARTWORK", "GameFontNormal")
lightningRandLabel:SetPoint("LEFT", lightningSparkRandomCheckbox, "RIGHT", 4, 0)
lightningRandLabel:SetText("Random")
lightningRandLabel:SetTextColor(1, 0.82, 0)

local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
lightningSparkRandomCheckbox:SetChecked(profile and profile.randomLightningSparkColor == true)

lightningSparkRandomCheckbox:SetScript("OnClick", function(self)
  local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
  if not profile then return end
  profile.randomLightningSparkColor = self:GetChecked()
  EasyCursorTrails.SaveToCurrentProfile("randomLightningSparkColor", profile.randomLightningSparkColor)
  --✅ Saved randomLightningSparkColor:", self:GetChecked())

end)


-- ♻️ Reset Button
local resetLightningSparkBtn = CreateFrame("Button", "EasyCursorTrails_LightningSparkResetButton", menu, "UIPanelButtonTemplate")
resetLightningSparkBtn:SetPoint("LEFT", EasyCursorTrails.resetStaticArcRandomBtn, "RIGHT", -48, -48) -- Increased spacing
resetLightningSparkBtn:SetSize(48, 24)
resetLightningSparkBtn:SetText("Reset")
resetLightningSparkBtn:SetScript("OnClick", function()
  EasyCursorTrails.ResetLightningEffect()
end)




--===================================================================================================================
-- 🔥 Fire Effect Checkbox
local fireEffectCheckbox = EasyCursorTrails.CreateCheckbox(
  "EnableFire",
  menu,
  "Burning Fire",
  EasyCursorTrails.currentProfileTable and EasyCursorTrails.currentProfileTable.enableFireEffect,
  function(checked)
    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    if not profile then return end

    profile.enableFireEffect = checked
    EasyCursorTrails.SaveToCurrentProfile("enableFireEffect", checked)

    -- 🛑 Stop old ticker
    if EasyCursorTrails.fireEffectTicker then
      EasyCursorTrails.fireEffectTicker:Cancel()
      EasyCursorTrails.fireEffectTicker = nil
    end

    if checked then
      -- 🔥 Start fire glow ticker
      EasyCursorTrails.fireEffectTicker = C_Timer.NewTicker(0.2, function()
        local current = EasyCursorTrails.currentProfileTable
        if current and current.enableFireEffect then
          for _, layerPool in pairs(EasyCursorTrails.trailPool or {}) do
            for _, trail in ipairs(layerPool) do
              if trail:IsVisible() then
                local color = current.randomFireColor and EasyCursorTrails.GetRandomVibrantColor()
                            or current.fireColor or { r = 1, g = 0.5, b = 0.1, a = 0.8 }
                EasyCursorTrails.SpawnFireGlow(trail, color)
              end
            end
          end
        end
      end)
    else
      -- 🧼 Clear fire visuals
      for _, pool in pairs(EasyCursorTrails.trailPool or {}) do
        for _, trail in ipairs(pool) do
          EasyCursorTrails.ClearFireGlow(trail)
        end
      end
    end
  end
)

-- ✅ Resize checkbox to 28x28
fireEffectCheckbox:SetSize(28, 28)

-- ✅ Store reference
EasyCursorTrails.fireEffectCheckbox = fireEffectCheckbox

-- ✅ Position relative to Lightning Spark checkbox
EasyCursorTrails.fireEffectCheckbox:SetPoint("TOPLEFT", EasyCursorTrails.lightningSparkCheckbox, "BOTTOMLEFT", 0, -20)

-- 🎨 Fire Glow Color Picker
EasyCursorTrails.fireColorPicker = EasyCursorTrails.CreateColorPicker(
  "FireGlowColor",
  menu,
  "",
  EasyCursorTrails.currentProfileTable and EasyCursorTrails.currentProfileTable.fireColor
    or EasyCursorTrails.GetDefaultColor("fireColor"),
  function(r, g, b, a)
    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    if not profile then return end

    profile.fireColor = { r = r, g = g, b = b, a = a }
    EasyCursorTrails.SaveToCurrentProfile("fireColor", profile.fireColor)
  end
)
EasyCursorTrails.fireColorPicker:SetPoint("LEFT", EasyCursorTrails.fireEffectCheckbox, "RIGHT", 104, 0)

-- 🎲 Random Fire Color Toggle
local fireRandomColorCheckbox = CreateFrame("CheckButton", "EasyCursorTrails_FireRandomColorToggle", menu, "ChatConfigCheckButtonTemplate")
fireRandomColorCheckbox:SetPoint("LEFT", EasyCursorTrails.fireColorPicker, "RIGHT", 20, 0)
fireRandomColorCheckbox:SetSize(28, 28)
fireRandomColorCheckbox:SetHitRectInsets(0, 0, 0, 0)
EasyCursorTrails.fireRandomColorCheckbox = fireRandomColorCheckbox

local fireRandLabel = menu:CreateFontString(nil, "ARTWORK", "GameFontNormal")
fireRandLabel:SetPoint("LEFT", fireRandomColorCheckbox, "RIGHT", 4, 0)
fireRandLabel:SetText("Random")
fireRandLabel:SetTextColor(1, 0.82, 0)

local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
fireRandomColorCheckbox:SetChecked(profile and profile.randomFireColor == true)

fireRandomColorCheckbox:SetScript("OnClick", function(self)
  local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
  if not profile then return end

  profile.randomFireColor = self:GetChecked()
  EasyCursorTrails.SaveToCurrentProfile("randomFireColor", profile.randomFireColor)

  if profile.enableFireEffect then
    for _, layerPool in pairs(EasyCursorTrails.trailPool or {}) do
      for _, trail in ipairs(layerPool) do
        EasyCursorTrails.ClearFireGlow(trail)
        local color = profile.randomFireColor and EasyCursorTrails.GetRandomVibrantColor()
                    or profile.fireColor or { r = 1, g = 0.5, b = 0.1, a = 0.8 }
        EasyCursorTrails.SpawnFireGlow(trail, color)
      end
    end
  end
end)

-- ♻️ Fire Trail Reset Button
local resetFireBtn = CreateFrame("Button", "EasyCursorTrails_FireColorResetButton", menu, "UIPanelButtonTemplate")
resetFireBtn:SetPoint("LEFT", resetLightningSparkBtn, "RIGHT", -48, -48)
resetFireBtn:SetSize(48, 24)
resetFireBtn:SetText("Reset")

resetFireBtn:SetScript("OnClick", function()
  local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
  if not profile then
    --⚠️ No active profile found during Fire reset")
    return
  end

  -- 🛑 Stop fire ticker if active
  if EasyCursorTrails.fireEffectTicker then
    EasyCursorTrails.fireEffectTicker:Cancel()
    EasyCursorTrails.fireEffectTicker = nil
  end

  -- 🔥 Disable fire effect in profile
  profile.enableFireEffect = false
  EasyCursorTrails.SaveToCurrentProfile("enableFireEffect", false)

  local effectCheckbox = EasyCursorTrails.fireEffectCheckbox
  if effectCheckbox then
    local originalScript = effectCheckbox:GetScript("OnClick")
    effectCheckbox:SetScript("OnClick", nil)
    effectCheckbox:SetChecked(false)
    effectCheckbox:SetScript("OnClick", originalScript)
    --✅ Fire effect checkbox successfully unchecked")
  else
    --⚠️ fireEffectCheckbox is nil or missing SetChecked")
  end

  -- 🔥 Disable random fire toggle
  profile.randomFireColor = false
  EasyCursorTrails.SaveToCurrentProfile("randomFireColor", false)

  local randomCheckbox = EasyCursorTrails.fireRandomColorCheckbox
  if randomCheckbox then
    local originalScript = randomCheckbox:GetScript("OnClick")
    randomCheckbox:SetScript("OnClick", nil)
    randomCheckbox:SetChecked(false)
    randomCheckbox:SetScript("OnClick", originalScript)
    --✅ Fire random color checkbox successfully reset")
  else
    --⚠️ fireRandomColorCheckbox not found")
  end

  -- 🎨 Reset fire color
  local defaultColor = EasyCursorTrails.GetDefaultColor("fireColor") or { r = 1, g = 0.5, b = 0.1, a = 0.8 }
  profile.fireColor = CopyTable(defaultColor)
  EasyCursorTrails.SaveToCurrentProfile("fireColor", profile.fireColor)

  local picker = EasyCursorTrails.fireColorPicker
  if picker then
    if picker.SetColorRGBA then
      picker:SetColorRGBA(defaultColor.r, defaultColor.g, defaultColor.b, defaultColor.a)
    elseif picker.swatch then
      picker.swatch:SetColorTexture(defaultColor.r, defaultColor.g, defaultColor.b, defaultColor.a)
    else
      --⚠️ fireColorPicker present but missing SetColorRGBA and swatch")
    end
  else
    --⚠️ fireColorPicker is nil during reset")
  end

  -- 🔄 Clear visuals
  for _, layerPool in pairs(EasyCursorTrails.trailPool or {}) do
    for _, trail in ipairs(layerPool) do
      EasyCursorTrails.ClearFireGlow(trail)
    end
  end

  -- 🧼 Optionally rebuild trail visuals
  if EasyCursorTrails.RebuildTrails then
    EasyCursorTrails.RebuildTrails()
    --🔄 Trails rebuilt after fire reset")
  else
    --⚠️ RebuildTrails not available")
  end
end)


--===================================================================================================================
-- 🟣 Trail Shadow Toggle Checkbox (create and store)
local shadowEffectCheckbox = EasyCursorTrails.CreateCheckbox(
  "EnableTrailShadows",
  menu,
  "Trail Shadow",
  (EasyCursorTrails.currentProfileTable and EasyCursorTrails.currentProfileTable.enableTrailShadows) == true,
  function(isChecked)
    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    if not profile then return end

    profile.enableTrailShadows = isChecked
    EasyCursorTrails.SaveToCurrentProfile("enableTrailShadows", isChecked)

    if isChecked then
      -- 🛑 Cancel existing ticker if any
      if EasyCursorTrails.shadowEffectTicker then
        EasyCursorTrails.shadowEffectTicker:Cancel()
      end

      -- 🟣 Start shadow effect ticker
      EasyCursorTrails.shadowEffectTicker = C_Timer.NewTicker(0.1, function()
        if not profile.enableTrailShadows then return end
        for _, pool in pairs(EasyCursorTrails.trailPool or {}) do
          for _, trail in ipairs(pool) do
            local shadow = trail.shadowFrame
            if trail:IsVisible() and trail.texture and trail.texture:GetAlpha() > 0.01 then
              EasyCursorTrails.SpawnTrailShadow(trail)
              if shadow and shadow.glowTex then
                shadow:Show()
                shadow.glowTex:SetAlpha(0.25)
              end
            elseif shadow and shadow.glowTex then
              shadow:Hide()
              shadow.glowTex:SetAlpha(0)
            end
          end
        end
      end)
    else
      -- 🧼 Stop shadow ticker
      if EasyCursorTrails.shadowEffectTicker then
        EasyCursorTrails.shadowEffectTicker:Cancel()
        EasyCursorTrails.shadowEffectTicker = nil
      end
    end
  end
)

-- ✅ Resize checkbox to 28x28
shadowEffectCheckbox:SetSize(28, 28)

-- ✅ Store reference
EasyCursorTrails.shadowEffectCheckbox = shadowEffectCheckbox

-- 📌 Position the checkbox once
EasyCursorTrails.shadowEffectCheckbox:SetPoint("TOPLEFT", EasyCursorTrails.fireEffectCheckbox, "BOTTOMLEFT", 0, -20)


-- Ensure settings apply after game reload
C_Timer.After(0.1, function()
    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    if profile and EasyCursorTrails.shadowEffectCheckbox then
        local checkbox = EasyCursorTrails.shadowEffectCheckbox
        checkbox:SetChecked(profile.enableTrailShadows == true)

        local onClick = checkbox:GetScript("OnClick")
        if onClick then onClick(checkbox) end
    end
end)

-- Safely access current profile
local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]

-- 🎨 Shadow color picker
EasyCursorTrails.shadowColorPicker = EasyCursorTrails.CreateColorPicker(
    "ShadowTrailColor",
    menu,
    "",
    (profile and profile.shadowTrailColor) or { r = 0, g = 0, b = 0, a = 0.4 },
    function(r, g, b, a)
        local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
        if not profile then return end

        profile.shadowTrailColor = { r = r, g = g, b = b, a = a }
        EasyCursorTrails.SaveToCurrentProfile("shadowTrailColor", profile.shadowTrailColor)

        -- 🌀 Force refresh shadows with updated color
        for _, pool in pairs(EasyCursorTrails.trailPool or {}) do
            for _, trail in ipairs(pool) do
                EasyCursorTrails.SpawnTrailShadow(trail)
            end
        end
    end
)

EasyCursorTrails.shadowColorPicker:SetPoint("LEFT", EasyCursorTrails.shadowEffectCheckbox, "RIGHT", 104, 0)
EasyCursorTrails.shadowColorPicker:SetScript("OnEnter", function(self)
    GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
    GameTooltip:SetText("Pick a color for trail shadows.", 1, 1, 1)
    GameTooltip:Show()
end)
EasyCursorTrails.shadowColorPicker:SetScript("OnLeave", function()
    GameTooltip:Hide()
end)

-- 🔀 Random color toggle
local shadowRandCheckbox = CreateFrame("CheckButton", "EasyCursorTrails_ShadowRandomColorToggle", menu, "ChatConfigCheckButtonTemplate")
shadowRandCheckbox:SetPoint("LEFT", EasyCursorTrails.shadowColorPicker, "RIGHT", 20, 0)
shadowRandCheckbox:SetSize(28, 28) -- 📏 Smaller hit box

-- 🏷️ Label
local shadowRandLabel = menu:CreateFontString(nil, "ARTWORK", "GameFontNormal")
shadowRandLabel:SetPoint("LEFT", shadowRandCheckbox, "RIGHT", 4, 0)
shadowRandLabel:SetText("Random")
shadowRandLabel:SetTextColor(1, 0.82, 0)

-- 🧾 Checkbox visual cleanup
shadowRandCheckbox:SetHitRectInsets(0, 0, 0, 0) -- Ensure the hit box matches the visual box
shadowRandCheckbox:SetChecked(profile and profile.randomShadowColor == true)
EasyCursorTrails.shadowRandomColorCheckbox = shadowRandCheckbox

-- 🧠 Behavior
shadowRandCheckbox:SetScript("OnClick", function(self)
    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    if not profile then return end

    profile.randomShadowColor = self:GetChecked()
    EasyCursorTrails.SaveToCurrentProfile("randomShadowColor", profile.randomShadowColor)

    -- 🌀 Force respawn with random coloring
    for _, pool in pairs(EasyCursorTrails.trailPool or {}) do
        for _, trail in ipairs(pool) do
            EasyCursorTrails.SpawnTrailShadow(trail)
        end
    end
end)



-- 🔄 Shadow Trail Reset Button
local resetShadowColorButton = CreateFrame("Button", "EasyCursorTrails_ShadowColorResetButton", menu, "UIPanelButtonTemplate")
resetShadowColorButton:SetSize(48, 24)
resetShadowColorButton:SetPoint("LEFT", resetFireBtn, "RIGHT", -48, -48)
resetShadowColorButton:SetText("Reset")
resetShadowColorButton:SetScript("OnClick", function()
  local activeProfile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
  if not activeProfile then
    --⚠️ No active profile found during Shadow reset")
    return
  end

  -- 🛑 Stop ticker BEFORE changing state
  if EasyCursorTrails.shadowEffectTicker then
    EasyCursorTrails.shadowEffectTicker:Cancel()
    EasyCursorTrails.shadowEffectTicker = nil
  end

  -- ✅ Disable effect using consistent key
  activeProfile.enableTrailShadows = false
  EasyCursorTrails.SaveToCurrentProfile("enableTrailShadows", false)

  -- ⛔ Suppress checkbox callback and visually uncheck
  local checkbox = EasyCursorTrails.shadowEffectCheckbox
  if checkbox then
    local originalScript = checkbox:GetScript("OnClick")
    checkbox:SetScript("OnClick", nil)
    checkbox:SetChecked(false)
    checkbox:SetScript("OnClick", originalScript)
  else
    --⚠️ shadowEffectCheckbox is nil during reset")
  end

  -- 🌈 Reset color
  local defaultColor = EasyCursorTrails.GetDefaultColor("shadowTrailColor") or { r = 0, g = 0, b = 0, a = 0.4 }
  activeProfile.shadowTrailColor = CopyTable(defaultColor)
  EasyCursorTrails.SaveToCurrentProfile("shadowTrailColor", activeProfile.shadowTrailColor)


  if EasyCursorTrails.shadowColorPicker then
    local picker = EasyCursorTrails.shadowColorPicker
        if picker and picker.SetColorRGBA then
        picker:SetColorRGBA(defaultColor.r, defaultColor.g, defaultColor.b, defaultColor.a)
        elseif picker and picker.swatch then
        picker.swatch:SetColorTexture(defaultColor.r, defaultColor.g, defaultColor.b, defaultColor.a)
        else
        --⚠️ shadowColorPicker is present but missing SetColorRGBA and swatch")
        end

    end


  -- 🎲 Disable random toggle
  activeProfile.randomShadowColor = false
  EasyCursorTrails.SaveToCurrentProfile("randomShadowColor", false)

  if EasyCursorTrails.shadowRandomColorCheckbox then
    EasyCursorTrails.shadowRandomColorCheckbox:SetChecked(false)
  end

  -- ✨ Refresh visuals
  if EasyCursorTrails.trailPool and EasyCursorTrails.SpawnTrailShadow then
    for _, pool in pairs(EasyCursorTrails.trailPool) do
      for _, trail in ipairs(pool) do
        EasyCursorTrails.SpawnTrailShadow(trail)
      end
    end
  end
end)

--===================================================================================================================
-- 🏷️ Section Header: Particle Effects
local EmberEffectsHeader = menu:CreateFontString(nil, "OVERLAY", "GameFontNormal")
EmberEffectsHeader:SetPoint("TOPLEFT", EasyCursorTrails.shadowEffectCheckbox, "TOPRIGHT", -25, -50)
EmberEffectsHeader:SetText("Particle Effects")



-- 🌟 Sparkles Checkbox
local starEmbersCheckbox = EasyCursorTrails.CreateCheckbox(
  "EnableStarEmbers",
  menu,
  "Star Dust",
  EasyCursorTrails.currentProfileTable and EasyCursorTrails.currentProfileTable.enableStarEmbers,
  function(isChecked)
    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    if not profile then return end

    profile.enableStarEmbers = isChecked
    EasyCursorTrails.SaveToCurrentProfile("enableStarEmbers", isChecked)

    if isChecked then
      EasyCursorTrails.StartStarTicker()
      for _, pool in pairs(EasyCursorTrails.trailPool or {}) do
        for _, trail in ipairs(pool) do
          EasyCursorTrails.SpawnSparkles(trail)
        end
      end
    else
      EasyCursorTrails.StopStarTicker()
    end
  end
)

-- ✅ Resize checkbox to 28x28
starEmbersCheckbox:SetSize(28, 28)

-- ✅ Store reference
EasyCursorTrails.starEmbersCheckbox = starEmbersCheckbox

-- 📌 Position under Particle Effects header
EasyCursorTrails.starEmbersCheckbox:SetPoint("TOPLEFT", EmberEffectsHeader, "BOTTOMLEFT", 0, -10)

-- 🌈 Sparkle Color Picker
EasyCursorTrails.starColorPicker = EasyCursorTrails.CreateColorPicker(
  "StarColor",
  menu,
  "",
  EasyCursorTrails.currentProfileTable and EasyCursorTrails.currentProfileTable.starColor
    or EasyCursorTrails.GetDefaultColor("starColor"),
  function(r, g, b, a)
    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    if not profile then return end

    profile.starColor = { r = r, g = g, b = b, a = a }
    EasyCursorTrails.SaveToCurrentProfile("starColor", profile.starColor)
  end
)
EasyCursorTrails.starColorPicker:SetPoint("LEFT", EasyCursorTrails.starEmbersCheckbox.Text, "RIGHT", 58, 0)

-- 🎲 Sparkle Randomizer Checkbox
local starRandomCheckbox = CreateFrame(
  "CheckButton",
  "EasyCursorTrails_StarRandomColorToggle",
  menu,
  "ChatConfigCheckButtonTemplate"
)
starRandomCheckbox:SetPoint("LEFT", EasyCursorTrails.starColorPicker, "RIGHT", 20, 0)
starRandomCheckbox:SetSize(28, 28)
starRandomCheckbox:SetHitRectInsets(0, 0, 0, 0)


local starRandLabel = menu:CreateFontString(nil, "ARTWORK", "GameFontNormal")
starRandLabel:SetPoint("LEFT", starRandomCheckbox, "RIGHT", 4, 0)
starRandLabel:SetText("Random")
starRandLabel:SetTextColor(1, 0.82, 0)

local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
starRandomCheckbox:SetChecked(profile and profile.randomStarColor ~= false)
EasyCursorTrails.starRandomColorCheckbox = starRandomCheckbox

starRandomCheckbox:SetScript("OnClick", function(self)
  local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
  if not profile then return end

  profile.randomStarColor = self:GetChecked()
  EasyCursorTrails.SaveToCurrentProfile("randomStarColor", profile.randomStarColor)
end)
-- ♻️ Star Reset Button
local resetStarColorBtn = CreateFrame("Button", nil, menu, "UIPanelButtonTemplate")
resetStarColorBtn:SetPoint("LEFT", resetShadowColorButton, "RIGHT", -48, -68)
resetStarColorBtn:SetSize(48, 24)
resetStarColorBtn:SetText("Reset")

resetStarColorBtn:SetScript("OnClick", function()
  local activeProfile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
  if not activeProfile then
    --⚠️ No active profile found during Star reset")
    return
  end

  -- 🎲 Reset random toggle
  activeProfile.randomStarColor = false
  EasyCursorTrails.SaveToCurrentProfile("randomStarColor", false)

  if starRandomCheckbox and starRandomCheckbox.SetChecked then
    starRandomCheckbox:SetChecked(false)
  else
    --⚠️ starRandomCheckbox is nil or missing SetChecked")
  end

  -- 🎨 Reset color
  local defaultColor = EasyCursorTrails.GetDefaultColor("starColor") or { r = 1, g = 1, b = 0.8, a = 0.6 }
  activeProfile.starColor = CopyTable(defaultColor)
  EasyCursorTrails.SaveToCurrentProfile("starColor", activeProfile.starColor)

  local picker = EasyCursorTrails.starColorPicker
  if picker then
    if picker.SetColorRGBA then
      picker:SetColorRGBA(defaultColor.r, defaultColor.g, defaultColor.b, defaultColor.a)
    elseif picker.swatch then
      picker.swatch:SetColorTexture(defaultColor.r, defaultColor.g, defaultColor.b, defaultColor.a)
    end
  else
    --⚠️ starColorPicker is nil during reset")
  end

  -- ❌ Disable star effect toggle
  activeProfile.enableStarEffect = false
  EasyCursorTrails.SaveToCurrentProfile("enableStarEffect", false)

  if EasyCursorTrails.starEmbersCheckbox then
    local checkbox = EasyCursorTrails.starEmbersCheckbox
    local originalScript = checkbox:GetScript("OnClick")
    checkbox:SetScript("OnClick", nil) -- mute callback
    checkbox:SetChecked(false)
    checkbox:SetScript("OnClick", originalScript) -- restore
  else
    --⚠️ starEmbersCheckbox is nil or missing SetChecked")
  end

  if EasyCursorTrails.StopStarTicker then
    EasyCursorTrails.StopStarTicker()
  end

  -- ⏳ Delay trail rebuild to let UI settle
  C_Timer.After(0.1, function()
    EasyCursorTrails.RebuildTrails()
  end)
end)

--==============================================================================================
-- 💨 Smoke Effect Checkbox
local smokeEffectCheckbox = EasyCursorTrails.CreateCheckbox(
  "EnableSmokeEffect",
  menu,
  "Smokes",
  EasyCursorTrails.currentProfileTable and EasyCursorTrails.currentProfileTable.enableSmokeEffect,
  function(isChecked)
    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    if not profile then return end

    profile.enableSmokeEffect = isChecked
    EasyCursorTrails.SaveToCurrentProfile("enableSmokeEffect", isChecked)

    if isChecked then
      EasyCursorTrails.StartSmokeTicker()
    else
      EasyCursorTrails.StopSmokeTicker()
    end
  end
)

-- ✅ Resize checkbox to 28x28
smokeEffectCheckbox:SetSize(28, 28)

-- ✅ Store reference
EasyCursorTrails.smokeEffectCheckbox = smokeEffectCheckbox

-- 📌 Position below Star Embers checkbox
EasyCursorTrails.smokeEffectCheckbox:SetPoint("TOPLEFT", EasyCursorTrails.starEmbersCheckbox, "BOTTOMLEFT", 0, -20)

-- 💨 Smoke Color Picker
EasyCursorTrails.smokeColorPicker = EasyCursorTrails.CreateColorPicker(
  "SmokeColor",
  menu,
  "",
  EasyCursorTrails.currentProfileTable and EasyCursorTrails.currentProfileTable.smokeColor
    or EasyCursorTrails.GetDefaultColor("smokeColor"),
  function(r, g, b, a)
    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    if not profile then return end

    profile.smokeColor = { r = r, g = g, b = b, a = a }
    EasyCursorTrails.SaveToCurrentProfile("smokeColor", profile.smokeColor)
  end
)
EasyCursorTrails.smokeColorPicker:SetPoint("LEFT", EasyCursorTrails.smokeEffectCheckbox.Text, "RIGHT", 65, 0)

-- 🎲 Smoke Random Toggle
local smokeRandomCheckbox = CreateFrame("CheckButton", "EasyCursorTrails_SmokeRandomColorToggle", menu, "ChatConfigCheckButtonTemplate")
smokeRandomCheckbox:SetPoint("LEFT", EasyCursorTrails.smokeColorPicker, "RIGHT", 20, 0)
smokeRandomCheckbox:SetSize(28, 28)
smokeRandomCheckbox:SetHitRectInsets(0, 0, 0, 0)

local smokeRandLabel = menu:CreateFontString(nil, "ARTWORK", "GameFontNormal")
smokeRandLabel:SetPoint("LEFT", smokeRandomCheckbox, "RIGHT", 4, 0)
smokeRandLabel:SetText("Random")
smokeRandLabel:SetTextColor(1, 0.82, 0)

local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
smokeRandomCheckbox:SetChecked(profile and profile.randomSmokeColor ~= false)
EasyCursorTrails.smokeRandomColorCheckbox = smokeRandomCheckbox

smokeRandomCheckbox:SetScript("OnClick", function(self)
  local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
  if not profile then return end

  profile.randomSmokeColor = self:GetChecked()
  EasyCursorTrails.SaveToCurrentProfile("randomSmokeColor", profile.randomSmokeColor)
end)
-- ♻️ Smoke Reset Button
local resetSmokeColorButton = CreateFrame("Button", nil, menu, "UIPanelButtonTemplate")
resetSmokeColorButton:SetPoint("LEFT", resetStarColorBtn, "RIGHT", -48, -46)
resetSmokeColorButton:SetSize(48, 24)
resetSmokeColorButton:SetText("Reset")

resetSmokeColorButton:SetScript("OnClick", function()
  local activeProfile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
  if not activeProfile then
    --⚠️ No active profile found during Smoke reset")
    return
  end

  -- 🔄 Reset random toggle
  activeProfile.randomSmokeColor = false
  EasyCursorTrails.SaveToCurrentProfile("randomSmokeColor", false)
  if smokeRandomCheckbox and smokeRandomCheckbox.SetChecked then
    smokeRandomCheckbox:SetChecked(false)
  end

  -- 🎨 Reset color
  local defaultColor = EasyCursorTrails.GetDefaultColor("smokeColor") or { r = 0.1, g = 0.1, b = 0.1, a = 0.4 }
  activeProfile.smokeColor = CopyTable(defaultColor)
  EasyCursorTrails.SaveToCurrentProfile("smokeColor", activeProfile.smokeColor)

  local picker = EasyCursorTrails.smokeColorPicker
  if picker then
    if picker.SetColorRGBA then
      picker:SetColorRGBA(defaultColor.r, defaultColor.g, defaultColor.b, defaultColor.a)
    elseif picker.swatch then
      picker.swatch:SetColorTexture(defaultColor.r, defaultColor.g, defaultColor.b, defaultColor.a)
    end
  end

  -- ❌ Disable smoke effect and prevent reactivation
-- ✅ Disable smoke effect correctly
activeProfile.enableSmokeEffect = false
EasyCursorTrails.SaveToCurrentProfile("enableSmokeEffect", false)


  if EasyCursorTrails.StopSmokeTicker then
    EasyCursorTrails.StopSmokeTicker()
  end

  -- 🧤 Temporarily suppress checkbox callback
  if EasyCursorTrails.smokeEffectCheckbox then
    local checkbox = EasyCursorTrails.smokeEffectCheckbox
    local originalScript = checkbox:GetScript("OnClick")
    checkbox:SetScript("OnClick", nil) -- mute callback
    checkbox:SetChecked(false)
    checkbox:SetScript("OnClick", originalScript) -- restore
  end

  -- ⏳ Delay trail rebuild
  C_Timer.After(0.1, function()
    EasyCursorTrails.RebuildTrails()
  end)
end)

--==============================================================================================
-- 🌸 Spring Season Checkbox
EasyCursorTrails.springSeasonCheckbox = EasyCursorTrails.CreateCheckbox(
  "SpringSeasonToggle",
  menu,
  "Spring Season",
  profile.enableSpringSeasonTrails ~= false,
  function(isChecked)
    profile.enableSpringSeasonTrails = isChecked
    EasyCursorTrails.SaveToCurrentProfile("enableSpringSeasonTrails", isChecked)

    if isChecked then
      EasyCursorTrails.StartNatureTicker()
    else
      EasyCursorTrails.StopNatureTicker()
    end
  end
)
EasyCursorTrails.springSeasonCheckbox:SetPoint("TOPLEFT", EasyCursorTrails.smokeEffectCheckbox, "TOPRIGHT", -24, -45)

-- 🎨 Spring Season Color Picker
EasyCursorTrails.springSeasonColorPicker = EasyCursorTrails.CreateColorPicker(
  "SpringSeasonColor",
  menu,
  "",
  profile.springSeasonColor or { r = 0.8, g = 0.9, b = 1, a = 0.8 },
  function(r, g, b, a)
    profile.springSeasonColor = { r = r, g = g, b = b, a = a }
    EasyCursorTrails.SaveToCurrentProfile("springSeasonColor", profile.springSeasonColor)
    if EasyCursorTrails.springSeasonColorPicker.swatch then
      EasyCursorTrails.springSeasonColorPicker.swatch:SetColorTexture(r, g, b, a)
    end
  end
)
EasyCursorTrails.springSeasonColorPicker:SetPoint("LEFT", EasyCursorTrails.springSeasonCheckbox.Text, "RIGHT", 31, 0)

EasyCursorTrails.springSeasonColorPicker:SetScript("OnEnter", function(self)
  GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
  GameTooltip:SetText("Click to choose Spring Season color.", 1, 1, 1)
  GameTooltip:Show()
end)
EasyCursorTrails.springSeasonColorPicker:SetScript("OnLeave", GameTooltip_Hide)

-- 🎲 SpringSeason Random Checkbox
local springSeasonRandomCheckbox = CreateFrame("CheckButton", "EasyCursorTrails_SpringSeasonRandomColorToggle", menu, "ChatConfigCheckButtonTemplate")
springSeasonRandomCheckbox:SetPoint("LEFT", EasyCursorTrails.springSeasonColorPicker, "RIGHT", 20, 0)
springSeasonRandomCheckbox:SetSize(28, 28)
springSeasonRandomCheckbox:SetHitRectInsets(0, 0, 0, 0)

local springSeasonRandLabel = menu:CreateFontString(nil, "ARTWORK", "GameFontNormal")
springSeasonRandLabel:SetPoint("LEFT", springSeasonRandomCheckbox, "RIGHT", 4, 0)
springSeasonRandLabel:SetText("Random")
springSeasonRandLabel:SetTextColor(1, 0.82, 0)

springSeasonRandomCheckbox:SetChecked(profile.randomSpringSeasonColor ~= false)
EasyCursorTrails.springSeasonRandomColorCheckbox = springSeasonRandomCheckbox

springSeasonRandomCheckbox:SetScript("OnClick", function(self)
  profile.randomSpringSeasonColor = self:GetChecked()
  EasyCursorTrails.SaveToCurrentProfile("randomSpringSeasonColor", profile.randomSpringSeasonColor)
end)

-- ♻️ Reset Spring Season Button
local resetSpringSeasonButton = CreateFrame("Button", nil, menu, "UIPanelButtonTemplate")
resetSpringSeasonButton:SetPoint("LEFT", resetSmokeColorButton, "RIGHT", -48, -46)
resetSpringSeasonButton:SetSize(48, 24)
resetSpringSeasonButton:SetText("Reset")

resetSpringSeasonButton:SetScript("OnClick", function()
  local activeProfile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
  if not activeProfile then
    --⚠️ No active profile found during Spring Season reset")
    return
  end

  -- 🎲 Reset random toggle
  activeProfile.randomSpringSeasonColor = false
  EasyCursorTrails.SaveToCurrentProfile("randomSpringSeasonColor", false)

  if springSeasonRandomCheckbox and springSeasonRandomCheckbox.SetChecked then
    springSeasonRandomCheckbox:SetChecked(false)
  else
    --⚠️ springSeasonRandomCheckbox is nil or missing SetChecked")
  end

  -- 🎨 Reset color
  local defaultColor = { r = 0.8, g = 0.9, b = 1, a = 0.8 }
  activeProfile.springSeasonColor = CopyTable(defaultColor)
  EasyCursorTrails.SaveToCurrentProfile("springSeasonColor", activeProfile.springSeasonColor)

  local picker = EasyCursorTrails.springSeasonColorPicker
  if picker then
    if picker.SetColorRGBA then
      picker:SetColorRGBA(defaultColor.r, defaultColor.g, defaultColor.b, defaultColor.a)
    elseif picker.swatch then
      picker.swatch:SetColorTexture(defaultColor.r, defaultColor.g, defaultColor.b, defaultColor.a)
    end
  else
    --⚠️ springSeasonColorPicker is nil during reset")
  end

  -- ❌ Disable spring season effect
  activeProfile.enableSpringSeasonTrails = false
  EasyCursorTrails.SaveToCurrentProfile("enableSpringSeasonTrails", false)

  if EasyCursorTrails.springSeasonCheckbox and EasyCursorTrails.springSeasonCheckbox.SetChecked then
    EasyCursorTrails.springSeasonCheckbox:SetChecked(false)
  else
    --⚠️ springSeasonCheckbox is nil or missing SetChecked")
  end

  if EasyCursorTrails.StopNatureTicker then
    EasyCursorTrails.StopNatureTicker()
  else
    --⚠️ StopNatureTicker function is missing")
  end

  -- ⏳ Delay to avoid UI sync hiccups
  C_Timer.After(0.1, function()
    EasyCursorTrails.RebuildTrails()
  end)
end)

-- ✅ Restore ticker after load if enabled
C_Timer.After(0.2, function()
  local active = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
  if active and active.enableSpringSeasonTrails and EasyCursorTrails.StartNatureTicker then
    EasyCursorTrails.StartNatureTicker()
  end
end)


--=======================================================================================================
-- 🔥 Ember Toggle
local enableEmbers = profile.enableEmbers
if enableEmbers == nil then
    enableEmbers = EasyCursorTrails.defaults.enableEmbers or false
end

EasyCursorTrails.emberCheckbox = EasyCursorTrails.CreateCheckbox(
  "EmberToggle",
  menu,
  "Embers",
  enableEmbers,
  function(isChecked)
    profile.enableEmbers = isChecked == true
    EasyCursorTrails.SaveToCurrentProfile("enableEmbers", profile.enableEmbers)

    if profile.enableEmbers then
      EasyCursorTrails.StartEmberTicker()
    else
      EasyCursorTrails.StopEmberTicker()
    end
  end
)
EasyCursorTrails.emberCheckbox:SetPoint("TOPLEFT", EasyCursorTrails.springSeasonCheckbox, "TOPRIGHT", -26, -45)

-- 🎨 Ember Color Picker
EasyCursorTrails.emberColorPicker = EasyCursorTrails.CreateColorPicker(
  "EmberColor",
  menu,
  "",
  profile.emberColor or { r = 1, g = 0.4, b = 0.1, a = 0.8 },
  function(r, g, b, a)
    profile.emberColor = { r = r, g = g, b = b, a = a }
    EasyCursorTrails.SaveToCurrentProfile("emberColor", profile.emberColor)
    if EasyCursorTrails.emberColorPicker.swatch then
      EasyCursorTrails.emberColorPicker.swatch:SetColorTexture(r, g, b, a)
    end

    if profile.enableEmbers and not profile.randomEmberColor then
      for _, pool in pairs(EasyCursorTrails.trailPool or {}) do
        for _, trail in ipairs(pool) do
          EasyCursorTrails.SpawnEmberEffect(trail)
        end
      end
    end
  end
)
EasyCursorTrails.emberColorPicker:SetPoint("LEFT", EasyCursorTrails.emberCheckbox.Text, "RIGHT", 65, 0)

EasyCursorTrails.emberColorPicker:SetScript("OnEnter", function(self)
  GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
  GameTooltip:SetText("Click to choose Ember color.", 1, 1, 1)
  GameTooltip:Show()
end)
EasyCursorTrails.emberColorPicker:SetScript("OnLeave", GameTooltip_Hide)

-- 🎲 Ember Random Toggle
local emberRandomCheckbox = CreateFrame("CheckButton", "EasyCursorTrails_EmberRandomColorToggle", menu, "ChatConfigCheckButtonTemplate")
emberRandomCheckbox:SetPoint("LEFT", EasyCursorTrails.emberColorPicker, "RIGHT", 20, 0)
emberRandomCheckbox:SetSize(28, 28)
emberRandomCheckbox:SetHitRectInsets(0, 0, 0, 0)

local emberRandLabel = menu:CreateFontString(nil, "ARTWORK", "GameFontNormal")
emberRandLabel:SetPoint("LEFT", emberRandomCheckbox, "RIGHT", 4, 0)
emberRandLabel:SetText("Random")
emberRandLabel:SetTextColor(1, 0.82, 0)

emberRandomCheckbox:SetChecked(profile.randomEmberColor ~= false)
EasyCursorTrails.emberRandomColorCheckbox = emberRandomCheckbox

emberRandomCheckbox:SetScript("OnClick", function(self)
  profile.randomEmberColor = self:GetChecked()
  EasyCursorTrails.SaveToCurrentProfile("randomEmberColor", profile.randomEmberColor)

  if profile.enableEmbers then
    for _, pool in pairs(EasyCursorTrails.trailPool or {}) do
      for _, trail in ipairs(pool) do
        EasyCursorTrails.SpawnEmberEffect(trail)
      end
    end
  end
end)

-- ♻️ Ember Reset Button
local resetEmberButton = CreateFrame("Button", nil, menu, "UIPanelButtonTemplate")
resetEmberButton:SetPoint("LEFT", resetSpringSeasonButton, "RIGHT", -48, -46)
resetEmberButton:SetSize(48, 24)
resetEmberButton:SetText("Reset")

resetEmberButton:SetScript("OnClick", function()
  local activeProfile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
  if not activeProfile then
    --⚠️ No active profile found during Ember reset")
    return
  end

  -- 🔄 Reset random ember toggle
  activeProfile.randomEmberColor = false
  if emberRandomCheckbox and emberRandomCheckbox.SetChecked then
    emberRandomCheckbox:SetChecked(false)
  else
    --⚠️ emberRandomCheckbox is nil or missing SetChecked")
  end
  EasyCursorTrails.SaveToCurrentProfile("randomEmberColor", false)

  -- 🌈 Reset ember color to default
  local defaultColor = { r = 1, g = 0.4, b = 0.1, a = 0.8 }
  activeProfile.emberColor = CopyTable(defaultColor)
  EasyCursorTrails.SaveToCurrentProfile("emberColor", activeProfile.emberColor)

  local picker = EasyCursorTrails.emberColorPicker
  if picker then
    if picker.SetColorRGBA then
      picker:SetColorRGBA(defaultColor.r, defaultColor.g, defaultColor.b, defaultColor.a)
    elseif picker.swatch then
      picker.swatch:SetColorTexture(defaultColor.r, defaultColor.g, defaultColor.b, defaultColor.a)
    end
  else
    --⚠️ emberColorPicker is nil during reset")
  end

  -- 🔌 Disable embers entirely and update checkbox
  activeProfile.enableEmbers = false
  EasyCursorTrails.SaveToCurrentProfile("enableEmbers", false)
  if EasyCursorTrails.emberCheckbox and EasyCursorTrails.emberCheckbox.SetChecked then
    EasyCursorTrails.emberCheckbox:SetChecked(false)
  else
    --⚠️ emberCheckbox is nil or missing SetChecked")
  end

  -- 🛑 Stop ember ticker if running
  if EasyCursorTrails.StopEmberTicker then
    EasyCursorTrails.StopEmberTicker()
  else
    --⚠️ StopEmberTicker function is missing")
  end

  -- ⏳ Delay rebuild to avoid UI sync issues
  C_Timer.After(0.1, function()
    EasyCursorTrails.RebuildTrails()
  end)
end)



-- 🧭 Activate Ember Ticker on Load if enabled
local activeProfile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
if activeProfile and activeProfile.enableEmbers then
  EasyCursorTrails.StartEmberTicker()
end

--========================================================================================================

--------------------------------------------------------------------------
-- 🧭 Trail Behavior Settings
-- Customize how trails respond to cursor movement.
-- These options affect how trail segments behave visually.
--------------------------------------------------------------------------

-- Connect Trails Checkbox
local connectTrailsCheckbox = CreateFrame("CheckButton", "ConnectTrailsCheckbox", menu, "UICheckButtonTemplate")
connectTrailsCheckbox:SetPoint("TOPLEFT", EasyCursorTrails.emberCheckbox, "BOTTOMLEFT", 0, -10)
connectTrailsCheckbox:SetSize(28, 28)
connectTrailsCheckbox:SetHitRectInsets(0, 0, 0, 0)

connectTrailsCheckbox.text = connectTrailsCheckbox:CreateFontString(nil, "OVERLAY", "GameFontNormal")
connectTrailsCheckbox.text:SetPoint("LEFT", connectTrailsCheckbox, "RIGHT", 8, 0)
connectTrailsCheckbox.text:SetText("Connect Trails")

connectTrailsCheckbox:SetChecked(currentProfile and currentProfile.connectTrails or false)

connectTrailsCheckbox:SetScript("OnClick", function(self)
    local isConnected = self:GetChecked()
    EasyCursorTrails.SaveToCurrentProfile("connectTrails", isConnected)
    if EasyCursorTrails.RebuildTrails then
        EasyCursorTrails.RebuildTrails()
    else
        EasyCursorTrails.HandleError("ConnectTrailsCheckbox: RebuildTrails function is missing.")
    end
    if EasyCursorTrails.RefreshSettingsUI then
        EasyCursorTrails.RefreshSettingsUI()
    end
end)

connectTrailsCheckbox:SetScript("OnEnter", function(self)
    GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
    GameTooltip:SetText("Connect Trails", 1, 1, 1)
    GameTooltip:AddLine("Smoothly links trail segments to avoid gaps when moving quickly.", nil, nil, nil, true)
    GameTooltip:Show()
end)

connectTrailsCheckbox:SetScript("OnLeave", function()
    GameTooltip:Hide()
end)

EasyCursorTrails.connectTrailsCheckbox = connectTrailsCheckbox

--========================================================================================================

function EasyCursorTrails.OnProfileSelected(profileName)
    if not profileName or not EasyCursorTrailsDB.profiles[profileName] then
        --EasyCursorTrails: Invalid profile selected.")
        return
    end

    EasyCursorTrailsDB.currentProfile = profileName
    EasyCursorTrails.currentProfileTable = EasyCursorTrailsDB.profiles[profileName]

    -- ✅ Refresh UI elements
    EasyCursorTrails.LoadSettingsToUI()

    -- ✅ Reapply visual effects if needed
    EasyCursorTrails.ApplyColorEffectCursor()
    EasyCursorTrails.ApplySelectedGlowEffect()
    if EasyCursorTrails.trailPool then
        for _, layerPool in pairs(EasyCursorTrails.trailPool) do
            for _, trail in ipairs(layerPool) do
                if trail and trail.texture then
                    EasyCursorTrails.ApplyColorEffectTrail(trail)
                end
            end
        end
    end
end


function EasyCursorTrails.LoadSettingsToUI()
    local p = EasyCursorTrails.currentProfileTable
    if not p then return end

    -- Sliders
    if EasyCursorTrails.cursorSizeSlider then
        EasyCursorTrails.cursorSizeSlider:SetValue(p.cursorSize or 38)
    end
    -- Repeat for other sliders...

    -- Checkboxes
    if EasyCursorTrails.enableTrailsCheckbox then
        EasyCursorTrails.enableTrailsCheckbox:SetChecked(p.enableTrails)
    end
    -- Repeat for other checkboxes...

    -- Dropdowns
    if EasyCursorTrails.trailTextureDropdown then
        UIDropDownMenu_SetSelectedID(EasyCursorTrails.trailTextureDropdown, p.trailTexture or 1)
    end
    -- Repeat for other dropdowns...

    -- Color edit boxes
    if EasyCursorTrails.cursorColorEditBox then
        EasyCursorTrails.cursorColorEditBox:SetText(RGBToHex(p.cursorColor.r, p.cursorColor.g, p.cursorColor.b, p.cursorColor.a))
    end
    if EasyCursorTrails.glowColorEditBox then
        EasyCursorTrails.glowColorEditBox:SetText(RGBToHex(p.glowColor.r, p.glowColor.g, p.glowColor.b, p.glowColor.a))
    end
    if EasyCursorTrails.trailColorEditBox then
        EasyCursorTrails.trailColorEditBox:SetText(RGBToHex(p.trailColor.r, p.trailColor.g, p.trailColor.b, p.trailColor.a))
    end
end

--==============================================================================================
-- ✅ Random vibrant sparkle color
function EasyCursorTrails.GetRandomSparkleColor()
    local vibrant = {
        { r = 1, g = 1, b = 0.8 },
        { r = 0.9, g = 0.7, b = 1 },
        { r = 0.7, g = 1, b = 0.9 },
        { r = 1, g = 0.6, b = 0.6 },
        { r = 0.8, g = 0.9, b = 1 },
    }
    local pick = vibrant[math.random(#vibrant)]
    return { r = pick.r, g = pick.g, b = pick.b, a = 0.6 }
end

-- ✅ Random neutral tone generator
function EasyCursorTrails.GetRandomNeutralColor()
    local gray = math.random(20, 80) / 100
    return { r = gray, g = gray, b = gray, a = 0.4 }
end

-- ✅ Update sparkle visuals with color logic
function EasyCursorTrails.UpdateSparkleVisualTraits()
    if not profile.enableEmberSparkles then return end

    for _, sparkle in ipairs(EasyCursorTrails.sparklePool or {}) do
        local color

        if profile.randomSparkleColor then
            local useNeutral = math.random() < 0.25  -- 25% chance to use neutral
            color = useNeutral and EasyCursorTrails.GetRandomNeutralColor()
                              or EasyCursorTrails.GetRandomSparkleColor()
        else
            color = profile.sparkleColor or { r = 1, g = 1, b = 0.8, a = 0.6 }
        end

        -- Vary scale and alpha for uniqueness
        local alpha = color.a * (math.random(90, 100) / 100)
        sparkle:SetVertexColor(color.r, color.g, color.b, alpha)
        sparkle:SetScale(0.9 + math.random() * 0.2)
    end
end

-- ✅ Main sparkle activation logic
function EasyCursorTrails.ApplySparkleSettings()
    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    if not profile then return end

    if profile.enableEmberSparkles then
        if EasyCursorTrails.StartSparkleTicker then
            EasyCursorTrails.StartSparkleTicker()
        else
            EasyCursorTrails.SpawnSparkles()
        end

        EasyCursorTrails.UpdateSparkleVisualTraits()
    end
end


function EasyCursorTrails.GetRandomSparkleColor()
    local vibrant = {
        { r = 1, g = 1, b = 0.8 },
        { r = 0.9, g = 0.7, b = 1 },
        { r = 0.7, g = 1, b = 0.9 },
    }
    local pick = vibrant[math.random(#vibrant)]
    return { r = pick.r, g = pick.g, b = pick.b, a = 0.6 }
end

--===========================================================================================


function EasyCursorTrails.GetSavedTrailTextureIndex()
    local profileName = EasyCursorTrailsDB.currentProfile or "Default"
    local profileSettings = EasyCursorTrailsDB.profiles[profileName] or {}
    local defaultSettings = EasyCursorTrails.defaults or {}

    local savedIndex = profileSettings.trailTexture or defaultSettings.trailTexture or 1

    -- Verify index is within bounds before returning
    if not EasyCursorTrails.trailTextures or not EasyCursorTrails.trailTextures[savedIndex] then
        return 1 -- Default to first texture if saved index is invalid
    end

    return savedIndex
end


--------------------------------------------------------------------------
-- 2) Trail Movements Effects Dropdown
--------------------------------------------------------------------------
local trailMovementEffectDropdown = EasyCursorTrails.CreateValidatedDropdown(
    "TrailMovementEffectDropdown",
    menu,
    "Movement Effects",
    trailMovementEffectOptions,  -- This should be your local options table  
    EasyCursorTrailsDB.trailMovementEffect or 1,
    function(index)
        if not trailMovementEffectOptions[index] then
            return
        end

        EasyCursorTrailsDB.trailMovementEffect = index
        EasyCursorTrails.settingsChanged = true
        EasyCursorTrails.SaveToCurrentProfile("trailMovementEffect", index)

        if EasyCursorTrails.UpdateTrailTextureDropdown then
            local success, err = pcall(EasyCursorTrails.UpdateTrailTextureDropdown, index)
            if not success then
                -- Debug error if needed.
            end
        end

        if EasyCursorTrails.RefreshSettingsUI then
            EasyCursorTrails.RefreshSettingsUI()
        end
    end
)
trailMovementEffectDropdown:SetPoint("TOPLEFT", EasyCursorTrails.trailFollowSpeedSlider, "BOTTOMLEFT", -20, -45)
EasyCursorTrails.trailMovementEffectDropdown = trailMovementEffectDropdown  -- Global assignment

-- IMPORTANT: Also assign the options table globally for refresh purposes.
EasyCursorTrails.trailMovementEffectOptions = trailMovementEffectOptions

--------------------------------------------------------------------------
-- Trail Color Effects Dropdown
--------------------------------------------------------------------------
local trailColorEffectDropdown = CreateDropdown(
    "TrailColorEffectDropdown",
    menu,
    "Trail Color Effects",
    TrailcolorEffects,
    EasyCursorTrailsDB.trailColorEffect or 1,
    function(index)
        EasyCursorTrailsDB.trailColorEffect = index
        EasyCursorTrails.settingsChanged = true
        EasyCursorTrails.SaveToCurrentProfile("trailColorEffect", index)

        -- Apply new color effect across trails
        if EasyCursorTrails.trailPool then
            for layer, trails in pairs(EasyCursorTrails.trailPool) do
                for trailIndex, trail in ipairs(trails) do
                    if trail and trail.texture then
                        EasyCursorTrails.ApplyColorEffectTrail(trail, trailIndex)
                    end
                end
            end
        end

        -- ✅ Ensure UI updates when values change
        EasyCursorTrails.RefreshSettingsUI()
    end
)
trailColorEffectDropdown:SetPoint("TOPLEFT", trailMovementEffectDropdown, "BOTTOMLEFT", 0, -15)
EasyCursorTrails.trailColorEffectDropdown = trailColorEffectDropdown

-----------------------------------------------------------
-- RGB ↔ HTML Color Code Conversion Functions
-----------------------------------------------------------
-- Converts normalized RGB (0–1) and optional alpha to hex string "#RRGGBB" or "#RRGGBBAA"
function RGBToHex(r, g, b, a)
    local function clamp(v) return math.max(0, math.min(1, v or 1)) end

    r = math.floor(clamp(r) * 255)
    g = math.floor(clamp(g) * 255)
    b = math.floor(clamp(b) * 255)

    if a ~= nil then
        a = math.floor(clamp(a) * 255)
        return string.format("#%02X%02X%02X%02X", r, g, b, a)
    else
        return string.format("#%02X%02X%02X", r, g, b)
    end
end

-- Converts hex string "#RGB", "#RRGGBB", or "#RRGGBBAA" to normalized r, g, b, a
function HexToRGB(hex)
    if type(hex) ~= "string" then return 1, 1, 1, 1 end

    hex = hex:gsub("#", "")
    local len = #hex

    -- Expand shorthand "#RGB" to "#RRGGBB"
    if len == 3 then
        hex = hex:sub(1,1):rep(2) .. hex:sub(2,2):rep(2) .. hex:sub(3,3):rep(2)
        len = 6
    end

    if len ~= 6 and len ~= 8 then return 1, 1, 1, 1 end

    local r = tonumber(hex:sub(1, 2), 16) or 255
    local g = tonumber(hex:sub(3, 4), 16) or 255
    local b = tonumber(hex:sub(5, 6), 16) or 255
    local a = len == 8 and tonumber(hex:sub(7, 8), 16) or 255

    return r / 255, g / 255, b / 255, a / 255
end


-- Create the Select Trail Color Button
local selectTrailColorButton = CreateFrame("Button", "SelectTrailColorButton", menu, "UIPanelButtonTemplate")
selectTrailColorButton:SetSize(120, 25)
selectTrailColorButton:SetText("Select Trail Color")
selectTrailColorButton:SetPoint("TOPLEFT", trailColorEffectDropdown, "BOTTOMLEFT", 20, -10)
EasyCursorTrails.selectTrailColorButton = selectTrailColorButton

-- Create the Trail Color Edit Box
local trailColorEditBox = CreateFrame("EditBox", "TrailColorEditBox", menu, "InputBoxTemplate")
trailColorEditBox:SetSize(60, 25)
trailColorEditBox:SetAutoFocus(false)
trailColorEditBox:SetMaxLetters(9)
trailColorEditBox:SetPoint("LEFT", selectTrailColorButton, "RIGHT", 10, 0) -- Horizontal alignment
EasyCursorTrails.trailColorEditBox = trailColorEditBox

-- Add a label above the edit box
local trailColorLabel = menu:CreateFontString(nil, "OVERLAY", "GameFontNormal")
trailColorLabel:SetPoint("BOTTOMLEFT", trailColorEditBox, "TOPLEFT", -10, 0)
trailColorLabel:SetText("HTML Color Code")

-- Update the edit box text based on saved trail color
local function UpdateTrailColorEditBox()
    local profileName = EasyCursorTrailsDB.currentProfile or "Default"
    local profile = EasyCursorTrailsDB.profiles[profileName] or {}
    local defaults = EasyCursorTrails.defaults or {}

    local color = profile.trailColor or EasyCursorTrailsDB.trailColor or defaults.trailColor or { r = 1, g = 1, b = 1, a = 1 }
    local colorText = RGBToHex(color.r, color.g, color.b, color.a)

    if trailColorEditBox:GetText() ~= colorText then
        trailColorEditBox:SetText(colorText)
    end

    local textWidth = trailColorEditBox:GetText():len() * 8
    trailColorEditBox:SetWidth(math.max(80, textWidth + 20))
end

-- Handle user input when Enter is pressed
trailColorEditBox:SetScript("OnEnterPressed", function(self)
    local hexColor = "#" .. self:GetText():gsub("#", "")
    local r, g, b, a = HexToRGB(hexColor)
    if r and g and b then
        a = a or 1
        EasyCursorTrailsDB.trailColor = { r = r, g = g, b = b, a = a }
        EasyCursorTrails.settingsChanged = true
        EasyCursorTrails.SaveToCurrentProfile("trailColor", EasyCursorTrailsDB.trailColor)

        if EasyCursorTrails.trailPool then
            for _, layerPool in pairs(EasyCursorTrails.trailPool) do
                for _, trail in ipairs(layerPool) do
                    if trail and trail.texture then
                        EasyCursorTrails.ApplyColorEffectTrail(trail)
                    end
                end
            end
        end

        UpdateTrailColorEditBox()
    else
        --Invalid HTML color format! Use #RRGGBB or #RRGGBBAA")
    end

    self:ClearFocus()
end)

trailColorEditBox:SetScript("OnEditFocusLost", function(self)
    self:GetScript("OnEnterPressed")(self)
end)

-- Button click logic
selectTrailColorButton:SetScript("OnClick", function()
    local initialColor = EasyCursorTrailsDB.trailColor or { r = 1, g = 1, b = 1, a = 1 }
    EasyCursorTrails.OpenColorPicker(initialColor, function(color)
        EasyCursorTrailsDB.trailColor = color
        EasyCursorTrails.settingsChanged = true
        EasyCursorTrails.SaveToCurrentProfile("trailColor", color)

        if EasyCursorTrails.trailPool then
            for _, layerPool in pairs(EasyCursorTrails.trailPool) do
                for _, trail in ipairs(layerPool) do
                    if trail and trail.texture then
                        EasyCursorTrails.ApplyColorEffectTrail(trail)
                    end
                end
            end
        end

        UpdateTrailColorEditBox()
    end)
end)

-- Initialize edit box
UpdateTrailColorEditBox()

--------------------------------------------------------------------------
-- 6) (Optional) Save to Current Profile if needed on load
--------------------------------------------------------------------------
-- 🌱 Ensure required globals
effectsSettingsHeader = effectsSettingsHeader or menu

-- 🧭 Profile Management Header
local profileHeader = menu:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
profileHeader:SetPoint("TOPLEFT", menuTitle, "BOTTOMLEFT", 300, -20)
profileHeader:SetText("Profile Settings")

-- 🔽 Profile Dropdown
local profileDropdown = CreateFrame("Frame", "ProfileDropdown", menu, "UIDropDownMenuTemplate")
profileDropdown:SetPoint("TOPLEFT", profileHeader, "TOPRIGHT", -140, -20)
EasyCursorTrails.profileDropdown = profileDropdown

-- 🧬 Ensure default profile exists
local function EnsureDefaultProfile()
    if not EasyCursorTrailsDB.profiles then
        EasyCursorTrailsDB.profiles = {}
    end

    if not EasyCursorTrailsDB.profiles["Default"] then
        EasyCursorTrailsDB.profiles["Default"] = EasyCursorTrails.DeepCopyDefaults(EasyCursorTrails.defaults or {})
    end
end
-- 🐉 Ensure Coper_Dragon profile exists
local function EnsureCoperDragonProfile()
    -- Ensure DB and profiles table exist
    EasyCursorTrailsDB = EasyCursorTrailsDB or {}
    EasyCursorTrailsDB.profiles = EasyCursorTrailsDB.profiles or {}

 -- Coper_Dragon
    if not EasyCursorTrailsDB.profiles["Coper_Dragon"] then
        EasyCursorTrailsDB.profiles["Coper_Dragon"] = {
    enableTrails = true,
    selectedGlowEffect = 19,
    enableStaticArc = false,
    cursorColorEffect = 4,
    connectTrails = true,
    horizontalScale = 1,
    enableStaticArcs = false,
    glowAboveCursor = false,
    randomLightningSparkColor = false,
    glowRadius = 0.1,
    glowColor = { r = 0.7215686274509804, g = 0.4470588235294118, b = 0.2, a = 1 },
    numGlows = 30,
    trailRadius = 20,
    cursorOffsetX = 0,
    enableTrailShadows = true,
    glowThickness = 0.6,
    trailColorEffect = 9,
    pulsingSpeed = 10,
    trailDelay = 0,
    chainSegment = 10,
    disableGlowPulsing = false,
    trailUpdateMultiplier = 100,
    enableStars = true,
    selectedCursorTextureName = "Yin_Yang_1",
    randomEmberColor = false,
    staticArcColor = { r = 1, g = 1, b = 1, a = 1 },
    enableTwinkleStars = true,
    enableSmokeEffect = false,
    patternGlowCount = 29,
    cursorFrameStrata = "HIGH",
    trailTexture = 1,
    cursorSize = 40,
    glowIntensity = 1,
    randomFireColor = false,
    randomStaticArcColor = false,
    randomStarColor = false,
    shadowTrailColor = { r = 0, g = 0, b = 0, a = 0.4 },
    glowHollowness = 0,
    trailCount = 50,
    trailSpacing = 10,
    glowBelow = false,
    enableEmbers = true,
    randomSpringSeasonColor = false,
    cursorColor = { r = 0.7215686274509804, g = 0.4470588235294118, b = 0.2, a = 1 },
    trailFrameStrata = "HIGH",
    trailMovementEffect = 1,
    trailInitialSeparation = 36,
    glowPulsingIntensity = 0.5,
    starColor = { r = 0.7215686440467834, g = 0.4509804248809815, b = 0.2000000178813934, a = 1 },
    trailIntensity = 0.5,
    additionalEffects = 1,
    enableDirectionalOffset = false,
    enableSmoke = false,
    enableStarEmbers = true,
    trailSizeStart = 18,
    enableSpringSeasonTrails = false,
    menuPosition = {
        x = -244.833,
        y = 72.4999,
        point = "RIGHT",
        relativePoint = "RIGHT",
    },
    glowIntensityFactor = 0.2999999821186066,
    chainSpacing = 1,
    enableLightningSparks = false,
    randomSmokeColor = false,
    trailLayerSpacing = 0,
    randomShadowColor = false,
    numTrails = 10,
    enableFire = false,
    trailOffsetX = -37,
    cursorOffsetY = 0,
    trailSizeEnd = 1,
    enableSmokeTrails = false,
    twinkleStarsColor = { r = 0.937255, g = 1, b = 0.97647065, a = 1 },
    pulseMin = 0.3,
    verticalScale = 2,
    minimapPosition = { x = 0, y = 0 },
    trailColor = { r = 0.7215686274509804, g = 0.4509803921568628, b = 0.2, a = 1 },
    trailOffsetY = -1,
    cursorTexture = 32,
    enableFireTrails = false,
    emberColor = { r = 0.7215686440467834, g = 0.4509804248809815, b = 0.2000000178813934, a = 0.8 },
    randomTwinkleStarsColor = false,
    trailGlowIntensity = 1,
    enableSpringSeason = false,
    trailLayerCount = 1,
    trailCountSlider = 25,
    glowSize = 0.6

        }
    end

    
          -- Ghost_Sparkles
    if not EasyCursorTrailsDB.profiles["Heart_2_heart"] then
        EasyCursorTrailsDB.profiles["Heart_2_heart"] = {
    verticalScale = 2,
    selectedGlowEffect = 5,
    enableStaticArc = false,
    cursorColorEffect = 6,
    minimapPosition = { x = 0, y = 0 },
    horizontalScale = 1,
    enableStaticArcs = true,
    glowAboveCursor = false,
    randomLightningSparkColor = false,
    glowRadius = 0.26,
    glowColor = { r = 1, g = 0.5333333333333333, b = 0.7254901960784313, a = 1 },
    numGlows = 30,
    trailRadius = 20,
    cursorOffsetX = 0,
    enableTrailShadows = true,
    glowThickness = 0.8,
    trailColorEffect = 9,
    pulsingSpeed = 10,
    trailDelay = 0,
    chainSegment = 69,
    disableGlowPulsing = false,
    cursorTexture = 26,
    enableStars = true,
    selectedCursorTextureName = "Heart_White",
    randomEmberColor = false,
    staticArcColor = { r = 1, g = 1, b = 1, a = 1 },
    enableTwinkleStars = false,
    enableSmokeEffect = false,
    patternGlowCount = 29,
    cursorFrameStrata = 4,
    trailTexture = 28,
    cursorSize = 40,
    glowIntensity = 1,
    randomFireColor = false,
    randomStaticArcColor = false,
    randomStarColor = false,
    shadowTrailColor = { r = 0, g = 0, b = 0, a = 0.4 },
    glowHollowness = 0,
    trailCount = 30,
    trailSpacing = 69,
    glowBelow = false,
    enableEmbers = false,
    randomSpringSeasonColor = false,
    cursorColor = { r = 1, g = 0.1921568627450981, b = 0.1568627450980392, a = 1 },
    trailFrameStrata = "HIGH",
    trailMovementEffect = 1,
    additionalEffects = 1,
    enableLightningSpark = false,
    glowPulsingIntensity = 0.5,
    smokeColor = { r = 1, g = 0.5490196347236633, b = 0.9803922176361084, a = 1 },
    trailIntensity = 0.5,
    lightningSparkColor = { r = 1, g = 0.4509804248809815, b = 0.8666667342185974, a = 1 },
    enableDirectionalOffset = false,
    twinkleStarsColor = { r = 0.9, g = 0.95, b = 1, a = 1 },
    trailUpdateMultiplier = 20,
    trailSizeStart = 40,
    trailInitialSeparation = 30,
    menuPosition = {
        x = 250.1666412353516,
        y = -87.33332061767578,
        point = "TOP",
        relativePoint = "TOP",
    },
    pulseMin = 0.3,
    chainSpacing = 1,
    glowIntensityFactor = 0.71,
    randomSmokeColor = false,
    trailLayerSpacing = 0,
    connectTrails = true,
    numTrails = 10,
    enableFire = false,
    randomShadowColor = false,
    cursorOffsetY = 0,
    trailOffsetY = -20,
    trailOffsetX = -32,
    enableSpringSeasonTrails = false,
    enableSpringSeason = false,
    enableLightningSparks = false,
    enableSmokeTrails = true,
    trailSizeEnd = 10,
    enableStarEmbers = false,
    enableTrails = true,
    enableFireTrails = false,
    trailColor = { r = 1, g = 0.3921568989753723, b = 0.4431372880935669, a = 1 },
    randomTwinkleStarsColor = false,
    trailGlowIntensity = 1,
    enableSmoke = false,
    trailLayerCount = 1,
    trailTextureOpacity = 1,
    glowSize = 0.603499174118042,

        }
    end



          -- Butterfly
    if not EasyCursorTrailsDB.profiles["Butterfly"] then
        EasyCursorTrailsDB.profiles["Butterfly"] = {
      
    verticalScale = 2,
    selectedGlowEffect = 5,
    enableStaticArc = false,
    cursorColorEffect = 1,
    minimapPosition = { x = 0, y = 0 },
    horizontalScale = 1,
    enableStaticArcs = false,
    glowAboveCursor = false,
    randomLightningSparkColor = false,
    glowRadius = 0.17,
    glowColor = { r = 0.407843137254902, g = 1, b = 0.3333333333333333, a = 1 },
    numGlows = 14,
    trailRadius = 20,
    cursorOffsetX = 31,
    enableTrailShadows = true,
    glowThickness = 1.648499727249146,
    trailColorEffect = 10,
    pulsingSpeed = 10,
    trailDelay = 0,
    chainSegment = 10,
    disableGlowPulsing = false,
    cursorTexture = 36,
    enableStars = true,
    selectedCursorTextureName = "Butterfly_1",
    randomEmberColor = false,
    staticArcColor = { r = 1, g = 1, b = 1, a = 1 },
    enableTwinkleStars = false,
    enableSmokeEffect = false,
    patternGlowCount = 14,
    cursorFrameStrata = 4,
    trailTexture = 30,
    cursorSize = 60,
    glowIntensity = 0.1,
    randomFireColor = false,
    randomStaticArcColor = false,
    randomStarColor = false,
    shadowTrailColor = { r = 0, g = 0, b = 0, a = 0.4 },
    glowHollowness = 0,
    trailCount = 40,
    trailSpacing = 10,
    glowBelow = false,
    enableEmbers = false,
    randomSpringSeasonColor = true,
    cursorColor = { r = 1, g = 0.1921568627450981, b = 0.1568627450980392, a = 1 },
    trailFrameStrata = "HIGH",
    trailMovementEffect = 1,
    additionalEffects = 1,
    glowPulsingIntensity = 0.5,
    trailIntensity = 0.5,
    enableDirectionalOffset = false,
    trailTextureOpacity = 0,
    twinkleStarsColor = { r = 0.9, g = 0.95, b = 1, a = 1 },
    trailSizeStart = 1,
    trailInitialSeparation = 30,
    menuPosition = {
        x = 250.1666412353516,
        y = -87.33332061767578,
        point = "TOP",
        relativePoint = "TOP",
    },
    enableSmoke = false,
    chainSpacing = 1,
    glowIntensityFactor = 0.1,
    trailColor = { r = 0.2588235437870026, g = 0.4117647409439087, b = 0.1450980454683304, a = 1 },
    trailLayerSpacing = 0,
    randomSmokeColor = false,
    numTrails = 10,
    enableFire = false,
    trailSizeEnd = 21.4598445892334,
    cursorOffsetY = 45,
    trailOffsetY = 31,
    trailOffsetX = 26,
    randomShadowColor = false,
    enableTrails = true,
    enableStarEmbers = false,
    enableSmokeTrails = true,
    enableLightningSparks = false,
    enableSpringSeason = true,
    enableSpringSeasonTrails = true,
    enableFireTrails = false,
    connectTrails = true,
    randomTwinkleStarsColor = false,
    trailGlowIntensity = 1,
    pulseMin = 0.3,
    trailLayerCount = 1,
    trailUpdateMultiplier = 100,
    glowSize = 1.379332542419434,
                  }
    end
 
          -- Ghost_Sparkles
    if not EasyCursorTrailsDB.profiles["Ghost_Sparkles"] then
        EasyCursorTrailsDB.profiles["Ghost_Sparkles"] = {
    verticalScale = 2,
    trailColor = { r = 0.5137255191802979, g = 1, b = 0.06666667014360428, a = 1 },
    enableStaticArc = true,
    cursorColorEffect = 2,
    minimapPosition = { x = 0, y = 0 },
    horizontalScale = 1,
    enableStaticArcs = true,
    glowAboveCursor = false,
    randomLightningSparkColor = false,
    glowRadius = 0.1,
    glowColor = { r = 0.7176470588235294, g = 0.4196078431372549, b = 0.9568627450980393, a = 1 },
    numGlows = 30,
    trailRadius = 20,
    cursorOffsetX = 0,
    enableTrailShadows = true,
    glowThickness = 0.8,
    trailColorEffect = 9,
    pulsingSpeed = 10,
    trailDelay = 0,
    chainSegment = 10,
    disableGlowPulsing = false,
    cursorTexture = 32,
    enableStars = true,
    selectedCursorTextureName = "Yin_Yang_1",
    randomEmberColor = true,
    staticArcColor = { r = 1, g = 1, b = 1, a = 1 },
    enableTwinkleStars = false,
    enableSmokeEffect = false,
    patternGlowCount = 29,
    cursorFrameStrata = 4,
    trailTexture = 26,
    cursorSize = 10,
    glowIntensity = 1,
    randomFireColor = false,
    randomStaticArcColor = true,
    randomStarColor = true,
    shadowTrailColor = { r = 0, g = 0, b = 0, a = 0.4 },
    glowHollowness = 0,
    trailCount = 50,
    trailSpacing = 10,
    glowBelow = false,
    enableEmbers = true,
    randomSpringSeasonColor = false,
    cursorColor = { r = 0.5411764705882353, g = 0.9921568627450981, b = 1, a = 1 },
    trailFrameStrata = "HIGH",
    trailMovementEffect = 1,
    trailInitialSeparation = 30,
    glowPulsingIntensity = 0.5,
    trailIntensity = 0.5,
    enableLightningSpark = false,
    enableDirectionalOffset = false,
    trailTextureOpacity = 0.15,
    additionalEffects = 1,
    trailSizeStart = 5,
    twinkleStarsColor = { r = 0.9, g = 0.95, b = 1, a = 1 },
    menuPosition = {
        x = 250.1666412353516,
        y = -87.33332061767578,
        point = "TOP",
        relativePoint = "TOP",
    },
    enableSmoke = false,
    pulseMin = 0.3,
    glowIntensityFactor = 0.1,
    selectedGlowEffect = 22,
    trailLayerSpacing = 0,
    randomShadowColor = false,
    numTrails = 10,
    enableFire = false,
    randomSmokeColor = false,
    cursorOffsetY = 0,
    trailOffsetY = -28,
    trailOffsetX = -28,
    enableTrails = true,
    enableSpringSeasonTrails = false,
    enableSpringSeason = false,
    enableLightningSparks = false,
    enableSmokeTrails = false,
    enableStarEmbers = true,
    trailSizeEnd = 3,
    enableFireTrails = false,
    chainSpacing = 1,
    randomTwinkleStarsColor = false,
    trailGlowIntensity = 1,
    trailUpdateMultiplier = 80,
    trailLayerCount = 1,
    connectTrails = false,
    glowSize = 0.5,
                  }
    end

        -- Green Serpent
    if not EasyCursorTrailsDB.profiles["Green_Serpent"] then
        EasyCursorTrailsDB.profiles["Green_Serpent"] = {
    verticalScale = 2,
    trailColor = { r = 0.3764705882352941, g = 1, b = 0.08627450980392157, a = 1 },
    enableStaticArc = false,
    cursorColorEffect = 2,
    minimapPosition = { x = 0, y = 0 },
    horizontalScale = 1,
    enableStaticArcs = true,
    glowAboveCursor = false,
    randomLightningSparkColor = false,
    glowRadius = 0.1,
    glowColor = { r = 0.3764705882352941, g = 1, b = 0.08627450980392157, a = 1 },
    numGlows = 30,
    trailRadius = 20,
    cursorOffsetX = 0,
    enableTrailShadows = true,
    glowThickness = 0.8,
    trailColorEffect = 9,
    pulsingSpeed = 10,
    trailDelay = 0,
    chainSegment = 10,
    disableGlowPulsing = false,
    cursorTexture = 32,
    enableStars = true,
    selectedCursorTextureName = "Yin_Yang_1",
    randomEmberColor = false,
    staticArcColor = { r = 1, g = 1, b = 1, a = 1 },
    enableTwinkleStars = false,
    enableSmokeEffect = true,
    patternGlowCount = 29,
    cursorFrameStrata = "HIGH",
    trailTexture = 1,
    cursorSize = 40,
    glowIntensity = 1,
    randomFireColor = false,
    randomStaticArcColor = false,
    randomStarColor = false,
    shadowTrailColor = { r = 0, g = 0, b = 0, a = 0.4 },
    glowHollowness = 0,
    trailCount = 40,
    trailSpacing = 10,
    glowBelow = false,
    enableEmbers = true,
    randomSpringSeasonColor = false,
    cursorColor = { r = 0.5411764705882353, g = 0.9921568627450981, b = 1, a = 1 },
    trailFrameStrata = "HIGH",
    trailTextureOpacity = 1,
    trailMovementEffect = 1,
    trailInitialSeparation = 36,
    connectTrails = false,
    glowPulsingIntensity = 0.5,
    additionalEffects = 1,
    trailIntensity = 0.5,
    enableLightningSpark = false,
    lightningSparkColor = { r = 0.04313725605607033, g = 1, b = 0.4470588564872742, a = 1 },
    enableSmoke = true,
    trailUpdateMultiplier = 100,
    trailSizeStart = 14,
    twinkleStarsColor = { r = 0.9, g = 0.95, b = 1, a = 1 },
    menuPosition = {
        x = 250.1666412353516,
        y = -87.33332061767578,
        point = "TOP",
        relativePoint = "TOP",
    },
    pulseMin = 0.3,
    randomShadowColor = false,
    chainSpacing = 1,
    randomSmokeColor = false,
    trailLayerSpacing = 0,
    enableTrails = true,
    numTrails = 10,
    enableFire = false,
    trailSizeEnd = 1,
    cursorOffsetY = 0,
    trailOffsetY = -1,
    enableSmokeTrails = false,
    enableSpringSeasonTrails = false,
    enableSpringSeason = false,
    enableLightningSparks = false,
    trailOffsetX = -37,
    enableStarEmbers = false,
    selectedGlowEffect = 5,
    glowIntensityFactor = 0.4999999701976776,
    enableFireTrails = false,
    emberColor = { r = 0.3764706254005432, g = 1, b = 0.08627451211214066, a = 0.8 },
    randomTwinkleStarsColor = false,
    trailGlowIntensity = 1,
    enableDirectionalOffset = false,
    trailLayerCount = 1,
    smokeColor = { r = 0.9372549653053284, g = 1, b = 0.09019608050584793, a = 1 },
    glowSize = 0.5
                }
    end
   
    -- Golden_Dragon
    if not EasyCursorTrailsDB.profiles["Golden_Dragon"] then
        EasyCursorTrailsDB.profiles["Golden_Dragon"] = {
    enableTrails = true,
    selectedGlowEffect = 5,
    enableStaticArc = false,
    cursorColorEffect = 5,
    minimapPosition = { x = 0, y = 0 },
    horizontalScale = 1,
    enableStaticArcs = false,
    glowAboveCursor = false,
    randomLightningSparkColor = false,
    glowRadius = 0.1,
    layerCount = 1,
    glowColor = { r = 1, g = 0.792156862745098, b = 0.2901960784313726, a = 1 },
    numGlows = 30,
    trailRadius = 20,
    cursorOffsetX = 0,
    enableTrailShadows = true,
    glowThickness = 0.6,
    trailColorEffect = 10,
    enableSmoke = false,
    trailDelay = 0,
    chainSegment = 10,
    disableGlowPulsing = false,
    trailUpdateMultiplier = 100,
    enableStars = true,
    selectedCursorTextureName = "Circle_focus_1",
    randomEmberColor = false,
    staticArcColor = { r = 0.7960785031318665, g = 0.6313725709915161, b = 0.2352941334247589, a = 0.8 },
    enableTwinkleStars = true,
    enableSmokeEffect = false,
    patternGlowCount = 29,
    cursorFrameStrata = "HIGH",
    trailTexture = 1,
    cursorSize = 40,
    glowIntensity = 1,
    randomFireColor = false,
    randomStaticArcColor = false,
    randomStarColor = false,
    shadowTrailColor = { r = 0, g = 0, b = 0, a = 0.4 },
    glowHollowness = 0,
    trailCount = 50,
    trailSpacing = 10,
    glowBelow = false,
    enableEmbers = true,
    randomSpringSeasonColor = false,
    cursorColor = { r = 0.796078431372549, g = 0.6313725490196078, b = 0.207843137254902, a = 1 },
    trailFrameStrata = "HIGH",
    trailTextureOpacity = 1,
    trailMovementEffect = 1,
    trailInitialSeparation = 36,
    smokeColor = { r = 1, g = 1, b = 1, a = 1 },
    glowPulsingIntensity = 0.5,
    trailCountSlider = 25,
    trailIntensity = 0.5,
    additionalEffects = 1,
    enableDirectionalOffset = false,
    connectTrails = true,
    enableSpringSeasonTrails = false,
    trailSizeStart = 18,
    enableStarEmbers = true,
    menuPosition = {
        x = -244.833,
        y = 72.4999,
        point = "RIGHT",
        relativePoint = "RIGHT",
    },
    trailColor = { r = 0.796078431372549, g = 0.6313725490196078, b = 0.207843137254902, a = 1 },
    glowIntensityFactor = 0.4999999701976776,
    enableLightningSparks = false,
    randomSmokeColor = false,
    trailLayerSpacing = 0,
    randomShadowColor = false,
    numTrails = 10,
    enableFire = false,
    trailOffsetX = -39,
    cursorOffsetY = 0,
    trailOffsetY = -1,
    enableSmokeTrails = false,
    twinkleStarsColor = { r = 0.7960785031318665, g = 0.6313725709915161, b = 0.207843154668808, a = 1 },
    pulseMin = 0.3,
    verticalScale = 2,
    trailSizeEnd = 1,
    cursorTexture = 35,
    pulsingSpeed = 10,
    chainSpacing = 1,
    enableFireTrails = false,
    emberColor = { r = 0.7960785031318665, g = 0.6313725709915161, b = 0.2352941334247589, a = 0.8 },
    randomTwinkleStarsColor = false,
    trailGlowIntensity = 1,
    enableSpringSeason = false,
    trailLayerCount = 1,
    starColor = { r = 0.7960785031318665, g = 0.6313725709915161, b = 0.207843154668808, a = 1 },
    glowSize = 0.6
        }
    end

    
      -- Echo
    if not EasyCursorTrailsDB.profiles["Echo"] then
        EasyCursorTrailsDB.profiles["Echo"] = {
    verticalScale = 2,
    selectedGlowEffect = 5,
    enableStaticArc = false,
    cursorColorEffect = 6,
    minimapPosition = { x = 0, y = 0 },
    horizontalScale = 1,
    enableStaticArcs = true,
    glowAboveCursor = false,
    randomLightningSparkColor = false,
    glowRadius = 0.14,
    glowColor = { r = 1, g = 0.4117647058823529, b = 0.0392156862745098, a = 1 },
    numGlows = 30,
    trailRadius = 20,
    cursorOffsetX = 0,
    enableTrailShadows = true,
    glowThickness = 0.5,
    trailColorEffect = 12,
    pulsingSpeed = 10,
    trailDelay = 0,
    chainSegment = 10,
    disableGlowPulsing = false,
    cursorTexture = 12,
    enableStars = true,
    selectedCursorTextureName = "Circle4",
    randomEmberColor = false,
    staticArcColor = { r = 1, g = 1, b = 1, a = 1 },
    enableTwinkleStars = false,
    enableSmokeEffect = false,
    patternGlowCount = 29,
    cursorFrameStrata = "HIGH",
    trailTexture = 13,
    cursorSize = 40,
    glowIntensity = 0.8,
    randomFireColor = false,
    randomStaticArcColor = false,
    randomStarColor = false,
    shadowTrailColor = { r = 0, g = 0, b = 0, a = 0.4 },
    glowHollowness = 0,
    trailCount = 35,
    trailSpacing = 10,
    glowBelow = false,
    enableEmbers = false,
    randomSpringSeasonColor = false,
    cursorColor = { r = 1, g = 0.4117647058823529, b = 0.0392156862745098, a = 1 },
    trailFrameStrata = "HIGH",
    trailMovementEffect = 1,
    additionalEffects = 1,
    glowPulsingIntensity = 0.5,
    enableLightningSpark = true,
    trailIntensity = 0.5,
    lightningSparkColor = { r = 1, g = 0.4117647409439087, b = 0.04313725605607033, a = 1 },
    enableDirectionalOffset = true,
    twinkleStarsColor = { r = 0.9, g = 0.95, b = 1, a = 1 },
    trailInitialSeparation = 30,
    trailSizeStart = 18,
    enableSmoke = false,
    menuPosition = {
        x = 250.1666412353516,
        y = -87.33332061767578,
        point = "TOP",
        relativePoint = "TOP",
    },
    pulseMin = 0.3,
    glowIntensityFactor = 0.34,
    chainSpacing = 1,
    connectTrails = true,
    trailLayerSpacing = 0,
    randomSmokeColor = false,
    numTrails = 10,
    enableFire = false,
    enableSpringSeasonTrails = false,
    cursorOffsetY = 0,
    trailSizeEnd = 1,
    trailOffsetX = -33,
    enableSpringSeason = false,
    enableLightningSparks = true,
    enableSmokeTrails = true,
    enableStarEmbers = false,
    enableTrails = true,
    trailOffsetY = 1,
    randomShadowColor = false,
    enableFireTrails = false,
    trailColor = { r = 1, g = 1, b = 1, a = 1 },
    randomTwinkleStarsColor = false,
    trailGlowIntensity = 1,
    trailUpdateMultiplier = 100,
    trailLayerCount = 1,
    trailTextureOpacity = 0.42,
    glowSize = 0.7,
            }
    end

      -- Chain
    if not EasyCursorTrailsDB.profiles["Chain"] then
        EasyCursorTrailsDB.profiles["Chain"] = {
    verticalScale = 2,
    trailColor = { r = 0.71764706, g = 0.25490196, b = 0.05490196, a = 1 },
    enableStaticArc = false,
    cursorColorEffect = 5,
    connectTrails = true,
    horizontalScale = 1,
    enableStaticArcs = true,
    glowAboveCursor = true,
    randomLightningSparkColor = false,
    glowRadius = 0.15,
    layerCount = 1,
    glowColor = { r = 0.7176470588235294, g = 0.2470588235294118, b = 0.0392156862745098, a = 1 },
    numGlows = 30,
    trailRadius = 20,
    cursorOffsetX = 0,
    enableTrailShadows = true,
    glowThickness = 0.5,
    trailColorEffect = 9,
    pulsingSpeed = 10,
    trailDelay = 0,
    chainSegment = 20,
    disableGlowPulsing = false,
    cursorTexture = 35,
    enableStars = true,
    selectedCursorTextureName = "Circle_focus_1",
    randomEmberColor = false,
    staticArcColor = { r = 1, g = 1, b = 1, a = 1 },
    enableTwinkleStars = false,
    enableSmokeEffect = true,
    patternGlowCount = 29,
    cursorFrameStrata = "HIGH",
    trailTexture = 46,
    cursorSize = 35,
    glowIntensity = 1,
    randomFireColor = false,
    randomStaticArcColor = false,
    randomStarColor = false,
    shadowTrailColor = { r = 0, g = 0, b = 0, a = 0.4 },
    glowHollowness = 0,
    trailCount = 30,
    trailSpacing = 20,
    glowBelow = false,
    enableEmbers = true,
    randomSpringSeasonColor = false,
    cursorColor = { r = 1, g = 0.6470588235294118, b = 0.4627450980392157, a = 1 },
    trailFrameStrata = "HIGH",
    trailMovementEffect = 1,
    additionalEffects = 0,
    glowPulsingIntensity = 0.5,
    trailIntensity = 0.5,
    trailTextureOpacity = 1,
    enableDirectionalOffset = false,
    smokeColor = { r = 0.1294117718935013, g = 0.1215686351060867, b = 0.1176470667123795, a = 0.4 },
    minimapPosition = { x = 0, y = 0 },
    trailSizeStart = 19,
    randomSmokeColor = false,
    menuPosition = {
        x = -20,
        y = -5,
        point = "CENTER",
        relativePoint = "CENTER",
    },
    selectedGlowEffect = 5,
    chainSpacing = 1,
    glowIntensityFactor = 1,
    enableSpringSeasonTrails = false,
    trailLayerSpacing = 0,
    trailUpdateMultiplier = 50,
    numTrails = 10,
    enableFire = false,
    trailSizeEnd = 19,
    cursorOffsetY = 0,
    trailOffsetY = 1,
    trailOffsetX = -31,
    enableTrails = true,
    enableSmoke = true,
    pulseMin = 0.3,
    randomShadowColor = false,
    enableStarEmbers = false,
    enableSmokeTrails = false,
    enableLightningSparks = false,
    enableFireTrails = false,
    enableSpringSeason = false,
    randomTwinkleStarsColor = false,
    trailGlowIntensity = 1,
    trailInitialSeparation = 30,
    trailLayerCount = 1,
    twinkleStarsColor = { r = 0.937255, g = 1, b = 0.97647065, a = 1 },
    glowSize = 0.8
        }
    end

     -- Pink_Serpent
    if not EasyCursorTrailsDB.profiles["Pink_Serpent"] then
        EasyCursorTrailsDB.profiles["Pink_Serpent"] = {

    verticalScale = 2,
    trailColor = { r = 0.7215686274509804, g = 0.1019607843137255, b = 0.9294117647058824, a = 1 },
    enableStaticArc = false,
    cursorColorEffect = 2,
    minimapPosition = { x = 0, y = 0 },
    horizontalScale = 1,
    enableStaticArcs = true,
    glowAboveCursor = false,
    randomLightningSparkColor = false,
    glowRadius = 0.1,
    glowColor = { r = 0.7176470588235294, g = 0.4196078431372549, b = 0.9568627450980393, a = 1 },
    numGlows = 30,
    trailRadius = 20,
    cursorOffsetX = 0,
    enableTrailShadows = true,
    glowThickness = 0.8,
    trailColorEffect = 10,
    pulsingSpeed = 10,
    trailDelay = 0,
    chainSegment = 10,
    disableGlowPulsing = false,
    cursorTexture = 32,
    enableStars = true,
    selectedCursorTextureName = "Yin_Yang_1",
    randomEmberColor = false,
    staticArcColor = { r = 1, g = 1, b = 1, a = 0.8 },
    enableTwinkleStars = true,
    enableSmokeEffect = false,
    patternGlowCount = 29,
    cursorFrameStrata = "HIGH",
    trailTexture = 1,
    cursorSize = 40,
    glowIntensity = 1,
    randomFireColor = false,
    randomStaticArcColor = false,
    randomStarColor = false,
    shadowTrailColor = { r = 0, g = 0, b = 0, a = 0.4 },
    glowHollowness = 0,
    trailCount = 50,
    trailSpacing = 10,
    glowBelow = false,
    enableEmbers = true,
    randomSpringSeasonColor = false,
    cursorColor = { r = 0.5411764705882353, g = 0.9921568627450981, b = 1, a = 1 },
    trailFrameStrata = "HIGH",
    trailMovementEffect = 1,
    trailInitialSeparation = 36,
    smokeColor = { r = 1, g = 1, b = 1, a = 1 },
    glowPulsingIntensity = 0.5,
    starColor = { r = 0.8901961445808411, g = 0.6313725709915161, b = 0.8862745761871338, a = 1 },
    trailIntensity = 0.5,
    connectTrails = true,
    enableDirectionalOffset = false,
    trailUpdateMultiplier = 100,
    randomShadowColor = false,
    trailSizeStart = 15,
    enableSmoke = false,
    menuPosition = {
        x = 250.1666412353516,
        y = -87.33332061767578,
        point = "TOP",
        relativePoint = "TOP",
    },
    twinkleStarsColor = { r = 0.9215686917304993, g = 0.6980392336845398, b = 0.8235294818878174, a = 1 },
    pulseMin = 0.3,
    glowIntensityFactor = 0.2999999821186066,
    randomSmokeColor = false,
    trailLayerSpacing = 0,
    enableTrails = true,
    numTrails = 10,
    enableFire = false,
    trailOffsetY = -4,
    cursorOffsetY = 0,
    trailSizeEnd = 1,
    trailOffsetX = -36,
    enableSpringSeasonTrails = false,
    enableSpringSeason = false,
    enableLightningSparks = false,
    enableSmokeTrails = false,
    enableStarEmbers = true,
    selectedGlowEffect = 5,
    chainSpacing = 1,
    enableFireTrails = false,
    emberColor = { r = 0.9215686917304993, g = 0.615686297416687, b = 0.8352941870689392, a = 0.8 },
    randomTwinkleStarsColor = false,
    trailGlowIntensity = 1,
    additionalEffects = 1,
    trailLayerCount = 1,
    trailTextureOpacity = 0.8,
    glowSize = 0.5

        }
    end



     -- Super Charge
    if not EasyCursorTrailsDB.profiles["Super_Charge"] then
        EasyCursorTrailsDB.profiles["Super_Charge"] = {
    verticalScale = 2,
    trailColor = { r = 0.4823529720306397, g = 0.9490196704864502, b = 1, a = 1 },
    enableStaticArc = false,
    cursorColorEffect = 6,
    minimapPosition = { x = 0, y = 0 },
    horizontalScale = 1,
    enableStaticArcs = true,
    glowAboveCursor = false,
    randomLightningSparkColor = false,
    glowRadius = 0.14,
    glowColor = { r = 0.0196078431372549, g = 0.7176470588235294, b = 0.7098039215686275, a = 1 },
    numGlows = 30,
    trailRadius = 20,
    cursorOffsetX = 0,
    enableTrailShadows = true,
    glowThickness = 0.9,
    trailColorEffect = 9,
    pulsingSpeed = 10,
    trailDelay = 0,
    chainSegment = 11,
    disableGlowPulsing = false,
    cursorTexture = 31,
    enableStars = true,
    selectedCursorTextureName = "Yin_Yang_v1",
    randomEmberColor = false,
    staticArcColor = { r = 0.1176470667123795, g = 0.1176470667123795, b = 0.1176470667123795, a = 1 },
    enableTwinkleStars = false,
    enableSmokeEffect = true,
    patternGlowCount = 29,
    cursorFrameStrata = 4,
    trailTexture = 15,
    cursorSize = 35,
    useMufflerSmoke = true,
    glowIntensity = 1,
    randomFireColor = false,
    randomStaticArcColor = false,
    randomStarColor = false,
    shadowTrailColor = { r = 0, g = 0, b = 0, a = 0.4 },
    glowHollowness = 0,
    trailCount = 40,
    trailSpacing = 11,
    glowBelow = false,
    enableEmbers = true,
    randomSpringSeasonColor = false,
    cursorColor = { r = 0.5372549019607843, g = 0.9882352941176471, b = 1, a = 1 },
    trailTextureOpacity = 0.06,
    trailFrameStrata = "HIGH",
    starColor = { r = 0.08627451, g = 0.92549026, b = 0.8588236, a = 1 },
    trailMovementEffect = 1,
    trailInitialSeparation = 36,
    pulseMin = 0.3,
    glowPulsingIntensity = 0.5,
    enableLightningSpark = true,
    trailIntensity = 0.5,
    enableDirectionalOffset = false,
    lightningSparkColor = { r = 0.02352941408753395, g = 0.7176470756530762, b = 0.6901960968971252, a = 1 },
    randomShadowColor = false,
    enableSmoke = true,
    trailSizeStart = 4,
    trailUpdateMultiplier = 100,
    menuPosition = {
        x = 250.1666412353516,
        y = -87.33332061767578,
        point = "TOP",
        relativePoint = "TOP",
    },
    selectedGlowEffect = 5,
    randomSmokeColor = false,
    glowIntensityFactor = 0.3,
    enableTrails = true,
    trailLayerSpacing = 0,
    enableSpringSeasonTrails = false,
    numTrails = 10,
    enableFire = false,
    trailOffsetY = 2,
    cursorOffsetY = 0,
    trailSizeEnd = 8,
    enableSmokeTrails = false,
    enableSpringSeason = false,
    enableLightningSparks = true,
    trailOffsetX = -33,
    enableStarEmbers = false,
    chainSpacing = 1,
    additionalEffects = 1,
    twinkleStarsColor = { r = 0.9, g = 0.95, b = 1, a = 1 },
    enableFireTrails = false,
    emberColor = { r = 0.05098039656877518, g = 0.7568628191947937, b = 1, a = 0.8 },
    randomTwinkleStarsColor = false,
    trailGlowIntensity = 1,
    connectTrails = true,
    trailLayerCount = 1,
    smokeColor = { r = 0.1333333402872086, g = 0.1882353127002716, b = 0.2000000178813934, a = 0.4 },
    glowSize = 0.5,

        }
    end


    -- Silver_Dragon
    if not EasyCursorTrailsDB.profiles["Silver_Dragon"] then
        EasyCursorTrailsDB.profiles["Silver_Dragon"] = {
    enableTrails = true,
    selectedGlowEffect = 19,
    enableStaticArc = false,
    cursorColorEffect = 6,
    connectTrails = true,
    horizontalScale = 1,
    enableStaticArcs = false,
    glowAboveCursor = false,
    randomLightningSparkColor = false,
    glowRadius = 0.1,
    layerCount = 1,
    glowColor = { r = 0.7529411764705882, g = 0.7529411764705882, b = 0.7529411764705882, a = 1 },
    numGlows = 30,
    trailRadius = 20,
    cursorOffsetX = 0,
    enableTrailShadows = true,
    glowThickness = 0.6,
    trailColorEffect = 10,
    enableSmoke = false,
    trailDelay = 0,
    chainSegment = 10,
    disableGlowPulsing = false,
    cursorTexture = 32,
    enableStars = true,
    selectedCursorTextureName = "Yin_Yang_1",
    randomEmberColor = false,
    staticArcColor = { r = 1, g = 1, b = 1, a = 1 },
    enableTwinkleStars = true,
    enableSmokeEffect = false,
    patternGlowCount = 29,
    twinkleStarsColor = { r = 0.9, g = 0.95, b = 1, a = 1 },
    trailTexture = 1,
    cursorSize = 45,
    glowIntensity = 1,
    randomFireColor = false,
    randomStaticArcColor = false,
    randomStarColor = false,
    shadowTrailColor = { r = 0, g = 0, b = 0, a = 0.4 },
    glowHollowness = 0,
    trailCount = 50,
    trailSpacing = 10,
    glowBelow = false,
    enableEmbers = true,
    randomSpringSeasonColor = false,
    cursorColor = { r = 1, g = 0.4627450980392157, b = 0.0196078431372549, a = 1 },
    trailFrameStrata = "HIGH",
    trailMovementEffect = 1,
    trailInitialSeparation = 36,
    trailTextureOpacity = 1,
    glowPulsingIntensity = 0.5,
    trailUpdateMultiplier = 100,
    trailIntensity = 0.5,
    additionalEffects = 1,
    enableDirectionalOffset = false,
    enableSpringSeasonTrails = false,
    enableSpringSeason = false,
    trailSizeStart = 18,
    enableStarEmbers = true,
    menuPosition = {
        x = -244.833,
        y = 72.4999,
        point = "RIGHT",
        relativePoint = "RIGHT",
    },
    chainSpacing = 1,
    glowIntensityFactor = 0.2999999821186066,
    enableLightningSparks = false,
    minimapPosition = { x = 0, y = 0 },
    trailLayerSpacing = 0,
    trailColor = { r = 0.9764706492424011, g = 0.9764706492424011, b = 0.9764706492424011, a = 1 },
    numTrails = 10,
    enableFire = false,
    pulsingSpeed = 10,
    cursorOffsetY = 0,
    trailOffsetY = -1,
    trailOffsetX = -34,
    cursorFrameStrata = "HIGH",
    verticalScale = 2,
    pulseMin = 0.3,
    randomShadowColor = false,
    enableSmokeTrails = false,
    trailSizeEnd = 1,
    randomSmokeColor = false,
    enableFireTrails = false,
    emberColor = { r = 0.8274510502815247, g = 0.8274510502815247, b = 0.8274510502815247, a = 0.8 },
    randomTwinkleStarsColor = false,
    trailGlowIntensity = 1,
    trailCountSlider = 25,
    trailLayerCount = 1,
    starColor = { r = 0.8274510502815247, g = 0.8274510502815247, b = 0.8274510502815247, a = 1 },
    glowSize = 0.6
        }
    end

    -- Burning_Serpent
    if not EasyCursorTrailsDB.profiles["Burning_Serpent"] then
        EasyCursorTrailsDB.profiles["Burning_Serpent"] = {
     verticalScale = 2,
    trailColor = { r = 1, g = 0.1568627506494522, b = 0.0470588281750679, a = 1 },
    enableStaticArc = false,
    cursorColorEffect = 5,
    connectTrails = true,
    enableFireEffect = true,
    horizontalScale = 1,
    enableStaticArcs = false,
    glowAboveCursor = false,
    randomLightningSparkColor = false,
    glowRadius = 0.1,
    glowColor = { r = 1, g = 0.2313725490196079, b = 0.07450980392156863, a = 1 },
    numGlows = 30,
    trailRadius = 20,
    cursorOffsetX = 0,
    enableTrailShadows = true,
    glowThickness = 0.6,
    trailColorEffect = 10,
    enableSmoke = true,
    trailDelay = 0,
    chainSegment = 10,
    disableGlowPulsing = false,
    cursorTexture = 32,
    enableStars = true,
    selectedCursorTextureName = "Yin_Yang_1",
    randomEmberColor = false,
    staticArcColor = { r = 1, g = 1, b = 1, a = 1 },
    enableTwinkleStars = false,
    enableSmokeEffect = true,
    patternGlowCount = 29,
    cursorFrameStrata = "HIGH",
    trailTexture = 1,
    cursorSize = 40,
    glowIntensity = 1,
    randomFireColor = false,
    randomStaticArcColor = false,
    randomStarColor = false,
    shadowTrailColor = { r = 0, g = 0, b = 0, a = 0.4 },
    glowHollowness = 0,
    trailCount = 50,
    trailSpacing = 10,
    glowBelow = false,
    enableEmbers = true,
    randomSpringSeasonColor = false,
    cursorColor = { r = 1, g = 0.2313725490196079, b = 0.07450980392156863, a = 1 },
    trailFrameStrata = "HIGH",
    enableLightningSpark = false,
    trailMovementEffect = 1,
    trailInitialSeparation = 36,
    smokeColor = { r = 0.1, g = 0.1, b = 0.1, a = 0.4 },
    glowPulsingIntensity = 0.5,
    selectedGlowEffect = 1,
    trailIntensity = 0.5,
    trailUpdateMultiplier = 100,
    enableDirectionalOffset = false,
    fireColor = { r = 1, g = 0.2392157, b = 0.07843138, a = 1 },
    minimapPosition = { x = 0, y = 0 },
    trailSizeStart = 15,
    pulseMin = 0.3,
    menuPosition = {
        x = -244.833,
        y = 72.4999,
        point = "RIGHT",
        relativePoint = "RIGHT",
    },
    pulsingSpeed = 10,
    additionalEffects = 1,
    glowIntensityFactor = 0.2999999821186066,
    enableLightningSparks = false,
    trailLayerSpacing = 0,
    trailOffsetY = -30,
    numTrails = 10,
    enableFire = true,
    enableSmokeTrails = true,
    cursorOffsetY = 0,
    trailSizeEnd = 1,
    trailOffsetX = -32,
    enableSpringSeason = false,
    enableSpringSeasonTrails = false,
    enableStarEmbers = false,
    randomSmokeColor = false,
    randomShadowColor = false,
    chainSpacing = 1,
    twinkleStarsColor = { r = 0.88627458, g = 0.34509805, b = 0.13333334, a = 1 },
    enableFireTrails = false,
    emberColor = { r = 0.7215686440467834, g = 0.4509804248809815, b = 0.2000000178813934, a = 0.8 },
    randomTwinkleStarsColor = false,
    trailGlowIntensity = 1,
    trailTextureOpacity = 1,
    trailLayerCount = 1,
    enableTrails = true,
    glowSize = 0.6
        }
    end

    -- Rainbow_Comet
    if not EasyCursorTrailsDB.profiles["Rainbow_Comet"] then
        EasyCursorTrailsDB.profiles["Rainbow_Comet"] = {
        verticalScale = 2,
    selectedGlowEffect = 5,
    enableStaticArc = true,
    cursorColorEffect = 6,
    connectTrails = true,
    horizontalScale = 1,
    enableStaticArcs = true,
    glowAboveCursor = false,
    randomLightningSparkColor = false,
    glowRadius = 0.1,
    layerCount = 1,
    glowColor = { r = 0.7176470588235294, g = 0.4196078431372549, b = 0.9568627450980393, a = 1 },
    numGlows = 30,
    trailRadius = 20,
    cursorOffsetX = 0,
    enableTrailShadows = true,
    glowThickness = 0.8,
    trailColorEffect = 11,
    pulsingSpeed = 10,
    enableSpringSeason = false,
    chainSegment = 25,
    disableGlowPulsing = false,
    cursorTexture = 32,
    enableStars = true,
    selectedCursorTextureName = "Yin_Yang_1",
    randomEmberColor = false,
    staticArcColor = { r = 1, g = 1, b = 1, a = 0.8 },
    pulseStep = 0.02,
    enableTwinkleStars = false,
    enableSmokeEffect = true,
    patternGlowCount = 21,
    cursorFrameStrata = "HIGH",
    trailTexture = 3,
    cursorSize = 45,
    glowIntensity = 1,
    randomFireColor = false,
    randomStaticArcColor = true,
    randomStarColor = true,
    shadowTrailColor = { r = 0, g = 0, b = 0, a = 0.4 },
    glowHollowness = 0,
    trailCount = 20,
    randomSmokeColor = true,
    glowBelow = false,
    enableEmbers = false,
    randomSpringSeasonColor = false,
    cursorColor = { r = 0.5411764705882353, g = 0.9921568627450981, b = 1, a = 1 },
    trailTextureOpacity = 1,
    enableLightningSpark = false,
    trailFrameStrata = "HIGH",
    enableTrails = true,
    trailMovementEffect = 1,
    additionalEffects = 1,
    trailCountSlider = 25,
    glowPulsingIntensity = 0.5,
    randomShadowColor = false,
    trailIntensity = 0.5,
    pulseMin = 0.3,
    enableDirectionalOffset = false,
    trailInitialSeparation = 36,
    enableSpringSeasonTrails = false,
    trailSizeStart = 18,
    twinkleStarsColor = { r = 0.9, g = 0.95, b = 1, a = 1 },
    menuPosition = {
        x = 250.1666412353516,
        y = -87.33332061767578,
        point = "TOP",
        relativePoint = "TOP",
    },
    trailSpacing = 30,
    trailColor = { r = 1, g = 0.4627451300621033, b = 0.02745098248124123, a = 1 },
    chainSpacing = 1,
    enableSmoke = true,
    trailLayerSpacing = 0,
    enableStarEmbers = true,
    numTrails = 10,
    enableFire = false,
    enableSmokeTrails = false,
    cursorOffsetY = 0,
    trailOffsetY = -1,
    trailOffsetX = -36,
    trailUpdateMultiplier = 100,
    trailSizeEnd = 1,
    pulseMax = 1,
    glowIntensityFactor = 0.2999999821186066,
    enableLightningSparks = false,
    enableFireTrails = false,
    emberColor = { r = 0.8274510502815247, g = 0.8274510502815247, b = 0.8274510502815247, a = 0.8 },
    randomTwinkleStarsColor = false,
    trailGlowIntensity = 1,
    trailDelay = 0,
    trailLayerCount = 1,
    minimapPosition = { x = 0, y = 0 },
    glowSize = 0.5
        }
    end

    -- Fairy
    if not EasyCursorTrailsDB.profiles["Fairy"] then
        EasyCursorTrailsDB.profiles["Fairy"] = {
   enableTrails = true,
    selectedGlowEffect = 20,
    enableStaticArc = false,
    cursorColorEffect = 6,
    connectTrails = true,
    horizontalScale = 1,
    trailCountSlider = 15,
    glowAboveCursor = false,
    randomLightningSparkColor = false,
    glowRadius = 0.15,
    layerCount = 50,
    glowColor = { r = 1, g = 0.8431372549019608, b = 0, a = 1 },
    numGlows = 30,
    trailRadius = 20,
    cursorOffsetX = 52,
    enableTrailShadows = false,
    glowThickness = 2,
    trailColorEffect = 10,
    pulsingSpeed = 1,
    trailDelay = 0,
    chainSegment = 100,
    disableGlowPulsing = false,
    trailUpdateMultiplier = 100,
    enableStars = true,
    selectedCursorTextureName = "Fairy_Left_1_Hovering",
    randomEmberColor = true,
    staticArcColor = { r = 0.9019608497619629, g = 0.7882353663444519, b = 0, a = 1 },
    enableTwinkleStars = true,
    enableSmokeEffect = false,
    patternGlowCount = 21,
    twinkleStarsColor = { r = 0.9, g = 0.95, b = 1, a = 1 },
    trailTexture = 19,
    cursorSize = 100,
    glowIntensity = 0.1,
    randomFireColor = false,
    randomStaticArcColor = false,
    randomStarColor = false,
    shadowTrailColor = { r = 0, g = 0, b = 0, a = 0.4 },
    glowHollowness = 0,
    trailCount = 10,
    trailSpacing = 100,
    glowBelow = false,
    enableEmbers = true,
    randomSpringSeasonColor = false,
    cursorColor = { r = 1, g = 0.8431372549019608, b = 0, a = 1 },
    smokeColor = { r = 1, g = 0.8352941870689392, b = 0.09019608050584793, a = 1 },
    trailFrameStrata = "HIGH",
    trailTextureOpacity = 1,
    trailMovementEffect = 1,
    trailInitialSeparation = 40,
    starColor = { r = 0.9019608497619629, g = 0.7882353663444519, b = 0, a = 1 },
    glowPulsingIntensity = 0.5,
    additionalEffects = 1,
    trailIntensity = 0.5,
    enableSpringSeason = false,
    enableDirectionalOffset = false,
    enableStaticArcs = true,
    enableSpringSeasonTrails = false,
    trailSizeStart = 4,
    enableStarEmbers = true,
    menuPosition = {
        x = -244.833,
        y = 72.4999,
        point = "RIGHT",
        relativePoint = "RIGHT",
    },
    randomShadowColor = false,
    chainSpacing = 1,
    enableLightningSparks = false,
    pulseMin = 0.3,
    trailLayerSpacing = 55,
    trailSizeEnd = 3,
    numTrails = 10,
    enableFire = false,
    trailOffsetX = 53,
    cursorOffsetY = 32,
    trailOffsetY = 35,
    enableSmokeTrails = false,
    verticalScale = 2,
    cursorFrameStrata = 4,
    enableSmoke = false,
    minimapPosition = { x = 0, y = 0 },
    trailColor = { r = 1, g = 0.8431373238563538, b = 0, a = 1 },
    glowIntensityFactor = 0.1,
    randomSmokeColor = false,
    enableFireTrails = false,
    emberColor = { r = 0.9019608497619629, g = 0.7882353663444519, b = 0, a = 0.8 },
    randomTwinkleStarsColor = false,
    trailGlowIntensity = 1,
    cursorTexture = 37,
    trailLayerCount = 4,
    enableLightningSpark = false,
    glowSize = 1,
        }
    end


      -- Blue_Serpent
    if not EasyCursorTrailsDB.profiles["Blue_Serpent"] then
        EasyCursorTrailsDB.profiles["Blue_Serpent"] = {
           verticalScale = 2,
    trailColor = { r = 0, g = 1, b = 1, a = 1 },
    enableStaticArc = false,
    cursorColorEffect = 2,
    minimapPosition = { x = 0, y = 0 },
    horizontalScale = 1,
    enableStaticArcs = true,
    glowAboveCursor = false,
    randomLightningSparkColor = false,
    glowRadius = 0.1,
    glowColor = { r = 0, g = 1, b = 1, a = 1 },
    numGlows = 30,
    trailRadius = 20,
    cursorOffsetX = 0,
    enableTrailShadows = true,
    glowThickness = 0.8,
    trailColorEffect = 10,
    pulsingSpeed = 10,
    trailDelay = 0,
    chainSegment = 10,
    disableGlowPulsing = false,
    cursorTexture = 32,
    enableStars = true,
    selectedCursorTextureName = "Yin_Yang_1",
    randomEmberColor = false,
    staticArcColor = { r = 1, g = 1, b = 1, a = 0.8 },
    enableTwinkleStars = true,
    enableSmokeEffect = false,
    patternGlowCount = 29,
    cursorFrameStrata = "HIGH",
    trailTexture = 1,
    cursorSize = 40,
    glowIntensity = 1,
    randomFireColor = false,
    randomStaticArcColor = false,
    randomStarColor = false,
    shadowTrailColor = { r = 0, g = 0, b = 0, a = 0.4 },
    glowHollowness = 0,
    trailCount = 50,
    trailSpacing = 10,
    glowBelow = false,
    enableEmbers = true,
    randomSpringSeasonColor = false,
    cursorColor = { r = 0.5411764705882353, g = 0.9921568627450981, b = 1, a = 1 },
    trailFrameStrata = "HIGH",
    trailMovementEffect = 1,
    trailInitialSeparation = 36,
    glowPulsingIntensity = 0.5,
    connectTrails = true,
    trailIntensity = 0.5,
    starColor = { r = 0, g = 1, b = 0.9411765336990356, a = 1 },
    enableDirectionalOffset = false,
    randomShadowColor = false,
    trailTextureOpacity = 1,
    trailSizeStart = 15,
    trailUpdateMultiplier = 100,
    menuPosition = {
        x = 250.1666412353516,
        y = -87.33332061767578,
        point = "TOP",
        relativePoint = "TOP",
    },
    twinkleStarsColor = { r = 1, g = 1, b = 0.9568628072738647, a = 1 },
    pulseMin = 0.3,
    glowIntensityFactor = 0.2999999821186066,
    chainSpacing = 1,
    trailLayerSpacing = 0,
    selectedGlowEffect = 5,
    numTrails = 10,
    enableFire = false,
    trailSizeEnd = 1,
    cursorOffsetY = 0,
    trailOffsetY = -28,
    trailOffsetX = -39,
    randomSmokeColor = false,
    enableTrails = true,
    enableSpringSeasonTrails = false,
    enableSpringSeason = false,
    enableLightningSparks = false,
    enableSmokeTrails = false,
    enableStarEmbers = true,
    enableFireTrails = false,
    emberColor = { r = 1, g = 0.4509804248809815, b = 0.1725490242242813, a = 0.8 },
    randomTwinkleStarsColor = false,
    trailGlowIntensity = 1,
    enableSmoke = false,
    trailLayerCount = 1,
    additionalEffects = 1,
    glowSize = 0.5
            }
    end

      -- Black_Pink_Serpent
    if not EasyCursorTrailsDB.profiles["Black_Pink_Serpent"] then
        EasyCursorTrailsDB.profiles["Black_Pink_Serpent"] = {

             verticalScale = 2,
    trailColor = { r = 0.2862745225429535, g = 0.2313725650310516, b = 0.250980406999588, a = 1 },
    enableStaticArc = false,
    cursorColorEffect = 2,
    minimapPosition = { x = 0, y = 0 },
    horizontalScale = 1,
    enableStaticArcs = true,
    glowAboveCursor = false,
    randomLightningSparkColor = false,
    glowRadius = 0.1,
    glowColor = { r = 0.7176470588235294, g = 0.4196078431372549, b = 0.9568627450980393, a = 1 },
    numGlows = 30,
    trailRadius = 20,
    cursorOffsetX = 0,
    enableTrailShadows = true,
    glowThickness = 0.8,
    trailColorEffect = 10,
    pulsingSpeed = 10,
    trailDelay = 0,
    chainSegment = 10,
    disableGlowPulsing = false,
    cursorTexture = 32,
    enableStars = true,
    selectedCursorTextureName = "Yin_Yang_1",
    randomEmberColor = false,
    staticArcColor = { r = 0.7960785031318665, g = 0.6392157077789307, b = 0.6980392336845398, a = 1 },
    enableTwinkleStars = true,
    enableSmokeEffect = false,
    patternGlowCount = 29,
    cursorFrameStrata = "HIGH",
    trailTexture = 1,
    cursorSize = 40,
    glowIntensity = 1,
    randomFireColor = false,
    randomStaticArcColor = false,
    randomStarColor = false,
    shadowTrailColor = { r = 0, g = 0, b = 0, a = 0.4 },
    glowHollowness = 0,
    trailCount = 50,
    trailSpacing = 10,
    glowBelow = false,
    enableEmbers = true,
    randomSpringSeasonColor = false,
    cursorColor = { r = 0.5411764705882353, g = 0.9921568627450981, b = 1, a = 1 },
    trailFrameStrata = "HIGH",
    trailMovementEffect = 1,
    trailInitialSeparation = 36,
    glowPulsingIntensity = 0.5,
    trailIntensity = 0.5,
    connectTrails = true,
    enableDirectionalOffset = false,
    randomShadowColor = false,
    starColor = { r = 0.7960785031318665, g = 0.6392157077789307, b = 0.6980392336845398, a = 1 },
    trailSizeStart = 15,
    trailUpdateMultiplier = 100,
    menuPosition = {
        x = 250.1666412353516,
        y = -87.33332061767578,
        point = "TOP",
        relativePoint = "TOP",
    },
    twinkleStarsColor = { r = 0.7960785031318665, g = 0.6392157077789307, b = 0.6980392336845398, a = 1 },
    pulseMin = 0.3,
    glowIntensityFactor = 0.30,
    chainSpacing = 1,
    trailLayerSpacing = 0,
    selectedGlowEffect = 5,
    numTrails = 10,
    enableFire = false,
    trailOffsetY = 1,
    cursorOffsetY = 0,
    trailSizeEnd = 1,
    trailOffsetX = -34,
    randomSmokeColor = false,
    enableTrails = true,
    enableSpringSeasonTrails = false,
    enableSpringSeason = false,
    enableLightningSparks = false,
    enableSmokeTrails = false,
    enableStarEmbers = true,
    enableFireTrails = false,
    emberColor = { r = 0.5843137502670288, g = 0.125490203499794, b = 0.0313725508749485, a = 0.8 },
    randomTwinkleStarsColor = false,
    trailGlowIntensity = 1,
    enableSmoke = false,
    trailLayerCount = 1,
    additionalEffects = 1,
    glowSize = 0.5,

       }
    end

      -- Black_Serpent
    if not EasyCursorTrailsDB.profiles["Black_Serpent"] then
        EasyCursorTrailsDB.profiles["Black_Serpent"] = {

    verticalScale = 2,
    trailColor = { r = 0.02745098248124123, g = 0.003921568859368563, b = 0, a = 1 },
    enableStaticArc = false,
    cursorColorEffect = 5,
    minimapPosition = { x = 0, y = 0 },
    enableFireEffect = false,
    horizontalScale = 1,
    enableStaticArcs = true,
    glowAboveCursor = false,
    randomLightningSparkColor = false,
    glowRadius = 0.1,
    glowColor = { r = 0.7176470588235294, g = 0.1843137254901961, b = 0.0392156862745098, a = 1 },
    numGlows = 30,
    trailRadius = 20,
    cursorOffsetX = 0,
    enableTrailShadows = true,
    glowThickness = 0.8,
    trailColorEffect = 10,
    pulsingSpeed = 10,
    trailDelay = 0,
    chainSegment = 10,
    disableGlowPulsing = false,
    cursorTexture = 32,
    enableStars = true,
    selectedCursorTextureName = "Yin_Yang_1",
    randomEmberColor = false,
    staticArcColor = { r = 0.1176470667123795, g = 0.1176470667123795, b = 0.1176470667123795, a = 1 },
    enableTwinkleStars = false,
    enableSmokeEffect = true,
    patternGlowCount = 29,
    cursorFrameStrata = "HIGH",
    trailTexture = 1,
    cursorSize = 40,
    useMufflerSmoke = true,
    glowIntensity = 1,
    randomFireColor = false,
    randomStaticArcColor = false,
    randomStarColor = false,
    shadowTrailColor = { r = 0, g = 0, b = 0, a = 0.4 },
    glowHollowness = 0,
    trailCount = 50,
    trailSpacing = 10,
    glowBelow = false,
    enableEmbers = true,
    randomSpringSeasonColor = false,
    cursorColor = { r = 0.5411764705882353, g = 0.9921568627450981, b = 1, a = 1 },
    trailFrameStrata = "HIGH",
    smokeColor = { r = 0.1294117718935013, g = 0.1215686351060867, b = 0.1176470667123795, a = 0.4 },
    trailMovementEffect = 1,
    trailInitialSeparation = 36,
    enableLightningSpark = false,
    glowPulsingIntensity = 0.5,
    trailTextureOpacity = 1,
    trailIntensity = 0.5,
    fireColor = { r = 1, g = 0.125490203499794, b = 0.05098039656877518, a = 1 },
    enableDirectionalOffset = true,
    randomShadowColor = false,
    additionalEffects = 1,
    trailSizeStart = 18,
    twinkleStarsColor = { r = 0.9843137860298157, g = 0.9294118285179138, b = 1, a = 1 },
    menuPosition = {
        x = 250.1666412353516,
        y = -87.33332061767578,
        point = "TOP",
        relativePoint = "TOP",
    },
    enableSmoke = true,
    pulseMin = 0.3,
    glowIntensityFactor = 1,
    chainSpacing = 1,
    trailLayerSpacing = 0,
    selectedGlowEffect = 5,
    numTrails = 10,
    enableFire = false,
    randomSmokeColor = false,
    cursorOffsetY = 0,
    trailOffsetY = -1,
    trailOffsetX = -38,
    enableTrails = true,
    enableSpringSeasonTrails = false,
    enableSpringSeason = false,
    enableSmokeTrails = false,
    trailSizeEnd = 1,
    enableLightningSparks = false,
    enableStarEmbers = false,
    enableFireTrails = false,
    emberColor = { r = 1, g = 0.3686274588108063, b = 0.06666667014360428, a = 0.8 },
    randomTwinkleStarsColor = false,
    trailGlowIntensity = 1,
    trailUpdateMultiplier = 100,
    trailLayerCount = 1,
    connectTrails = true,
    glowSize = 0.5

     }
    end    

        -- Jade_Dragon
    if not EasyCursorTrailsDB.profiles["Jade_Dragon"] then
        EasyCursorTrailsDB.profiles["Jade_Dragon"] = {

    verticalScale = 2,
    trailColor = { r = 0.05882353335618973, g = 1, b = 0.5490196347236633, a = 1 },
    enableStaticArc = false,
    cursorColorEffect = 6,
    minimapPosition = { x = 0, y = 0 },
    horizontalScale = 1,
    enableStaticArcs = false,
    glowAboveCursor = false,
    randomLightningSparkColor = false,
    glowRadius = 0.17,
    layerCount = 1,
    glowColor = { r = 0.05882352941176471, g = 1, b = 0.5490196078431373, a = 1 },
    numGlows = 30,
    trailRadius = 20,
    cursorOffsetX = 0,
    enableTrailShadows = true,
    glowThickness = 0.9,
    trailColorEffect = 10,
    pulsingSpeed = 10,
    trailDelay = 0,
    chainSegment = 10,
    disableGlowPulsing = false,
    cursorTexture = 35,
    enableStars = true,
    selectedCursorTextureName = "Circle_focus_1",
    randomEmberColor = false,
    staticArcColor = { r = 0.7960785031318665, g = 0.6392157077789307, b = 0.6980392336845398, a = 1 },
    enableTwinkleStars = true,
    enableSmokeEffect = false,
    patternGlowCount = 29,
    cursorFrameStrata = "HIGH",
    trailTexture = 1,
    cursorSize = 30,
    glowIntensity = 0.5,
    randomFireColor = false,
    randomStaticArcColor = false,
    randomStarColor = false,
    shadowTrailColor = { r = 0, g = 0, b = 0, a = 0.4 },
    glowHollowness = 0,
    trailCount = 50,
    trailSpacing = 10,
    glowBelow = false,
    enableEmbers = true,
    randomSpringSeasonColor = false,
    cursorColor = { r = 0.05882352941176471, g = 1, b = 0.5490196078431373, a = 1 },
    trailFrameStrata = "HIGH",
    trailTextureOpacity = 1,
    trailMovementEffect = 1,
    additionalEffects = 0,
    trailUpdateMultiplier = 100,
    glowPulsingIntensity = 0.5,
    starColor = { r = 0, g = 0.658823549747467, b = 0.4196078777313232, a = 1 },
    trailIntensity = 0.5,
    enableSmoke = false,
    enableDirectionalOffset = false,
    selectedGlowEffect = 19,
    trailInitialSeparation = 30,
    trailSizeStart = 18,
    enableSpringSeason = false,
    menuPosition = {
        x = -244.833,
        y = 72.4999,
        point = "RIGHT",
        relativePoint = "RIGHT",
    },
    enableSpringSeasonTrails = false,
    enableStarEmbers = true,
    glowIntensityFactor = 0.3,
    connectTrails = true,
    trailLayerSpacing = 0,
    enableTrails = true,
    numTrails = 10,
    enableFire = false,
    trailSizeEnd = 1,
    cursorOffsetY = 0,
    trailOffsetY = -2,
    trailOffsetX = -32,
    pulseMin = 0.3,
    twinkleStarsColor = { r = 0.9, g = 0.95, b = 1, a = 1 },
    chainSpacing = 1,
    enableSmokeTrails = false,
    randomShadowColor = false,
    randomSmokeColor = false,
    enableLightningSparks = false,
    enableFireTrails = false,
    emberColor = { r = 0, g = 0.9294118285179138, b = 0.5921568870544434, a = 0.8 },
    randomTwinkleStarsColor = false,
    trailGlowIntensity = 1,
    lightningSparkColor = { r = 0.2156862914562225, g = 0.5647059082984924, b = 1, a = 1 },
    trailLayerCount = 1,
    enableLightningSpark = false,
    glowSize  = 0.7


     }
    end  

    
    -- Silver_Sky_Dragon
    if not EasyCursorTrailsDB.profiles["Silver_Sky_Dragon"] then
        EasyCursorTrailsDB.profiles["Silver_Sky_Dragon"] = {

            verticalScale = 2,
    selectedGlowEffect = 5,
    enableStaticArc = false,
    cursorColorEffect = 2,
    minimapPosition = { x = 0, y = 0 },
    horizontalScale = 1,
    enableStaticArcs = true,
    glowAboveCursor = false,
    randomLightningSparkColor = false,
    glowRadius = 0.1,
    glowColor = { r = 1, g = 1, b = 1, a = 1 },
    numGlows = 30,
    trailRadius = 20,
    cursorOffsetX = 0,
    enableTrailShadows = true,
    glowThickness = 0.5,
    trailColorEffect = 10,
    pulsingSpeed = 10,
    trailDelay = 0,
    chainSegment = 10,
    disableGlowPulsing = false,
    cursorTexture = 32,
    enableStars = true,
    selectedCursorTextureName = "Yin_Yang_1",
    randomEmberColor = false,
    staticArcColor = { r = 1, g = 1, b = 1, a = 1 },
    enableTwinkleStars = false,
    enableSmokeEffect = true,
    patternGlowCount = 29,
    cursorFrameStrata = 4,
    trailTexture = 1,
    cursorSize = 40,
    glowIntensity = 1,
    randomFireColor = false,
    randomStaticArcColor = false,
    randomStarColor = true,
    shadowTrailColor = { r = 0, g = 0, b = 0, a = 0.4 },
    glowHollowness = 0,
    trailCount = 50,
    trailSpacing = 10,
    glowBelow = false,
    enableEmbers = false,
    randomSpringSeasonColor = false,
    cursorColor = { r = 0.5411764705882353, g = 0.9921568627450981, b = 1, a = 1 },
    trailFrameStrata = "HIGH",
    trailMovementEffect = 1,
    additionalEffects = 1,
    glowPulsingIntensity = 0.5,
    trailIntensity = 0.5,
    starColor = { r = 1, g = 1, b = 1, a = 1 },
    enableDirectionalOffset = true,
    enableSmoke = true,
    twinkleStarsColor = { r = 0.9, g = 0.95, b = 1, a = 1 },
    trailSizeStart = 15,
    pulseMin = 0.3,
    menuPosition = {
        x = 250.1666412353516,
        y = -87.33332061767578,
        point = "TOP",
        relativePoint = "TOP",
    },
    trailInitialSeparation = 30,
    chainSpacing = 1,
    glowIntensityFactor = 0.5,
    connectTrails = true,
    trailLayerSpacing = 0,
    randomSmokeColor = false,
    numTrails = 10,
    enableFire = false,
    enableSpringSeasonTrails = false,
    cursorOffsetY = 0,
    trailOffsetY = 1,
    trailOffsetX = -33,
    enableSpringSeason = false,
    enableLightningSparks = false,
    enableSmokeTrails = true,
    enableStarEmbers = true,
    enableTrails = true,
    randomShadowColor = false,
    trailSizeEnd = 1,
    enableFireTrails = false,
    trailColor = { r = 1, g = 1, b = 1, a = 1 },
    randomTwinkleStarsColor = false,
    trailGlowIntensity = 1,
    trailUpdateMultiplier = 100,
    trailLayerCount = 1,
    smokeColor = { r = 0.9372549653053284, g = 0.9372549653053284, b = 0.9372549653053284, a = 1 },
    glowSize = 0.7
                }
    end  

    -- Sniper
    if not EasyCursorTrailsDB.profiles["Sniper"] then
        EasyCursorTrailsDB.profiles["Sniper"] = {
    enableTrails = true,
    trailColor = { r = 1, g = 0.592156862745098, b = 0.1098039215686275, a = 1 },
    enableStaticArc = false,
    cursorColorEffect = 5,
    connectTrails = true,
    horizontalScale = 1,
    enableStaticArcs = true,
    glowAboveCursor = false,
    randomLightningSparkColor = false,
    glowRadius = 0.13,
    layerCount = 1,
    glowColor = { r = 1, g = 0.592156862745098, b = 0.1098039215686275, a = 1 },
    numGlows = 30,
    trailRadius = 20,
    cursorOffsetX = 0,
    enableTrailShadows = true,
    glowThickness = 0.50,
    trailColorEffect = 19,
    pulsingSpeed = 10,
    trailDelay = 0,
    chainSegment = 100,
    disableGlowPulsing = false,
    cursorTexture = 8,
    enableStars = true,
    selectedCursorTextureName = "dirty_lens",
    randomEmberColor = false,
    staticArcColor = { r = 1, g = 1, b = 1, a = 1 },
    enableTwinkleStars = true,
    enableSmokeEffect = false,
    patternGlowCount = 29,
    twinkleStarsColor = { r = 1, g = 0.5921568870544434, b = 0.1215686351060867, a = 1 },
    trailTexture = 9,
    cursorSize = 40,
    glowIntensity = 1,
    randomFireColor = false,
    randomStaticArcColor = false,
    randomStarColor = false,
    shadowTrailColor = { r = 0, g = 0, b = 0, a = 0.4 },
    glowHollowness = 0,
    trailCount = 15,
    trailSpacing = 100,
    glowBelow = false,
    enableEmbers = true,
    randomSpringSeasonColor = false,
    cursorColor = { r = 0.4117647058823529, g = 0.4941176470588236, b = 0.207843137254902, a = 1 },
    trailFrameStrata = "HIGH",
    trailMovementEffect = 1,
    trailInitialSeparation = 36,
    trailTextureOpacity = 1,
    glowPulsingIntensity = 0.5,
    enableStarEmbers = false,
    trailIntensity = 0.5,
    additionalEffects = 1,
    enableDirectionalOffset = false,
    trailUpdateMultiplier = 100,
    enableSpringSeason = false,
    trailSizeStart = 18,
    enableSpringSeasonTrails = false,
    menuPosition = {
        x = -244.833,
        y = 72.4999,
        point = "RIGHT",
        relativePoint = "RIGHT",
    },
    chainSpacing = 1,
    glowIntensityFactor = 0.2100000083446503,
    enableLightningSparks = false,
    trailCountSlider = 25,
    trailLayerSpacing = 0,
    randomShadowColor = false,
    numTrails = 10,
    enableFire = false,
    enableSmokeTrails = false,
    cursorOffsetY = 0,
    trailSizeEnd = 18,
    trailOffsetX = -29,
    pulseMin = 0.3,
    verticalScale = 2,
    cursorFrameStrata = "HIGH",
    minimapPosition = { x = 0, y = 0 },
    trailOffsetY = -4,
    enableSmoke = false,
    randomSmokeColor = false,
    enableFireTrails = false,
    emberColor = { r = 1, g = 0.3411764800548554, b = 0.0784313753247261, a = 0.8 },
    randomTwinkleStarsColor = false,
    trailGlowIntensity = 1,
    selectedGlowEffect = 17,
    trailLayerCount = 1,
    enableLightningSpark = false,
    glowSize = 0.50


        }
    end
end




-- 🧠 Optional: Save trailMovementEffect on load
local function EnsureTrailMovementEffect()
    local currentProfileName = EasyCursorTrailsDB.currentProfile
    local currentProfile = currentProfileName and EasyCursorTrailsDB.profiles[currentProfileName]
    local defaultEffect = (EasyCursorTrails.defaults and EasyCursorTrails.defaults.trailMovementEffect) or 4

    if currentProfile and not currentProfile.trailMovementEffect then
        EasyCursorTrails.SaveToCurrentProfile("trailMovementEffect", defaultEffect)
    end
end

-- 🔽 Populate Profile Dropdown
function EasyCursorTrails.PopulateProfileDropdown()
    local dropdown = EasyCursorTrails.profileDropdown
    if not dropdown then return end

    EnsureDefaultProfile()
    EnsureCoperDragonProfile()
    EnsureTrailMovementEffect()

    local profiles = EasyCursorTrailsDB.profiles
    local currentProfile = EasyCursorTrailsDB.currentProfile or "Default"

    -- Sort profiles with current one first
    local sortedProfiles = {}
    for profileName in pairs(profiles) do
        table.insert(sortedProfiles, profileName)
    end
    table.sort(sortedProfiles, function(a, b)
        if a == currentProfile then return true end
        if b == currentProfile then return false end
        return a < b
    end)

    UIDropDownMenu_Initialize(dropdown, function(self, level)
        if level ~= 1 then return end

        for _, profileName in ipairs(sortedProfiles) do
            local info = UIDropDownMenu_CreateInfo()
            info.text = profileName
            info.checked = (profileName == currentProfile)
            info.func = function()
                EasyCursorTrailsDB.currentProfile = profileName
                EasyCursorTrails.SaveLastSelectedProfile(profileName)
                EasyCursorTrails.LoadCurrentProfile()
                EasyCursorTrails.RefreshSettingsUI()
                EasyCursorTrails.PopulateProfileDropdown()
                UIDropDownMenu_SetText(dropdown, profileName)
            end
            UIDropDownMenu_AddButton(info, level)
        end
    end)

    UIDropDownMenu_SetText(dropdown, currentProfile)
end


-- 🌐 Store dropdown reference and populate
EasyCursorTrails.profileDropdown = profileDropdown
EasyCursorTrails.PopulateProfileDropdown()

-- 📦 Button Dimensions & Spacing
local buttonHeight = 25
local buttonSpacing = 10
local dropdownBottomOffset = -10

function EasyCursorTrails.OpenTextInputDialog(promptText, onAccept, defaultText, editBoxWidth)
    local dialog = StaticPopupDialogs["EASYCURSORTRAILS_TEXT_INPUT"]
    dialog.text = promptText or "Enter text:"
    EasyCursorTrails._onTextInputAccept = onAccept

    StaticPopup_Show("EASYCURSORTRAILS_TEXT_INPUT")

    local popupFrame = StaticPopup_FindVisible("EASYCURSORTRAILS_TEXT_INPUT")
    if popupFrame and popupFrame.editBox then
        popupFrame.editBox:SetText(defaultText or "")
        popupFrame.editBox:SetWidth(editBoxWidth or 200)
        popupFrame.editBox:SetFocus()
    end
end


-- 🌱 Create Profile Button
local createProfileButton = CreateFrame("Button", "CreateProfileButton", menu, "UIPanelButtonTemplate")
createProfileButton:SetSize(60, 25)
createProfileButton:SetText("Create")
createProfileButton:SetPoint("TOPLEFT", profileDropdown, "BOTTOMLEFT", -20, -10)

createProfileButton:SetScript("OnClick", function()
    EasyCursorTrails.OpenTextInputDialog("Enter new profile name:", function(newProfileName)
        if not newProfileName or newProfileName == "" then return end
        if EasyCursorTrailsDB.profiles[newProfileName] then
            UIErrorsFrame:AddMessage("Profile '" .. newProfileName .. "' already exists.", 1, 0.5, 0)
            return
        end

        EasyCursorTrailsDB.profiles[newProfileName] = EasyCursorTrails.DeepCopyDefaults(EasyCursorTrails.defaults)
        EasyCursorTrailsDB.currentProfile = newProfileName

        if EasyCursorTrails.PopulateProfileDropdown then
            EasyCursorTrails.PopulateProfileDropdown(EasyCursorTrails.profileDropdown)
        end
        UIDropDownMenu_SetText(EasyCursorTrails.profileDropdown, newProfileName)

        if EasyCursorTrails.LoadCurrentProfile then EasyCursorTrails.LoadCurrentProfile() end
        if EasyCursorTrails.RefreshSettingsUI then EasyCursorTrails.RefreshSettingsUI() end

        --EasyCursorTrails: Created and selected profile '" .. newProfileName .. "'.")
        UIErrorsFrame:AddMessage("Profile '" .. newProfileName .. "' created.", 0, 1, 0)
    end, "", 220)
end)
-- 🗑️ Delete Profile Button
local deleteProfileButton = CreateFrame("Button", "DeleteProfileButton", menu, "UIPanelButtonTemplate")
deleteProfileButton:SetSize(65, 25)
deleteProfileButton:SetText("Delete")
deleteProfileButton:SetPoint("LEFT", createProfileButton, "RIGHT", 10, 0)

StaticPopupDialogs["EASYCURSORTRAILS_CONFIRM_DELETE"] = {
    text = "Are you sure you want to delete this profile?",
    button1 = "Yes",
    button2 = "No",
    OnAccept = function(self, data)
        local profileName = data
        if type(profileName) == "string" and EasyCursorTrailsDB.profiles[profileName] then
            -- Delete profile
            EasyCursorTrailsDB.profiles[profileName] = nil

            -- Fallback to Default if current profile was deleted
            if EasyCursorTrailsDB.currentProfile == profileName then
                EasyCursorTrailsDB.currentProfile = "Default"
                EasyCursorTrails.SaveLastSelectedProfile("Default")
            end

            -- Refresh dropdown
            if EasyCursorTrails.profileDropdown then
                EasyCursorTrails.PopulateProfileDropdown(EasyCursorTrails.profileDropdown)
                UIDropDownMenu_SetSelectedName(EasyCursorTrails.profileDropdown, EasyCursorTrailsDB.currentProfile)
                UIDropDownMenu_SetText(EasyCursorTrails.profileDropdown, EasyCursorTrailsDB.currentProfile)
            end

            -- Reload profile and UI
            EasyCursorTrails.LoadCurrentProfile()
            EasyCursorTrails.RefreshSettingsUI()

            --EasyCursorTrails: Deleted profile '" .. profileName .. "'.")
            UIErrorsFrame:AddMessage("Profile '" .. profileName .. "' deleted.", 1, 0.2, 0.2)
        else
            --EasyCursorTrails: Failed to delete — profile not found.")
            UIErrorsFrame:AddMessage("Deletion failed: Profile not found.", 1, 0.2, 0.2)
        end
    end,
    timeout = 0,
    whileDead = true,
    hideOnEscape = true,
    preferredIndex = 3,
}

deleteProfileButton:SetScript("OnClick", function()
    local selectedProfile = UIDropDownMenu_GetText(EasyCursorTrails.profileDropdown)

    if selectedProfile and selectedProfile ~= "Default" and EasyCursorTrailsDB.profiles[selectedProfile] then
        -- Update popup text dynamically
        StaticPopupDialogs["EASYCURSORTRAILS_CONFIRM_DELETE"].text =
            "Are you sure you want to delete profile '" .. selectedProfile .. "'?"

        -- Show popup and explicitly assign data
        local popup = StaticPopup_Show("EASYCURSORTRAILS_CONFIRM_DELETE")
        if popup then
            popup.data = selectedProfile
        end
    else
                -- Set font size and style for UIErrorsFrame
        UIErrorsFrame:SetFont("Fonts\\FRIZQT__.TTF", 18, "OUTLINE")

        -- Show green message
        UIErrorsFrame:AddMessage("Cannot delete 'Default', click 'Reset' button to reset.", 0, 1, 0)

    end
end)

-- 🔄 Reset Profile Button
local resetButton = CreateFrame("Button", "ResetSettingsButton", menu, "UIPanelButtonTemplate")
resetButton:SetSize(80, 25)
resetButton:SetText("Reset")
resetButton:SetPoint("TOPLEFT", createProfileButton, "BOTTOMLEFT", 145, 25)

StaticPopupDialogs["EASYCURSORTRAILS_RESET_CONFIRM"] = {
    text = "Reset all settings to default values? This will apply immediately.",
    button1 = "Yes",
    button2 = "No",
    OnAccept = function()
        local defaults = EasyCursorTrails.defaults
        local defaultProfileName = "Default"

        if defaults then
            -- Deep copy and sanitize default settings
            local newDefaults = EasyCursorTrails.DeepCopyDefaults(defaults)
            EasyCursorTrailsDB.profiles[defaultProfileName] = newDefaults
            EasyCursorTrails.SanitizeProfileState(newDefaults)

            -- Switch to Default profile
            EasyCursorTrailsDB.currentProfile = defaultProfileName
            EasyCursorTrails.SaveLastSelectedProfile(defaultProfileName)

            -- Refresh dropdown selection
            if EasyCursorTrails.profileDropdown then
                EasyCursorTrails.PopulateProfileDropdown(EasyCursorTrails.profileDropdown)
                UIDropDownMenu_SetSelectedName(EasyCursorTrails.profileDropdown, defaultProfileName)
                UIDropDownMenu_SetText(EasyCursorTrails.profileDropdown, defaultProfileName)
            end

            -- Reload profile and UI
            EasyCursorTrails.LoadCurrentProfile()
            EasyCursorTrails.menuInitialized = true
            if EasyCursorTrails.RefreshSettingsUI then EasyCursorTrails.RefreshSettingsUI() end

            -- Rebuild visuals
            if newDefaults.enableTrails and EasyCursorTrails.RebuildTrails then
                EasyCursorTrails.RebuildTrails()
            elseif EasyCursorTrails.HideAllTrails then
                EasyCursorTrails.HideAllTrails()
            end

            if newDefaults.enableEmbers and EasyCursorTrails.StartEmberTicker then
                EasyCursorTrails.StartEmberTicker()
            elseif EasyCursorTrails.StopEmberTicker then
                EasyCursorTrails.StopEmberTicker()
            end

            if EasyCursorTrails.UpdateGlowFrames then EasyCursorTrails.UpdateGlowFrames() end
            if EasyCursorTrails.InitializeCustomCursor then EasyCursorTrails.InitializeCustomCursor() end

            --EasyCursorTrails: Reset to 'Default' profile.")
            UIErrorsFrame:AddMessage("Reset complete. Switched to 'Default' profile.", 0, 1, 0)
        else
            --EasyCursorTrails: Error — Defaults missing.")
            UIErrorsFrame:AddMessage("Reset failed: No default settings found.", 1, 0.2, 0.2, 53)
        end
    end,
    timeout = 0,
    whileDead = true,
    hideOnEscape = true,
    preferredIndex = 3,
}

resetButton:SetScript("OnClick", function()
    StaticPopup_Show("EASYCURSORTRAILS_RESET_CONFIRM")
end)


function EasyCursorTrails.TraceEmberState()
    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    local defaults = EasyCursorTrails.defaults or {}

    --=== EasyCursorTrails: Ember Debug ===")
    if not profile then
        --❌ Profile missing. Cannot read ember state.")
        return
    end

    local rawFlag = profile.enableEmbers
    local defaultFlag = defaults.enableEmbers
    local checkbox = EasyCursorTrails.emberCheckbox
    local tickerRunning = EasyCursorTrails.EmberTickerActive and true or false

    --Profile Flag:", rawFlag)
    --Default Flag:", defaultFlag)
    --Checkbox Exists:", checkbox ~= nil)
    if checkbox then
        --Checkbox Checked:", checkbox:GetChecked())
    end
    --Ticker Running:", tickerRunning)

    if rawFlag == false then
        --⚠ Profile flag explicitly disables embers.")
    elseif checkbox and not checkbox:GetChecked() then
        --⚠ Checkbox is not checked despite profile flag.")
    elseif not tickerRunning then
        --⚠ Ember ticker not running. Try StartEmberTicker().")
    else
        --✅ Embers should be active.")
    end
end




-- Glow Settings Header
local glowSettingsHeader = menu:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
glowSettingsHeader:SetPoint("TOPLEFT", glowEffectDropdown, "BOTTOMLEFT", 0, -20)
glowSettingsHeader:SetText("Glow Settings")

------------------------------------------------------------------
-- Number of Glows Slider
------------------------------------------------------------------
local numGlowsSlider = CreateSlider(
    "NumGlowsSlider",
    menu,
    "Number of Glows",
    0,
    30,
    1,
    EasyCursorTrailsDB.numGlows or EasyCursorTrails.defaults.numGlows,
    function(slider, value)
        value = math.floor(value)
        EasyCursorTrailsDB.numGlows = value
        slider:SetValue(value)
        EasyCursorTrails.settingsChanged = true
        EasyCursorTrails.SaveToCurrentProfile("numGlows", value)
        EasyCursorTrails.UpdateGlowFrames()
        

    end
)
numGlowsSlider:SetPoint("TOPLEFT", trailCountSlider, "BOTTOMLEFT", -270, -30)
EasyCursorTrails.numGlowsSlider = numGlowsSlider

------------------------------------------------------------------
-- Update Function for Number of Glows Slider
------------------------------------------------------------------
local function UpdateNumGlowsSliderFromProfile()
    if not EasyCursorTrailsDB or not EasyCursorTrailsDB.currentProfile then
        EasyCursorTrails.HandleError("UpdateNumGlowsSliderFromProfile: Database or current profile is missing.")
        return
    end

    local profileName = EasyCursorTrailsDB.currentProfile
    local profileSettings = EasyCursorTrailsDB.profiles and EasyCursorTrailsDB.profiles[profileName]

    if not profileSettings then
        EasyCursorTrails.HandleError("UpdateNumGlowsSliderFromProfile: Profile '" .. tostring(profileName) .. "' is missing or invalid.")
        return
    end

    local numGlows = profileSettings.numGlows or EasyCursorTrails.defaults.numGlows
    if EasyCursorTrails.numGlowsSlider then
        EasyCursorTrails.numGlowsSlider:SetValue(numGlows)
        if EasyCursorTrails.numGlowsSlider.valueText then
            EasyCursorTrails.numGlowsSlider.valueText:SetText(tostring(numGlows))
        else
            EasyCursorTrails.HandleError("UpdateNumGlowsSliderFromProfile: 'numGlowsSlider.valueText' is nil.")
        end
        if EasyCursorTrails.numGlowsSlider.editBox then
            EasyCursorTrails.numGlowsSlider.editBox:SetText(tostring(numGlows))
        else
            EasyCursorTrails.HandleError("UpdateNumGlowsSliderFromProfile: 'numGlowsSlider.editBox' is nil.")
        end
    else
        EasyCursorTrails.HandleError("UpdateNumGlowsSliderFromProfile: 'numGlowsSlider' is nil.")
    end
end

if type(EasyCursorTrails.RefreshSettingsUI) == "function" then
    hooksecurefunc(EasyCursorTrails, "RefreshSettingsUI", UpdateNumGlowsSliderFromProfile)
else
    EasyCursorTrails.HandleError("EasyCursorTrails.RefreshSettingsUI is not valid when attempting to hook numGlows update.")
end


------------------------------------------------------------------
-- Pattern Glow Count Slider
------------------------------------------------------------------
local patternGlowCountSlider = CreateSlider(
    "PatternGlowCountSlider",
    menu,
    "Pattern Glow Count",
    3,
    29,
    1,
    EasyCursorTrailsDB.patternGlowCount or EasyCursorTrails.defaults.patternGlowCount,
    function(slider, value)
        value = math.floor(value)
        EasyCursorTrailsDB.patternGlowCount = value
        slider:SetValue(value)
        EasyCursorTrails.settingsChanged = true
        EasyCursorTrails.SaveToCurrentProfile("patternGlowCount", value)
        EasyCursorTrails.UpdateGlowFrames()
        

    end
)
patternGlowCountSlider:SetPoint("TOPLEFT", numGlowsSlider, "BOTTOMLEFT", 0, -30)
EasyCursorTrails.patternGlowCountSlider = patternGlowCountSlider

------------------------------------------------------------------
-- Glow Radius Slider
------------------------------------------------------------------
local initialGlowRadius =
    EasyCursorTrails.currentProfileTable and EasyCursorTrails.currentProfileTable.glowRadius
    or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile].glowRadius
    or EasyCursorTrails.defaults.glowRadius
    or 0.1

local glowRadiusSlider = CreateSlider(
    "GlowRadiusSlider",
    menu,
    "Glow Radius",
    0.1,
    1.1,
    0.01,
    initialGlowRadius,
    function(slider, value)
        local profile = EasyCursorTrails.currentProfileTable
            or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
        if not profile then
            EasyCursorTrails.HandleError("glowRadiusSlider: Failed to retrieve current profile.")
            return
        end

        profile.glowRadius = value
        EasyCursorTrails.SaveToCurrentProfile("glowRadius", value)

        -- 🔁 Trigger live update
        EasyCursorTrails.ApplySelectedGlowEffect()
        

    end,
    2
)

glowRadiusSlider:SetPoint("TOPLEFT", patternGlowCountSlider, "BOTTOMLEFT", 0, -30)
EasyCursorTrails.glowRadiusSlider = glowRadiusSlider

------------------------------------------------------------------
-- Glow Intensity Slider
------------------------------------------------------------------
local initialGlowIntensity =
    EasyCursorTrails.currentProfileTable and EasyCursorTrails.currentProfileTable.glowIntensity
    or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile].glowIntensity
    or EasyCursorTrails.defaults.glowIntensity
    or 0.8

local glowIntensitySlider = CreateSlider(
    "GlowIntensitySlider",
    menu,
    "Glow Intensity",
    0.1,
    1.0,
    0.05,
    initialGlowIntensity,
    function(slider, value)
        local profile = EasyCursorTrails.currentProfileTable
            or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
        if not profile then
            EasyCursorTrails.HandleError("glowIntensitySlider: No profile found.")
            return
        end

        profile.glowIntensity = value
        EasyCursorTrails.SaveToCurrentProfile("glowIntensity", value)

        -- 🔁 Fully reapply glow visuals with new intensity
        EasyCursorTrails.ApplySelectedGlowEffect()
        

    end,
    2 -- Show decimals like 0.75
)

glowIntensitySlider:SetPoint("TOPLEFT", glowRadiusSlider, "BOTTOMLEFT", 0, -30)
EasyCursorTrails.glowIntensitySlider = glowIntensitySlider

------------------------------------------------------------------
-- Glow Size Slider
------------------------------------------------------------------
local glowSizeSlider = CreateSlider(
    "GlowSizeSlider",
    menu,
    "Glow Size",
    0.1,
    2.0,
    0.1,
    EasyCursorTrailsDB.glowSize or EasyCursorTrails.defaults.glowSize,
    function(slider, value)
        EasyCursorTrailsDB.glowSize = value
        slider:SetValue(value)
        EasyCursorTrails.settingsChanged = true
        EasyCursorTrails.SaveToCurrentProfile("glowSize", value)
        EasyCursorTrails.UpdateGlowFrames()
        

    end
)
glowSizeSlider:SetPoint("TOPLEFT", glowIntensitySlider, "BOTTOMLEFT", 0, -30)
EasyCursorTrails.glowSizeSlider = glowSizeSlider

------------------------------------------------------------------
-- Glow Thickness Slider
------------------------------------------------------------------
local glowThicknessSlider = CreateSlider(
    "GlowThicknessSlider",
    menu,
    "Glow Thickness",
    0.1,
    2.0,
    0.1,
    EasyCursorTrailsDB.glowThickness or EasyCursorTrails.defaults.glowThickness,
    function(slider, value)
        EasyCursorTrailsDB.glowThickness = value
        slider:SetValue(value)
        EasyCursorTrails.settingsChanged = true
        EasyCursorTrails.SaveToCurrentProfile("glowThickness", value)
        EasyCursorTrails.UpdateGlowFrames()
        

    end
)
glowThicknessSlider:SetPoint("TOPLEFT", glowSizeSlider, "BOTTOMLEFT", 0, -30)
EasyCursorTrails.glowThicknessSlider = glowThicknessSlider

------------------------------------------------------------------
-- Cursor Size Slider
------------------------------------------------------------------
local cursorSizeSlider = CreateSlider(
    "CursorSizeSlider",
    menu,
    "Cursor Size",
    10,
    200,
    1,
    (EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile] and EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile].cursorSize) or EasyCursorTrails.defaults.cursorSize,
    function(slider, value)
        EasyCursorTrailsDB.cursorSize = value
        EasyCursorTrails.settingsChanged = true
        EasyCursorTrails.SaveToCurrentProfile("cursorSize", value)
        EasyCursorTrails.UpdateCustomCursorSize(value)
        

    end
)
cursorSizeSlider:SetPoint("TOPLEFT", glowBelowCheckbox, "BOTTOMLEFT", 0, -30)
EasyCursorTrails.cursorSizeSlider = cursorSizeSlider


------------------------------------------------------------------
-- Cursor Offset X Slider
------------------------------------------------------------------
local cursorOffsetXSlider = CreateSlider(
    "CursorOffsetXSlider",
    menu,
    "Cursor Offset X",
    -100,
    100,
    1,
    EasyCursorTrailsDB.cursorOffsetX or EasyCursorTrails.defaults.cursorOffsetX,
    function(slider, value)
        EasyCursorTrailsDB.cursorOffsetX = value
        slider:SetValue(value)
        EasyCursorTrails.settingsChanged = true
        EasyCursorTrails.SaveToCurrentProfile("cursorOffsetX", value)
        EasyCursorTrails.UpdateCustomCursorPosition()
        

    end
)
cursorOffsetXSlider:SetPoint("TOPLEFT", cursorSizeSlider, "BOTTOMLEFT", 0, -30)
EasyCursorTrails.cursorOffsetXSlider = cursorOffsetXSlider

------------------------------------------------------------------
-- Cursor Offset Y Slider
------------------------------------------------------------------
local cursorOffsetYSlider = CreateSlider(
    "CursorOffsetYSlider",
    menu,
    "Cursor Offset Y",
    -100,
    100,
    1,
    EasyCursorTrailsDB.cursorOffsetY or EasyCursorTrails.defaults.cursorOffsetY,
    function(slider, value)
        value = math.max(-100, math.min(100, value))
        EasyCursorTrailsDB.cursorOffsetY = value
        slider:SetValue(value)
        EasyCursorTrails.settingsChanged = true
        EasyCursorTrails.SaveToCurrentProfile("cursorOffsetY", value)
        EasyCursorTrails.UpdateCustomCursorPosition()
        

    end
)
cursorOffsetYSlider:SetPoint("TOPLEFT", cursorOffsetXSlider, "BOTTOMLEFT", 0, -30)
EasyCursorTrails.cursorOffsetYSlider = cursorOffsetYSlider


-- Frame Strata Options (for reference, not used in this snippet)
EasyCursorTrails.frameStrataOptions = {
    { text = "BACKGROUND" },
    { text = "LOW" },
    { text = "MEDIUM" },
    { text = "HIGH" },
    { text = "DIALOG" },
}

-----------------------------------------------
-- Create the "Select Glow Color" Button
-----------------------------------------------
-- 🌟 Select Glow Color Button
local selectGlowColorButton = CreateFrame("Button", "SelectGlowColorButton", menu, "UIPanelButtonTemplate")
selectGlowColorButton:SetSize(150, 25)
selectGlowColorButton:SetText("Select Glow Color")
selectGlowColorButton:SetPoint("TOPLEFT", glowThicknessSlider, "BOTTOMLEFT", 0, -60)
EasyCursorTrails.selectGlowColorButton = selectGlowColorButton

-- 🖍️ Glow Color Edit Box
local glowColorEditBox = CreateFrame("EditBox", "GlowColorEditBox", menu, "InputBoxTemplate")
glowColorEditBox:SetSize(80, 25)
glowColorEditBox:SetPoint("LEFT", selectGlowColorButton, "RIGHT", 10, 0)
glowColorEditBox:SetAutoFocus(false)
glowColorEditBox:SetMaxLetters(9) -- Supports #RRGGBBAA
EasyCursorTrails.glowColorEditBox = glowColorEditBox

-- 🏷️ Label: HTML Color Code
local glowColorLabel = menu:CreateFontString(nil, "OVERLAY", "GameFontNormal")
glowColorLabel:SetPoint("BOTTOMLEFT", glowColorEditBox, "TOPLEFT", -10, -40)
glowColorLabel:SetText("HTML Color Code")

-- 🔄 Update Edit Box Text
local function UpdateGlowColorEditBox()
    local color = EasyCursorTrailsDB.glowColor or { r = 1, g = 1, b = 1, a = 1 }
    glowColorEditBox:SetText(RGBToHex(color.r, color.g, color.b, color.a))

    local textWidth = glowColorEditBox:GetText():len() * 8
    glowColorEditBox:SetWidth(math.max(80, textWidth + 20))
end

-- 🎯 Handle Enter Pressed
glowColorEditBox:SetScript("OnEnterPressed", function(self)
    local hexColor = "#" .. self:GetText():gsub("#", "")
    local r, g, b, a = HexToRGB(hexColor)
    if r and g and b then
        a = a or 1
        EasyCursorTrailsDB.glowColor = { r = r, g = g, b = b, a = a }
        EasyCursorTrails.settingsChanged = true
        EasyCursorTrails.SaveToCurrentProfile("glowColor", EasyCursorTrailsDB.glowColor)
        EasyCursorTrails.ApplySelectedGlowEffect()
        UpdateGlowColorEditBox()
    else
        --Invalid HTML color code. Use #RRGGBB or #RRGGBBAA")
    end
    self:ClearFocus()
end)

-- 🧠 Apply on Focus Lost
glowColorEditBox:SetScript("OnEditFocusLost", function(self)
    self:GetScript("OnEnterPressed")(self)
end)

-- 🎨 Button Click Logic
selectGlowColorButton:SetScript("OnClick", function()
    local initialColor = EasyCursorTrailsDB.glowColor or { r = 1, g = 1, b = 1, a = 1 }
    EasyCursorTrails.OpenColorPicker(initialColor, function(color)
        EasyCursorTrailsDB.glowColor = color
        EasyCursorTrails.settingsChanged = true
        EasyCursorTrails.SaveToCurrentProfile("glowColor", color)
        EasyCursorTrails.ApplySelectedGlowEffect()
        UpdateGlowColorEditBox()
    end)
end)

-- 🔧 Initialize Edit Box
UpdateGlowColorEditBox()

------------------------------------------------------------
-- Glow Effect Dropdown Setup
------------------------------------------------------------

-- Define the Glow Effect Options list
EasyCursorTrails.glowEffectOptions = {
    { id = 1, text = "Custom Color", description = "Use a custom static color for the glow effect." },
    { id = 2, text = "Custom + Normal Pulse", description = "Apply a steady pulsing effect to the custom color." },
    { id = 3, text = "Rainbow Glow", description = "Create a dynamic animated rainbow glow effect." },
    { id = 4, text = "Flickering Glow", description = "Add a flickering fire-like effect." },
    { id = 5, text = "Strobing Glow", description = "Apply a strobing light effect." },
    { id = 6, text = "Trailing Glow", description = "Create a trailing light effect as the cursor moves." },
    { id = 7, text = "Vibrant Pulse", description = "Add a vibrant and dynamic pulsing glow." },
    { id = 8, text = "Disco Lights", description = "Create a randomized multicolor disco effect." },
    { id = 9, text = "Wave Effect", description = "Apply a wave-like motion to the glow." },
    { id = 10, text = "Airport Lights", description = "Simulate trailing airport runway lights." },
    { id = 11, text = "Custom + Pulse (Clockwise)", description = "Pulse the glow effect in a clockwise direction." },
    { id = 12, text = "Random Colors (Clockwise)", description = "Use random colors for a clockwise glow effect." },
    { id = 13, text = "Custom + Pulse (Anticlockwise)", description = "Pulse the glow effect in an anticlockwise direction." },
    { id = 14, text = "Random Colors (Anticlockwise)", description = "Use random colors for an anticlockwise glow effect." },
    { id = 15, text = "Custom + Fast Pulsing", description = "Apply a fast pulsing effect to the custom color." },
    { id = 16, text = "Custom + Slow Pulsing", description = "Apply a slow pulsing effect to the custom color." },
    { id = 17, text = "Custom + Stretch Segments", description = "Stretch and contract glow segments dynamically." },
    { id = 18, text = "Burning Effect", description = "Simulate a burning fire effect for the glow." },
    { id = 19, text = "Custom + Lightning Pulse", description = "Add a pulsing lightning effect to the custom color." },
    { id = 20, text = "Tinker Bell Effect", description = "Create a whimsical, fairy-like effect." },
    { id = 21, text = "Random Effect", description = "Select a random glow effect each time." },
    { id = 22, text = "Random Sparkle Effect", description = "Random Sparkle Effect" },
}

EasyCursorTrails.glowEffectDropdown = CreateDropdown(
    "GlowEffectDropdown",
    menu,
    "Glow Effects",
    EasyCursorTrails.glowEffectOptions,
    EasyCursorTrailsDB.selectedGlowEffect or 1,
    function(index)
        -- ✅ Ensure glowEffectDropdown exists before updating
        if EasyCursorTrails.glowEffectDropdown then
            UIDropDownMenu_SetSelectedID(EasyCursorTrails.glowEffectDropdown, index)
            local effectText = EasyCursorTrails.glowEffectOptions[index] and EasyCursorTrails.glowEffectOptions[index].text or "Custom Color"
            UIDropDownMenu_SetText(EasyCursorTrails.glowEffectDropdown, effectText)
        else
            --print("Error: glowEffectDropdown is nil! Ensure it is created before updating.")
        end

        -- ✅ Save selection
        EasyCursorTrailsDB.selectedGlowEffect = index
        EasyCursorTrails.settingsChanged = true
        EasyCursorTrails.SaveToCurrentProfile("selectedGlowEffect", index)

        -- ✅ Apply the selected effect
        EasyCursorTrails.ApplySelectedGlowEffect()
    end
)

-- ✅ Set the dropdown position **after global assignment**
EasyCursorTrails.glowEffectDropdown:SetPoint("TOPLEFT", selectGlowColorButton, "BOTTOMLEFT", -20, 60)


-- Frame Strata Options
EasyCursorTrails.frameStrataOptions = {
    { text = "BACKGROUND" },
    { text = "LOW" },
    { text = "MEDIUM" },
    { text = "HIGH" },
    { text = "DIALOG" },
}

-- Function to get the index of a given frame strata
EasyCursorTrails.GetStrataIndex = function(strata)
    if not strata then return 4 end -- Default to "HIGH" if nil

    for i, v in ipairs(EasyCursorTrails.frameStrataOptions) do
        if v.text == strata then
            return i
        end
    end

    return 4 -- Default to "HIGH" if no match is found
end
-- 🧭 Create container to join cursor UI elements
local cursorOptionsGroup = CreateFrame("Frame", "EasyCursorTrails_CursorOptionsGroup", menu)
cursorOptionsGroup:SetSize(1, 1)
cursorOptionsGroup:SetPoint("TOPLEFT", selectGlowColorButton, "BOTTOMLEFT", -20, -20)

local spacing = -14
local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]

-- 1️⃣ Cursor Frame Strata Dropdown
local initialFrameStrataIndex = EasyCursorTrails.GetStrataIndex(EasyCursorTrailsDB.cursorFrameStrata or "HIGH")
local cursorFrameStrataDropdown = CreateDropdown(
    "CursorFrameStrataDropdown",
    cursorOptionsGroup,
    "Cursor Frame Strata",
    EasyCursorTrails.frameStrataOptions,
    initialFrameStrataIndex,
    function(selectedIndex)
        local selectedStrata = EasyCursorTrails.frameStrataOptions[selectedIndex].text
        EasyCursorTrailsDB.cursorFrameStrata = selectedStrata
        EasyCursorTrails.settingsChanged = true
        EasyCursorTrails.SaveToCurrentProfile("cursorFrameStrata", selectedStrata)
        if customCursor then
            customCursor:SetFrameStrata(selectedStrata)
        end
    end
)
cursorFrameStrataDropdown:SetPoint("TOPLEFT", cursorOptionsGroup, "TOPLEFT", 0, 0)
EasyCursorTrails.cursorFrameStrataDropdown = cursorFrameStrataDropdown

-- 2️⃣ Cursor Texture Dropdown
local cursorTextureOptions = {}
for _, cursorData in ipairs(EasyCursorTrails.customCursorTextures or {}) do
    local name = cursorData.name or "Unknown"
    if cursorData.animated then name = name .. " (Animated)" end
    table.insert(cursorTextureOptions, { text = name, icon = cursorData.texture })
end
EasyCursorTrails.cursorTextureDropdown = CreateDropdown(
    "CursorTextureDropdown",
    cursorOptionsGroup,
    "Cursor Textures",
    cursorTextureOptions,
    EasyCursorTrailsDB.cursorTexture or 1,
    function(index)
        EasyCursorTrailsDB.cursorTexture = index
        EasyCursorTrails.settingsChanged = true
        EasyCursorTrails.SaveToCurrentProfile("cursorTexture", index)
        EasyCursorTrails.InitializeCustomCursor()
    end
)
EasyCursorTrails.cursorTextureDropdown:SetPoint("TOPLEFT", cursorFrameStrataDropdown, "BOTTOMLEFT", 0, spacing)

-- 3️⃣ Cursor Color Effect Dropdown
EasyCursorTrails.cursorColorEffectOptions = {}
for _, effect in ipairs(colorEffects or {}) do
    table.insert(EasyCursorTrails.cursorColorEffectOptions, { text = effect.text })
end
local cursorColorEffectDropdown = CreateDropdown(
    "CursorColorEffectDropdown",
    cursorOptionsGroup,
    "Cursor Color Effects",
    EasyCursorTrails.cursorColorEffectOptions,
    EasyCursorTrailsDB.cursorColorEffect or 1,
    function(index)
        EasyCursorTrailsDB.cursorColorEffect = index
        EasyCursorTrails.settingsChanged = true
        EasyCursorTrails.SaveToCurrentProfile("cursorColorEffect", index)
        EasyCursorTrails.ApplyColorEffectCursor()
    end
)
cursorColorEffectDropdown:SetPoint("TOPLEFT", EasyCursorTrails.cursorTextureDropdown, "BOTTOMLEFT", 0, spacing)
EasyCursorTrails.cursorColorEffectDropdown = cursorColorEffectDropdown
-- 4️⃣ Select Cursor Color Button
local selectCursorColorButton = CreateFrame("Button", "SelectCursorColorButton", cursorOptionsGroup, "UIPanelButtonTemplate")
selectCursorColorButton:SetSize(150, 25)
selectCursorColorButton:SetText("Select Cursor Color")
selectCursorColorButton:SetPoint("TOPLEFT", cursorColorEffectDropdown, "BOTTOMLEFT", 18, -2)
EasyCursorTrails.selectCursorColorButton = selectCursorColorButton

-- 5️⃣ Cursor Color Edit Box
local cursorColorEditBox = CreateFrame("EditBox", "CursorColorEditBox", cursorOptionsGroup, "InputBoxTemplate")
cursorColorEditBox:SetSize(80, 25)
cursorColorEditBox:SetPoint("LEFT", selectCursorColorButton, "RIGHT", 10, 0)
cursorColorEditBox:SetAutoFocus(false)
cursorColorEditBox:SetMaxLetters(9)
EasyCursorTrails.cursorColorEditBox = cursorColorEditBox

-- 🏷️ Label: HTML Color Code
local cursorColorLabel = cursorOptionsGroup:CreateFontString(nil, "OVERLAY", "GameFontNormal")
cursorColorLabel:SetPoint("BOTTOMLEFT", cursorColorEditBox, "TOPLEFT", -10, 0)
cursorColorLabel:SetText("HTML Color Code")

-- 🔄 Update Edit Box Text
local function UpdateCursorColorEditBox()
    local color = EasyCursorTrailsDB.cursorColor or { r = 1, g = 1, b = 1, a = 1 }
    local colorText = RGBToHex(color.r, color.g, color.b, color.a)
    if cursorColorEditBox:GetText() ~= colorText then
        cursorColorEditBox:SetText(colorText)
    end
    local textWidth = cursorColorEditBox:GetText():len() * 8
    cursorColorEditBox:SetWidth(math.max(80, textWidth + 20))
end

-- 🎯 Handle Enter Pressed
cursorColorEditBox:SetScript("OnEnterPressed", function(self)
    local hexColor = "#" .. self:GetText():gsub("#", "")
    local r, g, b, a = HexToRGB(hexColor)
    if r and g and b then
        a = a or 1
        EasyCursorTrailsDB.cursorColor = { r = r, g = g, b = b, a = a }
        EasyCursorTrails.settingsChanged = true
        EasyCursorTrails.SaveToCurrentProfile("cursorColor", EasyCursorTrailsDB.cursorColor)
        EasyCursorTrails.ApplyColorEffectCursor()
        UpdateCursorColorEditBox()
    else
        print("Invalid HTML color format! Use #RRGGBB or #RRGGBBAA")
    end
    self:ClearFocus()
end)

-- 🧠 Apply on Focus Lost
cursorColorEditBox:SetScript("OnEditFocusLost", function(self)
    self:GetScript("OnEnterPressed")(self)
end)

-- 🎨 Button Click Logic
selectCursorColorButton:SetScript("OnClick", function()
    local initialColor = EasyCursorTrailsDB.cursorColor or { r = 1, g = 1, b = 1, a = 1 }
    EasyCursorTrails.OpenColorPicker(initialColor, function(color)
        local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
        if not profile then return end
        local savedRadius = profile.glowRadius

        EasyCursorTrailsDB.cursorColor = color
        EasyCursorTrails.settingsChanged = true
        EasyCursorTrails.SaveToCurrentProfile("cursorColor", color)
        EasyCursorTrails.ApplyColorEffectCursor()

        if savedRadius then
            profile.glowRadius = savedRadius
            EasyCursorTrails.SaveToCurrentProfile("glowRadius", savedRadius)
            if EasyCursorTrails.UpdateCursorGlow then
                EasyCursorTrails.UpdateCursorGlow(savedRadius)
            end
        end

        UpdateCursorColorEditBox()
    end)
end)

-- 🔧 Initialize Edit Box
UpdateCursorColorEditBox()

-- Store reference
EasyCursorTrails.cursorColorEditBox = cursorColorEditBox


-- ===========================
-- Define Static Popup Dialogs
-- ===========================

-- 🔄 Save & Reload Confirmation
StaticPopupDialogs["EASYCURSORTRAILS_RELOAD_WARNING"] = {
    text = "Are you sure you want to save and reload the UI to apply the changes?",
    button1 = "Yes",
    button2 = "No",
    OnAccept = function()
        -- Save settings to current profile
        if EasyCursorTrails.SaveAllSettingsToProfile then
            EasyCursorTrails.SaveAllSettingsToProfile()
        end

        -- Save connectTrails checkbox state
        local checkbox = EasyCursorTrails.connectTrailsCheckbox
        if checkbox and checkbox.GetChecked then
            EasyCursorTrails.SaveToCurrentProfile("connectTrails", checkbox:GetChecked())
        end

        ReloadUI()
    end,
    OnCancel = function()
        -- Optional: log or notify cancellation
        -- print("EasyCursorTrails: Reload canceled. Changes saved but not applied.")
    end,
    timeout = 0,
    whileDead = true,
    hideOnEscape = true,
    preferredIndex = 3,
}

-- 🔁 Reload Prompt After Saving
StaticPopupDialogs["EASYCURSORTRAILS_RELOAD_UI"] = {
    text = "Configuration changes saved. Reload UI to apply changes? This will also improves the effects.",
    button1 = "Reload",
    button2 = "Later",
    OnAccept = function()
        ReloadUI()
    end,
    timeout = 0,
    whileDead = true,
    hideOnEscape = true,
    preferredIndex = 3,
}

-- ===========================
-- Save Button
-- ===========================
local SaveButton = CreateFrame("Button", "SaveButton", menu, "UIPanelButtonTemplate")
SaveButton:SetSize(100, 25)
SaveButton:SetText("Save")
SaveButton:SetPoint("BOTTOMRIGHT", menu, "BOTTOMRIGHT", -230, 10)

SaveButton:SetScript("OnClick", function()
    -- 💾 Commit profile changes
    if EasyCursorTrails.SaveAllSettingsToProfile then
        EasyCursorTrails.SaveAllSettingsToProfile()
    end

    -- 📦 Reload current profile table
    local profileName = EasyCursorTrails.currentProfileName or EasyCursorTrailsDB.currentProfile or "Default"
    EasyCursorTrails.currentProfileName = profileName
    EasyCursorTrails.currentProfileTable = EasyCursorTrailsDB.profiles[profileName]

    -- ✅ Sync enableTrails to checkbox state
    local checkboxState = enableTrailsCheckbox and enableTrailsCheckbox:GetChecked()
    EasyCursorTrails.currentProfileTable.enableTrails = checkboxState
    EasyCursorTrailsDB.profiles[profileName].enableTrails = checkboxState

    -- 🔁 Rebuild trails if checkbox is checked
    if checkboxState and EasyCursorTrails.RebuildTrails then
        EasyCursorTrails.RebuildTrails()
    elseif EasyCursorTrails.trailPool then
        for _, layerPool in pairs(EasyCursorTrails.trailPool) do
            for _, trail in ipairs(layerPool) do
                if trail then trail:Hide() end
            end
        end
    end

    -- 💬 Show reload prompt
    local popup = StaticPopup_Show("EASYCURSORTRAILS_RELOAD_WARNING")
    if popup then
        popup:SetPoint("CENTER", UIParent, "CENTER")
    end

    -- 🔒 Reset dirty flag
    EasyCursorTrails.settingsChanged = false
end)

menu:HookScript("OnHide", function()
    if EasyCursorTrails.settingsChanged then
        if EasyCursorTrails.SaveAllSettingsToProfile then
            EasyCursorTrails.SaveAllSettingsToProfile()
        end

        -- ✅ Respect checkbox state
        local checkboxState = enableTrailsCheckbox and enableTrailsCheckbox:GetChecked()
        local profile = EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
        if profile then
            profile.enableTrails = checkboxState
            EasyCursorTrails.currentProfileTable.enableTrails = checkboxState
        end

        local popup = StaticPopup_Show("EASYCURSORTRAILS_RELOAD_UI")
        if popup then
            popup:SetPoint("CENTER", UIParent, "CENTER")
        end

        EasyCursorTrails.settingsChanged = false
    end
end)



-- ❌ Close Button
local closeButton = CreateFrame("Button", "CloseButton", menu, "UIPanelButtonTemplate")
closeButton:SetSize(100, 25)
closeButton:SetText("Close")
closeButton:SetPoint("BOTTOMRIGHT", SaveButton, "BOTTOMRIGHT", 150, 0)

closeButton:SetScript("OnClick", function()
    menu:Hide() -- Triggers OnHide logic
end)


-- Minimap Button
local minimapButton = CreateFrame("Button", "EasyCursorTrailsMinimapButton", Minimap)
minimapButton:SetSize(32, 32)
minimapButton:SetNormalTexture("Interface\\AddOns\\EasyCursorTrails\\Textures\\icon.tga")
minimapButton:SetHighlightTexture("Interface\\Buttons\\UI-Minimap-ZoomButton-Highlight.blp")
minimapButton:SetPoint("TOPLEFT", Minimap, "TOPLEFT", -10, -10)
minimapButton:SetScript("OnClick", function()
    menu:SetShown(not menu:IsShown())
end)

minimapButton:SetScript("OnEnter", function(self)
    GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
    GameTooltip:AddLine("Easy Cursor Trails")
    GameTooltip:AddLine("Click to open the settings menu.", 1, 1, 1)
    GameTooltip:Show()
end)

minimapButton:SetScript("OnLeave", function()
    GameTooltip:Hide()
end)



end




--------------------------------------------------------
-- Animations for Glow
--------------------------------------------------------
function CreatePulsingAnimation(animationGroup, color, intensity, duration, delay)
    local dur = duration or 0.5
    local dly = delay or 0

    local peakAlpha = color.a or 1.0
    local dipAlpha = math.max(0.02, peakAlpha * 0.1 * (intensity or 1))

    local pulseIn = animationGroup:CreateAnimation("Alpha")
    pulseIn:SetFromAlpha(dipAlpha)
    pulseIn:SetToAlpha(peakAlpha)
    pulseIn:SetDuration(dur)
    pulseIn:SetStartDelay(dly)
    pulseIn:SetOrder(1)

    local pulseOut = animationGroup:CreateAnimation("Alpha")
    pulseOut:SetFromAlpha(peakAlpha)
    pulseOut:SetToAlpha(dipAlpha)
    pulseOut:SetDuration(dur)
    pulseOut:SetOrder(2)

    -- Optional: breathing scale for visual depth
    local scalePulse = animationGroup:CreateAnimation("Scale")
    scalePulse:SetScale(1.05, 1.05)
    scalePulse:SetDuration(dur * 2)
    scalePulse:SetOrder(3)

    animationGroup:SetLooping("REPEAT")
end


function EasyCursorTrails.ApplyDefaultCircularGlow()
    -- Ensure we have a valid customCursor and glowEffects
    if not customCursor or not customCursor.glowEffects then
        ----print("EasyCursorTrails: customCursor or glowEffects not initialized.")
        return
    end

    local NUM_GLOWS = #customCursor.glowEffects
    if NUM_GLOWS < 1 then return end

    ------------------------------------------------
    -- 1) Safely retrieve glow-related settings
    ------------------------------------------------
    local glowColor     = EasyCursorTrailsDB.glowColor or EasyCursorTrails.defaults.glowColor or { r = 1, g = 1, b = 1, a = 1 }
    local glowSize      = EasyCursorTrailsDB.glowSize or EasyCursorTrails.defaults.glowSize or 1
    local glowThickness = EasyCursorTrailsDB.glowThickness or EasyCursorTrails.defaults.glowThickness or 1
    local glowIntensity = EasyCursorTrailsDB.glowIntensity or EasyCursorTrails.defaults.glowIntensity or 1

    ------------------------------------------------
    -- 2) Compute layout geometry
    ------------------------------------------------
    local angleStep    = 360 / NUM_GLOWS
    local cursorRadius = customCursor:GetWidth() / 1.5
    -- fallback if EasyCursorTrailsDB.glowRadius is missing
    local rad          = EasyCursorTrailsDB.glowRadius or EasyCursorTrails.defaults.glowRadius or 0.1
    local offsetDist   = cursorRadius * rad

    ------------------------------------------------
    -- 3) Position each glow around the cursor
    ------------------------------------------------
    for i, glow in ipairs(customCursor.glowEffects) do
        if glow and glow.texture then
            local angle = math.rad((i - 1) * angleStep)
            local offsetX = math.cos(angle) * offsetDist
            local offsetY = math.sin(angle) * offsetDist

            -- Move the glow
            glow:ClearAllPoints()
            glow:SetPoint("CENTER", customCursor, "CENTER", offsetX, offsetY)

            -- Scale the glow
            local newSize = (customCursor:GetWidth() * glowSize) * glowThickness
            glow:SetSize(newSize, newSize)

            -- Color and alpha
            glow.texture:SetVertexColor(
                glowColor.r, 
                glowColor.g, 
                glowColor.b
            )
            -- If glowColor.a is missing, default to 1
            local alpha = glowIntensity * (glowColor.a or 1)
            glow.texture:SetAlpha(alpha)

            glow:Show()
        end
    end
end


function EasyCursorTrails.ClearAllGlows()
    for _, glow in ipairs(EasyCursorTrails.activeGlows or {}) do
        glow:Hide()
        glow:SetTexture(nil)
    end
    EasyCursorTrails.activeGlows = {}
end

function EasyCursorTrails.SpawnGlows(count)
    EasyCursorTrails.ClearAllGlows()

    for i = 1, count do
        local glow = CreateFrame("Frame", nil, UIParent)
        glow:SetSize(16, 16)
        glow.texture = glow:CreateTexture(nil, "OVERLAY")
        glow.texture:SetAllPoints()
        glow.texture:SetTexture("Interface\\AddOns\\YourAddon\\Textures\\Glow")
        glow:Show()

        table.insert(EasyCursorTrails.activeGlows, glow)
    end
end


function EasyCursorTrails.OnGlowCountChanged(newCount)
    EasyCursorTrailsDB.glowCount = newCount
    EasyCursorTrails.SpawnGlows(newCount)
end



function EasyCursorTrails.ApplySelectedGlowEffect()

     local selectedEffect = EasyCursorTrailsDB.selectedGlowEffect
    local intensity = EasyCursorTrailsDB.glowIntensity or 1

    -- ✅ Ensure glows are spawned before applying any effect
    if not EasyCursorTrails.activeGlows or #EasyCursorTrails.activeGlows == 0 then
        EasyCursorTrails.SpawnGlows(EasyCursorTrailsDB.glowCount or 5)
    end
    
    -- 1. Verify glow frames exist
    if not customCursor or not customCursor.glowEffects then
        EasyCursorTrails.HandleError("ApplySelectedGlowEffect: customCursor or glowEffects not initialized.")
        return
    end

    -- 2. Load active profile
    local profileName = EasyCursorTrailsDB.currentProfile or "Default"
    local currentProfile = EasyCursorTrailsDB.profiles[profileName]
    if not currentProfile then
        EasyCursorTrails.HandleError("ApplySelectedGlowEffect: Profile '" .. profileName .. "' not found.")
        return
    end
    EasyCursorTrails.currentProfileTable = currentProfile

    -- 3. Get effect list
    local glowEffectOptions = EasyCursorTrails.glowEffectOptions
    if not glowEffectOptions then
        EasyCursorTrails.HandleError("ApplySelectedGlowEffect: glowEffectOptions table missing.")
        return
    end

    -- 4. Resolve selected effect (or randomized one)
    local selectedEffect = currentProfile.selectedGlowEffect or 1
    local totalEffects = #glowEffectOptions
    if glowEffectOptions[selectedEffect]
        and glowEffectOptions[selectedEffect].text == "Random - Keep selecting for random effects"
    then
        selectedEffect = math.random(1, totalEffects - 1)
        currentProfile.selectedGlowEffect = selectedEffect
        EasyCursorTrails.SaveToCurrentProfile("selectedGlowEffect", selectedEffect)
    end

    -- 5. Resolve texture + pattern
    local textureName = currentProfile.selectedCursorTextureName
    if not textureName or textureName == "" then
        EasyCursorTrails.ApplyDefaultCircularGlow()
        return
    end

    local patternKey = EasyCursorTrails.cursorGlowMapping[textureName]
    local glowPattern = patternKey and EasyCursorTrails.glowPatterns[patternKey]
    if not glowPattern then
        EasyCursorTrails.ApplyDefaultCircularGlow()
        return
    end

    -- 6. Load glow settings
    local glowColor     = currentProfile.glowColor     or EasyCursorTrails.defaults.glowColor     or { r = 1, g = 1, b = 1, a = 1 }
    local intensity     = math.max(0, math.min(1, currentProfile.glowIntensity or EasyCursorTrails.defaults.glowIntensity or 1))
    local clampedAlpha  = math.max(0.2, (glowColor.a or 1) * intensity) -- ✨ clamp alpha to avoid invisible glows
    local glowRadius    = tonumber(currentProfile.glowRadius)    or EasyCursorTrails.defaults.glowRadius    or 0.1
    local glowSize      = currentProfile.glowSize      or EasyCursorTrails.defaults.glowSize      or 1
    local glowThickness = currentProfile.glowThickness or EasyCursorTrails.defaults.glowThickness or 1

    local cursorWidth = customCursor:GetWidth() or 64
    local radiusScale = glowRadius * (cursorWidth / 5.5)

    -- 7. Generate coordinates
    local coords = type(glowPattern) == "function"
        and glowPattern(currentProfile.patternGlowCount or EasyCursorTrails.defaults.patternGlowCount or 8)
        or glowPattern

    if not coords or type(coords) ~= "table" then
        EasyCursorTrails.ApplyDefaultCircularGlow()
        return
    end

    -- 8. Get movement pattern ID
    local movementPatternID = tonumber(currentProfile.movementPatternID) or 1

    -- ✔ Ready for animation loop
    -- That would follow right after this block, where you loop over customCursor.glowEffects
    function CreatePulsingAnimation(animationGroup, color, intensity, duration, delay)
        local dur = duration or 0.5  -- Lower = faster
        local dly = delay or 0

        local fromAlpha = math.min(0.4 + 0.3 * intensity, 1.0)
        local toAlpha   = math.min(color.a or 1.0, 1.0)

        local pulseIn = animationGroup:CreateAnimation("Alpha")
        pulseIn:SetFromAlpha(fromAlpha)
        pulseIn:SetToAlpha(toAlpha)
        pulseIn:SetDuration(dur)
        pulseIn:SetStartDelay(dly)
        pulseIn:SetOrder(1)

        local pulseOut = animationGroup:CreateAnimation("Alpha")
        pulseOut:SetFromAlpha(toAlpha)
        pulseOut:SetToAlpha(fromAlpha)
        pulseOut:SetDuration(dur)
        pulseOut:SetOrder(2)

        animationGroup:SetLooping("REPEAT")
    end


    function CreateFlickeringAnimation(animationGroup, color, intensity)
        local fromAlpha = 0.4 + 0.3 * intensity
        local toAlpha   = math.min(color.a or 1.0, 1.0)

        local flicker = animationGroup:CreateAnimation("Alpha")
        flicker:SetFromAlpha(fromAlpha)
        flicker:SetToAlpha(toAlpha)
        flicker:SetDuration(0.12 + math.random() * 0.15)
        flicker:SetOrder(1)

        animationGroup:SetLooping("REPEAT")
    end

    function CreateStrobingAnimation(animationGroup, color, intensity)
        local maxAlpha = math.min(color.a or 1, 1.0)
        local minAlpha = 0.1 + 0.20 * (intensity or 1) -- never fully disappear

        local flash = animationGroup:CreateAnimation("Alpha")
        flash:SetFromAlpha(minAlpha)
        flash:SetToAlpha(maxAlpha)
        flash:SetDuration(0.08)
        flash:SetOrder(1)

        local dim = animationGroup:CreateAnimation("Alpha")
        dim:SetFromAlpha(maxAlpha)
        dim:SetToAlpha(minAlpha)
        dim:SetDuration(0.18)
        dim:SetOrder(2)

        animationGroup:SetLooping("REPEAT")
    end

    function CreateTrailingAnimation(animationGroup, color, intensity)
        local maxAlpha = math.min(color.a or 1, 1.0)
        local minAlpha = 0.3 + 0.3 * (intensity or 1)

        local fadeIn = animationGroup:CreateAnimation("Alpha")
        fadeIn:SetFromAlpha(minAlpha)
        fadeIn:SetToAlpha(maxAlpha)
        fadeIn:SetDuration(0.3)
        fadeIn:SetOrder(1)

        local fadeOut = animationGroup:CreateAnimation("Alpha")
        fadeOut:SetFromAlpha(maxAlpha)
        fadeOut:SetToAlpha(minAlpha)
        fadeOut:SetDuration(0.3)
        fadeOut:SetOrder(2)

        
        animationGroup:SetLooping("REPEAT")
    end

    function CreateLightningAnimation(animationGroup, color, intensity)
        local peakAlpha = math.min(color.a or 1, 1.0)
        local baseAlpha = 0.1 + 0.3 * (intensity or 1)

        local flash = animationGroup:CreateAnimation("Alpha")
        flash:SetFromAlpha(baseAlpha)        -- ensures it's always visible
        flash:SetToAlpha(peakAlpha)
        flash:SetDuration(0.05)              -- very fast burst
        flash:SetStartDelay(0.1)
        flash:SetOrder(1)

        local fadeOut = animationGroup:CreateAnimation("Alpha")
        fadeOut:SetFromAlpha(peakAlpha)
        fadeOut:SetToAlpha(baseAlpha)
        fadeOut:SetDuration(0.2)
        fadeOut:SetOrder(2)

        animationGroup:SetLooping("REPEAT")
    end

    function CreateRainbowAnimation(animationGroup, glow, alpha, speed)
        local hueSpeed = (speed and speed > 0) and speed or 1

        -- Restartable animation tick
        local anim = animationGroup:CreateAnimation("Animation")
        anim:SetDuration(0.02)

        anim:SetScript("OnUpdate", function()
            local hue = (GetTime() * 50 * hueSpeed) % 360
            local r, g, b = EasyCursorTrails.HSVToRGB(hue, 1, 1)
            glow.texture:SetVertexColor(r, g, b, alpha or 1)
        end)

        animationGroup:SetLooping("REPEAT")
    end

    local function GetCursorWorldPosition()
        local x, y = GetCursorPosition()
        local scale = UIParent:GetEffectiveScale()
        return x / scale, y / scale
    end

    function EasyCursorTrails.ClearActiveGlows()
        if not EasyCursorTrails.activeGlows then return end

        for _, glow in ipairs(EasyCursorTrails.activeGlows) do
            if glow then
                glow:SetScript("OnUpdate", nil)

                if glow.animationGroup then
                    glow.animationGroup:Stop()
                    glow.animationGroup:SetScript("OnFinished", nil)
                    glow.animationGroup = nil
                end

                glow:Hide()
            end
        end
    end


    function CreateRandomSparkleAnimation(glow, radius, speed, spiralOut, intensity)
    if not glow or not glow.texture then return end

    -- 🧼 Clear previous animation and updater
    glow:SetScript("OnUpdate", nil)
    if glow.animationGroup then
        glow.animationGroup:Stop()
        glow.animationGroup:SetScript("OnFinished", nil)
        glow.animationGroup = nil
    end

    -- 🌟 Setup sparkle texture
    glow.texture:SetTexture("Interface\\Cooldown\\star4")
    glow.texture:SetBlendMode("ADD")
    glow.texture:SetTexCoord(0.2, 0.8, 0.2, 0.8)
    glow:SetSize(8, 8)
    glow:SetAlpha(1)
    glow:Show()

    -- ✨ Sparkle initializer
    local function ApplySparkle()
        local hue = math.random(0, 360)
        local r, g, b = EasyCursorTrails.HSVToRGB(hue, 1, 1)
        local sparkleSize = 10 + math.random(2, 4)

        glow:SetSize(sparkleSize, sparkleSize)
        glow.texture:SetVertexColor(
            math.min(r * 1.1, 1),
            math.min(g * 1.1, 1),
            math.min(b * 1.1, 1),
            0.7 + math.random() * 0.2
        )
        glow.texture:SetRotation(math.random() * 2 * math.pi)
    end

    ApplySparkle()

    -- 🌀 Spiral motion using OnUpdate
    local angle = math.random() * 2 * math.pi
    local spiralStep = spiralOut and 0.5 or 0
    local baseRadius = radius or 10
    local orbitSpeed = speed or 0.05

    glow:SetScript("OnUpdate", function(self, elapsed)
        angle = angle + orbitSpeed * elapsed * 60 -- normalize speed
        local r = baseRadius + (spiralOut and angle * spiralStep or 0)
        local x = math.cos(angle) * r
        local y = math.sin(angle) * r

        local cursorX, cursorY = GetCursorPosition()
        local scale = UIParent:GetEffectiveScale()
        cursorX, cursorY = cursorX / scale, cursorY / scale

        self:ClearAllPoints()
        self:SetPoint("CENTER", UIParent, "BOTTOMLEFT", cursorX + x, cursorY + y)
    end)

    -- 🎞️ Flicker and scale animation
    glow.animationGroup = glow:CreateAnimationGroup()

    local flicker = glow.animationGroup:CreateAnimation("Alpha")
    flicker:SetFromAlpha(0.2)
    flicker:SetToAlpha(math.max(0.8, math.min(1, intensity or 1)))
    flicker:SetDuration(0.05)
    flicker:SetSmoothing("IN_OUT")
    flicker:SetOrder(1)

    local scale = glow.animationGroup:CreateAnimation("Scale")
    scale:SetScale(1.1 + math.random() * 0.2, 1.1)
    scale:SetOrigin("CENTER", 0, 0)
    scale:SetDuration(0.05)
    scale:SetSmoothing("OUT")
    scale:SetOrder(1)

    local fade = glow.animationGroup:CreateAnimation("Alpha")
    fade:SetFromAlpha(flicker:GetToAlpha())
    fade:SetToAlpha(0.1)
    fade:SetDuration(0.06)
    fade:SetOrder(2)

    glow.animationGroup:SetScript("OnFinished", function()
        ApplySparkle()
        glow.animationGroup:Play()
    end)

    glow.animationGroup:SetLooping("NONE")
    glow.animationGroup:Play()
end



-- Main Loop for Applying Glow Effects
for i, glow in ipairs(customCursor.glowEffects) do
    if glow and glow.texture then
        -- 🔁 Clear any existing animations
        if glow.animationGroup then
            glow.animationGroup:Stop()
            glow.animationGroup:SetScript("OnFinished", nil)
            for _, anim in ipairs({ glow.animationGroup:GetAnimations() }) do
                anim:SetScript("OnUpdate", nil)
            end
            glow.animationGroup = nil
        end

        -- 🎬 Fresh animation group
        glow.animationGroup = glow:CreateAnimationGroup()
        glow.texture:SetBlendMode("ADD")

        -- 🎨 Resolve visual properties
        local r, g, b = glowColor.r, glowColor.g, glowColor.b
        local a = math.max(0.08, (glowColor.a or 1) * intensity)


        if movementPatternID == 43 then
            local hue = (i * 30 + GetTime() * 50) % 360
            r, g, b = EasyCursorTrails.HSVToRGB(hue, 1, 1)
            a = math.max(0.08, 0.6 * intensity) -- tie rainbow alpha to intensity
        end


        glow.texture:SetVertexColor(r, g, b, a)

        -- 📍 Position glow
        if coords and coords[i] then
            local x = coords[i].x * radiusScale
            local y = coords[i].y * radiusScale
            glow:ClearAllPoints()
            glow:SetPoint("CENTER", customCursor, "CENTER", x, y)
            glow:Show()
        else
            glow:Hide()
        end

        -- 📐 Set size
        local size = (cursorWidth * glowSize) * glowThickness
        glow:SetSize(size, size)

        -- 💡 Dispatch effect logic
        local delay = 0
        if     selectedEffect == 1  then glow.texture:SetVertexColor(r, g, b, a)
        elseif selectedEffect == 2  then CreatePulsingAnimation(glow.animationGroup, glowColor, intensity, 1.0)
        elseif selectedEffect == 3  then CreateRainbowAnimation(glow.animationGroup, glow, a, 3.0)
        elseif selectedEffect == 4  then CreateFlickeringAnimation(glow.animationGroup, glowColor, intensity)
        elseif selectedEffect == 5  then CreateStrobingAnimation(glow.animationGroup, glowColor, intensity)
        elseif selectedEffect == 6  then CreateTrailingAnimation(glow.animationGroup, glowColor, intensity)
        elseif selectedEffect == 7  then CreatePulsingAnimation(glow.animationGroup, glowColor, intensity, 0.8)
        elseif selectedEffect == 8 then
        local function ApplyDiscoColor()
            local hue = math.random(0, 360)
            local r, g, b = EasyCursorTrails.HSVToRGB(hue, 1, 1)
            glow.texture:SetVertexColor(r, g, b, a)
        end

        -- Initial color burst
        ApplyDiscoColor()

        -- Pulse + color change per cycle
        local pulseIn = glow.animationGroup:CreateAnimation("Alpha")
        pulseIn:SetFromAlpha(0.4)
        pulseIn:SetToAlpha(a)
        pulseIn:SetDuration(0.2)
        pulseIn:SetOrder(1)

        local pulseOut = glow.animationGroup:CreateAnimation("Alpha")
        pulseOut:SetFromAlpha(a)
        pulseOut:SetToAlpha(0.4)
        pulseOut:SetDuration(0.2)
        pulseOut:SetOrder(2)

        -- 🔁 When the pulse finishes, choose a new color and restart
        glow.animationGroup:SetScript("OnFinished", function()
            ApplyDiscoColor()
            glow.animationGroup:Play()
        end)

        glow.animationGroup:SetLooping("NONE")

        elseif selectedEffect == 9  then
            delay = (i - 1) * 0.1
            CreatePulsingAnimation(glow.animationGroup, glowColor, intensity, 1.0, delay)
        elseif selectedEffect == 10 then
            delay = (i % 2 == 0) and 0 or 0.1
            CreatePulsingAnimation(glow.animationGroup, glowColor, intensity, 0.2, delay)
        elseif selectedEffect == 11 then
            delay = (i - 1) * 0.05
            CreatePulsingAnimation(glow.animationGroup, glowColor, intensity, 1.0, delay)
        elseif selectedEffect == 12 then
            local rr, gg, bb = math.random(), math.random(), math.random()
            glow.texture:SetVertexColor(rr, gg, bb, a)
            delay = (i - 1) * 0.05
            CreatePulsingAnimation(glow.animationGroup, { r = rr, g = gg, b = bb, a = a }, intensity, 1.0, delay)
        elseif selectedEffect == 13 then
            delay = (#customCursor.glowEffects - i) * 0.05
            CreatePulsingAnimation(glow.animationGroup, glowColor, intensity, 1.0, delay)
        elseif selectedEffect == 14 then
            local rr, gg, bb = math.random(), math.random(), math.random()
            glow.texture:SetVertexColor(rr, gg, bb, a)
            delay = (#customCursor.glowEffects - i) * 0.05
            CreatePulsingAnimation(glow.animationGroup, { r = rr, g = gg, b = bb, a = a }, intensity, 1.0, delay)
        elseif selectedEffect == 15 then
            CreatePulsingAnimation(glow.animationGroup, glowColor, intensity, 0.1)
        elseif selectedEffect == 16 then
            CreatePulsingAnimation(glow.animationGroup, glowColor, intensity, 2.0)
        elseif selectedEffect == 17 then
            local stretch = glow.animationGroup:CreateAnimation("Scale")
            stretch:SetScale(1.2, 1.2)
            stretch:SetDuration(0.3)
            stretch:SetOrder(1)
            local contract = glow.animationGroup:CreateAnimation("Scale")
            contract:SetScale(0.8, 0.8)
            contract:SetDuration(0.3)
            contract:SetOrder(2)
            glow.animationGroup:SetLooping("REPEAT")
        elseif selectedEffect == 18 then
            glow.texture:SetVertexColor(1, 0.5, 0, a)
            CreateFlickeringAnimation(glow.animationGroup, { r = 1, g = 0.5, b = 0, a = a }, intensity)
        elseif selectedEffect == 19 then
            CreateLightningAnimation(glow.animationGroup, glowColor, intensity)
        elseif selectedEffect == 20 then
            glow.texture:SetVertexColor(1, 0.84, 0, a)
            CreatePulsingAnimation(glow.animationGroup, glowColor, intensity, 0.4 + math.random() * 0.2)
        elseif selectedEffect == 21 then
            selectedEffect = math.random(1, #glowEffectOptions - 1)
            currentProfile.selectedGlowEffect = selectedEffect
            EasyCursorTrails.SaveToCurrentProfile("selectedGlowEffect", selectedEffect)
            EasyCursorTrails.ApplySelectedGlowEffect()
            return
         elseif selectedEffect == 22 then
            -- 🧹 Clear previous glow animations
            EasyCursorTrails.ClearActiveGlows()

            -- Ensure glows are initialized
            if not EasyCursorTrails.activeGlows or #EasyCursorTrails.activeGlows == 0 then
                EasyCursorTrails.SpawnGlows(EasyCursorTrailsDB.glowCount or 5)
            end

            -- 🌟 Apply staggered spiral sparkle animation to each glow
            for i, glow in ipairs(EasyCursorTrails.activeGlows) do
                if glow and glow.texture then
                    C_Timer.After(i * 0.05, function()
                        local clockwise = (i % 2 == 0)
                        local speed = clockwise and 0.2 or -0.2
                        local radius = 10

                        CreateRandomSparkleAnimation(glow, radius, speed, false, intensity or 1)
                    end)
                end
            end
        end




        -- ▶ Start animation loop
        if glow.animationGroup then
            glow.animationGroup:Play()
        end
    end
end

end

function EasyCursorTrails.UpdateGlowIntensity()
    if not customCursor or not customCursor.glowEffects then return end

    local currentProfile = EasyCursorTrails.currentProfileTable
    local alpha = math.max(0, math.min(1, currentProfile.glowIntensity or 1))

    for _, glow in ipairs(customCursor.glowEffects) do
        if glow.texture then
            local r, g, b = glow.texture:GetVertexColor()
            glow.texture:SetVertexColor(r, g, b, alpha) -- only update alpha
        end
    end
end


function EasyCursorTrails.InitializeGlowFrames()
    -- 1. Retrieve the current profile or fallback to "Default"
    local currentProfileName = EasyCursorTrailsDB.currentProfile or "Default"
    local currentProfile = EasyCursorTrailsDB.profiles[currentProfileName]
    
    if not currentProfile then
        --print("EasyCursorTrails: Current profile '" .. currentProfileName .. "' not found. Falling back to 'Default'.")
        currentProfileName = "Default"
        currentProfile = EasyCursorTrailsDB.profiles["Default"]
        if not currentProfile then
            error("EasyCursorTrails: 'Default' profile is missing or not a table. Cannot initialize glow frames.")
            return
        end
    end
    
    -- 2. Safety check: Ensure customCursor and its texture exist
    if not customCursor or not customCursor.texture then
        --print("EasyCursorTrails: customCursor or its texture is not initialized.")
        return
    end
    
    -- 3. Initialize glowEffects table if it doesn't exist
    if not customCursor.glowEffects then
        customCursor.glowEffects = {}
    else
        -- Clear existing glows
        for _, glow in ipairs(customCursor.glowEffects) do
            glow:Hide()
            glow:ClearAllPoints()
            glow:SetParent(nil)
        end
        customCursor.glowEffects = {}
    end
    
    -- 4. Retrieve settings from current profile or use defaults
    local NUM_GLOWS    = currentProfile.numGlows or EasyCursorTrails.defaults.numGlows or 30
    local cursorWidth  = customCursor:GetWidth() or 64

    -- 🚧 Clamp + debug radius to avoid hidden fallbacks
    local savedRadius = currentProfile.glowRadius
    if not savedRadius then
        EasyCursorTrails.HandleError("⚠ glowRadius not found in profile — defaulting to fallback")
    end
    local userRadius = math.max(0.01, tonumber(savedRadius) or EasyCursorTrails.defaults.glowRadius or 0.1)

    local cursorRadius = cursorWidth / 1.5

    -- Retrieve scaling factors from current profile (set via sliders)
    local horizontalScale = currentProfile.horizontalScale or EasyCursorTrails.defaults.horizontalScale or 1.0 -- Width scaling
    local verticalScale   = currentProfile.verticalScale or EasyCursorTrails.defaults.verticalScale or 2.0 -- Height scaling
    local enableRotation   = currentProfile.enableRotation or EasyCursorTrails.defaults.enableRotation or false -- Rotation toggle
    
    -- 5. Loop to create each glow segment
    for i = 1, NUM_GLOWS do
        -- Create a new frame for the glow
        local glow = CreateFrame("Frame", nil, customCursor, "BackdropTemplate")
        glow:SetSize(8 * horizontalScale, 16 * verticalScale) -- Apply scaling for pointiness
        glow:SetFrameStrata("HIGH")
        glow:SetFrameLevel(customCursor:GetFrameLevel() + 3)
    
        -- Create and configure the texture for the glow
        glow.texture = glow:CreateTexture(nil, "OVERLAY")
        glow.texture:SetAllPoints(true)
        glow.texture:SetBlendMode("ADD")
        glow.texture:SetTexture("Interface\\GLUES\\MODELS\\UI_Draenei\\GenericGlow64") -- Replace with custom texture if desired
    
        -- Adjust glow intensity
        local glowIntensity = math.max(0, math.min(1, currentProfile.glowIntensity or EasyCursorTrails.defaults.glowIntensity or 1)) -- Clamp between 0 and 1
        glow.texture:SetVertexColor(1, 1, 1, glowIntensity)
    
        -- Calculate the angle for the current glow segment
        local angle = math.rad((i - 1) * (360 / NUM_GLOWS)) -- Evenly spaced angles
        local offsetX = math.cos(angle) * cursorRadius * userRadius -- X offset from cursor
        local offsetY = math.sin(angle) * cursorRadius * userRadius -- Y offset from cursor
        glow:SetPoint("CENTER", customCursor, "CENTER", offsetX, offsetY) -- Position the glow
    
        -- Apply rotation to the texture if enabled
        if enableRotation and glow.texture.SetRotation then
            glow.texture:SetRotation(angle)
        end
    
        -- Show the glow segment
        glow:Show()
    
        -- Add the glow segment to the glowEffects table
        table.insert(customCursor.glowEffects, glow)
    end
end

function EasyCursorTrails.InitializeTrailFrames()
    -- 1. Retrieve the current profile or fallback to "Default"
    local currentProfileName = EasyCursorTrailsDB.currentProfile or "Default"
    local currentProfile = EasyCursorTrailsDB.profiles[currentProfileName]
    
    if not currentProfile then
        currentProfileName = "Default"
        currentProfile = EasyCursorTrailsDB.profiles["Default"]
        if not currentProfile then
            error("EasyCursorTrails: 'Default' profile is missing or not a table. Cannot initialize trail frames.")
            return
        end
    end
    
    -- 2. Safety check: Ensure customCursor and its texture exist
    if not customCursor or not customCursor.texture then
        return
    end
    
    -- 3. Initialize trailEffects table if it doesn't exist
    if not customCursor.trailEffects then
        customCursor.trailEffects = {}
    else
        -- Clear existing trails
        for _, trail in ipairs(customCursor.trailEffects) do
            trail:Hide()
            trail:ClearAllPoints()
            trail:SetParent(nil)
        end
        customCursor.trailEffects = {}
    end
    
    -- 4. Retrieve trail settings from current profile or use EasyCursorTrails.defaults
    local NUM_TRAILS      = currentProfile.numTrails or EasyCursorTrails.defaults.numTrails or 10
    local trailSpacing    = currentProfile.trailSpacing or EasyCursorTrails.defaults.trailSpacing or 10
    local trailRadius     = currentProfile.trailRadius or EasyCursorTrails.defaults.trailRadius or 20
    local trailIntensity  = math.max(0.1, math.min(1, currentProfile.trailIntensity or EasyCursorTrails.defaults.trailIntensity or 1))
    
    local previousTrail = nil
    
    -- 5. Loop to create each trail segment
    for i = 1, NUM_TRAILS do
        local trail = CreateFrame("Frame", nil, customCursor, "BackdropTemplate")
        trail:SetSize(8, 8)
        trail:SetFrameStrata("LOW")
        trail:SetFrameLevel(customCursor:GetFrameLevel() + 2)

        trail.texture = trail:CreateTexture(nil, "OVERLAY")
        trail.texture:SetAllPoints(true)
        trail.texture:SetBlendMode("ADD")
        trail.texture:SetTexture("Interface\\GLUES\\MODELS\\UI_Draenei\\GenericGlow64")
        trail.texture:SetVertexColor(1, 1, 1, trailIntensity)

        -- ✅ Add ripple control and indexing
        trail._trailIndex = i
        trail._rippleShown = nil

        if currentProfile.connectTrails then
            if previousTrail then
                trail:SetPoint("CENTER", previousTrail, "CENTER", trailSpacing, 0)
            else
                trail:SetPoint("CENTER", customCursor, "CENTER", 0, 0)
            end
        else
            local angle = math.rad((i - 1) * (360 / NUM_TRAILS))
            local offsetX = math.cos(angle) * trailRadius
            local offsetY = math.sin(angle) * trailRadius
            trail:SetPoint("CENTER", customCursor, "CENTER", offsetX, offsetY)
        end

        trail:Show()
        table.insert(customCursor.trailEffects, trail)

        if currentProfile.connectTrails then
            previousTrail = trail
        end
    end
end


function EasyCursorTrails.UpdateGlowFrames()
    -- Ensure that customCursor and its texture exist.
    if not customCursor or not customCursor.texture then
        return
    end

    -- Set a local reference to the defaults table.
    local defaults = EasyCursorTrails.defaults

    -- Initialize glow frames if needed.
    EasyCursorTrails.InitializeGlowFrames()

    local cursorWidth   = customCursor:GetWidth() or 64
    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile] or {}
    local glowRadius    = tonumber(profile.glowRadius)    or defaults.glowRadius
    local glowSize      = tonumber(profile.glowSize)      or defaults.glowSize
    local glowThickness = tonumber(profile.glowThickness) or defaults.glowThickness
    local numGlows      = math.max(1, math.min(tonumber(profile.numGlows) or 30, 30))
    local alpha         = profile.glowIntensity or defaults.glowIntensity

    local currentGlows = #customCursor.glowEffects
    if currentGlows > numGlows then
        for i = currentGlows, numGlows + 1, -1 do
            local glow = table.remove(customCursor.glowEffects, i)
            if glow then
                glow:Hide()
                glow:SetParent(nil)
                if glow.texture then
                    glow.texture:SetTexture(nil)
                end
            end
        end
    elseif currentGlows < numGlows then
        for i = currentGlows + 1, numGlows do
            local glow = CreateFrame("Frame", nil, customCursor)
            glow:SetSize(16, 16)
            glow:SetFrameStrata("HIGH")
            glow:SetFrameLevel(customCursor:GetFrameLevel() + 3)
            local tex = glow:CreateTexture(nil, "OVERLAY")
            tex:SetAllPoints(true)
            tex:SetBlendMode("ADD")
            tex:SetTexture("Interface\\GLUES\\MODELS\\UI_Draenei\\GenericGlow64")
            tex:SetVertexColor(1, 1, 1)
            glow.texture = tex
            glow:Hide()
            table.insert(customCursor.glowEffects, glow)
        end
    end

    local shortName       = EasyCursorTrailsDB.selectedCursorTextureName
    local patternKey      = shortName and EasyCursorTrails.cursorGlowMapping[shortName] or nil
    local patternFunction = patternKey and EasyCursorTrails.dynamicPatterns[patternKey] or nil

    local cursorRadius = cursorWidth / 5.5
    local coords = nil

    if patternFunction then
        local patternCount = EasyCursorTrailsDB.patternGlowCount or defaults.patternGlowCount
        coords = patternFunction(patternCount)
    end

    if coords then
        for i, glow in ipairs(customCursor.glowEffects) do
            if coords[i] and i <= numGlows then
                local x = coords[i].x
                local y = coords[i].y
                local scaleFactor = (glowRadius * cursorRadius) / 20
                local offsetX = x * scaleFactor
                local offsetY = y * scaleFactor
                glow:ClearAllPoints()
                glow:SetPoint("CENTER", customCursor, "CENTER", offsetX, offsetY)
                local size = (cursorWidth * glowSize) * glowThickness
                glow:SetSize(size, size)
                glow.texture:SetAlpha(alpha)
                glow:Show()
            else
                glow:Hide()
            end
        end
    else
        -- Fallback to a circular arrangement.
        local angleStep = (numGlows > 0) and (360 / numGlows) or 0
        for i, glow in ipairs(customCursor.glowEffects) do
            if i <= numGlows and glow and glow.texture then
                local angle = math.rad((i - 1) * angleStep)
                local offsetDist = cursorRadius * glowRadius
                local offsetX = offsetDist * math.cos(angle)
                local offsetY = offsetDist * math.sin(angle)
                glow:ClearAllPoints()
                glow:SetPoint("CENTER", customCursor, "CENTER", offsetX, offsetY)
                local size = (cursorWidth * glowSize) * glowThickness
                glow:SetSize(size, size)
                glow.texture:SetAlpha(alpha)
                glow:Show()
            else
                glow:Hide()
            end
        end
    end

    if EasyCursorTrails.ApplySelectedGlowEffect then
        EasyCursorTrails.ApplySelectedGlowEffect()
    end
end




function EasyCursorTrails.InitializeCustomCursor()
    -- 1) Retrieve the current profile or fallback to "Default"
    local currentProfileName = EasyCursorTrailsDB.currentProfile or "Default"
    local currentProfile = EasyCursorTrailsDB.profiles[currentProfileName]
    if not currentProfile then
        -- Fallback if somehow missing
        currentProfile = EasyCursorTrailsDB.profiles["Default"] or {}
    end

    -- 2) Create the custom cursor frame if it doesn't exist
    if not customCursor then
        customCursor = CreateFrame("Frame", "EasyCursorCustomCursor", UIParent, "BackdropTemplate")
        customCursor:SetPoint("CENTER", UIParent, "CENTER")
        customCursor:EnableMouse(false)
    end

    -- 3) Apply the saved frame strata from profile or use "MEDIUM" as fallback
    local frameStrata = currentProfile.cursorFrameStrata or "MEDIUM"
    customCursor:SetFrameStrata(frameStrata)

    -- 4) Set cursor size from the profile (or default if not found)
    local cursorSize = currentProfile.cursorSize or (EasyCursorTrails.defaults.cursorSize or 32)
    customCursor:SetSize(cursorSize, cursorSize)

    -- 5) Ensure we have a texture to draw on
    if not customCursor.texture then
        customCursor.texture = customCursor:CreateTexture(nil, "OVERLAY")
        customCursor.texture:SetAllPoints(true)
        customCursor.texture:SetBlendMode("ADD")  -- typical usage
    end

    -- 6) Retrieve the saved cursor index from the profile
    local cursorIndex = currentProfile.cursorTexture or 1
    local cursorData  = EasyCursorTrails.customCursorTextures[cursorIndex]

    -- 7) If cursorData is invalid, fallback to the default Blizzard arrow
    if not cursorData then
        customCursor.texture:SetTexture("Interface\\CURSOR\\Arrow")
        customCursor:SetScript("OnUpdate", nil)
        currentProfile.selectedCursorTextureName = "Default"
    else
        -- Helper to strip path -> filename (without extension)
        local function extractFilename(path)
            local filename = path:match("([^/\\]+)$") or ""
            return filename:gsub("%.tga", ""):gsub("%.blp", "")
        end

        -- 7a) Record the name of the selected cursor texture
        if cursorData.texture then
            currentProfile.selectedCursorTextureName = extractFilename(cursorData.texture)
        elseif (cursorData.textures and #cursorData.textures > 0) then
            currentProfile.selectedCursorTextureName = extractFilename(cursorData.textures[1])
        else
            currentProfile.selectedCursorTextureName = "Unknown"
        end

        -- 7b) Animated or static cursors
        if cursorData.animated and cursorData.textures then
            local totalFrames       = #cursorData.textures
            local animationDuration = cursorData.animationDuration or 1

            -- Set the first frame initially
            customCursor.texture:SetTexture(cursorData.textures[1])

            -- Use OnUpdate to flip through frames
            customCursor:SetScript("OnUpdate", function(self, elapsed)
                self.elapsedTime = (self.elapsedTime or 0) + elapsed
                local frameIndex = math.floor(
                    (self.elapsedTime % animationDuration) / animationDuration * totalFrames
                ) + 1

                local texturePath = cursorData.textures[frameIndex] or "Interface\\CURSOR\\Arrow"
                self.texture:SetTexture(texturePath)
            end)
        else
            -- Just a single static texture
            customCursor.texture:SetTexture(cursorData.texture or "Interface\\CURSOR\\Arrow")
            customCursor:SetScript("OnUpdate", nil)
        end
    end

    -- 8) (Re)initialize glow effects if needed
    if not customCursor.glowEffects or #customCursor.glowEffects == 0 then
        EasyCursorTrails.InitializeGlowFrames() -- create glow frames
    end

    -- 9) Update the glow frames to match your settings (e.g. size, color, pattern)
    EasyCursorTrails.UpdateGlowFrames()

    -- 10) (Re)apply any glow effect or animations you want around the cursor
    EasyCursorTrails.ApplySelectedGlowEffect()

    -- 11) Finally, ensure the custom cursor is visible
    customCursor:Show()
end



---------------------------------------------------------
-- UpdateCustomCursorPosition:
---------------------------------------------------------
-- This is the function that repositions your custom cursor overlay based on the system cursor.
function EasyCursorTrails.UpdateCustomCursorPosition()
    if not customCursor then
        return
    end

    -- Retrieve the active profile or fall back to "Default"
    local cp = EasyCursorTrailsDB.currentProfile or "Default"
    local profile = EasyCursorTrailsDB.profiles[cp] or EasyCursorTrailsDB.profiles["Default"]
    if not profile then
        return
    end

    -- Obtain user-defined offsets (if any)
    local xOffset = profile.cursorOffsetX or 0
    local yOffset = profile.cursorOffsetY or 0

    -- Get the system cursor’s position.
    local x, y = GetCursorPosition()
    
    -- Adjust the coordinates for UI scaling.
    local scale = UIParent:GetEffectiveScale()
    local computedX = (x / scale) + xOffset
    local computedY = (y / scale) + yOffset

    -- Immediately reposition the custom cursor overlay.
    customCursor:ClearAllPoints()
    customCursor:SetPoint("CENTER", UIParent, "BOTTOMLEFT", computedX, computedY)
    customCursor:Show()
end

---------------------------------------------------------
-- High-Frequency Custom Cursor Update:
-- We use C_Timer.NewTicker to update the custom cursor position
-- at a very high frequency (every 0.005 seconds, ~200 Hz).
-- This is our best effort to keep the overlay in sync with the system cursor.
---------------------------------------------------------
if C_Timer then
    if not EasyCursorTrails.CustomCursorTicker then
        EasyCursorTrails.CustomCursorTicker = C_Timer.NewTicker(0.001, function()
            EasyCursorTrails.UpdateCustomCursorPosition()
  
        end)
    end
else
    -- If C_Timer is unavailable, fall back to an OnUpdate handler.
    if not EasyCursorTrails.CustomCursorFrameUpdater then
        local updateFrame = CreateFrame("Frame", "EasyCursorTrailsCursorUpdater", UIParent)
        updateFrame:SetAllPoints(UIParent)
        updateFrame:SetFrameStrata("TOOLTIP")
        updateFrame:SetFrameLevel(100)
        updateFrame:SetScript("OnUpdate", function(self, elapsed)
            EasyCursorTrails.UpdateCustomCursorPosition()
          end)
        EasyCursorTrails.CustomCursorFrameUpdater = updateFrame
    end
end



function EasyCursorTrails.UpdateCustomCursorSize(size)
    if type(size) ~= "number" then
        EasyCursorTrails.HandleError("UpdateCustomCursorSize: 'size' is not a number. Received: " .. tostring(size))
        ---- ----print("Debug: 'size' is of type " .. type(size))
        return
    end

    if customCursor then
        ---- ----print(string.format("Debug: Setting customCursor size to %d", size))
        customCursor:SetSize(size, size)
        EasyCursorTrails.UpdateGlowFrames()
    end
end

-- Helper function to save settings to the profile
function SaveSetting(key, value)
    if EasyCursorTrailsDB and EasyCursorTrailsDB.profiles and EasyCursorTrailsDB.currentProfile then
        EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile][key] = value
        -- ----print(string.format("EasyCursorTrails: '%s' set to index %d. Saved to profile '%s'.", key, value, EasyCursorTrailsDB.currentProfile))
    else
        -- ----print("EasyCursorTrails: Failed to save setting. Profile data is missing.")
    end
end


function EasyCursorTrails.ClearAllTrailShadows()
    for _, pool in pairs(EasyCursorTrails.trailPool or {}) do
        for _, trail in ipairs(pool) do
            local shadow = trail.shadowFrame
            if shadow then
                shadow:Hide()
                shadow:SetParent(nil)
                trail.shadowFrame = nil
                trail:SetScript("OnUpdate", nil)
            end
        end
    end
end

function EasyCursorTrails.RefreshTrailShadows()
    EasyCursorTrails.ClearAllTrailShadows()
    for _, pool in pairs(EasyCursorTrails.trailPool or {}) do
        for _, trail in ipairs(pool) do
            if not trail.shadowFrame then
                EasyCursorTrails.SpawnTrailShadow(trail)
            end
        end
    end
end


function EasyCursorTrails.InitializeEffects()
    local profile = EasyCursorTrails.currentProfileTable or EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    if not profile then return end

    -- 🔥 Fire
    if profile.enableFire then
        if EasyCursorTrails.StartFireTicker then
            EasyCursorTrails.StartFireTicker()
        end
        if EasyCursorTrails.UpdateFireVisualTraits then
            EasyCursorTrails.UpdateFireVisualTraits()
        end
    end

    -- 💨 Smoke Trails
    if profile.enableSmokeTrails then
        if EasyCursorTrails.StartSmokeEffect then
            EasyCursorTrails.StartSmokeEffect()
        end
    end

    -- 🌫️ Smoke Glow (legacy or alternate)
    if profile.enableSmoke then
        if EasyCursorTrails.StartSmokeTicker then
            EasyCursorTrails.StartSmokeTicker()
        end
    end

    -- ⚡ Lightning Sparks
    if profile.enableLightningSparks then
        EasyCursorTrails.StartLightningSparkEffect()
    else
        EasyCursorTrails.StopLightningSparkEffect()
    end


    -- 🔗 Static Arcs
    if profile.enableStaticArcs then
        if EasyCursorTrails.StartStaticArcEffect then
            EasyCursorTrails.StartStaticArcEffect()
        end
    end

    -- 🌠 Star Trails
    if profile.enableStars then
        if EasyCursorTrails.StartStarTrailEffect then
            EasyCursorTrails.StartStarTrailEffect()
        end
    end

    -- ✨ Twinkle Stars
    if profile.enableTwinkleStars then
        if EasyCursorTrails.StartTwinkleStarsEffect then
            EasyCursorTrails.StartTwinkleStarsEffect()
        end
    end

    -- 🌸 Spring Season Trails
    if profile.enableSpringSeasonTrails then
        if EasyCursorTrails.StartSpringSeasonEffect then
            EasyCursorTrails.StartSpringSeasonEffect()
        end
    end

    -- 🔥 Embers
    if profile.enableEmbers then
        EasyCursorTrails.StartEmberTicker()
    else
        EasyCursorTrails.StopEmberTicker()
    end

    -- 🌟 Star Embers
    if profile.enableStarEmbers then
        EasyCursorTrails.StartStarTicker()
    else
        EasyCursorTrails.StopStarTicker()
    end

    -- ✨ Sparkles
    if profile.enableEmberSparkles then
        if EasyCursorTrails.StartSparkleTicker then
            EasyCursorTrails.StartSparkleTicker()
        elseif EasyCursorTrails.SpawnSparkles then
            EasyCursorTrails.SpawnSparkles()
        end
        if EasyCursorTrails.UpdateSparkleVisualTraits then
            EasyCursorTrails.UpdateSparkleVisualTraits()
        end
    end
end


function EasyCursorTrails.RebuildTrails()
    local currentProfileName = EasyCursorTrails.currentProfileName or "Default"
    local currentProfile = EasyCursorTrails.currentProfileTable

    if not currentProfile then
        currentProfile = EasyCursorTrailsDB.profiles[currentProfileName]
        EasyCursorTrails.currentProfileTable = currentProfile
        EasyCursorTrails.currentProfileName = currentProfileName
        if not currentProfile then
            EasyCursorTrails.HandleError("RebuildTrails: '" .. currentProfileName .. "' profile is missing or invalid.")
            return
        end
    end

    -- 🧭 Reset directional offset if disabled
    if not currentProfile.enableDirectionalOffset then
        currentTrailOffsetX, currentTrailOffsetY = 0, 0
        targetTrailOffsetX, targetTrailOffsetY = 0, 0
    end

   
    -- 🖌️ Utility: Update swatch color
    local function updateSwatch(picker, color)
        if picker and color then
            if picker.SetColorRGBA then
                picker:SetColorRGBA(color.r or 1, color.g or 1, color.b or 1, color.a or 1)
            elseif picker.swatch then
                picker.swatch:SetColorTexture(color.r or 1, color.g or 1, color.b or 1, color.a or 1)
            end
        end
    end

    -- 🎨 Centralized defaults
    EasyCursorTrails.GetDefaultColor = function(effectKey)
        local defaults = {
            shadowTrailColor = { r = 0, g = 0, b = 0, a = 0.4 },
            fireColor = { r = 1, g = 0.3, b = 0, a = 1 },
            emberColor = { r = 1, g = 0.6, b = 0.2, a = 1 },
            smokeColor = { r = 0.4, g = 0.4, b = 0.4, a = 0.4 },
            lightningSparkColor = { r = 0.8, g = 0.8, b = 1, a = 1 },
            starColor = { r = 1, g = 1, b = 1, a = 1 },
            twinkleStarsColor = { r = 1, g = 1, b = 1, a = 1 },
            springSeasonColor = { r = 0.5, g = 1, b = 0.5, a = 1 },
        }
        return defaults[effectKey]
    end

    -- 🔄 Sync effects
local effects = {
    { key = "twinkleStars",      flag = "enableTwinkleStars",      colorKey = "twinkleStarsColor" },
    { key = "staticArc",         flag = "enableStaticArc",         colorKey = "staticArcColor" },
    { key = "lightningEmbers",   flag = "enableLightningEmbers",   colorKey = "lightningEmberColor" },
    { key = "fireEffect",        flag = "enableFireEffect",        colorKey = "fireColor" },
    { key = "ember",             flag = "enableEmbers",            colorKey = "emberColor" }, -- 🧯 Fixed ambiguity
    { key = "lightningSpark",    flag = "enableLightningSpark",    colorKey = "lightningSparkColor" },
    { key = "starEmbers",        flag = "enableStarEmbers",        colorKey = "starColor" },
    { key = "smokeEffect",       flag = "enableSmokeEffect",       colorKey = "smokeColor" },
    { key = "springSeason",      flag = "enableSpringSeason",      colorKey = "springSeasonColor" },
}

for _, effect in ipairs(effects) do
    local checkbox = EasyCursorTrails[effect.key .. "Checkbox"]
    if checkbox then
        checkbox:SetChecked(currentProfile[effect.flag] or false)
    end
    updateSwatch(EasyCursorTrails[effect.key .. "ColorPicker"], currentProfile[effect.colorKey])
end


    -- 🧼 Reset trail shadows checkbox
    if EasyCursorTrails.trailShadowsCheckbox then
        EasyCursorTrails.trailShadowsCheckbox:SetChecked(false)
        local onClick = EasyCursorTrails.trailShadowsCheckbox:GetScript("OnClick")
        if onClick then onClick(EasyCursorTrails.trailShadowsCheckbox) end
    end

    -- 🧹 Reset & reattach shadow trails
    EasyCursorTrails.RefreshTrailShadows()

    local defaultShadowColor = EasyCursorTrails.GetDefaultColor("shadowTrailColor")
    currentProfile.shadowTrailColor = CopyTable(defaultShadowColor)
    EasyCursorTrails.SaveToCurrentProfile("shadowTrailColor", defaultShadowColor)
    updateSwatch(EasyCursorTrails.shadowColorPicker, defaultShadowColor)

    -- 🚧 TODO: Your trail pool rebuild logic should come here —
    -- something like: EasyCursorTrails.BuildTrailPool()

    -- 👻 Then re-spawn shadows for new trails
    for _, pool in pairs(EasyCursorTrails.trailPool or {}) do
        for _, trail in ipairs(pool) do
            EasyCursorTrails.SpawnTrailShadow(trail)
        end
    end



    local defaultShadowColor = EasyCursorTrails.GetDefaultColor("shadowTrailColor")
    currentProfile.shadowTrailColor = CopyTable(defaultShadowColor)
    EasyCursorTrails.SaveToCurrentProfile("shadowTrailColor", defaultShadowColor)
    updateSwatch(EasyCursorTrails.shadowColorPicker, defaultShadowColor)


    -- ✅ Validate and sanitize profile settings
    local settingsToValidate = {
        { key = "trailSizeStart",      type = "number", min = 1,   max = 200 },
        { key = "trailSizeEnd",        type = "number", min = 1,   max = 200 },
        { key = "trailCount",          type = "number", min = 1,   max = 200 },
        { key = "trailSpacing",        type = "number", min = 1,   max = 50 },
        { key = "trailIntensity",      type = "number", min = 0.1, max = 1.0 },
        { key = "glowIntensityFactor", type = "number", min = 0.0, max = 1.0 },
        { key = "chainSegment",        type = "number", min = 1,   max = 100 },
        { key = "trailLayerCount",     type = "number", min = 1,   max = 20 },
        { key = "enableTrails",        type = "boolean" },
    }

    for _, setting in ipairs(settingsToValidate) do
        local val = currentProfile[setting.key]
        local def = EasyCursorTrails.defaults[setting.key]
        if type(val) ~= setting.type or (setting.type == "number" and (val < setting.min or val > setting.max)) then
            EasyCursorTrails.HandleError(("Setting '%s' invalid. Resetting to default."):format(setting.key))
            currentProfile[setting.key] = def
        end
    end

    currentProfile.trailLayerCount = math.floor(currentProfile.trailLayerCount)
    currentProfile.trailSpacing = currentProfile.chainSegment or EasyCursorTrails.defaults.chainSegment or 10
  -- 🧼 Clear previous trails
if EasyCursorTrails.trailPool then
    for _, layerPool in pairs(EasyCursorTrails.trailPool) do
        for _, trail in ipairs(layerPool) do
            if trail then
                -- 💫 Stop animations
                if trail.twinkleSpark and trail.twinkleSpark.ag then trail.twinkleSpark.ag:Stop() end
                if trail.twinkleSpark then trail.twinkleSpark:Hide() trail.twinkleSpark = nil end

                if trail.staticArc and trail.staticArc.ag then trail.staticArc.ag:Stop() end
                if trail.staticArc then trail.staticArc:Hide() trail.staticArc = nil end

                -- ⚡ Clear visual effects
                EasyCursorTrails.ClearLightningSparkEffect(trail)
                EasyCursorTrails.ClearFireGlow(trail)
 

                -- 🌠 Cleanup glow layers
                if trail.glowLayers then
                    for _, g in ipairs(trail.glowLayers) do
                        if g.texture then g.texture:Hide() g.texture:SetTexture(nil) end
                        g:Hide()
                        g:SetParent(nil)
                    end
                    trail.glowLayers = nil
                end

                -- 🎨 Ensure texture is hidden
                if trail.texture then
                    trail.texture:Hide()
                    trail.texture:SetTexture(nil)
                    trail.texture:SetParent(nil)
                end

                -- 🧽 Clear trail frame
                trail:Hide()
                trail:ClearAllPoints()
                trail:SetParent(nil)
            end
        end
    end
end
EasyCursorTrails.trailPool = {}


    if not currentProfile.enableTrails then return end

    -- 🛠 Create trail frames
    local layerCount  = currentProfile.trailLayerCount
    local trailCount  = currentProfile.trailCount
    local sStart      = currentProfile.trailSizeStart
    local sEnd        = currentProfile.trailSizeEnd
    local chainSeg    = currentProfile.trailSpacing
    local trailStrata = currentProfile.trailFrameStrata or "TOOLTIP"
    local textureIdx  = currentProfile.trailTexture or 1
    local trailTex    = (EasyCursorTrails.trailTextures[textureIdx] and EasyCursorTrails.trailTextures[textureIdx].texture)
                        or "Interface\\CURSOR\\Arrow"

    local glowFactor = currentProfile.glowIntensityFactor or 1

    for layer = 1, layerCount do
        EasyCursorTrails.trailPool[layer] = {}
        for i = 1, trailCount do
            local size = sStart + ((sEnd - sStart) * ((i - 1) / (trailCount - 1)))
            local trail = CreateFrame("Frame", nil, UIParent, "BackdropTemplate")
            trail:SetSize(size, size)
            trail:SetFrameStrata(trailStrata)
            trail:Show()

            local tex = trail:CreateTexture(nil, "BACKGROUND")
            tex:SetAllPoints()
            tex:SetTexture(trailTex)
            tex:SetVertexColor(1, 1, 1, currentProfile.trailIntensity or 0.5)
            trail.texture = tex


            if i == 1 then
                local x, y = GetCursorPosition()
                trail:SetPoint("CENTER", UIParent, "BOTTOMLEFT", x, y)
            else
                trail:SetPoint("CENTER", EasyCursorTrails.trailPool[layer][i - 1], "CENTER", chainSeg, 0)
            end

            trail.twinkleSpark   = nil
            trail.staticArc      = nil
            trail.lightningSpark = nil
            trail.fireGlow       = nil
            trail.glowLayers     = nil

            table.insert(EasyCursorTrails.trailPool[layer], trail)
        end
    end

 
        -- ✨ Apply color overlays & restore trail texture
        for _, layerPool in pairs(EasyCursorTrails.trailPool) do
            for i, trail in ipairs(layerPool) do
                EasyCursorTrails.ApplyColorEffectTrail(trail, i)

                -- 🖼 Restore texture visibility (if ApplyColorEffectTrail altered it)
                if trail.texture then
                    trail.texture:SetTexture(trailTex)
                    trail.texture:SetVertexColor(1, 1, 1, currentProfile.trailIntensity or 0.5)
                    trail.texture:Show()
                end

                -- 🛠 Patch glow intensity
                if trail.glowLayers then
                    for _, glowLayer in ipairs(trail.glowLayers) do
                        if glowLayer.texture then
                            local r, g, b, a = glowLayer.texture:GetVertexColor()
                            glowLayer.texture:SetVertexColor(
                                r * glowFactor,
                                g * glowFactor,
                                b * glowFactor,
                                glowFactor == 0 and 0 or a * glowFactor
                            )
                        end
                    end
                end
            end
        end


    -- 🔥 FireGlow ticker
        if EasyCursorTrails.fireEffectCheckbox then
            local fireEnabled = currentProfile.enableFireEffect or false
            EasyCursorTrails.fireEffectCheckbox:SetChecked(fireEnabled)

            if fireEnabled then
                local clickFunc = EasyCursorTrails.fireEffectCheckbox:GetScript("OnClick")
                if clickFunc then clickFunc(EasyCursorTrails.fireEffectCheckbox) end
            else
                if EasyCursorTrails.fireEffectTicker then
                    EasyCursorTrails.fireEffectTicker:Cancel()
                    EasyCursorTrails.fireEffectTicker = nil
                end
                if EasyCursorTrails.ClearFireGlow then
                    for _, layerPool in pairs(EasyCursorTrails.trailPool or {}) do
                        for _, trail in ipairs(layerPool) do
                            EasyCursorTrails.ClearFireGlow(trail)
                        end
                    end
                end
            end
        end
EasyCursorTrails.InitializeEffects()
end




function EasyCursorTrails.ReapplyEffects(trail, index)
    local profile = EasyCursorTrails.currentProfileTable
    if not profile then return end

    EasyCursorTrails.ApplyColorEffectTrail(trail, index)

    -- Restore texture visibility
    if trail.texture then
        local textureIdx = profile.trailTexture or 1
        local trailTex = (EasyCursorTrails.trailTextures[textureIdx] and EasyCursorTrails.trailTextures[textureIdx].texture)
                         or "Interface\\CURSOR\\Arrow"
        trail.texture:SetTexture(trailTex)
        trail.texture:SetVertexColor(1, 1, 1, profile.trailIntensity or 0.5)
        trail.texture:Show()
    end

    -- Patch glow intensity
    local glowFactor = profile.glowIntensityFactor or 1
    if trail.glowLayers then
        for _, glowLayer in ipairs(trail.glowLayers) do
            if glowLayer.texture then
                local r, g, b, a = glowLayer.texture:GetVertexColor()
                glowLayer.texture:SetVertexColor(
                    r * glowFactor,
                    g * glowFactor,
                    b * glowFactor,
                    glowFactor == 0 and 0 or a * glowFactor
                )
            end
        end
    end
end

function EasyCursorTrails.CleanupTrail(trail)
    if not trail then return end

    if trail.twinkleSpark and trail.twinkleSpark.ag then trail.twinkleSpark.ag:Stop() end
    if trail.twinkleSpark then trail.twinkleSpark:Hide() trail.twinkleSpark = nil end

    if trail.staticArc and trail.staticArc.ag then trail.staticArc.ag:Stop() end
    if trail.staticArc then trail.staticArc:Hide() trail.staticArc = nil end

    EasyCursorTrails.ClearLightningSparkEffect(trail)
    EasyCursorTrails.ClearFireGlow(trail)

    if trail.glowLayers then
        for _, g in ipairs(trail.glowLayers) do
            if g.texture then g.texture:Hide() g.texture:SetTexture(nil) end
            g:Hide()
            g:SetParent(nil)
        end
        trail.glowLayers = nil
    end

    if trail.texture then
        trail.texture:Hide()
        trail.texture:SetTexture(nil)
        trail.texture:SetParent(nil)
    end

    trail:Hide()
    trail:ClearAllPoints()
    trail:SetParent(nil)
end





EasyCursorTrails.movementEffects = {
    -- 1: No Effect
    [1] = function(layerDirection, separationFactor, offsetDistance, profile, f, movementAngle, maximumOffset)
        return {0, 0}
    end,

    -- 2: Linear Separation
    [2] = function(layerDirection, separationFactor, offsetDistance, profile, f, movementAngle, maximumOffset)
        local offsetX = offsetDistance * math.cos(movementAngle)
        local offsetY = offsetDistance * math.sin(movementAngle)
        return {offsetX, offsetY}
    end,

    -- 3: Spiral Expansion
    [3] = function(layerDirection, separationFactor, offsetDistance, profile, f, movementAngle, maximumOffset)
        local spiralSpeed = 20 * math.pi * separationFactor
        local radius = offsetDistance * separationFactor
        local offsetX = radius * math.cos(spiralSpeed + movementAngle)
        local offsetY = radius * math.sin(spiralSpeed + movementAngle)
        return {offsetX, offsetY}
    end,

    -- 4: Zig‑Zag
    [4] = function(layerDirection, separationFactor, offsetDistance, profile, f, movementAngle, maximumOffset)
        local zigzagFactor = 25 * math.sin(separationFactor * 10 * math.pi)
        local offsetX = offsetDistance * math.cos(movementAngle) + zigzagFactor
        local offsetY = offsetDistance * math.sin(movementAngle)
        return {offsetX, offsetY}
    end,

    -- 5: Wave Oscillation
    [5] = function(layerDirection, separationFactor, offsetDistance, profile, f, movementAngle, maximumOffset)
        local waveAmplitude = 25 * math.sin(2 * math.pi * separationFactor)
        local offsetX = offsetDistance * math.cos(movementAngle)
        local offsetY = offsetDistance * math.sin(movementAngle) + waveAmplitude
        return {offsetX, offsetY}
    end,

    -- 6: Galactic Orbit
    [6] = function(layerDirection, separationFactor, offsetDistance, profile, f, movementAngle, maximumOffset)
        local orbitRadius = 15 * separationFactor
        local orbitSpeed = 3 * math.pi * separationFactor
        local offsetX = orbitRadius * math.cos(orbitSpeed + movementAngle)
        local offsetY = orbitRadius * math.sin(orbitSpeed + movementAngle)
        return {offsetX, offsetY}
    end,

    -- 7: Firestorm
    [7] = function(layerDirection, separationFactor, offsetDistance, profile, f, movementAngle, maximumOffset)
        local fireJitter = 10 * math.random(-1, 1)
        local offsetX = offsetDistance * math.cos(movementAngle) + fireJitter
        local offsetY = offsetDistance * math.sin(movementAngle) + fireJitter
        return {offsetX, offsetY}
    end,

    -- 8: Wind Spiral
    [8] = function(layerDirection, separationFactor, offsetDistance, profile, f, movementAngle, maximumOffset)
        local windShift = 20 * math.cos(separationFactor * 6 * math.pi)
        local offsetX = offsetDistance * math.cos(movementAngle) + windShift
        local offsetY = offsetDistance * math.sin(movementAngle)
        return {offsetX, offsetY}
    end,

    -- 9: Spiral (Existing Example)
    [9] = function(layerDirection, separationFactor, offsetDistance, profile, trailIndex, movementAngle, maximumOffset)
        local cursorSize = (profile.cursorSize or 80)
        local baseFrac = 0.2
        local maxFrac  = 0.5
        local radius = cursorSize * (baseFrac + (maxFrac - baseFrac) * separationFactor)
        local spinSpeed = 5
        -- Here, you expect the caller to pass trailIndex (or use f) to distinguish layers.
        local effectiveDirection = (trailIndex % 1 == 0) and -1 or 1
        local baseAngle = movementAngle or 0
        local timeAngle = baseAngle + (GetTime() * spinSpeed * effectiveDirection) + (trailIndex * 0.6)
        local offsetX = radius * math.cos(timeAngle)
        local offsetY = radius * math.sin(timeAngle)
        return { offsetX, offsetY }
    end,

    -- New Effects (Indices 10 to 19)
    -- 10: Radial Burst
    [10] = function(layerDirection, separationFactor, offsetDistance, profile, f, movementAngle, maximumOffset)
        local burstSpeed = 10
        local angle = movementAngle + math.sin(GetTime() * burstSpeed + separationFactor * 2 * math.pi)
        local offsetX = offsetDistance * math.cos(angle)
        local offsetY = offsetDistance * math.sin(angle)
        return { offsetX, offsetY }
    end,

    -- 11: Vortex Spiral
    [11] = function(layerDirection, separationFactor, offsetDistance, profile, f, movementAngle, maximumOffset)
        local vortexSpeed = 10
        local angle = movementAngle + (GetTime() * vortexSpeed * layerDirection) + (separationFactor * math.pi)
        local factor = 1 - separationFactor * 1.5
        local offsetX = offsetDistance * factor * math.cos(angle)
        local offsetY = offsetDistance * factor * math.sin(angle)
        return { offsetX, offsetY }
    end,

    -- 12: Oscillating Swirl
    [12] = function(layerDirection, separationFactor, offsetDistance, profile, f, movementAngle, maximumOffset)
        local oscillation = math.sin(GetTime() * 3 + separationFactor * 2 * math.pi)
        local angle = movementAngle + layerDirection * oscillation * 0.5
        local offsetX = offsetDistance * math.cos(angle)
        local offsetY = offsetDistance * math.sin(angle)
        return { offsetX, offsetY }
    end,

    -- 13: Drifting Fog
    [13] = function(layerDirection, separationFactor, offsetDistance, profile, f, movementAngle, maximumOffset)
        local driftAngle = movementAngle + math.sin(GetTime() + separationFactor * 2 * math.pi) * 0.9
        local offsetX = offsetDistance * math.cos(driftAngle)
        local offsetY = offsetDistance * math.sin(driftAngle)
        return { offsetX, offsetY }
    end,

    -- 14: Counter Wave
    [14] = function(layerDirection, separationFactor, offsetDistance, profile, f, movementAngle, maximumOffset)
        local waveSpeed = 2
        local frequency = 4
        local waveOffset = math.sin(GetTime() * waveSpeed + separationFactor * frequency * math.pi)
        local offsetX = offsetDistance * math.cos(movementAngle) + waveOffset * (maximumOffset or 15)
        local offsetY = offsetDistance * math.sin(movementAngle) + waveOffset * (maximumOffset or 15)
        return { offsetX, offsetY }
    end,

    -- 15: Chaotic Jab
    [15] = function(layerDirection, separationFactor, offsetDistance, profile, f, movementAngle, maximumOffset)
        local chaos = math.sin(GetTime() * 10 + separationFactor * 10)
        local offsetX = offsetDistance * math.cos(movementAngle) + chaos * (maximumOffset or 10)
        local offsetY = offsetDistance * math.sin(movementAngle) + chaos * (maximumOffset or 10)
        return { offsetX, offsetY }
    end,

    -- 16: Heartbeat Pulse
    [16] = function(layerDirection, separationFactor, offsetDistance, profile, f, movementAngle, maximumOffset)
        local pulse = (math.sin(GetTime() * 2 * math.pi) + 1) / 2  -- cycles between 0 and 1
        local offsetX = offsetDistance * pulse * math.cos(movementAngle)
        local offsetY = offsetDistance * pulse * math.sin(movementAngle)
        return { offsetX, offsetY }
    end,

    -- 17: Pendulum Swing
    [17] = function(layerDirection, separationFactor, offsetDistance, profile, f, movementAngle, maximumOffset)
        local swing = math.sin(GetTime() * 1.5 + separationFactor * math.pi)
        local angle = movementAngle + swing * 0.5
        local offsetX = offsetDistance * math.cos(angle)
        local offsetY = offsetDistance * math.sin(angle)
        return { offsetX, offsetY }
    end,

    -- 18: Elliptical Orbit
    [18] = function(layerDirection, separationFactor, offsetDistance, profile, f, movementAngle, maximumOffset)
        local orbitSpeed = 5
        local orbitAngle = GetTime() * orbitSpeed + separationFactor * 2 * math.pi
        local a = offsetDistance                  -- horizontal semi-axis
        local b = offsetDistance * 0.5            -- vertical semi-axis
        local offsetX = a * math.cos(orbitAngle)
        local offsetY = b * math.sin(orbitAngle)
        return { offsetX, offsetY }
    end,

    -- 19: Rising Spiral
    [19] = function(layerDirection, separationFactor, offsetDistance, profile, f, movementAngle, maximumOffset)
        local spiralSpeed = 6
        local verticalRise = offsetDistance * 0.3   -- constant upward drift
        local angle = GetTime() * spiralSpeed * layerDirection + separationFactor * math.pi
        local offsetX = offsetDistance * math.cos(angle)
        local offsetY = offsetDistance * math.sin(angle) + verticalRise
        return { offsetX, offsetY }
    end,
    -- 20: Cosmic Ripple
    [20] = function(layerDirection, separationFactor, offsetDistance, profile, f, movementAngle, maximumOffset)
        -- Use the provided movement angle or default to 0.
        local baseAngle = movementAngle or 0
        -- Define a ripple frequency in radians per second (2π gives roughly one pulse per second).
        local rippleFrequency = 2 * math.pi  
        -- Calculate the ripple value. We include layerDirection and separationFactor in the phase so
        -- that different layers (or segments) will pulse a bit differently.
        local ripple = math.sin(GetTime() * rippleFrequency + separationFactor * math.pi * layerDirection)
        -- Modulate the base offsetDistance by up to ±30% (adjust 0.3 for higher/lower amplitude).
        local modulatedDistance = offsetDistance * (1 + 0.3 * ripple)
        -- Calculate final offsets along the base movement angle.
        local offsetX = modulatedDistance * math.cos(baseAngle)
        local offsetY = modulatedDistance * math.sin(baseAngle)
        return { offsetX, offsetY }
    end,

}


    

    
-- ============================
-- EasyCursorTrails Addon Code
-- ============================
-- 🔄 Essential cursor tracking variables
EasyCursorTrails.previousCursorX = nil
EasyCursorTrails.previousCursorY = nil
EasyCursorTrails.cursorPositions = {}
EasyCursorTrails.cursorStopped   = false

-- ⏱ Initialize ring buffer
EasyCursorTrails.headIndex     = 0
EasyCursorTrails.bufferSize    = 200     -- Adjust for trail depth
EasyCursorTrails.skipSpacing   = 10      -- Controls visual spacing
EasyCursorTrails.cursorHistory = {}

-- 💡 Prefill buffer with empty positions to avoid nil
for i = 1, EasyCursorTrails.bufferSize do
    EasyCursorTrails.cursorHistory[i] = { x = 0, y = 0 }
end

-- 🧭 Initialize spawn management
EasyCursorTrails._initTime = GetTime()          -- Warm-up logic
EasyCursorTrails.lastSpawnX = nil               -- For proximity throttling
EasyCursorTrails.lastSpawnY = nil
EasyCursorTrails.lastSpawnTime = GetTime()

-- 🧨 Add your shadow density map if needed
EasyCursorTrails.shadowDensityMap = {}


-- 🌀 Velocity and directional offset controls
local handleTrailMovementTimer     = 10
local handleTrailMovementInterval  = 0.02  -- ~every frame

-- 📏 Configurable magnitude (can be set per profile)
local defaultTrailOffsetMagnitude = 0.05  -- fallback if profile.trailOffsetMagnitude is missing

local previousCursorX, previousCursorY = nil, nil
local currentTrailOffsetX, currentTrailOffsetY = 0, 0
local targetTrailOffsetX, targetTrailOffsetY = 0, 0


function EasyCursorTrails.HandleTrailMovement(elapsed)
    handleTrailMovementTimer = handleTrailMovementTimer + elapsed
    if handleTrailMovementTimer < handleTrailMovementInterval then return end
    handleTrailMovementTimer = 0

    local profile = EasyCursorTrailsDB.profiles[EasyCursorTrailsDB.currentProfile]
    if not profile then
        EasyCursorTrails.HandleError("HandleTrailMovement: Current profile not found.")
        return
    end

    local maximumOffset     = tonumber(profile.trailLayerSpacingSlider) or 30
    local initialSeparation = tonumber(profile.trailInitialSeparation) or 30
    local connectTrails     = profile.connectTrails
    local layerCount        = math.floor(tonumber(profile.trailLayerCount) or 14)
    local trailCount        = tonumber(profile.trailCount) or 10
    local chainSegment      = tonumber(profile.chainSegment) or 10.0

    local effectIndex       = profile.trailMovementEffect or 1
    local movementFunc = EasyCursorTrails.movementEffects and EasyCursorTrails.movementEffects[effectIndex]
        or function() return {0, 0} end

    local cursorX, cursorY = GetCursorPosition()
    local scale = UIParent:GetEffectiveScale()
    cursorX, cursorY = cursorX / scale, cursorY / scale
    if EasyCursorTrails.UpdateCustomCursorPosition then EasyCursorTrails.UpdateCustomCursorPosition() end

    if not profile.enableTrails then
        for _, layerTrails in pairs(EasyCursorTrails.trailPool or {}) do
            for _, trail in ipairs(layerTrails) do trail:Hide() end
        end
        return
    end

    EasyCursorTrails.cursorHistory = EasyCursorTrails.cursorHistory or {}
    EasyCursorTrails.headIndex     = EasyCursorTrails.headIndex or 0
    EasyCursorTrails._initTime     = EasyCursorTrails._initTime or GetTime()
    local bufferSize               = tonumber(EasyCursorTrails.bufferSize) or 100

    local cursorMoved = false
    local dx, dy = 0, 0
    if EasyCursorTrails.previousCursorX and EasyCursorTrails.previousCursorY then
        dx = cursorX - EasyCursorTrails.previousCursorX
        dy = cursorY - EasyCursorTrails.previousCursorY
        local distSq = dx * dx + dy * dy
        if distSq >= 0.01 then
            cursorMoved = true
            local dist = math.sqrt(distSq)
            local steps = math.floor(dist / chainSegment)
            for s = 1, steps do
                local t = s / (steps + 1)
                local interX = EasyCursorTrails.previousCursorX + dx * t
                local interY = EasyCursorTrails.previousCursorY + dy * t
                EasyCursorTrails.headIndex = (EasyCursorTrails.headIndex % bufferSize) + 1
                EasyCursorTrails.cursorHistory[EasyCursorTrails.headIndex] = { x = interX, y = interY }
            end
        end
    end

    -- 🧭 Directional Offset (global, reactive to movement)
local directionalOffsetX, directionalOffsetY = 0, 0
if profile.enableDirectionalOffset then
    local movementLength = math.sqrt(dx * dx + dy * dy)
    local unitX, unitY = 0, 0
    if movementLength > 0 then
        unitX = dx / movementLength
        unitY = dy / movementLength
    end

    local baseOffset = math.min(tonumber(profile.trailOffsetMagnitude) or defaultTrailOffsetMagnitude, 1.0)
    targetTrailOffsetX = -unitX * baseOffset
    targetTrailOffsetY = -unitY * baseOffset

    local smoothing = 0.2
    currentTrailOffsetX = currentTrailOffsetX + (targetTrailOffsetX - currentTrailOffsetX) * smoothing
    currentTrailOffsetY = currentTrailOffsetY + (targetTrailOffsetY - currentTrailOffsetY) * smoothing

    directionalOffsetX = currentTrailOffsetX
    directionalOffsetY = currentTrailOffsetY
end

    -- 🧭 Directional Offset (optional)
    local dynamicOffsetX, dynamicOffsetY = 0, 0
    if profile.enableDirectionalOffset then
        local movementLength = math.sqrt(dx * dx + dy * dy)
        local unitX, unitY = 0, 0
        if movementLength > 0 then
            unitX = dx / movementLength
            unitY = dy / movementLength
        end

        local baseOffset = tonumber(profile.trailOffsetMagnitude) or defaultTrailOffsetMagnitude
        targetTrailOffsetX = -unitX * baseOffset
        targetTrailOffsetY = -unitY * baseOffset

        local smoothing = 0.2
        currentTrailOffsetX = currentTrailOffsetX + (targetTrailOffsetX - currentTrailOffsetX) * smoothing
        currentTrailOffsetY = currentTrailOffsetY + (targetTrailOffsetY - currentTrailOffsetY) * smoothing

        dynamicOffsetX = currentTrailOffsetX
        dynamicOffsetY = currentTrailOffsetY
    end

    -- 🧱 Slider Offset (always applied)
    local sliderOffsetX = tonumber(profile.trailOffsetX) or 0
    local sliderOffsetY = tonumber(profile.trailOffsetY) or 0

    -- 🧮 Final base offset for trail placement
    local baseTrailOffsetX = sliderOffsetX + dynamicOffsetX
    local baseTrailOffsetY = sliderOffsetY + dynamicOffsetY

    if cursorMoved then
        EasyCursorTrails.headIndex = (EasyCursorTrails.headIndex % bufferSize) + 1
        EasyCursorTrails.cursorHistory[EasyCursorTrails.headIndex] = { x = cursorX, y = cursorY }
    else
        local rawMult     = tonumber(EasyCursorTrails.currentProfileTable.trailUpdateMultiplier) or 1
        local iterations  = math.min(math.max(1, math.floor(rawMult / 8 + 0.02)), 10)
        for i = 1, iterations do
            local nextIndex = (EasyCursorTrails.headIndex % bufferSize) + 1
            local prevIndex = nextIndex - 1 < 1 and bufferSize or nextIndex - 1
            local prevPos   = EasyCursorTrails.cursorHistory[prevIndex] or { x = cursorX, y = cursorY }
            local blendFactor = 0.5
            EasyCursorTrails.cursorHistory[nextIndex] = {
                x = prevPos.x + blendFactor * (cursorX - prevPos.x),
                y = prevPos.y + blendFactor * (cursorY - prevPos.y)
            }
            EasyCursorTrails.headIndex = nextIndex
        end
    end

    EasyCursorTrails.previousCursorX = cursorX
    EasyCursorTrails.previousCursorY = cursorY

    local layerDirections = {}
    for layer = 1, layerCount do
        layerDirections[layer] = (layerCount > 1) and (((layer - 1) / (layerCount - 1)) * (2 * math.pi)) or 0
    end

    local separationFactors, offsetDistances = {}, {}
    for i = 1, trailCount do
        local frac = (i - 1) / math.max(trailCount - 1, 1)
        separationFactors[i] = frac
        offsetDistances[i] = initialSeparation + frac * (maximumOffset - initialSeparation)
    end

    local trailPool = EasyCursorTrails.trailPool
    for layer = 1, layerCount do
        local layerTrails = trailPool and trailPool[layer]
        if not layerTrails then
            EasyCursorTrails.HandleError("Missing trailPool for layer " .. layer)
            break
        end

        local layerAngle = layerDirections[layer] or 0
        for i = 1, trailCount do
            local trail = layerTrails[i]
            if trail then
                local posIndex = EasyCursorTrails.headIndex - i
                if posIndex < 1 then posIndex = posIndex + bufferSize end
                local pos = EasyCursorTrails.cursorHistory[posIndex]
                local prevIndex = posIndex - 1 < 1 and bufferSize or posIndex - 1
                local nextPos = EasyCursorTrails.cursorHistory[prevIndex]

                local tooSoon = (GetTime() - EasyCursorTrails._initTime < 0.3)
                local badPos = not pos or not nextPos or (pos.x == 0 and pos.y == 0)
                if tooSoon or badPos then
                    trail:Hide()
                else
                    local dx, dy = pos.x - nextPos.x, pos.y - nextPos.y
                    local angle = math.atan2(dy, dx)
                    trail.texture:SetRotation(angle)

                    local frac = separationFactors[i]
                    local dist = offsetDistances[i]
                    local offsetXY = movementFunc(layerAngle, frac, dist, profile, i, angle, maximumOffset)
                    local effectX = offsetXY[1] or 0
                    local effectY = offsetXY[2] or 0

                    local cosA, sinA = math.cos(layerAngle), math.sin(layerAngle)
                    local layerOffsetX = effectX + dist * cosA
                    local layerOffsetY = effectY + dist * sinA

                    -- Scale directional offset based on trail index (i = 1 is head)
                    -- 🧭 Per-trail directional offset based on local movement
                    local trailDX = pos.x - nextPos.x
                    local trailDY = pos.y - nextPos.y
                    local trailLength = math.sqrt(trailDX * trailDX + trailDY * trailDY)

                    local trailUnitX, trailUnitY = 0, 0
                    if trailLength > 0 then
                        trailUnitX = trailDX / trailLength
                        trailUnitY = trailDY / trailLength
                    end

                   local movementLength = math.sqrt(dx * dx + dy * dy)
local unitX, unitY = 0, 0
if movementLength > 0 then
    unitX = dx / movementLength
    unitY = dy / movementLength
end

local baseOffset = math.min(tonumber(profile.trailOffsetMagnitude) or defaultTrailOffsetMagnitude, 1.0)
targetTrailOffsetX = -unitX * baseOffset
targetTrailOffsetY = -unitY * baseOffset

-- Smooth transition
local smoothing = 0.2
currentTrailOffsetX = currentTrailOffsetX + (targetTrailOffsetX - currentTrailOffsetX) * smoothing
currentTrailOffsetY = currentTrailOffsetY + (targetTrailOffsetY - currentTrailOffsetY) * smoothing

-- Final offset to apply to all trails
local directionalOffsetX = currentTrailOffsetX
local directionalOffsetY = currentTrailOffsetY



                    local finalX = pos.x + sliderOffsetX + directionalOffsetX + layerOffsetX
                    local finalY = pos.y + sliderOffsetY + directionalOffsetY + layerOffsetY


                                        trail:ClearAllPoints()
                    trail:SetPoint("CENTER", UIParent, "BOTTOMLEFT", finalX, finalY)

                    if EasyCursorTrails.ApplyColorEffectTrail then
                        EasyCursorTrails.ApplyColorEffectTrail(trail, i)
                    end

                    local distSqToCursor = (pos.x - cursorX)^2 + (pos.y - cursorY)^2
                    if connectTrails and distSqToCursor < 25 then
                        trail:Hide()
                    else
                        trail:Show()
                    end
                end
            end
        end
    end

    -- 🧼 Cleanup logic for static trails when not connecting and cursor hasn't moved
    if not connectTrails and not cursorMoved then
        for layer = 1, layerCount do
            for _, trail in ipairs(trailPool[layer] or {}) do
                trail:Hide()
            end
        end
    end
end



-- Function to sort textures alphabetically by name within each category
local function SortTrailTextures()
    for category, textures in pairs(EasyCursorTrails.trailTextures) do
        table.sort(textures, function(a, b)
            return a.name < b.name
        end)
        --print(string.format("EasyCursorTrails: Sorted trailTextures[%d] alphabetically by name.", category))
    end
end

function EasyCursorTrails.InitializeAddon()
    -- 1) Ensure the DB structure is OK
    EasyCursorTrails.InitializeEasyCursorTrailsDB()

    -- Init saved variables and merge
    EasyCursorTrailsDB = EasyCursorTrailsDB or {}
    EasyCursorTrails:MergeDefaults(EasyCursorTrailsDB, EasyCursorTrails.defaults)

    -- 2) Profile setup
    EasyCursorTrails.InitializeProfile()
    EasyCursorTrails.LoadCurrentProfile()

    -- 🛡️ Prevent UI callbacks during sync
    EasyCursorTrails.isSyncingUI = true

    -- ✅ Sync UI controls to loaded profile
    if EasyCursorTrails.RefreshSettingsUI then
        EasyCursorTrails.RefreshSettingsUI()
    else
        EasyCursorTrails.HandleError("RefreshSettingsUI is missing.")
    end

    EasyCursorTrails.isSyncingUI = false

    -- 3) Settings menu
    if EasyCursorTrails.InitializeSettingsMenu then
        EasyCursorTrails.InitializeSettingsMenu()
    else
        EasyCursorTrails.HandleError("InitializeSettingsMenu is missing.")
    end

    -- 4) Custom cursor
    if EasyCursorTrails.InitializeCustomCursor then
        EasyCursorTrails.InitializeCustomCursor()
    else
        EasyCursorTrails.HandleError("InitializeCustomCursor is missing.")
    end

    -- 5) Glow position
    if EasyCursorTrails.UpdateGlowBelowCursor then
        EasyCursorTrails.UpdateGlowBelowCursor()
    end

    -- 6) Live Preview Initialization 🌟
    EasyCursorTrails.TrailPreview = CreateFrame("Frame", "TrailPreview", UIParent)
    EasyCursorTrails.TrailPreview:SetSize(64, 64)
    EasyCursorTrails.TrailPreview:SetPoint("CENTER", UIParent, "CENTER", 0, 200)
    EasyCursorTrails.TrailPreview:SetFrameStrata("TOOLTIP")
    EasyCursorTrails.TrailPreview:Show()

    local previewTex = EasyCursorTrails.TrailPreview:CreateTexture(nil, "OVERLAY")
    previewTex:SetAllPoints()
    previewTex:SetBlendMode("ADD")
    previewTex:SetTexture("Interface\\AddOns\\EasyCursorTrails\\Media\\GlowTexture.tga")
    EasyCursorTrails.TrailPreview.texture = previewTex
    EasyCursorTrails.TrailPreview.texture:Show()

    EasyCursorTrails.TrailPreview.glowLayers = {}
    for i = 1, 2 do
        local glowFrame = CreateFrame("Frame", nil, EasyCursorTrails.TrailPreview)
        glowFrame:SetSize(64 + (i * 20), 64 + (i * 20))
        glowFrame:SetPoint("CENTER", EasyCursorTrails.TrailPreview, "CENTER")
        glowFrame:SetFrameStrata("TOOLTIP")

        local glowTex = glowFrame:CreateTexture(nil, "OVERLAY")
        glowTex:SetTexture("Interface\\AddOns\\EasyCursorTrails\\Media\\GlowTexture.tga")
        glowTex:SetBlendMode("ADD")
        glowTex:SetAllPoints(true)
        glowFrame.texture = glowTex

        glowFrame:Show()
        table.insert(EasyCursorTrails.TrailPreview.glowLayers, glowFrame)
    end

    -- 7) Pulse defaults
    EasyCursorTrails.pulseValueTrail = 0.5
    EasyCursorTrails.pulseDirectionTrail = 1
    EasyCursorTrailsDB.pulseStep = EasyCursorTrailsDB.pulseStep or 0.02
    EasyCursorTrailsDB.pulseMin  = EasyCursorTrailsDB.pulseMin  or 0.3
    EasyCursorTrailsDB.pulseMax  = EasyCursorTrailsDB.pulseMax  or 1.0

    -- 8) Color and trail updates
    local animationUpdateFrame = CreateFrame("Frame")
    animationUpdateFrame:SetScript("OnUpdate", function(_, elapsed)
        EasyCursorTrails.colorIndexTrail = (EasyCursorTrails.colorIndexTrail or 0) + (elapsed * 300)
        if EasyCursorTrails.colorIndexTrail >= 360 then
            EasyCursorTrails.colorIndexTrail = EasyCursorTrails.colorIndexTrail - 360
        end

        if EasyCursorTrails.UpdatePulseValue then
            EasyCursorTrails.UpdatePulseValue()
        end

        if EasyCursorTrails.trailPool then
            for _, layer in pairs(EasyCursorTrails.trailPool) do
                for _, trail in ipairs(layer) do
                    if trail and trail.index then
                        EasyCursorTrails.ApplyColorEffectTrail(trail, trail.index)
                    end
                end
            end
        end
    end)

    -- 9) Static Arc Effect Ticker
    function EasyCursorTrails:OnEnable()
        C_Timer.NewTicker(0.15, function()
            local profile = EasyCursorTrails.currentProfileTable
            if not (profile and profile.enableStaticArc and EasyCursorTrails.trailPool) then return end

            local poolCount = #EasyCursorTrails.trailPool
            if poolCount < 1 then return end

            local now = GetTime()
            for _ = 1, 2 do
                local layerIndex = math.random(1, poolCount)
                local pool = EasyCursorTrails.trailPool[layerIndex]
                if pool and #pool > 1 then
                    local i = math.random(1, #pool)
                    local trail = pool[i]

                    if trail and (not EasyCursorTrails.lastArcTime[trail] or now - EasyCursorTrails.lastArcTime[trail] > 0.25) then
                        local arcColor = profile.staticArcColor or { r = 1, g = 1, b = 1, a = 1 }
                        EasyCursorTrails.ApplyStaticArcEffect(trail, i, arcColor)
                        EasyCursorTrails.lastArcTime[trail] = now
                    end
                end
            end
        end)
    end

    if type(EasyCursorTrails.OnEnable) == "function" then
        EasyCursorTrails:OnEnable()
    end

    -- ✅ Normalize trail textures after reload to prevent deformation
    C_Timer.After(0.5, function()
        if EasyCursorTrails.trailPool then
            for _, layer in pairs(EasyCursorTrails.trailPool) do
                for _, trail in ipairs(layer) do
                    EasyCursorTrails.ResetTrailTexture(trail)
                end
            end
        end
    end)
end




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

eventFrame:SetScript("OnEvent", function(_, event, addonName)
    if event == "ADDON_LOADED" and addonName == "EasyCursorTrails" then
        -- 🔧 Initialize core systems
        if EasyCursorTrails.InitializeAddon then
            EasyCursorTrails.InitializeAddon()
        else
            EasyCursorTrails.HandleError("InitializeAddon function is missing.")
        end

        if EasyCursorTrails.InitializeEffects then
            EasyCursorTrails.InitializeEffects()
        else
            EasyCursorTrails.HandleError("InitializeEffects function is missing.")
        end

        -- 📦 Load current profile
        local profileName = EasyCursorTrailsDB.currentProfile or "Default"
        local profile = EasyCursorTrailsDB.profiles[profileName]

        if not profile then
            EasyCursorTrails.HandleError("Profile '" .. profileName .. "' not found. Creating default.")
            profile = CopyTable(EasyCursorTrails.defaults or {})
            EasyCursorTrailsDB.profiles[profileName] = profile
        end

        EasyCursorTrails.currentProfileTable = profile

        -- 🧼 Sanitize profile values
        if EasyCursorTrails.SanitizeProfileState then
            EasyCursorTrails.SanitizeProfileState(profile)
        end

        -- 🛡️ Prevent UI callbacks during sync
        EasyCursorTrails.isSyncingUI = true

        -- 🎛️ Sync UI controls to profile
        if EasyCursorTrails.RefreshSettingsUI then
            EasyCursorTrails.RefreshSettingsUI()
        else
            EasyCursorTrails.HandleError("RefreshSettingsUI function is missing.")
        end

        -- ✅ Done syncing
        EasyCursorTrails.isSyncingUI = false
    end
end)


-- Initialize an OnUpdate handler for cursor effects
local updateInterval = 0.05 -- Update every 0.05 seconds
local accumulatedTime = 0 -- Accumulator for elapsed time

local frame = CreateFrame("Frame")
frame:SetScript("OnUpdate", function(_, elapsed)
    -- Accumulate elapsed time
    accumulatedTime = accumulatedTime + elapsed
    
    -- Check if enough time has passed for the next update
    if accumulatedTime >= updateInterval then
        -- Ensure ApplyColorEffectCursor exists before calling
        if EasyCursorTrails.ApplyColorEffectCursor then
            EasyCursorTrails.ApplyColorEffectCursor(accumulatedTime) -- Pass the accumulated time
        else
            EasyCursorTrails.HandleError("ApplyColorEffectCursor function is missing.")
        end
        
        -- Reset the accumulator while preserving leftover time
        accumulatedTime = accumulatedTime % updateInterval
    end
end)


-- Update Frame for Animations and Trail Updates
local updateFrame = CreateFrame("Frame")
updateFrame:SetScript("OnUpdate", function(self, elapsed)
    -- Increment colorIndexTrail for smooth cycling
    EasyCursorTrails.colorIndexTrail = (EasyCursorTrails.colorIndexTrail or 0) + (elapsed * 60)

    -- Keep colorIndexTrail within bounds (0-360 degrees)
    if EasyCursorTrails.colorIndexTrail >= 360 then
        EasyCursorTrails.colorIndexTrail = EasyCursorTrails.colorIndexTrail - 360
    end

    -- Update pulse value for pulsating effect
    if EasyCursorTrails.UpdatePulseValue then
        EasyCursorTrails.UpdatePulseValue()
    else
        EasyCursorTrails.HandleError("UpdatePulseValue function is missing.")
    end

    -- Handle trail movement and animations
    if EasyCursorTrails.HandleTrailMovement then
        EasyCursorTrails.HandleTrailMovement(elapsed)
    else
        EasyCursorTrails.HandleError("HandleTrailMovement function is missing.")
    end

    -- Iterate through all active trails and update their rainbow colors
    if EasyCursorTrails.trailPool and type(EasyCursorTrails.trailPool) == "table" then
        for _, trailLayer in pairs(EasyCursorTrails.trailPool) do
            for _, trail in ipairs(trailLayer) do
                if trail and trail.index and trail.texture then
                    -- Apply rainbow animation effect
                    local hue = (EasyCursorTrails.colorIndexTrail + (trail.index * 15)) % 360 / 360
                    local r, g, b = EasyCursorTrails.HSVToRGB(hue * 360, 1, 1)
                    trail.texture:SetVertexColor(r, g, b, 1)
                    trail.texture:Show()
                    trail:SetAlpha(1) -- Ensure parent isn't fading or hidden
                    trail:SetFrameStrata(trailStrata or "TOOLTIP")

                    -- Update trail visibility based on proximity to cursor
                    if EasyCursorTrails.cursorHistory and EasyCursorTrails.cursorHistory[EasyCursorTrails.headIndex] then
                        local cursorPos = EasyCursorTrails.cursorHistory[EasyCursorTrails.headIndex]
                        local dx = trail:GetLeft() - cursorPos.x
                        local dy = trail:GetTop() - cursorPos.y
                        local distanceSquared = dx * dx + dy * dy

                        if EasyCursorTrailsDB.connectTrails and distanceSquared < 100 then
                            trail:Hide()
                        else
                            trail:Show()
                        end
                    end
                end
            end
        end
    else
        EasyCursorTrails.HandleError("trailPool is missing or invalid.")
    end
end)




-- Slash Command to Toggle Settings Menu
SLASH_EASYCURSORMENU1 = "/easymenu"
SlashCmdList["EASYCURSORMENU"] = function()
    local menu = _G["EasyCursorTrailsMenu"]
    if menu then
        menu:SetShown(not menu:IsShown())
    else
       -- ----print("EasyCursorTrails Error: Settings menu frame not found. Ensure the menu is initialized.")
    end
end
