/** biome-ignore-all lint/a11y/useValidAnchor: TODO: fix this */
import { config } from "components";
import { renderToString } from "react-dom/server";

const getRichTextConfig = (): IRichTextConfig | null => {
	return config.schemas.config.richTextConfig || null;
};

const parseClassNames = (styles: { label: string; className: string }[]) =>
	styles.reduce(
		// biome-ignore lint/performance/noAccumulatingSpread: TODO: fix this
		(acc, current: { label: string; className: string }) => ({ ...acc, [current.className]: current.label }),
		{},
	);

interface IRichTextConfig {
	paragraphStyles?: { label: string; className: string }[];
	tableStyles?: { label: string; className: string }[];
	tableCellStyles?: { label: string; className: string }[];
	editorLangs?: { name: string; iso: string }[];
}

const getLanguageMenuHtml = (languages: { name: string; iso: string; featured?: boolean }[]) => {
	const borderStyle = {
		borderBottom: "1px solid #DBDDE9",
		paddingBottom: "4px",
		marginBottom: "4px",
	};

	const featuredLanguages = languages
		.filter((lang) => lang.featured === true)
		.map((lang, index, { length }) => (
			<li role="presentation" key={lang.iso} style={index + 1 === length ? borderStyle : {}}>
				<a
					className="fr-command"
					tabIndex={-1}
					role="option"
					data-cmd="langDropdown"
					data-param1={lang.iso}
					title={lang.name}
					aria-selected="false"
				>
					{lang.name}
				</a>
			</li>
		));

	const otherLanguages = languages
		.filter((lang) => lang.featured !== true)
		.map((lang) => (
			<li role="presentation" key={lang.iso}>
				<a
					className="fr-command"
					tabIndex={-1}
					role="option"
					data-cmd="langDropdown"
					data-param1={lang.iso}
					title={lang.name}
					aria-selected="false"
				>
					{lang.name}
				</a>
			</li>
		));

	return renderToString(
		<ul className="fr-dropdown-list" role="presentation">
			<li role="presentation" key="remove" style={borderStyle}>
				<a
					className="fr-command"
					tabIndex={-1}
					role="option"
					data-cmd="langDropdown"
					data-param1={""}
					title="Remove"
					aria-selected="false"
					style={{ fontStyle: "italic" }}
				>
					Remove
				</a>
			</li>
			{featuredLanguages}
			{otherLanguages}
		</ul>,
	);
};

export { getRichTextConfig, parseClassNames, getLanguageMenuHtml, type IRichTextConfig };
