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

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

  local RootDB = deps.RootDB
  local Print = deps.Print
  local TrimText = deps.TrimText
  local NormalizeCharacterKey = deps.NormalizeCharacterKey
  local FirstNonEmptyText = deps.FirstNonEmptyText
  local CloneProfileSyncDomainList = deps.CloneProfileSyncDomainList
  local SetProfileSyncRuntimeState = deps.SetProfileSyncRuntimeState
  local profileSyncRuntimeState = deps.profileSyncRuntimeState or {}
  local PROFILE_REVISION_DOMAINS = deps.PROFILE_REVISION_DOMAINS or {}
  local PROFILE_REVISION_DOMAIN_LABELS = deps.PROFILE_REVISION_DOMAIN_LABELS or {}
  local GetCharacterKey = deps.GetCharacterKey
  local GetActiveLootSession = deps.GetActiveLootSession
  local GetLootProfileId = deps.GetLootProfileId
  local FindLootProfileNameById = deps.FindLootProfileNameById
  local GetLootProfileRevisionSummary = deps.GetLootProfileRevisionSummary
  local ExportLootProfileSnapshot = deps.ExportLootProfileSnapshot
  local ExportLootProfileDomainSnapshot = deps.ExportLootProfileDomainSnapshot
  local ExportLootProfileSubdomainSnapshot = deps.ExportLootProfileSubdomainSnapshot
  local ExportLootProfileSubdomainPatch = deps.ExportLootProfileSubdomainPatch
  local ExportLootProfileConflictRowPatch = deps.ExportLootProfileConflictRowPatch
  local ExportLootProfileSubdomainPatchManifest = deps.ExportLootProfileSubdomainPatchManifest
  local ImportLootProfileSnapshot = deps.ImportLootProfileSnapshot
  local ImportLootProfileDomainSnapshot = deps.ImportLootProfileDomainSnapshot
  local ImportLootProfileSubdomainSnapshot = deps.ImportLootProfileSubdomainSnapshot
  local ImportLootProfileSubdomainPatch = deps.ImportLootProfileSubdomainPatch
  local ImportLootProfileConflictRowPatch = deps.ImportLootProfileConflictRowPatch
  local PreviewLootProfileSnapshot = deps.PreviewLootProfileSnapshot
  local PreviewLootProfileDomainSnapshot = deps.PreviewLootProfileDomainSnapshot
  local PreviewLootProfileSubdomainSnapshot = deps.PreviewLootProfileSubdomainSnapshot
  local PreviewLootProfileSubdomainPatch = deps.PreviewLootProfileSubdomainPatch
  local PreviewLootProfileConflictRowPatch = deps.PreviewLootProfileConflictRowPatch
  local PreviewLootProfileSubdomainPatchManifest = deps.PreviewLootProfileSubdomainPatchManifest
  local BuildLootProfileSnapshotDiff = deps.BuildLootProfileSnapshotDiff
  local BuildLootProfileDomainSnapshotDiff = deps.BuildLootProfileDomainSnapshotDiff
  local BuildLootProfileSubdomainSnapshotDiff = deps.BuildLootProfileSubdomainSnapshotDiff
  local BuildLootProfileSubdomainPatchDiff = deps.BuildLootProfileSubdomainPatchDiff
  local BuildLootProfileConflictRowPatchDiff = deps.BuildLootProfileConflictRowPatchDiff
  local BuildLootProfileTransferConflictPreview = deps.BuildLootProfileTransferConflictPreview
  local ApplyLootProfileTransferConflictResolution = deps.ApplyLootProfileTransferConflictResolution
  local GetLootProfileSubchecksumManifest = deps.GetLootProfileSubchecksumManifest
  local NormalizeLootProfileSubdomainList = deps.NormalizeLootProfileSubdomainList
  local CloneLootProfileSubdomainList = deps.CloneLootProfileSubdomainList
  local FilterLootProfilePatchCapableSubdomains = deps.FilterLootProfilePatchCapableSubdomains
  local GetLootProfileSubdomainKeysForDomain = deps.GetLootProfileSubdomainKeysForDomain
  local GetLootProfileSubdomainLabel = deps.GetLootProfileSubdomainLabel
  local GetLootProfileSubdomainParentDomain = deps.GetLootProfileSubdomainParentDomain
  local ResolveLootProfileDomainsForSubdomains = deps.ResolveLootProfileDomainsForSubdomains
  local SendComm = deps.SendComm
  local MarkOutboundProfileTransferAcked = deps.MarkOutboundProfileTransferAcked
  local AnnotateOutboundProfileTransfer = deps.AnnotateOutboundProfileTransfer
  local IsActiveSessionHostSender = deps.IsActiveSessionHostSender
  local IsJoinedSessionCharacter = deps.IsJoinedSessionCharacter
  local IsCurrentGroupCharacter = deps.IsCurrentGroupCharacter
  local DoesActiveSessionMatch = deps.DoesActiveSessionMatch
  local RefreshEditor = deps.RefreshEditor
  local ResolveOptionalApiFunction = deps.ResolveOptionalApiFunction
  local GetLootProfile = deps.GetLootProfile
  local GetLootProfileRole = deps.GetLootProfileRole
  local GetLootProfileMaster = deps.GetLootProfileMaster
  local NormalizeLootRollOptions = deps.NormalizeLootRollOptions
  local UpsertLootSessionMember = deps.UpsertLootSessionMember
  local RememberPersistedMemberBaseline = deps.RememberPersistedMemberBaseline
  local GetPersistedMemberBaseline = deps.GetPersistedMemberBaseline
  local RecordRepairHistory = deps.RecordRepairHistory
  local GetRepairHistory = deps.GetRepairHistory
  local PushUndoSnapshot = deps.PushUndoSnapshot
  local GetUndoStatus = deps.GetUndoStatus
  local UndoLastRepair = deps.UndoLastRepair
  local GetProfileSnapshotChunkSize = type(deps.GetProfileSnapshotChunkSize) == "function" and deps.GetProfileSnapshotChunkSize or function()
    return 120
  end
  local GetCommOutboundIntervalSeconds = type(deps.GetCommOutboundIntervalSeconds) == "function" and deps.GetCommOutboundIntervalSeconds or function()
    return 0.12
  end
  local GetCommOutboundQueueStatus = type(deps.GetCommOutboundQueueStatus) == "function" and deps.GetCommOutboundQueueStatus or nil

  local pendingProfileSyncs = {}
  local pendingSnapshotBatch = {}
  local snapshotBatchJoinHoldUntilBySession = {}
  local snapshotBatchRunning = false
  local snapshotBatchTimerToken = 0
  local PreviewProfileTransferSnapshot
  local BuildProfileTransferDiff
  local ImportProfileTransferSnapshot
  local memberSubchecksumCacheBySession = {}
  local pendingMemberSubchecksumPartsBySession = {}
  local memberPatchManifestCacheBySession = {}
  local pendingMemberPatchManifestPartsBySession = {}
  local recentPatchManifestRequests = {}
  local QueueSelectedPreviewRepairPropagation
  local PersistSessionMemberBaseline
  local PROFILE_SYNC_SUBCHECK_CHUNK_LIMIT = 80
  local PROFILE_SYNC_PATCH_MANIFEST_REQUEST_LIMIT = 120
  local PROFILE_SYNC_PATCH_MANIFEST_DEDUPE_SECONDS = 8
  local PROFILE_SYNC_PREVIEW_CONFLICT_TTL_SECONDS = 120

  local function NormalizeSenderKey(sender)
    return NormalizeCharacterKey(sender)
  end

  local function GetNow()
    if type(GetServerTime) == "function" then
      return tonumber(GetServerTime()) or 0
    end
    return tonumber(time and time() or 0) or 0
  end

  local function BuildEmptyRevisionSummary(profileName, profileId)
    return {
      profileName = TrimText(profileName),
      profileId = TrimText(profileId),
      settings = 0,
      permissions = 0,
      operational = 0,
      loot = 0,
      session = 0,
      settingsChecksum = "",
      permissionsChecksum = "",
      operationalChecksum = "",
      lootChecksum = "",
      sessionChecksum = "",
      updatedAt = 0,
    }
  end

  local function NormalizeRevisionSummary(summary, fallbackName, fallbackId)
    summary = type(summary) == "table" and summary or {}
    local operationalRevision = math.max(0, tonumber(summary.operational) or 0)
    local operationalChecksum = TrimText(summary.operationalChecksum)
    local lootRevision = math.max(0, tonumber(summary.loot) or operationalRevision)
    local sessionRevision = math.max(0, tonumber(summary.session) or operationalRevision)
    local lootChecksum = TrimText(summary.lootChecksum)
    if lootChecksum == "" then
      lootChecksum = operationalChecksum
    end
    local sessionChecksum = TrimText(summary.sessionChecksum)
    if sessionChecksum == "" then
      sessionChecksum = operationalChecksum
    end
    return {
      profileName = FirstNonEmptyText(summary.profileName, fallbackName),
      profileId = FirstNonEmptyText(summary.profileId, fallbackId),
      settings = math.max(0, tonumber(summary.settings) or 0),
      permissions = math.max(0, tonumber(summary.permissions) or 0),
      operational = operationalRevision,
      loot = lootRevision,
      session = sessionRevision,
      settingsChecksum = TrimText(summary.settingsChecksum),
      permissionsChecksum = TrimText(summary.permissionsChecksum),
      operationalChecksum = operationalChecksum,
      lootChecksum = lootChecksum,
      sessionChecksum = sessionChecksum,
      updatedAt = math.max(
        0,
        tonumber(summary.updatedAt) or 0,
        tonumber(summary.settingsUpdatedAt) or 0,
        tonumber(summary.permissionsUpdatedAt) or 0,
        tonumber(summary.operationalUpdatedAt) or 0,
        tonumber(summary.lootUpdatedAt) or 0,
        tonumber(summary.sessionUpdatedAt) or 0
      ),
    }
  end

  local function ResolveProfileRevisionDomainList(domains)
    local seen = {}
    local resolved = {}
    local requested = type(domains) == "table" and domains or PROFILE_REVISION_DOMAINS
    for _, domain in ipairs(requested or {}) do
      local key = string.lower(TrimText(domain))
      if PROFILE_REVISION_DOMAIN_LABELS[key] and not seen[key] then
        seen[key] = true
        resolved[#resolved + 1] = key
      end
    end
    if #resolved == 0 then
      for _, domain in ipairs(PROFILE_REVISION_DOMAINS) do
        if not seen[domain] then
          resolved[#resolved + 1] = domain
        end
      end
    end
    return resolved
  end

  local function DoRevisionSummariesMatch(leftSummary, rightSummary, domains)
    leftSummary = NormalizeRevisionSummary(leftSummary, "", "")
    rightSummary = NormalizeRevisionSummary(rightSummary, "", "")
    local comparedDomains = ResolveProfileRevisionDomainList(domains)
    if leftSummary.profileId ~= "" and rightSummary.profileId ~= ""
      and string.lower(leftSummary.profileId) ~= string.lower(rightSummary.profileId)
    then
      return false
    end
    for _, domain in ipairs(comparedDomains) do
      if math.max(0, tonumber(leftSummary[domain]) or 0) ~= math.max(0, tonumber(rightSummary[domain]) or 0) then
        return false
      end
      if TrimText(leftSummary[domain .. "Checksum"]) ~= TrimText(rightSummary[domain .. "Checksum"]) then
        return false
      end
    end
    return true
  end

  local function CaptureSessionMemberRevisionSummary(sessionId, memberKey, profileName, profileId)
    local activeSession, activeProfileName = GetActiveLootSession()
    local resolvedSessionId = TrimText(sessionId)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if type(activeSession) ~= "table" or TrimText(activeSession.id) ~= resolvedSessionId or resolvedMemberKey == "" then
      return nil
    end
    local member = type(activeSession.members) == "table" and activeSession.members[resolvedMemberKey] or nil
    if type(member) ~= "table" and type(activeSession.members) == "table" then
      for storedMemberKey, storedMember in pairs(activeSession.members) do
        if NormalizeCharacterKey(storedMemberKey) == resolvedMemberKey and type(storedMember) == "table" then
          member = storedMember
          break
        end
      end
    end
    if type(member) ~= "table" then
      return nil
    end
    return NormalizeRevisionSummary({
      profileName = FirstNonEmptyText(profileName, activeProfileName),
      profileId = FirstNonEmptyText(member.sharedProfileId, profileId),
      settings = tonumber(member.settingsRevision) or 0,
      permissions = tonumber(member.permissionsRevision) or 0,
      operational = tonumber(member.operationalRevision) or 0,
      loot = tonumber(member.lootRevision) or tonumber(member.operationalRevision) or 0,
      session = tonumber(member.sessionRevision) or tonumber(member.operationalRevision) or 0,
      settingsChecksum = TrimText(member.settingsChecksum),
      permissionsChecksum = TrimText(member.permissionsChecksum),
      operationalChecksum = TrimText(member.operationalChecksum),
      lootChecksum = TrimText(member.lootChecksum),
      sessionChecksum = TrimText(member.sessionChecksum),
      updatedAt = tonumber(member.profileUpdatedAt) or 0,
    }, FirstNonEmptyText(profileName, activeProfileName), FirstNonEmptyText(member.sharedProfileId, profileId))
  end

  local function ClearRuntimePreviewConflictState()
    profileSyncRuntimeState.detailDiff = nil
    profileSyncRuntimeState.detailConflict = nil
    profileSyncRuntimeState.detailSnapshotData = nil
    profileSyncRuntimeState.detailPreviewSummary = nil
    profileSyncRuntimeState.detailBaseSummary = nil
  end

  local function EncodeProfileRevisionDomains(domains)
    local resolved = ResolveProfileRevisionDomainList(domains)
    return table.concat(resolved, ",")
  end

  local function DecodeProfileRevisionDomains(text)
    local domains = {}
    local value = TrimText(text)
    if value ~= "" then
      for token in string.gmatch(value, "[^,%s;|]+") do
        domains[#domains + 1] = token
      end
    end
    return ResolveProfileRevisionDomainList(domains)
  end

  local function MergeProfileRevisionDomains(...)
    local merged = {}
    local seen = {}
    for index = 1, select("#", ...) do
      for _, domain in ipairs(ResolveProfileRevisionDomainList(select(index, ...))) do
        if not seen[domain] then
          seen[domain] = true
          merged[#merged + 1] = domain
        end
      end
    end
    return merged
  end

  local function CloneProfileSyncSubdomainList(subdomains)
    if type(CloneLootProfileSubdomainList) == "function" then
      return CloneLootProfileSubdomainList(subdomains)
    end
    local cloned = {}
    for _, subdomain in ipairs(type(subdomains) == "table" and subdomains or {}) do
      local value = TrimText(subdomain)
      if value ~= "" then
        cloned[#cloned + 1] = value
      end
    end
    return cloned
  end

  local function NormalizeProfileSyncSubdomainList(subdomains, domains)
    if type(NormalizeLootProfileSubdomainList) == "function" then
      return NormalizeLootProfileSubdomainList(subdomains, domains)
    end
    return CloneProfileSyncSubdomainList(subdomains)
  end

  local function NormalizeRequestedProfileSyncSubdomains(subdomains, domains)
    local hasExplicitSubdomains = false
    if type(subdomains) == "string" then
      hasExplicitSubdomains = TrimText(subdomains) ~= ""
    elseif type(subdomains) == "table" then
      hasExplicitSubdomains = #subdomains > 0
    end
    if not hasExplicitSubdomains then
      return {}
    end
    return NormalizeProfileSyncSubdomainList(subdomains, domains)
  end

  local function EncodeProfileSyncSubchecks(domain, subchecksums)
    local orderedKeys = type(GetLootProfileSubdomainKeysForDomain) == "function"
      and GetLootProfileSubdomainKeysForDomain(domain)
      or {}
    local parts = {}
    local seen = {}
    for _, subdomain in ipairs(orderedKeys or {}) do
      local checksum = TrimText(type(subchecksums) == "table" and subchecksums[subdomain] or "")
      if checksum ~= "" then
        parts[#parts + 1] = tostring(subdomain) .. "=" .. checksum
        seen[string.lower(tostring(subdomain))] = true
      end
    end
    if type(subchecksums) == "table" then
      local extraKeys = {}
      for subdomain in pairs(subchecksums) do
        extraKeys[#extraKeys + 1] = subdomain
      end
      table.sort(extraKeys, function(left, right)
        return string.lower(tostring(left)) < string.lower(tostring(right))
      end)
      for _, subdomain in ipairs(extraKeys) do
        local checksum = subchecksums[subdomain]
        local key = TrimText(subdomain)
        local checksumText = TrimText(checksum)
        if key ~= "" and checksumText ~= "" and not seen[string.lower(key)] then
          parts[#parts + 1] = key .. "=" .. checksumText
        end
      end
    end
    return table.concat(parts, ",")
  end

  local function DecodeProfileSyncSubchecks(domain, text)
    local decoded = {}
    local parentDomain = TrimText(domain)
    for token in string.gmatch(TrimText(text), "[^,%s]+") do
      local key, checksum = token:match("^([^=]+)=(.*)$")
      key = TrimText(key)
      checksum = TrimText(checksum)
      if key ~= "" and checksum ~= "" then
        local resolvedParent = type(GetLootProfileSubdomainParentDomain) == "function"
          and GetLootProfileSubdomainParentDomain(key)
          or ""
        if resolvedParent == "" or resolvedParent == parentDomain then
          decoded[key] = checksum
        end
      end
    end
    return decoded
  end

  local function BuildProfileSyncSubcheckMessageParts(domain, subchecksums)
    local encoded = EncodeProfileSyncSubchecks(domain, subchecksums)
    if encoded == "" then
      return { "" }
    end
    local parts = {}
    local current = ""
    for token in string.gmatch(encoded, "[^,%s]+") do
      if current == "" then
        current = token
      elseif (#current + 1 + #token) <= PROFILE_SYNC_SUBCHECK_CHUNK_LIMIT then
        current = current .. "," .. token
      else
        parts[#parts + 1] = current
        current = token
      end
    end
    if current ~= "" then
      parts[#parts + 1] = current
    end
    if #parts == 0 then
      parts[1] = ""
    end
    return parts
  end

  local function JoinProfileSyncSubcheckParts(parts, totalParts)
    local joined = {}
    totalParts = math.max(1, tonumber(totalParts) or 1)
    for index = 1, totalParts do
      local part = TrimText(type(parts) == "table" and parts[index] or "")
      if part ~= "" then
        joined[#joined + 1] = part
      end
    end
    return table.concat(joined, ",")
  end

  local function GetMemberSubchecksumSessionCache(sessionId, createIfMissing)
    local resolvedSessionId = string.lower(TrimText(sessionId))
    if resolvedSessionId == "" then
      return nil
    end
    local bucket = memberSubchecksumCacheBySession[resolvedSessionId]
    if not bucket and createIfMissing then
      bucket = {}
      memberSubchecksumCacheBySession[resolvedSessionId] = bucket
    end
    return bucket
  end

  local function GetPendingMemberSubchecksumSessionCache(sessionId, createIfMissing)
    local resolvedSessionId = string.lower(TrimText(sessionId))
    if resolvedSessionId == "" then
      return nil
    end
    local bucket = pendingMemberSubchecksumPartsBySession[resolvedSessionId]
    if not bucket and createIfMissing then
      bucket = {}
      pendingMemberSubchecksumPartsBySession[resolvedSessionId] = bucket
    end
    return bucket
  end

  local function RememberPendingMemberSubchecksumPayload(sessionId, memberKey, domain, token, partIndex, partTotal, payload)
    local sessionCache = GetPendingMemberSubchecksumSessionCache(sessionId, true)
    local resolvedMemberKey = string.lower(NormalizeCharacterKey(memberKey))
    local resolvedDomain = string.lower(TrimText(domain))
    local resolvedToken = TrimText(token)
    partIndex = math.max(1, tonumber(partIndex) or 1)
    partTotal = math.max(partIndex, tonumber(partTotal) or 1)
    if not sessionCache or resolvedMemberKey == "" or resolvedDomain == "" or resolvedToken == "" then
      return nil
    end

    sessionCache[resolvedMemberKey] = sessionCache[resolvedMemberKey] or {}
    local bucket = sessionCache[resolvedMemberKey][resolvedDomain]
    if type(bucket) ~= "table" or bucket.token ~= resolvedToken or bucket.total ~= partTotal then
      bucket = {
        token = resolvedToken,
        total = partTotal,
        parts = {},
      }
      sessionCache[resolvedMemberKey][resolvedDomain] = bucket
    end
    bucket.parts[partIndex] = TrimText(payload)

    for index = 1, partTotal do
      if bucket.parts[index] == nil then
        return nil
      end
    end

    local encoded = JoinProfileSyncSubcheckParts(bucket.parts, partTotal)
    sessionCache[resolvedMemberKey][resolvedDomain] = nil
    if not next(sessionCache[resolvedMemberKey]) then
      sessionCache[resolvedMemberKey] = nil
    end
    return encoded
  end

  local function GetMemberSubchecksumState(sessionId, memberKey)
    local sessionCache = GetMemberSubchecksumSessionCache(sessionId, false)
    local resolvedMemberKey = string.lower(NormalizeCharacterKey(memberKey))
    if not sessionCache or resolvedMemberKey == "" then
      return nil
    end
    return sessionCache[resolvedMemberKey]
  end

  local function RememberMemberSubchecksumState(sessionId, memberKey, profileName, profileId, domain, domainChecksum, subchecksums)
    local sessionCache = GetMemberSubchecksumSessionCache(sessionId, true)
    local resolvedMemberKey = string.lower(NormalizeCharacterKey(memberKey))
    local resolvedDomain = string.lower(TrimText(domain))
    if not sessionCache or resolvedMemberKey == "" or resolvedDomain == "" then
      return nil
    end
    local state = sessionCache[resolvedMemberKey]
    if type(state) ~= "table" then
      state = {
        byDomain = {},
      }
      sessionCache[resolvedMemberKey] = state
    end
    state.profileName = FirstNonEmptyText(profileName, state.profileName)
    state.profileId = FirstNonEmptyText(profileId, state.profileId)
    state.updatedAt = GetNow()
    state.revisionSummary = CaptureSessionMemberRevisionSummary(sessionId, memberKey, state.profileName, state.profileId) or state.revisionSummary
    state.byDomain[resolvedDomain] = {
      checksum = TrimText(domainChecksum),
      subchecksums = DecodeProfileSyncSubchecks(resolvedDomain, EncodeProfileSyncSubchecks(resolvedDomain, subchecksums)),
      updatedAt = GetNow(),
    }
    PersistSessionMemberBaseline(sessionId, memberKey, profileName)
    return state
  end

  local function GetMemberPatchManifestSessionCache(sessionId, createIfMissing)
    local resolvedSessionId = string.lower(TrimText(sessionId))
    if resolvedSessionId == "" then
      return nil
    end
    local bucket = memberPatchManifestCacheBySession[resolvedSessionId]
    if not bucket and createIfMissing then
      bucket = {}
      memberPatchManifestCacheBySession[resolvedSessionId] = bucket
    end
    return bucket
  end

  local function GetPendingMemberPatchManifestSessionCache(sessionId, createIfMissing)
    local resolvedSessionId = string.lower(TrimText(sessionId))
    if resolvedSessionId == "" then
      return nil
    end
    local bucket = pendingMemberPatchManifestPartsBySession[resolvedSessionId]
    if not bucket and createIfMissing then
      bucket = {}
      pendingMemberPatchManifestPartsBySession[resolvedSessionId] = bucket
    end
    return bucket
  end

  local function RememberPendingMemberPatchManifestPayload(sessionId, memberKey, token, partIndex, partTotal, payload)
    local sessionCache = GetPendingMemberPatchManifestSessionCache(sessionId, true)
    local resolvedMemberKey = string.lower(NormalizeCharacterKey(memberKey))
    local resolvedToken = TrimText(token)
    partIndex = math.max(1, tonumber(partIndex) or 1)
    partTotal = math.max(partIndex, tonumber(partTotal) or 1)
    if not sessionCache or resolvedMemberKey == "" or resolvedToken == "" then
      return nil
    end

    local bucket = sessionCache[resolvedMemberKey]
    if type(bucket) ~= "table" or bucket.token ~= resolvedToken or bucket.total ~= partTotal then
      bucket = {
        token = resolvedToken,
        total = partTotal,
        parts = {},
      }
      sessionCache[resolvedMemberKey] = bucket
    end
    bucket.parts[partIndex] = tostring(payload or "")

    for index = 1, partTotal do
      if bucket.parts[index] == nil then
        return nil
      end
    end

    local combined = table.concat(bucket.parts)
    sessionCache[resolvedMemberKey] = nil
    return combined
  end

  local function GetMemberPatchManifestState(sessionId, memberKey)
    local sessionCache = GetMemberPatchManifestSessionCache(sessionId, false)
    local resolvedMemberKey = string.lower(NormalizeCharacterKey(memberKey))
    if not sessionCache or resolvedMemberKey == "" then
      return nil
    end
    return sessionCache[resolvedMemberKey]
  end

  local function RememberMemberPatchManifestState(sessionId, memberKey, profileName, profileId, manifestSummary, manifestToken)
    local sessionCache = GetMemberPatchManifestSessionCache(sessionId, true)
    local resolvedMemberKey = string.lower(NormalizeCharacterKey(memberKey))
    manifestSummary = type(manifestSummary) == "table" and manifestSummary or {}
    if not sessionCache or resolvedMemberKey == "" then
      return nil
    end

    local state = sessionCache[resolvedMemberKey]
    if type(state) ~= "table" then
      state = {
        bySubdomain = {},
      }
      sessionCache[resolvedMemberKey] = state
    end
    state.profileName = FirstNonEmptyText(profileName, manifestSummary.profileName, state.profileName)
    state.profileId = FirstNonEmptyText(profileId, manifestSummary.profileId, state.profileId)
    state.token = TrimText(manifestToken) ~= "" and TrimText(manifestToken) or state.token
    state.updatedAt = GetNow()
    state.revisionSummary = CaptureSessionMemberRevisionSummary(sessionId, memberKey, state.profileName, state.profileId) or state.revisionSummary
    state.scopeDomains = ResolveProfileRevisionDomainList(manifestSummary.scopeDomains)
    state.scopeSubdomains = CloneProfileSyncSubdomainList(manifestSummary.scopeSubdomains)
    for _, subdomain in ipairs(state.scopeSubdomains) do
      if type(manifestSummary.detailsBySubdomain) == "table" and type(manifestSummary.detailsBySubdomain[subdomain]) == "table" then
        state.bySubdomain[subdomain] = manifestSummary.detailsBySubdomain[subdomain]
      end
    end
    PersistSessionMemberBaseline(sessionId, memberKey, state.profileName)
    return state
  end

  local function InvalidateMemberPreciseSyncState(sessionId, memberKey)
    local resolvedSessionId = string.lower(TrimText(sessionId))
    local resolvedMemberKey = string.lower(NormalizeCharacterKey(memberKey))
    if resolvedSessionId == "" or resolvedMemberKey == "" then
      return false
    end

    local removed = false
    local subchecksumCache = memberSubchecksumCacheBySession[resolvedSessionId]
    if type(subchecksumCache) == "table" and subchecksumCache[resolvedMemberKey] ~= nil then
      subchecksumCache[resolvedMemberKey] = nil
      removed = true
    end
    local pendingSubchecksumCache = pendingMemberSubchecksumPartsBySession[resolvedSessionId]
    if type(pendingSubchecksumCache) == "table" and pendingSubchecksumCache[resolvedMemberKey] ~= nil then
      pendingSubchecksumCache[resolvedMemberKey] = nil
      removed = true
    end
    local patchManifestCache = memberPatchManifestCacheBySession[resolvedSessionId]
    if type(patchManifestCache) == "table" and patchManifestCache[resolvedMemberKey] ~= nil then
      patchManifestCache[resolvedMemberKey] = nil
      removed = true
    end
    local pendingPatchManifestCache = pendingMemberPatchManifestPartsBySession[resolvedSessionId]
    if type(pendingPatchManifestCache) == "table" and pendingPatchManifestCache[resolvedMemberKey] ~= nil then
      pendingPatchManifestCache[resolvedMemberKey] = nil
      removed = true
    end

    local requestPrefix = resolvedSessionId .. "|" .. resolvedMemberKey .. "|"
    for stamp in pairs(recentPatchManifestRequests) do
      if stamp:sub(1, #requestPrefix) == requestPrefix then
        recentPatchManifestRequests[stamp] = nil
        removed = true
      end
    end

    local detailConflict = type(profileSyncRuntimeState.detailConflict) == "table" and profileSyncRuntimeState.detailConflict or nil
    if type(detailConflict) == "table"
      and string.lower(TrimText(profileSyncRuntimeState.sessionId)) == resolvedSessionId
      and string.lower(NormalizeCharacterKey(detailConflict.memberKey)) == resolvedMemberKey
    then
      ClearRuntimePreviewConflictState()
      removed = true
    end
    return removed
  end

  local function EnsureCurrentMemberPreciseSyncState(sessionId, memberKey, revisionSummary)
    local normalizedSummary = NormalizeRevisionSummary(revisionSummary, "", "")
    local subchecksumState = GetMemberSubchecksumState(sessionId, memberKey)
    if type(subchecksumState) == "table"
      and type(subchecksumState.revisionSummary) == "table"
      and not DoRevisionSummariesMatch(subchecksumState.revisionSummary, normalizedSummary, PROFILE_REVISION_DOMAINS)
    then
      return InvalidateMemberPreciseSyncState(sessionId, memberKey)
    end
    local patchManifestState = GetMemberPatchManifestState(sessionId, memberKey)
    if type(patchManifestState) == "table"
      and type(patchManifestState.revisionSummary) == "table"
      and not DoRevisionSummariesMatch(patchManifestState.revisionSummary, normalizedSummary, PROFILE_REVISION_DOMAINS)
    then
      return InvalidateMemberPreciseSyncState(sessionId, memberKey)
    end
    return false
  end

  local function BuildRemoteMemberRevisionSummary(profileName, member)
    member = type(member) == "table" and member or {}
    return NormalizeRevisionSummary({
      profileName = TrimText(profileName),
      profileId = TrimText(member.sharedProfileId),
      settings = tonumber(member.settingsRevision) or 0,
      permissions = tonumber(member.permissionsRevision) or 0,
      operational = tonumber(member.operationalRevision) or 0,
      loot = tonumber(member.lootRevision) or tonumber(member.operationalRevision) or 0,
      session = tonumber(member.sessionRevision) or tonumber(member.operationalRevision) or 0,
      settingsChecksum = TrimText(member.settingsChecksum),
      permissionsChecksum = TrimText(member.permissionsChecksum),
      operationalChecksum = TrimText(member.operationalChecksum),
      lootChecksum = TrimText(member.lootChecksum),
      sessionChecksum = TrimText(member.sessionChecksum),
      updatedAt = tonumber(member.profileUpdatedAt) or 0,
    }, profileName, TrimText(member.sharedProfileId))
  end

  PersistSessionMemberBaseline = function(sessionId, memberKey, profileName)
    if type(RememberPersistedMemberBaseline) ~= "function" then
      return false
    end
    local activeSession, activeProfileName = GetActiveLootSession()
    local resolvedSessionId = TrimText(sessionId)
    local resolvedProfileName = FirstNonEmptyText(profileName, activeProfileName)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if type(activeSession) ~= "table" or TrimText(activeSession.id) ~= resolvedSessionId or resolvedProfileName == "" or resolvedMemberKey == "" then
      return false
    end
    local localProfileId = TrimText(select(1, GetLootProfileId(resolvedProfileName)) or "")
    local member = type(activeSession.members) == "table" and activeSession.members[resolvedMemberKey] or nil
    if localProfileId == "" or type(member) ~= "table" then
      return false
    end
    return RememberPersistedMemberBaseline(
      localProfileId,
      resolvedMemberKey,
      BuildRemoteMemberRevisionSummary(resolvedProfileName, member),
      GetMemberSubchecksumState(resolvedSessionId, resolvedMemberKey),
      GetMemberPatchManifestState(resolvedSessionId, resolvedMemberKey)
    )
  end

  local function HydratePersistedSessionMemberBaseline(sessionId, localProfileId, profileName, memberKey, revisionSummary)
    if type(GetPersistedMemberBaseline) ~= "function" then
      return nil
    end
    local resolvedSessionId = TrimText(sessionId)
    local resolvedLocalProfileId = TrimText(localProfileId)
    local resolvedProfileName = TrimText(profileName)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    if resolvedSessionId == "" or resolvedLocalProfileId == "" or resolvedProfileName == "" or resolvedMemberKey == "" then
      return nil
    end
    local hasSubchecksumState = type(GetMemberSubchecksumState(resolvedSessionId, resolvedMemberKey)) == "table"
    local hasPatchManifestState = type(GetMemberPatchManifestState(resolvedSessionId, resolvedMemberKey)) == "table"
    if hasSubchecksumState and hasPatchManifestState then
      return nil
    end
    local persisted = GetPersistedMemberBaseline(resolvedLocalProfileId, resolvedMemberKey, revisionSummary)
    if type(persisted) ~= "table" then
      return nil
    end
    local persistedProfileId = TrimText(type(persisted.revisionSummary) == "table" and persisted.revisionSummary.profileId or "")
    if not hasSubchecksumState and type(persisted.subchecksumState) == "table" and type(persisted.subchecksumState.byDomain) == "table" then
      for domain, domainState in pairs(persisted.subchecksumState.byDomain) do
        if type(domainState) == "table" then
          RememberMemberSubchecksumState(
            resolvedSessionId,
            resolvedMemberKey,
            resolvedProfileName,
            persistedProfileId,
            domain,
            TrimText(domainState.checksum),
            type(domainState.subchecksums) == "table" and domainState.subchecksums or {}
          )
        end
      end
    end
    if not hasPatchManifestState and type(persisted.patchManifestState) == "table" then
      RememberMemberPatchManifestState(
        resolvedSessionId,
        resolvedMemberKey,
        resolvedProfileName,
        persistedProfileId,
        persisted.patchManifestState,
        TrimText(persisted.patchManifestState.token)
      )
    end
    return persisted
  end

  local function BuildCandidateSafeRecommendation(candidate)
    candidate = type(candidate) == "table" and candidate or {}
    local comparison = string.lower(TrimText(candidate.comparison))
    if comparison == "same" then
      return {
        action = "none",
        label = "No action",
        reason = "The host and member shared copies are already aligned.",
      }
    elseif comparison == "local_newer" then
      return {
        action = "push",
        label = candidate.precisePushReady and "Push precise host repair" or "Push host repair",
        reason = candidate.precisePushReady
          and "The host is newer and precise safe scopes are loaded."
          or "The host is newer; a broader host repair is currently the safe action.",
        domains = CloneProfileSyncDomainList(candidate.hostRepairDomains),
        subdomains = CloneProfileSyncSubdomainList(candidate.precisePushReady and candidate.precisePushSubdomains or {}),
      }
    elseif comparison == "remote_newer" then
      return {
        action = "pull",
        label = candidate.precisePullReady and "Pull precise member repair" or "Pull member repair",
        reason = candidate.precisePullReady
          and "The member is newer and precise safe scopes are loaded."
          or "The member is newer; request their shared copy back to the host.",
        domains = CloneProfileSyncDomainList(candidate.memberRepairDomains),
        subdomains = CloneProfileSyncSubdomainList(candidate.precisePullReady and candidate.precisePullSubdomains or {}),
      }
    elseif comparison == "diverged" then
      return {
        action = "preview",
        label = candidate.precisePreviewReady and "Preview precise conflict" or "Preview member repair",
        reason = "Both sides changed data. Preview first and resolve only the scopes you actually want.",
        domains = MergeProfileRevisionDomains(candidate.remoteNewerDomains, candidate.localNewerDomains),
        subdomains = CloneProfileSyncSubdomainList(candidate.precisePreviewReady and candidate.precisePreviewSubdomains or {}),
      }
    elseif comparison == "different_lineage" then
      return {
        action = "check",
        label = "Review lineage",
        reason = "The joined member is on a different shared profile lineage. Use a full repair only if that overwrite is intentional.",
      }
    end
    return {
      action = "check",
      label = "Check differences",
      reason = "More detailed comparison is needed before a safe repair can be chosen.",
    }
  end

  local function BuildCandidatePreciseDiffInfo(candidate, localManifest, remoteManifest)
    candidate = type(candidate) == "table" and candidate or {}
    local result = {
      scopeDomains = {},
      byDomain = {},
      differentSubdomains = {},
      differentSubdomainsByDomain = {},
      pushSubdomains = {},
      pullSubdomains = {},
      previewSubdomains = {},
    }
    if type(localManifest) ~= "table" or type(remoteManifest) ~= "table" or type(remoteManifest.byDomain) ~= "table" then
      return result
    end
    local comparison = string.lower(TrimText(candidate.comparison))
    if comparison == "different_lineage" or comparison == "unknown" then
      return result
    end

    local candidateChecksumByDomain = {
      settings = TrimText(candidate.settingsChecksum),
      permissions = TrimText(candidate.permissionsChecksum),
      loot = TrimText(candidate.lootChecksum ~= "" and candidate.lootChecksum or candidate.operationalChecksum),
      session = TrimText(candidate.sessionChecksum ~= "" and candidate.sessionChecksum or candidate.operationalChecksum),
    }
    local localChecksums = type(localManifest.checksums) == "table" and localManifest.checksums or {}
    local mergedDomains = MergeProfileRevisionDomains(candidate.remoteNewerDomains, candidate.localNewerDomains)

    for _, domain in ipairs(mergedDomains) do
      local remoteDomain = type(remoteManifest.byDomain[domain]) == "table" and remoteManifest.byDomain[domain] or nil
      local remoteDomainChecksum = TrimText(remoteDomain and remoteDomain.checksum or "")
      if remoteDomainChecksum ~= "" and remoteDomainChecksum == candidateChecksumByDomain[domain] then
        local changed = {}
        local subchecksums = type(remoteDomain.subchecksums) == "table" and remoteDomain.subchecksums or {}
        local comparedSubdomains = {}
        for subdomainKey, _ in pairs(localChecksums) do
          if type(GetLootProfileSubdomainParentDomain) == "function" and GetLootProfileSubdomainParentDomain(subdomainKey) == domain then
            comparedSubdomains[subdomainKey] = true
          end
        end
        for subdomainKey in pairs(subchecksums) do
          if type(GetLootProfileSubdomainParentDomain) == "function" and GetLootProfileSubdomainParentDomain(subdomainKey) == domain then
            comparedSubdomains[subdomainKey] = true
          end
        end
        local orderedSubdomains = {}
        for subdomainKey in pairs(comparedSubdomains) do
          orderedSubdomains[#orderedSubdomains + 1] = subdomainKey
        end
        table.sort(orderedSubdomains, function(left, right)
          local leftLabel = type(GetLootProfileSubdomainLabel) == "function" and GetLootProfileSubdomainLabel(left) or left
          local rightLabel = type(GetLootProfileSubdomainLabel) == "function" and GetLootProfileSubdomainLabel(right) or right
          if string.lower(tostring(leftLabel)) == string.lower(tostring(rightLabel)) then
            return tostring(left) < tostring(right)
          end
          return string.lower(tostring(leftLabel)) < string.lower(tostring(rightLabel))
        end)
        for _, subdomain in ipairs(orderedSubdomains) do
          local localChecksum = TrimText(localChecksums[subdomain])
          local remoteChecksum = TrimText(subchecksums[subdomain])
          if localChecksum ~= remoteChecksum and (localChecksum ~= "" or remoteChecksum ~= "") then
            changed[#changed + 1] = subdomain
            result.differentSubdomains[#result.differentSubdomains + 1] = subdomain
          end
        end
        if #changed > 0 then
          result.scopeDomains[#result.scopeDomains + 1] = domain
          result.byDomain[domain] = {
            domain = domain,
            subdomains = CloneProfileSyncSubdomainList(changed),
            text = "",
          }
          result.differentSubdomainsByDomain[domain] = CloneProfileSyncSubdomainList(changed)
          local labels = {}
          for _, subdomain in ipairs(changed) do
            labels[#labels + 1] = type(GetLootProfileSubdomainLabel) == "function"
              and GetLootProfileSubdomainLabel(subdomain)
              or subdomain
          end
          result.byDomain[domain].text = table.concat(labels, ", ")
        end
      end
    end

    for _, domain in ipairs(candidate.localNewerDomains or {}) do
      for _, subdomain in ipairs(result.differentSubdomainsByDomain[domain] or {}) do
        result.pushSubdomains[#result.pushSubdomains + 1] = subdomain
      end
    end
    for _, domain in ipairs(candidate.remoteNewerDomains or {}) do
      for _, subdomain in ipairs(result.differentSubdomainsByDomain[domain] or {}) do
        result.pullSubdomains[#result.pullSubdomains + 1] = subdomain
      end
    end
    result.previewSubdomains = CloneProfileSyncSubdomainList(result.differentSubdomains)
    return result
  end

  local function BuildFilteredCandidateDomains(primaryDomains, blockedDomains)
    local filtered = {}
    local blocked = {}
    for _, domain in ipairs(type(blockedDomains) == "table" and blockedDomains or {}) do
      blocked[string.lower(TrimText(domain))] = true
    end
    for _, domain in ipairs(type(primaryDomains) == "table" and primaryDomains or {}) do
      local key = string.lower(TrimText(domain))
      if key ~= "" and not blocked[key] then
        filtered[#filtered + 1] = key
      end
    end
    return filtered
  end

  local function HasPreciseCoverageForDomains(domains, preciseByDomain)
    domains = type(domains) == "table" and domains or {}
    preciseByDomain = type(preciseByDomain) == "table" and preciseByDomain or {}
    if #domains == 0 then
      return false
    end
    for _, domain in ipairs(domains) do
      if type(preciseByDomain[domain]) ~= "table" or #(preciseByDomain[domain] or {}) == 0 then
        return false
      end
    end
    return true
  end

  local function BuildPatchManifestRequestParts(subdomains)
    local normalized = type(FilterLootProfilePatchCapableSubdomains) == "function"
      and FilterLootProfilePatchCapableSubdomains(subdomains)
      or CloneProfileSyncSubdomainList(subdomains)
    if #normalized == 0 then
      return {}
    end
    local parts = {}
    local current = ""
    for _, subdomain in ipairs(normalized) do
      if current == "" then
        current = subdomain
      elseif (#current + 1 + #subdomain) <= PROFILE_SYNC_PATCH_MANIFEST_REQUEST_LIMIT then
        current = current .. "," .. subdomain
      else
        parts[#parts + 1] = current
        current = subdomain
      end
    end
    if current ~= "" then
      parts[#parts + 1] = current
    end
    return parts
  end

  local function HasLoadedPatchManifestSubdomains(sessionId, memberKey, subdomains)
    local state = GetMemberPatchManifestState(sessionId, memberKey)
    if type(state) ~= "table" or type(state.bySubdomain) ~= "table" then
      return false
    end
    for _, subdomain in ipairs(type(FilterLootProfilePatchCapableSubdomains) == "function"
      and FilterLootProfilePatchCapableSubdomains(subdomains)
      or CloneProfileSyncSubdomainList(subdomains)) do
      if type(state.bySubdomain[subdomain]) ~= "table" then
        return false
      end
    end
    return true
  end

  local function BuildPreparedTransferPatchManifestSummary(profileName, subdomains)
    local patchCapableSubdomains = type(FilterLootProfilePatchCapableSubdomains) == "function"
      and FilterLootProfilePatchCapableSubdomains(subdomains)
      or CloneProfileSyncSubdomainList(subdomains)
    if #patchCapableSubdomains == 0
      or type(ExportLootProfileSubdomainPatchManifest) ~= "function"
      or type(PreviewLootProfileSubdomainPatchManifest) ~= "function"
    then
      return nil
    end
    local manifestData = ExportLootProfileSubdomainPatchManifest(profileName, patchCapableSubdomains)
    if type(manifestData) ~= "string" or manifestData == "" then
      return nil
    end
    local manifestSummary = PreviewLootProfileSubdomainPatchManifest(manifestData)
    if type(manifestSummary) ~= "table" then
      return nil
    end
    manifestSummary.scopeDomains = ResolveProfileRevisionDomainList(manifestSummary.scopeDomains)
    manifestSummary.scopeSubdomains = CloneProfileSyncSubdomainList(
      type(FilterLootProfilePatchCapableSubdomains) == "function"
        and FilterLootProfilePatchCapableSubdomains(
          type(manifestSummary.scopeSubdomains) == "table" and manifestSummary.scopeSubdomains or patchCapableSubdomains
        )
        or (type(manifestSummary.scopeSubdomains) == "table" and manifestSummary.scopeSubdomains or patchCapableSubdomains)
    )
    return manifestSummary
  end

  local function BuildPatchManifestRequestStamp(sessionId, memberKey, subdomains)
    return string.lower(TrimText(sessionId)) .. "|"
      .. string.lower(NormalizeCharacterKey(memberKey)) .. "|"
      .. table.concat(type(FilterLootProfilePatchCapableSubdomains) == "function"
        and FilterLootProfilePatchCapableSubdomains(subdomains)
        or CloneProfileSyncSubdomainList(subdomains), ",")
  end

  local function SendPatchManifestRequests(targetMemberKey, subdomains, options)
    options = type(options) == "table" and options or {}
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or not profileName then
      return 0
    end

    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not IsActiveSessionHostSender(activeSession, selfKey) then
      return 0
    end

    local resolvedTarget = NormalizeCharacterKey(targetMemberKey)
    local parts = BuildPatchManifestRequestParts(subdomains)
    if resolvedTarget == "" or #parts == 0 or not IsJoinedSessionCharacter(activeSession, resolvedTarget) then
      return 0
    end

    if not options.force and HasLoadedPatchManifestSubdomains(activeSession.id, resolvedTarget, subdomains) then
      return 0
    end

    local requestStamp = BuildPatchManifestRequestStamp(activeSession.id, resolvedTarget, subdomains)
    local now = tonumber(time and time() or 0) or 0
    local lastRequestedAt = tonumber(recentPatchManifestRequests[requestStamp]) or 0
    if not options.force and (now - lastRequestedAt) < PROFILE_SYNC_PATCH_MANIFEST_DEDUPE_SECONDS then
      return 0
    end

    local sentCount = 0
    local profileId = TrimText(select(1, GetLootProfileId(profileName)) or "")
    for _, part in ipairs(parts) do
      local sent = SendComm(
        "PSUBPATCH_REQ",
        "WHISPER",
        resolvedTarget,
        activeSession.id,
        profileName,
        profileId,
        part
      )
      if sent then
        sentCount = sentCount + 1
      end
    end
    if sentCount > 0 then
      recentPatchManifestRequests[requestStamp] = now
    end
    return sentCount
  end

  local function QueueAutoPatchManifestRequest(memberKey, subdomains)
    local resolvedMemberKey = NormalizeCharacterKey(memberKey)
    local normalizedSubdomains = type(FilterLootProfilePatchCapableSubdomains) == "function"
      and FilterLootProfilePatchCapableSubdomains(subdomains)
      or CloneProfileSyncSubdomainList(subdomains)
    if resolvedMemberKey == "" or #normalizedSubdomains == 0 then
      return
    end
    local function RunAutoRequest()
      SendPatchManifestRequests(resolvedMemberKey, normalizedSubdomains, {
        auto = true,
      })
    end
    if type(C_Timer) == "table" and type(C_Timer.After) == "function" then
      C_Timer.After(0.25, RunAutoRequest)
    else
      RunAutoRequest()
    end
  end

  local function CompareProfileRevisionSummaries(localSummary, remoteSummary, domains)
    local remoteNewer = {}
    local localNewer = {}
    local left = NormalizeRevisionSummary(localSummary)
    local right = NormalizeRevisionSummary(remoteSummary)
    for _, domain in ipairs(ResolveProfileRevisionDomainList(domains)) do
      local localRevision = math.max(0, tonumber(left[domain]) or 0)
      local remoteRevision = math.max(0, tonumber(right[domain]) or 0)
      local checksumKey = domain .. "Checksum"
      local localChecksum = TrimText(left[checksumKey])
      local remoteChecksum = TrimText(right[checksumKey])
      local haveChecksums = localChecksum ~= "" and remoteChecksum ~= ""
      if haveChecksums and localChecksum == remoteChecksum then
        -- Matching checksums mean the domain content is aligned even if older clients bumped a revision counter.
      elseif haveChecksums and localChecksum ~= remoteChecksum then
        if remoteRevision > localRevision then
          remoteNewer[#remoteNewer + 1] = domain
        elseif localRevision > remoteRevision then
          localNewer[#localNewer + 1] = domain
        else
          remoteNewer[#remoteNewer + 1] = domain
          localNewer[#localNewer + 1] = domain
        end
      elseif remoteRevision > localRevision then
        remoteNewer[#remoteNewer + 1] = domain
      elseif localRevision > remoteRevision then
        localNewer[#localNewer + 1] = domain
      end
    end
    return remoteNewer, localNewer
  end

  local function FormatProfileRevisionDomains(domains)
    if type(domains) ~= "table" or #domains == 0 then
      return "none"
    end
    local labels = {}
    for _, domain in ipairs(domains) do
      labels[#labels + 1] = PROFILE_REVISION_DOMAIN_LABELS[domain] or tostring(domain)
    end
    return table.concat(labels, ", ")
  end

  local function SendLocalProfileStateToHost(sessionId, profileName, targetProfileName)
    if type(SendComm) ~= "function" then
      return false
    end
    local activeSession = GetActiveLootSession()
    if type(activeSession) ~= "table" or TrimText(activeSession.id) ~= TrimText(sessionId) then
      return false
    end
    local host = NormalizeCharacterKey(activeSession.host)
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if host == "" or selfKey == "" or string.lower(host) == string.lower(selfKey) then
      return false
    end

    local localProfileName = TrimText(targetProfileName)
    if localProfileName == "" then
      localProfileName = TrimText(profileName)
    end
    local profileId = TrimText(select(1, GetLootProfileId(localProfileName)) or "")
    local summary = NormalizeRevisionSummary(GetLootProfileRevisionSummary(localProfileName), localProfileName, profileId)
    return SendComm(
      "PSTATE",
      "WHISPER",
      host,
      TrimText(sessionId),
      TrimText(profileName),
      selfKey,
      profileId,
      tostring(summary.settings or 0),
      tostring(summary.permissions or 0),
      tostring(summary.operational or 0),
      tostring(summary.updatedAt or 0),
      TrimText(summary.settingsChecksum),
      TrimText(summary.permissionsChecksum),
      TrimText(summary.operationalChecksum),
      tostring(summary.loot or summary.operational or 0),
      tostring(summary.session or summary.operational or 0),
      TrimText(summary.lootChecksum),
      TrimText(summary.sessionChecksum)
    )
  end

  local function ResolveProfileSyncComparison(localSummary, remoteSummary)
    local remoteNewerDomains, localNewerDomains = CompareProfileRevisionSummaries(localSummary, remoteSummary)
    local comparison = "same"
    local localProfileId = TrimText(type(localSummary) == "table" and localSummary.profileId or "")
    local remoteProfileId = TrimText(type(remoteSummary) == "table" and remoteSummary.profileId or "")

    if remoteProfileId == "" then
      if #remoteNewerDomains > 0 and #localNewerDomains > 0 then
        comparison = "diverged"
      elseif #remoteNewerDomains > 0 then
        comparison = "remote_newer"
      elseif #localNewerDomains > 0 then
        comparison = "local_newer"
      else
        comparison = "unknown"
      end
    elseif localProfileId ~= "" and string.lower(localProfileId) ~= string.lower(remoteProfileId) then
      comparison = "different_lineage"
    elseif #remoteNewerDomains > 0 and #localNewerDomains > 0 then
      comparison = "diverged"
    elseif #remoteNewerDomains > 0 then
      comparison = "remote_newer"
    elseif #localNewerDomains > 0 then
      comparison = "local_newer"
    end

    return comparison, remoteNewerDomains, localNewerDomains
  end

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

  local function ResolveBootstrapCandidateState(candidate)
    candidate = type(candidate) == "table" and candidate or {}
    local comparison = string.lower(TrimText(candidate.comparison))
    if comparison == "different_lineage" then
      return "lineage"
    end
    if comparison == "unknown" or TrimText(candidate.profileId) == "" then
      return "pending"
    end

    local settingsRemote = HasComparedDomain(candidate.remoteNewerDomains, "settings")
    local settingsLocal = HasComparedDomain(candidate.localNewerDomains, "settings")
    local permissionsRemote = HasComparedDomain(candidate.remoteNewerDomains, "permissions")
    local permissionsLocal = HasComparedDomain(candidate.localNewerDomains, "permissions")

    if not settingsRemote and not settingsLocal and not permissionsRemote and not permissionsLocal then
      return "ready"
    end
    if settingsRemote or permissionsRemote then
      return "review"
    end
    if settingsLocal or permissionsLocal then
      return "pending"
    end
    return "unknown"
  end

  local function GetActiveProfileSyncCandidates()
    local activeSession, profileName = GetActiveLootSession()
    if not activeSession or not profileName then
      return {}
    end

    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    local localProfileId = TrimText(select(1, GetLootProfileId(profileName)) or "")
    local localRevisionSummary = NormalizeRevisionSummary(
      GetLootProfileRevisionSummary(profileName),
      profileName,
      localProfileId
    )
    local localSubchecksumManifest = type(GetLootProfileSubchecksumManifest) == "function"
      and GetLootProfileSubchecksumManifest(profileName)
      or nil

    local candidates = {}
    for memberKey, member in pairs(activeSession.members or {}) do
      local resolvedKey = NormalizeCharacterKey(memberKey)
      if resolvedKey ~= "" and resolvedKey ~= selfKey and type(member) == "table" and tostring(member.status or "JOINED") == "JOINED" then
        local remoteRevisionSummary = BuildRemoteMemberRevisionSummary(profileName, member)
        local comparison, remoteNewerDomains, localNewerDomains = ResolveProfileSyncComparison(localRevisionSummary, remoteRevisionSummary)
        local candidate = {
          memberKey = resolvedKey,
          isSessionHost = string.lower(TrimText(activeSession.host or "")) == string.lower(resolvedKey),
          role = TrimText(member.role),
          addonVersion = TrimText(member.addonVersion),
          className = TrimText(member.className),
          classFile = TrimText(member.classFile),
          specName = TrimText(member.specName),
          specIcon = TrimText(member.specIcon),
          profileId = remoteRevisionSummary.profileId,
          settings = remoteRevisionSummary.settings,
          permissions = remoteRevisionSummary.permissions,
          operational = remoteRevisionSummary.operational,
          loot = remoteRevisionSummary.loot,
          session = remoteRevisionSummary.session,
          settingsChecksum = remoteRevisionSummary.settingsChecksum,
          permissionsChecksum = remoteRevisionSummary.permissionsChecksum,
          operationalChecksum = remoteRevisionSummary.operationalChecksum,
          lootChecksum = remoteRevisionSummary.lootChecksum,
          sessionChecksum = remoteRevisionSummary.sessionChecksum,
          updatedAt = remoteRevisionSummary.updatedAt,
          comparison = comparison,
          remoteNewerDomains = remoteNewerDomains,
          localNewerDomains = localNewerDomains,
          remoteDomainText = FormatProfileRevisionDomains(remoteNewerDomains),
          localDomainText = FormatProfileRevisionDomains(localNewerDomains),
        }
        candidate.bootstrapState = ResolveBootstrapCandidateState(candidate)
        if comparison == "different_lineage" or comparison == "unknown" or TrimText(remoteRevisionSummary.profileId) == "" then
          InvalidateMemberPreciseSyncState(activeSession.id, resolvedKey)
        else
          EnsureCurrentMemberPreciseSyncState(activeSession.id, resolvedKey, remoteRevisionSummary)
        end
        HydratePersistedSessionMemberBaseline(activeSession.id, localProfileId, profileName, resolvedKey, remoteRevisionSummary)
        local preciseDiff = BuildCandidatePreciseDiffInfo(
          candidate,
          localSubchecksumManifest,
          GetMemberSubchecksumState(activeSession.id, resolvedKey)
        )
        candidate.preciseScopeDomains = preciseDiff.scopeDomains
        candidate.preciseDifferentSubdomains = preciseDiff.differentSubdomains
        candidate.preciseDifferentSubdomainsByDomain = preciseDiff.differentSubdomainsByDomain
        candidate.hostRepairDomains = BuildFilteredCandidateDomains(candidate.localNewerDomains, candidate.remoteNewerDomains)
        candidate.memberRepairDomains = BuildFilteredCandidateDomains(candidate.remoteNewerDomains, candidate.localNewerDomains)
        candidate.precisePushSubdomains = {}
        for _, domain in ipairs(candidate.hostRepairDomains) do
          for _, subdomain in ipairs(preciseDiff.differentSubdomainsByDomain[domain] or {}) do
            candidate.precisePushSubdomains[#candidate.precisePushSubdomains + 1] = subdomain
          end
        end
        candidate.precisePullSubdomains = {}
        for _, domain in ipairs(candidate.memberRepairDomains) do
          for _, subdomain in ipairs(preciseDiff.differentSubdomainsByDomain[domain] or {}) do
            candidate.precisePullSubdomains[#candidate.precisePullSubdomains + 1] = subdomain
          end
        end
        candidate.precisePreviewSubdomains = preciseDiff.previewSubdomains
        candidate.preciseScopeTextByDomain = {}
        candidate.preciseDetailLoaded = #preciseDiff.scopeDomains > 0
        for domain, domainInfo in pairs(preciseDiff.byDomain or {}) do
          candidate.preciseScopeTextByDomain[domain] = TrimText(type(domainInfo) == "table" and domainInfo.text or "")
        end
        candidate.precisePushReady = HasPreciseCoverageForDomains(candidate.hostRepairDomains, preciseDiff.differentSubdomainsByDomain)
        candidate.precisePullReady = HasPreciseCoverageForDomains(candidate.memberRepairDomains, preciseDiff.differentSubdomainsByDomain)
        candidate.precisePreviewReady = HasPreciseCoverageForDomains(
          MergeProfileRevisionDomains(candidate.remoteNewerDomains, candidate.localNewerDomains),
          preciseDiff.differentSubdomainsByDomain
        )
        candidate.precisePushText = ""
        candidate.precisePullText = ""
        candidate.precisePreviewText = ""
        if candidate.precisePushReady then
          local labels = {}
          for _, subdomain in ipairs(candidate.precisePushSubdomains) do
            labels[#labels + 1] = type(GetLootProfileSubdomainLabel) == "function"
              and GetLootProfileSubdomainLabel(subdomain)
              or subdomain
          end
          candidate.precisePushText = table.concat(labels, ", ")
        end
        if candidate.precisePullReady then
          local labels = {}
          for _, subdomain in ipairs(candidate.precisePullSubdomains) do
            labels[#labels + 1] = type(GetLootProfileSubdomainLabel) == "function"
              and GetLootProfileSubdomainLabel(subdomain)
              or subdomain
          end
          candidate.precisePullText = table.concat(labels, ", ")
        end
        if candidate.precisePreviewReady then
          local labels = {}
          for _, subdomain in ipairs(candidate.precisePreviewSubdomains) do
            labels[#labels + 1] = type(GetLootProfileSubdomainLabel) == "function"
              and GetLootProfileSubdomainLabel(subdomain)
              or subdomain
          end
          candidate.precisePreviewText = table.concat(labels, ", ")
        end
        local patchManifestState = GetMemberPatchManifestState(activeSession.id, resolvedKey)
        candidate.patchPushSubdomains = type(FilterLootProfilePatchCapableSubdomains) == "function"
          and FilterLootProfilePatchCapableSubdomains(candidate.precisePushSubdomains)
          or {}
        candidate.patchPullSubdomains = type(FilterLootProfilePatchCapableSubdomains) == "function"
          and FilterLootProfilePatchCapableSubdomains(candidate.precisePullSubdomains)
          or {}
        candidate.patchPreviewSubdomains = type(FilterLootProfilePatchCapableSubdomains) == "function"
          and FilterLootProfilePatchCapableSubdomains(candidate.precisePreviewSubdomains)
          or {}
        candidate.patchPushReady = candidate.precisePushReady
          and HasLoadedPatchManifestSubdomains(activeSession.id, resolvedKey, candidate.patchPushSubdomains)
        candidate.patchDetailLoaded = type(patchManifestState) == "table" and type(patchManifestState.bySubdomain) == "table"
        candidate.patchPushText = ""
        if #candidate.patchPushSubdomains > 0 then
          local labels = {}
          for _, subdomain in ipairs(candidate.patchPushSubdomains) do
            labels[#labels + 1] = type(GetLootProfileSubdomainLabel) == "function"
              and GetLootProfileSubdomainLabel(subdomain)
              or subdomain
          end
          candidate.patchPushText = table.concat(labels, ", ")
        end
        candidate.patchPullText = ""
        if #candidate.patchPullSubdomains > 0 then
          local labels = {}
          for _, subdomain in ipairs(candidate.patchPullSubdomains) do
            labels[#labels + 1] = type(GetLootProfileSubdomainLabel) == "function"
              and GetLootProfileSubdomainLabel(subdomain)
              or subdomain
          end
          candidate.patchPullText = table.concat(labels, ", ")
        end
        candidate.patchPreviewText = ""
        if #candidate.patchPreviewSubdomains > 0 then
          local labels = {}
          for _, subdomain in ipairs(candidate.patchPreviewSubdomains) do
            labels[#labels + 1] = type(GetLootProfileSubdomainLabel) == "function"
              and GetLootProfileSubdomainLabel(subdomain)
              or subdomain
          end
          candidate.patchPreviewText = table.concat(labels, ", ")
        end
        candidate.safeRecommendation = BuildCandidateSafeRecommendation(candidate)
        candidates[#candidates + 1] = candidate
      end
    end

    local comparisonPriority = {
      remote_newer = 1,
      diverged = 2,
      unknown = 3,
      different_lineage = 4,
      same = 5,
      local_newer = 6,
    }
    table.sort(candidates, function(a, b)
      if (a.isSessionHost and not b.isSessionHost) or (b.isSessionHost and not a.isSessionHost) then
        return a.isSessionHost == true
      end
      local aPriority = comparisonPriority[a.comparison] or 99
      local bPriority = comparisonPriority[b.comparison] or 99
      if aPriority ~= bPriority then
        return aPriority < bPriority
      end
      return string.lower(tostring(a.memberKey or "")) < string.lower(tostring(b.memberKey or ""))
    end)

    return candidates
  end

  local function GetActiveProfileSyncStatus(precomputedCandidates)
    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    local isHost = activeSession and NormalizeCharacterKey(activeSession.host or "") == selfKey or false
    local counts = {
      remote_newer = 0,
      diverged = 0,
      local_newer = 0,
      same = 0,
      unknown = 0,
      different_lineage = 0,
    }
    local bootstrapCounts = {
      ready = 0,
      pending = 0,
      review = 0,
      lineage = 0,
      unknown = 0,
    }

    if isHost then
      local candidates = type(precomputedCandidates) == "table" and precomputedCandidates or GetActiveProfileSyncCandidates()
      for _, candidate in ipairs(candidates or {}) do
        local comparison = TrimText(candidate.comparison)
        if counts[comparison] ~= nil then
          counts[comparison] = counts[comparison] + 1
        end
        local bootstrapState = TrimText(candidate.bootstrapState)
        if bootstrapCounts[bootstrapState] ~= nil then
          bootstrapCounts[bootstrapState] = bootstrapCounts[bootstrapState] + 1
        else
          bootstrapCounts.unknown = bootstrapCounts.unknown + 1
        end
      end
    end

    local status = {
      activeSession = activeSession ~= nil,
      sessionId = TrimText(activeSession and activeSession.id or ""),
      profileName = TrimText(activeProfileName or (activeSession and activeSession.profileName) or ""),
      isHost = isHost and true or false,
      candidateCounts = counts,
      bootstrapCounts = bootstrapCounts,
      mode = TrimText(profileSyncRuntimeState.mode),
      severity = TrimText(profileSyncRuntimeState.severity),
      message = TrimText(profileSyncRuntimeState.message),
      sender = TrimText(profileSyncRuntimeState.sender),
      updatedAt = tonumber(profileSyncRuntimeState.updatedAt) or 0,
      remoteDomains = CloneProfileSyncDomainList(profileSyncRuntimeState.remoteDomains),
      localDomains = CloneProfileSyncDomainList(profileSyncRuntimeState.localDomains),
      detailDiff = type(profileSyncRuntimeState.detailDiff) == "table" and profileSyncRuntimeState.detailDiff or nil,
      detailConflict = type(profileSyncRuntimeState.detailConflict) == "table" and profileSyncRuntimeState.detailConflict or nil,
    }
    if type(status.detailConflict) == "table"
      and math.max(0, GetNow() - math.max(0, tonumber(status.updatedAt) or 0)) > PROFILE_SYNC_PREVIEW_CONFLICT_TTL_SECONDS
    then
      ClearRuntimePreviewConflictState()
      status.detailDiff = nil
      status.detailConflict = nil
    end

    if status.activeSession ~= true then
      status.mode = "idle"
      status.severity = "info"
      status.message = ""
      status.sender = ""
      status.updatedAt = 0
      status.remoteDomains = {}
      status.localDomains = {}
      status.detailDiff = nil
      status.detailConflict = nil
    elseif status.sessionId ~= TrimText(profileSyncRuntimeState.sessionId)
        or status.profileName ~= TrimText(profileSyncRuntimeState.profileName) then
      status.mode = "idle"
      status.severity = "info"
      status.message = ""
      status.sender = ""
      status.updatedAt = 0
      status.remoteDomains = {}
      status.localDomains = {}
      status.detailDiff = nil
      status.detailConflict = nil
    end

    return status
  end

  local function BuildCandidateRevisionSummary(candidate, profileName)
    candidate = type(candidate) == "table" and candidate or {}
    return NormalizeRevisionSummary({
      profileName = TrimText(profileName),
      profileId = TrimText(candidate.profileId),
      settings = tonumber(candidate.settings) or 0,
      permissions = tonumber(candidate.permissions) or 0,
      operational = tonumber(candidate.operational) or 0,
      loot = tonumber(candidate.loot) or tonumber(candidate.operational) or 0,
      session = tonumber(candidate.session) or tonumber(candidate.operational) or 0,
      settingsChecksum = TrimText(candidate.settingsChecksum),
      permissionsChecksum = TrimText(candidate.permissionsChecksum),
      operationalChecksum = TrimText(candidate.operationalChecksum),
      lootChecksum = TrimText(candidate.lootChecksum),
      sessionChecksum = TrimText(candidate.sessionChecksum),
      updatedAt = tonumber(candidate.updatedAt) or 0,
    }, profileName, TrimText(candidate.profileId))
  end

  local function DoSummariesMatchForDomains(leftSummary, rightSummary, domains)
    return DoRevisionSummariesMatch(leftSummary, rightSummary, domains)
  end

  local function GetActiveProfileSyncConflictPreview(memberKey)
    local detailConflict = type(profileSyncRuntimeState.detailConflict) == "table" and profileSyncRuntimeState.detailConflict or nil
    if type(detailConflict) ~= "table" then
      return nil
    end
    if math.max(0, GetNow() - math.max(0, tonumber(profileSyncRuntimeState.updatedAt) or 0)) > PROFILE_SYNC_PREVIEW_CONFLICT_TTL_SECONDS then
      ClearRuntimePreviewConflictState()
      return nil
    end
    local requestedKey = NormalizeCharacterKey(memberKey)
    if requestedKey ~= "" and requestedKey ~= NormalizeCharacterKey(detailConflict.memberKey) then
      return nil
    end
    return detailConflict
  end

  local function ApplyActiveProfilePreviewConflictResolution(memberKey, resolution)
    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if type(activeSession) ~= "table" or TrimText(activeProfileName) == "" then
      Print("No active loot session.")
      return false, "No active loot session."
    end
    if NormalizeCharacterKey(activeSession.host or "") ~= selfKey then
      Print("Only the loot session host can apply preview conflict selections.")
      return false, "Only the host can apply preview conflict selections."
    end

    local detailConflict = type(profileSyncRuntimeState.detailConflict) == "table" and profileSyncRuntimeState.detailConflict or nil
    local detailSnapshotData = type(profileSyncRuntimeState.detailSnapshotData) == "string" and profileSyncRuntimeState.detailSnapshotData or nil
    local detailPreviewSummary = type(profileSyncRuntimeState.detailPreviewSummary) == "table" and profileSyncRuntimeState.detailPreviewSummary or nil
    local detailBaseSummary = type(profileSyncRuntimeState.detailBaseSummary) == "table" and profileSyncRuntimeState.detailBaseSummary or nil
    local requestedMemberKey = NormalizeCharacterKey(memberKey)
    if type(detailConflict) ~= "table" or type(detailSnapshotData) ~= "string" or type(detailPreviewSummary) ~= "table" or type(detailBaseSummary) ~= "table" then
      Print("No preview conflict state is ready. Request Preview Member Repair again.")
      return false, "No preview conflict state is ready."
    end
    if TrimText(profileSyncRuntimeState.sessionId) ~= TrimText(activeSession.id)
      or TrimText(profileSyncRuntimeState.profileName) ~= TrimText(activeProfileName) then
      ClearRuntimePreviewConflictState()
      Print("The stored preview state is no longer current.")
      return false, "The stored preview state is stale."
    end
    local previewAge = math.max(0, GetNow() - math.max(0, tonumber(profileSyncRuntimeState.updatedAt) or 0))
    if previewAge > PROFILE_SYNC_PREVIEW_CONFLICT_TTL_SECONDS then
      ClearRuntimePreviewConflictState()
      Print("That preview is too old. Request Preview Member Repair again.")
      return false, "Preview expired."
    end
    if requestedMemberKey == "" or requestedMemberKey ~= NormalizeCharacterKey(detailConflict.memberKey) then
      Print("The selected preview does not match that joined member anymore.")
      return false, "The selected preview does not match that joined member."
    end

    local currentLocalSummary = type(GetLootProfileRevisionSummary) == "function"
      and GetLootProfileRevisionSummary(activeProfileName)
      or BuildEmptyRevisionSummary(activeProfileName, TrimText(detailPreviewSummary.profileId))
    if not DoSummariesMatchForDomains(currentLocalSummary, detailBaseSummary, detailConflict.scopeDomains) then
      ClearRuntimePreviewConflictState()
      Print("Your local host copy changed after the preview. Request a fresh preview before applying nested selections.")
      return false, "Local host copy changed after preview."
    end

    local matchedCandidate = nil
    for _, candidate in ipairs(GetActiveProfileSyncCandidates() or {}) do
      if NormalizeCharacterKey(type(candidate) == "table" and candidate.memberKey or "") == requestedMemberKey then
        matchedCandidate = candidate
        break
      end
    end
    if type(matchedCandidate) ~= "table" then
      ClearRuntimePreviewConflictState()
      Print("That joined member is no longer available for preview resolution.")
      return false, "Member is no longer available."
    end
    if not DoSummariesMatchForDomains(BuildCandidateRevisionSummary(matchedCandidate, activeProfileName), detailPreviewSummary, detailConflict.scopeDomains) then
      InvalidateMemberPreciseSyncState(activeSession.id, requestedMemberKey)
      ClearRuntimePreviewConflictState()
      Print("That member reported newer sync state after the preview. Request a fresh preview before applying nested selections.")
      return false, "Member state changed after preview."
    end

    local rowMapsBySubdomain = {}
    for _, leaf in ipairs(type(detailConflict.leaves) == "table" and detailConflict.leaves or {}) do
      if type(leaf) == "table" and TrimText(leaf.subdomain) ~= "" and type(leaf.rowMap) == "table" then
        rowMapsBySubdomain[TrimText(leaf.subdomain)] = leaf.rowMap
      end
    end

    if type(PushUndoSnapshot) == "function" then
      PushUndoSnapshot(activeProfileName, {
        kind = "preview_resolution",
        memberKey = requestedMemberKey,
        profileId = TrimText(detailConflict.profileId) ~= "" and TrimText(detailConflict.profileId) or TrimText(detailPreviewSummary.profileId),
        summary = "Before applying selected preview rows from " .. tostring(requestedMemberKey) .. ".",
      })
    end

    local ok, result = ApplyLootProfileTransferConflictResolution(activeProfileName, detailSnapshotData, resolution, {
      expectedProfileId = TrimText(detailConflict.profileId) ~= "" and TrimText(detailConflict.profileId) or TrimText(detailPreviewSummary.profileId),
      sourceCharacter = requestedMemberKey,
    })
    if not ok then
      Print(tostring(result or "Could not apply preview conflict selections."))
      return false, result
    end

    local activeProfile = type(GetLootProfile) == "function" and select(1, GetLootProfile(activeProfileName)) or nil
    if type(activeProfile) == "table" and type(NormalizeLootRollOptions) == "function" then
      activeSession.rollOptions = NormalizeLootRollOptions(activeProfile.settings and activeProfile.settings.rollOptions)
    end
    if type(activeSession.members) == "table" then
      for storedMemberKey, member in pairs(activeSession.members) do
        if type(member) == "table" then
          member.profileMaster = type(GetLootProfileMaster) == "function" and GetLootProfileMaster(activeProfileName) or member.profileMaster
          member.role = type(GetLootProfileRole) == "function" and GetLootProfileRole(activeProfileName, storedMemberKey) or member.role
        end
      end
    end
    activeSession.sharedProfileReady = true
    activeSession.__sharedProfilePendingNoticeShown = nil
    ClearRuntimePreviewConflictState()

    local appliedSubdomains = type(result) == "table" and type(result.subdomains) == "table" and result.subdomains or {}
    local domainCount = #(type(result) == "table" and type(result.domains) == "table" and result.domains or {})
    local rowCount = tonumber(type(result) == "table" and result.appliedRows or 0) or 0
    local subdomainCount = tonumber(type(result) == "table" and result.appliedSubdomains or 0) or 0
    local queuedDirectRepair, directRepairStats = false, nil
    local appliedSelectionsBySubdomain = {}
    local appliedLookup = {}
    for _, subdomain in ipairs(appliedSubdomains) do
      appliedLookup[string.lower(TrimText(subdomain))] = true
    end
    for subdomain, selectedRows in pairs(type(resolution.selectionsBySubdomain) == "table" and resolution.selectionsBySubdomain or {}) do
      if appliedLookup[string.lower(TrimText(subdomain))] and type(selectedRows) == "table" and #selectedRows > 0 then
        appliedSelectionsBySubdomain[subdomain] = selectedRows
      end
    end
    if type(QueueSelectedPreviewRepairPropagation) == "function" and #appliedSubdomains > 0 then
      queuedDirectRepair, directRepairStats = QueueSelectedPreviewRepairPropagation(
        activeSession,
        activeProfileName,
        requestedMemberKey,
        appliedSubdomains,
        appliedSelectionsBySubdomain,
        rowMapsBySubdomain
      )
    end
    local directRepairMembers = math.max(0, tonumber(type(directRepairStats) == "table" and directRepairStats.queuedMembers or 0) or 0)
    local directRepairTransfers = math.max(0, tonumber(type(directRepairStats) == "table" and directRepairStats.queuedTransfers or 0) or 0)
    local directRepairRowPatchTransfers = math.max(0, tonumber(type(directRepairStats) == "table" and directRepairStats.rowPatchTransfers or 0) or 0)
    local directRepairRowPatchRows = math.max(0, tonumber(type(directRepairStats) == "table" and directRepairStats.rowPatchRows or 0) or 0)
    local directRepairPatchTransfers = math.max(0, tonumber(type(directRepairStats) == "table" and directRepairStats.patchTransfers or 0) or 0)
    local directRepairPatchScopes = math.max(0, tonumber(type(directRepairStats) == "table" and directRepairStats.patchSubdomains or 0) or 0)
    local directRepairSnapshotTransfers = math.max(0, tonumber(type(directRepairStats) == "table" and directRepairStats.snapshotTransfers or 0) or 0)
    local directRepairSkippedLineage = math.max(0, tonumber(type(directRepairStats) == "table" and directRepairStats.skippedLineage or 0) or 0)
    local directRepairFailures = math.max(0, tonumber(type(directRepairStats) == "table" and directRepairStats.failedMembers or 0) or 0)
    local resolutionMessage = "Applied " .. tostring(rowCount) .. " preview row" .. (rowCount == 1 and "" or "s")
      .. " across " .. tostring(subdomainCount) .. " leaf scope" .. (subdomainCount == 1 and "" or "s")
      .. " for " .. tostring(requestedMemberKey) .. "."
    if queuedDirectRepair and directRepairMembers > 0 then
      resolutionMessage = resolutionMessage
        .. " Queued direct host repair for " .. tostring(directRepairMembers) .. " joined member"
        .. (directRepairMembers == 1 and "" or "s")
        .. " (" .. tostring(directRepairTransfers) .. " transfer" .. (directRepairTransfers == 1 and "" or "s")
        .. ", " .. tostring(directRepairRowPatchTransfers) .. " row-patch transfer" .. (directRepairRowPatchTransfers == 1 and "" or "s")
        .. ", " .. tostring(directRepairRowPatchRows) .. " selected row" .. (directRepairRowPatchRows == 1 and "" or "s")
        .. ", " .. tostring(directRepairPatchTransfers) .. " patch transfer" .. (directRepairPatchTransfers == 1 and "" or "s")
        .. ", " .. tostring(directRepairPatchScopes) .. " patch scope" .. (directRepairPatchScopes == 1 and "" or "s")
        .. ", " .. tostring(directRepairSnapshotTransfers) .. " snapshot fallback transfer" .. (directRepairSnapshotTransfers == 1 and "" or "s") .. ")."
    elseif directRepairSkippedLineage > 0 then
      resolutionMessage = resolutionMessage
        .. " Skipped " .. tostring(directRepairSkippedLineage) .. " joined member"
        .. (directRepairSkippedLineage == 1 and "" or "s")
        .. " because the shared profile lineage did not match."
    end
    if directRepairFailures > 0 then
      resolutionMessage = resolutionMessage
        .. " " .. tostring(directRepairFailures) .. " direct repair target"
        .. (directRepairFailures == 1 and " could" or "s could")
        .. " not be queued cleanly."
    end
    if type(RecordRepairHistory) == "function" then
      RecordRepairHistory({
        profileName = activeProfileName,
        sessionId = TrimText(activeSession.id),
        memberKey = requestedMemberKey,
        kind = "preview_resolution",
        summary = resolutionMessage,
        createdAt = GetNow(),
      })
    end
    SetProfileSyncRuntimeState(activeSession.id, activeProfileName, "preview_resolution_applied", "success",
      resolutionMessage, {
        sender = requestedMemberKey,
        remoteDomains = domainCount > 0 and result.domains or {},
        localDomains = {},
        refreshEditor = false,
      })
    if queuedDirectRepair and directRepairMembers > 0 then
      Print("Applied selected preview rows from " .. tostring(requestedMemberKey) .. " to the host copy and queued direct host repair for the affected leaf scopes.")
    else
      Print("Applied selected preview rows from " .. tostring(requestedMemberKey) .. " to the host copy.")
    end
    RefreshEditor()
    return true, result
  end

  local function BuildUniqueLocalProfileName(preferredName, profileMaster)
    local root = RootDB()
    local baseName = TrimText(preferredName)
    if baseName == "" then
      baseName = "Shared Profile"
    end
    if not root.profiles[baseName] then
      return baseName
    end

    local suffixBase = baseName
    local masterLabel = TrimText(profileMaster)
    if masterLabel ~= "" then
      masterLabel = TrimText(masterLabel:match("^[^-]+") or masterLabel)
      if masterLabel ~= "" then
        suffixBase = string.format("%s [%s]", baseName, masterLabel)
        if not root.profiles[suffixBase] then
          return suffixBase
        end
      end
    end

    local counter = 2
    while true do
      local candidate = string.format("%s (%d)", suffixBase, counter)
      if not root.profiles[candidate] then
        return candidate
      end
      counter = counter + 1
    end
  end

  local function ActivateLocalSessionProfile(profileName)
    local root = RootDB()
    local resolvedProfileName = TrimText(profileName)
    if resolvedProfileName == "" or type(root.profiles) ~= "table" or type(root.profiles[resolvedProfileName]) ~= "table" then
      return false
    end

    for otherName, otherProfile in pairs(root.profiles or {}) do
      if type(otherProfile) == "table" then
        otherProfile.settings = type(otherProfile.settings) == "table" and otherProfile.settings or {}
        otherProfile.settings.enabled = tostring(otherName) == tostring(resolvedProfileName)
      end
    end

    root.currentProfile = resolvedProfileName
    root.ui = type(root.ui) == "table" and root.ui or {}
    if resolvedProfileName ~= "Simulation" then
      root.ui.lastNonSimulationProfile = resolvedProfileName
    end
    return true
  end

  local function AreCharacterKeysSame(left, right)
    local leftKey = NormalizeCharacterKey(left)
    local rightKey = NormalizeCharacterKey(right)
    if leftKey == "" or rightKey == "" then
      return false
    end
    if string.lower(leftKey) == string.lower(rightKey) then
      return true
    end

    local leftName, leftRealm = leftKey:match("^([^%-]+)%-(.+)$")
    local rightName, rightRealm = rightKey:match("^([^%-]+)%-(.+)$")
    leftName = string.lower(TrimText(leftName or leftKey))
    rightName = string.lower(TrimText(rightName or rightKey))
    leftRealm = string.lower(TrimText(leftRealm or ""))
    rightRealm = string.lower(TrimText(rightRealm or ""))
    if leftName == "" or rightName == "" or leftName ~= rightName then
      return false
    end
    return leftRealm == "" or rightRealm == "" or leftRealm == rightRealm
  end

  local function FindSharedReplicaProfileName(preferredName, profileId, profileMaster)
    local root = RootDB()
    local cleanName = TrimText(preferredName)
    local resolvedProfileId = string.lower(TrimText(profileId))
    local resolvedMaster = string.lower(NormalizeCharacterKey(profileMaster))

    for profileName, profile in pairs(root.profiles or {}) do
      if type(profile) == "table" then
        local meta = type(profile.meta) == "table" and profile.meta or {}
        local syncState = type(meta.sync) == "table" and meta.sync or {}
        local profileIdMatch = resolvedProfileId ~= ""
          and (
            string.lower(TrimText(meta.profileId)) == resolvedProfileId
            or string.lower(TrimText(syncState.sharedSourceProfileId)) == resolvedProfileId
          )
        if profileIdMatch then
          return tostring(profileName)
        end

        local isSharedReplica = string.upper(TrimText(syncState.mode)) == "SHARED"
        local sourceNameMatches = cleanName ~= ""
          and (
            string.lower(tostring(profileName)) == string.lower(cleanName)
            or string.lower(TrimText(syncState.sharedSourceProfileName)) == string.lower(cleanName)
          )
        local sourceMaster = string.lower(NormalizeCharacterKey(syncState.sharedSourceCharacter))
        local sourceMasterMatches = resolvedMaster == ""
          or sourceMaster == ""
          or AreCharacterKeysSame(sourceMaster, resolvedMaster)
        if isSharedReplica and sourceNameMatches and sourceMasterMatches then
          return tostring(profileName)
        end
      end
    end

    return ""
  end

  local function RememberSharedReplicaPlaceholder(profileName, remoteProfileName, profileId, profileMaster)
    local resolvedName = TrimText(profileName)
    local resolvedProfileId = TrimText(profileId)
    if resolvedName == "" or type(GetLootProfile) ~= "function" then
      return false
    end

    local profile = select(1, GetLootProfile(resolvedName))
    if type(profile) ~= "table" then
      return false
    end

    profile.meta = type(profile.meta) == "table" and profile.meta or {}
    profile.meta.sync = type(profile.meta.sync) == "table" and profile.meta.sync or {}
    local syncState = profile.meta.sync
    syncState.mode = "SHARED"
    if TrimText(syncState.origin) == "" then
      syncState.origin = "SESSION_INVITE"
    end
    if resolvedProfileId ~= "" then
      syncState.sharedSourceProfileId = resolvedProfileId
    end
    syncState.sharedSourceProfileName = FirstNonEmptyText(remoteProfileName, profileName)
    syncState.sharedSourceCharacter = NormalizeCharacterKey(profileMaster)
    syncState.sharedAppliedAt = tonumber(syncState.sharedAppliedAt) or (time and time() or 0)
    return true
  end

  local function ResolveLocalSharedProfileName(preferredName, profileId, profileMaster)
    local resolvedProfileId = TrimText(profileId)
    if resolvedProfileId ~= "" then
      local existingName = TrimText(FindLootProfileNameById(resolvedProfileId) or "")
      if existingName ~= "" then
        return existingName
      end
    end

    local existingReplicaName = FindSharedReplicaProfileName(preferredName, profileId, profileMaster)
    if existingReplicaName ~= "" then
      return existingReplicaName
    end

    local root = RootDB()
    local cleanName = TrimText(preferredName)
    if cleanName == "" then
      cleanName = "Shared Profile"
    end

    local existingProfile = root.profiles[cleanName]
    if type(existingProfile) ~= "table" then
      return cleanName
    end

    local existingProfileId = TrimText(select(1, GetLootProfileId(cleanName)) or "")
    if existingProfileId ~= "" and resolvedProfileId ~= "" and string.lower(existingProfileId) == string.lower(resolvedProfileId) then
      return cleanName
    end

    return BuildUniqueLocalProfileName(cleanName, profileMaster)
  end

  local function EnsureProfileSyncPopup()
    if type(StaticPopupDialogs) ~= "table" or StaticPopupDialogs.LIDCOUNCIL_PROFILE_SYNC_UPDATE then
      return
    end

    StaticPopupDialogs.LIDCOUNCIL_PROFILE_SYNC_UPDATE = {
      text = "Shared profile update available.",
      button1 = "Accept Update",
      button2 = "Keep Mine",
      timeout = 0,
      whileDead = 1,
      hideOnEscape = 1,
      preferredIndex = 3,
      OnAccept = function(self, data)
        local prompt = data or self.data
        if not prompt then
          return
        end
        local ok, result = ImportProfileTransferSnapshot(
          prompt.targetProfileName,
          prompt.snapshotData,
          prompt.profileId,
          prompt.sender,
          prompt.transferKind
        )
        if not ok then
          Print(tostring(result or "Could not apply incoming profile snapshot."))
          return
        end
        ActivateLocalSessionProfile(prompt.targetProfileName)
        SetProfileSyncRuntimeState(prompt.sessionId, prompt.profileName, "accepted", "success",
          "Accepted the host shared profile update.", {
            sender = prompt.sender,
            remoteDomains = prompt.remoteDomains,
            refreshEditor = false,
          })
        Print("Accepted newer shared profile update for \"" .. tostring(prompt.profileName) .. "\" from " .. tostring(prompt.sender) .. ".")
        RefreshEditor()
      end,
      OnCancel = function(self, data)
        local prompt = data or self.data
        if prompt then
          SetProfileSyncRuntimeState(prompt.sessionId, prompt.profileName, "kept_local", "warn",
            "Kept your local shared profile copy.", {
              sender = prompt.sender,
              remoteDomains = prompt.remoteDomains,
              refreshEditor = false,
            })
          Print("Kept your local shared profile copy for \"" .. tostring(prompt.profileName) .. "\".")
        end
        RefreshEditor()
      end,
    }
  end

  local function ShowProfileSyncPopup(prompt)
    EnsureProfileSyncPopup()
    if type(StaticPopup_Show) ~= "function" then
      return
    end
    local dialog = StaticPopup_Show("LIDCOUNCIL_PROFILE_SYNC_UPDATE")
    if not dialog then
      return
    end
    dialog.data = prompt
    if dialog.text and dialog.text.SetText then
      dialog.text:SetText(string.format(
        "The session host %s has newer shared profile data for \"%s\".\n\nNewer domains: %s.\n\nAccept Update replaces only your local shared copy for this shared profile lineage. Keep Mine leaves your current local copy unchanged.\n\nDo you want to apply the host update now?",
        tostring(prompt.sender or "Unknown"),
        tostring(prompt.profileName or "Unknown"),
        tostring(prompt.remoteDomainText or "none")
      ))
    end
  end

  local function BuildProfileSnapshotChunks(snapshot)
    local chunks = {}
    local text = tostring(snapshot or "")
    local chunkSize = math.max(1, tonumber(GetProfileSnapshotChunkSize()) or 120)
    local textLength = #text
    local index = 1
    while index <= textLength do
      chunks[#chunks + 1] = text:sub(index, index + chunkSize - 1)
      index = index + chunkSize
    end
    if #chunks == 0 then
      chunks[1] = ""
    end
    return chunks
  end

  PreviewProfileTransferSnapshot = function(snapshotData)
    local previewSummary = type(PreviewLootProfileSnapshot) == "function" and PreviewLootProfileSnapshot(snapshotData) or nil
    if type(previewSummary) == "table" then
      local normalized = NormalizeRevisionSummary(previewSummary, previewSummary.profileName, previewSummary.profileId)
      normalized.scopeDomains = ResolveProfileRevisionDomainList(previewSummary.scopeDomains)
      normalized.transferKind = "FULL"
      normalized.exportedAt = tonumber(previewSummary.exportedAt) or nil
      return normalized
    end

    previewSummary = type(PreviewLootProfileSubdomainSnapshot) == "function" and PreviewLootProfileSubdomainSnapshot(snapshotData) or nil
    if type(previewSummary) == "table" then
      local normalized = NormalizeRevisionSummary(previewSummary, previewSummary.profileName, previewSummary.profileId)
      normalized.scopeDomains = ResolveProfileRevisionDomainList(previewSummary.scopeDomains)
      normalized.scopeSubdomains = NormalizeProfileSyncSubdomainList(previewSummary.scopeSubdomains, previewSummary.scopeDomains)
      normalized.transferKind = "SUBDOMAINS"
      normalized.exportedAt = tonumber(previewSummary.exportedAt) or nil
      return normalized
    end

    previewSummary = type(PreviewLootProfileSubdomainPatch) == "function" and PreviewLootProfileSubdomainPatch(snapshotData) or nil
    if type(previewSummary) == "table" then
      local normalized = NormalizeRevisionSummary(previewSummary, previewSummary.profileName, previewSummary.profileId)
      normalized.scopeDomains = ResolveProfileRevisionDomainList(previewSummary.scopeDomains)
      normalized.scopeSubdomains = NormalizeProfileSyncSubdomainList(previewSummary.scopeSubdomains, previewSummary.scopeDomains)
      normalized.transferKind = "PATCHES"
      normalized.exportedAt = tonumber(previewSummary.exportedAt) or nil
      return normalized
    end

    previewSummary = type(PreviewLootProfileConflictRowPatch) == "function" and PreviewLootProfileConflictRowPatch(snapshotData) or nil
    if type(previewSummary) == "table" then
      local normalized = NormalizeRevisionSummary(previewSummary, previewSummary.profileName, previewSummary.profileId)
      normalized.scopeDomains = ResolveProfileRevisionDomainList(previewSummary.scopeDomains)
      normalized.scopeSubdomains = NormalizeProfileSyncSubdomainList(previewSummary.scopeSubdomains, previewSummary.scopeDomains)
      normalized.transferKind = "ROWPATCHES"
      normalized.exportedAt = tonumber(previewSummary.exportedAt) or nil
      normalized.selectedRowCount = math.max(0, tonumber(previewSummary.selectedRowCount) or 0)
      return normalized
    end

    previewSummary = type(PreviewLootProfileDomainSnapshot) == "function" and PreviewLootProfileDomainSnapshot(snapshotData) or nil
    if type(previewSummary) == "table" then
      local normalized = NormalizeRevisionSummary(previewSummary, previewSummary.profileName, previewSummary.profileId)
      normalized.scopeDomains = ResolveProfileRevisionDomainList(previewSummary.scopeDomains)
      normalized.transferKind = "DOMAINS"
      normalized.exportedAt = tonumber(previewSummary.exportedAt) or nil
      return normalized
    end
    return nil
  end

  BuildProfileTransferDiff = function(profileName, snapshotData)
    local detailDiff = type(BuildLootProfileSnapshotDiff) == "function" and BuildLootProfileSnapshotDiff(profileName, snapshotData) or nil
    if type(detailDiff) == "table" then
      detailDiff.scopeDomains = ResolveProfileRevisionDomainList(detailDiff.scopeDomains)
      return detailDiff
    end
    detailDiff = type(BuildLootProfileSubdomainSnapshotDiff) == "function" and BuildLootProfileSubdomainSnapshotDiff(profileName, snapshotData) or nil
    if type(detailDiff) == "table" then
      detailDiff.scopeDomains = ResolveProfileRevisionDomainList(detailDiff.scopeDomains)
      detailDiff.scopeSubdomains = NormalizeProfileSyncSubdomainList(detailDiff.scopeSubdomains, detailDiff.scopeDomains)
      return detailDiff
    end
    detailDiff = type(BuildLootProfileSubdomainPatchDiff) == "function" and BuildLootProfileSubdomainPatchDiff(profileName, snapshotData) or nil
    if type(detailDiff) == "table" then
      detailDiff.scopeDomains = ResolveProfileRevisionDomainList(detailDiff.scopeDomains)
      detailDiff.scopeSubdomains = NormalizeProfileSyncSubdomainList(detailDiff.scopeSubdomains, detailDiff.scopeDomains)
      return detailDiff
    end
    detailDiff = type(BuildLootProfileConflictRowPatchDiff) == "function" and BuildLootProfileConflictRowPatchDiff(profileName, snapshotData) or nil
    if type(detailDiff) == "table" then
      detailDiff.scopeDomains = ResolveProfileRevisionDomainList(detailDiff.scopeDomains)
      detailDiff.scopeSubdomains = NormalizeProfileSyncSubdomainList(detailDiff.scopeSubdomains, detailDiff.scopeDomains)
      return detailDiff
    end
    detailDiff = type(BuildLootProfileDomainSnapshotDiff) == "function" and BuildLootProfileDomainSnapshotDiff(profileName, snapshotData) or nil
    if type(detailDiff) == "table" then
      detailDiff.scopeDomains = ResolveProfileRevisionDomainList(detailDiff.scopeDomains)
      return detailDiff
    end
    return nil
  end

  ImportProfileTransferSnapshot = function(targetProfileName, snapshotData, profileId, sender, transferKind)
    local importOptions = {
      expectedProfileId = profileId,
      sourceCharacter = sender,
    }
    if transferKind == "SUBDOMAINS" and type(ImportLootProfileSubdomainSnapshot) == "function" then
      return ImportLootProfileSubdomainSnapshot(targetProfileName, snapshotData, importOptions)
    end
    if transferKind == "PATCHES" and type(ImportLootProfileSubdomainPatch) == "function" then
      return ImportLootProfileSubdomainPatch(targetProfileName, snapshotData, importOptions)
    end
    if transferKind == "ROWPATCHES" and type(ImportLootProfileConflictRowPatch) == "function" then
      return ImportLootProfileConflictRowPatch(targetProfileName, snapshotData, importOptions)
    end
    if transferKind == "DOMAINS" and type(ImportLootProfileDomainSnapshot) == "function" then
      return ImportLootProfileDomainSnapshot(targetProfileName, snapshotData, importOptions)
    end
    return ImportLootProfileSnapshot(targetProfileName, snapshotData, importOptions)
  end

  local function PrepareProfileSnapshotTransfer(profileName, opts)
    opts = type(opts) == "table" and opts or {}
    local domains = ResolveProfileRevisionDomainList(opts.domains)
    local subdomains = NormalizeRequestedProfileSyncSubdomains(opts.subdomains, domains)
    local domainCsv = TrimText(type(opts.domains) ~= "nil" and EncodeProfileRevisionDomains(domains) or "")
    local snapshot
    local transferKind = "FULL"
    if #subdomains > 0
      and type(opts.rowSelectionsBySubdomain) == "table"
      and type(ExportLootProfileConflictRowPatch) == "function" then
      snapshot = ExportLootProfileConflictRowPatch(
        profileName,
        opts.rowSelectionsBySubdomain,
        opts.rowMapsBySubdomain,
        opts.prebuiltRowsBySubdomain
      )
      if type(snapshot) == "string" and snapshot ~= "" then
        transferKind = "ROWPATCHES"
        domains = type(ResolveLootProfileDomainsForSubdomains) == "function"
          and ResolveLootProfileDomainsForSubdomains(subdomains)
          or ResolveProfileRevisionDomainList(domains)
      end
    end
    if (type(snapshot) ~= "string" or snapshot == "") and #subdomains > 0
      and type(opts.prebuiltRowsBySubdomain) == "table"
      and type(ExportLootProfileConflictRowPatch) == "function"
    then
      snapshot = ExportLootProfileConflictRowPatch(
        profileName,
        opts.rowSelectionsBySubdomain or {},
        opts.rowMapsBySubdomain or {},
        opts.prebuiltRowsBySubdomain
      )
      if type(snapshot) == "string" and snapshot ~= "" then
        transferKind = "ROWPATCHES"
        domains = type(ResolveLootProfileDomainsForSubdomains) == "function"
          and ResolveLootProfileDomainsForSubdomains(subdomains)
          or ResolveProfileRevisionDomainList(domains)
      end
    end
    if (type(snapshot) ~= "string" or snapshot == "") and #subdomains > 0 and type(opts.patchManifest) == "table" and type(ExportLootProfileSubdomainPatch) == "function" then
      snapshot = ExportLootProfileSubdomainPatch(profileName, subdomains, opts.patchManifest)
      if type(snapshot) == "string" and snapshot ~= "" then
        transferKind = "PATCHES"
        domains = type(ResolveLootProfileDomainsForSubdomains) == "function"
          and ResolveLootProfileDomainsForSubdomains(subdomains)
          or ResolveProfileRevisionDomainList(domains)
      end
    end
    if (type(snapshot) ~= "string" or snapshot == "") and #subdomains > 0 and type(ExportLootProfileSubdomainSnapshot) == "function" then
      snapshot = ExportLootProfileSubdomainSnapshot(profileName, subdomains)
      transferKind = "SUBDOMAINS"
      domains = type(ResolveLootProfileDomainsForSubdomains) == "function"
        and ResolveLootProfileDomainsForSubdomains(subdomains)
        or ResolveProfileRevisionDomainList(domains)
    elseif domainCsv ~= "" and type(ExportLootProfileDomainSnapshot) == "function" then
      snapshot = ExportLootProfileDomainSnapshot(profileName, domains)
      transferKind = "DOMAINS"
    else
      snapshot = ExportLootProfileSnapshot(profileName)
    end
    if type(snapshot) ~= "string" or snapshot == "" then
      return nil, "Profile snapshot export failed."
    end
    return {
      profileName = TrimText(profileName),
      profileId = TrimText(select(1, GetLootProfileId(profileName)) or ""),
      chunks = BuildProfileSnapshotChunks(snapshot),
      domains = transferKind == "FULL" and CloneProfileSyncDomainList(PROFILE_REVISION_DOMAINS) or CloneProfileSyncDomainList(domains),
      subdomains = (transferKind == "SUBDOMAINS" or transferKind == "PATCHES" or transferKind == "ROWPATCHES") and CloneProfileSyncSubdomainList(subdomains) or {},
      patchManifestSummary = BuildPreparedTransferPatchManifestSummary(profileName, subdomains),
      transferKind = transferKind,
    }
  end

  local function SendPreparedProfileSnapshot(preparedSnapshot, sessionId, target, opts)
    if type(preparedSnapshot) ~= "table" or type(preparedSnapshot.chunks) ~= "table" then
      return false, "Profile snapshot is not prepared."
    end

    opts = type(opts) == "table" and opts or {}
    local profileName = TrimText(preparedSnapshot.profileName)
    local profileId = TrimText(preparedSnapshot.profileId)
    local chunks = preparedSnapshot.chunks
    local transferId = string.format("PX-%d-%d", tonumber(time and time() or 0) or 0, math.random(1000, 9999))
    local mode = TrimText(opts.mode)
    local domains = preparedSnapshot.transferKind ~= "FULL" and EncodeProfileRevisionDomains(preparedSnapshot.domains) or ""
    local transferKind = TrimText(preparedSnapshot.transferKind)
    local subdomains = (preparedSnapshot.transferKind == "SUBDOMAINS" or preparedSnapshot.transferKind == "PATCHES" or preparedSnapshot.transferKind == "ROWPATCHES")
      and table.concat(preparedSnapshot.subdomains or {}, ",")
      or ""
    if #subdomains > PROFILE_SYNC_SUBCHECK_CHUNK_LIMIT then
      subdomains = ""
    end

    local sent, sendError = SendComm("PSYNC_START", "WHISPER", target, transferId, sessionId, profileName, profileId, tostring(#chunks), mode, domains, transferKind, subdomains)
    if not sent then
      return false, sendError or "Profile snapshot start could not be sent."
    end
    for index, chunk in ipairs(chunks) do
      local chunkSent, chunkError = SendComm("PSYNC_CHUNK", "WHISPER", target, transferId, tostring(index), chunk)
      if not chunkSent then
        return false, chunkError or ("Profile snapshot chunk " .. tostring(index) .. " could not be sent.")
      end
    end
    local endSent, endError = SendComm("PSYNC_END", "WHISPER", target, transferId)
    if not endSent then
      return false, endError or "Profile snapshot end could not be sent."
    end
    if type(AnnotateOutboundProfileTransfer) == "function" then
      AnnotateOutboundProfileTransfer(transferId, {
        sessionId = TrimText(sessionId),
        profileName = profileName,
        profileId = profileId,
        mode = mode,
        domains = domains,
        transferKind = transferKind,
        subdomains = subdomains,
        scopeDomains = CloneProfileSyncDomainList(preparedSnapshot.domains),
        scopeSubdomains = CloneProfileSyncSubdomainList(preparedSnapshot.subdomains),
        patchManifestSummary = preparedSnapshot.patchManifestSummary,
        target = NormalizeCharacterKey(target),
        totalChunks = #chunks,
      })
    end
    return true
  end

  local function SendProfileSnapshot(profileName, sessionId, target, opts)
    local preparedSnapshot, err = PrepareProfileSnapshotTransfer(profileName, opts)
    if not preparedSnapshot then
      return false, err
    end
    return SendPreparedProfileSnapshot(preparedSnapshot, sessionId, target, opts)
  end

  local function BuildPreparedProfileRepairTransfers(profileName, sessionId, memberKey, opts)
    opts = type(opts) == "table" and opts or {}
    local resolvedDomains = ResolveProfileRevisionDomainList(opts.domains)
    local resolvedSubdomains = NormalizeRequestedProfileSyncSubdomains(opts.subdomains, resolvedDomains)
    local transfers = {}
    local detail = {
      patchTransfers = 0,
      patchSubdomains = 0,
      snapshotTransfers = 0,
      snapshotSubdomains = 0,
    }

    if #resolvedSubdomains == 0 then
      local preparedSnapshot, prepareError = PrepareProfileSnapshotTransfer(profileName, opts)
      if not preparedSnapshot then
        return nil, prepareError, detail
      end
      detail.snapshotTransfers = 1
      transfers[1] = preparedSnapshot
      return transfers, nil, detail
    end

    local patchReadySubdomains = {}
    local patchReadyLookup = {}
    local patchManifestState = GetMemberPatchManifestState(sessionId, memberKey)
    local expectedPatchManifestToken = TrimText(opts.patchManifestToken)
    local patchManifestMatches = expectedPatchManifestToken == ""
      or (type(patchManifestState) == "table" and TrimText(patchManifestState.token) == expectedPatchManifestToken)
    if patchManifestMatches and type(patchManifestState) == "table" and type(patchManifestState.bySubdomain) == "table" then
      for _, subdomain in ipairs(type(FilterLootProfilePatchCapableSubdomains) == "function"
        and FilterLootProfilePatchCapableSubdomains(resolvedSubdomains)
        or {}) do
        if type(patchManifestState.bySubdomain[subdomain]) == "table" then
          patchReadyLookup[string.lower(subdomain)] = true
          patchReadySubdomains[#patchReadySubdomains + 1] = subdomain
        end
      end
    end

    local requestedSubdomainsByDomain = {}
    for _, subdomain in ipairs(resolvedSubdomains) do
      local domain = type(GetLootProfileSubdomainParentDomain) == "function"
        and GetLootProfileSubdomainParentDomain(subdomain)
        or ""
      if domain ~= "" then
        requestedSubdomainsByDomain[domain] = requestedSubdomainsByDomain[domain] or {}
        requestedSubdomainsByDomain[domain][#requestedSubdomainsByDomain[domain] + 1] = subdomain
      end
    end

    local patchTransferSubdomains = {}
    local snapshotFallbackSubdomains = {}
    for _, domain in ipairs(type(ResolveLootProfileDomainsForSubdomains) == "function"
      and ResolveLootProfileDomainsForSubdomains(resolvedSubdomains)
      or resolvedDomains) do
      local domainSubdomains = requestedSubdomainsByDomain[domain] or {}
      local domainFullyPatchReady = #domainSubdomains > 0
      for _, subdomain in ipairs(domainSubdomains) do
        if not patchReadyLookup[string.lower(subdomain)] then
          domainFullyPatchReady = false
          break
        end
      end
      for _, subdomain in ipairs(domainSubdomains) do
        if domainFullyPatchReady then
          patchTransferSubdomains[#patchTransferSubdomains + 1] = subdomain
        else
          snapshotFallbackSubdomains[#snapshotFallbackSubdomains + 1] = subdomain
        end
      end
    end

    if #patchTransferSubdomains > 0 then
      local preparedPatch = PrepareProfileSnapshotTransfer(profileName, {
        domains = type(ResolveLootProfileDomainsForSubdomains) == "function"
          and ResolveLootProfileDomainsForSubdomains(patchTransferSubdomains)
          or resolvedDomains,
        subdomains = patchTransferSubdomains,
        patchManifest = patchManifestState,
      })
      if type(preparedPatch) == "table" and preparedPatch.transferKind == "PATCHES" then
        transfers[#transfers + 1] = preparedPatch
        detail.patchTransfers = 1
        detail.patchSubdomains = #patchTransferSubdomains
      else
        for _, subdomain in ipairs(patchTransferSubdomains) do
          snapshotFallbackSubdomains[#snapshotFallbackSubdomains + 1] = subdomain
        end
      end
    end

    if #snapshotFallbackSubdomains > 0 then
      local preparedSnapshot, prepareError = PrepareProfileSnapshotTransfer(profileName, {
        domains = type(ResolveLootProfileDomainsForSubdomains) == "function"
          and ResolveLootProfileDomainsForSubdomains(snapshotFallbackSubdomains)
          or resolvedDomains,
        subdomains = snapshotFallbackSubdomains,
      })
      if not preparedSnapshot then
        return #transfers > 0 and transfers or nil, prepareError, detail
      end
      transfers[#transfers + 1] = preparedSnapshot
      detail.snapshotTransfers = detail.snapshotTransfers + 1
      detail.snapshotSubdomains = #snapshotFallbackSubdomains
    end

    if #transfers == 0 then
      return nil, "No repair transfer could be prepared.", detail
    end
    return transfers, nil, detail
  end

  local function SendProfileSubdomainPatchManifest(profileName, sessionId, target, subdomains)
    local resolvedProfileName = TrimText(profileName)
    local resolvedSessionId = TrimText(sessionId)
    local resolvedTarget = NormalizeCharacterKey(target)
    local normalizedSubdomains = type(FilterLootProfilePatchCapableSubdomains) == "function"
      and FilterLootProfilePatchCapableSubdomains(subdomains)
      or CloneProfileSyncSubdomainList(subdomains)
    if resolvedProfileName == "" or resolvedSessionId == "" or resolvedTarget == "" or #normalizedSubdomains == 0 then
      return false, "Patch manifest target or scope is missing."
    end

    local manifestData = type(ExportLootProfileSubdomainPatchManifest) == "function"
      and ExportLootProfileSubdomainPatchManifest(resolvedProfileName, normalizedSubdomains)
      or nil
    if type(manifestData) ~= "string" or manifestData == "" then
      return false, "Patch manifest export failed."
    end

    local localProfileId = TrimText(select(1, GetLootProfileId(resolvedProfileName)) or "")
    local chunks = BuildProfileSnapshotChunks(manifestData)
    local responseToken = string.format("PSP-%d-%d", tonumber(time and time() or 0) or 0, math.random(1000, 9999))
    local sentCount = 0
    for index, chunk in ipairs(chunks) do
      local sent = SendComm(
        "PSUBPATCH_STATE",
        "WHISPER",
        resolvedTarget,
        resolvedSessionId,
        resolvedProfileName,
        localProfileId,
        responseToken,
        tostring(index),
        tostring(#chunks),
        chunk
      )
      if not sent then
        return false, "Patch manifest chunk could not be sent.", responseToken
      end
      sentCount = sentCount + 1
    end
    return sentCount > 0, sentCount, responseToken
  end

  local function EstimateSnapshotTargetDelay(preparedSnapshot)
    local chunkCount = type(preparedSnapshot) == "table" and type(preparedSnapshot.chunks) == "table" and #preparedSnapshot.chunks or 0
    local transferKind = TrimText(type(preparedSnapshot) == "table" and preparedSnapshot.transferKind or "")
    local intervalSeconds = math.max(0, tonumber(GetCommOutboundIntervalSeconds()) or 0.12)
    local outboundStatus = type(GetCommOutboundQueueStatus) == "function" and GetCommOutboundQueueStatus() or nil
    local queuePressure = #pendingSnapshotBatch + math.max(0, tonumber(type(outboundStatus) == "table" and outboundStatus.pending) or 0)
    local throttlePressure = type(outboundStatus) == "table"
      and math.max(0, tonumber(outboundStatus.throttledTotal) or 0) > math.max(0, tonumber(outboundStatus.sentTotal) or 0)
      or false
    local delayScale = queuePressure >= 16 and 1.55 or (queuePressure >= 8 and 1.25 or 1.0)
    if throttlePressure then
      delayScale = delayScale * 1.20
    end
    if transferKind == "ROWPATCHES" then
      return math.max(intervalSeconds, (((chunkCount * 0.35) + 1.00) * intervalSeconds) * delayScale)
    elseif transferKind == "PATCHES" then
      return math.max(intervalSeconds, (((chunkCount * 0.50) + 1.20) * intervalSeconds) * delayScale)
    elseif transferKind == "SUBDOMAINS" then
      return math.max(intervalSeconds, (((chunkCount * 0.75) + 1.60) * intervalSeconds) * delayScale)
    end
    return math.max(0, (((chunkCount + 2) * intervalSeconds) + intervalSeconds) * delayScale)
  end

  local function GetPreparedTransferPriority(preparedSnapshot)
    local transferKind = TrimText(type(preparedSnapshot) == "table" and preparedSnapshot.transferKind or "")
    if transferKind == "ROWPATCHES" then
      return 1
    elseif transferKind == "PATCHES" then
      return 2
    elseif transferKind == "SUBDOMAINS" then
      return 3
    elseif transferKind == "DOMAINS" then
      return 4
    end
    return 5
  end

  local function GetPreparedTransferBurstLimit(preparedSnapshot)
    local transferKind = TrimText(type(preparedSnapshot) == "table" and preparedSnapshot.transferKind or "")
    local chunkCount = type(preparedSnapshot) == "table" and type(preparedSnapshot.chunks) == "table" and #preparedSnapshot.chunks or 0
    local outboundStatus = type(GetCommOutboundQueueStatus) == "function" and GetCommOutboundQueueStatus() or nil
    local queuePressure = #pendingSnapshotBatch + math.max(0, tonumber(type(outboundStatus) == "table" and outboundStatus.pending) or 0)
    local burstLimit
    if transferKind == "ROWPATCHES" then
      burstLimit = chunkCount <= 3 and 4 or 2
    elseif transferKind == "PATCHES" then
      burstLimit = chunkCount <= 4 and 3 or 2
    elseif transferKind == "SUBDOMAINS" and chunkCount <= 3 then
      burstLimit = 2
    else
      burstLimit = 1
    end
    if queuePressure >= 18 then
      return 1
    elseif queuePressure >= 10 then
      return math.max(1, burstLimit - 1)
    elseif queuePressure <= 2 and transferKind == "ROWPATCHES" and chunkCount <= 2 then
      return burstLimit + 1
    end
    return burstLimit
  end

  local function InsertPendingSnapshotBatchItem(item)
    local priority = GetPreparedTransferPriority(type(item) == "table" and item.preparedSnapshot or nil)
    local chunkCount = type(item) == "table" and type(item.preparedSnapshot) == "table" and type(item.preparedSnapshot.chunks) == "table"
      and #item.preparedSnapshot.chunks
      or math.huge
    local insertAt = #pendingSnapshotBatch + 1
    for index, existing in ipairs(pendingSnapshotBatch) do
      local existingPriority = GetPreparedTransferPriority(type(existing) == "table" and existing.preparedSnapshot or nil)
      local existingChunkCount = type(existing) == "table" and type(existing.preparedSnapshot) == "table" and type(existing.preparedSnapshot.chunks) == "table"
        and #existing.preparedSnapshot.chunks
        or math.huge
      if existingPriority > priority or (existingPriority == priority and existingChunkCount > chunkCount) then
        insertAt = index
        break
      end
    end
    table.insert(pendingSnapshotBatch, insertAt, item)
  end

  local function GetSnapshotBatchHoldDelay(item)
    local sessionId = TrimText(type(item) == "table" and item.sessionId or "")
    if sessionId == "" then
      return 0
    end
    local holdUntil = tonumber(snapshotBatchJoinHoldUntilBySession[sessionId]) or 0
    local now = GetNow()
    if holdUntil <= now then
      snapshotBatchJoinHoldUntilBySession[sessionId] = nil
      return 0
    end
    return math.max(0.1, holdUntil - now)
  end

  local RunNextSnapshotBatchItem

  local function ScheduleNextSnapshotBatchItem(delay)
    local resolvedDelay = math.max(0, tonumber(delay) or 0)
    snapshotBatchTimerToken = snapshotBatchTimerToken + 1
    local token = snapshotBatchTimerToken
    if type(C_Timer) == "table" and type(C_Timer.After) == "function" then
      C_Timer.After(resolvedDelay, function()
        if token ~= snapshotBatchTimerToken then
          return
        end
        RunNextSnapshotBatchItem()
      end)
    else
      RunNextSnapshotBatchItem()
    end
  end

  local function DelayProfileSnapshotBatchForJoins(sessionId, seconds, reason, profileName)
    local resolvedSessionId = TrimText(sessionId)
    if resolvedSessionId == "" then
      return false, 0
    end
    local delaySeconds = math.max(0, tonumber(seconds) or 0)
    if delaySeconds <= 0 then
      return false, 0
    end
    local holdUntil = GetNow() + delaySeconds
    snapshotBatchJoinHoldUntilBySession[resolvedSessionId] = math.max(
      tonumber(snapshotBatchJoinHoldUntilBySession[resolvedSessionId]) or 0,
      holdUntil
    )
    if #pendingSnapshotBatch > 0 and not snapshotBatchRunning then
      snapshotBatchRunning = true
      ScheduleNextSnapshotBatchItem(delaySeconds)
    end
    local stateProfileName = TrimText(profileName)
    if stateProfileName == "" then
      for _, item in ipairs(pendingSnapshotBatch) do
        if TrimText(type(item) == "table" and item.sessionId or "") == resolvedSessionId then
          stateProfileName = TrimText(item.profileName or (type(item.preparedSnapshot) == "table" and item.preparedSnapshot.profileName) or "")
          break
        end
      end
    end
    SetProfileSyncRuntimeState(resolvedSessionId, stateProfileName, "join_grace", "info",
      "Profile snapshot sync is waiting briefly for more raid members to join before sending the next profile copy.", {
        sender = TrimText(reason),
        refreshEditor = false,
      })
    return true, math.max(0, snapshotBatchJoinHoldUntilBySession[resolvedSessionId] - GetNow())
  end

  local function GetProfileSnapshotBatchStatus()
    local firstItem = pendingSnapshotBatch[1]
    local holdRemaining = 0
    local heldSessionId = ""
    if type(firstItem) == "table" then
      heldSessionId = TrimText(firstItem.sessionId)
      holdRemaining = GetSnapshotBatchHoldDelay(firstItem)
    end
    return {
      running = snapshotBatchRunning and true or false,
      pendingTargets = #pendingSnapshotBatch,
      holdRemaining = math.max(0, tonumber(holdRemaining) or 0),
      heldSessionId = heldSessionId,
      nextTarget = NormalizeCharacterKey(type(firstItem) == "table" and firstItem.target or ""),
      nextProfileName = TrimText(type(firstItem) == "table" and (firstItem.profileName or (type(firstItem.preparedSnapshot) == "table" and firstItem.preparedSnapshot.profileName) or "") or ""),
    }
  end

  RunNextSnapshotBatchItem = function()
    local nextItem = pendingSnapshotBatch[1]
    if nextItem then
      local holdDelay = GetSnapshotBatchHoldDelay(nextItem)
      if holdDelay > 0 then
        ScheduleNextSnapshotBatchItem(holdDelay)
        return
      end
    end

    local item = table.remove(pendingSnapshotBatch, 1)
    if not item then
      snapshotBatchRunning = false
      return
    end

    local function resolvePreparedSnapshot(batchItem)
      local preparedSnapshot = type(batchItem) == "table" and batchItem.preparedSnapshot or nil
      if not preparedSnapshot and TrimText(type(batchItem) == "table" and batchItem.profileName or "") ~= "" then
        preparedSnapshot = select(1, PrepareProfileSnapshotTransfer(batchItem.profileName, batchItem.opts))
      end
      return preparedSnapshot
    end

    local preparedSnapshot = resolvePreparedSnapshot(item)
    local burstLimit = math.max(1, GetPreparedTransferBurstLimit(preparedSnapshot))
    local sentCount = 0
    local maxDelay = EstimateSnapshotTargetDelay(preparedSnapshot)
    local basePriority = GetPreparedTransferPriority(preparedSnapshot)
    local baseSessionId = TrimText(item.sessionId)

    while item do
      preparedSnapshot = resolvePreparedSnapshot(item)
      if preparedSnapshot then
        SendPreparedProfileSnapshot(preparedSnapshot, item.sessionId, item.target, item.opts)
        sentCount = sentCount + 1
        maxDelay = math.max(maxDelay, EstimateSnapshotTargetDelay(preparedSnapshot))
      end
      if sentCount >= burstLimit then
        break
      end
      local candidate = pendingSnapshotBatch[1]
      if not candidate then
        break
      end
      if GetSnapshotBatchHoldDelay(candidate) > 0 then
        break
      end
      if TrimText(candidate.sessionId) ~= baseSessionId then
        break
      end
      if GetPreparedTransferPriority(type(candidate) == "table" and candidate.preparedSnapshot or nil) ~= basePriority then
        break
      end
      item = table.remove(pendingSnapshotBatch, 1)
    end

    local intervalSeconds = math.max(0, tonumber(GetCommOutboundIntervalSeconds()) or 0.12)
    local delay = sentCount > 1
      and math.max(intervalSeconds, maxDelay / math.max(1, sentCount))
      or maxDelay
    ScheduleNextSnapshotBatchItem(delay)
  end

  local function SendPreparedProfileSnapshotBatch(preparedSnapshot, sessionId, targets, opts)
    if type(preparedSnapshot) ~= "table" or type(preparedSnapshot.chunks) ~= "table" then
      return false, "Profile snapshot is not prepared."
    end
    if type(targets) ~= "table" or #targets == 0 then
      return false, "No profile snapshot targets."
    end

    opts = type(opts) == "table" and opts or {}
    local queued = 0
    for _, target in ipairs(targets) do
      local resolvedTarget = NormalizeCharacterKey(target)
      if resolvedTarget ~= "" then
        InsertPendingSnapshotBatchItem({
          preparedSnapshot = preparedSnapshot,
          sessionId = sessionId,
          target = resolvedTarget,
          opts = opts,
        })
        queued = queued + 1
      end
    end

    if queued > 0 and not snapshotBatchRunning then
      snapshotBatchRunning = true
      RunNextSnapshotBatchItem()
    end
    return queued > 0, queued
  end

  QueueSelectedPreviewRepairPropagation = function(activeSession, activeProfileName, previewMemberKey, subdomains, rowSelectionsBySubdomain, rowMapsBySubdomain)
    local resolvedProfileName = TrimText(activeProfileName)
    local resolvedPreviewMemberKey = NormalizeCharacterKey(previewMemberKey)
    local resolvedDomains = type(ResolveLootProfileDomainsForSubdomains) == "function"
      and ResolveLootProfileDomainsForSubdomains(subdomains)
      or ResolveProfileRevisionDomainList(nil)
    local resolvedSubdomains = NormalizeRequestedProfileSyncSubdomains(subdomains, resolvedDomains)
    if type(activeSession) ~= "table" or TrimText(activeSession.id) == "" or resolvedProfileName == "" or #resolvedSubdomains == 0 then
      return false, {
        queuedMembers = 0,
        queuedTransfers = 0,
        patchTransfers = 0,
        patchSubdomains = 0,
        snapshotTransfers = 0,
        skippedLineage = 0,
      }
    end

    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    local localProfileId = TrimText(select(1, GetLootProfileId(resolvedProfileName)) or "")
    local candidatesByKey = {}
    for _, candidate in ipairs(GetActiveProfileSyncCandidates() or {}) do
      local candidateKey = NormalizeCharacterKey(type(candidate) == "table" and candidate.memberKey or "")
      if candidateKey ~= "" then
        candidatesByKey[string.lower(candidateKey)] = candidate
      end
    end

    local stats = {
      queuedMembers = 0,
      queuedTransfers = 0,
      rowPatchTransfers = 0,
      rowPatchRows = 0,
      patchTransfers = 0,
      patchSubdomains = 0,
      snapshotTransfers = 0,
      skippedLineage = 0,
      failedMembers = 0,
      previewMemberQueued = false,
      lastError = "",
    }

    local queuedRowTargets = {}
    local preparedRowPatch = nil
    if type(rowSelectionsBySubdomain) == "table" and type(rowMapsBySubdomain) == "table" then
      preparedRowPatch = PrepareProfileSnapshotTransfer(resolvedProfileName, {
        domains = resolvedDomains,
        subdomains = resolvedSubdomains,
        rowSelectionsBySubdomain = rowSelectionsBySubdomain,
        rowMapsBySubdomain = rowMapsBySubdomain,
      })
    end

    for memberKey, member in pairs(activeSession.members or {}) do
      local resolvedMemberKey = NormalizeCharacterKey(memberKey)
      if resolvedMemberKey ~= "" and resolvedMemberKey ~= selfKey
        and type(member) == "table" and tostring(member.status or "JOINED") == "JOINED" then
        local candidate = candidatesByKey[string.lower(resolvedMemberKey)]
        local remoteProfileId = TrimText(
          type(candidate) == "table" and candidate.profileId
            or type(member) == "table" and member.sharedProfileId
            or ""
        )
        if localProfileId ~= "" and remoteProfileId ~= "" and string.lower(localProfileId) ~= string.lower(remoteProfileId) then
          stats.skippedLineage = stats.skippedLineage + 1
        elseif type(preparedRowPatch) == "table" and TrimText(preparedRowPatch.transferKind) == "ROWPATCHES" then
          queuedRowTargets[#queuedRowTargets + 1] = resolvedMemberKey
        else
          local preparedTransfers, prepareError, prepareDetail = BuildPreparedProfileRepairTransfers(
            resolvedProfileName,
            activeSession.id,
            resolvedMemberKey,
            {
              domains = resolvedDomains,
              subdomains = resolvedSubdomains,
            }
          )
          if type(preparedTransfers) ~= "table" or #preparedTransfers == 0 then
            local resolvedPrepareError = TrimText(prepareError)
            if string.lower(resolvedPrepareError) ~= "no repair transfer could be prepared." and resolvedPrepareError ~= "" then
              stats.failedMembers = stats.failedMembers + 1
              stats.lastError = TrimText(prepareError)
            end
          else
            local memberQueued = false
            for _, preparedSnapshot in ipairs(preparedTransfers) do
              local ok, queuedCount = SendPreparedProfileSnapshotBatch(preparedSnapshot, activeSession.id, { resolvedMemberKey }, {
                mode = "LIVE",
                reason = "preview_resolution_sync",
                domains = resolvedDomains,
                subdomains = resolvedSubdomains,
                preparedSnapshot = preparedSnapshot,
              })
              if ok then
                stats.queuedTransfers = stats.queuedTransfers + math.max(1, tonumber(queuedCount) or 1)
                memberQueued = true
              elseif TrimText(queuedCount) ~= "" then
                stats.lastError = TrimText(queuedCount)
              end
            end
            if memberQueued then
              stats.queuedMembers = stats.queuedMembers + 1
              stats.patchTransfers = stats.patchTransfers + math.max(0, tonumber(type(prepareDetail) == "table" and prepareDetail.patchTransfers or 0) or 0)
              stats.patchSubdomains = stats.patchSubdomains + math.max(0, tonumber(type(prepareDetail) == "table" and prepareDetail.patchSubdomains or 0) or 0)
              stats.snapshotTransfers = stats.snapshotTransfers + math.max(0, tonumber(type(prepareDetail) == "table" and prepareDetail.snapshotTransfers or 0) or 0)
              if resolvedPreviewMemberKey ~= "" and resolvedMemberKey == resolvedPreviewMemberKey then
                stats.previewMemberQueued = true
              end
            end
          end
        end
      end
    end

    if #queuedRowTargets > 0 and type(preparedRowPatch) == "table" and TrimText(preparedRowPatch.transferKind) == "ROWPATCHES" then
      local ok, queuedCount = SendPreparedProfileSnapshotBatch(preparedRowPatch, activeSession.id, queuedRowTargets, {
        mode = "LIVE",
        reason = "preview_resolution_rowpatch_sync",
        domains = resolvedDomains,
        subdomains = resolvedSubdomains,
        preparedSnapshot = preparedRowPatch,
      })
      if ok then
        stats.queuedMembers = stats.queuedMembers + math.max(0, tonumber(queuedCount) or #queuedRowTargets)
        stats.queuedTransfers = stats.queuedTransfers + math.max(0, tonumber(queuedCount) or #queuedRowTargets)
        stats.rowPatchTransfers = stats.rowPatchTransfers + math.max(0, tonumber(queuedCount) or #queuedRowTargets)
        local rowPatchRows = 0
        for _, selectedRows in pairs(type(rowSelectionsBySubdomain) == "table" and rowSelectionsBySubdomain or {}) do
          rowPatchRows = rowPatchRows + math.max(0, tonumber(type(selectedRows) == "table" and #selectedRows or 0) or 0)
        end
        stats.rowPatchRows = rowPatchRows
        if resolvedPreviewMemberKey ~= "" then
          for _, queuedTarget in ipairs(queuedRowTargets) do
            if queuedTarget == resolvedPreviewMemberKey then
              stats.previewMemberQueued = true
              break
            end
          end
        end
      elseif TrimText(queuedCount) ~= "" then
        stats.lastError = TrimText(queuedCount)
      end
    end

    return stats.queuedMembers > 0, stats
  end

  local function SendProfileSnapshotBatch(profileName, sessionId, targets, opts)
    local resolvedProfileName = TrimText(profileName)
    if resolvedProfileName == "" then
      return false, "Profile name is missing."
    end
    if type(targets) ~= "table" or #targets == 0 then
      return false, "No profile snapshot targets."
    end

    opts = type(opts) == "table" and opts or {}
    local queued = 0
    for _, target in ipairs(targets) do
      local resolvedTarget = NormalizeCharacterKey(target)
      if resolvedTarget ~= "" then
        InsertPendingSnapshotBatchItem({
          profileName = resolvedProfileName,
          sessionId = sessionId,
          target = resolvedTarget,
          opts = opts,
        })
        queued = queued + 1
      end
    end

    if queued > 0 and not snapshotBatchRunning then
      snapshotBatchRunning = true
      RunNextSnapshotBatchItem()
    end
    return queued > 0, queued
  end

  local function CancelProfileSnapshotBatchForSession(sessionId)
    local resolvedSessionId = TrimText(sessionId)
    if resolvedSessionId == "" then
      return 0
    end
    local removed = 0
    local kept = {}
    for _, item in ipairs(pendingSnapshotBatch) do
      if TrimText(type(item) == "table" and item.sessionId or "") == resolvedSessionId then
        removed = removed + 1
      else
        kept[#kept + 1] = item
      end
    end
    pendingSnapshotBatch = kept
    snapshotBatchJoinHoldUntilBySession[resolvedSessionId] = nil
    memberSubchecksumCacheBySession[string.lower(resolvedSessionId)] = nil
    pendingMemberSubchecksumPartsBySession[string.lower(resolvedSessionId)] = nil
    memberPatchManifestCacheBySession[string.lower(resolvedSessionId)] = nil
    pendingMemberPatchManifestPartsBySession[string.lower(resolvedSessionId)] = nil
    local requestPrefix = string.lower(resolvedSessionId) .. "|"
    for stamp in pairs(recentPatchManifestRequests) do
      if stamp:sub(1, #requestPrefix) == requestPrefix then
        recentPatchManifestRequests[stamp] = nil
      end
    end
    return removed
  end

  local function SendProfileSyncAck(syncState, targetProfileName, revisionSummary)
    if type(syncState) ~= "table" or type(SendComm) ~= "function" then
      return false
    end
    local target = NormalizeCharacterKey(syncState.sender)
    if target == "" then
      return false
    end

    local profileName = TrimText(targetProfileName)
    if profileName == "" then
      profileName = TrimText(syncState.profileName)
    end
    local profileId = TrimText(select(1, GetLootProfileId(profileName)) or syncState.profileId or "")
    local summary = NormalizeRevisionSummary(revisionSummary or GetLootProfileRevisionSummary(profileName), profileName, profileId)
    return SendComm(
      "PSYNC_ACK",
      "WHISPER",
      target,
      TrimText(syncState.transferId),
      TrimText(syncState.sessionId),
      TrimText(syncState.profileName),
      profileId,
      tostring(math.max(0, tonumber(syncState.chunkCount) or 0)),
      tostring(summary.settings or 0),
      tostring(summary.permissions or 0),
      tostring(summary.operational or 0),
      tostring(summary.updatedAt or 0),
      TrimText(summary.settingsChecksum),
      TrimText(summary.permissionsChecksum),
      TrimText(summary.operationalChecksum),
      tostring(summary.loot or summary.operational or 0),
      tostring(summary.session or summary.operational or 0),
      TrimText(summary.lootChecksum),
      TrimText(summary.sessionChecksum)
    )
  end

  local function HandleProfileSyncStart(fields, sender)
    local transferId = TrimText(fields[2])
    local sessionId = TrimText(fields[3])
    local profileName = TrimText(fields[4])
    local profileId = TrimText(fields[5])
    local chunkCount = math.max(0, tonumber(fields[6]) or 0)
    local syncMode = string.upper(TrimText(fields[7]))
    local requestedDomains = DecodeProfileRevisionDomains(fields[8])
    local transferKind = string.upper(TrimText(fields[9]))
    local requestedSubdomains = NormalizeRequestedProfileSyncSubdomains(fields[10], requestedDomains)
    local isLiveSync = syncMode == "LIVE"
    local isReviewSync = syncMode == "REVIEW"
    local isPreviewSync = syncMode == "PREVIEW"
    if transferId == "" or sessionId == "" or profileName == "" or chunkCount <= 0 then
      return
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    if not activeSession or activeSession.id ~= sessionId then
      return
    end
    local senderKey = NormalizeSenderKey(sender)
    if not IsCurrentGroupCharacter(senderKey) then
      return
    end
    if isLiveSync or isReviewSync or isPreviewSync then
      if not IsJoinedSessionCharacter(activeSession, senderKey) then
        return
      end
    elseif not IsActiveSessionHostSender(activeSession, sender) then
      return
    end

    pendingProfileSyncs[transferId] = {
      transferId = transferId,
      sessionId = sessionId,
      profileName = profileName,
      profileId = profileId,
      targetProfileName = TrimText(activeProfileName),
      sender = senderKey,
      chunkCount = chunkCount,
      chunks = {},
      hadLocalSharedProfile = false,
      localRevisionSummary = nil,
      liveSync = isLiveSync,
      reviewSync = isReviewSync,
      previewSync = isPreviewSync,
      scopeDomains = requestedDomains,
      scopeSubdomains = requestedSubdomains,
      transferKind = transferKind ~= "" and transferKind or "FULL",
    }

    local existingSharedProfileName = TrimText(profileId ~= "" and FindLootProfileNameById(profileId) or "")
    if existingSharedProfileName ~= "" then
      pendingProfileSyncs[transferId].hadLocalSharedProfile = true
      pendingProfileSyncs[transferId].localRevisionSummary = NormalizeRevisionSummary(
        GetLootProfileRevisionSummary(existingSharedProfileName),
        existingSharedProfileName,
        profileId
      )
    else
      pendingProfileSyncs[transferId].localRevisionSummary = BuildEmptyRevisionSummary(activeProfileName, profileId)
    end
  end

  local function HandleProfileSyncRequest(fields, sender)
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local profileId = TrimText(fields[4])
    local requestMode = string.upper(TrimText(fields[5]))
    local requestDomains = TrimText(fields[6])
    local requestSubdomains = NormalizeRequestedProfileSyncSubdomains(fields[7], requestDomains)
    local expectedPatchManifestToken = TrimText(fields[8])
    if sessionId == "" or profileName == "" then
      return
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not DoesActiveSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      return
    end
    if not IsActiveSessionHostSender(activeSession, sender) then
      return
    end
    if not IsCurrentGroupCharacter(NormalizeSenderKey(sender)) then
      return
    end
    if selfKey == "" or not IsJoinedSessionCharacter(activeSession, selfKey) then
      return
    end

    local localProfileId = TrimText(select(1, GetLootProfileId(activeProfileName)) or "")
    if profileId ~= "" and localProfileId ~= "" and string.lower(profileId) ~= string.lower(localProfileId) then
      return
    end

    local responseMode = requestMode == "PREVIEW" and "PREVIEW" or "REVIEW"
    local requestDomainList = requestDomains ~= "" and DecodeProfileRevisionDomains(requestDomains) or nil
    local target = NormalizeSenderKey(sender)
    local ok = false
    local transferCount = 0
    local patchTransferCount = 0
    local patchScopeCount = 0
    local sentViaPatchBuilder = false

    if #requestSubdomains > 0 and type(BuildPreparedProfileRepairTransfers) == "function" then
      local preparedTransfers, _, prepareDetail = BuildPreparedProfileRepairTransfers(activeProfileName, sessionId, target, {
        mode = responseMode,
        domains = requestDomainList,
        subdomains = requestSubdomains,
        patchManifestToken = expectedPatchManifestToken,
      })
      if type(preparedTransfers) == "table" and #preparedTransfers > 0 then
        sentViaPatchBuilder = true
        patchTransferCount = math.max(0, tonumber(type(prepareDetail) == "table" and prepareDetail.patchTransfers) or 0)
        patchScopeCount = math.max(0, tonumber(type(prepareDetail) == "table" and prepareDetail.patchSubdomains) or 0)
        ok = true
        for _, preparedSnapshot in ipairs(preparedTransfers) do
          local sent = SendPreparedProfileSnapshot(preparedSnapshot, sessionId, target, {
            mode = responseMode,
          })
          if sent then
            transferCount = transferCount + 1
          else
            ok = false
            break
          end
        end
      end
    end

    if not sentViaPatchBuilder then
      ok = SendProfileSnapshot(activeProfileName, sessionId, target, {
        mode = responseMode,
        domains = requestDomainList,
        subdomains = #requestSubdomains > 0 and requestSubdomains or nil,
      })
      transferCount = ok and 1 or 0
    end

    if ok then
      local isPreview = responseMode == "PREVIEW"
      local patchSuffix = patchTransferCount > 0
        and (" Nested patch transfers: " .. tostring(patchTransferCount) .. " for " .. tostring(patchScopeCount) .. " scope" .. (patchScopeCount == 1 and "" or "s") .. ".")
        or ""
      SetProfileSyncRuntimeState(sessionId, activeProfileName, isPreview and "member_sent_preview" or "member_sent_update", "success",
        (isPreview and "Sent your local shared profile change preview to the session host." or "Sent your local shared profile update to the session host.")
          .. (transferCount > 1 and (" Transfers: " .. tostring(transferCount) .. ".") or "")
          .. patchSuffix, {
          sender = NormalizeSenderKey(sender),
          refreshEditor = false,
        })
      Print("Sent your shared profile " .. (isPreview and "change preview" or "update") .. " to the session host " .. tostring(NormalizeSenderKey(sender))
        .. (patchTransferCount > 0 and (" using " .. tostring(patchTransferCount) .. " nested patch transfer" .. (patchTransferCount == 1 and "" or "s")) or "")
        .. ".")
    end
  end

  local function HandleProfileSubchecksumRequest(fields, sender)
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local profileId = TrimText(fields[4])
    local requestedDomains = DecodeProfileRevisionDomains(fields[5])
    if sessionId == "" or profileName == "" then
      return
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not DoesActiveSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      return
    end
    if not IsActiveSessionHostSender(activeSession, sender) then
      return
    end
    if not IsCurrentGroupCharacter(NormalizeSenderKey(sender)) then
      return
    end
    if selfKey == "" or not IsJoinedSessionCharacter(activeSession, selfKey) then
      return
    end

    local localProfileId = TrimText(select(1, GetLootProfileId(activeProfileName)) or "")
    if profileId ~= "" and localProfileId ~= "" and string.lower(profileId) ~= string.lower(localProfileId) then
      return
    end

    local manifest = type(GetLootProfileSubchecksumManifest) == "function"
      and GetLootProfileSubchecksumManifest(activeProfileName, requestedDomains)
      or nil
    if type(manifest) ~= "table" or type(manifest.byDomain) ~= "table" then
      return
    end

    local target = NormalizeSenderKey(sender)
    local sentCount = 0
    for _, domain in ipairs(manifest.domains or {}) do
      local domainState = type(manifest.byDomain[domain]) == "table" and manifest.byDomain[domain] or nil
      local messageParts = BuildProfileSyncSubcheckMessageParts(domain, domainState and domainState.subchecksums or {})
      local responseToken = string.format("PSC-%d-%d", tonumber(time and time() or 0) or 0, math.random(1000, 9999))
      local domainSent = true
      for partIndex, partPayload in ipairs(messageParts) do
        local sent = SendComm(
          "PSUB_STATE",
          "WHISPER",
          target,
          sessionId,
          profileName,
          localProfileId,
          domain,
          TrimText(domainState and domainState.checksum or ""),
          partPayload,
          responseToken,
          tostring(partIndex),
          tostring(#messageParts)
        )
        if not sent then
          domainSent = false
          break
        end
      end
      if domainSent then
        sentCount = sentCount + 1
      end
    end
    if sentCount > 0 then
      SetProfileSyncRuntimeState(sessionId, activeProfileName, "member_sent_subchecks", "success",
        "Sent detailed shared-profile checksum scopes to the session host.", {
          sender = target,
          refreshEditor = false,
        })
    end
  end

  local function HandleProfileSubchecksumState(fields, sender)
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local profileId = TrimText(fields[4])
    local domain = string.lower(TrimText(fields[5]))
    local domainChecksum = TrimText(fields[6])
    local encodedSubchecks = TrimText(fields[7])
    local responseToken = TrimText(fields[8])
    local partIndex = math.max(1, tonumber(fields[9]) or 1)
    local partTotal = math.max(partIndex, tonumber(fields[10]) or 1)
    if sessionId == "" or profileName == "" or domain == "" then
      return
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not DoesActiveSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      return
    end
    if selfKey == "" then
      return
    end

    local senderKey = NormalizeSenderKey(sender)
    local selfIsHost = IsActiveSessionHostSender(activeSession, selfKey)
    if selfIsHost then
      if not IsJoinedSessionCharacter(activeSession, senderKey) then
        return
      end
    else
      if not IsActiveSessionHostSender(activeSession, sender) then
        return
      end
      if not IsJoinedSessionCharacter(activeSession, selfKey) then
        return
      end
    end
    if senderKey == "" then
      return
    end

    if responseToken ~= "" and partTotal > 1 then
      encodedSubchecks = RememberPendingMemberSubchecksumPayload(
        sessionId,
        senderKey,
        domain,
        responseToken,
        partIndex,
        partTotal,
        encodedSubchecks
      )
      if encodedSubchecks == nil then
        return
      end
    end

    RememberMemberSubchecksumState(
      sessionId,
      senderKey,
      profileName,
      profileId,
      domain,
      domainChecksum,
      DecodeProfileSyncSubchecks(domain, encodedSubchecks)
    )
    local patchCache = GetMemberPatchManifestSessionCache(sessionId, false)
    if type(patchCache) == "table" then
      patchCache[string.lower(senderKey)] = nil
    end
    local patchRequestPrefix = string.lower(TrimText(sessionId)) .. "|" .. string.lower(senderKey) .. "|"
    for stamp in pairs(recentPatchManifestRequests) do
      if stamp:sub(1, #patchRequestPrefix) == patchRequestPrefix then
        recentPatchManifestRequests[stamp] = nil
      end
    end
    local senderCandidate = nil
    for _, candidate in ipairs(GetActiveProfileSyncCandidates() or {}) do
      if NormalizeCharacterKey(type(candidate) == "table" and candidate.memberKey or "") == senderKey then
        senderCandidate = candidate
        break
      end
    end
    if type(senderCandidate) == "table"
      and senderCandidate.patchPushReady ~= true
      and type(senderCandidate.patchPushSubdomains) == "table"
      and #senderCandidate.patchPushSubdomains > 0
    then
      QueueAutoPatchManifestRequest(senderKey, senderCandidate.patchPushSubdomains)
    end
    SetProfileSyncRuntimeState(sessionId, activeProfileName, "subchecks_loaded", "info",
      "Loaded detailed checksum scopes from " .. tostring(senderKey) .. " for "
        .. tostring(PROFILE_REVISION_DOMAIN_LABELS[domain] or domain) .. ".", {
        sender = senderKey,
        refreshEditor = false,
      })
    RefreshEditor()
  end

  local function HandleProfileSubdomainPatchManifestRequest(fields, sender)
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local profileId = TrimText(fields[4])
    local requestedSubdomains = type(FilterLootProfilePatchCapableSubdomains) == "function"
      and FilterLootProfilePatchCapableSubdomains(fields[5])
      or CloneProfileSyncSubdomainList(fields[5])
    if sessionId == "" or profileName == "" or #requestedSubdomains == 0 then
      return
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not DoesActiveSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      return
    end
    if not IsActiveSessionHostSender(activeSession, sender) then
      return
    end
    if not IsCurrentGroupCharacter(NormalizeSenderKey(sender)) then
      return
    end
    if selfKey == "" or not IsJoinedSessionCharacter(activeSession, selfKey) then
      return
    end

    local localProfileId = TrimText(select(1, GetLootProfileId(activeProfileName)) or "")
    if profileId ~= "" and localProfileId ~= "" and string.lower(profileId) ~= string.lower(localProfileId) then
      return
    end

    local target = NormalizeSenderKey(sender)
    local _, sentCount = SendProfileSubdomainPatchManifest(activeProfileName, sessionId, target, requestedSubdomains)
    sentCount = math.max(0, tonumber(sentCount) or 0)
    if sentCount > 0 then
      SetProfileSyncRuntimeState(sessionId, activeProfileName, "member_sent_patch_manifest", "success",
        "Sent nested patch manifests to the session host.", {
          sender = target,
          refreshEditor = false,
        })
    end
  end

  local function HandleProfileSubdomainPatchManifestState(fields, sender)
    local sessionId = TrimText(fields[2])
    local profileName = TrimText(fields[3])
    local profileId = TrimText(fields[4])
    local responseToken = TrimText(fields[5])
    local partIndex = math.max(1, tonumber(fields[6]) or 1)
    local partTotal = math.max(partIndex, tonumber(fields[7]) or 1)
    local chunkPayload = tostring(fields[8] or "")
    if sessionId == "" or profileName == "" then
      return
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not DoesActiveSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      return
    end
    if selfKey == "" or not IsActiveSessionHostSender(activeSession, selfKey) then
      return
    end

    local senderKey = NormalizeSenderKey(sender)
    if not IsJoinedSessionCharacter(activeSession, senderKey) then
      return
    end
    local localProfileId = TrimText(select(1, GetLootProfileId(activeProfileName)) or "")
    if profileId ~= "" and localProfileId ~= "" and string.lower(profileId) ~= string.lower(localProfileId) then
      return
    end

    local manifestData = chunkPayload
    if responseToken ~= "" and partTotal > 1 then
      manifestData = RememberPendingMemberPatchManifestPayload(sessionId, senderKey, responseToken, partIndex, partTotal, chunkPayload)
      if manifestData == nil then
        return
      end
    end

    local manifestSummary = type(PreviewLootProfileSubdomainPatchManifest) == "function"
      and PreviewLootProfileSubdomainPatchManifest(manifestData)
      or nil
    if type(manifestSummary) ~= "table" then
      return
    end

    RememberMemberPatchManifestState(sessionId, senderKey, profileName, profileId, manifestSummary, responseToken)
    SetProfileSyncRuntimeState(sessionId, activeProfileName, "patch_manifest_loaded", "info",
      "Loaded nested patch manifests from " .. tostring(senderKey) .. ".", {
        sender = senderKey,
        refreshEditor = false,
      })
    RefreshEditor()
  end

  local function HandleProfileSyncChunk(fields, sender)
    local transferId = TrimText(fields[2])
    local chunkIndex = tonumber(fields[3]) or 0
    local chunkData = tostring(fields[4] or "")
    if transferId == "" or chunkIndex < 1 then
      return
    end
    local syncState = pendingProfileSyncs[transferId]
    if type(syncState) ~= "table" then
      return
    end
    if NormalizeSenderKey(sender) ~= TrimText(syncState.sender) then
      return
    end
    syncState.chunks[chunkIndex] = chunkData
  end

  local function HandleProfileSyncEnd(fields, sender)
    local transferId = TrimText(fields[2])
    if transferId == "" then
      return
    end
    local syncState = pendingProfileSyncs[transferId]
    if type(syncState) ~= "table" then
      return
    end
    pendingProfileSyncs[transferId] = nil

    if NormalizeSenderKey(sender) ~= TrimText(syncState.sender) then
      return
    end

    local activeSession, activeProfileName = GetActiveLootSession()
    if not activeSession or activeSession.id ~= syncState.sessionId then
      return
    end
    if syncState.liveSync or syncState.reviewSync or syncState.previewSync then
      if not IsJoinedSessionCharacter(activeSession, NormalizeSenderKey(sender)) then
        return
      end
    elseif not IsActiveSessionHostSender(activeSession, sender) then
      return
    end

    local parts = {}
    for index = 1, tonumber(syncState.chunkCount) or 0 do
      local chunk = syncState.chunks[index]
      if type(chunk) ~= "string" then
        if type(activeSession) == "table" and activeSession.id == syncState.sessionId then
          activeSession.sharedProfileReady = false
        end
        SetProfileSyncRuntimeState(syncState.sessionId, syncState.profileName, "host_snapshot_incomplete", "warn",
          "The host snapshot was incomplete. Ask the host to resend the shared profile update.", {
            sender = NormalizeSenderKey(sender),
            refreshEditor = false,
          })
        Print("The shared profile snapshot from the session host was incomplete. Ask the host to use Push Host Repair or resend the invite.")
        return
      end
      parts[#parts + 1] = chunk
    end

    local targetProfileName = TrimText(syncState.targetProfileName)
    if targetProfileName == "" then
      targetProfileName = TrimText(activeProfileName)
    end
    if targetProfileName == "" then
      targetProfileName = ResolveLocalSharedProfileName(syncState.profileName, syncState.profileId, "")
    end
    if targetProfileName == "" then
      return
    end

    local snapshotData = table.concat(parts)
    local previewSummary = PreviewProfileTransferSnapshot(snapshotData)
    if type(previewSummary) ~= "table" then
      Print("Could not inspect the incoming shared profile snapshot.")
      return
    end
    if syncState.profileId ~= "" and previewSummary.profileId ~= "" and string.lower(previewSummary.profileId) ~= string.lower(syncState.profileId) then
      Print("Ignored incoming shared profile snapshot because the profile identity did not match.")
      return
    end

    local comparedDomains = MergeProfileRevisionDomains(syncState.scopeDomains, previewSummary.scopeDomains)
    local remoteNewerDomains = {}
    local localNewerDomains = {}
    local reviewSyncDetailDiff = nil
    local reviewSyncDetailConflict = nil
    local reviewLocalRevisionSummary = nil

    if syncState.reviewSync or syncState.previewSync then
      reviewLocalRevisionSummary = NormalizeRevisionSummary(syncState.localRevisionSummary, targetProfileName, syncState.profileId)
      remoteNewerDomains, localNewerDomains = CompareProfileRevisionSummaries(reviewLocalRevisionSummary, previewSummary, comparedDomains)
      reviewSyncDetailDiff = BuildProfileTransferDiff(targetProfileName, snapshotData)
      if type(reviewSyncDetailDiff) == "table" then
        reviewSyncDetailDiff.memberKey = NormalizeSenderKey(sender)
        reviewSyncDetailDiff.profileName = targetProfileName
        reviewSyncDetailDiff.remoteDomains = CloneProfileSyncDomainList(remoteNewerDomains)
        reviewSyncDetailDiff.localDomains = CloneProfileSyncDomainList(localNewerDomains)
        reviewSyncDetailDiff.comparison = select(1, ResolveProfileSyncComparison(reviewLocalRevisionSummary, previewSummary))
      end
      if syncState.previewSync and type(BuildLootProfileTransferConflictPreview) == "function" then
        reviewSyncDetailConflict = BuildLootProfileTransferConflictPreview(targetProfileName, snapshotData)
        if type(reviewSyncDetailConflict) == "table" then
          reviewSyncDetailConflict.memberKey = NormalizeSenderKey(sender)
          reviewSyncDetailConflict.profileName = targetProfileName
          reviewSyncDetailConflict.remoteDomains = CloneProfileSyncDomainList(remoteNewerDomains)
          reviewSyncDetailConflict.localDomains = CloneProfileSyncDomainList(localNewerDomains)
          reviewSyncDetailConflict.comparison = select(1, ResolveProfileSyncComparison(reviewLocalRevisionSummary, previewSummary))
          reviewSyncDetailConflict.previewProfileId = TrimText(previewSummary.profileId)
        end
      end
    end

    if syncState.previewSync then
      SetProfileSyncRuntimeState(syncState.sessionId, syncState.profileName, "preview_snapshot_received", "success",
        "Received a member change preview snapshot from " .. tostring(NormalizeSenderKey(sender)) .. ".", {
          sender = NormalizeSenderKey(sender),
          remoteDomains = remoteNewerDomains,
          localDomains = localNewerDomains,
          detailDiff = reviewSyncDetailDiff,
          detailConflict = reviewSyncDetailConflict,
          detailSnapshotData = snapshotData,
          detailPreviewSummary = previewSummary,
          detailBaseSummary = reviewLocalRevisionSummary,
          refreshEditor = false,
        })
      Print("Received a member change preview snapshot from " .. tostring(NormalizeSenderKey(sender)) .. ".")
      RefreshEditor()
      return
    end

    local function ApplyIncomingProfileSnapshot(mode, successMessage)
      local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
      local hostSideApply = type(activeSession) == "table" and NormalizeCharacterKey(activeSession.host or "") == selfKey
      if hostSideApply and type(PushUndoSnapshot) == "function" then
        PushUndoSnapshot(targetProfileName, {
          kind = mode,
          memberKey = NormalizeSenderKey(sender),
          profileId = TrimText(syncState.profileId),
          summary = "Before applying incoming shared profile data from " .. tostring(NormalizeSenderKey(sender)) .. ".",
        })
      end
      local ok, result = ImportProfileTransferSnapshot(
        targetProfileName,
        snapshotData,
        syncState.profileId,
        NormalizeSenderKey(sender),
        previewSummary.transferKind
      )
      if not ok then
        if type(activeSession) == "table" and activeSession.id == syncState.sessionId then
          activeSession.sharedProfileReady = false
        end
        SetProfileSyncRuntimeState(syncState.sessionId, syncState.profileName, mode .. "_failed", "warn",
          "The incoming shared profile update could not be applied.", {
            sender = NormalizeSenderKey(sender),
            refreshEditor = false,
          })
        Print(tostring(result or "Could not apply incoming profile snapshot."))
        return false
      end

      if type(activeSession) == "table" and activeSession.id == syncState.sessionId then
        local profile = type(GetLootProfile) == "function" and select(1, GetLootProfile(targetProfileName)) or nil
        if type(profile) == "table" and type(NormalizeLootRollOptions) == "function" then
          activeSession.rollOptions = NormalizeLootRollOptions(profile.settings and profile.settings.rollOptions)
        end
        if type(activeSession.members) == "table" then
          for memberKey, member in pairs(activeSession.members) do
            if type(member) == "table" then
              if type(GetLootProfileMaster) == "function" then
                member.profileMaster = GetLootProfileMaster(targetProfileName)
              end
              if type(GetLootProfileRole) == "function" then
                member.role = GetLootProfileRole(targetProfileName, memberKey)
              end
            end
          end
        end
        local senderKey = NormalizeSenderKey(sender)
        local senderMember = type(activeSession.members) == "table" and activeSession.members[senderKey] or nil
        if type(senderMember) == "table" then
          senderMember.sharedProfileId = TrimText(previewSummary.profileId)
          senderMember.settingsRevision = tonumber(previewSummary.settings) or 0
          senderMember.permissionsRevision = tonumber(previewSummary.permissions) or 0
          senderMember.operationalRevision = tonumber(previewSummary.operational) or 0
          senderMember.lootRevision = tonumber(previewSummary.loot) or tonumber(previewSummary.operational) or 0
          senderMember.sessionRevision = tonumber(previewSummary.session) or tonumber(previewSummary.operational) or 0
          senderMember.settingsChecksum = TrimText(previewSummary.settingsChecksum)
          senderMember.permissionsChecksum = TrimText(previewSummary.permissionsChecksum)
          senderMember.operationalChecksum = TrimText(previewSummary.operationalChecksum)
          senderMember.lootChecksum = TrimText(previewSummary.lootChecksum)
          senderMember.sessionChecksum = TrimText(previewSummary.sessionChecksum)
          senderMember.profileUpdatedAt = tonumber(previewSummary.updatedAt) or tonumber(time and time() or 0) or 0
          senderMember.lastSyncAt = tonumber(time and time() or 0) or 0
        end
        activeSession.sharedProfileReady = true
        activeSession.__sharedProfilePendingNoticeShown = nil
      end
      ActivateLocalSessionProfile(targetProfileName)
      SetProfileSyncRuntimeState(syncState.sessionId, syncState.profileName, mode, "success",
        successMessage or "Applied incoming shared profile update.", {
          sender = NormalizeSenderKey(sender),
          remoteDomains = CloneProfileSyncDomainList(remoteNewerDomains or {}),
          localDomains = CloneProfileSyncDomainList(localNewerDomains or {}),
          detailDiff = reviewSyncDetailDiff,
          refreshEditor = false,
        })
      if hostSideApply and type(RecordRepairHistory) == "function" and string.find(string.lower(tostring(mode or "")), "applied", 1, true) then
        RecordRepairHistory({
          profileName = targetProfileName,
          sessionId = TrimText(syncState.sessionId),
          memberKey = NormalizeSenderKey(sender),
          kind = mode,
          summary = successMessage or "Applied incoming shared profile update.",
          createdAt = GetNow(),
        })
      end
      SendLocalProfileStateToHost(syncState.sessionId, syncState.profileName, targetProfileName)
      SendProfileSyncAck(syncState, targetProfileName, previewSummary)
      local refreshChoicePopup = type(ResolveOptionalApiFunction) == "function" and ResolveOptionalApiFunction("LIDCOUNCIL_RefreshChoicePopup") or nil
      if type(refreshChoicePopup) == "function" then
        refreshChoicePopup()
      end
      RefreshEditor()
      return true
    end

    if syncState.reviewSync then
      if ApplyIncomingProfileSnapshot("review_snapshot_applied", "Applied requested shared-profile update from " .. tostring(NormalizeSenderKey(sender)) .. ".") then
        Print("Applied requested shared-profile update from " .. tostring(NormalizeSenderKey(sender)) .. ".")
      end
      return
    end

    if not syncState.hadLocalSharedProfile then
      if not ApplyIncomingProfileSnapshot("received_missing_copy", "Received a missing shared profile copy from the session.") then
        return
      end
      Print("Received shared profile \"" .. tostring(syncState.profileName) .. "\" from " .. tostring(NormalizeSenderKey(sender)) .. ".")
      return
    end

    local localRevisionSummary = NormalizeRevisionSummary(syncState.localRevisionSummary, targetProfileName, syncState.profileId)
    remoteNewerDomains, localNewerDomains = CompareProfileRevisionSummaries(localRevisionSummary, previewSummary, comparedDomains)

    if syncState.liveSync then
      if #remoteNewerDomains == 0 then
        return
      end
      ApplyIncomingProfileSnapshot("live_update_applied", "Applied a live shared profile update from " .. tostring(NormalizeSenderKey(sender)) .. ".")
      return
    end

    if #remoteNewerDomains == 0 then
      if #localNewerDomains > 0 then
        SetProfileSyncRuntimeState(syncState.sessionId, syncState.profileName, "kept_local_newer", "info",
          "Kept your local shared profile copy because it is newer than the host copy.", {
            sender = NormalizeSenderKey(sender),
            localDomains = localNewerDomains,
            refreshEditor = false,
          })
        Print("Kept your local shared profile copy for \"" .. tostring(syncState.profileName) .. "\" because it is newer than the session host version.")
      end
      return
    end

    if #localNewerDomains > 0 then
      SetProfileSyncRuntimeState(syncState.sessionId, syncState.profileName, "diverged_local_and_host", "warn",
        "Kept your local shared profile copy because both versions changed.", {
          sender = NormalizeSenderKey(sender),
          remoteDomains = remoteNewerDomains,
          localDomains = localNewerDomains,
          refreshEditor = false,
        })
      Print(
        "Kept your local shared profile copy for \"" .. tostring(syncState.profileName) .. "\" because both versions changed."
        .. " Host newer: " .. FormatProfileRevisionDomains(remoteNewerDomains)
        .. ". Local newer: " .. FormatProfileRevisionDomains(localNewerDomains) .. "."
      )
      return
    end

    SetProfileSyncRuntimeState(syncState.sessionId, syncState.profileName, "update_available", "warn",
      "A newer host shared profile update is ready for review.", {
        sender = NormalizeSenderKey(sender),
        remoteDomains = remoteNewerDomains,
        refreshEditor = false,
      })
    Print(
      "A newer shared profile update is available from the session host for \"" .. tostring(syncState.profileName)
      .. "\". Review the popup to accept it or keep your local copy."
    )
    ShowProfileSyncPopup({
      sessionId = syncState.sessionId,
      profileName = syncState.profileName,
      targetProfileName = targetProfileName,
      profileId = syncState.profileId,
      sender = NormalizeSenderKey(sender),
      snapshotData = snapshotData,
      transferKind = previewSummary.transferKind,
      remoteDomainText = FormatProfileRevisionDomains(remoteNewerDomains),
      remoteDomains = CloneProfileSyncDomainList(remoteNewerDomains),
    })
  end

  local function HandleProfileSyncAck(fields, sender)
    local transferId = TrimText(fields[2])
    local sessionId = TrimText(fields[3])
    local profileName = TrimText(fields[4])
    local sharedProfileId = TrimText(fields[5])
    local chunkCount = math.max(0, tonumber(fields[6]) or 0)
    local settingsRevision = math.max(0, tonumber(fields[7]) or 0)
    local permissionsRevision = math.max(0, tonumber(fields[8]) or 0)
    local operationalRevision = math.max(0, tonumber(fields[9]) or 0)
    local profileUpdatedAt = math.max(0, tonumber(fields[10]) or 0)
    local settingsChecksum = TrimText(fields[11])
    local permissionsChecksum = TrimText(fields[12])
    local operationalChecksum = TrimText(fields[13])
    local lootRevision = math.max(0, tonumber(fields[14]) or operationalRevision)
    local sessionRevision = math.max(0, tonumber(fields[15]) or operationalRevision)
    local lootChecksum = TrimText(fields[16])
    if lootChecksum == "" then
      lootChecksum = operationalChecksum
    end
    local sessionChecksum = TrimText(fields[17])
    if sessionChecksum == "" then
      sessionChecksum = operationalChecksum
    end

    if transferId == "" or sessionId == "" or profileName == "" then
      return
    end
    local activeSession, activeProfileName = GetActiveLootSession()
    local selfKey = NormalizeCharacterKey(GetCharacterKey() or "")
    if not DoesActiveSessionMatch(activeSession, activeProfileName, sessionId, profileName) then
      return
    end
    if selfKey == "" or not IsActiveSessionHostSender(activeSession, selfKey) then
      return
    end
    if not IsJoinedSessionCharacter(activeSession, NormalizeSenderKey(sender)) then
      return
    end

    local localProfileName = TrimText(activeProfileName) ~= "" and activeProfileName or profileName
    local senderKey = NormalizeSenderKey(sender)
    local outboundTransfer = type(MarkOutboundProfileTransferAcked) == "function"
      and MarkOutboundProfileTransferAcked(transferId, senderKey)
      or nil
    if type(outboundTransfer) == "table" and type(outboundTransfer.patchManifestSummary) == "table" then
      RememberMemberPatchManifestState(
        sessionId,
        senderKey,
        FirstNonEmptyText(outboundTransfer.profileName, localProfileName),
        FirstNonEmptyText(outboundTransfer.profileId, sharedProfileId),
        outboundTransfer.patchManifestSummary,
        ""
      )
    end
    local ok, member
    if type(UpsertLootSessionMember) == "function" then
      ok, member = UpsertLootSessionMember(localProfileName, sessionId, senderKey, {
        sharedProfileId = sharedProfileId,
        settingsRevision = settingsRevision,
        permissionsRevision = permissionsRevision,
        operationalRevision = operationalRevision,
        lootRevision = lootRevision,
        sessionRevision = sessionRevision,
        settingsChecksum = settingsChecksum,
        permissionsChecksum = permissionsChecksum,
        operationalChecksum = operationalChecksum,
        lootChecksum = lootChecksum,
        sessionChecksum = sessionChecksum,
        profileUpdatedAt = profileUpdatedAt,
        lastSyncAt = time and time() or 0,
        suppressProfileTouch = true,
      })
    end
    if ok then
      local broadcastMemberUpdate = type(ResolveOptionalApiFunction) == "function" and ResolveOptionalApiFunction("LIDCOUNCIL_BroadcastSessionMemberUpdate") or nil
      if type(broadcastMemberUpdate) == "function" then
        broadcastMemberUpdate(
          localProfileName,
          sessionId,
          senderKey,
          member or (type(activeSession.members) == "table" and activeSession.members[senderKey]) or {}
        )
      end
    end
    SetProfileSyncRuntimeState(sessionId, localProfileName, "snapshot_ack", "success",
      "Profile snapshot was applied by " .. tostring(senderKey) .. " (" .. tostring(chunkCount) .. " chunks).", {
        sender = senderKey,
        refreshEditor = false,
      })
    RefreshEditor()
  end

  return {
    BuildEmptyRevisionSummary = BuildEmptyRevisionSummary,
    NormalizeRevisionSummary = NormalizeRevisionSummary,
    CompareProfileRevisionSummaries = CompareProfileRevisionSummaries,
    FormatProfileRevisionDomains = FormatProfileRevisionDomains,
    GetActiveProfileSyncCandidates = GetActiveProfileSyncCandidates,
    GetActiveProfileSyncStatus = GetActiveProfileSyncStatus,
    GetActiveProfileSyncConflictPreview = GetActiveProfileSyncConflictPreview,
    ApplyActiveProfilePreviewConflictResolution = ApplyActiveProfilePreviewConflictResolution,
    RememberSharedReplicaPlaceholder = RememberSharedReplicaPlaceholder,
    ResolveLocalSharedProfileName = ResolveLocalSharedProfileName,
    EnsureProfileSyncPopup = EnsureProfileSyncPopup,
    PrepareProfileSnapshotTransfer = PrepareProfileSnapshotTransfer,
    BuildPreparedProfileRepairTransfers = BuildPreparedProfileRepairTransfers,
    HasLoadedPatchManifestSubdomains = HasLoadedPatchManifestSubdomains,
    SendProfileSubdomainPatchManifest = SendProfileSubdomainPatchManifest,
    SendPreparedProfileSnapshot = SendPreparedProfileSnapshot,
    SendProfileSnapshot = SendProfileSnapshot,
    SendPreparedProfileSnapshotBatch = SendPreparedProfileSnapshotBatch,
    SendProfileSnapshotBatch = SendProfileSnapshotBatch,
    SendLocalProfileStateToHost = SendLocalProfileStateToHost,
    DelayProfileSnapshotBatchForJoins = DelayProfileSnapshotBatchForJoins,
    GetProfileSnapshotBatchStatus = GetProfileSnapshotBatchStatus,
    CancelProfileSnapshotBatchForSession = CancelProfileSnapshotBatchForSession,
    HandleProfileSyncStart = HandleProfileSyncStart,
    HandleProfileSyncRequest = HandleProfileSyncRequest,
    HandleProfileSyncChunk = HandleProfileSyncChunk,
    HandleProfileSyncEnd = HandleProfileSyncEnd,
    HandleProfileSyncAck = HandleProfileSyncAck,
    HandleProfileSubchecksumRequest = HandleProfileSubchecksumRequest,
    HandleProfileSubchecksumState = HandleProfileSubchecksumState,
    HandleProfileSubdomainPatchManifestRequest = HandleProfileSubdomainPatchManifestRequest,
    HandleProfileSubdomainPatchManifestState = HandleProfileSubdomainPatchManifestState,
  }
end
