local API = rawget(_G, "LIDCOUNCIL_API")
local INTERNAL_API = type(API) == "table" and type(API.__internal) == "table" and API.__internal or nil
if type(INTERNAL_API) ~= "table" then
  error("LidCouncil missing internal API registry.")
end

INTERNAL_API.LIDCOUNCIL_CreateLootProfileRefreshHelpers_Impl = function(deps)
  deps = type(deps) == "table" and deps or {}

  local editor = deps.editor
  local RootDB = deps.RootDB
  local GetSelectedProfileName = deps.GetSelectedProfileName
  local GetLootProfile = deps.GetLootProfile
  local GetLootProfileAccessInfo = deps.GetLootProfileAccessInfo
  local GetLootProfileAccessInfoForRole = deps.GetLootProfileAccessInfoForRole
  local GetLootProfilePermissionPolicyRoleState = deps.GetLootProfilePermissionPolicyRoleState
  local GetLootProfileRoleEntries = deps.GetLootProfileRoleEntries
  local SetLootProfilePermissionPolicyValue = deps.SetLootProfilePermissionPolicyValue
  local ResetLootProfilePermissionPolicy = deps.ResetLootProfilePermissionPolicy
  local PermissionPolicyRowDefs = deps.PermissionPolicyRowDefs or {}
  local SetPermissionPolicyCellState = deps.SetPermissionPolicyCellState
  local BuildLootProfileNavRows = deps.BuildLootProfileNavRows
  local EnsureTextListButtons = deps.EnsureTextListButtons
  local ToggleLootProfileGroupCollapsed = deps.ToggleLootProfileGroupCollapsed
  local SetListButtonSelected = deps.SetListButtonSelected
  local SetTextListButtonTextColor = deps.SetTextListButtonTextColor
  local TrimText = deps.TrimText
  local GetActiveLootSession = deps.GetActiveLootSession
  local GetEnabledLootProfileName = deps.GetEnabledLootProfileName
  local GetPrimaryLootProfileName = deps.GetPrimaryLootProfileName
  local FormatLootProfileRoleLabel = deps.FormatLootProfileRoleLabel
  local BuildLootProfileRoleBuckets = deps.BuildLootProfileRoleBuckets
  local ResolveProfileMemberDisplay = deps.ResolveProfileMemberDisplay
  local ResolveProfileIconData = deps.ResolveProfileIconData
  local GetProfileClassColor = deps.GetProfileClassColor
  local ApplyProfileIcon = deps.ApplyProfileIcon
  local BuildProfileClassSummary = deps.BuildProfileClassSummary
  local RefreshProfileMemberRows = deps.RefreshProfileMemberRows
  local ApplyProfileActionButtonStyle = deps.ApplyProfileActionButtonStyle
  local CollectSeasonLootEntries = deps.CollectSeasonLootEntries
  local FindRaidEntryByProfile = deps.FindRaidEntryByProfile
  local BuildSeasonRaidNamesText = deps.BuildSeasonRaidNamesText
  local ResolvePointMode = deps.ResolvePointMode
  local ResolveRollTemplate = deps.ResolveRollTemplate
  local GetRollTemplateText = deps.GetRollTemplateText
  local ResolveRollOptionIcon = deps.ResolveRollOptionIcon
  local ResolveRaidPreviewTexture = deps.ResolveRaidPreviewTexture
  local ClearItemRuleSelection = deps.ClearItemRuleSelection
  local SetDropdownValue = deps.SetDropdownValue
  local FindSeasonLootEntry = deps.FindSeasonLootEntry
  local FormatRaidLootItemLabel = deps.FormatRaidLootItemLabel
  local RefreshRollOptionRows = deps.RefreshRollOptionRows
  local RefreshPointRuleRows = deps.RefreshPointRuleRows
  local RefreshLidTableRows = deps.RefreshLidTableRows
  local BuildRollOptionsText = deps.BuildRollOptionsText
  local BuildPointRulesText = deps.BuildPointRulesText
  local BuildLidTableSummaryText = deps.BuildLidTableSummaryText
  local LayoutProfileContent = deps.LayoutProfileContent
  local CreatePurpleOutline = deps.CreatePurpleOutline
  local ClampListPage = deps.ClampListPage
  local GetListPageForValue = deps.GetListPageForValue
  local UpdatePagerControls = deps.UpdatePagerControls
  local AssignProfileToGroup = deps.AssignProfileToGroup
  local GetLootProfileIdentityInfo = type(API) == "table" and API.LIDCOUNCIL_GetLootProfileIdentityInfo or rawget(_G, "LIDCOUNCIL_GetLootProfileIdentityInfo")
  local ExportLootProfileSnapshot = type(API) == "table" and API.LIDCOUNCIL_ExportLootProfileSnapshot or rawget(_G, "LIDCOUNCIL_ExportLootProfileSnapshot")
  local GetProfileSyncEstimate = type(API) == "table" and API.LIDCOUNCIL_GetProfileSyncEstimate or rawget(_G, "LIDCOUNCIL_GetProfileSyncEstimate")
  local PROFILE_NAV_PAGE_SIZE = 25
  local profileSizeDisplayCache = {}
  local LOCKED_ROLE_PERMISSION_POLICY = {
    COUNCIL = {
      canDeleteProfile = true,
      canOpenLiveBoard = true,
      canVote = true,
    },
    SESSION_HOST = {
      canDeleteProfile = true,
      canManageSession = true,
      canOpenLiveBoard = true,
      canVote = true,
      canAssignLoot = true,
    },
    RAIDER = {
      canDeleteProfile = true,
      canManageRights = false,
    },
  }

  local function IsPermissionPolicyLocked(role, permissionKey)
    local resolvedRole = string.upper(TrimText(role))
    local locks = LOCKED_ROLE_PERMISSION_POLICY[resolvedRole]
    return type(locks) == "table" and locks[permissionKey] ~= nil
  end

  local function ResolveInlineRollPopupSection(option)
    local section = string.upper(TrimText(type(option) == "table" and option.popupSection or ""))
    if section == "NEED" or section == "GREEDPASS" then
      return section
    end

    local pointBehavior = string.upper(TrimText(type(option) == "table" and option.pointBehavior or ""))
    if pointBehavior == "OFFSPEC" or pointBehavior == "TRANSMOG" or pointBehavior == "DISENCHANT" or pointBehavior == "NONE" then
      return "GREEDPASS"
    end

    local key = TrimText(type(option) == "table" and option.key or "")
    local label = TrimText(type(option) == "table" and option.label or "")
    local hint = string.lower(key ~= "" and key or label):gsub("[%s%-%_]+", "")
    if hint == "greed" or hint == "pass" or hint == "offspec" or hint == "transmog" or hint == "mog" or hint == "disenchant" or hint == "de" then
      return "GREEDPASS"
    end
    return "NEED"
  end

  local function GetLockedPermissionPolicyMessage(permissionKey)
    if permissionKey == "canManageRights" then
      return "Denied. Manage Rights can only be granted to Session Host or Council."
    end
    if permissionKey == "canDeleteProfile" then
      return "Delete Local Profile Copy is fixed for every role. It only removes your local copy and is blocked while a session is active."
    end
    return "Denied. Revoking this right would eliminate the purpose of this role."
  end

  local function FormatProfileSizeBytes(byteCount)
    local bytes = math.max(0, tonumber(byteCount) or 0)
    local kb = bytes / 1024
    if kb >= 10 then
      return string.format("%.0f KB (%d bytes)", kb, bytes)
    end
    return string.format("%.1f KB (%d bytes)", kb, bytes)
  end

  local function FormatProfileSizeShort(byteCount)
    local bytes = math.max(0, tonumber(byteCount) or 0)
    local kb = bytes / 1024
    if kb >= 10 then
      return string.format("%.0f KB", kb)
    end
    return string.format("%.1f KB", kb)
  end

  local function BuildProfileSyncEstimate(byteCount)
    if type(GetProfileSyncEstimate) == "function" then
      local ok, result = pcall(GetProfileSyncEstimate, byteCount)
      if ok and type(result) == "table" then
        return result
      end
    end

    local bytes = math.max(0, tonumber(byteCount) or 0)
    local chunkSize = 120
    local chunks = math.max(1, math.ceil(bytes / chunkSize))
    local messages = chunks + 2
    local intervalSeconds = 0.12
    return {
      bytes = bytes,
      chunkSize = chunkSize,
      chunks = chunks,
      messages = messages,
      intervalSeconds = intervalSeconds,
      seconds = messages * intervalSeconds,
    }
  end

  local function FormatProfileSyncExample(kb)
    local bytes = math.max(0, (tonumber(kb) or 0) * 1024)
    local estimate = BuildProfileSyncEstimate(bytes)
    return string.format("%d KB: ~%.1fs per target", kb, tonumber(estimate.seconds) or 0)
  end

  local function BuildProfileSizeCacheSignature(profileName, profile)
    local root = RootDB()
    local meta = type(profile) == "table" and type(profile.meta) == "table" and profile.meta or {}
    local revisions = type(meta.domainRevisions) == "table" and meta.domainRevisions or {}
    local ui = type(root) == "table" and type(root.ui) == "table" and root.ui or {}
    local parts = {
      TrimText(profileName),
      tostring(profile),
      TrimText(meta.profileId),
      tostring(math.max(0, tonumber(meta.revision) or 0)),
      tostring(math.max(0, tonumber(meta.updatedAt) or 0)),
      tostring(math.max(0, tonumber(type(revisions.settings) == "table" and revisions.settings.revision) or 0)),
      tostring(math.max(0, tonumber(type(revisions.permissions) == "table" and revisions.permissions.revision) or 0)),
      tostring(math.max(0, tonumber(type(revisions.operational) == "table" and revisions.operational.revision) or 0)),
      tostring(math.max(0, tonumber(type(revisions.loot) == "table" and revisions.loot.revision) or 0)),
      tostring(math.max(0, tonumber(type(revisions.session) == "table" and revisions.session.revision) or 0)),
      tostring(math.max(1, tonumber(ui.profileSyncChunkSize) or 120)),
      tostring(math.max(0, tonumber(ui.profileSyncDelaySeconds) or 0.12)),
    }
    return table.concat(parts, "\031")
  end

  local function BuildProfileSizeDisplay(profileName, profile)
    local resolvedName = TrimText(profileName)
    if resolvedName == "" then
      return nil
    end
    local signature = BuildProfileSizeCacheSignature(resolvedName, profile)
    local cached = profileSizeDisplayCache[resolvedName]
    if type(cached) == "table" and cached.signature == signature and type(cached.display) == "table" then
      return cached.display
    end
    if type(ExportLootProfileSnapshot) ~= "function" then
      return {
        text = "Profile Size: unavailable",
        lines = {
          "The profile export helper is not loaded yet.",
        },
      }
    end

    local exportStartedAt = INTERNAL_API.LIDCOUNCIL_BeginSyncPerformanceSample_Impl("editor_profile_size_export", 1)
    local ok, snapshot = pcall(ExportLootProfileSnapshot, resolvedName)
    INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl("editor_profile_size_export", exportStartedAt, {
      context = resolvedName,
    })
    if not ok or type(snapshot) ~= "string" or snapshot == "" then
      return {
        text = "Profile Size: unavailable",
        lines = {
          "The profile snapshot could not be serialized right now.",
        },
      }
    end

    local bytes = #snapshot
    local estimate = BuildProfileSyncEstimate(bytes)
    local seconds = tonumber(estimate.seconds) or 0
    local chunks = tonumber(estimate.chunks) or 0
    local messages = tonumber(estimate.messages) or 0
    local chunkSize = tonumber(estimate.chunkSize) or 0
    local intervalSeconds = tonumber(estimate.intervalSeconds) or 0
    local display = {
      text = string.format("Profile Size: %s | ~%.1fs/player", FormatProfileSizeShort(bytes), seconds),
      lines = {
        "Serialized snapshot: " .. FormatProfileSizeBytes(bytes),
        string.format("Current sync estimate: %d chunks, %d queued addon messages.", chunks, messages),
        string.format("Current chunk size: %d bytes | queue delay: %.2fs/message.", chunkSize, intervalSeconds),
        "Rough examples with the current queue settings:",
        FormatProfileSyncExample(10),
        FormatProfileSyncExample(25),
        FormatProfileSyncExample(50),
        "For a full raid push, multiply the per-target estimate by the number of players receiving the profile.",
      },
    }
    profileSizeDisplayCache[resolvedName] = {
      signature = signature,
      display = display,
    }
    return display
  end

  local function SetProfilesFeedback(owner, text, r, g, b, a)
    if not owner or not owner.lootProfilesFeedback then
      return
    end
    if owner.lootProfilesFeedback.SetText then
      owner.lootProfilesFeedback:SetText(tostring(text or ""))
    end
    if owner.lootProfilesFeedback.SetTextColor then
      owner.lootProfilesFeedback:SetTextColor(
        tonumber(r) or 0.82,
        tonumber(g) or 0.82,
        tonumber(b) or 0.86,
        tonumber(a) or 1.00
      )
    end
  end

  local function SetProfileNavButtonVariant(button, variantKey, selected)
    if not button then
      return
    end
    if not button.__profileVariantBg then
      local bg = button:CreateTexture(nil, "BORDER", nil, 0)
      bg:SetTexture("Interface\\Buttons\\WHITE8x8")
      bg:SetPoint("TOPLEFT", 1, -1)
      bg:SetPoint("BOTTOMRIGHT", -1, 1)
      bg:SetVertexColor(0, 0, 0, 0)
      button.__profileVariantBg = bg
    end
    if not button.__profileVariantAccent then
      local accent = button:CreateTexture(nil, "ARTWORK", nil, 0)
      accent:SetTexture("Interface\\Buttons\\WHITE8x8")
      accent:SetPoint("TOPLEFT", 1, -1)
      accent:SetPoint("BOTTOMLEFT", 1, 1)
      accent:SetWidth(3)
      accent:SetVertexColor(0, 0, 0, 0)
      button.__profileVariantAccent = accent
    end

    if variantKey == "SIMULATION" then
      local bgColor = selected and { 0.46, 0.10, 0.10, 0.52 } or { 0.32, 0.07, 0.07, 0.38 }
      local accentColor = selected and { 1.00, 0.56, 0.56, 0.96 } or { 0.92, 0.24, 0.24, 0.92 }
      button.__profileVariantBg:SetVertexColor(bgColor[1], bgColor[2], bgColor[3], bgColor[4])
      button.__profileVariantAccent:SetVertexColor(accentColor[1], accentColor[2], accentColor[3], accentColor[4])
    else
      button.__profileVariantBg:SetVertexColor(0, 0, 0, 0)
      button.__profileVariantAccent:SetVertexColor(0, 0, 0, 0)
    end
  end

  local function SetLockedPermissionPolicyFeedbackCell(owner, cell, permissionKey)
    if not cell then
      return
    end
    cell.__interactive = false
    cell:EnableMouse(true)
    if cell.Enable then
      cell:Enable()
    end
    cell:SetScript("OnClick", function()
      SetProfilesFeedback(owner, GetLockedPermissionPolicyMessage(permissionKey), 1.00, 0.32, 0.32, 1.00)
    end)
  end

  local function FinishPermissionPolicyUpdate(owner, profileName, roleKey, roleLabel, permissionLabel, permissionKey, desiredEnabled, ok, result, fallbackError)
    if ok then
      if owner.RequestLootProfilePageRefresh then
        owner:RequestLootProfilePageRefresh()
      elseif owner.RefreshLootProfilePage then
        owner:RefreshLootProfilePage()
      end
      local actualEnabled = desiredEnabled and true or false
      if type(GetLootProfilePermissionPolicyRoleState) == "function" then
        local refreshedRoleState = GetLootProfilePermissionPolicyRoleState(profileName, roleKey)
        if type(refreshedRoleState) == "table" and refreshedRoleState[permissionKey] ~= nil then
          actualEnabled = refreshedRoleState[permissionKey] and true or false
        end
      elseif type(result) == "table" and result[permissionKey] ~= nil then
        actualEnabled = result[permissionKey] and true or false
      end
      if actualEnabled ~= (desiredEnabled and true or false) then
        SetProfilesFeedback(owner, string.format(
          "Could not verify %s permission: %s.",
          tostring(roleLabel or "role"),
          tostring(permissionLabel or permissionKey or "?")
        ), 1.00, 0.82, 0.24, 1.00)
        return
      end
      local suffix = actualEnabled and "granted" or "revoked"
      if actualEnabled then
        SetProfilesFeedback(owner, string.format(
          "Updated %s permission: %s %s.",
          tostring(roleLabel or "role"),
          tostring(permissionLabel or permissionKey or "?"),
          suffix
        ), 0.30, 0.90, 0.36, 1.00)
      else
        SetProfilesFeedback(owner, string.format(
          "Updated %s permission: %s %s.",
          tostring(roleLabel or "role"),
          tostring(permissionLabel or permissionKey or "?"),
          suffix
        ), 1.00, 0.32, 0.32, 1.00)
      end
    else
      SetProfilesFeedback(owner, tostring(result or fallbackError or "Could not update the permission."), 1.00, 0.32, 0.32, 1.00)
    end
  end
  local EnsureLootProfileGroupDragBadge

  local function BuildLootProfileIdentitySummary(identity, includeInternalDetails)
    identity = type(identity) == "table" and identity or {}
    local syncMode = string.upper(TrimText(identity.syncMode or ""))
    local origin = string.upper(TrimText(identity.origin or ""))
    local profileId = TrimText(identity.profileId)

    local kindLabel = "Local Profile"
    if syncMode == "SHARED" then
      kindLabel = "Shared Session Copy"
    elseif origin == "COPY" or origin == "IMPORT" then
      kindLabel = "Independent Local Clone"
    end

    local sourceLabel = ""
    if syncMode == "SHARED" then
      local sourceName = TrimText(identity.sharedSourceProfileName)
      local sourceCharacter = TrimText(identity.sharedSourceCharacter)
      if sourceName ~= "" and sourceCharacter ~= "" then
        sourceLabel = " | Source: " .. sourceName .. " from " .. sourceCharacter
      elseif sourceName ~= "" then
        sourceLabel = " | Source: " .. sourceName
      elseif sourceCharacter ~= "" then
        sourceLabel = " | Source: " .. sourceCharacter
      end
    else
      local cloneSource = TrimText(identity.cloneSourceProfileName)
      if cloneSource ~= "" then
        sourceLabel = " | Based on: " .. cloneSource
      end
    end

    if not includeInternalDetails then
      return kindLabel .. sourceLabel
    end
    if profileId ~= "" then
      return string.format("Profile Details: %s | ID: %s%s", kindLabel, profileId, sourceLabel)
    end
    return "Profile Details: " .. kindLabel .. sourceLabel
  end

  local function ClearLootProfileGroupDrag(self, preserveFeedback)
    if not self then
      return nil
    end
    local state = self.__lootProfileGroupDrag
    if not state then
      return nil
    end

    if state.sourceButton and state.sourceButton.SetAlpha then
      state.sourceButton:SetAlpha(1)
    end
    if state.sourceButton and state.sourceButton.__profileDragSourceBorder then
      state.sourceButton.__profileDragSourceBorder:Hide()
    end
    if state.sourceButton and state.sourceButton.SetScript then
      state.sourceButton:SetScript("OnDragStop", nil)
    end
    for _, button in ipairs(self.lootProfileGroupButtons or {}) do
      if button and button.__profileDragDropBorder then
        if button.__profileDragDropBorder.SetBackdropBorderColor then
          button.__profileDragDropBorder:SetBackdropBorderColor(0.6588, 0.4784, 0.9098, 0.95)
        end
        button.__profileDragDropBorder:Hide()
      end
    end
    if self.__lootProfileGroupDragMonitor then
      self.__lootProfileGroupDragMonitor:Hide()
    end
    if self.__lootProfileGroupDragBadge then
      self.__lootProfileGroupDragBadge:Hide()
    end
    if (not preserveFeedback) and self.lootProfilesFeedback and self.lootProfilesFeedback.GetText and self.lootProfilesFeedback:GetText() and string.find(self.lootProfilesFeedback:GetText(), "Dragging:", 1, true) == 1 then
      self.lootProfilesFeedback:SetText("")
    end
    self.__lootProfileGroupDrag = nil
    return state
  end

  local function RefreshLootProfileAfterGroupMove(self, profileName)
    self.selectedLootProfileName = profileName
    self.selectedProfileName = profileName
    self.selectedLootProfileGroupName = nil
    self.selectedProfileGroupName = nil
    if self.RequestLootProfilePageRefresh then
      self:RequestLootProfilePageRefresh()
    elseif self.RefreshLootProfilePage then
      self:RefreshLootProfilePage()
    elseif self.Refresh then
      self:Refresh()
    end
  end

  local function SetLootProfileGroupMoveFeedback(self, text)
    if self and self.lootProfilesFeedback then
      self.lootProfilesFeedback:SetText(tostring(text or ""))
    end
  end

  local function MoveLootProfileToGroup(self, profileName, targetGroupName, sourceGroupName)
    if type(AssignProfileToGroup) ~= "function" then
      SetLootProfileGroupMoveFeedback(self, "Could not move the profile: group assignment is unavailable.")
      return false
    end
    local name = TrimText(profileName)
    if name == "" then
      SetLootProfileGroupMoveFeedback(self, "Could not move the profile: no profile was selected.")
      return false
    end
    local targetName = TrimText(targetGroupName)
    local sourceName = TrimText(sourceGroupName)
    if targetName == sourceName then
      if targetName ~= "" then
        SetLootProfileGroupMoveFeedback(self, name .. " is already in " .. targetName .. ".")
      else
        SetLootProfileGroupMoveFeedback(self, name .. " is already outside a group.")
      end
      return true
    end
    local ok = AssignProfileToGroup(name, targetName ~= "" and targetName or nil)
    if ok then
      RefreshLootProfileAfterGroupMove(self, name)
      if targetName ~= "" then
        SetLootProfileGroupMoveFeedback(self, "Moved " .. name .. " to " .. targetName .. ".")
      else
        SetLootProfileGroupMoveFeedback(self, "Removed " .. name .. " from its group.")
      end
    else
      SetLootProfileGroupMoveFeedback(self, "Could not move " .. name .. ".")
    end
    return ok
  end

  local function CursorIsOverLootProfileFrame(frame)
    if not frame or not frame.IsShown or not frame:IsShown() then
      return false
    end
    if type(MouseIsOver) == "function" then
      local ok, isOver = pcall(MouseIsOver, frame)
      if ok and isOver then
        return true
      end
    end
    if type(GetCursorPosition) ~= "function"
        or not frame.GetEffectiveScale
        or not frame.GetLeft
        or not frame.GetRight
        or not frame.GetTop
        or not frame.GetBottom then
      return false
    end
    local left, right, top, bottom = frame:GetLeft(), frame:GetRight(), frame:GetTop(), frame:GetBottom()
    if not left or not right or not top or not bottom then
      return false
    end
    local scale = tonumber(frame:GetEffectiveScale()) or 1
    if scale <= 0 then
      scale = 1
    end
    local cursorX, cursorY = GetCursorPosition()
    if not cursorX or not cursorY then
      return false
    end
    cursorX = cursorX / scale
    cursorY = cursorY / scale
    return cursorX >= left and cursorX <= right and cursorY >= bottom and cursorY <= top
  end

  local function ResolveLootProfileGroupDropTarget(self)
    local hoveredButton = nil
    local overList = false
    for _, button in ipairs(self.lootProfileGroupButtons or {}) do
      if CursorIsOverLootProfileFrame(button) then
        hoveredButton = button
        break
      end
    end
    overList = CursorIsOverLootProfileFrame(self.lootProfilesListScroll)
      or CursorIsOverLootProfileFrame(self.lootProfilesListContent)
    return hoveredButton, overList
  end

  local function CompleteLootProfileGroupDrag(self, sourceButton)
    local state = self and self.__lootProfileGroupDrag or nil
    if not state or (sourceButton and state.sourceButton ~= sourceButton) then
      return false
    end

    local hoveredButton, overList = ResolveLootProfileGroupDropTarget(self)
    local targetGroupName = hoveredButton and hoveredButton.__profileGroupName or nil
    local completedState = ClearLootProfileGroupDrag(self, true)
    if not completedState then
      return false
    end

    local classifier = type(INTERNAL_API.LIDCOUNCIL_LootEditorShared_Impl) == "table"
      and INTERNAL_API.LIDCOUNCIL_LootEditorShared_Impl.ClassifyLootProfileGroupDrop
      or nil
    local disposition, classifiedTarget
    if type(classifier) == "function" then
      disposition, classifiedTarget = classifier(targetGroupName, overList)
    elseif TrimText(targetGroupName) ~= "" then
      disposition, classifiedTarget = "GROUP", TrimText(targetGroupName)
    elseif overList then
      disposition = "UNGROUP"
    else
      disposition = "CANCEL"
    end

    if disposition == "GROUP" then
      return MoveLootProfileToGroup(self, completedState.name, classifiedTarget, completedState.sourceGroupName)
    end
    if disposition == "UNGROUP" then
      return MoveLootProfileToGroup(self, completedState.name, nil, completedState.sourceGroupName)
    end

    SetLootProfileGroupMoveFeedback(self, "Move cancelled for " .. completedState.name .. ".")
    return false
  end

  local function EnsureLootProfileGroupDragMonitor(self)
    if not self then
      return nil
    end
    if self.__lootProfileGroupDragMonitor then
      return self.__lootProfileGroupDragMonitor
    end

    local monitor = CreateFrame("Frame", nil, self)
    monitor:SetAllPoints(self)
    monitor:Hide()
    monitor:SetScript("OnUpdate", function(frame)
      local state = self.__lootProfileGroupDrag
      if not state then
        frame:Hide()
        return
      end

      local hoveredButton, overList = ResolveLootProfileGroupDropTarget(self)

      if hoveredButton ~= state.hoveredButton then
        if state.hoveredButton and state.hoveredButton.__profileDragDropBorder then
          if state.hoveredButton.__profileDragDropBorder.SetBackdropBorderColor then
            state.hoveredButton.__profileDragDropBorder:SetBackdropBorderColor(0.6588, 0.4784, 0.9098, 0.42)
          end
          state.hoveredButton.__profileDragDropBorder:Show()
        end
        state.hoveredButton = hoveredButton
        if hoveredButton and hoveredButton.__profileDragDropBorder then
          if hoveredButton.__profileDragDropBorder.SetBackdropBorderColor then
            hoveredButton.__profileDragDropBorder:SetBackdropBorderColor(0.6588, 0.4784, 0.9098, 1.00)
          end
          hoveredButton.__profileDragDropBorder:Show()
        end
      end

      if self.lootProfilesFeedback then
        local targetName = hoveredButton and hoveredButton.__profileGroupName or nil
        if targetName and targetName ~= "" then
          self.lootProfilesFeedback:SetText("Dragging: " .. state.name .. " -> " .. targetName)
        elseif overList then
          self.lootProfilesFeedback:SetText("Dragging: " .. state.name .. " -> No group")
        else
          self.lootProfilesFeedback:SetText("Dragging: " .. state.name .. " | Drop on a group or release in the list to ungroup.")
        end
      end

      local badge = EnsureLootProfileGroupDragBadge(self)
      if badge and badge.text then
        local targetName = hoveredButton and hoveredButton.__profileGroupName or nil
        if targetName and targetName ~= "" then
          badge.text:SetText("Moving: " .. state.name .. " -> " .. targetName)
        elseif overList then
          badge.text:SetText("Moving: " .. state.name .. " -> No group")
        else
          badge.text:SetText("Moving: " .. state.name .. " | Drop on a group or release in the list.")
        end
        local scale = (UIParent and UIParent.GetEffectiveScale and UIParent:GetEffectiveScale()) or 1
        if scale == 0 then scale = 1 end
        local cx, cy = GetCursorPosition()
        if cx and cy then
          cx = cx / scale
          cy = cy / scale
          badge:ClearAllPoints()
          badge:SetPoint("BOTTOMLEFT", UIParent, "BOTTOMLEFT", cx + 18, cy - 16)
        end
        badge:Show()
      end

    end)

    self.__lootProfileGroupDragMonitor = monitor
    return monitor
  end

  EnsureLootProfileGroupDragBadge = function(self)
    if not self then
      return nil
    end
    if self.__lootProfileGroupDragBadge then
      return self.__lootProfileGroupDragBadge
    end

    local badge = CreateFrame("Frame", nil, UIParent, "BackdropTemplate")
    badge:SetFrameStrata("TOOLTIP")
    badge:SetFrameLevel(250)
    badge:SetClampedToScreen(true)
    badge:SetSize(336, 42)
    badge:SetBackdrop({
      bgFile = "Interface\\Buttons\\WHITE8x8",
      edgeFile = "Interface\\Buttons\\WHITE8x8",
      edgeSize = 1,
    })
    badge:SetBackdropColor(0.13, 0.08, 0.20, 0.98)
    badge:SetBackdropBorderColor(0.6588, 0.4784, 0.9098, 1.00)
    badge:Hide()

    local text = badge:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    text:SetPoint("LEFT", 12, 0)
    text:SetPoint("RIGHT", -12, 0)
    text:SetJustifyH("LEFT")
    text:SetTextColor(0.98, 0.94, 1.00, 1.00)
    badge.text = text

    self.__lootProfileGroupDragBadge = badge
    return badge
  end

  local function BeginLootProfileGroupDrag(self, profileName, sourceGroupName, sourceButton)
    if not self or not sourceButton then
      return false
    end
    local name = TrimText(profileName)
    if name == "" then
      return false
    end

    ClearLootProfileGroupDrag(self, true)

    if type(CreatePurpleOutline) == "function" then
      sourceButton.__profileDragSourceBorder = sourceButton.__profileDragSourceBorder or CreatePurpleOutline(sourceButton)
      if sourceButton.__profileDragSourceBorder then
        sourceButton.__profileDragSourceBorder:Show()
      end
      for _, button in ipairs(self.lootProfileGroupButtons or {}) do
        button.__profileDragDropBorder = button.__profileDragDropBorder or CreatePurpleOutline(button)
        if button.__profileDragDropBorder and button.__profileDragDropBorder.SetBackdropBorderColor then
          button.__profileDragDropBorder:SetBackdropBorderColor(0.6588, 0.4784, 0.9098, 0.42)
          button.__profileDragDropBorder:Show()
        end
      end
    end

    if sourceButton.SetAlpha then
      sourceButton:SetAlpha(0.72)
    end

    self.__lootProfileGroupDrag = {
      name = name,
      sourceGroupName = TrimText(sourceGroupName),
      sourceButton = sourceButton,
      hoveredButton = nil,
    }
    sourceButton:SetScript("OnDragStop", function(completedButton)
      CompleteLootProfileGroupDrag(self, completedButton)
    end)

    if self.lootProfilesFeedback then
      self.lootProfilesFeedback:SetText("Dragging: " .. name .. " | Drop on a group or release in the list to ungroup.")
    end

    local badge = EnsureLootProfileGroupDragBadge(self)
    if badge and badge.text then
      badge.text:SetText("Moving: " .. name .. " | Drop on a group or release in the list to ungroup.")
      badge:Show()
    end

    local monitor = EnsureLootProfileGroupDragMonitor(self)
    if monitor then
      monitor:Show()
    end
    return true
  end

  local function RefreshProfilePage(self)
    local function SetCurrentProfileFont(fontString, text, color)
      if not fontString then
        return
      end
      fontString:SetText(text)
      fontString.__lid_customTextColor = color
      if color and fontString.SetTextColor then
        fontString:SetTextColor(color[1], color[2], color[3], color[4] or 1)
      elseif fontString.SetTextColor then
        fontString:SetTextColor(0.92, 0.96, 1.00, 1.00)
      end
    end

    local owner = editor or self
    local root = RootDB()
    local currentName = GetSelectedProfileName(self)
    if TrimText(self.__lootProfileLastSelectedProfile) ~= TrimText(currentName) then
      self.__lootProfileLastSelectedProfile = currentName
      self.__lootProfileRaidersCollapsed = true
      self.__lootProfileOpenSection = "overview"
      self.__lootProfileRoleTarget = nil
    end
    self.selectedLootProfileName = currentName
    self.selectedProfileName = currentName
    local rows = BuildLootProfileNavRows(root)
    local selectedGroupKey = self.selectedLootProfileGroupName and ("group:" .. string.lower(self.selectedLootProfileGroupName)) or nil
    local selectedProfileName = TrimText(self.selectedLootProfileName or currentName)
    local profilePageFocus = selectedGroupKey or (selectedProfileName ~= "" and ("profile:" .. selectedProfileName) or nil)
    local selectedProfilePage = type(GetListPageForValue) == "function" and GetListPageForValue(rows, profilePageFocus, PROFILE_NAV_PAGE_SIZE, function(row)
      return row and row.key
    end) or nil
    local totalPages = math.max(1, math.ceil(#rows / PROFILE_NAV_PAGE_SIZE))
    if profilePageFocus ~= self.__lastLootProfilePageFocus and selectedProfilePage then
      self.lootProfileListPage = selectedProfilePage
    end
    self.lootProfileListPage = type(ClampListPage) == "function" and ClampListPage(self.lootProfileListPage or 1, totalPages) or math.max(1, math.min(self.lootProfileListPage or 1, totalPages))
    self.__lastLootProfilePageFocus = profilePageFocus
    local rowStartIndex = ((self.lootProfileListPage - 1) * PROFILE_NAV_PAGE_SIZE) + 1
    local rowEndIndex = math.min(#rows, rowStartIndex + PROFILE_NAV_PAGE_SIZE - 1)
    local visibleRowCount = math.max(1, rowEndIndex - rowStartIndex + 1)
    local totalHeight = math.max(1, visibleRowCount * 24)
    self.lootProfilesListContent:SetHeight(totalHeight)
    self.lootProfileGroupButtons = {}
    self.lootProfileButtons = EnsureTextListButtons(self.lootProfileButtons, self.lootProfilesListContent, visibleRowCount, function(row)
      if type(row) ~= "table" then return end
      if row.type == "group" then
        self.selectedLootProfileGroupName = row.name
        self.selectedProfileGroupName = row.name
        ToggleLootProfileGroupCollapsed(root, row.name)
      elseif row.type == "profile" and row.name then
        local _, nextSelectedProfileName = GetLootProfile(row.name)
        self.selectedLootProfileName = nextSelectedProfileName
        self.selectedProfileName = self.selectedLootProfileName
        self.selectedLootProfileGroupName = nil
        self.selectedProfileGroupName = nil
      end
      if self.RequestLootProfilePageRefresh then
        self:RequestLootProfilePageRefresh()
      elseif self.RefreshLootProfilePage then
        self:RefreshLootProfilePage()
      elseif self.Refresh then
        self:Refresh()
      end
    end)
    for i = 1, #self.lootProfileButtons do
      local button = self.lootProfileButtons[i]
      local row = rows[rowStartIndex + i - 1]
      if row then
        button.__value = row
        button.__row = row
        button:ClearAllPoints()
        button:SetPoint("TOPLEFT", row.type == "profile" and 16 or 0, -((i - 1) * 24))
        button:SetWidth(row.type == "profile" and 192 or 208)
        button.__lid_customText = nil

        if row.type == "group" then
          button.__profileGroupName = row.name
          button.__profileDragName = nil
          button.__profileDragSourceGroupName = nil
          button:SetScript("OnDragStart", nil)
          button:SetScript("OnDragStop", nil)
          button:SetText(string.format("%s %s (%d)", row.collapsed and ">" or "v", tostring(row.name or ""), tonumber(row.childCount) or 0))
          button.__lid_customText = { 0.92, 0.82, 1.00, 1.00 }
          SetProfileNavButtonVariant(button, nil, selectedGroupKey == row.key)
          SetListButtonSelected(button, selectedGroupKey == row.key)
          SetTextListButtonTextColor(button, selectedGroupKey == row.key and { 1.00, 0.94, 0.62, 1.00 } or button.__lid_customText)
          self.lootProfileGroupButtons[#self.lootProfileGroupButtons + 1] = button
        else
          button.__profileGroupName = nil
          button.__profileDragName = row.name
          button.__profileDragSourceGroupName = row.groupName
          if type(CreatePurpleOutline) == "function" then
            button.__profileDragSourceBorder = button.__profileDragSourceBorder or CreatePurpleOutline(button)
            if button.__profileDragSourceBorder then
              button.__profileDragSourceBorder:Hide()
            end
          end
          button:RegisterForDrag("LeftButton")
          button:SetScript("OnDragStart", function(sourceButton)
            BeginLootProfileGroupDrag(self, sourceButton.__profileDragName, sourceButton.__profileDragSourceGroupName, sourceButton)
          end)
          button:SetScript("OnDragStop", nil)
          local rowProfile = GetLootProfile(row.name)
          local enabledMark = rowProfile and rowProfile.settings and rowProfile.settings.enabled and "|TInterface\\Buttons\\UI-CheckBox-Check:14:14:0:0|t " or ""
          button:SetText(enabledMark .. tostring(row.name or ""))
          local isSelected = TrimText(row.name) == selectedProfileName
          local isSimulationRow = TrimText(row.name) == "Simulation"
          SetProfileNavButtonVariant(button, isSimulationRow and "SIMULATION" or nil, isSelected)
          SetListButtonSelected(button, isSelected)
          SetTextListButtonTextColor(button, isSelected and { 1.00, 0.94, 0.62, 1.00 } or (isSimulationRow and { 1.00, 0.78, 0.78, 1.00 } or { 0.82, 0.82, 0.86, 1.00 }))
        end

        button:Show()
      else
        button.__value = nil
        button.__row = nil
        button.__profileGroupName = nil
        button.__profileDragName = nil
        button.__profileDragSourceGroupName = nil
        button:SetScript("OnDragStart", nil)
        button:SetScript("OnDragStop", nil)
        SetProfileNavButtonVariant(button, nil, false)
        button:Hide()
      end
    end
    if self.lootProfilesListScroll then
      self.lootProfilesListScroll:SetVerticalScroll(0)
      if self.lootProfilesListScroll.UpdateScrollChildRect then
        self.lootProfilesListScroll:UpdateScrollChildRect()
      end
    end
    if type(UpdatePagerControls) == "function" then
      UpdatePagerControls(self.lootProfilesPrevBtn, self.lootProfilesNextBtn, self.lootProfilesPageText, self.lootProfileListPage, totalPages)
    end

    local hasProfile = type(currentName) == "string" and currentName ~= ""
    if not hasProfile then
      self.selectedLootProfileName = nil
      self.selectedProfileName = nil
      self.selectedLootProfileGroupName = nil
      self.selectedProfileGroupName = nil
      self.__lootProfilesHasVisibleSelection = false

      if self.lootProfilesRightScroll then
        self.lootProfilesRightScroll:Hide()
      end
      if self.lootProfilesEmptyStateFrame then
        self.lootProfilesEmptyStateFrame:Show()
      end
      if self.lootProfilesTitle then
        self.lootProfilesTitle:SetText("Profile Settings")
      end
      if self.lootProfileStatus then
        self.lootProfileStatus:SetText("No profile created")
        self.lootProfileStatus:SetTextColor(1.00, 0.82, 0.28, 1.00)
      end
      if self.lootProfileStatusDetail then
        self.lootProfileStatusDetail:SetText("Create a profile to configure loot and prepare a session.")
        self.lootProfileStatusDetail:SetTextColor(0.82, 0.82, 0.86, 1.00)
      end
      if self.lootProfileStatusDot and self.lootProfileStatusDot.SetVertexColor then
        self.lootProfileStatusDot:SetVertexColor(1.00, 0.82, 0.28, 1.00)
      end
      if self.lootProfileSizeFrame then
        self.lootProfileSizeFrame:Hide()
        self.lootProfileSizeFrame.__tooltipLines = nil
      end
      if self.lootProfileSizeText then
        self.lootProfileSizeText:SetText("")
      end
      SetCurrentProfileFont(self.profilesCurrentLabel, "Current Profile: No profile activated :(", { 1.00, 0.35, 0.25, 1.00 })
      SetCurrentProfileFont(self.profileBarText, "Current Profile: No profile activated :(", { 1.00, 0.35, 0.25, 1.00 })
      if self.lootProfilesFeedback then
        self.lootProfilesFeedback:SetText("")
        if self.lootProfilesFeedback.SetTextColor then
          self.lootProfilesFeedback:SetTextColor(0.82, 0.82, 0.86, 1.00)
        end
      end
      if self.lootProfilesActionHint then
        self.lootProfilesActionHint:SetText("Select or create a profile to unlock actions.")
        self.lootProfilesActionHint:SetTextColor(0.82, 0.82, 0.86, 1.00)
      end
      if self.lootAddGroupBtn and self.lootAddGroupBtn.Disable then
        self.lootAddGroupBtn:Disable()
      end
      if self.lootDeleteGroupBtn and self.lootDeleteGroupBtn.Disable then
        self.lootDeleteGroupBtn:Disable()
      end
      if self.lootActivateProfileBtn and self.lootActivateProfileBtn.Disable then
        self.lootActivateProfileBtn:Hide()
        self.lootActivateProfileBtn:Disable()
      end
      if self.lootDeactivateProfileBtn and self.lootDeactivateProfileBtn.Disable then
        self.lootDeactivateProfileBtn:Hide()
        self.lootDeactivateProfileBtn:Disable()
      end
      if self.lootCopyProfileBtn and self.lootCopyProfileBtn.Disable then
        self.lootCopyProfileBtn:Hide()
        self.lootCopyProfileBtn:Disable()
      end
      if self.lootDeleteProfileBtn and self.lootDeleteProfileBtn.Disable then
        self.lootDeleteProfileBtn:Disable()
      end
      if self.lootClearSimulationContentBtn then
        self.lootClearSimulationContentBtn:Hide()
      end
      return
    end

    self.__lootProfilesHasVisibleSelection = true
    if self.lootProfilesRightScroll then
      self.lootProfilesRightScroll:Show()
    end
    if self.lootProfilesEmptyStateFrame then
      self.lootProfilesEmptyStateFrame:Hide()
    end
    if self.lootAddGroupBtn and self.lootAddGroupBtn.Enable then
      self.lootAddGroupBtn:Enable()
    end

    local profile = GetLootProfile(currentName)
    local access = GetLootProfileAccessInfo(currentName)
    local openSection = string.lower(TrimText(self.__lootProfileOpenSection))
    local importExportFeatureEnabled = type(root.ui) == "table"
      and root.ui.developerMode == true
      and root.ui.importExportFeature == true
    if openSection == "transfer" and not importExportFeatureEnabled then
      openSection = "overview"
      self.__lootProfileOpenSection = openSection
    end
    if openSection ~= "overview" and openSection ~= "access" and openSection ~= "raid"
      and openSection ~= "roll" and openSection ~= "points" and openSection ~= "backups"
      and openSection ~= "transfer" then
      openSection = "overview"
      self.__lootProfileOpenSection = openSection
    end
    local combatLocked = type(InCombatLockdown) == "function" and InCombatLockdown() == true
    local canEditRollSettings = access.canEditRollSettings and not combatLocked
    local roleEntries = (openSection == "overview" or openSection == "access") and GetLootProfileRoleEntries(currentName) or {}
    local enabled = profile.settings and profile.settings.enabled
    local activeProfileLabel = TrimText(type(GetEnabledLootProfileName) == "function" and GetEnabledLootProfileName() or "")
    local canManageProfile = access.canManageProfile
    local roleBuckets = openSection == "overview" and BuildLootProfileRoleBuckets(roleEntries, profile) or nil
    local activeSession, activeSessionProfile = GetActiveLootSession()
    local hasRunningSession = activeSession and tostring(activeSessionProfile or activeSession.profileName or "") == tostring(currentName)
    local hasAnyRunningSession = activeSession ~= nil
    local identity = hasProfile and type(GetLootProfileIdentityInfo) == "function" and GetLootProfileIdentityInfo(currentName) or nil
    local isSharedReplica = type(identity) == "table" and string.upper(TrimText(identity.syncMode or "")) == "SHARED"
    local canDeleteProfile = hasProfile
      and currentName ~= "Default"
      and currentName ~= "Simulation"
      and not hasAnyRunningSession
      and not enabled
      and TrimText(currentName) ~= activeProfileLabel
      and (access.canDeleteProfile or isSharedReplica)
    local showSimulationProfile = type(root.ui) == "table" and root.ui.developerMode == true and root.ui.showSimulationProfile == true
    if activeProfileLabel == "Simulation" and not showSimulationProfile then
      activeProfileLabel = ""
    end
    if activeProfileLabel == "" then
      SetCurrentProfileFont(self.profilesCurrentLabel, "Current Profile: No profile activated :(", { 1.00, 0.35, 0.25, 1.00 })
      SetCurrentProfileFont(self.profileBarText, "Current Profile: No profile activated :(", { 1.00, 0.35, 0.25, 1.00 })
    else
      SetCurrentProfileFont(self.profilesCurrentLabel, "Current Profile: " .. activeProfileLabel, nil)
      SetCurrentProfileFont(self.profileBarText, "Current Profile: " .. activeProfileLabel, nil)
    end
    if self.lootProfilesTitle then
      self.lootProfilesTitle:SetText(tostring(currentName ~= "" and currentName or "Profile Settings"))
    end
    if self.lootProfileSizeFrame and self.lootProfileSizeText then
      local showProfileSize = type(root.ui) == "table"
        and root.ui.developerMode == true
        and root.ui.showProfileSize == true
      if showProfileSize then
        local sizeDisplay = BuildProfileSizeDisplay(currentName, profile)
        if sizeDisplay then
          self.lootProfileSizeText:SetText(tostring(sizeDisplay.text or "Profile Size: unavailable"))
          self.lootProfileSizeFrame.__tooltipLines = type(sizeDisplay.lines) == "table" and sizeDisplay.lines or {}
          self.lootProfileSizeFrame:Show()
        else
          self.lootProfileSizeFrame:Hide()
          self.lootProfileSizeFrame.__tooltipLines = nil
        end
      else
        self.lootProfileSizeFrame:Hide()
        self.lootProfileSizeFrame.__tooltipLines = nil
        self.lootProfileSizeText:SetText("")
      end
    end
    if self.lootProfilesFeedback and self.lootProfilesFeedback.SetTextColor then
      if not canManageProfile then
        self.lootProfilesFeedback:SetText("Read-only access: your current role cannot edit this profile.")
        self.lootProfilesFeedback:SetTextColor(1.00, 0.32, 0.32, 1.00)
      else
        if self.lootProfilesFeedback.GetText and self.lootProfilesFeedback:GetText() == "Read-only access: your current role cannot edit this profile." then
          self.lootProfilesFeedback:SetText("")
        end
        self.lootProfilesFeedback:SetTextColor(0.82, 0.82, 0.86, 1.00)
      end
    end
    if self.lootProfilesActionHint then
      local actionHint = ""
      local hintColor = { 0.82, 0.82, 0.86, 1.00 }
      if not canManageProfile then
        actionHint = "Edits locked: read-only role."
        hintColor = { 1.00, 0.52, 0.42, 1.00 }
      elseif hasAnyRunningSession then
        actionHint = "Profile copy and deletion are locked while a session is prepared or running."
        hintColor = { 1.00, 0.82, 0.28, 1.00 }
      elseif enabled or TrimText(currentName) == activeProfileLabel then
        actionHint = "Deactivate this profile before deleting it."
        hintColor = { 1.00, 0.82, 0.28, 1.00 }
      elseif TrimText(self.selectedLootProfileGroupName) == "" then
        actionHint = "Select a group to delete it."
      end
      self.lootProfilesActionHint:SetText(actionHint)
      self.lootProfilesActionHint:SetTextColor(hintColor[1], hintColor[2], hintColor[3], hintColor[4])
    end
    if self.lootProfileStatus then
      if enabled then
        self.lootProfileStatus:SetText(hasRunningSession and "Active profile - Session running" or "Active profile")
        self.lootProfileStatus:SetTextColor(0.2, 0.9, 0.2, 1)
      else
        self.lootProfileStatus:SetText("Inactive")
        self.lootProfileStatus:SetTextColor(1.0, 0.35, 0.25, 1)
      end
    end
    if self.lootProfileStatusDetail then
      local statusDetail = "Selected for editing. Activate to prepare a session."
      local detailColor = { 0.82, 0.82, 0.86, 1.00 }
      if not canManageProfile then
        statusDetail = "View-only: your role cannot change this profile."
        detailColor = { 1.00, 0.52, 0.42, 1.00 }
      elseif hasRunningSession then
        statusDetail = "Used by the current session."
        detailColor = { 0.30, 0.90, 0.36, 1.00 }
      elseif enabled then
        statusDetail = "Active and ready to prepare a session."
        detailColor = { 0.30, 0.90, 0.36, 1.00 }
      end
      self.lootProfileStatusDetail:SetText(statusDetail)
      self.lootProfileStatusDetail:SetTextColor(detailColor[1], detailColor[2], detailColor[3], detailColor[4])
    end
    if self.lootProfileStatusDot and self.lootProfileStatusDot.SetVertexColor then
      if enabled then
        self.lootProfileStatusDot:SetVertexColor(0.20, 0.90, 0.30, 1.00)
      else
        self.lootProfileStatusDot:SetVertexColor(0.95, 0.28, 0.24, 1.00)
      end
    end
    if self.lootActivateProfileBtn and self.lootActivateProfileBtn.Enable then
      self.lootActivateProfileBtn:SetShown(hasProfile and not enabled)
      if hasProfile and not enabled then self.lootActivateProfileBtn:Enable() else self.lootActivateProfileBtn:Disable() end
    end
    if self.lootDeactivateProfileBtn and self.lootDeactivateProfileBtn.Enable then
      self.lootDeactivateProfileBtn:SetShown(hasProfile and enabled)
      if hasProfile and enabled then self.lootDeactivateProfileBtn:Enable() else self.lootDeactivateProfileBtn:Disable() end
    end
    if self.lootCopyProfileBtn and self.lootCopyProfileBtn.Enable then
      self.lootCopyProfileBtn:SetShown(hasProfile)
      if hasProfile and not hasAnyRunningSession then self.lootCopyProfileBtn:Enable() else self.lootCopyProfileBtn:Disable() end
    end
    if self.lootClearSimulationContentBtn then
      local showClearSimulation = hasProfile and TrimText(currentName) == "Simulation"
      self.lootClearSimulationContentBtn:SetShown(showClearSimulation)
      if self.lootClearSimulationContentBtn.Enable then
        if showClearSimulation and not hasAnyRunningSession then
          self.lootClearSimulationContentBtn:Enable()
        else
          self.lootClearSimulationContentBtn:Disable()
        end
      end
    end
    if self.lootDeleteProfileBtn and self.lootDeleteProfileBtn.Enable then
      if self.lootDeleteProfileBtn.SetText then
        self.lootDeleteProfileBtn:SetText("Delete Profile")
      end
      if canDeleteProfile then self.lootDeleteProfileBtn:Enable() else self.lootDeleteProfileBtn:Disable() end
    end
    if self.lootDeleteGroupBtn and self.lootDeleteGroupBtn.Enable then
      if canManageProfile and TrimText(self.selectedLootProfileGroupName) ~= "" then
        self.lootDeleteGroupBtn:Enable()
      else
        self.lootDeleteGroupBtn:Disable()
      end
    end
    if openSection == "access" then
      local roleContextRole = string.upper(TrimText(access.role))
      local localCharacterKey = string.lower(TrimText(access.characterKey))
      if localCharacterKey ~= "" then
        for _, roleEntry in ipairs(roleEntries or {}) do
          local entryCharacter = string.lower(TrimText(type(roleEntry) == "table" and roleEntry.character or ""))
          if entryCharacter == localCharacterKey then
            roleContextRole = string.upper(TrimText(roleEntry.role))
            break
          end
        end
      end
      if roleContextRole ~= "MASTER" and roleContextRole ~= "COUNCIL" and roleContextRole ~= "RAIDER" then
        roleContextRole = "RAIDER"
      end

      local roleContextTitle = roleContextRole
      local roleContextDetail = "Standard participant permissions"
      local roleContextTexture = "Interface\\AddOns\\LidCouncil\\Media\\LidCouncil\\Emblems\\Emblem_Raider.tga"
      local accentColor = { 0.38, 0.52, 0.70, 0.86 }
      local backgroundColor = { 0.05, 0.08, 0.12, 0.94 }
      if roleContextRole == "MASTER" then
        roleContextDetail = "Full profile authority"
        roleContextTexture = "Interface\\AddOns\\LidCouncil\\Media\\LidCouncil\\Emblems\\Emblem_Master.tga"
        accentColor = { 0.84, 0.64, 0.20, 0.92 }
        backgroundColor = { 0.12, 0.09, 0.04, 0.94 }
      elseif roleContextRole == "COUNCIL" then
        roleContextDetail = "Profile management permissions"
        roleContextTexture = "Interface\\AddOns\\LidCouncil\\Media\\LidCouncil\\Emblems\\Emblem_Council.tga"
        accentColor = { 0.34, 0.60, 0.86, 0.92 }
        backgroundColor = { 0.04, 0.08, 0.13, 0.94 }
      end

      if self.lootProfileAccessSummary then
        self.lootProfileAccessSummary:SetText("")
      end
      if self.lootProfileRoleContextFrame then
        if self.lootProfileRoleContextFrame.SetBackdropColor then
          self.lootProfileRoleContextFrame:SetBackdropColor(backgroundColor[1], backgroundColor[2], backgroundColor[3], backgroundColor[4])
        end
        if self.lootProfileRoleContextFrame.SetBackdropBorderColor then
          self.lootProfileRoleContextFrame:SetBackdropBorderColor(accentColor[1], accentColor[2], accentColor[3], accentColor[4])
        end
      end
      if self.lootProfileRoleContextIcon then
        self.lootProfileRoleContextIcon:SetTexture(roleContextTexture)
      end
      if self.lootProfileRoleContextTitle then
        self.lootProfileRoleContextTitle:SetText(roleContextTitle)
        self.lootProfileRoleContextTitle:SetTextColor(accentColor[1], accentColor[2], accentColor[3], 1.00)
      end
      if self.lootProfileRoleContextDetail then
        self.lootProfileRoleContextDetail:SetText(roleContextDetail)
        self.lootProfileRoleContextDetail:SetTextColor(0.90, 0.90, 0.94, 1.00)
      end
      if self.lootProfileRoleSessionBadge then
        local showSessionBadge = access.isSessionHost == true
        self.lootProfileRoleSessionBadge:SetShown(showSessionBadge)
        if showSessionBadge then
          if self.lootProfileRoleSessionBadge.SetBackdropColor then
            self.lootProfileRoleSessionBadge:SetBackdropColor(0.05, 0.20, 0.10, 0.96)
          end
          if self.lootProfileRoleSessionBadge.SetBackdropBorderColor then
            self.lootProfileRoleSessionBadge:SetBackdropBorderColor(0.20, 0.78, 0.38, 0.92)
          end
          if self.lootProfileRoleSessionBadge.label then
            self.lootProfileRoleSessionBadge.label:SetTextColor(0.54, 0.96, 0.66, 1.00)
          end
        end
      end
    end
    if openSection == "access" then
      local masterPreview = type(GetLootProfilePermissionPolicyRoleState) == "function" and GetLootProfilePermissionPolicyRoleState(currentName, "MASTER")
        or (type(GetLootProfileAccessInfoForRole) == "function" and GetLootProfileAccessInfoForRole(currentName, "MASTER") or {})
      local sessionHostPreview = type(GetLootProfilePermissionPolicyRoleState) == "function" and GetLootProfilePermissionPolicyRoleState(currentName, "SESSION_HOST")
        or (type(GetLootProfileAccessInfoForRole) == "function" and GetLootProfileAccessInfoForRole(currentName, "SESSION_HOST") or {})
      local councilPreview = type(GetLootProfilePermissionPolicyRoleState) == "function" and GetLootProfilePermissionPolicyRoleState(currentName, "COUNCIL")
        or (type(GetLootProfileAccessInfoForRole) == "function" and GetLootProfileAccessInfoForRole(currentName, "COUNCIL") or {})
      local raiderPreview = type(GetLootProfilePermissionPolicyRoleState) == "function" and GetLootProfilePermissionPolicyRoleState(currentName, "RAIDER")
        or (type(GetLootProfileAccessInfoForRole) == "function" and GetLootProfileAccessInfoForRole(currentName, "RAIDER") or {})
      self.__lootProfilePermissionPolicyRowCount = #PermissionPolicyRowDefs

      if self.lootProfilePermissionPolicySummary then
        self.lootProfilePermissionPolicySummary:SetText(
          "Green: editable allowed. Red: editable denied. Gray: locked by LidCouncil safeguards. Click a section to collapse it."
        )
      end
      if self.lootProfilePermissionPolicyResetBtn then
        if access.canManageRights then
          self.lootProfilePermissionPolicyResetBtn:Show()
          if self.lootProfilePermissionPolicyResetBtn.Enable then
            self.lootProfilePermissionPolicyResetBtn:Enable()
          end
        else
          self.lootProfilePermissionPolicyResetBtn:Show()
          if self.lootProfilePermissionPolicyResetBtn.Disable then
            self.lootProfilePermissionPolicyResetBtn:Disable()
          end
        end
      end

      self.__lootProfilePermissionSectionsCollapsed = self.__lootProfilePermissionSectionsCollapsed or {}
      local collapsedPermissionSections = self.__lootProfilePermissionSectionsCollapsed
      local activePermissionSection = ""
      for index, rowDef in ipairs(PermissionPolicyRowDefs) do
        local row = self.lootProfilePermissionPolicyRows and self.lootProfilePermissionPolicyRows[index] or nil
        if row then
          row.__permissionKey = rowDef.key
          row:Show()
          row.__isPermissionSection = rowDef.section and true or false
          if row.__isPermissionSection then
            if row.SetBackdropColor then
              row:SetBackdropColor(0.08, 0.07, 0.04, 0.72)
            end
            if row.SetBackdropBorderColor then
              row:SetBackdropBorderColor(0.58, 0.44, 0.14, 0.74)
            end
            activePermissionSection = tostring(rowDef.section or "")
            local sectionName = activePermissionSection
            local sectionCollapsed = collapsedPermissionSections[sectionName] and true or false
            row.__permissionSectionName = sectionName
            row.__permissionHidden = false
            if row.labelText then
              row.labelText:SetText((sectionCollapsed and "+ " or "- ") .. sectionName)
              row.labelText:SetTextColor(1.00, 0.82, 0.32, 1.00)
            end
            row:EnableMouse(true)
            if row.Enable then row:Enable() end
            row:SetScript("OnClick", function()
              collapsedPermissionSections[sectionName] = not (collapsedPermissionSections[sectionName] and true or false)
              if self.RequestLootProfilePageRefresh then
                self:RequestLootProfilePageRefresh()
              elseif self.RefreshLootProfilePage then
                self:RefreshLootProfilePage()
              end
            end)
            row:SetScript("OnEnter", function(sectionRow)
              if sectionRow.SetBackdropColor then
                sectionRow:SetBackdropColor(0.13, 0.10, 0.05, 0.86)
              end
            end)
            row:SetScript("OnLeave", function(sectionRow)
              if sectionRow.SetBackdropColor then
                sectionRow:SetBackdropColor(0.08, 0.07, 0.04, 0.72)
              end
            end)
            if row.masterCell then row.masterCell:Hide() end
            if row.sessionHostCell then row.sessionHostCell:Hide() end
            if row.councilCell then row.councilCell:Hide() end
            if row.raiderCell then row.raiderCell:Hide() end
          else
            row.__permissionSectionName = activePermissionSection
            row.__permissionHidden = collapsedPermissionSections[activePermissionSection] and true or false
            row:EnableMouse(false)
            row:SetScript("OnClick", nil)
            row:SetScript("OnEnter", nil)
            row:SetScript("OnLeave", nil)
            if row.SetBackdropColor then
              row:SetBackdropColor(0.05, 0.05, 0.07, 0.98)
            end
            if row.SetBackdropBorderColor then
              row:SetBackdropBorderColor(0.16, 0.18, 0.22, 0.42)
            end
            if row.labelText then
              row.labelText:SetText(tostring(rowDef.label or rowDef.key or ""))
              row.labelText:SetTextColor(0.92, 0.92, 0.96, 1.00)
            end
            if row.masterCell then
              row.masterCell:Show()
              SetPermissionPolicyCellState(row.masterCell, masterPreview[rowDef.key], false, true)
            end
            if row.sessionHostCell then
              local locked = IsPermissionPolicyLocked("SESSION_HOST", rowDef.key)
              local interactive = access.canManageRights and not locked
              row.sessionHostCell:Show()
              SetPermissionPolicyCellState(row.sessionHostCell, sessionHostPreview[rowDef.key], interactive, locked)
              row.sessionHostCell:SetScript("OnClick", nil)
              if locked and access.canManageRights then
                SetLockedPermissionPolicyFeedbackCell(self, row.sessionHostCell, rowDef.key)
              elseif interactive then
                row.sessionHostCell:SetScript("OnClick", function()
                if not access.canManageRights or type(SetLootProfilePermissionPolicyValue) ~= "function" then
                  return
                end
                local desiredEnabled = not (sessionHostPreview[rowDef.key] and true or false)
                local ok, result = SetLootProfilePermissionPolicyValue(currentName, "SESSION_HOST", rowDef.key, desiredEnabled)
                FinishPermissionPolicyUpdate(self, currentName, "SESSION_HOST", "Session Host", rowDef.label or rowDef.key, rowDef.key, desiredEnabled, ok, result, "Could not update the Session Host permission.")
                end)
              end
            end
            if row.councilCell then
              local locked = IsPermissionPolicyLocked("COUNCIL", rowDef.key)
              local interactive = access.canManageRights and not locked
              row.councilCell:Show()
              SetPermissionPolicyCellState(row.councilCell, councilPreview[rowDef.key], interactive, locked)
              row.councilCell:SetScript("OnClick", nil)
              if locked and access.canManageRights then
                SetLockedPermissionPolicyFeedbackCell(self, row.councilCell, rowDef.key)
              elseif interactive then
                row.councilCell:SetScript("OnClick", function()
                if not access.canManageRights or type(SetLootProfilePermissionPolicyValue) ~= "function" then
                  return
                end
                local desiredEnabled = not (councilPreview[rowDef.key] and true or false)
                local ok, result = SetLootProfilePermissionPolicyValue(currentName, "COUNCIL", rowDef.key, desiredEnabled)
                FinishPermissionPolicyUpdate(self, currentName, "COUNCIL", "Council", rowDef.label or rowDef.key, rowDef.key, desiredEnabled, ok, result, "Could not update the Council permission.")
                end)
              end
            end
            if row.raiderCell then
              local locked = IsPermissionPolicyLocked("RAIDER", rowDef.key)
              local interactive = access.canManageRights and not locked
              row.raiderCell:Show()
              SetPermissionPolicyCellState(row.raiderCell, raiderPreview[rowDef.key], interactive, locked)
              row.raiderCell:SetScript("OnClick", nil)
              if locked and access.canManageRights then
                SetLockedPermissionPolicyFeedbackCell(self, row.raiderCell, rowDef.key)
              elseif interactive then
                row.raiderCell:SetScript("OnClick", function()
                  if not access.canManageRights or type(SetLootProfilePermissionPolicyValue) ~= "function" then
                    return
                  end
                  local desiredEnabled = not (raiderPreview[rowDef.key] and true or false)
                  local ok, result = SetLootProfilePermissionPolicyValue(currentName, "RAIDER", rowDef.key, desiredEnabled)
                  FinishPermissionPolicyUpdate(self, currentName, "RAIDER", "Raider", rowDef.label or rowDef.key, rowDef.key, desiredEnabled, ok, result, "Could not update the Raider permission.")
                end)
              end
            end
          end
        end
      end
      for index = (#PermissionPolicyRowDefs + 1), #(self.lootProfilePermissionPolicyRows or {}) do
        local row = self.lootProfilePermissionPolicyRows[index]
        if row then
          row:Hide()
        end
      end
    end
    if openSection == "overview" then
      do
      local masterDisplay = ResolveProfileMemberDisplay(profile, roleBuckets.master)
      local masterIconData = ResolveProfileIconData(masterDisplay)
      local masterR, masterG, masterB = GetProfileClassColor(masterDisplay.classFile)
      local masterMetaParts = {}
      if TrimText(masterDisplay.specName) ~= "" then
        masterMetaParts[#masterMetaParts + 1] = masterDisplay.specName
      end
      if TrimText(masterDisplay.className) ~= "" then
        masterMetaParts[#masterMetaParts + 1] = masterDisplay.className
      end
      if self.lootProfileMasterCardIcon then
        ApplyProfileIcon(self.lootProfileMasterCardIcon, masterIconData)
      end
      if self.lootProfileMasterCardValue then
        self.lootProfileMasterCardValue:SetText(roleBuckets.master ~= "" and tostring(roleBuckets.master) or "Unassigned")
        self.lootProfileMasterCardValue:SetTextColor(masterR, masterG, masterB, 1)
      end
      if self.lootProfileMasterCardMeta then
        self.lootProfileMasterCardMeta:SetText((#masterMetaParts > 0) and table.concat(masterMetaParts, " | ") or "Full profile control")
      end
    end
      if self.lootProfileMasterCardValue then
      if roleBuckets.master == "" then
        self.lootProfileMasterCardValue:SetTextColor(0.82, 0.82, 0.86, 1)
      end
      end
      if self.lootProfileMasterCardTitle then
      self.lootProfileMasterCardTitle:SetText(string.format("MASTER | %d", roleBuckets.master ~= "" and 1 or 0))
      end
      if self.lootProfileCouncilCardValue then
      self.lootProfileCouncilCardValue:SetText(#roleBuckets.council == 0 and "No council members yet." or "")
      end
      if self.lootProfileCouncilCardTitle then
      self.lootProfileCouncilCardTitle:SetText(string.format("COUNCIL | %d", #roleBuckets.council))
      end
      if self.lootProfileCouncilCardMeta then
      if #roleBuckets.council == 0 then
        self.lootProfileCouncilCardMeta:SetText("Council role permissions are configured in Roles & Rights.")
      else
        self.lootProfileCouncilCardMeta:SetText("")
      end
      end
      local canCollapseRaiders = #roleBuckets.raiders > 6
      self.__lootProfileRaidersCanCollapse = canCollapseRaiders
      if not canCollapseRaiders then
        self.__lootProfileRaidersCollapsed = false
      end
      if self.lootProfileRaiderToggleBtn then
      if self.lootProfileRaiderToggleBtn.arrowText then
        self.lootProfileRaiderToggleBtn.arrowText:SetText(canCollapseRaiders and (self.__lootProfileRaidersCollapsed and ">" or "v") or "")
      end
      if self.lootProfileRaiderToggleBtn.labelText then
        self.lootProfileRaiderToggleBtn.labelText:SetText(string.format("RAIDERS | %d", #roleBuckets.raiders))
      end
      self.lootProfileRaiderToggleBtn:EnableMouse(canCollapseRaiders)
      end
      if self.lootProfileRaiderSummary then
      if #roleBuckets.raiders == 0 then
        self.lootProfileRaiderSummary:SetText("Raiders appear here after they join a LidCouncil session.")
      else
        self.lootProfileRaiderSummary:SetText("")
      end
      end
      self.__lootProfileCouncilRowCount = #roleBuckets.council
      self.__lootProfileRaiderRowCount = #roleBuckets.raiders
      self.__lootProfileCouncilRowsHeight = RefreshProfileMemberRows("lootProfileCouncilRows", self.lootProfileCouncilRowsFrame, roleBuckets.council, profile, "COUNCIL")
      self.__lootProfileRaiderRowsHeight = RefreshProfileMemberRows("lootProfileRaiderRows", self.lootProfileRaiderRowsFrame, roleBuckets.raiders, profile, "RAIDER")

      local selectedRoleTarget = TrimText(self.__lootProfileRoleTarget)
      local selectedRoleEntry = nil
      for _, entry in ipairs(roleEntries) do
      if not entry.isMaster and string.lower(tostring(entry.character or "")) == string.lower(selectedRoleTarget) then
        selectedRoleEntry = entry
        break
      end
      end
      self.__lootProfileRoleTarget = selectedRoleEntry and selectedRoleEntry.character or nil
      self.__lootProfileRoleValue = string.upper(TrimText((selectedRoleEntry and selectedRoleEntry.role) or self.__lootProfileRoleValue or "RAIDER"))
      if self.__lootProfileRoleValue ~= "COUNCIL" then
        self.__lootProfileRoleValue = "RAIDER"
      end

      if self.lootProfileMembersActionHint then
      if not access.canManageRoles then
        self.lootProfileMembersActionHint:SetText("Role changes require profile-management rights.")
        self.lootProfileMembersActionHint:SetTextColor(0.62, 0.62, 0.68, 1)
      elseif selectedRoleEntry then
        self.lootProfileMembersActionHint:SetText(string.format("Selected for master transfer: %s", tostring(selectedRoleEntry.character)))
        self.lootProfileMembersActionHint:SetTextColor(1.00, 0.82, 0.24, 1)
      elseif (#roleBuckets.council + #roleBuckets.raiders) > 0 and access.canTransferMaster then
        self.lootProfileMembersActionHint:SetText("Select a Council Member or Raider to transfer Master.")
        self.lootProfileMembersActionHint:SetTextColor(0.72, 0.72, 0.78, 1)
      else
        self.lootProfileMembersActionHint:SetText("")
      end
      end
      if self.lootProfileMembersHeader then
      local memberCount = (roleBuckets.master ~= "" and 1 or 0) + #roleBuckets.council + #roleBuckets.raiders
      self.lootProfileMembersHeader:SetText(string.format("Members & Roles | %d Members", memberCount))
      end
      if self.lootProfileTransferMasterBtn then
      ApplyProfileActionButtonStyle(self.lootProfileTransferMasterBtn, "transfer")
      if self.lootProfileTransferMasterBtn.label then
        self.lootProfileTransferMasterBtn.label:SetText("Transfer Master")
      end
      if selectedRoleEntry then
        self.lootProfileTransferMasterBtn.__lidTooltipTitle = "Transfer Profile Master"
        self.lootProfileTransferMasterBtn.__lidTooltipDetail = string.format(
          "Make %s the Profile Master. The current master becomes a Council Member. A confirmation is required.",
          tostring(selectedRoleEntry.character)
        )
      else
        self.lootProfileTransferMasterBtn.__lidTooltipTitle = "Transfer Profile Master"
        self.lootProfileTransferMasterBtn.__lidTooltipDetail = "Select a Council Member or Raider in Overview first."
      end
      if access.canTransferMaster and (#roleBuckets.council + #roleBuckets.raiders) > 0 then
        self.lootProfileTransferMasterBtn:Show()
        if self.lootProfileTransferMasterBtn.Enable then
          if selectedRoleEntry then
            self.lootProfileTransferMasterBtn:Enable()
          else
            self.lootProfileTransferMasterBtn:Disable()
          end
        end
      else
        self.lootProfileTransferMasterBtn:Hide()
        if self.lootProfileTransferMasterBtn.Enable then
          self.lootProfileTransferMasterBtn:Disable()
        end
      end
      ApplyProfileActionButtonStyle(self.lootProfileTransferMasterBtn, "transfer")
      end
    end

    local seasonContext, seasonLootItems = nil, {}
    if openSection == "raid" or openSection == "points" then
      seasonContext, seasonLootItems = CollectSeasonLootEntries(profile)
    end
    local selectedRaidEntry = FindRaidEntryByProfile(profile)
    local selectedRaidInSeason = nil
    if type(selectedRaidEntry) == "table" and not selectedRaidEntry.unresolved and tonumber(selectedRaidEntry.instanceID)
      and (not seasonContext or tonumber(selectedRaidEntry.tier) == tonumber(seasonContext.tier)) then
      selectedRaidInSeason = selectedRaidEntry
    end
    local seasonName = tostring(seasonContext and seasonContext.tierName or "Current Season")
    local pointMode = ResolvePointMode(profile)
    local rollTemplate = ResolveRollTemplate(profile)
    self.__lootPointMode = pointMode
    local raidPreviewTexture = selectedRaidInSeason and ResolveRaidPreviewTexture(selectedRaidInSeason.instanceID) or nil
    if openSection == "overview" then
      local rollCount = profile.settings and profile.settings.rollOptions and #profile.settings.rollOptions or 0
      local sessionCount = profile.sessions and #profile.sessions or 0
      local awardedItemCount = 0
      local participantSeen = {}
      local participantCount = 0
      for _, ledgerRow in pairs(profile.lootLedger or {}) do
        if type(ledgerRow) == "table" and type(ledgerRow.items) == "table" then
          for _, ledgerItem in ipairs(ledgerRow.items) do
            if type(ledgerItem) == "table" and ledgerItem.isManual ~= true then
              awardedItemCount = awardedItemCount + 1
            end
          end
        end
      end
      for participantKey in pairs(profile.lootLedger or {}) do
        participantSeen[tostring(participantKey)] = true
      end
      for memberKey in pairs(profile.lootLedgerMeta or {}) do
        participantSeen[tostring(memberKey)] = true
      end
      for _, roleEntry in ipairs(roleEntries) do
        local characterKey = TrimText(type(roleEntry) == "table" and roleEntry.character or "")
        if characterKey ~= "" then
          participantSeen[characterKey] = true
        end
      end
      for _ in pairs(participantSeen) do
        participantCount = participantCount + 1
      end
      if self.lootProfileStatCards then
        if self.lootProfileStatCards.sessions and self.lootProfileStatCards.sessions.value then
          self.lootProfileStatCards.sessions.value:SetText(tostring(sessionCount))
        end
        if self.lootProfileStatCards.items and self.lootProfileStatCards.items.value then
          self.lootProfileStatCards.items.value:SetText(tostring(awardedItemCount))
        end
        if self.lootProfileStatCards.participants and self.lootProfileStatCards.participants.value then
          self.lootProfileStatCards.participants.value:SetText(tostring(participantCount))
        end
        if self.lootProfileStatCards.rolls and self.lootProfileStatCards.rolls.value then
          self.lootProfileStatCards.rolls.value:SetText(tostring(rollCount))
        end
      end
    end
    if self.lootProfileSummary then
      local root = type(RootDB) == "function" and RootDB() or nil
      local showDeveloperDetails = type(root) == "table" and type(root.ui) == "table" and root.ui.showInternalProfileId == true
      local summaryLines = {
        string.format(
          "Point Mode: %s | Roll Template: %s",
          tostring(pointMode == "CUSTOM" and "Custom" or "LidTable"),
          tostring(GetRollTemplateText(rollTemplate))
        ),
      }
      if showDeveloperDetails then
        summaryLines[#summaryLines + 1] = "Developer: " .. BuildLootProfileIdentitySummary(identity, true)
      end
      self.lootProfileSummary:SetText(table.concat(summaryLines, "\n"))
    end

    if openSection == "points" and self.__lootPointItemSeasonTier ~= tonumber(seasonContext and seasonContext.tier) then
      self.__lootPointItemSeasonTier = tonumber(seasonContext and seasonContext.tier)
      ClearItemRuleSelection()
    end

    if openSection == "raid" or openSection == "points" then
      owner.__lootRaidSelectedTier = tonumber(seasonContext and seasonContext.tier)
    end
    local hasFrozenSeason = seasonContext and seasonContext.frozen == true

    if openSection == "raid" and self.lootRaidDropdown then
      if selectedRaidInSeason then
        SetDropdownValue(self.lootRaidDropdown, tonumber(selectedRaidInSeason.instanceID), tostring(selectedRaidInSeason.name or "?"))
      else
        local selectText = hasFrozenSeason and "(select profile-season image)" or "(select current-season image)"
        local emptyText = hasFrozenSeason and "(no profile-season images)" or "(no current-season images)"
        SetDropdownValue(self.lootRaidDropdown, nil, (#(seasonContext and seasonContext.raids or {}) > 0) and selectText or emptyText)
      end
    end
    if openSection == "raid" and self.lootRaidSeasonDropdown then
      SetDropdownValue(self.lootRaidSeasonDropdown, tonumber(seasonContext and seasonContext.tier), seasonName)
      if self.lootRaidSeasonDropdown.SetEnabled then
        self.lootRaidSeasonDropdown:SetEnabled(not hasFrozenSeason)
      end
    end
    if openSection == "points" and self.lootPointModeDropdown then
      local pointModeText = pointMode == "CUSTOM" and "Custom" or "LidTable"
      SetDropdownValue(self.lootPointModeDropdown, pointMode, pointModeText)
    end
    if openSection == "roll" and self.lootRollTemplateDropdown then
      SetDropdownValue(self.lootRollTemplateDropdown, rollTemplate, GetRollTemplateText(rollTemplate))
    end

    if openSection == "points" and self.lootPointItemDropdown then
      local selectedItemEntry = FindSeasonLootEntry(self.__lootSelectedRuleItemID, profile)
      if selectedItemEntry then
        owner.__lootSelectedRuleItemID = tonumber(selectedItemEntry.itemID)
        owner.__lootSelectedRuleItemName = selectedItemEntry.name
        owner.__lootSelectedRuleItemLink = selectedItemEntry.link
        owner.__lootSelectedRuleItemLevel = tonumber(selectedItemEntry.itemLevel)
        SetDropdownValue(self.lootPointItemDropdown, selectedItemEntry.itemID, string.format("%s | %s", FormatRaidLootItemLabel(selectedItemEntry), tostring(selectedItemEntry.sourceRaidName or "?")))
      else
        local itemText = hasFrozenSeason and "(select profile-season loot item)" or "(select current-season loot item)"
        SetDropdownValue(self.lootPointItemDropdown, nil, #seasonLootItems > 0 and itemText or "(no season loot items found)")
      end
    end

    if openSection == "raid" then
      if self.lootRaidHint then
        local seasonLabel = hasFrozenSeason and "profile's raid season" or "current raid season"
        self.lootRaidHint:SetText("Choose the artwork used in this profile's overview. Images are limited to the " .. seasonLabel .. ".")
      end
      if self.lootRaidGalleryTitle then
        self.lootRaidGalleryTitle:SetText("Available Artwork | " .. seasonName)
      end

      local galleryTiles = self.lootProfileImageTiles or {}
      local maxGalleryArtwork = math.max(0, #galleryTiles - 1)
      local galleryEntries = {}
      for _, raidEntry in ipairs(type(seasonContext) == "table" and seasonContext.raids or {}) do
        if #galleryEntries < maxGalleryArtwork and type(raidEntry) == "table" and tonumber(raidEntry.instanceID) then
          galleryEntries[#galleryEntries + 1] = raidEntry
        end
      end
      galleryEntries[#galleryEntries + 1] = false
      self.__lootProfileImageGalleryEntryCount = #galleryEntries
      for index, tile in ipairs(galleryTiles) do
        local raidEntry = galleryEntries[index]
        if tile then
          if raidEntry ~= nil then
            local isClearChoice = raidEntry == false
            local selected = isClearChoice and not selectedRaidInSeason
              or (type(raidEntry) == "table" and selectedRaidInSeason and tonumber(raidEntry.instanceID) == tonumber(selectedRaidInSeason.instanceID))
            local tileTexture = not isClearChoice and ResolveRaidPreviewTexture(raidEntry.instanceID) or nil
            tile.__lootProfileImageEntry = isClearChoice and nil or raidEntry
            tile.__lootProfileImageName = isClearChoice and "No Image" or tostring(raidEntry.name or "?")
            tile.__lootProfileImageIsClear = isClearChoice
            tile.__lootProfileImageSelected = selected and true or false
            if tile.artwork then
              tile.artwork:SetTexture(tileTexture)
              tile.artwork:SetShown(tileTexture ~= nil)
            end
            if tile.artworkShade then
              tile.artworkShade:SetColorTexture(0, 0, 0, selected and 0.06 or 0.24)
            end
            if tile.emptyText then
              tile.emptyText:SetShown(isClearChoice or not tileTexture)
              tile.emptyText:SetText(isClearChoice and "No Image" or "Artwork unavailable")
            end
            if tile.nameText then
              tile.nameText:SetText(isClearChoice and "No Image" or tostring(raidEntry.name or "?"))
              tile.nameText:SetTextColor(selected and 1.00 or 0.86, selected and 0.82 or 0.90, selected and 0.24 or 0.96, 1.00)
            end
            if tile.selectedText then
              tile.selectedText:SetShown(selected and true or false)
            end
            if tile.SetBackdropColor then
              tile:SetBackdropColor(selected and 0.13 or 0.02, selected and 0.10 or 0.03, selected and 0.03 or 0.05, 0.98)
            end
            if tile.SetBackdropBorderColor then
              tile:SetBackdropBorderColor(selected and 1.00 or 0.26, selected and 0.78 or 0.33, selected and 0.20 or 0.43, selected and 1.00 or 0.90)
            end
            tile:Show()
          else
            tile.__lootProfileImageEntry = nil
            tile.__lootProfileImageName = nil
            tile:Hide()
          end
        end
      end
    end
    if openSection == "points" and self.lootPointsHint then
      self.lootPointsHint:SetText("")
    end

    if self.lootProfileHeroRaidPreviewTitle then
      self.lootProfileHeroRaidPreviewTitle:SetText("")
      self.lootProfileHeroRaidPreviewTitle:Hide()
    end
    if self.lootProfileHeroRaidPreviewLabel then
      self.lootProfileHeroRaidPreviewLabel:SetText("")
      self.lootProfileHeroRaidPreviewLabel:Hide()
    end
    if self.lootProfileHeroRaidPreviewFrame then
      if self.lootProfileHeroRaidPreviewFrame.SetBackdropColor then
        self.lootProfileHeroRaidPreviewFrame:SetBackdropColor(0, 0, 0, 0)
      end
      if self.lootProfileHeroRaidPreviewFrame.SetBackdropBorderColor then
        self.lootProfileHeroRaidPreviewFrame:SetBackdropBorderColor(0, 0, 0, 0)
      end
    end
    if self.lootProfileHeroRaidPreviewTexture then
      if raidPreviewTexture then
        self.lootProfileHeroRaidPreviewTexture:SetTexture(raidPreviewTexture)
        self.lootProfileHeroRaidPreviewTexture:SetVertexColor(1, 1, 1, 1)
        self.lootProfileHeroRaidPreviewTexture:SetTexCoord(0.05, 0.80, 0.04, 0.64)
        self.lootProfileHeroRaidPreviewTexture:Show()
      else
        self.lootProfileHeroRaidPreviewTexture:SetTexture(nil)
        self.lootProfileHeroRaidPreviewTexture:Hide()
      end
    end
    if self.lootProfileHeroRaidPreviewEmpty then
      if raidPreviewTexture then
        self.lootProfileHeroRaidPreviewEmpty:Hide()
      else
        self.lootProfileHeroRaidPreviewEmpty:SetText("No image selected")
        self.lootProfileHeroRaidPreviewEmpty:Show()
      end
    end

    local function SetControlInteractive(control, allow)
      if not control then
        return
      end
      if control.Enable and control.Disable then
        if allow then
          control:Enable()
        else
          control:Disable()
        end
      elseif control.SetEnabled then
        control:SetEnabled(allow and true or false)
      end
      if control.SetAlpha then
        control:SetAlpha(allow and 1.00 or 0.52)
      end
    end

    if openSection == "roll" and self.lootRollAccessHint then
      if combatLocked then
        self.lootRollAccessHint:SetText("Combat active: roll settings are temporarily locked. Leave combat to edit or preview.")
        self.lootRollAccessHint:SetTextColor(1.00, 0.78, 0.28, 1.00)
        self.lootRollAccessHint:Show()
      elseif not access.canEditRollSettings then
        self.lootRollAccessHint:SetText("Read-only: your current role cannot edit, import, or preview this profile's roll settings.")
        self.lootRollAccessHint:SetTextColor(0.70, 0.74, 0.82, 1.00)
        self.lootRollAccessHint:Show()
      else
        self.lootRollAccessHint:SetText("")
        self.lootRollAccessHint:Hide()
      end
    end

    if openSection == "roll" then
      SetControlInteractive(self.lootRollOptionEdit, canEditRollSettings)
      SetControlInteractive(self.lootAddRollOptionBtn, canEditRollSettings)
      SetControlInteractive(self.lootRemoveRollOptionBtn, canEditRollSettings)
      SetControlInteractive(self.lootTestRollPopupBtn, canEditRollSettings)
      SetControlInteractive(self.lootPreviewHostBoardBtn, canEditRollSettings)
      SetControlInteractive(self.lootRollTemplateDropdown, canEditRollSettings)
      SetControlInteractive(self.lootRollSettingsToolsDropdown, canEditRollSettings)
      SetControlInteractive(self.lootRollExportBtn, canEditRollSettings)
      SetControlInteractive(self.lootRollImportStringBtn, canEditRollSettings)
      SetControlInteractive(self.lootRollImportProfileDropdown, canEditRollSettings)
    end
    if openSection == "raid" and self.lootProfileHeroRaidPreviewButton then
      self.lootProfileHeroRaidPreviewButton:EnableMouse(false)
      self.lootProfileHeroRaidPreviewButton:Hide()
    end
    if openSection == "raid" then
      SetControlInteractive(self.lootRaidDropdown, access.canEditRaidSettings)
      SetControlInteractive(self.lootSaveRaidBtn, access.canEditRaidSettings)
      for _, tile in ipairs(self.lootProfileImageTiles or {}) do
        if tile and tile:IsShown() then
          SetControlInteractive(tile, access.canEditRaidSettings)
        end
      end
    end
    if openSection == "points" then
      SetControlInteractive(self.lootPointModeDropdown, access.canEditPointSettings)
      SetControlInteractive(self.lootPointItemLevelEdit, access.canEditPointSettings)
      SetControlInteractive(self.lootPointItemDropdown, access.canEditPointSettings)
      SetControlInteractive(self.lootPointLevelValueEdit or self.lootPointValueEdit, access.canEditPointSettings)
      SetControlInteractive(self.lootPointItemValueEdit, access.canEditPointSettings)
      SetControlInteractive(self.lootAddPointRuleBtn, access.canEditPointSettings)
      SetControlInteractive(self.lootAddItemPointRuleBtn, access.canEditPointSettings)
      SetControlInteractive(self.lootRemovePointRuleBtn, access.canEditPointSettings)
      SetControlInteractive(self.lootPointExportBtn, access.canEditPointSettings)
      SetControlInteractive(self.lootPointImportStringBtn, access.canEditPointSettings)
      SetControlInteractive(self.lootPointImportProfileDropdown, access.canEditPointSettings)
    end

    if openSection == "roll" then
      RefreshRollOptionRows(profile)
      local rollOptions = type(profile.settings) == "table" and type(profile.settings.rollOptions) == "table" and profile.settings.rollOptions or {}
      if self.lootRollInlinePreviewButtons then
      local previewGroups = {
        NEED = {},
        GREEDPASS = {},
      }
      for sourceIndex, option in ipairs(rollOptions) do
        local section = ResolveInlineRollPopupSection(option)
        previewGroups[section][#previewGroups[section] + 1] = {
          option = option,
          sourceIndex = sourceIndex,
        }
      end
      local orderedPreviewEntries = {}
      for _, section in ipairs({ "NEED", "GREEDPASS" }) do
        for _, entry in ipairs(previewGroups[section]) do
          orderedPreviewEntries[#orderedPreviewEntries + 1] = entry
        end
      end
      local visiblePreviewCount = math.min(#orderedPreviewEntries, #self.lootRollInlinePreviewButtons)
      self.__lootRollInlinePreviewCount = visiblePreviewCount
      self.__lootRollInlinePreviewNeedCount = #previewGroups.NEED
      self.__lootRollInlinePreviewGreedCount = #previewGroups.GREEDPASS
      if self.lootRollInlinePreviewNeedEmpty then
        self.lootRollInlinePreviewNeedEmpty:SetShown(#previewGroups.NEED == 0)
      end
      if self.lootRollInlinePreviewGreedEmpty then
        self.lootRollInlinePreviewGreedEmpty:SetShown(#previewGroups.GREEDPASS == 0)
      end
      for index, previewButton in ipairs(self.lootRollInlinePreviewButtons) do
        local entry = orderedPreviewEntries[index]
        local option = type(entry) == "table" and entry.option or nil
        if type(option) == "table" then
          local section = index <= #previewGroups.NEED and "NEED" or "GREEDPASS"
          local parent = section == "NEED" and self.lootRollInlinePreviewNeedFrame or self.lootRollInlinePreviewGreedFrame
          if parent and previewButton:GetParent() ~= parent then
            previewButton:SetParent(parent)
          end
          if parent and previewButton.SetFrameLevel then
            previewButton:SetFrameLevel((parent:GetFrameLevel() or 1) + 2)
          end
          local color = type(option.color) == "table" and option.color or { 0.82, 0.82, 0.86 }
          local red = tonumber(color[1]) or 0.82
          local green = tonumber(color[2]) or 0.82
          local blue = tonumber(color[3]) or 0.86
          if previewButton.SetBackdropColor then
            previewButton:SetBackdropColor(0.03 + (red * 0.05), 0.04 + (green * 0.05), 0.06 + (blue * 0.05), 0.98)
          end
          if previewButton.SetBackdropBorderColor then
            previewButton:SetBackdropBorderColor(red, green, blue, 0.92)
          end
          if previewButton.icon then
            previewButton.icon:SetTexture(type(ResolveRollOptionIcon) == "function" and ResolveRollOptionIcon(option) or "Interface\\Icons\\INV_Misc_QuestionMark")
          end
          if previewButton.label then
            previewButton.label:SetText(tostring(option.label or option.key or "Option"))
            previewButton.label:SetTextColor(red, green, blue, 1.00)
          end
          previewButton.__popupSection = section
          previewButton.__sourceIndex = tonumber(entry.sourceIndex) or index
          previewButton:Show()
        else
          previewButton:Hide()
        end
      end
      if self.lootRollInlinePreviewEmpty then
        self.lootRollInlinePreviewEmpty:Hide()
      end
      end
      local rollOptionCount = tonumber(self.__lootRollOptionRowCount) or 0
      local selectedRollOptionIndex = tonumber(self.__lootSelectedRollOptionIndex)
      local hasSelectedRollOption = selectedRollOptionIndex and selectedRollOptionIndex >= 1 and selectedRollOptionIndex <= rollOptionCount
      for _, row in ipairs(self.lootRollOptionRows or {}) do
        if row and row:IsShown() then
          local optionIndex = tonumber(row.__optionIndex) or 0
          row.__canSelect = canEditRollSettings
          SetControlInteractive(row.selectButton, canEditRollSettings)
          SetControlInteractive(row.nameEdit, canEditRollSettings)
          SetControlInteractive(row.moveUpBtn, canEditRollSettings and optionIndex > 1)
          SetControlInteractive(row.moveDownBtn, canEditRollSettings and optionIndex < rollOptionCount)
          SetControlInteractive(row.iconDropdown, canEditRollSettings)
          SetControlInteractive(row.pointBehaviorDropdown, canEditRollSettings)
          SetControlInteractive(row.popupSectionDropdown, canEditRollSettings)
          SetControlInteractive(row.colorButton, canEditRollSettings)
        end
      end
      SetControlInteractive(self.lootRemoveRollOptionBtn, canEditRollSettings and hasSelectedRollOption)
      if self.lootRollOptionsText then
        self.lootRollOptionsText:SetText(BuildRollOptionsText(profile))
      end
    end

    if openSection == "points" then
      RefreshLidTableRows(profile)
      if type(RefreshPointRuleRows) == "function" then
        RefreshPointRuleRows(profile)
      end
      local pointRuleCount = tonumber(self.__lootPointRuleRowCount) or 0
      local selectedPointRuleIndex = tonumber(self.__lootSelectedPointRuleIndex)
      local hasSelectedPointRule = selectedPointRuleIndex and selectedPointRuleIndex >= 1 and selectedPointRuleIndex <= pointRuleCount
      for _, row in ipairs(self.lootPointRuleRows or {}) do
        if row and row:IsShown() then
          row.__canSelect = access.canEditPointSettings
          SetControlInteractive(row.selectButton, access.canEditPointSettings)
        end
      end
      SetControlInteractive(self.lootRemovePointRuleBtn, access.canEditPointSettings and hasSelectedPointRule)
      for _, row in ipairs(self.lootLidTableRows or {}) do
        SetControlInteractive(row and row.pointsEdit, access.canEditPointSettings)
        SetControlInteractive(row and row.itemLevelEdit, access.canEditPointSettings)
        SetControlInteractive(row and row.setPieceEdit, access.canEditPointSettings)
        SetControlInteractive(row and row.offSpecEdit, access.canEditPointSettings)
        SetControlInteractive(row and row.transmogEdit, access.canEditPointSettings)
        SetControlInteractive(row and row.disenchantEdit, access.canEditPointSettings)
      end
      if self.lootPointRulesText then
        if pointMode == "CUSTOM" then
          self.lootPointRulesText:SetText(BuildPointRulesText(profile))
        else
          self.lootPointRulesText:SetText(BuildLidTableSummaryText(profile))
        end
      end
      if self.lootPointRuleFeedback then
        self.lootPointRuleFeedback:SetText("")
        self.lootPointRuleFeedback:Hide()
      end
    end
    do
      local layoutStartedAt = INTERNAL_API.LIDCOUNCIL_BeginSyncPerformanceSample_Impl("editor_layout_profiles", 1)
      LayoutProfileContent(self)
      INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl("editor_layout_profiles", layoutStartedAt, {
        context = openSection,
      })
    end
    if self.currentPage == "Profiles" and self.UpdateScrollLayout then
      self:UpdateScrollLayout(true)
    end
  end

  return {
    RefreshProfilePage = RefreshProfilePage,
  }
end
