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 RequireApi = shared.RequireApi
local BindMouseWheelScroll = shared.BindMouseWheelScroll
local RootDB = shared.RootDB
local ApplyFrameSkin = shared.ApplyFrameSkin
local MakeYellowSubHeader = shared.MakeYellowSubHeader
local GetCharacterKey = shared.GetCharacterKey
local GetEnglishClassAndSpec = RequireApi("LIDCOUNCIL_GetEnglishClassAndSpec", nil)
local GetEnabledLootProfileName = shared.GetEnabledLootProfileName or RequireApi("LIDCOUNCIL_GetEnabledLootProfileName", _G.LIDCOUNCIL_GetEnabledLootProfileName)
local GetLootProfile = shared.GetLootProfile
local GetPrimaryLootProfileName = shared.GetPrimaryLootProfileName
local GetLootProfileNames = shared.GetLootProfileNames
local IsLootProfileVisibleInEditor = shared.IsLootProfileVisibleInEditor or function(_, profileName)
  return profileName ~= nil and profileName ~= ""
end
local GetLootProfileAccessInfo = shared.GetLootProfileAccessInfo
local GetLootProfilePermissionPolicyRoleState = shared.GetLootProfilePermissionPolicyRoleState
local SetCurrentLootProfile = shared.SetCurrentLootProfile
local CreateLootProfile = shared.CreateLootProfile
local DeleteLootProfile = shared.DeleteLootProfile
local CopyLootProfile = shared.CopyLootProfile
local SetLootProfileEnabled = shared.SetLootProfileEnabled
local SetLootProfileRaid = shared.SetLootProfileRaid
local AddLootRollOption = shared.AddLootRollOption
local UpdateLootRollOption = shared.UpdateLootRollOption
local RemoveLootRollOption = shared.RemoveLootRollOption
local UpdateLootPointMode = shared.UpdateLootPointMode
local UpdateLootLidTableRow = shared.UpdateLootLidTableRow
local AddLootPointRule = shared.AddLootPointRule
local RemoveLootPointRule = shared.RemoveLootPointRule
local StartLootSession = shared.StartLootSession
local StopLootSession = shared.StopLootSession
local GetActiveLootSession = shared.GetActiveLootSession
local AddLootLedgerEntry = shared.AddLootLedgerEntry
local GetLootLedgerCharacters = shared.GetLootLedgerCharacters
local ResolveOptionalApiFunction = shared.ResolveOptionalApiFunction
local NormalizeCharacterKey = shared.NormalizeCharacterKey or ResolveOptionalApiFunction("LIDCOUNCIL_NormalizeCharacterKey")
local CreateCustomDropdownControl = shared.CreateCustomDropdownControl
local TrimText = shared.TrimText
local FormatDateTime = shared.FormatDateTime
local FormatDuration = shared.FormatDuration
local CreateSimpleEditBox = shared.CreateSimpleEditBox
local SetListButtonSelected = shared.SetListButtonSelected
local SetTextListButtonTextColor = shared.SetTextListButtonTextColor
local EnsureTextListButtons = shared.EnsureTextListButtons
local CreateSectionShell = shared.CreateSectionShell
local ClampLayoutValue = shared.ClampLayoutValue
local GetResponsiveSectionLayout = shared.GetResponsiveSectionLayout
local SetControlWidth = shared.SetControlWidth
local GetFontStringWidth = shared.GetFontStringWidth
local CreateSectionDivider = shared.CreateSectionDivider
local FlowLayoutControls = shared.FlowLayoutControls
local LayoutRollOptionRow = shared.LayoutRollOptionRow
local LayoutLidTableEditorRow = shared.LayoutLidTableEditorRow
local BuildRollOptionsText = shared.BuildRollOptionsText
local DEFAULT_ROLL_OPTION_ICON_CHOICES = shared.DEFAULT_ROLL_OPTION_ICON_CHOICES
local ResolveTextureAsset = shared.ResolveTextureAsset
local ResolveDefaultRollOptionIcon = shared.ResolveDefaultRollOptionIcon
local ResolveRollOptionIcon = shared.ResolveRollOptionIcon
local GetRollOptionIconLabel = shared.GetRollOptionIconLabel
local EnsureRollOptionRows = shared.EnsureRollOptionRows
local EnsureLidTableEditorRows = shared.EnsureLidTableEditorRows
local ExtractItemID = shared.ExtractItemID
local ExtractItemLinkName = shared.ExtractItemLinkName
local FormatPointRuleItemLabel = shared.FormatPointRuleItemLabel
local FormatRaidLootItemLabel = shared.FormatRaidLootItemLabel
local LOOT_ITEM_MENU_PAGE_SIZE = shared.LOOT_ITEM_MENU_PAGE_SIZE
local NormalizeInstanceTuple = shared.NormalizeInstanceTuple
local NormalizeEncounterTuple = shared.NormalizeEncounterTuple
local NormalizeLootInfo = shared.NormalizeLootInfo
local EnsureEncounterJournalLoaded = shared.EnsureEncounterJournalLoaded
local CollectRaidEntries = shared.CollectRaidEntries
local CollectRaidLootEntries = shared.CollectRaidLootEntries
local FindRaidEntryByProfile = shared.FindRaidEntryByProfile
local FindRaidLootEntry = shared.FindRaidLootEntry
local EnsureLootLiveBoardMode = shared.EnsureLootLiveBoardMode
local ClampMenuPage = shared.ClampMenuPage
local GetSelectedValuePage = shared.GetSelectedValuePage
local NormalizeLootSessionSectionTargets = shared.NormalizeEditorLootSessionSections
local BuildLootSessionSectionRefreshTargets = shared.BuildEditorLootSessionSectionTargets
local RequestEditorWorkflowRefresh = shared.RequestEditorWorkflowRefresh
local RequestLootSessionSectionRefresh = shared.RequestEditorLootSessionSectionRefresh

if type(NormalizeCharacterKey) ~= "function" then
  NormalizeCharacterKey = function(value)
    value = tostring(value or "")
    value = value:gsub("^%s+", ""):gsub("%s+$", "")
    value = value:gsub("%s*%-%s*", "-")
    value = value:gsub("%s+", "")
    return value
  end
end

local ACTIVATE_PROFILE_REQUIRED_TEXT = "Please go to Profile and activate one Profile first"
local NO_ACTIVE_PROFILE_CURRENT_TEXT = "Current Profile: No profile activated :("
local NO_ACTIVE_PROFILE_TEXT_COLOR = { 1.00, 0.35, 0.25, 1.00 }

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 function GetSessionContextProfileName()
  local root = RootDB()
  local enabledProfileName = TrimText(GetEnabledLootProfileName() or "")
  if enabledProfileName ~= "" and IsLootProfileVisibleInEditor(root, enabledProfileName) then
    return enabledProfileName
  end
  return nil
end

local EMPTY_SESSION_CONTEXT_PROFILE = {
  settings = {},
  sessions = {},
  lootLedger = {},
  lootLedgerMeta = {},
}

local EMPTY_SESSION_CONTEXT_ACCESS = {
  canStartSession = false,
  canManageSession = false,
  canOpenLiveBoard = false,
  canUseVoting = false,
  canAssignLoot = false,
}

local function ResolveSessionContextProfile()
  local root = RootDB()
  local profileName = TrimText(GetSessionContextProfileName())
  if profileName == "" or not root.profiles or type(root.profiles[profileName]) ~= "table" then
    return EMPTY_SESSION_CONTEXT_PROFILE, nil
  end
  return GetLootProfile(profileName)
end

local function ResolveSessionContextAccess(profileName)
  if TrimText(profileName) == "" then
    return EMPTY_SESSION_CONTEXT_ACCESS
  end
  return GetLootProfileAccessInfo(profileName)
end

local function ResolveRequiredSessionProfileName(actionLabel)
  local _, profileName = ResolveSessionContextProfile()
  if TrimText(profileName) ~= "" then
    return profileName
  end
  local message = ACTIVATE_PROFILE_REQUIRED_TEXT
  local printFn = ResolveOptionalApiFunction("LIDCOUNCIL_Print")
  if type(printFn) == "function" then
    printFn(message)
  end
  return nil
end

local function IsCombatLocked()
  return type(InCombatLockdown) == "function" and InCombatLockdown() and true or false
end
local EnsureLootProfileGroups = shared.EnsureLootProfileGroups
local FindLootProfileGroupIndex = shared.FindLootProfileGroupIndex
local RemoveLootProfileFromGroups = shared.RemoveLootProfileFromGroups
local ToggleLootProfileGroupCollapsed = shared.ToggleLootProfileGroupCollapsed
local GetLootProfileGroupName = shared.GetLootProfileGroupName
local BuildLootProfileNavRows = shared.BuildLootProfileNavRows
local BuildPointRulesText = shared.BuildPointRulesText
local ResolvePointMode = shared.ResolvePointMode
local GetLidTableRows = shared.GetLidTableRows
local BuildLidTableSummaryText = shared.BuildLidTableSummaryText
local POINT_MODE_CHOICES = shared.POINT_MODE_CHOICES
local GetSelectedProfileName = shared.GetSelectedProfileName
local RefreshCurrentSessionView
local RefreshCurrentSessionPriorityTelemetry
local RefreshCurrentSessionRosterIfChanged
local LayoutCurrentSessionSection
local BuildSessionHistoryRowsData
local GetPagedSessionHistoryRows
local RefreshSessionHistoryRows
local LayoutSessionHistorySection
local RefreshSyncManagementView
local LayoutSyncManagementSection
local RefreshRoleSimulationView
local LayoutRoleSimulationSection
local RefreshAutoPassView
local LayoutAutoPassSection
local SIMULATION_ROLE_OPTIONS
local ROLE_SIM_RIGHTS_MATRIX

local function FormatLootProfileRoleLabel(role)
  local resolvedRole = string.upper(TrimText(role))
  if resolvedRole == "MASTER" then
    return "Master"
  end
  if resolvedRole == "COUNCIL" then
    return "Council Member"
  end
  if resolvedRole == "SESSION_HOST" then
    return "Session Host"
  end
  return "Raider"
end
local SESSION_CLASS_ICON_TEXTURE = "Interface\\GLUES\\CHARACTERCREATE\\UI-CHARACTERCREATE-CLASSES"
if type(NormalizeLootSessionSectionTargets) ~= "function" then
  NormalizeLootSessionSectionTargets = type(INTERNAL_API.LIDCOUNCIL_NormalizeEditorLootSessionSections_Impl) == "function"
    and INTERNAL_API.LIDCOUNCIL_NormalizeEditorLootSessionSections_Impl
    or function(sectionTargets)
      if type(sectionTargets) ~= "table" then
        return nil
      end
      local normalized = {}
      for sectionName, enabled in pairs(sectionTargets) do
        if enabled then
          local resolvedSection = string.upper(TrimText(sectionName))
          if resolvedSection == "AUTOPASS"
            or resolvedSection == "CURRENT"
            or resolvedSection == "HISTORY"
            or resolvedSection == "ROLESIM"
            or resolvedSection == "SYNCMGMT"
          then
            normalized[resolvedSection] = true
          end
        end
      end
      return next(normalized) ~= nil and normalized or nil
    end
end

if type(BuildLootSessionSectionRefreshTargets) ~= "function" then
  BuildLootSessionSectionRefreshTargets = type(INTERNAL_API.LIDCOUNCIL_BuildEditorLootSessionSectionTargets_Impl) == "function"
    and INTERNAL_API.LIDCOUNCIL_BuildEditorLootSessionSectionTargets_Impl
    or function(editor, sectionTargets)
      local normalizedTargets = NormalizeLootSessionSectionTargets(type(sectionTargets) == "table" and sectionTargets or nil)
      if normalizedTargets ~= nil then
        return normalizedTargets
      end

      local resolvedSection = string.upper(TrimText(sectionTargets))
      if resolvedSection == "AUTOPASS"
        or resolvedSection == "CURRENT"
        or resolvedSection == "HISTORY"
        or resolvedSection == "ROLESIM"
        or resolvedSection == "SYNCMGMT"
      then
        return {
          [resolvedSection] = true,
        }
      end

      local fallbackSection = string.upper(TrimText(type(editor) == "table" and editor.lootSessionSection or ""))
      if fallbackSection ~= "AUTOPASS"
        and fallbackSection ~= "CURRENT"
        and fallbackSection ~= "HISTORY"
        and fallbackSection ~= "ROLESIM"
        and fallbackSection ~= "SYNCMGMT"
      then
        fallbackSection = "CURRENT"
      end
      return {
        [fallbackSection] = true,
      }
    end
end

if type(RequestEditorWorkflowRefresh) ~= "function" then
  RequestEditorWorkflowRefresh = type(INTERNAL_API.LIDCOUNCIL_RequestEditorWorkflowRefresh_Impl) == "function"
    and INTERNAL_API.LIDCOUNCIL_RequestEditorWorkflowRefresh_Impl
    or function(editor, opts)
      if type(editor) ~= "table" then
        return false
      end
      if type(editor.RequestWorkflowRefresh) == "function" then
        local handled = editor.RequestWorkflowRefresh(opts)
        if handled then
          return true
        end
      end
      if type(editor.Refresh) == "function" then
        editor:Refresh()
        return true
      end
      return false
    end
end

if type(RequestLootSessionSectionRefresh) ~= "function" then
  RequestLootSessionSectionRefresh = function(editor, sectionTargets, refreshPages)
    if type(editor) == "table" and type(editor.RequestLootSessionSectionRefresh) == "function" then
      local handled = editor.RequestLootSessionSectionRefresh(sectionTargets, refreshPages)
      if handled then
        return true
      end
    end
    return RequestEditorWorkflowRefresh(editor, {
      refreshPages = refreshPages,
      lootSessionSections = BuildLootSessionSectionRefreshTargets(editor, sectionTargets),
    })
  end
end

local function BuildActiveLootSessionSectionRefreshTargets(editor, sectionOverride)
  return BuildLootSessionSectionRefreshTargets(
    editor,
    TrimText(sectionOverride) ~= "" and sectionOverride or (type(editor) == "table" and editor.lootSessionSection or "CURRENT")
  )
end

local function RequestSessionWorkflowRefresh(editor, refreshPages, sectionOverride)
  return RequestEditorWorkflowRefresh(editor, {
    refreshPages = refreshPages,
    lootSessionSections = BuildActiveLootSessionSectionRefreshTargets(editor, sectionOverride),
  })
end

local function GetRoleSimMatrixCellText(allowed)
  if allowed then
    return "|cff4adf6b✔|r"
  end
  return "|cffff5a5a✖|r"
end

GetRoleSimMatrixCellText = function(allowed)
  if allowed then
    return "|cff4adf6bOK|r"
  end
  return "|cffff5a5aX|r"
end

local function ResolveRoleSimMatrixValue(rowDef, roleState, staticKey)
  rowDef = type(rowDef) == "table" and rowDef or {}
  roleState = type(roleState) == "table" and roleState or {}

  if type(rowDef.permissionKey) == "string" and rowDef.permissionKey ~= "" then
    return roleState[rowDef.permissionKey] and true or false
  end

  if type(rowDef.permissionKeys) == "table" and #rowDef.permissionKeys > 0 then
    for _, permissionKey in ipairs(rowDef.permissionKeys) do
      if not roleState[permissionKey] then
        return false
      end
    end
    return true
  end

  return rowDef[staticKey] and true or false
end

local function GetSessionClassColor(classFile)
  local resolvedClassFile = TrimText(classFile)
  local colorTable = (type(CUSTOM_CLASS_COLORS) == "table" and CUSTOM_CLASS_COLORS[resolvedClassFile])
    or (type(RAID_CLASS_COLORS) == "table" and RAID_CLASS_COLORS[resolvedClassFile])
    or nil
  if colorTable then
    return tonumber(colorTable.r or colorTable[1]) or 0.82,
      tonumber(colorTable.g or colorTable[2]) or 0.82,
      tonumber(colorTable.b or colorTable[3]) or 0.86,
      1
  end
  return 0.82, 0.82, 0.86, 1
end

local function ResolveSessionDisplayInfo(profile, memberKey, member)
  local meta = type(profile) == "table" and type(profile.lootLedgerMeta) == "table" and profile.lootLedgerMeta[memberKey] or nil
  local classFile = TrimText(type(member) == "table" and member.classFile or (type(meta) == "table" and meta.classFile) or "")
  local className = TrimText(type(member) == "table" and member.className or (type(meta) == "table" and meta.className) or "")
  local specName = TrimText(type(member) == "table" and member.specName or (type(meta) == "table" and meta.specName) or "")
  local specIcon = TrimText(type(member) == "table" and member.specIcon or (type(meta) == "table" and meta.specIcon) or "")
  local specID = tonumber(type(member) == "table" and member.specID or (type(meta) == "table" and meta.specID))
  if type(GetEnglishClassAndSpec) == "function" then
    className, specName = GetEnglishClassAndSpec(classFile, specID, className, specName, specIcon)
  end
  return {
    className = className,
    classFile = classFile,
    specName = specName,
    specIcon = specIcon,
  }
end

local function ResolveSessionIconData(displayInfo)
  if type(displayInfo) ~= "table" then
    return nil
  end
  local specIcon = TrimText(displayInfo.specIcon)
  if specIcon ~= "" then
    return { texture = specIcon }
  end
  local classFile = TrimText(displayInfo.classFile)
  local coords = classFile ~= "" and type(CLASS_ICON_TCOORDS) == "table" and CLASS_ICON_TCOORDS[classFile] or nil
  if type(coords) == "table" then
    return {
      texture = SESSION_CLASS_ICON_TEXTURE,
      left = coords[1],
      right = coords[2],
      top = coords[3],
      bottom = coords[4],
    }
  end
  return nil
end

local function ApplySessionIcon(texture, iconData)
  if not texture then
    return
  end
  if type(iconData) ~= "table" or TrimText(iconData.texture) == "" then
    texture:SetTexture("Interface\\Icons\\INV_Misc_QuestionMark")
    texture:SetTexCoord(0, 1, 0, 1)
    return
  end
  texture:SetTexture(iconData.texture)
  if type(iconData.left) == "number" and type(iconData.right) == "number" and type(iconData.top) == "number" and type(iconData.bottom) == "number" then
    texture:SetTexCoord(iconData.left, iconData.right, iconData.top, iconData.bottom)
  else
    texture:SetTexCoord(0, 1, 0, 1)
  end
end

local function BuildCurrentSessionLiveRosterLookup(session)
  local rosterLookup = {}
  local function AddCharacter(characterKey)
    local resolvedKey = NormalizeCharacterKey(characterKey)
    if resolvedKey ~= "" then
      rosterLookup[string.lower(resolvedKey)] = true
    end
  end
  if type(session) == "table" then
    AddCharacter(session.host)
    for memberKey, member in pairs(session.members or {}) do
      if type(member) == "table" and string.upper(TrimText(member.status or "JOINED")) == "JOINED" then
        AddCharacter(memberKey)
      end
    end
  end
  return rosterLookup
end

local function ClassifyCurrentSessionLootSubdomainTier(subdomain, session)
  local resolvedSubdomain = string.lower(TrimText(subdomain))
  if resolvedSubdomain == "" then
    return ""
  end
  if resolvedSubdomain == "lls" or resolvedSubdomain:find("^llg:", 1, false) then
    return "live"
  end
  if resolvedSubdomain:find("^lre:", 1, false)
    or resolvedSubdomain:find("^lve:", 1, false)
    or resolvedSubdomain == "lrsr"
    or resolvedSubdomain == "lrsv"
  then
    return "stats"
  end
  if resolvedSubdomain:find("^llr:", 1, false) or resolvedSubdomain:find("^lmr:", 1, false) then
    local identity = NormalizeCharacterKey((TrimText(subdomain):match("^[^:]+:(.+)$")) or "")
    if identity ~= "" then
      local rosterLookup = BuildCurrentSessionLiveRosterLookup(session)
      if rosterLookup[string.lower(identity)] then
        return "live"
      end
    end
    return "archive"
  end
  return "archive"
end

local function BuildCurrentSessionLiveLootChecksum(profileName, session)
  local getSubchecksumManifest = ResolveOptionalApiFunction("LIDCOUNCIL_GetLootProfileSubchecksumManifest")
  local calculateStableChecksum = ResolveOptionalApiFunction("LIDCOUNCIL_CalculateStableChecksum")
  if type(getSubchecksumManifest) ~= "function" or type(calculateStableChecksum) ~= "function" then
    return ""
  end
  local manifest = getSubchecksumManifest(profileName, { "loot" })
  if type(manifest) ~= "table" then
    return ""
  end
  local byDomain = type(manifest.byDomain) == "table" and manifest.byDomain or {}
  local lootState = type(byDomain.loot) == "table" and byDomain.loot or {}
  local subchecksums = type(lootState.subchecksums) == "table" and lootState.subchecksums or {}
  local liveChecksums = {}
  for subdomain, checksum in pairs(subchecksums) do
    local resolvedSubdomain = TrimText(subdomain)
    if resolvedSubdomain ~= "" and ClassifyCurrentSessionLootSubdomainTier(resolvedSubdomain, session) == "live" then
      liveChecksums[resolvedSubdomain] = TrimText(checksum)
    end
  end
  if next(liveChecksums) == nil then
    return ""
  end
  return TrimText(calculateStableChecksum(liveChecksums))
end

