ADDON_SETS = {
  [1] = {1},
  [2] = {2},
  [3] = {1, 2},
  [4] = {3},
  [5] = {1, 3},
  [6] = {2, 3},
  [7] = {1, 2, 3}
}

outfitWindow = nil
outfit = nil
outfits = nil
outfitCreatureBox = nil
currentOutfit = 1
selectedOutfitGridItem = nil

addons = nil
currentColorBox = nil
currentClotheButtonBox = nil
colorBoxes = {}

mount = nil
mounts = nil
mountCreatureBox = nil
currentMount = 1
ignoreNextOutfitWindow = 0

function init()
  connect(
    g_game,
    {
      onOpenOutfitWindow = create,
      onGameEnd = destroy
    }
  )
end

function terminate()
  disconnect(
    g_game,
    {
      onOpenOutfitWindow = create,
      onGameEnd = destroy
    }
  )
  destroy()
end

function updateMount()
  if table.empty(mounts) or not mount then
    return
  end
  local nameMountWidget = outfitWindow:getChildById("mountName")
  nameMountWidget:setText(mounts[currentMount][2])

  mount.type = mounts[currentMount][1]
  mountCreature:setOutfit(mount)
end

local function setSelectedGridItem(index)
  if not outfitWindow then
    return
  end

  local grid = outfitWindow:recursiveGetChildById("outfitGrid")
  if not grid then
    return
  end

  -- Always clear every card first. This keeps the visual selection
  -- exclusive even when the client reuses the Button checked state.
  selectedOutfitGridItem = nil
  for _, item in ipairs(grid:getChildren()) do
    if not item:isDestroyed() then
      item:setChecked(false)
    end
  end

  for _, item in ipairs(grid:getChildren()) do
    if item.outfitIndex == index and not item:isDestroyed() then
      item:setChecked(true)
      selectedOutfitGridItem = item
      break
    end
  end
end

local function populateOutfitGrid(widget, list, currentOutfit)
  local grid = outfitWindow:recursiveGetChildById('outfitGrid')
  if not grid then
    return
  end

  grid:destroyChildren()
  selectedOutfitGridItem = nil

  local previewOutfit = {
    type = currentOutfit.type or 0,
    head = currentOutfit.head or 0,
    body = currentOutfit.body or 0,
    legs = currentOutfit.legs or 0,
    feet = currentOutfit.feet or 0,
    addons = 0
  }

  local seen = {}
  local displayEntries = {}

  -- Some servers send the same outfit more than once. Keep the first
  -- occurrence for the visual grid while preserving the original list
  -- indexes used by the protocol and selectors.
  for index, entry in ipairs(list) do
    if entry[1] and entry[1] > 0 then
      local name = tostring(entry[2] or '-')
      local key = tostring(entry[1]) .. '\31' .. name:lower()
      if not seen[key] then
        seen[key] = true
        table.insert(displayEntries, {index = index, entry = entry})
      end
    end
  end

  for _, display in ipairs(displayEntries) do
    local index = display.index
    local entry = display.entry
    local item = g_ui.createWidget('OutfitGridItem', grid)
    item.outfitIndex = index
    item.label:setText(entry[2] or '-')
    item.creature:setOutfit({
      type = entry[1],
      head = previewOutfit.head,
      body = previewOutfit.body,
      legs = previewOutfit.legs,
      feet = previewOutfit.feet
    })

    local function selectOutfitCard()
      if not outfitWindow then
        return
      end
      local selected = item.outfitIndex
      if not list[selected] then
        return
      end
      setSelectedGridItem(selected)
      local current = widget.creature:getOutfit()
      current.type = list[selected][1]
      widget.outfit = list[selected]
      widget.creature:setOutfit(current)
      widget.label:setText(list[selected][2] or '-')
      if widget.outfitList then
        widget.outfitList:setCurrentIndex(selected, true)
      end
      updateOutfit()
    end

    -- Make the entire outfit card clickable, not only the empty area
    -- around the creature/name. Child widgets receive mouse events in
    -- this client, so forward their clicks to the same selection handler.
    item.onClick = selectOutfitCard
    item.creature.onClick = selectOutfitCard
    item.label.onClick = selectOutfitCard
  end

  -- Select only the first card matching the current outfit type.
  for _, display in ipairs(displayEntries) do
    if display.entry[1] == currentOutfit.type then
      setSelectedGridItem(display.index)
      break
    end
  end
