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

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

  local ApplyFrameSkin = deps.ApplyFrameSkin
  local RootDB = deps.RootDB
  local TrimText = deps.TrimText
  local ResolveSessionDisplayInfo = deps.ResolveSessionDisplayInfo
  local ResolveSessionSyncState = deps.ResolveSessionSyncState
  local ResolveSessionBootstrapState = deps.ResolveSessionBootstrapState
  local ResolveSessionIconData = deps.ResolveSessionIconData
  local ApplySessionIcon = deps.ApplySessionIcon
  local GetSessionClassColor = deps.GetSessionClassColor
  local GetSessionSyncLabel = deps.GetSessionSyncLabel
  local GetSessionSyncDescription = deps.GetSessionSyncDescription
  local GetSessionBootstrapLabel = deps.GetSessionBootstrapLabel
  local GetSessionBootstrapDescription = deps.GetSessionBootstrapDescription
  local GetSessionBootstrapColor = deps.GetSessionBootstrapColor
  local ApplyTrafficLight = deps.ApplyTrafficLight
  local GetTrafficLightColor = deps.GetTrafficLightColor
  local GetSessionStatusColor = deps.GetSessionStatusColor
  local GetLocalAutoPassEnabled = deps.GetLocalAutoPassEnabled
  local FormatDateTime = deps.FormatDateTime
  local FlowLayoutControls = deps.FlowLayoutControls
  local ClampLayoutValue = deps.ClampLayoutValue

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

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

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

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

  local function BuildSessionMemberColumnLayout(rowWidth)
    local resolvedWidth = math.max(260, math.floor(tonumber(rowWidth) or 260))
    local nameX = 36
    local gap = 8
    local minNameWidth = resolvedWidth < 420 and 72 or (resolvedWidth < 560 and 96 or 140)
    local rightBudget = math.max(120, resolvedWidth - nameX - minNameWidth - 12)
    local distributedWidth = math.max(96, rightBudget - (gap * 4))
    local syncWidth = ClampLayoutValue(math.floor(distributedWidth * 0.12), 46, 72)
    local versionWidth = ClampLayoutValue(math.floor(distributedWidth * 0.10), 44, 58)
    local statusWidth = ClampLayoutValue(math.floor(distributedWidth * 0.18), 64, 84)
    local joinedWidth = ClampLayoutValue(math.floor(distributedWidth * 0.32), 92, 156)
    local autoPassWidth = ClampLayoutValue(math.floor(distributedWidth * 0.16), 72, 86)
    local totalRightWidth = syncWidth + versionWidth + statusWidth + joinedWidth + autoPassWidth + (gap * 4)
    local nameWidth = resolvedWidth - nameX - totalRightWidth - 12

    local function ShrinkWidth(current, minimum, amount)
      if amount <= 0 or current <= minimum then
        return current, amount
      end
      local reduced = math.min(amount, current - minimum)
      return current - reduced, amount - reduced
    end

    if nameWidth < minNameWidth then
      local shortage = minNameWidth - nameWidth
      joinedWidth, shortage = ShrinkWidth(joinedWidth, 84, shortage)
      statusWidth, shortage = ShrinkWidth(statusWidth, 58, shortage)
      versionWidth, shortage = ShrinkWidth(versionWidth, 44, shortage)
      syncWidth, shortage = ShrinkWidth(syncWidth, 42, shortage)
      autoPassWidth, shortage = ShrinkWidth(autoPassWidth, 64, shortage)
      totalRightWidth = syncWidth + versionWidth + statusWidth + joinedWidth + autoPassWidth + (gap * 4)
      nameWidth = math.max(40, resolvedWidth - nameX - totalRightWidth - 12)
    end

    local autoPassX = resolvedWidth - autoPassWidth
    local joinedX = autoPassX - joinedWidth - gap
    local statusX = joinedX - statusWidth - gap
    local versionX = statusX - versionWidth - gap
    local syncX = versionX - syncWidth - gap
    return {
      rowWidth = resolvedWidth,
      nameX = nameX,
      nameWidth = nameWidth,
      joinedX = joinedX,
      joinedWidth = joinedWidth,
      statusX = statusX,
      statusWidth = statusWidth,
      versionX = versionX,
      versionWidth = versionWidth,
      syncX = syncX,
      syncWidth = syncWidth,
      autoPassX = autoPassX,
      autoPassWidth = autoPassWidth,
    }
  end

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

    for memberKey, member in pairs(activeSession.members or {}) do
      local resolvedKey = TrimText(memberKey ~= "" and memberKey or (type(member) == "table" and member.name) or "")
      if resolvedKey ~= "" then
        local memberStatus = TrimText(type(member) == "table" and member.status or "JOINED")
        if string.upper(memberStatus) ~= "REMOVED" then
          local displayInfo = ResolveSessionDisplayInfo(profile, resolvedKey, member)
          local syncState = ResolveSessionSyncState(member, resolvedKey, activeSession, selfCharacter)
          local bootstrapState = ResolveSessionBootstrapState(member, resolvedKey, activeSession, selfCharacter)
          local localAutoPassEnabled = type(member) == "table" and member.localAutoPassEnabled
          if localAutoPassEnabled == nil and resolvedKey == TrimText(selfCharacter) and type(GetLocalAutoPassEnabled) == "function" then
            localAutoPassEnabled = GetLocalAutoPassEnabled() and true or false
          end
          if localAutoPassEnabled == nil then
            localAutoPassEnabled = true
          end
          rows[#rows + 1] = {
            key = resolvedKey,
            name = resolvedKey,
            status = memberStatus,
            joinedAt = tonumber(type(member) == "table" and member.joinedAt) or nil,
            addonVersion = TrimText(type(member) == "table" and member.addonVersion or ""),
            clientVersion = TrimText(type(member) == "table" and member.clientVersion or ""),
            className = displayInfo.className,
            classFile = displayInfo.classFile,
            specName = displayInfo.specName,
            specIcon = displayInfo.specIcon,
            localAutoPassEnabled = localAutoPassEnabled and true or false,
            syncState = syncState,
            bootstrapState = bootstrapState,
            isHost = resolvedKey == TrimText(activeSession.host),
            isSelf = resolvedKey == TrimText(selfCharacter),
          }
        end
      end
    end

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

    return rows
  end

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    local activeSession = context.activeSession
    local activeSessionProfile = context.activeSessionProfile
    local selfCharacter = TrimText(context.selfCharacter)
    local activeSessionIsHost = context.activeSessionIsHost and true or false
    local activeSessionIsJoined = context.activeSessionIsJoined and true or false
    local activeProfileName = context.activeProfileName
    local profileName = context.profileName
    local roleLabel = tostring(context.roleLabel or "")
    local liveSummaryState = context.liveSummaryState

    local memberRowsData = activeSession and BuildSessionMemberRowsData(activeSession, activeSessionProfile, selfCharacter) or {}
    local overallSyncState = ResolveOverallSyncState(memberRowsData)
    local overallBootstrapCounts = ResolveOverallBootstrapCounts(memberRowsData)

    EnsureSessionMemberRows(editor, math.max(1, #memberRowsData))
    local selectedMemberKey = TrimText(editor.lootSessionSelectedMemberKey)
    local selectedStillVisible = false
    for index, row in ipairs(editor.lootSessionMemberRows or {}) do
      local data = memberRowsData[index]
      if data then
        if selectedMemberKey ~= "" and string.lower(selectedMemberKey) == string.lower(data.key) then
          selectedStillVisible = true
        end
        local iconData = ResolveSessionIconData(data)
        local r, g, b = GetSessionClassColor(data.classFile)
        local syncR, syncG, syncB = GetTrafficLightColor(data.syncState)
        local bootstrapR, bootstrapG, bootstrapB = GetSessionBootstrapColor(data.bootstrapState)
        local statusR, statusG, statusB = GetSessionStatusColor(data.status)
        local roleText = data.specName ~= "" and data.specName or (data.className ~= "" and data.className or "Unknown")
        if data.isHost then
          roleText = roleText .. " | Host"
        elseif data.isSelf then
          roleText = roleText .. " | You"
        end
        ApplySessionIcon(row.icon, iconData)
        row.nameText:SetText(data.name)
        row.nameText:SetTextColor(r, g, b, 1)
        if data.clientVersion ~= "" then
          row.metaText:SetText(roleText .. " | WoW " .. data.clientVersion .. " | " .. GetSessionBootstrapLabel(data.bootstrapState))
        else
          row.metaText:SetText(roleText .. " | " .. GetSessionBootstrapLabel(data.bootstrapState))
        end
        row.metaText:SetTextColor(bootstrapR, bootstrapG, bootstrapB, 1)
        ApplyTrafficLight(row.syncDot, data.syncState)
        row.syncText:SetText(GetSessionSyncLabel(data.syncState))
        row.syncText:SetTextColor(syncR, syncG, syncB, 1)
        row.autoPassText:SetText(data.localAutoPassEnabled and "ON" or "OFF")
        row.autoPassText:SetTextColor(
          data.localAutoPassEnabled and 0.30 or 1.00,
          data.localAutoPassEnabled and 0.90 or 0.32,
          data.localAutoPassEnabled and 0.36 or 0.24,
          1
        )
        row.versionText:SetText(TrimText(data.addonVersion) ~= "" and data.addonVersion or "Legacy")
        row.statusText:SetText(TrimText(data.status) ~= "" and data.status or "JOINED")
        row.statusText:SetTextColor(statusR, statusG, statusB, 1)
        row.joinedText:SetText(data.joinedAt and FormatDateTime(data.joinedAt) or "-")
        row.__memberKey = data.key
        row:EnableMouse(true)
        row:SetScript("OnMouseDown", function()
          editor.lootSessionSelectedMemberKey = data.key
          if editor.Refresh then
            editor:Refresh()
          end
        end)
        local isSelected = selectedMemberKey ~= "" and string.lower(selectedMemberKey) == string.lower(data.key)
        if row.selectionFill then
          row.selectionFill:SetShown(isSelected)
        end
        if row.selectionStripe then
          row.selectionStripe:SetShown(isSelected)
        end
        if row.SetBackdropColor then
          if isSelected then
            row:SetBackdropColor(0.12, 0.18, 0.28, 0.98)
          else
            row:SetBackdropColor(0.05, 0.05, 0.07, 0.94)
          end
        end
        if row.SetBackdropBorderColor then
          if isSelected then
            row:SetBackdropBorderColor(1.00, 0.82, 0.32, 0.95)
          else
            row:SetBackdropBorderColor(0.22, 0.24, 0.30, 0.80)
          end
        end
        row:Show()
      else
        row.__memberKey = nil
        row:SetScript("OnMouseDown", nil)
        row:EnableMouse(false)
        if row.selectionFill then
          row.selectionFill:Hide()
        end
        if row.selectionStripe then
          row.selectionStripe:Hide()
        end
        if row.SetBackdropBorderColor then
          row:SetBackdropBorderColor(0.22, 0.24, 0.30, 0.80)
        end
        row:Hide()
      end
    end
    if selectedMemberKey ~= "" and not selectedStillVisible then
      editor.lootSessionSelectedMemberKey = nil
    end
    editor.lootSessionMemberRowsHeight = math.max(0, #memberRowsData * 38)

    editor.lootSessionTitle:SetText("Current Session")
    if activeSession then
      local sessionStatus = string.upper(TrimText(activeSession.status or "ACTIVE"))
      local sessionIsPreparing = sessionStatus == "PREPARING"
      local statusLabel
      local statusColor
      if sessionIsPreparing and activeSessionIsHost then
        statusLabel = "Preparation lobby open"
        statusColor = { 1.00, 0.82, 0.32, 1.00 }
      elseif sessionIsPreparing and activeSessionIsJoined then
        statusLabel = "Joined preparation lobby"
        statusColor = { 1.00, 0.82, 0.32, 1.00 }
      elseif sessionIsPreparing then
        statusLabel = "Observed preparation lobby"
        statusColor = { 0.82, 0.82, 0.86, 1.00 }
      elseif activeSessionIsHost then
        statusLabel = "Current session active"
        statusColor = { 0.20, 0.90, 0.20, 1.00 }
      elseif activeSessionIsJoined then
        statusLabel = "Joined session active"
        statusColor = { 1.00, 0.82, 0.32, 1.00 }
      else
        statusLabel = "Observed session active"
        statusColor = { 0.82, 0.82, 0.86, 1.00 }
      end
      editor.lootSessionStatus:SetText(statusLabel)
      editor.lootSessionStatus:SetTextColor(statusColor[1], statusColor[2], statusColor[3], statusColor[4])
      ApplyTrafficLight(editor.lootSessionStatusIndicator, overallSyncState)

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

      editor.lootSessionOverviewTitle:SetText(sessionIsPreparing and "Prepared LidCouncil session overview" or "Shared LidCouncil session overview")
      editor.lootSessionOverviewMeta:SetText("")
      editor.lootSessionOverviewMeta:Hide()
      local cardValues = {
        tostring(activeProfileName or activeSession.profileName or profileName),
        roleLabel,
        FormatDateTime(activeSession.startedAt),
        tostring(joinedCount),
        tostring(activeSession.host or "Unknown"),
        string.format("%d / %d", overallBootstrapCounts.ready, overallBootstrapCounts.joined),
        GetSessionSyncLabel(overallSyncState),
      }
      local hostMember = type(activeSession.members) == "table" and activeSession.members[activeSession.host] or nil
      local hostDisplay = ResolveSessionDisplayInfo(activeSessionProfile, activeSession.host, hostMember)
      local hostR, hostG, hostB = GetSessionClassColor(hostDisplay.classFile)
      local syncR, syncG, syncB = GetTrafficLightColor(overallSyncState)
      local bootstrapState = overallBootstrapCounts.review > 0 and "REVIEW"
        or (overallBootstrapCounts.pending > 0 and "PENDING" or "READY")
      local bootstrapR, bootstrapG, bootstrapB = GetSessionBootstrapColor(bootstrapState)
      for index, card in ipairs(editor.lootSessionOverviewCards or {}) do
        card.valueText:SetText(cardValues[index] or "-")
        card.valueText:SetTextColor(0.95, 0.95, 0.98, 1)
        TintSessionCard(card.frame, 0.18, 0.18, 0.22)
        if card.label == "Session Sync" then
          ApplyTrafficLight(card.dot, overallSyncState)
          card.valueText:SetTextColor(syncR, syncG, syncB, 1)
          TintSessionCard(card.frame, syncR, syncG, syncB)
          card.dot:Show()
        elseif card.label == "Roll Ready" then
          ApplyTrafficLight(card.dot, bootstrapState == "READY" and "SYNCED" or (bootstrapState == "REVIEW" and "DECLINED" or "PARTIAL"))
          card.valueText:SetTextColor(bootstrapR, bootstrapG, bootstrapB, 1)
          TintSessionCard(card.frame, bootstrapR, bootstrapG, bootstrapB)
          card.dot:Show()
        elseif card.label == "Host" then
          card.valueText:SetTextColor(hostR, hostG, hostB, 1)
          TintSessionCard(card.frame, hostR, hostG, hostB)
        else
          card.dot:Hide()
        end
      end

      if sessionIsPreparing and activeSessionIsHost then
        SetLiveSummaryText(
          editor.lootSessionLiveSummary,
          IsTutorialModeEnabled() and "Preparation: joined members and profile revisions can be checked here. Press Start Session when the host profile should become authoritative." or
            string.format(
              "Preparation: %d / %d joined member(s) are roll-ready. Full loot/session history can keep syncing in the background.",
              tonumber(overallBootstrapCounts.ready) or 0,
              tonumber(overallBootstrapCounts.joined) or 0
            ),
          true
        )
      elseif sessionIsPreparing then
        SetLiveSummaryText(
          editor.lootSessionLiveSummary,
          IsTutorialModeEnabled() and "Preparation: waiting for the host to start the active loot session." or "",
          true
        )
      elseif type(liveSummaryState) == "table" and liveSummaryState.itemCount and liveSummaryState.itemCount > 0 and activeSessionIsHost then
        local latestText = liveSummaryState.latestItem and (" | Latest: " .. tostring(liveSummaryState.latestItem)) or ""
        SetLiveSummaryText(editor.lootSessionLiveSummary, string.format(
          "Live Board: %d tracked item(s) | %d pending choice(s)%s",
          tonumber(liveSummaryState.itemCount) or 0,
          tonumber(liveSummaryState.pendingChoices) or 0,
          latestText
        ), false)
      elseif type(liveSummaryState) == "table" and liveSummaryState.isPreview then
        local latestText = liveSummaryState.latestItem and (" | Latest: " .. tostring(liveSummaryState.latestItem)) or ""
        SetLiveSummaryText(editor.lootSessionLiveSummary, string.format(
          "Live Board Simulation: %d tracked item(s) | %d pending choice(s)%s",
          tonumber(liveSummaryState.itemCount) or 0,
          tonumber(liveSummaryState.pendingChoices) or 0,
          latestText
        ), false)
      elseif activeSessionIsJoined then
        SetLiveSummaryText(
          editor.lootSessionLiveSummary,
          IsTutorialModeEnabled() and "Live Board: The host assigns loot on the board while joined members use the roll popup." or "",
          true
        )
      else
        SetLiveSummaryText(
          editor.lootSessionLiveSummary,
          IsTutorialModeEnabled() and "Live Board: Visible in the Live Board section and ready for host assignment." or "",
          true
        )
      end

      local syncExplanation = GetSessionSyncDescription(overallSyncState)
      local bootstrapStateLabel = overallBootstrapCounts.review > 0 and "REVIEW"
        or (overallBootstrapCounts.pending > 0 and "PENDING" or "READY")
      local bootstrapExplanation = GetSessionBootstrapDescription(bootstrapStateLabel)
      if activeProfileName and activeProfileName ~= profileName then
        editor.lootSessionBody:SetTextColor(0.82, 0.82, 0.86, 1.00)
        editor.lootSessionBody:SetText(
          "This active session belongs to profile \"" .. tostring(activeProfileName) .. "\". Current profile history remains unchanged until you switch profiles.\n\n" ..
          bootstrapExplanation .. "\n\n" .. syncExplanation
        )
        editor.lootSessionBody:Show()
      elseif overallSyncState ~= "SYNCED" then
        editor.lootSessionBody:SetTextColor(0.82, 0.82, 0.86, 1.00)
        editor.lootSessionBody:SetText(bootstrapExplanation .. "\n\n" .. syncExplanation)
        editor.lootSessionBody:Show()
      elseif overallBootstrapCounts.ready < overallBootstrapCounts.joined then
        editor.lootSessionBody:SetTextColor(0.82, 0.82, 0.86, 1.00)
        editor.lootSessionBody:SetText(bootstrapExplanation)
        editor.lootSessionBody:Show()
      else
        editor.lootSessionBody:SetText("")
        editor.lootSessionBody:Hide()
      end
    else
      editor.lootSessionStatus:SetText("No active session")
      editor.lootSessionStatus:SetTextColor(1.00, 0.35, 0.25, 1.00)
      ApplyTrafficLight(editor.lootSessionStatusIndicator, "PENDING")
      SetLiveSummaryText(
        editor.lootSessionLiveSummary,
        IsTutorialModeEnabled() and "Live Board: Ready. Start a session to broadcast joins and session sync status." or "",
        true
      )
      editor.lootSessionOverviewTitle:SetText("Ready to start a LidCouncil session")
      editor.lootSessionOverviewMeta:SetText("")
      editor.lootSessionOverviewMeta:Hide()
      local cardValues = {
        tostring(profileName),
        "Idle",
        "-",
        "0",
        "-",
        "0 / 0",
        "Waiting",
      }
      for index, card in ipairs(editor.lootSessionOverviewCards or {}) do
        card.valueText:SetText(cardValues[index] or "-")
        card.valueText:SetTextColor(0.95, 0.95, 0.98, 1)
        TintSessionCard(card.frame, 0.18, 0.18, 0.22)
        if card.label == "Session Sync" then
          ApplyTrafficLight(card.dot, "PENDING")
          card.dot:Show()
          TintSessionCard(card.frame, 0.70, 0.70, 0.76)
        elseif card.label == "Roll Ready" then
          ApplyTrafficLight(card.dot, "PENDING")
          card.dot:Show()
          TintSessionCard(card.frame, 1.00, 0.82, 0.28)
        else
          card.dot:Hide()
        end
      end
      if IsTutorialModeEnabled() then
        editor.lootSessionBody:SetText(
          "Use Prepare Session to invite the current party or raid into a shared LidCouncil preparation lobby.\n\n" ..
          "Joined members will appear in the table above with sync state, addon version, and join status as soon as they answer the invite."
        )
        editor.lootSessionBody:SetTextColor(1.00, 0.82, 0.24, 1.00)
        editor.lootSessionBody:Show()
      else
        editor.lootSessionBody:SetText("")
        editor.lootSessionBody:Hide()
      end
    end
  end

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

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

    local overviewTop = liveSummaryTop - liveSummaryHeight - 12

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

    local cardTop = -56
    local cardGap = 8
    local cardColumns = GetSessionOverviewCardColumns(rightContentWidth)
    local overviewInnerWidth = math.max(120, rightContentWidth - 28)
    local cardRows = math.ceil(#(editor.lootSessionOverviewCards or {}) / cardColumns)
    local cardWidth = math.max(120, math.floor((overviewInnerWidth - (cardGap * (cardColumns - 1))) / cardColumns))
    local cardHeight = 58
    local overviewHeight = 64 + (cardRows * cardHeight) + ((cardRows - 1) * cardGap)
    if editor.lootSessionOverviewFrame then
      editor.lootSessionOverviewFrame:SetHeight(overviewHeight)
    end
    for index, card in ipairs(editor.lootSessionOverviewCards or {}) do
      if card.frame then
        local rowIndex = math.floor((index - 1) / cardColumns)
        local colIndex = (index - 1) % cardColumns
        card.frame:ClearAllPoints()
        card.frame:SetPoint("TOPLEFT", 14 + (colIndex * (cardWidth + cardGap)), cardTop - (rowIndex * (cardHeight + cardGap)))
        card.frame:SetSize(cardWidth, cardHeight)
        card.valueText:SetWidth(cardWidth - 20)
        if card.valueText.SetMaxLines then
          card.valueText:SetMaxLines(1)
        end
        if card.labelText then
          card.labelText:SetWidth(cardWidth - 20)
          if card.labelText.SetMaxLines then
            card.labelText:SetMaxLines(1)
          end
        end
      end
    end

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

    local layout = BuildSessionMemberColumnLayout(rightContentWidth)
    local rowWidth = layout.rowWidth
    local joinedWidth = layout.joinedWidth
    local statusWidth = layout.statusWidth
    local versionWidth = layout.versionWidth
    local autoPassWidth = layout.autoPassWidth
    local syncWidth = layout.syncWidth
    local nameX = layout.nameX
    local joinedX = layout.joinedX
    local statusX = layout.statusX
    local versionX = layout.versionX
    local autoPassX = layout.autoPassX
    local syncX = layout.syncX
    local nameWidth = layout.nameWidth

    editor.lootSessionMemberColumns:ClearAllPoints()
    editor.lootSessionMemberColumns:SetPoint("TOPLEFT", 18, membersHeaderTop - 26)
    editor.lootSessionMemberColumns:SetSize(rowWidth, 22)

    editor.lootSessionMemberHeaderName:ClearAllPoints()
    editor.lootSessionMemberHeaderName:SetPoint("TOPLEFT", nameX, -4)
    editor.lootSessionMemberHeaderName:SetWidth(nameWidth)
    editor.lootSessionMemberHeaderSync:ClearAllPoints()
    editor.lootSessionMemberHeaderSync:SetPoint("TOPLEFT", syncX + 12, -4)
    editor.lootSessionMemberHeaderSync:SetWidth(syncWidth - 12)
    editor.lootSessionMemberHeaderAutoPass:ClearAllPoints()
    editor.lootSessionMemberHeaderAutoPass:SetPoint("TOPLEFT", autoPassX, -4)
    editor.lootSessionMemberHeaderAutoPass:SetWidth(autoPassWidth)
    editor.lootSessionMemberHeaderVersion:ClearAllPoints()
    editor.lootSessionMemberHeaderVersion:SetPoint("TOPLEFT", versionX, -4)
    editor.lootSessionMemberHeaderVersion:SetWidth(versionWidth)
    editor.lootSessionMemberHeaderStatus:ClearAllPoints()
    editor.lootSessionMemberHeaderStatus:SetPoint("TOPLEFT", statusX, -4)
    editor.lootSessionMemberHeaderStatus:SetWidth(statusWidth)
    editor.lootSessionMemberHeaderJoined:ClearAllPoints()
    editor.lootSessionMemberHeaderJoined:SetPoint("TOPLEFT", joinedX, -4)
    editor.lootSessionMemberHeaderJoined:SetWidth(joinedWidth)

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

    for index, row in ipairs(editor.lootSessionMemberRows or {}) do
      row:ClearAllPoints()
      row:SetPoint("TOPLEFT", 0, -((index - 1) * 38))
      row:SetWidth(rowWidth)
      row.icon:ClearAllPoints()
      row.icon:SetPoint("TOPLEFT", 10, -8)
      row.nameText:ClearAllPoints()
      row.nameText:SetPoint("TOPLEFT", nameX, -7)
      row.nameText:SetWidth(nameWidth)
      row.metaText:ClearAllPoints()
      row.metaText:SetPoint("TOPLEFT", nameX, -21)
      row.metaText:SetWidth(nameWidth)
      row.syncDot:ClearAllPoints()
      row.syncDot:SetPoint("TOPLEFT", syncX, -13)
      row.syncText:ClearAllPoints()
      row.syncText:SetPoint("LEFT", row.syncDot, "RIGHT", 6, 0)
      row.syncText:SetWidth(syncWidth - 14)
      row.autoPassText:ClearAllPoints()
      row.autoPassText:SetPoint("TOPLEFT", autoPassX, -13)
      row.autoPassText:SetWidth(autoPassWidth)
      row.versionText:ClearAllPoints()
      row.versionText:SetPoint("TOPLEFT", versionX, -13)
      row.versionText:SetWidth(versionWidth)
      row.statusText:ClearAllPoints()
      row.statusText:SetPoint("TOPLEFT", statusX, -13)
      row.statusText:SetWidth(statusWidth)
      row.joinedText:ClearAllPoints()
      row.joinedText:SetPoint("TOPLEFT", joinedX, -13)
      row.joinedText:SetWidth(joinedWidth)
    end

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

  return {
    RefreshCurrentSessionView = RefreshCurrentSessionView,
    LayoutCurrentSessionSection = LayoutCurrentSessionSection,
  }
end
