print("Loaded game_forge module!")

forgeWindow = nil

function init()
	print("[Forge] Init called.")

	local ui = g_ui.loadUI('game_forge')
	if not ui then
		print("[Forge] Failed to load UI file with loadUI.")
		return
	end
  

	forgeWindow = ui:recursiveGetChildById('LoadForgeWindow')
	if not forgeWindow then
	  print("[Forge] Failed to find Forge Window in UI.")
	  return
	end

	modules.game_interface.getRootPanel():addChild(forgeWindow)
	forgeWindow:show()
	forgeWindow:breakAnchors()
	forgeWindow:move(
	  (g_window.getWidth() - forgeWindow:getWidth()) / 2,
	  (g_window.getHeight() - forgeWindow:getHeight()) / 2
	)

	local conversionLayout = forgeWindow:recursiveGetChildById('conversion_layout')
	local transferLayout   = forgeWindow:recursiveGetChildById('transfer_layout')
	local historyLayout    = forgeWindow:recursiveGetChildById('history_layout')
	local fusionLayout     = forgeWindow:recursiveGetChildById('fusion_layout')

	if fusionLayout and conversionLayout and transferLayout and historyLayout then
 		 fusionLayout:setVisible(true)
 		 conversionLayout:setVisible(false)
 		 transferLayout:setVisible(false)
 		 historyLayout:setVisible(false)
	end

	if fusionButton then
		fusionButton:setChecked(true)
	end

	local sliverActionButton = forgeWindow:recursiveGetChildById('sliver_action')
	sliverActionButton.onClick = function()
		print("[Forge] Sliver action button.")
	end

	local coreActionButton = forgeWindow:recursiveGetChildById('exalted_core_action')
	coreActionButton.onClick = function()
		print("[Forge] Exalted Core action button.")
	end
	  
	local dustLimitActionButton = forgeWindow:recursiveGetChildById('dust_limit_action')
	dustLimitActionButton.onClick = function()
		print("[Forge] Dust limit action button.")
	end
  
	local closeButton = forgeWindow:recursiveGetChildById('close_forge')
	if closeButton then
		closeButton.onClick = function()
		print("[Forge] Close button clicked.")
		forgeWindow:hide()
		end
	else
		print("[Forge] close_forge button not found.")
	end
	
	
	local conversionLayout = forgeWindow:recursiveGetChildById('conversion_layout')
	local transferLayout = forgeWindow:recursiveGetChildById('transfer_layout')
	local historyLayout = forgeWindow:recursiveGetChildById('history_layout')
	local fusionLayout = forgeWindow:recursiveGetChildById('fusion_layout')

	local fusionButton = forgeWindow:recursiveGetChildById('fusion_button')
	fusionButton.onClick = function()
		print("[Forge] Fusion button clicked.")
		fusionLayout:setVisible(true)
		conversionLayout:setVisible(false)
		historyLayout:setVisible(false)
		transferLayout:setVisible(false)
	end

	local transferButton = forgeWindow:recursiveGetChildById('transfer_button')
	transferButton.onClick = function()
		print("[Forge] Transfer button clicked.")
		transferLayout:setVisible(true)
		fusionLayout:setVisible(false)
		conversionLayout:setVisible(false)
		historyLayout:setVisible(false)
	end

	local conversionButton = forgeWindow:recursiveGetChildById('conversion_button')
	conversionButton.onClick = function()
		print("[Forge] Conversion button clicked.")
		conversionLayout:setVisible(true)
		transferLayout:setVisible(false)
		fusionLayout:setVisible(false)
		historyLayout:setVisible(false)
	end

	local historyButton = forgeWindow:recursiveGetChildById('history_button')
	historyButton.onClick = function()
		print("[Forge] History button clicked.")
		historyLayout:setVisible(true)
		transferLayout:setVisible(false)
		fusionLayout:setVisible(false)
		conversionLayout:setVisible(false)
		
		modules.game_forge.loadHistoryPage(1)
	end

	local transferLayout = forgeWindow:recursiveGetChildById('transfer_layout')
	transferLayout = forgeWindow:recursiveGetChildById('transfer_layout')
	if not transferLayout then
		print("[Forge] transfer_layout not found.")
	end
	
	local transferActionButton = forgeWindow:recursiveGetChildById('transfer_item_action')
	transferActionButton.onClick = function()
		print("[Forge] Transfer Action - button clicked to Transfer Item's Tier.")
	end
	
	local currentPage = 1
	local nextButton = forgeWindow:recursiveGetChildById('next_page_button')
	if nextButton then
	  nextButton.onClick = function()
		currentPage = currentPage + 1
		modules.game_forge.loadHistoryPage(currentPage)
	  end
	end

	local previousButton = forgeWindow:recursiveGetChildById('previous_page_button')
	if previousButton then
	  previousButton.onClick = function()
		currentPage = currentPage - 1
		modules.game_forge.loadHistoryPage(currentPage)
	  end
	end

	local fusionActionButton = forgeWindow:recursiveGetChildById('fusion_action')
	if fusionActionButton then
		fusionActionButton.onClick = function()
			print("FUSION USED: FUSING ITEMS!")
		end
	else
		print("[Forge] fusion_action button not found.")
	end
