#![ cfg( feature = "test-support" ) ]

mod common;
use common::{ lw_none, lw_button, rect };

use ltk::test_support::{ find_widget_at, find_widget, find_handlers, WidgetHandlers };
use ltk::Point;

fn pt( x: f32, y: f32 ) -> Point
{
	Point { x, y }
}

// ── find_widget_at ────────────────────────────────────────────────────────────

#[ test ]
fn hit_test_misses_when_empty()
{
	let widgets: Vec<_> = vec![];
	assert_eq!( find_widget_at::<()>( &widgets, pt( 10.0, 10.0 ) ), None );
}

#[ test ]
fn hit_test_misses_outside_all_rects()
{
	let widgets = vec![
		lw_none( 1, rect( 0.0, 0.0, 50.0, 50.0 ) ),
		lw_none( 2, rect( 100.0, 100.0, 50.0, 50.0 ) ),
	];
	assert_eq!( find_widget_at( &widgets, pt( 75.0, 75.0 ) ), None );
}

#[ test ]
fn hit_test_returns_widget_under_point()
{
	let widgets = vec![
		lw_none( 7, rect( 0.0, 0.0, 100.0, 100.0 ) ),
		lw_none( 8, rect( 200.0, 0.0, 100.0, 100.0 ) ),
	];
	assert_eq!( find_widget_at( &widgets, pt(  50.0,  50.0 ) ), Some( 7 ) );
	assert_eq!( find_widget_at( &widgets, pt( 250.0,  50.0 ) ), Some( 8 ) );
}

#[ test ]
fn hit_test_returns_topmost_when_overlapping()
{
	// Topmost wins. Layout pushes parents before children, so iteration in
	// reverse must return the child (drawn last, last in the slice).
	let widgets = vec![
		lw_none( 1, rect( 0.0, 0.0, 200.0, 200.0 ) ),
		lw_none( 2, rect( 50.0, 50.0, 100.0, 100.0 ) ),
	];
	assert_eq!( find_widget_at( &widgets, pt( 100.0, 100.0 ) ), Some( 2 ) );
	assert_eq!( find_widget_at( &widgets, pt(  10.0,  10.0 ) ), Some( 1 ) );
}

// ── find_widget ───────────────────────────────────────────────────────────────

#[ test ]
fn find_widget_returns_match_by_flat_idx()
{
	let widgets = vec![
		lw_none( 10, rect( 0.0, 0.0, 10.0, 10.0 ) ),
		lw_none( 20, rect( 0.0, 0.0, 10.0, 10.0 ) ),
		lw_none( 30, rect( 0.0, 0.0, 10.0, 10.0 ) ),
	];
	let w = find_widget( &widgets, 20 ).expect( "widget 20 should be found" );
	assert_eq!( w.flat_idx, 20 );
}

#[ test ]
fn find_widget_returns_none_for_missing_idx()
{
	let widgets = vec![ lw_none( 1, rect( 0.0, 0.0, 10.0, 10.0 ) ) ];
	assert!( find_widget( &widgets, 999 ).is_none() );
}

// ── find_handlers ─────────────────────────────────────────────────────────────

#[ test ]
fn find_handlers_returns_button_handler()
{
	let widgets = vec![
		lw_button( 5, rect( 0.0, 0.0, 10.0, 10.0 ) ),
	];
	let h = find_handlers( &widgets, 5 ).expect( "handler should be present" );
	assert!( matches!( h, WidgetHandlers::Button { on_press: Some( () ), .. } ) );
}

#[ test ]
fn find_handlers_returns_none_for_missing_idx()
{
	let widgets = vec![
		lw_button( 5, rect( 0.0, 0.0, 10.0, 10.0 ) ),
	];
	assert!( find_handlers( &widgets, 6 ).is_none() );
}
