<!--
    Component: FontVirtualList
    - Renders a virtualized list of fonts
    - Handles font registration with the manager
-->
<script lang="ts" generics="T extends UnifiedFont">
import type { FontConfigRequest } from '$entities/Font/model/store/appliedFontsStore/appliedFontsStore.svelte';
import { VirtualList } from '$shared/ui';
import type { ComponentProps } from 'svelte';
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[]) {
    // Auto-register fonts with the manager
    const configs = visibleItems.map<FontConfigRequest>(item => ({
        id: item.id,
        name: item.name,
        weight,
        url: item.styles.regular!,
    }));
    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>
