'use client'

/**
 * OpenClawPanel - figma-v2 設計對齊版
 * ======================================
 * @updated 2026-04-03 Claude Code — 完整對齊 figma-v2
 *   - 移除 "AWOOOI v1.0.0 | 正式環境" header
 *   - W●●●Claw 混合字體 (DM Mono + VT323 #d97757)
 *   - WOODCLAW PIPELINE badge (9px, rgba(74,144,217,0.1), #4A90D9)
 *   - 3個脈衝點動畫
 *   - 保留 NemoClaw SVG (68px)
 */

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

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

export type OpenClawStatus =
  | 'patrolling'   // [AGENT] patrolling...
  | 'intercepting' // [SYS] 攔截異常...
  | 'analyzing'    // [SYS] Analyzing blast radius...
  | 'generating'   // [SYS] Generating proposed action...
  | 'complete'     // [SYS] Analysis complete

export interface OpenClawPanelProps {
  status?: OpenClawStatus
  alertType?: string
  onAnalysisComplete?: () => void
  className?: string
}

// =============================================================================
// NemoClaw 3D Ceramic SVG Component (68px, figma-v2 spec)
// =============================================================================

function NemoClaw({ isActive, isPulsing }: { isActive: boolean; isPulsing: boolean }) {
  return (
    <svg width="68" height="68" viewBox="0 0 140 140" fill="none" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <linearGradient id="oc2-ceramic" x1="0%" y1="0%" x2="100%" y2="100%">
          <stop offset="0%" stopColor="#FFFFFF" />
          <stop offset="40%" stopColor="#F8F8F8" />
          <stop offset="70%" stopColor="#E8E8E8" />
          <stop offset="100%" stopColor="#D8D8D8" />
        </linearGradient>
        <radialGradient id="oc2-led" cx="40%" cy="35%" r="60%">
          <stop offset="0%" stopColor="#7AB8F5" />
          <stop offset="100%" stopColor="#2B6CB0" />
        </radialGradient>
      </defs>
      <circle cx="70" cy="70" r="32" fill="url(#oc2-ceramic)" stroke="#E0E0E0" strokeWidth="1" />
      <circle cx="70" cy="70" r="16" fill={isActive ? '#4A90D9' : 'url(#oc2-led)'}>
        {isPulsing && <animate attributeName="r" values="14;17;14" dur="2s" repeatCount="indefinite" />}
      </circle>
      <circle cx="70" cy="70" r="8" fill="white" opacity="0.8" />
      <path d="M 70 38 L 70 18 L 58 6 M 70 18 L 82 6" stroke="url(#oc2-ceramic)" strokeWidth="6" strokeLinecap="round" fill="none" />
      <path d="M 70 38 L 70 18 L 58 6 M 70 18 L 82 6" stroke="#4A90D9" strokeWidth="3" strokeLinecap="round" fill="none" opacity="0.5" />
      <path d="M 38 70 L 18 70 L 6 58 M 18 70 L 6 82" stroke="url(#oc2-ceramic)" strokeWidth="6" strokeLinecap="round" fill="none" />
      <path d="M 38 70 L 18 70 L 6 58 M 18 70 L 6 82" stroke="#4A90D9" strokeWidth="3" strokeLinecap="round" fill="none" opacity="0.5" />
      <path d="M 102 70 L 122 70 L 134 58 M 122 70 L 134 82" stroke="url(#oc2-ceramic)" strokeWidth="6" strokeLinecap="round" fill="none" />
      <path d="M 102 70 L 122 70 L 134 58 M 122 70 L 134 82" stroke="#4A90D9" strokeWidth="3" strokeLinecap="round" fill="none" opacity="0.5" />
      <path d="M 48 92 L 28 112 L 16 116" stroke="url(#oc2-ceramic)" strokeWidth="6" strokeLinecap="round" fill="none" />
      <path d="M 92 92 L 112 112 L 124 116" stroke="url(#oc2-ceramic)" strokeWidth="6" strokeLinecap="round" fill="none" />
      <circle cx="70" cy="70" r="42" fill="none" stroke="#4A90D9" strokeWidth="1" strokeDasharray="6 6" opacity="0.3">
        <animateTransform attributeName="transform" type="rotate" from="0 70 70" to="360 70 70" dur="8s" repeatCount="indefinite" />
      </circle>
    </svg>
  )
}

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

