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

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

  local ApplyFrameSkin = deps.ApplyFrameSkin
  local RootDB = deps.RootDB
  local TrimText = deps.TrimText
  local RequestLootSessionSectionRefresh = deps.RequestLootSessionSectionRefresh
  local GetActiveLootSession = deps.GetActiveLootSession
  local BuildCurrentSessionStateSignature = deps.BuildCurrentSessionStateSignature
  local ResolveSessionDisplayInfo = deps.ResolveSessionDisplayInfo
  local ResolveSessionSyncState = deps.ResolveSessionSyncState
  local ResolveSessionBootstrapState = deps.ResolveSessionBootstrapState
  local ResolveSessionHistorySyncState = deps.ResolveSessionHistorySyncState
  local ResolveSessionIconData = deps.ResolveSessionIconData
  local ApplySessionIcon = deps.ApplySessionIcon
  local GetSessionClassColor = deps.GetSessionClassColor
  local GetSessionSyncLabel = deps.GetSessionSyncLabel
  local GetSessionSyncDescription = deps.GetSessionSyncDescription
  local GetSessionBootstrapLabel = deps.GetSessionBootstrapLabel
  local GetSessionBootstrapDescription = deps.GetSessionBootstrapDescription
  local GetSessionBootstrapColor = deps.GetSessionBootstrapColor
  local ApplyTrafficLight = deps.ApplyTrafficLight
  local GetTrafficLightColor = deps.GetTrafficLightColor
  local GetSessionStatusColor = deps.GetSessionStatusColor
  local GetLocalAutoPassEnabled = deps.GetLocalAutoPassEnabled
  local GetSessionCommQueueStatus = deps.GetSessionCommQueueStatus
  local GetMemberLootListDifferenceDiagnostics = deps.GetMemberLootListDifferenceDiagnostics
  local GetMemberItemHistoryDifferenceDiagnostics = deps.GetMemberItemHistoryDifferenceDiagnostics
  local GetMemberSessionHistoryDifferenceDiagnostics = deps.GetMemberSessionHistoryDifferenceDiagnostics
  local GetMemberP2ProofDiagnostics = deps.GetMemberP2ProofDiagnostics
  local FormatDateTime = deps.FormatDateTime
  local FlowLayoutControls = deps.FlowLayoutControls
  local ClampLayoutValue = deps.ClampLayoutValue

  local function IsTutorialModeEnabled()
    local root = type(RootDB) == "function" and RootDB() or nil
    local ui = type(root) == "table" and type(root.ui) == "table" and root.ui or nil
    return type(ui) == "table" and ui.tutorialMode == true
  end

  local function SetLiveSummaryText(fontString, text, isTutorial)
    if not fontString then
      return
    end
    fontString:SetText(tostring(text or ""))
    if isTutorial then
      fontString:SetTextColor(1.00, 0.82, 0.24, 1.00)
    else
      fontString:SetTextColor(0.82, 0.82, 0.86, 1.00)
    end
    fontString:SetShown(TrimText(text) ~= "")
  end

  local function TintSessionCard(frame, r, g, b)
    if not frame or not frame.SetBackdropColor then
      return
    end
    frame:SetBackdropColor(
      math.min(0.18, 0.03 + ((tonumber(r) or 0) * 0.10)),
      math.min(0.18, 0.03 + ((tonumber(g) or 0) * 0.10)),
      math.min(0.18, 0.04 + ((tonumber(b) or 0) * 0.10)),
      0.96
    )
  end

  local function FormatSessionMoment(timestamp)
    local value = math.floor(tonumber(timestamp) or 0)
    if value <= 0 then
      return "Unknown"
    end
    if type(date) == "function" then
      local now = type(time) == "function" and math.floor(tonumber(time()) or 0) or 0
      if now > 0 and date("%Y-%m-%d", value) == date("%Y-%m-%d", now) then
        return "Today, " .. tostring(date("%H:%M", value))
      end
      return tostring(date("%b %d, %H:%M", value))
    end
    return type(FormatDateTime) == "function" and FormatDateTime(value) or tostring(value)
  end

  local function HideSessionOverviewCards(editor)
    for _, card in ipairs(editor.lootSessionOverviewCards or {}) do
      if card.frame then
        card.frame:Hide()
      end
      if card.dot then
        card.dot:Hide()
      end
    end
  end

  local function ShowSessionOverviewStatusCards(editor, overallSyncState, bootstrapState, bootstrapCounts)
    local syncR, syncG, syncB = GetTrafficLightColor(overallSyncState)
    local bootstrapR, bootstrapG, bootstrapB = GetSessionBootstrapColor(bootstrapState)
    for _, card in ipairs(editor.lootSessionOverviewCards or {}) do
      local showCard = card.label == "Roll Ready" or card.label == "Session Sync"
      if card.frame then
        card.frame:SetShown(showCard)
      end
      if showCard then
        if card.label == "Session Sync" then
          card.valueText:SetText(GetSessionSyncLabel(overallSyncState))
          card.valueText:SetTextColor(syncR, syncG, syncB, 1)
          TintSessionCard(card.frame, syncR, syncG, syncB)
          ApplyTrafficLight(card.dot, overallSyncState)
        else
          card.valueText:SetText(string.format("%d / %d", bootstrapCounts.ready, bootstrapCounts.joined))
          card.valueText:SetTextColor(bootstrapR, bootstrapG, bootstrapB, 1)
          TintSessionCard(card.frame, bootstrapR, bootstrapG, bootstrapB)
          ApplyTrafficLight(card.dot, bootstrapState == "READY" and "SYNCED" or (bootstrapState == "REVIEW" and "DECLINED" or "PARTIAL"))
        end
        if card.dot then
          card.dot:Show()
        end
      elseif card.dot then
        card.dot:Hide()
      end
    end
  end

  local function RefreshCurrentSessionSection(editor)
    if type(RequestLootSessionSectionRefresh) == "function" then
      return RequestLootSessionSectionRefresh(editor, "CURRENT")
    end
    if editor and editor.RefreshLootSessionPage then
      editor:RefreshLootSessionPage({
        lootSessionSections = {
          CURRENT = true,
        },
      })
      return true
    end
    if editor and editor.Refresh then
      editor:Refresh()
      return true
    end
    return false
  end

  local function ResolveSessionMemberRecoveryInfo(member)
    member = type(member) == "table" and member or nil
    if type(member) ~= "table" then
      return nil
    end
    local state = string.lower(TrimText(member.lastDeltaRecoveryState))
    local recoveryAt = math.max(0, tonumber(member.lastDeltaRecoveryAt) or 0)
    local lastSyncAt = math.max(0, tonumber(member.lastSyncAt) or 0)
    if state == "" then
      if member.lastDeltaRecoveryFullSnapshotFallback == true then
        state = "full_fallback"
      elseif member.lastDeltaRecoveryScopeEscalated == true then
        state = "widened"
      elseif TrimText(member.lastDeltaRecoveryKind) == "aligned" then
        state = "aligned"
      elseif recoveryAt > 0 then
        state = "recovered"
      end
    elseif state == "deferred" and lastSyncAt > 0 and lastSyncAt >= recoveryAt then
      state = "recovered"
    end
    if state == "" or state == "aligned" then
      return nil
    end
    if state == "deferred" then
      return {
        state = state,
        shortLabel = "Deferred",
        longLabel = "Recovery deferred",
        color = { 1.00, 0.82, 0.28, 1.00 },
      }
    elseif state == "review" then
      return {
        state = state,
        shortLabel = "Review",
        longLabel = "Needs review",
        color = { 0.98, 0.74, 0.30, 1.00 },
      }
    elseif state == "widened" then
      return {
        state = state,
        shortLabel = "Widened",
        longLabel = "Repair widened",
        color = { 0.38, 0.72, 1.00, 1.00 },
      }
    elseif state == "full_fallback" then
      return {
        state = state,
        shortLabel = "Full FB",
        longLabel = "Full fallback",
        color = { 0.94, 0.62, 0.28, 1.00 },
      }
    elseif state == "failed" then
      return {
        state = state,
        shortLabel = "Failed",
        longLabel = "Recovery failed",
        color = { 0.95, 0.32, 0.26, 1.00 },
      }
    end
    return {
      state = state,
      shortLabel = "Recovered",
      longLabel = "Recovery applied",
      color = { 0.30, 0.90, 0.36, 1.00 },
    }
  end

  local function GetSessionOverviewCardColumns(rightContentWidth)
    local width = math.max(300, math.floor(tonumber(rightContentWidth) or 300))
    if width < 460 then
      return 1
    elseif width < 860 then
      return 2
    end
    return 4
  end

  local function BuildSessionMemberColumnLayout(rowWidth)
    local resolvedWidth = math.max(260, math.floor(tonumber(rowWidth) or 260))
    local nameX = 36
    local compact = resolvedWidth < 900
    local showPriority3 = resolvedWidth >= 440
    local showPriorityLabels = resolvedWidth >= 940
    local showArchiveDetails = resolvedWidth >= 520
    local showPriority3Detail = showPriority3
    local gap = resolvedWidth < 720 and 6 or (compact and 8 or 12)
    local autoPassWidth = resolvedWidth < 720 and 54 or (compact and 58 or 78)
    local priorityWidth = showPriorityLabels and 72 or (resolvedWidth < 720 and 32 or 34)
    local endPadding = resolvedWidth < 720 and 6 or 8
    local archiveMinimumWidth = resolvedWidth < 720 and 46 or 54
    -- Keep identity compact so every readiness and archive column remains visible.
    local minimumRightWidth = (priorityWidth * 2) + autoPassWidth + (gap * 3) + endPadding
    if showArchiveDetails then
      minimumRightWidth = minimumRightWidth + (archiveMinimumWidth * 4) + (gap * 4)
    elseif showPriority3 then
      minimumRightWidth = minimumRightWidth + priorityWidth + gap
    end
    local availableNameWidth = resolvedWidth - nameX - minimumRightWidth
    local nameWidth = math.max(56, math.min(220, math.floor(resolvedWidth * 0.22), availableNameWidth))
    local autoPassX = resolvedWidth - autoPassWidth - endPadding
    local priority1X = nameX + nameWidth + gap
    local priority2X = priority1X + priorityWidth + gap
    local priority3X = showPriority3 and (priority2X + priorityWidth + gap) or 0
    local priority3Width = priorityWidth
    local archiveWidth = priorityWidth
    local itemHistoryX = 0
    local sessionHistoryX = 0
    local funAwardsX = 0
    local priority3TextWidth = priorityWidth

    if showArchiveDetails then
      local archiveSpace = autoPassX - priority3X - gap - (gap * 3)
      archiveWidth = math.max(archiveMinimumWidth, math.floor(archiveSpace / 4))
      itemHistoryX = priority3X + archiveWidth + gap
      sessionHistoryX = itemHistoryX + archiveWidth + gap
      funAwardsX = sessionHistoryX + archiveWidth + gap
      priority3Width = archiveWidth
      priority3TextWidth = (funAwardsX + archiveWidth) - priority3X
    elseif showPriority3 and showPriority3Detail then
      priority3Width = math.max(priorityWidth, autoPassX - priority3X - gap)
      priority3TextWidth = priority3Width
    end
    return {
      rowWidth = resolvedWidth,
      nameX = nameX,
      nameWidth = nameWidth,
      compact = compact,
      showPriority3 = showPriority3,
      showPriorityLabels = showPriorityLabels,
      showPriority3Detail = showPriority3Detail,
      showArchiveDetails = showArchiveDetails,
      priority1X = priority1X,
      priority2X = priority2X,
      priority3X = priority3X,
      priorityWidth = priorityWidth,
      priority3Width = priority3Width,
      priority3TextWidth = priority3TextWidth,
      archiveWidth = archiveWidth,
      itemHistoryX = itemHistoryX,
      sessionHistoryX = sessionHistoryX,
      funAwardsX = funAwardsX,
      autoPassX = autoPassX,
      autoPassWidth = autoPassWidth,
    }
  end

  local function GetPriorityPhaseLabel(state)
    local resolvedState = string.upper(TrimText(state))
    if resolvedState == "READY" then
      return "Ready"
    elseif resolvedState == "REVIEW" then
      return "Review required"
    elseif resolvedState == "VALIDATING" then
      return "Validating"
    elseif resolvedState == "STALE" then
      return "Archive differs"
    elseif resolvedState == "PENDING" or resolvedState == "" then
      return "Proof unknown"
    end
    return "Proof unknown"
  end

  local function GetPriorityPhaseTexture(state)
    local resolvedState = string.upper(TrimText(state))
    if resolvedState == "READY" then
      return "Interface\\RaidFrame\\ReadyCheck-Ready"
    elseif resolvedState == "STALE" then
      return "Interface\\DialogFrame\\UI-Dialog-Icon-AlertNew"
    elseif resolvedState == "REVIEW" then
      return "Interface\\RaidFrame\\ReadyCheck-NotReady"
    elseif resolvedState == "VALIDATING" then
      return "Interface\\Buttons\\UI-RefreshButton"
    end
    return "Interface\\RaidFrame\\ReadyCheck-Waiting"
  end

  local function GetTransferScopeLabel(transfer)
    transfer = type(transfer) == "table" and transfer or {}
    local fragments = {
      string.lower(TrimText(transfer.lane)),
      string.lower(TrimText(transfer.reason)),
      string.lower(TrimText(transfer.domains)),
      string.lower(TrimText(transfer.subdomains)),
    }
    for _, key in ipairs({ "scopeDomains", "scopeSubdomains" }) do
      for _, value in ipairs(type(transfer[key]) == "table" and transfer[key] or {}) do
        fragments[#fragments + 1] = string.lower(TrimText(value))
      end
    end
    local scopeText = table.concat(fragments, " ")
    if scopeText:find("fun_award", 1, true) or scopeText:find("fun award", 1, true) then
      return "Fun Awards"
    elseif scopeText:find("item_history", 1, true)
      or scopeText:find("item history", 1, true)
      or scopeText:find("session_live_board", 1, true)
      or scopeText:find("slb:", 1, true)
    then
      return "Item History"
    elseif scopeText:find("session_history", 1, true)
      or scopeText:find("session history", 1, true)
      or scopeText:find("session_archive", 1, true)
      or scopeText:find("latest_session", 1, true)
      or scopeText:find("ssr:", 1, true)
      or scopeText:find("session", 1, true)
    then
      return "Session History"
    elseif scopeText:find("loot", 1, true) or string.lower(TrimText(transfer.lane)) == "archive" then
      return "Loot Archive"
    end
    return "Background"
  end

  local function GetTransferStateRank(state)
    state = string.lower(TrimText(state))
    if state == "failed" then
      return 90
    elseif state == "ack_timeout" then
      return 80
    elseif state == "waiting_apply" or state == "superseded_waiting_apply" then
      return 70
    elseif state == "waiting_ack" then
      return 60
    elseif state == "sending" or state == "receiving" then
      return 50
    elseif state == "queued" then
      return 40
    end
    return 0
  end

  local function GetTransferRecoveryLabel(transfer)
    transfer = type(transfer) == "table" and transfer or {}
    if math.max(0, tonumber(transfer.ackTimeoutRecoveryQueuedCount) or 0) > 0 then
      return "Recovery queued after receipt timeout"
    end
    local outcome = string.lower(TrimText(transfer.ackTimeoutRecoveryOutcome))
    if outcome ~= "" then
      return outcome == "failed" and "Recovery failed after receipt timeout"
        or "Recovering after receipt timeout"
    end
    if math.max(0, tonumber(transfer.ackTimeoutRevalidationRequestedAt) or 0) > 0 then
      return "Revalidating after receipt timeout"
    end
    return ""
  end

  local function ResolvePriorityDataPresentation(state, phase)
    local dataReady = string.upper(TrimText(state)) == "READY"
    if not dataReady then
      return false, ""
    end

    phase = type(phase) == "table" and phase or {}
    local primaryState = string.lower(TrimText(phase.primaryState))
    if primaryState == "failed" or (tonumber(phase.failed) or 0) > 0 then
      return true, "delivery_failed"
    elseif TrimText(phase.recoveryLabel) ~= "" then
      return true, "receipt_recovery"
    elseif primaryState == "ack_timeout" or (tonumber(phase.ack_timeout) or 0) > 0 then
      return true, "receipt_timeout"
    elseif primaryState == "waiting_apply" or primaryState == "superseded_waiting_apply"
      or (tonumber(phase.waiting_apply) or 0) > 0
      or (tonumber(phase.superseded_waiting_apply) or 0) > 0
    then
      return true, "apply_pending"
    elseif primaryState == "waiting_ack" or (tonumber(phase.waiting_ack) or 0) > 0 then
      return true, "receipt_pending"
    elseif primaryState == "sending" or primaryState == "receiving" or primaryState == "queued"
      or (tonumber(phase.sending) or 0) > 0
      or (tonumber(phase.receiving) or 0) > 0
      or (tonumber(phase.queued) or 0) > 0
    then
      return true, "delivery_active"
    end
    return true, ""
  end

  local function ResolvePriorityIndicator(state, phase)
    phase = type(phase) == "table" and phase or {}
    local resolvedState = string.upper(TrimText(state))
    local dataReady = ResolvePriorityDataPresentation(state, phase)
    local isActive = (tonumber(phase.sending) or 0) > 0
      or (tonumber(phase.receiving) or 0) > 0
      or (tonumber(phase.queued) or 0) > 0
      or (tonumber(phase.waiting_ack) or 0) > 0
      or (tonumber(phase.waiting_apply) or 0) > 0
      or (tonumber(phase.superseded_waiting_apply) or 0) > 0
    local isFailed = resolvedState == "REVIEW" or (tonumber(phase.failed) or 0) > 0
    local isWarning = resolvedState == "STALE" or (tonumber(phase.ack_timeout) or 0) > 0

    if dataReady then
      return {
        kind = "ALIGNED",
        texture = GetPriorityPhaseTexture("READY"),
        color = { 1, 1, 1, 1 },
        desaturated = false,
      }
    elseif isFailed then
      return {
        kind = "FAILED",
        texture = GetPriorityPhaseTexture("REVIEW"),
        color = { 0.95, 0.32, 0.26, 1 },
        desaturated = false,
      }
    elseif resolvedState == "VALIDATING" or isActive then
      return {
        kind = "PROGRESS",
        texture = GetPriorityPhaseTexture("VALIDATING"),
        color = { 0.38, 0.72, 1.00, 1 },
        desaturated = true,
      }
    elseif isWarning then
      return {
        kind = "DIFFERS",
        texture = GetPriorityPhaseTexture("STALE"),
        color = { 1.00, 0.78, 0.28, 1 },
        desaturated = true,
      }
    end
    return {
      kind = "UNKNOWN",
      texture = GetPriorityPhaseTexture("PENDING"),
      color = { 0.62, 0.66, 0.72, 1 },
      desaturated = true,
    }
  end

  local function ApplyPriorityPhaseIcon(texture, state, phase)
    if not texture then
      return
    end
    local indicator = ResolvePriorityIndicator(state, phase)
    if texture.SetAtlas then
      texture:SetAtlas(nil)
    end
    texture:SetTexture(indicator.texture)
    if texture.SetDesaturated then
      texture:SetDesaturated(indicator.desaturated == true)
    end
    local color = indicator.color or { 1, 1, 1, 1 }
    texture:SetVertexColor(color[1], color[2], color[3], color[4] or 1)
  end

  local function GetPriorityIndicatorTextColor(state, phase)
    local kind = ResolvePriorityIndicator(state, phase).kind
    if kind == "ALIGNED" then
      return 0.30, 0.90, 0.36, 1
    elseif kind == "PROGRESS" then
      return 0.38, 0.72, 1.00, 1
    elseif kind == "DIFFERS" then
      return 1.00, 0.78, 0.28, 1
    elseif kind == "FAILED" then
      return 0.95, 0.32, 0.26, 1
    end
    return 0.62, 0.66, 0.72, 1
  end

  local function BuildSessionMemberPriorityProgressByMember(queueStatus, activeSession, selfCharacter)
    queueStatus = type(queueStatus) == "table" and queueStatus or {}
    local activeSessionId = TrimText(type(activeSession) == "table" and activeSession.id or "")
    local progressByMember = {}

    local function ResolvePriorityStage(priority, transfer)
      local resolvedPriority = math.max(0, tonumber(priority) or 0)
      if resolvedPriority <= 0 then
        transfer = type(transfer) == "table" and transfer or {}
        local transferKind = string.upper(TrimText(transfer.transferKind))
        local transferKindOffset = transferKind == "ROWPATCHES" and 0
          or transferKind == "PATCHES" and 1
          or transferKind == "SUBDOMAINS" and 3
          or transferKind == "DOMAINS" and 5
          or 7
        local lane = string.lower(TrimText(transfer.lane))
        local reason = string.lower(TrimText(transfer.reason))
        local mode = string.upper(TrimText(transfer.mode))
        local scopeLabel = GetTransferScopeLabel(transfer)
        local backgroundArchive = lane == "archive" or lane == "stats"
          or scopeLabel == "Session History" or scopeLabel == "Fun Awards"
        if mode == "BACKGROUND" then
          -- P2 carries raid-time continuity. Session history, old loot and
          -- awards remain P3 even if their transport uses a generic live lane.
          resolvedPriority = backgroundArchive and 60 or 28
        elseif string.find(reason, "bootstrap", 1, true) then
          resolvedPriority = (lane == "archive" and 14 or (lane == "stats" and 10 or 6)) + transferKindOffset
        else
          resolvedPriority = (lane == "archive" and 36 or (lane == "stats" and 22 or 16)) + transferKindOffset
        end
      end
      return resolvedPriority <= 15 and 1 or (resolvedPriority <= 30 and 2 or 3)
    end

    local function RecordProgress(memberKey, stage, state, rosterSettling, transfer)
      local key = string.lower(TrimText(memberKey))
      if key == "" then
        return
      end
      local memberProgress = progressByMember[key] or {}
      progressByMember[key] = memberProgress
      local phase = memberProgress[stage] or {}
      memberProgress[stage] = phase
      phase[state] = (tonumber(phase[state]) or 0) + 1
      if rosterSettling then
        phase.rosterSettling = true
      end
      transfer = type(transfer) == "table" and transfer or {}
      local sentChunks = math.max(0, tonumber(transfer.sentChunks) or 0)
      local receivedChunks = math.max(0, tonumber(transfer.receivedChunkCount) or 0)
      local totalChunks = math.max(0, tonumber(transfer.totalChunks or transfer.chunkCount) or 0)
      if state == "sending" then
        phase.sentChunks = sentChunks
        phase.totalChunks = totalChunks
      elseif state == "receiving" then
        phase.receivedChunks = receivedChunks
        phase.totalChunks = totalChunks
      end
      if stage == 3 then
        local stateRank = GetTransferStateRank(state)
        if stateRank >= math.max(0, tonumber(phase.primaryStateRank) or 0) then
          phase.primaryStateRank = stateRank
          phase.scopeLabel = GetTransferScopeLabel(transfer)
          phase.primaryState = string.lower(TrimText(state))
          phase.acknowledgementAgeSeconds = math.max(
            0,
            tonumber(transfer.acknowledgementAgeSeconds) or tonumber(transfer.ageSeconds) or 0
          )
          phase.failureReason = TrimText(transfer.failureReason or transfer.failedKind)
          if state == "sending" then
            phase.sentChunks = sentChunks
            phase.totalChunks = totalChunks
          elseif state == "receiving" then
            phase.receivedChunks = receivedChunks
            phase.totalChunks = totalChunks
          end
        end
        local recoveryLabel = GetTransferRecoveryLabel(transfer)
        if recoveryLabel ~= "" then
          phase.recoveryLabel = recoveryLabel
        end
      end
    end

    for _, transfer in ipairs(type(queueStatus.profileTransfers) == "table" and queueStatus.profileTransfers or {}) do
      if type(transfer) == "table"
        and (activeSessionId == "" or TrimText(transfer.sessionId) == activeSessionId)
      then
        local state = string.lower(TrimText(transfer.state))
        if state == "queued" or state == "sending" or state == "waiting_ack"
          or state == "waiting_apply" or state == "superseded_waiting_apply"
          or state == "ack_timeout" or state == "failed"
        then
          RecordProgress(transfer.target, ResolvePriorityStage(nil, transfer), state, false, transfer)
        end
      end
    end

    local snapshotBatch = type(queueStatus.profileSnapshotBatch) == "table" and queueStatus.profileSnapshotBatch or {}
    local incomingTransfer = type(snapshotBatch.incomingTransfer) == "table" and snapshotBatch.incomingTransfer or nil
    if type(incomingTransfer) == "table"
      and (activeSessionId == "" or TrimText(incomingTransfer.sessionId) == activeSessionId)
    then
      local incomingMode = string.upper(TrimText(incomingTransfer.mode))
      local incomingLane = string.lower(TrimText(incomingTransfer.lane))
      local incomingPriority = incomingMode == "LIVE" and incomingLane == "live" and 6 or nil
      RecordProgress(
        selfCharacter,
        ResolvePriorityStage(incomingPriority, incomingTransfer),
        "receiving",
        false,
        incomingTransfer
      )
    end
    for _, item in ipairs(type(snapshotBatch.pendingItems) == "table" and snapshotBatch.pendingItems or {}) do
      if type(item) == "table"
        and (activeSessionId == "" or TrimText(item.sessionId) == activeSessionId)
      then
        RecordProgress(
          item.target,
          ResolvePriorityStage(item.priority, item),
          "queued",
          math.max(0, tonumber(item.holdRemaining) or 0) > 0,
          item
        )
      end
    end

    if queueStatus.archiveSyncPaused == true then
      for _, memberProgress in pairs(progressByMember) do
        local phase = type(memberProgress) == "table" and memberProgress[3] or nil
        local transferInFlight = type(phase) == "table" and (
          (tonumber(phase.sending) or 0) > 0
          or (tonumber(phase.receiving) or 0) > 0
          or (tonumber(phase.waiting_ack) or 0) > 0
          or (tonumber(phase.waiting_apply) or 0) > 0
          or (tonumber(phase.superseded_waiting_apply) or 0) > 0
        )
        if type(phase) == "table" and not transferInFlight then
          phase.archivePaused = true
        end
      end
    end

    return progressByMember
  end

  local function GetPriorityProgressLabel(phase)
    phase = type(phase) == "table" and phase or nil
    if not phase then
      return ""
    end
    if phase.archivePaused == true then
      return "Paused by archive sync"
    elseif TrimText(phase.recoveryLabel) ~= "" then
      return TrimText(phase.recoveryLabel)
    end
    local primaryState = string.lower(TrimText(phase.primaryState))
    if primaryState == "failed" then
      return "Send failed"
    elseif primaryState == "ack_timeout" then
      return "Receipt timed out"
    elseif primaryState == "waiting_apply" or primaryState == "superseded_waiting_apply" then
      return "Received; waiting for combat"
    elseif primaryState == "waiting_ack" then
      return "Sent; waiting for receipt"
    elseif primaryState == "receiving" then
      local receivedChunks = math.max(0, tonumber(phase.receivedChunks) or 0)
      local totalChunks = math.max(0, tonumber(phase.totalChunks) or 0)
      return totalChunks > 0 and ("Receiving " .. tostring(math.min(receivedChunks, totalChunks)) .. "/" .. tostring(totalChunks)) or "Receiving"
    elseif primaryState == "sending" then
      local sentChunks = math.max(0, tonumber(phase.sentChunks) or 0)
      local totalChunks = math.max(0, tonumber(phase.totalChunks) or 0)
      return totalChunks > 0 and ("Sending " .. tostring(math.min(sentChunks, totalChunks)) .. "/" .. tostring(totalChunks)) or "Sending"
    elseif primaryState == "queued" then
      return phase.rosterSettling and "Queued; roster settling" or "Queued"
    elseif (tonumber(phase.waiting_apply) or 0) > 0 or (tonumber(phase.superseded_waiting_apply) or 0) > 0 then
      return "Received; waiting for combat"
    elseif (tonumber(phase.receiving) or 0) > 0 then
      local receivedChunks = math.max(0, tonumber(phase.receivedChunks) or 0)
      local totalChunks = math.max(0, tonumber(phase.totalChunks) or 0)
      return totalChunks > 0 and ("Receiving " .. tostring(math.min(receivedChunks, totalChunks)) .. "/" .. tostring(totalChunks)) or "Receiving"
    elseif (tonumber(phase.sending) or 0) > 0 then
      local sentChunks = math.max(0, tonumber(phase.sentChunks) or 0)
      local totalChunks = math.max(0, tonumber(phase.totalChunks) or 0)
      return totalChunks > 0 and ("Sending " .. tostring(math.min(sentChunks, totalChunks)) .. "/" .. tostring(totalChunks)) or "Sending"
    elseif (tonumber(phase.queued) or 0) > 0 then
      return phase.rosterSettling and "Queued; roster settling" or "Queued"
    elseif (tonumber(phase.waiting_ack) or 0) > 0 then
      return "Sent; waiting for receipt"
    elseif (tonumber(phase.ack_timeout) or 0) > 0 then
      return "Receipt timed out"
    elseif (tonumber(phase.failed) or 0) > 0 then
      return "Send failed"
    end
    return ""
  end

  local function GetCompactTransferScopeLabel(scopeLabel)
    local resolvedScope = TrimText(scopeLabel)
    if resolvedScope == "Item History" then
      return "Items"
    elseif resolvedScope == "Session History" then
      return "Sessions"
    end
    return resolvedScope
  end

  local function GetPriorityRowLabel(state, phase, options)
    options = type(options) == "table" and options or {}
    local progressLabel = GetPriorityProgressLabel(phase)
    local scopeLabel = options.showScope == true and TrimText(type(phase) == "table" and phase.scopeLabel or "") or ""
    local dataReady, deliveryState = ResolvePriorityDataPresentation(state, phase)
    if dataReady then
      if deliveryState == "" then
        return ""
      end
      local compactScope = GetCompactTransferScopeLabel(scopeLabel)
      if deliveryState == "delivery_active" then
        local primaryState = string.lower(TrimText(type(phase) == "table" and phase.primaryState or ""))
        local completedChunks = math.max(
          0,
          primaryState == "receiving" and (tonumber(phase.receivedChunks) or 0)
            or (tonumber(phase.sentChunks) or 0)
        )
        local totalChunks = math.max(0, tonumber(type(phase) == "table" and phase.totalChunks) or 0)
        if compactScope ~= "" and totalChunks > 0 then
          return compactScope .. " " .. tostring(math.min(completedChunks, totalChunks)) .. "/" .. tostring(totalChunks)
        elseif totalChunks > 0 then
          return "Delivery " .. tostring(math.min(completedChunks, totalChunks)) .. "/" .. tostring(totalChunks)
        end
      end
      local deliveryLabels = {
        delivery_failed = "Delivery warning",
        receipt_timeout = "Receipt timeout",
        receipt_recovery = "Receipt recovery",
        apply_pending = "Apply pending",
        receipt_pending = "Receipt pending",
        delivery_active = "Delivery active",
      }
      local compactLabels = {
        delivery_failed = " warning",
        receipt_timeout = " timeout",
        receipt_recovery = " recovery",
        apply_pending = " apply",
        receipt_pending = " receipt",
        delivery_active = " delivery",
      }
      if compactScope ~= "" then
        return compactScope .. (compactLabels[deliveryState] or " delivery")
      end
      return deliveryLabels[deliveryState] or "Delivery active"
    end
    if scopeLabel ~= "" then
      local compactScope = GetCompactTransferScopeLabel(scopeLabel)
      local primaryState = string.lower(TrimText(type(phase) == "table" and phase.primaryState or ""))
      if primaryState == "sending" or primaryState == "receiving" then
        local completedChunks = math.max(
          0,
          primaryState == "sending" and phase.sentChunks or phase.receivedChunks or 0
        )
        local totalChunks = math.max(0, tonumber(phase.totalChunks) or 0)
        if totalChunks > 0 then
          return compactScope .. " " .. tostring(math.min(completedChunks, totalChunks)) .. "/" .. tostring(totalChunks)
        end
      elseif progressLabel == "Sent; waiting for receipt" then
        return compactScope .. " receipt"
      elseif progressLabel == "Receipt timed out" then
        return compactScope .. " timeout"
      elseif progressLabel == "Send failed" then
        return compactScope .. " failed"
      elseif progressLabel == "Paused by archive sync" then
        return compactScope .. " paused"
      elseif progressLabel:find("Recovery", 1, true) or progressLabel:find("Revalidating", 1, true) then
        return compactScope .. " recovery"
      elseif progressLabel == "Queued" or progressLabel == "Queued; roster settling" then
        return compactScope .. " queued"
      end
    end
    if progressLabel == "Received; waiting for combat" then
      return "Apply queued"
    elseif progressLabel == "Sent; waiting for receipt" then
      return "Receipt"
    elseif progressLabel == "Receipt timed out" then
      return "Timeout"
    elseif progressLabel == "Send failed" then
      return "Failed"
    elseif progressLabel == "Queued; roster settling" then
      return "Queued"
    elseif progressLabel ~= "" then
      return progressLabel:gsub("Sending", "Send"):gsub("Receiving", "Get")
    end
    local resolvedState = string.upper(TrimText(state))
    if resolvedState == "READY" then
      return ""
    elseif resolvedState == "REVIEW" then
      return "Review"
    elseif resolvedState == "VALIDATING" then
      return "Validating"
    elseif resolvedState == "STALE" then
      return "Archive differs"
    elseif options.showScope == true then
      return "Proof pending"
    end
    return "Proof pending"
  end

  local function SetPriorityRowText(fontString, state, phase, visible, options)
    if not fontString then
      return
    end
    if not visible then
      fontString:Hide()
      return
    end
    local label = GetPriorityRowLabel(state, phase, options)
    if label == "" then
      fontString:Hide()
      return
    end
    fontString:SetText(label)
    local lowerLabel = string.lower(label)
    if label == "Review" or label == "Failed" or label == "Timeout"
      or lowerLabel:find("failed", 1, true) or lowerLabel:find("warning", 1, true)
    then
      fontString:SetTextColor(0.95, 0.32, 0.26, 1)
    elseif lowerLabel:find("archive", 1, true) then
      fontString:SetTextColor(1.00, 0.78, 0.28, 1)
    elseif lowerLabel:find("send", 1, true) or lowerLabel:find("get", 1, true)
      or lowerLabel:find("delivery", 1, true) or label:find("/", 1, true)
      or lowerLabel:find("queued", 1, true) or label == "Validating"
    then
      fontString:SetTextColor(0.38, 0.72, 1.00, 1)
    elseif lowerLabel:find("receipt", 1, true) or lowerLabel:find("apply", 1, true)
      or lowerLabel:find("recovery", 1, true)
    then
      fontString:SetTextColor(1.00, 0.78, 0.28, 1)
    elseif lowerLabel:find("paused", 1, true) then
      fontString:SetTextColor(0.70, 0.74, 0.80, 1)
    elseif lowerLabel:find("proof", 1, true) then
      fontString:SetTextColor(0.62, 0.66, 0.72, 1)
    else
      fontString:SetTextColor(0.74, 0.78, 0.84, 1)
    end
    fontString:Show()
  end

  local GetPriorityTooltipStatus

  local function ApplySessionMemberPriorityTelemetry(editor, progressByMember, archiveSyncPaused, isHostView)
    if type(editor) ~= "table" then
      return
    end
    local showPriorityLabels = editor.__lidCurrentSessionShowPriorityLabels == true
    local showPriority3 = editor.__lidCurrentSessionShowPriority3 == true
    local showPriority3Detail = editor.__lidCurrentSessionShowPriority3Detail == true
    local showArchiveDetails = editor.__lidCurrentSessionShowArchiveDetails == true
    for _, row in ipairs(editor.lootSessionMemberRows or {}) do
      local memberKey = string.lower(TrimText(row.__memberKey))
      local states = type(row.__lidPriorityStates) == "table" and row.__lidPriorityStates or nil
      if memberKey ~= "" and states then
        local memberProgress = type(progressByMember) == "table" and progressByMember[memberKey] or {}
        local priority1 = memberProgress[1]
        local priority2 = memberProgress[2]
        local priority3 = memberProgress[3]
        local transferInFlight = type(priority3) == "table" and (
          (tonumber(priority3.sending) or 0) > 0
          or (tonumber(priority3.receiving) or 0) > 0
          or (tonumber(priority3.waiting_ack) or 0) > 0
          or (tonumber(priority3.waiting_apply) or 0) > 0
          or (tonumber(priority3.superseded_waiting_apply) or 0) > 0
        )
        if archiveSyncPaused == true and isHostView == true and not transferInFlight
          and string.upper(TrimText(states.priority3)) ~= "READY"
        then
          priority3 = type(priority3) == "table" and priority3 or {}
          priority3.archivePaused = true
          priority3.scopeLabel = TrimText(priority3.scopeLabel) ~= "" and priority3.scopeLabel or "Background"
          memberProgress[3] = priority3
        end
        ApplyPriorityPhaseIcon(row.priority1Icon, states.priority1, priority1)
        ApplyPriorityPhaseIcon(row.priority2Icon, states.priority2, priority2)
        ApplyPriorityPhaseIcon(
          row.priority3Icon,
          showArchiveDetails and states.archiveLootList or states.priority3,
          showArchiveDetails and {} or priority3
        )
        ApplyPriorityPhaseIcon(row.itemHistoryIcon, states.archiveItemHistory, {})
        ApplyPriorityPhaseIcon(row.sessionHistoryIcon, states.archiveSessionHistory, {})
        ApplyPriorityPhaseIcon(row.funAwardsIcon, states.archiveFunAwards, {})
        SetPriorityRowText(row.priority1Text, states.priority1, priority1, showPriorityLabels)
        SetPriorityRowText(row.priority2Text, states.priority2, priority2, showPriorityLabels)
        SetPriorityRowText(row.priority3Text, states.priority3, priority3, showPriority3Detail and showPriority3, {
          showScope = true,
        })
        local tooltip = type(row.__lidMemberTooltip) == "table" and row.__lidMemberTooltip or nil
        if tooltip then
          tooltip.priority1 = GetPriorityTooltipStatus(states.priority1, priority1)
          tooltip.priority1Color = { GetPriorityIndicatorTextColor(states.priority1, priority1) }
          tooltip.priority2 = select(3, GetPriorityTooltipStatus(states.priority2, priority2))
          tooltip.priority2Delivery = select(2, GetPriorityTooltipStatus(states.priority2, priority2))
          tooltip.priority2Color = { GetPriorityIndicatorTextColor(states.priority2, priority2) }
          tooltip.priority3 = select(3, GetPriorityTooltipStatus(states.priority3, priority3, true))
          tooltip.priority3Delivery = select(2, GetPriorityTooltipStatus(states.priority3, priority3, true))
          tooltip.priority3Color = { GetPriorityIndicatorTextColor(states.priority3, priority3) }
          tooltip.archiveLootList = GetPriorityTooltipStatus(states.archiveLootList, {})
          tooltip.archiveLootListColor = { GetPriorityIndicatorTextColor(states.archiveLootList, {}) }
          tooltip.archiveItemHistory = GetPriorityTooltipStatus(states.archiveItemHistory, {})
          tooltip.archiveItemHistoryColor = { GetPriorityIndicatorTextColor(states.archiveItemHistory, {}) }
          tooltip.archiveSessionHistory = GetPriorityTooltipStatus(states.archiveSessionHistory, {})
          tooltip.archiveSessionHistoryColor = { GetPriorityIndicatorTextColor(states.archiveSessionHistory, {}) }
          tooltip.archiveFunAwards = GetPriorityTooltipStatus(states.archiveFunAwards, {})
          tooltip.archiveFunAwardsColor = { GetPriorityIndicatorTextColor(states.archiveFunAwards, {}) }
        end
      end
    end
  end

  local function RefreshCurrentSessionPriorityTelemetry(editor)
    if type(editor) ~= "table" or type(GetSessionCommQueueStatus) ~= "function" then
      return false
    end
    local context = type(editor.__lidCurrentSessionPriorityContext) == "table"
      and editor.__lidCurrentSessionPriorityContext or nil
    if type(context) ~= "table" or type(context.activeSession) ~= "table" then
      return false
    end
    local ok, queueStatus = pcall(GetSessionCommQueueStatus)
    if not ok or type(queueStatus) ~= "table" then
      return false
    end
    local progressByMember = BuildSessionMemberPriorityProgressByMember(
      queueStatus,
      context.activeSession,
      context.selfCharacter
    )
    local isHostView = string.lower(TrimText(context.activeSession.host)) == string.lower(TrimText(context.selfCharacter))
    ApplySessionMemberPriorityTelemetry(editor, progressByMember, queueStatus.archiveSyncPaused == true, isHostView)
    return true
  end

  local function RefreshCurrentSessionRosterIfChanged(editor)
    if type(editor) ~= "table" or type(GetActiveLootSession) ~= "function"
      or type(BuildCurrentSessionStateSignature) ~= "function"
    then
      return false
    end
    local ok, activeSession = pcall(GetActiveLootSession)
    if not ok then
      return false
    end
    local signatureOk, currentSignature = pcall(BuildCurrentSessionStateSignature, activeSession)
    if not signatureOk then
      return false
    end
    currentSignature = type(currentSignature) == "string" and currentSignature or ""
    local previousSignature = editor.__lidCurrentSessionRosterSignature
    if previousSignature == nil then
      editor.__lidCurrentSessionRosterSignature = currentSignature
      return false
    end
    if previousSignature == currentSignature then
      return false
    end
    local refreshed = RefreshCurrentSessionSection(editor) == true
    if refreshed then
      editor.__lidCurrentSessionRosterSignature = currentSignature
    end
    return refreshed
  end

  GetPriorityTooltipStatus = function(state, phase, showScope)
    local phaseLabel = GetPriorityPhaseLabel(state)
    local progressLabel = GetPriorityProgressLabel(phase)
    local scopeLabel = showScope == true and TrimText(type(phase) == "table" and phase.scopeLabel or "") or ""
    local dataReady, deliveryState = ResolvePriorityDataPresentation(state, phase)
    local indicatorKind = ResolvePriorityIndicator(state, phase).kind
    local detail
    local deliveryLabel = ""
    local indicatorLabels = {
      ALIGNED = "Ready",
      PROGRESS = "Validating",
      DIFFERS = "Archive differs",
      UNKNOWN = "Proof unknown",
      FAILED = "Review required",
    }
    local dataLabel = indicatorLabels[indicatorKind] or phaseLabel
    if dataReady then
      detail = "Data ready"
      if deliveryState ~= "" then
        local alignedDeliveryLabels = {
          delivery_failed = "Send failed",
          receipt_timeout = "Receipt timed out",
          receipt_recovery = TrimText(type(phase) == "table" and phase.recoveryLabel or ""),
          apply_pending = "Received; waiting for combat",
          receipt_pending = "Sent; waiting for receipt",
          delivery_active = progressLabel,
        }
        deliveryLabel = TrimText(alignedDeliveryLabels[deliveryState])
        if deliveryLabel ~= "" then
          detail = detail .. " | Delivery: " .. deliveryLabel
        end
      end
    else
      detail = progressLabel ~= "" and (dataLabel .. " | " .. progressLabel) or dataLabel
      deliveryLabel = progressLabel
    end
    if scopeLabel ~= "" then
      detail = scopeLabel .. " | " .. detail
      if deliveryLabel ~= "" then
        deliveryLabel = scopeLabel .. " | " .. deliveryLabel
      end
    end
    local acknowledgementAge = math.max(0, tonumber(type(phase) == "table" and phase.acknowledgementAgeSeconds) or 0)
    if acknowledgementAge > 0 and (tonumber(type(phase) == "table" and phase.waiting_ack) or 0) > 0 then
      detail = detail .. " | " .. tostring(acknowledgementAge) .. "s waiting for receipt"
      deliveryLabel = (deliveryLabel ~= "" and (deliveryLabel .. " | ") or "")
        .. tostring(acknowledgementAge) .. "s waiting for receipt"
    end
    local failureReason = TrimText(type(phase) == "table" and phase.failureReason or "")
    if failureReason ~= "" then
      detail = detail .. " | " .. failureReason
      deliveryLabel = (deliveryLabel ~= "" and (deliveryLabel .. " | ") or "") .. failureReason
    end
    return detail, deliveryLabel, dataLabel
  end

  local function BuildPriorityPresentationForValidation(state, phase, showScope)
    local dataReady, deliveryState = ResolvePriorityDataPresentation(state, phase)
    local indicator = ResolvePriorityIndicator(state, phase)
    return {
      dataReady = dataReady,
      deliveryState = deliveryState,
      indicatorKind = indicator.kind,
      indicatorTexture = indicator.texture,
      rowLabel = GetPriorityRowLabel(state, phase, { showScope = showScope == true }),
      tooltip = GetPriorityTooltipStatus(state, phase, showScope == true),
    }
  end

  local function BuildSessionMemberRowsData(activeSession, profile, selfCharacter, syncCandidates, queueStatus)
    local rows = {}
    if type(activeSession) ~= "table" or type(activeSession.members) ~= "table" then
      return rows
    end

    local syncCandidateByMemberKey = {}
    for _, candidate in ipairs(type(syncCandidates) == "table" and syncCandidates or {}) do
      local candidateKey = string.lower(TrimText(type(candidate) == "table" and candidate.memberKey or ""))
      if candidateKey ~= "" then
        syncCandidateByMemberKey[candidateKey] = candidate
      end
    end
    local priorityProgressByMember = BuildSessionMemberPriorityProgressByMember(queueStatus, activeSession, selfCharacter)
    local resolvedHostKey = string.lower(TrimText(activeSession.host))
    local hostMember = nil
    for hostMemberKey, candidateHostMember in pairs(activeSession.members or {}) do
      if string.lower(TrimText(hostMemberKey)) == resolvedHostKey and type(candidateHostMember) == "table" then
        hostMember = candidateHostMember
        break
      end
    end
    local p2DiagnosticContext = {}

    local function ResolveArchiveScopeState(member, memberKey, checksumField, matrixField, hostStatusMatrix)
      if string.lower(TrimText(memberKey)) == resolvedHostKey then
        return "READY"
      end
      local hostChecksum = TrimText(type(hostMember) == "table" and hostMember[checksumField] or "")
      local memberChecksum = TrimText(type(member) == "table" and member[checksumField] or "")
      if hostChecksum ~= "" and memberChecksum ~= "" then
        if string.lower(hostChecksum) == string.lower(memberChecksum) then
          return "READY"
        end
        if type(hostStatusMatrix) == "table" and TrimText(hostStatusMatrix[matrixField]) ~= "" then
          return hostStatusMatrix[matrixField]
        end
        return "STALE"
      end
      if type(hostStatusMatrix) == "table" and TrimText(hostStatusMatrix[matrixField]) ~= "" then
        return hostStatusMatrix[matrixField]
      end
      return "PENDING"
    end

    for memberKey, member in pairs(activeSession.members or {}) do
      local resolvedKey = TrimText(memberKey ~= "" and memberKey or (type(member) == "table" and member.name) or "")
      if resolvedKey ~= "" then
        local memberStatus = TrimText(type(member) == "table" and member.status or "JOINED")
        -- LEFT entries remain in the session roster for sync cleanup and audit,
        -- but the Joined Members table must contain active participants only.
        if string.upper(memberStatus) == "JOINED" then
          local displayInfo = ResolveSessionDisplayInfo(profile, resolvedKey, member)
          local hostStatusMatrix = type(INTERNAL_API.LIDCOUNCIL_GetHostMemberSyncStatusMatrix) == "function"
            and INTERNAL_API.LIDCOUNCIL_GetHostMemberSyncStatusMatrix(member)
            or nil
          local syncState = ResolveSessionSyncState(member, resolvedKey, activeSession, selfCharacter)
          local p2ProofDiagnostics = syncState ~= "SYNCED"
            and type(GetMemberP2ProofDiagnostics) == "function"
            and GetMemberP2ProofDiagnostics(
              activeSession,
              activeSession.profileName,
              resolvedKey,
              member,
              selfCharacter,
              p2DiagnosticContext
            )
            or nil
          local bootstrapState = ResolveSessionBootstrapState(member, resolvedKey, activeSession, selfCharacter)
          local historyState = type(ResolveSessionHistorySyncState) == "function"
            and ResolveSessionHistorySyncState(
              member,
              resolvedKey,
              activeSession,
              selfCharacter,
              syncCandidateByMemberKey[string.lower(resolvedKey)],
              true
            )
            or "PENDING"
          local priorityProgress = priorityProgressByMember[string.lower(resolvedKey)]
          local isHostView = string.lower(TrimText(activeSession.host)) == string.lower(TrimText(selfCharacter))
          if isHostView and queueStatus and queueStatus.archiveSyncPaused == true
            and historyState ~= "READY"
          then
            priorityProgress = type(priorityProgress) == "table" and priorityProgress or {}
            priorityProgressByMember[string.lower(resolvedKey)] = priorityProgress
            priorityProgress[3] = type(priorityProgress[3]) == "table" and priorityProgress[3] or {}
            local priority3 = priorityProgress[3]
            local transferInFlight = (tonumber(priority3.sending) or 0) > 0
              or (tonumber(priority3.receiving) or 0) > 0
              or (tonumber(priority3.waiting_ack) or 0) > 0
              or (tonumber(priority3.waiting_apply) or 0) > 0
              or (tonumber(priority3.superseded_waiting_apply) or 0) > 0
            if not transferInFlight then
              priority3.archivePaused = true
              priority3.scopeLabel = priority3.scopeLabel or "Background"
            end
          end
          local localAutoPassEnabled = type(member) == "table" and member.localAutoPassEnabled
          local isSelfMember = string.lower(resolvedKey) == string.lower(TrimText(selfCharacter))
          if isSelfMember and type(GetLocalAutoPassEnabled) == "function" then
            localAutoPassEnabled = GetLocalAutoPassEnabled() and true or false
          end
          if localAutoPassEnabled == nil then
            localAutoPassEnabled = false
          end
          rows[#rows + 1] = {
            key = resolvedKey,
            name = resolvedKey,
            status = memberStatus,
            joinedAt = tonumber(type(member) == "table" and member.joinedAt) or nil,
            addonVersion = TrimText(type(member) == "table" and member.addonVersion or ""),
            clientVersion = TrimText(type(member) == "table" and member.clientVersion or ""),
            className = displayInfo.className,
            classFile = displayInfo.classFile,
            specName = displayInfo.specName,
            specIcon = displayInfo.specIcon,
            localAutoPassEnabled = localAutoPassEnabled and true or false,
            syncState = syncState,
            p2ProofDiagnostics = p2ProofDiagnostics,
            bootstrapState = bootstrapState,
            historyState = historyState,
            archiveStates = {
              lootList = ResolveArchiveScopeState(
                member,
                resolvedKey,
                "lootListArchiveChecksum",
                "lootList",
                hostStatusMatrix
              ),
              itemHistory = ResolveArchiveScopeState(
                member,
                resolvedKey,
                "itemHistoryArchiveChecksum",
                "itemHistory",
                hostStatusMatrix
              ),
              sessionHistory = ResolveArchiveScopeState(
                member,
                resolvedKey,
                "sessionHistoryArchiveChecksum",
                "sessionHistory",
                hostStatusMatrix
              ),
              funAwards = ResolveArchiveScopeState(
                member,
                resolvedKey,
                "funAwardsArchiveChecksum",
                "funAwards",
                hostStatusMatrix
              ),
            },
            lootListDifferenceDiagnostics = type(GetMemberLootListDifferenceDiagnostics) == "function"
              and GetMemberLootListDifferenceDiagnostics(activeSession.id, resolvedKey)
              or nil,
            itemHistoryDifferenceDiagnostics = type(GetMemberItemHistoryDifferenceDiagnostics) == "function"
              and GetMemberItemHistoryDifferenceDiagnostics(activeSession.id, resolvedKey)
              or nil,
            sessionHistoryDifferenceDiagnostics = type(GetMemberSessionHistoryDifferenceDiagnostics) == "function"
              and GetMemberSessionHistoryDifferenceDiagnostics(activeSession.id, resolvedKey)
              or nil,
            priorityProgress = priorityProgress,
            recoveryInfo = ResolveSessionMemberRecoveryInfo(member),
            isHost = resolvedKey == TrimText(activeSession.host),
            isSelf = resolvedKey == TrimText(selfCharacter),
          }
        end
      end
    end

    table.sort(rows, function(a, b)
      if a.isHost ~= b.isHost then
        return a.isHost
      end
      local aStatus = string.upper(TrimText(a.status))
      local bStatus = string.upper(TrimText(b.status))
      if aStatus ~= bStatus then
        if aStatus == "JOINED" then
          return true
        elseif bStatus == "JOINED" then
          return false
        end
      end
      return string.lower(tostring(a.name or "")) < string.lower(tostring(b.name or ""))
    end)

    return rows
  end

  local function ResolveOverallSyncState(rows)
    local joinedCount = 0
    local syncedCount = 0
    local partialCount = 0
    for _, row in ipairs(rows or {}) do
      if string.upper(TrimText(row.status)) == "JOINED" then
        joinedCount = joinedCount + 1
        if row.syncState == "SYNCED" then
          syncedCount = syncedCount + 1
        elseif row.syncState == "PARTIAL" then
          partialCount = partialCount + 1
        end
      end
    end

    if joinedCount > 0 and syncedCount == joinedCount then
      return "SYNCED"
    elseif syncedCount > 0 or partialCount > 0 then
      return "PARTIAL"
    end
    return "PENDING"
  end

  local function ResolveOverallSyncPresentationState(rows)
    local liveState = ResolveOverallSyncState(rows)
    if liveState ~= "SYNCED" then
      return liveState
    end

    for _, row in ipairs(rows or {}) do
      if string.upper(TrimText(row.status)) == "JOINED"
        and string.upper(TrimText(row.bootstrapState)) ~= "READY"
      then
        return "PARTIAL"
      end
    end

    local hasArchiveProgress = false
    local hasArchiveDifference = false
    local hasArchiveUnknown = false
    local hasArchiveFailure = false
    for _, row in ipairs(rows or {}) do
      if string.upper(TrimText(row.status)) == "JOINED" then
        local archiveStates = type(row.archiveStates) == "table" and row.archiveStates or {}
        local states = {
          TrimText(row.historyState),
          TrimText(archiveStates.lootList),
          TrimText(archiveStates.itemHistory),
          TrimText(archiveStates.sessionHistory),
          TrimText(archiveStates.funAwards),
        }
        for _, state in ipairs(states) do
          local resolvedState = string.upper(TrimText(state))
          if resolvedState == "REVIEW" then
            hasArchiveFailure = true
          elseif resolvedState == "VALIDATING" then
            hasArchiveProgress = true
          elseif resolvedState == "STALE" then
            hasArchiveDifference = true
          elseif resolvedState ~= "READY" then
            hasArchiveUnknown = true
          end
        end

        local priorityProgress = type(row.priorityProgress) == "table" and row.priorityProgress or {}
        local phase = type(priorityProgress[3]) == "table" and priorityProgress[3] or {}
        if (tonumber(phase.failed) or 0) > 0 then
          hasArchiveFailure = true
        elseif (tonumber(phase.sending) or 0) > 0
          or (tonumber(phase.receiving) or 0) > 0
          or (tonumber(phase.queued) or 0) > 0
          or (tonumber(phase.waiting_ack) or 0) > 0
          or (tonumber(phase.waiting_apply) or 0) > 0
          or (tonumber(phase.superseded_waiting_apply) or 0) > 0
        then
          hasArchiveProgress = true
        elseif (tonumber(phase.ack_timeout) or 0) > 0 then
          hasArchiveDifference = true
        end
      end
    end

    if hasArchiveFailure then
      return "ARCHIVE_REVIEW"
    elseif hasArchiveProgress then
      return "ARCHIVE_SYNCING"
    elseif hasArchiveDifference then
      return "ARCHIVE_DIFFERS"
    elseif hasArchiveUnknown then
      return "ARCHIVE_UNKNOWN"
    end
    return "SYNCED"
  end

  local function ResolveOverallBootstrapCounts(rows)
    local counts = {
      joined = 0,
      ready = 0,
      pending = 0,
      review = 0,
    }
    for _, row in ipairs(rows or {}) do
      if string.upper(TrimText(row.status)) == "JOINED" then
        counts.joined = counts.joined + 1
        local bootstrapState = string.upper(TrimText(row.bootstrapState))
        if bootstrapState == "READY" then
          counts.ready = counts.ready + 1
        elseif bootstrapState == "REVIEW" then
          counts.review = counts.review + 1
        else
          counts.pending = counts.pending + 1
        end
      end
    end
    return counts
  end

  local function EnsureSessionMemberRows(editor, count)
    if not editor or not editor.lootSessionMemberRowsFrame then
      return
    end
    editor.lootSessionMemberRows = editor.lootSessionMemberRows or {}
    while #(editor.lootSessionMemberRows or {}) < count do
      local row = CreateFrame("Frame", nil, editor.lootSessionMemberRowsFrame, "BackdropTemplate")
      ApplyFrameSkin(row)
      row:SetHeight(34)

      local selectionFill = row:CreateTexture(nil, "BORDER")
      selectionFill:SetTexture("Interface\\Buttons\\WHITE8x8")
      selectionFill:SetPoint("TOPLEFT", 1, -1)
      selectionFill:SetPoint("BOTTOMRIGHT", -1, 1)
      selectionFill:SetVertexColor(0.34, 0.52, 0.78, 0.20)
      selectionFill:Hide()
      row.selectionFill = selectionFill

      local selectionStripe = row:CreateTexture(nil, "ARTWORK")
      selectionStripe:SetTexture("Interface\\Buttons\\WHITE8x8")
      selectionStripe:SetPoint("TOPLEFT", 2, -2)
      selectionStripe:SetPoint("BOTTOMLEFT", 2, 2)
      selectionStripe:SetWidth(4)
      selectionStripe:SetVertexColor(1.00, 0.82, 0.32, 0.95)
      selectionStripe:Hide()
      row.selectionStripe = selectionStripe

      local icon = row:CreateTexture(nil, "ARTWORK")
      icon:SetSize(18, 18)
      row.icon = icon

      local nameText = row:CreateFontString(nil, "OVERLAY", "GameFontNormal")
      nameText:SetJustifyH("LEFT")
      if nameText.SetMaxLines then
        nameText:SetMaxLines(1)
      end
      row.nameText = nameText

      local metaText = row:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
      metaText:SetJustifyH("LEFT")
      if metaText.SetMaxLines then
        metaText:SetMaxLines(1)
      end
      row.metaText = metaText

      local syncDot = row:CreateTexture(nil, "ARTWORK")
      syncDot:SetSize(8, 8)
      row.syncDot = syncDot

      local syncText = row:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
      syncText:SetJustifyH("LEFT")
      if syncText.SetMaxLines then
        syncText:SetMaxLines(1)
      end
      row.syncText = syncText

      local versionText = row:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
      versionText:SetJustifyH("LEFT")
      if versionText.SetMaxLines then
        versionText:SetMaxLines(1)
      end
      row.versionText = versionText

      local autoPassText = row:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
      autoPassText:SetJustifyH("LEFT")
      if autoPassText.SetMaxLines then
        autoPassText:SetMaxLines(1)
      end
      row.autoPassText = autoPassText

      local statusText = row:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
      statusText:SetJustifyH("LEFT")
      if statusText.SetMaxLines then
        statusText:SetMaxLines(1)
      end
      row.statusText = statusText

      local priority1Icon = row:CreateTexture(nil, "ARTWORK")
      priority1Icon:SetSize(16, 16)
      row.priority1Icon = priority1Icon

      local priority2Icon = row:CreateTexture(nil, "ARTWORK")
      priority2Icon:SetSize(16, 16)
      row.priority2Icon = priority2Icon

      local priority3Icon = row:CreateTexture(nil, "ARTWORK")
      priority3Icon:SetSize(16, 16)
      row.priority3Icon = priority3Icon

      row.itemHistoryIcon = row:CreateTexture(nil, "ARTWORK")
      row.itemHistoryIcon:SetSize(16, 16)
      row.sessionHistoryIcon = row:CreateTexture(nil, "ARTWORK")
      row.sessionHistoryIcon:SetSize(16, 16)
      row.funAwardsIcon = row:CreateTexture(nil, "ARTWORK")
      row.funAwardsIcon:SetSize(16, 16)

      local priority1Text = row:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
      priority1Text:SetJustifyH("CENTER")
      if priority1Text.SetMaxLines then
        priority1Text:SetMaxLines(1)
      end
      row.priority1Text = priority1Text

      local priority2Text = row:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
      priority2Text:SetJustifyH("CENTER")
      if priority2Text.SetMaxLines then
        priority2Text:SetMaxLines(1)
      end
      row.priority2Text = priority2Text

      local priority3Text = row:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
      priority3Text:SetJustifyH("CENTER")
      if priority3Text.SetMaxLines then
        priority3Text:SetMaxLines(1)
      end
      row.priority3Text = priority3Text

      local joinedText = row:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
      joinedText:SetJustifyH("LEFT")
      if joinedText.SetMaxLines then
        joinedText:SetMaxLines(1)
      end
      row.joinedText = joinedText

      row:SetScript("OnEnter", function(self)
        if not GameTooltip or type(self.__lidMemberTooltip) ~= "table" then
          return
        end
        local details = self.__lidMemberTooltip
        local function AddPriorityStatusLine(label, value, color)
          color = type(color) == "table" and color or { 0.82, 0.86, 0.92, 1 }
          GameTooltip:AddDoubleLine(
            label,
            tostring(value or "Waiting"),
            0.82,
            0.86,
            0.92,
            color[1] or 0.82,
            color[2] or 0.86,
            color[3] or 0.92
          )
        end
        GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
        GameTooltip:SetText(tostring(details.name or "Member"), details.r or 0.92, details.g or 0.96, details.b or 1.00)
        GameTooltip:AddLine(tostring(details.role or "Unknown role"), 0.82, 0.86, 0.92, true)
        AddPriorityStatusLine("P1 Raid-ready", details.priority1, details.priority1Color)
        AddPriorityStatusLine("P2 Current Session State", details.priority2, details.priority2Color)
        if tostring(details.priority2Delivery or "") ~= "" then
          GameTooltip:AddDoubleLine("P2 Delivery", tostring(details.priority2Delivery), 0.82, 0.86, 0.92, 0.40, 0.72, 1.00)
        end
        local p2Diagnostics = type(details.p2ProofDiagnostics) == "table"
          and details.p2ProofDiagnostics
          or nil
        if type(p2Diagnostics) == "table"
          and tostring(p2Diagnostics.state or "") ~= "READY"
          and tostring(p2Diagnostics.label or "") ~= ""
        then
          local diagnosticState = string.upper(tostring(p2Diagnostics.state or "PENDING"))
          local diagnosticColor = diagnosticState == "REVIEW"
            and { 1.00, 0.78, 0.28 }
            or { 0.40, 0.72, 1.00 }
          GameTooltip:AddLine(
            "P2 Diagnostic: " .. tostring(p2Diagnostics.label),
            diagnosticColor[1],
            diagnosticColor[2],
            diagnosticColor[3],
            true
          )
          if tostring(p2Diagnostics.detail or "") ~= "" then
            GameTooltip:AddLine(tostring(p2Diagnostics.detail), 0.68, 0.74, 0.84, true)
          end
        end
        AddPriorityStatusLine("P3 Archive Data", details.priority3, details.priority3Color)
        if tostring(details.priority3Delivery or "") ~= "" then
          GameTooltip:AddDoubleLine("P3 Delivery", tostring(details.priority3Delivery), 0.82, 0.86, 0.92, 0.40, 0.72, 1.00)
        end
        AddPriorityStatusLine("Loot List", details.archiveLootList, details.archiveLootListColor)
        local lootListDiagnostics = type(details.lootListDiagnostics) == "table"
          and details.lootListDiagnostics
          or nil
        if type(lootListDiagnostics) == "table"
          and lootListDiagnostics.available == true
          and string.upper(tostring(details.archiveLootListState or "")) == "STALE"
        then
          local differenceCount = math.max(0, tonumber(lootListDiagnostics.count) or 0)
          if differenceCount > 0 then
            GameTooltip:AddLine(
              "Exact Loot List difference" .. (differenceCount == 1 and "" or "s"),
              1.00,
              0.78,
              0.28,
              true
            )
            local shown = 0
            for _, leaf in ipairs(type(lootListDiagnostics.leaves) == "table" and lootListDiagnostics.leaves or {}) do
              if shown >= 6 then
                break
              end
              shown = shown + 1
              local label = TrimText(type(leaf) == "table" and leaf.label or "")
              local status = TrimText(type(leaf) == "table" and leaf.status or "")
              local detail = TrimText(type(leaf) == "table" and leaf.detail or "")
              local subdomain = TrimText(type(leaf) == "table" and leaf.subdomain or "")
              GameTooltip:AddLine(
                (label ~= "" and label or subdomain) .. (status ~= "" and (" - " .. status) or ""),
                1.00,
                0.86,
                0.54,
                true
              )
              if detail ~= "" then
                GameTooltip:AddLine(detail, 0.72, 0.76, 0.84, true)
              end
              if subdomain ~= "" then
                GameTooltip:AddLine(subdomain, 0.62, 0.68, 0.76, true)
              end
            end
            local remaining = math.max(0, differenceCount - shown)
            if remaining > 0 then
              GameTooltip:AddLine("+ " .. tostring(remaining) .. " more differing leaves", 0.72, 0.76, 0.82, true)
            end
          elseif lootListDiagnostics.aggregateDiffers == true then
            GameTooltip:AddLine("Loot List aggregate checksum differs", 1.00, 0.78, 0.28, true)
            GameTooltip:AddLine(
              "No individual leaf mismatch was found in the completed proof.",
              0.72,
              0.76,
              0.84,
              true
            )
          end
        end
        AddPriorityStatusLine("Item History", details.archiveItemHistory, details.archiveItemHistoryColor)
        local itemHistoryDiagnostics = type(details.itemHistoryDiagnostics) == "table"
          and details.itemHistoryDiagnostics
          or nil
        if type(itemHistoryDiagnostics) == "table"
          and itemHistoryDiagnostics.available == true
          and (tonumber(itemHistoryDiagnostics.count) or 0) > 0
          and string.upper(tostring(details.archiveItemHistoryState or "")) == "STALE"
        then
          GameTooltip:AddLine(
            "Exact Item History difference" .. ((tonumber(itemHistoryDiagnostics.count) or 0) == 1 and "" or "s"),
            1.00,
            0.78,
            0.28,
            true
          )
          local shown = 0
          for _, leaf in ipairs(type(itemHistoryDiagnostics.leaves) == "table" and itemHistoryDiagnostics.leaves or {}) do
            if shown >= 6 then
              break
            end
            shown = shown + 1
            local label = TrimText(type(leaf) == "table" and leaf.label or "")
            local status = TrimText(type(leaf) == "table" and leaf.status or "")
            local subdomain = TrimText(type(leaf) == "table" and leaf.subdomain or "")
            GameTooltip:AddLine(
              (label ~= "" and label or subdomain) .. (status ~= "" and (" - " .. status) or ""),
              1.00,
              0.86,
              0.54,
              true
            )
            if subdomain ~= "" then
              GameTooltip:AddLine(subdomain, 0.62, 0.68, 0.76, true)
            end
          end
          local remaining = math.max(0, (tonumber(itemHistoryDiagnostics.count) or 0) - shown)
          if remaining > 0 then
            GameTooltip:AddLine("+ " .. tostring(remaining) .. " more differing leaves", 0.72, 0.76, 0.82, true)
          end
        end
        AddPriorityStatusLine("Session History", details.archiveSessionHistory, details.archiveSessionHistoryColor)
        local sessionHistoryDiagnostics = type(details.sessionHistoryDiagnostics) == "table"
          and details.sessionHistoryDiagnostics
          or nil
        if type(sessionHistoryDiagnostics) == "table"
          and sessionHistoryDiagnostics.available == true
          and (tonumber(sessionHistoryDiagnostics.count) or 0) > 0
          and string.upper(tostring(details.archiveSessionHistoryState or "")) == "STALE"
        then
          GameTooltip:AddLine(
            "Exact Session History difference" .. ((tonumber(sessionHistoryDiagnostics.count) or 0) == 1 and "" or "s"),
            1.00,
            0.78,
            0.28,
            true
          )
          local shown = 0
          for _, leaf in ipairs(type(sessionHistoryDiagnostics.leaves) == "table" and sessionHistoryDiagnostics.leaves or {}) do
            if shown >= 6 then
              break
            end
            shown = shown + 1
            local label = TrimText(type(leaf) == "table" and leaf.label or "")
            local status = TrimText(type(leaf) == "table" and leaf.status or "")
            local subdomain = TrimText(type(leaf) == "table" and leaf.subdomain or "")
            GameTooltip:AddLine(
              (label ~= "" and label or subdomain) .. (status ~= "" and (" - " .. status) or ""),
              1.00,
              0.86,
              0.54,
              true
            )
            if subdomain ~= "" then
              GameTooltip:AddLine(subdomain, 0.62, 0.68, 0.76, true)
            end
          end
          local remaining = math.max(0, (tonumber(sessionHistoryDiagnostics.count) or 0) - shown)
          if remaining > 0 then
            GameTooltip:AddLine("+ " .. tostring(remaining) .. " more differing leaves", 0.72, 0.76, 0.82, true)
          end
        end
        AddPriorityStatusLine("Fun Awards", details.archiveFunAwards, details.archiveFunAwardsColor)
        GameTooltip:AddDoubleLine("Sync", tostring(details.sync or "Waiting"), 0.82, 0.86, 0.92, 0.82, 0.86, 0.92)
        GameTooltip:AddDoubleLine("Join status", tostring(details.status or "JOINED"), 0.82, 0.86, 0.92, 0.82, 0.86, 0.92)
        if tostring(details.recovery or "") ~= "" then
          GameTooltip:AddDoubleLine("Background recovery", tostring(details.recovery), 0.82, 0.86, 0.92, 1.00, 0.82, 0.28)
        end
        GameTooltip:AddDoubleLine("Auto-Pass", tostring(details.autoPass or "ON"), 0.82, 0.86, 0.92, 0.82, 0.86, 0.92)
        GameTooltip:AddDoubleLine("Addon version", tostring(details.addonVersion or "Legacy"), 0.82, 0.86, 0.92, 0.82, 0.86, 0.92)
        if tostring(details.clientVersion or "") ~= "" then
          GameTooltip:AddDoubleLine("WoW client", tostring(details.clientVersion), 0.82, 0.86, 0.92, 0.82, 0.86, 0.92)
        end
        if tostring(details.joinedAt or "") ~= "" then
          GameTooltip:AddDoubleLine("Joined", tostring(details.joinedAt), 0.82, 0.86, 0.92, 0.82, 0.86, 0.92)
        end
        GameTooltip:Show()
      end)
      row:SetScript("OnLeave", function()
        if GameTooltip then
          GameTooltip:Hide()
        end
      end)

      editor.lootSessionMemberRows[#editor.lootSessionMemberRows + 1] = row
    end
  end

  local function RefreshCurrentSessionView(editor, context)
    if not editor then
      return
    end
    context = type(context) == "table" and context or {}

    local activeSession = context.activeSession
    local activeSessionProfile = context.activeSessionProfile
    local selfCharacter = TrimText(context.selfCharacter)
    local activeSessionIsHost = context.activeSessionIsHost and true or false
    local activeSessionIsJoined = context.activeSessionIsJoined and true or false
    local activeProfileName = context.activeProfileName
    local syntheticDisplayProfileName = TrimText(context.syntheticDisplayProfileName)
    local syntheticSession = context.syntheticSession and true or false
    local profileName = context.profileName
    local roleLabel = tostring(context.roleLabel or "")
    local liveSummaryState = context.liveSummaryState
    local syncCandidates = type(context.syncCandidates) == "table" and context.syncCandidates or {}
    if type(BuildCurrentSessionStateSignature) == "function" then
      local signatureOk, currentSignature = pcall(BuildCurrentSessionStateSignature, activeSession)
      if signatureOk then
        editor.__lidCurrentSessionRosterSignature = type(currentSignature) == "string" and currentSignature or ""
      end
    end
    editor.__lidCurrentSessionPriorityContext = type(activeSession) == "table" and {
      activeSession = activeSession,
      selfCharacter = selfCharacter,
    } or nil

    local memberRowsData = activeSession and BuildSessionMemberRowsData(
      activeSession,
      activeSessionProfile,
      selfCharacter,
      syncCandidates,
      context.queueStatus
    ) or {}
    local overallSyncPresentationState = ResolveOverallSyncPresentationState(memberRowsData)
    local overallBootstrapCounts = ResolveOverallBootstrapCounts(memberRowsData)

    EnsureSessionMemberRows(editor, math.max(1, #memberRowsData))
    local selectedMemberKey = TrimText(editor.lootSessionSelectedMemberKey)
    local selectedStillVisible = false
    for index, row in ipairs(editor.lootSessionMemberRows or {}) do
      local data = memberRowsData[index]
      if data then
        if selectedMemberKey ~= "" and string.lower(selectedMemberKey) == string.lower(data.key) then
          selectedStillVisible = true
        end
        local iconData = ResolveSessionIconData(data)
        local r, g, b = GetSessionClassColor(data.classFile)
        local memberSyncPresentationState = ResolveOverallSyncPresentationState({ data })
        local syncR, syncG, syncB = GetTrafficLightColor(memberSyncPresentationState)
        local bootstrapR, bootstrapG, bootstrapB = GetSessionBootstrapColor(data.bootstrapState)
        local statusR, statusG, statusB = GetSessionStatusColor(data.status)
        local recoveryInfo = type(data.recoveryInfo) == "table" and data.recoveryInfo or nil
        local priority2State = data.syncState == "SYNCED" and "READY"
          or (string.upper(TrimText(data.bootstrapState)) == "REVIEW" and "REVIEW" or "PENDING")
        local priorityProgress = type(data.priorityProgress) == "table" and data.priorityProgress or {}
        local archiveStates = type(data.archiveStates) == "table" and data.archiveStates or {}
        local roleText = data.specName ~= "" and data.specName or (data.className ~= "" and data.className or "Unknown")
        if data.isHost then
          roleText = roleText .. " | Host"
        elseif data.isSelf then
          roleText = roleText .. " | You"
        end
        ApplySessionIcon(row.icon, iconData)
        row.nameText:SetText(data.name)
        row.nameText:SetTextColor(r, g, b, 1)
        row.metaText:SetText(roleText)
        row.metaText:SetTextColor(0.72, 0.78, 0.84, 1)
        row.__lidMemberRoleText = roleText
        ApplyTrafficLight(row.syncDot, memberSyncPresentationState)
        row.syncText:SetText(GetSessionSyncLabel(memberSyncPresentationState))
        row.syncText:SetTextColor(syncR, syncG, syncB, 1)
        ApplyPriorityPhaseIcon(row.priority1Icon, data.bootstrapState, priorityProgress[1])
        ApplyPriorityPhaseIcon(row.priority2Icon, priority2State, priorityProgress[2])
        ApplyPriorityPhaseIcon(row.priority3Icon, data.historyState, priorityProgress[3])
        ApplyPriorityPhaseIcon(row.itemHistoryIcon, archiveStates.itemHistory, {})
        ApplyPriorityPhaseIcon(row.sessionHistoryIcon, archiveStates.sessionHistory, {})
        ApplyPriorityPhaseIcon(row.funAwardsIcon, archiveStates.funAwards, {})
        SetPriorityRowText(row.priority1Text, data.bootstrapState, priorityProgress[1], true)
        SetPriorityRowText(row.priority2Text, priority2State, priorityProgress[2], true)
        SetPriorityRowText(row.priority3Text, data.historyState, priorityProgress[3], true, {
          showScope = true,
        })
        row.__lidPriorityStates = {
          priority1 = data.bootstrapState,
          priority2 = priority2State,
          priority3 = data.historyState,
          archiveLootList = archiveStates.lootList,
          archiveItemHistory = archiveStates.itemHistory,
          archiveSessionHistory = archiveStates.sessionHistory,
          archiveFunAwards = archiveStates.funAwards,
        }
        row.autoPassText:SetText(data.localAutoPassEnabled and "ON" or "OFF")
        row.autoPassText:SetTextColor(
          data.localAutoPassEnabled and 0.30 or 1.00,
          data.localAutoPassEnabled and 0.90 or 0.32,
          data.localAutoPassEnabled and 0.36 or 0.24,
          1
        )
        row.versionText:Hide()
        -- Join status must describe session membership. Recovery work continues
        -- independently and is exposed in the tooltip instead of replacing JOINED.
        row.statusText:SetText(TrimText(data.status) ~= "" and data.status or "JOINED")
        row.statusText:SetTextColor(statusR, statusG, statusB, 1)
        row.__lidMemberJoinText = row.statusText:GetText()
        row.joinedText:Hide()
        row.__lidMemberTooltip = {
          name = data.name,
          role = roleText .. " | " .. GetSessionBootstrapLabel(data.bootstrapState),
          sync = GetSessionSyncLabel(memberSyncPresentationState),
          status = row.statusText:GetText(),
          priority1 = GetPriorityTooltipStatus(data.bootstrapState, priorityProgress[1]),
          priority1Color = { GetPriorityIndicatorTextColor(data.bootstrapState, priorityProgress[1]) },
          priority2 = select(3, GetPriorityTooltipStatus(priority2State, priorityProgress[2])),
          priority2Delivery = select(2, GetPriorityTooltipStatus(priority2State, priorityProgress[2])),
          priority2Color = { GetPriorityIndicatorTextColor(priority2State, priorityProgress[2]) },
          p2ProofDiagnostics = data.p2ProofDiagnostics,
          priority3 = select(3, GetPriorityTooltipStatus(data.historyState, priorityProgress[3], true)),
          priority3Delivery = select(2, GetPriorityTooltipStatus(data.historyState, priorityProgress[3], true)),
          priority3Color = { GetPriorityIndicatorTextColor(data.historyState, priorityProgress[3]) },
          archiveLootList = GetPriorityTooltipStatus(archiveStates.lootList, {}),
          archiveLootListColor = { GetPriorityIndicatorTextColor(archiveStates.lootList, {}) },
          archiveLootListState = archiveStates.lootList,
          lootListDiagnostics = data.lootListDifferenceDiagnostics,
          archiveItemHistory = GetPriorityTooltipStatus(archiveStates.itemHistory, {}),
          archiveItemHistoryColor = { GetPriorityIndicatorTextColor(archiveStates.itemHistory, {}) },
          archiveItemHistoryState = archiveStates.itemHistory,
          itemHistoryDiagnostics = data.itemHistoryDifferenceDiagnostics,
          archiveSessionHistory = GetPriorityTooltipStatus(archiveStates.sessionHistory, {}),
          archiveSessionHistoryColor = { GetPriorityIndicatorTextColor(archiveStates.sessionHistory, {}) },
          archiveSessionHistoryState = archiveStates.sessionHistory,
          sessionHistoryDiagnostics = data.sessionHistoryDifferenceDiagnostics,
          archiveFunAwards = GetPriorityTooltipStatus(archiveStates.funAwards, {}),
          archiveFunAwardsColor = { GetPriorityIndicatorTextColor(archiveStates.funAwards, {}) },
          recovery = type(recoveryInfo) == "table" and recoveryInfo.longLabel or "",
          autoPass = data.localAutoPassEnabled and "ON" or "OFF",
          addonVersion = TrimText(data.addonVersion) ~= "" and data.addonVersion or "Legacy",
          clientVersion = data.clientVersion,
          joinedAt = data.joinedAt and FormatDateTime(data.joinedAt) or "",
          r = r,
          g = g,
          b = b,
        }
        row.__memberKey = data.key
        row:EnableMouse(true)
        row:SetScript("OnMouseDown", function()
          editor.lootSessionSelectedMemberKey = data.key
          RefreshCurrentSessionSection(editor)
        end)
        local isSelected = selectedMemberKey ~= "" and string.lower(selectedMemberKey) == string.lower(data.key)
        if row.selectionFill then
          row.selectionFill:SetShown(isSelected)
        end
        if row.selectionStripe then
          row.selectionStripe:SetShown(isSelected)
        end
        if row.SetBackdropColor then
          if isSelected then
            row:SetBackdropColor(0.12, 0.18, 0.28, 0.98)
          else
            row:SetBackdropColor(0.05, 0.05, 0.07, 0.94)
          end
        end
        if row.SetBackdropBorderColor then
          if isSelected then
            row:SetBackdropBorderColor(1.00, 0.82, 0.32, 0.95)
          else
            row:SetBackdropBorderColor(0.22, 0.24, 0.30, 0.80)
          end
        end
        row:Show()
      else
        row.__memberKey = nil
        row.__lidPriorityStates = nil
        row:SetScript("OnMouseDown", nil)
        row:EnableMouse(false)
        if row.selectionFill then
          row.selectionFill:Hide()
        end
        if row.selectionStripe then
          row.selectionStripe:Hide()
        end
        if row.SetBackdropBorderColor then
          row:SetBackdropBorderColor(0.22, 0.24, 0.30, 0.80)
        end
        row:Hide()
      end
    end
    if selectedMemberKey ~= "" and not selectedStillVisible then
      editor.lootSessionSelectedMemberKey = nil
    end
    editor.lootSessionMemberRowsHeight = math.max(0, #memberRowsData * 38)

    editor.lootSessionTitle:SetText("Current Session")
    if activeSession then
      local sessionStatus = string.upper(TrimText(activeSession.status or "ACTIVE"))
      local sessionIsPreparing = sessionStatus == "PREPARING"
      local statusLabel
      local statusColor
      if syntheticSession then
        statusLabel = "Developer synthetic session"
        statusColor = { 0.38, 0.72, 1.00, 1.00 }
      elseif sessionIsPreparing and activeSessionIsHost then
        statusLabel = "Preparation lobby open"
        statusColor = { 1.00, 0.82, 0.32, 1.00 }
      elseif sessionIsPreparing and activeSessionIsJoined then
        statusLabel = "Joined preparation lobby"
        statusColor = { 1.00, 0.82, 0.32, 1.00 }
      elseif sessionIsPreparing then
        statusLabel = "Observed preparation lobby"
        statusColor = { 0.82, 0.82, 0.86, 1.00 }
      elseif activeSessionIsHost then
        statusLabel = "Hosting shared session"
        statusColor = { 0.20, 0.90, 0.20, 1.00 }
      elseif activeSessionIsJoined then
        statusLabel = "Connected to host"
        statusColor = { 0.30, 0.88, 0.72, 1.00 }
      else
        statusLabel = "Observed session active"
        statusColor = { 0.82, 0.82, 0.86, 1.00 }
      end
      -- Auto Pass owns a separate status field; remove any old transient
      -- override so the session state cannot inherit its green/red color.
      editor.lootSessionStatus.__lid_customTextColor = nil
      editor.lootSessionStatus:SetText(statusLabel)
      editor.lootSessionStatus:SetTextColor(statusColor[1], statusColor[2], statusColor[3], statusColor[4])
      ApplyTrafficLight(editor.lootSessionStatusIndicator, overallSyncPresentationState)

      local joinedCount = 0
      for _, row in ipairs(memberRowsData) do
        if string.upper(TrimText(row.status)) == "JOINED" then
          joinedCount = joinedCount + 1
        end
      end

      local bootstrapState = overallBootstrapCounts.review > 0 and "REVIEW"
        or (overallBootstrapCounts.pending > 0 and "PENDING" or "READY")
      local sessionMomentLabel = sessionIsPreparing and "Lobby opened" or "Session started"
      local memberLabel = joinedCount == 1 and "member" or "members"
      editor.lootSessionOverviewTitle:SetText(sessionIsPreparing and "Preparation lobby" or "Shared LidCouncil session")
      editor.lootSessionOverviewMeta:SetText(string.format(
        "Profile: %s | Your role: %s\nHost: %s | %s: %s | %d %s",
        tostring(syntheticDisplayProfileName ~= "" and syntheticDisplayProfileName or activeProfileName or activeSession.profileName or profileName),
        roleLabel,
        tostring(activeSession.host or "Unknown"),
        sessionMomentLabel,
        FormatSessionMoment(activeSession.startedAt),
        joinedCount,
        memberLabel
      ))
      editor.lootSessionOverviewMeta:SetTextColor(0.78, 0.82, 0.88, 1.00)
      editor.lootSessionOverviewMeta:Show()
      if editor.lootSessionOverviewFrame then
        editor.lootSessionOverviewFrame.__lidSessionExactTime = FormatDateTime(activeSession.startedAt)
      end
      ShowSessionOverviewStatusCards(editor, overallSyncPresentationState, bootstrapState, overallBootstrapCounts)

      if syntheticSession then
        SetLiveSummaryText(
          editor.lootSessionLiveSummary,
          string.format(
            "Developer Sync Harness: %d synthetic joined member(s). Use Sync Management to rehearse pull, preview, and push repair flows against scratch profiles.",
            tonumber(joinedCount) or 0
          ),
          true
        )
      elseif sessionIsPreparing and activeSessionIsHost then
        local readyCount = tonumber(overallBootstrapCounts.ready) or 0
        local joinedMemberCount = tonumber(overallBootstrapCounts.joined) or 0
        local memberLabel = joinedMemberCount == 1 and "member" or "members"
        local preparationSummary
        if joinedMemberCount == 0 then
          preparationSummary = "Lobby open\nInvite your party or raid before starting the session."
        elseif readyCount >= joinedMemberCount then
          preparationSummary = string.format(
            "Ready to start\n%d of %d %s %s roll-ready. History can continue syncing in the background.",
            readyCount,
            joinedMemberCount,
            memberLabel,
            joinedMemberCount == 1 and "is" or "are"
          )
        else
          preparationSummary = string.format(
            "Members are still preparing\n%d of %d %s %s roll-ready. History can continue syncing in the background.",
            readyCount,
            joinedMemberCount,
            memberLabel,
            joinedMemberCount == 1 and "is" or "are"
          )
        end
        SetLiveSummaryText(
          editor.lootSessionLiveSummary,
          IsTutorialModeEnabled() and "Preparation: joined members and profile revisions can be checked here. Press Start Session when the host profile should become authoritative." or
            preparationSummary,
          true
        )
      elseif sessionIsPreparing then
        SetLiveSummaryText(
          editor.lootSessionLiveSummary,
          IsTutorialModeEnabled() and "Preparation: waiting for the host to start the active loot session." or "",
          true
        )
      elseif type(liveSummaryState) == "table" and liveSummaryState.itemCount and liveSummaryState.itemCount > 0 and activeSessionIsHost then
        local latestText = liveSummaryState.latestItem and (" | Latest: " .. tostring(liveSummaryState.latestItem)) or ""
        SetLiveSummaryText(editor.lootSessionLiveSummary, string.format(
          "Live Board: %d tracked item(s) | %d pending choice(s)%s",
          tonumber(liveSummaryState.itemCount) or 0,
          tonumber(liveSummaryState.pendingChoices) or 0,
          latestText
        ), false)
      elseif type(liveSummaryState) == "table" and liveSummaryState.isPreview then
        local latestText = liveSummaryState.latestItem and (" | Latest: " .. tostring(liveSummaryState.latestItem)) or ""
        SetLiveSummaryText(editor.lootSessionLiveSummary, string.format(
          "Live Board Simulation: %d tracked item(s) | %d pending choice(s)%s",
          tonumber(liveSummaryState.itemCount) or 0,
          tonumber(liveSummaryState.pendingChoices) or 0,
          latestText
        ), false)
      elseif activeSessionIsJoined then
        SetLiveSummaryText(
          editor.lootSessionLiveSummary,
          IsTutorialModeEnabled() and "Live Board: The host assigns loot on the board while joined members use the roll popup." or "",
          true
        )
      else
        SetLiveSummaryText(
          editor.lootSessionLiveSummary,
          IsTutorialModeEnabled() and "Live Board: Visible in the Live Board section and ready for host assignment." or "",
          true
        )
      end

      local syncExplanation = GetSessionSyncDescription(overallSyncPresentationState)
      local bootstrapStateLabel = overallBootstrapCounts.review > 0 and "REVIEW"
        or (overallBootstrapCounts.pending > 0 and "PENDING" or "READY")
      local bootstrapExplanation = GetSessionBootstrapDescription(bootstrapStateLabel)
      if syntheticSession then
        editor.lootSessionBody:SetTextColor(0.82, 0.82, 0.86, 1.00)
        editor.lootSessionBody:SetText(
          "This is a developer-only synthetic session overlay. LidCouncil uses hidden scratch profiles for the host and fake joined members, so preview, pull, and push repair rehearsal does not change your real source profile.\n\nClear it in About -> Developer Mode -> Sync Harness -> Clear Result + Session."
        )
        editor.lootSessionBody:Show()
      elseif activeProfileName and activeProfileName ~= profileName then
        editor.lootSessionBody:SetTextColor(0.82, 0.82, 0.86, 1.00)
        editor.lootSessionBody:SetText(
          "This active session belongs to profile \"" .. tostring(activeProfileName) .. "\". Current profile history remains unchanged until you switch profiles.\n\n" ..
          bootstrapExplanation .. "\n\n" .. syncExplanation
        )
        editor.lootSessionBody:Show()
      elseif overallSyncPresentationState ~= "SYNCED" then
        editor.lootSessionBody:SetTextColor(0.82, 0.82, 0.86, 1.00)
        editor.lootSessionBody:SetText(bootstrapExplanation .. "\n\n" .. syncExplanation)
        editor.lootSessionBody:Show()
      elseif overallBootstrapCounts.ready < overallBootstrapCounts.joined then
        editor.lootSessionBody:SetTextColor(0.82, 0.82, 0.86, 1.00)
        editor.lootSessionBody:SetText(bootstrapExplanation)
        editor.lootSessionBody:Show()
      else
        editor.lootSessionBody:SetText("")
        editor.lootSessionBody:Hide()
      end
    else
      editor.lootSessionStatus.__lid_customTextColor = nil
      editor.lootSessionStatus:SetText("Ready to prepare")
      editor.lootSessionStatus:SetTextColor(1.00, 0.82, 0.28, 1.00)
      ApplyTrafficLight(editor.lootSessionStatusIndicator, "PENDING")
      SetLiveSummaryText(
        editor.lootSessionLiveSummary,
        IsTutorialModeEnabled() and "Live Board: Ready. Start a session to broadcast joins and session sync status." or "",
        true
      )
      editor.lootSessionOverviewTitle:SetText("Ready to start a LidCouncil session")
      editor.lootSessionOverviewMeta:SetText(string.format(
        "Profile: %s\nPrepare a session to open a lobby and invite your party or raid.",
        tostring(profileName)
      ))
      editor.lootSessionOverviewMeta:SetTextColor(0.78, 0.82, 0.88, 1.00)
      editor.lootSessionOverviewMeta:Show()
      if editor.lootSessionOverviewFrame then
        editor.lootSessionOverviewFrame.__lidSessionExactTime = nil
      end
      HideSessionOverviewCards(editor)
      if IsTutorialModeEnabled() then
        editor.lootSessionBody:SetText(
          "Use Prepare Session to invite the current party or raid into a shared LidCouncil preparation lobby.\n\n" ..
          "Joined members will appear in the table above with sync state, join status, and Auto-Pass as soon as they answer the invite. Hover a member for version and join-time details."
        )
        editor.lootSessionBody:SetTextColor(1.00, 0.82, 0.24, 1.00)
        editor.lootSessionBody:Show()
      else
        editor.lootSessionBody:SetText("")
        editor.lootSessionBody:Hide()
      end
    end
  end

  local function LayoutCurrentSessionSection(editor, page, rightContentWidth)
    if not editor then
      return 180
    end

    local actionHeight = FlowLayoutControls({
      editor.sessionStartBtn,
      editor.sessionActivateBtn,
      editor.sessionInviteBtn,
      editor.sessionRefreshReadinessBtn,
      editor.sessionLeaveBtn,
      editor.sessionRemoveMemberBtn,
      editor.sessionStopBtn,
    }, 18, -78, rightContentWidth, 10, 8)
    local liveSummaryTop = -78 - actionHeight - 8
    if editor.lootSessionLiveSummary then
      editor.lootSessionLiveSummary:ClearAllPoints()
      editor.lootSessionLiveSummary:SetPoint("TOPLEFT", 18, liveSummaryTop)
    end
    local liveSummaryHeight = math.max(18, math.ceil((editor.lootSessionLiveSummary and editor.lootSessionLiveSummary:IsShown() and editor.lootSessionLiveSummary:GetStringHeight() or 0)))

    local overviewTop = liveSummaryTop - liveSummaryHeight - 12

    if editor.lootSessionOverviewFrame then
      editor.lootSessionOverviewFrame:ClearAllPoints()
      editor.lootSessionOverviewFrame:SetPoint("TOPLEFT", 18, overviewTop)
      editor.lootSessionOverviewFrame:SetWidth(rightContentWidth)
    end
    if editor.lootSessionOverviewTitle then
      editor.lootSessionOverviewTitle:SetWidth(rightContentWidth - 28)
    end
    if editor.lootSessionOverviewMeta then
      editor.lootSessionOverviewMeta:SetWidth(rightContentWidth - 28)
    end

    local overviewMetaHeight = math.max(0, math.ceil((editor.lootSessionOverviewMeta and editor.lootSessionOverviewMeta:IsShown() and editor.lootSessionOverviewMeta:GetStringHeight() or 0)))
    local cardTop = -42 - overviewMetaHeight
    local cardGap = 8
    local visibleOverviewCards = {}
    for _, card in ipairs(editor.lootSessionOverviewCards or {}) do
      if card.frame and card.frame:IsShown() then
        visibleOverviewCards[#visibleOverviewCards + 1] = card
      end
    end
    local cardColumns = #visibleOverviewCards > 0 and math.min(GetSessionOverviewCardColumns(rightContentWidth), #visibleOverviewCards) or 1
    local overviewInnerWidth = math.max(120, rightContentWidth - 28)
    local cardRows = #visibleOverviewCards > 0 and math.ceil(#visibleOverviewCards / cardColumns) or 0
    local cardWidth = math.max(120, math.floor((overviewInnerWidth - (cardGap * (cardColumns - 1))) / cardColumns))
    local cardHeight = 58
    local overviewHeight = 42 + overviewMetaHeight
    if cardRows > 0 then
      overviewHeight = overviewHeight + 10 + (cardRows * cardHeight) + ((cardRows - 1) * cardGap) + 12
    else
      overviewHeight = overviewHeight + 12
    end
    if editor.lootSessionOverviewFrame then
      editor.lootSessionOverviewFrame:SetHeight(overviewHeight)
    end
    for index, card in ipairs(visibleOverviewCards) do
      local rowIndex = math.floor((index - 1) / cardColumns)
      local colIndex = (index - 1) % cardColumns
      card.frame:ClearAllPoints()
      card.frame:SetPoint("TOPLEFT", 14 + (colIndex * (cardWidth + cardGap)), cardTop - (rowIndex * (cardHeight + cardGap)))
      card.frame:SetSize(cardWidth, cardHeight)
      card.valueText:SetWidth(cardWidth - 20)
      if card.valueText.SetMaxLines then
        card.valueText:SetMaxLines(1)
      end
      if card.labelText then
        card.labelText:SetWidth(cardWidth - 20)
        if card.labelText.SetMaxLines then
          card.labelText:SetMaxLines(1)
        end
      end
    end

    local membersHeaderTop = overviewTop - overviewHeight - 16
    editor.lootSessionMembersHeader:ClearAllPoints()
    editor.lootSessionMembersHeader:SetPoint("TOPLEFT", 18, membersHeaderTop)

    local layout = BuildSessionMemberColumnLayout(rightContentWidth)
    local rowWidth = layout.rowWidth
    local autoPassWidth = layout.autoPassWidth
    local nameX = layout.nameX
    local autoPassX = layout.autoPassX
    local nameWidth = layout.nameWidth
    local priority1X = layout.priority1X
    local priority2X = layout.priority2X
    local priority3X = layout.priority3X
    local priorityWidth = layout.priorityWidth
    local priority3Width = layout.priority3Width or priorityWidth
    local priority3TextWidth = layout.priority3TextWidth or priority3Width
    local archiveWidth = layout.archiveWidth or priorityWidth
    local itemHistoryX = layout.itemHistoryX or 0
    local sessionHistoryX = layout.sessionHistoryX or 0
    local funAwardsX = layout.funAwardsX or 0
    local showPriority3 = layout.showPriority3 == true
    local showPriorityLabels = layout.showPriorityLabels == true
    local showPriority3Detail = layout.showPriority3Detail == true
    local showArchiveDetails = layout.showArchiveDetails == true
    editor.__lidCurrentSessionShowPriority3 = showPriority3
    editor.__lidCurrentSessionShowPriorityLabels = showPriorityLabels
    editor.__lidCurrentSessionShowPriority3Detail = showPriority3Detail
    editor.__lidCurrentSessionShowArchiveDetails = showArchiveDetails
    local membersLegendTop = membersHeaderTop - 21
    if editor.lootSessionMembersLegend then
      editor.lootSessionMembersLegend:ClearAllPoints()
      editor.lootSessionMembersLegend:SetPoint("TOPLEFT", 18, membersLegendTop)
      editor.lootSessionMembersLegend:SetWidth(rowWidth)
      editor.lootSessionMembersLegend:SetText(showArchiveDetails
        and "P1: roll-ready | P2: current-session state | P3: Loot List, Item History, Session History, Fun Awards"
        or "P1: roll-ready (required) | P2: current-session state | P3: background archive")
    end
    local membersLegendHeight = math.max(16, math.ceil((editor.lootSessionMembersLegend and editor.lootSessionMembersLegend:GetStringHeight() or 0)))
    local memberColumnsTop = membersLegendTop - membersLegendHeight - 6

    editor.lootSessionMemberColumns:ClearAllPoints()
    editor.lootSessionMemberColumns:SetPoint("TOPLEFT", 18, memberColumnsTop)
    editor.lootSessionMemberColumns:SetSize(rowWidth, 22)

    editor.lootSessionMemberHeaderName:ClearAllPoints()
    editor.lootSessionMemberHeaderName:SetPoint("TOPLEFT", nameX, -4)
    editor.lootSessionMemberHeaderName:SetWidth(nameWidth)
    editor.lootSessionMemberHeaderSync:ClearAllPoints()
    editor.lootSessionMemberHeaderSync:SetPoint("TOPLEFT", priority2X, -4)
    editor.lootSessionMemberHeaderSync:SetWidth(priorityWidth)
    editor.lootSessionMemberHeaderSync:SetText(showPriorityLabels and "P2 State" or "P2")
    editor.lootSessionMemberHeaderAutoPass:ClearAllPoints()
    editor.lootSessionMemberHeaderAutoPass:SetPoint("TOPLEFT", autoPassX, -4)
    editor.lootSessionMemberHeaderAutoPass:SetWidth(autoPassWidth)
    editor.lootSessionMemberHeaderVersion:Hide()
    editor.lootSessionMemberHeaderStatus:ClearAllPoints()
    editor.lootSessionMemberHeaderStatus:SetPoint("TOPLEFT", priority1X, -4)
    editor.lootSessionMemberHeaderStatus:SetWidth(priorityWidth)
    editor.lootSessionMemberHeaderStatus:SetText(showPriorityLabels and "P1 Ready" or "P1")
    editor.lootSessionMemberHeaderStatus:Show()
    if editor.lootSessionMemberHeaderPriority3 then
      editor.lootSessionMemberHeaderPriority3:ClearAllPoints()
      editor.lootSessionMemberHeaderPriority3:SetPoint("TOPLEFT", priority3X, -4)
      editor.lootSessionMemberHeaderPriority3:SetWidth(showArchiveDetails and archiveWidth or priority3Width)
      editor.lootSessionMemberHeaderPriority3:SetJustifyH(showArchiveDetails and "CENTER" or "LEFT")
      editor.lootSessionMemberHeaderPriority3:SetText(showArchiveDetails and "Loot List" or (showPriority3Detail and "P3 Archive" or "P3"))
      editor.lootSessionMemberHeaderPriority3:SetShown(showPriority3)
    end
    editor.lootSessionMemberHeaderItemHistory:ClearAllPoints()
    editor.lootSessionMemberHeaderItemHistory:SetPoint("TOPLEFT", itemHistoryX, -4)
    editor.lootSessionMemberHeaderItemHistory:SetWidth(archiveWidth)
    editor.lootSessionMemberHeaderItemHistory:SetShown(showArchiveDetails)
    editor.lootSessionMemberHeaderSessionHistory:ClearAllPoints()
    editor.lootSessionMemberHeaderSessionHistory:SetPoint("TOPLEFT", sessionHistoryX, -4)
    editor.lootSessionMemberHeaderSessionHistory:SetWidth(archiveWidth)
    editor.lootSessionMemberHeaderSessionHistory:SetShown(showArchiveDetails)
    editor.lootSessionMemberHeaderFunAwards:ClearAllPoints()
    editor.lootSessionMemberHeaderFunAwards:SetPoint("TOPLEFT", funAwardsX, -4)
    editor.lootSessionMemberHeaderFunAwards:SetWidth(archiveWidth)
    editor.lootSessionMemberHeaderFunAwards:SetShown(showArchiveDetails)
    editor.lootSessionMemberHeaderJoined:Hide()

    local memberRowsHeight = tonumber(editor.lootSessionMemberRowsHeight) or 0
    local memberRowsTop = memberColumnsTop - 26
    editor.lootSessionMemberRowsFrame:ClearAllPoints()
    editor.lootSessionMemberRowsFrame:SetPoint("TOPLEFT", 18, memberRowsTop)
    editor.lootSessionMemberRowsFrame:SetSize(rowWidth, math.max(1, memberRowsHeight))

    for index, row in ipairs(editor.lootSessionMemberRows or {}) do
      row:ClearAllPoints()
      row:SetPoint("TOPLEFT", 0, -((index - 1) * 38))
      row:SetWidth(rowWidth)
      row.icon:ClearAllPoints()
      row.icon:SetPoint("TOPLEFT", 10, -8)
      row.nameText:ClearAllPoints()
      row.nameText:SetPoint("TOPLEFT", nameX, -7)
      row.nameText:SetWidth(nameWidth)
      row.metaText:ClearAllPoints()
      row.metaText:SetPoint("TOPLEFT", nameX, -21)
      row.metaText:SetWidth(nameWidth)
      row.syncDot:ClearAllPoints()
      row.syncDot:Hide()
      row.syncText:ClearAllPoints()
      row.syncText:Hide()
      row.autoPassText:ClearAllPoints()
      row.autoPassText:SetPoint("TOPLEFT", autoPassX, -13)
      row.autoPassText:SetWidth(autoPassWidth)
      row.versionText:Hide()
      row.joinedText:Hide()
      row.statusText:ClearAllPoints()
      row.statusText:Hide()
      row.metaText:SetText(tostring(row.__lidMemberRoleText or ""))
      row.priority1Icon:ClearAllPoints()
      row.priority1Icon:SetPoint("TOP", row, "TOPLEFT", priority1X + math.floor(priorityWidth / 2), -9)
      row.priority1Icon:Show()
      row.priority1Text:ClearAllPoints()
      row.priority1Text:SetPoint("TOP", row, "TOPLEFT", priority1X, -23)
      row.priority1Text:SetWidth(priorityWidth)
      row.priority1Text:SetShown(showPriorityLabels and TrimText(row.priority1Text:GetText()) ~= "")
      row.priority2Icon:ClearAllPoints()
      row.priority2Icon:SetPoint("TOP", row, "TOPLEFT", priority2X + math.floor(priorityWidth / 2), -9)
      row.priority2Icon:Show()
      row.priority2Text:ClearAllPoints()
      row.priority2Text:SetPoint("TOP", row, "TOPLEFT", priority2X, -23)
      row.priority2Text:SetWidth(priorityWidth)
      row.priority2Text:SetShown(showPriorityLabels and TrimText(row.priority2Text:GetText()) ~= "")
      row.priority3Icon:ClearAllPoints()
      row.priority3Icon:SetPoint(
        "TOP",
        row,
        "TOPLEFT",
        priority3X + math.floor((showArchiveDetails and archiveWidth or priority3Width) / 2),
        -9
      )
      if showArchiveDetails and type(row.__lidPriorityStates) == "table" then
        ApplyPriorityPhaseIcon(row.priority3Icon, row.__lidPriorityStates.archiveLootList, {})
      end
      row.priority3Icon:SetShown(showPriority3)
      row.priority3Text:ClearAllPoints()
      row.priority3Text:SetPoint("BOTTOMLEFT", row, "BOTTOMLEFT", priority3X, 1)
      row.priority3Text:SetWidth(priority3TextWidth)
      row.priority3Text:SetShown(showPriority3 and showPriority3Detail and TrimText(row.priority3Text:GetText()) ~= "")
      row.itemHistoryIcon:ClearAllPoints()
      row.itemHistoryIcon:SetPoint("TOP", row, "TOPLEFT", itemHistoryX + math.floor(archiveWidth / 2), -9)
      row.itemHistoryIcon:SetShown(showArchiveDetails)
      row.sessionHistoryIcon:ClearAllPoints()
      row.sessionHistoryIcon:SetPoint("TOP", row, "TOPLEFT", sessionHistoryX + math.floor(archiveWidth / 2), -9)
      row.sessionHistoryIcon:SetShown(showArchiveDetails)
      row.funAwardsIcon:ClearAllPoints()
      row.funAwardsIcon:SetPoint("TOP", row, "TOPLEFT", funAwardsX + math.floor(archiveWidth / 2), -9)
      row.funAwardsIcon:SetShown(showArchiveDetails)
    end

    local bodyTop = memberRowsTop - 10 - memberRowsHeight
    if editor.lootSessionBody then
      editor.lootSessionBody:ClearAllPoints()
      editor.lootSessionBody:SetPoint("TOPLEFT", 18, bodyTop)
    end
    local bodyHeight = math.max(40, math.ceil((editor.lootSessionBody and editor.lootSessionBody:IsShown() and editor.lootSessionBody:GetStringHeight() or 0)))
    local contentBottom = math.abs(bodyTop) + bodyHeight + 24
    if page then
      page.__contentHeight = math.max(420, contentBottom)
    end
    return contentBottom
  end

  return {
    RefreshCurrentSessionView = RefreshCurrentSessionView,
    RefreshCurrentSessionPriorityTelemetry = RefreshCurrentSessionPriorityTelemetry,
    RefreshCurrentSessionRosterIfChanged = RefreshCurrentSessionRosterIfChanged,
    LayoutCurrentSessionSection = LayoutCurrentSessionSection,
    BuildPriorityPresentationForValidation = BuildPriorityPresentationForValidation,
    ResolveTransferScopeLabelForValidation = GetTransferScopeLabel,
    ResolveOverallSyncPresentationStateForValidation = ResolveOverallSyncPresentationState,
    BuildSessionMemberColumnLayoutForValidation = BuildSessionMemberColumnLayout,
  }
end
