// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>

use smithay_client_toolkit::seat::keyboard::{ KeyEvent, Keysym };

use crate::app::App;
use crate::event_loop::{ AppData, SurfaceFocus };

impl<A: App> AppData<A>
{
	/// Run the same dispatch logic that the Wayland press-key handler
	/// runs, but without the trait-callback signature — used both by
	/// the trait method and by the key-repeat timer.
	pub( crate ) fn dispatch_key( &mut self, focus: SurfaceFocus, event: KeyEvent )
	{
		// `set_focus` (Tab handling) needs a `QueueHandle`. Cloning is
		// cheap (an `Arc`-equivalent under the hood) and avoids
		// threading the qh through every helper.
		let qh = self.qh.clone();
		let qh = &qh;
		match event.keysym
		{
			Keysym::BackSpace                 => self.handle_key_backspace( focus, &event ),
			Keysym::Delete                    => self.handle_key_delete( focus, &event ),
			Keysym::Return | Keysym::KP_Enter => self.handle_key_return( focus, &event ),
			Keysym::Down | Keysym::Up         => self.handle_key_arrow_vertical( focus, &event ),
			Keysym::Left | Keysym::Right      => self.handle_key_arrow_horizontal( focus, &event ),
			Keysym::Home                      => self.handle_key_home( focus ),
			Keysym::End                       => self.handle_key_end( focus ),
			Keysym::a | Keysym::A if self.ctrl_pressed => self.handle_key_ctrl_a( focus ),
			Keysym::c | Keysym::C if self.ctrl_pressed => self.handle_key_ctrl_c( focus ),
			Keysym::x | Keysym::X if self.ctrl_pressed => self.handle_key_ctrl_x( focus ),
			Keysym::v | Keysym::V if self.ctrl_pressed => self.handle_key_ctrl_v( focus ),
			Keysym::Tab | Keysym::ISO_Left_Tab => self.handle_key_tab( focus, &event, qh ),
			Keysym::Escape                    => self.handle_key_escape( focus, &event, qh ),
			Keysym::space                     => self.handle_key_space( focus, &event ),
			_                                 => self.handle_key_default( focus, &event ),
		}
		self.surface_mut( focus ).request_redraw();
	}
}