local function FindCurrentSessionSyncCandidate(memberKey)
  local getCandidates = ResolveOptionalApiFunction("LIDCOUNCIL_GetActiveProfileSyncCandidates")
  local resolvedMemberKey = NormalizeCharacterKey(memberKey)
  if resolvedMemberKey == "" or type(getCandidates) ~= "function" then
    return nil
  end
  for _, candidate in ipairs(getCandidates() or {}) do
    if NormalizeCharacterKey(type(candidate) == "table" and candidate.memberKey or "") == resolvedMemberKey then
      return candidate
    end
  end
  return nil
end

local ResolveCandidateCurrentSessionSyncState

local function BuildEditorCurrentSessionStateContext(memberKey, session, selfCharacter)
  local resolvedMemberKey = NormalizeCharacterKey(memberKey)
  local resolvedSelfKey = NormalizeCharacterKey(selfCharacter)
  local resolvedSessionHost = NormalizeCharacterKey(type(session) == "table" and session.host or "")
  local resolvedProfileName = TrimText(type(session) == "table" and session.profileName or "")
  local isHostView = resolvedSelfKey ~= "" and resolvedSessionHost ~= "" and resolvedSelfKey == resolvedSessionHost
  local memberContext = nil
  local hostContext = nil

  if isHostView then
    if type(INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionDisplayContext) == "function" then
      hostContext = INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionDisplayContext(
        session,
        resolvedProfileName,
        resolvedMemberKey,
        {
          candidateState = ResolveCandidateCurrentSessionSyncState(
            FindCurrentSessionSyncCandidate(resolvedMemberKey),
            session
          ),
        }
      )
    end
  else
    local candidateSyncStateByMemberKey = {}
    if resolvedSessionHost ~= "" then
      candidateSyncStateByMemberKey[resolvedSessionHost] = ResolveCandidateCurrentSessionSyncState(
        FindCurrentSessionSyncCandidate(resolvedSessionHost),
        session
      )
    end
    if type(INTERNAL_API.LIDCOUNCIL_BuildMemberCurrentSessionDisplayContext) == "function" then
      memberContext = INTERNAL_API.LIDCOUNCIL_BuildMemberCurrentSessionDisplayContext(
        session,
        resolvedProfileName,
        resolvedSelfKey,
        {
          sessionHost = resolvedSessionHost,
          candidateSyncStateByMemberKey = candidateSyncStateByMemberKey,
        }
      )
    end
  end

  return {
    profileName = resolvedProfileName,
    memberKey = resolvedMemberKey,
    selfKey = resolvedSelfKey,
    sessionHost = resolvedSessionHost,
    isHostView = isHostView,
    hostContext = hostContext,
    memberContext = memberContext,
  }
end

ResolveCandidateCurrentSessionSyncState = function(candidate, session)
  candidate = type(candidate) == "table" and candidate or nil
  if not candidate then
    return nil
  end
  if type(INTERNAL_API.LIDCOUNCIL_GetPreciseSyncCandidateState) == "function" then
    return INTERNAL_API.LIDCOUNCIL_GetPreciseSyncCandidateState(
      candidate,
      type(session) == "table" and BuildCurrentSessionLiveRosterLookup(session) or nil
    )
  end
  local visibleState = string.lower(TrimText(candidate.visibleState))
  local comparison = TrimText(candidate.effectiveComparison ~= "" and candidate.effectiveComparison or candidate.comparison)
  if visibleState == "waiting_apply" or string.upper(TrimText(candidate.applyAckPhase)) == "QUEUED" then
    return "PENDING"
  end
  if visibleState == "aligned" or visibleState == "converged" or visibleState == "background" or comparison == "same" then
    return "SYNCED"
  end
  if visibleState == "lineage" or visibleState == "unknown" or comparison == "different_lineage" or comparison == "unknown" then
    return "PARTIAL"
  end

  local blockingDomains = {}
  for _, domain in ipairs(type(candidate.effectiveRemoteNewerDomains) == "table" and candidate.effectiveRemoteNewerDomains or candidate.remoteNewerDomains or {}) do
    blockingDomains[string.lower(TrimText(domain))] = true
  end
  for _, domain in ipairs(type(candidate.effectiveLocalNewerDomains) == "table" and candidate.effectiveLocalNewerDomains or candidate.localNewerDomains or {}) do
    blockingDomains[string.lower(TrimText(domain))] = true
  end
  if blockingDomains.settings or blockingDomains.permissions then
    return "PARTIAL"
  end
  if visibleState == "converged" or candidate.generationConverged == true then
    return "SYNCED"
  end

  if not blockingDomains.loot then
    return "SYNCED"
  end
  if candidate.liveLootAligned == true then
    return "SYNCED"
  end
  if candidate.preciseDetailLoaded ~= true then
    return nil
  end

  local differentByDomain = type(candidate.preciseDifferentSubdomainsByDomain) == "table" and candidate.preciseDifferentSubdomainsByDomain or {}
  local liveLootMismatch = false
  for _, subdomain in ipairs(differentByDomain.loot or {}) do
    if ClassifyCurrentSessionLootSubdomainTier(subdomain, session) == "live" then
      liveLootMismatch = true
      break
    end
  end
  return liveLootMismatch and "PARTIAL" or "SYNCED"
end

local function ResolveSessionMemberSyncAgainstReference(member, referenceMember)
  if type(member) ~= "table" or type(referenceMember) ~= "table" then
    return nil
  end
  if type(INTERNAL_API.LIDCOUNCIL_GetReferenceMemberSyncState) == "function" then
    return INTERNAL_API.LIDCOUNCIL_GetReferenceMemberSyncState(referenceMember, member)
  end

  local referenceProfileId = TrimText(referenceMember.sharedProfileId)
  local memberProfileId = TrimText(member.sharedProfileId)
  if referenceProfileId == "" or memberProfileId == "" then
    return nil
  end
  if string.lower(referenceProfileId) ~= string.lower(memberProfileId) then
    return "PARTIAL"
  end

  local referenceOperationalRevision = math.max(0, tonumber(referenceMember.operationalRevision) or 0)
  local referenceLootRevision = math.max(0, tonumber(referenceMember.lootRevision) or referenceOperationalRevision)
  local referenceSettingsRevision = math.max(0, tonumber(referenceMember.settingsRevision) or 0)
  local referencePermissionsRevision = math.max(0, tonumber(referenceMember.permissionsRevision) or 0)
  local referenceSettingsChecksum = TrimText(referenceMember.settingsChecksum)
  local referencePermissionsChecksum = TrimText(referenceMember.permissionsChecksum)
  local referenceOperationalChecksum = TrimText(referenceMember.operationalChecksum)
  local referenceLootChecksum = TrimText(referenceMember.lootChecksum)
  if referenceLootChecksum == "" then
    referenceLootChecksum = referenceOperationalChecksum
  end
  local referenceLiveLootChecksum = TrimText(referenceMember.liveLootChecksum)

  local memberOperationalRevision = math.max(0, tonumber(member.operationalRevision) or 0)
  local memberLootRevision = math.max(0, tonumber(member.lootRevision) or memberOperationalRevision)
  local memberSettingsRevision = math.max(0, tonumber(member.settingsRevision) or 0)
  local memberPermissionsRevision = math.max(0, tonumber(member.permissionsRevision) or 0)
  local memberSettingsChecksum = TrimText(member.settingsChecksum)
  local memberPermissionsChecksum = TrimText(member.permissionsChecksum)
  local memberOperationalChecksum = TrimText(member.operationalChecksum)
  local memberLootChecksum = TrimText(member.lootChecksum)
  if memberLootChecksum == "" then
    memberLootChecksum = memberOperationalChecksum
  end
  local memberLiveLootChecksum = TrimText(member.liveLootChecksum)

  local hasSettingsChecksum = referenceSettingsChecksum ~= "" and memberSettingsChecksum ~= ""
  local hasPermissionsChecksum = referencePermissionsChecksum ~= "" and memberPermissionsChecksum ~= ""
  local hasLootChecksum = referenceLootChecksum ~= "" and memberLootChecksum ~= ""

  if hasSettingsChecksum and referenceSettingsChecksum ~= memberSettingsChecksum then
    return "PARTIAL"
  end
  if hasPermissionsChecksum and referencePermissionsChecksum ~= memberPermissionsChecksum then
    return "PARTIAL"
  end
  if referenceLiveLootChecksum ~= "" and memberLiveLootChecksum ~= "" and referenceLiveLootChecksum == memberLiveLootChecksum then
    return "SYNCED"
  end
  if hasLootChecksum and referenceLootChecksum ~= memberLootChecksum then
    return "PARTIAL"
  end
  if hasSettingsChecksum and hasPermissionsChecksum and hasLootChecksum then
    return "SYNCED"
  end

  if referenceSettingsRevision == memberSettingsRevision
      and referencePermissionsRevision == memberPermissionsRevision
      and referenceLootRevision == memberLootRevision then
    return "SYNCED"
  end
  return "PARTIAL"
end

local function ResolveSessionSyncState(member, memberKey, session, selfCharacter)
  if type(member) ~= "table" then
    return "PENDING"
  end
  local hostStatusMatrix = type(INTERNAL_API.LIDCOUNCIL_GetHostMemberSyncStatusMatrix) == "function"
    and INTERNAL_API.LIDCOUNCIL_GetHostMemberSyncStatusMatrix(member)
    or nil
  if type(hostStatusMatrix) == "table" then
    return hostStatusMatrix.p2 == "READY" and "SYNCED"
      or hostStatusMatrix.p2 == "REVIEW" and "PARTIAL"
      or "PENDING"
  end
  local resolvedKey = NormalizeCharacterKey(memberKey ~= "" and memberKey or member.name or "")
  local selfKey = NormalizeCharacterKey(selfCharacter)
  local sessionHost = NormalizeCharacterKey(type(session) == "table" and session.host or "")
  local isHostView = selfKey ~= "" and sessionHost ~= "" and selfKey == sessionHost
  local isHostRow = resolvedKey ~= "" and resolvedKey == sessionHost
  if tonumber(member.lastSyncAt) and isHostRow then
    return "SYNCED"
  end
  local context = BuildEditorCurrentSessionStateContext(memberKey, session, selfCharacter)
  if type(INTERNAL_API.LIDCOUNCIL_GetJoinedMemberSyncState) == "function" then
    if context.isHostView and type(context.hostContext) == "table" then
      return INTERNAL_API.LIDCOUNCIL_GetJoinedMemberSyncState(
        session,
        context.profileName,
        context.memberKey,
        member,
        {
          localProfileId = context.hostContext.localProfileId,
          localSummary = context.hostContext.localSummary,
          localLiveLootChecksum = context.hostContext.localLiveLootChecksum,
          candidateState = context.hostContext.candidateState,
          currentSessionOnly = true,
        }
      ) or "PENDING"
    elseif type(context.memberContext) == "table" then
      return INTERNAL_API.LIDCOUNCIL_GetJoinedMemberSyncState(
        session,
        context.profileName,
        context.memberKey,
        member,
        {
          localProfileId = context.memberContext.localProfileId,
          localSummary = context.memberContext.localSummary,
          localLiveLootChecksum = context.memberContext.localLiveLootChecksum,
          candidateState = context.memberKey == context.memberContext.selfMemberKey
            and context.memberContext.selfVsHostCandidateState
            or nil,
          referenceMember = context.memberContext.hostReferenceMember,
          referenceFallbackState = "PENDING",
          currentSessionOnly = true,
        }
      ) or "PENDING"
    end
  end
  local status = string.upper(TrimText(member.status or "JOINED"))
  if status == "DECLINED" then
    return "DECLINED"
  end
  local localProfileName = TrimText(type(session) == "table" and session.profileName or "")
  local getProfileId = ResolveOptionalApiFunction("LIDCOUNCIL_GetLootProfileId")
  local getRevisionSummary = ResolveOptionalApiFunction("LIDCOUNCIL_GetLootProfileRevisionSummary")
  if tonumber(member.lastSyncAt) and TrimText(member.addonVersion) ~= "" then
    if not isHostView then
      if resolvedKey == selfKey and sessionHost ~= "" then
        local selfVsHostState = ResolveCandidateCurrentSessionSyncState(FindCurrentSessionSyncCandidate(sessionHost), session)
        if selfVsHostState ~= nil then
          return selfVsHostState
        end
      end

      local hostMember = type(session) == "table" and type(session.members) == "table" and session.members[sessionHost] or nil
      local hostReferenceState = ResolveSessionMemberSyncAgainstReference(member, hostMember)
      if hostReferenceState ~= nil then
        return hostReferenceState
      end
      return "PENDING"
    end
    if localProfileName == "" or type(getProfileId) ~= "function" or type(getRevisionSummary) ~= "function" then
      return "PARTIAL"
    end

    local localProfileId = TrimText(select(1, getProfileId(localProfileName)) or "")
    local memberProfileId = TrimText(member.sharedProfileId)
    if localProfileId == "" or memberProfileId == "" or string.lower(localProfileId) ~= string.lower(memberProfileId) then
      return "PARTIAL"
    end

    local candidateState = ResolveCandidateCurrentSessionSyncState(FindCurrentSessionSyncCandidate(resolvedKey), session)
    if candidateState ~= nil then
      return candidateState
    end

    local localSummary = getRevisionSummary(localProfileName)
    local settingsRevision = math.max(0, tonumber(type(localSummary) == "table" and localSummary.settings) or 0)
    local permissionsRevision = math.max(0, tonumber(type(localSummary) == "table" and localSummary.permissions) or 0)
    local operationalRevision = math.max(0, tonumber(type(localSummary) == "table" and localSummary.operational) or 0)
    local lootRevision = math.max(0, tonumber(type(localSummary) == "table" and localSummary.loot) or operationalRevision)
    local settingsChecksum = TrimText(type(localSummary) == "table" and localSummary.settingsChecksum or "")
    local permissionsChecksum = TrimText(type(localSummary) == "table" and localSummary.permissionsChecksum or "")
    local operationalChecksum = TrimText(type(localSummary) == "table" and localSummary.operationalChecksum or "")
    local lootChecksum = TrimText(type(localSummary) == "table" and localSummary.lootChecksum or "")
    if lootChecksum == "" then
      lootChecksum = operationalChecksum
    end
    local localLiveLootChecksum = BuildCurrentSessionLiveLootChecksum(localProfileName, session)
    local memberSettingsChecksum = TrimText(member.settingsChecksum)
    local memberPermissionsChecksum = TrimText(member.permissionsChecksum)
    local memberOperationalChecksum = TrimText(member.operationalChecksum)
    local memberLootChecksum = TrimText(member.lootChecksum)
    if memberLootChecksum == "" then
      memberLootChecksum = memberOperationalChecksum
    end
    local memberLiveLootChecksum = TrimText(member.liveLootChecksum)
    local hasSettingsChecksum = settingsChecksum ~= "" and memberSettingsChecksum ~= ""
    local hasPermissionsChecksum = permissionsChecksum ~= "" and memberPermissionsChecksum ~= ""
    local hasLootChecksum = lootChecksum ~= "" and memberLootChecksum ~= ""

    if hasSettingsChecksum and settingsChecksum ~= memberSettingsChecksum then
      return "PARTIAL"
    end
    if hasPermissionsChecksum and permissionsChecksum ~= memberPermissionsChecksum then
      return "PARTIAL"
    end
    if localLiveLootChecksum ~= "" and memberLiveLootChecksum ~= "" and localLiveLootChecksum == memberLiveLootChecksum then
      return "SYNCED"
    end
    if hasLootChecksum and lootChecksum ~= memberLootChecksum then
      return "PARTIAL"
    end
    if hasSettingsChecksum and hasPermissionsChecksum and hasLootChecksum then
      return "SYNCED"
    end

    if settingsRevision == math.max(0, tonumber(member.settingsRevision) or 0)
        and permissionsRevision == math.max(0, tonumber(member.permissionsRevision) or 0)
        and lootRevision == math.max(0, tonumber(member.lootRevision) or tonumber(member.operationalRevision) or 0) then
      return "SYNCED"
    end
    return "PARTIAL"
  end
  if tonumber(member.lastSyncAt) then
    return "PARTIAL"
  end
  return "PENDING"
end

local function ResolveSessionHistorySyncState(member, memberKey, session, selfCharacter, candidate, candidateSnapshotProvided)
  member = type(member) == "table" and member or nil
  local resolvedMemberKey = NormalizeCharacterKey(memberKey)
  local resolvedSelfKey = NormalizeCharacterKey(selfCharacter)
  local resolvedHostKey = NormalizeCharacterKey(type(session) == "table" and session.host or "")
  if not member or resolvedMemberKey == "" then
    return "PENDING"
  end
  local hostStatusMatrix = type(INTERNAL_API.LIDCOUNCIL_GetHostMemberSyncStatusMatrix) == "function"
    and INTERNAL_API.LIDCOUNCIL_GetHostMemberSyncStatusMatrix(member)
    or nil
  if type(hostStatusMatrix) == "table" then
    return hostStatusMatrix.p3 or "PENDING"
  end
  if resolvedMemberKey == resolvedHostKey or (resolvedMemberKey == resolvedSelfKey and resolvedSelfKey == resolvedHostKey) then
    return "READY"
  end

  -- The host/member archive checksums are the authoritative P3 receipt state.
  -- Candidate comparisons are repair diagnostics and may legitimately change
  -- while manifests are loading, so they must not make a completed P3 regress.
  local hostMember = type(session) == "table" and type(session.members) == "table"
    and session.members[resolvedHostKey] or nil
  if type(hostMember) ~= "table" and type(session) == "table" and type(session.members) == "table" then
    for hostMemberKey, candidateHostMember in pairs(session.members) do
      if NormalizeCharacterKey(hostMemberKey) == resolvedHostKey and type(candidateHostMember) == "table" then
        hostMember = candidateHostMember
        break
      end
    end
  end
  local hostArchiveChecksum = TrimText(type(hostMember) == "table" and hostMember.archiveLootChecksum or "")
  local memberArchiveChecksum = TrimText(member.archiveLootChecksum)
  if hostArchiveChecksum ~= "" and memberArchiveChecksum ~= "" then
    return hostArchiveChecksum == memberArchiveChecksum and "READY" or "PENDING"
  end

  candidate = type(candidate) == "table" and candidate
    or (candidateSnapshotProvided ~= true and FindCurrentSessionSyncCandidate(resolvedMemberKey) or nil)
  if type(candidate) ~= "table" then
    -- A detailed comparison is optional P3 diagnostics. The host's replicated
    -- archive checksum remains the shared completion signal while it is absent.
    return "PENDING"
  end
  local visibleState = string.lower(TrimText(candidate.visibleState))
  local effectiveComparison = TrimText(candidate.effectiveComparison)
  local comparison = string.lower(effectiveComparison ~= "" and effectiveComparison or TrimText(candidate.comparison))
  if visibleState == "background" or candidate.backgroundOnlyLootDifference == true then
    return "PENDING"
  end
  if visibleState == "aligned" or visibleState == "converged" or comparison == "same" then
    return "READY"
  end
  if visibleState == "review" or visibleState == "lineage" or comparison == "diverged" or comparison == "different_lineage" then
    return "REVIEW"
  end
  return "PENDING"
end

local function ResolveBootstrapDomainMatch(localRevision, localChecksum, memberRevision, memberChecksum)
  local resolvedLocalChecksum = TrimText(localChecksum)
  local resolvedMemberChecksum = TrimText(memberChecksum)
  if resolvedLocalChecksum ~= "" and resolvedMemberChecksum ~= "" then
    return resolvedLocalChecksum == resolvedMemberChecksum
  end
  return math.max(0, tonumber(localRevision) or 0) == math.max(0, tonumber(memberRevision) or 0)
end

