<script setup>
import { computed } from "vue";
import { useRoute } from "vue-router";

const props = defineProps({
  breadcrumbData: Array, // مسیرهای اصلی
  tabs: {
    type: Array,
    default: () => [],
  },
  activeTabId: String, // تب فعال
});

const route = useRoute();
let breadcrumbTabs = props.tabs;
/**
 * پیدا کردن مسیر breadcrumb از breadcrumbData
 */
function findBreadcrumbPath(path, items, parentPath = "") {
  const result = [];
  for (const item of items) {
    const fullPath = item.to || parentPath;
    if (path.startsWith(fullPath)) {
      result.push({
        label: item.label,
        to: fullPath,
        icon: item.icon,
        children: item.children,
      });
      if (item.children) findBreadcrumbPath(item.children, fullPath);
    }
  }
  return result;
}

const breadcrumbItems = computed(() => {
  if (route.path === "/dashboard/base") return [];

  const crumbs = findBreadcrumbPath(route.path, props.breadcrumbData);

  if (breadcrumbTabs.length) {
    let tabToShow = breadcrumbTabs[0]; // default tab

    if (props.activeTabId) {
      const activeTab = breadcrumbTabs.find((t) => t.id === props.activeTabId);
      if (activeTab) tabToShow = activeTab;
    }

    crumbs.push({
      label: tabToShow.label,
      to: undefined,
      icon: tabToShow.icon,
    });
  }

  return crumbs;
});
</script>

<template>
  <UBreadcrumb
    v-if="breadcrumbItems.length"
    :items="breadcrumbItems"
    separator-icon="i-lucide-arrow-right"
  >
    <template #separator="{ ui }">
      <span class="mx-2 text-muted">/</span>
    </template>
    <template #item-label="{ item, active }">
      <span :class="active ? 'font-semibold text-primary' : ''">
        {{ item.label }}
      </span>
    </template>
  </UBreadcrumb>
</template>
