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_CreateLootSessionAutoPassHelpers_Impl = function(deps)
  deps = type(deps) == "table" and deps or {}

  local TrimText = deps.TrimText
  local ResolveOptionalApiFunction = deps.ResolveOptionalApiFunction
  local AUTO_PASS_ON_TEXTURE = "Interface\\AddOns\\LidCouncil\\Media\\LidCouncil\\Logos\\LidCouncil_Autopass_On.tga"
  local AUTO_PASS_OFF_TEXTURE = "Interface\\AddOns\\LidCouncil\\Media\\LidCouncil\\Logos\\LidCouncil_Autopass_Off.tga"

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

    context = type(context) == "table" and context or {}
    local activeSession = context.activeSession
    local selfCharacter = TrimText(context.selfCharacter)
    local inCombat = type(InCombatLockdown) == "function" and InCombatLockdown() and true or false

    local getLocalAutoPassEnabled = ResolveOptionalApiFunction("LIDCOUNCIL_GetLocalAutoPassEnabled")
    local hasLocalAutoPassState = type(getLocalAutoPassEnabled) == "function"
    local localAutoPassEnabled = true
    if hasLocalAutoPassState then
      localAutoPassEnabled = getLocalAutoPassEnabled() and true or false
    end
    local sessionId = TrimText(type(activeSession) == "table" and activeSession.id or "")
    local activeSessionStatus = string.upper(TrimText(type(activeSession) == "table" and activeSession.status or ""))
    local autoPassAvailable = activeSessionStatus == "PREPARING" or activeSessionStatus == "ACTIVE"
    if editor.__lidAutoPassDisplaySessionId ~= sessionId then
      editor.__lidAutoPassDisplaySessionId = sessionId
      editor.__lidAutoPassDisplayOverride = nil
    end
    local explicitState = context.localAutoPassEnabled
    if type(explicitState) == "boolean" then
      localAutoPassEnabled = explicitState
      editor.__lidAutoPassDisplayOverride = explicitState
    elseif type(editor.__lidAutoPassDisplayOverride) == "boolean" then
      localAutoPassEnabled = editor.__lidAutoPassDisplayOverride
    elseif not hasLocalAutoPassState and activeSession and type(activeSession.members) == "table" then
      -- Older clients can lack the local setting API; only then fall back to the member record.
      local selfMember = activeSession.members[selfCharacter]
      if type(selfMember) ~= "table" then
        for memberKey, member in pairs(activeSession.members) do
          if string.lower(TrimText(memberKey)) == string.lower(selfCharacter) then
            selfMember = member
            break
          end
        end
      end
      if type(selfMember) == "table" and selfMember.localAutoPassEnabled ~= nil then
        localAutoPassEnabled = selfMember.localAutoPassEnabled and true or false
      end
    end

    -- Auto-Pass only applies to a prepared lobby or an active shared session.
    -- Keep the idle page intentionally neutral, even if an old local preference remains stored.
    local showAutoPassEnabled = autoPassAvailable and localAutoPassEnabled
    if editor.lootSessionAutoPassIcon then
      editor.lootSessionAutoPassIcon:SetTexture(showAutoPassEnabled and AUTO_PASS_ON_TEXTURE or AUTO_PASS_OFF_TEXTURE)
      editor.lootSessionAutoPassIcon:Show()
    end
    if editor.lootSessionTitle then
      editor.lootSessionTitle:SetText("Personal Auto Pass")
    end
    if editor.lootSessionAutoPassStatus then
      if not autoPassAvailable then
        editor.lootSessionAutoPassStatus:SetText("Auto-Pass is unavailable until a session is prepared or started.")
        editor.lootSessionAutoPassStatus.__lid_customTextColor = { 0.82, 0.82, 0.86, 1.00 }
        editor.lootSessionAutoPassStatus:SetTextColor(0.82, 0.82, 0.86, 1.00)
      elseif inCombat then
        editor.lootSessionAutoPassStatus:SetText("Combat active. Personal Auto Pass changes are blocked until you leave combat.")
        editor.lootSessionAutoPassStatus.__lid_customTextColor = { 1.00, 0.82, 0.24, 1.00 }
        editor.lootSessionAutoPassStatus:SetTextColor(1.00, 0.82, 0.24, 1.00)
      elseif localAutoPassEnabled then
        editor.lootSessionAutoPassStatus:SetText("Auto Pass activated. Council-managed loot rolls are auto-passed on your client. Collectibles, toys, and Housing Decor stay visible as Non-Council Items. Bonus Rolls are not affected.")
        editor.lootSessionAutoPassStatus.__lid_customTextColor = { 0.30, 0.90, 0.36, 1.00 }
        editor.lootSessionAutoPassStatus:SetTextColor(0.30, 0.90, 0.36, 1.00)
      else
        editor.lootSessionAutoPassStatus:SetText("Auto Pass deactivated. You will receive the Blizzard loot roll window and the LidCouncil roll window at the same time.")
        editor.lootSessionAutoPassStatus.__lid_customTextColor = { 1.00, 0.32, 0.28, 1.00 }
        editor.lootSessionAutoPassStatus:SetTextColor(1.00, 0.32, 0.28, 1.00)
      end
    end

    if editor.lootSessionAutoPassHeader then
      editor.lootSessionAutoPassHeader:SetText(autoPassAvailable and "How Auto-Pass works" or "Session required")
    end
    if editor.lootSessionAutoPassDesc then
      if not autoPassAvailable then
        editor.lootSessionAutoPassDesc:SetText(
          "Auto-Pass only affects council-managed loot while you are in a prepared or active LidCouncil session.\n\n" ..
          "Prepare a session as host or join an existing session to manage this setting. " ..
          "Hosts default to |cffff5a5aOFF|r and joined members default to |cff4adf6bON|r for each session."
        )
      else
        editor.lootSessionAutoPassDesc:SetText(
          "Auto Pass is a |cff4adf6bpersonal setting|r.\n" ..
          "- When you |cff4adf6bstart|r a session as the host, your personal Auto Pass defaults to |cffff5a5aOFF|r.\n" ..
          "- When you |cff4adf6bjoin|r a session, your personal Auto Pass defaults to |cff4adf6bON|r.\n" ..
          "- Starting or accepting a session applies those defaults again for that session.\n" ..
          "- You can change your own setting while the session is available.\n\n" ..
          "If your personal Auto Pass is |cff4adf6bON|r, LidCouncil will auto-pass Blizzard loot rolls on your client for council-managed items.\n" ..
          "Collectibles, toys, and Housing Decor stay visible as |cffffd100Non-Council Items|r and are not auto-passed by LidCouncil.\n" ..
          "Bonus Rolls are not affected by LidCouncil Auto Pass.\n" ..
          "If your personal Auto Pass is |cffff5a5aOFF|r, you keep Blizzard's normal loot roll window."
        )
      end
    end
    if editor.lootSessionAutoPassCurrent then
      editor.lootSessionAutoPassCurrent:SetText("")
    end
    if editor.sessionAutoPassLocalBtn then
      editor.sessionAutoPassLocalBtn:SetText(localAutoPassEnabled and "Deactivate Auto-Pass" or "Activate Auto-Pass")
      editor.sessionAutoPassLocalBtn:SetShown(autoPassAvailable)
      if editor.sessionAutoPassLocalBtn.Enable then
        if not autoPassAvailable or inCombat then
          editor.sessionAutoPassLocalBtn:Disable()
        else
          editor.sessionAutoPassLocalBtn:Enable()
        end
      end
    end
    if editor.lootSessionAutoPassState then
      if not autoPassAvailable then
        editor.lootSessionAutoPassState:SetText(
          "Auto-Pass: OFF\n" ..
          "A prepared or active session is required before this setting can be changed."
        )
        editor.lootSessionAutoPassState.__lid_customTextColor = { 0.82, 0.82, 0.86, 1.00 }
        editor.lootSessionAutoPassState:SetTextColor(0.82, 0.82, 0.86, 1.00)
      elseif localAutoPassEnabled then
        editor.lootSessionAutoPassState:SetText(
          "|cff4adf6bCurrent Auto Pass: ON|r\n" ..
          "Council-managed items are passed automatically. Collectibles, toys, and Housing Decor remain visible as Non-Council Items."
        )
        editor.lootSessionAutoPassState.__lid_customTextColor = { 0.30, 0.90, 0.36, 1.00 }
        editor.lootSessionAutoPassState:SetTextColor(0.30, 0.90, 0.36, 1.00)
      else
        editor.lootSessionAutoPassState:SetText(
          "|cffff5a5aCurrent Auto Pass: OFF|r\n" ..
          "Blizzard's Loot Window appears as usual together with the LidCouncil Loot Window."
        )
        editor.lootSessionAutoPassState.__lid_customTextColor = { 1.00, 0.32, 0.28, 1.00 }
        editor.lootSessionAutoPassState:SetTextColor(1.00, 0.32, 0.28, 1.00)
      end
    end

    if editor.lootSessionBody then
      editor.lootSessionBody:SetText("")
      editor.lootSessionBody:Hide()
    end
  end

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

    if editor.sessionSyncBoardBtn then
      editor.sessionSyncBoardBtn:Hide()
    end
    if editor.lootSessionAutoPassCurrent then
      editor.lootSessionAutoPassCurrent:Hide()
    end

    local textWidth = math.max(160, rightContentWidth - 164)
    if editor.lootSessionAutoPassStatus then
      editor.lootSessionAutoPassStatus:SetWidth(textWidth)
    end
    if editor.lootSessionAutoPassIcon and editor.lootSessionRightBg then
      editor.lootSessionAutoPassIcon:ClearAllPoints()
      editor.lootSessionAutoPassIcon:SetPoint("TOPRIGHT", editor.lootSessionRightBg, "TOPRIGHT", -20, -18)
      editor.lootSessionAutoPassIcon:SetSize(132, 132)
    end

    local statusHeight = math.max(18, math.ceil((editor.lootSessionAutoPassStatus and editor.lootSessionAutoPassStatus:GetStringHeight()) or 0))
    local buttonTop = -48 - statusHeight - 12
    local showToggle = editor.sessionAutoPassLocalBtn and editor.sessionAutoPassLocalBtn:IsShown()
    if editor.sessionAutoPassLocalBtn then
      editor.sessionAutoPassLocalBtn:ClearAllPoints()
      editor.sessionAutoPassLocalBtn:SetPoint("TOPLEFT", 18, buttonTop)
    end
    local stateTop = showToggle and (buttonTop - 34) or buttonTop
    if editor.lootSessionAutoPassState then
      editor.lootSessionAutoPassState:ClearAllPoints()
      editor.lootSessionAutoPassState:SetPoint("TOPLEFT", 18, stateTop)
      editor.lootSessionAutoPassState:SetWidth(textWidth)
    end
    local stateHeight = math.max(38, math.ceil((editor.lootSessionAutoPassState and editor.lootSessionAutoPassState:IsShown() and editor.lootSessionAutoPassState:GetStringHeight() or 0)))

    local notesHeaderTop = stateTop - stateHeight - 18
    if editor.lootSessionAutoPassHeader then
      editor.lootSessionAutoPassHeader:ClearAllPoints()
      editor.lootSessionAutoPassHeader:SetPoint("TOPLEFT", 18, notesHeaderTop)
    end

    local notesTop = notesHeaderTop - 28
    if editor.lootSessionAutoPassDesc then
      editor.lootSessionAutoPassDesc:ClearAllPoints()
      editor.lootSessionAutoPassDesc:SetPoint("TOPLEFT", 18, notesTop)
      editor.lootSessionAutoPassDesc:SetWidth(rightContentWidth)
    end
    local descHeight = math.max(84, math.ceil((editor.lootSessionAutoPassDesc and editor.lootSessionAutoPassDesc:IsShown() and editor.lootSessionAutoPassDesc:GetStringHeight() or 0)))

    local contentBottom = math.abs(notesTop) + descHeight + 24
    if page then
      page.__contentHeight = math.max(420, contentBottom)
    end
    return contentBottom
  end

  return {
    RefreshAutoPassView = RefreshAutoPassView,
    LayoutAutoPassSection = LayoutAutoPassSection,
  }
end
