'use client'

/**
 * AIModelStatus — AI 模型狀態 2×2 網格
 * Sprint 5R S9: 設計稿 L531-545
 * @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 ModelInfo {
  name: string
  tag: string
  healthy: boolean
}

export function AIModelStatus() {
  const t = useTranslations('dashboard')
  const [models, setModels] = useState<ModelInfo[]>([
    { name: 'OpenClaw Nemo', tag: 'local', healthy: false },
    { name: 'Ollama gemma3', tag: 'local', healthy: false },
    { name: 'Gemini Pro', tag: 'cloud', healthy: false },
    { name: 'NVIDIA NIM', tag: 'cloud', healthy: false },
  ])

  useEffect(() => {
    fetch(`${API_BASE}/api/v1/health`)
      .then(r => r.ok ? r.json() : null)
      .then(d => {
        if (!d?.components) return
        setModels(prev => prev.map(m => {
          if (m.name.includes('OpenClaw') && d.components.openclaw) return { ...m, healthy: d.components.openclaw.status === 'up' }
          if (m.name.includes('Ollama') && d.components.ollama) return { ...m, healthy: d.components.ollama.status === 'up' }
          // 2026-04-09 Claude Sonnet 4.6: 移除假數據 — /api/v1/health 無 gemini/nvidia component
          // cloud 模型狀態未知，保持 false，不顯示假綠燈
          if (m.name.includes('Gemini') && d.components.gemini) return { ...m, healthy: d.components.gemini.status === 'up' }
          if (m.name.includes('NVIDIA') && d.components.nvidia) return { ...m, healthy: d.components.nvidia.status === 'up' }
          return m
        }))
      })
      .catch(() => {})
  }, [])

  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' }}>{t('aiModelStatus')}</span>
      </div>
      <div style={{ padding: 14, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
        {models.map(m => (
          <div key={m.name} style={{
            border: '0.5px solid #e0ddd4', borderRadius: 6, padding: '6px 8px',
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <span style={{ width: 5, height: 5, borderRadius: '50%', background: m.healthy ? '#22C55E' : '#cc2200', flexShrink: 0 }} />
            <span style={{ fontSize: 12, fontWeight: 500, color: '#141413' }}>{m.name}</span>
            <span style={{ fontSize: 10, color: '#87867f', marginLeft: 'auto' }}>{m.tag}</span>
          </div>
        ))}
      </div>
    </div>
  )
}
