proficiencyWindow = nil
local experienceProgress = nil
local numDivisions = 7
local separatorIds = {}
local starIds = {}

function updateImages(numStars)
  local scrollImage = ""
  if numStars >= 1 and numStars <= 2 then
    scrollImage = "/images/game/weapon_proficiency/scroll1"
  elseif numStars >= 3 and numStars <= 4 then
    scrollImage = "/images/game/weapon_proficiency/scroll2"
  elseif numStars >= 5 and numStars <= 6 then
    scrollImage = "/images/game/weapon_proficiency/scroll3"
  elseif numStars == 7 then
    scrollImage = "/images/game/weapon_proficiency/scroll4"
  else
    scrollImage = "/images/game/weapon_proficiency/scroll1"
  end

  local starVal = math.max(1, math.min(numStars, 7))
  local borderImage = "/images/game/weapon_proficiency/" .. tostring(starVal) .. "Full"

  local scrollLabel = g_ui.getRootWidget():recursiveGetChildById("item_scroll")
  local borderLabel = g_ui.getRootWidget():recursiveGetChildById("item_border")

  if scrollLabel then
    scrollLabel:setImageSource(scrollImage)
  end

  if borderLabel then
    borderLabel:setImageSource(borderImage)
  end
end

function addSeparatorStars(numFilledStars)
  if not experienceProgress then return end

  numFilledStars = tonumber(numFilledStars) or 0
  numFilledStars = math.max(0, math.min(numFilledStars, numDivisions))

  for _, id in ipairs(separatorIds or {}) do
    local sep = experienceProgress:getChildById(id)
    if sep then sep:destroy() end
  end
  for _, id in ipairs(starIds or {}) do
    local star = experienceProgress:getChildById(id)
    if star then star:destroy() end
  end
  separatorIds = {}
  starIds = {}

  local barWidth = experienceProgress:getWidth()
  local barHeight = experienceProgress:getHeight()

  local progressFill = experienceProgress:getChildById("progressFill")
  if not progressFill then
    progressFill = g_ui.createWidget("UIWidget", experienceProgress)

    progressFill:setId("progressFill")
    progressFill:addAnchor(AnchorTop, "parent", AnchorTop)
    progressFill:addAnchor(AnchorBottom, "parent", AnchorBottom)
    progressFill:addAnchor(AnchorLeft, "parent", AnchorLeft)
    progressFill:setBackgroundColor("#1f736d")
    progressFill:setMarginTop(2)
    progressFill:setMarginBottom(3)
    progressFill:setMarginLeft(2)
    progressFill:setMarginRight(2)
  end

  local fillPercent = numFilledStars / numDivisions
  local fillWidth = math.floor(barWidth * fillPercent) - 4
  fillWidth = math.max(fillWidth, 0)
  progressFill:setWidth(fillWidth)

  for i = 1, numDivisions - 1 do
    local relPos = i / numDivisions
    local marginLeft = math.floor(barWidth * relPos)

    local separator = g_ui.createWidget("VerticalSeparator", experienceProgress)
    local sepId = "separator" .. i
    separator:setId(sepId)
    table.insert(separatorIds, sepId)

    separator:setHeight(barHeight)
    separator:setWidth(1)
    separator:setMarginTop(1)
    separator:setMarginBottom(2)
    separator:addAnchor(AnchorTop, "parent", AnchorTop)
    separator:addAnchor(AnchorBottom, "parent", AnchorBottom)
    separator:addAnchor(AnchorLeft, "parent", AnchorLeft)
    separator:setMarginLeft(marginLeft)
    separator:setImageBorder(2)
  end

  for i = 1, numDivisions do
    local relCenter = (2 * i - 1) / (2 * numDivisions)
    local marginLeft = math.floor(barWidth * relCenter)

    local star = g_ui.createWidget("Label", experienceProgress)
    local starId = "experience_star" .. i
    star:setId(starId)
    table.insert(starIds, starId)

    if i <= numFilledStars then
      star:setImageSource("/images/game/weapon_proficiency/full_star")
    else
      star:setImageSource("/images/game/weapon_proficiency/empty_star")
    end

    star:setSize({width = 9, height = 10})
    star:addAnchor(AnchorTop, "parent", AnchorTop)
    star:addAnchor(AnchorLeft, "parent", AnchorLeft)
    star:setMarginLeft(marginLeft - math.floor(star:getWidth() / 2))
    star:setMarginTop(math.floor((barHeight - star:getHeight()) / 2) - 1)
  end
  updateImages(numFilledStars)
end

