---
import { componentDataByCssVariable } from 'virtual:astro:assets/fonts/internal';
import { filterPreloads } from '../dist/assets/fonts/core/filter-preloads.js';
import { AstroError, AstroErrorData } from '../dist/core/errors/index.js';

interface Props {
	/** The `cssVariable` registered in your Astro configuration. */
	cssVariable: import('astro:assets').CssVariable;
	/** Whether it should output [preload links](https://web.dev/learn/performance/optimize-web-fonts#preload) or not. */
	preload?: import('astro:assets').FontPreloadFilter;
}

const { cssVariable, preload = false } = Astro.props as Props;
const data = componentDataByCssVariable.get(cssVariable);
if (!data) {
	throw new AstroError({
		...AstroErrorData.FontFamilyNotFound,
		message: AstroErrorData.FontFamilyNotFound.message(cssVariable),
	});
}

const filteredPreloadData = filterPreloads(data.preloads, preload);
---

<style set:html={data.css}></style>
{
	filteredPreloadData?.map(({ url, type }) => (
		<link rel="preload" href={url} as="font" type={`font/${type}`} crossorigin />
	))
}
