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

local shared = INTERNAL_API.LIDCOUNCIL_LootRuntimeShared_Impl
if type(shared) ~= "table" then
  error("LidCouncil missing loot runtime shared helpers.")
end

local simulation = INTERNAL_API.LIDCOUNCIL_LootRuntimeSimulation_Impl
if type(simulation) ~= "table" then
  error("LidCouncil missing loot runtime simulation helpers.")
end

local GetLootProfile = shared.GetLootProfile
local GetActiveLootSession = shared.GetActiveLootSession
local GetLootProfileAccessInfo = shared.GetLootProfileAccessInfo
local GetLootProfileAccessInfoForRole = shared.GetLootProfileAccessInfoForRole
local ResolveLootPointValue = shared.ResolveLootPointValue
local ResolveLootAwardOutcome = shared.ResolveLootAwardOutcome
local ApplyFrameSkin = shared.ApplyFrameSkin
local SendSessionComm = shared.SendSessionComm
local SendChoicePacket = shared.SendChoicePacket
local SendAwardPacket = shared.SendAwardPacket
local BroadcastAuthoritativeChoice = shared.BroadcastAuthoritativeChoice
local ResolveOptionalFunction = shared.ResolveOptionalFunction
local Print = shared.Print
local DeepCopy = shared.DeepCopy
local DEFAULT_OPTIONS = shared.DEFAULT_OPTIONS
local NOTE_ICON_TEXTURE = shared.NOTE_ICON_TEXTURE
local MAX_SELECTION_NOTE_LENGTH = shared.MAX_SELECTION_NOTE_LENGTH
local REAL_SIMULATION_ITEM_COUNT = shared.REAL_SIMULATION_ITEM_COUNT
local runtime = shared.RuntimeState
local uiState = shared.UIState
local TrimText = shared.TrimText
local IsRealSimulationItemKey = shared.IsRealSimulationItemKey
local ExtractItemID = shared.ExtractItemID
local NormalizeSelectionNote = shared.NormalizeSelectionNote
local RefreshEditor = shared.RefreshEditor
local WrapColor = shared.WrapColor
local ResolveOptionIconTexture = shared.ResolveOptionIconTexture
local ResolveRollOptions = shared.ResolveRollOptions
local GetSelfKey = shared.GetSelfKey
local BuildMemberDisplayText = shared.BuildMemberDisplayText
local IsSelfHost = shared.IsSelfHost
local GetJoinedSessionState = shared.GetJoinedSessionState
local GetBroadcastDistribution = shared.GetBroadcastDistribution
local BuildPendingSelection = shared.BuildPendingSelection
local EnsurePreviewBoardContext = shared.EnsurePreviewBoardContext
local PersistRuntimeBoardHistory = shared.PersistRuntimeBoardHistory
local PersistPreviewBoardHistory = shared.PersistPreviewBoardHistory
local GetLiveBoardHistoryEntries = shared.GetLiveBoardHistoryEntries
local GetLiveBoardHistoryPage = shared.GetLiveBoardHistoryPage
local GetLiveBoardHistorySnapshot = shared.GetLiveBoardHistorySnapshot
local RestoreLatestPreviewBoardState = shared.RestoreLatestPreviewBoardState
local ResolveLootLedgerTotals = shared.ResolveLootLedgerTotals
local ClearRuntimeState = shared.ClearRuntimeState
local EnsureRuntimeSession = shared.EnsureRuntimeSession
local EnsureSelectedMember = shared.EnsureSelectedMember
local CycleSelectedMember = shared.CycleSelectedMember
local BuildAwardNote = shared.BuildAwardNote
local RemoveAwardFromEntry = shared.RemoveAwardFromEntry
local ApplyAwardMessage = shared.ApplyAwardMessage
local RefreshBoardAndEditor = shared.RefreshBoardAndEditor
local RecordChoice = shared.RecordChoice
local GetLiveLootBoardSummary = shared.GetLiveLootBoardSummary
local GetEntryVoteTargetForVoter = shared.GetEntryVoteTargetForVoter
local SetEntryVoteTarget = shared.SetEntryVoteTarget
local GetEntryVoteVoterKeys = shared.GetEntryVoteVoterKeys
local GetEntryVoteCount = shared.GetEntryVoteCount

local BuildPreviewBoardState = simulation.BuildPreviewBoardState
local BuildSimulationBoardState = simulation.BuildSimulationBoardState
local BuildRealSimulationItemDefs = shared.BuildRealSimulationItemDefs
local GetSelectionPriority = simulation.GetSelectionPriority
local FormatSelectionLabel = simulation.FormatSelectionLabel
local EnsurePreviewSelectedMember = simulation.EnsurePreviewSelectedMember
local CyclePreviewSelectedMember = simulation.CyclePreviewSelectedMember
local ApplySimulationAward = simulation.ApplySimulationAward
local ApplySimulationChoice = simulation.ApplySimulationChoice

