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

local shared = INTERNAL_API.LIDCOUNCIL_LootEditorShared_Impl
if type(shared) ~= "table" then
  error("LidCouncil missing loot editor shared helpers.")
end

local lootListData = INTERNAL_API.LIDCOUNCIL_LootListData_Impl
if type(lootListData) ~= "table" then
  error("LidCouncil missing loot list data helpers.")
end

local RootDB = shared.RootDB
local GetEnglishClassAndSpec = shared.RequireApi("LIDCOUNCIL_GetEnglishClassAndSpec", nil)
local ApplyFrameSkin = shared.ApplyFrameSkin
local GetLootProfile = shared.GetLootProfile
local GetPrimaryLootProfileName = shared.GetPrimaryLootProfileName
local IsLootProfileVisibleInEditor = shared.IsLootProfileVisibleInEditor or function(_, profileName)
  return profileName ~= nil and profileName ~= ""
end
local GetLootProfileAccessInfo = shared.GetLootProfileAccessInfo
local TrimText = shared.TrimText
local FormatDateTime = shared.FormatDateTime
local ClampLayoutValue = shared.ClampLayoutValue
local SetControlWidth = shared.SetControlWidth
local GetFontStringWidth = shared.GetFontStringWidth
local FlowLayoutControls = shared.FlowLayoutControls
local GetLootProfileDomainRevision = type(shared.ResolveOptionalApiFunction) == "function"
  and shared.ResolveOptionalApiFunction("LIDCOUNCIL_GetLootProfileDomainRevision")
  or nil

local EnsureLootLedgerMetaLocal = lootListData.EnsureLootLedgerMetaLocal
local ToggleLootLedgerGroupCollapsedLocal = lootListData.ToggleLootLedgerGroupCollapsedLocal
local NormalizeLootLedgerRoleLocal = lootListData.NormalizeLootLedgerRoleLocal
local BuildLootLedgerNavRows = lootListData.BuildLootLedgerNavRows
local GetEditorThemePalette = type(INTERNAL_API.LIDCOUNCIL_GetEditorThemePalette_Impl) == "function" and INTERNAL_API.LIDCOUNCIL_GetEditorThemePalette_Impl or nil
local EnsureLootLedgerRowFrames
local GetSelectedLootLedgerRow
local GetClassColorForRow
local BuildSpecLabel
local GetLootLedgerHeaderIconData
local RefreshLootListTableView
local EnsureLootLedgerHistoryRows
local EnsureLootLedgerMemberRows
local ResolveLootLedgerEntryIcon
local BuildLootLedgerHistoryEntries
local FormatLootLedgerPointBehaviorLabel
local BuildLootLedgerAwardInsight
local BuildLootLedgerNeedDiceInsight
local BuildNeedDiceSummaryText
local BuildBisItemSummaryText
local ApplyLootLedgerTextureIcon
local GetLootLedgerTalentBackground
local UpdateLootLedgerDetailLayout

local function BuildLootListInlineIconText(iconData)
  if type(iconData) ~= "table" or TrimText(iconData.texture) == "" then
    return ""
  end
  if type(iconData.left) == "number" and type(iconData.right) == "number" and type(iconData.top) == "number" and type(iconData.bottom) == "number" then
    local fileWidth = tonumber(iconData.fileWidth) or 256
    local fileHeight = tonumber(iconData.fileHeight) or 256
    return string.format(
      "|T%s:14:14:0:0:%d:%d:%d:%d:%d:%d|t ",
      tostring(iconData.texture),
      fileWidth,
      fileHeight,
      math.floor((tonumber(iconData.left) or 0) * fileWidth),
      math.floor((tonumber(iconData.right) or 1) * fileWidth),
      math.floor((tonumber(iconData.top) or 0) * fileHeight),
      math.floor((tonumber(iconData.bottom) or 1) * fileHeight)
    )
  end
  return string.format("|T%s:14:14:0:0|t ", tostring(iconData.texture))
end

local function BuildLootLedgerMainDropdownText(row)
  if type(row) ~= "table" then
    return "(select main)"
  end
  local iconText = BuildLootListInlineIconText(GetLootLedgerHeaderIconData(row))
  local r, g, b = GetClassColorForRow(row)
  local colorHex = string.format("%02x%02x%02x", math.floor((r or 1) * 255), math.floor((g or 1) * 255), math.floor((b or 1) * 255))
  return string.format(
    "%s|cff%s%s|r | %s | %d pts",
    iconText,
    colorHex,
    tostring(row.character or "?"),
    tostring(BuildSpecLabel(row)),
    tonumber(row.totalPoints) or 0
  )
end

local function GetLootListViewMode()
  local root = RootDB()
  root.ui = root.ui or {}
  local mode = TrimText(root.ui.lootLedgerViewMode)
  if mode ~= "DETAILS" then
    mode = "LIST_ONLY"
  end
  root.ui.lootLedgerViewMode = mode
  return mode
end

local function ResolveEffectiveLootListProfileName(requestedName)
  local root = RootDB()
  local resolvedName = TrimText(GetPrimaryLootProfileName(requestedName))
  if resolvedName ~= "" and not IsLootProfileVisibleInEditor(root, resolvedName) then
    resolvedName = ""
  end
  if resolvedName ~= "" then
    return resolvedName
  end
  resolvedName = TrimText(root and root.currentProfile or "")
  if resolvedName ~= "" and not IsLootProfileVisibleInEditor(root, resolvedName) then
    resolvedName = TrimText(type(root.ui) == "table" and root.ui.lastNonSimulationProfile or "")
  end
  if resolvedName ~= "" then
    return resolvedName
  end
  return "Default"
end

local CreateLootListDetailsHelpers = INTERNAL_API.LIDCOUNCIL_CreateLootListDetailsHelpers_Impl
if type(CreateLootListDetailsHelpers) ~= "function" then
  error("LidCouncil missing loot list details helpers.")
end

local lootListDetailsHelpers = CreateLootListDetailsHelpers({
  ApplyFrameSkin = ApplyFrameSkin,
  TrimText = TrimText,
  FormatDateTime = FormatDateTime,
  ClampLayoutValue = ClampLayoutValue,
  SetControlWidth = SetControlWidth,
  GetFontStringWidth = GetFontStringWidth,
  FlowLayoutControls = FlowLayoutControls,
})

