use markdown_it::{Node, NodeValue, Renderer};

#[derive(Debug)]
pub struct SmartLink {
	pub url: String,
	pub title: Option<String>,
}

impl NodeValue for SmartLink {
	fn render(&self, node: &Node, fmt: &mut dyn Renderer) {
		let mut attrs = node.attrs.clone();
		attrs.push(("href", self.url.clone()));

		if let Some(title) = &self.title {
			attrs.push(("title", title.clone()));
		}

		let external = !(self.url.starts_with(".") || self.url.starts_with("/"));

		// Open external links in a new tab
		if external {
			attrs.push(("target", "_blank".into()));
			attrs.push(("rel", "noopener noreferrer".into()));
		}

		fmt.open("a", &attrs);
		fmt.contents(&node.children);
		fmt.close("a");
	}
}
