function template(type, icon, title, text) {
	return `
		<div class="toast toast-${type}" role="alert">
	    <div class="toast-content">
	      <h4 class="toast-title">${icon} ${title}</h4>
	      <p class="toast-text">${text}</p>
	    </div>
	    <button class="btn-icon toast-close" type="button" aria-label="Close">✕</button>
	  </div>
	`;
}

function init(toast, props) {
	if(props?.alone) {
		document.querySelectorAll(".toast").forEach(i => i.close());
	}

	toast.close = function() {
		this.classList.add("a-hide");
		setTimeout(() => {
			this.remove();
		}, 300);
	}

	toast.querySelector(".toast-close").addEventListener("click", e => {
		toast.close();
	});

	toast.show = function() {
		document.querySelector("body").append(toast);

		setTimeout(() => {
			toast.classList.add("a-show");
		}, 10);
	}

	if(typeof Screens != "undefined") {
		Screens.onSwitch((scr, alias) => {
			setTimeout(() => {
				toast?.close();
			}, 10000);
		});
	}

	toast.addEventListener("mouseover", e => toast.ishovered = true);
	toast.addEventListener("mouseout", e => toast.ishovered = false);

	if(props?.lifetime) {
		console.log(props);
		const lifetimeInterval = setInterval(() => {
			if(!toast.ishovered) {
				toast.close();
				clearInterval(lifetimeInterval);
			}
		}, props?.lifetime);
	}

	return toast;
}

function create(type, icon, title, text, props) {
	const div = document.createElement("div");
	div.innerHTML = template(type, icon, title, text);

	return init(div.childNodes[1], props);
}

function createSuccess(title, text, props) {
	if(typeof props == "undefined") {
		props = {};
	}

	if(typeof props.lifetime == "undefined") {
		props.lifetime = 4000;
	}

	if(typeof props.alone == "undefined") {
		props.alone = true;
	}

	return create(
		"success", 
		`<i class="ph ph-check-circle"></i>`, 
		title, 
		text,
		props
	);
}

function createInfo(title, text, props) {
	return create(
		"info", 
		`<i class="ph ph-info"></i>`, 
		title, 
		text,
		props
	);
}

function createWarning(title, text, props) {
	return create(
		"warning", 
		`<i class="ph ph-warning"></i>`, 
		title, 
		text,
		props
	);
}

function createError(title, text, props) {
	return create(
		"danger", 
		`<i class="ph ph-warning-octagon"></i>`, 
		title, 
		text,
		props
	);
}

export default {
  create,
  createInfo,
  createSuccess,
  createWarning,
  createError,
  "createDanger": createError
};