<script setup lang="ts">
import { computed, ref } from "vue";

import MetricCard from "../components/MetricCard.vue";
import StatusBadge from "../components/StatusBadge.vue";
import SurfaceCard from "../components/SurfaceCard.vue";
import { useDesktopRuntime } from "../composables/useDesktopRuntime";
import { formatClock, formatRelativeTime, titleCaseToken } from "../lib/formatters";
import { healthTone, taskTone } from "../lib/runtime-ui";

const { snapshot, loading, refresh } = useDesktopRuntime();
const spotlightActionPending = ref(false);
const spotlightActionError = ref<string | null>(null);

const tasks = computed(() => snapshot.value?.tasks ?? []);
const accounts = computed(() => snapshot.value?.accounts ?? []);
const activity = computed(() => snapshot.value?.activity ?? []);

const spotlightTask = computed(() => {
  return (
    tasks.value.find((item) => item.status === "waiting_user") ??
    tasks.value.find((item) => item.status === "in_progress") ??
    tasks.value[0] ??
    null
  );
});

const riskyAccounts = computed(() => accounts.value.filter((item) => item.health !== "live"));

const subsystemCards = computed(() => {
  const subsystems = snapshot.value?.subsystems ?? {};
  return [
    {
      title: "Transport",
      detail: JSON.stringify(subsystems.transport ?? {}, null, 2),
    },
    {
      title: "Lease Manager",
      detail: JSON.stringify(subsystems.leaseManager ?? {}, null, 2),
    },
    {
      title: "Vault",
      detail: JSON.stringify(subsystems.vault ?? {}, null, 2),
    },
  ];
});

async function openSpotlightReview() {
  if (!spotlightTask.value) {
    return;
  }
  spotlightActionPending.value = true;
  spotlightActionError.value = null;
  try {
    await window.desktopBridge.app.openTaskReview(spotlightTask.value.id);
  } catch (error) {
    spotlightActionError.value = error instanceof Error ? error.message : "打开审核页失败";
  } finally {
    spotlightActionPending.value = false;
  }
}

async function resolveSpotlightTask(status: "succeeded" | "failed") {
  if (!spotlightTask.value) {
    return;
  }
  spotlightActionPending.value = true;
  spotlightActionError.value = null;
  try {
    await window.desktopBridge.app.resolveParkedTask(spotlightTask.value.id, status);
    await refresh();
  } catch (error) {
    spotlightActionError.value = error instanceof Error ? error.message : "回写审核结果失败";
  } finally {
    spotlightActionPending.value = false;
  }
}
</script>