end

function modules.game_forge.updateWindowDescription(widget)
  local desc = forgeWindow:recursiveGetChildById('windows_description')
  if not desc then return end

  local isHovered = widget:isHovered()
  print(string.format("[Forge] Hover state: %s = %s", widget:getId(), tostring(isHovered)))

  if isHovered then
     if widget:getId() == "sliver_action" then
       desc:setText("Convert your dust into slivers.\nSlivers are used to create exalted cores which are useful for fusions and transfers.")
     elseif widget:getId() == "exalted_core_action" then
       desc:setText("Convert slivers into exalted cores.\nExalted cores are useful for fusions and transfers.")
     elseif widget:getId() == "dust_limit_action" then
       desc:setText("Use dust to increase permanently the amount of dust you can gather (141) currently.")
     end
   else
    desc:setText("Move mouse over an action buttons to see more details.")
   end
end

function modules.game_forge.onImprove65Clicked()
  if not forgeWindow then return end

  local button = forgeWindow:recursiveGetChildById('improve_to_65_button')
  local label  = forgeWindow:recursiveGetChildById('improve_to_65_label')
  if not button or not label then return end

  button.__pushed = not button.__pushed

  if button.__pushed then
    button:setText("Active!")
    label:setText("Success rate 65%")
    if label.setColor then
      label:setColor("#33cc66")
    else
      label:setStyle("color: #33cc66")
    end
    print("[Forge] Improve Success Rate to 65%: ACTIVE!")
  else
    button:setText("Improve to 65%")
    label:setText("Success rate 50%")
    if label.setColor then
      label:setColor("#ff4d4d")
    else
      label:setStyle("color: #ff4d4d")
    end
    print("[Forge] Improve Success Rate to 65%: NOT ACTIVE!")
  end
end

function modules.game_forge.onReduce50Clicked()
  if not forgeWindow then return end
  local button = forgeWindow:recursiveGetChildById('reduce_to_50_button')
  local label  = forgeWindow:recursiveGetChildById('reduce_to_50_label')
  if not button or not label then return end

  button.__pushed = not button.__pushed

  if button.__pushed then
    button:setText("Active!")
    label:setText("Tier loss 100%")
    if label.setColor then
      label:setColor("#33cc66")
    else
      label:setStyle("color: #33cc66")
    end
    print("[Forge] Reduce Tier Loss to 100%: ACTIVE!")
  else
    button:setText("Tier loss 50%")
    label:setText("Tier loss 50%")
    if label.setColor then
      label:setColor("#ff4d4d")
    else
      label:setStyle("color: #ff4d4d")
    end
    print("[Forge] Reduce Tier Loss to 100%: NOT ACTIVE!")
  end
end

function modules.game_forge.updateWindowTransferRequirements(widget)
  local description = forgeWindow:recursiveGetChildById('windows_description_transfer')
  if not description then return end

  local isHovered = widget:isHovered()
  print(string.format("[Forge] Hover state: %s = %s", widget:getId(), tostring(isHovered)))

  if isHovered then
     if widget:getId() == "questionmark_image_on_transfer" then
       description:setText("You do not carry an item whose tier can be transferred. Not that imbued items cannot be used for a transfer.")
     elseif widget:getId() == "dust_image_on_transfer" then
       description:setText("A transfer requres 100 dust.")
     elseif widget:getId() == "core_image_on_transfer" then
       description:setText("You do not carry an item whose tier can be transferred. Not that imbued items cannot be used for a transfer.")
	 elseif widget:getId() == "transfer_item_action" then
       description:setText("Please select both the item whose tier you wish to transfer and the item you want to transfer the tier to.")
     end
   else
	description:setText("You can transfer the tier of an item to another item of the same classification. To do so, you need at least a tier 2 item that will be consumed during the transfer and additional resources. The other item will recieve the consumed item's tier reduced by one.")
   end