export function OpenClawPanel({
  status = 'patrolling',
  alertType,
  onAnalysisComplete,
  className,
}: OpenClawPanelProps) {
  const tPanel = useTranslations('openclawPanel')

  const isActive = status !== 'patrolling'
  const isPulsing = status === 'intercepting' || status === 'analyzing'

  // Notify when complete
  useEffect(() => {
    if (status === 'complete') {
      const timeout = setTimeout(() => {
        onAnalysisComplete?.()
      }, 1000)
      return () => clearTimeout(timeout)
    }
  }, [status, onAnalysisComplete])

  return (
    <div
      className={className}
      style={{
        padding: 14,
        display: 'flex',
        gap: 14,
        alignItems: 'flex-start',
      }}
    >
      {/* NemoClaw SVG — 68px */}
      <div style={{ flexShrink: 0 }}>
        <NemoClaw isActive={isActive} isPulsing={isPulsing} />
      </div>

      {/* 右側文字欄 */}
      <div style={{ flex: 1, minWidth: 0 }}>
        {/* W●●●Claw 混合字體名稱 */}
        <div style={{ marginBottom: 3 }}>
          <span style={{
            fontFamily: 'var(--font-body), "DM Mono", monospace',
            fontSize: 15,
            fontWeight: 700,
            color: '#141413',
            letterSpacing: '-0.5px',
          }}>W</span>
          <span style={{
            fontFamily: 'var(--font-dot-matrix), "VT323", monospace',
            fontSize: 26,
            color: '#d97757',
            letterSpacing: 2,
            lineHeight: 1,
          }}>ooo</span>
          <span style={{
            fontFamily: 'var(--font-body), "DM Mono", monospace',
            fontSize: 15,
            fontWeight: 700,
            color: '#141413',
            letterSpacing: '-0.5px',
          }}>Claw</span>
        </div>

        {/* WOODCLAW PIPELINE badge */}
        <div style={{
          display: 'inline-block',
          fontSize: 9,
          padding: '2px 7px',
          background: 'rgba(74,144,217,0.1)',
          color: '#4A90D9',
          borderRadius: 2,
          textTransform: 'uppercase',
          letterSpacing: '1.5px',
          marginBottom: 8,
        }}>
          WoooClaw Pipeline
        </div>

        {/* 狀態文字 + 脈衝點 */}
        <div style={{ fontSize: 12, color: '#87867f', lineHeight: 1.5 }}>
          {tPanel(status)}
          {/* 脈衝點動畫 */}
          <style>{`
            @keyframes oc-dot-pulse {
              0%, 60%, 100% { opacity: 0.3; }
              30% { opacity: 1; }
            }
          `}</style>
          <span style={{ display: 'inline-flex', gap: 3, marginLeft: 4, verticalAlign: 'middle' }}>
            {[0, 0.2, 0.4].map((delay, i) => (
              <span key={i} style={{
                width: 4,
                height: 4,
                borderRadius: '50%',
                background: '#4A90D9',
                display: 'inline-block',
                animation: `oc-dot-pulse 1.4s ease-in-out ${delay}s infinite`,
              }} />
            ))}
          </span>
        </div>

        {/* alertType badge (optional) */}
        {alertType && (
          <div style={{ marginTop: 6 }}>
            <span style={{
              fontSize: 10,
              padding: '2px 8px',
              background: 'rgba(204,34,0,0.1)',
              color: '#cc2200',
              borderRadius: 4,
              fontWeight: 600,
            }}>
              {alertType}
            </span>
          </div>
        )}

        {/* Sprint 5R S6: 狀態數據 + AI Terminal */}
        <div style={{ marginTop: 8, paddingTop: 8, borderTop: '0.5px solid #e0ddd4' }}>
          <div style={{ display: 'flex', gap: 8, marginBottom: 4 }}>
            <div style={{ flex: 1, fontSize: 10, color: '#555550' }}>
              模型: <span style={{ fontWeight: 600, color: '#141413' }}>openclaw_nemo</span>
            </div>
            <div style={{ fontSize: 10, color: '#22C55E', fontWeight: 500 }}>● 運行中</div>
          </div>
          <OpenClawStats />
          <OpenClawTerminal />
        </div>
      </div>
    </div>
  )
}