local function GetBoardPreviewState(frame)
  if type(uiState.previewState) == "table" then
    return uiState.previewState
  end
  local framePreview = type(frame) == "table" and frame.__previewState or nil
  if type(framePreview) == "table" then
    return framePreview
  end

  local activeSession = GetActiveLootSession()
  if activeSession then
    return nil
  end

  local _, currentProfileName = GetLootProfile(nil)
  local restoredPreview = type(RestoreLatestPreviewBoardState) == "function" and RestoreLatestPreviewBoardState(currentProfileName) or nil
  if type(restoredPreview) == "table" then
    uiState.previewState = restoredPreview
    if type(frame) == "table" then
      frame.__previewState = restoredPreview
    end
    return restoredPreview
  end
  return nil
end

local function SetBoardPreviewState(frame, preview)
  uiState.previewState = type(preview) == "table" and preview or nil
  if frame then
    frame.__previewState = uiState.previewState
  end
end

local function PersistBoardState(frame, opts)
  local preview = GetBoardPreviewState(frame)
  if type(preview) == "table" then
    EnsurePreviewBoardContext(preview)
    PersistPreviewBoardHistory(preview)
  else
    PersistRuntimeBoardHistory(opts)
  end
end

local function ResolveBoardProfileName(frame, preview)
  preview = type(preview) == "table" and preview or GetBoardPreviewState(frame)
  if type(preview) == "table" then
    EnsurePreviewBoardContext(preview)
    return TrimText(preview.historyProfileName ~= "" and preview.historyProfileName or preview.profileName)
  end
  return TrimText(runtime.historyProfileName ~= "" and runtime.historyProfileName or runtime.profileName)
end

local function ResolveAuthoritativeItemTooltipMode(hasDescriptor, authoritativeItemLevel, resolvedItemLevel, nativeRendered)
  local expectedLevel = tonumber(authoritativeItemLevel)
  local resolvedLevel = tonumber(resolvedItemLevel)
  if expectedLevel and expectedLevel > 0 then
    expectedLevel = math.floor(expectedLevel + 0.5)
    resolvedLevel = resolvedLevel and math.floor(resolvedLevel + 0.5) or nil
    if nativeRendered == true and hasDescriptor == true and resolvedLevel == expectedLevel then
      return "native", expectedLevel, resolvedLevel
    end
    return "authoritative_fallback", expectedLevel, resolvedLevel
  end
  if nativeRendered == true then
    return "native", nil, resolvedLevel
  end
  return "basic_fallback", nil, resolvedLevel
end

INTERNAL_API.LIDCOUNCIL_ResolveAuthoritativeItemTooltipMode_Impl = ResolveAuthoritativeItemTooltipMode

local function ResolveTooltipItemLevel(itemLink)
  local descriptor = TrimText(itemLink)
  if descriptor == "" then
    return nil
  end
  if type(C_Item) == "table" and type(C_Item.GetDetailedItemLevelInfo) == "function" then
    local ok, itemLevel = pcall(C_Item.GetDetailedItemLevelInfo, descriptor)
    if ok and tonumber(itemLevel) and tonumber(itemLevel) > 0 then
      return tonumber(itemLevel)
    end
  end
  if type(GetDetailedItemLevelInfo) == "function" then
    local ok, itemLevel = pcall(GetDetailedItemLevelInfo, descriptor)
    if ok and tonumber(itemLevel) and tonumber(itemLevel) > 0 then
      return tonumber(itemLevel)
    end
  end
  return nil
end

local function RequestTooltipItemData(itemID)
  local resolvedItemID = tonumber(itemID)
  if not resolvedItemID then
    return
  end
  if type(C_Item) == "table" and type(C_Item.RequestLoadItemDataByID) == "function" then
    pcall(C_Item.RequestLoadItemDataByID, resolvedItemID)
  end
end

