<!--
    Component: FontVirtualList
    - Renders a virtualized list of fonts
    - Handles font registration with the manager
-->
<script lang="ts">
import { debounce } from '$shared/lib/utils';
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,
    fontCatalogStore,
    fontLifecycleManager,
} 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;
    /**
     * Empty-state snippet rendered when the query settled with zero fonts
     */
    empty?: Snippet;
}

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

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

let visibleFonts = $state<UnifiedFont[]>([]);
let isCatchingUp = $state(false);

const showInitialSkeleton = $derived(!!skeleton && isLoading && fontCatalogStore.fonts.length === 0);
const showCatchupSkeleton = $derived(!!skeleton && isCatchingUp);
// Settled query with no matches — empty state replaces the (otherwise blank) list.
const showEmpty = $derived(!!empty && !isLoading && !isCatchingUp && fontCatalogStore.fonts.length === 0);

function handleInternalVisibleChange(items: UnifiedFont[]) {
    visibleFonts = items;
    // Forward the call to any external listener
    onVisibleItemsChange?.(items);
}

/**
 * Handle jump scroll — batch-load all missing pages then re-enable font loading.
 * Suppresses fontLifecycleManager.touch() during catch-up to avoid loading
 * font files for thousands of intermediate fonts.
 */
async function handleJump(targetIndex: number) {
    if (isCatchingUp || !fontCatalogStore.pagination.hasMore) {
        return;
    }
    isCatchingUp = true;
    try {
        await fontCatalogStore.fetchAllPagesTo(targetIndex);
    } finally {
        isCatchingUp = false;
    }
}

/**
 * Debounce wait before asking the font lifecycle manager to load fonts
 * for the current visible window. Coalesces rapid scroll into one batch.
 */
const TOUCH_DEBOUNCE_MS = 150;

const debouncedTouch = debounce((configs: FontLoadRequestConfig[]) => {
    fontLifecycleManager.touch(configs);
}, TOUCH_DEBOUNCE_MS);

// Re-touch whenever visible set or weight changes — fixes weight-change gap
$effect(() => {
    if (isCatchingUp) {
        return;
    }
    const configs: FontLoadRequestConfig[] = visibleFonts.flatMap(item => {
        const url = getFontUrl(item, weight);
        if (!url) {
            return [];
        }
        return [{ id: item.id, name: item.name, weight, url, isVariable: item.features?.isVariable }];
    });
    if (configs.length > 0) {
        debouncedTouch(configs);
    }
});

// Pin visible fonts so the eviction policy never removes on-screen entries.
// Cleanup captures the snapshot values, so a weight change unpins the old
// weight before pinning the new one.
$effect(() => {
    const w = weight;
    const fonts = visibleFonts;
    for (const f of fonts) {
        fontLifecycleManager.pin(f.id, w, f.features?.isVariable);
    }
    return () => {
        for (const f of fonts) {
            fontLifecycleManager.unpin(f.id, w, f.features?.isVariable);
        }
    };
});

/**
 * Load more fonts by moving to the next page
 */
function loadMore() {
    if (
        !fontCatalogStore.pagination.hasMore
        || fontCatalogStore.isFetching
    ) {
        return;
    }
    fontCatalogStore.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 } = fontCatalogStore.pagination;

    // VirtualList already checks if we're near the bottom of loaded items.
    // Guard isCatchingUp: fetchAllPagesTo bypasses TQ so isFetching stays false
    // during batch catch-up, which would otherwise let nextPage() race with it.
    if (hasMore && !fontCatalogStore.isFetching && !isCatchingUp) {
        loadMore();
    }
}
</script>

<div class="relative w-full h-full">
    {#if showInitialSkeleton && skeleton}
        <!-- Show skeleton only on initial load when no fonts are loaded yet -->
        <div class="overflow-hidden h-full" transition:fade={{ duration: 300 }}>
            {@render skeleton()}
        </div>
    {:else if showEmpty && empty}
        <div class="h-full" transition:fade={{ duration: 200 }}>
            {@render empty()}
        </div>
    {:else}
        <!-- VirtualList persists during pagination - no destruction/recreation -->
        <VirtualList
            items={fontCatalogStore.fonts}
            total={fontCatalogStore.pagination.total}
            isLoading={isLoading || isCatchingUp}
            onVisibleItemsChange={handleInternalVisibleChange}
            onNearBottom={handleNearBottom}
            onJump={handleJump}
            {...rest}
        >
            {#snippet children(scope)}
                {@render children(scope)}
            {/snippet}
        </VirtualList>
        {#if showCatchupSkeleton && skeleton}
            <div class="absolute inset-0 overflow-hidden" transition:fade={{ duration: 150 }}>
                {@render skeleton()}
            </div>
        {/if}
    {/if}
</div>
