import { registerIcons } from '@10up/block-components';

const addClassToSVG = (svgString, classNames = '') => {
	const parser = new DOMParser();
	const doc = parser.parseFromString(svgString, 'image/svg+xml');
	const svg = doc.querySelector('svg');

	if (svg) {
		classNames.split(' ').forEach(cls => svg.classList.add(cls));
		return svg.outerHTML;
	}

	return svgString;
};

const loadIcons = (context, setName, setLabel) => {
	const icons = context.keys().map((key) => {
		const name = key.replace('./', '').replace('.svg', '');
		const label = name.replace(/-/g, ' ').replace(/\b\w/g, (char) => char.toUpperCase());
		const rawSvg = context(key).default;
		const svgWithClass = addClassToSVG(rawSvg, 'svg-inline--fa btn-icon');

		return {
			source: svgWithClass,
			name,
			label,
			iconSet: setName,
		};
	});

	registerIcons({
		name: `fontawesome/${setName}`,
		label: `Font Awesome ${setLabel}`,
		icons,
	});
};

export const registerFontAwesomeIcons = () => {
	if (window.fontAwesomeIconsLoaded) return; // Prevent double registration
	window.fontAwesomeIconsLoaded = true;

	const solidIconsContext = require.context(
		'!!raw-loader!@fortawesome/fontawesome-free/svgs/solid',
		false,
		/\.svg$/
	);
	const regularIconsContext = require.context(
		'!!raw-loader!@fortawesome/fontawesome-free/svgs/regular',
		false,
		/\.svg$/
	);
	const brandsIconsContext = require.context(
		'!!raw-loader!@fortawesome/fontawesome-free/svgs/brands',
		false,
		/\.svg$/
	);

	loadIcons(solidIconsContext, 'solid', 'Solid');
	loadIcons(regularIconsContext, 'regular', 'Regular');
	loadIcons(brandsIconsContext, 'brands', 'Brands');
};