<template>
  <a-dropdown v-model:open="open" :trigger="['click']" placement="bottomLeft">
    <div
      class="column-header-menu"
      tabindex="0"
      role="button"
      :aria-label="`字段 ${field.name} 菜单`"
      :aria-expanded="open"
      @click.stop
      @keydown.enter.prevent="open = true"
      @keydown.space.prevent="open = true"
    >
      <span class="column-header-menu__title">{{ field.name }}</span>
      <DownOutlined class="column-header-menu__arrow" />
    </div>
    <template #overlay>
      <a-menu @click="handleMenuClick">
        <a-menu-item key="edit-inline">
          <EditOutlined /> 编辑字段
        </a-menu-item>
        <a-menu-item key="open-batch-panel">
          <AppstoreOutlined /> 批量管理
        </a-menu-item>
        <a-menu-item key="hide">
          <EyeInvisibleOutlined /> 隐藏字段
        </a-menu-item>
        <a-menu-divider />
        <a-menu-item key="delete" danger>
          <DeleteOutlined /> 删除字段
        </a-menu-item>
      </a-menu>
    </template>
  </a-dropdown>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import {
  DownOutlined,
  EditOutlined,
  EyeInvisibleOutlined,
  DeleteOutlined,
  AppstoreOutlined,
} from '@ant-design/icons-vue'
import type { IBitableField } from '@/api/bitable'

const props = defineProps<{
  field: IBitableField
}>()

const emit = defineEmits<{
  (e: 'edit-inline', field: IBitableField): void
  (e: 'open-batch-panel', field: IBitableField): void
  (e: 'hide', fieldId: string): void
  (e: 'delete', field: IBitableField): void
}>()

// Controlled open state so Enter/Space on the focusable header opens the menu
// (U2 scenario 5: Tab to header -> Enter opens menu).
const open = ref(false)

function handleMenuClick({ key }: { key: string }): void {
  // Close the menu immediately after a choice (a-menu does not auto-close on
  // programmatic emit when controlled via v-model:open).
  open.value = false
  switch (key) {
    case 'edit-inline':
      emit('edit-inline', props.field)
      break
    case 'open-batch-panel':
      emit('open-batch-panel', props.field)
      break
    case 'hide':
      emit('hide', props.field.id)
      break
    case 'delete':
      emit('delete', props.field)
      break
  }
}
</script>

<style scoped>
.column-header-menu {
  display: flex;
  align-items: center;
  gap: var(--bitable-spacing-xs);
  cursor: pointer;
  width: 100%;
  height: 100%;
  user-select: none;
  outline: none;
  border-radius: var(--bitable-radius-sm);
}

.column-header-menu__title {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-weight: 600;
  font-size: var(--bitable-font-sm);
}

.column-header-menu__arrow {
  font-size: 10px;
  color: var(--bitable-color-text-secondary);
  flex-shrink: 0;
  opacity: 0.6;
  transition: opacity 0.15s;
}

.column-header-menu:hover .column-header-menu__arrow {
  opacity: 1;
}

.column-header-menu:focus-visible {
  box-shadow: 0 0 0 2px var(--bitable-color-primary) inset;
}
</style>
