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

use std::sync::Arc;

use crate::types::{ Length, Rect, WidgetId };
use crate::render::Canvas;
use super::{ elide, Element };

mod theme;

#[ cfg( test ) ]
mod tests;

/// A row inside a list with a primary label and optional subtitle / trailing
/// text.
///
/// Use to build settings menus, navigation lists, contact rows or any other
/// vertically-stacked tappable content. The widget paints its own hover and
/// pressed surfaces and a rounded focus ring; wrap a column of `ListItem`s
/// inside a [`scroll`](crate::scroll) for scrollable lists.
///
/// ```rust,no_run
/// # use ltk::{ column, list_item, scroll, Element };
/// # #[ derive( Clone ) ] enum Msg { OpenWifi, OpenBluetooth, OpenDisplay }
/// # fn _ex() -> Element<Msg> {
/// // In view():
/// scroll(
///     column()
///         .push( list_item( "Wi-Fi" ).trailing( "Eduroam" ).on_press( Msg::OpenWifi ) )
///         .push( list_item( "Bluetooth" ).subtitle( "AirPods Pro" ).on_press( Msg::OpenBluetooth ) )
///         .push( list_item( "Display" ).trailing( "Light" ).on_press( Msg::OpenDisplay ) ),
/// )
/// .into()
/// # }
/// ```
pub struct ListItem<Msg: Clone>
{
	/// Primary label (always visible, top-aligned when a subtitle is
	/// present).
	pub( crate ) label:    String,
	/// Optional secondary line drawn below the label in muted colour.
	/// Makes the row taller when set.
	pub( crate ) subtitle: Option<String>,
	/// Optional right-aligned text (current setting, badge count).
	/// Drawn in muted colour.
	pub( crate ) trailing: Option<String>,
	/// Optional right-aligned icon — RGBA bytes + native dimensions.
	/// Drawn at `theme::TRAILING_ICON_SIZE`, to the right of the
	/// trailing text when both are set. Symbolic icons should be
	/// pre-tinted by the caller (see [`crate::tint_symbolic`]).
	pub( crate ) trailing_icon: Option<( Arc<Vec<u8>>, u32, u32 )>,
	/// Message emitted on tap. `None` keeps the item visible but inert.
	pub( crate ) on_press: Option<Msg>,
	/// Optional stable identifier for focus management.
	pub( crate ) id:       Option<WidgetId>,
	/// `true` paints the row with the dark selected surface and white
	/// text, regardless of hover / press state. Use to indicate the
	/// active item in a list of choices (combo dropdown, settings
	/// group with a single active value).
	pub( crate ) selected: bool,
	/// Optional leading icon — RGBA bytes + native dimensions. The
	/// row reserves `theme::ICON_SIZE + theme::ICON_GAP` on the left
	/// when this is set, and offsets the label / subtitle by the
	/// same amount. Pass `None` to keep the icon-less layout.
	pub( crate ) icon: Option<( Arc<Vec<u8>>, u32, u32 )>,
	/// Optional override of the horizontal content inset. `None`
	/// falls back to `theme::PAD_H`.
	pub( crate ) pad_h: Option<Length>,
	/// Optional override of the theme row height.
	pub( crate ) height: Option<Length>,
	/// Optional override of the primary-label font size.
	pub( crate ) font_size: Option<Length>,
}

impl<Msg: Clone> ListItem<Msg>
{
	/// Create a list item with the given primary label, no subtitle, no
	/// trailing text and no callback.
	pub fn new( label: impl Into<String> ) -> Self
	{
		Self
		{
			label:         label.into(),
			subtitle:      None,
			trailing:      None,
			trailing_icon: None,
			on_press:      None,
			id:            None,
			selected:      false,
			icon:          None,
			pad_h:         None,
			height:        None,
			font_size:     None,
		}
	}

	/// Attach a leading icon. Pass the decoded RGBA buffer alongside
	/// the image's native width and height; the draw path scales it
	/// down to `theme::ICON_SIZE` on the same row baseline as the
	/// label. Symbolic icons should be pre-tinted by the caller (see
	/// [`crate::tint_symbolic`]).
	pub fn icon( mut self, rgba: Arc<Vec<u8>>, w: u32, h: u32 ) -> Self
	{
		self.icon = Some( ( rgba, w, h ) );
		self
	}

	/// Mark this row as the currently-selected option in its list.
	/// Selected rows paint with a dark surface and white text and
	/// override hover / press visuals.
	pub fn selected( mut self, yes: bool ) -> Self
	{
		self.selected = yes;
		self
	}

	/// Add a secondary line below the label. Makes the row taller to
	/// fit both lines comfortably.
	pub fn subtitle( mut self, s: impl Into<String> ) -> Self
	{
		self.subtitle = Some( s.into() );
		self
	}