local function ResolveSessionBootstrapState(member, memberKey, session, selfCharacter)
  if type(member) ~= "table" then
    return "PENDING"
  end
  local hostStatusMatrix = type(INTERNAL_API.LIDCOUNCIL_GetHostMemberSyncStatusMatrix) == "function"
    and INTERNAL_API.LIDCOUNCIL_GetHostMemberSyncStatusMatrix(member)
    or nil
  if type(hostStatusMatrix) == "table" then
    return hostStatusMatrix.p1 or "PENDING"
  end
  local resolvedKey = TrimText(memberKey ~= "" and memberKey or member.name or "")
  local selfKey = TrimText(selfCharacter)
  local sessionHost = TrimText(type(session) == "table" and session.host or "")
  if resolvedKey ~= "" and resolvedKey == sessionHost then
    return "READY"
  end
  if resolvedKey ~= "" and resolvedKey == selfKey then
    if type(session) == "table" and session.sharedProfileReady == false then
      return "PENDING"
    end
    return "READY"
  end
  local context = BuildEditorCurrentSessionStateContext(memberKey, session, selfCharacter)
  if type(INTERNAL_API.LIDCOUNCIL_GetDeferredJoinMemberBootstrapState) == "function" then
    if context.isHostView and type(context.hostContext) == "table" then
      return INTERNAL_API.LIDCOUNCIL_GetDeferredJoinMemberBootstrapState(
        session,
        context.profileName,
        context.memberKey,
        member,
        {
          localProfileId = context.hostContext.localProfileId,
          localSummary = context.hostContext.localSummary,
        }
      ) or "PENDING"
    elseif type(context.memberContext) == "table" then
      return INTERNAL_API.LIDCOUNCIL_GetDeferredJoinMemberBootstrapState(
        session,
        context.profileName,
        context.memberKey,
        member,
        {
          localProfileId = context.memberContext.localProfileId,
          localSummary = context.memberContext.localSummary,
          selfMemberKey = context.memberContext.selfMemberKey,
          localSharedProfileReady = context.memberContext.localSharedProfileReady,
        }
      ) or "PENDING"
    end
  end
  local status = string.upper(TrimText(member.status or "JOINED"))
  if status == "DECLINED" then
    return "DECLINED"
  end

  if not tonumber(member.lastSyncAt) then
    return "PENDING"
  end

  local localProfileName = TrimText(type(session) == "table" and session.profileName or "")
  local getProfileId = ResolveOptionalApiFunction("LIDCOUNCIL_GetLootProfileId")
  local getRevisionSummary = ResolveOptionalApiFunction("LIDCOUNCIL_GetLootProfileRevisionSummary")
  if TrimText(member.addonVersion) == "" or localProfileName == ""
      or type(getProfileId) ~= "function" or type(getRevisionSummary) ~= "function" then
    return "PENDING"
  end

  local localProfileId = TrimText(select(1, getProfileId(localProfileName)) or "")
  local memberProfileId = TrimText(member.sharedProfileId)
  if localProfileId == "" or memberProfileId == "" then
    return "PENDING"
  end
  if string.lower(localProfileId) ~= string.lower(memberProfileId) then
    return "REVIEW"
  end

  local localSummary = getRevisionSummary(localProfileName)
  local settingsRevision = math.max(0, tonumber(type(localSummary) == "table" and localSummary.settings) or 0)
  local permissionsRevision = math.max(0, tonumber(type(localSummary) == "table" and localSummary.permissions) or 0)
  local settingsChecksum = TrimText(type(localSummary) == "table" and localSummary.settingsChecksum or "")
  local permissionsChecksum = TrimText(type(localSummary) == "table" and localSummary.permissionsChecksum or "")
  local memberSettingsRevision = math.max(0, tonumber(member.settingsRevision) or 0)
  local memberPermissionsRevision = math.max(0, tonumber(member.permissionsRevision) or 0)
  local memberSettingsChecksum = TrimText(member.settingsChecksum)
  local memberPermissionsChecksum = TrimText(member.permissionsChecksum)

  local settingsMatch = ResolveBootstrapDomainMatch(settingsRevision, settingsChecksum, memberSettingsRevision, memberSettingsChecksum)
  local permissionsMatch = ResolveBootstrapDomainMatch(permissionsRevision, permissionsChecksum, memberPermissionsRevision, memberPermissionsChecksum)
  if settingsMatch and permissionsMatch then
    return "READY"
  end

  if memberSettingsRevision > settingsRevision or memberPermissionsRevision > permissionsRevision then
    return "REVIEW"
  end
  return "PENDING"
end

local function GetSessionBootstrapLabel(state)
  local resolved = string.upper(TrimText(state))
  if resolved == "READY" then
    return "Roll Ready"
  elseif resolved == "REVIEW" then
    return "Needs Review"
  elseif resolved == "DECLINED" then
    return "Declined"
  end
  return "Bootstrap Pending"
end

local function GetSessionBootstrapDescription(state)
  local resolved = string.upper(TrimText(state))
  if resolved == "READY" then
    return "Roll-Ready means the joined member matches the current shared profile lineage plus Settings and Permissions, so loot choices can open even if Loot or Session history is still syncing."
  elseif resolved == "REVIEW" then
    return "Needs Review means the joined member differs in shared profile lineage or in bootstrap-critical Settings or Permissions and should be reviewed before trusting loot choices."
  elseif resolved == "DECLINED" then
    return "The invited member declined the current session."
  end
  return "Bootstrap Pending means the joined member has not finished the initial host bootstrap yet. Roll choices may still be blocked while the host pushes Settings and Permissions."
end

local function GetSessionBootstrapColor(state)
  local resolved = string.upper(TrimText(state))
  if resolved == "READY" then
    return 0.20, 0.88, 0.32, 1
  elseif resolved == "REVIEW" then
    return 0.95, 0.32, 0.26, 1
  elseif resolved == "DECLINED" then
    return 0.90, 0.32, 0.24, 1
  end
  return 1.00, 0.82, 0.28, 1
end

local function GetSessionSyncLabel(syncState)
  if syncState == "SYNCED" then
    return "Fully Synced"
  elseif syncState == "ARCHIVE_SYNCING" then
    return "Live Ready - Archive Syncing"
  elseif syncState == "ARCHIVE_DIFFERS" then
    return "Live Ready - Archive Differs"
  elseif syncState == "ARCHIVE_UNKNOWN" then
    return "Live Ready - Validating Archive"
  elseif syncState == "ARCHIVE_REVIEW" then
    return "Live Ready - Review Needed"
  elseif syncState == "PARTIAL" then
    return "Partial Sync"
  elseif syncState == "DECLINED" then
    return "Declined"
  end
  return "Waiting"
end

local function GetSessionSyncDescription(syncState)
  if syncState == "SYNCED" then
    return "Fully Synced means every displayed P1, P2, and P3 scope has exact canonical checksum proof and no archive apply step remains."
  elseif syncState == "ARCHIVE_SYNCING" then
    return "Live Ready means the raid-critical profile and current-session data are usable. Archive Syncing means at least one P3 scope is actively validating, queued, moving, waiting for receipt, or waiting to apply."
  elseif syncState == "ARCHIVE_DIFFERS" then
    return "Live Ready means the raid can start. Archive Differs means both sides supplied proof but at least one non-blocking historical scope remains different or exhausted its bounded automatic repair."
  elseif syncState == "ARCHIVE_UNKNOWN" then
    return "Live Ready means the raid can start. Validating Archive means at least one P3 proof is still missing or inconclusive, so exact historical alignment is not yet known."
  elseif syncState == "ARCHIVE_REVIEW" then
    return "Live Ready means raid-critical data is usable, but at least one archive scope has a conclusive failure or requires manual review."
  elseif syncState == "PARTIAL" then
    return "Partial Sync means at least one joined member still differs in current shared profile identity, Settings, Permissions, or live/current loot data. Archive and older history are treated separately."
  elseif syncState == "DECLINED" then
    return "One or more invited members declined the current session."
  end
  return "Waiting for joined members to answer the session invite and report sync data."
end

local function ApplyTrafficLight(texture, syncState)
  if not texture then
    return
  end
  texture:SetTexture("Interface\\Buttons\\WHITE8x8")
  local r, g, b, a = 0.70, 0.70, 0.76, 1
  if syncState == "SYNCED" then
    r, g, b = 0.20, 0.88, 0.32
  elseif syncState == "ARCHIVE_SYNCING" then
    r, g, b = 0.38, 0.72, 1.00
  elseif syncState == "ARCHIVE_DIFFERS" then
    r, g, b = 1.00, 0.78, 0.28
  elseif syncState == "ARCHIVE_REVIEW" then
    r, g, b = 0.95, 0.32, 0.26
  elseif syncState == "ARCHIVE_UNKNOWN" then
    r, g, b = 0.62, 0.66, 0.72
  elseif syncState == "PARTIAL" then
    r, g, b = 1.00, 0.82, 0.28
  elseif syncState == "DECLINED" then
    r, g, b = 0.90, 0.32, 0.24
  end
  texture:SetVertexColor(r, g, b, a)
end

local function GetTrafficLightColor(syncState)
  if syncState == "SYNCED" then
    return 0.20, 0.88, 0.32, 1
  elseif syncState == "ARCHIVE_SYNCING" then
    return 0.38, 0.72, 1.00, 1
  elseif syncState == "ARCHIVE_DIFFERS" then
    return 1.00, 0.78, 0.28, 1
  elseif syncState == "ARCHIVE_REVIEW" then
    return 0.95, 0.32, 0.26, 1
  elseif syncState == "ARCHIVE_UNKNOWN" then
    return 0.62, 0.66, 0.72, 1
  elseif syncState == "PARTIAL" then
    return 1.00, 0.82, 0.28, 1
  elseif syncState == "DECLINED" then
    return 0.90, 0.32, 0.24, 1
  end
  return 0.70, 0.70, 0.76, 1
end

local function GetSessionStatusColor(status)
  local upperStatus = string.upper(TrimText(status))
  if upperStatus == "JOINED" or upperStatus == "ACTIVE" or upperStatus == "FINISHED" then
    return 0.20, 0.88, 0.32, 1
  elseif upperStatus == "LEFT" then
    return 1.00, 0.82, 0.28, 1
  elseif upperStatus == "DECLINED" or upperStatus == "FAILED" or upperStatus == "STOPPED" then
    return 0.90, 0.32, 0.24, 1
  elseif upperStatus == "INVITED" or upperStatus == "PENDING" or upperStatus == "PREPARING" then
    return 1.00, 0.82, 0.28, 1
  end
  return 0.82, 0.82, 0.86, 1
end

local function SetLootSessionActionStatusOverride(owner, text, color, indicatorState)
  if type(owner) ~= "table" then
    return
  end
  text = TrimText(text)
  if text == "" then
    owner.__lootSessionActionStatusOverride = nil
    return
  end
  local resolvedColor = type(color) == "table" and color or { 1.00, 0.55, 0.44, 1.00 }
  local resolvedIndicatorState = TrimText(indicatorState)
  if resolvedIndicatorState == "" then
    resolvedIndicatorState = "PARTIAL"
  end
  owner.__lootSessionActionStatusOverride = {
    text = text,
    color = resolvedColor,
    indicatorState = resolvedIndicatorState,
  }
  if owner.lootSessionStatus then
    owner.lootSessionStatus:SetText(text)
    owner.lootSessionStatus:SetTextColor(
      resolvedColor[1] or 1.00,
      resolvedColor[2] or 0.55,
      resolvedColor[3] or 0.44,
      resolvedColor[4] or 1.00
    )
  end
  if owner.lootSessionStatusIndicator then
    ApplyTrafficLight(owner.lootSessionStatusIndicator, resolvedIndicatorState)
  end
  if owner.lootSessionProfileSyncStatus then
    owner.lootSessionProfileSyncStatus:SetText(text)
    owner.lootSessionProfileSyncStatus:SetTextColor(
      resolvedColor[1] or 1.00,
      resolvedColor[2] or 0.55,
      resolvedColor[3] or 0.44,
      resolvedColor[4] or 1.00
    )
    if string.upper(TrimText(owner.lootSessionSection or "")) == "SYNCMGMT" then
      owner.lootSessionProfileSyncStatus:Show()
    end
  end
end

local function ClearLootSessionActionStatusOverride(owner)
  if type(owner) == "table" then
    owner.__lootSessionActionStatusOverride = nil
  end
end

local function ApplyLootSessionActionStatusOverride(owner, section)
  local override = type(owner) == "table" and owner.__lootSessionActionStatusOverride or nil
  if type(override) ~= "table" then
    return
  end
  local color = type(override.color) == "table" and override.color or { 1.00, 0.55, 0.44, 1.00 }
  local indicatorState = TrimText(override.indicatorState)
  if owner.lootSessionStatus then
    owner.lootSessionStatus:SetText(tostring(override.text or ""))
    owner.lootSessionStatus:SetTextColor(color[1], color[2], color[3], color[4] or 1.00)
  end
  if owner.lootSessionStatusIndicator then
    ApplyTrafficLight(owner.lootSessionStatusIndicator, indicatorState ~= "" and indicatorState or "PARTIAL")
  end
  if string.upper(TrimText(section or owner.lootSessionSection or "")) == "SYNCMGMT" and owner.lootSessionProfileSyncStatus then
    owner.lootSessionProfileSyncStatus:SetText(tostring(override.text or ""))
    owner.lootSessionProfileSyncStatus:SetTextColor(color[1], color[2], color[3], color[4] or 1.00)
    owner.lootSessionProfileSyncStatus:Show()
  end
end

local function RunLootSessionAction(owner, actionLabel, fn, ...)
  if type(fn) ~= "function" then
    SetLootSessionActionStatusOverride(
      owner,
      tostring(actionLabel or "Session action") .. " is unavailable.",
      { 1.00, 0.55, 0.44, 1.00 }
    )
    return false
  end
  local ok, result, detail = pcall(fn, ...)
  if not ok then
    SetLootSessionActionStatusOverride(
      owner,
      tostring(actionLabel or "Session action") .. " failed: " .. tostring(result),
      { 1.00, 0.35, 0.25, 1.00 }
    )
    return false
  end
  if result == false and TrimText(detail) == "START_CONFIRM_REQUIRED" then
    owner.__lootSessionStartConfirmationPending = true
    SetLootSessionActionStatusOverride(
      owner,
      "Start Session: review the roll-ready warning or choose Force Start.",
      { 1.00, 0.72, 0.22, 1.00 },
      "PENDING"
    )
    return true, result, detail
  end
  if result == false and TrimText(detail) ~= "" then
    SetLootSessionActionStatusOverride(
      owner,
      tostring(actionLabel or "Session action") .. " failed: " .. tostring(detail),
      { 1.00, 0.35, 0.25, 1.00 }
    )
    return false
  end
  ClearLootSessionActionStatusOverride(owner)
  return true, result, detail
end

local function ReadLootSessionActionValue(owner, actionLabel, fn, fallback, ...)
  if type(fn) ~= "function" then
    return fallback
  end
  local ok, result = pcall(fn, ...)
  if not ok then
    SetLootSessionActionStatusOverride(
      owner,
      tostring(actionLabel or "Session read") .. " failed: " .. tostring(result),
      { 1.00, 0.35, 0.25, 1.00 }
    )
    return fallback
  end
  return result
end

