<script lang="ts">
    import { page } from '$app/state';
    import type { BreadcrumbItem } from '$lib/types/breadcrumbs';

    interface Props {
        crumbs?: BreadcrumbItem[];
    }

    let { crumbs }: Props = $props();
    
    let segments = $derived.by(() => page.url.pathname.split('/').filter(Boolean));
    let locale = $derived(segments[0] || 'de');
    let showBreadcrumbs = $derived(segments.length > 2);

    // Fallback: if no crumbs provided, generate from URL segments
    let items = $derived.by(() => {
        if (crumbs && crumbs.length > 0) {
            return crumbs;
        }
        if (!showBreadcrumbs) return [];
        return segments.slice(1).map((seg, i) => {
            const pathSoFar = `/${segments.slice(0, i + 2).join('/')}`;
            return { label: seg, href: pathSoFar };
        });
    });
</script>

{#if showBreadcrumbs && items.length > 0}
  <nav class="text-sm text-gray-500 mb-6" aria-label="Breadcrumb">
    <ol class="flex flex-wrap gap-2">
      <li>
        <a href={`/${locale}`} class="hover:text-brand">Home</a>
      </li>
      {#each items as item (item.href)}
        <li class="flex items-center gap-2">
          <span>/</span>
          {#if item.href !== page.url.pathname}
            <a href={item.href} class="hover:text-brand">{item.label}</a>
          {:else}
            <span class="text-gray-700">{item.label}</span>
          {/if}
        </li>
      {/each}
    </ol>
  </nav>
{/if}
