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

  local ApplyFrameSkin = deps.ApplyFrameSkin
  local ApplyLootListToolbarButtonStyle = deps.ApplyLootListToolbarButtonStyle
  local BindMouseWheelScroll = deps.BindMouseWheelScroll
  local TrimText = deps.TrimText
  local ResolveOptionalApiFunction = deps.ResolveOptionalApiFunction
  local FormatDateTime = deps.FormatDateTime

  local function trim(value)
    if type(TrimText) == "function" then
      return TrimText(value)
    end
    local text = tostring(value or "")
    text = text:gsub("^%s+", "")
    text = text:gsub("%s+$", "")
    return text
  end

  local function SetWidgetShown(widget, shown)
    if not widget then
      return
    end
    if widget.SetShown then
      widget:SetShown(shown and true or false)
    elseif shown and widget.Show then
      widget:Show()
    elseif (not shown) and widget.Hide then
      widget:Hide()
    end
  end

  local function GetAwardsProvider()
    if type(ResolveOptionalApiFunction) == "function" then
      return ResolveOptionalApiFunction("LIDCOUNCIL_GetLootRollAwards")
    end
    local api = rawget(_G, "LIDCOUNCIL_API")
    if type(api) == "table" and type(api.LIDCOUNCIL_GetLootRollAwards) == "function" then
      return api.LIDCOUNCIL_GetLootRollAwards
    end
    return rawget(_G, "LIDCOUNCIL_GetLootRollAwards")
  end

  local function EnsureAwardRows(frame, count)
    frame.awardRows = frame.awardRows or {}
    while #frame.awardRows < count do
      local row = CreateFrame("Frame", nil, frame, "BackdropTemplate")
      row:SetSize(520, 76)
      if type(ApplyFrameSkin) == "function" then
        ApplyFrameSkin(row)
      end

      local accent = row:CreateTexture(nil, "ARTWORK")
      accent:SetTexture("Interface\\Buttons\\WHITE8x8")
      accent:SetPoint("TOPLEFT", 0, 0)
      accent:SetPoint("BOTTOMLEFT", 0, 0)
      accent:SetWidth(3)
      accent:SetVertexColor(1.00, 0.66, 0.20, 0.90)
      row.accent = accent

      local title = row:CreateFontString(nil, "OVERLAY", "GameFontNormal")
      title:SetPoint("TOPLEFT", 14, -10)
      title:SetJustifyH("LEFT")
      row.title = title

      local winner = row:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
      winner:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -7)
      winner:SetJustifyH("LEFT")
      row.winner = winner

      local metric = row:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
      metric:SetPoint("TOPRIGHT", -14, -12)
      metric:SetJustifyH("RIGHT")
      row.metric = metric

      local detail = row:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
      detail:SetPoint("TOPLEFT", winner, "BOTTOMLEFT", 0, -7)
      detail:SetJustifyH("LEFT")
      row.detail = detail

      frame.awardRows[#frame.awardRows + 1] = row
    end
    return frame.awardRows
  end

  local function EnsureAwardsPopup(editor)
    if editor and editor.lootLedgerAwardsPopupFrame then
      return editor.lootLedgerAwardsPopupFrame
    end
    if not editor then
      return nil
    end

    local frame = CreateFrame("Frame", "LIDCOUNCIL_LootListAwardsPopup", UIParent, "BackdropTemplate")
    frame:SetSize(650, 660)
    frame:SetPoint("CENTER", 0, 0)
    frame:SetFrameStrata("FULLSCREEN_DIALOG")
    frame:SetMovable(true)
    frame:EnableMouse(true)
    frame:SetToplevel(true)
    frame:RegisterForDrag("LeftButton")
    frame:SetScript("OnDragStart", frame.StartMoving)
    frame:SetScript("OnDragStop", frame.StopMovingOrSizing)
    if type(ApplyFrameSkin) == "function" then
      ApplyFrameSkin(frame)
    end
    frame:SetScript("OnShow", function()
      if editor and editor.UpdateLootListModeButtons then
        editor.UpdateLootListModeButtons()
      end
    end)
    frame:SetScript("OnHide", function()
      if editor and editor.UpdateLootListModeButtons then
        editor.UpdateLootListModeButtons()
      end
    end)

    local title = frame:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    title:SetPoint("TOPLEFT", 18, -17)
    title:SetText("Fun Awards")
    frame.popupTitle = title

    local closeBtn = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate,BackdropTemplate")
    closeBtn:SetSize(78, 22)
    closeBtn:SetPoint("TOPRIGHT", -14, -14)
    closeBtn:SetText("Close")
    if type(ApplyLootListToolbarButtonStyle) == "function" then
      ApplyLootListToolbarButtonStyle(closeBtn)
    elseif type(ApplyFrameSkin) == "function" then
      ApplyFrameSkin(closeBtn)
    end
    closeBtn:SetScript("OnClick", function()
      frame:Hide()
    end)
    frame.closeBtn = closeBtn

    local scroll = CreateFrame("ScrollFrame", nil, frame, "UIPanelScrollFrameTemplate")
    scroll:SetPoint("TOPLEFT", 14, -48)
    scroll:SetPoint("BOTTOMRIGHT", -32, 14)
    if type(BindMouseWheelScroll) == "function" then
      BindMouseWheelScroll(scroll, 18)
    end
    frame.scroll = scroll

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

    editor.lootLedgerAwardsPopupFrame = frame
    editor.lootLedgerAwardsPopupContent = content
    frame:Hide()
    return frame
  end

  local function EnsureAwardsFrame(editor)
    local popup = EnsureAwardsPopup(editor)
    local parent = popup and popup.content or nil
    if not parent then
      return nil
    end
    if editor.lootLedgerAwardsFrame then
      return editor.lootLedgerAwardsFrame
    end

    local frame = CreateFrame("Frame", nil, parent, "BackdropTemplate")
    frame:SetPoint("TOPLEFT", parent, "TOPLEFT", 0, 0)
    frame:EnableMouse(true)
    if type(ApplyFrameSkin) == "function" then
      ApplyFrameSkin(frame)
    end
    if frame.SetBackdropColor then
      frame:SetBackdropColor(0.035, 0.035, 0.050, 0.98)
    end

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

    local intro = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    intro:SetPoint("TOPLEFT", 18, -44)
    intro:SetJustifyH("LEFT")
    intro:SetText("Silly long-term awards based on the host profile. Roll statistics are compact counters and do not send extra live sync messages.")
    frame.intro = intro

    local updated = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    updated:SetPoint("TOPLEFT", 18, -82)
    updated:SetJustifyH("LEFT")
    updated:SetText("")
    frame.updated = updated

    editor.lootLedgerAwardsFrame = frame
    frame:Hide()
    return frame
  end

  local function RefreshLootListAwardsView(editor, profileName, width)
    local frame = EnsureAwardsFrame(editor)
    if not frame then
      return 0
    end
    local popup = EnsureAwardsPopup(editor)

    local resolvedWidth = math.max(360, tonumber(width) or 540)
    frame:SetSize(resolvedWidth + 36, 1)
    if frame.intro then
      frame.intro:SetWidth(resolvedWidth)
    end
    if frame.updated then
      frame.updated:SetWidth(resolvedWidth)
    end

    local getAwards = GetAwardsProvider()
    local report = type(getAwards) == "function" and getAwards(profileName) or nil
    local awards = type(report) == "table" and type(report.awards) == "table" and report.awards or {}
    EnsureAwardRows(frame, math.max(1, #awards))

    local rollEventCount = tonumber(type(report) == "table" and report.rollEventCount) or 0
    local updatedAt = tonumber(type(report) == "table" and report.updatedAt) or 0
    if frame.updated then
      local updatedText = "Roll stat events: " .. tostring(rollEventCount)
      if updatedAt > 0 and type(FormatDateTime) == "function" then
        updatedText = updatedText .. " | Last update: " .. FormatDateTime(updatedAt)
      end
      frame.updated:SetText(updatedText)
    end

    local rowTop = -112
    local rowHeight = 76
    local rowGap = 10
    for index, row in ipairs(frame.awardRows or {}) do
      local award = awards[index]
      if award then
        row:ClearAllPoints()
        row:SetPoint("TOPLEFT", 18, rowTop - ((index - 1) * (rowHeight + rowGap)))
        row:SetSize(resolvedWidth, rowHeight)
        row.title:SetWidth(math.max(160, resolvedWidth - 170))
        row.winner:SetWidth(math.max(160, resolvedWidth - 170))
        row.metric:SetWidth(150)
        row.detail:SetWidth(math.max(180, resolvedWidth - 28))
        row.title:SetText(tostring(award.title or "Award"))
        row.winner:SetText(tostring(award.winner or "No winner yet"))
        row.metric:SetText(tostring(award.metric or "-"))
        row.detail:SetText(tostring(award.detail or ""))
        if award.hasWinner then
          row.winner:SetTextColor(1.00, 0.88, 0.36, 1.00)
          row.metric:SetTextColor(0.82, 0.92, 1.00, 1.00)
          row.accent:SetVertexColor(1.00, 0.66, 0.20, 0.90)
        else
          row.winner:SetTextColor(0.70, 0.70, 0.76, 1.00)
          row.metric:SetTextColor(0.70, 0.70, 0.76, 1.00)
          row.accent:SetVertexColor(0.45, 0.45, 0.50, 0.70)
        end
        row:Show()
      else
        row:Hide()
      end
    end

    if #awards == 0 and frame.awardRows and frame.awardRows[1] then
      local row = frame.awardRows[1]
      row:ClearAllPoints()
      row:SetPoint("TOPLEFT", 18, rowTop)
      row:SetSize(resolvedWidth, rowHeight)
      row.title:SetText("Fun Awards unavailable")
      row.winner:SetText("No award provider found")
      row.metric:SetText("-")
      row.detail:SetText("Reload the addon if this stays visible.")
      row:Show()
    end

    local contentHeight = math.max(460, math.abs(rowTop) + (math.max(1, #awards) * (rowHeight + rowGap)) + 24)
    frame:SetHeight(contentHeight)
    if popup and popup.content then
      popup.content:SetSize(resolvedWidth + 36, contentHeight)
    end
    if popup and popup.scroll and popup.scroll.UpdateScrollChildRect then
      popup.scroll:UpdateScrollChildRect()
    end
    frame:Show()
    return contentHeight
  end

  local function OpenLootListAwardsPopup(editor, profileName)
    local popup = EnsureAwardsPopup(editor)
    if not popup then
      return
    end
    local width = math.max(540, (popup.GetWidth and popup:GetWidth() or 650) - 70)
    RefreshLootListAwardsView(editor, profileName, width)
    popup:Show()
    if popup.Raise then
      popup:Raise()
    end
  end

  local function SetLootListAwardsViewShown(editor, shown)
    local popup = EnsureAwardsPopup(editor)
    SetWidgetShown(popup, shown)
  end

  local function IsLootListAwardsPopupShown(editor)
    local popup = editor and editor.lootLedgerAwardsPopupFrame or nil
    return popup and popup.IsShown and popup:IsShown() or false
  end

  return {
    OpenLootListAwardsPopup = OpenLootListAwardsPopup,
    RefreshLootListAwardsView = RefreshLootListAwardsView,
    SetLootListAwardsViewShown = SetLootListAwardsViewShown,
    IsLootListAwardsPopupShown = IsLootListAwardsPopupShown,
  }
end
