// Screen 02 — Select language.
//
// Long, scrollable list of endonyms with a chevron on the right. Tap
// commits the locale and advances to Welcome (handled by
// `Msg::SelectLanguage` in `app::update`).

use ltk::
{
	Element,
	column, pressable, row, scroll, separator, spacer, text,
};

use crate::app::Msg;
use crate::assets;
use crate::flow::Screen;
use crate::i18n;
use crate::state::State;
use crate::ui::chrome;
use crate::ui::theme as t;

pub fn view( state: &State ) -> Element<Msg>
{
	let mut list = column::<Msg>().spacing( 0.0 );
	for ( i, lang ) in i18n::SUPPORTED.iter().enumerate()
	{
		if i > 0 { list = list.push( separator() ); }
		list = list.push( language_row(
			lang.endonym,
			Msg::SelectLanguage( lang.code.to_string() ),
		) );
	}

	let ( w, h ) = state.viewport;
	let short_side = w.min( h ) as f32;
	let icon_px = ( short_side * 0.12 ) as u32;
	let badge: Element<Msg> = assets::illustration_widget::<Msg>( assets::LANGUAGE_ICON, icon_px )
		.unwrap_or_else( || spacer().into() );

	let mut body = column::<Msg>()
		.padding( t::PAGE_PADDING_H )
		.spacing( t::SECTION_SPACING )
		.align_center_x( true )
		.push( chrome::top_bar( Screen::SelectLanguage, false, state.mode ) )
		.push( badge )
		.push( scroll( list ) );

	// Landscape: cap the column to half the surface so the list does
	// not stretch across a wide laptop window.
	if w > h
	{
		body = body.max_width( w as f32 * 0.4 );
	}

	chrome::page( body )
}

fn language_row( label: &str, on_press: Msg ) -> Element<Msg>
{
	let palette = ltk::theme_palette();

	let chevron: Element<Msg> = assets::theme_icon::<Msg>( "general/right", 13 )
		.unwrap_or_else( || spacer().into() );

	let inner = row::<Msg>()
		.spacing( t::ITEM_SPACING )
		.padding( 14.0 )
		.push(
			text( label.to_string() )
				.size( t::BODY_SIZE )
				.color( palette.text_primary ),
		)
		.push( spacer() )
		.push( chevron );

	pressable::<Msg>( inner ).on_press( on_press ).into()
}
