<script lang="ts">
    import type FileViewState from "../models/FileViewState.svelte";
    import type { Trace } from "../models/Primitive.svelte";
    import PrimitiveIcon from "./PrimitiveIcon.svelte";
    import { CaretRightOutline } from "flowbite-svelte-icons";

    class Path {
        public value: string;
        public jump?: string;
        public index: number;

        constructor(value: string, index: number, jump?: string) {
            this.value = value;
            this.jump = jump;
            this.index = index;
        }
    }

    let {
        fState,
        footerHeight,
    }: { fState: FileViewState | undefined; footerHeight: number } = $props();
    let elements: Path[] | undefined = $derived(
        fState && fState.container_prim ? toElements(fState.container_prim.trace) : undefined,
    );

    function toElements(path: Trace[]): Path[] {
        if (path.length == 0) {
            return [new Path("Trailer", 0)];
        }
        let display: Path[] = [];
        let lastJump: string | undefined;
        for (let i = 0; i < path.length; i++) {
            const pathElement = path[i];
            if (pathElement.last_jump !== lastJump) {
                lastJump = pathElement.last_jump;
                display.push(new Path(pathElement.key, i, lastJump));
            } else {
                display.push(new Path(pathElement.key, i, undefined));
            }
        }
        return display;
    }

    function selectPath(path: Path) {
        if (fState) {
            let newPath = fState.copyPath().slice(0, path.index + 1);
            fState.selectPath(newPath);
        }
    }
</script>

<div class="footer" style="height: {footerHeight}px">
    {#if elements}
        {#each elements as path}
            <button
                class="flex flex-row items-center ml-2"
                onclick={() => selectPath(path)}
            >
                {#if path.jump}
                    <PrimitiveIcon ptype={"Reference"}></PrimitiveIcon>
                {:else}
                    <CaretRightOutline class="text-forge-sec" />
                {/if}
                <p class="text-xs ml-1">{path.value}</p>
            </button>
        {/each}
    {/if}
</div>

<style lang="postcss">
    .footer {
        @apply bg-forge-prim border border-forge-bound flex flex-row items-center;
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
    }
</style>