	/// Add right-aligned text (settings value, badge, disclosure arrow).
	pub fn trailing( mut self, s: impl Into<String> ) -> Self
	{
		self.trailing = Some( s.into() );
		self
	}

	/// Attach a right-aligned icon (disclosure arrow). Pass the decoded
	/// RGBA buffer alongside the image's native width and height; the
	/// draw path scales it down to `theme::TRAILING_ICON_SIZE`.
	pub fn trailing_icon( mut self, rgba: Arc<Vec<u8>>, w: u32, h: u32 ) -> Self
	{
		self.trailing_icon = Some( ( rgba, w, h ) );
		self
	}

	/// Override the horizontal inset between the row edge and its
	/// content (leading icon / label on the left, trailing text or
	/// icon on the right). Accepts logical `f32` pixels or any
	/// [`Length`]; without this it uses the theme default.
	pub fn pad_h( mut self, p: impl Into<Length> ) -> Self
	{
		self.pad_h = Some( p.into() );
		self
	}

	/// Override the preferred row height (default: the theme row
	/// height, `theme::HEIGHT` / `theme::HEIGHT_SUB` design px).
	/// Accepts any [`Length`] so dense menus can trade the touch-target
	/// generosity for row density. The resolved value is floored at the
	/// label's rendered height so the text never clips.
	pub fn height( mut self, h: impl Into<Length> ) -> Self
	{
		self.height = Some( h.into() );
		self
	}

	/// Override the primary-label font size (default: `theme::LABEL_SIZE`
	/// design px, resolved through the widget-scaling mode). Subtitle and
	/// trailing text keep their theme sizes.
	pub fn font_size( mut self, s: impl Into<Length> ) -> Self
	{
		self.font_size = Some( s.into() );
		self
	}

	/// Set the message emitted when the row is tapped.
	pub fn on_press( mut self, msg: Msg ) -> Self
	{
		self.on_press = Some( msg );
		self
	}

	/// Assign a stable identifier for focus management.
	pub fn id( mut self, id: WidgetId ) -> Self
	{
		self.id = Some( id );
		self
	}

	/// Effective primary-label font size on `canvas`, honouring the
	/// [`Self::font_size`] override.
	fn label_px( &self, canvas: &Canvas ) -> f32
	{
		match self.font_size
		{
			Some( l ) => canvas.resolve_font( l ),
			None      => canvas.font_px( theme::LABEL_SIZE ),
		}
	}

	pub fn preferred_size( &self, max_width: f32, canvas: &Canvas ) -> (f32, f32)
	{
		let h = match self.height
		{
			Some( l ) =>
			{
				// Floor at the label's physical height so the row can be
				// squeezed but the text never clips.
				let label_phys = self.label_px( canvas ) * canvas.dpi_scale();
				canvas.resolve_geom( l ).max( label_phys + 4.0 )
			}
			None if self.subtitle.is_some() => canvas.geom_px( theme::HEIGHT_SUB ),
			None                            => canvas.geom_px( theme::HEIGHT ),
		};
		( max_width, h )
	}

	/// Focus stroke is centered on `rect`, so half the stroke width plus ~1 px
	/// of antialiasing bleed sits outside.
	pub fn paint_bounds( &self, rect: Rect ) -> Rect
	{
		rect.expand( theme::FOCUS_W * 0.5 + 1.0 )
	}

