import React from 'react';
import marked from 'marked';

import * as styles from './Style.less';

const renderer = new marked.Renderer();

renderer.link = (href, title, text) => {
	if (href === null) {
		return text;
	}

	let out;

	if (href.includes('/glossary/')) {
		out = `<a onclick="PP_Sidebar_OpenSignal('${href.replace(/https:\/\/[^/]*\/glossary\//gi, '').replace('/', '')}')"`;
	} else {
		out = `<a href="${href}" target="_blank" foo="bar"`;
	}

	if (title) {
		out += ` title="${title}"`;
	}

	out += `>${text}</a>`;

	return out;
};

renderer.image = (href, title, text) => {
	if (href === null) {
		return text;
	}

	let out = `<img src="${href}" alt="${text}" onclick="PP_Sidebar_OpenImage('${href}')"`;

	if (title) {
		out += ` title="${title}"`;
	}

	out += marked.options.xhtml ? '/>' : '>';

	return out;
};

marked.display = (contents) => {
	return (
		<div
			className={styles.Marked}
			dangerouslySetInnerHTML={{ __html: marked(contents) }} // eslint-disable-line react/no-danger
		/>
	);
};

marked.setOptions({ renderer });

export default marked;
