#[macro_export]
macro_rules! runtime {
	($lua:ident) => {{
		use mlua::ExternalError;
		$lua.app_data_ref::<$crate::Runtime>().ok_or_else(|| "Runtime not found".into_lua_err())
	}};
}

#[macro_export]
macro_rules! runtime_mut {
	($lua:ident) => {{
		use mlua::ExternalError;
		$lua.app_data_mut::<$crate::Runtime>().ok_or_else(|| "Runtime not found".into_lua_err())
	}};
}

#[macro_export]
macro_rules! runtime_scope {
	($lua:ident, $name:expr, $block:expr) => {{
		let mut f = || {
			$crate::runtime_mut!($lua)?.enter_inherited($name, true);
			let result = (|| $block)();
			$crate::runtime_mut!($lua)?.leave()?;
			result
		};
		f()
	}};
}

#[macro_export]
macro_rules! deprecate {
	($lua:ident, $tt:tt) => {{
		static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
		if !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) {
			let source = match $crate::runtime!($lua)?.name()? {
				"init" => "`init.lua` config file",
				s => &format!("`{s}.yazi` plugin"),
			};
			yazi_macro::emit!(Call(
				yazi_macro::relay!(app:deprecate).with("content", format!($tt, source))
			));
		}
	}};
}

#[macro_export]
macro_rules! impl_area_method {
	($methods:ident) => {
		$methods.add_function(
			"area",
			|lua, (ud, area): (mlua::AnyUserData, Option<mlua::AnyUserData>)| {
				use mlua::IntoLua;
				use $crate::elements::Spatial;

				if let Some(v) = area {
					ud.borrow_mut::<Self>()?.set_area((&v).try_into()?);
					ud.into_lua(lua)
				} else {
					ud.borrow::<Self>()?.area().into_lua(lua)
				}
			},
		);
	};
}

#[macro_export]
macro_rules! impl_style_method {
	($methods:ident, $($field:tt).+) => {
		$methods.add_function("style", |_, (ud, style): (mlua::AnyUserData, $crate::style::Style)| {
			ud.borrow_mut::<Self>()?.$($field).+ = style.0;
			Ok(ud)
		});
	};
}

