<script setup>
import { useRouter } from 'vue-router';
import { ref, watchEffect } from 'vue';
import { useQuasar } from 'quasar';
import { useI18n } from 'vue-i18n';
import { useCamelCase } from 'src/composables/useCamelCase';

const { currentRoute } = useRouter();
const { screen } = useQuasar();
const { t, te } = useI18n();

let matched = ref([]);
let breadcrumbs = ref([]);
let root = ref(null);

watchEffect(() => {
    matched.value = currentRoute.value.matched.filter(
        (matched) => Object.keys(matched.meta).length
    );
    breadcrumbs.value.length = 0;
    if (!matched.value[0]) return;
    if (matched.value[0].name != 'Dashboard') {
        root.value = useCamelCase(matched.value[0].path.substring(1).toLowerCase());

        for (let index in matched.value)
            breadcrumbs.value.push(getBreadcrumb(matched.value[index]));

        breadcrumbs.value[breadcrumbs.value.length - 1].path = undefined;
    }
});

function getBreadcrumb(param) {
    const breadcrumb = {
        icon: param.meta.icon,
        path: param.path,
        root: root.value,
        locale: t(`globals.pageTitles.${param.meta.title}`),
    };

    if (screen.gt.sm) {
        breadcrumb.name = param.name;
        breadcrumb.title = useCamelCase(param.meta.title);
    }

    const moduleLocale = `${breadcrumb.root}.pageTitles.${breadcrumb.title}`;
    if (te(moduleLocale)) breadcrumb.locale = t(moduleLocale);

    return breadcrumb;
}
</script>
<template>
    <QBreadcrumbs v-if="breadcrumbs.length && $q.screen.gt.sm" class="q-pa-xs">
        <QBreadcrumbsEl
            v-for="(breadcrumb, index) of breadcrumbs"
            :key="index"
            :icon="breadcrumb.icon"
            :label="breadcrumb.locale"
            :to="breadcrumb.path"
        />
    </QBreadcrumbs>
    <QBreadcrumbs v-else class="q-pa-xs">
        <QBreadcrumbsEl
            v-for="(breadcrumb, index) of breadcrumbs"
            :key="index"
            :icon="breadcrumb.icon"
            :to="breadcrumb.path"
        />
    </QBreadcrumbs>
</template>
<style lang="scss">
.q-breadcrumbs {
    &__el,
    > div {
        flex-wrap: nowrap;
    }
    &--last,
    &__separator {
        color: var(--vn-label-color);
    }
}
@media (max-width: $breakpoint-md) {
    .q-breadcrumbs {
        overflow: hidden;

        &__el:not(:first-child):not(:last-child) {
            display: none !important;
        }
    }
}
</style>
