mod app;
mod auth;
mod config;
mod idle;
mod lockscreen_password;
mod message;
mod osk;
mod state;
mod view;

use state::{ Mode, State, UnlockMethod };

rust_i18n::i18n!( "locales", fallback = "en" );

fn detect_locale() -> String
{
	for var in [ "LC_ALL", "LC_MESSAGES", "LANG" ]
	{
		if let Ok( v ) = std::env::var( var )
		{
			let v = v.trim();
			if v.is_empty() || v == "C" || v == "POSIX" { continue; }
			let base = v.split( '.' ).next().unwrap_or( v );
			let lang = base.split( '_' ).next().unwrap_or( base );
			return lang.to_string();
		}
	}
	"en".to_string()
}

fn main()
{
	tracing_subscriber::fmt().with_target( false ).init();
	rust_i18n::set_locale( &detect_locale() );

	let user          = std::env::var( "USER" ).unwrap_or_default();
	let force_lock    = std::env::args().any( |a| a == "--lock" )
		|| std::env::var( "LOCKSCREEN_MODE" ).as_deref() == Ok( "lock" );
	let force_greeter = std::env::args().any( |a| a == "--greeter" )
		|| std::env::var( "LOCKSCREEN_MODE" ).as_deref() == Ok( "greeter" );
	let force_light   = std::env::args().any( |a| a == "--light" );
	let force_dark    = std::env::args().any( |a| a == "--dark" );

	// Default mode by who runs us: the greeter is launched as `_loginmanager`,
	// the session lock as the logged-in user. Explicit flags/env override.
	let mode = if force_lock
	{
		Mode::Lock
	} else if force_greeter {
		Mode::Greeter
	} else if user == "_loginmanager" {
		Mode::Greeter
	} else {
		Mode::Lock
	};

	use chrono::Timelike as _;
	let hour      = chrono::Local::now().hour();
	let env_theme = std::env::var( "LOCKSCREEN_THEME" ).ok();
	let tmode = if force_dark || env_theme.as_deref() == Some( "dark" )
	{
		ltk::ThemeMode::Dark
	} else if force_light || env_theme.as_deref() == Some( "light" ) {
		ltk::ThemeMode::Light
	} else if ( 6..18 ).contains( &hour ) {
		ltk::ThemeMode::Light
	} else {
		ltk::ThemeMode::Dark
	};

	if let Err( e ) = ltk::set_default_theme( tmode )
	{
		eprintln!( "lockscreen: default theme not loadable ({e}). Install ltk-theme-default or set LTK_THEMES_DIR." );
		std::process::exit( 1 );
	}

	let tint = ltk::theme_palette().text_secondary;

	let mut state = State::new( vec![ UnlockMethod::Password ] );
	state.mode      = mode;
	state.wallpaper    = Some( ltk::wallpaper_bundle_or_solid() );
	state.lockscreen_wp = Some( ltk::branding_bundle_or_solid( "lockscreen" ) );
	state.swipe_up     = ltk::theme_icon_tinted( "general/up-simple", 64, tint );

	state.logo = ltk::theme_logo_rgba( 512 );

	if mode == Mode::Greeter
	{
		state.username       = config::load_last_user().unwrap_or_default();
		state.shutdown_icon  = ltk::theme_icon_tinted( "session/power",   96, tint );
		state.reboot_icon    = ltk::theme_icon_tinted( "session/restart", 96, tint );
		state.allow_shutdown = true;
		state.allow_reboot   = true;
	} else {
		// Lock: the username is the current (forge-owner) user, shown read-only.
		state.username = user.clone();
	}

	ltk::run( app::LockscreenApp::new( state, user ) );
}
