local M = {}

function M.create(ctx)
	local mp = ctx.mp
	local input = ctx.input
	local process = ctx.process
	local state = ctx.state
	local subminer_log = ctx.log.subminer_log
	local show_osd = ctx.log.show_osd

	local function ensure_binary_for_menu()
		if process.check_binary_available() then
			return true
		end
		subminer_log("error", "binary", "SubMiner binary not found")
		show_osd("Error: binary not found")
		return false
	end

	local function show_menu()
		if not ensure_binary_for_menu() then
			return
		end

		local items = {
			"Start overlay",
			"Stop overlay",
			"Toggle overlay",
			"Open options",
			"Restart overlay",
			"Check status",
			"Stats",
		}

		local actions = {
			function()
				process.start_overlay()
			end,
			function()
				process.stop_overlay()
			end,
			function()
				process.toggle_overlay()
			end,
			function()
				process.open_options()
			end,
			function()
				process.restart_overlay()
			end,
			function()
				process.check_status()
			end,
			function()
				mp.commandv("script-message", "subminer-stats-toggle")
			end,
		}

		input.select({
			prompt = "SubMiner: ",
			items = items,
			submit = function(index)
				if index and actions[index] then
					actions[index]()
				end
			end,
		})
	end

	local function register_keybindings()
		mp.add_key_binding("y-s", "subminer-start", function()
			process.start_overlay()
		end)
		mp.add_key_binding("y-S", "subminer-stop", function()
			process.stop_overlay()
		end)
		mp.add_key_binding("y-t", "subminer-toggle", function()
			process.toggle_overlay()
		end)
		mp.add_forced_key_binding("v", "subminer-toggle-primary-subtitle-bar", function()
			process.toggle_primary_subtitle_bar()
		end)
		mp.add_key_binding("y-y", "subminer-menu", show_menu)
		mp.add_key_binding("y-o", "subminer-options", function()
			process.open_options()
		end)
		mp.add_key_binding("y-r", "subminer-restart", function()
			process.restart_overlay()
		end)
		mp.add_key_binding("y-c", "subminer-status", function()
			process.check_status()
		end)
		mp.add_key_binding("y-h", "subminer-session-help", function()
			if not ensure_binary_for_menu() then
				return
			end
			process.run_binary_command_async({
				state.binary_path,
				"--session-action",
				'{"actionId":"openSessionHelp"}',
			}, function(ok, result, error)
				if ok then
					return
				end
				local reason = error or (result and result.stderr) or "unknown error"
				subminer_log("warn", "session-bindings", "Session action failed: " .. tostring(reason))
				show_osd("Session action failed")
			end)
		end)
	end

	return {
		show_menu = show_menu,
		register_keybindings = register_keybindings,
	}
end

return M
