// wow https://stackoverflow.com/questions/3891641/regex-test-only-works-every-other-time
// watch out for places we need to set `lastIndex` ... :frown:

const EMBEDS = [
	embed_tidal,
	embed_spotify,
	embed_youtube,
	embed_vimeo,
	embed_audio,
	embed_gif,
	embed_mkv,
	embed_mov,
	embed_mp4,
	embed_image,
	embed_link,
];

const URL_MATCHING_REGEX =
	/(?:(?<protocol>[a-zA-Z]+):)?(?:\/\/)?(?:(?<auth>(?<username>\S.+)\:(?<password>.+))\@)?(?<host>(?:(?<hostname>[-a-zA-Z0-9\.]+)\.)?(?<domain>(?:[-a-zA-Z0-9]+?\.(?<tld>[-a-zA-Z0-9]{2,64}))|localhost)(?:\:(?<port>[0-9]{1,6}))?)\b(?<path>[-a-zA-Z0-9@:%_{}\[\]<>\(\)\+.~&\/="]*?(?<extension>\.[^\.?/#"\n<>]+)?)(?:\?(?<query>[a-zA-Z0-9!$%&<>()*+,-\.\/\:\;\=\?\@_~"]+))?(?:#(?<hash>[a-zA-Z0-9!$&'()*+,-\.\/\:\;\=\?\@_~"]*?))?(?:$|\s)/gim;

function htmlify(content) {
	let html_content = (content ?? "").replace(/\n/g, "<br/>");
	let match;

	URL_MATCHING_REGEX.lastIndex = 0;
	while ((match = URL_MATCHING_REGEX.exec(content)) !== null) {
		const url = match[0];

		const {
			groups: { protocol, host, hostname, domain, tld, path, extension, query, hash },
		} = match;

		const link_info = {
			url,
			protocol,
			host,
			hostname,
			domain,
			tld,
			path,
			extension,
			query,
			hash,
		};

		for (const embed of EMBEDS) {
			const result = embed(link_info);

			if (typeof result === "string") {
				html_content = html_content.replace(url, result);
				break;
			}
		}
	}

	return html_content;
}
