'use client'

/**
 * SloKpiCard — SLO 單指標卡片
 * ============================
 * Nothing.tech × Anthropic Warmth 設計語言
 *
 * 特點：
 *   - Syne 大值字體 28px fw-700
 *   - StatusOrb 右上角狀態指示
 *   - 7d sparkline（Recharts LineChart 80×24px，無座標軸）
 *   - 狀態色：healthy=#22C55E, warning=#F59E0B, critical=#FF3300
 *
 * @created 2026-05-02 Claude Sonnet 4.6 — governance PR 3-5
 */

import { LineChart, Line, ResponsiveContainer } from 'recharts'
import { StatusOrb, type StatusType } from '@/components/ui/status-orb'
import { GlassCard } from '@/components/ui/glass-card'
import { useTranslations } from 'next-intl'

// =============================================================================
// Types
// =============================================================================

export interface SloMetric {
  name:
    | 'autonomy_rate'
    | 'decision_accuracy'
    | 'confidence_calibration'
    | 'km_growth_rate'
    | 'mcp_call_diversity'
    | 'auto_execute_success_rate'
    | 'human_override_rate'
    | 'verifier_false_neg_rate'
  current: number | null
  target: number
  status: 'healthy' | 'warning' | 'critical' | 'idle' | 'syncing'
  state?: 'ok' | 'warning' | 'violated' | 'skipped_low_volume' | 'no_data' | 'error' | 'partial'
  unit?: '%' | 'count'
  sparkline?: number[]  // 7 points, most recent last
  sampleCount?: number | null
  window?: string
  reason?: string | null
}

interface SloKpiCardProps {
  metric: SloMetric
  loading?: boolean
}

// =============================================================================
// Status colour map
// =============================================================================

const statusColor: Record<SloMetric['status'], string> = {
  healthy:  '#22C55E',
  warning:  '#F59E0B',
  critical: '#FF3300',
  idle:     '#87867f',
  syncing:  '#3B82F6',
}

function formatCompactNumber(value: number): string {
  if (value >= 100) return value.toFixed(0)
  if (value >= 10) return value.toFixed(1)
  return value.toFixed(2)
}

function reasonKey(reason?: string | null): string {
  if (!reason) return 'none'
  if (reason === 'denominator_below_minimum_events') return 'denominator_below_minimum_events'
  if (reason === 'prometheus_nan_or_inf') return 'prometheus_nan_or_inf'
  if (reason === 'prometheus_empty_result_metric_not_emitted') return 'prometheus_empty_result_metric_not_emitted'
  return 'unknown'
}

// =============================================================================
// Skeleton
// =============================================================================

function KpiSkeleton() {
  return (
    <GlassCard variant="elevated" padding="md" className="min-w-0">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <div style={{ width: 80, height: 10, borderRadius: 4, background: '#e0ddd4', animation: 'pulse 1.5s infinite' }} />
        <div style={{ width: 60, height: 28, borderRadius: 4, background: '#e0ddd4', animation: 'pulse 1.5s infinite' }} />
        <div style={{ width: 100, height: 8, borderRadius: 4, background: '#e0ddd4', animation: 'pulse 1.5s infinite' }} />
      </div>
    </GlassCard>
  )
}

// =============================================================================
// Component
// =============================================================================

export function SloKpiCard({ metric, loading = false }: SloKpiCardProps) {
  const t = useTranslations('governance.slo.kpi')

  if (loading) return <KpiSkeleton />

  const color = statusColor[metric.status]
  const orbStatus: StatusType = metric.status

  const formattedValue = metric.current == null
    ? '--'
    : metric.unit === '%'
      ? `${(metric.current * 100).toFixed(1)}%`
      : metric.current.toFixed(0)

  const formattedTarget = metric.unit === '%'
    ? `${(metric.target * 100).toFixed(0)}%`
    : metric.target.toFixed(0)

  const sparkData = (metric.sparkline ?? Array(7).fill(0)).map((v, i) => ({ i, v }))
  const stateLabel = metric.state ? t(`state.${metric.state}`) : ''
  const reasonLabel = metric.reason ? t(`reason.${reasonKey(metric.reason)}`) : null
  const sampleLabel = metric.sampleCount == null
    ? null
    : t('sampleCount', { count: formatCompactNumber(metric.sampleCount) })

  return (
    <GlassCard variant="elevated" padding="md" className="min-w-0 flex-1">
      {/* Header row: metric name + status orb */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
        <span style={{
          fontFamily: 'Syne, sans-serif',
          fontSize: 11,
          fontWeight: 600,
          color: '#87867f',
          textTransform: 'uppercase',
          letterSpacing: '0.6px',
        }}>
          {t(metric.name)}
        </span>
        <StatusOrb status={orbStatus} size="sm" pulse={orbStatus !== 'healthy'} glow />
      </div>

      {/* Big value */}
      <div style={{
        fontFamily: 'Syne, sans-serif',
        fontSize: 28,
        fontWeight: 700,
        color,
        lineHeight: 1,
        marginBottom: 4,
        letterSpacing: 0,
      }}>
        {formattedValue}
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {/* Target + sparkline row */}
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 8 }}>
          <span style={{
            fontFamily: "'DM Mono', monospace",
            fontSize: 10,
            color: '#87867f',
          }}>
            {t('target')} {formattedTarget}
          </span>

          {/* Sparkline 80×24px */}
          <div style={{ width: 80, height: 24, flexShrink: 0 }} aria-label={t('sparkline')}>
            <ResponsiveContainer width="100%" height="100%">
              <LineChart data={sparkData} margin={{ top: 2, right: 0, bottom: 2, left: 0 }}>
                <Line
                  type="monotone"
                  dataKey="v"
                  stroke={color}
                  strokeWidth={1.5}
                  dot={false}
                  isAnimationActive={false}
                />
              </LineChart>
            </ResponsiveContainer>
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 3, minHeight: 28 }}>
          <span style={{ fontFamily: "'DM Mono', monospace", fontSize: 10, color }}>
            {stateLabel}
          </span>
          <span style={{ fontFamily: "'DM Mono', monospace", fontSize: 9, color: '#87867f', lineHeight: 1.35 }}>
            {reasonLabel ?? sampleLabel ?? (metric.window ? t('window', { window: metric.window }) : '')}
          </span>
        </div>
      </div>
    </GlassCard>
  )
}
