<script setup lang="ts">
import { computed, ref } from "vue";
import StatusBadge from "@/components/common/StatusBadge.vue";
import { displayTimeLabel } from "@/config/runtime";
import type { LiveSurface } from "@/types";
import { formatTimestamp, summarizeBuilds } from "@/stores/workbench-live";

const props = defineProps<{ live: LiveSurface | null }>();
const open = ref(false);
const summary = computed(() => summarizeBuilds(props.live));
const timeLabel = computed(() => displayTimeLabel());
const unavailableTimeText = computed(() => `构建时间不可用（${timeLabel.value}）`);
</script>

<template>
  <section class="live-build-summary" data-live-build-summary>
    <button id="live-build-toggle" class="status-chip-button" type="button" aria-haspopup="dialog" @click="open = true">
      <span class="status-chip-label">最新镜像构建时间（{{ timeLabel }}）</span>
      <StatusBadge :status="summary.tone" :label="summary.latest.builtAt ? formatTimestamp(summary.latest.builtAt) : unavailableTimeText" />
      <span class="status-chip-meta">{{ summary.latest.label }} · tag {{ summary.latest.tag || 'unknown' }} · commit {{ summary.latest.commitShort || 'unknown' }}</span>
    </button>
    <div v-if="open" class="workbench-dialog-backdrop" role="presentation" @click.self="open = false">
      <section id="live-build-dialog" class="workbench-dialog wide" role="dialog" aria-modal="true" aria-labelledby="live-build-title">
        <header>
          <strong id="live-build-title">构建版本明细</strong>
          <button type="button" class="dialog-close" aria-label="关闭" @click="open = false">x</button>
        </header>
        <div class="live-build-dialog-summary">
          <p>{{ summary.latestText }}</p>
          <p v-if="summary.countsText">{{ summary.countsText }}</p>
        </div>
        <ul class="live-build-list" role="list">
          <li v-for="row in summary.rows" :key="row.key" class="live-build-row" :data-live-build-row="row.key">
            <div class="live-build-row-head">
              <strong>{{ row.label }}</strong>
              <StatusBadge :status="row.status" :label="row.builtAt ? formatTimestamp(row.builtAt) : unavailableTimeText" />
            </div>
            <div class="live-build-meta">
              <span>tag {{ row.tag || 'unknown' }}</span>
              <span>env {{ row.envImageTag || 'unknown' }}</span>
              <span>commit {{ row.actualCommitShort || row.commitShort || 'unknown' }}</span>
              <span>revision {{ row.revisionShort || 'unknown' }}</span>
              <span v-if="row.digestShort">digest {{ row.digestShort }}</span>
              <span v-if="row.source">来源 {{ row.source }}</span>
              <span v-if="row.rollout">rollout {{ row.rollout }}</span>
            </div>
            <p v-if="row.reason" class="live-build-reason">{{ row.reason }}</p>
          </li>
        </ul>
      </section>
    </div>
  </section>
</template>
