<script lang="ts">
  // 시스템 상태 도트 — Phase B 신규.
  // dashboardSummary store를 구독해 한 색상 + tooltip을 표시한다.
  // 색상 규칙(우선순위 순):
  //   1) failed_count > 0           → bg-error
  //   2) 어떤 stage라도 pending > 10 → bg-warning
  //   3) 그 외 (failed_count === 0) → bg-success
  // 첫 fetch 전(null)에는 dim 회색 표시.

  import {
    dashboardSummary,
    type DashboardSummary,
    type PipelineStatus,
  } from '$lib/stores/system';

  type Tone = 'success' | 'error' | 'warning' | 'idle';

  function pickTone(failedCount: number, pipeline: PipelineStatus[]): Tone {
    if (failedCount > 0) return 'error';
    const hasPendingBacklog = pipeline.some(
      (p) => p.status === 'pending' && p.count > 10,
    );
    if (hasPendingBacklog) return 'warning';
    return 'success';
  }

  const TONE_CLASS: Record<Tone, string> = {
    success: 'bg-success',
    error: 'bg-error',
    warning: 'bg-warning',
    idle: 'bg-default',
  };

  const TONE_LABEL: Record<Tone, string> = {
    success: '정상',
    error: '실패 있음',
    warning: '대기열 적체',
    idle: '확인 중',
  };

  let tone: Tone = $derived(
    $dashboardSummary
      ? pickTone($dashboardSummary.failed_count, $dashboardSummary.pipeline_status)
      : 'idle',
  );

  function buildStageRows(pipeline: PipelineStatus[]) {
    // stage별로 status 카운트 합산 (extract/classify/embed/preview 등)
    const grouped = new Map<string, Record<string, number>>();
    for (const p of pipeline) {
      const cur = grouped.get(p.stage) ?? {};
      cur[p.status] = (cur[p.status] ?? 0) + p.count;
      grouped.set(p.stage, cur);
    }
    return [...grouped.entries()].map(([stage, counts]) => ({
      stage,
      pending: counts.pending ?? 0,
      processing: counts.processing ?? 0,
      failed: counts.failed ?? 0,
    }));
  }

  let stageRows = $derived(
    $dashboardSummary ? buildStageRows($dashboardSummary.pipeline_status) : [],
  );

  function buildTooltip(
    summary: DashboardSummary | null,
    rows: ReturnType<typeof buildStageRows>,
    currentTone: Tone,
  ): string {
    if (!summary) return '시스템 상태 확인 중';
    const head = `시스템: ${TONE_LABEL[currentTone]} (실패 ${summary.failed_count})`;
    if (rows.length === 0) return head;
    const lines = rows.map(
      (r) => `${r.stage}: 대기 ${r.pending} · 처리 ${r.processing} · 실패 ${r.failed}`,
    );
    return [head, ...lines].join('\n');
  }

  let tooltipText = $derived(buildTooltip($dashboardSummary, stageRows, tone));
</script>

<span
  class="inline-flex h-2 w-2 rounded-full {TONE_CLASS[tone]}"
  role="img"
  aria-label={TONE_LABEL[tone]}
  title={tooltipText}
></span>
