<!--
    Component: FontApplicator
    Loads fonts from fontshare with link tag
    - Loads font only if it's not already applied
    - Uses IntersectionObserver to detect when font is visible
    - Adds smooth transition when font is loaded
-->
<script lang="ts">
import { cn } from '$shared/shadcn/utils/shadcn-utils';
import type { Snippet } from 'svelte';
import { appliedFontsManager } from '../../model';

interface Props {
    /**
     * Font name to set
     */
    name: string;
    /**
     * Font id to load
     */
    id: string;
    /**
     * Additional classes
     */
    className?: string;
    /**
     * Children
     */
    children?: Snippet;
}

let { name, 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>
