<script setup lang="ts">
import { computed } from 'vue'
import type { KbxExternalDataProvenance, KbxDataFreshness } from '@kbx/contracts'
import KbxFreshnessIndicator from './KbxFreshnessIndicator.vue'
const props=defineProps<{ provenance:KbxExternalDataProvenance; compact?:boolean }>()
const emit=defineEmits<{ refresh:[] }>()
const freshness=computed<KbxDataFreshness>(()=>({ observedAt:props.provenance.providerObservedAt ?? props.provenance.receivedAt, staleAfterSeconds:props.provenance.freshUntil?Math.max(0,Math.floor((new Date(props.provenance.freshUntil).getTime()-new Date(props.provenance.receivedAt).getTime())/1000)):undefined, source:props.provenance.sourceLabel }))
const stateLabel=computed(()=>({fresh:'최신',stale:'최신 데이터 확인 중',expired:'만료',unavailable:'사용 불가'}[props.provenance.state]))
</script>
<template>
  <section class="kbx-provenance" :class="{compact}" aria-label="데이터 출처와 신선도">
    <div class="summary">
      <strong>{{ provenance.sourceLabel }}</strong>
      <span>{{ stateLabel }}</span>
      <KbxFreshnessIndicator :freshness="freshness" @refresh="emit('refresh')" />
    </div>
    <dl v-if="!compact">
      <div><dt>데이터셋</dt><dd>{{ provenance.datasetId }}</dd></div>
      <div v-if="provenance.providerObservedAt"><dt>공급자 기준</dt><dd>{{ provenance.providerObservedAt }}</dd></div>
      <div><dt>수신</dt><dd>{{ provenance.receivedAt }}</dd></div>
      <div><dt>정규화</dt><dd>{{ provenance.ingestedAt }}</dd></div>
      <div><dt>정규화 버전</dt><dd>{{ provenance.normalizerVersion }}</dd></div>
      <div><dt>증거 Hash</dt><dd class="hash">{{ provenance.payloadSha256 }}</dd></div>
    </dl>
    <p v-if="provenance.warning" class="warning">{{ provenance.warning }}</p>
  </section>
</template>
<style scoped>
.kbx-provenance{display:grid;gap:var(--kbx-space-2);border:thin solid var(--kbx-color-border);padding:var(--kbx-space-2);background:var(--kbx-color-surface)}
.summary{display:flex;gap:var(--kbx-space-2);align-items:center;flex-wrap:wrap}.summary>span{color:var(--kbx-color-text-muted)}
dl{display:grid;gap:var(--kbx-space-1);margin:0}dl>div{display:grid;grid-template-columns:max-content minmax(0,1fr);gap:var(--kbx-space-2)}dt{color:var(--kbx-color-text-muted)}dd{margin:0}.hash{overflow-wrap:anywhere;font-family:monospace}.warning{margin:0;color:var(--kbx-color-warning)}
.compact{border:0;padding:0;background:transparent}.compact dl{display:none}
</style>
