<script setup lang="ts">
import { nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
import KbxButton from './KbxButton.vue'

const props = withDefaults(defineProps<{
  canImport?: boolean
  canExport?: boolean
  disabled?: boolean
  title?: string
}>(), { canImport: true, canExport: true, disabled:false, title:'' })

const emit = defineEmits<{
  export: []
  template: []
  import: []
  paste: []
  history: []
}>()

type ExcelAction = 'export' | 'template' | 'import' | 'paste' | 'history'
const open = ref(false)
const root = ref<HTMLElement | null>(null)
const trigger = ref<any>(null)
const menu = ref<HTMLElement | null>(null)

function focusTrigger() { (trigger.value?.$el as HTMLElement | undefined)?.focus?.() }
function items() { return [...(menu.value?.querySelectorAll<HTMLButtonElement>('[role="menuitem"]:not(:disabled)') ?? [])] }
async function show() {
  if (props.disabled) return
  open.value = !open.value
  if (open.value) { await nextTick(); items()[0]?.focus() }
}
function close(restoreFocus = false) { open.value = false; if (restoreFocus) nextTick(focusTrigger) }
function choose(action: ExcelAction) { close(); emit(action) }
function onDocumentPointerDown(event:PointerEvent) { if (open.value && root.value && !root.value.contains(event.target as Node)) close() }
function onKeydown(event:KeyboardEvent) {
  if (!open.value) return
  if (event.key === 'Escape') { event.preventDefault(); close(true); return }
  const list = items(); if (!list.length) return
  const current = document.activeElement as HTMLButtonElement | null
  const index = Math.max(list.indexOf(current as HTMLButtonElement), 0)
  if (event.key === 'ArrowDown') { event.preventDefault(); list[(index + 1) % list.length]?.focus() }
  else if (event.key === 'ArrowUp') { event.preventDefault(); list[(index - 1 + list.length) % list.length]?.focus() }
  else if (event.key === 'Home') { event.preventDefault(); list[0]?.focus() }
  else if (event.key === 'End') { event.preventDefault(); list.at(-1)?.focus() }
  else if (event.key === 'Tab') close()
}
onMounted(()=>{document.addEventListener('pointerdown',onDocumentPointerDown);document.addEventListener('keydown',onKeydown)})
onBeforeUnmount(()=>{document.removeEventListener('pointerdown',onDocumentPointerDown);document.removeEventListener('keydown',onKeydown)})
</script>

<template>
  <div ref="root" class="kbx-excel-menu">
    <KbxButton
      ref="trigger"
      label="엑셀"
      variant="secondary"
      :disabled="props.disabled"
      :title="props.title || undefined"
      aria-haspopup="menu"
      :aria-expanded="open"
      @click="show"
    />
    <div v-if="open" ref="menu" class="kbx-excel-menu__popup" role="menu" aria-label="엑셀 작업">
      <button v-if="props.canExport" type="button" role="menuitem" @click="choose('export')">현재 조회결과 다운로드</button>
      <button v-if="props.canImport" type="button" role="menuitem" @click="choose('template')">업로드 양식 다운로드</button>
      <button v-if="props.canImport" type="button" role="menuitem" @click="choose('import')">엑셀 업로드</button>
      <button v-if="props.canImport" type="button" role="menuitem" @click="choose('paste')">Excel에서 붙여넣기</button>
      <button v-if="props.canImport" type="button" role="menuitem" @click="choose('history')">최근 업로드 결과</button>
    </div>
  </div>
</template>

<style scoped>
.kbx-excel-menu{position:relative;display:inline-block}.kbx-excel-menu__popup{position:absolute;right:0;top:calc(100% + var(--kbx-space-1));min-width:var(--kbx-excel-menu-min-width);padding:var(--kbx-space-1);background:var(--kbx-color-surface);border:var(--kbx-border-width) solid var(--kbx-color-border);border-radius:var(--kbx-radius-sm);box-shadow:var(--kbx-shadow-overlay);z-index:var(--kbx-z-popover)}.kbx-excel-menu__popup button{display:block;width:100%;height:var(--kbx-control-sm);padding:0 var(--kbx-space-2);text-align:left;border:0;background:transparent;color:var(--kbx-color-text);border-radius:var(--kbx-radius-sm)}.kbx-excel-menu__popup button:hover,.kbx-excel-menu__popup button:focus-visible{background:var(--kbx-color-surface-hover)}
</style>
