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

INTERNAL_API.LIDCOUNCIL_FormatSyncPerformanceMetrics_Impl = function(performance)
  local metrics = type(performance) == "table" and type(performance.metrics) == "table"
    and performance.metrics
    or {}
  local function formatMetric(key, label)
    local metric = type(metrics[key]) == "table" and metrics[key] or nil
    local samples = type(metric) == "table" and math.max(0, tonumber(metric.samples) or 0) or 0
    if samples <= 0 then
      return ""
    end
    return label .. " " .. string.format(
      "%.1f/%.1f/%.1fms",
      math.max(0, tonumber(metric.lastMs) or 0),
      math.max(0, tonumber(metric.averageMs) or 0),
      math.max(0, tonumber(metric.maxMs) or 0)
    )
  end
  local function buildGroup(definitions)
    local values = {}
    for _, definition in ipairs(definitions) do
      local value = formatMetric(definition[1], definition[2])
      if value ~= "" then
        values[#values + 1] = value
      end
    end
    return table.concat(values, " | ")
  end
  local function formatLatestMetric(definitions)
    local latestDefinition = nil
    local latestClock = -1
    for _, definition in ipairs(definitions) do
      local metric = type(metrics[definition[1]]) == "table" and metrics[definition[1]] or nil
      local samples = type(metric) == "table" and math.max(0, tonumber(metric.samples) or 0) or 0
      local metricClock = type(metric) == "table"
        and math.max(0, tonumber(metric.lastClock) or tonumber(metric.lastAt) or 0)
        or 0
      if samples > 0 and metricClock >= latestClock then
        latestDefinition = definition
        latestClock = metricClock
      end
    end
    return latestDefinition and formatMetric(latestDefinition[1], latestDefinition[2]) or ""
  end

  local lines = {}
  local snapshotText = buildGroup({
    { "snapshot_prepare_total", "Prepare" },
    { "snapshot_export", "Export" },
    { "snapshot_chunks", "Chunks" },
    { "snapshot_manifest", "Manifest" },
  })
  if snapshotText ~= "" then
    local prepareMetric = type(metrics.snapshot_prepare_total) == "table" and metrics.snapshot_prepare_total or {}
    lines[#lines + 1] = "Snapshot last/avg/max: " .. snapshotText
      .. (math.max(0, tonumber(prepareMetric.lastChunkCount) or 0) > 0
        and (" | Last " .. tostring(math.max(0, tonumber(prepareMetric.lastChunkCount) or 0)) .. " chunks") or "")
  end
  local queueText = buildGroup({
    { "queue_insert", "Insert" },
    { "queue_prune", "Prune" },
    { "queue_select", "Select" },
    { "queue_remove", "Remove" },
    { "queue_flush_total", "Flush" },
  })
  if queueText ~= "" then
    local insertMetric = type(metrics.queue_insert) == "table" and metrics.queue_insert or {}
    lines[#lines + 1] = "Queue sampled last/avg/max: " .. queueText
      .. (math.max(0, tonumber(insertMetric.lastQueueDepth) or 0) > 0
        and (" | Last depth " .. tostring(math.max(0, tonumber(insertMetric.lastQueueDepth) or 0))) or "")
  end
  local editorText = formatMetric("editor_refresh", "Refresh")
  if editorText ~= "" then
    lines[#lines + 1] = "Editor last/avg/max: " .. editorText
  end
  local latestPageText = formatLatestMetric({
    { "editor_page_profiles", "Profile" },
    { "editor_page_session", "Session" },
    { "editor_page_live_board", "Live Board" },
    { "editor_page_loot_list", "Loot List" },
    { "editor_page_loot_presets", "Loot Presets" },
  })
  if latestPageText ~= "" then
    lines[#lines + 1] = "Latest page last/avg/max: " .. latestPageText
  end
  local latestProfileText = formatLatestMetric({
    { "editor_profile_overview", "Overview" },
    { "editor_profile_access", "Roles & Rights" },
    { "editor_profile_raid", "Image" },
    { "editor_profile_roll", "Rolls" },
    { "editor_profile_points", "Points" },
    { "editor_profile_backups", "Backups" },
    { "editor_profile_transfer", "Transfer" },
  })
  if latestProfileText ~= "" then
    lines[#lines + 1] = "Latest Profile subsection: " .. latestProfileText
  end
  local presentationText = buildGroup({
    { "editor_layout_profiles", "Profile Layout" },
    { "editor_theme", "Theme" },
  })
  if presentationText ~= "" then
    lines[#lines + 1] = "Presentation last/avg/max: " .. presentationText
  end
  return table.concat(lines, "\n")
end

INTERNAL_API.LIDCOUNCIL_BuildSyncPerformanceReport_Impl = function(queueStatus)
  queueStatus = type(queueStatus) == "table" and queueStatus or {}
  local performance = type(queueStatus.syncPerformance) == "table" and queueStatus.syncPerformance or {}
  local metrics = type(performance.metrics) == "table" and performance.metrics or {}
  local snapshotBatch = type(queueStatus.profileSnapshotBatch) == "table" and queueStatus.profileSnapshotBatch or {}
  local acceptedJoinBurst = type(queueStatus.acceptedJoinBurstStatus) == "table"
    and queueStatus.acceptedJoinBurstStatus
    or {}
  local function readMetric(key)
    local metric = type(metrics[key]) == "table" and metrics[key] or {}
    return math.max(0, tonumber(metric.lastMs) or 0),
      math.max(0, tonumber(metric.averageMs) or 0),
      math.max(0, tonumber(metric.maxMs) or 0)
  end
  local function metricSummary(key, label)
    local lastMs, averageMs, maxMs = readMetric(key)
    return label .. ": last " .. string.format("%.1fms", lastMs)
      .. " | avg " .. string.format("%.1fms", averageMs)
      .. " | max " .. string.format("%.1fms", maxMs)
  end
  local function readWorstMetric(definitions)
    local worstLabel, worstAverage, worstMax = "", 0, 0
    for _, definition in ipairs(definitions) do
      local _, averageMs, maxMs = readMetric(definition[1])
      if maxMs > worstMax or (maxMs == worstMax and averageMs > worstAverage) then
        worstLabel = definition[2]
        worstAverage = averageMs
        worstMax = maxMs
      end
    end
    return worstLabel, worstAverage, worstMax
  end

  local findings = {}
  local _, prepareAverage, prepareMax = readMetric("snapshot_prepare_total")
  local _, selectAverage, selectMax = readMetric("queue_select")
  local _, flushAverage, flushMax = readMetric("queue_flush_total")
  local _, editorAverage, editorMax = readMetric("editor_refresh")
  if prepareMax >= 200 or prepareAverage >= 80 then
    findings[#findings + 1] = "WATCH: Snapshot preparation exceeded the host-frame target; inspect uncached export and manifest timings."
  end
  if selectMax >= 15 or selectAverage >= 5 then
    findings[#findings + 1] = "WATCH: Queue selection remains expensive at the sampled queue depth."
  end
  if flushMax >= 20 or flushAverage >= 8 then
    findings[#findings + 1] = "WATCH: Queue flush remains expensive at the sampled queue depth."
  end
  if editorMax >= 300 or editorAverage >= 200 then
    findings[#findings + 1] = "INFO: Sync Management rendering is expensive while open; transport continues normally after navigating away."
  end
  local slowPageLabel, slowPageAverage, slowPageMax = readWorstMetric({
    { "editor_page_profiles", "Profile" },
    { "editor_page_session", "Session" },
    { "editor_page_live_board", "Live Board" },
    { "editor_page_loot_list", "Loot List" },
    { "editor_page_loot_presets", "Loot Presets" },
  })
  if slowPageMax >= 100 or slowPageAverage >= 50 then
    findings[#findings + 1] = string.format(
      "WATCH: %s is the slowest measured Editor page (%.1fms average, %.1fms max).",
      slowPageLabel,
      slowPageAverage,
      slowPageMax
    )
  end
  local slowProfileLabel, slowProfileAverage, slowProfileMax = readWorstMetric({
    { "editor_profile_overview", "Profile Overview" },
    { "editor_profile_access", "Profile Roles & Rights" },
    { "editor_profile_raid", "Profile Image" },
    { "editor_profile_roll", "Profile Rolls" },
    { "editor_profile_points", "Profile Points" },
    { "editor_profile_backups", "Profile Backups" },
    { "editor_profile_transfer", "Profile Transfer" },
  })
  if slowProfileMax >= 100 or slowProfileAverage >= 50 then
    findings[#findings + 1] = string.format(
      "WATCH: %s is the slowest measured Profile subsection (%.1fms average, %.1fms max).",
      slowProfileLabel,
      slowProfileAverage,
      slowProfileMax
    )
  end
  local slowSessionLabel, slowSessionAverage, slowSessionMax = readWorstMetric({
    { "editor_session_context", "Session context/state" },
    { "editor_session_controls", "Session controls" },
    { "editor_session_sync_management", "Sync Management render" },
    { "editor_session_history", "Session History render" },
    { "editor_session_visibility", "Session visibility" },
    { "editor_session_candidates", "Current Session sync candidates" },
    { "editor_session_queue", "Current Session queue status" },
    { "editor_session_current_render", "Current Session render" },
    { "editor_session_layout", "Session layout" },
    { "editor_session_scroll", "Session scroll layout" },
  })
  if slowSessionMax >= 50 or slowSessionAverage >= 25 then
    findings[#findings + 1] = string.format(
      "WATCH: %s is the slowest measured Session phase (%.1fms average, %.1fms max).",
      slowSessionLabel,
      slowSessionAverage,
      slowSessionMax
    )
  end
  local _, rollTestAverage, rollTestMax = readMetric("roll_test_total")
  if rollTestMax >= 150 or rollTestAverage >= 80 then
    findings[#findings + 1] = string.format(
      "WATCH: Test Raid Items local preparation is expensive (%.1fms average, %.1fms max); inspect its phase timings below.",
      rollTestAverage,
      rollTestMax
    )
  end
  local _, rollChoiceAverage, rollChoiceMax = readMetric("roll_choice_total")
  if rollChoiceMax >= 100 or rollChoiceAverage >= 50 then
    findings[#findings + 1] = string.format(
      "WATCH: Local roll-choice submission is expensive (%.1fms average, %.1fms max); inspect record, dispatch, refresh, and popup timings below.",
      rollChoiceAverage,
      rollChoiceMax
    )
  end
  if #findings == 0 then
    findings[1] = "No measured performance threshold is currently exceeded."
  end

  local generatedAt = type(date) == "function" and date("%Y-%m-%d %H:%M:%S") or "time unavailable"
  local lines = {
    "LidCouncil Sync Performance Report",
    "Generated: " .. generatedAt,
    "Queue: " .. tostring(math.max(0, tonumber(queueStatus.pending) or 0))
      .. " pending | " .. string.format("%.2f msg/s", math.max(0, tonumber(queueStatus.sendRatePerSecond) or 0))
      .. " | " .. string.format("%.0f bytes/s", math.max(0, tonumber(queueStatus.byteRatePerSecond) or 0)),
    "Transport tuning: chunk size " .. tostring(math.max(1, tonumber(queueStatus.profileSyncChunkSize) or 120))
      .. " | interval " .. string.format("%.3fs", math.max(0, tonumber(queueStatus.intervalSeconds) or 0.12)),
    "Prepared snapshot cache: " .. tostring(math.max(0, tonumber(snapshotBatch.preparedSnapshotCacheHits) or 0))
      .. " hit(s) | " .. tostring(math.max(0, tonumber(snapshotBatch.preparedSnapshotCacheMisses) or 0))
      .. " miss(es) | " .. tostring(math.max(0, tonumber(snapshotBatch.preparedSnapshotCacheEntries) or 0))
      .. " active entr" .. (math.max(0, tonumber(snapshotBatch.preparedSnapshotCacheEntries) or 0) == 1 and "y" or "ies"),
    "Accepted JOIN worker: " .. tostring(math.max(0, tonumber(acceptedJoinBurst.pending) or 0))
      .. " pending | " .. tostring(math.max(0, tonumber(acceptedJoinBurst.acceptedTotal) or 0))
      .. " accepted | " .. tostring(math.max(0, tonumber(acceptedJoinBurst.coalescedTotal) or 0))
      .. " coalesced | " .. tostring(math.max(0, tonumber(acceptedJoinBurst.processedTotal) or 0))
      .. " processed | " .. tostring(math.max(0, tonumber(acceptedJoinBurst.failedTotal) or 0))
      .. " failed | last/max " .. string.format("%.1f/%.1fms",
        math.max(0, tonumber(acceptedJoinBurst.lastDurationMs) or 0),
        math.max(0, tonumber(acceptedJoinBurst.maxDurationMs) or 0)),
    "",
    "Assessment:",
  }
  for _, finding in ipairs(findings) do
    lines[#lines + 1] = "- " .. finding
  end
  lines[#lines + 1] = ""
  lines[#lines + 1] = "Measurements:"
  for _, definition in ipairs({
    { "snapshot_prepare_total", "Snapshot prepare" },
    { "snapshot_export", "Snapshot export" },
    { "snapshot_chunks", "Chunk build" },
    { "snapshot_manifest", "Manifest" },
    { "queue_insert", "Queue insert" },
    { "queue_prune", "Queue prune" },
    { "queue_select", "Queue select" },
    { "queue_remove", "Queue remove" },
    { "queue_flush_total", "Queue flush" },
    { "editor_refresh", "Editor refresh" },
    { "editor_page_profiles", "Editor page - Profile" },
    { "editor_page_session", "Editor page - Session" },
    { "editor_page_live_board", "Editor page - Live Board" },
    { "editor_page_loot_list", "Editor page - Loot List" },
    { "editor_page_loot_presets", "Editor page - Loot Presets" },
    { "editor_session_context", "Session page - context/state" },
    { "editor_session_controls", "Session page - controls" },
    { "editor_session_sync_management", "Session page - Sync Management render" },
    { "editor_session_history", "Session page - history render" },
    { "editor_session_visibility", "Session page - visibility" },
    { "editor_session_candidates", "Session page - sync candidates" },
    { "editor_session_queue", "Session page - queue status" },
    { "editor_session_current_render", "Session page - Current Session render" },
    { "editor_session_layout", "Session page - layout" },
    { "editor_session_scroll", "Session page - scroll layout" },
    { "editor_live_board_state", "Live Board page - state/readiness" },
    { "editor_live_board_attach", "Live Board page - attach board" },
    { "editor_live_board_controls", "Live Board page - controls/status" },
    { "editor_live_board_layout", "Live Board page - layout" },
    { "editor_live_board_scroll", "Live Board page - scroll layout" },
    { "live_board_attach_total", "Live Board attach - total" },
    { "live_board_attach_layout", "Live Board attach - embedded layout" },
    { "live_board_attach_render", "Live Board attach - board render" },
    { "live_board_attach_finalize", "Live Board attach - finalize" },
    { "live_board_refresh_total", "Live Board render - total" },
    { "live_board_refresh_layout", "Live Board render - layout" },
    { "live_board_refresh_items", "Live Board render - item list" },
    { "live_board_refresh_ledger", "Live Board render - Loot List totals" },
    { "live_board_refresh_members", "Live Board render - candidate rows" },
    { "editor_profile_overview", "Profile subsection - Overview" },
    { "editor_profile_access", "Profile subsection - Roles & Rights" },
    { "editor_profile_raid", "Profile subsection - Image" },
    { "editor_profile_roll", "Profile subsection - Rolls" },
    { "editor_profile_points", "Profile subsection - Points" },
    { "editor_profile_backups", "Profile subsection - Backups" },
    { "editor_profile_transfer", "Profile subsection - Transfer" },
    { "editor_profile_size_export", "Profile developer size export" },
    { "editor_layout_profiles", "Profile layout" },
    { "editor_theme", "Editor theme" },
    { "roll_test_total", "Test Raid Items - total" },
    { "roll_test_prepare", "Test Raid Items - runtime prepare" },
    { "roll_test_item_defs", "Test Raid Items - item definitions" },
    { "roll_test_runtime_build", "Test Raid Items - runtime rows" },
    { "roll_test_persist", "Test Raid Items - persist" },
    { "roll_test_popup", "Test Raid Items - popup" },
    { "roll_test_board_render", "Test Raid Items - board render" },
    { "roll_test_dispatch", "Test Raid Items - dispatch prepare" },
    { "roll_test_dispatch_serialization", "Test dispatch - board serialization" },
    { "roll_test_dispatch_recipients", "Test dispatch - recipient selection" },
    { "roll_test_dispatch_admission", "Test dispatch - queue admission" },
    { "roll_test_dispatch_local_state", "Test dispatch - local board state/refresh" },
    { "roll_test_dispatch_target_plan", "Test dispatch - per-target planning" },
    { "roll_test_dispatch_receipts", "Test dispatch - receipt bookkeeping" },
    { "roll_test_dispatch_enqueue", "Test dispatch - initial queue enqueue" },
    { "roll_test_editor_refresh", "Test Raid Items - Editor summary refresh" },
    { "roll_choice_total", "Roll choice - submit total" },
    { "roll_choice_record", "Roll choice - local record" },
    { "roll_choice_dispatch", "Roll choice - dispatch" },
    { "roll_choice_ui_refresh", "Roll choice - board/summary refresh" },
    { "roll_popup_refresh_total", "Roll popup - total refresh" },
    { "roll_popup_navigator", "Roll popup - queue navigator" },
    { "roll_popup_options", "Roll popup - options/layout" },
    { "roll_popup_render", "Roll popup - render" },
  }) do
    lines[#lines + 1] = metricSummary(definition[1], definition[2])
  end
  return table.concat(lines, "\n")
end

INTERNAL_API.LIDCOUNCIL_CreateLootSessionSyncHelpers_Impl = function(deps)
  deps = type(deps) == "table" and deps or {}
  local GetEditorThemePalette = type(INTERNAL_API.LIDCOUNCIL_GetEditorThemePalette_Impl) == "function"
    and INTERNAL_API.LIDCOUNCIL_GetEditorThemePalette_Impl
    or nil

  local ApplyFrameSkin = deps.ApplyFrameSkin
  local RootDB = deps.RootDB
  local TrimText = deps.TrimText
  local RequestLootSessionSectionRefresh = deps.RequestLootSessionSectionRefresh
  local GetSessionClassColor = deps.GetSessionClassColor
  local ResolveOptionalApiFunction = deps.ResolveOptionalApiFunction
  local FlowLayoutControls = deps.FlowLayoutControls
  local ClampLayoutValue = deps.ClampLayoutValue
  local FormatDateTime = deps.FormatDateTime
  local ApplyTrafficLight = deps.ApplyTrafficLight

  local function RefreshSyncManagementSection(editor)
    if type(RequestLootSessionSectionRefresh) == "function" then
      if RequestLootSessionSectionRefresh(editor, "SYNCMGMT") then
        return
      end
    end
    if editor and editor.RefreshLootSessionPage then
      editor:RefreshLootSessionPage({
        lootSessionSections = {
          SYNCMGMT = true,
        },
      })
    elseif editor and editor.Refresh then
      editor:Refresh()
    end
  end

  local function SetSyncActionStatusOverride(editor, text, color)
    if type(editor) ~= "table" then
      return
    end
    text = TrimText(text)
    if text == "" then
      editor.__lootSessionSyncActionStatusOverride = nil
      return
    end
    editor.__lootSessionSyncActionStatusOverride = {
      text = text,
      color = type(color) == "table" and color or { 1.00, 0.55, 0.44, 1.00 },
    }
    if editor.lootSessionProfileSyncStatus then
      editor.lootSessionProfileSyncStatus:SetText(text)
      editor.lootSessionProfileSyncStatus:SetTextColor(
        editor.__lootSessionSyncActionStatusOverride.color[1],
        editor.__lootSessionSyncActionStatusOverride.color[2],
        editor.__lootSessionSyncActionStatusOverride.color[3],
        editor.__lootSessionSyncActionStatusOverride.color[4] or 1
      )
    end
  end

  local function ClearSyncActionStatusOverride(editor)
    if type(editor) == "table" then
      editor.__lootSessionSyncActionStatusOverride = nil
    end
  end

  local function ApplySyncActionStatusOverride(editor)
    local override = type(editor) == "table" and editor.__lootSessionSyncActionStatusOverride or nil
    if type(override) ~= "table" or not editor.lootSessionProfileSyncStatus then
      return
    end
    local color = type(override.color) == "table" and override.color or { 1.00, 0.55, 0.44, 1.00 }
    editor.lootSessionProfileSyncStatus:SetText(tostring(override.text or ""))
    editor.lootSessionProfileSyncStatus:SetTextColor(color[1], color[2], color[3], color[4] or 1)
  end

  local function SetSyncDetailActionMessage(frame, text)
    if type(frame) ~= "table" then
      return
    end
    text = TrimText(text)
    frame.__actionMessageText = text ~= "" and text or nil
  end

  local function ClearSyncDetailActionMessage(frame)
    if type(frame) == "table" then
      frame.__actionMessageText = nil
    end
  end

  local function RunSyncAction(editor, frame, actionLabel, fn, ...)
    if type(fn) ~= "function" then
      local message = tostring(actionLabel or "Sync action") .. " is unavailable."
      SetSyncActionStatusOverride(editor, message, { 1.00, 0.55, 0.44, 1.00 })
      SetSyncDetailActionMessage(frame, message)
      return false
    end
    local ok, result = pcall(fn, ...)
    if not ok then
      local message = tostring(actionLabel or "Sync action") .. " failed: " .. tostring(result)
      SetSyncActionStatusOverride(editor, message, { 1.00, 0.35, 0.25, 1.00 })
      SetSyncDetailActionMessage(frame, message)
      return false
    end
    ClearSyncActionStatusOverride(editor)
    ClearSyncDetailActionMessage(frame)
    return true, result
  end

  local function ReadSyncActionValue(editor, frame, actionLabel, fn, fallback, ...)
    if type(fn) ~= "function" then
      return fallback
    end
    local ok, result = pcall(fn, ...)
    if not ok then
      local message = tostring(actionLabel or "Sync state") .. " failed: " .. tostring(result)
      SetSyncActionStatusOverride(editor, message, { 1.00, 0.35, 0.25, 1.00 })
      SetSyncDetailActionMessage(frame, message)
      return fallback
    end
    return result
  end

  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 GetDeveloperAccentHex()
    local palette = GetEditorThemePalette and GetEditorThemePalette() or nil
    local color = type(palette) == "table" and type(palette.aboutTitle) == "table"
      and palette.aboutTitle
      or { 0.6588, 0.4784, 0.9098, 1.0 }
    local function ToHex(component)
      local value = tonumber(component) or 1
      value = math.max(0, math.min(255, math.floor((value * 255) + 0.5)))
      return string.format("%02x", value)
    end
    return ToHex(color[1]) .. ToHex(color[2]) .. ToHex(color[3])
  end

  local function ApplyDeveloperAccentMarkup(text)
    return tostring(text or ""):gsub("|cffa87ae8", "|cff" .. GetDeveloperAccentHex())
  end

  local function GetProfileSyncCandidateVisibleState(candidate)
    candidate = type(candidate) == "table" and candidate or {}
    local visibleState = string.lower(TrimText(candidate.visibleState))
    if visibleState ~= "" then
      return visibleState
    end
    local effectiveComparison = TrimText(candidate.effectiveComparison)
    local comparison = effectiveComparison ~= "" and effectiveComparison or TrimText(candidate.comparison)
    if candidate.generationConverged and comparison == "same" then
      return "converged"
    end
    if candidate.backgroundOnlyLootDifference and comparison == "same" then
      return "background"
    end
    if comparison == "same" then
      return "aligned"
    elseif comparison == "remote_newer" then
      return "member_newer"
    elseif comparison == "local_newer" then
      return "host_newer"
    elseif comparison == "diverged" then
      return "conflict"
    elseif comparison == "different_lineage" then
      return "lineage"
    end
    return "unknown"
  end

  local function GetProfileSyncCandidateComparisonKey(candidate)
    candidate = type(candidate) == "table" and candidate or {}
    local visibleState = GetProfileSyncCandidateVisibleState(candidate)
    if visibleState == "waiting_apply" then
      return "waiting_apply"
    elseif visibleState == "member_newer" then
      return "remote_newer"
    elseif visibleState == "host_newer" then
      return "local_newer"
    elseif visibleState == "conflict" then
      return "diverged"
    elseif visibleState == "lineage" then
      return "different_lineage"
    elseif visibleState == "aligned" or visibleState == "background" or visibleState == "converged" then
      return "same"
    end
    local effectiveComparison = TrimText(candidate.effectiveComparison)
    local comparison = string.lower(effectiveComparison ~= "" and effectiveComparison or TrimText(candidate.comparison))
    return comparison ~= "" and comparison or "unknown"
  end

  local function GetProfileSyncCandidateDisplayBootstrapState(candidate)
    candidate = type(candidate) == "table" and candidate or {}
    local dashboardBootstrapState = TrimText(candidate.__dashboardBootstrapState)
    if dashboardBootstrapState ~= "" then
      return dashboardBootstrapState
    end
    return TrimText(candidate.bootstrapState)
  end

  local function FindSessionMemberInSession(activeSession, memberKey)
    activeSession = type(activeSession) == "table" and activeSession or nil
    local resolvedKey = string.lower(TrimText(memberKey))
    if type(activeSession) ~= "table" or type(activeSession.members) ~= "table" or resolvedKey == "" then
      return nil
    end
    for storedKey, member in pairs(activeSession.members) do
      local compareKey = string.lower(TrimText(storedKey ~= "" and storedKey or (type(member) == "table" and member.name) or ""))
      if compareKey ~= "" and compareKey == resolvedKey then
        return type(member) == "table" and member or nil
      end
    end
    return nil
  end

  local function FindActiveSessionMemberByKey(memberKey)
    local resolvedKey = string.lower(TrimText(memberKey))
    local getActiveLootSession = ResolveOptionalApiFunction("LIDCOUNCIL_GetActiveLootSession")
    if resolvedKey == "" or type(getActiveLootSession) ~= "function" then
      return nil
    end
    local activeSession = select(1, getActiveLootSession())
    if type(activeSession) ~= "table" or type(activeSession.members) ~= "table" then
      return nil
    end
    for storedKey, member in pairs(activeSession.members) do
      local compareKey = string.lower(TrimText(storedKey ~= "" and storedKey or (type(member) == "table" and member.name) or ""))
      if compareKey ~= "" and compareKey == resolvedKey then
        return type(member) == "table" and member or nil
      end
    end
    return nil
  end

  local GetProfileSyncDomainState

  local function GetProfileSyncFallbackBootstrapState(candidate)
    candidate = type(candidate) == "table" and candidate or {}
    local state = string.lower(TrimText(candidate.bootstrapState))
    if state ~= "" then
      return state
    end
    local comparisonKey = GetProfileSyncCandidateComparisonKey(candidate)
    if comparisonKey == "different_lineage" then
      return "lineage"
    elseif comparisonKey == "unknown" or TrimText(candidate.profileId) == "" then
      return "pending"
    end
    local settingsState = GetProfileSyncDomainState(candidate, "settings")
    local permissionsState = GetProfileSyncDomainState(candidate, "permissions")
    if settingsState == "same" and permissionsState == "same" then
      return "ready"
    end
    if settingsState == "member_newer" or settingsState == "conflict"
      or permissionsState == "member_newer" or permissionsState == "conflict"
    then
      return "review"
    end
    if settingsState == "host_newer" or permissionsState == "host_newer" then
      return "pending"
    end
    return "unknown"
  end

  local function GetProfileSyncCandidateBootstrapState(candidate, activeSession, isHost)
    candidate = type(candidate) == "table" and candidate or {}
    activeSession = type(activeSession) == "table" and activeSession or nil
    local fallbackState = GetProfileSyncFallbackBootstrapState(candidate)
    local comparisonKey = GetProfileSyncCandidateComparisonKey(candidate)
    if comparisonKey == "different_lineage" then
      return "lineage"
    end
    if type(activeSession) ~= "table"
      or type(INTERNAL_API.LIDCOUNCIL_GetDeferredJoinMemberBootstrapState) ~= "function"
    then
      return fallbackState
    end

    local memberKey = TrimText(candidate.memberKey)
    local member = FindSessionMemberInSession(activeSession, memberKey)
    local profileName = TrimText(activeSession.profileName or activeSession.remoteProfileName or "")
    if type(member) ~= "table" or profileName == "" then
      return fallbackState
    end

    local bootstrapState = nil
    if isHost == true and type(INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionDisplayContext) == "function" then
      local hostContext = INTERNAL_API.LIDCOUNCIL_BuildHostCurrentSessionDisplayContext(
        activeSession,
        profileName,
        memberKey
      )
      bootstrapState = INTERNAL_API.LIDCOUNCIL_GetDeferredJoinMemberBootstrapState(
        activeSession,
        profileName,
        memberKey,
        member,
        {
          localProfileId = type(hostContext) == "table" and hostContext.localProfileId or nil,
          localSummary = type(hostContext) == "table" and hostContext.localSummary or nil,
        }
      )
    elseif type(INTERNAL_API.LIDCOUNCIL_BuildMemberCurrentSessionDisplayContext) == "function" then
      local getCharacterKey = ResolveOptionalApiFunction("LIDCOUNCIL_GetCharacterKey")
      local selfMemberKey = type(getCharacterKey) == "function" and TrimText(getCharacterKey() or "") or ""
      local memberContext = INTERNAL_API.LIDCOUNCIL_BuildMemberCurrentSessionDisplayContext(
        activeSession,
        profileName,
        selfMemberKey
      )
      bootstrapState = INTERNAL_API.LIDCOUNCIL_GetDeferredJoinMemberBootstrapState(
        activeSession,
        profileName,
        memberKey,
        member,
        {
          localProfileId = type(memberContext) == "table" and memberContext.localProfileId or nil,
          localSummary = type(memberContext) == "table" and memberContext.localSummary or nil,
          selfMemberKey = type(memberContext) == "table" and memberContext.selfMemberKey or nil,
          localSharedProfileReady = type(memberContext) == "table" and memberContext.localSharedProfileReady or nil,
        }
      )
    end

    bootstrapState = string.upper(TrimText(bootstrapState))
    if bootstrapState == "READY" then
      return "ready"
    elseif bootstrapState == "PENDING" then
      return "pending"
    elseif bootstrapState == "REVIEW" then
      return "review"
    elseif bootstrapState == "DECLINED" then
      return "declined"
    end
    return fallbackState
  end

  local function GetSessionMemberRecoveryInfo(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 > recoveryAt then
      state = "recovered"
    end
    if state == "" then
      return nil
    end
    local info = {
      state = state,
      requestedScope = TrimText(member.lastDeltaRecoveryRequestedScope),
      summary = TrimText(member.lastDeltaRecoverySummary),
      scopeKinds = TrimText(member.lastDeltaRecoveryScopeEscalationKinds),
      at = recoveryAt,
    }
    if state == "deferred" then
      info.label = "Deferred"
      info.candidateSuffix = "recovery deferred"
    elseif state == "review" then
      info.label = "Needs Review"
      info.candidateSuffix = "repair skipped for review"
    elseif state == "widened" then
      info.label = "Widened Repair"
      info.candidateSuffix = "last recovery widened"
    elseif state == "full_fallback" then
      info.label = "Full Fallback"
      info.candidateSuffix = "last recovery full fallback"
    elseif state == "failed" then
      info.label = "Recovery Failed"
      info.candidateSuffix = "last recovery failed"
    elseif state == "aligned" then
      info.label = "Already Aligned"
      info.candidateSuffix = "last recovery unnecessary"
    else
      info.label = "Recovered"
      info.candidateSuffix = "last recovery applied"
    end
    return info
  end

  local function GetCandidateRecoveryInfo(candidate)
    if type(candidate) ~= "table" then
      return nil
    end
    return GetSessionMemberRecoveryInfo(FindActiveSessionMemberByKey(candidate.memberKey))
  end

  local function GetProfileSyncVisibleComparisonColorKey(candidate)
    local visibleState = GetProfileSyncCandidateVisibleState(candidate)
    if visibleState == "waiting_apply" then
      return "waiting_apply"
    elseif visibleState == "member_newer" then
      return "remote_newer"
    elseif visibleState == "host_newer" then
      return "local_newer"
    elseif visibleState == "conflict" then
      return "diverged"
    elseif visibleState == "lineage" then
      return "different_lineage"
    end
    return "same"
  end

  -- Declared ahead of the label builder because the implementation below also
  -- serves the later dashboard controls.
  local GetProfileSyncCandidateDisplayDomainText
  local GetProfileSyncComparisonLabel
  local GetProfileSyncBootstrapLabel

  local function BuildProfileSyncCandidateLabel(candidate)
    if type(candidate) ~= "table" then
      return "(select joined member)"
    end
    local memberLabel = tostring(candidate.memberKey or "Unknown")
    local comparisonKey = GetProfileSyncCandidateComparisonKey(candidate)
    local visibleState = GetProfileSyncCandidateVisibleState(candidate)
    local bootstrapState = string.lower(GetProfileSyncCandidateDisplayBootstrapState(candidate))
    local readinessSuffix = bootstrapState == "ready" and " | roll-ready" or ""
    local preciseSuffix = candidate.preciseDetailLoaded and " | precise scope ready" or ""
    local recoveryInfo = GetCandidateRecoveryInfo(candidate)
    local recoverySuffix = type(recoveryInfo) == "table" and TrimText(recoveryInfo.candidateSuffix) ~= ""
      and (" | " .. tostring(recoveryInfo.candidateSuffix))
      or ""
    if candidate.patchPushReady then
      preciseSuffix = preciseSuffix .. " | patch ready"
    end
    if visibleState == "converged" then
      return memberLabel .. " | same version | latest repair acknowledged" .. readinessSuffix .. preciseSuffix .. recoverySuffix
    end
    if visibleState == "waiting_apply" then
      return memberLabel .. " | update received; waiting for combat to end" .. readinessSuffix .. recoverySuffix
    end
    if visibleState == "background" then
      return memberLabel .. " | live aligned; background loot history still syncing" .. readinessSuffix .. preciseSuffix .. recoverySuffix
    end
    if visibleState == "member_newer" then
      return memberLabel .. " | member newer: "
        .. tostring(GetProfileSyncCandidateDisplayDomainText(candidate, "remote", "shared data"))
        .. readinessSuffix .. preciseSuffix .. recoverySuffix
    elseif visibleState == "conflict" then
      return memberLabel .. " | conflict: "
        .. tostring(GetProfileSyncCandidateDisplayDomainText(candidate, "remote", "shared data"))
        .. readinessSuffix .. preciseSuffix .. recoverySuffix
    elseif visibleState == "lineage" then
      return memberLabel .. " | different profile lineage" .. recoverySuffix
    elseif visibleState == "host_newer" then
      return memberLabel .. " | host newer: "
        .. tostring(GetProfileSyncCandidateDisplayDomainText(candidate, "local", "shared data"))
        .. readinessSuffix .. preciseSuffix .. recoverySuffix
    elseif visibleState == "aligned" or comparisonKey == "same" then
      return memberLabel .. " | same version" .. readinessSuffix .. recoverySuffix
    end
    return memberLabel .. " | status unknown" .. recoverySuffix
  end

  local function BuildProfileSyncCandidateSearchText(candidate)
    candidate = type(candidate) == "table" and candidate or {}
    local parts = {
      TrimText(candidate.memberKey),
      TrimText(candidate.role),
      BuildProfileSyncCandidateLabel(candidate),
      GetProfileSyncCandidateDisplayDomainText(candidate, "remote", ""),
      GetProfileSyncCandidateDisplayDomainText(candidate, "local", ""),
      GetProfileSyncComparisonLabel(GetProfileSyncCandidateComparisonKey(candidate)),
      GetProfileSyncBootstrapLabel(GetProfileSyncCandidateDisplayBootstrapState(candidate)),
    }
    return table.concat(parts, " ")
  end

  GetProfileSyncComparisonLabel = function(comparison)
    local resolved = TrimText(comparison)
    if resolved == "remote_newer" then
      return "Member newer"
    elseif resolved == "diverged" then
      return "Conflict"
    elseif resolved == "local_newer" then
      return "Local copy newer"
    elseif resolved == "same" then
      return "Aligned"
    elseif resolved == "different_lineage" then
      return "Different lineage"
    elseif resolved == "waiting_apply" then
      return "Waiting for combat"
    end
    return "Unknown"
  end

  local function GetProfileSyncComparisonColor(comparison)
    local resolved = TrimText(comparison)
    if resolved == "remote_newer" then
      return 1.00, 0.82, 0.32, 1.00
    elseif resolved == "diverged" then
      return 0.95, 0.32, 0.26, 1.00
    elseif resolved == "local_newer" then
      return 0.30, 0.90, 0.36, 1.00
    elseif resolved == "same" then
      return 0.82, 0.82, 0.86, 1.00
    elseif resolved == "different_lineage" then
      return 0.94, 0.62, 0.28, 1.00
    elseif resolved == "waiting_apply" then
      return 0.76, 0.84, 1.00, 1.00
    end
    return 0.82, 0.82, 0.86, 1.00
  end

  local function HasProfileSyncDomain(domains, domain)
    local needle = TrimText(domain)
    if needle == "" then
      return false
    end
    for _, value in ipairs(type(domains) == "table" and domains or {}) do
      if TrimText(value) == needle then
        return true
      end
    end
    return false
  end

  GetProfileSyncDomainState = function(candidate, domain)
    candidate = type(candidate) == "table" and candidate or {}
    local visibleState = GetProfileSyncCandidateVisibleState(candidate)
    if visibleState == "lineage" then
      return "lineage"
    end
    if string.lower(TrimText(domain)) == "loot" and visibleState == "background" then
      return "background"
    end
    if visibleState == "converged" or visibleState == "aligned" then
      return "same"
    end
    local memberNewer = HasProfileSyncDomain(
      type(candidate.effectiveRemoteNewerDomains) == "table" and candidate.effectiveRemoteNewerDomains or candidate.remoteNewerDomains,
      domain
    )
    local hostNewer = HasProfileSyncDomain(
      type(candidate.effectiveLocalNewerDomains) == "table" and candidate.effectiveLocalNewerDomains or candidate.localNewerDomains,
      domain
    )
    if memberNewer and hostNewer then
      return "conflict"
    elseif memberNewer then
      return "member_newer"
    elseif hostNewer then
      return "host_newer"
    end
    return "same"
  end

  local function GetProfileSyncDomainStateLabel(state)
    local resolved = TrimText(state)
    if resolved == "same" then
      return "Identical"
    elseif resolved == "background" then
      return "Background"
    elseif resolved == "member_newer" then
      return "Member newer"
    elseif resolved == "host_newer" then
      return "Host newer"
    elseif resolved == "conflict" then
      return "Both changed"
    elseif resolved == "lineage" then
      return "Lineage"
    end
    return "Unknown"
  end

  local function GetProfileSyncDomainStateColor(state)
    local resolved = TrimText(state)
    if resolved == "same" then
      return 0.30, 0.90, 0.36, 1.00
    elseif resolved == "background" then
      return 0.70, 0.64, 0.94, 1.00
    elseif resolved == "member_newer" then
      return 1.00, 0.82, 0.32, 1.00
    elseif resolved == "host_newer" then
      return 0.38, 0.72, 1.00, 1.00
    elseif resolved == "conflict" then
      return 0.95, 0.32, 0.26, 1.00
    elseif resolved == "lineage" then
      return 0.94, 0.62, 0.28, 1.00
    end
    return 0.82, 0.82, 0.86, 1.00
  end

  local function GetProfileSyncBootstrapStateColor(state)
    local resolved = string.lower(TrimText(state))
    if resolved == "ready" then
      return 0.30, 0.90, 0.36, 1.00
    elseif resolved == "pending" then
      return 1.00, 0.82, 0.32, 1.00
    elseif resolved == "review" or resolved == "declined" then
      return 0.95, 0.32, 0.26, 1.00
    elseif resolved == "lineage" then
      return 0.94, 0.62, 0.28, 1.00
    end
    return 0.82, 0.82, 0.86, 1.00
  end

  local function GetProfileSyncDomainLabel(text)
    local resolved = TrimText(text)
    return resolved ~= "" and resolved or "-"
  end

  GetProfileSyncCandidateDisplayDomainText = function(candidate, domainSide, fallbackText)
    candidate = type(candidate) == "table" and candidate or {}
    local effectiveText
    local baseText
    if string.lower(TrimText(domainSide)) == "local" then
      effectiveText = TrimText(candidate.effectiveLocalDomainText)
      baseText = TrimText(candidate.localDomainText)
    else
      effectiveText = TrimText(candidate.effectiveRemoteDomainText)
      baseText = TrimText(candidate.remoteDomainText)
    end
    if effectiveText ~= "" then
      return (string.gsub(effectiveText, "Session Data", "Current Session State"))
    end
    if baseText ~= "" then
      return (string.gsub(baseText, "Session Data", "Current Session State"))
    end
    return (string.gsub(TrimText(fallbackText), "Session Data", "Current Session State"))
  end

  GetProfileSyncBootstrapLabel = function(state)
    local resolved = string.lower(TrimText(state))
    if resolved == "ready" then
      return "Roll-Ready"
    elseif resolved == "pending" then
      return "Bootstrap Pending"
    elseif resolved == "review" then
      return "Bootstrap Needs Review"
    elseif resolved == "declined" then
      return "Bootstrap Declined"
    elseif resolved == "lineage" then
      return "Different Lineage"
    end
    return "Bootstrap Unknown"
  end

  local function GetProfileSyncActionLabel(candidate, isHost)
    candidate = type(candidate) == "table" and candidate or {}
    local recommendation = type(candidate.safeRecommendation) == "table" and candidate.safeRecommendation or nil
    if isHost and type(recommendation) == "table" and TrimText(recommendation.label) ~= "" then
      return TrimText(recommendation.label)
    end
    local comparisonKey = GetProfileSyncCandidateComparisonKey(candidate)
    if comparisonKey == "waiting_apply" then
      return "Waiting for combat"
    elseif comparisonKey == "same" then
      return "No action"
    elseif comparisonKey == "local_newer" then
      if isHost then
        return candidate.precisePushReady and "Push precise" or "Push host repair"
      end
      return "Wait for host push"
    elseif comparisonKey == "remote_newer" then
      if isHost then
        return candidate.precisePullReady and "Pull precise" or "Pull member repair"
      end
      return "Host may pull"
    elseif comparisonKey == "diverged" then
      if isHost then
        return candidate.precisePreviewReady and "Preview precise" or "Preview first"
      end
      return "Review with host"
    elseif comparisonKey == "different_lineage" then
      return "Full snapshot"
    end
    return "Inspect"
  end

  local function BuildProfileSyncDashboardCandidate(candidate, activeSession, isHost, bootstrapProgressByMember, archiveProgressByMember)
    candidate = type(candidate) == "table" and candidate or nil
    if type(candidate) ~= "table" then
      return nil
    end
    local model = {}
    for key, value in pairs(candidate) do
      model[key] = value
    end
    model.__dashboardComparisonKey = GetProfileSyncCandidateComparisonKey(candidate)
    model.__dashboardBootstrapState = GetProfileSyncCandidateBootstrapState(candidate, activeSession, isHost)
    model.__dashboardActionLabel = GetProfileSyncActionLabel(candidate, isHost)
    local bootstrapProgress = type(bootstrapProgressByMember) == "table"
      and bootstrapProgressByMember[string.lower(TrimText(candidate.memberKey))]
      or nil
    if type(bootstrapProgress) == "table" then
      model.__dashboardBootstrapProgress = TrimText(bootstrapProgress.label)
      model.__dashboardBootstrapProgressColor = TrimText(bootstrapProgress.color)
    end
    local archiveProgress = type(archiveProgressByMember) == "table"
      and archiveProgressByMember[string.lower(TrimText(candidate.memberKey))]
      or nil
    if type(archiveProgress) == "table" then
      model.__dashboardArchiveProgress = TrimText(archiveProgress.label)
      model.__dashboardArchiveProgressColor = TrimText(archiveProgress.color)
      model.__dashboardArchiveAgeSeconds = math.max(0, tonumber(archiveProgress.ageSeconds) or 0)
      model.__dashboardArchiveScope = TrimText(archiveProgress.scopeLabel)
      model.__dashboardArchivePhase = TrimText(archiveProgress.phase)
    end
    model.__dashboardDomainStates = {
      settings = GetProfileSyncDomainState(candidate, "settings"),
      permissions = GetProfileSyncDomainState(candidate, "permissions"),
      loot = GetProfileSyncDomainState(candidate, "loot"),
      session = GetProfileSyncDomainState(candidate, "session"),
    }
    local archiveProgressColor = TrimText(model.__dashboardArchiveProgressColor)
    if candidate.backgroundOnlyLootDifference == true
      or archiveProgressColor == "queued"
      or archiveProgressColor == "sending"
      or archiveProgressColor == "waiting_receipt"
      or archiveProgressColor == "waiting_apply"
      or archiveProgressColor == "background"
      or archiveProgressColor == "review"
    then
      model.__dashboardArchiveState = "backlog"
    elseif model.__dashboardComparisonKey == "same" and archiveProgressColor == "" then
      model.__dashboardArchiveState = "aligned"
    else
      model.__dashboardArchiveState = "unknown"
    end
    return model
  end

  local function BuildBootstrapProgressByMember(queueStatus, activeSession)
    queueStatus = type(queueStatus) == "table" and queueStatus or {}
    activeSession = type(activeSession) == "table" and activeSession or {}
    local activeSessionId = TrimText(activeSession.id)
    local progressByMember = {}
    local phaseRank = {
      queued = 1,
      sending = 2,
      waiting_receipt = 3,
      waiting_apply = 4,
    }

    local function setProgress(memberKey, label, color, rank)
      local key = string.lower(TrimText(memberKey))
      if key == "" then
        return
      end
      local existing = progressByMember[key]
      if type(existing) == "table" and math.max(0, tonumber(existing.rank) or 0) > rank then
        return
      end
      progressByMember[key] = {
        label = TrimText(label),
        color = TrimText(color),
        rank = rank,
      }
    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" then
          setProgress(transfer.target, "Bootstrap queued", "queued", phaseRank.queued)
        elseif state == "sending" then
          setProgress(transfer.target, "Bootstrap sending", "sending", phaseRank.sending)
        elseif state == "waiting_ack" then
          setProgress(transfer.target, "Waiting for receipt", "waiting_receipt", phaseRank.waiting_receipt)
        elseif state == "waiting_apply" then
          setProgress(transfer.target, "Received; waiting for combat", "waiting_apply", phaseRank.waiting_apply)
        end
      end
    end

    local snapshotBatch = type(queueStatus.profileSnapshotBatch) == "table" and queueStatus.profileSnapshotBatch or {}
    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
        local priority = math.max(0, tonumber(item.priority) or 0)
        local priorityLabel = priority <= 15 and "P1" or (priority <= 30 and "P2" or "P3")
        local transferKind = string.upper(TrimText(item.transferKind))
        local packageLabel = transferKind == "FULL" and "full"
          or ((transferKind == "PATCHES" or transferKind == "ROWPATCHES") and "patch" or "profile")
        local rosterSettling = math.max(0, tonumber(item.holdRemaining) or 0) > 0
        setProgress(
          item.target,
          priorityLabel .. " " .. packageLabel .. " queued" .. (rosterSettling and " (roster settling)" or ""),
          "queued",
          phaseRank.queued
        )
      end
    end
    return progressByMember
  end

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

    local function GetArchiveScopeLabel(transfer)
      local scopeParts = {
        string.lower(TrimText(transfer.mode)),
        string.lower(TrimText(transfer.reason)),
        string.lower(TrimText(transfer.lane)),
        string.lower(TrimText(transfer.domains)),
        string.lower(TrimText(transfer.subdomains)),
      }
      for _, fieldName in ipairs({ "scopeDomains", "scopeSubdomains" }) do
        for _, value in ipairs(type(transfer[fieldName]) == "table" and transfer[fieldName] or {}) do
          local text = string.lower(TrimText(value))
          if text ~= "" then
            scopeParts[#scopeParts + 1] = text
          end
        end
      end
      local scopeText = table.concat(scopeParts, " ")
      local isArchive = string.find(scopeText, "background", 1, true)
        or string.find(scopeText, "archive", 1, true)
        or string.find(scopeText, "history", 1, true)
        or string.find(scopeText, "session record", 1, true)
        or string.find(scopeText, "live-session", 1, true)
        or string.find(scopeText, "fun_award", 1, true)
      if not isArchive then
        return "", false
      end
      if string.find(scopeText, "fun_award", 1, true) or string.find(scopeText, "fun award", 1, true) then
        return "Awards", true
      elseif string.find(scopeText, "loot", 1, true) then
        return "Loot", true
      elseif string.find(scopeText, "history", 1, true) or string.find(scopeText, "session record", 1, true)
        or string.find(scopeText, "live-session", 1, true) then
        return "History", true
      end
      return "Archive", true
    end

    local function GetArchiveOutcome(transfer, scopeLabel)
      local state = string.lower(TrimText(transfer.state))
      local sentChunks = math.max(0, tonumber(transfer.sentChunks) or 0)
      local totalChunks = math.max(0, tonumber(transfer.totalChunks) or 0)
      if math.max(0, tonumber(transfer.ackedAt) or 0) > 0 or state == "acked" then
        return scopeLabel .. " ACK", "ready"
      elseif state == "waiting_apply" then
        return scopeLabel .. " apply", "waiting_apply"
      elseif state == "waiting_ack" then
        return scopeLabel .. " waiting ACK", "waiting_receipt"
      elseif state == "ack_timeout" then
        local recovery = TrimText(transfer.ackTimeoutRecoveryOutcome)
        return scopeLabel .. (recovery ~= "" and " recovery" or " timeout"), "review"
      elseif state == "failed" then
        return scopeLabel .. " failed", "review"
      elseif state == "sending" then
        return scopeLabel .. " " .. tostring(sentChunks) .. "/" .. tostring(totalChunks), "sending"
      elseif state == "queued" or math.max(0, tonumber(transfer.priority) or 0) > 0 then
        return scopeLabel .. " queued", "queued"
      end
      return scopeLabel .. " pending", "background"
    end

    local function GetArchiveElapsedSeconds(transfer)
      local state = string.lower(TrimText(transfer.state))
      if state == "waiting_ack" then
        return math.max(0, tonumber(transfer.acknowledgementAgeSeconds) or 0)
      end
      if state == "queued" or state == "sending" or state == "waiting_apply" or state == "ack_timeout" then
        local queuedAt = math.max(0, tonumber(transfer.queuedAt) or 0)
        local now = type(time) == "function" and time() or 0
        return queuedAt > 0 and math.max(0, now - queuedAt) or 0
      end
      return 0
    end

    local function FormatArchiveElapsed(seconds)
      seconds = math.max(0, tonumber(seconds) or 0)
      if seconds >= 120 then
        return tostring(math.floor(seconds / 60)) .. "m"
      end
      return tostring(math.ceil(seconds)) .. "s"
    end

    local function SetProgress(transfer, scopeLabel)
      local memberKey = string.lower(TrimText(transfer.target))
      if memberKey == "" then
        return
      end
      local timestamp = math.max(
        0,
        tonumber(transfer.ackedAt) or 0,
        tonumber(transfer.failedAt) or 0,
        tonumber(transfer.completedAt) or 0,
        tonumber(transfer.startedAt) or 0,
        tonumber(transfer.queuedAt) or 0
      )
      local existing = progressByMember[memberKey]
      if type(existing) == "table" and math.max(0, tonumber(existing.timestamp) or 0) > timestamp then
        return
      end
      local label, color = GetArchiveOutcome(transfer, scopeLabel)
      local ageSeconds = GetArchiveElapsedSeconds(transfer)
      local phase = string.lower(TrimText(transfer.state))
      if phase == "" and math.max(0, tonumber(transfer.priority) or 0) > 0 then
        phase = "queued"
      end
      if ageSeconds > 0 then
        label = label .. " " .. FormatArchiveElapsed(ageSeconds)
      end
      progressByMember[memberKey] = {
        label = label,
        color = color,
        timestamp = timestamp,
        ageSeconds = ageSeconds,
        scopeLabel = scopeLabel,
        phase = phase,
      }
    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 scopeLabel, isArchive = GetArchiveScopeLabel(transfer)
        if isArchive then
          SetProgress(transfer, scopeLabel)
        end
      end
    end
    local snapshotBatch = type(queueStatus.profileSnapshotBatch) == "table" and queueStatus.profileSnapshotBatch or {}
    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
        local scopeLabel, isArchive = GetArchiveScopeLabel(item)
        if not isArchive and math.max(0, tonumber(item.priority) or 0) > 30 then
          scopeLabel = "Archive"
          isArchive = true
        end
        if isArchive then
          SetProgress(item, scopeLabel)
        end
      end
    end
    return progressByMember
  end

  local function CanPullProfileSyncCandidate(candidate)
    candidate = type(candidate) == "table" and candidate or {}
    local comparisonKey = GetProfileSyncCandidateComparisonKey(candidate)
    if comparisonKey == "remote_newer" then
      return true
    end
    if comparisonKey ~= "diverged" then
      return false
    end
    local remoteDomains = type(candidate.effectiveRemoteNewerDomains) == "table" and candidate.effectiveRemoteNewerDomains or candidate.remoteNewerDomains or {}
    local localDomains = type(candidate.effectiveLocalNewerDomains) == "table" and candidate.effectiveLocalNewerDomains or candidate.localNewerDomains or {}
    for _, domain in ipairs(remoteDomains) do
      if not HasProfileSyncDomain(localDomains, domain) then
        return true
      end
    end
    return false
  end

  local function GetProfileSyncRequestButtonText(candidate)
    if type(candidate) ~= "table" then
      return "Select Member"
    end
    local visibleState = GetProfileSyncCandidateVisibleState(candidate)
    if visibleState == "waiting_apply" then
      return "Waiting for combat"
    elseif visibleState == "member_newer" then
      return candidate.precisePullReady and "Pull Precise Repair" or "Pull Member Repair"
    elseif visibleState == "conflict" then
      return CanPullProfileSyncCandidate(candidate) and "Pull Selected Repair" or "Preview First"
    elseif visibleState == "aligned" or visibleState == "converged" or visibleState == "background" then
      return "Already synced - no new data"
    elseif visibleState == "host_newer" then
      return "Host copy newer - no pull"
    elseif visibleState == "lineage" then
      return "Different lineage"
    end
    return "No newer data"
  end

  local function BuildSelectedProfileSyncHint(candidate, isHost)
    if type(candidate) ~= "table" then
      return "Select one joined member to inspect the recommended repair path."
    end
    local comparisonKey = GetProfileSyncCandidateComparisonKey(candidate)
    local visibleState = GetProfileSyncCandidateVisibleState(candidate)
    local memberName = TrimText(candidate.memberKey)
    local bootstrapLine = (memberName ~= "" and memberName or "Selected member")
      .. " is " .. GetProfileSyncBootstrapLabel(GetProfileSyncCandidateDisplayBootstrapState(candidate)) .. ". "
    if visibleState == "waiting_apply" then
      return bootstrapLine .. "The update was received and will be applied after combat ends."
    end
    if visibleState == "converged" then
      return bootstrapLine .. "The newest live repair was already acknowledged by this member. Sync state is converging on the latest applied generation."
    end
    if visibleState == "background" then
      return bootstrapLine .. "Current live loot and roll-ready data are aligned. Remaining loot archive or fun-award history can keep syncing in the background."
    end
    if visibleState == "aligned" or comparisonKey == "same" then
      return bootstrapLine .. "No repair is needed for this joined member."
    elseif visibleState == "host_newer" then
      if candidate.patchPushReady then
        return bootstrapLine .. "Host newer. Push Host Repair can send nested patch transfers for these loaded scopes: " .. tostring(candidate.patchPushText)
      end
      if candidate.precisePushReady then
        return bootstrapLine .. "Host newer. Push Host Repair can send only these loaded scopes: " .. tostring(candidate.precisePushText)
      end
      if TrimText(candidate.patchPushText) ~= "" then
        return bootstrapLine .. "Host newer. Patch-capable leaf scopes were found, but nested patch manifests are still loading. Push Host Repair will fall back to precise snapshots until they arrive."
      end
      return bootstrapLine .. "Host newer. Push Host Repair will use domain-level repair. Use Load Precise Differences first to load smaller leaf repair scopes."
    elseif visibleState == "member_newer" then
      if TrimText(candidate.patchPullText) ~= "" then
        return bootstrapLine .. "Member newer. Pull Member Repair can use nested patch transfers for patch-capable scopes and precise snapshots for the rest: " .. tostring(candidate.patchPullText)
      end
      if candidate.precisePullReady then
        return bootstrapLine .. "Member newer. Pull Member Repair can request only these loaded scopes: " .. tostring(candidate.precisePullText)
      end
      return bootstrapLine .. "Member newer. Use Load Precise Differences first if you want a smaller pull scope before applying their repair."
    elseif visibleState == "conflict" then
      local domainText = TrimText(candidate.effectiveLocalDomainText)
      if domainText == "" then
        domainText = TrimText(candidate.localDomainText)
      end
      return bootstrapLine
        .. "Both copies changed " .. (domainText ~= "" and domainText or "shared data")
        .. ". Next: preview the selected difference scopes."
    elseif visibleState == "lineage" then
      return bootstrapLine .. "Only a full snapshot fallback is possible; preview first if you need to inspect it."
    end
    return bootstrapLine .. (isHost and "Load Precise Differences can request detailed leaf checksum scopes without replacing profile data." or "Waiting for the host to decide the repair path.")
  end

  local function FindProfileSyncCandidateByKey(candidates, memberKey)
    local resolvedKey = TrimText(memberKey)
    if resolvedKey == "" then
      return nil
    end
    for _, candidate in ipairs(candidates or {}) do
      if TrimText(candidate.memberKey) == resolvedKey then
        return candidate
      end
    end
    return nil
  end

  local function GetProfileSyncStatusColor(severity)
    local resolvedSeverity = string.lower(TrimText(severity))
    if resolvedSeverity == "success" then
      return 0.30, 0.90, 0.36, 1.00
    elseif resolvedSeverity == "warn" then
      return 1.00, 0.82, 0.32, 1.00
    elseif resolvedSeverity == "error" then
      return 0.95, 0.32, 0.26, 1.00
    end
    return 0.82, 0.82, 0.86, 1.00
  end

  local OpenProfileSyncDetailPopup
  local CreateSyncDashboardHelpers = INTERNAL_API.LIDCOUNCIL_CreateLootSessionSyncDashboardHelpers_Impl
  if type(CreateSyncDashboardHelpers) ~= "function" then
    error("LidCouncil missing loot session sync dashboard helpers.")
  end
  local CreateSyncScopeHelpers = INTERNAL_API.LIDCOUNCIL_CreateLootSessionSyncScopeHelpers_Impl
  if type(CreateSyncScopeHelpers) ~= "function" then
    error("LidCouncil missing loot session sync scope helpers.")
  end
  local CreateSyncConflictResolverHelpers = INTERNAL_API.LIDCOUNCIL_CreateLootSessionSyncConflictResolverHelpers_Impl
  if type(CreateSyncConflictResolverHelpers) ~= "function" then
    error("LidCouncil missing loot session sync conflict resolver helpers.")
  end
  local CreateSyncHistoryHelpers = INTERNAL_API.LIDCOUNCIL_CreateLootSessionSyncHistoryHelpers_Impl
  if type(CreateSyncHistoryHelpers) ~= "function" then
    error("LidCouncil missing loot session sync history helpers.")
  end
  local syncDashboardHelpers = CreateSyncDashboardHelpers({
    ApplyFrameSkin = ApplyFrameSkin,
    TrimText = TrimText,
    FormatDateTime = FormatDateTime,
    GetSessionClassColor = GetSessionClassColor,
    GetProfileSyncDomainState = GetProfileSyncDomainState,
    GetProfileSyncDomainStateLabel = GetProfileSyncDomainStateLabel,
    GetProfileSyncDomainStateColor = GetProfileSyncDomainStateColor,
    GetProfileSyncComparisonLabel = GetProfileSyncComparisonLabel,
    GetProfileSyncComparisonColor = GetProfileSyncComparisonColor,
    GetProfileSyncBootstrapLabel = GetProfileSyncBootstrapLabel,
    GetProfileSyncBootstrapStateColor = GetProfileSyncBootstrapStateColor,
    OpenProfileSyncDetail = function(editor, candidate)
      if type(OpenProfileSyncDetailPopup) == "function" then
        OpenProfileSyncDetailPopup(editor, candidate)
      end
    end,
  })
  local RefreshSyncDashboard = syncDashboardHelpers.RefreshSyncDashboard
  local LayoutSyncDashboard = syncDashboardHelpers.LayoutSyncDashboard
  local syncScopeHelpers = CreateSyncScopeHelpers({
    ApplyFrameSkin = ApplyFrameSkin,
    TrimText = TrimText,
    RequestLootSessionSectionRefresh = RequestLootSessionSectionRefresh,
    GetSubdomainLabel = function(subdomain)
      local fn = ResolveOptionalApiFunction("LIDCOUNCIL_GetLootProfileSubdomainLabel")
      return type(fn) == "function" and fn(subdomain) or subdomain
    end,
    GetSubdomainParentDomain = function(subdomain)
      local fn = ResolveOptionalApiFunction("LIDCOUNCIL_GetLootProfileSubdomainParentDomain")
      return type(fn) == "function" and fn(subdomain) or ""
    end,
  })
  local RefreshSyncScopePicker = syncScopeHelpers.RefreshSyncScopePicker
  local LayoutSyncScopePicker = syncScopeHelpers.LayoutSyncScopePicker
  local syncConflictResolverHelpers = CreateSyncConflictResolverHelpers({
    ApplyFrameSkin = ApplyFrameSkin,
    TrimText = TrimText,
    GetSubdomainParentDomain = function(subdomain)
      local fn = ResolveOptionalApiFunction("LIDCOUNCIL_GetLootProfileSubdomainParentDomain")
      return type(fn) == "function" and fn(subdomain) or ""
    end,
  })
  local RefreshSyncConflictResolver = syncConflictResolverHelpers.RefreshSyncConflictResolver
  local BuildSelectedConflictResolution = syncConflictResolverHelpers.BuildSelectedConflictResolution
  local BuildSelectedHostSessionHistoryRepair = syncConflictResolverHelpers.BuildSelectedHostSessionHistoryRepair

  local function BuildHostSessionHistoryRepairFromUiSelection(editor, candidate, detailConflict)
    if type(BuildSelectedHostSessionHistoryRepair) ~= "function" then
      return nil
    end
    local opts = {}
    local selectedPreview = type(editor) == "table"
      and type(editor.lootSessionSelectedScopeActions) == "table"
      and type(editor.lootSessionSelectedScopeActions.preview) == "table"
      and editor.lootSessionSelectedScopeActions.preview
      or nil
    if type(selectedPreview) == "table"
      and selectedPreview.selectionActive == true
      and string.lower(TrimText(selectedPreview.targetMemberKey)) == string.lower(TrimText(type(candidate) == "table" and candidate.memberKey or ""))
    then
      opts.preselectedSubdomains = selectedPreview.subdomains
    end
    return BuildSelectedHostSessionHistoryRepair(editor, candidate, detailConflict, opts)
  end
  local syncHistoryHelpers = CreateSyncHistoryHelpers({
    ApplyFrameSkin = ApplyFrameSkin,
    TrimText = TrimText,
    FormatDateTime = FormatDateTime,
    RequestLootSessionSectionRefresh = RequestLootSessionSectionRefresh,
    ResolveOptionalApiFunction = ResolveOptionalApiFunction,
  })
  local RefreshSyncHistoryPanel = syncHistoryHelpers.RefreshSyncHistoryPanel
  local LayoutSyncHistoryPanel = syncHistoryHelpers.LayoutSyncHistoryPanel

  local function AppendDomainDiffLines(lines, diff, key)
    local domain = type(diff) == "table" and type(diff[key]) == "table" and diff[key] or nil
    if not domain then
      return
    end
    if math.max(0, tonumber(domain.count) or 0) <= 0 and #(domain.lines or {}) == 0 then
      return
    end
    lines[#lines + 1] = tostring(domain.label or key) .. ": " .. tostring(tonumber(domain.count) or 0) .. " difference(s)"
    for _, text in ipairs(domain.lines or {}) do
      lines[#lines + 1] = "  - " .. tostring(text)
    end
  end

  local function ColorMarkup(text, hexColor)
    local resolvedText = tostring(text or "")
    local resolvedColor = TrimText(hexColor)
    if resolvedColor == "" then
      return resolvedText
    end
    return "|cff" .. resolvedColor .. resolvedText .. "|r"
  end

  local function FormatComparedChecksum(checksum, otherChecksum)
    local resolved = TrimText(checksum)
    local other = TrimText(otherChecksum)
    local label = GetProfileSyncDomainLabel(resolved)
    if resolved == "" or other == "" then
      return ColorMarkup(label, "b8b8c2")
    end
    if resolved == other then
      return ColorMarkup(label, "4de66b")
    end
    return ColorMarkup(label, "ff5145")
  end

  local function EnsureRecommendedActionHighlight(button)
    if type(button) ~= "table" then
      return nil
    end
    if button.__lootSessionRecommendedHighlight then
      return button.__lootSessionRecommendedHighlight
    end
    local fill = button:CreateTexture(nil, "BACKGROUND")
    fill:SetPoint("TOPLEFT", 2, -2)
    fill:SetPoint("BOTTOMRIGHT", -2, 2)
    fill:SetColorTexture(1.00, 0.82, 0.24, 0.16)
    fill:Hide()

    local stripe = button:CreateTexture(nil, "BORDER")
    stripe:SetPoint("TOPLEFT", 2, -2)
    stripe:SetPoint("BOTTOMLEFT", 2, 2)
    stripe:SetWidth(4)
    stripe:SetColorTexture(1.00, 0.82, 0.24, 0.95)
    stripe:Hide()

    button.__lootSessionRecommendedHighlight = {
      fill = fill,
      stripe = stripe,
    }
    return button.__lootSessionRecommendedHighlight
  end

  local function SetRecommendedActionHighlight(button, active)
    local highlight = EnsureRecommendedActionHighlight(button)
    if type(highlight) ~= "table" then
      return
    end
    local show = active and true or false
    if highlight.fill then
      highlight.fill:SetShown(show)
    end
    if highlight.stripe then
      highlight.stripe:SetShown(show)
    end
  end

  local function BuildProfileSyncDetailText(candidate, syncStatus)
    candidate = type(candidate) == "table" and candidate or {}
    syncStatus = type(syncStatus) == "table" and syncStatus or {}
    local memberKey = TrimText(candidate.memberKey)
    local comparisonKey = GetProfileSyncCandidateComparisonKey(candidate)
    local bootstrapState = GetProfileSyncCandidateDisplayBootstrapState(candidate)
    local recoveryInfo = GetCandidateRecoveryInfo(candidate)
    local getRevisionSummary = ResolveOptionalApiFunction("LIDCOUNCIL_GetLootProfileRevisionSummary")
    local localSummary = type(getRevisionSummary) == "function" and getRevisionSummary(syncStatus.profileName) or nil
    local function GetSummaryRevision(summary, key)
      return math.max(0, tonumber(type(summary) == "table" and summary[key]) or 0)
    end
    local function GetSummaryChecksum(summary, key)
      return GetProfileSyncDomainLabel(type(summary) == "table" and summary[key] or "")
    end
    local function FirstDomainText(primary, fallback)
      local resolved = TrimText(primary)
      if resolved ~= "" then
        return resolved
      end
      return TrimText(fallback)
    end
    local localSettingsChecksum = TrimText(type(localSummary) == "table" and localSummary.settingsChecksum or "")
    local localPermissionsChecksum = TrimText(type(localSummary) == "table" and localSummary.permissionsChecksum or "")
    local localLootChecksum = TrimText(type(localSummary) == "table" and localSummary.lootChecksum or "")
    local localSessionChecksum = TrimText(type(localSummary) == "table" and localSummary.sessionChecksum or "")
    local memberSettingsChecksum = TrimText(candidate.settingsChecksum)
    local memberPermissionsChecksum = TrimText(candidate.permissionsChecksum)
    local memberLootChecksum = TrimText(FirstDomainText(candidate.lootChecksum, candidate.operationalChecksum))
    local memberSessionChecksum = TrimText(FirstDomainText(candidate.sessionChecksum, candidate.operationalChecksum))
    local lines = {
      "Member: " .. (memberKey ~= "" and memberKey or "Unknown"),
      "State: " .. GetProfileSyncComparisonLabel(comparisonKey),
      "Bootstrap: " .. GetProfileSyncBootstrapLabel(bootstrapState),
      "Member newer: " .. GetProfileSyncDomainLabel(GetProfileSyncCandidateDisplayDomainText(candidate, "remote", "shared data")),
      "Host newer: " .. GetProfileSyncDomainLabel(GetProfileSyncCandidateDisplayDomainText(candidate, "local", "shared data")),
      "Last profile timestamp: " .. ((tonumber(candidate.updatedAt) or 0) > 0 and FormatDateTime(candidate.updatedAt) or "-"),
    }
    if type(recoveryInfo) == "table" then
      lines[#lines + 1] = "Last delta recovery: " .. tostring(recoveryInfo.label)
      if TrimText(recoveryInfo.requestedScope) ~= "" then
        lines[#lines + 1] = "Requested repair scope: " .. tostring(recoveryInfo.requestedScope)
      end
      if TrimText(recoveryInfo.scopeKinds) ~= "" then
        lines[#lines + 1] = "Scope escalation: " .. tostring(recoveryInfo.scopeKinds)
      end
      if recoveryInfo.at > 0 then
        lines[#lines + 1] = "Recovery recorded: " .. FormatDateTime(recoveryInfo.at)
      end
      if TrimText(recoveryInfo.summary) ~= "" then
        lines[#lines + 1] = "Recovery summary: " .. tostring(recoveryInfo.summary)
      end
    end
    lines[#lines + 1] = ""
    lines[#lines + 1] = "Your local copy:"
    lines[#lines + 1] = "Settings: r" .. tostring(GetSummaryRevision(localSummary, "settings")) .. " | " .. FormatComparedChecksum(localSettingsChecksum, memberSettingsChecksum)
    lines[#lines + 1] = "Permissions: r" .. tostring(GetSummaryRevision(localSummary, "permissions")) .. " | " .. FormatComparedChecksum(localPermissionsChecksum, memberPermissionsChecksum)
    lines[#lines + 1] = "Loot Data: r" .. tostring(GetSummaryRevision(localSummary, "loot")) .. " | " .. FormatComparedChecksum(localLootChecksum, memberLootChecksum)
    lines[#lines + 1] = "Current Session State: r" .. tostring(GetSummaryRevision(localSummary, "session")) .. " | " .. FormatComparedChecksum(localSessionChecksum, memberSessionChecksum)
    lines[#lines + 1] = ""
    lines[#lines + 1] = "Selected member report:"
    lines[#lines + 1] = "Settings: r" .. tostring(candidate.settings or 0) .. " | " .. FormatComparedChecksum(memberSettingsChecksum, localSettingsChecksum)
    lines[#lines + 1] = "Permissions: r" .. tostring(candidate.permissions or 0) .. " | " .. FormatComparedChecksum(memberPermissionsChecksum, localPermissionsChecksum)
    lines[#lines + 1] = "Loot Data: r" .. tostring(candidate.loot or candidate.operational or 0) .. " | " .. FormatComparedChecksum(memberLootChecksum, localLootChecksum)
    lines[#lines + 1] = "Current Session State: r" .. tostring(candidate.session or candidate.operational or 0) .. " | " .. FormatComparedChecksum(memberSessionChecksum, localSessionChecksum)

    if candidate.generationConverged then
      lines[#lines + 1] = ""
      lines[#lines + 1] = ColorMarkup(
        "Latest live repair acknowledged. The visible sync state is following the newest applied repair generation.",
        "7fd0ff"
      )
    end

    if candidate.backgroundOnlyLootDifference then
      lines[#lines + 1] = ""
      lines[#lines + 1] = ColorMarkup(
        "Live-ready note: current roster / live loot data are aligned. Remaining loot archive or fun-award history can continue syncing in the background.",
        "b3a3f0"
      )
    end

    if TrimText(candidate.preciseRequestState) == "waiting" then
      lines[#lines + 1] = ""
      lines[#lines + 1] = "Precise comparison: waiting for "
        .. tostring(math.max(0, tonumber(candidate.preciseRequestedDomainCount) or 0)
          - math.max(0, tonumber(candidate.preciseReceivedDomainCount) or 0))
        .. " domain response(s). Previously loaded scopes are hidden until this request completes."
    elseif TrimText(candidate.preciseRequestState) == "failed" then
      lines[#lines + 1] = ""
      lines[#lines + 1] = "Precise comparison failed: " .. tostring(TrimText(candidate.preciseRequestError) ~= ""
        and candidate.preciseRequestError or "response_timeout") .. ". Retry before choosing a repair scope."
    elseif candidate.preciseNoDifferences == true then
      lines[#lines + 1] = ""
      lines[#lines + 1] = "Precise comparison complete: no differing leaf scopes were found. Broad fallback is disabled for this result."
    elseif candidate.preciseDetailLoaded then
      lines[#lines + 1] = ""
      lines[#lines + 1] = "Loaded precise leaf scopes:"
      if TrimText(candidate.precisePushText) ~= "" then
        lines[#lines + 1] = "Host repair scope: " .. tostring(candidate.precisePushText)
      end
      if TrimText(candidate.precisePullText) ~= "" then
        lines[#lines + 1] = "Member repair scope: " .. tostring(candidate.precisePullText)
      end
      if TrimText(candidate.precisePreviewText) ~= "" and TrimText(candidate.precisePreviewText) ~= TrimText(candidate.precisePullText)
          and TrimText(candidate.precisePreviewText) ~= TrimText(candidate.precisePushText) then
        lines[#lines + 1] = "Preview scope: " .. tostring(candidate.precisePreviewText)
      end
    end

    local detailDiff = type(syncStatus.detailDiff) == "table" and syncStatus.detailDiff or nil
    if type(detailDiff) == "table" and TrimText(detailDiff.memberKey) == memberKey then
      lines[#lines + 1] = ""
      lines[#lines + 1] = "Detailed snapshot diff:"
      if detailDiff.hasChanges == false then
        lines[#lines + 1] = "No exact differences were found in the compared sync domains."
      else
        local shownDomain = false
        for _, domain in ipairs(type(detailDiff.scopeDomains) == "table" and detailDiff.scopeDomains or { "settings", "permissions", "loot", "session" }) do
          AppendDomainDiffLines(lines, detailDiff, domain)
          shownDomain = true
        end
        if not shownDomain then
          AppendDomainDiffLines(lines, detailDiff, "settings")
          AppendDomainDiffLines(lines, detailDiff, "permissions")
          AppendDomainDiffLines(lines, detailDiff, "loot")
          AppendDomainDiffLines(lines, detailDiff, "session")
        end
      end
    else
      lines[#lines + 1] = ""
      lines[#lines + 1] = "Detailed snapshot diff is not loaded yet."
      if comparisonKey == "local_newer" then
        lines[#lines + 1] = ColorMarkup(
          "No newer member information is available. Please push the host profile to this member at this stage.",
          "4de66b"
        )
      else
        lines[#lines + 1] = "Use Preview Member Repair or Preview Selected Repair to request this member's differing shared-profile data for inspection without applying it."
      end
    end

    local detailConflict = type(syncStatus.detailConflict) == "table" and syncStatus.detailConflict or nil
    if type(detailConflict) == "table" and TrimText(detailConflict.memberKey) == memberKey and tonumber(detailConflict.totalRows) and tonumber(detailConflict.totalRows) > 0 then
      lines[#lines + 1] = ""
      lines[#lines + 1] = "Nested preview rows:"
      lines[#lines + 1] = tostring(detailConflict.totalRows) .. " member-selectable nested differences are loaded below."
      lines[#lines + 1] = "Check only the rows you want to resolve: Apply uses member values; Host Session Sync sends selected historical session leaves from the host."
      lines[#lines + 1] = "What Differs shows the exact field inside that leaf, such as one fun-award roll entry, one live-board vote, one selection, or one session member record."
    end

    return table.concat(lines, "\n")
  end

  local function BuildProfileSyncDeliveryHistoryText(editor, candidate)
    editor = type(editor) == "table" and editor or {}
    candidate = type(candidate) == "table" and candidate or {}
    local queueStatus = type(editor.lootSessionCommQueueStatusData) == "table"
      and editor.lootSessionCommQueueStatusData or {}
    local memberKey = string.lower(TrimText(candidate.memberKey))
    local activeSessionId = TrimText(editor.__lidSyncDetailActiveSessionId)
    if memberKey == "" then
      return ""
    end

    local function AppendScopePart(parts, value)
      local text = string.lower(TrimText(value))
      if text ~= "" then
        parts[#parts + 1] = text
      end
    end

    local function GetScopeText(record)
      local parts = {}
      AppendScopePart(parts, record.reason)
      AppendScopePart(parts, record.mode)
      AppendScopePart(parts, record.lane)
      AppendScopePart(parts, record.scope)
      AppendScopePart(parts, record.transferKind)
      AppendScopePart(parts, record.domains)
      AppendScopePart(parts, record.subdomains)
      for _, fieldName in ipairs({ "scopeDomains", "scopeSubdomains", "domains", "subdomains", "requestedDomains", "requestedSubdomains" }) do
        local values = type(record[fieldName]) == "table" and record[fieldName] or nil
        if values then
          for _, value in ipairs(values) do
            AppendScopePart(parts, value)
          end
        end
      end
      return table.concat(parts, " ")
    end

    local function GetDeliveryScope(record)
      local scopeText = GetScopeText(record)
      if string.find(scopeText, "fun_award", 1, true) or string.find(scopeText, "fun award", 1, true) then
        return "Fun Awards", "P3"
      end
      if string.find(scopeText, "bootstrap", 1, true) or string.find(scopeText, "roll_ready", 1, true) then
        return "Roll-ready profile", "P1"
      end
      if string.find(scopeText, "archive", 1, true) or string.find(scopeText, "history", 1, true)
        or string.find(scopeText, "session record", 1, true) or string.find(scopeText, "live-session", 1, true)
      then
        if string.find(scopeText, "loot", 1, true) then
          return "Loot Archive", "P3"
        end
        return "Session History", "P3"
      end
      if string.find(scopeText, "session", 1, true) or string.find(scopeText, "live", 1, true) then
        return "Current Session State", "P2"
      end
      return "Profile Data", "P2"
    end

    local function GetTransferOutcome(transfer)
      local state = string.lower(TrimText(transfer.state))
      local sentChunks = math.max(0, tonumber(transfer.sentChunks) or 0)
      local totalChunks = math.max(0, tonumber(transfer.totalChunks) or 0)
      local acknowledgementAge = math.max(0, tonumber(transfer.acknowledgementAgeSeconds) or 0)
      if math.max(0, tonumber(transfer.ackedAt) or 0) > 0 or state == "acked" then
        return "Receipt confirmed"
      elseif state == "waiting_apply" then
        return "Receipt confirmed; waiting for combat to end"
      elseif state == "waiting_ack" then
        return "Receipt pending (" .. tostring(math.ceil(acknowledgementAge)) .. "s)"
      elseif state == "ack_timeout" then
        local recoveryOutcome = string.gsub(TrimText(transfer.ackTimeoutRecoveryOutcome), "_", " ")
        local recoveryError = TrimText(transfer.ackTimeoutRecoveryError)
        if recoveryOutcome == "" then
          recoveryOutcome = "pending"
        end
        local result = "Receipt timed out; recovery " .. recoveryOutcome
        if recoveryError ~= "" then
          result = result .. " (" .. recoveryError .. ")"
        end
        return result
      elseif state == "failed" then
        local reason = TrimText(transfer.failureReason)
        if reason == "" then
          reason = TrimText(transfer.terminalReason)
        end
        if reason == "" then
          reason = TrimText(transfer.failedKind)
        end
        return "Failed" .. (reason ~= "" and (": " .. reason) or "")
      elseif state == "sending" then
        return "Sending " .. tostring(sentChunks) .. "/" .. tostring(totalChunks) .. " chunks"
      elseif state == "queued" then
        return "Queued"
      elseif state ~= "" then
        return state
      end
      return "Awaiting delivery state"
    end

    local transfers = {}
    for _, transfer in ipairs(type(queueStatus.profileTransfers) == "table" and queueStatus.profileTransfers or {}) do
      if type(transfer) == "table"
        and string.lower(TrimText(transfer.target)) == memberKey
        and (activeSessionId == "" or TrimText(transfer.sessionId) == activeSessionId)
      then
        transfers[#transfers + 1] = transfer
      end
    end
    table.sort(transfers, function(left, right)
      return math.max(0, tonumber(left.queuedAt) or 0) > math.max(0, tonumber(right.queuedAt) or 0)
    end)

    local lines = { "Delivery History for " .. TrimText(candidate.memberKey) .. " (this session):" }
    if #transfers == 0 then
      lines[#lines + 1] = "No active or retained delivery record for this member. A sent transfer is only complete after receiver ACK."
    else
      for index = 1, math.min(#transfers, 4) do
        local transfer = transfers[index]
        local scopeLabel, priorityLabel = GetDeliveryScope(transfer)
        local chunkTotal = math.max(0, tonumber(transfer.totalChunks) or 0)
        local chunkSent = math.min(chunkTotal, math.max(0, tonumber(transfer.sentChunks) or 0))
        local chunkText = chunkTotal > 0 and (" | " .. tostring(chunkSent) .. "/" .. tostring(chunkTotal) .. " chunks") or ""
        lines[#lines + 1] = priorityLabel .. " | " .. scopeLabel .. " | " .. GetTransferOutcome(transfer) .. chunkText
      end
    end

    local eventLines = 0
    local decisionStats = type(queueStatus.profileSyncDecisionStats) == "table" and queueStatus.profileSyncDecisionStats or {}
    for _, event in ipairs(type(decisionStats.recentEvents) == "table" and decisionStats.recentEvents or {}) do
      if eventLines >= 3 then
        break
      end
      if type(event) == "table"
        and string.lower(TrimText(event.target)) == memberKey
        and (activeSessionId == "" or TrimText(event.sessionId) == activeSessionId)
      then
        local scopeLabel, priorityLabel = GetDeliveryScope(event)
        if priorityLabel == "P3" then
          if eventLines == 0 then
            lines[#lines + 1] = "Recent P3 delivery decisions:"
          end
          local action = string.gsub(TrimText(event.action), "_", " ")
          local stage = TrimText(event.stage)
          local outcome = action ~= "" and action or (stage ~= "" and stage or "recorded")
          local chunks = math.max(0, tonumber(event.chunkCount) or 0)
          local errorText = TrimText(event.error)
          local recordedAt = math.max(0, tonumber(event.lastRecordedAt) or tonumber(event.recordedAt) or 0)
          local timestamp = recordedAt > 0 and FormatDateTime(recordedAt) or "time unavailable"
          local suffix = chunks > 0 and (" | " .. tostring(chunks) .. " chunks") or ""
          if errorText ~= "" then
            suffix = suffix .. " | failed: " .. errorText
          elseif event.fallback == true then
            suffix = suffix .. " | safe recovery"
          end
          lines[#lines + 1] = timestamp .. " | " .. priorityLabel .. " | " .. scopeLabel .. " | " .. outcome .. suffix
          eventLines = eventLines + 1
        end
      end
    end

    local payloadLines = 0
    local resolvedKind = TrimText(queueStatus.lastOutboundIssueResolvedKind)
    local resolvedTarget = string.lower(TrimText(queueStatus.lastOutboundIssueResolvedTarget))
    local resolvedAt = math.max(0, tonumber(queueStatus.lastOutboundIssueResolvedAt) or 0)
    for _, issue in ipairs(type(queueStatus.outboundIssueHistory) == "table" and queueStatus.outboundIssueHistory or {}) do
      if payloadLines >= 3 then
        break
      end
      local issueTarget = string.lower(TrimText(type(issue) == "table" and issue.target or ""))
      local issueSessionId = TrimText(type(issue) == "table" and issue.sessionId or "")
      local category = string.lower(TrimText(type(issue) == "table" and issue.category or ""))
      local reason = TrimText(type(issue) == "table" and issue.reason or "")
      if type(issue) == "table"
        and issueTarget == memberKey
        and (activeSessionId == "" or issueSessionId == "" or issueSessionId == activeSessionId)
        and category == "payload_rejected"
        and (string.find(reason, "payload_exceeds_safe_limit", 1, true)
          or string.find(reason, "comm_payload_exceeds_safe_limit", 1, true))
      then
        local scopeRecord = issue
        local transferId = TrimText(issue.transferId)
        if transferId ~= "" then
          for _, transfer in ipairs(transfers) do
            if TrimText(transfer.transferId) == transferId then
              scopeRecord = transfer
              break
            end
          end
        end
        local scopeLabel, priorityLabel = GetDeliveryScope(scopeRecord)
        if priorityLabel == "P3" then
          if payloadLines == 0 then
            lines[#lines + 1] = "Payload-blocked P3 deliveries:"
          end
          local issueAt = math.max(0, tonumber(issue.at) or 0)
          local timestamp = issueAt > 0 and FormatDateTime(issueAt) or "time unavailable"
          local bytes = math.max(0, tonumber(issue.bytes) or 0)
          local kind = TrimText(issue.kind)
          local resolution = ""
          if resolvedAt > 0 and resolvedAt >= issueAt
            and string.upper(resolvedKind) == string.upper(kind)
            and (resolvedTarget == "" or resolvedTarget == memberKey)
          then
            resolution = " | later send resolved " .. FormatDateTime(resolvedAt)
          end
          lines[#lines + 1] = timestamp .. " | " .. scopeLabel .. " | "
            .. (kind ~= "" and kind or "unknown opcode")
            .. (bytes > 0 and (" | " .. tostring(bytes) .. " bytes") or "")
            .. " | " .. reason .. resolution
          payloadLines = payloadLines + 1
        end
      end
    end
    return table.concat(lines, "\n")
  end

  local function RefreshProfileSyncDetailPopup(editor, frame, candidate, syncStatus)
    frame = frame or (editor and editor.lootSessionSyncDetailPopup)
    candidate = type(candidate) == "table" and candidate or type(frame) == "table" and frame.__candidate or nil
    syncStatus = type(syncStatus) == "table" and syncStatus or {}
    if not frame or type(candidate) ~= "table" then
      return
    end

    local detailDiff = type(syncStatus.detailDiff) == "table"
      and TrimText(syncStatus.detailDiff.memberKey) == TrimText(candidate.memberKey)
      and syncStatus.detailDiff
      or nil
    local detailConflict = type(syncStatus.detailConflict) == "table"
      and TrimText(syncStatus.detailConflict.memberKey) == TrimText(candidate.memberKey)
      and syncStatus.detailConflict
      or nil
    local hasResolver = type(detailConflict) == "table" and tonumber(detailConflict.totalRows) and tonumber(detailConflict.totalRows) > 0
    local hasLoadedPreview = type(detailDiff) == "table" or hasResolver
    local canResolveHostSessionHistory = hasResolver and syncStatus.isHost == true
    local recommendationAction = string.lower(TrimText(type(candidate.safeRecommendation) == "table" and candidate.safeRecommendation.action or ""))

    frame:SetSize(hasResolver and 820 or 620, hasResolver and 600 or 480)
    if frame.bodyScroll then
      frame.bodyScroll:ClearAllPoints()
      frame.bodyScroll:SetPoint("TOPLEFT", 18, -50)
      frame.bodyScroll:SetPoint("BOTTOMRIGHT", -32, hasResolver and 344 or 50)
    end
    if frame.body then
      local scrollWidth = math.max(180, (frame:GetWidth() or 0) - 62)
      frame.body:SetWidth(math.max(180, scrollWidth - 8))
      local detailText = BuildProfileSyncDetailText(candidate, syncStatus)
      local deliveryHistoryText = BuildProfileSyncDeliveryHistoryText(editor, candidate)
      if deliveryHistoryText ~= "" then
        detailText = deliveryHistoryText .. "\n\n" .. detailText
      end
      local actionMessage = TrimText(frame.__actionMessageText)
      if actionMessage ~= "" then
        detailText = "Last action: " .. actionMessage .. "\n\n" .. detailText
      end
      frame.body:SetText(detailText)
      if frame.bodyContent then
        frame.bodyContent:SetWidth(math.max(180, scrollWidth - 8))
        frame.bodyContent:SetHeight(math.max(1, math.ceil(frame.body:GetStringHeight() or 0) + 8))
      end
      if frame.bodyScroll and frame.bodyScroll.UpdateScrollChildRect then
        frame.bodyScroll:UpdateScrollChildRect()
      end
    end
    if frame.requestBtn then
      local selectedActions = type(editor.lootSessionSelectedScopeActions) == "table" and editor.lootSessionSelectedScopeActions.preview or nil
      local comparisonKey = GetProfileSyncCandidateComparisonKey(candidate)
      if comparisonKey == "waiting_apply" then
        frame.requestBtn:SetText("Waiting for Combat")
      elseif comparisonKey == "local_newer" then
        frame.requestBtn:SetText("Preview Not Needed")
      elseif type(selectedActions) == "table"
        and selectedActions.selectionActive
        and selectedActions.compatibleCount > 0
        and string.lower(TrimText(selectedActions.targetMemberKey)) == string.lower(TrimText(candidate.memberKey)) then
        frame.requestBtn:SetText("Preview Repair (" .. tostring(selectedActions.compatibleCount) .. ")")
      else
        frame.requestBtn:SetText(candidate.precisePreviewReady and "Preview Repair" or "Preview Member Repair")
      end
      if frame.requestBtn.Enable then
        if comparisonKey == "local_newer" or comparisonKey == "waiting_apply"
          or candidate.preciseNoDifferences == true
          or TrimText(candidate.preciseRequestState) == "waiting"
          or TrimText(candidate.preciseRequestState) == "failed" then
          frame.requestBtn:Disable()
        else
          frame.requestBtn:Enable()
        end
      end
    end
    if frame.pullBtn then
      frame.pullBtn:SetText("Pull Repair")
      if frame.pullBtn.Enable then
        if hasLoadedPreview and candidate.preciseNoDifferences ~= true
          and TrimText(candidate.preciseRequestState) ~= "waiting"
          and TrimText(candidate.preciseRequestState) ~= "failed"
          and CanPullProfileSyncCandidate(candidate) then
          frame.pullBtn:Enable()
        else
          frame.pullBtn:Disable()
        end
      end
    end
    if frame.pushBtn then
      frame.pushBtn:SetText("Push Repair")
      local pushDomains = type(candidate.effectiveHostRepairDomains) == "table" and candidate.effectiveHostRepairDomains or candidate.hostRepairDomains
      local canPush = type(pushDomains) == "table" and #pushDomains > 0
      local pushComparison = GetProfileSyncCandidateComparisonKey(candidate)
      if frame.pushBtn.Enable then
        if pushComparison ~= "waiting_apply" and candidate.preciseNoDifferences ~= true
          and TrimText(candidate.preciseRequestState) ~= "waiting"
          and TrimText(candidate.preciseRequestState) ~= "failed"
          and (hasLoadedPreview or pushComparison == "local_newer") and canPush then
          frame.pushBtn:Enable()
        else
          frame.pushBtn:Disable()
        end
      end
    end
    SetRecommendedActionHighlight(frame.requestBtn, recommendationAction == "preview")
    SetRecommendedActionHighlight(frame.pullBtn, recommendationAction == "pull")
    SetRecommendedActionHighlight(frame.pushBtn, recommendationAction == "push")
    if frame.applyBtn then
      if hasResolver then
        local resolution = BuildSelectedConflictResolution(editor, candidate, detailConflict)
        frame.applyBtn:Show()
        frame.applyBtn:SetText(
          resolution.selectionActive
            and ("Apply + Sync Selected (" .. tostring(resolution.selectedCount) .. ")")
            or "Apply + Sync Selected"
        )
        if resolution.selectionActive and GetProfileSyncCandidateComparisonKey(candidate) ~= "waiting_apply" then
          frame.applyBtn:Enable()
        else
          frame.applyBtn:Disable()
        end
      else
        frame.applyBtn:Hide()
        frame.applyBtn:Disable()
      end
    end
    if frame.hostSessionHistoryBtn then
      local hostRepair = BuildHostSessionHistoryRepairFromUiSelection(editor, candidate, detailConflict)
      local compatibleCount = math.max(0, tonumber(type(hostRepair) == "table" and hostRepair.compatibleCount or 0) or 0)
      local incompatibleCount = math.max(0, tonumber(type(hostRepair) == "table" and hostRepair.incompatibleCount or 0) or 0)
      frame.hostSessionHistoryBtn:SetText(
        compatibleCount > 0
          and ("Keep Host Session History + Sync (" .. tostring(compatibleCount) .. ")")
          or "Keep Host Session History + Sync"
      )
      frame.hostSessionHistoryBtn:ClearAllPoints()
      frame.hostSessionHistoryBtn:SetPoint("BOTTOMLEFT", 18, hasResolver and 310 or 46)
      if canResolveHostSessionHistory then
        frame.hostSessionHistoryBtn:Show()
      else
        frame.hostSessionHistoryBtn:Hide()
      end
      if frame.hostSessionHistoryBtn.Enable then
        if canResolveHostSessionHistory
          and GetProfileSyncCandidateComparisonKey(candidate) ~= "waiting_apply"
          and compatibleCount > 0
        then
          frame.hostSessionHistoryBtn:Enable()
        else
          frame.hostSessionHistoryBtn:Disable()
        end
      end
      if frame.hostSessionHistoryHint then
        if canResolveHostSessionHistory then
          frame.hostSessionHistoryHint:Show()
        else
          frame.hostSessionHistoryHint:Hide()
        end
        if incompatibleCount > 0 then
          frame.hostSessionHistoryHint:SetText(
            "Selected non-session values stay protected. This action sends only selected Session Records and saved Live Board history from the host."
          )
        else
          frame.hostSessionHistoryHint:SetText(
            "Selected Session Records and saved Live Board history will be sent from the host in the background archive lane."
          )
        end
      end
    end
    if type(RefreshSyncConflictResolver) == "function" then
      RefreshSyncConflictResolver(editor, frame, candidate, detailConflict)
    end
  end

  local function EnsureProfileSyncDetailPopup(editor)
    if not editor then
      return nil
    end
    if editor.lootSessionSyncDetailPopup then
      return editor.lootSessionSyncDetailPopup
    end

    local frame = CreateFrame("Frame", "LIDCOUNCIL_ProfileSyncDetailPopup", UIParent, "BackdropTemplate")
    frame:SetSize(620, 480)
    frame:SetPoint("CENTER")
    frame:SetFrameStrata("DIALOG")
    frame:SetFrameLevel(500)
    frame:EnableMouse(true)
    frame:SetMovable(true)
    frame:RegisterForDrag("LeftButton")
    frame:SetScript("OnDragStart", frame.StartMoving)
    frame:SetScript("OnDragStop", frame.StopMovingOrSizing)
    ApplyFrameSkin(frame)
    frame:Hide()

    local title = frame:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    title:SetPoint("TOPLEFT", 18, -16)
    title:SetText("Sync Detail")
    frame.title = title

    local closeBtn = CreateFrame("Button", nil, frame, "UIPanelCloseButton")
    closeBtn:SetPoint("TOPRIGHT", -6, -6)
    frame.closeBtn = closeBtn

    local bodyScroll = CreateFrame("ScrollFrame", nil, frame, "UIPanelScrollFrameTemplate")
    bodyScroll:SetPoint("TOPLEFT", 18, -50)
    bodyScroll:SetPoint("BOTTOMRIGHT", -32, 80)
    frame.bodyScroll = bodyScroll

    local bodyContent = CreateFrame("Frame", nil, bodyScroll)
    bodyContent:SetSize(1, 1)
    bodyScroll:SetScrollChild(bodyContent)
    frame.bodyContent = bodyContent

    local body = bodyContent:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    body:SetPoint("TOPLEFT", 0, 0)
    body:SetJustifyH("LEFT")
    body:SetJustifyV("TOP")
    body:SetSpacing(2)
    frame.body = body

    local requestBtn = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    requestBtn:SetSize(118, 24)
    requestBtn:SetPoint("BOTTOMLEFT", 18, 16)
    requestBtn:SetText("Preview Repair")
    requestBtn:SetScript("OnClick", function()
      local candidate = frame.__candidate
      local memberKey = TrimText(type(candidate) == "table" and candidate.memberKey or "")
      if memberKey == "" then
        return
      end
      editor.lootSessionSelectedSyncMember = memberKey
      local requestProfileUpdate = ResolveOptionalApiFunction("LIDCOUNCIL_RequestActiveProfileSnapshotFlow")
      local previewOptions = { mode = "PREVIEW" }
      local selectedActions = type(editor.lootSessionSelectedScopeActions) == "table" and editor.lootSessionSelectedScopeActions.preview or nil
      if type(selectedActions) == "table"
        and selectedActions.selectionActive
        and selectedActions.compatibleCount > 0
        and string.lower(TrimText(selectedActions.targetMemberKey)) == string.lower(memberKey) then
        previewOptions.domains = selectedActions.domains
        previewOptions.subdomains = selectedActions.subdomains
      end
      if RunSyncAction(editor, frame, "Preview repair", requestProfileUpdate, memberKey, previewOptions) then
        RefreshSyncManagementSection(editor)
        local getProfileSyncStatus = ResolveOptionalApiFunction("LIDCOUNCIL_GetActiveProfileSyncStatus")
        local syncStatus = ReadSyncActionValue(
          editor,
          frame,
          "Refresh preview detail",
          getProfileSyncStatus,
          {},
          editor and editor.lootSessionAllSyncCandidates or nil
        )
        RefreshProfileSyncDetailPopup(editor, frame, candidate, syncStatus)
      else
        RefreshProfileSyncDetailPopup(editor, frame, candidate, editor and editor.lootSessionProfileSyncStatusData or {})
      end
      if frame.bodyScroll then
        frame.bodyScroll:SetVerticalScroll(0)
      end
    end)
    frame.requestBtn = requestBtn
    editor.lootSessionSyncDetailPreviewBtn = requestBtn

    local pullBtn = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    pullBtn:SetSize(118, 24)
    pullBtn:SetPoint("LEFT", requestBtn, "RIGHT", 6, 0)
    pullBtn:SetText("Pull Repair")
    pullBtn:Disable()
    pullBtn:SetScript("OnClick", function()
      local candidate = frame.__candidate
      local memberKey = TrimText(type(candidate) == "table" and candidate.memberKey or "")
      if memberKey == "" then
        return
      end
      local requestProfileUpdate = ResolveOptionalApiFunction("LIDCOUNCIL_RequestActiveProfileSnapshotFlow")
      local options = nil
      local selectedActions = type(editor.lootSessionSelectedScopeActions) == "table" and editor.lootSessionSelectedScopeActions.pull or nil
      if type(selectedActions) == "table"
        and selectedActions.selectionActive
        and selectedActions.compatibleCount > 0
        and string.lower(TrimText(selectedActions.targetMemberKey)) == string.lower(memberKey) then
        options = {
          domains = selectedActions.domains,
          subdomains = selectedActions.subdomains,
        }
      end
      if RunSyncAction(editor, frame, "Pull repair", requestProfileUpdate, memberKey, options) then
        RefreshSyncManagementSection(editor)
      else
        RefreshProfileSyncDetailPopup(editor, frame, candidate, editor and editor.lootSessionProfileSyncStatusData or {})
      end
    end)
    frame.pullBtn = pullBtn
    editor.lootSessionSyncDetailPullBtn = pullBtn

    local pushBtn = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    pushBtn:SetSize(118, 24)
    pushBtn:SetPoint("LEFT", pullBtn, "RIGHT", 6, 0)
    pushBtn:SetText("Push Repair")
    pushBtn:Disable()
    pushBtn:SetScript("OnClick", function()
      local candidate = frame.__candidate
      local memberKey = TrimText(type(candidate) == "table" and candidate.memberKey or "")
      if memberKey == "" then
        return
      end
      local pushProfileUpdate = ResolveOptionalApiFunction("LIDCOUNCIL_PushActiveProfileSnapshotFlow")
      local options = nil
      local selectedActions = type(editor.lootSessionSelectedScopeActions) == "table" and editor.lootSessionSelectedScopeActions.push or nil
      if type(selectedActions) == "table"
        and selectedActions.selectionActive
        and selectedActions.compatibleCount > 0
        and string.lower(TrimText(selectedActions.targetMemberKey)) == string.lower(memberKey) then
        options = {
          domains = selectedActions.domains,
          subdomains = selectedActions.subdomains,
        }
      end
      if RunSyncAction(editor, frame, "Push repair", pushProfileUpdate, memberKey, options) then
        RefreshSyncManagementSection(editor)
      else
        RefreshProfileSyncDetailPopup(editor, frame, candidate, editor and editor.lootSessionProfileSyncStatusData or {})
      end
    end)
    frame.pushBtn = pushBtn
    editor.lootSessionSyncDetailPushBtn = pushBtn

    local applyBtn = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    applyBtn:SetSize(190, 24)
    applyBtn:SetPoint("BOTTOMRIGHT", -18, 16)
    applyBtn:SetText("Apply + Sync Selected")
    applyBtn:Hide()
    applyBtn:SetScript("OnClick", function()
      local candidate = frame.__candidate
      local memberKey = TrimText(type(candidate) == "table" and candidate.memberKey or "")
      if memberKey == "" then
        return
      end
      local getProfileSyncStatus = ResolveOptionalApiFunction("LIDCOUNCIL_GetActiveProfileSyncStatus")
      local syncStatus = ReadSyncActionValue(
        editor,
        frame,
        "Load selected sync detail",
        getProfileSyncStatus,
        {},
        editor and editor.lootSessionAllSyncCandidates or nil
      )
      local detailConflict = type(syncStatus.detailConflict) == "table"
        and TrimText(syncStatus.detailConflict.memberKey) == memberKey
        and syncStatus.detailConflict
        or nil
      local resolution = type(BuildSelectedConflictResolution) == "function"
        and BuildSelectedConflictResolution(editor, candidate, detailConflict)
        or nil
      if type(resolution) ~= "table" or resolution.selectionActive ~= true then
        return
      end
      local applyResolution = ResolveOptionalApiFunction("LIDCOUNCIL_ApplyActiveProfilePreviewConflictResolution")
      if RunSyncAction(editor, frame, "Apply selected repair", applyResolution, memberKey, resolution) then
        local refreshedStatus = ReadSyncActionValue(
          editor,
          frame,
          "Refresh applied sync detail",
          getProfileSyncStatus,
          {},
          editor and editor.lootSessionAllSyncCandidates or nil
        )
        RefreshProfileSyncDetailPopup(editor, frame, candidate, refreshedStatus)
      else
        RefreshProfileSyncDetailPopup(editor, frame, candidate, syncStatus)
      end
    end)
    frame.applyBtn = applyBtn
    editor.lootSessionSyncDetailApplyBtn = applyBtn

    local hostSessionHistoryBtn = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    hostSessionHistoryBtn:SetSize(250, 24)
    hostSessionHistoryBtn:SetPoint("BOTTOMLEFT", 18, 46)
    hostSessionHistoryBtn:SetText("Keep Host Session History + Sync")
    hostSessionHistoryBtn:Disable()
    hostSessionHistoryBtn:SetScript("OnClick", function()
      local candidate = frame.__candidate
      local memberKey = TrimText(type(candidate) == "table" and candidate.memberKey or "")
      if memberKey == "" then
        return
      end
      local getProfileSyncStatus = ResolveOptionalApiFunction("LIDCOUNCIL_GetActiveProfileSyncStatus")
      local syncStatus = ReadSyncActionValue(
        editor,
        frame,
        "Load selected sync detail",
        getProfileSyncStatus,
        {},
        editor and editor.lootSessionAllSyncCandidates or nil
      )
      local detailConflict = type(syncStatus.detailConflict) == "table"
        and TrimText(syncStatus.detailConflict.memberKey) == memberKey
        and syncStatus.detailConflict
        or nil
      local hostRepair = BuildHostSessionHistoryRepairFromUiSelection(editor, candidate, detailConflict)
      if type(hostRepair) ~= "table" or math.max(0, tonumber(hostRepair.compatibleCount) or 0) <= 0 then
        return
      end
      local pushProfileUpdate = ResolveOptionalApiFunction("LIDCOUNCIL_PushActiveProfileSnapshotFlow")
      local options = {
        domains = { "session" },
        subdomains = hostRepair.subdomains,
        mode = "BACKGROUND",
        reason = "host_session_history_conflict_archive",
      }
      if RunSyncAction(editor, frame, "Keep host session history", pushProfileUpdate, memberKey, options) then
        RefreshSyncManagementSection(editor)
        local refreshedStatus = ReadSyncActionValue(
          editor,
          frame,
          "Refresh host session history detail",
          getProfileSyncStatus,
          {},
          editor and editor.lootSessionAllSyncCandidates or nil
        )
        RefreshProfileSyncDetailPopup(editor, frame, candidate, refreshedStatus)
      else
        RefreshProfileSyncDetailPopup(editor, frame, candidate, syncStatus)
      end
    end)
    frame.hostSessionHistoryBtn = hostSessionHistoryBtn
    editor.lootSessionSyncDetailHostSessionHistoryBtn = hostSessionHistoryBtn

    local hostSessionHistoryHint = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    hostSessionHistoryHint:SetJustifyH("LEFT")
    hostSessionHistoryHint:SetPoint("LEFT", hostSessionHistoryBtn, "RIGHT", 8, 0)
    hostSessionHistoryHint:SetPoint("RIGHT", -18, 0)
    hostSessionHistoryHint:SetText("")
    frame.hostSessionHistoryHint = hostSessionHistoryHint

    if editor and editor.ApplyTheme then
      editor:ApplyTheme()
    end

    editor.lootSessionSyncDetailPopup = frame
    return frame
  end

  local function EnsureSyncRepairInfoButton(editor)
    if not editor then
      return nil
    end
    if editor.lootSessionSyncRepairInfoBtn then
      return editor.lootSessionSyncRepairInfoBtn
    end
    local parent = editor.lootSessionRightContent or editor.lootSessionRightBg or UIParent
    local button = CreateFrame("Button", nil, parent, "UIPanelButtonTemplate")
    button:SetSize(18, 18)
    button:SetText("?")
    button:SetScript("OnEnter", function(self)
      if type(GameTooltip) ~= "table" then
        return
      end
      GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
      GameTooltip:ClearLines()
      GameTooltip:AddLine("Push or Pull Repair Help", 1.00, 0.82, 0.28, true)
      GameTooltip:AddLine("First choose one joined member above, then click individual leaf rows if you want to narrow repair to exact scopes.", 0.92, 0.92, 0.96, true)
      GameTooltip:AddLine("Current leaf filter only affects the selected member. Leaving all rows clear keeps the broader repair behavior.", 0.92, 0.92, 0.96, true)
      GameTooltip:AddLine("The safest next action is highlighted directly on the real repair buttons below. There is no separate recommended-action button anymore.", 0.92, 0.92, 0.96, true)
      GameTooltip:AddLine("Preview only loads exact differences for inspection. The result is shown below this section and inside Sync Detail. It does not apply or sync anything by itself.", 0.92, 0.92, 0.96, true)
      GameTooltip:AddLine("Push Host Repair sends host-newer scopes. Pull Member Repair applies member-newer scopes back to the host. Preview is the safe first step for conflicts.", 0.92, 0.92, 0.96, true)
      GameTooltip:Show()
    end)
    button:SetScript("OnLeave", function()
      if type(GameTooltip) == "table" then
        GameTooltip:Hide()
      end
    end)
    editor.lootSessionSyncRepairInfoBtn = button
    return button
  end

  local function EnsureInlinePreviewPanel(editor)
    if not editor then
      return nil
    end
    if editor.lootSessionSyncInlinePreviewFrame then
      return editor.lootSessionSyncInlinePreviewFrame
    end
    local parent = editor.lootSessionRightContent or editor.lootSessionRightBg or UIParent
    local frame = CreateFrame("Frame", nil, parent, "BackdropTemplate")
    ApplyFrameSkin(frame)
    if frame.SetBackdropColor then
      frame:SetBackdropColor(0.05, 0.06, 0.08, 0.96)
    end
    frame:Hide()

    local title = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    title:SetJustifyH("LEFT")
    frame.title = title

    local hint = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    hint:SetJustifyH("LEFT")
    hint:SetJustifyV("TOP")
    frame.hint = hint

    local scroll = CreateFrame("ScrollFrame", nil, frame, "UIPanelScrollFrameTemplate")
    frame.scroll = scroll

    local content = CreateFrame("Frame", nil, scroll)
    content:SetSize(1, 1)
    scroll:SetScrollChild(content)
    frame.content = content

    local body = content:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    body:SetPoint("TOPLEFT", 0, 0)
    body:SetJustifyH("LEFT")
    body:SetJustifyV("TOP")
    body:SetSpacing(2)
    frame.body = body

    local resolverHost = CreateFrame("Frame", nil, parent)
    resolverHost:Hide()
    editor.lootSessionSyncInlineResolverHost = resolverHost

    editor.lootSessionSyncInlinePreviewFrame = frame
    return frame
  end

  local function GetInlinePreviewState(syncStatus, candidate)
    syncStatus = type(syncStatus) == "table" and syncStatus or {}
    candidate = type(candidate) == "table" and candidate or nil
    local memberKey = TrimText(type(candidate) == "table" and candidate.memberKey or "")
    if memberKey == "" then
      return nil, nil
    end
    local detailDiff = type(syncStatus.detailDiff) == "table" and TrimText(syncStatus.detailDiff.memberKey) == memberKey and syncStatus.detailDiff or nil
    local detailConflict = type(syncStatus.detailConflict) == "table" and TrimText(syncStatus.detailConflict.memberKey) == memberKey and syncStatus.detailConflict or nil
    if type(detailDiff) ~= "table" and type(detailConflict) ~= "table" then
      return nil, nil
    end
    return detailDiff, detailConflict
  end

  local function BuildInlinePreviewScopeNote(editor)
    local scopeFrame = editor and editor.lootSessionSyncScopeFrame or nil
    local rows = type(scopeFrame) == "table" and type(scopeFrame.__rows) == "table" and scopeFrame.__rows or {}
    local previewAction = type(editor) == "table"
      and type(editor.lootSessionSelectedScopeActions) == "table"
      and type(editor.lootSessionSelectedScopeActions.preview) == "table"
      and editor.lootSessionSelectedScopeActions.preview
      or nil
    local selectedLookup = {}
    for _, subdomain in ipairs(type(previewAction) == "table" and type(previewAction.subdomains) == "table" and previewAction.subdomains or {}) do
      local key = string.lower(TrimText(subdomain))
      if key ~= "" then
        selectedLookup[key] = true
      end
    end

    local selectedRows = {}
    for _, row in ipairs(rows) do
      local key = string.lower(TrimText(type(row) == "table" and row.subdomain or ""))
      if key ~= "" and selectedLookup[key] then
        selectedRows[#selectedRows + 1] = row
      end
    end
    if #selectedRows == 0 then
      return ""
    end

    table.sort(selectedRows, function(left, right)
      return string.lower(tostring(left.label or "")) < string.lower(tostring(right.label or ""))
    end)

    if #selectedRows == 1 then
      local row = selectedRows[1]
      local transportExplain = "Snapshot means the current preview or repair uses the whole selected leaf scope."
      if row.transportKey == "patch_ready" then
        transportExplain = "Patch-ready means LidCouncil already has the nested patch details needed to use a smaller transfer now."
      elseif row.transportKey == "patch_later" then
        transportExplain = "Patch pending means this leaf can use nested patch repair later, but the current preview starts from a snapshot because the patch details are not loaded yet."
      end
      return "Selected leaf: " .. tostring(row.label or row.subdomain or "-")
        .. "\nSuggested action: " .. tostring(row.actionText or "-")
        .. " | Transport: " .. tostring(row.transportText or "-")
        .. "\n" .. transportExplain
    end

    local labels = {}
    for index, row in ipairs(selectedRows) do
      if index > 3 then
        break
      end
      labels[#labels + 1] = tostring(row.label or row.subdomain or "-")
    end
    local labelText = table.concat(labels, ", ")
    if #selectedRows > #labels then
      labelText = labelText .. " +" .. tostring(#selectedRows - #labels) .. " more"
    end
    return "Selected leaves: " .. tostring(#selectedRows) .. " (" .. labelText .. "). Preview is limited to those exact leaf scopes."
  end

  OpenProfileSyncDetailPopup = function(editor, candidate)
    local frame = EnsureProfileSyncDetailPopup(editor)
    if not frame or type(candidate) ~= "table" then
      return
    end
    local getProfileSyncStatus = ResolveOptionalApiFunction("LIDCOUNCIL_GetActiveProfileSyncStatus")
    local syncStatus = ReadSyncActionValue(
      editor,
      frame,
      "Open sync detail",
      getProfileSyncStatus,
      {},
      editor and editor.lootSessionAllSyncCandidates or nil
    )
    frame.__candidate = candidate
    if frame.title then
      frame.title:SetText("Sync Detail - " .. tostring(candidate.memberKey or "Unknown"))
    end
    RefreshProfileSyncDetailPopup(editor, frame, candidate, syncStatus)
    frame:Show()
    if frame.bodyScroll then
      frame.bodyScroll:SetVerticalScroll(0)
    end
    if frame.Raise then
      frame:Raise()
    end
  end

  local function EnsureProfileSyncReviewRows(editor, count)
    if not editor or not editor.lootSessionSyncReviewRowsFrame then
      return
    end
    editor.lootSessionSyncReviewRows = editor.lootSessionSyncReviewRows or {}
    while #(editor.lootSessionSyncReviewRows or {}) < count do
      local row = CreateFrame("Frame", nil, editor.lootSessionSyncReviewRowsFrame, "BackdropTemplate")
      ApplyFrameSkin(row)
      row:SetHeight(24)
      row:EnableMouse(true)
      row:SetScript("OnMouseUp", function(self)
        if type(OpenProfileSyncDetailPopup) == "function" then
          OpenProfileSyncDetailPopup(editor, self.__candidate)
        end
      end)

      local memberText = row:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
      memberText:SetJustifyH("LEFT")
      row.memberText = memberText

      local stateText = row:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
      stateText:SetJustifyH("LEFT")
      row.stateText = stateText

      local remoteText = row:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
      remoteText:SetJustifyH("LEFT")
      row.remoteText = remoteText

      local localText = row:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
      localText:SetJustifyH("LEFT")
      row.localText = localText

      local sessionText = row:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
      sessionText:SetJustifyH("LEFT")
      row.sessionText = sessionText

      local updatedText = row:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
      updatedText:SetJustifyH("LEFT")
      row.updatedText = updatedText

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

  local function RefreshProfileSyncReviewRows(editor, candidates)
    if not editor then
      return
    end
    candidates = type(candidates) == "table" and candidates or {}
    EnsureProfileSyncReviewRows(editor, #candidates)
    for index, row in ipairs(editor.lootSessionSyncReviewRows or {}) do
      local candidate = candidates[index]
      if candidate then
        row.__candidate = candidate
        local classR, classG, classB = GetSessionClassColor(candidate.classFile)
        row.memberText:SetText(tostring(candidate.memberKey or "-"))
        row.memberText:SetTextColor(classR, classG, classB, 1.00)
        local settingsState = GetProfileSyncDomainState(candidate, "settings")
        local permissionsState = GetProfileSyncDomainState(candidate, "permissions")
        local lootState = GetProfileSyncDomainState(candidate, "loot")
        local sessionState = GetProfileSyncDomainState(candidate, "session")
        local settingsR, settingsG, settingsB = GetProfileSyncDomainStateColor(settingsState)
        local permissionsR, permissionsG, permissionsB = GetProfileSyncDomainStateColor(permissionsState)
        local lootR, lootG, lootB = GetProfileSyncDomainStateColor(lootState)
        local sessionR, sessionG, sessionB = GetProfileSyncDomainStateColor(sessionState)
        row.stateText:SetText(GetProfileSyncDomainStateLabel(settingsState))
        row.stateText:SetTextColor(settingsR, settingsG, settingsB, 1.00)
        row.remoteText:SetText(GetProfileSyncDomainStateLabel(permissionsState))
        row.remoteText:SetTextColor(permissionsR, permissionsG, permissionsB, 1.00)
        row.localText:SetText(GetProfileSyncDomainStateLabel(lootState))
        row.localText:SetTextColor(lootR, lootG, lootB, 1.00)
        if row.sessionText then
          row.sessionText:SetText(GetProfileSyncDomainStateLabel(sessionState))
          row.sessionText:SetTextColor(sessionR, sessionG, sessionB, 1.00)
        end
        if row.updatedText then
          row.updatedText:SetText((tonumber(candidate.updatedAt) or 0) > 0 and FormatDateTime(candidate.updatedAt) or "-")
        end
        row:Show()
      else
        row.__candidate = nil
        row:Hide()
      end
    end
    editor.lootSessionSyncReviewRowsHeight = math.max(0, #candidates * 28)
  end

  local function BuildProfileSyncStatusText(syncStatus)
    syncStatus = type(syncStatus) == "table" and syncStatus or {}
    local tutorialMode = IsTutorialModeEnabled()
    if syncStatus.activeSession ~= true then
      return tutorialMode and "Shared Profile Sync: idle until a session starts." or ""
    end

    local lines = {}
    local message = TrimText(syncStatus.message)
    local counts = type(syncStatus.candidateCounts) == "table" and syncStatus.candidateCounts or {}
    local bootstrapCounts = type(syncStatus.bootstrapCounts) == "table" and syncStatus.bootstrapCounts or {}
    local sender = TrimText(syncStatus.sender)
    local mode = string.lower(TrimText(syncStatus.mode))
    local severity = string.lower(TrimText(syncStatus.severity))
    local waitingApplyCount = math.max(0, tonumber(counts.waiting_apply) or 0)
    local recentRosterEvents = type(syncStatus.recentRosterEvents) == "table" and syncStatus.recentRosterEvents or {}

    if message ~= "" then
      if tutorialMode or mode ~= "session_started" or severity ~= "info" then
        lines[#lines + 1] = "Shared Profile Sync: " .. message
      end
    elseif syncStatus.isHost then
      local newerCount = tonumber(counts.remote_newer) or 0
      local conflictCount = tonumber(counts.diverged) or 0
      local sameCount = tonumber(counts.same) or 0
      local olderCount = tonumber(counts.local_newer) or 0
      local readyCount = tonumber(bootstrapCounts.ready) or 0
      local pendingBootstrapCount = tonumber(bootstrapCounts.pending) or 0
      local reviewBootstrapCount = tonumber(bootstrapCounts.review) or 0
      if newerCount > 0 or conflictCount > 0 then
        local reviewParts = {}
        if newerCount > 0 then
          reviewParts[#reviewParts + 1] = tostring(newerCount) .. " joined copy/copies are newer"
        end
        if conflictCount > 0 then
          reviewParts[#reviewParts + 1] = tostring(conflictCount) .. " conflict(s) need review"
        end
        lines[#lines + 1] = string.format(
          "Shared Profile Sync: %d roll-ready, %d waiting bootstrap, %d need bootstrap review. %s. Roll-ready members can keep playing while history review waits.",
          readyCount,
          pendingBootstrapCount,
          reviewBootstrapCount,
          table.concat(reviewParts, " and ")
        )
      elseif pendingBootstrapCount > 0 or reviewBootstrapCount > 0 then
        lines[#lines + 1] = string.format(
          "Shared Profile Sync: %d roll-ready, %d still waiting bootstrap, and %d need bootstrap review while the remaining profile history keeps syncing.",
          readyCount,
          pendingBootstrapCount,
          reviewBootstrapCount
        )
      elseif olderCount > 0 then
        lines[#lines + 1] = string.format(
          "Shared Profile Sync: %d roll-ready, while %d joined member copy/copies are still catching up on non-bootstrap loot or session history.",
          readyCount,
          olderCount
        )
      elseif tutorialMode then
        lines[#lines + 1] = string.format(
          "Shared Profile Sync: %d roll-ready, %d joined copy/copies match and %d are older than the host copy.",
          readyCount,
          sameCount,
          olderCount
        )
      end
    elseif tutorialMode then
      lines[#lines + 1] = "Shared Profile Sync: host snapshots are compared against your local shared copy before anything is replaced."
    elseif severity == "warn" or severity == "error" or (tonumber(counts.local_newer) or 0) > 0 or (tonumber(counts.remote_newer) or 0) > 0 then
      lines[#lines + 1] = string.format(
        "Shared Profile Sync: %d remote scope(s) are newer, %d scope(s) are newer on your local copy, and %d conflict(s) are waiting on host review.",
        tonumber(counts.remote_newer) or 0,
        tonumber(counts.local_newer) or 0,
        tonumber(counts.diverged) or 0
      )
    end
    if syncStatus.isHost and waitingApplyCount > 0 then
      lines[#lines + 1] = tostring(waitingApplyCount)
        .. " member update" .. (waitingApplyCount == 1 and " was" or "s were")
        .. " received and will be applied after combat ends."
    end

    if #lines > 0 and syncStatus.isHost and (tutorialMode or severity == "warn" or severity == "error") then
      lines[#lines + 1] = "Continue below: select the member, load and choose scopes, preview them, then open Sync Detail. Host push and pull repairs are advanced actions."
    elseif #lines > 0 and not syncStatus.isHost and ((tonumber(counts.local_newer) or 0) > 0 or (tonumber(counts.remote_newer) or 0) > 0 or (tonumber(counts.diverged) or 0) > 0) then
      lines[#lines + 1] = "Wait for the session host to push repairs, preview conflicts, or pull your newer scopes. Joined-member profile sync can continue in the background while the raid is running."
    elseif #lines > 0 and sender ~= "" then
      lines[#lines + 1] = "Last shared-profile event involved " .. sender .. "."
    end

    if #lines > 0 and tonumber(syncStatus.updatedAt) and tonumber(syncStatus.updatedAt) > 0 then
      lines[#lines + 1] = "Last event: " .. FormatDateTime(syncStatus.updatedAt)
    end

    if syncStatus.isHost and #recentRosterEvents > 0 then
      local timelineEntries = {}
      for index = 1, math.min(3, #recentRosterEvents) do
        local event = recentRosterEvents[index]
        local action = string.lower(TrimText(type(event) == "table" and event.action or ""))
        local memberKey = TrimText(type(event) == "table" and event.memberKey or "")
        if memberKey ~= "" and (action == "joined" or action == "left") then
          local eventAt = math.max(0, tonumber(type(event) == "table" and event.at or 0) or 0)
          local timestamp = eventAt > 0 and type(date) == "function" and date("%H:%M", eventAt) or ""
          if timestamp == "" and eventAt > 0 then
            timestamp = FormatDateTime(eventAt)
          end
          timelineEntries[#timelineEntries + 1] = (timestamp ~= "" and (timestamp .. " ") or "")
            .. memberKey .. " " .. action
        end
      end
      if #timelineEntries > 0 then
        lines[#lines + 1] = "Roster timeline: " .. table.concat(timelineEntries, " | ")
      end
    end

    return table.concat(lines, "\n")
  end

  local function EnsureSyncProgressPanel(editor)
    if not editor then
      return nil
    end
    if editor.lootSessionSyncProgressFrame then
      return editor.lootSessionSyncProgressFrame
    end

    local parent = editor.lootSessionRightContent or editor.lootSessionRightBg or UIParent
    local frame = CreateFrame("Frame", nil, parent, "BackdropTemplate")
    ApplyFrameSkin(frame)
    if frame.SetBackdropColor then
      frame:SetBackdropColor(0.05, 0.06, 0.08, 0.96)
    end

    local title = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    title:SetJustifyH("LEFT")
    title:SetText("Background Sync Monitor")
    frame.title = title

    local stateText = frame:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    stateText:SetJustifyH("RIGHT")
    frame.stateText = stateText

    local healthSummary = frame:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    healthSummary:SetJustifyH("LEFT")
    frame.healthSummary = healthSummary

    local healthMetrics = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    healthMetrics:SetJustifyH("LEFT")
    frame.healthMetrics = healthMetrics

    frame.healthCards = {}
    for _, cardDef in ipairs({
      { key = "queue", label = "Queue" },
      { key = "traffic", label = "Traffic" },
      { key = "delivery", label = "Delivery" },
    }) do
      local card = CreateFrame("Frame", nil, frame, "BackdropTemplate")
      ApplyFrameSkin(card)
      if card.SetBackdropColor then
        card:SetBackdropColor(0.06, 0.07, 0.10, 0.94)
      end
      local label = card:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
      label:SetJustifyH("LEFT")
      label:SetText(cardDef.label)
      label:SetTextColor(0.72, 0.78, 0.88, 1.00)
      local value = card:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
      value:SetJustifyH("LEFT")
      card.label = label
      card.value = value
      frame.healthCards[cardDef.key] = card
    end

    local attentionText = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    attentionText:SetJustifyH("LEFT")
    attentionText:SetJustifyV("TOP")
    attentionText:SetSpacing(2)
    attentionText:Hide()
    frame.attentionText = attentionText

    local archivePauseBtn = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    archivePauseBtn:SetSize(132, 22)
    frame.archivePauseBtn = archivePauseBtn
    editor.lootSessionSyncArchivePauseBtn = archivePauseBtn

    local archivePauseInfoBtn = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    archivePauseInfoBtn:SetSize(22, 22)
    archivePauseInfoBtn:SetText("i")
    archivePauseInfoBtn:SetScript("OnEnter", function(self)
      if type(GameTooltip) ~= "table" then
        return
      end
      GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
      GameTooltip:ClearLines()
      GameTooltip:AddLine("Archive Sync", 1.00, 0.82, 0.28, true)
      GameTooltip:AddLine("Pausing stops only low-priority background archive transfers.", 0.92, 0.92, 0.96, true)
      GameTooltip:AddLine("Session joins, current loot, roll-ready data, important profile updates, and Live Board operations continue normally.", 0.92, 0.92, 0.96, true)
      GameTooltip:AddLine("Older Loot List history and fun-award data remain queued and resume when Archive Sync is enabled again.", 0.92, 0.92, 0.96, true)
      GameTooltip:AddLine("Leave Archive Sync enabled normally. Pause it during a raid if you want to eliminate nonessential historical traffic or diagnose congestion.", 0.78, 0.84, 1.00, true)
      GameTooltip:AddLine("The pause setting persists until you resume it.", 1.00, 0.72, 0.42, true)
      GameTooltip:Show()
    end)
    archivePauseInfoBtn:SetScript("OnLeave", function()
      if type(GameTooltip) == "table" then
        GameTooltip:Hide()
      end
    end)
    frame.archivePauseInfoBtn = archivePauseInfoBtn
    editor.lootSessionSyncArchivePauseInfoBtn = archivePauseInfoBtn
    archivePauseBtn:Hide()
    archivePauseInfoBtn:Hide()

    local refreshCadenceDropdown = type(deps.CreateCustomDropdownControl) == "function"
      and deps.CreateCustomDropdownControl(editor, frame, {
        width = 116,
        buttonHeight = 22,
        text = "Refresh: Manual",
        maxVisibleEntries = 6,
      })
      or nil
    frame.refreshCadenceDropdown = refreshCadenceDropdown
    editor.lootSessionSyncRefreshCadenceDropdown = refreshCadenceDropdown

    local refreshNowBtn = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    refreshNowBtn:SetSize(82, 22)
    refreshNowBtn:SetText("Refresh Now")
    refreshNowBtn:SetScript("OnClick", function()
      RefreshSyncManagementSection(editor)
    end)
    frame.refreshNowBtn = refreshNowBtn
    editor.lootSessionSyncRefreshNowBtn = refreshNowBtn

    function frame:SetRefreshCadence(seconds)
      seconds = math.max(0, math.min(5, math.floor(tonumber(seconds) or 0)))
      local root = type(RootDB) == "function" and RootDB() or nil
      if type(root) == "table" then
        root.ui = type(root.ui) == "table" and root.ui or {}
        root.ui.syncManagementRefreshSeconds = seconds
      end
      self.__syncRefreshSeconds = seconds
      editor.__lootSessionSyncProgressRefreshDueAt = nil
      RefreshSyncManagementSection(editor)
    end

    function frame:UpdateRefreshCadence(isHost)
      local root = type(RootDB) == "function" and RootDB() or nil
      local ui = type(root) == "table" and type(root.ui) == "table" and root.ui or nil
      local stored = type(ui) == "table" and tonumber(ui.syncManagementRefreshSeconds) or nil
      local seconds = stored ~= nil
        and math.max(0, math.min(5, math.floor(stored)))
        or (isHost == true and 1 or 0)
      self.__syncRefreshSeconds = seconds
      if not self.refreshCadenceDropdown then
        return
      end
      self.refreshCadenceDropdown:SetSelectedValue(seconds)
      self.refreshCadenceDropdown:SetText(seconds > 0 and ("Refresh: " .. tostring(seconds) .. "s") or "Refresh: Manual")
      self.refreshCadenceDropdown:SetMenuBuilder(function(dropdown)
        local entries = {}
        for value = 0, 5 do
          local cadenceValue = value
          local label = cadenceValue > 0 and (tostring(cadenceValue) .. (cadenceValue == 1 and " second" or " seconds")) or "Manual"
          entries[#entries + 1] = {
            text = label,
            value = cadenceValue,
            checked = cadenceValue == self.__syncRefreshSeconds,
            func = function()
              dropdown:SetSelectedValue(cadenceValue)
              self:SetRefreshCadence(cadenceValue)
            end,
          }
        end
        return {
          width = math.max(116, tonumber(dropdown.dropdownWidth) or 116),
          entries = entries,
        }
      end)
    end

    local copyPerformanceBtn = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    copyPerformanceBtn:SetSize(170, 22)
    copyPerformanceBtn:SetText("Copy Performance Report")
    copyPerformanceBtn:SetScript("OnClick", function()
      local reportText = tostring(frame.__syncPerformanceReportText or "")
      if reportText == "" then
        return
      end
      local showCopyTextWindow = ResolveOptionalApiFunction("LIDCOUNCIL_ShowCopyTextWindow")
      if type(showCopyTextWindow) == "function" then
        showCopyTextWindow("Sync Performance Report", reportText)
      end
    end)
    copyPerformanceBtn:Hide()
    frame.copyPerformanceBtn = copyPerformanceBtn
    editor.lootSessionSyncCopyPerformanceBtn = copyPerformanceBtn

    frame.rows = {}
    frame.rowsByKey = {}
    local rowDefs = {
      { key = "queue", label = "Queue" },
      { key = "next", label = "Next Msg" },
      { key = "pending", label = "Pending Mix" },
      { key = "throughput", label = "Throughput" },
      { key = "localCpu", label = "Local CPU Work" },
      { key = "inviteTransport", label = "Invite Transport" },
      { key = "joinWorker", label = "JOIN Worker" },
      { key = "lanes", label = "Outbound Lanes" },
      { key = "trafficTargets", label = "Traffic Targets" },
      { key = "inbound", label = "Inbound" },
      { key = "inboundSnapshot", label = "Inbound Snapshot" },
      { key = "inboundSnapshotRejects", label = "Snapshot Rejects" },
      { key = "delta", label = "Delta ACKs" },
      { key = "liveCapacity", label = "Live Capacity" },
      { key = "boardSyncTargets", label = "BSYNC Targets" },
      { key = "capacityWarning", label = "Capacity Warning" },
      { key = "criticalReceipts", label = "Critical Receipts" },
      { key = "receiptDetail", label = "Receipt Detail" },
      { key = "boardReceiver", label = "Board Receive" },
      { key = "itemReceiver", label = "Item Delivery" },
      { key = "popupGate", label = "Roll Popup" },
      { key = "ackRecovery", label = "ACK Recovery" },
      { key = "timerFallbacks", label = "Timer Fallbacks" },
      { key = "startupHealth", label = "Startup Health" },
      { key = "results", label = "Results" },
      { key = "lastDiagnostic", label = "Last Diagnostic" },
      { key = "targets", label = "Profile Targets" },
      { key = "transfer1", label = "Transfer 1" },
      { key = "transfer2", label = "Transfer 2" },
      { key = "transfer3", label = "Transfer 3" },
      { key = "deliveryEvents", label = "Recent Sync Log" },
      { key = "notes", label = "Notes" },
    }
    for _, rowDef in ipairs(rowDefs) do
      local label = frame:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
      label:SetJustifyH("LEFT")
      label:SetText(tostring(rowDef.label or ""))

      local value = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
      value:SetJustifyH("LEFT")
      value:SetJustifyV("TOP")

      local row = {
        key = rowDef.key,
        label = label,
        value = value,
        visible = true,
      }
      frame.rows[#frame.rows + 1] = row
      frame.rowsByKey[rowDef.key] = row
    end

    editor.lootSessionSyncProgressFrame = frame
    return frame
  end

  local function GetSyncProgressStateColor(queueStatus)
    queueStatus = type(queueStatus) == "table" and queueStatus or {}
    local pending = math.max(0, tonumber(queueStatus.pending) or 0)
    local diagnosticUnresolved = queueStatus.outboundIssueUnresolved == true
      or TrimText(queueStatus.outboundDiagnosticState) == "unresolved"
    local prefixRegistrationActiveFailure = queueStatus.prefixRegistrationActiveFailure == true
      and queueStatus.prefixRegistered ~= true
    local optionalApiFailureCount = math.max(0, tonumber(queueStatus.optionalApiFailureCount) or 0)
    local startupHealthStatus = type(queueStatus.startupHealthStatus) == "table"
      and queueStatus.startupHealthStatus
      or {}
    local archivePaused = queueStatus.archiveSyncPaused == true
    local busy = queueStatus.busy == true or queueStatus.running == true or pending > 0

    if startupHealthStatus.ran == true and startupHealthStatus.ready ~= true then
      return "Health Error", 1.00, 0.55, 0.44, 1.00
    elseif startupHealthStatus.ran == true and math.max(0, tonumber(startupHealthStatus.warningCount) or 0) > 0 then
      return "Health Warning", 1.00, 0.78, 0.62, 1.00
    elseif archivePaused and not busy then
      return "Archive Paused", 0.80, 0.68, 1.00, 1.00
    elseif busy and queueStatus.chatLockdownActive == true then
      return "WoW Paused", 1.00, 0.82, 0.32, 1.00
    elseif busy and queueStatus.currentFailureRetryActive == true then
      return "Retrying", 1.00, 0.62, 0.28, 1.00
    elseif busy and queueStatus.currentThrottleActive == true then
      return "Throttled", 1.00, 0.82, 0.32, 1.00
    elseif prefixRegistrationActiveFailure then
      return "API Error", 1.00, 0.55, 0.44, 1.00
    elseif optionalApiFailureCount > 0 then
      return "API Warning", 1.00, 0.78, 0.62, 1.00
    elseif diagnosticUnresolved then
      return "Delivery Warning", 1.00, 0.82, 0.32, 1.00
    elseif archivePaused then
      return "Archive Paused", 0.80, 0.68, 1.00, 1.00
    elseif busy then
      return "Running", 0.38, 0.72, 1.00, 1.00
    end
    return "Idle", 0.30, 0.90, 0.36, 1.00
  end

  local function BuildSyncProgressHealthSummary(model)
    model = type(model) == "table" and model or {}
    local activeTraffic = model.queueActive == true
      or (tonumber(model.sendRate) or 0) > 0
      or (tonumber(model.inboundRate) or 0) > 0
      or (tonumber(model.pendingIncomingTransfers) or 0) > 0
    local hardBlock = (tonumber(model.startupHealthErrors) or 0) > 0
      or (tonumber(model.missingProtocolHandlerCount) or 0) > 0
      or (tonumber(model.protocolOwnerMismatchCount) or 0) > 0
      or (tonumber(model.uncontractedProtocolHandlerCount) or 0) > 0
      or model.prefixRegistrationActiveFailure == true
    local criticalReceiptWaiting = math.max(0, tonumber(model.criticalReceiptWaiting) or 0)
    local criticalReceiptUnconfirmed = math.max(0, tonumber(model.criticalReceiptUnconfirmed) or 0)
    local capacityBlocked = model.capacityBlocked == true
    local unresolvedDeliveryIssue = model.diagnosticUnresolved == true
    local chatLockdownActive = model.chatLockdownActive == true
    local label = "Healthy"
    local color = { 0.30, 0.90, 0.36, 1.00 }
    local message = "No action required."
    if hardBlock then
      label = "Blocked"
      color = { 1.00, 0.55, 0.44, 1.00 }
      message = "Communication setup requires attention."
    elseif capacityBlocked then
      label = "Delayed"
      color = { 1.00, 0.82, 0.32, 1.00 }
      message = "Live Board delivery is waiting for safe queue headroom."
    elseif chatLockdownActive then
      label = "Delayed"
      color = { 1.00, 0.82, 0.32, 1.00 }
      message = "WoW temporarily paused addon messaging; queued data is retained."
    elseif model.incomingSnapshotHealth == "stalled" and (tonumber(model.pendingIncomingTransfers) or 0) > 0 then
      label = "Delayed"
      color = { 1.00, 0.82, 0.32, 1.00 }
      message = "An inbound profile snapshot is waiting for data."
    elseif criticalReceiptUnconfirmed > 0 then
      label = "Delayed"
      color = { 1.00, 0.82, 0.32, 1.00 }
      message = "A critical board delivery will reconcile during the next board sync."
    elseif unresolvedDeliveryIssue and activeTraffic then
      label = "Delayed"
      color = { 1.00, 0.82, 0.32, 1.00 }
      message = "Delivery is recovering after an outbound message issue."
    elseif activeTraffic then
      label = "Working"
      color = { 0.38, 0.72, 1.00, 1.00 }
      message = criticalReceiptWaiting > 0
        and "Data is moving; a critical board action is awaiting confirmation."
        or "Data is currently moving."
    elseif model.archivePaused == true then
      label = "Paused"
      color = { 0.80, 0.68, 1.00, 1.00 }
      message = "Archive transfers are paused; live traffic remains available."
    elseif model.diagnosticResolved == true then
      label = "Healthy"
      color = { 0.42, 1.00, 0.52, 1.00 }
      message = "No action required; the latest delivery fallback recovered."
    elseif unresolvedDeliveryIssue then
      label = "Delayed"
      color = { 1.00, 0.82, 0.32, 1.00 }
      message = "The latest outbound delivery issue remains unresolved."
    elseif (tonumber(model.startupHealthWarnings) or 0) > 0
      or (tonumber(model.optionalApiFailureCount) or 0) > 0
    then
      label = "Delayed"
      color = { 1.00, 0.82, 0.32, 1.00 }
      message = "Startup or optional API diagnostics need review."
    end

    local queueMetric = model.queueActive == true and (tostring(math.max(0, tonumber(model.pending) or 0)) .. " queued") or "Clear"
    if model.archivePaused == true and model.queueActive ~= true then
      queueMetric = "Paused"
    end
    local trafficMetric = "Idle"
    if chatLockdownActive then
      trafficMetric = "Paused by WoW"
    elseif (tonumber(model.sendRate) or 0) > 0 and (tonumber(model.inboundRate) or 0) > 0 then
      trafficMetric = "Two-way"
    elseif (tonumber(model.sendRate) or 0) > 0 then
      trafficMetric = "Sending"
    elseif (tonumber(model.inboundRate) or 0) > 0 or (tonumber(model.pendingIncomingTransfers) or 0) > 0 then
      trafficMetric = "Receiving"
    elseif activeTraffic then
      trafficMetric = "Processing"
    end
    local deliveryMetric = "Healthy"
    if chatLockdownActive then
      deliveryMetric = "Chat lockdown"
    elseif capacityBlocked then
      deliveryMetric = "Capacity waiting"
    elseif criticalReceiptUnconfirmed > 0 then
      deliveryMetric = tostring(criticalReceiptUnconfirmed) .. " unconfirmed"
    elseif criticalReceiptWaiting > 0 then
      deliveryMetric = tostring(criticalReceiptWaiting) .. " awaiting"
    elseif model.diagnosticResolved == true then
      deliveryMetric = "Recovered"
    elseif unresolvedDeliveryIssue and model.lastOutboundIssueCategory == "payload_rejected" then
      deliveryMetric = "Fallback pending"
    elseif unresolvedDeliveryIssue and model.lastOutboundIssueCategory == "api_failure" then
      deliveryMetric = "API blocked"
    elseif unresolvedDeliveryIssue and model.lastOutboundIssueCategory == "throttle_exhausted" then
      deliveryMetric = "Retry exhausted"
    elseif unresolvedDeliveryIssue then
      deliveryMetric = "Needs attention"
    end

    local attention = ""
    local attentionColor = color
    local diagnosticKind = TrimText(model.latestDiagnosticKind)
    if hardBlock then
      attention = "Attention Required: Communication setup is invalid. Review Startup Health before continuing the session."
    elseif chatLockdownActive then
      attention = "WoW temporarily restricted addon messages. LidCouncil retained the queue without spending retry budgets and resumes automatically when messaging is available."
    elseif capacityBlocked then
      attention = TrimText(model.capacityWarning) ~= "" and TrimText(model.capacityWarning)
        or "Attention Required: Live Board capacity protection stopped new BSYNC work before queue overflow. Delivery resumes automatically when headroom recovers."
    elseif model.incomingSnapshotHealth == "stalled" and (tonumber(model.pendingIncomingTransfers) or 0) > 0 then
      attention = "Attention Required: Inbound Snapshot is stalled. Wait for the sender or inspect the Snapshot Rejects row."
    elseif criticalReceiptUnconfirmed > 0 then
      attention = "Attention Required: A critical Live Board receipt was not confirmed. Review Critical Receipts; the next board sync will reconcile it."
    elseif diagnosticKind ~= "" then
      local affectedArea = model.lastOutboundIssueCategory == "payload_rejected" and "outbound message size"
        or (model.lastOutboundIssueCategory == "throttle_exhausted" and "outbound retry budget")
        or (model.lastOutboundIssueCategory == "api_failure" and "outbound communication API")
        or "outbound delivery"
      local diagnosticLabel = diagnosticKind
      if (tonumber(model.latestDiagnosticBytes) or 0) > 0 then
        diagnosticLabel = diagnosticLabel .. " (" .. tostring(math.max(0, tonumber(model.latestDiagnosticBytes) or 0)) .. " bytes)"
      end
      if unresolvedDeliveryIssue then
        attention = "Attention Required: " .. diagnosticLabel .. ". Area: " .. affectedArea
          .. ". Keep the monitor open while LidCouncil retries with a safe packet."
      end
    end

    local queueColor = model.archivePaused == true and { 0.70, 0.74, 0.82, 1.00 }
      or (model.queueActive == true and { 0.38, 0.72, 1.00, 1.00 } or { 0.30, 0.90, 0.36, 1.00 })
    local trafficColor = chatLockdownActive and { 1.00, 0.82, 0.32, 1.00 }
      or (activeTraffic and { 0.38, 0.72, 1.00, 1.00 }
      or { 0.72, 0.78, 0.86, 1.00 }
      )
    local deliveryColor = (chatLockdownActive or capacityBlocked) and { 1.00, 0.82, 0.32, 1.00 }
      or (model.diagnosticResolved == true and { 0.42, 1.00, 0.52, 1.00 }
      or (criticalReceiptUnconfirmed > 0 and { 1.00, 0.82, 0.32, 1.00 }
        or (criticalReceiptWaiting > 0 and { 0.38, 0.72, 1.00, 1.00 }
          or (unresolvedDeliveryIssue and { 1.00, 0.82, 0.32, 1.00 }
            or { 0.30, 0.90, 0.36, 1.00 }))))

    return {
      label = label,
      color = color,
      summary = "Sync Health: " .. label .. " - " .. message,
      metrics = "Queue: " .. queueMetric .. "  |  Traffic: " .. trafficMetric .. "  |  Delivery: " .. deliveryMetric,
      attention = attention,
      attentionColor = attentionColor,
      cards = {
        queue = { value = queueMetric, color = queueColor },
        traffic = { value = trafficMetric, color = trafficColor },
        delivery = { value = deliveryMetric, color = deliveryColor },
      },
    }
  end

  local function SetSyncProgressRow(frame, key, valueText, color, visible)
    local row = type(frame) == "table" and type(frame.rowsByKey) == "table" and frame.rowsByKey[key] or nil
    if not row then
      return
    end

    row.visible = visible ~= false
    row.value:SetText(tostring(valueText or "-"))
    row.label:SetTextColor(0.72, 0.78, 0.88, 1.00)
    local resolvedColor = type(color) == "table" and color or { 0.86, 0.88, 0.94, 1.00 }
    row.value:SetTextColor(
      tonumber(resolvedColor[1]) or 0.86,
      tonumber(resolvedColor[2]) or 0.88,
      tonumber(resolvedColor[3]) or 0.94,
      tonumber(resolvedColor[4]) or 1.00
    )
  end

  local function SetSyncProgressHealthCard(frame, key, model)
    local card = type(frame) == "table" and type(frame.healthCards) == "table" and frame.healthCards[key] or nil
    if type(card) ~= "table" then
      return
    end
    model = type(model) == "table" and model or {}
    local color = type(model.color) == "table" and model.color or { 0.82, 0.84, 0.92, 1.00 }
    card.value:SetText(TrimText(model.value) ~= "" and TrimText(model.value) or "-")
    card.value:SetTextColor(color[1] or 0.82, color[2] or 0.84, color[3] or 0.92, color[4] or 1.00)
    if card.SetBackdropBorderColor then
      card:SetBackdropBorderColor((color[1] or 0.82) * 0.72, (color[2] or 0.84) * 0.72, (color[3] or 0.92) * 0.72, 0.88)
    end
  end

  local function FormatSyncTransferReason(reason)
    local resolvedReason = TrimText(reason)
    if resolvedReason == "missing_member_bootstrap" then
      return "Bootstrap"
    elseif resolvedReason == "missing_member_current_session_sync" then
      return "Current Session"
    elseif resolvedReason == "missing_member_loot_bootstrap" then
      return "Loot Bootstrap"
    elseif resolvedReason == "missing_member_fun_awards_background"
      or resolvedReason == "missing_member_fun_awards_stats_background_deferred"
    then
      return "Fun Awards"
    elseif resolvedReason == "missing_member_loot_background"
      or resolvedReason == "missing_member_loot_archive_background_deferred"
    then
      return "Loot Archive"
    elseif resolvedReason == "missing_member_session_archive_background_deferred" then
      return "Session Archive"
    elseif resolvedReason == "join_repair_precise" or resolvedReason == "join_repair_targeted" or resolvedReason == "join_repair" then
      return "Join Repair"
    elseif resolvedReason == "join_repair_precise_deferred" or resolvedReason == "join_repair_targeted_deferred" or resolvedReason == "join_repair_deferred" then
      return "Deferred Repair"
    elseif resolvedReason == "host_push_repair" or resolvedReason == "host_push_full" then
      return "Host Repair"
    elseif resolvedReason == "checkpoint" or resolvedReason == "session_checkpoint" then
      return "Live Checkpoint"
    elseif resolvedReason == "manual_ledger_checkpoint" then
      return "Loot Row Checkpoint"
    elseif resolvedReason == "member_meta_checkpoint" then
      return "Member Meta Checkpoint"
    elseif resolvedReason == "member_delete_checkpoint" then
      return "Character Delete Checkpoint"
    end
    return resolvedReason
  end

  local function FormatSyncTransferLane(transfer)
    transfer = type(transfer) == "table" and transfer or {}
    local lane = string.lower(TrimText(transfer.lane))
    if lane == "live" then
      return "Live"
    elseif lane == "stats" then
      return "Stats"
    elseif lane == "archive" then
      return "Archive"
    end
    local mode = TrimText(transfer.mode)
    if mode == "BACKGROUND" then
      return "Background"
    elseif mode == "LIVE" then
      return "Live"
    end
    return mode ~= "" and mode or "Standard"
  end

  local function FormatSyncTransferKindLabel(transfer)
    local transferKind = TrimText(type(transfer) == "table" and transfer.transferKind or "")
    if transferKind == "PATCHES" or transferKind == "ROWPATCHES" then
      return "Patch"
    elseif transferKind == "SUBDOMAINS" then
      return "Scoped"
    elseif transferKind == "DOMAINS" then
      return "Domain"
    elseif transferKind == "FULL" then
      return "Full"
    end
    return ""
  end

  local function FormatSyncQueueKindLabel(kind)
    local resolvedKind = TrimText(kind)
    if resolvedKind == "PDELTA" then
      return "Live Delta"
    elseif resolvedKind == "PDELTA_REQ" then
      return "Delta Request"
    elseif resolvedKind == "PDELTA_ACK" then
      return "Delta ACK"
    elseif resolvedKind == "PDELTA_NACK" then
      return "Delta Retry"
    elseif resolvedKind == "PSTATE" or resolvedKind == "PSTATE_PART" then
      return "Profile State"
    elseif resolvedKind == "PSUB_REQ" then
      return "Detail Request"
    elseif resolvedKind == "PSUB_STATE" then
      return "Detail State"
    elseif resolvedKind == "PSUBPATCH_REQ" then
      return "Patch Manifest Req"
    elseif resolvedKind == "PSUBPATCH_STATE" then
      return "Patch Manifest"
    elseif resolvedKind == "PSYNC_START" or resolvedKind == "PSYNC_CHUNK" or resolvedKind == "PSYNC_END" then
      return "Profile Snapshot"
    end
    return resolvedKind ~= "" and resolvedKind or "Queued Message"
  end

  local function BuildSyncQueuePreviewText(nextItem)
    nextItem = type(nextItem) == "table" and nextItem or {}
    local kind = TrimText(nextItem.kind)
    if kind == "" then
      return ""
    end
    local parts = {}
    local priority = math.max(0, tonumber(nextItem.priority) or 0)
    local kindLabel = FormatSyncQueueKindLabel(kind)
    if priority > 0 then
      parts[#parts + 1] = "P" .. tostring(priority) .. " " .. kindLabel
    else
      parts[#parts + 1] = kindLabel
    end
    local summary = TrimText(nextItem.summary)
    if summary ~= "" then
      parts[#parts + 1] = summary
    end
    local profileName = TrimText(nextItem.profileName)
    if profileName ~= "" then
      parts[#parts + 1] = profileName
    end
    if nextItem.archiveYieldDeferred == true then
      parts[#parts + 1] = "yielded for live/control traffic"
    end
    return table.concat(parts, " | ")
  end

  local function EnsurePushScopeHelp(editor)
    if not editor then
      return nil
    end
    if editor.lootSessionSyncPushHelp then
      return editor.lootSessionSyncPushHelp
    end
    local parent = editor.lootSessionRightContent or editor.lootSessionRightBg or UIParent
    local text = parent:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    text:SetJustifyH("LEFT")
    text:SetJustifyV("TOP")
    text:SetSpacing(2)
    editor.lootSessionSyncPushHelp = text
    return text
  end

  local function RefreshCriticalReceiptRows(frame, receiptStatus)
    local liveRuntimeDiagnostics = type(receiptStatus) == "table" and receiptStatus or {}
    local criticalReceipts = type(liveRuntimeDiagnostics.criticalReceipts) == "table"
      and liveRuntimeDiagnostics.criticalReceipts
      or {}
    local waiting = math.max(0, tonumber(criticalReceipts.waiting) or 0)
    local unconfirmed = math.max(0, tonumber(criticalReceipts.unconfirmed) or 0)
    local summaryParts = {}
    if waiting > 0 then
      summaryParts[#summaryParts + 1] = tostring(waiting) .. " awaiting confirmation"
    end
    if unconfirmed > 0 then
      summaryParts[#summaryParts + 1] = tostring(unconfirmed) .. " unconfirmed; board sync will reconcile"
    end
    local lastConfirmed = type(criticalReceipts.lastConfirmed) == "table" and criticalReceipts.lastConfirmed or nil
    if type(lastConfirmed) == "table" then
      local kind = TrimText(lastConfirmed.kind)
      local target = TrimText(lastConfirmed.target)
      if kind ~= "" then
        summaryParts[#summaryParts + 1] = "Last confirmed: " .. kind
          .. (target ~= "" and (" -> " .. target) or "")
      end
    end
    if #summaryParts == 0 and TrimText(liveRuntimeDiagnostics.activeSessionId) ~= "" then
      summaryParts[#summaryParts + 1] = "No critical Live Board receipts are waiting"
    end
    local summaryText = table.concat(summaryParts, " | ")
    local summaryColor = unconfirmed > 0 and { 1.00, 0.82, 0.32, 1.00 }
      or (waiting > 0 and { 0.38, 0.72, 1.00, 1.00 } or { 0.42, 1.00, 0.52, 1.00 })
    SetSyncProgressRow(frame, "criticalReceipts", summaryText, summaryColor, summaryText ~= "")

    local detailLines = {}
    for index, receipt in ipairs(type(criticalReceipts.details) == "table" and criticalReceipts.details or {}) do
      if index > 3 or type(receipt) ~= "table" then
        break
      end
      local kind = TrimText(receipt.kind)
      local target = TrimText(receipt.target)
      local state = string.lower(TrimText(receipt.state))
      local detail = (kind ~= "" and kind or "Live Board action")
        .. (target ~= "" and (" -> " .. target) or "")
        .. " | " .. (state == "unconfirmed" and "unconfirmed; board sync will reconcile" or "awaiting receipt")
      local attempts = math.max(0, tonumber(receipt.attempts) or 0)
      if attempts > 0 then
        detail = detail .. " | delivery try " .. tostring(attempts) .. "/4"
      end
      local itemKey = TrimText(receipt.itemKey)
      if itemKey ~= "" then
        detail = detail .. " | " .. string.sub(itemKey, 1, 64)
      end
      detailLines[#detailLines + 1] = detail
    end
    SetSyncProgressRow(
      frame,
      "receiptDetail",
      table.concat(detailLines, "\n"),
      unconfirmed > 0 and { 1.00, 0.82, 0.32, 1.00 } or { 0.76, 0.84, 1.00, 1.00 },
      #detailLines > 0
    )

    local activeSessionId = TrimText(liveRuntimeDiagnostics.activeSessionId)
    local receiver = type(liveRuntimeDiagnostics.boardSyncReceiver) == "table"
      and liveRuntimeDiagnostics.boardSyncReceiver
      or {}
    local receiverMatches = activeSessionId ~= ""
      and activeSessionId == TrimText(receiver.sessionId)
    local receiverState = string.lower(TrimText(receiver.state))
    local receiverText = ""
    local receiverColor = { 0.68, 0.74, 0.84, 1.00 }
    if activeSessionId ~= "" and not receiverMatches and liveRuntimeDiagnostics.isSessionHost ~= true then
      receiverText = "No Test Raid Items board transaction received in this session yet"
    elseif receiverMatches then
      local counts = tostring(math.max(0, tonumber(receiver.receivedItems) or 0))
        .. "/" .. tostring(math.max(0, tonumber(receiver.expectedItems) or 0)) .. " items | "
        .. tostring(math.max(0, tonumber(receiver.receivedSelections) or 0))
        .. "/" .. tostring(math.max(0, tonumber(receiver.expectedSelections) or 0)) .. " choices | "
        .. tostring(math.max(0, tonumber(receiver.receivedVotes) or 0))
        .. "/" .. tostring(math.max(0, tonumber(receiver.expectedVotes) or 0)) .. " votes"
      local sender = TrimText(receiver.sender)
      if receiverState == "complete" or receiverState == "duplicate_complete" then
        receiverText = "Complete" .. (sender ~= "" and (" from " .. sender) or "") .. " | " .. counts
          .. " | receipt " .. (receiver.ackSent == true and "sent" or "FAILED")
        receiverColor = receiver.ackSent == true and { 0.42, 1.00, 0.52, 1.00 } or { 1.00, 0.36, 0.30, 1.00 }
      elseif receiverState == "incomplete" then
        receiverText = "Incomplete | " .. counts .. " | missing "
          .. tostring(math.max(0, tonumber(receiver.missingCount) or 0)) .. " row(s) | repair requested"
        receiverColor = { 1.00, 0.82, 0.32, 1.00 }
      elseif receiverState == "checksum_mismatch" then
        receiverText = "Checksum mismatch | " .. counts .. " | rebuild requested"
        receiverColor = { 1.00, 0.36, 0.30, 1.00 }
      elseif receiverState == "rejected" then
        receiverText = "Rejected | " .. (TrimText(receiver.reason) ~= "" and TrimText(receiver.reason) or "unknown reason")
        receiverColor = { 1.00, 0.36, 0.30, 1.00 }
      else
        receiverText = (receiverState == "start_received" and "Start received" or "Receiving")
          .. (sender ~= "" and (" from " .. sender) or "") .. " | " .. counts
        receiverColor = { 0.38, 0.72, 1.00, 1.00 }
      end
    end
    SetSyncProgressRow(frame, "boardReceiver", receiverText, receiverColor, receiverText ~= "")

    local itemReceiver = type(liveRuntimeDiagnostics.itemOpenReceiver) == "table"
      and liveRuntimeDiagnostics.itemOpenReceiver
      or {}
    local transportTest = type(liveRuntimeDiagnostics.liveTransportTest) == "table"
      and liveRuntimeDiagnostics.liveTransportTest
      or {}
    local itemDispatch = type(liveRuntimeDiagnostics.itemOpenDispatch) == "table"
      and liveRuntimeDiagnostics.itemOpenDispatch
      or {}
    local itemReceiverMatches = activeSessionId ~= ""
      and activeSessionId == TrimText(itemReceiver.sessionId)
    local transportTestMatches = activeSessionId ~= ""
      and activeSessionId == TrimText(transportTest.sessionId)
    local itemDispatchMatches = activeSessionId ~= ""
      and activeSessionId == TrimText(itemDispatch.sessionId)
    local itemReceiverText = ""
    local itemReceiverColor = { 0.68, 0.74, 0.84, 1.00 }
    if liveRuntimeDiagnostics.isSessionHost == true and itemDispatchMatches then
      itemReceiverText = (transportTestMatches and TrimText(transportTest.itemKey) == TrimText(itemDispatch.itemKey)
          and "Test ITEM_OPEN" or "Live ITEM_OPEN")
        .. " | receipts " .. tostring(math.max(0, tonumber(itemDispatch.acknowledgedCount) or 0))
        .. "/" .. tostring(math.max(0, tonumber(itemDispatch.expectedCount) or 0))
        .. " | pending " .. tostring(math.max(0, tonumber(itemDispatch.pendingReceiptCount) or 0))
        .. " | failed " .. tostring(math.max(0, tonumber(itemDispatch.failedTargetCount) or 0))
      local targetDetails = {}
      for _, target in pairs(type(itemDispatch.targets) == "table" and itemDispatch.targets or {}) do
        local targetState = string.lower(TrimText(type(target) == "table" and target.state or "pending"))
        targetDetails[#targetDetails + 1] = TrimText(target.targetKey) .. "="
          .. (targetState == "acknowledged" and "ACK" or targetState)
      end
      table.sort(targetDetails)
      if #targetDetails > 0 then
        itemReceiverText = itemReceiverText .. " | " .. table.concat(targetDetails, ", ")
      end
      itemReceiverColor = math.max(0, tonumber(itemDispatch.failedTargetCount) or 0) > 0
        and { 1.00, 0.36, 0.30, 1.00 }
        or (math.max(0, tonumber(itemDispatch.pendingReceiptCount) or 0) > 0
          and { 1.00, 0.82, 0.32, 1.00 }
          or { 0.42, 1.00, 0.52, 1.00 })
    elseif liveRuntimeDiagnostics.isSessionHost == true and transportTestMatches then
      itemReceiverText = "ITEM_OPEN dispatch failed | "
        .. (TrimText(transportTest.code) ~= "" and TrimText(transportTest.code) or "unknown reason")
      itemReceiverColor = { 1.00, 0.36, 0.30, 1.00 }
    elseif itemReceiverMatches then
      itemReceiverText = "Admitted from " .. (TrimText(itemReceiver.sender) ~= "" and TrimText(itemReceiver.sender) or "session host")
        .. (itemReceiver.simulationOnly == true and " | simulation-only" or " | live item")
        .. " | choice " .. (itemReceiver.choiceQueued == true and "queued" or "not queued")
        .. " | receipt " .. (itemReceiver.receiptSent == true and "sent" or "FAILED")
        .. " | popup " .. (TrimText(itemReceiver.popupState) ~= "" and TrimText(itemReceiver.popupState) or "not recorded")
      if itemReceiver.choiceQueued ~= true and TrimText(itemReceiver.choiceQueueReason) ~= "" then
        itemReceiverText = itemReceiverText .. " | queue gate " .. TrimText(itemReceiver.choiceQueueReason)
      end
      if TrimText(itemReceiver.popupReason) ~= "" then
        itemReceiverText = itemReceiverText .. " (" .. TrimText(itemReceiver.popupReason) .. ")"
      end
      itemReceiverColor = itemReceiver.choiceQueued == true
        and { 0.42, 1.00, 0.52, 1.00 }
        or { 1.00, 0.82, 0.32, 1.00 }
    end
    SetSyncProgressRow(frame, "itemReceiver", itemReceiverText, itemReceiverColor, itemReceiverText ~= "")

    local popup = type(liveRuntimeDiagnostics.choicePopupState) == "table"
      and liveRuntimeDiagnostics.choicePopupState
      or {}
    local popupMatches = activeSessionId ~= "" and activeSessionId == TrimText(popup.sessionId)
    local popupState = string.lower(TrimText(popup.state))
    local popupReason = TrimText(popup.reason)
    local popupText = ""
    local popupColor = { 0.68, 0.74, 0.84, 1.00 }
    if receiverMatches and not popupMatches then
      popupState = string.lower(TrimText(receiver.popupState))
      popupReason = TrimText(receiver.popupReason)
    end
    if popupState == "opened" then
      popupText = "Opened | " .. tostring(math.max(0, tonumber(popup.queueCount or receiver.popupQueueCount) or 0))
        .. " pending choice(s)"
      popupColor = { 0.42, 1.00, 0.52, 1.00 }
    elseif popupState == "deferred" then
      popupText = "Deferred until combat ends | board data and receipt already committed"
      popupColor = { 1.00, 0.82, 0.32, 1.00 }
    elseif popupState == "blocked" then
      popupText = "Not opened | " .. (popupReason ~= "" and popupReason or "unknown popup gate")
      popupColor = { 1.00, 0.36, 0.30, 1.00 }
    elseif receiverMatches and (receiverState == "complete" or receiverState == "duplicate_complete") then
      popupText = "Board complete, but no popup decision was recorded"
      popupColor = { 1.00, 0.82, 0.32, 1.00 }
    end
    SetSyncProgressRow(frame, "popupGate", popupText, popupColor, popupText ~= "")
    return { waiting = waiting, unconfirmed = unconfirmed }
  end

  local function RefreshLiveCapacityRows(frame, queueStatus, liveRuntimeDiagnostics, receiptState)
    queueStatus = type(queueStatus) == "table" and queueStatus or {}
    liveRuntimeDiagnostics = type(liveRuntimeDiagnostics) == "table" and liveRuntimeDiagnostics or {}
    receiptState = type(receiptState) == "table" and receiptState or {}

    local activeSessionId = TrimText(liveRuntimeDiagnostics.activeSessionId)
    local admission = type(liveRuntimeDiagnostics.boardSyncAdmissionPlan) == "table"
      and liveRuntimeDiagnostics.boardSyncAdmissionPlan or {}
    local staged = type(liveRuntimeDiagnostics.boardSyncStagedDispatch) == "table"
      and liveRuntimeDiagnostics.boardSyncStagedDispatch or {}
    local admissionMatches = activeSessionId ~= "" and TrimText(admission.sessionId) == activeSessionId
    local stagedMatches = activeSessionId ~= "" and TrimText(staged.sessionId) == activeSessionId
    if not admissionMatches then
      admission = {}
    end
    if not stagedMatches then
      staged = {}
    end

    local pending = math.max(0, tonumber(queueStatus.pending) or 0)
    local maxQueueDepth = math.max(1, tonumber(queueStatus.maxQueueDepth) or 6000)
    local queueHeadroom = math.max(0, maxQueueDepth - pending)
    local requiredLiveHeadroom = math.max(0, tonumber(admission.requiredLiveHeadroom) or 0)
    local liveSafeHeadroom = math.max(0, queueHeadroom - requiredLiveHeadroom)
    local projectedMessages = math.max(0, tonumber(admission.projectedMessages) or 0)
    local delayedReceipts = math.max(0, tonumber(receiptState.waiting) or 0)
      + math.max(0, tonumber(receiptState.unconfirmed) or 0)
    local capacityText = "Queue " .. tostring(pending) .. "/" .. tostring(maxQueueDepth)
      .. " | Headroom " .. tostring(queueHeadroom)
    if admissionMatches then
      capacityText = capacityText
        .. " | Live-safe " .. tostring(liveSafeHeadroom)
        .. " | BSYNC " .. tostring(projectedMessages) .. " projected"
        .. " | Reserve " .. tostring(requiredLiveHeadroom)
    else
      capacityText = capacityText .. " | No BSYNC plan in this session"
    end
    capacityText = capacityText .. " | Delayed live receipts " .. tostring(delayedReceipts)
    SetSyncProgressRow(
      frame,
      "liveCapacity",
      capacityText,
      delayedReceipts > 0 and { 0.38, 0.72, 1.00, 1.00 } or { 0.58, 0.90, 0.70, 1.00 },
      activeSessionId ~= "" or pending > 0
    )

    local targetText = ""
    if stagedMatches then
      local targetCount = math.max(0, tonumber(staged.targetCount) or 0)
      targetText = "Active " .. tostring(math.max(0, tonumber(staged.activeTargetCount) or 0))
        .. "/" .. tostring(math.max(0, tonumber(staged.activeTargetLimit) or 0))
        .. " | Staged " .. tostring(math.max(0, tonumber(staged.stagedCount) or 0))
        .. " | ACK " .. tostring(math.max(0, tonumber(staged.acknowledgedCount) or 0))
        .. "/" .. tostring(targetCount)
        .. " | Failed " .. tostring(math.max(0, tonumber(staged.failedCount) or 0))
        .. " | Latest retained " .. tostring(math.max(0, tonumber(staged.pendingLatestCount) or 0))
        .. " | Coalesced " .. tostring(math.max(0, tonumber(staged.totalCoalescedCount) or 0))
        .. " | Released " .. tostring(math.max(0, tonumber(staged.totalReleasedCount) or 0))
        .. " | " .. (TrimText(staged.state) ~= "" and string.gsub(TrimText(staged.state), "_", " ") or "idle")
    elseif admissionMatches then
      targetText = "Planned " .. tostring(math.max(0, tonumber(admission.targetCount) or 0))
        .. " | Active limit " .. tostring(math.max(0, tonumber(admission.activeTargetLimit) or 0))
        .. " | Not dispatched"
    end
    SetSyncProgressRow(
      frame,
      "boardSyncTargets",
      targetText,
      stagedMatches and math.max(0, tonumber(staged.failedCount) or 0) > 0
        and { 1.00, 0.55, 0.44, 1.00 } or { 0.76, 0.84, 1.00, 1.00 },
      targetText ~= ""
    )

    local stagedState = string.lower(TrimText(staged.state))
    local blocked = queueStatus.atCapacity == true
      or queueStatus.usingCriticalOverflow == true
      or (admissionMatches and admission.admitted == false)
      or (stagedMatches and stagedState == "waiting_capacity")
    local warningText = ""
    if blocked then
      local messagesPerTarget = math.max(0, tonumber(admission.messagesPerTarget) or 0)
      warningText = "Attention Required: Capacity protection stopped new BSYNC work before queue overflow."
      if messagesPerTarget > 0 then
        warningText = warningText .. " Next target needs " .. tostring(messagesPerTarget)
          .. " safe slots; " .. tostring(liveSafeHeadroom) .. " available."
      end
      if stagedMatches and stagedState == "waiting_capacity" then
        warningText = warningText .. " Staged delivery resumes automatically when headroom recovers."
      elseif admissionMatches and admission.admitted == false then
        warningText = warningText .. " Retry the board action after headroom recovers."
      else
        warningText = warningText .. " New BSYNC work remains protected until headroom recovers."
      end
    end
    SetSyncProgressRow(
      frame,
      "capacityWarning",
      warningText,
      { 1.00, 0.82, 0.32, 1.00 },
      warningText ~= ""
    )
    return {
      blocked = blocked,
      warning = warningText,
      projectedMessages = projectedMessages,
      queueHeadroom = queueHeadroom,
      liveSafeHeadroom = liveSafeHeadroom,
      activeTargets = math.max(0, tonumber(staged.activeTargetCount) or 0),
      stagedTargets = math.max(0, tonumber(staged.stagedCount) or 0),
      delayedReceipts = delayedReceipts,
    }
  end

  local function RefreshActiveTransferRows(frame, queueStatus, outboundSessionTelemetry, activeTelemetrySessionId)
    local function FormatTransferBytes(byteCount)
      local bytes = math.max(0, tonumber(byteCount) or 0)
      if bytes >= 1024 then
        return string.format("%.1fKB", bytes / 1024)
      end
      return tostring(bytes) .. "B"
    end
    local activeTransfers = {}
    for _, transfer in ipairs(type(queueStatus.profileTransfers) == "table" and queueStatus.profileTransfers or {}) do
      local state = TrimText(transfer.state)
      if outboundSessionTelemetry.active == true
        and activeTelemetrySessionId ~= ""
        and TrimText(transfer.sessionId) == activeTelemetrySessionId
        and state ~= "" and state ~= "acked" and string.sub(state, 1, 10) ~= "superseded"
      then
        activeTransfers[#activeTransfers + 1] = transfer
      end
      if #activeTransfers >= 3 then
        break
      end
    end
    for index = 1, 3 do
      local transfer = activeTransfers[index]
      if type(transfer) == "table" then
        local totalChunks = math.max(0, tonumber(transfer.totalChunks) or 0)
        local sentChunks = math.min(totalChunks, math.max(0, tonumber(transfer.sentChunks) or 0))
        local target = TrimText(transfer.target)
        if target == "" then
          target = "unknown target"
        end
        local transferState = TrimText(transfer.state)
        local transferStateLabel = transferState
        local acknowledgementAge = math.max(0, tonumber(transfer.acknowledgementAgeSeconds) or 0)
        local acknowledgementDeadline = math.max(0, tonumber(transfer.acknowledgementDeadlineAt) or 0)
        local acknowledgementRemaining = acknowledgementDeadline > 0
          and math.max(0, acknowledgementDeadline - (time and time() or 0)) or 0
        local recoveryOutcome = TrimText(transfer.ackTimeoutRecoveryOutcome)
        local recoveryError = TrimText(transfer.ackTimeoutRecoveryError)
        if transferState == "waiting_apply" then
          transferStateLabel = "received; waiting for combat to end"
        elseif transferState == "waiting_ack" then
          transferStateLabel = "receipt pending"
            .. (acknowledgementDeadline > 0 and (" (" .. tostring(math.ceil(acknowledgementAge))
              .. "s sent, " .. tostring(math.ceil(acknowledgementRemaining)) .. "s before recovery)") or "")
        elseif transferState == "ack_timeout" then
          if recoveryOutcome == "revalidation_pending" then
            local recoveryDomain = type(transfer.ackTimeoutRevalidationDomains) == "table"
              and TrimText(transfer.ackTimeoutRevalidationDomains[1]) or ""
            transferStateLabel = "Receipt timed out - revalidating" .. (recoveryDomain ~= "" and (" " .. recoveryDomain) or "")
          elseif recoveryOutcome == "queued" or recoveryOutcome == "deferred" then
            transferStateLabel = "Receipt timed out - targeted repair queued"
          elseif recoveryOutcome ~= "" then
            transferStateLabel = "Receipt timed out - recovery " .. string.gsub(recoveryOutcome, "_", " ")
          else
            transferStateLabel = "Receipt timed out - recovery pending"
          end
          if recoveryError ~= "" then
            transferStateLabel = transferStateLabel .. " (" .. recoveryError .. ")"
          end
        elseif transferState == "failed" and TrimText(transfer.failureReason) ~= "" then
          transferStateLabel = "failed: " .. TrimText(transfer.failureReason)
        end
        local transferText = target .. " - " .. transferStateLabel
          .. (math.max(0, tonumber(transfer.generation) or 0) > 0
            and (" g" .. tostring(math.max(0, tonumber(transfer.generation) or 0))) or "")
          .. " (" .. tostring(sentChunks) .. "/" .. tostring(totalChunks) .. " chunks)"
        local attemptedBytes = math.max(0, tonumber(transfer.bytesAttempted) or 0)
        local sentBytes = math.max(0, tonumber(transfer.bytesSent) or 0)
        local attemptedMessages = math.max(0, tonumber(transfer.attemptedMessages) or 0)
        local sentMessages = math.max(0, tonumber(transfer.sentMessages) or 0)
        local throttledMessages = math.max(0, tonumber(transfer.throttledMessages) or 0)
        local failedMessages = math.max(0, tonumber(transfer.failedMessages) or 0)
        local transferColor = transferState == "waiting_ack" and { 0.76, 0.84, 1.00, 1.00 }
          or (transferState == "ack_timeout" and { 1.00, 0.82, 0.32, 1.00 }
            or (transferState == "failed" and { 1.00, 0.55, 0.44, 1.00 } or { 0.86, 0.88, 0.94, 1.00 }))
        if attemptedBytes > 0 or sentBytes > 0 then
          transferText = transferText .. " | " .. FormatTransferBytes(sentBytes) .. " sent"
            .. " / " .. FormatTransferBytes(attemptedBytes) .. " attempted"
            .. " (" .. tostring(sentMessages) .. "/" .. tostring(attemptedMessages) .. " msgs)"
        end
        if throttledMessages > 0 or failedMessages > 0 then
          transferText = transferText
            .. (throttledMessages > 0 and (" | T" .. tostring(throttledMessages)) or "")
            .. (failedMessages > 0 and (" F" .. tostring(failedMessages)) or "")
        end
        local laneLabel = FormatSyncTransferLane(transfer)
        local reasonLabel = FormatSyncTransferReason(transfer.reason)
        local kindLabel = FormatSyncTransferKindLabel(transfer)
        if laneLabel ~= "" or reasonLabel ~= "" or kindLabel ~= "" then
          transferText = transferText .. " | " .. laneLabel
          if reasonLabel ~= "" then
            transferText = transferText .. " | " .. reasonLabel
          end
          if kindLabel ~= "" then
            transferText = transferText .. " | " .. kindLabel
          end
        end
        local ackTimerFallbackAt = math.max(0, tonumber(transfer.ackTimeoutTimerFallbackAt) or 0)
        local ackTimerFallbackReason = TrimText(transfer.ackTimeoutTimerFallbackReason)
        if ackTimerFallbackAt > 0 or ackTimerFallbackReason ~= "" then
          transferText = transferText .. " | ACK timer fallback"
            .. (ackTimerFallbackReason ~= "" and (" (" .. ackTimerFallbackReason .. ")") or "")
          transferColor = { 1.00, 0.78, 0.62, 1.00 }
        end
        SetSyncProgressRow(frame, "transfer" .. tostring(index), transferText, transferColor, true)
      else
        SetSyncProgressRow(frame, "transfer" .. tostring(index), "", nil, false)
      end
    end
    return activeTransfers[1]
  end

  local function RefreshDeliveryEventRow(frame, queueStatus)
    local recentEvents = {}
    local function AddEvent(eventAt, eventText, severity)
      local text = TrimText(eventText)
      if text == "" then
        return
      end
      recentEvents[#recentEvents + 1] = {
        at = math.max(0, tonumber(eventAt) or 0),
        text = text,
        severity = TrimText(severity),
      }
    end
    local decisionStats = type(queueStatus.profileSyncDecisionStats) == "table" and queueStatus.profileSyncDecisionStats or {}
    for _, event in ipairs(type(decisionStats.recentEvents) == "table" and decisionStats.recentEvents or {}) do
      if type(event) == "table" then
        local target = TrimText(event.target)
        local scope = type(event.subdomains) == "table" and TrimText(event.subdomains[1]) or ""
        if scope == "" and type(event.domains) == "table" then
          scope = TrimText(event.domains[1])
        end
        local details = {}
        local reason = FormatSyncTransferReason(event.reason)
        local transferKind = string.upper(TrimText(event.transferKind))
        local action = string.gsub(TrimText(event.action), "_", " ")
        if reason ~= "" then
          details[#details + 1] = reason
        end
        if scope ~= "" then
          details[#details + 1] = scope
        elseif transferKind ~= "" then
          details[#details + 1] = transferKind
        end
        if action ~= "" then
          details[#details + 1] = action
        end
        local chunks = math.max(0, tonumber(event.chunkCount) or 0)
        if chunks > 0 then
          details[#details + 1] = tostring(chunks) .. " chunks"
        end
        local eventError = TrimText(event.error)
        if eventError ~= "" then
          details[#details + 1] = "failed: " .. eventError
        elseif event.fallback == true then
          details[#details + 1] = "safe fallback"
        end
        AddEvent(
          math.max(0, tonumber(event.lastRecordedAt) or tonumber(event.recordedAt) or 0),
          (target ~= "" and target or "group") .. " | " .. table.concat(details, " | "),
          eventError ~= "" and "error" or (event.fallback == true and "recovered" or "normal")
        )
      end
    end
    for _, issue in ipairs(type(queueStatus.outboundIssueHistory) == "table" and queueStatus.outboundIssueHistory or {}) do
      if type(issue) == "table" then
        local target = TrimText(issue.target)
        local category = string.gsub(TrimText(issue.category), "_", " ")
        local detail = TrimText(issue.reason)
        local bytes = math.max(0, tonumber(issue.bytes) or 0)
        local recovered = queueStatus.outboundIssueRecovered == true
          and TrimText(issue.kind) == TrimText(queueStatus.lastOutboundIssueResolvedKind)
          and (TrimText(issue.target) == ""
            or string.lower(TrimText(issue.target)) == string.lower(TrimText(queueStatus.lastOutboundIssueResolvedTarget)))
          and math.max(0, tonumber(queueStatus.lastOutboundIssueResolvedAt) or 0) >= math.max(0, tonumber(issue.at) or 0)
        if recovered then
          category = category == "payload rejected" and "payload fallback recovered"
            or ((category ~= "" and category or "delivery issue") .. " recovered")
        end
        if bytes > 0 then
          detail = detail .. (detail ~= "" and " | " or "") .. tostring(bytes) .. " bytes"
        end
        AddEvent(
          issue.at,
          (target ~= "" and target or "group") .. " | " .. TrimText(issue.kind)
            .. " | " .. (category ~= "" and category or "delivery issue")
            .. (detail ~= "" and (" | " .. detail) or ""),
          recovered and "recovered" or "error"
        )
      end
    end
    table.sort(recentEvents, function(left, right)
      return (tonumber(left.at) or 0) > (tonumber(right.at) or 0)
    end)
    local lines = {}
    local color = { 0.82, 0.84, 0.92, 1.00 }
    for index, event in ipairs(recentEvents) do
      if index > 5 then
        break
      end
      lines[#lines + 1] = "[" .. FormatDateTime(event.at) .. "] " .. event.text
      if index == 1 then
        color = event.severity == "error" and { 1.00, 0.78, 0.62, 1.00 }
          or (event.severity == "recovered" and { 0.42, 1.00, 0.52, 1.00 }
            or { 0.82, 0.84, 0.92, 1.00 })
      end
    end
    SetSyncProgressRow(frame, "deliveryEvents", table.concat(lines, "\n"), color, #lines > 0)
  end

  local function RefreshSyncProgressPanel(editor, queueStatus, displayOptions)
    if type(InCombatLockdown) == "function" and InCombatLockdown() then
      editor.__lootSessionSyncProgressRefreshDeferred = true
      return
    end
    editor.__lootSessionSyncProgressRefreshDeferred = nil
    local frame = EnsureSyncProgressPanel(editor)
    if not frame then
      return
    end

    queueStatus = type(queueStatus) == "table" and queueStatus or {}
    displayOptions = type(displayOptions) == "table" and displayOptions or {}
    frame.__canControlArchiveSync = displayOptions.canControlArchiveSync == true
    frame.__showArchivePauseControl = frame.__canControlArchiveSync
    frame.__isSessionHost = displayOptions.isSessionHost == true
    frame:UpdateRefreshCadence(frame.__isSessionHost)
    queueStatus.inviteDeliveryStatus = ReadSyncActionValue(
      editor,
      nil,
      "Read invite delivery receipts",
      ResolveOptionalApiFunction("LIDCOUNCIL_GetInviteDeliveryStatus"),
      {}
    )
    queueStatus.acceptedJoinBurstStatus = ReadSyncActionValue(
      editor,
      nil,
      "Read accepted JOIN worker status",
      ResolveOptionalApiFunction("LIDCOUNCIL_GetAcceptedJoinBurstStatus"),
      {}
    )
    queueStatus.criticalReceiptStatus = ReadSyncActionValue(
      editor,
      nil,
      "Read live board delivery receipts",
      ResolveOptionalApiFunction("LIDCOUNCIL_GetLiveLootRuntimeDiagnostics"),
      {}
    )
    local pending = math.max(0, tonumber(queueStatus.pending) or 0)
    local interval = tonumber(queueStatus.intervalSeconds) or 0.12
    local estimatedSeconds = math.ceil(pending * interval)
    local stateLabel, stateR, stateG, stateB, stateA = GetSyncProgressStateColor(queueStatus)
    local byKind = type(queueStatus.byKind) == "table" and queueStatus.byKind or {}
    local profileChunks = math.max(0, tonumber(byKind.PSYNC_CHUNK) or 0)
    local profileControl = math.max(0, (tonumber(byKind.PSYNC_START) or 0) + (tonumber(byKind.PSYNC_END) or 0))
    local detailCompare = math.max(0, (tonumber(byKind.PSUB_REQ) or 0) + (tonumber(byKind.PSUB_STATE) or 0))
    local patchManifest = math.max(0, (tonumber(byKind.PSUBPATCH_REQ) or 0) + (tonumber(byKind.PSUBPATCH_STATE) or 0))
    local sessionControl = math.max(0,
      (tonumber(byKind.START) or 0)
      + (tonumber(byKind.BEGIN) or 0)
      + (tonumber(byKind.JOIN) or 0)
      + (tonumber(byKind.MEMBER) or 0)
      + (tonumber(byKind.STOP) or 0)
      + (tonumber(byKind.PSTATE) or 0)
      + (tonumber(byKind.PSTATE_PART) or 0)
      + (tonumber(byKind.PSYNC_ACK) or 0)
    )

    local sendRate = tonumber(queueStatus.sendRatePerSecond) or 0
    local byteRate = tonumber(queueStatus.byteRatePerSecond) or 0
    local outboundSessionTelemetry = type(queueStatus.outboundSessionTelemetry) == "table"
      and queueStatus.outboundSessionTelemetry
      or {}
    local activeTelemetrySessionId = TrimText(outboundSessionTelemetry.sessionId)
    local outboundTelemetryScope = outboundSessionTelemetry.active == true and outboundSessionTelemetry or queueStatus
    local outboundLaneTelemetry = type(outboundTelemetryScope.outboundLaneTelemetry) == "table"
      and outboundTelemetryScope.outboundLaneTelemetry
      or {}
    local outboundMemberTelemetry = type(outboundTelemetryScope.outboundMemberTelemetry) == "table"
      and outboundTelemetryScope.outboundMemberTelemetry
      or {}
    local outboundOpcodeTelemetry = type(outboundTelemetryScope.outboundOpcodeTelemetry) == "table"
      and outboundTelemetryScope.outboundOpcodeTelemetry
      or {}
    local outboundLanePressure = type(outboundTelemetryScope.outboundLanePressure) == "table"
      and outboundTelemetryScope.outboundLanePressure
      or {}
    local lanePressureText = {}
    local lanePressureSeverity = ""
    for index, pressure in ipairs(outboundLanePressure) do
      if index > 2 then
        break
      end
      if type(pressure) == "table" then
        local lane = TrimText(pressure.lane)
        local reasons = type(pressure.reasons) == "table" and pressure.reasons or {}
        if lane ~= "" and #reasons > 0 then
          lanePressureText[#lanePressureText + 1] = lane .. " (" .. table.concat(reasons, ", ") .. ")"
          if lanePressureSeverity == "" or pressure.severity == "critical" then
            lanePressureSeverity = TrimText(pressure.severity)
          elseif lanePressureSeverity == "watch" and pressure.severity == "warning" then
            lanePressureSeverity = "warning"
          end
        end
      end
    end
    local topOutboundOpcode = type(outboundOpcodeTelemetry.opcodes) == "table" and outboundOpcodeTelemetry.opcodes[1] or {}
    local topOutboundOpcodeKind = TrimText(type(topOutboundOpcode) == "table" and topOutboundOpcode.kind or "")
    local topOutboundOpcodeSent = math.max(0, tonumber(type(topOutboundOpcode) == "table" and topOutboundOpcode.sent or 0) or 0)
    local topOutboundOpcodeQueued = math.max(0, tonumber(type(topOutboundOpcode) == "table" and topOutboundOpcode.queuedNow or 0) or 0)
    local topOutboundOpcodeBytes = math.max(0, tonumber(type(topOutboundOpcode) == "table" and topOutboundOpcode.bytesSent or 0) or 0)
    local startQueuedTotal = 0
    local startQueuedNow = 0
    local startAttemptedTotal = 0
    local startSentTotal = 0
    local startFailedTotal = 0
    queueStatus.inviteAckQueuedTotal = 0
    queueStatus.inviteAckSentTotal = 0
    queueStatus.inviteAckFailedTotal = 0
    for _, opcode in ipairs(type(outboundOpcodeTelemetry.opcodes) == "table" and outboundOpcodeTelemetry.opcodes or {}) do
      if TrimText(type(opcode) == "table" and opcode.kind or "") == "START" then
        startQueuedTotal = math.max(0, tonumber(opcode.queuedTotal) or 0)
        startQueuedNow = math.max(0, tonumber(opcode.queuedNow) or 0)
        startAttemptedTotal = math.max(0, tonumber(opcode.attempted) or 0)
        startSentTotal = math.max(0, tonumber(opcode.sent) or 0)
        startFailedTotal = math.max(0, tonumber(opcode.failed) or 0)
      elseif TrimText(type(opcode) == "table" and opcode.kind or "") == "IACK" then
        queueStatus.inviteAckQueuedTotal = math.max(0, tonumber(opcode.queuedTotal) or 0)
        queueStatus.inviteAckSentTotal = math.max(0, tonumber(opcode.sent) or 0)
        queueStatus.inviteAckFailedTotal = math.max(0, tonumber(opcode.failed) or 0)
      end
    end
    local outboundOpcodePressure = type(outboundOpcodeTelemetry.pressure) == "table" and outboundOpcodeTelemetry.pressure or {}
    local opcodePressureText = {}
    local opcodePressureSeverity = ""
    for index, pressure in ipairs(outboundOpcodePressure) do
      if index > 2 then
        break
      end
      if type(pressure) == "table" then
        local kind = TrimText(pressure.kind)
        local reasons = type(pressure.reasons) == "table" and pressure.reasons or {}
        if kind ~= "" and #reasons > 0 then
          opcodePressureText[#opcodePressureText + 1] = kind .. " (" .. table.concat(reasons, ", ") .. ")"
          if opcodePressureSeverity == "" or pressure.severity == "critical" then
            opcodePressureSeverity = TrimText(pressure.severity)
          elseif opcodePressureSeverity == "watch" and pressure.severity == "warning" then
            opcodePressureSeverity = "warning"
          end
        end
      end
    end
    local sessionPressureSeverity = opcodePressureSeverity
    if lanePressureSeverity == "critical" or sessionPressureSeverity == "" then
      sessionPressureSeverity = lanePressureSeverity
    elseif sessionPressureSeverity == "watch" and lanePressureSeverity == "warning" then
      sessionPressureSeverity = "warning"
    end
    local inboundRate = tonumber(queueStatus.inboundRatePerSecond) or 0
    local inboundByteRate = tonumber(queueStatus.inboundByteRatePerSecond) or 0
    local inboundTotal = math.max(0, tonumber(queueStatus.inboundTotal) or 0)
    local inboundDispatchedTotal = math.max(0, tonumber(queueStatus.inboundDispatchedTotal) or 0)
    local inboundRejectedTotal = math.max(0, tonumber(queueStatus.inboundRejectedTotal) or 0)
    local inboundRejectedContractTotal = math.max(0, tonumber(queueStatus.inboundRejectedContractTotal) or 0)
    local inboundUnknownOpcodeTotal = math.max(0, tonumber(queueStatus.inboundUnknownOpcodeTotal) or 0)
    local inboundStaleSessionBoundDropTotal = math.max(0, tonumber(queueStatus.inboundStaleSessionBoundDropTotal) or 0)
    local inboundHandlerErrorTotal = math.max(0, tonumber(queueStatus.inboundHandlerErrorTotal) or 0)
    local inboundDispatchedByKind = type(queueStatus.inboundDispatchedByKind) == "table"
      and queueStatus.inboundDispatchedByKind
      or {}
    local inviteReceiptTotal = math.max(0, tonumber(inboundDispatchedByKind.IACK) or 0)
    queueStatus.inviteInboundStages = type(queueStatus.inboundStageByKind) == "table"
      and type(queueStatus.inboundStageByKind.START) == "table"
      and queueStatus.inboundStageByKind.START
      or {}
    queueStatus.inviteInboundText = ""
    if math.max(0, tonumber(queueStatus.inviteInboundStages.RECEIVED) or 0) > 0
      or math.max(0, tonumber(queueStatus.inviteInboundStages.CONTRACT) or 0) > 0
      or math.max(0, tonumber(queueStatus.inviteInboundStages.ADMITTED) or 0) > 0
      or math.max(0, tonumber(queueStatus.inviteInboundStages.DISPATCHED) or 0) > 0
      or math.max(0, tonumber(queueStatus.inviteInboundStages.REJECTED) or 0) > 0
    then
      queueStatus.inviteInboundText = " | local START rx/contract/admit/handler/reject "
        .. tostring(math.max(0, tonumber(queueStatus.inviteInboundStages.RECEIVED) or 0))
        .. "/" .. tostring(math.max(0, tonumber(queueStatus.inviteInboundStages.CONTRACT) or 0))
        .. "/" .. tostring(math.max(0, tonumber(queueStatus.inviteInboundStages.ADMITTED) or 0))
        .. "/" .. tostring(math.max(0, tonumber(queueStatus.inviteInboundStages.DISPATCHED) or 0))
        .. "/" .. tostring(math.max(0, tonumber(queueStatus.inviteInboundStages.REJECTED) or 0))
    end
    if queueStatus.inviteAckQueuedTotal > 0 or queueStatus.inviteAckSentTotal > 0 or queueStatus.inviteAckFailedTotal > 0 then
      queueStatus.inviteInboundText = queueStatus.inviteInboundText
        .. " | local receipt queued/sent/failed "
        .. tostring(queueStatus.inviteAckQueuedTotal)
        .. "/" .. tostring(queueStatus.inviteAckSentTotal)
        .. "/" .. tostring(queueStatus.inviteAckFailedTotal)
    end
    queueStatus.inviteDeliveryText = ""
    if type(queueStatus.inviteDeliveryStatus) == "table"
      and queueStatus.inviteDeliveryStatus.isHost == true
      and math.max(0, tonumber(queueStatus.inviteDeliveryStatus.total) or 0) > 0
    then
      queueStatus.inviteDeliveryText = " | popup "
        .. tostring(math.max(0, tonumber(queueStatus.inviteDeliveryStatus.confirmed) or 0))
        .. "/" .. tostring(math.max(0, tonumber(queueStatus.inviteDeliveryStatus.total) or 0))
        .. " confirmed"
        .. (math.max(0, tonumber(queueStatus.inviteDeliveryStatus.pending) or 0) > 0
          and (" | awaiting " .. tostring(math.max(0, tonumber(queueStatus.inviteDeliveryStatus.pending) or 0))) or "")
        .. (math.max(0, tonumber(queueStatus.inviteDeliveryStatus.retrying) or 0) > 0
          and (" | retrying " .. tostring(math.max(0, tonumber(queueStatus.inviteDeliveryStatus.retrying) or 0))) or "")
        .. (math.max(0, tonumber(queueStatus.inviteDeliveryStatus.rejected) or 0) > 0
          and (" | rejected " .. tostring(math.max(0, tonumber(queueStatus.inviteDeliveryStatus.rejected) or 0))) or "")
        .. (math.max(0, tonumber(queueStatus.inviteDeliveryStatus.timedOut) or 0) > 0
          and (" | no receipt " .. tostring(math.max(0, tonumber(queueStatus.inviteDeliveryStatus.timedOut) or 0))) or "")
        .. (math.max(0, tonumber(queueStatus.inviteDeliveryStatus.sendFailed) or 0) > 0
          and (" | send failed " .. tostring(math.max(0, tonumber(queueStatus.inviteDeliveryStatus.sendFailed) or 0))) or "")
    end
    local lastInboundHandlerErrorKind = TrimText(queueStatus.lastInboundHandlerErrorKind)
    local lastInboundHandlerErrorSender = TrimText(queueStatus.lastInboundHandlerErrorSender)
    local lastInboundHandlerErrorDetail = TrimText(queueStatus.lastInboundHandlerErrorDetail)
    local inboundRateLimitedTotal = math.max(0, tonumber(queueStatus.inboundRateLimitedTotal) or 0)
    local lastInboundRateLimitedKind = TrimText(queueStatus.lastInboundRateLimitedKind)
    local lastInboundRateLimitedSender = TrimText(queueStatus.lastInboundRateLimitedSender)
    local lastInboundRateLimitedLane = TrimText(queueStatus.lastInboundRateLimitedLane)
    local missingProtocolHandlerCount = math.max(0, tonumber(queueStatus.commProtocolMissingHandlerCount) or 0)
    local protocolOwnerMismatchCount = math.max(0, tonumber(queueStatus.commProtocolOwnerMismatchCount) or 0)
    local uncontractedProtocolHandlerCount = math.max(0, tonumber(queueStatus.commProtocolUncontractedHandlerCount) or 0)
    local stalePreciseResponseDrops = math.max(0, tonumber(queueStatus.stalePreciseResponseDrops) or 0)
    local pendingProfileDeltaAcks = math.max(0, tonumber(queueStatus.pendingProfileDeltaAcks) or 0)
    local pendingProfileDeltaAckMembers = math.max(0, tonumber(queueStatus.pendingProfileDeltaAckMembers) or 0)
    local profileDeltaAckSupersededTotal = math.max(0, tonumber(queueStatus.profileDeltaAckSupersededTotal) or 0)
    local ackTimeoutRevalidationStats = type(queueStatus.ackTimeoutRevalidationStats) == "table"
      and queueStatus.ackTimeoutRevalidationStats
      or {}
    local suppressedAckTimeoutDomains = math.max(0, tonumber(ackTimeoutRevalidationStats.suppressedDomainTotal) or 0)
    local coalescedAckTimeoutCallbacks = math.max(0, tonumber(ackTimeoutRevalidationStats.coalescedRecoveryCallbackTotal) or 0)
    local sharedAckTimeoutRecoveryBatches = math.max(0, tonumber(ackTimeoutRevalidationStats.sharedRecoveryBatchTotal) or 0)
    local sharedAckTimeoutRecoveryTransfers = math.max(0, tonumber(ackTimeoutRevalidationStats.sharedRecoveryTransferTotal) or 0)
    local timerFallbackTotal = math.max(0, tonumber(queueStatus.timerFallbackTotal) or 0)
    local lastTimerFallbackReason = TrimText(queueStatus.lastTimerFallbackReason)
    local profileAckTimeoutTimerFallbackTotal = math.max(0,
      tonumber(queueStatus.profileAckTimeoutTimerFallbackTotal) or 0)
    local lastProfileAckTimeoutTimerFallbackReason = TrimText(queueStatus.lastProfileAckTimeoutTimerFallbackReason)
    local deferredEditorRefreshTimerFallbackTotal = math.max(0,
      tonumber(queueStatus.deferredEditorRefreshTimerFallbackTotal) or 0)
    local lastDeferredEditorRefreshTimerFallbackReason = TrimText(queueStatus.lastDeferredEditorRefreshTimerFallbackReason)
    local compatTimerStatus = type(queueStatus.compatTimerStatus) == "table" and queueStatus.compatTimerStatus or {}
    local startupHealthStatus = type(queueStatus.startupHealthStatus) == "table"
      and queueStatus.startupHealthStatus
      or {}
    local startupHealthErrors = math.max(0, tonumber(startupHealthStatus.errorCount) or 0)
    local startupHealthWarnings = math.max(0, tonumber(startupHealthStatus.warningCount) or 0)
    local startupHealthChecks = math.max(0, tonumber(startupHealthStatus.checkCount) or 0)
    local startupHealthPassed = math.max(0, tonumber(startupHealthStatus.passedCount) or 0)
    local rejectedProtocolFieldTotal = math.max(0, tonumber(queueStatus.rejectedProtocolFieldTotal) or 0)
    local rejectedProtocolMinimumTotal = math.max(0, tonumber(queueStatus.rejectedProtocolMinimumTotal) or 0)
    local rejectedPayloadTotal = math.max(0, tonumber(queueStatus.rejectedPayloadTotal) or 0)
    local lastRejectedPayloadKind = TrimText(queueStatus.lastRejectedPayloadKind)
    local lastRejectedPayloadReason = TrimText(queueStatus.lastRejectedPayloadReason)
    local lastRejectedPayloadBytes = math.max(0, tonumber(queueStatus.lastRejectedPayloadBytes) or 0)
    local apiFailureTotal = math.max(0, tonumber(queueStatus.apiFailureTotal) or 0)
    local throttleExhaustedTotal = math.max(0, tonumber(queueStatus.throttleExhaustedTotal) or 0)
    local lastOutboundIssueCategory = TrimText(queueStatus.lastOutboundIssueCategory)
    local lastOutboundIssueKind = TrimText(queueStatus.lastOutboundIssueKind)
    local lastOutboundIssueReason = TrimText(queueStatus.lastOutboundIssueReason)
    local lastOutboundIssueBytes = math.max(0, tonumber(queueStatus.lastOutboundIssueBytes) or 0)
    local lastOutboundIssueAt = math.max(0, tonumber(queueStatus.lastOutboundIssueAt) or 0)
    local lastOutboundIssueResolvedKind = TrimText(queueStatus.lastOutboundIssueResolvedKind)
    local lastOutboundIssueResolvedTarget = TrimText(queueStatus.lastOutboundIssueResolvedTarget)
    local lastOutboundIssueResolvedAt = math.max(0, tonumber(queueStatus.lastOutboundIssueResolvedAt) or 0)
    local latestDiagnosticKind = lastOutboundIssueKind ~= "" and lastOutboundIssueKind or lastRejectedPayloadKind
    local latestDiagnosticReason = lastOutboundIssueReason ~= "" and lastOutboundIssueReason or lastRejectedPayloadReason
    local latestDiagnosticBytes = math.max(lastOutboundIssueBytes, lastRejectedPayloadBytes)
    local diagnosticResolved = queueStatus.outboundIssueRecovered == true
      or TrimText(queueStatus.outboundDiagnosticState) == "recovered"
      or (TrimText(queueStatus.outboundDiagnosticState) == ""
        and latestDiagnosticKind ~= ""
        and latestDiagnosticKind == lastOutboundIssueResolvedKind
        and lastOutboundIssueResolvedAt > 0
        and lastOutboundIssueResolvedAt >= lastOutboundIssueAt)
    local outboundIssueScopeSessionId = TrimText(queueStatus.outboundIssueScopeSessionId)
    local inboundWindowSeconds = math.max(1, tonumber(queueStatus.inboundWindowSeconds) or 10)
    local sentTotal = math.max(0, tonumber(outboundTelemetryScope.sentTotal) or 0)
    local attemptedTotal = math.max(0, tonumber(outboundTelemetryScope.attemptedTotal) or 0)
    local throttledTotal = math.max(0, tonumber(outboundTelemetryScope.throttledTotal) or 0)
    local failedTotal = math.max(0, tonumber(outboundTelemetryScope.failedTotal) or 0)
    local staleSessionBoundPrunedTotal = math.max(0, tonumber(outboundTelemetryScope.staleSessionBoundPrunedTotal) or 0)
    local archivePressureDeferredTotal = math.max(0, tonumber(outboundTelemetryScope.archivePressureDeferredTotal) or 0)
    local archiveTargetPacingPreemptionsTotal = math.max(0,
      tonumber(outboundTelemetryScope.archiveTargetPacingPreemptionsTotal) or 0)
    local obsoleteProfileQueuePrunedTotal = math.max(0,
      tonumber(outboundTelemetryScope.obsoleteProfileQueuePrunedTotal) or 0)
    local archiveInFlightCoalescedTotal = math.max(0,
      tonumber(type(queueStatus.profileSnapshotBatch) == "table"
        and queueStatus.profileSnapshotBatch.archiveInFlightCoalescedTotal or 0) or 0)
    local archivePreparationCoalescedTotal = math.max(0,
      tonumber(type(queueStatus.profileSnapshotBatch) == "table"
        and queueStatus.profileSnapshotBatch.archivePreparationCoalescedTotal or 0) or 0)
    local preparedArchiveRepairCacheEntries = math.max(0,
      tonumber(type(queueStatus.profileSnapshotBatch) == "table"
        and queueStatus.profileSnapshotBatch.preparedArchiveRepairCacheEntries or 0) or 0)
    local archivePreparationPrunedTotal = math.max(0,
      tonumber(type(queueStatus.profileSnapshotBatch) == "table"
        and queueStatus.profileSnapshotBatch.archivePreparationPrunedTotal or 0) or 0)
    local lastFailureReason = TrimText(queueStatus.lastFailureReason)
    local prefixRegistrationFailures = math.max(0, tonumber(queueStatus.prefixRegistrationFailures) or 0)
    local optionalApiFailureCount = math.max(0, tonumber(queueStatus.optionalApiFailureCount) or 0)
    queueStatus.inboundMalformedTotal = math.max(0, tonumber(queueStatus.inboundMalformedTotal) or 0)
    queueStatus.inboundAdmissionDropTotal = math.max(0, tonumber(queueStatus.inboundAdmissionDropTotal) or 0)
    queueStatus.inboundVisibleRateLimitedTotal = math.max(inboundRateLimitedTotal,
      math.max(0, tonumber(queueStatus.inboundClassifiedRateLimitedTotal) or 0))
    queueStatus.inboundVisibleStaleTotal = math.max(inboundStaleSessionBoundDropTotal,
      math.max(0, tonumber(queueStatus.inboundClassifiedStaleTotal) or 0))

    local queueValue
    local queueColor
    local queueActive = pending > 0 or queueStatus.busy == true or queueStatus.running == true
    if queueActive then
      queueValue = tostring(pending) .. " pending message" .. (pending == 1 and "" or "s")
        .. (pending > 0 and (" (~" .. tostring(estimatedSeconds) .. "s minimum)") or "")
      queueColor = { stateR, stateG, stateB, stateA }
    else
      queueValue = "Idle"
      queueColor = { 0.30, 0.90, 0.36, 1.00 }
    end
    local payloadFallbackRecovered = queueStatus.outboundPayloadFallbackRecovered == true
      or (diagnosticResolved and lastOutboundIssueCategory == "payload_rejected")
    SetSyncProgressRow(frame, "queue", queueValue, queueColor)

    local nextQueueText = BuildSyncQueuePreviewText(queueStatus.nextItem)
    SetSyncProgressRow(
      frame,
      "next",
      nextQueueText ~= "" and nextQueueText or "",
      nextQueueText ~= "" and { 0.82, 0.84, 0.92, 1.00 } or nil,
      nextQueueText ~= ""
    )

    SetSyncProgressRow(
      frame,
      "pending",
      "Profile chunks " .. tostring(profileChunks)
        .. " | Profile control " .. tostring(profileControl)
        .. " | Detail compare " .. tostring(detailCompare)
        .. " | Patch manifests " .. tostring(patchManifest)
        .. " | Session control " .. tostring(sessionControl),
      { 0.82, 0.84, 0.92, 1.00 }
    )

    SetSyncProgressRow(
      frame,
      "throughput",
      string.format("%.2f msg/s | %.0f bytes/s (10s window)", sendRate, byteRate),
      { 0.72, 0.86, 0.92, 1.00 }
    )

    frame.__syncPerformanceText = INTERNAL_API.LIDCOUNCIL_FormatSyncPerformanceMetrics_Impl(queueStatus.syncPerformance)
    frame.__syncPerformanceReportText = INTERNAL_API.LIDCOUNCIL_BuildSyncPerformanceReport_Impl(queueStatus)
    SetSyncProgressRow(
      frame,
      "localCpu",
      frame.__syncPerformanceText,
      { 0.72, 0.86, 0.92, 1.00 },
      frame.__syncPerformanceText ~= ""
    )
    if frame.copyPerformanceBtn then
      if frame.__syncPerformanceText ~= "" then
        frame.copyPerformanceBtn:Show()
      else
        frame.copyPerformanceBtn:Hide()
      end
    end

    local hasInviteTransportActivity = startQueuedTotal > 0 or startQueuedNow > 0
      or startAttemptedTotal > 0 or startSentTotal > 0 or startFailedTotal > 0 or inviteReceiptTotal > 0
      or queueStatus.inviteDeliveryText ~= "" or queueStatus.inviteInboundText ~= ""
    local inviteTransportColor = (startFailedTotal > 0
        or math.max(0, tonumber(type(queueStatus.inviteDeliveryStatus) == "table"
          and queueStatus.inviteDeliveryStatus.timedOut or 0) or 0) > 0
        or math.max(0, tonumber(type(queueStatus.inviteDeliveryStatus) == "table"
          and queueStatus.inviteDeliveryStatus.sendFailed or 0) or 0) > 0
        or math.max(0, tonumber(type(queueStatus.inviteDeliveryStatus) == "table"
          and queueStatus.inviteDeliveryStatus.rejected or 0) or 0) > 0)
        and { 1.00, 0.55, 0.44, 1.00 }
      or startQueuedNow > 0 and { 1.00, 0.78, 0.32, 1.00 }
      or (math.max(0, tonumber(type(queueStatus.inviteDeliveryStatus) == "table"
          and queueStatus.inviteDeliveryStatus.pending or 0) or 0) > 0
        or math.max(0, tonumber(type(queueStatus.inviteDeliveryStatus) == "table"
          and queueStatus.inviteDeliveryStatus.retrying or 0) or 0) > 0) and { 1.00, 0.78, 0.32, 1.00 }
      or startSentTotal > 0 and { 0.68, 0.90, 0.76, 1.00 }
      or { 0.82, 0.84, 0.92, 1.00 }
    SetSyncProgressRow(
      frame,
      "inviteTransport",
      "START queued " .. tostring(startQueuedTotal) .. " (now " .. tostring(startQueuedNow) .. ")"
        .. " | attempted " .. tostring(startAttemptedTotal)
        .. " | sent " .. tostring(startSentTotal)
        .. " | failed " .. tostring(startFailedTotal)
        .. " | receipts " .. tostring(inviteReceiptTotal)
        .. queueStatus.inviteDeliveryText
        .. queueStatus.inviteInboundText,
      inviteTransportColor,
      hasInviteTransportActivity
    )

    local acceptedJoinBurst = type(queueStatus.acceptedJoinBurstStatus) == "table"
      and queueStatus.acceptedJoinBurstStatus
      or {}
    local acceptedJoinPending = math.max(0, tonumber(acceptedJoinBurst.pending) or 0)
    local acceptedJoinTotal = math.max(0, tonumber(acceptedJoinBurst.acceptedTotal) or 0)
    local acceptedJoinCoalesced = math.max(0, tonumber(acceptedJoinBurst.coalescedTotal) or 0)
    local acceptedJoinProcessed = math.max(0, tonumber(acceptedJoinBurst.processedTotal) or 0)
    local acceptedJoinFailed = math.max(0, tonumber(acceptedJoinBurst.failedTotal) or 0)
    local acceptedJoinWorkerVisible = acceptedJoinPending > 0 or acceptedJoinTotal > 0
      or acceptedJoinCoalesced > 0 or acceptedJoinProcessed > 0 or acceptedJoinFailed > 0
    SetSyncProgressRow(
      frame,
      "joinWorker",
      "Pending " .. tostring(acceptedJoinPending)
        .. (math.max(0, tonumber(acceptedJoinBurst.quietRemaining) or 0) > 0
          and (" | settling " .. string.format("%.1fs", math.max(0, tonumber(acceptedJoinBurst.quietRemaining) or 0)))
          or "")
        .. " | accepted " .. tostring(acceptedJoinTotal)
        .. " | coalesced " .. tostring(acceptedJoinCoalesced)
        .. " | processed " .. tostring(acceptedJoinProcessed)
        .. " | failed " .. tostring(acceptedJoinFailed)
        .. " | commits " .. tostring(math.max(0, tonumber(acceptedJoinBurst.commitTotal) or 0))
        .. "/" .. tostring(math.max(0, tonumber(acceptedJoinBurst.committedMemberTotal) or 0)) .. " members"
        .. " | last/max " .. string.format("%.1f/%.1fms",
          math.max(0, tonumber(acceptedJoinBurst.lastDurationMs) or 0),
          math.max(0, tonumber(acceptedJoinBurst.maxDurationMs) or 0)),
      acceptedJoinFailed > 0 and { 1.00, 0.55, 0.44, 1.00 }
        or acceptedJoinPending > 0 and { 1.00, 0.78, 0.32, 1.00 }
        or { 0.42, 1.00, 0.52, 1.00 },
      acceptedJoinWorkerVisible
    )

    local startupHealthText = startupHealthStatus.ran == true
      and (tostring(startupHealthPassed) .. "/" .. tostring(startupHealthChecks) .. " checks passed"
        .. (startupHealthWarnings > 0 and (" | " .. tostring(startupHealthWarnings) .. " warning(s)") or "")
        .. (startupHealthErrors > 0 and (" | " .. tostring(startupHealthErrors) .. " error(s)") or ""))
      or "Pending PLAYER_LOGIN"
    local startupHealthColor = startupHealthErrors > 0 and { 1.00, 0.55, 0.44, 1.00 }
      or startupHealthWarnings > 0 and { 1.00, 0.78, 0.62, 1.00 }
      or startupHealthStatus.ran == true and { 0.30, 0.90, 0.36, 1.00 }
      or { 0.82, 0.84, 0.92, 1.00 }
    SetSyncProgressRow(frame, "startupHealth", startupHealthText, startupHealthColor)

    local function FormatOutboundLaneBytes(byteCount)
      local bytes = math.max(0, tonumber(byteCount) or 0)
      if bytes >= 1024 then
        return string.format("%.1fKB", bytes / 1024)
      end
      return tostring(bytes) .. "B"
    end
    local laneTextParts = {}
    local laneFailureCount = 0
    for _, laneDefinition in ipairs({
      { key = "live", label = "Live" },
      { key = "bootstrap", label = "Bootstrap" },
      { key = "archive", label = "Archive" },
      { key = "stats", label = "Stats" },
    }) do
      local laneStats = type(outboundLaneTelemetry[laneDefinition.key]) == "table"
        and outboundLaneTelemetry[laneDefinition.key]
        or {}
      local attempted = math.max(0, tonumber(laneStats.attempted) or 0)
      local sent = math.max(0, tonumber(laneStats.sent) or 0)
      local sentBytes = math.max(0, tonumber(laneStats.bytesSent) or 0)
      local throttled = math.max(0, tonumber(laneStats.throttled) or 0)
      local failed = math.max(0, tonumber(laneStats.failed) or 0)
      if attempted > 0 or sent > 0 then
        laneTextParts[#laneTextParts + 1] = laneDefinition.label .. " " .. tostring(sent) .. "/" .. tostring(attempted)
          .. " " .. FormatOutboundLaneBytes(sentBytes)
          .. (throttled > 0 and (" T" .. tostring(throttled)) or "")
          .. (failed > 0 and (" F" .. tostring(failed)) or "")
      end
      laneFailureCount = laneFailureCount + throttled + failed
    end
    SetSyncProgressRow(
      frame,
      "lanes",
      table.concat(laneTextParts, " | "),
      laneFailureCount > 0 and { 1.00, 0.78, 0.62, 1.00 } or { 0.68, 0.90, 0.76, 1.00 },
      #laneTextParts > 0
    )

    local targetTextParts = {}
    local targetFailureCount = 0
    for index, memberStats in ipairs(type(outboundMemberTelemetry.members) == "table" and outboundMemberTelemetry.members or {}) do
      if index > 3 then
        break
      end
      local memberName = TrimText(memberStats.member)
      local attempted = math.max(0, tonumber(memberStats.attempted) or 0)
      local sent = math.max(0, tonumber(memberStats.sent) or 0)
      local sentBytes = math.max(0, tonumber(memberStats.bytesSent) or 0)
      local throttled = math.max(0, tonumber(memberStats.throttled) or 0)
      local failed = math.max(0, tonumber(memberStats.failed) or 0)
      if memberName ~= "" and (attempted > 0 or sent > 0) then
        targetTextParts[#targetTextParts + 1] = memberName .. " " .. tostring(sent) .. "/" .. tostring(attempted)
          .. " " .. FormatOutboundLaneBytes(sentBytes)
          .. (throttled > 0 and (" T" .. tostring(throttled)) or "")
          .. (failed > 0 and (" F" .. tostring(failed)) or "")
        targetFailureCount = targetFailureCount + throttled + failed
      end
    end
    local otherTargetStats = type(outboundMemberTelemetry.other) == "table" and outboundMemberTelemetry.other or {}
    local otherTargetAttempted = math.max(0, tonumber(otherTargetStats.attempted) or 0)
    local otherTargetSent = math.max(0, tonumber(otherTargetStats.sent) or 0)
    local otherTargetBytes = math.max(0, tonumber(otherTargetStats.bytesSent) or 0)
    local otherTargetThrottled = math.max(0, tonumber(otherTargetStats.throttled) or 0)
    local otherTargetFailed = math.max(0, tonumber(otherTargetStats.failed) or 0)
    if otherTargetAttempted > 0 or otherTargetSent > 0 then
      targetTextParts[#targetTextParts + 1] = "Other " .. tostring(otherTargetSent) .. "/" .. tostring(otherTargetAttempted)
        .. " " .. FormatOutboundLaneBytes(otherTargetBytes)
        .. (otherTargetThrottled > 0 and (" T" .. tostring(otherTargetThrottled)) or "")
        .. (otherTargetFailed > 0 and (" F" .. tostring(otherTargetFailed)) or "")
      targetFailureCount = targetFailureCount + otherTargetThrottled + otherTargetFailed
    end
    SetSyncProgressRow(
      frame,
      "trafficTargets",
      table.concat(targetTextParts, " | "),
      targetFailureCount > 0 and { 1.00, 0.78, 0.62, 1.00 } or { 0.72, 0.86, 0.92, 1.00 },
      #targetTextParts > 0
    )

    SetSyncProgressRow(
      frame,
      "inbound",
      string.format("%d received | %.2f msg/s | %.0f bytes/s (%ds)", inboundTotal, inboundRate, inboundByteRate, inboundWindowSeconds)
        .. (inboundDispatchedTotal > 0 and (" | Handled " .. tostring(inboundDispatchedTotal)) or "")
        .. (queueStatus.inboundMalformedTotal > 0 and (" | Malformed " .. tostring(queueStatus.inboundMalformedTotal)) or "")
        .. (queueStatus.inboundAdmissionDropTotal > 0 and (" | Admission ignored " .. tostring(queueStatus.inboundAdmissionDropTotal)) or "")
        .. (inboundUnknownOpcodeTotal > 0 and (" | Unknown opcode " .. tostring(inboundUnknownOpcodeTotal)) or "")
        .. (queueStatus.inboundVisibleStaleTotal > 0 and (" | Previous session ignored " .. tostring(queueStatus.inboundVisibleStaleTotal)) or "")
        .. (inboundHandlerErrorTotal > 0 and (" | Handler failures " .. tostring(inboundHandlerErrorTotal)) or "")
        .. (queueStatus.inboundVisibleRateLimitedTotal > 0 and (" | Burst-limited " .. tostring(queueStatus.inboundVisibleRateLimitedTotal)) or "")
        .. (stalePreciseResponseDrops > 0 and (" | Stale ignored " .. tostring(stalePreciseResponseDrops)) or ""),
      inboundHandlerErrorTotal > 0 and { 1.00, 0.55, 0.44, 1.00 }
        or ((queueStatus.inboundMalformedTotal > 0 or inboundUnknownOpcodeTotal > 0)
          and { 1.00, 0.78, 0.62, 1.00 } or { 0.72, 0.86, 0.92, 1.00 })
    )

    SetSyncProgressRow(
      frame,
      "delta",
      tostring(pendingProfileDeltaAcks) .. " delta update" .. (pendingProfileDeltaAcks == 1 and "" or "s")
        .. " awaiting " .. tostring(pendingProfileDeltaAckMembers) .. " member ACK" .. (pendingProfileDeltaAckMembers == 1 and "" or "s")
        .. (math.max(0, tonumber(queueStatus.queuedProfileDeltaAckMembers) or 0) > 0
          and (" | " .. tostring(math.max(0, tonumber(queueStatus.queuedProfileDeltaAckMembers) or 0))
          .. " received, waiting for combat to end") or "")
        .. (profileDeltaAckSupersededTotal > 0 and (" | " .. tostring(profileDeltaAckSupersededTotal) .. " older tracker" .. (profileDeltaAckSupersededTotal == 1 and "" or "s") .. " superseded") or ""),
      pendingProfileDeltaAcks > 0 and { 0.76, 0.84, 1.00, 1.00 } or { 0.82, 0.84, 0.92, 1.00 },
      pendingProfileDeltaAcks > 0 or profileDeltaAckSupersededTotal > 0
    )

    local criticalReceiptState = RefreshCriticalReceiptRows(frame, queueStatus.criticalReceiptStatus)
    queueStatus.liveCapacityState = RefreshLiveCapacityRows(
      frame,
      queueStatus,
      queueStatus.criticalReceiptStatus,
      criticalReceiptState
    )

    local showAckRecoveryStats = suppressedAckTimeoutDomains > 0
      or coalescedAckTimeoutCallbacks > 0
      or sharedAckTimeoutRecoveryBatches > 0
    SetSyncProgressRow(
      frame,
      "ackRecovery",
      "Suppressed domains " .. tostring(suppressedAckTimeoutDomains)
        .. " | Coalesced callbacks " .. tostring(coalescedAckTimeoutCallbacks)
        .. " | Shared recoveries " .. tostring(sharedAckTimeoutRecoveryBatches)
        .. " (" .. tostring(sharedAckTimeoutRecoveryTransfers) .. " transfers)",
      { 0.58, 0.90, 0.70, 1.00 },
      showAckRecoveryStats
    )

    local timerFallbackParts = {}
    if timerFallbackTotal > 0 then
      timerFallbackParts[#timerFallbackParts + 1] = "Queue " .. tostring(timerFallbackTotal)
        .. (lastTimerFallbackReason ~= "" and (" (" .. lastTimerFallbackReason .. ")") or "")
    end
    if profileAckTimeoutTimerFallbackTotal > 0 then
      timerFallbackParts[#timerFallbackParts + 1] = "ACK " .. tostring(profileAckTimeoutTimerFallbackTotal)
        .. (lastProfileAckTimeoutTimerFallbackReason ~= "" and (" (" .. lastProfileAckTimeoutTimerFallbackReason .. ")") or "")
    end
    if deferredEditorRefreshTimerFallbackTotal > 0 then
      timerFallbackParts[#timerFallbackParts + 1] = "UI " .. tostring(deferredEditorRefreshTimerFallbackTotal)
        .. (lastDeferredEditorRefreshTimerFallbackReason ~= "" and (" (" .. lastDeferredEditorRefreshTimerFallbackReason .. ")") or "")
    end
    do
      local compatFallbackTotal = math.max(0, tonumber(compatTimerStatus.fallbackTotal) or 0)
      local frameFallbackTotal = math.max(0, tonumber(compatTimerStatus.frameFallbackTotal) or 0)
      local immediateFallbackTotal = math.max(0, tonumber(compatTimerStatus.immediateFallbackTotal) or 0)
      local nativeFailureTotal = math.max(0, tonumber(compatTimerStatus.nativeFailureTotal) or 0)
      local lastFallbackReason = TrimText(compatTimerStatus.lastFallbackReason)
      if compatFallbackTotal > 0 then
        timerFallbackParts[#timerFallbackParts + 1] = "Compat " .. tostring(compatFallbackTotal)
          .. " (frame " .. tostring(frameFallbackTotal)
          .. ", immediate " .. tostring(immediateFallbackTotal)
          .. (nativeFailureTotal > 0 and (", native errors " .. tostring(nativeFailureTotal)) or "")
          .. (lastFallbackReason ~= "" and ("; last " .. lastFallbackReason) or "") .. ")"
      end
    end
    SetSyncProgressRow(
      frame,
      "timerFallbacks",
      table.concat(timerFallbackParts, " | "),
      { 1.00, 0.78, 0.62, 1.00 },
      #timerFallbackParts > 0
    )

    SetSyncProgressRow(
      frame,
      "results",
      (outboundSessionTelemetry.active == true and "Session " or "")
        .. tostring(sentTotal) .. " sent / " .. tostring(attemptedTotal) .. " attempted"
        .. " | Throttled " .. tostring(throttledTotal)
        .. " | Failed " .. tostring(failedTotal)
        .. (rejectedPayloadTotal > 0 and ((payloadFallbackRecovered and " | Payload fallbacks " or " | Payload blocked ")
          .. tostring(rejectedPayloadTotal)
          .. (payloadFallbackRecovered and " (latest recovered)" or "")) or "")
        .. (apiFailureTotal > 0 and (" | API terminal " .. tostring(apiFailureTotal)) or "")
        .. (throttleExhaustedTotal > 0 and (" | Throttle terminal " .. tostring(throttleExhaustedTotal)) or "")
        .. (topOutboundOpcodeKind ~= "" and (" | Top " .. topOutboundOpcodeKind .. " " .. tostring(topOutboundOpcodeSent)
          .. " sent / " .. tostring(topOutboundOpcodeQueued) .. " queued (" .. tostring(topOutboundOpcodeBytes) .. " B)") or "")
        .. (archivePressureDeferredTotal > 0 and (" | Archive yielded " .. tostring(archivePressureDeferredTotal)) or "")
        .. (archiveTargetPacingPreemptionsTotal > 0 and (" | Archive target switches "
          .. tostring(archiveTargetPacingPreemptionsTotal)) or "")
        .. (obsoleteProfileQueuePrunedTotal > 0 and (" | Obsolete profile packets pruned "
          .. tostring(obsoleteProfileQueuePrunedTotal)) or "")
        .. (archiveInFlightCoalescedTotal > 0 and (" | Archive in-flight coalesced "
          .. tostring(archiveInFlightCoalescedTotal)) or "")
        .. (archivePreparationCoalescedTotal > 0 and (" | Archive preparation coalesced "
          .. tostring(archivePreparationCoalescedTotal)) or "")
        .. (preparedArchiveRepairCacheEntries > 0 and (" | Archive repair cache "
          .. tostring(preparedArchiveRepairCacheEntries) .. " ready") or "")
        .. (archivePreparationPrunedTotal > 0 and (" | Archive repair cache pruned "
          .. tostring(archivePreparationPrunedTotal)) or "")
        .. (staleSessionBoundPrunedTotal > 0 and (" | Stale session pruned " .. tostring(staleSessionBoundPrunedTotal)) or ""),
      diagnosticResolved and { 0.42, 1.00, 0.52, 1.00 }
        or (failedTotal > 0 and { 1.00, 0.78, 0.62, 1.00 } or { 0.82, 0.84, 0.92, 1.00 })
    )

    local latestDiagnosticText = ""
    if latestDiagnosticKind ~= "" then
      local categoryLabel = lastOutboundIssueCategory
      if categoryLabel == "payload_rejected" then
        categoryLabel = diagnosticResolved and "Payload fallback recovered" or "Payload blocked"
      elseif categoryLabel == "api_failure" then
        categoryLabel = "API failure"
      elseif categoryLabel == "throttle_exhausted" then
        categoryLabel = "Throttle limit"
      elseif categoryLabel == "" then
        categoryLabel = "Outbound event"
      end
      latestDiagnosticText = categoryLabel .. ": " .. latestDiagnosticKind
      if latestDiagnosticBytes > 0 then
        latestDiagnosticText = latestDiagnosticText .. " | " .. tostring(latestDiagnosticBytes) .. " bytes"
      end
      if latestDiagnosticReason ~= "" then
        latestDiagnosticText = latestDiagnosticText .. " | " .. latestDiagnosticReason
      end
      if lastOutboundIssueAt > 0 then
        latestDiagnosticText = latestDiagnosticText .. " | " .. FormatDateTime(lastOutboundIssueAt)
      end
      if diagnosticResolved then
        latestDiagnosticText = latestDiagnosticText .. " | resolved by successful send "
          .. (lastOutboundIssueResolvedTarget ~= "" and ("to " .. lastOutboundIssueResolvedTarget .. " ") or "")
          .. FormatDateTime(lastOutboundIssueResolvedAt)
      else
        latestDiagnosticText = latestDiagnosticText
          .. (queueActive and " | queue active" or " | earlier event; queue idle")
      end
    end
    SetSyncProgressRow(
      frame,
      "lastDiagnostic",
      latestDiagnosticText,
      diagnosticResolved and { 0.42, 1.00, 0.52, 1.00 }
        or (queueActive and { 1.00, 0.78, 0.62, 1.00 } or { 1.00, 0.82, 0.32, 1.00 }),
      latestDiagnosticText ~= ""
    )

    local snapshotBatch = type(queueStatus.profileSnapshotBatch) == "table" and queueStatus.profileSnapshotBatch or {}
    local pendingTargets = math.max(0, tonumber(snapshotBatch.pendingTargets) or 0)
    local pausedTargets = math.max(0, tonumber(snapshotBatch.pausedTargets) or 0)
    local holdRemaining = math.max(0, tonumber(snapshotBatch.holdRemaining) or 0)
    local holdReason = TrimText(snapshotBatch.holdReason)
    local firstQueuedTarget = TrimText(snapshotBatch.firstQueuedTarget)
    local firstQueuedTransferKind = string.upper(TrimText(snapshotBatch.firstQueuedTransferKind))
    local firstQueuedPriority = math.max(0, tonumber(snapshotBatch.firstQueuedPriority) or 0)
    local nextQueuedTransferKind = string.upper(TrimText(snapshotBatch.nextTransferKind))
    local nextQueuedPriority = math.max(0, tonumber(snapshotBatch.nextPriority) or 0)
    local pendingIncomingTransfers = math.max(0, tonumber(snapshotBatch.pendingIncomingTransfers) or 0)
    local incomingSnapshotBytes = math.max(0, tonumber(snapshotBatch.incomingSnapshotBytes) or 0)
    local oldestIncomingTransferAge = math.max(0, tonumber(snapshotBatch.oldestIncomingTransferAge) or 0)
    local longestIncomingTransferIdleSeconds = math.max(0, tonumber(snapshotBatch.longestIncomingTransferIdleSeconds) or 0)
    local incomingSnapshotHealth = string.lower(TrimText(snapshotBatch.incomingSnapshotHealth))
    local incomingSnapshotCleanupTotal = math.max(0, tonumber(snapshotBatch.incomingSnapshotCleanupTotal) or 0)
    local lastIncomingSnapshotCleanupCount = math.max(0, tonumber(snapshotBatch.lastIncomingSnapshotCleanupCount) or 0)
    local incomingSnapshotRejectTotal = math.max(0, tonumber(snapshotBatch.incomingSnapshotRejectTotal) or 0)
    local incomingSnapshotDiagnosticsSessionId = TrimText(snapshotBatch.incomingSnapshotDiagnosticsSessionId)
    local lastIncomingSnapshotRejectReason = TrimText(snapshotBatch.lastIncomingSnapshotRejectReason)
    local lastIncomingSnapshotRejectSender = TrimText(snapshotBatch.lastIncomingSnapshotRejectSender)

    -- Keep raw diagnostics below, but expose the operational conclusion first.
    local health = BuildSyncProgressHealthSummary({
      queueActive = queueActive,
      pending = pending,
      sendRate = sendRate,
      inboundRate = inboundRate,
      pendingIncomingTransfers = pendingIncomingTransfers,
      criticalReceiptWaiting = criticalReceiptState.waiting,
      criticalReceiptUnconfirmed = criticalReceiptState.unconfirmed,
      capacityBlocked = type(queueStatus.liveCapacityState) == "table"
        and queueStatus.liveCapacityState.blocked == true,
      capacityWarning = type(queueStatus.liveCapacityState) == "table"
        and TrimText(queueStatus.liveCapacityState.warning) or "",
      chatLockdownActive = queueStatus.chatLockdownActive == true,
      archivePaused = queueStatus.archiveSyncPaused == true,
      startupHealthErrors = startupHealthErrors,
      startupHealthWarnings = startupHealthWarnings,
      missingProtocolHandlerCount = missingProtocolHandlerCount,
      protocolOwnerMismatchCount = protocolOwnerMismatchCount,
      uncontractedProtocolHandlerCount = uncontractedProtocolHandlerCount,
      prefixRegistrationActiveFailure = queueStatus.prefixRegistrationActiveFailure == true
        and queueStatus.prefixRegistered ~= true,
      optionalApiFailureCount = optionalApiFailureCount,
      incomingSnapshotHealth = incomingSnapshotHealth,
      rejectedPayloadTotal = rejectedPayloadTotal,
      apiFailureTotal = apiFailureTotal,
      throttleExhaustedTotal = throttleExhaustedTotal,
      failedTotal = failedTotal,
      throttledTotal = throttledTotal,
      latestDiagnosticKind = latestDiagnosticKind,
      latestDiagnosticBytes = latestDiagnosticBytes,
      diagnosticResolved = diagnosticResolved,
      diagnosticUnresolved = queueStatus.outboundIssueUnresolved == true
        or TrimText(queueStatus.outboundDiagnosticState) == "unresolved",
      lastOutboundIssueCategory = lastOutboundIssueCategory,
      lastOutboundIssueResolvedTarget = lastOutboundIssueResolvedTarget,
    })
    frame.stateText:SetText("Health: " .. health.label)
    frame.stateText:SetTextColor(health.color[1], health.color[2], health.color[3], health.color[4])
    if frame.SetBackdropBorderColor then
      frame:SetBackdropBorderColor(health.color[1] * 0.8, health.color[2] * 0.8, health.color[3] * 0.8, 0.90)
    end
    frame.healthSummary:SetText(health.summary)
    frame.healthSummary:SetTextColor(health.color[1], health.color[2], health.color[3], health.color[4])
    frame.healthMetrics:SetText(health.metrics)
    frame.healthMetrics:Hide()
    SetSyncProgressHealthCard(frame, "queue", health.cards and health.cards.queue)
    SetSyncProgressHealthCard(frame, "traffic", health.cards and health.cards.traffic)
    SetSyncProgressHealthCard(frame, "delivery", health.cards and health.cards.delivery)
    frame.attentionText:SetText(health.attention)
    frame.attentionText:SetTextColor(health.attentionColor[1], health.attentionColor[2], health.attentionColor[3], health.attentionColor[4])
    frame.__syncAttentionVisible = health.attention ~= ""
    frame.attentionText:SetShown(frame.__syncAttentionVisible)

    local displayedTransferKind = holdRemaining > 0 and firstQueuedTransferKind or nextQueuedTransferKind
    local displayedPriority = holdRemaining > 0 and firstQueuedPriority or nextQueuedPriority
    local queuedPackageLabel = "profile update"
    if displayedTransferKind == "FULL" then
      queuedPackageLabel = "full profile"
    elseif displayedTransferKind == "DOMAINS" then
      queuedPackageLabel = "profile domains"
    elseif displayedTransferKind == "SUBDOMAINS" then
      queuedPackageLabel = "targeted profile data"
    elseif displayedTransferKind == "PATCHES" or displayedTransferKind == "ROWPATCHES" then
      queuedPackageLabel = "profile patch"
    end
    local queuedPriorityLabel = displayedPriority <= 15 and "P1" or (displayedPriority <= 30 and "P2" or "P3")
    local targetsValue = "None queued"
    if pendingTargets > 0 then
      local nextTarget = TrimText(snapshotBatch.nextTarget)
      if nextTarget == "" then
        nextTarget = "next member"
      end
      targetsValue = tostring(pendingTargets) .. " waiting | Next " .. nextTarget
      if holdRemaining > 0 then
        local heldTarget = firstQueuedTarget ~= "" and firstQueuedTarget or nextTarget
        local holdReasonLabel = "roster update"
        if holdReason == "prepare_session" then
          holdReasonLabel = "session preparation"
        elseif holdReason == "manual_invite" then
          holdReasonLabel = "session invite"
        elseif string.sub(holdReason, 1, 5) == "join:" then
          holdReasonLabel = "member joined"
        end
        targetsValue = targetsValue .. " | Join grace " .. tostring(math.ceil(holdRemaining)) .. "s"
          .. " | " .. holdReasonLabel
          .. " | First " .. queuedPriorityLabel .. " " .. queuedPackageLabel .. " -> " .. heldTarget
      else
        targetsValue = targetsValue .. " | " .. queuedPriorityLabel .. " " .. queuedPackageLabel
      end
      if pausedTargets > 0 then
        targetsValue = targetsValue .. " | Archive paused " .. tostring(pausedTargets)
      end
    elseif holdRemaining > 0 then
      targetsValue = "Join grace active for ~" .. tostring(math.ceil(holdRemaining)) .. "s"
    elseif pausedTargets > 0 then
      targetsValue = tostring(pausedTargets) .. " archive target" .. (pausedTargets == 1 and "" or "s") .. " paused"
    end
    if incomingSnapshotCleanupTotal > 0 then
      targetsValue = targetsValue .. " | Inbound cleared " .. tostring(lastIncomingSnapshotCleanupCount)
        .. " (total " .. tostring(incomingSnapshotCleanupTotal) .. ")"
    end
    SetSyncProgressRow(
      frame,
      "targets",
      targetsValue,
      pendingTargets > 0 and { 1.00, 0.82, 0.32, 1.00 }
        or (incomingSnapshotCleanupTotal > 0 and { 0.58, 0.90, 0.70, 1.00 } or { 0.82, 0.84, 0.92, 1.00 })
    )

    if pendingIncomingTransfers > 0 then
      local inboundSnapshotText = tostring(pendingIncomingTransfers) .. " active | " .. FormatOutboundLaneBytes(incomingSnapshotBytes)
        .. " | Oldest " .. tostring(math.floor(oldestIncomingTransferAge)) .. "s"
      local inboundSnapshotColor = { 0.58, 0.90, 0.70, 1.00 }
      if incomingSnapshotHealth == "stalled" then
        inboundSnapshotText = inboundSnapshotText .. " | No chunks " .. tostring(math.floor(longestIncomingTransferIdleSeconds)) .. "s"
        inboundSnapshotColor = { 1.00, 0.82, 0.32, 1.00 }
      else
        inboundSnapshotText = inboundSnapshotText .. " | Receiving"
      end
      SetSyncProgressRow(frame, "inboundSnapshot", inboundSnapshotText, inboundSnapshotColor, true)
    else
      SetSyncProgressRow(frame, "inboundSnapshot", "", nil, false)
    end
    if incomingSnapshotRejectTotal > 0 then
      local rejectText = (incomingSnapshotDiagnosticsSessionId ~= "" and "This session: " or "Current runtime: ")
        .. tostring(incomingSnapshotRejectTotal) .. " rejected"
      if lastIncomingSnapshotRejectReason ~= "" then
        rejectText = rejectText .. " | Last " .. lastIncomingSnapshotRejectReason
      end
      if lastIncomingSnapshotRejectSender ~= "" then
        rejectText = rejectText .. " | " .. lastIncomingSnapshotRejectSender
      end
      SetSyncProgressRow(frame, "inboundSnapshotRejects", rejectText, { 1.00, 0.78, 0.62, 1.00 }, true)
    else
      SetSyncProgressRow(frame, "inboundSnapshotRejects", "", nil, false)
    end

    local leadTransfer = RefreshActiveTransferRows(frame, queueStatus, outboundSessionTelemetry, activeTelemetrySessionId)

    RefreshDeliveryEventRow(frame, queueStatus)

    local getArchiveSyncPaused = type(ResolveOptionalApiFunction) == "function"
      and ResolveOptionalApiFunction("LIDCOUNCIL_GetArchiveSyncPaused")
      or nil
    local setArchiveSyncPaused = type(ResolveOptionalApiFunction) == "function"
      and ResolveOptionalApiFunction("LIDCOUNCIL_SetArchiveSyncPaused")
      or nil
    if type(frame.archivePauseBtn) == "table" then
      local archivePaused = ReadSyncActionValue(editor, nil, "Read archive sync pause state", getArchiveSyncPaused, false) == true
      if frame.__canControlArchiveSync == true then
        frame.archivePauseBtn:Show()
        if frame.archivePauseInfoBtn then
          frame.archivePauseInfoBtn:Show()
        end
        frame.archivePauseBtn:SetText(archivePaused and "Resume Archive Sync" or "Pause Archive Sync")
        frame.archivePauseBtn:SetEnabled(type(setArchiveSyncPaused) == "function")
        frame.archivePauseBtn:SetScript("OnClick", function()
          if frame.__canControlArchiveSync ~= true then
            return
          end
          if not RunSyncAction(editor, nil, archivePaused and "Resume archive sync" or "Pause archive sync", setArchiveSyncPaused, not archivePaused) then
            return
          end
          local getQueueStatus = ResolveOptionalApiFunction("LIDCOUNCIL_GetSessionCommQueueStatus")
          RefreshSyncProgressPanel(editor, ReadSyncActionValue(editor, nil, "Refresh sync queue status", getQueueStatus, {}), {
            canControlArchiveSync = frame.__canControlArchiveSync == true,
            isSessionHost = frame.__isSessionHost == true,
          })
          RefreshSyncManagementSection(editor)
        end)
      else
        frame.archivePauseBtn:Hide()
        if frame.archivePauseInfoBtn then
          frame.archivePauseInfoBtn:Hide()
        end
      end
    end

    local notesText = ""
    local notesColor = { 0.82, 0.84, 0.92, 1.00 }
    if startupHealthStatus.ran == true and startupHealthErrors > 0 then
      local firstProblem = type(startupHealthStatus.problems) == "table"
        and TrimText(startupHealthStatus.problems[1])
        or ""
      notesText = "Startup health found " .. tostring(startupHealthErrors) .. " critical error(s)."
        .. (firstProblem ~= "" and (" " .. firstProblem .. ".") or " Reload the addon before starting a session.")
      notesColor = { 1.00, 0.55, 0.44, 1.00 }
    elseif missingProtocolHandlerCount > 0 or protocolOwnerMismatchCount > 0 or uncontractedProtocolHandlerCount > 0 then
      notesText = "Protocol handler registry is invalid: " .. tostring(missingProtocolHandlerCount) .. " missing handler(s), "
        .. tostring(protocolOwnerMismatchCount) .. " owner mismatch(es), " .. tostring(uncontractedProtocolHandlerCount)
        .. " uncontracted handler(s). Reload the addon before starting a session."
      notesColor = { 1.00, 0.55, 0.44, 1.00 }
    elseif queueStatus.chatLockdownActive == true then
      notesText = "WoW chat lockdown is active. LidCouncil parked " .. tostring(pending)
        .. " queued message(s) without consuming retry budgets; delivery resumes automatically."
      notesColor = { 1.00, 0.82, 0.32, 1.00 }
    elseif queueStatus.archiveSyncPaused == true and pausedTargets > 0 then
      notesText = "Archive sync is paused. Live/bootstrap traffic continues; deferred archive targets resume when you re-enable it."
      notesColor = { 0.80, 0.68, 1.00, 1.00 }
    elseif type(leadTransfer) == "table" and TrimText(leadTransfer.state) == "waiting_ack" then
      notesText = "Send complete. Waiting for the receiver ACK and state refresh."
      notesColor = { 0.76, 0.84, 1.00, 1.00 }
    elseif #lanePressureText > 0 or #opcodePressureText > 0 then
      local pressureSections = {}
      if #lanePressureText > 0 then
        pressureSections[#pressureSections + 1] = "Lanes: " .. table.concat(lanePressureText, "; ")
      end
      if #opcodePressureText > 0 then
        pressureSections[#pressureSections + 1] = "Opcodes: " .. table.concat(opcodePressureText, "; ")
      end
      if queueActive then
        notesText = "Current sync pressure: " .. table.concat(pressureSections, " | ") .. "."
      elseif diagnosticResolved then
        notesText = "Resolved session diagnostic: " .. table.concat(pressureSections, " | ")
          .. ". A later " .. latestDiagnosticKind .. " send succeeded "
          .. (lastOutboundIssueResolvedTarget ~= "" and ("to " .. lastOutboundIssueResolvedTarget .. " ") or "")
          .. "at " .. FormatDateTime(lastOutboundIssueResolvedAt) .. "."
      elseif queueStatus.outboundIssueUnresolved == true
        or TrimText(queueStatus.outboundDiagnosticState) == "unresolved"
      then
        notesText = "Unresolved session diagnostic: " .. table.concat(pressureSections, " | ")
          .. ". The latest outbound issue remains available for retry and review."
      else
        notesText = "Earlier session diagnostic (queue idle): " .. table.concat(pressureSections, " | ")
          .. ". No data is currently blocked or transmitting."
        if lastOutboundIssueAt > 0 then
          notesText = notesText .. " Last outbound event: " .. FormatDateTime(lastOutboundIssueAt) .. "."
        end
      end
      if archivePressureDeferredTotal > 0 then
        notesText = notesText .. " Archive queued " .. tostring(archivePressureDeferredTotal)
          .. " message(s) briefly yielded to protect live/control traffic."
      end
      if diagnosticResolved then
        notesColor = { 0.42, 1.00, 0.52, 1.00 }
      elseif not queueActive then
        notesColor = { 1.00, 0.82, 0.32, 1.00 }
      elseif sessionPressureSeverity == "critical" then
        notesColor = { 1.00, 0.55, 0.44, 1.00 }
      elseif sessionPressureSeverity == "warning" then
        notesColor = { 1.00, 0.78, 0.62, 1.00 }
      else
        notesColor = { 1.00, 0.82, 0.32, 1.00 }
      end
    elseif throttledTotal > 0 and (pending > 0 or queueStatus.busy == true or queueStatus.running == true) then
      notesText = "Throttle detected. LidCouncil requeues throttled messages and retries after at least 1 second."
      notesColor = { 1.00, 0.82, 0.32, 1.00 }
    elseif incomingSnapshotHealth == "stalled" and pendingIncomingTransfers > 0 then
      notesText = "Inbound profile snapshot is waiting for chunks for " .. tostring(math.floor(longestIncomingTransferIdleSeconds))
        .. " seconds. The transfer remains staged and will be discarded only when its session ends or its TTL expires."
      notesColor = { 1.00, 0.82, 0.32, 1.00 }
    elseif inboundHandlerErrorTotal > 0 then
      notesText = "Inbound protocol handlers failed " .. tostring(inboundHandlerErrorTotal) .. " time(s)."
      if lastInboundHandlerErrorKind ~= "" then
        notesText = notesText .. " Last failure: " .. lastInboundHandlerErrorKind
          .. (lastInboundHandlerErrorSender ~= "" and (" from " .. lastInboundHandlerErrorSender) or "") .. "."
      end
      if lastInboundHandlerErrorDetail ~= "" then
        notesText = notesText .. " Error: " .. lastInboundHandlerErrorDetail
      end
      notesColor = { 1.00, 0.55, 0.44, 1.00 }
    elseif queueStatus.inboundMalformedTotal > 0 then
      notesText = "Inbound validation rejected " .. tostring(queueStatus.inboundMalformedTotal)
        .. " malformed packet(s). These packets were not dispatched to a feature handler."
      notesColor = { 1.00, 0.78, 0.62, 1.00 }
    elseif queueStatus.inboundVisibleRateLimitedTotal > 0 then
      notesText = "Inbound burst protection limited " .. tostring(queueStatus.inboundVisibleRateLimitedTotal)
        .. " message(s) using independent per-sender traffic windows."
      if lastInboundRateLimitedKind ~= "" then
        notesText = notesText .. " Last: " .. lastInboundRateLimitedKind
          .. (lastInboundRateLimitedSender ~= "" and (" from " .. lastInboundRateLimitedSender) or "")
          .. (lastInboundRateLimitedLane ~= "" and (" (" .. lastInboundRateLimitedLane .. ")") or "") .. "."
      end
      notesColor = { 0.72, 0.86, 0.92, 1.00 }
    elseif queueStatus.inboundAdmissionDropTotal > 0 then
      notesText = "Inbound admission safely ignored " .. tostring(queueStatus.inboundAdmissionDropTotal)
        .. " context-invalid packet(s) before feature dispatch."
      notesColor = { 0.72, 0.86, 0.92, 1.00 }
    elseif queueStatus.inboundVisibleStaleTotal > 0 then
      notesText = "Inbound protection ignored " .. tostring(queueStatus.inboundVisibleStaleTotal)
        .. " packet(s) bound to a previous session."
      notesColor = { 0.72, 0.86, 0.92, 1.00 }
    elseif inboundRejectedTotal > 0 then
      notesText = "Inbound protection recorded " .. tostring(inboundRejectedTotal)
        .. " historical rejection(s); classified details are shown in the Inbound row."
      if inboundRejectedContractTotal > 0 then
        notesText = notesText .. " " .. tostring(inboundRejectedContractTotal) .. " were truncated known-opcode packet(s)."
      end
      if inboundUnknownOpcodeTotal > 0 then
        notesText = notesText .. " " .. tostring(inboundUnknownOpcodeTotal) .. " used an unknown opcode."
      end
      notesColor = { 1.00, 0.78, 0.62, 1.00 }
    elseif rejectedPayloadTotal > 0 or apiFailureTotal > 0 or throttleExhaustedTotal > 0 then
      local issueParts = {}
      if rejectedPayloadTotal > 0 then
        issueParts[#issueParts + 1] = tostring(rejectedPayloadTotal)
          .. (payloadFallbackRecovered and " payload fallback(s), latest recovered" or " payload block(s)")
      end
      if apiFailureTotal > 0 then
        issueParts[#issueParts + 1] = tostring(apiFailureTotal) .. " terminal API failure(s)"
      end
      if throttleExhaustedTotal > 0 then
        issueParts[#issueParts + 1] = tostring(throttleExhaustedTotal) .. " throttle retry exhaustion(s)"
      end
      notesText = (diagnosticResolved and "Resolved outbound diagnostic: "
          or (outboundIssueScopeSessionId ~= "" and "Current session outbound diagnostics: " or "Outbound diagnostics: "))
        .. table.concat(issueParts, "; ") .. "."
      if lastOutboundIssueCategory ~= "" then
        local categoryLabel = lastOutboundIssueCategory
        if lastOutboundIssueCategory == "payload_rejected" then
          categoryLabel = diagnosticResolved and "payload fallback recovered" or "payload blocked"
        elseif lastOutboundIssueCategory == "api_failure" then
          categoryLabel = "API failure"
        elseif lastOutboundIssueCategory == "throttle_exhausted" then
          categoryLabel = "throttle limit"
        end
        notesText = notesText .. " Latest " .. categoryLabel .. ": " .. lastOutboundIssueKind
        if lastOutboundIssueReason ~= "" then
          notesText = notesText .. " (" .. lastOutboundIssueReason .. ")"
        end
        if lastOutboundIssueBytes > 0 then
          notesText = notesText .. "; " .. tostring(lastOutboundIssueBytes) .. " bytes"
        end
        notesText = notesText .. "."
      elseif lastRejectedPayloadKind ~= "" then
        notesText = notesText .. " Latest payload: " .. lastRejectedPayloadKind
        if lastRejectedPayloadReason ~= "" then
          notesText = notesText .. " (" .. lastRejectedPayloadReason .. ")"
        end
        if lastRejectedPayloadBytes > 0 then
          notesText = notesText .. "; " .. tostring(lastRejectedPayloadBytes) .. " bytes"
        end
        notesText = notesText .. "."
      end
      if diagnosticResolved then
        notesText = notesText .. " A later " .. latestDiagnosticKind .. " send succeeded "
          .. (lastOutboundIssueResolvedTarget ~= "" and ("to " .. lastOutboundIssueResolvedTarget .. " ") or "")
          .. "at " .. FormatDateTime(lastOutboundIssueResolvedAt) .. "."
        notesColor = { 0.42, 1.00, 0.52, 1.00 }
      else
        notesColor = { 1.00, 0.78, 0.62, 1.00 }
      end
    elseif rejectedProtocolFieldTotal > 0 or rejectedProtocolMinimumTotal > 0 then
      if rejectedProtocolFieldTotal > 0 and rejectedProtocolMinimumTotal > 0 then
        notesText = "LidCouncil blocked " .. tostring(rejectedProtocolFieldTotal) .. " oversized and "
          .. tostring(rejectedProtocolMinimumTotal) .. " incomplete locally constructed message(s)."
      elseif rejectedProtocolFieldTotal > 0 then
        notesText = "LidCouncil blocked " .. tostring(rejectedProtocolFieldTotal) .. " locally constructed message(s) that exceeded the protocol field limit."
      else
        notesText = "LidCouncil blocked " .. tostring(rejectedProtocolMinimumTotal) .. " locally constructed message(s) that were missing required fields."
      end
      notesColor = { 1.00, 0.78, 0.62, 1.00 }
    elseif queueStatus.prefixRegistrationActiveFailure == true and queueStatus.prefixRegistered ~= true then
      notesText = "Addon message prefix registration failed " .. tostring(prefixRegistrationFailures) .. " time(s). Check the Blizzard chat API state."
      notesColor = { 1.00, 0.55, 0.44, 1.00 }
    elseif optionalApiFailureCount > 0 then
      notesText = "A non-critical LidCouncil API helper reported " .. tostring(optionalApiFailureCount) .. " failure signature(s); core sync remains active."
      notesColor = { 1.00, 0.78, 0.62, 1.00 }
    elseif lastFailureReason ~= "" and failedTotal > 0 then
      notesText = "Last send issue: " .. lastFailureReason
      notesColor = { 1.00, 0.55, 0.44, 1.00 }
    end
    SetSyncProgressRow(frame, "notes", notesText, notesColor, notesText ~= "")
  end

  local function LayoutSyncProgressPanel(editor, topOffset, rightContentWidth)
    local frame = EnsureSyncProgressPanel(editor)
    if not frame then
      return 0
    end

    local width = math.max(320, tonumber(rightContentWidth) or 320)
    frame:ClearAllPoints()
    frame:SetPoint("TOPLEFT", 18, topOffset)
    frame:SetWidth(width)

    frame.title:ClearAllPoints()
    frame.title:SetPoint("TOPLEFT", 14, -12)

    frame.stateText:ClearAllPoints()
    frame.stateText:SetPoint("TOPRIGHT", -14, -12)

    if frame.archivePauseBtn and frame.__showArchivePauseControl == true then
      frame.archivePauseBtn:ClearAllPoints()
      frame.archivePauseBtn:SetPoint("TOPRIGHT", frame.stateText, "BOTTOMRIGHT", 0, -8)
    end
    if frame.archivePauseInfoBtn and frame.__showArchivePauseControl == true then
      frame.archivePauseInfoBtn:ClearAllPoints()
      frame.archivePauseInfoBtn:SetPoint("RIGHT", frame.archivePauseBtn, "LEFT", -6, 0)
    end

    if frame.refreshNowBtn then
      frame.refreshNowBtn:ClearAllPoints()
      if frame.__showArchivePauseControl == true and frame.archivePauseInfoBtn then
        frame.refreshNowBtn:SetPoint("RIGHT", frame.archivePauseInfoBtn, "LEFT", -6, 0)
      else
        frame.refreshNowBtn:SetPoint("TOPRIGHT", -14, -34)
      end
    end
    if frame.refreshCadenceDropdown then
      frame.refreshCadenceDropdown:ClearAllPoints()
      frame.refreshCadenceDropdown:SetPoint("RIGHT", frame.refreshNowBtn, "LEFT", -6, 0)
    end

    local labelWidth = math.min(118, math.max(88, math.floor(width * 0.18)))
    local valueWidth = math.max(160, width - labelWidth - 34)
    local healthWidth = width - (frame.__showArchivePauseControl == true and 402 or 226)
    frame.healthSummary:ClearAllPoints()
    frame.healthSummary:SetPoint("TOPLEFT", 14, -38)
    frame.healthSummary:SetWidth(math.max(160, healthWidth))

    frame.healthMetrics:Hide()

    local healthCardGap = 6
    local healthCardWidth = math.max(88, math.floor((width - 28 - (healthCardGap * 2)) / 3))
    for index, key in ipairs({ "queue", "traffic", "delivery" }) do
      local card = type(frame.healthCards) == "table" and frame.healthCards[key] or nil
      if type(card) == "table" then
        card:ClearAllPoints()
        card:SetPoint("TOPLEFT", 14 + ((index - 1) * (healthCardWidth + healthCardGap)), -60)
        card:SetSize(healthCardWidth, 42)
        card.label:ClearAllPoints()
        card.label:SetPoint("TOPLEFT", 8, -6)
        card.label:SetWidth(math.max(40, healthCardWidth - 16))
        card.value:ClearAllPoints()
        card.value:SetPoint("TOPLEFT", 8, -22)
        card.value:SetWidth(math.max(40, healthCardWidth - 16))
        card:Show()
      end
    end

    local rowTop = -112
    if frame.attentionText and frame.__syncAttentionVisible == true then
      frame.attentionText:Show()
      frame.attentionText:ClearAllPoints()
      frame.attentionText:SetPoint("TOPLEFT", 14, -108)
      frame.attentionText:SetWidth(math.max(160, width - 28))
      local attentionHeight = math.max(16, math.ceil(frame.attentionText:GetStringHeight() or 0))
      rowTop = -108 - attentionHeight - 8
    elseif frame.attentionText then
      frame.attentionText:Hide()
    end
    local rowGap = 6
    local visibleRowsHeight = 0

    for _, row in ipairs(frame.rows or {}) do
      if row.visible == false then
        row.label:Hide()
        row.value:Hide()
      else
        row.label:Show()
        row.value:Show()
        row.label:ClearAllPoints()
        row.label:SetPoint("TOPLEFT", 14, rowTop)
        row.label:SetWidth(labelWidth)

        row.value:ClearAllPoints()
        row.value:SetPoint("TOPLEFT", 14 + labelWidth, rowTop)
        row.value:SetWidth(valueWidth)

        local rowHeight = math.max(
          16,
          math.ceil(row.label:GetStringHeight() or 0),
          math.ceil(row.value:GetStringHeight() or 0)
        )
        rowTop = rowTop - rowHeight - rowGap
        visibleRowsHeight = visibleRowsHeight + rowHeight + rowGap
      end
    end

    if frame.copyPerformanceBtn and frame.copyPerformanceBtn:IsShown() then
      frame.copyPerformanceBtn:ClearAllPoints()
      frame.copyPerformanceBtn:SetPoint("TOPLEFT", 14, rowTop)
      rowTop = rowTop - 28
    end

    local totalHeight = math.abs(rowTop) + 14
    frame:SetHeight(totalHeight)
    return totalHeight
  end

  local function BuildProfileSyncDifferenceSummary(candidates, isHost)
    candidates = type(candidates) == "table" and candidates or {}
    if #candidates == 0 then
      return "No joined member profile comparisons are available yet. Prepare a session and wait for members to join."
    end

    local sameCount = 0
    local backgroundCount = 0
    local convergedCount = 0
    local issueLines = {}
    for _, candidate in ipairs(candidates) do
      local comparisonKey = GetProfileSyncCandidateComparisonKey(candidate)
      local visibleState = GetProfileSyncCandidateVisibleState(candidate)
      if visibleState == "aligned" or visibleState == "background" or visibleState == "converged" or comparisonKey == "same" then
        sameCount = sameCount + 1
        if visibleState == "background" or candidate.backgroundOnlyLootDifference then
          backgroundCount = backgroundCount + 1
        end
        if visibleState == "converged" then
          convergedCount = convergedCount + 1
        end
      else
        local member = tostring(candidate.memberKey or "Unknown")
        local summary
        if visibleState == "waiting_apply" then
          summary = "Update received; waiting for combat to end"
        elseif visibleState == "member_newer" then
          summary = (isHost and "Member has newer " or "Compared member is newer in ")
            .. GetProfileSyncDomainLabel(GetProfileSyncCandidateDisplayDomainText(candidate, "remote", "shared data"))
        elseif visibleState == "host_newer" then
          summary = (isHost and "Host has newer " or "Your local copy is newer in ")
            .. GetProfileSyncDomainLabel(GetProfileSyncCandidateDisplayDomainText(candidate, "local", "shared data"))
        elseif visibleState == "conflict" then
          summary = "Conflict. Member newer: "
            .. GetProfileSyncDomainLabel(GetProfileSyncCandidateDisplayDomainText(candidate, "remote", "shared data"))
            .. "; " .. (isHost and "Host newer: " or "Local copy newer: ")
            .. GetProfileSyncDomainLabel(GetProfileSyncCandidateDisplayDomainText(candidate, "local", "shared data"))
        elseif visibleState == "lineage" then
          summary = "Different profile lineage"
        else
          summary = "Unknown sync state"
        end
        issueLines[#issueLines + 1] = "- " .. member .. ": " .. summary
      end
    end

    if #issueLines == 0 then
      local text = "All " .. tostring(sameCount) .. " joined member copy/copies currently match the "
        .. (isHost and "host" or "local") .. " live revision counters and checksums."
      if backgroundCount > 0 then
        text = text .. " " .. tostring(backgroundCount)
          .. " member copy/copies still have background loot archive or fun-award history syncing."
      end
      if convergedCount > 0 then
        text = text .. " " .. tostring(convergedCount)
          .. " member copy/copies are already following the latest acknowledged repair generation."
      end
      return text
    end
    local lines = {
      tostring(#issueLines) .. " joined member copy/copies need attention; " .. tostring(sameCount) .. " match the " .. (isHost and "host" or "local") .. " copy.",
    }
    if backgroundCount > 0 then
      lines[#lines + 1] = "- " .. tostring(backgroundCount)
        .. " additional member copy/copies are live-aligned and only continue background loot history sync."
    end
    for index = 1, math.min(#issueLines, 6) do
      lines[#lines + 1] = issueLines[index]
    end
    if #issueLines > 6 then
      lines[#lines + 1] = "- " .. tostring(#issueLines - 6) .. " more difference(s) are hidden in the table below."
    end
    return table.concat(lines, "\n")
  end

  local function RefreshSyncManagementView(editor, context)
    if not editor then
      return
    end

    context = type(context) == "table" and context or {}
    local activeSession = context.activeSession
    local activeSessionIsHost = context.activeSessionIsHost and true or false
    local access = type(context.access) == "table" and context.access or {}
    local syntheticSession = context.syntheticSession and true or false
    local inCombat = type(InCombatLockdown) == "function" and InCombatLockdown() and true or false

    local checkSyncBtn = editor.sessionCheckSyncBtn
    local pushProfileBtn = editor.sessionPushProfileBtn
    local pushHostSessionDataBtn = editor.sessionPushHostSessionDataBtn
    local profileSyncDropdown = editor.sessionProfileSyncMemberDropdown
    local requestProfileBtn = editor.sessionRequestProfileBtn
    local previewProfileBtn = editor.sessionPreviewProfileBtn
    local openSyncDetailBtn = editor.sessionOpenSyncDetailBtn
    local syncBoardBtn = editor.sessionSyncBoardBtn

    ClearSyncActionStatusOverride(editor)

    local getProfileSyncCandidates = ResolveOptionalApiFunction("LIDCOUNCIL_GetActiveProfileSyncCandidates")
    local getProfileSyncStatus = ResolveOptionalApiFunction("LIDCOUNCIL_GetActiveProfileSyncStatus")
    local getQueueStatus = ResolveOptionalApiFunction("LIDCOUNCIL_GetSessionCommQueueStatus")
    local queueStatus = ReadSyncActionValue(editor, nil, "Read sync queue status", getQueueStatus, {})
    local syncCandidates = ReadSyncActionValue(editor, nil, "Read joined member sync state", getProfileSyncCandidates, {})
    local syncStatus = ReadSyncActionValue(editor, nil, "Read shared profile sync status", getProfileSyncStatus, {
      activeSession = activeSession ~= nil,
      isHost = activeSessionIsHost,
    }, syncCandidates)
    queueStatus = type(queueStatus) == "table" and queueStatus or {}
    syncCandidates = type(syncCandidates) == "table" and syncCandidates or {}
    syncStatus = type(syncStatus) == "table" and syncStatus or {
      activeSession = activeSession ~= nil,
      isHost = activeSessionIsHost,
    }
    editor.lootSessionAllSyncCandidates = syncCandidates
    editor.lootSessionProfileSyncStatusData = syncStatus
    editor.lootSessionCommQueueStatusData = queueStatus
    editor.__lidSyncDetailActiveSessionId = TrimText(type(activeSession) == "table" and activeSession.id or "")

    local bootstrapProgressByMember = BuildBootstrapProgressByMember(queueStatus, activeSession)
    local archiveProgressByMember = BuildArchiveDeliveryProgressByMember(queueStatus, activeSession)
    local dashboardCandidates = {}
    for _, candidate in ipairs(syncCandidates or {}) do
      local dashboardCandidate = BuildProfileSyncDashboardCandidate(
        candidate,
        activeSession,
        activeSessionIsHost and access.canManageSession,
        bootstrapProgressByMember,
        archiveProgressByMember
      )
      if type(dashboardCandidate) == "table" then
        candidate.__dashboardComparisonKey = dashboardCandidate.__dashboardComparisonKey
        candidate.__dashboardBootstrapState = dashboardCandidate.__dashboardBootstrapState
        candidate.__dashboardActionLabel = dashboardCandidate.__dashboardActionLabel
        candidate.__dashboardBootstrapProgress = dashboardCandidate.__dashboardBootstrapProgress
        candidate.__dashboardBootstrapProgressColor = dashboardCandidate.__dashboardBootstrapProgressColor
        candidate.__dashboardArchiveProgress = dashboardCandidate.__dashboardArchiveProgress
        candidate.__dashboardArchiveProgressColor = dashboardCandidate.__dashboardArchiveProgressColor
        candidate.__dashboardArchiveAgeSeconds = dashboardCandidate.__dashboardArchiveAgeSeconds
        candidate.__dashboardArchiveScope = dashboardCandidate.__dashboardArchiveScope
        candidate.__dashboardArchivePhase = dashboardCandidate.__dashboardArchivePhase
        candidate.__dashboardArchiveState = dashboardCandidate.__dashboardArchiveState
        candidate.__dashboardDomainStates = dashboardCandidate.__dashboardDomainStates
        dashboardCandidates[#dashboardCandidates + 1] = dashboardCandidate
      end
    end
    editor.lootSessionSyncDashboardCandidates = dashboardCandidates

    local actionableSyncCandidates = {}
    for _, candidate in ipairs(syncCandidates or {}) do
      local comparisonKey = GetProfileSyncCandidateComparisonKey(candidate)
      if comparisonKey == "remote_newer" or comparisonKey == "diverged" then
        actionableSyncCandidates[#actionableSyncCandidates + 1] = candidate
      end
    end
    editor.lootSessionActionableSyncCandidates = actionableSyncCandidates
    editor.lootSessionSyncCandidates = syncCandidates

    if type(INTERNAL_API.LIDCOUNCIL_RefreshLootSessionHostOverridePanel_Impl) == "function" then
      INTERNAL_API.LIDCOUNCIL_RefreshLootSessionHostOverridePanel_Impl(editor, {
        activeSession = activeSession,
        activeSessionIsHost = activeSessionIsHost,
        access = access,
        syntheticSession = syntheticSession,
      })
    end

    local selectedSyncMember = TrimText(editor.lootSessionSelectedSyncMember)
    if not FindProfileSyncCandidateByKey(syncCandidates, selectedSyncMember) then
      selectedSyncMember = TrimText(type(syncCandidates[1]) == "table" and syncCandidates[1].memberKey or "")
      editor.lootSessionSelectedSyncMember = selectedSyncMember
    end
    local selectedSyncCandidate = FindProfileSyncCandidateByKey(syncCandidates, selectedSyncMember)
    editor.lootSessionSelectedSyncCandidate = selectedSyncCandidate
    local selectedSyncCandidateActionable = CanPullProfileSyncCandidate(selectedSyncCandidate)
    local selectedSyncCandidateVisibleState = type(selectedSyncCandidate) == "table"
      and GetProfileSyncCandidateVisibleState(selectedSyncCandidate)
      or ""
    local canSelectProfileSyncCandidate = activeSession and activeSessionIsHost and access.canManageSession and #syncCandidates > 0 and not inCombat
    local selectedScopeModel = RefreshSyncScopePicker(editor, {
      candidate = selectedSyncCandidate,
      isHost = activeSessionIsHost and access.canManageSession,
    })
    local selectedScopeActions = type(selectedScopeModel) == "table" and type(selectedScopeModel.actions) == "table"
      and selectedScopeModel.actions
      or {}
    editor.lootSessionSelectedScopeActions = selectedScopeActions
    editor.lootSessionSelectedScopeHint = type(selectedScopeModel) == "table" and TrimText(selectedScopeModel.selectionHint) or ""

    if profileSyncDropdown then
      profileSyncDropdown:SetMenuBuilder(function(dropdown)
        local entries = {}
        for _, candidate in ipairs(editor.lootSessionSyncCandidates or {}) do
          local memberLabel = BuildProfileSyncCandidateLabel(candidate)
          entries[#entries + 1] = {
            text = memberLabel,
            searchText = BuildProfileSyncCandidateSearchText(candidate),
            checked = TrimText(candidate.memberKey) == TrimText(editor.lootSessionSelectedSyncMember),
            func = function()
              editor.lootSessionSelectedSyncMember = TrimText(candidate.memberKey)
              dropdown:SetSelectedValue(editor.lootSessionSelectedSyncMember)
              dropdown:SetText(memberLabel)
              RefreshSyncManagementSection(editor)
            end,
          }
        end
        return {
          width = math.max(320, tonumber(dropdown.dropdownWidth) or 320),
          enableSearch = true,
          searchPlaceholder = "Search joined member",
          entries = entries,
        }
      end)
      profileSyncDropdown:SetSelectedValue(selectedSyncCandidate and selectedSyncCandidate.memberKey or nil)
      profileSyncDropdown:SetText(
        selectedSyncCandidate and BuildProfileSyncCandidateLabel(selectedSyncCandidate)
          or "No joined member comparisons available"
      )
      if profileSyncDropdown.SetEnabled then
        profileSyncDropdown:SetEnabled(canSelectProfileSyncCandidate)
      elseif profileSyncDropdown.button and profileSyncDropdown.button.Enable then
        if canSelectProfileSyncCandidate then
          profileSyncDropdown.button:Enable()
        else
          profileSyncDropdown.button:Disable()
        end
      end
    end

    RefreshSyncDashboard(editor, {
      candidates = dashboardCandidates,
      syncStatus = syncStatus,
      isHost = activeSessionIsHost and access.canManageSession,
    })

    local pushScopeAction = type(selectedScopeActions.push) == "table" and selectedScopeActions.push or {}
    local pullScopeAction = type(selectedScopeActions.pull) == "table" and selectedScopeActions.pull or {}
    local previewScopeAction = type(selectedScopeActions.preview) == "table" and selectedScopeActions.preview or {}
    local selectedRecommendation = type(selectedSyncCandidate) == "table" and type(selectedSyncCandidate.safeRecommendation) == "table"
      and selectedSyncCandidate.safeRecommendation
      or nil
    local detailDiff, detailConflict = GetInlinePreviewState(syncStatus, selectedSyncCandidate)
    local previewReady = type(detailDiff) == "table" or type(detailConflict) == "table"

    if checkSyncBtn and checkSyncBtn.Enable then
      if type(selectedSyncCandidate) == "table" and TrimText(selectedSyncCandidate.preciseRequestState) == "waiting" then
        checkSyncBtn:SetText("Waiting for Precise Reply")
      elseif type(selectedSyncCandidate) == "table" and TrimText(selectedSyncCandidate.preciseRequestState) == "failed" then
        checkSyncBtn:SetText("Retry Precise Differences")
      elseif type(selectedSyncCandidate) == "table" and selectedSyncCandidate.preciseResponseComplete == true then
        checkSyncBtn:SetText("Refresh Precise Differences")
      else
        checkSyncBtn:SetText("Load Precise Differences")
      end
      if activeSession and activeSessionIsHost and access.canManageSession and not inCombat
        and not (type(selectedSyncCandidate) == "table" and TrimText(selectedSyncCandidate.preciseRequestState) == "waiting") then
        checkSyncBtn:Enable()
      else
        checkSyncBtn:Disable()
      end
    end
    if pushProfileBtn and pushProfileBtn.Enable then
      local queueBusy = type(queueStatus) == "table" and (queueStatus.busy == true or math.max(0, tonumber(queueStatus.pending) or 0) > 0)
      pushProfileBtn.__lidDisabledReason = nil
      pushProfileBtn:SetText(
        pushScopeAction.selectionActive and pushScopeAction.compatibleCount > 0
          and ("Push Repair (" .. tostring(pushScopeAction.compatibleCount) .. ")")
          or "Push Host Repair"
      )
      if activeSession and activeSessionIsHost and access.canManageSession and not inCombat and not queueBusy
        and selectedSyncCandidateVisibleState ~= "waiting_apply"
        and not (type(selectedSyncCandidate) == "table" and selectedSyncCandidate.preciseNoDifferences == true)
        and not (type(selectedSyncCandidate) == "table"
          and (TrimText(selectedSyncCandidate.preciseRequestState) == "waiting"
            or TrimText(selectedSyncCandidate.preciseRequestState) == "failed"))
        and (not pushScopeAction.selectionActive or pushScopeAction.compatibleCount > 0) then
        pushProfileBtn:Enable()
      else
        pushProfileBtn:Disable()
        if inCombat then
          pushProfileBtn.__lidDisabledReason = "Repair controls are unavailable during combat."
        elseif not activeSession or not activeSessionIsHost or not access.canManageSession then
          pushProfileBtn.__lidDisabledReason = "Only the active session host can push profile repair data."
        elseif queueBusy or selectedSyncCandidateVisibleState == "waiting_apply" then
          pushProfileBtn.__lidDisabledReason = "Another sync transfer is still queued or waiting to be applied."
        elseif pushScopeAction.selectionActive and pushScopeAction.compatibleCount == 0 then
          pushProfileBtn.__lidDisabledReason = "The checked scopes are classified as Pull Member or Preview First. Push requires host-newer evidence for those exact scopes; a mixed Loot domain must be resolved from the nested preview rows."
        elseif type(selectedSyncCandidate) == "table" and TrimText(selectedSyncCandidate.preciseRequestState) == "waiting" then
          pushProfileBtn.__lidDisabledReason = "Precise checksum evidence is still loading."
        elseif type(selectedSyncCandidate) == "table" and TrimText(selectedSyncCandidate.preciseRequestState) == "failed" then
          pushProfileBtn.__lidDisabledReason = "The precise checksum request failed. Retry Precise Differences first."
        else
          pushProfileBtn.__lidDisabledReason = "No host-newer repair scope is currently proven for the selected member."
        end
      end
    end
    if pushHostSessionDataBtn and pushHostSessionDataBtn.Enable then
      local queueBusy = type(queueStatus) == "table" and (queueStatus.busy == true or math.max(0, tonumber(queueStatus.pending) or 0) > 0)
      local hasSelectedMember = TrimText(type(selectedSyncCandidate) == "table" and selectedSyncCandidate.memberKey or "") ~= ""
      if activeSession and activeSessionIsHost and access.canManageSession and not inCombat and not queueBusy
        and hasSelectedMember and selectedSyncCandidateVisibleState ~= "waiting_apply" then
        pushHostSessionDataBtn:Enable()
      else
        pushHostSessionDataBtn:Disable()
      end
    end
    if requestProfileBtn and requestProfileBtn.Enable then
      requestProfileBtn.__lidDisabledReason = nil
      if pullScopeAction.selectionActive and pullScopeAction.compatibleCount > 0 then
        requestProfileBtn:SetText("Pull Repair (" .. tostring(pullScopeAction.compatibleCount) .. ")")
      else
        requestProfileBtn:SetText(GetProfileSyncRequestButtonText(selectedSyncCandidate))
      end
      if activeSession and activeSessionIsHost and access.canManageSession and not inCombat
        and not (type(selectedSyncCandidate) == "table" and selectedSyncCandidate.preciseNoDifferences == true)
        and not (type(selectedSyncCandidate) == "table"
          and (TrimText(selectedSyncCandidate.preciseRequestState) == "waiting"
            or TrimText(selectedSyncCandidate.preciseRequestState) == "failed"))
        and ((pullScopeAction.selectionActive and pullScopeAction.compatibleCount > 0) or (not pullScopeAction.selectionActive and selectedSyncCandidateActionable)) then
        requestProfileBtn:Enable()
      else
        requestProfileBtn:Disable()
        if inCombat then
          requestProfileBtn.__lidDisabledReason = "Repair controls are unavailable during combat."
        elseif not activeSession or not activeSessionIsHost or not access.canManageSession then
          requestProfileBtn.__lidDisabledReason = "Only the active session host can pull member profile data."
        elseif pullScopeAction.selectionActive and pullScopeAction.compatibleCount == 0 then
          requestProfileBtn.__lidDisabledReason = "The checked scopes are not proven member-newer scopes. If both copies changed the same Loot domain, preview the exact nested rows and apply only the member values you intend to keep."
        elseif type(selectedSyncCandidate) == "table" and TrimText(selectedSyncCandidate.preciseRequestState) == "waiting" then
          requestProfileBtn.__lidDisabledReason = "Precise checksum evidence is still loading."
        elseif type(selectedSyncCandidate) == "table" and TrimText(selectedSyncCandidate.preciseRequestState) == "failed" then
          requestProfileBtn.__lidDisabledReason = "The precise checksum request failed. Retry Precise Differences first."
        else
          requestProfileBtn.__lidDisabledReason = "No member-newer repair scope is currently proven. Preview First is required for conflicts or uncertain ordering."
        end
      end
    end
    if previewProfileBtn and previewProfileBtn.Enable then
      previewProfileBtn.__lidDisabledReason = nil
      local hasSelectedPreviewScopes = previewScopeAction.selectionActive and previewScopeAction.compatibleCount > 0
      local canPreviewSelectedScopes = hasSelectedPreviewScopes and selectedSyncCandidateVisibleState ~= "waiting_apply"
      local canPreviewCandidate = not previewScopeAction.selectionActive
        and not (type(selectedSyncCandidate) == "table" and selectedSyncCandidate.preciseNoDifferences == true)
        and not (type(selectedSyncCandidate) == "table"
          and (TrimText(selectedSyncCandidate.preciseRequestState) == "waiting"
            or TrimText(selectedSyncCandidate.preciseRequestState) == "failed"))
        and selectedSyncCandidateVisibleState ~= "host_newer"
        and selectedSyncCandidateVisibleState ~= "aligned"
        and selectedSyncCandidateVisibleState ~= "converged"
        and selectedSyncCandidateVisibleState ~= "background"
        and selectedSyncCandidateVisibleState ~= "waiting_apply"
      if previewScopeAction.selectionActive and previewScopeAction.compatibleCount > 0 then
        previewProfileBtn:SetText("Preview Selected Differences (" .. tostring(previewScopeAction.compatibleCount) .. ")")
      elseif selectedSyncCandidate then
        previewProfileBtn:SetText("Preview Loaded Differences")
      else
        previewProfileBtn:SetText("Select Member First")
      end
      if activeSession and activeSessionIsHost and access.canManageSession and selectedSyncCandidate and not inCombat
        and (canPreviewSelectedScopes or canPreviewCandidate) then
        -- Explicitly selected loaded differences are safe to inspect even when
        -- a coarse status has already moved to a background-sync label.
        previewProfileBtn:Enable()
      else
        previewProfileBtn:Disable()
        if inCombat then
          previewProfileBtn.__lidDisabledReason = "Difference previews are unavailable during combat."
        elseif not activeSession or not activeSessionIsHost or not access.canManageSession then
          previewProfileBtn.__lidDisabledReason = "Only the active session host can request a member preview."
        elseif not selectedSyncCandidate then
          previewProfileBtn.__lidDisabledReason = "Select a joined member first."
        elseif previewScopeAction.selectionActive and previewScopeAction.compatibleCount == 0 then
          previewProfileBtn.__lidDisabledReason = "None of the checked scopes currently has preview evidence. Refresh Precise Differences and select a listed Preview First scope."
        elseif selectedSyncCandidateVisibleState == "waiting_apply" then
          previewProfileBtn.__lidDisabledReason = "A received repair is still waiting to be applied."
        elseif previewReady then
          previewProfileBtn.__lidDisabledReason = "The selected preview is already loaded below. Use its nested rows to choose the values to apply."
        else
          previewProfileBtn.__lidDisabledReason = "There is no unresolved difference available to preview."
        end
      end
    end
    if openSyncDetailBtn and openSyncDetailBtn.Enable then
      if not openSyncDetailBtn.__lidSyncDetailHooked then
        openSyncDetailBtn.__lidSyncDetailHooked = true
        openSyncDetailBtn:SetScript("OnClick", function()
          local candidate = editor.lootSessionSelectedSyncCandidate
          if type(candidate) == "table" and type(OpenProfileSyncDetailPopup) == "function" then
            OpenProfileSyncDetailPopup(editor, candidate)
          end
        end)
      end
      if previewReady and not inCombat then
        openSyncDetailBtn:SetText("Open Sync Detail")
        openSyncDetailBtn:Enable()
      elseif selectedSyncCandidate then
        openSyncDetailBtn:SetText("Preview Selected Data First")
        openSyncDetailBtn:Disable()
      else
        openSyncDetailBtn:SetText("Select Member First")
        openSyncDetailBtn:Disable()
      end
    end
    if syncBoardBtn and syncBoardBtn.Enable then
      if activeSession and not syntheticSession and activeSessionIsHost and access.canManageSession and not inCombat then
        syncBoardBtn:Enable()
      else
        syncBoardBtn:Disable()
      end
    end

    if editor.lootSessionTitle then
      editor.lootSessionTitle:SetText("Sync Management")
    end
    if editor.lootSessionStatus then
      if not activeSession then
        editor.lootSessionStatus:SetText("No active session")
        editor.lootSessionStatus:SetTextColor(1.00, 0.35, 0.25, 1.00)
        ApplyTrafficLight(editor.lootSessionStatusIndicator, "PENDING")
      elseif syntheticSession and activeSessionIsHost and access.canManageSession then
        editor.lootSessionStatus:SetText("Developer synthetic sync controls available")
        editor.lootSessionStatus:SetTextColor(0.38, 0.72, 1.00, 1.00)
        ApplyTrafficLight(editor.lootSessionStatusIndicator, "PARTIAL")
      elseif activeSessionIsHost and access.canManageSession and inCombat then
        editor.lootSessionStatus:SetText("Manual sync locked during combat")
        editor.lootSessionStatus:SetTextColor(1.00, 0.82, 0.32, 1.00)
        ApplyTrafficLight(editor.lootSessionStatusIndicator, "PARTIAL")
      elseif activeSessionIsHost and access.canManageSession then
        editor.lootSessionStatus:SetText("Host sync controls available")
        editor.lootSessionStatus:SetTextColor(0.20, 0.90, 0.20, 1.00)
        ApplyTrafficLight(editor.lootSessionStatusIndicator, "SYNCED")
      else
        editor.lootSessionStatus:SetText("Read-only sync overview")
        editor.lootSessionStatus:SetTextColor(1.00, 0.82, 0.32, 1.00)
        ApplyTrafficLight(editor.lootSessionStatusIndicator, "PARTIAL")
      end
    end

    if editor.lootSessionProfileSyncStatus then
      local statusText = BuildProfileSyncStatusText(syncStatus)
      if inCombat and activeSessionIsHost and access.canManageSession then
        if TrimText(statusText) ~= "" then
          statusText = statusText .. "\n"
        end
        statusText = statusText .. "Manual sync actions are disabled during combat."
      elseif syntheticSession then
        if TrimText(statusText) ~= "" then
          statusText = statusText .. "\n"
        end
        statusText = statusText .. "Developer synthetic mode uses hidden scratch profiles, so preview, pull, and push repair rehearsal does not modify the real source profile."
      end
      local r, g, b, a = GetProfileSyncStatusColor(syncStatus.severity)
      local candidateCounts = type(syncStatus.candidateCounts) == "table" and syncStatus.candidateCounts or {}
      local bootstrapCounts = type(syncStatus.bootstrapCounts) == "table" and syncStatus.bootstrapCounts or {}
      local onlyRollReadyReview = (tonumber(candidateCounts.diverged) or 0) > 0
        and (tonumber(candidateCounts.remote_newer) or 0) == 0
        and (tonumber(candidateCounts.local_newer) or 0) == 0
        and (tonumber(candidateCounts.waiting_apply) or 0) == 0
        and (tonumber(bootstrapCounts.pending) or 0) == 0
        and (tonumber(bootstrapCounts.review) or 0) == 0
      if onlyRollReadyReview then
        r, g, b, a = 1.00, 0.82, 0.32, 1.00
      end
      if IsTutorialModeEnabled() and string.lower(TrimText(syncStatus.severity)) == "info" then
        r, g, b, a = 1.00, 0.82, 0.24, 1.00
      end
      editor.lootSessionProfileSyncStatus:SetText(statusText)
      editor.lootSessionProfileSyncStatus:SetTextColor(r, g, b, a)
    end
    ApplySyncActionStatusOverride(editor)
    if editor.lootSessionSyncSelectedHint then
      local hintText = activeSession and BuildSelectedProfileSyncHint(selectedSyncCandidate, activeSessionIsHost and access.canManageSession) or ""
      if TrimText(editor.lootSessionSelectedScopeHint) ~= "" then
        if hintText ~= "" then
          hintText = hintText .. "\n"
        end
        hintText = hintText .. editor.lootSessionSelectedScopeHint
      end
      if type(selectedRecommendation) == "table" and TrimText(selectedRecommendation.label) ~= "" then
        if hintText ~= "" then
          hintText = hintText .. "\n"
        end
        local recommendationLine = TrimText(selectedRecommendation.label):gsub("^Run Recommended Repair:%s*", "")
        if not recommendationLine:find("^Recommended:") then
          recommendationLine = "Recommended: " .. recommendationLine
        end
        hintText = hintText .. recommendationLine .. ". " .. tostring(TrimText(selectedRecommendation.reason))
      end
      editor.lootSessionSyncSelectedHint:SetText(hintText)
      local hintColorKey = type(selectedSyncCandidate) == "table"
        and GetProfileSyncVisibleComparisonColorKey(selectedSyncCandidate)
        or ""
      local hr, hg, hb, ha = GetProfileSyncComparisonColor(hintColorKey)
      if hintColorKey == "diverged"
        and string.lower(GetProfileSyncCandidateDisplayBootstrapState(selectedSyncCandidate)) == "ready" then
        -- A roll-ready history conflict needs review, but does not block the raid.
        hr, hg, hb, ha = 1.00, 0.82, 0.32, 1.00
      end
      if hintText == "" then
        hr, hg, hb, ha = 0.82, 0.82, 0.86, 1.00
      end
      editor.lootSessionSyncSelectedHint:SetTextColor(hr, hg, hb, ha)
    end

    SetRecommendedActionHighlight(checkSyncBtn, false)
    SetRecommendedActionHighlight(pushProfileBtn, false)
    SetRecommendedActionHighlight(pushHostSessionDataBtn, false)
    SetRecommendedActionHighlight(requestProfileBtn, false)
    SetRecommendedActionHighlight(previewProfileBtn, false)
    SetRecommendedActionHighlight(openSyncDetailBtn, false)
    if previewReady then
      SetRecommendedActionHighlight(openSyncDetailBtn, true)
    else
      local recommendationAction = string.lower(TrimText(type(selectedRecommendation) == "table" and selectedRecommendation.action or ""))
      if recommendationAction == "check" then
        SetRecommendedActionHighlight(checkSyncBtn, true)
      elseif recommendationAction == "push" then
        SetRecommendedActionHighlight(pushProfileBtn, true)
      elseif recommendationAction == "pull" then
        SetRecommendedActionHighlight(requestProfileBtn, true)
      elseif recommendationAction == "preview" then
        SetRecommendedActionHighlight(previewProfileBtn, true)
      end
    end

    RefreshSyncProgressPanel(editor, queueStatus, {
      canControlArchiveSync = activeSession ~= nil and activeSessionIsHost and access.canManageSession == true,
      isSessionHost = activeSessionIsHost,
    })
    RefreshSyncHistoryPanel(editor, {
      activeSession = activeSession,
      activeSessionIsHost = activeSessionIsHost,
      access = access,
      inCombat = inCombat,
    })
    if type(Compat) == "table" and type(Compat.After) == "function"
        and type(editor.lootSessionSyncProgressFrame) == "table"
        and math.max(0, tonumber(editor.lootSessionSyncProgressFrame.__syncRefreshSeconds) or 0) > 0
        and not editor.__lootSessionSyncProgressRefreshDueAt then
      editor.__lootSessionSyncProgressRefreshDueAt = (type(GetTime) == "function" and GetTime() or 0)
        + math.max(1, tonumber(editor.lootSessionSyncProgressFrame.__syncRefreshSeconds) or 1)
      Compat.After(math.max(1, tonumber(editor.lootSessionSyncProgressFrame.__syncRefreshSeconds) or 1), function()
        if editor then
          local currentTime = type(GetTime) == "function" and GetTime() or 0
          local dueAt = tonumber(editor.__lootSessionSyncProgressRefreshDueAt) or 0
          if dueAt > currentTime + 0.05 then
            return
          end
          editor.__lootSessionSyncProgressRefreshDueAt = nil
          if string.upper(TrimText(editor.lootSessionSection or "")) == "SYNCMGMT" then
            local progressFrame = editor.lootSessionSyncProgressFrame
            local refreshSeconds = type(progressFrame) == "table"
              and math.max(0, tonumber(progressFrame.__syncRefreshSeconds) or 0)
              or 0
            if refreshSeconds <= 0 then
              return
            elseif type(InCombatLockdown) == "function" and InCombatLockdown() then
              editor.__lootSessionSyncProgressRefreshDeferred = true
            else
              editor.__lootSessionSyncProgressRefreshDeferred = nil
              RefreshSyncManagementSection(editor)
            end
          end
        end
      end)
    end

    if editor.lootSessionSyncIntro then
      editor.lootSessionSyncIntro:SetText(
        "Work top to bottom: select a member, load and choose differences, preview them, then open Sync Detail to resolve them. Roll-ready status is separate from background history sync."
      )
    end
    if editor.lootSessionSyncCheckHeader then
      editor.lootSessionSyncCheckHeader:SetText("1. Review Joined Members")
    end
    if editor.lootSessionSyncPushHeader then
      editor.lootSessionSyncPushHeader:SetText("2. Select Member and Difference Scopes")
    end
    local pushHelp = EnsurePushScopeHelp(editor)
    if pushHelp then
      pushHelp:SetText("")
      pushHelp:Hide()
    end
    if editor.lootSessionSyncPullHeader then
      editor.lootSessionSyncPullHeader:SetText("3. Preview Selected Differences")
    end
    if editor.lootSessionSyncResolveHeader then
      editor.lootSessionSyncResolveHeader:SetText("4. Review and Resolve Preview")
    end
    if editor.lootSessionSyncAdvancedHeader then
      editor.lootSessionSyncAdvancedHeader:SetText("Advanced Repairs and Recovery")
    end
    if editor.lootSessionSyncAutoHeader then
      editor.lootSessionSyncAutoHeader:SetText("Existing Sync Workflow Notes")
    end
    if editor.lootSessionSyncAutoText then
      editor.lootSessionSyncAutoText:SetText(ApplyDeveloperAccentMarkup(
        "|cffa87ae81. Player 1 starts a session|r\n" ..
        "- LidCouncil sends a session invite to the current party, raid, or instance group.\n" ..
        "- Synced with the invite: session ID, profile name, profile ID, host, session start time, and profile master.\n" ..
        "- Roll options are not sent in the invite itself. They come from the shared profile copy that already exists locally or from the automatic host snapshot after join.\n\n" ..
        "|cffa87ae82. Player 1 sends Session Invite later|r\n" ..
        "- The |cff4adf6bCurrent Session -> Send Session Invite|r button repeats the same invite for late joiners.\n" ..
        "- No profile data is pushed yet. The real profile sync starts only after the player accepts and joins.\n\n" ..
        "|cffa87ae83. Player 2 accepts the invite|r\n" ..
        "- The join reply syncs the member snapshot to the host: character key, joined time, addon/client version, class/spec, personal Auto Pass state, shared profile ID, revision counters, and checksums for |cff4adf6bSettings|r, |cff4adf6bPermissions|r, |cff4adf6bLoot Data|r, and the broad |cff4adf6bSession domain|r (Current Session State plus Session History).\n" ..
        "- The host compares that member copy against the host copy immediately.\n\n" ..
        "|cffa87ae84. Load Precise Differences|r\n" ..
        "- Host only.\n" ..
        "- Requests detailed leaf checksum scopes for only the mismatched joined members.\n" ..
        "- LidCouncil also refreshes these scopes automatically when a joined member reports mismatched state.\n" ..
        "- No profile data is replaced during this step. It only prepares smaller repair scopes for the buttons below.\n" ..
        "- The picker reports waiting progress, terminal timeout, a completed no-difference result, or actionable leaf rows. Empty is never treated as successful repair evidence.\n" ..
        "- The dashboard |cff4adf6bReady|r column is separate from full sync: it turns green once |cff4adf6bSettings|r and |cff4adf6bPermissions|r are aligned enough for roll choices, even if Loot or Session history is still catching up.\n" ..
        "- Once those scopes are loaded, first choose the joined member in the Leaf Scope Picker section, then click one or more leaf rows to narrow Push / Pull / Preview to exact leaves.\n\n" ..
        "|cffa87ae85. Automatic shared profile repair on join|r\n" ..
        "- If the joiner has no local shared copy, the host automatically sends a smaller |cff4adf6bSettings + Permissions|r bootstrap first so roll choices can unlock sooner.\n" ..
        "- After that bootstrap, the remaining |cff4adf6bLoot Data|r and |cff4adf6bSession domain|r (Current Session State plus Session History) continue syncing in the background.\n" ..
        "- If the joiner has an older copy of the same profile lineage, the host automatically sends only the newer host domains when that is enough.\n" ..
        "- If the joiner has newer or diverged data, nothing is overwritten automatically. Review is required first.\n\n" ..
        "|cffa87ae86. Automatic runtime session sync|r\n" ..
        "- While the session is active, LidCouncil automatically syncs joined member status, personal Auto Pass changes, live roll choices, council votes, awards, unassigns, and the active Live Board state.\n" ..
        "- When the host stops the session, the automatic session sync flow ends."
      ))
    end
    if editor.lootSessionSyncManualHeader then
      editor.lootSessionSyncManualHeader:SetText("Manual Sync Reference")
    end
    if editor.lootSessionSyncManualText then
      editor.lootSessionSyncManualText:SetText(ApplyDeveloperAccentMarkup(
        "|cffa87ae81. Leaf Scope Picker|r\n" ..
        "- Host only.\n" ..
        "- Choose the joined member you want to inspect or repair.\n" ..
        "- Use the dashboard |cff4adf6bReady|r column when you want to see who can already receive roll choices before the rest of the shared history fully finishes.\n" ..
        "- Click individual leaf rows to narrow Push / Pull / Preview to exact scopes.\n" ..
        "- LidCouncil highlights the currently safest next action in yellow directly on the matching repair button below.\n" ..
        "- Leaving every row clear keeps broader repair behavior only before a precise request has started. Waiting, failed, and completed no-difference results fail closed.\n\n" ..
        "|cffa87ae82. Push Host Repair|r\n" ..
        "- Host only.\n" ..
        "- Sends your current host copy only for the domains that the host is newer in. Member-newer and conflict scopes are skipped for safety.\n" ..
        "- If Load Precise Differences loaded precise leaf scopes, only those smaller scopes are sent. Domain-level fallback remains available only before a precise request establishes a terminal result.\n" ..
        "- If you tick individual rows in the Leaf Scope Picker, only those compatible selected leaves are pushed to the selected member. A completed empty comparison sends nothing; use the explicit Host Session History action only when archive replacement is intentional.\n" ..
        "- The nested Sync Detail resolver can also apply selected member rows to the host and immediately queue direct host repair for the affected leaf scopes.\n" ..
        "- For brand-new joiners without a shared copy, LidCouncil now prioritizes a smaller bootstrap first and lets the heavier loot/session history continue afterward.\n" ..
        "- Shared content: |cff4adf6bSettings|r, |cff4adf6bPermissions|r, |cff4adf6bLoot Data|r, and the |cff4adf6bSession domain|r (Current Session State plus Session History) for the active shared profile.\n\n" ..
        "|cffa87ae83. Pull Member Repair|r\n" ..
        "- Host only.\n" ..
        "- Requests only the selected joined-member scopes that are newer than the host copy.\n" ..
        "- If Load Precise Differences already loaded precise leaf scopes, the pull can be limited to those smaller scopes.\n" ..
        "- If you tick individual rows in the Leaf Scope Picker, only those compatible selected leaves are pulled from the selected member. Broader member repair remains available only before a precise request enters waiting, failed, or completed no-difference state.\n" ..
        "- Applies the selected joined member repair snapshot to your local host copy.\n" ..
        "- Use this only after the difference table or preview confirms you want their copy.\n\n" ..
        "|cffa87ae84. Preview Member Repair|r\n" ..
        "- Host only.\n" ..
        "- Requests the differing joined-member scopes for inspection only.\n" ..
        "- If you tick individual rows in the Leaf Scope Picker, preview is narrowed to those selected leaves for the current member.\n" ..
        "- This fills the Sync Detail popup with concrete differences and does |cffff5a5anot|r replace your local host copy.\n\n" ..
        "|cffa87ae85. Send Board Sync|r\n" ..
        "- Host only.\n" ..
        "- Sends only the current Live Board recovery snapshot: dropped items, selected board item, voting state, and assignment state.\n" ..
        "- It does |cffff5a5anot|r replace profile settings, permissions, loot ledger history, or point rules.\n" ..
        "- Use it when the board is desynced after a reload, UI error, or crash.\n\n" ..
        "|cffa87ae86. Repair History and Undo|r\n" ..
        "- Host only.\n" ..
        "- Recent host-side repair applies are listed with timestamps so you can see what changed and from which joined member it came.\n" ..
        "- Undo reimports the last host-side repair snapshot for the active shared profile only. It is a local host safety net, not a raid-wide rollback."
      ))
    end
    if editor.lootSessionSyncReviewEmpty then
      if not activeSession then
        editor.lootSessionSyncReviewEmpty:SetText("Start a session to compare joined shared copies.")
      elseif #(editor.lootSessionAllSyncCandidates or {}) > 0 then
        editor.lootSessionSyncReviewEmpty:SetText("")
      else
        editor.lootSessionSyncReviewEmpty:SetText("No joined member profile comparisons are available yet.")
      end
    end
    if editor.lootSessionSyncDetailPopup and editor.lootSessionSyncDetailPopup:IsShown() and type(editor.lootSessionSyncDetailPopup.__candidate) == "table" then
      RefreshProfileSyncDetailPopup(editor, editor.lootSessionSyncDetailPopup, editor.lootSessionSyncDetailPopup.__candidate, syncStatus)
    end
  end

  local function LayoutSyncManagementSection(editor, page, rightContentWidth)
    if not editor then
      return 220
    end

    local progressTop = -78
    local progressHeight = LayoutSyncProgressPanel(editor, progressTop, rightContentWidth)

    local checkHeaderTop = progressTop - progressHeight - 24
    if editor.lootSessionSyncCheckHeader then
      editor.lootSessionSyncCheckHeader:ClearAllPoints()
      editor.lootSessionSyncCheckHeader:SetPoint("TOPLEFT", 18, checkHeaderTop)
    end

    local syncIntro = editor.lootSessionSyncIntro
    local introTop = checkHeaderTop - 26
    local introHeight = 0
    if syncIntro then
      syncIntro:ClearAllPoints()
      syncIntro:SetPoint("TOPLEFT", 18, introTop)
      syncIntro:SetWidth(rightContentWidth)
      introHeight = math.max(18, math.ceil((syncIntro:IsShown() and syncIntro:GetStringHeight() or 0)))
    end

    local dashboardTop = introTop - introHeight - 12
    local dashboardHeight = LayoutSyncDashboard(editor, dashboardTop, rightContentWidth)

    local pushHeaderTop = dashboardTop - dashboardHeight - 24
    if editor.lootSessionSyncPushHeader then
      editor.lootSessionSyncPushHeader:ClearAllPoints()
      editor.lootSessionSyncPushHeader:SetPoint("TOPLEFT", 18, pushHeaderTop)
    end

    local requestTop = pushHeaderTop - 28
    local profileSyncDropdown = editor.sessionProfileSyncMemberDropdown
    local selectedHint = editor.lootSessionSyncSelectedHint
    local requestControlsHeight = 0
    if profileSyncDropdown then
      local dropdownWidth = math.max(220, rightContentWidth - 16)
      requestControlsHeight = math.max(profileSyncDropdown.buttonHeight or 22, 22)
      profileSyncDropdown.dropdownWidth = dropdownWidth
      profileSyncDropdown:SetSize(dropdownWidth + 24, profileSyncDropdown.buttonHeight or 22)
      if profileSyncDropdown.button then
        profileSyncDropdown.button:SetWidth(dropdownWidth)
      end
      profileSyncDropdown:ClearAllPoints()
      profileSyncDropdown:SetPoint("TOPLEFT", 18, requestTop)
    end

    local compareActionTop = requestTop - requestControlsHeight - 10
    local compareButtonHeight = FlowLayoutControls({
      editor.sessionCheckSyncBtn,
    }, 18, compareActionTop, rightContentWidth, 10, 8)

    local scopeTop = compareActionTop - compareButtonHeight - 10
    local scopeFrameHeight = LayoutSyncScopePicker(editor, scopeTop, rightContentWidth)
    local selectedHintTop = scopeTop - scopeFrameHeight - 10
    if selectedHint then
      selectedHint:ClearAllPoints()
      selectedHint:SetPoint("TOPLEFT", 18, selectedHintTop)
      selectedHint:SetWidth(rightContentWidth)
    end
    local selectedHintHeight = math.max(0, math.ceil((selectedHint and selectedHint:IsShown() and selectedHint:GetStringHeight() or 0)))

    local pullHeaderTop = selectedHintTop - selectedHintHeight - (selectedHintHeight > 0 and 18 or 24)
    if editor.lootSessionSyncPullHeader then
      editor.lootSessionSyncPullHeader:ClearAllPoints()
      editor.lootSessionSyncPullHeader:SetPoint("TOPLEFT", 18, pullHeaderTop)
    end
    local repairInfoBtn = EnsureSyncRepairInfoButton(editor)
    if repairInfoBtn then
      repairInfoBtn:ClearAllPoints()
      repairInfoBtn:Hide()
    end
    local previewActionTop = pullHeaderTop - 28
    local previewActionHeight = FlowLayoutControls({
      editor.sessionPreviewProfileBtn,
    }, 18, previewActionTop, rightContentWidth, 10, 8)

    local profileSyncStatusTop = previewActionTop - previewActionHeight - 10
    if editor.lootSessionProfileSyncStatus then
      editor.lootSessionProfileSyncStatus:ClearAllPoints()
      editor.lootSessionProfileSyncStatus:SetPoint("TOPLEFT", 18, profileSyncStatusTop)
      editor.lootSessionProfileSyncStatus:SetWidth(rightContentWidth)
    end
    local profileSyncStatusHeight = math.max(18, math.ceil((editor.lootSessionProfileSyncStatus and editor.lootSessionProfileSyncStatus:IsShown() and editor.lootSessionProfileSyncStatus:GetStringHeight() or 0)))

    local resolveHeaderTop = profileSyncStatusTop - profileSyncStatusHeight - 18
    if editor.lootSessionSyncResolveHeader then
      editor.lootSessionSyncResolveHeader:ClearAllPoints()
      editor.lootSessionSyncResolveHeader:SetPoint("TOPLEFT", 18, resolveHeaderTop)
    end
    local resolveActionTop = resolveHeaderTop - 28
    local resolveButtonHeight = FlowLayoutControls({
      editor.sessionOpenSyncDetailBtn,
    }, 18, resolveActionTop, rightContentWidth, 10, 8)

    local previewTop = resolveActionTop - resolveButtonHeight - 10
    local inlinePreviewHeight = 0
    local resolverHeight = 0
    local selectedCandidate = type(editor.lootSessionSelectedSyncCandidate) == "table" and editor.lootSessionSelectedSyncCandidate or nil
    local syncStatus = type(editor.lootSessionProfileSyncStatusData) == "table" and editor.lootSessionProfileSyncStatusData or {}
    local detailDiff, detailConflict = GetInlinePreviewState(syncStatus, selectedCandidate)
    local inlinePreview = EnsureInlinePreviewPanel(editor)
    local inlineResolverHost = editor.lootSessionSyncInlineResolverHost
    if inlinePreview and type(selectedCandidate) == "table" and (type(detailDiff) == "table" or type(detailConflict) == "table") then
      local basePreviewHeight = type(detailConflict) == "table" and 220 or 190
      local hintHeight = 32
      inlinePreview:Show()
      inlinePreview:ClearAllPoints()
      inlinePreview:SetPoint("TOPLEFT", 18, previewTop)
      inlinePreview:SetWidth(rightContentWidth)
      if inlinePreview.title then
        inlinePreview.title:ClearAllPoints()
        inlinePreview.title:SetPoint("TOPLEFT", 14, -12)
        inlinePreview.title:SetText("Preview Detail - " .. tostring(selectedCandidate.memberKey or "Unknown"))
      end
      if inlinePreview.hint then
        inlinePreview.hint:ClearAllPoints()
        inlinePreview.hint:SetPoint("TOPLEFT", 14, -34)
        inlinePreview.hint:SetWidth(rightContentWidth - 28)
        local hintText = (
          type(detailConflict) == "table"
            and "Preview loaded for the selected member. Scroll for exact diff details. The Nested Preview Resolver below can merge only the member paths you choose."
            or "Preview loaded for the selected member. Scroll for exact diff details. No changes have been applied."
        )
        local scopeNote = BuildInlinePreviewScopeNote(editor)
        if TrimText(scopeNote) ~= "" then
          hintText = hintText .. "\n" .. scopeNote
        end
        inlinePreview.hint:SetText(hintText)
        hintHeight = math.max(32, math.ceil(inlinePreview.hint:GetStringHeight() or 0))
      end
      inlinePreviewHeight = basePreviewHeight + math.max(0, hintHeight - 32)
      inlinePreview:SetHeight(inlinePreviewHeight)
      if inlinePreview.scroll then
        inlinePreview.scroll:ClearAllPoints()
        inlinePreview.scroll:SetPoint("TOPLEFT", 14, -(34 + hintHeight + 12))
        inlinePreview.scroll:SetPoint("BOTTOMRIGHT", -28, 12)
      end
      if inlinePreview.body then
        local bodyWidth = math.max(180, rightContentWidth - 56)
        inlinePreview.body:SetWidth(bodyWidth)
        inlinePreview.body:SetText(BuildProfileSyncDetailText(selectedCandidate, syncStatus))
        if inlinePreview.content then
          inlinePreview.content:SetWidth(bodyWidth)
          inlinePreview.content:SetHeight(math.max(1, math.ceil(inlinePreview.body:GetStringHeight() or 0) + 8))
        end
        if inlinePreview.scroll and inlinePreview.scroll.UpdateScrollChildRect then
          inlinePreview.scroll:UpdateScrollChildRect()
        end
      end
      if inlineResolverHost then
        inlineResolverHost:ClearAllPoints()
        inlineResolverHost:SetPoint("TOPLEFT", 18, previewTop - inlinePreviewHeight - 10)
        inlineResolverHost:SetSize(rightContentWidth, 250)
      end
      if type(detailConflict) == "table" and inlineResolverHost then
        local resolverFrame = type(RefreshSyncConflictResolver) == "function"
          and RefreshSyncConflictResolver(editor, inlineResolverHost, selectedCandidate, detailConflict, {
            frameKey = "lootSessionSyncInlineConflictResolver",
            title = "Nested Preview Resolver",
            layout = "inline",
            frameHeight = 250,
          })
          or nil
        if resolverFrame and resolverFrame:IsShown() then
          inlineResolverHost:Show()
          resolverHeight = 250
        else
          inlineResolverHost:Hide()
        end
      else
        if inlineResolverHost then
          inlineResolverHost:Hide()
        end
        if editor.lootSessionSyncInlineConflictResolver then
          editor.lootSessionSyncInlineConflictResolver:Hide()
        end
      end
    else
      if inlinePreview then
        inlinePreview:Hide()
      end
      if inlineResolverHost then
        inlineResolverHost:Hide()
      end
      if editor.lootSessionSyncInlineConflictResolver then
        editor.lootSessionSyncInlineConflictResolver:Hide()
      end
    end

    local advancedHeaderTop = previewTop - inlinePreviewHeight - (inlinePreviewHeight > 0 and 10 or 0) - resolverHeight - (resolverHeight > 0 and 10 or 0) - 18
    if editor.lootSessionSyncAdvancedHeader then
      editor.lootSessionSyncAdvancedHeader:ClearAllPoints()
      editor.lootSessionSyncAdvancedHeader:SetPoint("TOPLEFT", 18, advancedHeaderTop)
    end
    if repairInfoBtn and editor.lootSessionSyncAdvancedHeader then
      repairInfoBtn:ClearAllPoints()
      repairInfoBtn:SetPoint("LEFT", editor.lootSessionSyncAdvancedHeader, "RIGHT", 6, 0)
      repairInfoBtn:Show()
    end
    local advancedActionsTop = advancedHeaderTop - 28
    local advancedRepairHeight = FlowLayoutControls({
      editor.sessionPushProfileBtn,
      editor.sessionPushHostSessionDataBtn,
      editor.sessionRequestProfileBtn,
    }, 18, advancedActionsTop, rightContentWidth, 10, 8)
    local recoveryTop = advancedActionsTop - advancedRepairHeight - 8
    local recoveryHeight = FlowLayoutControls({
      editor.sessionSyncBoardBtn,
    }, 18, recoveryTop, rightContentWidth, 10, 8)

    local historyTop = recoveryTop - recoveryHeight - 18
    if type(INTERNAL_API.LIDCOUNCIL_LayoutLootSessionHostOverridePanel_Impl) == "function" then
      historyTop = INTERNAL_API.LIDCOUNCIL_LayoutLootSessionHostOverridePanel_Impl(editor, historyTop, rightContentWidth)
    end
    local historyHeight = LayoutSyncHistoryPanel(editor, historyTop, rightContentWidth)

    local autoHeaderTop = historyTop - historyHeight - 18
    if editor.lootSessionSyncAutoHeader then
      editor.lootSessionSyncAutoHeader:ClearAllPoints()
      editor.lootSessionSyncAutoHeader:SetPoint("TOPLEFT", 18, autoHeaderTop)
    end
    local autoTextTop = autoHeaderTop - 28
    if editor.lootSessionSyncAutoText then
      editor.lootSessionSyncAutoText:ClearAllPoints()
      editor.lootSessionSyncAutoText:SetPoint("TOPLEFT", 18, autoTextTop)
      editor.lootSessionSyncAutoText:SetWidth(rightContentWidth)
    end
    local autoTextHeight = math.max(110, math.ceil((editor.lootSessionSyncAutoText and editor.lootSessionSyncAutoText:IsShown() and editor.lootSessionSyncAutoText:GetStringHeight() or 0)))

    local manualHeaderTop = autoTextTop - autoTextHeight - 18
    if editor.lootSessionSyncManualHeader then
      editor.lootSessionSyncManualHeader:ClearAllPoints()
      editor.lootSessionSyncManualHeader:SetPoint("TOPLEFT", 18, manualHeaderTop)
    end
    local manualTextTop = manualHeaderTop - 28
    if editor.lootSessionSyncManualText then
      editor.lootSessionSyncManualText:ClearAllPoints()
      editor.lootSessionSyncManualText:SetPoint("TOPLEFT", 18, manualTextTop)
      editor.lootSessionSyncManualText:SetWidth(rightContentWidth)
    end
    local manualTextHeight = math.max(96, math.ceil((editor.lootSessionSyncManualText and editor.lootSessionSyncManualText:IsShown() and editor.lootSessionSyncManualText:GetStringHeight() or 0)))

    local contentBottom = math.abs(manualTextTop) + manualTextHeight + 32
    if page then
      page.__contentHeight = math.max(520, contentBottom)
    end
    return contentBottom
  end

  return {
    RefreshSyncManagementView = RefreshSyncManagementView,
    LayoutSyncManagementSection = LayoutSyncManagementSection,
  }
end
