<script setup lang="ts">
import { CheckCircle2, CircleAlert, LoaderCircle } from '@lucide/vue'
import type { OperationResultDto } from '../../api/contracts'
import EntityLink from './EntityLink.vue'

const props = defineProps<{
  result: OperationResultDto
  title?: string
}>()

const pendingStates = new Set(['queued', 'pending', 'awaiting_approval', 'provisioning'])
const failedStates = new Set([
  'failed',
  'rejected',
  'error',
  'invalid',
  'forbidden',
  'unavailable',
  'unsupported',
  'management_disabled',
  'not_found',
  'conflict',
  'stale',
  'idempotency_conflict',
  'in_doubt',
  'audit_unavailable',
  'audit_pending',
])
</script>

<template>
  <section class="operation-result nexus-panel" aria-live="polite">
    <div class="operation-result__status">
      <LoaderCircle v-if="pendingStates.has(props.result.status)" :size="18" class="spin" aria-hidden="true" />
      <CircleAlert v-else-if="failedStates.has(props.result.status)" :size="18" aria-hidden="true" />
      <CheckCircle2 v-else :size="18" aria-hidden="true" />
      <div>
        <strong>{{ title || 'Operation' }}</strong>
        <span>{{ props.result.status }}</span>
      </div>
    </div>
    <div v-if="props.result.primaryRef || props.result.affectedRefs.length" class="operation-result__refs">
      <EntityLink v-if="props.result.primaryRef" :entity="props.result.primaryRef" />
      <EntityLink
        v-for="entity in props.result.affectedRefs.filter(item => item.id !== props.result.primaryRef?.id)"
        :key="`${entity.type}:${entity.id}`"
        :entity="entity"
        compact
      />
    </div>
    <div class="operation-result__meta">
      <span>Revision {{ props.result.revision }}</span>
      <span v-if="props.result.traceId">Trace {{ props.result.traceId }}</span>
    </div>
  </section>
</template>

<style scoped>
.operation-result {
  display: grid;
  gap: 12px;
  padding: 14px;
}
.operation-result__status {
  display: flex;
  align-items: center;
  gap: 10px;
  color: var(--a-cyan);
}
.operation-result__status div {
  display: grid;
  gap: 2px;
}
.operation-result__status strong {
  color: var(--tx);
  font: 700 14px/1.2 'Space Grotesk', sans-serif;
}
.operation-result__status span,
.operation-result__meta {
  color: var(--tx-3);
  font: 10px/1.4 'JetBrains Mono', monospace;
}
.operation-result__refs {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.operation-result__meta {
  display: flex;
  justify-content: space-between;
  gap: 12px;
}
.spin {
  animation: spin .9s linear infinite;
}
@keyframes spin {
  to { transform: rotate(1turn); }
}
</style>
