<script setup lang="ts">
import type { Navigation } from '~/server/api/project/[projectId]/navigation.get';

interface Props {
    link: Navigation;
    project?: number;
}

const props = defineProps<Props>();
const hasChildren = computed(() => {
    return props.link && props.link.children && props.link.children.length > 0 || false;
});

if(hasChildren.value)
{
    props.link.children?.sort((a, b) => {
        if(a.order && b.order)
            return a.order - b.order;
        if(a.path === props.link.path)
            return -1;
        if(b.path === props.link.path)
            return 1;
        return 0;
    });
}

const collapsed = ref(!useRoute().path.startsWith('/explorer' + props.link.path));

function hideLeftPanel(_: Event)
{
    document?.querySelector('.published-container')?.classList.remove('is-left-column-open');
}
</script>

<template>
    <div class="tree-item" v-if="project && !isNaN(project)">
        <template v-if="hasChildren">
            <div class="tree-item-self"
                :class="{ 'is-collapsed': collapsed, 'mod-collapsible is-clickable': hasChildren }"
                data-path="{{ props.link.title }}" @click="collapsed = hasChildren && !collapsed">
                <div v-if="hasChildren" class="tree-item-icon collapse-icon">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
                        stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
                        class="svg-icon right-triangle">
                        <path d="M3 8L12 17L21 8"></path>
                    </svg>
                </div>
                <div class="tree-item-inner">{{ link.title }}</div>
            </div>
            <div v-if="!collapsed" class="tree-item-children">
                <NavigationLink v-if="hasChildren" v-for="l of link.children" :link="l" :project="project" />
            </div>
        </template>
        <NuxtLink @click="hideLeftPanel" v-else class="tree-item-self" :to="{ path: `/explorer/${project}${link.path}`, force: true }"
            :active-class="'mod-active'" :data-type="link.type === 'Canvas' ? 'graph' : undefined">
            <div class="tree-item-inner">{{ link.title }}</div>
        </NuxtLink>
    </div>
</template>