<!--
    Component: FontApplicator

    Loads fonts from fontshare with link tag
-->
<script lang="ts">
import {
    appliedFontsManager,
} from '$entities/Font/model/store/appliedFontsStore/appliedFontsStore.svelte';
import { cn } from '$shared/shadcn/utils/shadcn-utils';
import type { Snippet } from 'svelte';

interface Props {
    name: string;
    slug: string;
    id: string;
    className?: string;
    children?: Snippet;
}

let { name, slug, id, className, children }: Props = $props();
let element: Element;

$effect(() => {
    const observer = new IntersectionObserver(entries => {
        if (entries[0].isIntersecting) {
            appliedFontsManager.touch([id]);
        }
    });
    observer.observe(element);
    return () => observer.disconnect();
});

const isLoading = $derived(appliedFontsManager.getFontStatus(id) === 'loading');
</script>

<div
    bind:this={element}
    style:font-family={name}
    class={cn(
        'transition-all duration-200 ease-out',
        isLoading ? 'opacity-0 translate-y-1' : 'opacity-100 translate-y-0',
        className,
    )}
>
    {@render children?.()}
</div>
