<script setup lang="ts">
import { computed, ref } from 'vue'
import { useQuery } from '@tanstack/vue-query'
import { KbxListPage, KbxSearchPanel, KbxDataGrid } from '@kbx/ui'
import type { KbxGridColumn, KbxSearchField, KbxUxMetricRow } from '@kbx/contracts'
import { uxMetricsScreen } from './ux-metrics.definition'
import { uxMetricsApi } from './uxMetricsApi'
const today=new Date();const fromDate=new Date(today);fromDate.setDate(today.getDate()-6)
const iso=(d:Date)=>d.toISOString().slice(0,10)
const search=ref({from:iso(fromDate),to:iso(today),screenId:''})
const fields:KbxSearchField[]=[{key:'from',label:'시작일',type:'date',primary:true},{key:'to',label:'종료일',type:'date',primary:true},{key:'screenId',label:'화면코드',type:'text',primary:true,width:'md'}]
const query=useQuery({queryKey:['kbx','ux-metrics',search],queryFn:()=>uxMetricsApi.get({...search.value,screenId:search.value.screenId||undefined}),enabled:false})
const columns:KbxGridColumn<KbxUxMetricRow>[]=[
 {field:'label',header:'지표',width:240},{field:'value',header:'현재값',type:'decimal',width:140},{field:'unit',header:'단위',width:100},{field:'sampleCount',header:'표본',type:'integer',width:110},{field:'p50',header:'P50',type:'decimal',width:110},{field:'p95',header:'P95',type:'decimal',width:110},
]
async function command(id:string){if(id==='search')await query.refetch()}
</script>
<template>
  <KbxListPage :screen="uxMetricsScreen" :content-state="query.error.value?'error':query.isFetching.value&&!query.data.value?'loading':!query.data.value?'idle':query.data.value.metrics.length===0?'empty':'ready'" :refreshing="query.isFetching.value&&Boolean(query.data.value)" @command="command">
    <template #search><KbxSearchPanel v-model="search" :fields="fields" @search="query.refetch()" /></template>
    <template #quick-filter>
      <div class="notice"><strong>해석 기준</strong> — DOM 전체 클릭이나 검색어 원문을 수집하지 않습니다. 낮은 수치 자체보다 업무 위험·오류 감소와 함께 판단합니다.</div>
    </template>
    <template #content><KbxDataGrid :rows="query.data.value?.metrics ?? []" :columns="columns" row-key="metricKey" :loading="query.isFetching.value" /></template>
    <template #summary>{{ search.from }} ~ {{ search.to }} · Manual Intervention Rate를 자동화 개선의 핵심 추세로 봅니다.</template>
  </KbxListPage>
</template>
<style scoped>.notice{padding:8px 12px;border:1px solid var(--kbx-color-border);background:var(--kbx-color-surface-muted);font-size:13px}</style>