<template>
  <section class="page">
    <header class="hero">
      <div class="hero-copy">
        <p class="eyebrow">RUNTIME COCKPIT</p>
        <h2>运行控制台</h2>
        <p class="hero-summary">
          桌面客户端本地调度与运行时指标大盘。全局观测实时在线客户端、关联账号状态、MQ 任务分发健康度及错误拦截告警。
        </p>
      </div>

      <SurfaceCard
        class="spotlight"
        eyebrow="Spotlight Task"
        title="当前最需要人工关注的任务"
        description="优先把会阻断队列流转的 waiting_user 或 in_progress 任务顶到最前。"
      >
        <template #action>
          <button class="refresh-button" @click="refresh">刷新快照</button>
        </template>

        <div v-if="spotlightTask" class="spotlight-body">
          <div class="spotlight-headline">
            <div>
              <strong>{{ spotlightTask.title }}</strong>
              <p>{{ spotlightTask.summary }}</p>
            </div>
            <StatusBadge :tone="taskTone(spotlightTask.status)" :label="spotlightTask.status" />
          </div>

          <dl class="spotlight-grid">
            <div>
              <dt>Account</dt>
              <dd>{{ spotlightTask.accountName }}</dd>
            </div>
            <div>
              <dt>Routing</dt>
              <dd>{{ spotlightTask.routing }}</dd>
            </div>
            <div>
              <dt>Lease</dt>
              <dd>
                {{
                  spotlightTask.leaseExpiresAt
                    ? `expires ${formatRelativeTime(spotlightTask.leaseExpiresAt)}`
                    : "released"
                }}
              </dd>
            </div>
            <div>
              <dt>Updated</dt>
              <dd>{{ formatClock(spotlightTask.updatedAt) }}</dd>
            </div>
          </dl>

          <div v-if="spotlightTask.status === 'waiting_user'" class="spotlight-actions">
            <button
              type="button"
              class="spotlight-button secondary"
              :disabled="spotlightActionPending"
              @click="openSpotlightReview"
            >
              打开审核页
            </button>
            <button
              type="button"
              class="spotlight-button success"
              :disabled="spotlightActionPending"
              @click="resolveSpotlightTask('succeeded')"
            >
              标记已发布
            </button>
            <button
              type="button"
              class="spotlight-button danger"
              :disabled="spotlightActionPending"
              @click="resolveSpotlightTask('failed')"
            >
              标记失败
            </button>
          </div>
          <p v-if="spotlightActionError" class="spotlight-error">{{ spotlightActionError }}</p>
        </div>
      </SurfaceCard>
    </header>

    <div class="metric-grid">
      <MetricCard
        eyebrow="Clients"
        :value="snapshot?.summary.onlineClients ?? 0"
        label="当前在线 desktop clients"
        tone="brand"
      />
      <MetricCard
        eyebrow="Accounts"
        :value="snapshot?.summary.accountsBound ?? 0"
        label="已经绑定到 workspace 的账号"
        tone="info"
      />
      <MetricCard
        eyebrow="Queue"
        :value="snapshot?.summary.queuedTasks ?? 0"
        label="仍在等待租约领取的任务"
        tone="warn"
      />
      <MetricCard
        eyebrow="Issues"
        :value="snapshot?.summary.issuesOpen ?? 0"
        label="待人工介入或 reconcile 的事项"
        tone="danger"
      />
    </div>

    <div class="panel-grid">
      <SurfaceCard
        eyebrow="Risk Watch"
        title="账号健康看板"
        description="把需要修复登录态、验证码或风险确认的账号单独拉出来。"
      >
        <div v-if="riskyAccounts.length > 0" class="list-stack">
          <article v-for="account in riskyAccounts" :key="account.id" class="list-row">
            <div>
              <strong>{{ account.displayName }}</strong>
              <p>{{ titleCaseToken(account.platform) }} · {{ account.platformUid }}</p>
            </div>
            <div class="list-side">
              <StatusBadge :tone="healthTone(account.health)" :label="account.health" />
              <small>{{ formatRelativeTime(account.lastSyncAt) }}</small>
            </div>
          </article>
        </div>
        <p v-else class="empty-text" style="margin-top: 16px;">当前没有异常账号。</p>
      </SurfaceCard>

      <SurfaceCard
        eyebrow="Event Feed"
        title="最近事件"
        description="这里会先承接 MQ 广播和主进程的关键状态变化，后面再接真实 SSE。"
      >
        <div v-if="activity.length > 0" class="timeline">
          <article v-for="entry in activity" :key="entry.id" class="timeline-item">
            <div class="timeline-marker" :class="entry.severity"></div>
            <div class="timeline-copy">
              <div class="timeline-head">
                <strong>{{ entry.title }}</strong>
                <small>{{ formatRelativeTime(entry.at) }}</small>
              </div>
              <p>{{ entry.detail }}</p>
            </div>
          </article>
        </div>
        <p v-else class="empty-text" style="margin-top: 16px;">当前没有最近事件记录。</p>
      </SurfaceCard>
    </div>

    <SurfaceCard
      eyebrow="Subsystem Snapshot"
      title="核心子系统快照"
      description="用于快速确认 transport、lease manager 和 vault 这三段是否处在可工作状态。"
    >
      <div class="subsystem-grid">
        <article v-for="card in subsystemCards" :key="card.title" class="subsystem-card">
          <strong>{{ card.title }}</strong>
          <pre>{{ card.detail }}</pre>
        </article>
      </div>
    </SurfaceCard>

    <p v-if="loading" class="loading-text">正在刷新运行快照…</p>
  </section>
</template>

<style scoped>
.page {
  display: grid;
  gap: 22px;
}

.hero {
  display: grid;
  grid-template-columns: minmax(0, 1.05fr) minmax(380px, 0.95fr);
  gap: 20px;
  align-items: stretch;
}

.hero-copy {
  padding: 24px;
  border-radius: 12px;
  border: 1px solid #e6edf5;
  background: #ffffff;
}

.eyebrow,
.hero-summary,
h2 {
  margin: 0;
}

.eyebrow {
  color: var(--geo-color-text-tertiary);
  font-size: 11px;
  letter-spacing: 0.14em;
  text-transform: uppercase;
}

h2 {
  margin-top: 8px;
  font-size: 24px;
  font-weight: 600;
  color: #1a1a1a;
  line-height: 1.4;
}

.hero-summary {
  margin-top: 12px;
  max-width: 720px;
  color: #8c8c8c;
  line-height: 1.6;
  font-size: 13px;
}


.spotlight :deep(.description) {
  max-width: 420px;
}

.refresh-button {
  padding: 10px 14px;
  border: 1px solid var(--geo-color-border);
  border-radius: 999px;
  background: rgba(255, 255, 255, 0.45);
  color: var(--geo-color-text-primary);
  cursor: pointer;
}

.spotlight-body {
  margin-top: 18px;
  display: grid;
  gap: 18px;
}

.spotlight-headline {
  display: flex;
  justify-content: space-between;
  gap: 16px;
}

.spotlight-headline strong {
  display: block;
  font-size: 15px;
  font-weight: 600;
  color: #1a1a1a;
}