EnsureLootLedgerHistoryRows = lootListDetailsHelpers.EnsureLootLedgerHistoryRows
EnsureLootLedgerMemberRows = lootListDetailsHelpers.EnsureLootLedgerMemberRows
ResolveLootLedgerEntryIcon = lootListDetailsHelpers.ResolveLootLedgerEntryIcon
BuildLootLedgerHistoryEntries = lootListDetailsHelpers.BuildLootLedgerHistoryEntries
FormatLootLedgerPointBehaviorLabel = lootListDetailsHelpers.FormatLootLedgerPointBehaviorLabel
BuildLootLedgerAwardInsight = lootListDetailsHelpers.BuildLootLedgerAwardInsight
BuildLootLedgerNeedDiceInsight = lootListDetailsHelpers.BuildLootLedgerNeedDiceInsight
BuildNeedDiceSummaryText = lootListDetailsHelpers.BuildNeedDiceSummaryText
BuildBisItemSummaryText = lootListDetailsHelpers.BuildBisItemSummaryText
ApplyLootLedgerTextureIcon = lootListDetailsHelpers.ApplyLootLedgerTextureIcon
GetLootLedgerTalentBackground = lootListDetailsHelpers.GetLootLedgerTalentBackground
UpdateLootLedgerDetailLayout = lootListDetailsHelpers.UpdateLootLedgerDetailLayout

local CreateLootListTableHelpers = INTERNAL_API.LIDCOUNCIL_CreateLootListTableHelpers_Impl
if type(CreateLootListTableHelpers) ~= "function" then
  error("LidCouncil missing loot list table helpers.")
end

local lootListTableHelpers = CreateLootListTableHelpers({
  TrimText = TrimText,
  ClampLayoutValue = ClampLayoutValue,
  BuildLootLedgerNavRows = BuildLootLedgerNavRows,
  ToggleLootLedgerGroupCollapsedLocal = ToggleLootLedgerGroupCollapsedLocal,
  ApplyLootLedgerTextureIcon = ApplyLootLedgerTextureIcon,
  GetEnglishClassAndSpec = GetEnglishClassAndSpec,
  GetEditorThemePalette = GetEditorThemePalette,
})

GetClassColorForRow = lootListTableHelpers.GetClassColorForRow
BuildSpecLabel = lootListTableHelpers.BuildSpecLabel
GetLootLedgerHeaderIconData = lootListTableHelpers.GetLootLedgerHeaderIconData
EnsureLootLedgerRowFrames = lootListTableHelpers.EnsureLootLedgerRowFrames
GetSelectedLootLedgerRow = lootListTableHelpers.GetSelectedLootLedgerRow
RefreshLootListTableView = lootListTableHelpers.RefreshLootListTableView

local function RequestLootListRefresh(owner)
  if type(owner) ~= "table" then
    return false
  end
  if owner.RequestLootListPageRefresh then
    owner:RequestLootListPageRefresh()
    return true
  end
  if owner.RefreshLootListPage then
    owner:RefreshLootListPage()
    return true
  end
  if owner.Refresh then
    owner:Refresh()
    return true
  end
  return false
end

local function NormalizeLootLedgerDisplayPoints(value)
  local points = tonumber(value) or 0
  return points == 0 and 0 or points
end

local LOOT_LEDGER_HISTORY_PAGE_SIZE = 10

local function BuildLootLedgerHistoryCacheKey(profile, profileName, selectedRow)
  if type(profile) ~= "table" or type(selectedRow) ~= "table" or selectedRow.type ~= "character" then
    return ""
  end

  local memberKey = string.lower(TrimText(selectedRow.character))

  local operationalRevision = 0
  local settingsRevision = 0
  if type(GetLootProfileDomainRevision) == "function" then
    operationalRevision = tonumber(GetLootProfileDomainRevision(profile, "operational")) or 0
    settingsRevision = tonumber(GetLootProfileDomainRevision(profile, "settings")) or 0
  else
    operationalRevision = tonumber(type(profile.meta) == "table" and profile.meta.revision) or 0
    settingsRevision = operationalRevision
  end

  return table.concat({
    string.lower(TrimText(profileName)),
    tostring(operationalRevision),
    tostring(settingsRevision),
    string.lower(TrimText(selectedRow.key or selectedRow.character)),
    memberKey,
  }, "\031")
end

