'use client'

/**
 * AIThinkingPanel - OpenClaw AI 思考狀態面板
 * ==========================================
 * Phase 1: 視覺靈魂注入 (Frontend AI UX Integration)
 *
 * Features:
 * - 思維紫 (--status-thinking) 色彩
 * - 點陣字體打字機特效
 * - 脈衝呼吸燈動畫
 * - Slide Up 動畫過渡到 ApprovalCard
 */

import { useState, useEffect, useCallback } from 'react'
import { useTranslations } from 'next-intl'
import { cn } from '@/lib/utils'
import { Brain, Sparkles, Zap, Shield, AlertTriangle } from 'lucide-react'

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

export type ThinkingPhase =
  | 'intercepting'    // [SYS] 攔截異常...
  | 'analyzing'       // OpenClaw 正在分析爆炸半徑...
  | 'calculating'     // 計算風險矩陣...
  | 'generating'      // 生成修復建議...
  | 'complete'        // 分析完成

export interface AIThinkingPanelProps {
  isActive: boolean
  phase?: ThinkingPhase
  alertType?: string
  onComplete?: () => void
  className?: string
}

// =============================================================================
// Typewriter Messages (i18n keys or fallback)
// =============================================================================

const PHASE_MESSAGES: Record<ThinkingPhase, string> = {
  intercepting: '[SYS] 攔截異常訊號...',
  analyzing: 'OpenClaw 正在分析爆炸半徑...',
  calculating: '計算風險矩陣與簽核門檻...',
  generating: '生成修復腳本建議...',
  complete: '分析完成，待簽核卡片已建立',
}

const PHASE_ICONS: Record<ThinkingPhase, typeof Brain> = {
  intercepting: AlertTriangle,
  analyzing: Brain,
  calculating: Zap,
  generating: Shield,
  complete: Sparkles,
}

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

export function AIThinkingPanel({
  isActive,
  phase: _phase = 'intercepting',
  alertType,
  onComplete,
  className,
}: AIThinkingPanelProps) {
  const t = useTranslations('ai')
  const [displayText, setDisplayText] = useState('')
  // Phase 8.0 #16: 移除 cursorVisible state，改用 CSS animation
  const [currentPhase, setCurrentPhase] = useState<ThinkingPhase>('intercepting')

  // Typewriter effect
  const typeText = useCallback((text: string, callback?: () => void) => {
    let index = 0
    setDisplayText('')

    const interval = setInterval(() => {
      if (index < text.length) {
        setDisplayText(text.slice(0, index + 1))
        index++
      } else {
        clearInterval(interval)
        callback?.()
      }
    }, 50) // 50ms per character

    return () => clearInterval(interval)
  }, [])

  // Phase progression
  useEffect(() => {
    if (!isActive) {
      setCurrentPhase('intercepting')
      setDisplayText('')
      return
    }

    const phases: ThinkingPhase[] = ['intercepting', 'analyzing', 'calculating', 'generating', 'complete']
    let phaseIndex = 0

    const progressPhase = () => {
      if (phaseIndex < phases.length) {
        const currentPhase = phases[phaseIndex]
        setCurrentPhase(currentPhase)

        const cleanup = typeText(PHASE_MESSAGES[currentPhase], () => {
          phaseIndex++
          if (phaseIndex < phases.length) {
            setTimeout(progressPhase, 800) // Wait before next phase
          } else {
            onComplete?.()
          }
        })

        return cleanup
      }
    }

    const cleanup = progressPhase()
    return () => cleanup?.()
  }, [isActive, typeText, onComplete])

  // Phase 8.0 #16: 移除 setInterval cursor blink，改用 CSS animate-pulse

  if (!isActive) return null

  const PhaseIcon = PHASE_ICONS[currentPhase]

  return (
    <div
      className={cn(
        'relative overflow-hidden rounded-xl',
        'bg-gradient-to-br from-status-thinking/5 to-status-thinking/10',
        'border border-status-thinking/20',
        'p-6',
        'animate-fade-in',
        className
      )}
    >
      {/* Animated scan line */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        <div className="absolute h-[2px] w-full bg-gradient-to-r from-transparent via-status-thinking/50 to-transparent animate-scan" />
      </div>

      {/* Sparkle decorations */}
      <div className="absolute top-3 right-3">
        <Sparkles className="w-5 h-5 text-status-thinking/40 animate-pulse" />
      </div>
      <div className="absolute bottom-3 left-3">
        <Sparkles className="w-4 h-4 text-status-thinking/30 animate-pulse" style={{ animationDelay: '0.5s' }} />
      </div>

      {/* Main content */}
      <div className="flex items-start gap-4">
        {/* Brain icon with glow */}
        <div className="relative flex-shrink-0">
          <div className={cn(
            'w-14 h-14 rounded-xl flex items-center justify-center',
            'bg-gradient-to-br from-status-thinking/20 to-status-thinking/30',
            'border border-status-thinking/30',
            'shadow-glow-purple'
          )}>
            <PhaseIcon className={cn(
              'w-7 h-7 text-status-thinking',
              currentPhase !== 'complete' && 'animate-pulse'
            )} />
          </div>
          {/* Breathing indicator */}
          <div className="absolute -bottom-1 -right-1 w-4 h-4">
            <span className="absolute inline-flex h-full w-full rounded-full bg-status-thinking opacity-75 animate-ping" />
            <span className="relative inline-flex rounded-full h-4 w-4 bg-status-thinking" />
          </div>
        </div>

        {/* Text content */}
        <div className="flex-1 min-w-0">
          {/* Header */}
          <div className="flex items-center gap-2 mb-3">
            <span className="text-xs font-body text-status-thinking uppercase tracking-widest">
              OpenClaw AI
            </span>
            {alertType && (
              <span className="px-2 py-0.5 rounded text-[10px] font-body bg-status-thinking/10 text-status-thinking border border-status-thinking/20">
                {alertType}
              </span>
            )}
          </div>

          {/* Typewriter text - Dot Matrix Style (Phase 8.0 #16: CSS cursor blink) */}
          <div className="font-body text-lg text-nothing-gray-800 tracking-wide">
            <span className="whitespace-pre-wrap">{displayText}</span>
            <span className="inline-block w-2 h-5 bg-status-thinking ml-1 -mb-0.5 animate-pulse" />
          </div>

          {/* Progress dots */}
          <div className="flex items-center gap-2 mt-4">
            {(['intercepting', 'analyzing', 'calculating', 'generating', 'complete'] as ThinkingPhase[]).map((p, i) => (
              <div
                key={p}
                className={cn(
                  'w-2 h-2 rounded-full transition-all duration-300',
                  currentPhase === p
                    ? 'bg-status-thinking scale-125 shadow-glow-purple'
                    : i < ['intercepting', 'analyzing', 'calculating', 'generating', 'complete'].indexOf(currentPhase)
                      ? 'bg-status-thinking/50'
                      : 'bg-nothing-gray-300'
                )}
              />
            ))}
          </div>
        </div>
      </div>

      {/* Bottom status bar */}
      <div className="mt-4 pt-4 border-t border-status-thinking/10">
        <div className="flex items-center justify-between text-xs font-body text-nothing-gray-500">
          <span className="flex items-center gap-2">
            <span className="w-2 h-2 rounded-full bg-status-thinking animate-pulse" />
            {currentPhase === 'complete' ? t('analysisComplete') : t('processingAlert')}
          </span>
          <span className="text-status-thinking">
            AI Fallback: Ollama → Gemini → Claude
          </span>
        </div>
      </div>
    </div>
  )
}

// =============================================================================
// Export
// =============================================================================

export default AIThinkingPanel