.spotlight-headline p {
  margin: 4px 0 0;
  color: #8c8c8c;
  font-size: 12px;
  line-height: 1.5;
}

.spotlight-grid {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 14px;
  margin: 0;
}

.spotlight-grid dt {
  color: #8c8c8c;
  font-size: 12px;
}

.spotlight-grid dd {
  margin: 4px 0 0;
  color: #1a1a1a;
  font-weight: 500;
  font-size: 13px;
}

.spotlight-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.spotlight-button {
  border: 0;
  border-radius: 999px;
  padding: 10px 14px;
  font: inherit;
  cursor: pointer;
}

.spotlight-button:disabled {
  opacity: 0.55;
  cursor: not-allowed;
}

.spotlight-button.secondary {
  background: rgba(15, 23, 42, 0.08);
  color: var(--geo-color-text-primary);
}

.spotlight-button.success {
  background: rgba(5, 150, 105, 0.14);
  color: #047857;
}

.spotlight-button.danger {
  background: rgba(220, 38, 38, 0.12);
  color: #b91c1c;
}

.spotlight-error {
  margin: 0;
  color: #b91c1c;
}

.metric-grid,
.panel-grid,
.subsystem-grid {
  display: grid;
  gap: 16px;
}

.metric-grid {
  grid-template-columns: repeat(4, minmax(0, 1fr));
}

.panel-grid {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}

.list-stack,
.timeline {
  display: grid;
  gap: 12px;
  margin-top: 16px;
  max-height: 380px;
  overflow-y: auto;
  padding-right: 8px; /* For scrollbar breathing room */
}

.list-row {
  display: grid;
  grid-template-columns: minmax(0, 1fr) auto;
  gap: 16px;
  align-items: center;
  padding: 14px 16px;
  border-radius: 8px;
  border: 1px solid #e6edf5;
  background: #fafafb;
}

.list-row strong {
  display: block;
  font-size: 14px;
  font-weight: 600;
  color: #1a1a1a;
}

.list-row p {
  margin: 6px 0 0;
  color: var(--geo-color-text-secondary);
  line-height: 1.55;
}

.list-side {
  display: grid;
  justify-items: end;
  gap: 8px;
}

.list-side small,
.timeline-head small {
  color: var(--geo-color-text-tertiary);
}

.empty-text,
.loading-text {
  margin: 0;
  color: var(--geo-color-text-secondary);
}

.timeline-item {
  display: grid;
  grid-template-columns: auto 1fr;
  gap: 12px;
}

.timeline-marker {
  width: 10px;
  height: 10px;
  margin-top: 7px;
  border-radius: 999px;
  background: var(--geo-color-info);
  box-shadow: 0 0 0 6px rgba(37, 99, 235, 0.1);
}

.timeline-marker.success {
  background: var(--geo-color-success);
  box-shadow: 0 0 0 6px rgba(21, 128, 61, 0.1);
}

.timeline-marker.warn {
  background: var(--geo-color-warn);
  box-shadow: 0 0 0 6px rgba(180, 83, 9, 0.1);
}

.timeline-marker.danger {
  background: var(--geo-color-danger);
  box-shadow: 0 0 0 6px rgba(185, 28, 28, 0.1);
}

.timeline-head {
  display: flex;
  justify-content: space-between;
  gap: 12px;
}

.timeline-copy p {
  margin: 6px 0 0;
  color: var(--geo-color-text-secondary);
  line-height: 1.65;
}

.subsystem-grid {
  grid-template-columns: repeat(3, minmax(0, 1fr));
  margin-top: 18px;
}

.subsystem-card {
  padding: 16px;
  border-radius: 8px;
  border: 1px solid #e6edf5;
  background: #fafafb;
}

.subsystem-card strong {
  display: block;
}

.subsystem-card pre {
  margin: 12px 0 0;
  white-space: pre-wrap;
  word-break: break-word;
  color: var(--geo-color-text-secondary);
  line-height: 1.6;
  font-size: 12px;
}

html[data-theme="dark"] .list-row,
html[data-theme="dark"] .subsystem-card,
html[data-theme="dark"] .refresh-button {
  background: rgba(255, 255, 255, 0.03);
}

html[data-theme="dark"] .spotlight-button.secondary {
  background: rgba(255, 255, 255, 0.08);
}

html[data-theme="dark"] .spotlight-button.success {
  color: #6ee7b7;
}

html[data-theme="dark"] .spotlight-button.danger {
  color: #fca5a5;
}

@media (max-width: 1240px) {
  .hero,
  .panel-grid,
  .subsystem-grid,
  .metric-grid {
    grid-template-columns: 1fr;
  }

  .spotlight-grid {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

@media (max-width: 720px) {
  .hero-copy {
    padding: 22px;
  }

  .spotlight-grid {
    grid-template-columns: 1fr;
  }

  .spotlight-headline,
  .timeline-head {
    flex-direction: column;
  }
}
</style>
