-- luacheck: globals Character MyModGlobal CLIENT
if not CLIENT then return end

---@return Barotrauma.Item|nil, Barotrauma.Items.Components.Repairable|nil
local function getRepairableObjectInFocus()
	-- Make sure we have a controlled character
	local controlledCharacter = Character.Controlled
	if not controlledCharacter then
		-- MyModGlobal.debugPrint("No controlled character")
		return nil, nil
	end

	-- Check if we have a selected item - this is necessary for repair interfaces to show
	local selectedItem = controlledCharacter.SelectedItem
	if not selectedItem then
		-- MyModGlobal.debugPrint("No selected item")
		return nil, nil
	end

	-- Check if the selected item is in fact the repairable object itself
	for _, component in pairs(selectedItem.Components) do
		if component.Name == "Repairable" then
			-- Check if repair interface should be shown
			if component:ShouldDrawHUD(controlledCharacter) then
				return selectedItem, component
			end
		end
	end

	-- Nothing found
	return nil, nil
end

-- TODO: Character.HeldItems seems interesting
---@return boolean
local function clickRepairButton()
	local item, repairableComponent = getRepairableObjectInFocus()
	if not item or not repairableComponent then
		-- MyModGlobal.debugPrint("No repairable object in focus")
		return false
	end

	-- Access the controlled character
	local controlledCharacter = Character.Controlled
	if not controlledCharacter then
		-- MyModGlobal.debugPrint("No controlled character")
		return false
	end

	-- Call the StartRepairing method directly
	-- The second parameter (FixActions.Repair = 1) indicates a repair action
	local result = repairableComponent.StartRepairing(controlledCharacter, 1)
	local button = repairableComponent.RepairButton
	if button then
		MyModGlobal.debugPrint("Clicking repair button")
		-- Try to access repair functionality directly
		repairableComponent.requestStartFixAction = 1 -- FixActions.Repair = 1
	end
	-- MyModGlobal.debugPrint("StartRepairing result: " .. tostring(result))

	return result
end

local function tryRepair()
	clickRepairButton()
	-- local success = clickRepairButton()
	-- if success then
	-- 	-- MyModGlobal.debugPrint("Successfully clicked repair button")
	-- else
	-- 	-- MyModGlobal.debugPrint("Failed to click repair button")
	-- end
end

return {
	tryRepair = tryRepair
}