local function RefreshLootSessionPage_Impl(self, opts)
  if not self then
    return
  end

  local root = RootDB()
  local profile, profileName = ResolveSessionContextProfile()
  local hasActiveProfile = TrimText(profileName) ~= ""
  local access = ResolveSessionContextAccess(profileName)
  local section = self.lootSessionSection or "CURRENT"
  local selfCharacter = GetCharacterKey() or "Unknown"
  local isSimulationProfile = TrimText(profileName) == "Simulation"
  if section == "ROLESIM" and not isSimulationProfile then
    section = "CURRENT"
  end
  self.lootSessionSection = section
  local targetedSections = NormalizeLootSessionSectionTargets(type(opts) == "table" and opts.lootSessionSections or nil)

  local currentBtn = self.sessionNavCurrentBtn
  local historyBtn = self.sessionNavHistoryBtn
  local syncMgmtBtn = self.sessionNavSyncManagementBtn
  local roleSimBtn = self.sessionNavRoleSimBtn
  local autoPassSettingsBtn = self.sessionNavAutoPassSettingsBtn
  local startBtn = self.sessionStartBtn
  local activateBtn = self.sessionActivateBtn
  local stopBtn = self.sessionStopBtn
  local inviteBtn = self.sessionInviteBtn
  local removeMemberBtn = self.sessionRemoveMemberBtn
  local pushProfileBtn = self.sessionPushProfileBtn
  local pushHostSessionDataBtn = self.sessionPushHostSessionDataBtn
  local checkSyncBtn = self.sessionCheckSyncBtn
  local profileSyncDropdown = self.sessionProfileSyncMemberDropdown
  local recommendedRepairBtn = self.sessionRecommendedRepairBtn
  local requestProfileBtn = self.sessionRequestProfileBtn
  local previewProfileBtn = self.sessionPreviewProfileBtn
  local openSyncDetailBtn = self.sessionOpenSyncDetailBtn
  local syncBoardBtn = self.sessionSyncBoardBtn
  local liveSummary = self.lootSessionLiveSummary
  local overviewFrame = self.lootSessionOverviewFrame
  local currentMembersHeader = self.lootSessionMembersHeader
  local memberColumns = self.lootSessionMemberColumns
  local memberRowsFrame = self.lootSessionMemberRowsFrame
  local historyHeader = self.lootSessionHistoryHeader
  local historyColumns = self.lootSessionHistoryColumns
  local historyRowsFrame = self.lootSessionHistoryRowsFrame
  local roleSimHeader = self.lootSessionRoleSimHeader
  local roleSimDesc = self.lootSessionRoleSimDesc
  local roleSimCurrent = self.lootSessionRoleSimCurrent
  local roleSimMasterBtn = self.sessionRoleSimMasterBtn
  local roleSimSessionHostBtn = self.sessionRoleSimSessionHostBtn
  local roleSimCouncilBtn = self.sessionRoleSimCouncilBtn
  local roleSimRaiderBtn = self.sessionRoleSimRaiderBtn
  local roleSimMatrixFrame = self.lootSessionRoleSimMatrixFrame
  local roleSimMatrixHeader = self.lootSessionRoleSimMatrixHeader
  local roleSimState = self.lootSessionRoleSimState
  local autoPassHeader = self.lootSessionAutoPassHeader
  local autoPassDesc = self.lootSessionAutoPassDesc
  local autoPassCurrent = self.lootSessionAutoPassCurrent
  local autoPassStatus = self.lootSessionAutoPassStatus
  local autoPassLocalBtn = self.sessionAutoPassLocalBtn
  local autoPassState = self.lootSessionAutoPassState
  local autoPassIcon = self.lootSessionAutoPassIcon
  local syncCheckHeader = self.lootSessionSyncCheckHeader
  local syncIntro = self.lootSessionSyncIntro
  local syncResolveHeader = self.lootSessionSyncResolveHeader
  local syncAdvancedHeader = self.lootSessionSyncAdvancedHeader
  local syncDashboardFrame = self.lootSessionSyncDashboardFrame
  local syncScopeFrame = self.lootSessionSyncScopeFrame
  local syncPushHeader = self.lootSessionSyncPushHeader
  local syncPullHeader = self.lootSessionSyncPullHeader
  local syncAutoHeader = self.lootSessionSyncAutoHeader
  local syncAutoText = self.lootSessionSyncAutoText
  local syncManualHeader = self.lootSessionSyncManualHeader
  local syncManualText = self.lootSessionSyncManualText
  local syncReviewHeader = self.lootSessionSyncReviewHeader
  local syncReviewColumns = self.lootSessionSyncReviewColumns
  local syncReviewRowsFrame = self.lootSessionSyncReviewRowsFrame
  local syncReviewEmpty = self.lootSessionSyncReviewEmpty
  local body = self.lootSessionBody

  if self.lootSessionInactiveOverlay then
    self.lootSessionInactiveOverlay:SetShown(not hasActiveProfile)
  end
  if self.lootSessionNavBg then
    self.lootSessionNavBg:SetShown(hasActiveProfile)
  end
  if self.lootSessionRightBg then
    self.lootSessionRightBg:SetShown(hasActiveProfile)
  end

  if not hasActiveProfile then
    self.lootSessionSection = "CURRENT"
    if self.panelsTitle then self.panelsTitle:SetText("Profile") end
    SetCurrentProfileFont(self.panelsCurrentLabel, NO_ACTIVE_PROFILE_CURRENT_TEXT, NO_ACTIVE_PROFILE_TEXT_COLOR)
    if self.UpdateScrollLayout then
      self:UpdateScrollLayout()
    end
    return
  end
  if self.panelsTitle then self.panelsTitle:SetText("Session") end
  if tostring(self.currentPage or "") == "Panels"
    and type(targetedSections) == "table"
    and next(targetedSections)
    and not targetedSections[section]
  then
    return
  end

  self.__lootSessionPhaseStartedAt = INTERNAL_API.LIDCOUNCIL_BeginSyncPerformanceSample_Impl("editor_session_context", 1)
  local activeSession, activeProfileName = GetActiveLootSession()
  if self.__lootSessionStartConfirmationPending == true
    and type(activeSession) == "table"
    and string.upper(TrimText(activeSession.status or "")) == "ACTIVE"
  then
    self.__lootSessionStartConfirmationPending = nil
    ClearLootSessionActionStatusOverride(self)
  end
  local syntheticSessionActive = false
  local syntheticDisplayProfileName = nil
  local getSyntheticSessionContext = ResolveOptionalApiFunction("LIDCOUNCIL_GetDeveloperProfileSyncHarnessSessionContext")
  if not activeSession and type(getSyntheticSessionContext) == "function" then
    local syntheticContext = ReadLootSessionActionValue(self, "Read synthetic session state", getSyntheticSessionContext, nil)
    if type(syntheticContext) == "table" and syntheticContext.active == true and type(syntheticContext.activeSession) == "table" then
      activeSession = syntheticContext.activeSession
      activeProfileName = TrimText(syntheticContext.activeProfileName)
      syntheticDisplayProfileName = TrimText(syntheticContext.displayProfileName)
      syntheticSessionActive = true
    end
  end
  local activeSessionProfile = activeSession and root.profiles and root.profiles[activeProfileName] or nil
  activeSessionProfile = type(activeSessionProfile) == "table" and activeSessionProfile or profile
  local activeSessionIsHost = activeSession and tostring(activeSession.host or "") == tostring(selfCharacter)
  local activeSessionMember = activeSession and activeSession.members and activeSession.members[selfCharacter] or nil
  local activeSessionIsJoined = activeSessionIsHost or (type(activeSessionMember) == "table" and tostring(activeSessionMember.status or "JOINED") == "JOINED")
  local roleLabel = string.format(
    "%s | %s",
    FormatLootProfileRoleLabel(access.role),
    syntheticSessionActive and "Developer Synthetic Host" or (activeSessionIsHost and "Session Host" or (activeSessionIsJoined and "Joined Member" or "Observer"))
  )
  local liveSummaryProvider = ResolveOptionalApiFunction("LIDCOUNCIL_GetLiveLootBoardSummary")
  local liveSummaryState = ReadLootSessionActionValue(self, "Read Live Board summary", liveSummaryProvider, nil)
  local inCombat = IsCombatLocked()
  INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl("editor_session_context", self.__lootSessionPhaseStartedAt, {
    context = section,
  })

  self.__lootSessionPhaseStartedAt = INTERNAL_API.LIDCOUNCIL_BeginSyncPerformanceSample_Impl("editor_session_controls", 1)
  for _, button in ipairs(self.lootSessionNavButtons or {}) do
    SetListButtonSelected(button, false)
    SetTextListButtonTextColor(button, { 0.92, 0.92, 0.96, 1.00 })
  end
  if roleSimBtn then
    roleSimBtn:SetShown(isSimulationProfile)
  end
  if section == "CURRENT" then
    if currentBtn then
      SetListButtonSelected(currentBtn, true)
      SetTextListButtonTextColor(currentBtn, { 1.00, 0.88, 0.32, 1.00 })
    end
  elseif section == "SYNCMGMT" then
    if syncMgmtBtn then
      SetListButtonSelected(syncMgmtBtn, true)
      SetTextListButtonTextColor(syncMgmtBtn, { 1.00, 0.88, 0.32, 1.00 })
    end
  elseif section == "ROLESIM" then
    if roleSimBtn then
      SetListButtonSelected(roleSimBtn, true)
      SetTextListButtonTextColor(roleSimBtn, { 1.00, 0.88, 0.32, 1.00 })
    end
  elseif section == "AUTOPASS" then
    if autoPassSettingsBtn then
      SetListButtonSelected(autoPassSettingsBtn, true)
      SetTextListButtonTextColor(autoPassSettingsBtn, { 1.00, 0.88, 0.32, 1.00 })
    end
  else
    if historyBtn then
      SetListButtonSelected(historyBtn, true)
      SetTextListButtonTextColor(historyBtn, { 1.00, 0.88, 0.32, 1.00 })
    end
  end

  local activeSessionStatus = string.upper(TrimText(activeSession and activeSession.status or ""))
  local activeSessionIsPreparing = activeSessionStatus == "PREPARING"
  if startBtn and startBtn.SetText then
    startBtn:SetText("Prepare Session")
  end
  if activateBtn and activateBtn.SetText then
    activateBtn:SetText("Start Session")
  end
  if stopBtn and stopBtn.SetText then
    stopBtn:SetText(activeSessionIsPreparing and "Close Lobby" or "End Session")
  end
  if inviteBtn and inviteBtn.SetText then
    inviteBtn:SetText("Send Invite")
  end
  if startBtn and startBtn.Enable then
    if syntheticSessionActive then
      if activeSessionIsHost and access.canStartSession and not inCombat and activeSessionStatus ~= "PREPARING" and activeSessionStatus ~= "ACTIVE" then
        startBtn:Enable()
      else
        startBtn:Disable()
      end
    elseif activeSession or not access.canStartSession or inCombat then
      startBtn:Disable()
    else
      startBtn:Enable()
    end
  end
  if activateBtn and activateBtn.Enable then
    if activeSession and activeSessionIsPreparing and activeSessionIsHost and access.canStartSession and not inCombat then
      activateBtn:Enable()
    else
      activateBtn:Disable()
    end
  end
  if stopBtn and stopBtn.Enable then
    if activeSession and activeSessionIsHost and access.canManageSession and not inCombat and (not syntheticSessionActive or activeSessionStatus == "PREPARING" or activeSessionStatus == "ACTIVE") then
      stopBtn:Enable()
    else
      stopBtn:Disable()
    end
    if stopBtn.SetAlpha then
      stopBtn:SetAlpha(stopBtn:IsEnabled() and 0.78 or 0.45)
    end
  end
  if self.sessionLeaveBtn and self.sessionLeaveBtn.Enable then
    if activeSession and not syntheticSessionActive and activeSessionIsJoined and not activeSessionIsHost and not inCombat then
      self.sessionLeaveBtn:Enable()
    else
      self.sessionLeaveBtn:Disable()
    end
  end
  if inviteBtn and inviteBtn.Enable then
    if activeSession and not syntheticSessionActive and activeSessionIsHost and access.canManageSession and not inCombat then
      inviteBtn:Enable()
    else
      inviteBtn:Disable()
    end
  end
  if self.sessionRefreshReadinessBtn and self.sessionRefreshReadinessBtn.Enable then
    if activeSession and not syntheticSessionActive and activeSessionIsHost and access.canManageSession then
      self.sessionRefreshReadinessBtn:Enable()
    else
      self.sessionRefreshReadinessBtn:Disable()
    end
  end
  local canRemoveSelectedMember = false
  if removeMemberBtn and removeMemberBtn.Enable then
    local selectedMemberKey = TrimText(self.lootSessionSelectedMemberKey)
    local selectedMember = activeSession and activeSession.members and activeSession.members[selectedMemberKey] or nil
    local selectedIsHost = activeSession and string.lower(TrimText(activeSession.host)) == string.lower(selectedMemberKey)
    local selectedIsSelf = string.lower(selectedMemberKey) == string.lower(selfCharacter)
    canRemoveSelectedMember = activeSession ~= nil
      and not syntheticSessionActive
      and activeSessionIsHost
      and access.canManageSession
      and selectedMember ~= nil
      and not selectedIsHost
      and not selectedIsSelf
    if canRemoveSelectedMember and not inCombat then
      removeMemberBtn:Enable()
    else
      removeMemberBtn:Disable()
    end
  end
  if pushProfileBtn and pushProfileBtn.Enable then
    if activeSession and activeSessionIsHost and access.canManageSession and not inCombat then
      pushProfileBtn:Enable()
    else
      pushProfileBtn:Disable()
    end
  end
  if pushHostSessionDataBtn and pushHostSessionDataBtn.Enable then
    if activeSession and activeSessionIsHost and access.canManageSession and not inCombat then
      pushHostSessionDataBtn:Enable()
    else
      pushHostSessionDataBtn:Disable()
    end
  end

  local showingCurrent = (section == "CURRENT")
  local showingSyncManagement = (section == "SYNCMGMT")
  local showingRoleSimulation = (section == "ROLESIM")
  local showingAutoPassSetting = (section == "AUTOPASS")
  local showingHistory = not showingCurrent and not showingSyncManagement and not showingRoleSimulation and not showingAutoPassSetting
  INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl("editor_session_controls", self.__lootSessionPhaseStartedAt, {
    context = section,
  })

  if showingSyncManagement then
    self.__lootSessionPhaseStartedAt = INTERNAL_API.LIDCOUNCIL_BeginSyncPerformanceSample_Impl("editor_session_sync_management", 1)
    RefreshSyncManagementView(self, {
      activeSession = activeSession,
      activeSessionIsHost = activeSessionIsHost,
      access = access,
      syntheticSession = syntheticSessionActive,
      syntheticDisplayProfileName = syntheticDisplayProfileName,
    })
    INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl("editor_session_sync_management", self.__lootSessionPhaseStartedAt, {
      context = section,
    })
    syncDashboardFrame = self.lootSessionSyncDashboardFrame
    syncScopeFrame = self.lootSessionSyncScopeFrame
  else
    self.lootSessionAllSyncCandidates = {}
    self.lootSessionSyncCandidates = {}
  end

  local historyExpanded = self.lootSessionHistoryExpanded or {}
  self.lootSessionHistoryExpanded = historyExpanded
  local historyRowsData = {}
  if showingHistory then
    self.__lootSessionPhaseStartedAt = INTERNAL_API.LIDCOUNCIL_BeginSyncPerformanceSample_Impl("editor_session_history", 1)
    local allHistoryRowsData = BuildSessionHistoryRowsData(profile, selfCharacter)
    historyRowsData = GetPagedSessionHistoryRows(self, allHistoryRowsData)
    RefreshSessionHistoryRows(self, historyRowsData, historyExpanded, profile, selfCharacter)
    INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl("editor_session_history", self.__lootSessionPhaseStartedAt, {
      context = section,
    })
  end

  self.__lootSessionPhaseStartedAt = INTERNAL_API.LIDCOUNCIL_BeginSyncPerformanceSample_Impl("editor_session_visibility", 1)
  if startBtn then startBtn:SetShown(showingCurrent and (not activeSession or syntheticSessionActive) and access.canStartSession) end
  if activateBtn then activateBtn:SetShown(showingCurrent and activeSessionIsPreparing and activeSessionIsHost and access.canStartSession) end
  if stopBtn then stopBtn:SetShown(showingCurrent and activeSession ~= nil and activeSessionIsHost and access.canManageSession) end
  if self.sessionLeaveBtn then self.sessionLeaveBtn:SetShown(showingCurrent and activeSession ~= nil and activeSessionIsJoined and not activeSessionIsHost and not syntheticSessionActive) end
  if inviteBtn then inviteBtn:SetShown(showingCurrent and activeSession ~= nil and activeSessionIsHost and access.canManageSession and not syntheticSessionActive) end
  if self.sessionRefreshReadinessBtn then self.sessionRefreshReadinessBtn:SetShown(showingCurrent and activeSession ~= nil and activeSessionIsHost and access.canManageSession and not syntheticSessionActive) end
  if removeMemberBtn then removeMemberBtn:SetShown(showingCurrent and canRemoveSelectedMember) end
  if checkSyncBtn then checkSyncBtn:SetShown(showingSyncManagement) end
  if pushProfileBtn then pushProfileBtn:SetShown(showingSyncManagement) end
  if pushHostSessionDataBtn then pushHostSessionDataBtn:SetShown(showingSyncManagement) end
  if profileSyncDropdown then profileSyncDropdown:SetShown(showingSyncManagement) end
  if recommendedRepairBtn then recommendedRepairBtn:SetShown(false) end
  if requestProfileBtn then requestProfileBtn:SetShown(showingSyncManagement) end
  if previewProfileBtn then previewProfileBtn:SetShown(showingSyncManagement) end
  if openSyncDetailBtn then openSyncDetailBtn:SetShown(showingSyncManagement) end
  if syncBoardBtn then syncBoardBtn:SetShown(showingSyncManagement) end
  if self.lootSessionSyncHistoryFrame then
    self.lootSessionSyncHistoryFrame:SetShown(showingSyncManagement)
  end
  if self.lootSessionHostOverrideFrame then
    self.lootSessionHostOverrideFrame:SetShown(showingSyncManagement and self.__lootSessionHostOverrideAvailable == true)
  end
  if self.lootSessionSyncSelectedHint then
    self.lootSessionSyncSelectedHint:SetShown(showingSyncManagement and TrimText(self.lootSessionSyncSelectedHint:GetText()) ~= "")
  end
  if self.lootSessionProfileSyncStatus then
    self.lootSessionProfileSyncStatus:SetShown(showingSyncManagement and TrimText(self.lootSessionProfileSyncStatus:GetText()) ~= "")
  end
  if self.lootSessionSyncProgress then
    self.lootSessionSyncProgress:SetShown(false)
  end
  if self.lootSessionSyncProgressFrame then
    self.lootSessionSyncProgressFrame:SetShown(showingSyncManagement)
  end
  if liveSummary then liveSummary:SetShown(showingCurrent) end
  if self.lootSessionStatus then self.lootSessionStatus:SetShown(not showingAutoPassSetting) end
  if self.lootSessionStatusIndicator then self.lootSessionStatusIndicator:SetShown(not showingAutoPassSetting) end
  if overviewFrame then overviewFrame:SetShown(showingCurrent) end
  if currentMembersHeader then currentMembersHeader:SetShown(showingCurrent and activeSession ~= nil) end
  if self.lootSessionMembersLegend then self.lootSessionMembersLegend:SetShown(showingCurrent and activeSession ~= nil) end
  if memberColumns then memberColumns:SetShown(showingCurrent and activeSession ~= nil) end
  if memberRowsFrame then memberRowsFrame:SetShown(showingCurrent and activeSession ~= nil) end
  if historyHeader then historyHeader:SetShown(showingHistory) end
  if historyColumns then historyColumns:SetShown(showingHistory) end
  if historyRowsFrame then historyRowsFrame:SetShown(showingHistory) end
  local showHistoryPager = showingHistory and (tonumber(self.lootSessionHistoryTotalPages) or 1) > 1
  if self.sessionHistoryPrevBtn then
    self.sessionHistoryPrevBtn:SetEnabled((tonumber(self.lootSessionHistoryPage) or 1) > 1)
    self.sessionHistoryPrevBtn:SetShown(showHistoryPager)
  end
  if self.lootSessionHistoryPageText then
    if showHistoryPager then
      self.lootSessionHistoryPageText:SetText(string.format(
        "Page %d / %d",
        tonumber(self.lootSessionHistoryPage) or 1,
        tonumber(self.lootSessionHistoryTotalPages) or 1
      ))
    end
    self.lootSessionHistoryPageText:SetShown(showHistoryPager)
  end
  if self.sessionHistoryNextBtn then
    self.sessionHistoryNextBtn:SetEnabled((tonumber(self.lootSessionHistoryPage) or 1) < (tonumber(self.lootSessionHistoryTotalPages) or 1))
    self.sessionHistoryNextBtn:SetShown(showHistoryPager)
  end
  if roleSimHeader then roleSimHeader:SetShown(showingRoleSimulation) end
  if roleSimDesc then roleSimDesc:SetShown(showingRoleSimulation) end
  if roleSimCurrent then roleSimCurrent:SetShown(showingRoleSimulation) end
  if roleSimMasterBtn then roleSimMasterBtn:SetShown(showingRoleSimulation) end
  if roleSimSessionHostBtn then roleSimSessionHostBtn:SetShown(showingRoleSimulation) end
  if roleSimCouncilBtn then roleSimCouncilBtn:SetShown(showingRoleSimulation) end
  if roleSimRaiderBtn then roleSimRaiderBtn:SetShown(showingRoleSimulation) end
  if roleSimMatrixFrame then roleSimMatrixFrame:SetShown(showingRoleSimulation) end
  if roleSimMatrixHeader then roleSimMatrixHeader:SetShown(showingRoleSimulation) end
  for _, row in ipairs(self.lootSessionRoleSimMatrixRows or {}) do
    row:SetShown(showingRoleSimulation)
  end
  if roleSimState then roleSimState:SetShown(showingRoleSimulation) end
  if autoPassHeader then autoPassHeader:SetShown(showingAutoPassSetting) end
  if autoPassDesc then autoPassDesc:SetShown(showingAutoPassSetting) end
  if autoPassCurrent then autoPassCurrent:SetShown(false) end
  if autoPassStatus then autoPassStatus:SetShown(showingAutoPassSetting) end
  if autoPassLocalBtn then autoPassLocalBtn:SetShown(showingAutoPassSetting) end
  if autoPassState then autoPassState:SetShown(showingAutoPassSetting) end
  if autoPassIcon then autoPassIcon:SetShown(false) end
  if syncCheckHeader then syncCheckHeader:SetShown(showingSyncManagement) end
  if syncIntro then syncIntro:SetShown(showingSyncManagement) end
  if syncDashboardFrame then syncDashboardFrame:SetShown(showingSyncManagement) end
  if syncScopeFrame then syncScopeFrame:SetShown(showingSyncManagement) end
  if syncPushHeader then syncPushHeader:SetShown(showingSyncManagement) end
  if syncPullHeader then syncPullHeader:SetShown(showingSyncManagement) end
  if syncResolveHeader then syncResolveHeader:SetShown(showingSyncManagement) end
  if syncAdvancedHeader then syncAdvancedHeader:SetShown(showingSyncManagement) end
  if syncAutoHeader then syncAutoHeader:SetShown(showingSyncManagement) end
  if syncAutoText then syncAutoText:SetShown(showingSyncManagement) end
  if syncManualHeader then syncManualHeader:SetShown(showingSyncManagement) end
  if syncManualText then syncManualText:SetShown(showingSyncManagement) end
  if self.lootSessionSyncPushHelp then
    self.lootSessionSyncPushHelp:SetShown(showingSyncManagement and TrimText(self.lootSessionSyncPushHelp:GetText()) ~= "")
  end
  if syncReviewHeader then syncReviewHeader:SetShown(false) end
  if syncReviewColumns then syncReviewColumns:SetShown(false) end
  if syncReviewRowsFrame then syncReviewRowsFrame:SetShown(false) end
  if syncReviewEmpty then syncReviewEmpty:SetShown(false) end
  if body then
    body:SetShown(showingHistory)
  end
  if not showingSyncManagement then
    for _, row in ipairs(self.lootSessionSyncReviewRows or {}) do
      row:Hide()
    end
  end
  INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl("editor_session_visibility", self.__lootSessionPhaseStartedAt, {
    context = section,
  })

  if section == "CURRENT" then
    local currentSessionSyncCandidates = {}
    local currentSessionQueueStatus = type(self.__lootSessionCurrentQueueStatus) == "table"
      and self.__lootSessionCurrentQueueStatus
      or {}
    self.__lootSessionPhaseStartedAt = INTERNAL_API.LIDCOUNCIL_BeginSyncPerformanceSample_Impl("editor_session_candidates", 1)
    -- Real Current Session rows use the replicated P1/P2/P3 status matrix and
    -- archive receipt checksums. Full repair candidates belong to Sync Management.
    if syntheticSessionActive then
      local getActiveProfileSyncCandidates = ResolveOptionalApiFunction("LIDCOUNCIL_GetActiveProfileSyncCandidates")
      if type(getActiveProfileSyncCandidates) == "function" then
        currentSessionSyncCandidates = ReadLootSessionActionValue(
          self,
          "Read synthetic current-session sync candidates",
          getActiveProfileSyncCandidates,
          {}
        )
      end
    end
    INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl("editor_session_candidates", self.__lootSessionPhaseStartedAt, {
      context = section,
    })
    self.__lootSessionPhaseStartedAt = INTERNAL_API.LIDCOUNCIL_BeginSyncPerformanceSample_Impl("editor_session_queue", 1)
    local getSessionCommQueueStatus = ResolveOptionalApiFunction("LIDCOUNCIL_GetSessionCommQueueStatus")
    local activeSessionId = TrimText(type(activeSession) == "table" and activeSession.id or "")
    local currentTime = type(GetTime) == "function" and GetTime() or 0
    local lastQueueStatusAt = tonumber(self.__lootSessionCurrentQueueStatusAt) or 0
    local shouldRefreshQueueStatus = activeSessionId ~= "" and type(getSessionCommQueueStatus) == "function"
      and (
        TrimText(self.__lootSessionCurrentQueueStatusSessionId) ~= activeSessionId
        or currentTime <= 0
        or (currentTime - lastQueueStatusAt) >= 0.5
      )
    if shouldRefreshQueueStatus then
      currentSessionQueueStatus = ReadLootSessionActionValue(
        self,
        "Read current-session transfer progress",
        getSessionCommQueueStatus,
        {}
      )
      self.__lootSessionCurrentQueueStatus = currentSessionQueueStatus
      self.__lootSessionCurrentQueueStatusAt = currentTime
      self.__lootSessionCurrentQueueStatusSessionId = activeSessionId
    end
    INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl("editor_session_queue", self.__lootSessionPhaseStartedAt, {
      context = section,
    })
    self.__lootSessionPhaseStartedAt = INTERNAL_API.LIDCOUNCIL_BeginSyncPerformanceSample_Impl("editor_session_current_render", 1)
    RefreshCurrentSessionView(self, {
      activeSession = activeSession,
      activeSessionProfile = activeSessionProfile,
      selfCharacter = selfCharacter,
      activeSessionIsHost = activeSessionIsHost,
      activeSessionIsJoined = activeSessionIsJoined,
      activeProfileName = activeProfileName,
      syntheticDisplayProfileName = syntheticDisplayProfileName,
      syntheticSession = syntheticSessionActive,
      profileName = profileName,
      roleLabel = roleLabel,
      liveSummaryState = liveSummaryState,
      syncCandidates = currentSessionSyncCandidates,
      queueStatus = currentSessionQueueStatus,
    })
    INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl("editor_session_current_render", self.__lootSessionPhaseStartedAt, {
      context = section,
    })
  elseif showingSyncManagement then
    -- RefreshSyncManagementView already populated the sync-management content.
  elseif showingRoleSimulation then
    RefreshRoleSimulationView(self, {
      profileName = profileName,
      access = access,
    })
  elseif showingAutoPassSetting then
    RefreshAutoPassView(self, {
      activeSession = activeSession,
      selfCharacter = selfCharacter,
    })
  else
    self.lootSessionTitle:SetText("Session History")
    self.lootSessionStatus.__lid_customTextColor = nil
    self.lootSessionStatus:SetText("Profile: " .. tostring(profileName))
    self.lootSessionStatus:SetTextColor(0.82, 0.82, 0.86, 1.00)
    ApplyTrafficLight(self.lootSessionStatusIndicator, #historyRowsData > 0 and "SYNCED" or "PENDING")
    if body then
      body:SetText("")
      body:SetShown(false)
    end
  end

  self.__lootSessionPhaseStartedAt = INTERNAL_API.LIDCOUNCIL_BeginSyncPerformanceSample_Impl("editor_session_layout", 1)
  if self.LayoutLootSessionPage then
    self:LayoutLootSessionPage()
  end
  INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl("editor_session_layout", self.__lootSessionPhaseStartedAt, {
    context = section,
  })
  ApplyLootSessionActionStatusOverride(self, section)
  SetCurrentProfileFont(self.panelsCurrentLabel, "Current Profile: " .. tostring(profileName), nil)
  self.__lootSessionPhaseStartedAt = INTERNAL_API.LIDCOUNCIL_BeginSyncPerformanceSample_Impl("editor_session_scroll", 1)
  if self.UpdateScrollLayout then
    self:UpdateScrollLayout(true)
  end
  INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl("editor_session_scroll", self.__lootSessionPhaseStartedAt, {
    context = section,
  })
  self.__lootSessionPhaseStartedAt = nil
end

local CreateLootSessionCurrentHelpers = INTERNAL_API.LIDCOUNCIL_CreateLootSessionCurrentHelpers_Impl
if type(CreateLootSessionCurrentHelpers) ~= "function" then
  error("LidCouncil missing loot session current helpers.")
end

local lootSessionCurrentHelpers = CreateLootSessionCurrentHelpers({
  ApplyFrameSkin = ApplyFrameSkin,
  RootDB = RootDB,
  TrimText = TrimText,
  RequestLootSessionSectionRefresh = RequestLootSessionSectionRefresh,
  GetActiveLootSession = GetActiveLootSession,
  BuildCurrentSessionStateSignature = INTERNAL_API.LIDCOUNCIL_BuildCurrentSectionStateSignature,
  ResolveSessionDisplayInfo = ResolveSessionDisplayInfo,
  ResolveSessionSyncState = ResolveSessionSyncState,
  ResolveSessionBootstrapState = ResolveSessionBootstrapState,
  ResolveSessionHistorySyncState = ResolveSessionHistorySyncState,
  ResolveSessionIconData = ResolveSessionIconData,
  ApplySessionIcon = ApplySessionIcon,
  GetSessionClassColor = GetSessionClassColor,
  GetSessionSyncLabel = GetSessionSyncLabel,
  GetSessionSyncDescription = GetSessionSyncDescription,
  GetSessionBootstrapLabel = GetSessionBootstrapLabel,
  GetSessionBootstrapDescription = GetSessionBootstrapDescription,
  GetSessionBootstrapColor = GetSessionBootstrapColor,
  ApplyTrafficLight = ApplyTrafficLight,
  GetTrafficLightColor = GetTrafficLightColor,
  GetSessionStatusColor = GetSessionStatusColor,
  GetLocalAutoPassEnabled = rawget(_G, "LIDCOUNCIL_GetLocalAutoPassEnabled"),
  GetSessionCommQueueStatus = function()
    local getStatus = ResolveOptionalApiFunction("LIDCOUNCIL_GetSessionCommQueueStatus")
    return type(getStatus) == "function" and getStatus() or {}
  end,
  GetMemberLootListDifferenceDiagnostics = function(sessionId, memberKey)
    local getDiagnostics = ResolveOptionalApiFunction("LIDCOUNCIL_GetMemberLootListDifferenceDiagnostics")
    return type(getDiagnostics) == "function" and getDiagnostics(sessionId, memberKey) or nil
  end,
  GetMemberItemHistoryDifferenceDiagnostics = function(sessionId, memberKey)
    local getDiagnostics = ResolveOptionalApiFunction("LIDCOUNCIL_GetMemberItemHistoryDifferenceDiagnostics")
    return type(getDiagnostics) == "function" and getDiagnostics(sessionId, memberKey) or nil
  end,
  GetMemberSessionHistoryDifferenceDiagnostics = function(sessionId, memberKey)
    local getDiagnostics = ResolveOptionalApiFunction("LIDCOUNCIL_GetMemberSessionHistoryDifferenceDiagnostics")
    return type(getDiagnostics) == "function" and getDiagnostics(sessionId, memberKey) or nil
  end,
  GetMemberP2ProofDiagnostics = function(activeSession, profileName, memberKey, member, viewerKey, sharedContext)
    local getDiagnostics = INTERNAL_API.LIDCOUNCIL_GetHostMemberP2ProofDiagnostics
    return type(getDiagnostics) == "function"
      and getDiagnostics(activeSession, profileName, memberKey, member, viewerKey, sharedContext)
      or nil
  end,
  FormatDateTime = FormatDateTime,
  FlowLayoutControls = FlowLayoutControls,
  ClampLayoutValue = ClampLayoutValue,
})

RefreshCurrentSessionView = lootSessionCurrentHelpers.RefreshCurrentSessionView
RefreshCurrentSessionPriorityTelemetry = lootSessionCurrentHelpers.RefreshCurrentSessionPriorityTelemetry
RefreshCurrentSessionRosterIfChanged = lootSessionCurrentHelpers.RefreshCurrentSessionRosterIfChanged
LayoutCurrentSessionSection = lootSessionCurrentHelpers.LayoutCurrentSessionSection
INTERNAL_API.LIDCOUNCIL_BuildCurrentSessionPriorityPresentation_Impl =
  lootSessionCurrentHelpers.BuildPriorityPresentationForValidation
INTERNAL_API.LIDCOUNCIL_ResolveCurrentSessionTransferScopeLabel_Impl =
  lootSessionCurrentHelpers.ResolveTransferScopeLabelForValidation
INTERNAL_API.LIDCOUNCIL_ResolveCurrentSessionSyncPresentationState_Impl =
  lootSessionCurrentHelpers.ResolveOverallSyncPresentationStateForValidation
INTERNAL_API.LIDCOUNCIL_BuildCurrentSessionMemberColumnLayout_Impl =
  lootSessionCurrentHelpers.BuildSessionMemberColumnLayoutForValidation

local CreateLootSessionHistoryHelpers = INTERNAL_API.LIDCOUNCIL_CreateLootSessionHistoryHelpers_Impl
if type(CreateLootSessionHistoryHelpers) ~= "function" then
  error("LidCouncil missing loot session history helpers.")
end

local lootSessionHistoryHelpers = CreateLootSessionHistoryHelpers({
  ApplyFrameSkin = ApplyFrameSkin,
  TrimText = TrimText,
  RequestLootSessionSectionRefresh = RequestLootSessionSectionRefresh,
  ResolveSessionDisplayInfo = ResolveSessionDisplayInfo,
  ResolveSessionSyncState = ResolveSessionSyncState,
  ResolveSessionIconData = ResolveSessionIconData,
  ApplySessionIcon = ApplySessionIcon,
  GetSessionClassColor = GetSessionClassColor,
  GetSessionStatusColor = GetSessionStatusColor,
  GetTrafficLightColor = GetTrafficLightColor,
  GetSessionSyncLabel = GetSessionSyncLabel,
  ApplyTrafficLight = ApplyTrafficLight,
  FormatDateTime = FormatDateTime,
  FormatDuration = FormatDuration,
})

BuildSessionHistoryRowsData = lootSessionHistoryHelpers.BuildSessionHistoryRowsData
GetPagedSessionHistoryRows = lootSessionHistoryHelpers.GetPagedSessionHistoryRows
RefreshSessionHistoryRows = lootSessionHistoryHelpers.RefreshSessionHistoryRows
LayoutSessionHistorySection = lootSessionHistoryHelpers.LayoutSessionHistorySection

local CreateLootSessionSyncHelpers = INTERNAL_API.LIDCOUNCIL_CreateLootSessionSyncHelpers_Impl
if type(CreateLootSessionSyncHelpers) ~= "function" then
  error("LidCouncil missing loot session sync helpers.")
end

local lootSessionSyncHelpers = CreateLootSessionSyncHelpers({
  ApplyFrameSkin = ApplyFrameSkin,
  RootDB = RootDB,
  TrimText = TrimText,
  CreateCustomDropdownControl = CreateCustomDropdownControl,
  RequestLootSessionSectionRefresh = RequestLootSessionSectionRefresh,
  GetSessionClassColor = GetSessionClassColor,
  ResolveOptionalApiFunction = ResolveOptionalApiFunction,
  FlowLayoutControls = FlowLayoutControls,
  ClampLayoutValue = ClampLayoutValue,
  FormatDateTime = FormatDateTime,
  ApplyTrafficLight = ApplyTrafficLight,
})

RefreshSyncManagementView = lootSessionSyncHelpers.RefreshSyncManagementView
LayoutSyncManagementSection = lootSessionSyncHelpers.LayoutSyncManagementSection

local CreateLootSessionRoleSimHelpers = INTERNAL_API.LIDCOUNCIL_CreateLootSessionRoleSimHelpers_Impl
if type(CreateLootSessionRoleSimHelpers) ~= "function" then
  error("LidCouncil missing loot session role simulation helpers.")
end

local lootSessionRoleSimHelpers = CreateLootSessionRoleSimHelpers({
  TrimText = TrimText,
  ResolveOptionalApiFunction = ResolveOptionalApiFunction,
  GetLootProfilePermissionPolicyRoleState = GetLootProfilePermissionPolicyRoleState,
  ApplyTrafficLight = ApplyTrafficLight,
  SetListButtonSelected = SetListButtonSelected,
  SetTextListButtonTextColor = SetTextListButtonTextColor,
  FlowLayoutControls = FlowLayoutControls,
  ClampLayoutValue = ClampLayoutValue,
  FormatLootProfileRoleLabel = FormatLootProfileRoleLabel,
})

RefreshRoleSimulationView = lootSessionRoleSimHelpers.RefreshRoleSimulationView
LayoutRoleSimulationSection = lootSessionRoleSimHelpers.LayoutRoleSimulationSection
SIMULATION_ROLE_OPTIONS = lootSessionRoleSimHelpers.SIMULATION_ROLE_OPTIONS or {}
ROLE_SIM_RIGHTS_MATRIX = lootSessionRoleSimHelpers.ROLE_SIM_RIGHTS_MATRIX or {}

local CreateLootSessionAutoPassHelpers = INTERNAL_API.LIDCOUNCIL_CreateLootSessionAutoPassHelpers_Impl
if type(CreateLootSessionAutoPassHelpers) ~= "function" then
  error("LidCouncil missing loot session auto pass helpers.")
end

local lootSessionAutoPassHelpers = CreateLootSessionAutoPassHelpers({
  TrimText = TrimText,
  ResolveOptionalApiFunction = ResolveOptionalApiFunction,
})

RefreshAutoPassView = lootSessionAutoPassHelpers.RefreshAutoPassView
LayoutAutoPassSection = lootSessionAutoPassHelpers.LayoutAutoPassSection

local function BuildLootSessionPage(editor, page)
  if not editor or not page then
    return
  end

  local navBg, rightBg = CreateSectionShell(page, 220)
  editor.lootSessionNavBg = navBg
  editor.lootSessionRightBg = rightBg

  local rightScroll = CreateFrame("ScrollFrame", nil, rightBg, "UIPanelScrollFrameTemplate")
  rightScroll:SetPoint("TOPLEFT", 6, -6)
  rightScroll:SetPoint("BOTTOMRIGHT", -28, 6)
  rightScroll:EnableMouseWheel(true)
  if type(BindMouseWheelScroll) == "function" then
    BindMouseWheelScroll(rightScroll, 12)
  end
  local rightContent = CreateFrame("Frame", nil, rightScroll)
  rightContent:SetSize(1, 1)
  rightScroll:SetScrollChild(rightContent)
  editor.lootSessionRightScroll = rightScroll
  editor.lootSessionRightContent = rightContent

  local rightBg = rightContent

  local navTitle = navBg:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
  navTitle:SetPoint("TOPLEFT", 8, -8)
  navTitle:SetText("Session")

  local currentBtn = CreateFrame("Button", nil, navBg, "UIPanelButtonTemplate")
  currentBtn:SetSize(200, 22)
  currentBtn:SetPoint("TOPLEFT", 8, -34)
  currentBtn:SetText("Current Session")
  editor.sessionNavCurrentBtn = currentBtn

  local historyBtn = CreateFrame("Button", nil, navBg, "UIPanelButtonTemplate")
  historyBtn:SetSize(200, 22)
  historyBtn:SetPoint("TOPLEFT", 8, -62)
  historyBtn:SetText("Session History")
  editor.sessionNavHistoryBtn = historyBtn

  local syncMgmtBtn = CreateFrame("Button", nil, navBg, "UIPanelButtonTemplate")
  syncMgmtBtn:SetSize(200, 22)
  syncMgmtBtn:SetPoint("TOPLEFT", 8, -90)
  syncMgmtBtn:SetText("Sync Management")
  editor.sessionNavSyncManagementBtn = syncMgmtBtn

  local roleSimBtn = CreateFrame("Button", nil, navBg, "UIPanelButtonTemplate")
  roleSimBtn:SetSize(200, 22)
  roleSimBtn:SetPoint("TOPLEFT", 8, -118)
  roleSimBtn:SetText("Role Simulation")
  editor.sessionNavRoleSimBtn = roleSimBtn

  local autoPassSettingsBtn = CreateFrame("Button", nil, navBg, "UIPanelButtonTemplate")
  autoPassSettingsBtn:SetSize(200, 22)
  autoPassSettingsBtn:SetPoint("TOPLEFT", 8, -146)
  autoPassSettingsBtn:SetText("Auto Pass Setting")
  editor.sessionNavAutoPassSettingsBtn = autoPassSettingsBtn

  editor.lootSessionNavButtons = { currentBtn, historyBtn, syncMgmtBtn, roleSimBtn, autoPassSettingsBtn }

  local title = rightBg:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
  title:SetPoint("TOPLEFT", 18, -16)
  title:SetText("Current Session")
  editor.lootSessionTitle = title

  local statusIndicator = rightBg:CreateTexture(nil, "ARTWORK")
  statusIndicator:SetSize(10, 10)
  statusIndicator:SetPoint("TOPLEFT", 18, -48)
  editor.lootSessionStatusIndicator = statusIndicator

  local status = rightBg:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
  status:SetPoint("LEFT", statusIndicator, "RIGHT", 8, 0)
  status:SetJustifyH("LEFT")
  status:SetText("No active session")
  editor.lootSessionStatus = status

  local autoPassStatus = rightBg:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
  autoPassStatus:SetPoint("TOPLEFT", 18, -48)
  autoPassStatus:SetJustifyH("LEFT")
  autoPassStatus:SetText("")
  autoPassStatus:Hide()
  editor.lootSessionAutoPassStatus = autoPassStatus

  local startBtn = CreateFrame("Button", nil, rightBg, "UIPanelButtonTemplate")
  startBtn:SetSize(120, 22)
  startBtn:SetPoint("TOPLEFT", 18, -78)
  startBtn:SetText("Prepare Session")
  startBtn.__lid_customBg = { 0.24, 0.16, 0.04, 0.96 }
  startBtn.__lid_customHover = { 0.96, 0.72, 0.20, 0.26 }
  startBtn.__lid_customPushed = { 0.34, 0.22, 0.06, 0.98 }
  startBtn.__lid_customBorder = { 0.94, 0.68, 0.18, 0.96 }
  startBtn.__lid_customText = { 1.00, 0.95, 0.82, 1.00 }
  editor.sessionStartBtn = startBtn

  local activateBtn = CreateFrame("Button", nil, rightBg, "UIPanelButtonTemplate")
  activateBtn:SetSize(120, 22)
  activateBtn:SetPoint("LEFT", startBtn, "RIGHT", 10, 0)
  activateBtn:SetText("Start Session")
  activateBtn.__lid_customBg = { 0.05, 0.22, 0.12, 0.96 }
  activateBtn.__lid_customHover = { 0.22, 0.82, 0.42, 0.22 }
  activateBtn.__lid_customPushed = { 0.08, 0.32, 0.16, 0.98 }
  activateBtn.__lid_customBorder = { 0.24, 0.82, 0.38, 0.96 }
  activateBtn.__lid_customText = { 0.92, 1.00, 0.92, 1.00 }
  editor.sessionActivateBtn = activateBtn

  local stopBtn = CreateFrame("Button", nil, rightBg, "UIPanelButtonTemplate")
  stopBtn:SetSize(120, 22)
  stopBtn:SetPoint("LEFT", activateBtn, "RIGHT", 10, 0)
  stopBtn:SetText("Stop Session")
  stopBtn.__lid_customBg = { 0.07, 0.08, 0.10, 0.92 }
  stopBtn.__lid_customHover = { 0.88, 0.40, 0.32, 0.24 }
  stopBtn.__lid_customPushed = { 0.34, 0.10, 0.08, 0.98 }
  stopBtn.__lid_customBorder = { 0.48, 0.38, 0.34, 0.74 }
  stopBtn.__lid_customText = { 0.88, 0.90, 0.94, 1.00 }
  editor.sessionStopBtn = stopBtn

  local leaveBtn = CreateFrame("Button", nil, rightBg, "UIPanelButtonTemplate")
  leaveBtn:SetSize(120, 22)
  leaveBtn:SetPoint("LEFT", stopBtn, "RIGHT", 10, 0)
  leaveBtn:SetText("Leave Session")
  editor.sessionLeaveBtn = leaveBtn

  local inviteBtn = CreateFrame("Button", nil, rightBg, "UIPanelButtonTemplate")
  inviteBtn:SetSize(140, 22)
  inviteBtn:SetPoint("TOPRIGHT", -18, -78)
  inviteBtn:SetText("Send Invite")
  inviteBtn.__lid_customBg = { 0.05, 0.09, 0.16, 0.92 }
  inviteBtn.__lid_customHover = { 0.22, 0.48, 0.82, 0.18 }
  inviteBtn.__lid_customPushed = { 0.08, 0.16, 0.28, 0.98 }
  inviteBtn.__lid_customBorder = { 0.34, 0.58, 0.90, 0.90 }
  inviteBtn.__lid_customText = { 0.90, 0.96, 1.00, 1.00 }
  editor.sessionInviteBtn = inviteBtn

  editor.sessionRefreshReadinessBtn = CreateFrame("Button", nil, rightBg, "UIPanelButtonTemplate")
  editor.sessionRefreshReadinessBtn:SetSize(150, 22)
  editor.sessionRefreshReadinessBtn:SetPoint("RIGHT", inviteBtn, "LEFT", -10, 0)
  editor.sessionRefreshReadinessBtn:SetText("Refresh Readiness")
  editor.sessionRefreshReadinessBtn.__lid_customBg = { 0.05, 0.09, 0.16, 0.92 }
  editor.sessionRefreshReadinessBtn.__lid_customHover = { 0.22, 0.48, 0.82, 0.18 }
  editor.sessionRefreshReadinessBtn.__lid_customPushed = { 0.08, 0.16, 0.28, 0.98 }
  editor.sessionRefreshReadinessBtn.__lid_customBorder = { 0.34, 0.58, 0.90, 0.90 }
  editor.sessionRefreshReadinessBtn.__lid_customText = { 0.90, 0.96, 1.00, 1.00 }
  editor.sessionRefreshReadinessBtn:SetScript("OnEnter", function(self)
    if type(GameTooltip) ~= "table" then
      return
    end
    GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
    GameTooltip:ClearLines()
    GameTooltip:AddLine("Refresh Readiness", 1.00, 0.82, 0.28, true)
    GameTooltip:AddLine("Requests fresh compact Settings, Permissions, Loot, and Session proofs from every joined member, then republishes the host's recalculated Current Session matrix.", 0.92, 0.92, 0.96, true)
    GameTooltip:AddLine("This does not resend profile, Loot List, item-history, session-history, or Fun Awards payloads.", 0.42, 0.82, 1.00, true)
    GameTooltip:Show()
  end)
  editor.sessionRefreshReadinessBtn:SetScript("OnLeave", function()
    if type(GameTooltip) == "table" then
      GameTooltip:Hide()
    end
  end)
  local removeMemberBtn = CreateFrame("Button", nil, rightBg, "UIPanelButtonTemplate")
  removeMemberBtn:SetSize(150, 22)
  removeMemberBtn:SetPoint("RIGHT", inviteBtn, "LEFT", -10, 0)
  removeMemberBtn:SetText("Remove Member")
  removeMemberBtn.__lid_customBg = { 0.12, 0.07, 0.08, 0.92 }
  removeMemberBtn.__lid_customHover = { 0.92, 0.30, 0.30, 0.22 }
  removeMemberBtn.__lid_customPushed = { 0.40, 0.10, 0.10, 0.98 }
  removeMemberBtn.__lid_customBorder = { 0.72, 0.34, 0.34, 0.82 }
  removeMemberBtn.__lid_customText = { 1.00, 0.90, 0.90, 1.00 }
  editor.sessionRemoveMemberBtn = removeMemberBtn

  local function BindRepairAvailabilityTooltip(button, title)
    button:SetScript("OnEnter", function(self)
      local reason = tostring(self.__lidDisabledReason or "")
      if reason == "" or type(GameTooltip) ~= "table" then
        return
      end
      GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
      GameTooltip:ClearLines()
      GameTooltip:AddLine(title, 1.00, 0.82, 0.28, true)
      GameTooltip:AddLine(reason, 0.92, 0.92, 0.96, true)
      GameTooltip:Show()
    end)
    button:SetScript("OnLeave", function()
      if type(GameTooltip) == "table" then
        GameTooltip:Hide()
      end
    end)
  end

  local pushProfileBtn = CreateFrame("Button", nil, rightBg, "UIPanelButtonTemplate")
  pushProfileBtn:SetSize(184, 22)
  pushProfileBtn:SetPoint("LEFT", removeMemberBtn, "RIGHT", 10, 0)
  pushProfileBtn:SetText("Push Host Repair")
  BindRepairAvailabilityTooltip(pushProfileBtn, "Push Host Repair")
  editor.sessionPushProfileBtn = pushProfileBtn

  local pushHostSessionDataBtn = CreateFrame("Button", nil, rightBg, "UIPanelButtonTemplate")
  pushHostSessionDataBtn:SetSize(210, 22)
  pushHostSessionDataBtn:SetText("Send Host Session Data")
  pushHostSessionDataBtn:SetScript("OnEnter", function(self)
    if type(GameTooltip) ~= "table" then
      return
    end
    GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
    GameTooltip:ClearLines()
    GameTooltip:AddLine("Send Host Session Data", 1.00, 0.82, 0.28, true)
    GameTooltip:AddLine("Sends the selected member the host's Session Data in the background archive lane.", 0.92, 0.92, 0.96, true)
    GameTooltip:AddLine("This includes Session History and saved Live Board history. It does not replace Settings, Permissions, or Loot List data.", 0.92, 0.92, 0.96, true)
    GameTooltip:AddLine("It does not repair P2 Current Session State. Use Refresh Readiness to republish and request fresh P2 proof.", 0.40, 0.72, 1.00, true)
    GameTooltip:AddLine("Use it only when the host copy is authoritative; it intentionally bypasses the coarse member-newer recommendation.", 1.00, 0.72, 0.42, true)
    GameTooltip:Show()
  end)
  pushHostSessionDataBtn:SetScript("OnLeave", function()
    if type(GameTooltip) == "table" then
      GameTooltip:Hide()
    end
  end)
  editor.sessionPushHostSessionDataBtn = pushHostSessionDataBtn

  local checkSyncBtn = CreateFrame("Button", nil, rightBg, "UIPanelButtonTemplate")
  checkSyncBtn:SetSize(190, 22)
  checkSyncBtn:SetText("Load Precise Differences")
  editor.sessionCheckSyncBtn = checkSyncBtn

  local profileSyncDropdown = CreateCustomDropdownControl(editor, rightBg, {
    width = 320,
    buttonHeight = 22,
    text = "No member update review needed",
    maxVisibleEntries = 12,
  })
  editor.sessionProfileSyncMemberDropdown = profileSyncDropdown

  local requestProfileBtn = CreateFrame("Button", nil, rightBg, "UIPanelButtonTemplate")
  requestProfileBtn:SetSize(184, 22)
  requestProfileBtn:SetText("Pull Member Repair")
  BindRepairAvailabilityTooltip(requestProfileBtn, "Pull Member Repair")
  editor.sessionRequestProfileBtn = requestProfileBtn

  local recommendedRepairBtn = CreateFrame("Button", nil, rightBg, "UIPanelButtonTemplate")
  recommendedRepairBtn:SetSize(260, 22)
  recommendedRepairBtn:SetText("Run Recommended Repair")
  recommendedRepairBtn:Hide()
  editor.sessionRecommendedRepairBtn = recommendedRepairBtn

  local previewProfileBtn = CreateFrame("Button", nil, rightBg, "UIPanelButtonTemplate")
  previewProfileBtn:SetSize(190, 22)
  previewProfileBtn:SetText("Preview Member Repair")
  BindRepairAvailabilityTooltip(previewProfileBtn, "Preview Differences")
  editor.sessionPreviewProfileBtn = previewProfileBtn

  local openSyncDetailBtn = CreateFrame("Button", nil, rightBg, "UIPanelButtonTemplate")
  openSyncDetailBtn:SetSize(250, 22)
  openSyncDetailBtn:SetText("Preview Required")
  openSyncDetailBtn:Disable()
  editor.sessionOpenSyncDetailBtn = openSyncDetailBtn

  local profileSyncSelectedHint = rightBg:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  profileSyncSelectedHint:SetJustifyH("LEFT")
  profileSyncSelectedHint:SetText("")
  editor.lootSessionSyncSelectedHint = profileSyncSelectedHint

  local profileSyncStatus = rightBg:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  profileSyncStatus:SetJustifyH("LEFT")
  profileSyncStatus:SetText("")
  editor.lootSessionProfileSyncStatus = profileSyncStatus

  local syncProgress = rightBg:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  syncProgress:SetJustifyH("LEFT")
  syncProgress:SetText("")
  editor.lootSessionSyncProgress = syncProgress

  local syncBoardBtn = CreateFrame("Button", nil, rightBg, "UIPanelButtonTemplate")
  syncBoardBtn:SetSize(126, 22)
  syncBoardBtn:SetPoint("TOPRIGHT", -18, -142)
  syncBoardBtn:SetText("Send Board Sync")
  syncBoardBtn:Hide()
  editor.sessionSyncBoardBtn = syncBoardBtn

  local liveSummary = rightBg:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  liveSummary:SetPoint("TOPLEFT", 18, -106)
  liveSummary:SetWidth(560)
  liveSummary:SetJustifyH("LEFT")
  liveSummary:SetText("")
  editor.lootSessionLiveSummary = liveSummary

  local overviewFrame = CreateFrame("Frame", nil, rightBg, "BackdropTemplate")
  ApplyFrameSkin(overviewFrame)
  overviewFrame:EnableMouse(true)
  overviewFrame:SetScript("OnEnter", function(frame)
    local exactTime = TrimText(frame.__lidSessionExactTime)
    if exactTime == "" or not GameTooltip then
      return
    end
    GameTooltip:SetOwner(frame, "ANCHOR_RIGHT")
    GameTooltip:SetText("Session Timing", 1.00, 0.82, 0.28, 1.00)
    GameTooltip:AddDoubleLine("Exact time", exactTime, 0.82, 0.86, 0.92, 0.92, 0.94, 0.98)
    GameTooltip:Show()
  end)
  overviewFrame:SetScript("OnLeave", function()
    if GameTooltip then
      GameTooltip:Hide()
    end
  end)
  editor.lootSessionOverviewFrame = overviewFrame

  local overviewTitle = overviewFrame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
  overviewTitle:SetPoint("TOPLEFT", 14, -12)
  overviewTitle:SetJustifyH("LEFT")
  editor.lootSessionOverviewTitle = overviewTitle

  local overviewMeta = overviewFrame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  overviewMeta:SetPoint("TOPLEFT", 14, -34)
  overviewMeta:SetJustifyH("LEFT")
  editor.lootSessionOverviewMeta = overviewMeta

  editor.lootSessionOverviewCards = {}
  for _, label in ipairs({ "Profile", "Role", "Session Start", "Members", "Host", "Roll Ready", "Session Sync" }) do
    local card = CreateFrame("Frame", nil, overviewFrame, "BackdropTemplate")
    ApplyFrameSkin(card)
    local valueText = card:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    valueText:SetPoint("TOPLEFT", 10, -30)
    valueText:SetJustifyH("LEFT")
    local labelText = card:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    labelText:SetPoint("TOPLEFT", 10, -10)
    labelText:SetJustifyH("LEFT")
    labelText:SetText(string.upper(label))
    labelText.__lid_customTextColor = { 0.66, 0.70, 0.76, 1.00 }
    labelText:SetTextColor(0.66, 0.70, 0.76, 1.00)
    local dot = card:CreateTexture(nil, "ARTWORK")
    dot:SetSize(8, 8)
    dot:SetPoint("TOPRIGHT", -10, -32)
    dot:Hide()
    editor.lootSessionOverviewCards[#editor.lootSessionOverviewCards + 1] = {
      frame = card,
      valueText = valueText,
      labelText = labelText,
      dot = dot,
      label = label,
    }
  end

  local currentMembersHeader = MakeYellowSubHeader(rightBg, "Joined Members", 18, -240)
  editor.lootSessionMembersHeader = currentMembersHeader

  local membersLegend = rightBg:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  membersLegend:SetJustifyH("LEFT")
  membersLegend:SetText("P1: roll-ready (required) | P2: session continuity | P3: background archive")
  membersLegend.__lid_customTextColor = { 0.64, 0.70, 0.78, 1.00 }
  membersLegend:SetTextColor(0.64, 0.70, 0.78, 1.00)
  editor.lootSessionMembersLegend = membersLegend

  local memberColumns = CreateFrame("Frame", nil, rightBg, "BackdropTemplate")
  ApplyFrameSkin(memberColumns)
  if memberColumns.SetBackdropColor then
    memberColumns:SetBackdropColor(0.06, 0.06, 0.08, 0.98)
  end
  editor.lootSessionMemberColumns = memberColumns
  local memberHeaderName = memberColumns:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
  memberHeaderName:SetJustifyH("LEFT")
  memberHeaderName:SetText("Raider")
  editor.lootSessionMemberHeaderName = memberHeaderName
  local memberHeaderSync = memberColumns:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
  memberHeaderSync:SetJustifyH("LEFT")
  memberHeaderSync:SetText("Sync")
  editor.lootSessionMemberHeaderSync = memberHeaderSync
  local memberHeaderAutoPass = memberColumns:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
  memberHeaderAutoPass:SetJustifyH("LEFT")
  memberHeaderAutoPass:SetText("Auto-Pass")
  editor.lootSessionMemberHeaderAutoPass = memberHeaderAutoPass
  local memberHeaderVersion = memberColumns:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
  memberHeaderVersion:SetJustifyH("LEFT")
  memberHeaderVersion:SetText("Version")
  editor.lootSessionMemberHeaderVersion = memberHeaderVersion
  local memberHeaderStatus = memberColumns:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
  memberHeaderStatus:SetJustifyH("LEFT")
  memberHeaderStatus:SetText("P1 Ready")
  editor.lootSessionMemberHeaderStatus = memberHeaderStatus
  local memberHeaderPriority3 = memberColumns:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
  memberHeaderPriority3:SetJustifyH("LEFT")
  memberHeaderPriority3:SetText("P3 Background")
  editor.lootSessionMemberHeaderPriority3 = memberHeaderPriority3
  editor.lootSessionMemberHeaderItemHistory = memberColumns:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
  editor.lootSessionMemberHeaderItemHistory:SetJustifyH("CENTER")
  editor.lootSessionMemberHeaderItemHistory:SetText("Items")
  editor.lootSessionMemberHeaderSessionHistory = memberColumns:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
  editor.lootSessionMemberHeaderSessionHistory:SetJustifyH("CENTER")
  editor.lootSessionMemberHeaderSessionHistory:SetText("Sessions")
  editor.lootSessionMemberHeaderFunAwards = memberColumns:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
  editor.lootSessionMemberHeaderFunAwards:SetJustifyH("CENTER")
  editor.lootSessionMemberHeaderFunAwards:SetText("Awards")
  local memberHeaderJoined = memberColumns:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
  memberHeaderJoined:SetJustifyH("LEFT")
  memberHeaderJoined:SetText("Joined")
  editor.lootSessionMemberHeaderJoined = memberHeaderJoined
  memberHeaderName.__lid_customTextColor = { 0.76, 0.72, 0.56, 1.00 }
  memberHeaderName:SetTextColor(0.76, 0.72, 0.56, 1.00)
  memberHeaderSync.__lid_customTextColor = { 0.76, 0.72, 0.56, 1.00 }
  memberHeaderSync:SetTextColor(0.76, 0.72, 0.56, 1.00)
  memberHeaderAutoPass.__lid_customTextColor = { 0.76, 0.72, 0.56, 1.00 }
  memberHeaderAutoPass:SetTextColor(0.76, 0.72, 0.56, 1.00)
  memberHeaderVersion.__lid_customTextColor = { 0.76, 0.72, 0.56, 1.00 }
  memberHeaderVersion:SetTextColor(0.76, 0.72, 0.56, 1.00)
  memberHeaderStatus.__lid_customTextColor = { 0.76, 0.72, 0.56, 1.00 }
  memberHeaderStatus:SetTextColor(0.76, 0.72, 0.56, 1.00)
  memberHeaderPriority3.__lid_customTextColor = { 0.76, 0.72, 0.56, 1.00 }
  memberHeaderPriority3:SetTextColor(0.76, 0.72, 0.56, 1.00)
  editor.lootSessionMemberHeaderItemHistory.__lid_customTextColor = { 0.76, 0.72, 0.56, 1.00 }
  editor.lootSessionMemberHeaderItemHistory:SetTextColor(0.76, 0.72, 0.56, 1.00)
  editor.lootSessionMemberHeaderSessionHistory.__lid_customTextColor = { 0.76, 0.72, 0.56, 1.00 }
  editor.lootSessionMemberHeaderSessionHistory:SetTextColor(0.76, 0.72, 0.56, 1.00)
  editor.lootSessionMemberHeaderFunAwards.__lid_customTextColor = { 0.76, 0.72, 0.56, 1.00 }
  editor.lootSessionMemberHeaderFunAwards:SetTextColor(0.76, 0.72, 0.56, 1.00)
  memberHeaderJoined.__lid_customTextColor = { 0.76, 0.72, 0.56, 1.00 }
  memberHeaderJoined:SetTextColor(0.76, 0.72, 0.56, 1.00)

  local memberRowsFrame = CreateFrame("Frame", nil, rightBg)
  editor.lootSessionMemberRowsFrame = memberRowsFrame
  editor.lootSessionMemberRows = {}

  local historyHeader = MakeYellowSubHeader(rightBg, "Session History", 18, -78)
  editor.lootSessionHistoryHeader = historyHeader

  local historyColumns = CreateFrame("Frame", nil, rightBg, "BackdropTemplate")
  ApplyFrameSkin(historyColumns)
  if historyColumns.SetBackdropColor then
    historyColumns:SetBackdropColor(0.06, 0.06, 0.08, 0.98)
  end
  editor.lootSessionHistoryColumns = historyColumns

  local historyHeaderStarted = historyColumns:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
  historyHeaderStarted:SetJustifyH("LEFT")
  historyHeaderStarted:SetText("Started")
  editor.lootSessionHistoryHeaderStarted = historyHeaderStarted

  local historyHeaderHost = historyColumns:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
  historyHeaderHost:SetJustifyH("LEFT")
  historyHeaderHost:SetText("Host")
  editor.lootSessionHistoryHeaderHost = historyHeaderHost

  local historyHeaderMembers = historyColumns:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
  historyHeaderMembers:SetJustifyH("LEFT")
  historyHeaderMembers:SetText("Members")
  editor.lootSessionHistoryHeaderMembers = historyHeaderMembers

  local historyHeaderSource = historyColumns:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
  historyHeaderSource:SetJustifyH("LEFT")
  historyHeaderSource:SetText("Source")
  editor.lootSessionHistoryHeaderSource = historyHeaderSource

  local historyHeaderResult = historyColumns:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
  historyHeaderResult:SetJustifyH("LEFT")
  historyHeaderResult:SetText("Result")
  editor.lootSessionHistoryHeaderResult = historyHeaderResult

  local historyRowsFrame = CreateFrame("Frame", nil, rightBg)
  editor.lootSessionHistoryRowsFrame = historyRowsFrame
  editor.lootSessionHistoryRows = {}
  editor.lootSessionHistoryExpanded = editor.lootSessionHistoryExpanded or {}

  local historyPrevBtn = CreateFrame("Button", nil, rightBg, "UIPanelButtonTemplate")
  historyPrevBtn:SetSize(60, 20)
  historyPrevBtn:SetText("< Prev")
  historyPrevBtn:Hide()
  editor.sessionHistoryPrevBtn = historyPrevBtn

  local historyPageText = rightBg:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  historyPageText:SetJustifyH("CENTER")
  historyPageText:SetText("")
  historyPageText:Hide()
  editor.lootSessionHistoryPageText = historyPageText

  local historyNextBtn = CreateFrame("Button", nil, rightBg, "UIPanelButtonTemplate")
  historyNextBtn:SetSize(60, 20)
  historyNextBtn:SetText("Next >")
  historyNextBtn:Hide()
  editor.sessionHistoryNextBtn = historyNextBtn

  local roleSimHeader = MakeYellowSubHeader(rightBg, "Role Simulation", 18, -78)
  editor.lootSessionRoleSimHeader = roleSimHeader

  local roleSimDesc = rightBg:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  roleSimDesc:SetJustifyH("LEFT")
  roleSimDesc:SetText("")
  editor.lootSessionRoleSimDesc = roleSimDesc

  local roleSimCurrent = rightBg:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
  roleSimCurrent:SetJustifyH("LEFT")
  roleSimCurrent:SetText("")
  editor.lootSessionRoleSimCurrent = roleSimCurrent

  local roleSimMasterBtn = CreateFrame("Button", nil, rightBg, "UIPanelButtonTemplate")
  roleSimMasterBtn:SetSize(120, 22)
  roleSimMasterBtn:SetText("Master")
  editor.sessionRoleSimMasterBtn = roleSimMasterBtn

  local roleSimCouncilBtn = CreateFrame("Button", nil, rightBg, "UIPanelButtonTemplate")
  roleSimCouncilBtn:SetSize(140, 22)
  roleSimCouncilBtn:SetText("Council Member")
  editor.sessionRoleSimCouncilBtn = roleSimCouncilBtn

  local roleSimSessionHostBtn = CreateFrame("Button", nil, rightBg, "UIPanelButtonTemplate")
  roleSimSessionHostBtn:SetSize(130, 22)
  roleSimSessionHostBtn:SetText("Session Host")
  editor.sessionRoleSimSessionHostBtn = roleSimSessionHostBtn

  local roleSimRaiderBtn = CreateFrame("Button", nil, rightBg, "UIPanelButtonTemplate")
  roleSimRaiderBtn:SetSize(120, 22)
  roleSimRaiderBtn:SetText("Raider")
  editor.sessionRoleSimRaiderBtn = roleSimRaiderBtn

  local roleSimState = rightBg:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  roleSimState:SetJustifyH("LEFT")
  roleSimState:SetText("")
  editor.lootSessionRoleSimState = roleSimState

  local roleSimMatrixFrame = CreateFrame("Frame", nil, rightBg)
  editor.lootSessionRoleSimMatrixFrame = roleSimMatrixFrame

  local roleSimMatrixHeader = CreateFrame("Frame", nil, roleSimMatrixFrame)
  editor.lootSessionRoleSimMatrixHeader = roleSimMatrixHeader

  local matrixHeaderRight = roleSimMatrixHeader:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
  matrixHeaderRight:SetJustifyH("LEFT")
  matrixHeaderRight:SetText("Rights")
  editor.lootSessionRoleSimHeaderRight = matrixHeaderRight

  local matrixHeaderMaster = roleSimMatrixHeader:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
  matrixHeaderMaster:SetJustifyH("CENTER")
  matrixHeaderMaster:SetText("Master")
  editor.lootSessionRoleSimHeaderMaster = matrixHeaderMaster

  local matrixHeaderSessionHost = roleSimMatrixHeader:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
  matrixHeaderSessionHost:SetJustifyH("CENTER")
  matrixHeaderSessionHost:SetText("Session Host")
  editor.lootSessionRoleSimHeaderSessionHost = matrixHeaderSessionHost

  local matrixHeaderCouncil = roleSimMatrixHeader:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
  matrixHeaderCouncil:SetJustifyH("CENTER")
  matrixHeaderCouncil:SetText("Council")
  editor.lootSessionRoleSimHeaderCouncil = matrixHeaderCouncil

  local matrixHeaderRaider = roleSimMatrixHeader:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
  matrixHeaderRaider:SetJustifyH("CENTER")
  matrixHeaderRaider:SetText("Raider")
  editor.lootSessionRoleSimHeaderRaider = matrixHeaderRaider

  editor.lootSessionRoleSimMatrixRows = {}
  for _, rowDef in ipairs(ROLE_SIM_RIGHTS_MATRIX) do
    local row = CreateFrame("Frame", nil, roleSimMatrixFrame, "BackdropTemplate")
    ApplyFrameSkin(row)
    row.__isRoleSimSection = rowDef.section and true or false
    if row.SetBackdropColor then
      if row.__isRoleSimSection then
        row:SetBackdropColor(0, 0, 0, 0)
      else
        row:SetBackdropColor(0.05, 0.05, 0.07, 0.94)
      end
    end
    if row.__isRoleSimSection and row.SetBackdropBorderColor then
      row:SetBackdropBorderColor(0, 0, 0, 0)
    end
    local rightText = row:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    rightText:SetJustifyH("LEFT")
    rightText:SetText(rowDef.section or rowDef.right)
    local masterText = row:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    masterText:SetJustifyH("CENTER")
    local sessionHostText = row:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    sessionHostText:SetJustifyH("CENTER")
    local councilText = row:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    councilText:SetJustifyH("CENTER")
    local raiderText = row:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    raiderText:SetJustifyH("CENTER")
    row.masterText = masterText
    row.sessionHostText = sessionHostText
    row.councilText = councilText
    row.raiderText = raiderText
    row.rightText = rightText
    row.definition = rowDef
    editor.lootSessionRoleSimMatrixRows[#editor.lootSessionRoleSimMatrixRows + 1] = row
  end

  local autoPassHeader = MakeYellowSubHeader(rightBg, "Auto Pass Setting", 18, -78)
  editor.lootSessionAutoPassHeader = autoPassHeader

  local autoPassDesc = rightBg:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  autoPassDesc:SetJustifyH("LEFT")
  autoPassDesc:SetText("")
  editor.lootSessionAutoPassDesc = autoPassDesc

  local autoPassCurrent = rightBg:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
  autoPassCurrent:SetJustifyH("LEFT")
  autoPassCurrent:SetText("")
  editor.lootSessionAutoPassCurrent = autoPassCurrent

  local autoPassLocalBtn = CreateFrame("Button", nil, rightBg, "UIPanelButtonTemplate")
  autoPassLocalBtn:SetSize(190, 22)
  autoPassLocalBtn:SetText("Deactivate Auto-Pass")
  editor.sessionAutoPassLocalBtn = autoPassLocalBtn

  local autoPassIcon = rightBg:CreateTexture(nil, "ARTWORK")
  autoPassIcon:SetSize(28, 30)
  autoPassIcon:SetTexture("Interface\\AddOns\\LidCouncil\\Media\\LidCouncil\\Logos\\LidCouncil_Autopass_Off.tga")
  autoPassIcon:Hide()
  editor.lootSessionAutoPassIcon = autoPassIcon

  local autoPassState = rightBg:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  autoPassState:SetJustifyH("LEFT")
  autoPassState:SetText("")
  editor.lootSessionAutoPassState = autoPassState

  local syncCheckHeader = MakeYellowSubHeader(rightBg, "1. Check Differences", 18, -78)
  editor.lootSessionSyncCheckHeader = syncCheckHeader

  local syncIntro = rightBg:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  syncIntro:SetJustifyH("LEFT")
  syncIntro:SetText("")
  editor.lootSessionSyncIntro = syncIntro

  local syncPushHeader = MakeYellowSubHeader(rightBg, "2. Repair From Host", 18, -78)
  editor.lootSessionSyncPushHeader = syncPushHeader

  local syncPullHeader = MakeYellowSubHeader(rightBg, "3. Pull Repair From Member", 18, -78)
  editor.lootSessionSyncPullHeader = syncPullHeader

  local syncResolveHeader = MakeYellowSubHeader(rightBg, "4. Resolve Preview", 18, -78)
  editor.lootSessionSyncResolveHeader = syncResolveHeader

  local syncAdvancedHeader = MakeYellowSubHeader(rightBg, "Advanced Repairs and Recovery", 18, -78)
  editor.lootSessionSyncAdvancedHeader = syncAdvancedHeader

  local syncAutoHeader = MakeYellowSubHeader(rightBg, "Automatic Syncs", 18, -78)
  editor.lootSessionSyncAutoHeader = syncAutoHeader

  local syncAutoText = rightBg:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  syncAutoText:SetJustifyH("LEFT")
  syncAutoText:SetText("")
  editor.lootSessionSyncAutoText = syncAutoText

  local syncManualHeader = MakeYellowSubHeader(rightBg, "Manual Syncs", 18, -78)
  editor.lootSessionSyncManualHeader = syncManualHeader

  local syncManualText = rightBg:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  syncManualText:SetJustifyH("LEFT")
  syncManualText:SetText("")
  editor.lootSessionSyncManualText = syncManualText

  local syncReviewHeader = MakeYellowSubHeader(rightBg, "Joined Copy Status", 18, -78)
  editor.lootSessionSyncReviewHeader = syncReviewHeader

  local syncReviewColumns = CreateFrame("Frame", nil, rightBg, "BackdropTemplate")
  ApplyFrameSkin(syncReviewColumns)
  if syncReviewColumns.SetBackdropColor then
    syncReviewColumns:SetBackdropColor(0.06, 0.06, 0.08, 0.98)
  end
  editor.lootSessionSyncReviewColumns = syncReviewColumns

  local syncReviewHeaderMember = syncReviewColumns:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
  syncReviewHeaderMember:SetJustifyH("LEFT")
  syncReviewHeaderMember:SetText("Member")
  editor.lootSessionSyncReviewHeaderMember = syncReviewHeaderMember

  local syncReviewHeaderState = syncReviewColumns:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
  syncReviewHeaderState:SetJustifyH("LEFT")
  syncReviewHeaderState:SetText("State")
  editor.lootSessionSyncReviewHeaderState = syncReviewHeaderState

  local syncReviewHeaderRemote = syncReviewColumns:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
  syncReviewHeaderRemote:SetJustifyH("LEFT")
  syncReviewHeaderRemote:SetText("Member Newer")
  editor.lootSessionSyncReviewHeaderRemote = syncReviewHeaderRemote

  local syncReviewHeaderLocal = syncReviewColumns:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
  syncReviewHeaderLocal:SetJustifyH("LEFT")
  syncReviewHeaderLocal:SetText("Host Newer")
  editor.lootSessionSyncReviewHeaderLocal = syncReviewHeaderLocal

  local syncReviewHeaderUpdated = syncReviewColumns:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
  syncReviewHeaderUpdated:SetJustifyH("LEFT")
  syncReviewHeaderUpdated:SetText("Last Change")
  editor.lootSessionSyncReviewHeaderUpdated = syncReviewHeaderUpdated

  local syncReviewHeaderSession = syncReviewColumns:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
  syncReviewHeaderSession:SetJustifyH("LEFT")
  syncReviewHeaderSession:SetText("Session")
  editor.lootSessionSyncReviewHeaderSession = syncReviewHeaderSession

  local syncReviewRowsFrame = CreateFrame("Frame", nil, rightBg)
  editor.lootSessionSyncReviewRowsFrame = syncReviewRowsFrame
  editor.lootSessionSyncReviewRows = {}

  local syncReviewEmpty = rightBg:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  syncReviewEmpty:SetJustifyH("LEFT")
  syncReviewEmpty:SetText("")
  editor.lootSessionSyncReviewEmpty = syncReviewEmpty

  local body = rightBg:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  body:SetPoint("TOPLEFT", 18, -132)
  body:SetWidth(560)
  body:SetJustifyH("LEFT")
  body:SetText("")
  editor.lootSessionBody = body

  local inactiveOverlay = CreateFrame("Frame", nil, page, "BackdropTemplate")
  ApplyFrameSkin(inactiveOverlay)
  inactiveOverlay:SetPoint("TOPLEFT", page, "TOPLEFT", 0, 0)
  inactiveOverlay:SetPoint("BOTTOMRIGHT", page, "BOTTOMRIGHT", 0, 0)
  inactiveOverlay:EnableMouse(true)
  inactiveOverlay:SetFrameStrata("HIGH")
  inactiveOverlay:SetFrameLevel((page.GetFrameLevel and page:GetFrameLevel() or 0) + 20)
  inactiveOverlay:Hide()
  editor.lootSessionInactiveOverlay = inactiveOverlay

  local inactiveText = inactiveOverlay:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
  inactiveText:SetPoint("CENTER", 0, 0)
  inactiveText:SetWidth(520)
  inactiveText:SetJustifyH("CENTER")
  inactiveText:SetJustifyV("MIDDLE")
  inactiveText:SetText(ACTIVATE_PROFILE_REQUIRED_TEXT)
  editor.lootSessionInactiveText = inactiveText

  page.__contentHeight = 720

  local function LayoutLootSessionPage(self)
    if not self or not self.lootSessionRightBg then
      return
    end

    local _, navWidth = GetResponsiveSectionLayout(page, 220, 180, 260, 0.26)
    local rightViewportWidth = math.floor((self.lootSessionRightScroll and self.lootSessionRightScroll.GetWidth and self.lootSessionRightScroll:GetWidth()) or ((self.lootSessionRightBg:GetWidth() or 620) - 34))
    if rightViewportWidth < 320 then
      rightViewportWidth = math.floor((self.lootSessionRightBg:GetWidth() or 620) - 34)
    end
    local rightContentWidth = math.max(300, rightViewportWidth - 36)
    local rightViewportHeight = math.floor((self.lootSessionRightScroll and self.lootSessionRightScroll.GetHeight and self.lootSessionRightScroll:GetHeight()) or ((self.lootSessionRightBg:GetHeight() or 520) - 12))
    if rightViewportHeight < 220 then
      rightViewportHeight = math.floor((self.lootSessionRightBg:GetHeight() or 520) - 12)
    end
    local section = self.lootSessionSection or "CURRENT"
    local showingCurrent = (section == "CURRENT")
    local showingSyncManagement = (section == "SYNCMGMT")
    local showingRoleSimulation = (section == "ROLESIM")
    local isSimulationProfile = TrimText(GetSessionContextProfileName()) == "Simulation"
    local contentBottom = 180

    if self.lootSessionNavBg then
      self.lootSessionNavBg:SetWidth(navWidth)
    end
    if self.sessionNavCurrentBtn then self.sessionNavCurrentBtn:Show() end
    if self.sessionNavHistoryBtn then self.sessionNavHistoryBtn:Show() end
    if self.sessionNavSyncManagementBtn then self.sessionNavSyncManagementBtn:Show() end
    if self.sessionNavRoleSimBtn then self.sessionNavRoleSimBtn:SetShown(isSimulationProfile) end
    if self.sessionNavAutoPassSettingsBtn then self.sessionNavAutoPassSettingsBtn:Show() end
    local navTop = -34
    for _, button in ipairs({
      self.sessionNavCurrentBtn,
      self.sessionNavHistoryBtn,
      self.sessionNavSyncManagementBtn,
      isSimulationProfile and self.sessionNavRoleSimBtn or nil,
      self.sessionNavAutoPassSettingsBtn,
    }) do
      if button then
        button:SetSize(navWidth - 16, 22)
        button:ClearAllPoints()
        button:SetPoint("TOPLEFT", 8, navTop)
        navTop = navTop - 28
      end
    end
    if self.lootSessionLiveSummary then
      self.lootSessionLiveSummary:SetWidth(rightContentWidth)
    end
    if self.lootSessionBody then
      self.lootSessionBody:SetWidth(rightContentWidth)
    end
    if self.lootSessionStatus then
      self.lootSessionStatus:SetWidth(rightContentWidth - 38)
    end
    if self.lootSessionOverviewFrame then
      self.lootSessionOverviewFrame:SetWidth(rightContentWidth)
    end
    if self.lootSessionOverviewMeta then
      self.lootSessionOverviewMeta:SetWidth(rightContentWidth - 28)
    end
    if self.lootSessionSyncRepairInfoBtn then
      self.lootSessionSyncRepairInfoBtn:Hide()
    end
    if self.lootSessionSyncInlinePreviewFrame then
      self.lootSessionSyncInlinePreviewFrame:Hide()
    end
    if self.lootSessionSyncInlineResolverHost then
      self.lootSessionSyncInlineResolverHost:Hide()
    end
    if self.lootSessionSyncInlineConflictResolver then
      self.lootSessionSyncInlineConflictResolver:Hide()
    end

    if showingCurrent then
      contentBottom = LayoutCurrentSessionSection(self, page, rightContentWidth)
    elseif showingSyncManagement then
      if self.sessionRoleSimMasterBtn then self.sessionRoleSimMasterBtn:Hide() end
      if self.sessionRoleSimSessionHostBtn then self.sessionRoleSimSessionHostBtn:Hide() end
      if self.sessionRoleSimCouncilBtn then self.sessionRoleSimCouncilBtn:Hide() end
      if self.sessionRoleSimRaiderBtn then self.sessionRoleSimRaiderBtn:Hide() end
      contentBottom = LayoutSyncManagementSection(self, page, rightContentWidth)
    elseif showingRoleSimulation then
      contentBottom = LayoutRoleSimulationSection(self, page, rightContentWidth)
    elseif section == "AUTOPASS" then
      contentBottom = LayoutAutoPassSection(self, page, rightContentWidth)
    else
      if self.sessionSyncBoardBtn then
        self.sessionSyncBoardBtn:Hide()
      end
      local bodyTop = LayoutSessionHistorySection(self, rightContentWidth)
      if self.lootSessionBody then
        self.lootSessionBody:ClearAllPoints()
        self.lootSessionBody:SetPoint("TOPLEFT", 18, bodyTop)
      end
      local bodyHeight = math.max(40, math.ceil((self.lootSessionBody and self.lootSessionBody:IsShown() and self.lootSessionBody:GetStringHeight() or 0)))
      contentBottom = math.abs(bodyTop) + bodyHeight + 24
    end

    local contentHeight = math.max(420, contentBottom)
    if self.lootSessionRightContent then
      self.lootSessionRightContent:SetSize(math.max(1, rightViewportWidth), math.max(rightViewportHeight, contentHeight))
    end
    if self.lootSessionRightScroll and self.lootSessionRightScroll.UpdateScrollChildRect then
      self.lootSessionRightScroll:UpdateScrollChildRect()
    end
    page.__contentHeight = math.max(420, rightViewportHeight)
  end

  local function RefreshSessionView(sectionOverride)
    local targetedSection = string.upper(TrimText(sectionOverride or editor.lootSessionSection or ""))
    if editor.currentPage == "Panels"
      and editor.__refreshing ~= true
      and type(editor.RefreshLootSessionPage) == "function"
    then
      editor:RefreshLootSessionPage({
        lootSessionSections = {
          [targetedSection ~= "" and targetedSection or "CURRENT"] = true,
        },
      })
      if type(editor.ApplyTheme) == "function" then
        editor:ApplyTheme()
      end
      return
    end
    RequestLootSessionSectionRefresh(
      editor,
      targetedSection ~= "" and targetedSection or (editor.lootSessionSection or "CURRENT")
    )
  end

  local function SetSessionSection(section)
    editor.lootSessionSection = section
    RefreshSessionView(section)
  end

  currentBtn:SetScript("OnClick", function()
    SetSessionSection("CURRENT")
  end)
  historyBtn:SetScript("OnClick", function()
    SetSessionSection("HISTORY")
  end)
  historyPrevBtn:SetScript("OnClick", function()
    editor.lootSessionHistoryPage = math.max(1, (tonumber(editor.lootSessionHistoryPage) or 1) - 1)
    RefreshSessionView("HISTORY")
  end)
  historyNextBtn:SetScript("OnClick", function()
    local totalPages = math.max(1, tonumber(editor.lootSessionHistoryTotalPages) or 1)
    editor.lootSessionHistoryPage = math.min(totalPages, (tonumber(editor.lootSessionHistoryPage) or 1) + 1)
    RefreshSessionView("HISTORY")
  end)
  syncMgmtBtn:SetScript("OnClick", function()
    SetSessionSection("SYNCMGMT")
  end)
  roleSimBtn:SetScript("OnClick", function()
    SetSessionSection("ROLESIM")
  end)
  autoPassSettingsBtn:SetScript("OnClick", function()
    SetSessionSection("AUTOPASS")
  end)

  startBtn:SetScript("OnClick", function()
    if IsCombatLocked() then
      RefreshSessionView()
      return
    end
    local getSyntheticSessionContext = ResolveOptionalApiFunction("LIDCOUNCIL_GetDeveloperProfileSyncHarnessSessionContext")
    local syntheticContext = ReadLootSessionActionValue(editor, "Read synthetic session state", getSyntheticSessionContext, nil)
    if type(syntheticContext) == "table" and syntheticContext.active == true then
      local prepareSyntheticSession = ResolveOptionalApiFunction("LIDCOUNCIL_PrepareDeveloperProfileSyncHarnessSession")
      RunLootSessionAction(editor, "Prepare synthetic session", prepareSyntheticSession)
      RefreshSessionView()
      return
    end
    local profileName = ResolveRequiredSessionProfileName("Prepare Session")
    if not profileName then
      RefreshSessionView()
      return
    end
    if not GetLootProfileAccessInfo(profileName).canStartSession then
      return
    end
    local startFlow = ResolveOptionalApiFunction("LIDCOUNCIL_StartLootSessionFlow")
    if type(startFlow) == "function" then
      RunLootSessionAction(editor, "Prepare Session", startFlow, profileName)
      RefreshSessionView()
    else
      RunLootSessionAction(editor, "Prepare Session", StartLootSession, profileName)
      RefreshSessionView()
    end
  end)

  activateBtn:SetScript("OnClick", function()
    if IsCombatLocked() then
      RefreshSessionView()
      return
    end
    local getSyntheticSessionContext = ResolveOptionalApiFunction("LIDCOUNCIL_GetDeveloperProfileSyncHarnessSessionContext")
    local syntheticContext = ReadLootSessionActionValue(editor, "Read synthetic session state", getSyntheticSessionContext, nil)
    if type(syntheticContext) == "table" and syntheticContext.active == true then
      local activateSyntheticSession = ResolveOptionalApiFunction("LIDCOUNCIL_ActivateDeveloperProfileSyncHarnessSession")
      RunLootSessionAction(editor, "Start synthetic session", activateSyntheticSession)
      RefreshSessionView()
      return
    end
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or TrimText(profileName) == "" then
      RefreshSessionView()
      return
    end
    if not GetLootProfileAccessInfo(profileName).canStartSession then
      return
    end
    local activateFlow = ResolveOptionalApiFunction("LIDCOUNCIL_ActivatePreparedLootSessionFlow")
    if type(activateFlow) == "function" then
      RunLootSessionAction(editor, "Start Session", activateFlow)
      RefreshSessionView()
    else
      SetLootSessionActionStatusOverride(editor, "Start Session is unavailable.", { 1.00, 0.55, 0.44, 1.00 })
      RefreshSessionView()
    end
  end)

  stopBtn:SetScript("OnClick", function()
    if IsCombatLocked() then
      RefreshSessionView()
      return
    end
    local function ExecuteStopSession()
      if IsCombatLocked() then
        RefreshSessionView()
        return
      end
      local getSyntheticSessionContext = ResolveOptionalApiFunction("LIDCOUNCIL_GetDeveloperProfileSyncHarnessSessionContext")
      local syntheticContext = ReadLootSessionActionValue(editor, "Read synthetic session state", getSyntheticSessionContext, nil)
      if type(syntheticContext) == "table" and syntheticContext.active == true then
        local stopSyntheticSession = ResolveOptionalApiFunction("LIDCOUNCIL_StopDeveloperProfileSyncHarnessSession")
        RunLootSessionAction(editor, "Stop synthetic session", stopSyntheticSession)
        RefreshSessionView()
        return
      end
      local profileName = ResolveRequiredSessionProfileName("Stop Session")
      if not profileName then
        RefreshSessionView()
        return
      end
      if not GetLootProfileAccessInfo(profileName).canManageSession then
        return
      end
      local stopFlow = ResolveOptionalApiFunction("LIDCOUNCIL_StopLootSessionFlow")
      if type(stopFlow) == "function" then
        if not RunLootSessionAction(editor, "Stop Session", stopFlow) then
          RefreshSessionView()
        end
      else
        RunLootSessionAction(editor, "Stop Session", StopLootSession)
        RefreshSessionView()
      end
    end
    if type(StaticPopupDialogs) ~= "table" or type(StaticPopup_Show) ~= "function" then
      ExecuteStopSession()
      return
    end
    local activeSession = GetActiveLootSession()
    local closingLobby = type(activeSession) == "table" and string.upper(TrimText(activeSession.status)) == "PREPARING"
    local confirmationLabel = closingLobby and "Close Lobby" or "End Session"
    local confirmationText = closingLobby
      and "Close the LidCouncil preparation lobby?\n\nJoined members will be notified that the shared session has ended."
      or "End the active LidCouncil session?\n\nJoined members will be notified that the shared session has ended."
    if not StaticPopupDialogs.LIDCOUNCIL_STOP_SESSION_CONFIRM then
      StaticPopupDialogs.LIDCOUNCIL_STOP_SESSION_CONFIRM = {
        text = confirmationText,
        button1 = confirmationLabel,
        button2 = CANCEL,
        timeout = 0,
        whileDead = 1,
        hideOnEscape = 1,
        preferredIndex = 3,
        OnAccept = function(self, data)
          local action = data or self.data
          if type(action) == "table" and type(action.execute) == "function" then
            action.execute()
          end
        end,
      }
    end
    StaticPopupDialogs.LIDCOUNCIL_STOP_SESSION_CONFIRM.text = confirmationText
    StaticPopupDialogs.LIDCOUNCIL_STOP_SESSION_CONFIRM.button1 = confirmationLabel
    StaticPopup_Show("LIDCOUNCIL_STOP_SESSION_CONFIRM", nil, nil, { execute = ExecuteStopSession })
  end)

  inviteBtn:SetScript("OnClick", function()
    if IsCombatLocked() then
      RefreshSessionView()
      return
    end
    local profileName = ResolveRequiredSessionProfileName("Send Session Invite")
    if not profileName then
      RefreshSessionView()
      return
    end
    if not GetLootProfileAccessInfo(profileName).canManageSession then
      return
    end
    local sendInvites = ResolveOptionalApiFunction("LIDCOUNCIL_SendActiveSessionInviteFlow")
    if type(sendInvites) == "function" then
      if not RunLootSessionAction(editor, "Send Session Invite", sendInvites) then
        RefreshSessionView()
      end
    else
      SetLootSessionActionStatusOverride(editor, "Send Session Invite is unavailable.", { 1.00, 0.55, 0.44, 1.00 })
      RefreshSessionView()
    end
  end)

  editor.sessionRefreshReadinessBtn:SetScript("OnClick", function()
    local profileName = ResolveRequiredSessionProfileName("Refresh Readiness")
    if not profileName then
      RefreshSessionView()
      return
    end
    if not GetLootProfileAccessInfo(profileName).canManageSession then
      return
    end
    local refreshReadiness = ResolveOptionalApiFunction("LIDCOUNCIL_RefreshActiveSessionReadinessFlow")
    if type(refreshReadiness) == "function" then
      RunLootSessionAction(editor, "Refresh Readiness", refreshReadiness)
      RefreshSessionView("CURRENT")
    else
      SetLootSessionActionStatusOverride(editor, "Refresh Readiness is unavailable.", { 1.00, 0.55, 0.44, 1.00 })
      RefreshSessionView()
    end
  end)

  leaveBtn:SetScript("OnClick", function()
    if IsCombatLocked() then
      RefreshSessionView()
      return
    end
    local leaveFlow = ResolveOptionalApiFunction("LIDCOUNCIL_LeaveActiveSessionFlow")
    if type(leaveFlow) == "function" then
      if not RunLootSessionAction(editor, "Leave Session", leaveFlow) then
        RefreshSessionView()
      end
    else
      SetLootSessionActionStatusOverride(editor, "Leave Session is unavailable.", { 1.00, 0.55, 0.44, 1.00 })
      RefreshSessionView()
    end
    editor.lootSessionSelectedMemberKey = nil
  end)

  removeMemberBtn:SetScript("OnClick", function()
    if IsCombatLocked() then
      RefreshSessionView()
      return
    end
    local profileName = ResolveRequiredSessionProfileName("Remove Member")
    if not profileName then
      RefreshSessionView()
      return
    end
    if not GetLootProfileAccessInfo(profileName).canManageSession then
      return
    end
    local selectedMember = TrimText(editor.lootSessionSelectedMemberKey)
    if selectedMember == "" then
      return
    end
    local removeMember = ResolveOptionalApiFunction("LIDCOUNCIL_RemoveActiveSessionMemberFlow")
    if type(removeMember) == "function" then
      if not RunLootSessionAction(editor, "Remove Member", removeMember, selectedMember) then
        RefreshSessionView()
      end
    else
      SetLootSessionActionStatusOverride(editor, "Remove Member is unavailable.", { 1.00, 0.55, 0.44, 1.00 })
      RefreshSessionView()
    end
    editor.lootSessionSelectedMemberKey = nil
  end)

  pushProfileBtn:SetScript("OnClick", function()
    if IsCombatLocked() then
      RefreshSessionView()
      return
    end
    local profileName = ResolveRequiredSessionProfileName("Push Host Repair")
    if not profileName then
      RefreshSessionView()
      return
    end
    if not GetLootProfileAccessInfo(profileName).canManageSession then
      return
    end
    if type(editor.lootSessionSelectedSyncCandidate) == "table"
      and editor.lootSessionSelectedSyncCandidate.preciseNoDifferences == true
    then
      SetLootSessionActionStatusOverride(
        editor,
        "Precise comparison completed with no differing leaf scopes. No repair was sent; refresh the comparison or use the explicit Host Session Data action when replacement is intentional.",
        { 0.38, 0.90, 0.52, 1.00 }
      )
      RefreshSessionView()
      return
    end
    if type(editor.lootSessionSelectedSyncCandidate) == "table"
      and (TrimText(editor.lootSessionSelectedSyncCandidate.preciseRequestState) == "waiting"
        or TrimText(editor.lootSessionSelectedSyncCandidate.preciseRequestState) == "failed")
    then
      SetLootSessionActionStatusOverride(
        editor,
        TrimText(editor.lootSessionSelectedSyncCandidate.preciseRequestState) == "waiting"
          and "Precise comparison is still waiting for domain replies. No repair was sent."
          or "Precise comparison failed or timed out. Retry Precise Differences before sending a repair.",
        { 1.00, 0.72, 0.32, 1.00 }
      )
      RefreshSessionView()
      return
    end
    local pushProfileUpdate = ResolveOptionalApiFunction("LIDCOUNCIL_PushActiveProfileSnapshotFlow")
    local selectedScopeActions = type(editor.lootSessionSelectedScopeActions) == "table" and editor.lootSessionSelectedScopeActions.push or nil
    local targetMember = nil
    local options = nil
    if type(selectedScopeActions) == "table"
      and selectedScopeActions.selectionActive
      and selectedScopeActions.compatibleCount > 0 then
      targetMember = TrimText(selectedScopeActions.targetMemberKey)
      options = {
        domains = selectedScopeActions.domains,
        subdomains = selectedScopeActions.subdomains,
      }
    end
    if type(pushProfileUpdate) == "function" then
      if not RunLootSessionAction(editor, "Push Host Repair", pushProfileUpdate, targetMember, options) then
        RefreshSessionView()
      end
    else
      SetLootSessionActionStatusOverride(editor, "Push Host Repair is unavailable.", { 1.00, 0.55, 0.44, 1.00 })
      RefreshSessionView()
    end
  end)

  pushHostSessionDataBtn:SetScript("OnClick", function()
    if IsCombatLocked() then
      RefreshSessionView()
      return
    end
    local profileName = ResolveRequiredSessionProfileName("Send Host Session Data")
    if not profileName then
      RefreshSessionView()
      return
    end
    if not GetLootProfileAccessInfo(profileName).canManageSession then
      return
    end
    local selectedMember = TrimText(editor.lootSessionSelectedSyncMember or (profileSyncDropdown and profileSyncDropdown:GetSelectedValue()) or "")
    if selectedMember == "" then
      SetLootSessionActionStatusOverride(editor, "Select one joined member before sending host Session Data.", { 1.00, 0.55, 0.44, 1.00 })
      RefreshSessionView()
      return
    end
    local pushProfileUpdate = ResolveOptionalApiFunction("LIDCOUNCIL_PushActiveProfileSnapshotFlow")
    if type(pushProfileUpdate) == "function" then
      if not RunLootSessionAction(editor, "Send Host Session Data", pushProfileUpdate, selectedMember, {
        domains = { "session" },
        mode = "BACKGROUND",
        reason = "host_session_history_manual_archive",
      }) then
        RefreshSessionView()
      end
    else
      SetLootSessionActionStatusOverride(editor, "Send Host Session Data is unavailable.", { 1.00, 0.55, 0.44, 1.00 })
      RefreshSessionView()
    end
  end)

  checkSyncBtn:SetScript("OnClick", function()
    if IsCombatLocked() then
      RefreshSessionView()
      return
    end
    local profileName = ResolveRequiredSessionProfileName("Check Differences")
    if not profileName then
      RefreshSessionView()
      return
    end
    if not GetLootProfileAccessInfo(profileName).canManageSession then
      return
    end
    local requestSubchecks = ResolveOptionalApiFunction("LIDCOUNCIL_RequestActiveProfileSubchecksumFlow")
    if type(requestSubchecks) == "function" then
      local selectedMember = TrimText(editor.lootSessionSelectedSyncMember or (profileSyncDropdown and profileSyncDropdown:GetSelectedValue()) or "")
      if not RunLootSessionAction(editor, "Load Precise Differences", requestSubchecks, selectedMember ~= "" and selectedMember or nil) then
        RefreshSessionView()
      end
    else
      SetLootSessionActionStatusOverride(editor, "Load Precise Differences is unavailable.", { 1.00, 0.55, 0.44, 1.00 })
      RefreshSessionView()
    end
  end)

  recommendedRepairBtn:SetScript("OnClick", function()
    if IsCombatLocked() then
      RefreshSessionView()
      return
    end
    local profileName = ResolveRequiredSessionProfileName("Run Recommended Repair")
    if not profileName then
      RefreshSessionView()
      return
    end
    if not GetLootProfileAccessInfo(profileName).canManageSession then
      return
    end

    local selectedMember = TrimText(editor.lootSessionSelectedSyncMember or (profileSyncDropdown and profileSyncDropdown:GetSelectedValue()) or "")
    local selectedCandidate = nil
    for _, candidate in ipairs(editor.lootSessionAllSyncCandidates or {}) do
      if string.lower(TrimText(type(candidate) == "table" and candidate.memberKey or "")) == string.lower(selectedMember) then
        selectedCandidate = candidate
        break
      end
    end
    local recommendation = type(selectedCandidate) == "table" and type(selectedCandidate.safeRecommendation) == "table" and selectedCandidate.safeRecommendation or nil
    if type(recommendation) ~= "table" then
      return
    end

    editor.lootSessionSelectedSyncMember = selectedMember
    editor.lootSessionSyncScopeSelections = type(editor.lootSessionSyncScopeSelections) == "table" and editor.lootSessionSyncScopeSelections or {}
    editor.lootSessionSyncScopeSelections[selectedMember] = editor.lootSessionSyncScopeSelections[selectedMember] or { selected = {} }
    local selectionEntry = editor.lootSessionSyncScopeSelections[selectedMember]
    selectionEntry.selected = {}
    for _, subdomain in ipairs(type(recommendation.subdomains) == "table" and recommendation.subdomains or {}) do
      if TrimText(subdomain) ~= "" then
        selectionEntry.selected[TrimText(subdomain)] = true
      end
    end

    local action = string.lower(TrimText(recommendation.action))
    local dispatchedRecommendation = false
    if action == "push" then
      local pushProfileUpdate = ResolveOptionalApiFunction("LIDCOUNCIL_PushActiveProfileSnapshotFlow")
      if type(pushProfileUpdate) == "function" then
        dispatchedRecommendation = RunLootSessionAction(editor, "Run Recommended Repair", pushProfileUpdate, selectedMember ~= "" and selectedMember or nil, {
          domains = recommendation.domains,
          subdomains = recommendation.subdomains,
        })
      end
    elseif action == "pull" then
      local requestProfileUpdate = ResolveOptionalApiFunction("LIDCOUNCIL_RequestActiveProfileSnapshotFlow")
      if type(requestProfileUpdate) == "function" then
        dispatchedRecommendation = RunLootSessionAction(editor, "Run Recommended Repair", requestProfileUpdate, selectedMember, {
          domains = recommendation.domains,
          subdomains = recommendation.subdomains,
        })
      end
    elseif action == "preview" then
      local requestProfileUpdate = ResolveOptionalApiFunction("LIDCOUNCIL_RequestActiveProfileSnapshotFlow")
      if type(requestProfileUpdate) == "function" then
        dispatchedRecommendation = RunLootSessionAction(editor, "Run Recommended Repair", requestProfileUpdate, selectedMember, {
          mode = "PREVIEW",
          domains = recommendation.domains,
          subdomains = recommendation.subdomains,
        })
      end
    else
      local requestSubchecks = ResolveOptionalApiFunction("LIDCOUNCIL_RequestActiveProfileSubchecksumFlow")
      if type(requestSubchecks) == "function" then
        dispatchedRecommendation = RunLootSessionAction(editor, "Run Recommended Repair", requestSubchecks, selectedMember ~= "" and selectedMember or nil)
      end
    end
    if not dispatchedRecommendation then
      if type(editor.__lootSessionActionStatusOverride) ~= "table" then
        SetLootSessionActionStatusOverride(editor, "Run Recommended Repair could not dispatch the recommended action.", { 1.00, 0.55, 0.44, 1.00 })
      end
      RefreshSessionView()
    end
  end)

  requestProfileBtn:SetScript("OnClick", function()
    if IsCombatLocked() then
      RefreshSessionView()
      return
    end
    local profileName = ResolveRequiredSessionProfileName("Pull Member Repair")
    if not profileName then
      RefreshSessionView()
      return
    end
    if not GetLootProfileAccessInfo(profileName).canManageSession then
      return
    end
    if type(editor.lootSessionSelectedSyncCandidate) == "table"
      and (editor.lootSessionSelectedSyncCandidate.preciseNoDifferences == true
        or TrimText(editor.lootSessionSelectedSyncCandidate.preciseRequestState) == "waiting"
        or TrimText(editor.lootSessionSelectedSyncCandidate.preciseRequestState) == "failed")
    then
      SetLootSessionActionStatusOverride(editor, "No completed actionable precise scope is available for Pull Member Repair. Refresh or retry precise differences first.", { 1.00, 0.72, 0.32, 1.00 })
      RefreshSessionView()
      return
    end
    local requestProfileUpdate = ResolveOptionalApiFunction("LIDCOUNCIL_RequestActiveProfileSnapshotFlow")
    local selectedMember = TrimText(editor.lootSessionSelectedSyncMember or (profileSyncDropdown and profileSyncDropdown:GetSelectedValue()) or "")
    local selectedScopeActions = type(editor.lootSessionSelectedScopeActions) == "table" and editor.lootSessionSelectedScopeActions.pull or nil
    local options = nil
    if type(selectedScopeActions) == "table"
      and selectedScopeActions.selectionActive
      and selectedScopeActions.compatibleCount > 0
      and string.lower(TrimText(selectedScopeActions.targetMemberKey)) == string.lower(selectedMember) then
      options = {
        domains = selectedScopeActions.domains,
        subdomains = selectedScopeActions.subdomains,
      }
    end
    if type(requestProfileUpdate) == "function" then
      if not RunLootSessionAction(editor, "Pull Member Repair", requestProfileUpdate, selectedMember, options) then
        RefreshSessionView()
      end
    else
      SetLootSessionActionStatusOverride(editor, "Pull Member Repair is unavailable.", { 1.00, 0.55, 0.44, 1.00 })
      RefreshSessionView()
    end
  end)

  previewProfileBtn:SetScript("OnClick", function()
    if IsCombatLocked() then
      RefreshSessionView()
      return
    end
    local profileName = ResolveRequiredSessionProfileName("Preview Member Repair")
    if not profileName then
      RefreshSessionView()
      return
    end
    if not GetLootProfileAccessInfo(profileName).canManageSession then
      return
    end
    if type(editor.lootSessionSelectedSyncCandidate) == "table"
      and (editor.lootSessionSelectedSyncCandidate.preciseNoDifferences == true
        or TrimText(editor.lootSessionSelectedSyncCandidate.preciseRequestState) == "waiting"
        or TrimText(editor.lootSessionSelectedSyncCandidate.preciseRequestState) == "failed")
    then
      SetLootSessionActionStatusOverride(editor, "No completed actionable precise scope is available to preview. Refresh or retry precise differences first.", { 1.00, 0.72, 0.32, 1.00 })
      RefreshSessionView()
      return
    end
    local requestProfileUpdate = ResolveOptionalApiFunction("LIDCOUNCIL_RequestActiveProfileSnapshotFlow")
    local selectedMember = TrimText(editor.lootSessionSelectedSyncMember or (profileSyncDropdown and profileSyncDropdown:GetSelectedValue()) or "")
    local options = { mode = "PREVIEW" }
    local selectedScopeActions = type(editor.lootSessionSelectedScopeActions) == "table" and editor.lootSessionSelectedScopeActions.preview or nil
    if type(selectedScopeActions) == "table"
      and selectedScopeActions.selectionActive
      and selectedScopeActions.compatibleCount > 0
      and string.lower(TrimText(selectedScopeActions.targetMemberKey)) == string.lower(selectedMember) then
      options.domains = selectedScopeActions.domains
      options.subdomains = selectedScopeActions.subdomains
    end
    if type(requestProfileUpdate) == "function" then
      if not RunLootSessionAction(editor, "Preview Member Repair", requestProfileUpdate, selectedMember, options) then
        RefreshSessionView()
      end
    else
      SetLootSessionActionStatusOverride(editor, "Preview Member Repair is unavailable.", { 1.00, 0.55, 0.44, 1.00 })
      RefreshSessionView()
    end
  end)

  syncBoardBtn:SetScript("OnClick", function()
    if IsCombatLocked() then
      RefreshSessionView()
      return
    end
    local profileName = ResolveRequiredSessionProfileName("Send Board Sync")
    if not profileName then
      RefreshSessionView()
      return
    end
    if not GetLootProfileAccessInfo(profileName).canManageSession then
      return
    end
    local sendBoardSync = ResolveOptionalApiFunction("LIDCOUNCIL_SendActiveLiveBoardSyncFlow")
    if type(sendBoardSync) == "function" then
      if not RunLootSessionAction(editor, "Send Board Sync", sendBoardSync) then
        RequestSessionWorkflowRefresh(editor, {
          refreshPages = {
            Panels = true,
            LiveBoard = true,
            Backgrounds = true,
          },
        })
      end
    else
      SetLootSessionActionStatusOverride(editor, "Send Board Sync is unavailable.", { 1.00, 0.55, 0.44, 1.00 })
      RequestSessionWorkflowRefresh(editor, {
        refreshPages = {
          Panels = true,
          LiveBoard = true,
          Backgrounds = true,
        },
      })
    end
  end)

  local function ApplySimulationRoleOverride(roleKey)
    local _, profileName = ResolveSessionContextProfile()
    if TrimText(profileName) ~= "Simulation" then
      return
    end
    local setSimulationRole = ResolveOptionalApiFunction("LIDCOUNCIL_SetSimulationRoleOverride")
    if type(setSimulationRole) == "function" then
      if not RunLootSessionAction(editor, "Set simulation role", setSimulationRole, profileName, roleKey) then
        RequestSessionWorkflowRefresh(editor, {
          refreshPages = {
            Panels = true,
          },
        }, "ROLESIM")
        return
      end
    else
      SetLootSessionActionStatusOverride(editor, "Set simulation role is unavailable.", { 1.00, 0.55, 0.44, 1.00 })
      RequestSessionWorkflowRefresh(editor, {
        refreshPages = {
          Panels = true,
        },
      }, "ROLESIM")
      return
    end
    local refreshBoard = ResolveOptionalApiFunction("LIDCOUNCIL_RefreshLiveLootBoard")
    if type(refreshBoard) == "function" then
      RunLootSessionAction(editor, "Refresh simulation board", refreshBoard)
    end
    RequestSessionWorkflowRefresh(editor, {
      refreshPages = {
        Panels = true,
        LiveBoard = true,
      },
    }, "ROLESIM")
  end

  roleSimMasterBtn:SetScript("OnClick", function()
    ApplySimulationRoleOverride("MASTER")
  end)
  roleSimSessionHostBtn:SetScript("OnClick", function()
    ApplySimulationRoleOverride("SESSION_HOST")
  end)
  roleSimCouncilBtn:SetScript("OnClick", function()
    ApplySimulationRoleOverride("COUNCIL")
  end)
  roleSimRaiderBtn:SetScript("OnClick", function()
    ApplySimulationRoleOverride("RAIDER")
  end)

  autoPassLocalBtn:SetScript("OnClick", function()
    if IsCombatLocked() then
      RefreshSessionView()
      return
    end
    local activeSession = select(1, GetActiveLootSession())
    local activeSessionStatus = string.upper(TrimText(type(activeSession) == "table" and activeSession.status or ""))
    if activeSessionStatus ~= "PREPARING" and activeSessionStatus ~= "ACTIVE" then
      -- The button is hidden while idle; keep the handler safe if a stale click arrives during a refresh.
      RefreshSessionView()
      return
    end
    local getLocalAutoPassEnabled = ResolveOptionalApiFunction("LIDCOUNCIL_GetLocalAutoPassEnabled")
    local setLocalAutoPassEnabled = ResolveOptionalApiFunction("LIDCOUNCIL_SetLocalAutoPassEnabled")
    local notifyLocalAutoPassChanged = ResolveOptionalApiFunction("LIDCOUNCIL_NotifyLocalAutoPassChanged")
    if type(setLocalAutoPassEnabled) ~= "function" then
      SetLootSessionActionStatusOverride(editor, "Toggle Auto-Pass is unavailable.", { 1.00, 0.55, 0.44, 1.00 })
      RefreshSessionView()
      return
    end
    local currentEnabled = true
    if type(editor.__lidAutoPassDisplayOverride) == "boolean" then
      currentEnabled = editor.__lidAutoPassDisplayOverride
    elseif type(getLocalAutoPassEnabled) == "function" then
      currentEnabled = ReadLootSessionActionValue(editor, "Read local Auto-Pass state", getLocalAutoPassEnabled, true) and true or false
    end
    local nextEnabled = not currentEnabled
    local changed, persistedEnabled = RunLootSessionAction(
      editor,
      nextEnabled and "Activate Auto-Pass" or "Deactivate Auto-Pass",
      setLocalAutoPassEnabled,
      nextEnabled
    )
    if not changed then
      RefreshSessionView()
      return
    end
    if type(persistedEnabled) == "boolean" then
      nextEnabled = persistedEnabled
    end
    editor.__lidAutoPassDisplayOverride = nextEnabled
    editor.__lidHeaderAutoPassOverride = nextEnabled
    if type(editor.SetHeaderAutoPassIcon) == "function" then
      editor:SetHeaderAutoPassIcon(nextEnabled, true)
    end
    if type(notifyLocalAutoPassChanged) == "function" then
      RunLootSessionAction(editor, "Broadcast Auto-Pass change", notifyLocalAutoPassChanged, nextEnabled)
    end
    if editor.lootSessionSection == "AUTOPASS" then
      local activeSession = select(1, GetActiveLootSession())
      RefreshAutoPassView(editor, {
        activeSession = activeSession,
        selfCharacter = GetCharacterKey() or "",
        localAutoPassEnabled = nextEnabled,
      })
      if editor.LayoutLootSessionPage then
        editor:LayoutLootSessionPage()
      end
    end
    if type(editor.RefreshSyncActivityBanner) == "function" then
      editor:RefreshSyncActivityBanner()
    end
    RefreshSessionView()
  end)

  editor.RefreshLootSessionPage = function(self, opts)
    local pageStartedAt = INTERNAL_API.LIDCOUNCIL_BeginSyncPerformanceSample_Impl("editor_page_session", 1)
    local result = RefreshLootSessionPage_Impl(self, opts)
    INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl("editor_page_session", pageStartedAt, {
      context = string.upper(tostring(self and self.lootSessionSection or "CURRENT")),
    })
    return result
  end
  editor.RefreshCurrentSessionPriorityTelemetry = RefreshCurrentSessionPriorityTelemetry
  editor.RefreshCurrentSessionRosterIfChanged = RefreshCurrentSessionRosterIfChanged

  if not editor.lootSessionCombatEventFrame then
    local combatEventFrame = CreateFrame("Frame")
    combatEventFrame:RegisterEvent("PLAYER_REGEN_DISABLED")
    combatEventFrame:RegisterEvent("PLAYER_REGEN_ENABLED")
    combatEventFrame:SetScript("OnEvent", function(_, event)
      if event == "PLAYER_REGEN_DISABLED" then
        editor.__lootSessionSyncProgressRefreshDeferred = true
        return
      end
      editor.__lootSessionSyncProgressRefreshDeferred = nil
      RefreshSessionView()
    end)
    editor.lootSessionCombatEventFrame = combatEventFrame
  end

  if page and page.HookScript then
    page:HookScript("OnSizeChanged", function()
      LayoutLootSessionPage(editor)
    end)
  end
  editor.LayoutLootSessionPage = LayoutLootSessionPage
end

INTERNAL_API.LIDCOUNCIL_BuildLootSessionPage_Impl = BuildLootSessionPage

