<!--
    Component: FontVirtualList
    - Renders a virtualized list of fonts
    - Handles font registration with the manager
-->
<script lang="ts" generics="T extends UnifiedFont">
import { VirtualList } from '$shared/ui';
import type { ComponentProps } from 'svelte';
import { getFontUrl } from '../../lib';
import type { FontConfigRequest } from '../../model';
import {
    type UnifiedFont,
    appliedFontsManager,
} from '../../model';

interface Props extends Omit<ComponentProps<typeof VirtualList<T>>, 'onVisibleItemsChange'> {
    onVisibleItemsChange?: (items: T[]) => void;
    onNearBottom?: (lastVisibleIndex: number) => void;
    weight: number;
}

let { items, children, onVisibleItemsChange, onNearBottom, weight, ...rest }: Props = $props();

function handleInternalVisibleChange(visibleItems: T[]) {
    const configs: FontConfigRequest[] = [];

    visibleItems.forEach(item => {
        const url = getFontUrl(item, weight);

        if (url) {
            configs.push({
                id: item.id,
                name: item.name,
                weight,
                url,
                isVariable: item.features?.isVariable,
            });
        }
    });
    // Auto-register fonts with the manager
    appliedFontsManager.touch(configs);

    // Forward the call to any external listener
    // onVisibleItemsChange?.(visibleItems);
}

function handleNearBottom(lastVisibleIndex: number) {
    // Forward the call to any external listener
    onNearBottom?.(lastVisibleIndex);
}
</script>

<VirtualList
    {items}
    {...rest}
    onVisibleItemsChange={handleInternalVisibleChange}
    onNearBottom={handleNearBottom}
>
    {#snippet children(scope)}
        {@render children(scope)}
    {/snippet}
</VirtualList>