local function RenderAuthoritativeItemTooltip(tooltip, owner, anchor, data)
  if type(tooltip) ~= "table" or not owner then
    return "unavailable"
  end
  data = type(data) == "table" and data or {}
  local itemLink = TrimText(data.link)
  local itemID = ExtractItemID(data.itemID or itemLink)
  local itemName = TrimText(data.name)
  local authoritativeItemLevel = tonumber(data.itemLevel)
  local nativeRendered = false

  tooltip:SetOwner(owner, anchor or "ANCHOR_RIGHT")
  if itemLink ~= "" and type(tooltip.SetHyperlink) == "function" then
    local ok = pcall(tooltip.SetHyperlink, tooltip, itemLink)
    nativeRendered = ok == true
  elseif not authoritativeItemLevel and itemID and type(tooltip.SetItemByID) == "function" then
    local ok = pcall(tooltip.SetItemByID, tooltip, itemID)
    nativeRendered = ok == true
  end

  local resolvedItemLevel = itemLink ~= "" and ResolveTooltipItemLevel(itemLink) or nil
  local mode, expectedLevel, resolvedLevel = ResolveAuthoritativeItemTooltipMode(
    itemLink ~= "",
    authoritativeItemLevel,
    resolvedItemLevel,
    nativeRendered
  )
  if mode == "native" then
    return mode, expectedLevel, resolvedLevel
  end

  RequestTooltipItemData(itemID)
  if type(tooltip.ClearLines) == "function" then
    tooltip:ClearLines()
  end
  tooltip:SetText(
    itemName ~= "" and itemName or (itemID and ("Item #" .. tostring(itemID)) or "LidCouncil Item"),
    1,
    0.82,
    0.28,
    1,
    true
  )
  if expectedLevel and type(tooltip.AddLine) == "function" then
    tooltip:AddLine("Session Item Level: " .. tostring(expectedLevel), 1.00, 0.82, 0.28, true)
    if itemLink == "" then
      tooltip:AddLine(
        "Detailed item stats are unavailable because the complete item variant was not delivered. LidCouncil is using the host's session item level.",
        0.72,
        0.82,
        0.95,
        true
      )
    elseif not resolvedLevel then
      tooltip:AddLine(
        "Detailed item stats are loading. Move away and hover again; the host's session item level remains authoritative.",
        0.72,
        0.82,
        0.95,
        true
      )
    else
      tooltip:AddLine(
        "WoW resolved item level " .. tostring(resolvedLevel)
          .. " from a different item variant. LidCouncil is using the host's session item level.",
        1.00,
        0.62,
        0.32,
        true
      )
    end
  end
  return mode, expectedLevel, resolvedLevel
end

local function ResolveRuntimeItemDisplayText(entry, itemKey)
  entry = type(entry) == "table" and entry or {}
  local link = TrimText(entry.link)
  if link ~= "" and link:find("|Hitem:", 1, true) and link:find("|h", 1, true) then
    return link
  end
  local name = TrimText(entry.name)
  return name ~= "" and name or tostring(itemKey or "?")
end

