<script setup lang="ts">
import { nextTick, ref, watch } from 'vue'
import type { KbxOperationRun } from '@kbx/contracts'

const props=withDefaults(defineProps<{ operations: KbxOperationRun[]; activeId?: string | null }>(), { activeId:null })
const emit = defineEmits<{ open: [KbxOperationRun] }>()
const root=ref<HTMLElement|null>(null)

function progress(operation: KbxOperationRun) {
  if (!operation.total) return null
  return Math.min(100, Math.round(((operation.processed ?? 0) / operation.total) * 100))
}
async function focusActive(){
  if(!props.activeId)return
  await nextTick()
  const target=[...(root.value?.querySelectorAll<HTMLElement>('[data-operation-id]')??[])].find(el=>el.dataset.operationId===props.activeId)
  target?.focus({preventScroll:true});target?.scrollIntoView({block:'nearest'})
}
watch(()=>props.activeId,focusActive,{immediate:true})
</script>

<template>
  <section ref="root" class="kbx-operation-center" aria-label="작업 센터">
    <button v-for="operation in operations" :key="operation.id" type="button" class="operation" :class="{active:operation.id===activeId}" :data-operation-id="operation.id" :aria-current="operation.id===activeId?'true':undefined" @click="emit('open', operation)">
      <div class="top"><strong>{{ operation.title }}</strong><span>{{ operation.status }}</span></div>
      <div v-if="progress(operation) != null" class="progress"><i :style="{ width: `${progress(operation)}%` }" /></div>
      <small v-if="operation.total">{{ operation.processed ?? 0 }} / {{ operation.total }}</small>
      <small v-else-if="operation.resultMessage">{{ operation.resultMessage }}</small>
    </button>
    <p v-if="operations.length === 0" class="empty">진행 중이거나 최근 실행한 작업이 없습니다.</p>
  </section>
</template>

<style scoped>
.kbx-operation-center { display:grid; gap:8px; }
.operation { display:grid; gap:6px; padding:10px 12px; text-align:left; border:1px solid var(--kbx-color-border); border-radius:var(--kbx-radius-sm); background:var(--kbx-color-surface); cursor:pointer; }
.operation:hover{background:var(--kbx-color-surface-hover)}.operation.active{border-color:var(--kbx-color-primary);box-shadow:inset var(--kbx-accent-border-width) 0 0 var(--kbx-color-primary);background:var(--kbx-color-info-surface)}
.top { display:flex; justify-content:space-between; gap:8px; } .top span,small,.empty { color:var(--kbx-color-text-muted); }
.progress { height:6px; background:var(--kbx-color-surface-subtle); border-radius:999px; overflow:hidden; }
.progress i { display:block; height:100%; background:var(--kbx-color-primary); }
.empty { margin:0; padding:12px; }
</style>
