_G.LIDCOUNCIL_CreateLootProfileStateHelpers_Impl = function(deps)
  deps = type(deps) == "table" and deps or {}

  local TrimText = deps.TrimText
  local RootDB = deps.RootDB
  local DeepCopy = deps.DeepCopy
  local EnsureLootProfileDefaults = deps.EnsureLootProfileDefaults
  local EnsureLootProfilePermissionState = deps.EnsureLootProfilePermissionState
  local GetCharacterKey = deps.GetCharacterKey
  local GetLootProfileAccessInfo = deps.GetLootProfileAccessInfo
  local EnsureLootRootState = deps.EnsureLootRootState
  local GetActiveLootSession = deps.GetActiveLootSession
  local AssignNewLootProfileIdentity = deps.AssignNewLootProfileIdentity
  local MarkLootProfileAsIndependentClone = deps.MarkLootProfileAsIndependentClone
  local TouchLootProfileDomain = deps.TouchLootProfileDomain
  local CaptureCurrentLootSeasonSnapshot = deps.CaptureCurrentLootSeasonSnapshot

  local function TouchLootProfile(profile, domain)
    if type(profile) ~= "table" then return end
    if type(TouchLootProfileDomain) == "function" then
      TouchLootProfileDomain(profile, domain)
      return
    end
    profile.meta = profile.meta or {}
    profile.meta.revision = math.max(0, tonumber(profile.meta.revision) or 0) + 1
    profile.meta.updatedAt = time and time() or 0
  end

  local function TouchAllLootProfileDomains(profile)
    TouchLootProfile(profile, "settings")
    TouchLootProfile(profile, "permissions")
    TouchLootProfile(profile, "operational")
  end

  local function IsReservedProfileName(name)
    return TrimText(name) == "Simulation"
  end

  local function RepairSimulationProfileOwnership(root)
    root = root or RootDB()
    if type(root.profiles) ~= "table" or type(root.profiles.Simulation) ~= "table" then
      return false, "MISSING"
    end

    local profile = root.profiles.Simulation
    EnsureLootProfileDefaults(profile)

    local currentCharacterKey = type(GetCharacterKey) == "function" and TrimText(GetCharacterKey() or "") or ""
    if currentCharacterKey == "" then
      return false, "NO_CHARACTER"
    end

    profile.meta = type(profile.meta) == "table" and profile.meta or {}
    local storedPermissions = type(profile.meta.permissions) == "table" and profile.meta.permissions or nil
    local storedMaster = TrimText(storedPermissions and storedPermissions.master or "")
    local storedCreatedBy = TrimText(profile.meta.createdBy)

    if storedMaster ~= "" and storedCreatedBy ~= "" then
      return false, storedMaster
    end

    local permissions = EnsureLootProfilePermissionState(profile, currentCharacterKey)
    local resolvedMaster = TrimText(permissions.master)
    local changed = false

    if storedMaster == "" and resolvedMaster ~= "" then
      changed = true
    end
    if storedCreatedBy == "" and resolvedMaster ~= "" then
      profile.meta.createdBy = resolvedMaster
      changed = true
    end

    if changed then
      TouchLootProfile(profile, "permissions")
    end
    return changed, resolvedMaster
  end

  local function NormalizeLootProfileEnabledState(root, preferredProfileName)
    root = root or RootDB()
    local enabledNames = {}
    for profileName, profile in pairs(root.profiles or {}) do
      EnsureLootProfileDefaults(profile)
      if profile.settings and profile.settings.enabled then
        enabledNames[#enabledNames + 1] = tostring(profileName)
      end
    end

    if #enabledNames == 0 then
      return nil
    end
    if #enabledNames == 1 then
      return enabledNames[1]
    end

    table.sort(enabledNames, function(a, b)
      return string.lower(tostring(a or "")) < string.lower(tostring(b or ""))
    end)

    local keepName = TrimText(preferredProfileName)
    local currentProfileName = TrimText(root.currentProfile)
    if keepName == "" or not root.profiles[keepName] or not (root.profiles[keepName].settings and root.profiles[keepName].settings.enabled) then
      if currentProfileName ~= "" and root.profiles[currentProfileName] and root.profiles[currentProfileName].settings and root.profiles[currentProfileName].settings.enabled then
        keepName = currentProfileName
      else
        keepName = enabledNames[1]
      end
    end

    for profileName, profile in pairs(root.profiles or {}) do
      local shouldEnable = tostring(profileName) == tostring(keepName)
      if profile.settings.enabled ~= shouldEnable then
        profile.settings.enabled = shouldEnable
        TouchLootProfile(profile, "settings")
      end
    end

    return keepName
  end

  local function EnsureProfileRecord(root, name, opts)
    root = root or RootDB()
    root.profiles = type(root.profiles) == "table" and root.profiles or {}
    opts = type(opts) == "table" and opts or {}
    local profileName = TrimText(name)
    if profileName == "" then
      profileName = "Default"
    end
    if type(root.profiles[profileName]) ~= "table" then
      if IsReservedProfileName(profileName) and not opts.allowReservedCreate then
        return nil, profileName
      end
      root.profiles[profileName] = {
        panels = {},
        positions = {},
        spec = { auto = false, layouts = {} },
        __seeded = false,
      }
    end
    return EnsureLootProfileDefaults(root.profiles[profileName]), profileName
  end

  local function GetLootProfile(name, opts)
    local root = RootDB()
    local profile, profileName = EnsureProfileRecord(root, name or root.currentProfile or "Default", opts)
    return profile, profileName
  end

  local function GetLootProfileNames()
    local root = RootDB()
    local names = {}
    for name in pairs(root.profiles or {}) do
      names[#names + 1] = tostring(name)
    end
    table.sort(names, function(a, b)
      return string.lower(tostring(a or "")) < string.lower(tostring(b or ""))
    end)
    return names
  end

  local function SetCurrentLootProfile(name)
    local root = RootDB()
    local profile, profileName = EnsureProfileRecord(root, name)
    if type(profile) ~= "table" then
      return nil
    end
    root.currentProfile = profileName
    root.ui = root.ui or {}
    if TrimText(profileName) ~= "" and TrimText(profileName) ~= "Simulation" then
      root.ui.lastNonSimulationProfile = profileName
    end
    return profileName
  end

  local function GetEnabledLootProfileName()
    local root = RootDB()
    local currentEnabled = {}
    for profileName, profile in pairs(root.profiles or {}) do
      EnsureLootProfileDefaults(profile)
      if profile.settings and profile.settings.enabled then
        currentEnabled[#currentEnabled + 1] = tostring(profileName)
      end
    end

    if #currentEnabled == 0 then
      return nil
    end
    if #currentEnabled == 1 then
      return currentEnabled[1]
    end

    table.sort(currentEnabled, function(a, b)
      return string.lower(tostring(a or "")) < string.lower(tostring(b or ""))
    end)

    local currentProfileName = TrimText(root.currentProfile)
    if currentProfileName ~= "" then
      for _, profileName in ipairs(currentEnabled) do
        if tostring(profileName) == tostring(currentProfileName) then
          return profileName
        end
      end
    end

    return currentEnabled[1]
  end

  local function GetLootProfileId(name)
    local profile, profileName = GetLootProfile(name)
    if type(profile) ~= "table" then
      return nil
    end
    profile.meta = profile.meta or {}
    return TrimText(profile.meta.profileId) ~= "" and profile.meta.profileId or nil, profileName
  end

  local function GetLootProfileIdentityInfo(name)
    local profile, profileName = GetLootProfile(name)
    if type(profile) ~= "table" then
      return nil
    end
    profile.meta = profile.meta or {}
    local syncState = type(profile.meta.sync) == "table" and profile.meta.sync or {}
    return {
      profileName = profileName,
      profileId = TrimText(profile.meta.profileId),
      syncMode = TrimText(syncState.mode) ~= "" and syncState.mode or "LOCAL",
      origin = TrimText(syncState.origin) ~= "" and syncState.origin or "CREATE",
      cloneSourceProfileId = TrimText(syncState.cloneSourceProfileId),
      cloneSourceProfileName = TrimText(syncState.cloneSourceProfileName),
      cloneCreatedAt = tonumber(syncState.cloneCreatedAt) or nil,
      sharedSourceProfileId = TrimText(syncState.sharedSourceProfileId),
      sharedSourceProfileName = TrimText(syncState.sharedSourceProfileName),
      sharedSourceCharacter = TrimText(syncState.sharedSourceCharacter),
      sharedAppliedAt = tonumber(syncState.sharedAppliedAt) or nil,
    }
  end

  local function FindLootProfileNameById(profileId)
    local root = RootDB()
    local needle = string.lower(TrimText(profileId))
    if needle == "" then
      return nil
    end
    for profileName, profile in pairs(root.profiles or {}) do
      if type(profile) == "table" and type(profile.meta) == "table" then
        local storedId = string.lower(TrimText(profile.meta.profileId))
        if storedId ~= "" and storedId == needle then
          return tostring(profileName)
        end
      end
    end
    return nil
  end

  local function GetPrimaryLootProfileName(fallbackName)
    local enabledProfileName = TrimText(GetEnabledLootProfileName() or "")
    if enabledProfileName ~= "" then
      return enabledProfileName
    end
    local root = RootDB()
    local profile, profileName = GetLootProfile(fallbackName or root.currentProfile or "Default")
    if type(profile) == "table" then
      return profileName
    end
    if type(root.profiles) == "table" and type(root.profiles.Default) == "table" then
      return "Default"
    end
    return profileName
  end

  local function CreateLootProfile(name)
    local root = RootDB()
    local profileName = TrimText(name)
    if profileName == "" then
      return false, "Profile name is required."
    end
    if root.profiles[profileName] then
      return false, "Profile already exists."
    end
    local profile = EnsureProfileRecord(root, profileName, { allowReservedCreate = true })
    local creatorKey = type(GetCharacterKey) == "function" and TrimText(GetCharacterKey() or "") or ""
    EnsureLootProfilePermissionState(profile, creatorKey)
    if creatorKey ~= "" then
      profile.meta.createdBy = creatorKey
    end
    if type(AssignNewLootProfileIdentity) == "function" then
      AssignNewLootProfileIdentity(profile, profileName)
    end
    if type(MarkLootProfileAsIndependentClone) == "function" then
      MarkLootProfileAsIndependentClone(profile, "CREATE")
    end
    profile.settings = type(profile.settings) == "table" and profile.settings or {}
    if type(profile.settings.seasonSnapshot) ~= "table" and type(CaptureCurrentLootSeasonSnapshot) == "function" then
      profile.settings.seasonSnapshot = CaptureCurrentLootSeasonSnapshot()
    end
    TouchAllLootProfileDomains(profile)
    return true, profileName
  end

  local function DeleteLootProfile(name)
    local root = RootDB()
    local profileName = TrimText(name)
    local profile = root.profiles[profileName]
    if profileName == "" or type(profile) ~= "table" then
      return false, "Profile not found."
    end
    if profileName == "Default" then
      return false, "Default profile cannot be deleted."
    end

    EnsureLootProfileDefaults(profile)

    local syncState = type(profile.meta) == "table" and type(profile.meta.sync) == "table" and profile.meta.sync or nil
    local syncMode = string.upper(TrimText(syncState and syncState.mode or ""))
    local isSharedReplica = syncMode == "SHARED"

    local activeSession = GetActiveLootSession()
    if activeSession then
      return false, "Stop the active loot session before removing local profile copies."
    end

    local access = GetLootProfileAccessInfo(profileName)
    if not isSharedReplica and not access.canDeleteProfile then
      return false, "Your current role cannot delete this local profile copy."
    end

    local state = EnsureLootRootState(root)
    if state.profileName == profileName then
      state.active = false
      state.profileName = nil
      state.sessionId = nil
      state.host = nil
      state.startedAt = nil
    end

    root.profiles[profileName] = nil
    if root.currentProfile == profileName then
      root.currentProfile = "Default"
      EnsureProfileRecord(root, "Default")
    end
    root.ui = type(root.ui) == "table" and root.ui or {}
    if TrimText(root.ui.lastNonSimulationProfile) == profileName then
      root.ui.lastNonSimulationProfile = nil
    end
    return true, isSharedReplica and "LOCAL_COPY_REMOVED" or "PROFILE_DELETED"
  end

  local function CopyLootProfile(sourceName, targetName)
    local root = RootDB()
    local sourceProfile = root.profiles[TrimText(sourceName or "")]
    local newName = TrimText(targetName)
    if type(sourceProfile) ~= "table" then
      return false, "Source profile not found."
    end
    if newName == "" then
      return false, "Target profile name is required."
    end
    if root.profiles[newName] then
      return false, "Target profile already exists."
    end

    local copy = {
      panels = {},
      positions = {},
      spec = { auto = false, layouts = {} },
      __seeded = false,
      profileSpec = { enabled = false, mode = "SPEC", specID = nil, character = nil },
      settings = DeepCopy(type(sourceProfile.settings) == "table" and sourceProfile.settings or {}),
      sessions = {},
      lootLedger = {},
      lootLedgerMeta = {},
      lootRollStats = {},
      lootListGroups = {},
      lootLedgerView = {},
      liveBoardHistory = {},
      lootLedgerEntrySerial = 0,
      __lootLedgerDemoSeedVersion = nil,
      meta = {
        createdAt = time and time() or 0,
        updatedAt = time and time() or 0,
      },
    }

    EnsureLootProfileDefaults(copy)
    copy.settings = copy.settings or {}
    copy.settings.enabled = false
    if type(CaptureCurrentLootSeasonSnapshot) == "function" then
      copy.settings.seasonSnapshot = CaptureCurrentLootSeasonSnapshot() or copy.settings.seasonSnapshot
    end
    do
      local snapshot = type(copy.settings.seasonSnapshot) == "table" and copy.settings.seasonSnapshot or nil
      local selectedInstanceID = type(copy.settings.raid) == "table" and tonumber(copy.settings.raid.instanceID) or nil
      if selectedInstanceID and type(snapshot) == "table" and type(snapshot.raids) == "table" and #snapshot.raids > 0 then
        local allowed = false
        for _, raid in ipairs(snapshot.raids) do
          if tonumber(raid.instanceID) == selectedInstanceID then
            allowed = true
            break
          end
        end
        if not allowed then
          copy.settings.raid = {}
        end
      end
    end
    copy.meta = {
      createdAt = time and time() or 0,
      updatedAt = time and time() or 0,
    }
    local creatorKey = type(GetCharacterKey) == "function" and TrimText(GetCharacterKey() or "") or ""
    EnsureLootProfilePermissionState(copy, creatorKey)
    copy.meta.createdBy = creatorKey ~= "" and creatorKey or copy.meta.createdBy
    if type(AssignNewLootProfileIdentity) == "function" then
      AssignNewLootProfileIdentity(copy, newName)
    end
    if type(MarkLootProfileAsIndependentClone) == "function" then
      MarkLootProfileAsIndependentClone(copy, "COPY", {
        profileId = type(sourceProfile.meta) == "table" and sourceProfile.meta.profileId or nil,
        profileName = TrimText(sourceName),
      })
    end
    root.profiles[newName] = copy
    TouchAllLootProfileDomains(copy)
    return true, newName
  end

  local function ResetSimulationProfileContent(name)
    local profileName = TrimText(name)
    if profileName == "" then
      profileName = "Simulation"
    end
    if profileName ~= "Simulation" then
      return false, "Clear Content is only available for the Simulation profile."
    end
    local root = RootDB()
    if type(root.profiles) ~= "table" or type(root.profiles[profileName]) ~= "table" then
      return false, "Simulation profile not found."
    end
    local profile = GetLootProfile(profileName)
    if type(profile) ~= "table" then
      return false, "Simulation profile not found."
    end
    if GetActiveLootSession() then
      return false, "Stop the active loot session before clearing Simulation content."
    end

    profile.sessions = {}
    profile.lootLedger = {}
    profile.lootLedgerMeta = {}
    profile.lootRollStats = {}
    profile.lootListGroups = {}
    profile.lootLedgerView = {}
    profile.liveBoardHistory = {}
    profile.lootLedgerEntrySerial = 0
    profile.__lootLedgerDemoSeedVersion = nil
    profile.settings = type(profile.settings) == "table" and profile.settings or {}
    profile.settings.raid = {}
    profile.meta = type(profile.meta) == "table" and profile.meta or {}
    profile.meta.permissions = type(profile.meta.permissions) == "table" and profile.meta.permissions or {}
    profile.meta.permissions.members = {}

    TouchLootProfile(profile, "settings")
    TouchLootProfile(profile, "permissions")
    TouchLootProfile(profile, "operational")
    return true, "Simulation content cleared."
  end

  local function SetLootProfileEnabled(name, enabled)
    local root = RootDB()
    local profile, profileName = GetLootProfile(name)
    local shouldEnable = enabled and true or false
    local activeSession = GetActiveLootSession()
    local activeSessionBlockMessage = "A session is still running. Please stop the session before activating another profile."

    local hasStateChange = false
    if shouldEnable then
      for otherName, otherProfile in pairs(root.profiles or {}) do
        EnsureLootProfileDefaults(otherProfile)
        local nextEnabled = tostring(otherName) == tostring(profileName)
        if otherProfile.settings.enabled ~= nextEnabled then
          hasStateChange = true
          break
        end
      end
    else
      hasStateChange = profile.settings.enabled and true or false
    end

    if activeSession and hasStateChange then
      return false, activeSessionBlockMessage
    end

    if shouldEnable then
      for otherName, otherProfile in pairs(root.profiles or {}) do
        EnsureLootProfileDefaults(otherProfile)
        local nextEnabled = tostring(otherName) == tostring(profileName)
        if otherProfile.settings.enabled ~= nextEnabled then
          otherProfile.settings.enabled = nextEnabled
          TouchLootProfile(otherProfile, "settings")
        end
      end
      SetCurrentLootProfile(profileName)
    else
      if profile.settings.enabled then
        profile.settings.enabled = false
        TouchLootProfile(profile, "settings")
      end
    end

    return profile.settings.enabled, nil
  end

  return {
    NormalizeLootProfileEnabledState = NormalizeLootProfileEnabledState,
    EnsureProfileRecord = EnsureProfileRecord,
    RepairSimulationProfileOwnership = RepairSimulationProfileOwnership,
    TouchLootProfile = TouchLootProfile,
    GetLootProfile = GetLootProfile,
    GetLootProfileNames = GetLootProfileNames,
    SetCurrentLootProfile = SetCurrentLootProfile,
    GetEnabledLootProfileName = GetEnabledLootProfileName,
    GetPrimaryLootProfileName = GetPrimaryLootProfileName,
    GetLootProfileId = GetLootProfileId,
    GetLootProfileIdentityInfo = GetLootProfileIdentityInfo,
    FindLootProfileNameById = FindLootProfileNameById,
    CreateLootProfile = CreateLootProfile,
    DeleteLootProfile = DeleteLootProfile,
    CopyLootProfile = CopyLootProfile,
    ResetSimulationProfileContent = ResetSimulationProfileContent,
    SetLootProfileEnabled = SetLootProfileEnabled,
  }
end
