<!--
    Component: BreadcrumbHeader
    Fixed header for breadcrumbs navigation for sections in the page
-->
<script lang="ts">
import type { ResponsiveManager } from '$shared/lib';
import {
    Button,
    Label,
    Logo,
} from '$shared/ui';
import { getContext } from 'svelte';
import { cubicOut } from 'svelte/easing';
import { slide } from 'svelte/transition';
import {
    type BreadcrumbItem,
    getScrollBreadcrumbsStore,
} from '../../model';

const scrollBreadcrumbsStore = getScrollBreadcrumbsStore();
const breadcrumbs = $derived(scrollBreadcrumbsStore.scrolledPastItems);
const responsive = getContext<ResponsiveManager>('responsive');

function handleClick(item: BreadcrumbItem) {
    scrollBreadcrumbsStore.scrollTo(item.index);
}

function createButtonText(item: BreadcrumbItem) {
    const index = String(item.index + 1).padStart(2, '0');
    if (responsive.isMobileOrTablet) {
        return index;
    }

    return `${index} // ${item.title}`;
}
</script>

{#if breadcrumbs.length > 0}
    <div
        transition:slide={{ duration: 200 }}
        class="
            fixed top-0 left-0 right-0
            h-14
            md:h-16 px-4 md:px-6 lg:px-8
            flex items-center justify-between
            z-40
            surface-floating bg-surface/90 dark:bg-dark-bg/90
            border-x-0 border-t-0
        "
    >
        <div class="max-w-8xl px-4 sm:px-6 h-full w-full flex items-center justify-between gap-2 sm:gap-4">
            <Logo />

            <nav class="flex items-center overflow-x-auto scrollbar-hide">
                {#each breadcrumbs as item, _ (item.index)}
                    {@const active = scrollBreadcrumbsStore.activeIndex === item.index}
                    {@const text = createButtonText(item)}
                    <div class="ml-1 md:ml-4" transition:slide={{ duration: 200, axis: 'x', easing: cubicOut }}>
                        <Button
                            class="uppercase"
                            variant="tertiary"
                            size="xs"
                            {active}
                            onclick={() => handleClick(item)}
                        >
                            <Label class="text-inherit">
                                {text}
                            </Label>
                        </Button>
                    </div>
                {/each}
            </nav>
        </div>
    </div>
{/if}

<style>
/* Hide scrollbar but keep functionality */
.scrollbar-hide {
    -ms-overflow-style: none;
    scrollbar-width: none;
}
.scrollbar-hide::-webkit-scrollbar {
    display: none;
}
</style>