INTERNAL_API.LIDCOUNCIL_LootRuntimeUiShared_Impl = {
  GetLootProfile = GetLootProfile,
  GetActiveLootSession = GetActiveLootSession,
  GetLootProfileAccessInfo = GetLootProfileAccessInfo,
  GetLootProfileAccessInfoForRole = GetLootProfileAccessInfoForRole,
  ResolveLootPointValue = ResolveLootPointValue,
  ResolveLootAwardOutcome = ResolveLootAwardOutcome,
  ApplyFrameSkin = ApplyFrameSkin,
  SendSessionComm = SendSessionComm,
  SendChoicePacket = SendChoicePacket,
  SendAwardPacket = SendAwardPacket,
  BroadcastAuthoritativeChoice = BroadcastAuthoritativeChoice,
  ResolveOptionalFunction = ResolveOptionalFunction,
  Print = Print,
  DeepCopy = DeepCopy,
  DEFAULT_OPTIONS = DEFAULT_OPTIONS,
  NOTE_ICON_TEXTURE = NOTE_ICON_TEXTURE,
  MAX_SELECTION_NOTE_LENGTH = MAX_SELECTION_NOTE_LENGTH,
  REAL_SIMULATION_ITEM_COUNT = REAL_SIMULATION_ITEM_COUNT,
  RuntimeState = runtime,
  UIState = uiState,
  TrimText = TrimText,
  IsRealSimulationItemKey = IsRealSimulationItemKey,
  ExtractItemID = ExtractItemID,
  NormalizeSelectionNote = NormalizeSelectionNote,
  RefreshEditor = RefreshEditor,
  WrapColor = WrapColor,
  ResolveOptionIconTexture = ResolveOptionIconTexture,
  ResolveRollOptions = ResolveRollOptions,
  GetSelfKey = GetSelfKey,
  BuildMemberDisplayText = BuildMemberDisplayText,
  BuildPendingSelection = BuildPendingSelection,
  IsSelfHost = IsSelfHost,
  GetJoinedSessionState = GetJoinedSessionState,
  GetBroadcastDistribution = GetBroadcastDistribution,
  EnsurePreviewBoardContext = EnsurePreviewBoardContext,
  PersistRuntimeBoardHistory = PersistRuntimeBoardHistory,
  PersistPreviewBoardHistory = PersistPreviewBoardHistory,
  GetLiveBoardHistoryEntries = GetLiveBoardHistoryEntries,
  GetLiveBoardHistoryPage = GetLiveBoardHistoryPage,
  GetLiveBoardHistorySnapshot = GetLiveBoardHistorySnapshot,
  ResolveLootLedgerTotals = ResolveLootLedgerTotals,
  ClearRuntimeState = ClearRuntimeState,
  EnsureRuntimeSession = EnsureRuntimeSession,
  EnsureSelectedMember = EnsureSelectedMember,
  CycleSelectedMember = CycleSelectedMember,
  BuildAwardNote = BuildAwardNote,
  RemoveAwardFromEntry = RemoveAwardFromEntry,
  ApplyAwardMessage = ApplyAwardMessage,
  RefreshBoardAndEditor = RefreshBoardAndEditor,
  RecordChoice = RecordChoice,
  GetLiveLootBoardSummary = GetLiveLootBoardSummary,
  GetEntryVoteTargetForVoter = GetEntryVoteTargetForVoter,
  SetEntryVoteTarget = SetEntryVoteTarget,
  GetEntryVoteVoterKeys = GetEntryVoteVoterKeys,
  GetEntryVoteCount = GetEntryVoteCount,
  RenderAuthoritativeItemTooltip = RenderAuthoritativeItemTooltip,
  ResolveRuntimeItemDisplayText = ResolveRuntimeItemDisplayText,
  BuildPreviewBoardState = BuildPreviewBoardState,
  BuildSimulationBoardState = BuildSimulationBoardState,
  BuildRealSimulationItemDefs = BuildRealSimulationItemDefs,
  GetSelectionPriority = GetSelectionPriority,
  FormatSelectionLabel = FormatSelectionLabel,
  EnsurePreviewSelectedMember = EnsurePreviewSelectedMember,
  CyclePreviewSelectedMember = CyclePreviewSelectedMember,
  ApplySimulationAward = ApplySimulationAward,
  ApplySimulationChoice = ApplySimulationChoice,
  GetBoardPreviewState = GetBoardPreviewState,
  SetBoardPreviewState = SetBoardPreviewState,
  PersistBoardState = PersistBoardState,
  ResolveBoardProfileName = ResolveBoardProfileName,
}

local function CallUiImpl(name, ...)
  local fn = INTERNAL_API[name]
  if type(fn) ~= "function" then
    error("LidCouncil missing loot runtime UI implementation: " .. tostring(name))
  end
  return fn(...)
end

INTERNAL_API.LIDCOUNCIL_LootRuntimeUi_Impl = {
  OpenLiveLootBoard = function(...)
    return CallUiImpl("LIDCOUNCIL_OpenLiveLootBoard_Impl", ...)
  end,
  CloseLiveLootBoard = function(...)
    return CallUiImpl("LIDCOUNCIL_CloseLiveLootBoard_Impl", ...)
  end,
  AttachLiveLootBoard = function(...)
    return CallUiImpl("LIDCOUNCIL_AttachLiveLootBoard_Impl", ...)
  end,
  AttachLiveLootBoardHistory = function(...)
    return CallUiImpl("LIDCOUNCIL_AttachLiveLootBoardHistory_Impl", ...)
  end,
  PopoutLiveLootBoard = function(...)
    return CallUiImpl("LIDCOUNCIL_PopoutLiveLootBoard_Impl", ...)
  end,
  PreviewLiveLootBoard = function(...)
    return CallUiImpl("LIDCOUNCIL_PreviewLiveLootBoard_Impl", ...)
  end,
  RefreshLiveLootBoard = function(...)
    return CallUiImpl("LIDCOUNCIL_RefreshLiveLootBoard_Impl", ...)
  end,
  PreviewRollChoicePopup = function(...)
    return CallUiImpl("LIDCOUNCIL_PreviewRollChoicePopup_Impl", ...)
  end,
  RunLiveLootSimulation = function(...)
    return CallUiImpl("LIDCOUNCIL_RunLiveLootSimulation_Impl", ...)
  end,
  RunLiveLootRealSimulation = function(...)
    return CallUiImpl("LIDCOUNCIL_RunLiveLootRealSimulation_Impl", ...)
  end,
  RunLiveLootTransportTest = function(...)
    return CallUiImpl("LIDCOUNCIL_RunLiveLootTransportTest_Impl", ...)
  end,
  RefreshChoicePopup = function(...)
    return CallUiImpl("LIDCOUNCIL_RefreshChoicePopup_Impl", ...)
  end,
}