function addLocks(panelId, prefix, numDivisions)
    local panel = proficiencyWindow:recursiveGetChildById(panelId)
    if not panel then
        return
    end

    for i = 1, numDivisions do
        local lock = panel:getChildById(prefix .. "_lock" .. i)
        if lock then
            lock:destroy()
        end
    end

    local panelWidth = panel:getWidth()

    for i = 1, numDivisions do
        local relCenter = (2 * i - 1) / (2 * numDivisions)
        local marginLeft = math.floor(panelWidth * relCenter - 15)

        local lock = g_ui.createWidget("Label", panel)
        local lockId = prefix .. "_lock" .. i
        lock:setId(lockId)
        lock:setImageSource("/images/game/weapon_proficiency/lock")
        lock:setSize({width = 9, height = 14})

        lock:addAnchor(AnchorTop, "parent", AnchorTop)
        lock:setMarginTop(math.floor((panel:getHeight() - lock:getHeight()) / 2) - 20)

        lock:addAnchor(AnchorLeft, "parent", AnchorLeft)
        lock:setMarginLeft(marginLeft - math.floor(lock:getWidth() / 2))
    end

    panel.onGeometryChange = function()
        addLocks(panelId, prefix, numDivisions)
    end
end

function panelSeparators(panel, panelIdPrefix, numDivisions)
    if not panel then
        return
    end

    for i = 1, numDivisions - 1 do
        local sep = panel:getChildById(panelIdPrefix .. "_separator" .. i)
        if sep then
            sep:destroy()
        end
    end

    local panelWidth = panel:getWidth()

    for i = 1, numDivisions - 1 do
        local relPos = i / numDivisions
        local marginLeft = math.floor(panelWidth * relPos - 15)

        local separator = g_ui.createWidget("VerticalSeparator", panel)
        separator:setId(panelIdPrefix .. "_separator" .. i)

        separator:setHeight(panel:getHeight())
        separator:setWidth(1)
        separator:setMarginTop(-9)
        separator:setMarginBottom(-11)

        separator:addAnchor(AnchorTop, "parent", AnchorTop)
        separator:addAnchor(AnchorBottom, "parent", AnchorBottom)
        separator:addAnchor(AnchorLeft, "parent", AnchorLeft)
        separator:setMarginLeft(marginLeft)
        separator:setImageBorder(2) -- Can change back to 1 if you preffer the thinner margins?
    end
end

function testStars()
  local currentStar = 1

  local function nextStar()
    if currentStar > 7 then
      return
    end
    addSeparatorStars(currentStar)
    updateImages(currentStar)

    currentStar = currentStar + 1
    scheduleEvent(nextStar, 800)
  end
  nextStar()
end

function init()
    local ui = g_ui.loadUI("game_weapon_proficiency")
    if not ui then
        print("[Proficiency] Failed to load UI file.")
        return
    end
    proficiencyWindow = ui:recursiveGetChildById("Weapon_Proficiency_GunzodusOT")
    if not proficiencyWindow then
        print("[Proficiency] Failed to find Proficiency Window in UI. Is it here?")
        return
    end
    modules.game_interface.getRootPanel():addChild(proficiencyWindow)
    proficiencyWindow:show()
    proficiencyWindow:breakAnchors()
    proficiencyWindow:move(
        (g_window.getWidth() - proficiencyWindow:getWidth()) / 2,
        (g_window.getHeight() - proficiencyWindow:getHeight()) / 2
    )
    experienceProgress = proficiencyWindow:recursiveGetChildById("experience_progress")
    if experienceProgress then
        addSeparatorStars()
    else
        print("[Proficiency] experience_progress not found.")
    end
    local perkPanel1 = proficiencyWindow:recursiveGetChildById("perk_window")
    local perkPanel2 = proficiencyWindow:recursiveGetChildById("perk_window2")
    if perkPanel1 then
        panelSeparators(perkPanel1, "perk1", 7)
        perkPanel1.onGeometryChange = function()
            panelSeparators(perkPanel1, "perk1", 7)
        end
    end
    if perkPanel2 then
        panelSeparators(perkPanel2, "perk2", 7)
        addLocks("perk_window2", "perk2", 7)
        perkPanel2.onGeometryChange = function()
            panelSeparators(perkPanel2, "perk2", 7)
        end
    end
    testStars()
	
	local CloseButtonProfinciency = proficiencyWindow:recursiveGetChildById('close_button_work')
	if CloseButtonProfinciency then
		CloseButtonProfinciency.onClick = function()
		print("[Profinciency Window] Close button clicked.")
		proficiencyWindow:hide()
		end
	else
		print("[Forge] close_button_work button not found.")
	end
	
end

function terminate()
    if proficiencyWindow then
        proficiencyWindow:destroy()
        proficiencyWindow = nil
    end
end