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

//! Integration tests for [`ltk::Element::map`] — the Elm-style adapter
//! that re-tags every per-leaf message in a sub-tree.
//!
//! Each test renders the mapped tree through a software [`UiSurface`],
//! looks up the per-widget [`WidgetHandlers`] snapshot the runtime
//! produced, and asserts that pressing a leaf fires the *outer*
//! `AppMsg::Sub( ... )` instead of the inner `SubMsg::...`.

use ltk::core::{ RenderOptions, UiSurface };
use ltk::test_support::WidgetHandlers;
use ltk::{
	button, checkbox, column, list_item, radio, slider, text_edit, toggle,
	vslider,
	Color, Element,
};

#[ derive( Clone, Debug, PartialEq ) ]
enum SubMsg
{
	Pressed,
	Toggled,
	Selected,
	Open,
	Slid( i32 ),
	Vol( i32 ),
	Typed( String ),
	Submit,
}

#[ derive( Clone, Debug, PartialEq ) ]
enum AppMsg
{
	Sub( SubMsg ),
}

fn sub_view() -> Element<SubMsg>
{
	column::<SubMsg>()
		.padding( 0.0 )
		.spacing( 4.0 )
		.push( button( "press" ).on_press( SubMsg::Pressed ) )
		.push( toggle( false ).on_toggle( SubMsg::Toggled ) )
		.push( checkbox( true ).on_toggle( SubMsg::Toggled ) )
		.push( radio( false ).on_select( SubMsg::Selected ) )
		.push( list_item( "row" ).on_press( SubMsg::Open ) )
		.push( slider( 0.5 ).on_change( |v| SubMsg::Slid( ( v * 100.0 ) as i32 ) ) )
		.push( vslider( 0.25 ).on_change( |v| SubMsg::Vol( ( v * 100.0 ) as i32 ) ) )
		.push( text_edit::<SubMsg>( "ph", "" )
			.on_change( SubMsg::Typed )
			.on_submit( SubMsg::Submit ) )
		.into()
}

fn render_mapped() -> UiSurface<AppMsg>
{
	let mapped: Element<AppMsg> = sub_view().map( AppMsg::Sub );
	let mut surface = UiSurface::<AppMsg>::new( 320, 320 );
	let _ = surface.render(
		&mapped,
		RenderOptions::full_canvas( 320, 320 ).background( Color::rgb( 0.1, 0.1, 0.1 ) ),
	);
	surface
}

/// Walk every laid-out widget rect in `surface` and call `probe` with
/// each handler snapshot. The probe builds the test assertion for the
/// matching widget kind.
fn for_each_handler( surface: &UiSurface<AppMsg>, mut probe: impl FnMut( &WidgetHandlers<AppMsg> ) )
{
	for widget in surface.widget_rects()
	{
		probe( &widget.handlers );
	}
}

#[ test ]
fn button_press_msg_is_remapped()
{
	let surface = render_mapped();
	let mut found = false;
	for_each_handler( &surface, |h|
	{
		if let WidgetHandlers::Button { on_press, .. } = h
		{
			if let Some( msg ) = on_press
			{
				assert_eq!( *msg, AppMsg::Sub( SubMsg::Pressed ), "button.on_press" );
				found = true;
			}
		}
	} );
	assert!( found, "no Button handler with on_press in the rendered tree" );
}

#[ test ]
fn toggle_and_checkbox_messages_are_remapped()
{
	let surface = render_mapped();
	let mut toggle_seen   = false;
	let mut checkbox_seen = false;
	for_each_handler( &surface, |h|
	{
		match h
		{
			WidgetHandlers::Toggle   { on_toggle: Some( m ), .. } =>
			{
				assert_eq!( *m, AppMsg::Sub( SubMsg::Toggled ) );
				toggle_seen = true;
			}
			WidgetHandlers::Checkbox { on_toggle: Some( m ), .. } =>
			{
				assert_eq!( *m, AppMsg::Sub( SubMsg::Toggled ) );
				checkbox_seen = true;
			}
			_ => {}
		}
	} );
	assert!( toggle_seen );
	assert!( checkbox_seen );
}

#[ test ]
fn radio_and_list_item_messages_are_remapped()
{
	let surface = render_mapped();
	let mut radio_seen = false;
	let mut item_seen  = false;
	for_each_handler( &surface, |h|
	{
		match h
		{
			WidgetHandlers::Radio    { on_select: Some( m ), .. } =>
			{
				assert_eq!( *m, AppMsg::Sub( SubMsg::Selected ) );
				radio_seen = true;
			}
			WidgetHandlers::ListItem { on_press:  Some( m ) } =>
			{
				assert_eq!( *m, AppMsg::Sub( SubMsg::Open ) );
				item_seen = true;
			}
			_ => {}
		}
	} );
	assert!( radio_seen );
	assert!( item_seen );
}