end

local function filterOutfitGrid(text)
  if not outfitWindow then
    return
  end
  local grid = outfitWindow:recursiveGetChildById('outfitGrid')
  if not grid then
    return
  end
  text = string.lower(text or '')
  for _, item in ipairs(grid:getChildren()) do
    local name = string.lower(item.label:getText() or '')
    item:setVisible(text == '' or string.find(name, text, 1, true) ~= nil)
  end
end

function setupSelector(widget, id, outfit, list)
  widget:setId(id)
  if id == "type" then
    widget.label = widget:getChildById("outfitName")
  end
  if id == "healthBar" or id == "manaBar" then
    widget.title:setText(id == "healthBar" and "Health Bar" or "Mana Bar")
    table.insert(list, 1, {0, "-"})
  else
    if id == "type" then
      widget.title:setText("Selected Outfit")
    else
      widget.title:setText(id:gsub("^%l", string.upper))
    end
    if id ~= "type" or #list == 0 then
      table.insert(list, 1, {0, "-"})
    end
  end

  local pos = 1
  for i, o in pairs(list) do
    if (id == "shader" and outfit[id] == o[2]) or outfit[id] == o[1] then
      pos = i
    end
  end
  if list[pos] then
    widget.outfit = list[pos]
    if id == "shader" then
      widget.creature:setOutfit(
        {
          shader = list[pos][2]
        }
      )
    elseif id == "healthBar" then
      if pos ~= 1 then
        widget.bar:setImageSource(g_healthBars.getHealthBarPath(pos - 1))
      else
        widget.bar:setImageSource("")
      end
      widget.bar.selected = pos - 1
    elseif id == "manaBar" then
      if pos ~= 1 then
        widget.bar:setImageSource(g_healthBars.getManaBarPath(pos - 1))
      else
        widget.bar:setImageSource("")
      end
      widget.bar.selected = pos - 1
    else
      widget.creature:setOutfit(
        {
          type = list[pos][1]
        }
      )
    end
    widget.label:setText(list[pos][2])
  end

  -- Outfit list: keep the existing selector behavior, but add a faster
  -- dropdown for outfits when this is the main outfit selector.
  if id == "type" then
    local outfitListBox = widget:getChildById("outfitList")
    widget.outfitList = outfitListBox
    if outfitListBox then
      outfitListBox:clearOptions()
      for i, entry in ipairs(list) do
        outfitListBox:addOption(entry[2], i)
      end
      outfitListBox:setCurrentIndex(pos, true)
      outfitListBox.onOptionChange = function(combo, text, index)
        if not index or not list[index] then
          return
        end

        pos = index
        local selectedOutfit = widget.creature:getOutfit()
        selectedOutfit.type = list[pos][1]
        widget.outfit = list[pos]
        widget.creature:setOutfit(selectedOutfit)
        widget.label:setText(list[pos][2])
        setSelectedGridItem(pos)
        updateOutfit()
      end
    end
    populateOutfitGrid(widget, list, outfit)
    local search = outfitWindow:recursiveGetChildById('outfitSearch')
    if search then
      search.onTextChange = function(_, text)
        filterOutfitGrid(text)
      end
    end
  end

  widget.prevButton.onClick = function()
    if pos == 1 then
      pos = #list
    else
      pos = pos - 1
    end
    if id == "healthBar" or id == "manaBar" then
      if id == "healthBar" then
        if pos ~= 1 then
          widget.bar:setImageSource(g_healthBars.getHealthBarPath(pos - 1))
        else
          widget.bar:setImageSource("")
        end
      elseif id == "manaBar" then
        if pos ~= 1 then
          widget.bar:setImageSource(g_healthBars.getManaBarPath(pos - 1))
        else
          widget.bar:setImageSource("")
        end
      end
      widget.bar.selected = pos - 1
      widget.label:setText(list[pos][2])
    else
      local outfit = widget.creature:getOutfit()
      if id == "shader" then
        outfit.shader = list[pos][2]
      else
        outfit.type = list[pos][1]
      end
      widget.outfit = list[pos]
      widget.creature:setOutfit(outfit)
      widget.label:setText(list[pos][2])
      if id == "type" then
        if widget.outfitList then
          widget.outfitList:setCurrentIndex(pos, true)
        end
        setSelectedGridItem(pos)
      end
      updateOutfit()
    end
  end

  widget.nextButton.onClick = function()
    if pos == #list then
      pos = 1
    else
      pos = pos + 1
    end
    if id == "healthBar" or id == "manaBar" then
      if id == "healthBar" then
        if pos ~= 1 then
          widget.bar:setImageSource(g_healthBars.getHealthBarPath(pos - 1))
        else
          widget.bar:setImageSource("")
        end
      elseif id == "manaBar" then
        if pos ~= 1 then
          widget.bar:setImageSource(g_healthBars.getManaBarPath(pos - 1))
        else
          widget.bar:setImageSource("")
        end
      end
      widget.bar.selected = pos - 1
      widget.label:setText(list[pos][2])
    else
      local outfit = widget.creature:getOutfit()
      if id == "shader" then
        outfit.shader = list[pos][2]
      else
        outfit.type = list[pos][1]
      end
      widget.outfit = list[pos]
      widget.creature:setOutfit(outfit)
      widget.label:setText(list[pos][2])
      if id == "type" then
        if widget.outfitList then
          widget.outfitList:setCurrentIndex(pos, true)
        end
        setSelectedGridItem(pos)
      end
      updateOutfit()
    end
  end
  return widget