/** AI 即時統計 */
function OpenClawStats() {
  const [stats, setStats] = useState<{ analyses: number; successRate: string; mttr: string }>({ analyses: 0, successRate: '--', mttr: '--' })
  const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? ''

  useEffect(() => {
    Promise.all([
      fetch(`${API_BASE}/api/v1/stats/disposition`).then(r => r.ok ? r.json() : null).catch(() => null),
      fetch(`${API_BASE}/api/v1/incidents`).then(r => r.ok ? r.json() : null).catch(() => null),
    ]).then(([disp, inc]) => {
      const total = disp?.summary?.total ?? 0
      const rate = disp?.summary?.auto_rate != null ? `${Math.round(disp.summary.auto_rate * 100)}%` : '--'
      const incidents = inc?.incidents ?? inc ?? []
      const resolved = incidents.filter((i: any) => i.updated_at && (i.status === 'resolved' || i.status === 'closed'))
      let mttr = '--'
      if (resolved.length > 0) {
        const avg = resolved.reduce((sum: number, i: any) => sum + (new Date(i.updated_at).getTime() - new Date(i.created_at).getTime()), 0) / resolved.length
        mttr = `${(avg / 60000).toFixed(1)}m`
      }
      setStats({ analyses: total, successRate: rate, mttr })
    })
  }, [API_BASE])

  return (
    <div style={{ display: 'flex', gap: 12, fontSize: 10, color: '#555550' }}>
      <span>今日分析: <b style={{ color: '#141413' }}>{stats.analyses}</b></span>
      <span>成功率: <b style={{ color: '#22C55E' }}>{stats.successRate}</b></span>
      <span>MTTR: <b style={{ color: '#141413' }}>{stats.mttr}</b></span>
    </div>
  )
}

/** AI 推理終端 */
function OpenClawTerminal() {
  const [logs, setLogs] = useState<string[]>([])
  const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? ''

  useEffect(() => {
    fetch(`${API_BASE}/api/v1/alert-operation-logs?limit=4`)
      .then(r => r.ok ? r.json() : { items: [] })
      .then(d => {
        const items = (d.items ?? []).reverse()
        setLogs(items.map((item: any) => {
          const time = (() => { try { return new Date(item.created_at).toLocaleTimeString('zh-TW', { timeZone: 'Asia/Taipei', hour: '2-digit', minute: '2-digit' }) } catch { return '--:--' } })()
          return `[${time}] ${item.action_detail || item.event_type.replace(/_/g, ' ')}`
        }))
      })
      .catch(() => {})
  }, [API_BASE])

  return (
    <div style={{
      background: '#141413', borderRadius: 6, padding: '8px 10px', marginTop: 8,
      fontFamily: "'JetBrains Mono', monospace", fontSize: 10, color: '#a0e8a0',
      lineHeight: 1.6, maxHeight: 80, overflowY: 'auto',
    }}>
      <style>{`@keyframes cursor-blink { 0%,100%{opacity:1} 50%{opacity:0} }`}</style>
      {logs.length === 0 ? (
        <span style={{ color: '#555' }}>[--:--] Scanning cluster state...</span>
      ) : (
        logs.map((line, i) => (
          <div key={i}>
            {i < logs.length - 1 ? (
              <><span style={{ color: '#555' }}>{line.slice(0, 7)}</span>{line.slice(7)}</>
            ) : (
              <span style={{ color: '#ffd700' }}>{line} <span style={{ animation: 'cursor-blink 1s step-end infinite' }}>▎</span></span>
            )}
          </div>
        ))
      )}
    </div>
  )
}

export default OpenClawPanel
