'use client'

/**
 * DispositionMini — 處置統計迷你版 (環形圖 + 四類列表)
 * Sprint 5R S4: 設計稿 L386-414
 * @created 2026-04-09 Claude Opus 4.6 Asia/Taipei
 */

import { useState, useEffect } from 'react'
import { useTranslations } from 'next-intl'

const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? ''

interface DispositionSummary {
  total: number
  auto_rate: number
  by_type: { auto_repair: number; human_approved: number; manual_resolved: number; cold_start_trust: number }
}

export function DispositionMini() {
  const t = useTranslations('dashboard')
  const [data, setData] = useState<DispositionSummary | null>(null)

  useEffect(() => {
    fetch(`${API_BASE}/api/v1/stats/disposition`)
      .then(r => r.ok ? r.json() : null)
      .then(d => { if (d?.summary) setData(d.summary) })
      .catch(() => {})
  }, [])

  if (!data || data.total === 0) return null

  const { auto_repair = 0, human_approved = 0, manual_resolved = 0, cold_start_trust = 0 } = data.by_type ?? {}
  const total = data.total || 1
  const pct = Math.round(data.auto_rate * 100)

  // SVG 環形圖計算 (circumference = 2 * PI * 22 ≈ 138.2)
  const C = 2 * Math.PI * 22
  const segments = [
    { value: auto_repair, color: '#22C55E' },
    { value: human_approved, color: '#F59E0B' },
    { value: manual_resolved, color: '#A855F7' },
    { value: cold_start_trust, color: '#4A90D9' },
  ]
  let offset = 0
  const arcs = segments.map(seg => {
    const len = (seg.value / total) * C
    const arc = { len, gap: C - len, offset: -offset, color: seg.color }
    offset += len
    return arc
  })

  const items = [
    { label: t('autoRepairLabel'), value: auto_repair, color: '#22C55E' },
    { label: t('humanApprovedLabel'), value: human_approved, color: '#F59E0B' },
    { label: t('manualResolvedLabel'), value: manual_resolved, color: '#A855F7' },
    { label: t('coldStartLabel'), value: cold_start_trust, color: '#4A90D9' },
  ]

  return (
    <div style={{
      background: '#fff', border: '0.5px solid #e0ddd4', borderRadius: 10,
      overflow: 'hidden', boxShadow: '0 1px 3px rgba(0,0,0,0.04)', flexShrink: 0,
    }}>
      <div style={{
        padding: '10px 14px', borderBottom: '0.5px solid #e0ddd4',
        display: 'flex', alignItems: 'center', gap: 8, background: '#faf9f3',
      }}>
        <div style={{ width: 6, height: 6, borderRadius: '50%', background: '#d97757' }} />
        <span style={{ fontSize: 14, fontWeight: 700, color: '#141413', letterSpacing: '0.5px' }}>{t('dispositionBreakdown')}</span>
        <span style={{ marginLeft: 'auto', fontSize: 11, color: '#4A90D9', cursor: 'pointer', fontWeight: 500 }}>{t('viewAllReport')} →</span>
      </div>
      <div style={{ padding: 14, display: 'flex', gap: 14, alignItems: 'center' }}>
        {/* 環形圖 */}
        <div style={{ position: 'relative', width: 56, height: 56, flexShrink: 0 }}>
          <svg width="56" height="56" viewBox="0 0 56 56" style={{ transform: 'rotate(-90deg)' }}>
            <circle cx="28" cy="28" r="22" fill="none" stroke="#ebe8df" strokeWidth="5" />
            {arcs.map((arc, i) => (
              <circle key={i} cx="28" cy="28" r="22" fill="none"
                stroke={arc.color} strokeWidth="5" strokeLinecap="round"
                strokeDasharray={`${arc.len} ${arc.gap}`}
                strokeDashoffset={arc.offset}
              />
            ))}
          </svg>
          <div style={{
            position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 13, fontWeight: 700, color: '#22C55E',
          }}>
            {pct}%
          </div>
        </div>
        {/* 列表 */}
        <div style={{ flex: 1, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '2px 12px' }}>
          {items.map(item => (
            <div key={item.label} style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 12, color: '#555550' }}>
              <span style={{ width: 5, height: 5, borderRadius: '50%', background: item.color, flexShrink: 0 }} />
              {item.label}
              <span style={{ marginLeft: 'auto', fontWeight: 700, fontVariantNumeric: 'tabular-nums', color: item.color }}>{item.value}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}