	pub fn draw( &self, canvas: &mut Canvas, rect: Rect, focused: bool, hovered: bool, pressed: bool )
	{
		// Selected wins over hover and press: a chosen item stays
		// chosen even when the pointer is over it.
		let ( label_color, subtitle_color, trailing_color ) = if self.selected
		{
			canvas.fill_rect( rect, theme::selected_bg(), theme::RADIUS );
			// Selected row is filled with `text_primary` colour;
			// label / subtitle / trailing read as the inverse via
			// `bg` so they stay legible.
			let inverse = crate::theme::palette().bg;
			( inverse, inverse, inverse )
		}
		else
		{
			if pressed
			{
				canvas.fill_rect( rect, theme::press_bg(), theme::RADIUS );
			}
			else if hovered
			{
				canvas.fill_rect( rect, theme::hover_bg(), theme::RADIUS );
			}
			( theme::label_color(), theme::subtitle_color(), theme::trailing_color() )
		};

		if focused
		{
			canvas.stroke_rect( rect, theme::focus_color(), theme::FOCUS_W, theme::RADIUS );
		}

		let label_size = self.label_px( canvas );
		let pad_h      = self.pad_h
			.map( |l| canvas.resolve_geom( l ) )
			.unwrap_or_else( || canvas.geom_px( theme::PAD_H ) );
		let has_sub  = self.subtitle.is_some();
		let label_y  = if has_sub
		{
			rect.y + rect.height * 0.35 + label_size * 0.3
		} else {
			rect.y + ( rect.height + label_size ) / 2.0 - 2.0
		};

		// Leading-icon column shifts the text right by
		// `ICON_SIZE + ICON_GAP`. Symbolic icons (single channel
		// pre-tinted) draw at full opacity; the colour comes from
		// the bytes the caller passed in, which is why the helper
		// is in `theme::icon_rgba` rather than baked here.
		let text_x = if let Some( ( rgba, w, h ) ) = &self.icon
		{
			let icon_size = canvas.geom_px( theme::ICON_SIZE );
			let icon_gap  = canvas.geom_px( theme::ICON_GAP );
			let icon_y    = rect.y + ( rect.height - icon_size ) / 2.0;
			let icon_rect = Rect { x: rect.x + pad_h, y: icon_y, width: icon_size, height: icon_size };
			canvas.draw_image_data( rgba, *w, *h, icon_rect, 1.0 );
			rect.x + pad_h + icon_size + icon_gap
		}
		else
		{
			rect.x + pad_h
		};

		// The trailing slots are laid out before the label is painted: the
		// label has to be elided against the space they leave, or a long
		// title runs under the disclosure arrow.
		let mut trail_right = rect.x + rect.width - pad_h;
		let icon_gap        = canvas.geom_px( theme::ICON_GAP );

		let mut trail_icon_rect = None;
		if self.trailing_icon.is_some()
		{
			let icon_size = canvas.geom_px( theme::TRAILING_ICON_SIZE );
			let r = Rect
			{
				x:      trail_right - icon_size,
				y:      rect.y + ( rect.height - icon_size ) / 2.0,
				width:  icon_size,
				height: icon_size,
			};
			trail_right = r.x - icon_gap;
			trail_icon_rect = Some( r );
		}

		let mut trail_text = None;
		if let Some( ref trail ) = self.trailing
		{
			let trail_size = canvas.font_px( theme::TRAILING_SIZE );
			let tx = trail_right - canvas.measure_text( trail, trail_size );
			trail_right = tx - icon_gap;
			trail_text = Some( ( tx, trail_size ) );
		}

		let text_max = ( trail_right - text_x ).max( 0.0 );

		let label_text = elide( canvas, &self.label, label_size, text_max );
		canvas.draw_text( &label_text, text_x, label_y, label_size, label_color );

		if let Some( ref sub ) = self.subtitle
		{
			let sub_size = canvas.font_px( theme::SUBTITLE_SIZE );
			let sub_y    = rect.y + rect.height * 0.62 + sub_size * 0.3;
			let sub_text = elide( canvas, sub, sub_size, text_max );
			canvas.draw_text( &sub_text, text_x, sub_y, sub_size, subtitle_color );
		}

		if let ( Some( r ), Some( ( rgba, w, h ) ) ) = ( trail_icon_rect, &self.trailing_icon )
		{
			canvas.draw_image_data( rgba, *w, *h, r, 1.0 );
		}

		if let ( Some( ( tx, trail_size ) ), Some( trail ) ) = ( trail_text, &self.trailing )
		{
			let ty = rect.y + ( rect.height + trail_size ) / 2.0 - 2.0;
			canvas.draw_text( trail, tx, ty, trail_size, trailing_color );
		}
	}

	pub( crate ) fn map_msg<U>( self, f: &super::MapFn<Msg, U> ) -> ListItem<U>
	where
		U: Clone + 'static,
		Msg: 'static,
	{
		ListItem
		{
			label:         self.label,
			subtitle:      self.subtitle,
			trailing:      self.trailing,
			trailing_icon: self.trailing_icon,
			on_press:      self.on_press.map( |m| ( *f )( m ) ),
			id:            self.id,
			selected:      self.selected,
			icon:          self.icon,
			pad_h:         self.pad_h,
			height:        self.height,
			font_size:     self.font_size,
		}
	}
}

/// Create a [`ListItem`] with the given primary label.
///
/// Add detail and behaviour through the chained builders. For a
/// disclosure arrow use [`ListItem::trailing_icon`] with a theme icon
/// (e.g. `"general/right"`) rather than a text glyph:
///
/// ```rust,no_run
/// # use ltk::{ list_item, ListItem };
/// # #[ derive( Clone ) ] enum Msg { OpenDisplay }
/// # fn _ex() -> ListItem<Msg> {
/// list_item( "Display" )
///     .subtitle( "Resolution, brightness, night mode" )
///     .trailing( "Light" )
///     .on_press( Msg::OpenDisplay )
/// # }
/// ```
pub fn list_item<Msg: Clone>( label: impl Into<String> ) -> ListItem<Msg>
{
	ListItem::new( label )
}

impl<Msg: Clone + 'static> From<ListItem<Msg>> for Element<Msg>
{
	fn from( l: ListItem<Msg> ) -> Self
	{
		Element::ListItem( l )
	}
}