#[ test ]
fn slider_callbacks_run_through_the_mapper()
{
	let surface = render_mapped();
	let mut h_axis = false;
	let mut v_axis = false;
	for_each_handler( &surface, |h|
	{
		if let WidgetHandlers::Slider { on_change: Some( cb ), axis, .. } = h
		{
			// `cb` binds by-ref through default match ergonomics, so
			// reach the trait object via `**cb` to invoke it.
			let msg = ( **cb )( 0.5 );
			match axis
			{
				ltk::SliderAxis::Horizontal =>
				{
					assert_eq!( msg, AppMsg::Sub( SubMsg::Slid( 50 ) ) );
					h_axis = true;
				}
				ltk::SliderAxis::Vertical =>
				{
					assert_eq!( msg, AppMsg::Sub( SubMsg::Vol( 50 ) ) );
					v_axis = true;
				}
			}
		}
	} );
	assert!( h_axis, "horizontal slider handler not exercised" );
	assert!( v_axis, "vertical slider handler not exercised" );
}

#[ test ]
fn text_edit_on_change_and_submit_are_remapped()
{
	let surface = render_mapped();
	let mut found = false;
	for_each_handler( &surface, |h|
	{
		if let WidgetHandlers::TextEdit { on_change: Some( cb ), on_submit: Some( s ), .. } = h
		{
			let typed = ( **cb )( "hello".to_string() );
			assert_eq!( typed, AppMsg::Sub( SubMsg::Typed( "hello".to_string() ) ) );
			assert_eq!( *s, AppMsg::Sub( SubMsg::Submit ) );
			found = true;
		}
	} );
	assert!( found, "TextEdit handler not seen" );
}

#[ test ]
fn map_walks_into_nested_layouts()
{
	// One level of nesting: Column -> Container -> Button.
	use ltk::container;
	let inner: Element<SubMsg> = container( button( "inner" ).on_press( SubMsg::Pressed ) ).into();
	let outer: Element<SubMsg> = column::<SubMsg>().padding( 0.0 ).push( inner ).into();
	let mapped: Element<AppMsg> = outer.map( AppMsg::Sub );

	let mut surface = UiSurface::<AppMsg>::new( 200, 200 );
	let _ = surface.render(
		&mapped,
		RenderOptions::full_canvas( 200, 200 ).background( Color::rgb( 0.1, 0.1, 0.1 ) ),
	);

	let widget = surface.widget_rects().iter().find( |w|
		matches!( w.handlers, WidgetHandlers::Button { on_press: Some( _ ), .. } ) );
	let widget = widget.expect( "button under nested layout not found" );
	if let WidgetHandlers::Button { on_press: Some( msg ), .. } = &widget.handlers
	{
		assert_eq!( *msg, AppMsg::Sub( SubMsg::Pressed ) );
	} else { unreachable!() }
}

#[ test ]
fn map_can_be_chained()
{
	// `view -> map(L1) -> map(L2)` rewrites twice; the inner Sub gets
	// double-wrapped. Verifies that a child Element<U> mapped again is
	// still walkable and the closure chain composes left-to-right.
	#[ derive( Clone, Debug, PartialEq ) ]
	enum L1 { Wrap( SubMsg ) }
	#[ derive( Clone, Debug, PartialEq ) ]
	enum L2 { Wrap( L1 ) }

	let leaf: Element<SubMsg> = button( "x" ).on_press( SubMsg::Pressed ).into();
	let l1:   Element<L1>     = leaf.map( L1::Wrap );
	let l2:   Element<L2>     = l1.map( L2::Wrap );

	let mut surface = UiSurface::<L2>::new( 100, 80 );
	let _ = surface.render(
		&l2,
		RenderOptions::full_canvas( 100, 80 ).background( Color::rgb( 0.1, 0.1, 0.1 ) ),
	);
	let widget = &surface.widget_rects()[ 0 ];
	if let WidgetHandlers::Button { on_press: Some( msg ), .. } = &widget.handlers
	{
		assert_eq!( *msg, L2::Wrap( L1::Wrap( SubMsg::Pressed ) ) );
	} else { panic!( "expected Button handler" ) }
}
