<script>
    import { pendingRequests } from './stores.js';
    import { onMount, onDestroy } from 'svelte';
    
    let showSpinner = false;
    let timer;
    
    // Subscribe to the store
    const unsubscribe = pendingRequests.subscribe(count => {
        if (count > 0) {
            // Only show the spinner if the request takes longer than 300ms
            if (!timer) {
                timer = setTimeout(() => {
                    showSpinner = true;
                }, 300);
            }
        } else {
            // Instantly hide the spinner when all requests finish
            clearTimeout(timer);
            timer = null;
            showSpinner = false;
        }
    });

    onDestroy(() => {
        unsubscribe();
        if (timer) clearTimeout(timer);
    });
</script>

{#if showSpinner}
    <div class="fixed inset-0 z-[9999] flex items-center justify-center bg-black/40 backdrop-blur-sm transition-opacity duration-300">
        <div class="flex flex-col items-center p-8 bg-surface-base rounded-2xl shadow-xl border border-divider">
            <!-- Loading circle animation -->
            <div class="w-12 h-12 border-4 border-primary border-t-transparent rounded-full animate-spin"></div>
            <p class="mt-4 text-text-primary font-medium tracking-wide animate-pulse">Communicating with Device...</p>
        </div>
    </div>
{/if}

<style>
    /* 
     * Note: 'bg-surface-base', 'border-divider', 'text-text-primary' 
     * are assumed to be part of the app's global tailwind theme. 
     * Adjust classes if necessary.
     */
</style>