end

local FUSION_DESC_DEFAULT =
  "The aim of a fusion is to increase the tier of an item. The classification of an item defines its maximum tier. " ..
  "If two items are fused, you can spend exaltation cores. Items with a tier grant unique bonuses."

function modules.game_forge.setFusionDesc(widget)
  if not forgeWindow or not widget then return end
  local box = forgeWindow:recursiveGetChildById('windows_description_fusion')
  if not box then return end

  local isHovered = widget.isHovered and widget:isHovered() or false
  local wid = widget.getId and widget:getId() or ""

  if isHovered and wid == "dust_image_on_fusion" then
    box:setText("A fusion requires 100 dust. Unfortunately you do not own the needed amount.")
    if box.setColor then box:setColor("#ff4d4d") end
  elseif isHovered and wid == "fusion_action" then
    box:setText("Please select all required ingredients.")
    if box.setColor then box:setColor("#dfdfdf") end
  elseif isHovered and wid == "questionmark_image_on_fusion" then
    box:setText("Please select all required ingredients.")
    if box.setColor then box:setColor("#dfdfdf") end
  else
    box:setText(FUSION_DESC_DEFAULT)
    if box.setColor then box:setColor("#dfdfdf") end
  end
end

function modules.game_forge.onConvergenceToggled(isChecked)
  print("Transfer Convergence toggled: " .. tostring(isChecked))

  local checkbox = forgeWindow:recursiveGetChildById('convergence_small_box')
  local transferTitle = forgeWindow:recursiveGetChildById('transfer_tier_bottom')
  if not checkbox or not transferTitle then return end

  if isChecked then
    checkbox:setImageSource('/images/game/forge/checkmark_overlay')
    transferTitle:setText("Convergence Transfer Requirements")
  else
    checkbox:setImageSource('/images/ui/dark_background')
    transferTitle:setText("Transfer Requirements")
  end
end

local function setVisibleSafe(w, show)
  if not w then return end
  if w.show and w.hide then
    if show then w:show() else w:hide() end
  else
    w:setVisible(show)
  end
end