local function RefreshLootListPage(self, page)
  if not self or not page then
    return
  end

  if self.lootLedgerSearchEdit and (GetCurrentKeyBoardFocus == nil or GetCurrentKeyBoardFocus() ~= self.lootLedgerSearchEdit) then
    local desiredSearchText = self.__lootLedgerSearchText or ""
    if self.lootLedgerSearchEdit.GetText and self.lootLedgerSearchEdit:GetText() ~= desiredSearchText then
      self.lootLedgerSearchEdit:SetText(desiredSearchText)
    end
  end

  local root = RootDB()
  local resolvedProfileName = ResolveEffectiveLootListProfileName(root.currentProfile)
  local profile, profileName = GetLootProfile(resolvedProfileName)
  local access = GetLootProfileAccessInfo(profileName)
  local pageWidth = (page.GetWidth and page:GetWidth()) or (self.scrollChild and self.scrollChild:GetWidth()) or 980
  local viewMode = GetLootListViewMode()
  local detailsMode = viewMode == "DETAILS"
  local popupOpen = self.__lootLedgerPopupOpen and self.lootListRightBg and self.lootListRightBg:GetParent() ~= page
  local tableState = RefreshLootListTableView(self, page, {
    profile = profile,
    profileName = profileName,
    pageWidth = pageWidth,
    detailsMode = detailsMode,
    popupOpen = popupOpen,
  })
  local showRightPane = tableState and tableState.showRightPane or false
  local selectedRow = tableState and tableState.selectedRow or nil
  local allCharactersByKey = tableState and tableState.allCharactersByKey or {}

  local selectedCharacter = selectedRow and selectedRow.character or nil
  local detailContentWidth = math.max(540, math.floor((self.lootListRightBg and self.lootListRightBg:GetWidth() or 620) - 40))
  local rightWidth = math.max(320, detailContentWidth - 18)
  local metaByCharacter = EnsureLootLedgerMetaLocal(profile)
  local selectedMeta = selectedCharacter and metaByCharacter[selectedCharacter] or nil
  if self.__lootLedgerPendingRoleCharacter and (not selectedCharacter or string.lower(tostring(self.__lootLedgerPendingRoleCharacter or "")) ~= string.lower(tostring(selectedCharacter or ""))) then
    self.__lootLedgerPendingRole = nil
    self.__lootLedgerPendingRoleCharacter = nil
  end
  local selectedRole = NormalizeLootLedgerRoleLocal(selectedRow and selectedRow.mainAltRole or (selectedMeta and selectedMeta.mainAltRole))
  if self.__lootLedgerPendingRoleCharacter and selectedCharacter and string.lower(tostring(self.__lootLedgerPendingRoleCharacter or "")) == string.lower(tostring(selectedCharacter or "")) then
    selectedRole = NormalizeLootLedgerRoleLocal(self.__lootLedgerPendingRole)
  end
  local summaryTarget = TrimText(selectedRow and selectedRow.mainCharacter or (selectedMeta and selectedMeta.mainCharacter) or "")
  if summaryTarget ~= "" and not allCharactersByKey[summaryTarget] then
    summaryTarget = ""
  end
  if self.__lootLedgerLinkManagementCharacter and self.__lootLedgerLinkManagementCharacter ~= selectedCharacter then
    self.__lootLedgerLinkManagementCharacter = nil
  end
  if self.__lootLedgerManualAdjustmentCharacter and self.__lootLedgerManualAdjustmentCharacter ~= selectedCharacter then
    self.__lootLedgerManualAdjustmentCharacter = nil
  end
  if self.__lootLedgerNoteEditingCharacter and self.__lootLedgerNoteEditingCharacter ~= selectedCharacter then
    self.__lootLedgerNoteEditingCharacter = nil
  end
  local showLinkManagement = selectedCharacter ~= nil and self.__lootLedgerLinkManagementCharacter == selectedCharacter
  local showManualAdjustment = selectedCharacter ~= nil and self.__lootLedgerManualAdjustmentCharacter == selectedCharacter
  local showNoteEditor = selectedCharacter ~= nil and self.__lootLedgerNoteEditingCharacter == selectedCharacter
  self.__lootLedgerShowLinkManagement = showLinkManagement
  self.__lootLedgerShowManualAdjustment = showManualAdjustment
  self.__lootLedgerShowNoteEditor = showNoteEditor
  self.__lootLedgerHasSelectedCharacter = selectedCharacter ~= nil
  self.__lootLedgerShowMainAssignment = showLinkManagement and selectedRole == "ALT"

  if self.backgroundsCurrentLabel then
    self.backgroundsCurrentLabel:SetText("Current Profile: " .. tostring(profileName))
  end

  local textR, textG, textB, textA = GetClassColorForRow(selectedRow)
  local selectedClassName = selectedRow and TrimText(selectedRow.className) or ""
  local selectedSpecName = selectedRow and TrimText(selectedRow.specName) or ""
  if type(GetEnglishClassAndSpec) == "function" and selectedRow then
    selectedClassName, selectedSpecName = GetEnglishClassAndSpec(
      selectedRow.classFile,
      selectedRow.specID,
      selectedClassName,
      selectedSpecName,
      selectedRow.specIcon
    )
  end
  ApplyLootLedgerTextureIcon(self.lootLedgerHeroIcon, GetLootLedgerHeaderIconData(selectedRow))
  local talentBackgroundRow = selectedRow
  if selectedRow and selectedSpecName ~= TrimText(selectedRow.specName) then
    talentBackgroundRow = {
      type = "character",
      classFile = selectedRow.classFile,
      specName = selectedSpecName,
    }
  end
  local talentBackground = type(GetLootLedgerTalentBackground) == "function" and GetLootLedgerTalentBackground(talentBackgroundRow) or nil
  self.__lootLedgerHasTalentBackground = type(talentBackground) == "table" and talentBackground.fileID ~= nil
  if self.lootLedgerHeroTalentBackground then
    if self.__lootLedgerHasTalentBackground then
      self.lootLedgerHeroTalentBackground:SetTexture(talentBackground.fileID)
      self.lootLedgerHeroTalentBackground:SetTexCoord(
        talentBackground.left or 0,
        talentBackground.right or 1,
        talentBackground.top or 0,
        talentBackground.bottom or 1
      )
      self.lootLedgerHeroTalentBackground:SetVertexColor(1, 1, 1, 1)
      self.lootLedgerHeroTalentBackground:SetAlpha(1.00)
      self.lootLedgerHeroTalentBackground:Show()
    else
      self.lootLedgerHeroTalentBackground:Hide()
    end
  end
  if self.lootLedgerHeroTalentFade then
    self.lootLedgerHeroTalentFade:SetShown(self.__lootLedgerHasTalentBackground)
  end
  if self.lootLedgerSelectedLabel then
    self.lootLedgerSelectedLabel:SetText(tostring(selectedCharacter or "(no character selected)"))
    self.lootLedgerSelectedLabel:SetTextColor(textR, textG, textB, textA)
  end
  if self.lootLedgerHeroRoleBadge then
    local isAlt = selectedRole == "ALT"
    self.lootLedgerHeroRoleBadge:SetShown(selectedRow ~= nil)
    if self.lootLedgerHeroRoleBadge.SetBackdropColor then
      if isAlt then
        self.lootLedgerHeroRoleBadge:SetBackdropColor(0.20, 0.13, 0.03, 0.94)
      else
        self.lootLedgerHeroRoleBadge:SetBackdropColor(0.03, 0.16, 0.07, 0.94)
      end
    end
    if self.lootLedgerHeroRoleBadge.SetBackdropBorderColor then
      if isAlt then
        self.lootLedgerHeroRoleBadge:SetBackdropBorderColor(0.94, 0.70, 0.20, 0.96)
      else
        self.lootLedgerHeroRoleBadge:SetBackdropBorderColor(0.22, 0.88, 0.46, 0.96)
      end
    end
  end
  if self.lootLedgerHeroRoleText then
    if selectedRole == "ALT" then
      self.lootLedgerHeroRoleText:SetText("ALT")
      self.lootLedgerHeroRoleText:SetTextColor(1.00, 0.82, 0.30, 1)
    else
      self.lootLedgerHeroRoleText:SetText("MAIN")
      self.lootLedgerHeroRoleText:SetTextColor(0.46, 1.00, 0.58, 1)
    end
  end
  if self.lootLedgerTotalLabel then
    local classText = selectedClassName
    local specText = selectedRow and selectedSpecName or ""
    local headerLine = specText ~= "" and specText or "Unknown Specialization"
    if classText ~= "" and classText ~= specText then
      headerLine = headerLine .. " " .. classText
    end
    self.lootLedgerTotalLabel:SetText(headerLine)
    self.lootLedgerTotalLabel:SetTextColor(textR, textG, textB, textA)
  end
  if self.lootLedgerSummaryText then
    if not selectedRow then
      self.lootLedgerSummaryText:SetText("Select a character from the Loot List on the left.")
    else
      -- Linked-character context belongs to the section below, not the identity card.
      self.lootLedgerSummaryText:SetText("")
    end
  end
  local selectedNote = selectedRow and TrimText(selectedRow.note) or ""
  local hasCharacterNote = selectedNote ~= ""
  self.__lootLedgerHasCharacterNote = hasCharacterNote
  if self.lootLedgerCharacterNoteLabel then
    if hasCharacterNote then
      self.lootLedgerCharacterNoteLabel:SetTextColor(1.00, 0.82, 0.24, 1.00)
    else
      self.lootLedgerCharacterNoteLabel:SetTextColor(0.78, 0.68, 0.36, 1.00)
    end
  end
  if self.lootLedgerCharacterNoteDisplay then
    self.lootLedgerCharacterNoteDisplay:SetText(hasCharacterNote and selectedNote or "No note added.")
    if hasCharacterNote then
      self.lootLedgerCharacterNoteDisplay:SetTextColor(0.94, 0.94, 0.97, 1)
    else
      self.lootLedgerCharacterNoteDisplay:SetTextColor(0.72, 0.74, 0.80, 1)
    end
  end
  if self.lootLedgerCharacterNoteFrame then
    self.lootLedgerCharacterNoteFrame:SetShown(selectedRow ~= nil)
    if self.lootLedgerCharacterNoteFrame.SetBackdropColor then
      if hasCharacterNote or showNoteEditor then
        self.lootLedgerCharacterNoteFrame:SetBackdropColor(0.025, 0.03, 0.045, 0.96)
      else
        self.lootLedgerCharacterNoteFrame:SetBackdropColor(0, 0, 0, 0)
      end
    end
    if self.lootLedgerCharacterNoteFrame.SetBackdropBorderColor then
      if hasCharacterNote or showNoteEditor then
        self.lootLedgerCharacterNoteFrame:SetBackdropBorderColor(0.55, 0.55, 0.58, 0.72)
      else
        self.lootLedgerCharacterNoteFrame:SetBackdropBorderColor(0, 0, 0, 0)
      end
    end
  end
  if self.lootLedgerCharacterNoteToggleBtn then
    self.lootLedgerCharacterNoteToggleBtn:SetText(selectedNote ~= "" and "Edit Note" or "Add Note")
    if self.lootLedgerCharacterNoteToggleBtn.Enable then
      if access.canEditNotes and selectedRow then
        self.lootLedgerCharacterNoteToggleBtn:Enable()
      else
        self.lootLedgerCharacterNoteToggleBtn:Disable()
      end
    end
  end
  if self.lootLedgerCharacterNoteSaveBtn then
    self.lootLedgerCharacterNoteSaveBtn:SetShown(showNoteEditor)
    if self.lootLedgerCharacterNoteSaveBtn.Enable then
      if access.canEditNotes and selectedRow then
        self.lootLedgerCharacterNoteSaveBtn:Enable()
      else
        self.lootLedgerCharacterNoteSaveBtn:Disable()
      end
    end
  end
  if self.lootLedgerCharacterNoteCancelBtn then
    self.lootLedgerCharacterNoteCancelBtn:SetShown(showNoteEditor)
  end

  if self.lootLedgerStatCards then
    if self.lootLedgerStatCards.sessions and self.lootLedgerStatCards.sessions.value then
      self.lootLedgerStatCards.sessions.value:SetText(tostring(tonumber(selectedRow and selectedRow.ownSessionCount) or tonumber(selectedRow and selectedRow.sessionCount) or 0))
    end
    if self.lootLedgerStatCards.items and self.lootLedgerStatCards.items.value then
      self.lootLedgerStatCards.items.value:SetText(tostring(tonumber(selectedRow and selectedRow.ownItemCount) or tonumber(selectedRow and selectedRow.itemCount) or 0))
    end
    if self.lootLedgerStatCards.points and self.lootLedgerStatCards.points.value then
      self.lootLedgerStatCards.points.value:SetText(tostring(NormalizeLootLedgerDisplayPoints(tonumber(selectedRow and selectedRow.ownTotalPoints) or tonumber(selectedRow and selectedRow.totalPoints))))
    end
    if self.lootLedgerStatCards.total and self.lootLedgerStatCards.total.value then
      self.lootLedgerStatCards.total.value:SetText(tostring(NormalizeLootLedgerDisplayPoints(tonumber(selectedRow and selectedRow.groupTotalPoints) or tonumber(selectedRow and selectedRow.totalPoints))))
    end
    if self.lootLedgerStatCards.bis and self.lootLedgerStatCards.bis.value then
      self.lootLedgerStatCards.bis.value:SetText(tostring(tonumber(selectedRow and selectedRow.ownBisCount) or tonumber(selectedRow and selectedRow.bisCount) or 0))
    end
    if self.lootLedgerStatCards.offspec and self.lootLedgerStatCards.offspec.value then
      self.lootLedgerStatCards.offspec.value:SetText(tostring(tonumber(selectedRow and selectedRow.ownOffSpecCount) or tonumber(selectedRow and selectedRow.offSpecCount) or 0))
    end
    if self.lootLedgerStatCards.transmog and self.lootLedgerStatCards.transmog.value then
      self.lootLedgerStatCards.transmog.value:SetText(tostring(tonumber(selectedRow and selectedRow.ownTransmogCount) or tonumber(selectedRow and selectedRow.transmogCount) or 0))
    end
    if self.lootLedgerStatCards.disenchant and self.lootLedgerStatCards.disenchant.value then
      self.lootLedgerStatCards.disenchant.value:SetText(tostring(tonumber(selectedRow and selectedRow.ownDisenchantCount) or tonumber(selectedRow and selectedRow.disenchantCount) or 0))
    end
  end

  local membersHeaderText = "Linked Alts"
  local membersInfoText = ""
  local memberCards = {}

  if not selectedRow then
    membersInfoText = "No Loot List selection available."
  elseif selectedRole == "ALT" then
    membersHeaderText = "Linked Main"
    if summaryTarget == "" then
      membersInfoText = "No Main is assigned yet. Use Manage Links to attach this character."
    else
      local targetRow = allCharactersByKey and allCharactersByKey[summaryTarget] or nil
      if targetRow then
        membersHeaderText = "Linked Group"
        local includedMembers = {}
        local function AddLinkedMember(characterKey)
          if includedMembers[characterKey] then
            return
          end
          local row = allCharactersByKey and allCharactersByKey[characterKey] or nil
          if row then
            includedMembers[characterKey] = true
            memberCards[#memberCards + 1] = row
          end
        end
        for _, memberName in ipairs(targetRow.summaryMembers or {}) do
          AddLinkedMember(memberName)
        end
        AddLinkedMember(targetRow.character)
        AddLinkedMember(selectedCharacter)
        table.sort(memberCards, function(a, b)
          local aRole = NormalizeLootLedgerRoleLocal(a and a.mainAltRole)
          local bRole = NormalizeLootLedgerRoleLocal(b and b.mainAltRole)
          if aRole ~= bRole then
            return aRole == "MAIN"
          end
          return string.lower(tostring(a and a.character or "")) < string.lower(tostring(b and b.character or ""))
        end)
      else
        membersInfoText = "The assigned Main is no longer available in this Loot List."
      end
    end
  else
    for _, memberName in ipairs(selectedRow.summaryMembers or {}) do
      if memberName ~= selectedRow.character then
        local row = allCharactersByKey and allCharactersByKey[memberName] or nil
        if row then
          memberCards[#memberCards + 1] = row
        end
      end
    end
    table.sort(memberCards, function(a, b)
      return string.lower(tostring(a and a.character or "")) < string.lower(tostring(b and b.character or ""))
    end)
  end

  self.__lootLedgerLinkedAltsEmpty = selectedRow ~= nil
    and selectedRole ~= "ALT"
    and #memberCards == 0

  if self.lootLedgerMembersHeader then
    self.lootLedgerMembersHeader:SetText(membersHeaderText)
  end
  if self.lootLedgerMembersText then
    self.lootLedgerMembersText:SetText(membersInfoText)
    self.lootLedgerMembersText:SetShown(TrimText(membersInfoText) ~= "")
  end
  if self.lootLedgerManageLinksBtn then
    self.lootLedgerManageLinksBtn:SetShown(selectedRow ~= nil)
    self.lootLedgerManageLinksBtn:SetText("Manage Linked Characters")
    if self.lootLedgerManageLinksBtn.SetBackdropColor then
      if showLinkManagement then
        self.lootLedgerManageLinksBtn:SetBackdropColor(0.08, 0.20, 0.34, 1.00)
      else
        self.lootLedgerManageLinksBtn:SetBackdropColor(0.055, 0.12, 0.22, 0.98)
      end
    end
  end
  if self.lootLedgerManualToggleBtn then
    self.lootLedgerManualToggleBtn:SetShown(selectedRow ~= nil)
    self.lootLedgerManualToggleBtn:SetText(showManualAdjustment and "Hide Manual Adjustment" or "Add Manual Adjustment")
    if self.lootLedgerManualToggleBtn.SetBackdropColor then
      if showManualAdjustment then
        self.lootLedgerManualToggleBtn:SetBackdropColor(0.08, 0.20, 0.34, 1.00)
      else
        self.lootLedgerManualToggleBtn:SetBackdropColor(0.055, 0.12, 0.22, 0.98)
      end
    end
  end

  self.lootLedgerMembersRows = EnsureLootLedgerMemberRows(self.lootLedgerMembersRows, self.lootLedgerMembersRowsFrame, math.max(1, #memberCards))
  local memberCardWidth = rightWidth
  local memberNameWidth = math.max(160, memberCardWidth - 112)
  for index = 1, #self.lootLedgerMembersRows do
    local rowFrame = self.lootLedgerMembersRows[index]
    local memberRow = memberCards[index]
    if memberRow then
      local memberTextR, memberTextG, memberTextB, memberTextA = GetClassColorForRow(memberRow)
      local roleLabel = NormalizeLootLedgerRoleLocal(memberRow.mainAltRole) == "ALT" and "ALT" or "MAIN"
      if selectedRole == "ALT" and memberRow.character == selectedCharacter then
        roleLabel = roleLabel .. " | CURRENT"
      end
      local classText = TrimText(memberRow.className)
      local specText = TrimText(memberRow.specName)
      if type(GetEnglishClassAndSpec) == "function" then
        classText, specText = GetEnglishClassAndSpec(
          memberRow.classFile,
          memberRow.specID,
          classText,
          specText,
          memberRow.specIcon
        )
      end
      local specLine = specText
      if classText ~= "" and classText ~= specText then
        specLine = specLine .. " | " .. classText
      end

      rowFrame:ClearAllPoints()
      rowFrame:SetPoint("TOPLEFT", 0, -((index - 1) * 50))
      rowFrame:SetSize(memberCardWidth, 44)
      rowFrame:Show()

      if rowFrame.__bg then
        if (index % 2) == 0 then
          rowFrame.__bg:SetVertexColor(0.07, 0.06, 0.09, 0.40)
        else
          rowFrame.__bg:SetVertexColor(0.05, 0.045, 0.065, 0.36)
        end
      end
      if rowFrame.SetBackdropColor then
        rowFrame:SetBackdropColor(0.015, 0.018, 0.028, 0.72)
      end
      if rowFrame.SetBackdropBorderColor then
        rowFrame:SetBackdropBorderColor(0.24, 0.27, 0.34, 0.44)
      end
      if rowFrame.__accent then
        rowFrame.__accent:SetVertexColor(memberTextR, memberTextG, memberTextB, 0.70)
      end
      if rowFrame.__icon then
        ApplyLootLedgerTextureIcon(rowFrame.__icon, GetLootLedgerHeaderIconData(memberRow))
      end
      if rowFrame.__nameText then
        rowFrame.__nameText:SetWidth(memberNameWidth)
        rowFrame.__nameText:SetText(tostring(memberRow.character or "?"))
        rowFrame.__nameText:SetTextColor(memberTextR, memberTextG, memberTextB, memberTextA)
      end
      if rowFrame.__roleText then
        rowFrame.__roleText:SetWidth(76)
        rowFrame.__roleText:SetText(roleLabel)
        if roleLabel:find("ALT", 1, true) then
          rowFrame.__roleText:SetTextColor(0.92, 0.77, 0.28, 1)
        else
          rowFrame.__roleText:SetTextColor(0.46, 0.88, 0.62, 1)
        end
      end
      if rowFrame.__specText then
        local ownPoints = NormalizeLootLedgerDisplayPoints(tonumber(memberRow.ownTotalPoints) or tonumber(memberRow.totalPoints))
        rowFrame.__specText:SetWidth(memberCardWidth - 64)
        rowFrame.__specText:SetText(string.format(
          "%s | %d sessions | %d items | %d own points",
          specLine ~= "" and specLine or "Unknown Specialization",
          tonumber(memberRow.sessionCount) or 0,
          tonumber(memberRow.itemCount) or 0,
          ownPoints
        ))
        rowFrame.__specText:SetTextColor(0.80, 0.80, 0.86, 1)
      end
      if rowFrame.__statsText then
        rowFrame.__statsText:SetText("")
        rowFrame.__statsText:Hide()
      end
    else
      rowFrame:Hide()
    end
  end
  self.lootLedgerMembersRowsHeight = (#memberCards > 0) and ((((#memberCards) - 1) * 50) + 44) or 0

  if self.lootLedgerCharacterNoteEdit and (GetCurrentKeyBoardFocus == nil or GetCurrentKeyBoardFocus() ~= self.lootLedgerCharacterNoteEdit) then
    self.lootLedgerCharacterNoteEdit:SetText(selectedRow and TrimText(selectedRow.note) or "")
  end

  if self.lootLedgerRoleDropdown then
    if self.lootLedgerRoleDropdown.SetMenuBuilder then
      self.lootLedgerRoleDropdown:SetMenuBuilder(function(control)
        local currentValue = NormalizeLootLedgerRoleLocal((control and control.GetSelectedValue and control:GetSelectedValue()) or selectedRole)
        return {
          width = 140,
          entries = {
            {
              text = "Main",
              checked = currentValue == "MAIN",
              func = function()
                control:SetSelectedValue("MAIN")
                control:SetText("Main")
                self.__lootLedgerPendingRole = "MAIN"
                self.__lootLedgerPendingRoleCharacter = selectedCharacter
                RequestLootListRefresh(self)
              end,
            },
            {
              text = "Alt",
              checked = currentValue == "ALT",
              func = function()
                control:SetSelectedValue("ALT")
                control:SetText("Alt")
                self.__lootLedgerPendingRole = "ALT"
                self.__lootLedgerPendingRoleCharacter = selectedCharacter
                RequestLootListRefresh(self)
              end,
            },
          },
        }
      end)
      self.lootLedgerRoleDropdown:SetSelectedValue(selectedRole)
      self.lootLedgerRoleDropdown:SetText(selectedRole == "ALT" and "Alt" or "Main")
    elseif self.lootLedgerRoleDropdown.SetText then
      self.lootLedgerRoleDropdown:SetText(selectedRole == "ALT" and "Alt" or "Main")
    end
    if self.lootLedgerRoleDropdown.Enable then
      if access.canEditMainAlt and selectedCharacter then
        self.lootLedgerRoleDropdown:Enable()
      else
        self.lootLedgerRoleDropdown:Disable()
      end
    end
  end

  if self.lootLedgerSummaryDropdown then
    if self.lootLedgerSummaryDropdown.SetMenuBuilder then
      self.lootLedgerSummaryDropdown:SetMenuBuilder(function(control)
        local entries = {}
        local candidateKeys = {}
        for candidateKey, candidate in pairs(allCharactersByKey or {}) do
          if candidate.character ~= selectedCharacter and NormalizeLootLedgerRoleLocal(candidate.mainAltRole) == "MAIN" then
            candidateKeys[#candidateKeys + 1] = candidateKey
          end
        end
        table.sort(candidateKeys, function(a, b)
          return string.lower(tostring(a or "")) < string.lower(tostring(b or ""))
        end)
        for _, candidateKey in ipairs(candidateKeys) do
          local candidate = allCharactersByKey[candidateKey]
          if candidate then
            local entryText = BuildLootLedgerMainDropdownText(candidate)
            entries[#entries + 1] = {
              text = entryText,
              searchText = string.format(
                "%s %s %s",
                tostring(candidate.character or ""),
                tostring(candidate.specName or ""),
                tostring(candidate.className or "")
              ),
              checked = string.lower(tostring(candidate.character or "")) == string.lower(summaryTarget),
              func = function()
                control:SetSelectedValue(candidate.character)
                control:SetText(entryText)
              end,
            }
          end
        end
        if #entries == 0 then
          entries[1] = {
            text = "No Main characters available",
            disabled = true,
            notCheckable = true,
          }
        end
        return {
          width = math.max(320, math.floor((self.lootListRightBg and self.lootListRightBg:GetWidth() or 620) - 250)),
          entries = entries,
          enableSearch = true,
          searchPlaceholder = "Search Character-Realm",
        }
      end)
      if selectedRole ~= "ALT" then
        self.lootLedgerSummaryDropdown:SetSelectedValue(nil)
        self.lootLedgerSummaryDropdown:SetText("(mains cannot be attached)")
      elseif summaryTarget ~= "" and allCharactersByKey[summaryTarget] then
        local targetRow = allCharactersByKey[summaryTarget]
        self.lootLedgerSummaryDropdown:SetSelectedValue(summaryTarget)
        self.lootLedgerSummaryDropdown:SetText(BuildLootLedgerMainDropdownText(targetRow))
      else
        self.lootLedgerSummaryDropdown:SetSelectedValue(nil)
        self.lootLedgerSummaryDropdown:SetText(selectedCharacter and "(select main)" or "(select a character first)")
      end
    elseif self.lootLedgerSummaryDropdown.SetText then
      if selectedRole ~= "ALT" then
        self.lootLedgerSummaryDropdown:SetText("(mains cannot be attached)")
      else
        self.lootLedgerSummaryDropdown:SetText(summaryTarget)
      end
    end
    if self.lootLedgerSummaryDropdown.Enable then
      if access.canEditMainAlt and selectedCharacter and selectedRole == "ALT" then
        self.lootLedgerSummaryDropdown:Enable()
      else
        self.lootLedgerSummaryDropdown:Disable()
      end
    end
  end

  if self.lootLedgerCharacterEdit and (GetCurrentKeyBoardFocus == nil or GetCurrentKeyBoardFocus() ~= self.lootLedgerCharacterEdit) then
    self.lootLedgerCharacterEdit:SetText(selectedCharacter or "")
  end
  if self.lootLedgerCharacterNoteEdit and self.lootLedgerCharacterNoteEdit.SetEnabled then
    self.lootLedgerCharacterNoteEdit:SetEnabled(access.canEditNotes and selectedCharacter ~= nil)
  end
  if self.lootLedgerAddEntryBtn and self.lootLedgerAddEntryBtn.Enable then
    if selectedCharacter and access.canEditManualPoints then
      self.lootLedgerAddEntryBtn:Enable()
    else
      self.lootLedgerAddEntryBtn:Disable()
    end
  end
  local detailSelectionScope = tostring(selectedType or "") .. ":" .. tostring(selectedKey or selectedCharacter or "")
  if self.__lootLedgerHistorySelectionScope ~= detailSelectionScope then
    self.__lootLedgerHistorySelectionScope = detailSelectionScope
    self.selectedLootLedgerHistoryEntryId = nil
    self.selectedLootLedgerHistoryOwner = nil
  end
  if self.lootLedgerDeleteEntryBtn and self.lootLedgerDeleteEntryBtn.Enable then
    if access.canEditManualPoints and TrimText(self.selectedLootLedgerHistoryEntryId) ~= "" and TrimText(self.selectedLootLedgerHistoryOwner) ~= "" then
      self.lootLedgerDeleteEntryBtn:Enable()
    else
      self.lootLedgerDeleteEntryBtn:Disable()
    end
  end
  if self.lootLedgerDeleteCharacterBtn and self.lootLedgerDeleteCharacterBtn.Enable then
    if selectedCharacter and access.canDeleteLootListCharacter then
      self.lootLedgerDeleteCharacterBtn:Enable()
    else
      self.lootLedgerDeleteCharacterBtn:Disable()
    end
  end
  if self.lootLedgerSummaryLinkBtn and self.lootLedgerSummaryLinkBtn.Enable then
    if selectedCharacter and access.canEditMainAlt then
      self.lootLedgerSummaryLinkBtn:Enable()
    else
      self.lootLedgerSummaryLinkBtn:Disable()
    end
  end
  if self.lootLedgerSummaryClearBtn and self.lootLedgerSummaryClearBtn.Enable then
    if selectedCharacter and access.canEditMainAlt then
      self.lootLedgerSummaryClearBtn:Enable()
    else
      self.lootLedgerSummaryClearBtn:Disable()
    end
  end
  if self.lootLedgerAddGroupBtn and self.lootLedgerAddGroupBtn.Enable then
    if access.canEditLootList then self.lootLedgerAddGroupBtn:Enable() else self.lootLedgerAddGroupBtn:Disable() end
  end
  if self.lootLedgerDeleteGroupBtn and self.lootLedgerDeleteGroupBtn.Enable then
    if access.canEditLootList and tostring(self.selectedLootLedgerType or "") == "group" then
      self.lootLedgerDeleteGroupBtn:Enable()
    else
      self.lootLedgerDeleteGroupBtn:Disable()
    end
  end
  if self.lootLedgerSeedTestBtn then
    local showSeedTestBtn = TrimText(profileName) == "Simulation"
    self.lootLedgerSeedTestBtn:SetShown(showSeedTestBtn)
    if self.lootLedgerSeedTestBtn.Enable then
      if showSeedTestBtn and access.canEditLootList then
        self.lootLedgerSeedTestBtn:Enable()
      else
        self.lootLedgerSeedTestBtn:Disable()
      end
    end
    if self.UpdateLootListToolbarLayout then
      self:UpdateLootListToolbarLayout()
    end
  end

  local historyCacheKey = BuildLootLedgerHistoryCacheKey(profile, profileName, selectedRow)
  local historyEntries = self.__lootLedgerHistoryEntries
  if historyCacheKey == "" or self.__lootLedgerHistoryCacheKey ~= historyCacheKey or type(historyEntries) ~= "table" then
    historyEntries = BuildLootLedgerHistoryEntries(profile, selectedRow)
    self.__lootLedgerHistoryCacheKey = historyCacheKey
    self.__lootLedgerHistoryEntries = historyEntries
  end
  local function IsManualHistoryEntry(entry)
    if type(entry) ~= "table" then
      return false
    end
    if entry.isManual == true then
      return true
    end
    return TrimText(entry.itemLink) == ""
      and tonumber(entry.itemID) == nil
      and TrimText(entry.itemIcon) == "Interface\\Icons\\INV_Misc_Note_06"
  end
  local function FormatHistoryRollText(entry)
    if type(entry) ~= "table" then
      return ""
    end
    local label = TrimText(entry.rollOptionLabel)
    if label == "" then
      label = FormatLootLedgerPointBehaviorLabel(entry.pointBehavior)
    end
    if label == "" then
      return ""
    end
    local rollValue = tonumber(entry.rollValue)
    if rollValue then
      return string.format("%s (%d)", label, math.floor(rollValue + 0.5))
    end
    return label
  end

  local selectedHistoryEntryId = TrimText(self.selectedLootLedgerHistoryEntryId)
  local selectedHistoryOwner = TrimText(self.selectedLootLedgerHistoryOwner)
  local historyPageKey = string.lower(tostring(profileName or "") .. "\031" .. tostring(selectedRow and selectedRow.key or ""))
  if self.__lootLedgerHistoryPageKey ~= historyPageKey then
    self.__lootLedgerHistoryPageKey = historyPageKey
    self.__lootLedgerHistoryPage = 1
  end
  local historyPageCount = math.max(1, math.ceil(#historyEntries / LOOT_LEDGER_HISTORY_PAGE_SIZE))
  local historyPage = math.floor(tonumber(self.__lootLedgerHistoryPage) or 1)
  if historyPage < 1 then
    historyPage = 1
  elseif historyPage > historyPageCount then
    historyPage = historyPageCount
  end
  self.__lootLedgerHistoryPage = historyPage
  self.__lootLedgerHistoryPagerVisible = historyPageCount > 1

  local pageFirstIndex = ((historyPage - 1) * LOOT_LEDGER_HISTORY_PAGE_SIZE) + 1
  local pageLastIndex = math.min(#historyEntries, pageFirstIndex + LOOT_LEDGER_HISTORY_PAGE_SIZE - 1)
  local pageHistoryEntries = {}
  for index = pageFirstIndex, pageLastIndex do
    pageHistoryEntries[#pageHistoryEntries + 1] = historyEntries[index]
  end

  if self.lootLedgerHistoryPageText then
    self.lootLedgerHistoryPageText:SetText(string.format("Page %d / %d", historyPage, historyPageCount))
  end
  if self.lootLedgerHistoryPrevBtn then
    self.lootLedgerHistoryPrevBtn:SetShown(historyPageCount > 1)
    if historyPage > 1 then
      self.lootLedgerHistoryPrevBtn:Enable()
    else
      self.lootLedgerHistoryPrevBtn:Disable()
    end
  end
  if self.lootLedgerHistoryNextBtn then
    self.lootLedgerHistoryNextBtn:SetShown(historyPageCount > 1)
    if historyPage < historyPageCount then
      self.lootLedgerHistoryNextBtn:Enable()
    else
      self.lootLedgerHistoryNextBtn:Disable()
    end
  end

  local selectedHistoryStillExists = false
  for _, entry in ipairs(historyEntries) do
    if TrimText(entry.entryId) ~= "" and TrimText(entry.entryId) == selectedHistoryEntryId and TrimText(entry.owner) == selectedHistoryOwner then
      selectedHistoryStillExists = true
      break
    end
  end
  local selectedManualHistoryEntry = false
  self.lootLedgerHistoryRows = EnsureLootLedgerHistoryRows(self.lootLedgerHistoryRows, self.lootLedgerHistoryRowsFrame, math.max(1, #pageHistoryEntries))
  local historyItemWidth = math.max(170, rightWidth - 250)
  local historyReceivedX = math.max(186, rightWidth - 236)
  local historyPointsX = math.max(352, rightWidth - 74)
  for index = 1, #self.lootLedgerHistoryRows do
    local rowFrame = self.lootLedgerHistoryRows[index]
    local entry = pageHistoryEntries[index]
    if entry then
      local rowName = TrimText(entry.itemName)
      if rowName == "" then
        local itemLink = TrimText(entry.itemLink)
        rowName = TrimText(itemLink:match("%[(.-)%]") or itemLink)
      end
      if rowName == "" then
        rowName = "?"
      end
      if tonumber(entry.itemLevel) then
        rowName = string.format("%s (iLvl %d)", rowName, tonumber(entry.itemLevel))
      end
      local rollText = FormatHistoryRollText(entry)
      if rollText ~= "" then
        rowName = string.format("%s | %s", rowName, rollText)
      end
      if tonumber(selectedRow and selectedRow.summaryMemberCount) and tonumber(selectedRow.summaryMemberCount) > 1 then
        rowName = tostring(entry.owner or "?") .. " - " .. rowName
      end
      local isManualEntry = IsManualHistoryEntry(entry)
      if isManualEntry and TrimText(entry.note) ~= "" then
        rowName = rowName .. " | " .. tostring(entry.note)
      end
      if isManualEntry and TrimText(entry.grantedBy) ~= "" then
        rowName = rowName .. " | by " .. tostring(entry.grantedBy)
      end

      rowFrame:ClearAllPoints()
      rowFrame:SetPoint("TOPLEFT", 0, -((index - 1) * 26))
      rowFrame:SetSize(rightWidth, 24)
      rowFrame:Show()

      if rowFrame.__bg then
        local isSelectedHistory = TrimText(entry.entryId) ~= "" and TrimText(entry.entryId) == selectedHistoryEntryId and TrimText(entry.owner) == selectedHistoryOwner
        if isSelectedHistory then
          selectedManualHistoryEntry = isManualEntry
          rowFrame.__bg:SetVertexColor(0.26, 0.18, 0.06, 0.88)
        elseif (index % 2) == 0 then
          rowFrame.__bg:SetVertexColor(0.10, 0.06, 0.08, 0.76)
        else
          rowFrame.__bg:SetVertexColor(0.07, 0.04, 0.05, 0.72)
        end
      end
      if rowFrame.__icon then
        rowFrame.__icon:SetTexture(ResolveLootLedgerEntryIcon(entry))
        rowFrame.__icon:SetTexCoord(0, 1, 0, 1)
      end
      if rowFrame.__nameText then
        rowFrame.__nameText:ClearAllPoints()
        rowFrame.__nameText:SetPoint("LEFT", rowFrame.__icon, "RIGHT", 8, 0)
        rowFrame.__nameText:SetWidth(historyItemWidth - 26)
        rowFrame.__nameText:SetText(rowName)
        local rollColor = type(entry.rollOptionColor) == "table" and entry.rollOptionColor or nil
        local quality = tonumber(entry.itemQuality)
        if rollColor and tonumber(rollColor[1]) and tonumber(rollColor[2]) and tonumber(rollColor[3]) then
          rowFrame.__nameText:SetTextColor(tonumber(rollColor[1]), tonumber(rollColor[2]), tonumber(rollColor[3]), 1)
        elseif quality and type(GetItemQualityColor) == "function" then
          local qualityR, qualityG, qualityB = GetItemQualityColor(quality)
          rowFrame.__nameText:SetTextColor(tonumber(qualityR) or 1, tonumber(qualityG) or 1, tonumber(qualityB) or 1, 1)
        else
          rowFrame.__nameText:SetTextColor(1, 1, 1, 1)
        end
      end
      if rowFrame.__receivedText then
        rowFrame.__receivedText:ClearAllPoints()
        rowFrame.__receivedText:SetPoint("LEFT", historyReceivedX, 0)
        rowFrame.__receivedText:SetText(FormatDateTime(entry.awardedAt))
        rowFrame.__receivedText:SetTextColor(1, 1, 1, 1)
      end
      if rowFrame.__pointsText then
        rowFrame.__pointsText:ClearAllPoints()
        rowFrame.__pointsText:SetPoint("LEFT", historyPointsX, 0)
        rowFrame.__pointsText:SetText(tostring(NormalizeLootLedgerDisplayPoints(entry.points)))
        rowFrame.__pointsText:SetTextColor(1, 1, 1, 1)
      end
      rowFrame:EnableMouse(access.canEditManualPoints and IsManualHistoryEntry(entry))
      rowFrame:SetScript("OnClick", function()
        if not access.canEditManualPoints or not IsManualHistoryEntry(entry) then
          return
        end
        self.selectedLootLedgerHistoryEntryId = TrimText(entry.entryId)
        self.selectedLootLedgerHistoryOwner = TrimText(entry.owner)
        RequestLootListRefresh(self)
      end)
    else
      rowFrame:EnableMouse(false)
      rowFrame:SetScript("OnClick", nil)
      rowFrame:Hide()
    end
  end
  if (not selectedHistoryStillExists) and selectedHistoryEntryId ~= "" then
    self.selectedLootLedgerHistoryEntryId = nil
    self.selectedLootLedgerHistoryOwner = nil
  end
  self.__lootLedgerHasSelectedManualEntry = selectedManualHistoryEntry
  if self.lootLedgerDeleteEntryBtn then
    local canDeleteManualEntry = showManualAdjustment
      and selectedManualHistoryEntry
      and access.canEditManualPoints
    self.lootLedgerDeleteEntryBtn:SetShown(canDeleteManualEntry)
    if self.lootLedgerDeleteEntryBtn.Enable then
      if canDeleteManualEntry then
        self.lootLedgerDeleteEntryBtn:Enable()
      else
        self.lootLedgerDeleteEntryBtn:Disable()
      end
    end
  end
  self.lootLedgerHistoryRowsHeight = math.max(1, #pageHistoryEntries * 26)

  if not selectedRow then
    self.lootLedgerHistoryText:SetText("No Loot List entry selected.")
  elseif #historyEntries == 0 then
    self.lootLedgerHistoryText:SetText("No awarded items recorded yet for this character.")
  elseif selectedManualHistoryEntry then
    self.lootLedgerHistoryText:SetText("Manual adjustment selected. Use Delete Selected Adjustment below to remove it.")
  elseif historyPageCount > 1 then
    self.lootLedgerHistoryText:SetText(string.format(
      "Showing entries %d-%d of %d.",
      pageFirstIndex,
      pageLastIndex,
      #historyEntries
    ))
  else
    self.lootLedgerHistoryText:SetText("")
  end

  if showRightPane then
    UpdateLootLedgerDetailLayout(self)
    -- The embedded detail pane can be re-laid out after its first render.
    -- Reapply the identity color so split and popout modes match exactly.
    if self.lootLedgerSelectedLabel then
      self.lootLedgerSelectedLabel:SetTextColor(textR, textG, textB, textA)
    end
    if self.lootLedgerTotalLabel then
      self.lootLedgerTotalLabel:SetTextColor(textR, textG, textB, textA)
    end
  end
  if self.UpdateScrollLayout then
    self:UpdateScrollLayout(true)
  end
end

INTERNAL_API.LIDCOUNCIL_LootListRendering_Impl = {
  GetClassColorForRow = GetClassColorForRow,
  BuildSpecLabel = BuildSpecLabel,
  GetLootLedgerHeaderIconData = GetLootLedgerHeaderIconData,
  EnsureLootLedgerRowFrames = EnsureLootLedgerRowFrames,
  GetSelectedLootLedgerRow = GetSelectedLootLedgerRow,
  EnsureLootLedgerHistoryRows = EnsureLootLedgerHistoryRows,
  EnsureLootLedgerMemberRows = EnsureLootLedgerMemberRows,
  ResolveLootLedgerEntryIcon = ResolveLootLedgerEntryIcon,
  BuildLootLedgerHistoryEntries = BuildLootLedgerHistoryEntries,
  ApplyLootLedgerTextureIcon = ApplyLootLedgerTextureIcon,
  UpdateLootLedgerDetailLayout = UpdateLootLedgerDetailLayout,
  RefreshLootListPage = RefreshLootListPage,
}
