<script setup lang="ts">
import { computed } from 'vue';
import { FolderIcon } from 'tdesign-icons-vue-next';
import type { Account } from '../services/accountApi';

const props = defineProps<{
  selectedAccount: number | '';
  currentPath: string;
  accounts: Account[];
  isNewFile?: boolean;
}>();

const emit = defineEmits<{
  (e: 'pathClick', path: string): void;
  (e: 'rootClick'): void;
  (e: 'update:selectedAccount', value: number): void;
}>();

const pathBreadcrumbs = computed(() => {
  const { currentPath, isNewFile } = props;
  if (isNewFile) {
    // For new files, show "新建文件" at the end of the breadcrumb
    const paths = currentPath ? currentPath.split('/').filter(Boolean) : [];
    const breadcrumbs = paths.map((path: string, index: number) => ({
      text: path,
      path: paths.slice(0, index + 1).join('/')
    }));

    return breadcrumbs;
  }

  // Regular file browsing
  if (!currentPath || typeof currentPath !== 'string') return [];
  const paths = currentPath.split('/').filter(Boolean);
  if (paths.length === 0) return [];
  return paths.map((path: string, index: number) => ({
    text: path,
    path: paths.slice(0, index + 1).join('/')
  }));
});
</script>

<template>
  <div class="header-section bg-white p-4 rounded-lg shadow-sm">
    <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-3">
      <div class="flex flex-col md:flex-row md:items-center gap-3">
        <t-select :value="selectedAccount" class="w-full md:w-64" placeholder="选择仓库"
          @update:value="(val: number) => emit('update:selectedAccount', val)">
          <t-option v-for="acc in accounts" :key="acc.id" :value="acc.id" :label="`${acc.owner}/${acc.repo}`" />
        </t-select>

        <t-breadcrumb v-if="currentPath && pathBreadcrumbs.length > 0 || isNewFile" class="mt-3">
          <t-breadcrumb-item @click="emit('rootClick')" class="cursor-pointer hover:text-blue-500">
            <span class="flex items-center gap-1">
              <FolderIcon /> 根目录
            </span>
          </t-breadcrumb-item>
          <t-breadcrumb-item v-for="item in pathBreadcrumbs" :key="item.path" @click="emit('pathClick', item.path)"
            class="cursor-pointer hover:text-blue-500">
            {{ item.text }}
          </t-breadcrumb-item>
        </t-breadcrumb>
      </div>
      <slot></slot>
    </div>
  </div>
</template>
