<script setup lang="ts">
import { computed, nextTick, onMounted, ref, watch } from "vue";
import StatusBadge from "@/components/common/StatusBadge.vue";
import { useHwpodStore } from "@/stores/hwpod";
import { summarizeHwpodNodeOps, formatTimestamp, type HwpodDetail } from "@/stores/workbench-live";
import { useWorkbenchStore } from "@/stores/workbench";

const hwpod = useHwpodStore();
const workbench = useWorkbenchStore();
const selectedDetail = ref<HwpodDetail | null>(null);
const diagnosticsOpen = ref(false);
const follow = ref(true);
const scrollRef = ref<HTMLDivElement | null>(null);
const summary = computed(() => summarizeHwpodNodeOps({ live: workbench.live, specs: hwpod.specs, nodeOps: hwpod.nodeOps, error: hwpod.error }));

onMounted(() => void hwpod.refresh());

watch(() => summary.value.streamLines.join("\n"), () => {
  if (!follow.value) return;
  void nextTick(() => jumpToBottom());
});

function jumpToBottom(): void {
  const node = scrollRef.value;
  if (!node) return;
  node.scrollTop = node.scrollHeight;
}

function onStreamScroll(): void {
  const node = scrollRef.value;
  if (!node) return;
  if (node.scrollHeight - node.clientHeight - node.scrollTop > 24) follow.value = false;
}
</script>

<template>
  <aside class="hwpod-panel" id="hwpod-node-sidebar" aria-label="HWPOD node-ops 摘要看板">
    <div class="panel-header compact">
      <div>
        <p class="page-eyebrow">HWPOD</p>
        <h2>Node Ops</h2>
      </div>
      <div class="hwpod-panel-actions">
        <StatusBadge :status="summary.tone" :label="`node-ops ${summary.status}`" />
        <button class="hwpod-diagnostics-button" type="button" aria-label="HWPOD 诊断" aria-haspopup="dialog" @click="diagnosticsOpen = true">!</button>
      </div>
    </div>
    <section class="hwpod-event-panel" aria-label="node-ops 流">
      <header>
        <span>node-ops</span>
        <div>
          <button id="hwpod-event-follow" type="button" @click="follow = !follow">{{ follow ? '跟随' : '暂停' }}</button>
          <button id="hwpod-event-jump" type="button" @click="follow = true; jumpToBottom()">跳到底部</button>
        </div>
      </header>
      <div id="hwpod-event-scroll" ref="scrollRef" class="hwpod-event-scroll" @scroll="onStreamScroll">
        <pre id="hwpod-event-text">{{ summary.streamLines.join('\n') || '等待 HWPOD node-ops。' }}</pre>
      </div>
    </section>
    <div v-if="diagnosticsOpen" class="workbench-dialog-backdrop" role="presentation" @click.self="diagnosticsOpen = false">
      <section id="hwpod-diagnostics-dialog" class="workbench-dialog wide" role="dialog" aria-modal="true" aria-labelledby="hwpod-diagnostics-title">
        <header>
          <div class="dialog-title-stack">
            <h2 id="hwpod-diagnostics-title">HWPOD 诊断</h2>
            <p>{{ summary.hwpodName }} / {{ summary.nodeId }} / {{ formatTimestamp(summary.updatedAt) }}</p>
          </div>
          <button type="button" class="dialog-close" aria-label="关闭" @click="diagnosticsOpen = false">x</button>
        </header>
        <section class="hwpod-node-status" aria-label="HWPOD node-ops status">
          <div class="hwpod-node-summary" id="hwpod-node-summary">
            <button v-for="tile in summary.tiles" :key="tile.key" class="summary-tile" type="button" :data-hwpod-detail="tile.key" :data-hwpod-title="tile.detail.title" @click="selectedDetail = tile.detail">
              <span>{{ tile.label }}</span>
              <strong>{{ tile.value }}</strong>
            </button>
          </div>
          <dl class="hwpod-node-meta">
            <div><dt>hwpod</dt><dd>{{ summary.hwpodName }}</dd></div>
            <div><dt>node</dt><dd>{{ summary.nodeId }}</dd></div>
            <div><dt>workspace</dt><dd>{{ summary.workspacePath }}</dd></div>
            <div><dt>case</dt><dd>{{ summary.caseId }}</dd></div>
            <div><dt>route</dt><dd>{{ summary.route }}</dd></div>
            <div><dt>updated</dt><dd>{{ formatTimestamp(summary.updatedAt) }}</dd></div>
            <div><dt>ws</dt><dd>{{ summary.connectedCount }} connected / {{ summary.pendingCount }} pending</dd></div>
            <div><dt>supported ops</dt><dd>{{ summary.supportedOpsCount }}</dd></div>
          </dl>
        </section>
        <section v-if="summary.errors.length" class="hwpod-errors" aria-label="HWPOD blockers">
          <strong>阻塞聚合</strong>
          <ul>
            <li v-for="error in summary.errors" :key="error.key">
              <code>{{ error.code }}</code>
              <span>{{ error.message }}</span>
            </li>
          </ul>
        </section>
      </section>
    </div>
    <div v-if="selectedDetail" class="workbench-dialog-backdrop" role="presentation" @click.self="selectedDetail = null">
      <section id="hwpod-detail-dialog" class="workbench-dialog" role="dialog" aria-modal="true" aria-labelledby="hwpod-detail-title">
        <header>
          <strong id="hwpod-detail-title">{{ selectedDetail.title }}</strong>
          <button type="button" class="dialog-close" aria-label="关闭" @click="selectedDetail = null">x</button>
        </header>
        <pre id="hwpod-detail-body">{{ selectedDetail.body }}</pre>
      </section>
    </div>
  </aside>
</template>