function modules.game_forge.onFusionConvergenceToggled(isChecked)
  print("Fusion Convergence toggled: " .. tostring(isChecked))
  if not forgeWindow then return end

  local checkboxFusion = forgeWindow:recursiveGetChildById('convergence_small_box_in_fusion')
  local fusionTitle    = forgeWindow:recursiveGetChildById('fuse_window_bottom')
  if not checkboxFusion or not fusionTitle then return end

  local rightBox    = forgeWindow:recursiveGetChildById('transfer_tier_box_second_fusion')
  local rightScroll = forgeWindow:recursiveGetChildById('fusion_window_second_scroll_bar')

  local qSmall       = forgeWindow:recursiveGetChildById('questionmark_image_on_fusion')
  local qSmallCount  = forgeWindow:recursiveGetChildById('under_questionmark_numbers_on_fusion')
  local dust         = forgeWindow:recursiveGetChildById('dust_image_on_fusion')
  local dustCount    = forgeWindow:recursiveGetChildById('under_dust_image_numbers2')
  local arrowFirstTr = forgeWindow:recursiveGetChildById('arrow_east_first_transfer')
  local coreNear1    = forgeWindow:recursiveGetChildById('core_image_near_reducer')
  local coreNear2    = forgeWindow:recursiveGetChildById('core_image_near_reducer2')

  local toGoOne    = forgeWindow:recursiveGetChildById('label_one_to_go')
  local toGoTwo    = forgeWindow:recursiveGetChildById('label_two_to_go')

  local bgDustConv   = forgeWindow:recursiveGetChildById('bg_under_dust_conv')
  local dustConv     = forgeWindow:recursiveGetChildById('dust_image_on_fusion_conv')
  local dustNumConv  = forgeWindow:recursiveGetChildById('under_dust_image_numbers_conv')

  local improveBtn = forgeWindow:recursiveGetChildById('improve_to_65_button')
  local improveLbl = forgeWindow:recursiveGetChildById('improve_to_65_label')
  local reduceBtn  = forgeWindow:recursiveGetChildById('reduce_to_50_button')
  local reduceLbl  = forgeWindow:recursiveGetChildById('reduce_to_50_label')
  local coreCountTop    = forgeWindow:recursiveGetChildById('core_count_top_label')
  local coreCountBottom = forgeWindow:recursiveGetChildById('core_count_bottom_label')

  if isChecked then
    checkboxFusion:setImageSource('/images/game/forge/checkmark_overlay')
    fusionTitle:setText("Further Items Needed For Convergence Fusion")

    setVisibleSafe(dustCount, false)
    setVisibleSafe(coreNear1, false)
    setVisibleSafe(coreNear2, false)
    setVisibleSafe(improveBtn, false)
    setVisibleSafe(improveLbl, false)
    setVisibleSafe(reduceBtn, false)
    setVisibleSafe(reduceLbl, false)
    setVisibleSafe(coreCountTop, false)
    setVisibleSafe(coreCountBottom, false)

	setVisibleSafe(toGoOne, false)
    setVisibleSafe(toGoTwo, false)

	setVisibleSafe(bgDustConv, true)
    setVisibleSafe(dustConv, true)
	setVisibleSafe(dustNumConv, true)

    setVisibleSafe(qSmall, false)
    setVisibleSafe(qSmallCount, false)
    setVisibleSafe(dust, false)
    setVisibleSafe(arrowFirstTr, false)

    setVisibleSafe(rightBox, true)
    setVisibleSafe(rightScroll, true)

  else
    checkboxFusion:setImageSource('/images/ui/dark_background')
    fusionTitle:setText("Further Items Needed For Fusion")

    setVisibleSafe(dustCount, true)
    setVisibleSafe(coreNear1, true)
    setVisibleSafe(coreNear2, true)
    setVisibleSafe(improveBtn, true)
    setVisibleSafe(improveLbl, true)
    setVisibleSafe(reduceBtn, true)
    setVisibleSafe(reduceLbl, true)
    setVisibleSafe(coreCountTop, true)
    setVisibleSafe(coreCountBottom, true)

	setVisibleSafe(bgDustConv, false)
	setVisibleSafe(dustConv, false)
	setVisibleSafe(dustNumConv, false)

	setVisibleSafe(toGoOne, true)
    setVisibleSafe(toGoTwo, true)

    setVisibleSafe(qSmall, true)
    setVisibleSafe(qSmallCount, true)
    setVisibleSafe(dust, true)
    setVisibleSafe(arrowFirstTr, true)

    setVisibleSafe(rightBox, false)
    setVisibleSafe(rightScroll, false)
  end
end


function modules.game_forge.loadHistoryPage(page)
	local table = forgeWindow:recursiveGetChildById('history_table')
	if not table then return end

	table:destroyChildren()

	local entries = {
		{ "2025-07-28, 10:22:39", "Conversion", "Increased dust limit to 131." },
		{ "2025-02-07, 10:31:08", "Fusion", "Successful." },
		{ "2025-02-07, 10:28:38", "Fusion", "Unsuccessful." },
		{ "2025-01-10, 15:49:30", "Fusion", "Successful." },
		{ "2025-01-10, 15:42:14", "Conversion", "Increased dust limit to 129." },
		{ "2025-01-10, 15:42:14", "Conversion", "Increased dust limit to 130." },
		{ "2025-01-10, 15:41:26", "Conversion", "Increased dust limit to 127." },
		{ "2025-01-10, 15:41:26", "Conversion", "Increased dust limit to 128." },
		{ "2025-01-10, 15:40:16", "Conversion", "Increased dust limit to 126." }
	}

	for _, entry in ipairs(entries) do
		table:addRow({entry[1], entry[2], entry[3]})
	end

	-- Page logic (unchanged)
	local maxPage = 12
	local pageLabel = forgeWindow:recursiveGetChildById('page_label')
	if pageLabel then
		pageLabel:setText("Page " .. page .. "/" .. maxPage)
	end

	local prevButton = forgeWindow:recursiveGetChildById('previous_page_button')
	local nextButton = forgeWindow:recursiveGetChildById('next_page_button')

	if prevButton then
		prevButton:setVisible(page > 1)
	end

	if nextButton then
		nextButton:setVisible(page < maxPage)
	end
end




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

function hide()
  if forgeWindow then
    --print("[Forge] hide() called") 
    forgeWindow:hide()
  end
end