end

function create(currentOutfit, outfitList, mountList, wingList, auraList, shaderList, hpBarList, manaBarList)
  if ignoreNextOutfitWindow and g_clock.millis() < ignoreNextOutfitWindow + 1000 then
    return
  end
  if outfitWindow and not outfitWindow:isHidden() then
    return
  end

  destroy()

  outfitWindow = g_ui.displayUI("outfitwindow")

  setupSelector(outfitWindow:recursiveGetChildById("type"), "type", currentOutfit, outfitList)

  local outfit = outfitWindow:recursiveGetChildById("type").creature:getOutfit()
  outfit.head = currentOutfit.head
  outfit.body = currentOutfit.body
  outfit.legs = currentOutfit.legs
  outfit.feet = currentOutfit.feet
  outfitWindow:recursiveGetChildById("type").creature:setOutfit(outfit)

  if g_game.getFeature(GamePlayerMounts) then
    setupSelector(g_ui.createWidget("OutfitSelectorPanel", outfitWindow.extensions), "mount", currentOutfit, mountList)
  end
  if g_game.getFeature(GameWingsAndAura) then
    setupSelector(g_ui.createWidget("OutfitSelectorPanel", outfitWindow.extensions), "wings", currentOutfit, wingList)
    setupSelector(g_ui.createWidget("OutfitSelectorPanel", outfitWindow.extensions), "aura", currentOutfit, auraList)
  end
  if g_game.getFeature(GameOutfitShaders) then
    setupSelector(g_ui.createWidget("OutfitSelectorPanel", outfitWindow.extensions), "shader", currentOutfit, shaderList)
  end

  if g_game.getFeature(GameHealthInfoBackground) then
    setupSelector(g_ui.createWidget("BarSelectorPanel", outfitWindow.extensions), "healthBar", currentOutfit, hpBarList)
    setupSelector(g_ui.createWidget("BarSelectorPanel", outfitWindow.extensions), "manaBar", currentOutfit, manaBarList)
  end

  if not outfitWindow.extensions:getFirstChild() then
    outfitWindow:setHeight(outfitWindow:getHeight() - 128)
  end

  local colorPanel = outfitWindow:recursiveGetChildById("colorBoxPanel")
  if colorPanel then
    for j = 0, 6 do
      for i = 0, 18 do
        local colorBox = g_ui.createWidget("ColorBox", colorPanel)
      local outfitColor = getOutfitColor(j * 19 + i)
      colorBox:setImageColor(outfitColor)
      colorBox:setId("colorBox" .. j * 19 + i)
      colorBox.colorId = j * 19 + i

      if j * 19 + i == currentOutfit.head then
        currentColorBox = colorBox
        colorBox:setChecked(true)
      end
      colorBox.onCheckChange = onColorCheckChange
        colorBoxes[#colorBoxes + 1] = colorBox
      end
    end
  end

  -- set addons
  addons = {
    [1] = {widget = outfitWindow:recursiveGetChildById("addon1"), value = 1},
    [2] = {widget = outfitWindow:recursiveGetChildById("addon2"), value = 2},
    [3] = {widget = outfitWindow:recursiveGetChildById("addon3"), value = 4}
  }

  for _, addon in pairs(addons) do
    if addon.widget then
      addon.widget.onCheckChange = function(self)
        onAddonCheckChange(self, addon.value)
      end
    end
  end

  if currentOutfit.addons and currentOutfit.addons > 0 then
    for _, i in pairs(ADDON_SETS[currentOutfit.addons]) do
      if addons[i] and addons[i].widget then
        addons[i].widget:setChecked(true)
      end
    end
  end

  -- hook outfit sections
  currentClotheButtonBox = outfitWindow:recursiveGetChildById("head")
  for _, id in ipairs({"head", "primary", "secondary", "detail"}) do
    local button = outfitWindow:recursiveGetChildById(id)
    if button then
      button.onCheckChange = onClotheCheckChange
    end
  end

  updateOutfit()
end

function destroy()
  if outfitWindow then
    outfitWindow:destroy()
    outfitWindow = nil
    currentColorBox = nil
    currentClotheButtonBox = nil
    colorBoxes = {}
    addons = {}
    selectedOutfitGridItem = nil
  end
end

function randomize()
  if not outfitWindow or #colorBoxes == 0 then
    return
  end
  local outfitTemplate = {
    outfitWindow:recursiveGetChildById("head"),
    outfitWindow:recursiveGetChildById("primary"),
    outfitWindow:recursiveGetChildById("secondary"),
    outfitWindow:recursiveGetChildById("detail")
  }

  for i = 1, #outfitTemplate do
    if outfitTemplate[i] then
      outfitTemplate[i]:setChecked(true)
    end
    colorBoxes[math.random(1, #colorBoxes)]:setChecked(true)
    if outfitTemplate[i] then
      outfitTemplate[i]:setChecked(false)
    end
  end
  outfitTemplate[1]:setChecked(true)
end

function accept()
  local outfit = outfitWindow:recursiveGetChildById("type").creature:getOutfit()
  for i, child in pairs(outfitWindow.extensions:getChildren()) do
    if child:getId() == "healthBar" or child:getId() == "manaBar" then
      outfit[child:getId()] = child.bar.selected
    else
      if child.creature:getCreature() then
        if child:getId() == "shader" then
          outfit[child:getId()] = child.creature:getOutfit().shader
        else
          outfit[child:getId()] = child.creature:getOutfit().type
        end
      end
    end
  end

  g_game.changeOutfit(outfit)
  destroy()
end

function onAddonCheckChange(addon, value)
  local outfit = outfitWindow:recursiveGetChildById("type").creature:getOutfit()
  if addon:isChecked() then
    outfit.addons = outfit.addons + value
  else
    outfit.addons = outfit.addons - value
  end
  outfitWindow:recursiveGetChildById("type").creature:setOutfit(outfit)
end

function onColorCheckChange(colorBox)
  local outfit = outfitWindow:recursiveGetChildById("type").creature:getOutfit()
  if colorBox == currentColorBox then
    colorBox.onCheckChange = nil
    colorBox:setChecked(true)
    colorBox.onCheckChange = onColorCheckChange
  else
    if currentColorBox then
      currentColorBox.onCheckChange = nil
      currentColorBox:setChecked(false)
      currentColorBox.onCheckChange = onColorCheckChange
    end

    currentColorBox = colorBox

    if not currentClotheButtonBox then
      currentClotheButtonBox = outfitWindow:recursiveGetChildById("head")
    end
    if not currentClotheButtonBox then
      return
    end
    if currentClotheButtonBox:getId() == "head" then
      outfit.head = currentColorBox.colorId
    elseif currentClotheButtonBox:getId() == "primary" then
      outfit.body = currentColorBox.colorId
    elseif currentClotheButtonBox:getId() == "secondary" then
      outfit.legs = currentColorBox.colorId
    elseif currentClotheButtonBox:getId() == "detail" then
      outfit.feet = currentColorBox.colorId
    end
    outfitWindow:recursiveGetChildById("type").creature:setOutfit(outfit)
  end
end

function onClotheCheckChange(clotheButtonBox)
  local outfit = outfitWindow:recursiveGetChildById("type").creature:getOutfit()
  if clotheButtonBox == currentClotheButtonBox then
    clotheButtonBox.onCheckChange = nil
    clotheButtonBox:setChecked(true)
    clotheButtonBox.onCheckChange = onClotheCheckChange
  else
    currentClotheButtonBox.onCheckChange = nil
    currentClotheButtonBox:setChecked(false)
    currentClotheButtonBox.onCheckChange = onClotheCheckChange

    currentClotheButtonBox = clotheButtonBox

    local colorId = 0
    if not currentClotheButtonBox then
      currentClotheButtonBox = outfitWindow:recursiveGetChildById("head")
    end
    if not currentClotheButtonBox then
      return
    end
    if currentClotheButtonBox:getId() == "head" then
      colorId = outfit.head
    elseif currentClotheButtonBox:getId() == "primary" then
      colorId = outfit.body
    elseif currentClotheButtonBox:getId() == "secondary" then
      colorId = outfit.legs
    elseif currentClotheButtonBox:getId() == "detail" then
      colorId = outfit.feet
    end
    outfitWindow:recursiveGetChildById("colorBox" .. colorId):setChecked(true)
  end
end

function updateOutfit()
  local typeWidget = outfitWindow:recursiveGetChildById("type")
  if not typeWidget or not typeWidget.outfit then
    return
  end
  local currentSelection = typeWidget.outfit
  if not currentSelection then
    return
  end
  local outfit = outfitWindow:recursiveGetChildById("type").creature:getOutfit()

  local availableAddons = currentSelection[3]
  local prevAddons = {}
  for k, addon in pairs(addons) do
    if addon.widget then
      prevAddons[k] = addon.widget:isChecked()
      addon.widget:setChecked(false)
      addon.widget:setEnabled(false)
    else
      prevAddons[k] = false
    end
  end
  outfit.addons = 0
  outfitWindow:recursiveGetChildById("type").creature:setOutfit(outfit)

  local shader = outfitWindow.extensions:getChildById("shader")
  if shader then
    outfit.shader = shader.creature:getOutfit().shader
    if outfit.shader == "-" then
      outfit.shader = ""
    end
    shader.creature:setOutfit(outfit)
  end

  if availableAddons > 0 then
    for _, i in pairs(ADDON_SETS[availableAddons]) do
      addons[i].widget:setEnabled(true)
      if addons[i] and addons[i].widget then
        addons[i].widget:setChecked(true)
      end
    end
  end
end
