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

interface Props extends
    Omit<
        ComponentProps<typeof VirtualList<UnifiedFont>>,
        'items' | 'total' | 'isLoading' | 'onVisibleItemsChange' | 'onNearBottom'
    >
{
    /**
     * Visible items callback
     */
    onVisibleItemsChange?: (items: UnifiedFont[]) => void;
    /**
     * Font weight
     */
    weight: number;
    /**
     * Skeleton snippet
     */
    skeleton?: Snippet;
}

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

const isLoading = $derived(
    unifiedFontStore.isFetching || unifiedFontStore.isLoading,
);

function handleInternalVisibleChange(visibleItems: UnifiedFont[]) {
    const configs: FontLoadRequestConfig[] = [];

    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);
}

/**
 * Load more fonts by moving to the next page
 */
function loadMore() {
    if (
        !unifiedFontStore.pagination.hasMore
        || unifiedFontStore.isFetching
    ) {
        return;
    }
    unifiedFontStore.nextPage();
}

/**
 * Handle scroll near bottom - auto-load next page
 *
 * Triggered by VirtualList when the user scrolls within 5 items of the end
 * of the loaded items. Only fetches if there are more pages available.
 */
function handleNearBottom(_lastVisibleIndex: number) {
    const { hasMore } = unifiedFontStore.pagination;

    // VirtualList already checks if we're near the bottom of loaded items
    if (hasMore && !unifiedFontStore.isFetching) {
        loadMore();
    }
}
</script>

<div class="relative w-full h-full">
    {#if skeleton && isLoading && unifiedFontStore.fonts.length === 0}
        <!-- Show skeleton only on initial load when no fonts are loaded yet -->
        <div transition:fade={{ duration: 300 }}>
            {@render skeleton()}
        </div>
    {:else}
        <!-- VirtualList persists during pagination - no destruction/recreation -->
        <VirtualList
            items={unifiedFontStore.fonts}
            total={unifiedFontStore.pagination.total}
            isLoading={isLoading}
            onVisibleItemsChange={handleInternalVisibleChange}
            onNearBottom={handleNearBottom}
            {...rest}
        >
            {#snippet children(scope)}
                {@render children(scope)}
            {/snippet}
        </VirtualList>
    {/if}
</div>
