<script lang="ts">
    /**
     * Indeterminate loading bar — shows when API requests are in flight.
     * 300ms delay prevents flickering on fast requests.
     */
    import { activeRequests } from "../lib/requestsStore"

    let showLoading = $state(false)
    let hideTimeout: ReturnType<typeof setTimeout>
    let showTimeout: ReturnType<typeof setTimeout>

    $effect(() => {
        if ($activeRequests > 0) {
            if (hideTimeout) clearTimeout(hideTimeout)
            showTimeout = setTimeout(() => {
                showLoading = true
            }, 300)
        } else {
            if (showTimeout) clearTimeout(showTimeout)
            hideTimeout = setTimeout(() => {
                showLoading = false
            }, 150)
        }

        return () => {
            if (hideTimeout) clearTimeout(hideTimeout)
            if (showTimeout) clearTimeout(showTimeout)
        }
    })
</script>

<div class="fixed top-0 left-0 right-0 h-1 z-50 bg-blue-600/10 loading-bar" class:visible={showLoading}>
    <div class="h-full bg-blue-600 loading-bar-progress shadow-lg"></div>
</div>

<style>
    .loading-bar {
        opacity: 0;
        transition: opacity 300ms ease-out;
        pointer-events: none;
    }

    .loading-bar.visible {
        opacity: 1;
    }

    .loading-bar-progress {
        width: 100%;
        animation: loadingBarSlide 2s ease-in-out infinite;
    }

    @keyframes loadingBarSlide {
        0% {
            transform: translateX(-100%);
        }
        50% {
            transform: translateX(100%);
        }
        100% {
            transform: translateX(100%);
        }
    }
</style>
