local DR = select(2, ...)

--- Tie-breaker popup: shows the round number and the tied players as chips.
local RollOffModal = {
  frame = nil,
  chips = {},
}
LibStub("AceEvent-3.0"):Embed(RollOffModal)

local function Kit()
  return DR:Require("UI.Kit")
end

function RollOffModal:CreateFrame()
  if self.frame then
    return self.frame
  end

  local kit = Kit()
  local C = kit.COLORS
  local frame = kit:CreateWindow("RollOffModal", "Roll-Off", 420, 220, { strata = "DIALOG" })

  local roundText = kit:CreateLabel(frame.content, "Round: 0", "normal")
  roundText:SetPoint("TOPLEFT", 0, 0)
  frame.roundText = roundText

  local subtitle = kit:CreateLabel(frame.content, "Tied players - the leader re-rolls until one wins", "small", C.textDim)
  subtitle:SetPoint("TOPLEFT", roundText, "BOTTOMLEFT", 0, -4)

  self.frame = frame
  return frame
end

function RollOffModal:RenderChips(tiedGuids)
  local kit = Kit()
  local C = kit.COLORS
  local frame = self:CreateFrame()

  for _, chip in ipairs(self.chips) do
    chip:Hide()
  end

  local identity = DR:Require("Services.Identity")
  for i, guid in ipairs(tiedGuids or {}) do
    local chip = self.chips[i]
    if not chip then
      chip = kit:CreateCard(frame.content, 24)
      chip:SetWidth(188)
      chip:SetPoint("TOPLEFT", frame.content, "TOPLEFT", ((i - 1) % 2) * 198, -48 - (math.floor((i - 1) / 2) * 30))
      chip.label = kit:CreateLabel(chip, "", "small")
      chip.label:SetPoint("CENTER", 0, 0)
      self.chips[i] = chip
    end
    chip.label:SetText(identity:GetDisplayByGuid(guid) or guid)
    chip:Show()
  end
end

function RollOffModal:ShowRound(payload)
  local frame = self:CreateFrame()
  frame.roundText:SetText(string.format("Round: %d", payload.round or 0))
  -- ROLLOFF_START payloads carry tiedGuids; ROLLOFF_RESULT payloads carry tieGuids.
  self:RenderChips(payload.tiedGuids or payload.tieGuids)
  frame:Show()
end

function RollOffModal:OnInitialize()
  self:CreateFrame()

  self:RegisterMessage("DR_ROLLOFF_STARTED", function(_, payload)
    if DR.db.profile.ui.showRollOffModal then
      self:ShowRound(payload or {})
    end
  end)

  self:RegisterMessage("DR_ROLLOFF_RESULT", function(_, payload)
    if payload and payload.tie and DR.db.profile.ui.showRollOffModal then
      self:ShowRound(payload)
    elseif self.frame then
      self.frame:Hide()
    end
  end)

  self:RegisterMessage("DR_SESSION_RESOLVED", function()
    if self.frame then
      self.frame:Hide()
    end
  end)
end

DR:RegisterModule("Modules.RollOffModal", RollOffModal)
