'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: 'decision_accuracy' | 'km_growth_rate' | 'mcp_call_diversity'
  current: number | null
  target: number
  status: 'healthy' | 'warning' | 'critical'
  unit?: string
  sparkline?: number[]  // 7 points, most recent last
}

interface SloKpiCardProps {
  metric: SloMetric
  loading?: boolean
}

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

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

// =============================================================================
// 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 === 'healthy' ? 'healthy'
    : metric.status === 'warning' ? 'warning'
    : 'critical'

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

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

  const sparkData = (metric.sparkline ?? Array(7).fill(0)).map((v, i) => ({ i, v }))

  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.5px',
      }}>
        {formattedValue}
      </div>

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

        {/* Sparkline 80×24px */}
        <div style={{ width: 80, height: 24 }} 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>
    </GlassCard>
  )
}