#[macro_export]
macro_rules! impl_style_shorthands {
	($methods:ident, $($field:tt).+) => {
		$methods.add_function("fg", |lua, (ud, value): (mlua::AnyUserData, mlua::Value)| {
			use $crate::elements::Color;
			use mlua::FromLua;
			use ratatui_core::style::Modifier;

			let me = &mut ud.borrow_mut::<Self>()?.$($field).+;
			match value {
				mlua::Value::Boolean(true) if me.has_modifier(Modifier::REVERSED) => {
					me.bg.map(Color).into_lua(lua)
				}
				mlua::Value::Nil | mlua::Value::Boolean(_) => {
					me.fg.map(Color).into_lua(lua)
				}
				_ => {
					me.fg = Some(Color::from_lua(value, lua)?.0);
					ud.into_lua(lua)
				}
			}
		});
		$methods.add_function("bg", |lua, (ud, value): (mlua::AnyUserData, mlua::Value)| {
			use $crate::elements::Color;
			use mlua::FromLua;
			use ratatui_core::style::Modifier;

			let me = &mut ud.borrow_mut::<Self>()?.$($field).+;
			match value {
				mlua::Value::Boolean(true) if me.has_modifier(Modifier::REVERSED) => {
					me.fg.map(Color).into_lua(lua)
				}
				mlua::Value::Nil | mlua::Value::Boolean(_) => {
					me.bg.map(Color).into_lua(lua)
				}
				_ => {
					me.bg = Some(Color::from_lua(value, lua)?.0);
					ud.into_lua(lua)
				}
			}
		});
		$methods.add_function("bold", |_, (ud, remove): (mlua::AnyUserData, bool)| {
			let me = &mut ud.borrow_mut::<Self>()?.$($field).+;
			if remove {
				*me = me.remove_modifier(ratatui_core::style::Modifier::BOLD);
			} else {
				*me = me.add_modifier(ratatui_core::style::Modifier::BOLD);
			}
			Ok(ud)
		});
		$methods.add_function("dim", |_, (ud, remove): (mlua::AnyUserData, bool)| {
			let me = &mut ud.borrow_mut::<Self>()?.$($field).+;
			if remove {
				*me = me.remove_modifier(ratatui_core::style::Modifier::DIM);
			} else {
				*me = me.add_modifier(ratatui_core::style::Modifier::DIM);
			}
			Ok(ud)
		});
		$methods.add_function("italic", |_, (ud, remove): (mlua::AnyUserData, bool)| {
			let me = &mut ud.borrow_mut::<Self>()?.$($field).+;
			if remove {
				*me = me.remove_modifier(ratatui_core::style::Modifier::ITALIC);
			} else {
				*me = me.add_modifier(ratatui_core::style::Modifier::ITALIC);
			}
			Ok(ud)
		});
		$methods.add_function("underline", |_, (ud, remove): (mlua::AnyUserData, bool)| {
			let me = &mut ud.borrow_mut::<Self>()?.$($field).+;
			if remove {
				*me = me.remove_modifier(ratatui_core::style::Modifier::UNDERLINED);
			} else {
				*me = me.add_modifier(ratatui_core::style::Modifier::UNDERLINED);
			}
			Ok(ud)
		});
		$methods.add_function("blink", |_, (ud, remove): (mlua::AnyUserData, bool)| {
			let me = &mut ud.borrow_mut::<Self>()?.$($field).+;
			if remove {
				*me = me.remove_modifier(ratatui_core::style::Modifier::SLOW_BLINK);
			} else {
				*me = me.add_modifier(ratatui_core::style::Modifier::SLOW_BLINK);
			}
			Ok(ud)
		});
		$methods.add_function("blink_rapid", |_, (ud, remove): (mlua::AnyUserData, bool)| {
			let me = &mut ud.borrow_mut::<Self>()?.$($field).+;
			if remove {
				*me = me.remove_modifier(ratatui_core::style::Modifier::RAPID_BLINK);
			} else {
				*me = me.add_modifier(ratatui_core::style::Modifier::RAPID_BLINK);
			}
			Ok(ud)
		});
		$methods.add_function("reverse", |_, (ud, remove): (mlua::AnyUserData, bool)| {
			let me = &mut ud.borrow_mut::<Self>()?.$($field).+;
			if remove {
				*me = me.remove_modifier(ratatui_core::style::Modifier::REVERSED);
			} else {
				*me = me.add_modifier(ratatui_core::style::Modifier::REVERSED);
			}
			Ok(ud)
		});
		$methods.add_function("hidden", |_, (ud, remove): (mlua::AnyUserData, bool)| {
			let me = &mut ud.borrow_mut::<Self>()?.$($field).+;
			if remove {
				*me = me.remove_modifier(ratatui_core::style::Modifier::HIDDEN);
			} else {
				*me = me.add_modifier(ratatui_core::style::Modifier::HIDDEN);
			}
			Ok(ud)
		});
		$methods.add_function("crossed", |_, (ud, remove): (mlua::AnyUserData, bool)| {
			let me = &mut ud.borrow_mut::<Self>()?.$($field).+;
			if remove {
				*me = me.remove_modifier(ratatui_core::style::Modifier::CROSSED_OUT);
			} else {
				*me = me.add_modifier(ratatui_core::style::Modifier::CROSSED_OUT);
			}
			Ok(ud)
		});
		$methods.add_function("reset", |_, ud: mlua::AnyUserData| {
			ud.borrow_mut::<Self>()?.$($field).+ = ratatui_core::style::Style::reset();
			Ok(ud)
		});
	};
}

#[macro_export]
macro_rules! impl_file_fields {
	($fields:ident) => {
		use yazi_shim::mlua::UserDataFieldsExt;

		$fields.add_cached_field("cha", |_, me| Ok(me.cha));
		$fields.add_cached_field("url", |_, me| Ok(me.url_owned()));
		$fields.add_cached_field("link_to", |_, me| Ok(me.extra.link_to().cloned()));

		$fields.add_cached_field("name", |lua, me| {
			me.name().map(|s| lua.create_string(s.encoded_bytes())).transpose()
		});
		$fields.add_cached_field("path", |_, me| {
			use yazi_shared::path::PathBufDyn;
			Ok(PathBufDyn::from(me.content_path()))
		});
		$fields.add_cached_field("cache", |_, me| {
			use yazi_shared::path::PathBufDyn;
			Ok(me.cache().map(PathBufDyn::from))
		});
	};
}

#[macro_export]
macro_rules! impl_file_methods {
	($methods:ident) => {
		$methods.add_method("hash", |_, me, ()| {
			use yazi_fs::{FsHash64, file::FileSig};
			Ok(FileSig(me).hash_u64())
		});
	};
}
