<!--
    Component: FontView

    Loads fonts from fontshare with link tag
-->
<script lang="ts">
interface Props {
    name: string;
    slug: string;
    id: string;
    children?: import('svelte').Snippet;
}

let { name, slug, id, children }: Props = $props();
let isLoaded = $state(false);

// Construct the Fontshare API CSS URL
// We specify the weight (400) or 'all'
const cssUrl = $derived(`https://api.fontshare.com/v2/css?f[]=${id}&display=swap`);

$effect(() => {
    // Even though we use a link tag, we can still "watch"
    // for the font to be ready for a smooth fade-in
    document.fonts.load(`1em "${name}"`).then(() => {
        isLoaded = true;
    });
});
</script>

<svelte:head>
    <link rel="stylesheet" href={cssUrl} />
</svelte:head>

<div
    style:--f={name}
    style:font-family={name ? `'${name}', sans-serif` : 'inherit'}
    class="transition-opacity duration-500 {isLoaded ? 'font-[var(--f)] opacity-100' : 'font-sans opacity-0'}"
>
    {@render children?.()}
</div>
