'use client'

/**
 * ApprovalCard - CPO-107 HITL 授權卡片
 * =====================================
 * Nothing.tech 明亮工業風 + 防誤觸機制
 * Emergency Hotfix: 移除光害特效，回歸精密極簡
 *
 * i18n: 100% 使用 useTranslations，禁止任何寫死字串
 *
 * Visual Features:
 * - CRITICAL 風險: 左側紅色粗邊框 (border-l-4)
 * - 乾淨白色背景，確保資料可讀性
 * - 精確的 Typography 層級
 */

import { useState, useRef, useCallback, useEffect } from 'react'
import { useTranslations } from 'next-intl'
import {
  GlassCard,
  GlassCardHeader,
  GlassCardTitle,
  GlassCardContent,
  GlassCardFooter,
} from '@/components/ui/glass-card'
import { StatusOrb } from '@/components/ui/status-orb'
import { cn } from '@/lib/utils'
import { AlertTriangle, CheckCircle2, XCircle, Clock, Shield, Zap, ChevronDown } from 'lucide-react'

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

export type RiskLevel = 'low' | 'medium' | 'high' | 'critical'

export interface DryRunCheck {
  name: string
  passed: boolean
  message?: string
}

export interface BlastRadius {
  affectedPods: number
  estimatedDowntime: string
  relatedServices: string[]
  dataImpact: 'NONE' | 'READ_ONLY' | 'WRITE' | 'DESTRUCTIVE'
}

export interface ApprovalRequest {
  id: string
  action: string
  description: string
  riskLevel: RiskLevel
  blastRadius: BlastRadius
  dryRunChecks: DryRunCheck[]
  requiredSignatures: number
  currentSignatures: number
  requestedBy: string
  requestedAt: string
  // 戰略 B: 告警風暴收斂
  hitCount?: number  // 聚合觸發次數
  lastSeenAt?: string  // 最後觸發時間
  fingerprint?: string  // 告警指紋
}

export interface Signature {
  id: string
  signerName: string
  signedAt: string
  comment?: string
}

export interface ApprovalCardProps {
  request: ApprovalRequest
  signatures?: Signature[]
  onApprove?: (id: string) => void
  onReject?: (id: string) => void
  className?: string
  holdDuration?: number
  isLoading?: boolean
  /** 唯讀模式 (歷史紀錄用) */
  readOnly?: boolean
  /** 最終狀態標籤 (歷史紀錄用) */
  finalStatus?: 'approved' | 'rejected' | 'executed' | 'failed'
  /** 在 Modal 中使用時，移除高度限制 */
  fullHeight?: boolean
}

// =============================================================================
// Config
// =============================================================================

const HOLD_DURATION_DEFAULT = 2000

// =============================================================================
// Long Press Button Component
// =============================================================================

interface LongPressButtonProps {
  onComplete: () => void
  disabled?: boolean
  holdDuration?: number
  label: string
  labelHolding: string
  className?: string
  variant?: 'approve' | 'danger'
}

function LongPressButton({
  onComplete,
  disabled = false,
  holdDuration = HOLD_DURATION_DEFAULT,
  label,
  labelHolding,
  className,
  variant = 'approve',
}: LongPressButtonProps) {
  const [isHolding, setIsHolding] = useState(false)
  const [progress, setProgress] = useState(0)
  const [showRipple, setShowRipple] = useState(false)
  const startTimeRef = useRef<number | null>(null)
  const animationFrameRef = useRef<number | null>(null)

  const updateProgress = useCallback(() => {
    if (!startTimeRef.current) return

    const elapsed = Date.now() - startTimeRef.current
    const newProgress = Math.min((elapsed / holdDuration) * 100, 100)
    setProgress(newProgress)

    if (newProgress >= 100) {
      setIsHolding(false)
      setProgress(0)
      startTimeRef.current = null
      setShowRipple(true)
      setTimeout(() => setShowRipple(false), 600)
      onComplete()
    } else {
      animationFrameRef.current = requestAnimationFrame(updateProgress)
    }
  }, [holdDuration, onComplete])

  const handlePointerDown = useCallback(() => {
    if (disabled) return
    setIsHolding(true)
    startTimeRef.current = Date.now()
    animationFrameRef.current = requestAnimationFrame(updateProgress)
  }, [disabled, updateProgress])

  const handlePointerUp = useCallback(() => {
    setIsHolding(false)
    setProgress(0)
    startTimeRef.current = null
    if (animationFrameRef.current) {
      cancelAnimationFrame(animationFrameRef.current)
    }
  }, [])

  useEffect(() => {
    return () => {
      if (animationFrameRef.current) {
        cancelAnimationFrame(animationFrameRef.current)
      }
    }
  }, [])

  // UX 優化: 實心邊框 + 填充色 (更明確的可點擊狀態)
  const baseStyles = variant === 'danger'
    ? [
        'bg-status-critical/10',
        'border-2 border-status-critical/50',
        'text-status-critical',
        'hover:bg-status-critical/20',
        'hover:border-status-critical',
        'shadow-sm',
      ]
    : [
        'bg-claw-blue/10',
        'border-2 border-claw-blue/50',
        'text-claw-blue',
        'hover:bg-claw-blue/20',
        'hover:border-claw-blue',
        'shadow-sm',
      ]

  const progressBgColor = variant === 'danger' ? 'bg-status-critical' : 'bg-claw-blue'

  return (
    <button
      onPointerDown={handlePointerDown}
      onPointerUp={handlePointerUp}
      onPointerLeave={handlePointerUp}
      onPointerCancel={handlePointerUp}
      disabled={disabled}
      className={cn(
        'relative overflow-hidden px-6 py-3.5 rounded-xl font-body text-sm font-semibold',
        'transition-all duration-300 ease-out select-none touch-none',
        'active:scale-[0.97]',
        disabled
          ? 'bg-nothing-gray-100 border-2 border-nothing-gray-200 text-nothing-gray-400 cursor-not-allowed'
          : baseStyles,
        isHolding && 'scale-[0.98]',
        className
      )}
      aria-label={isHolding ? labelHolding : label}
    >
      {/* Progress fill */}
      <div
        className={cn(
          'absolute inset-0 transition-none origin-left',
          progressBgColor,
          'opacity-25'
        )}
        style={{
          width: `${progress}%`,
          clipPath: 'inset(0 0 0 0 round 10px)',
        }}
      />

      {/* Ripple effect on complete */}
      {showRipple && (
        <span
          className={cn(
            'absolute inset-0 flex items-center justify-center',
            'animate-ripple rounded-xl',
            variant === 'danger' ? 'bg-status-critical/30' : 'bg-status-healthy/30'
          )}
        />
      )}

      <span className="relative z-10 flex items-center justify-center gap-2">
        {isHolding ? (
          <>
            <svg className="w-4 h-4 animate-spin" viewBox="0 0 24 24" fill="none">
              <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeDasharray="60" strokeDashoffset="20" />
            </svg>
            <span className="tabular-nums">{labelHolding} ({Math.round(progress)}%)</span>
          </>
        ) : (
          <>
            {variant === 'danger' ? (
              <AlertTriangle className="w-4 h-4" />
            ) : (
              <Shield className="w-4 h-4" />
            )}
            {label}
          </>
        )}
      </span>
    </button>
  )
}

// =============================================================================
// Main Component
// =============================================================================

export function ApprovalCard({
  request,
  signatures,
  onApprove,
  onReject,
  className,
  holdDuration = HOLD_DURATION_DEFAULT,
  isLoading = false,
  readOnly = false,
  finalStatus,
  fullHeight = false,
}: ApprovalCardProps) {
  const t = useTranslations('approval')
  const tRisk = useTranslations('risk')
  const tBlast = useTranslations('blastRadius')
  const tDryRun = useTranslations('dryRun')

  // UX 優化: 折疊狀態 (預設收合，減少垂直空間佔用)
  const [_isExpanded, _setIsExpanded] = useState(false)

  // 微交互狀態: 處理中 + 滑出動畫
  const [isProcessing, setIsProcessing] = useState(false)
  const [isExiting, setIsExiting] = useState(false)

  const allChecksPassed = request.dryRunChecks?.every((c) => c.passed) ?? true
  const needsMoreSignatures = request.currentSignatures < request.requiredSignatures
  const hasPartialSignatures = request.currentSignatures > 0 && needsMoreSignatures
  const isCritical = request.riskLevel === 'critical'
  const isDestructive = request.blastRadius?.dataImpact === 'DESTRUCTIVE'

  // 處理核准 - 加入微交互
  const handleApproveWithAnimation = useCallback(() => {
    setIsProcessing(true)
    // 800ms 後開始滑出動畫，再呼叫父層
    setTimeout(() => {
      setIsExiting(true)
      setTimeout(() => {
        onApprove?.(request.id)
      }, 300) // 滑出動畫時間
    }, 800)
  }, [onApprove, request.id])

  // 處理拒絕 - 加入微交互
  const handleRejectWithAnimation = useCallback(() => {
    setIsProcessing(true)
    setTimeout(() => {
      setIsExiting(true)
      setTimeout(() => {
        onReject?.(request.id)
      }, 300)
    }, 500)
  }, [onReject, request.id])

  const riskLabel = tRisk(request.riskLevel)
  const orbStatus = isCritical || request.riskLevel === 'high'
    ? 'critical'
    : request.riskLevel === 'medium'
      ? 'warning'
      : 'healthy'

  const dataImpactLabel = tBlast(
    request.blastRadius?.dataImpact === 'READ_ONLY' ? 'readOnly' :
    request.blastRadius?.dataImpact === 'WRITE' ? 'write' :
    request.blastRadius?.dataImpact === 'DESTRUCTIVE' ? 'destructive' : 'none'
  )

  // 舊的直接呼叫方式 (保留相容性，但現在使用動畫版本)
  const handleApprove = handleApproveWithAnimation
  const handleReject = handleRejectWithAnimation

  const actualHoldDuration = isDestructive || isCritical ? holdDuration : holdDuration / 2
  const holdSeconds = actualHoldDuration / 1000

  return (
    <GlassCard
      variant={isCritical ? 'elevated' : 'default'}
      padding="none"
      className={cn(
        'relative transition-all duration-300 flex flex-col',
        // UX 優化: 限制最大高度，內容可滾動 (Modal 模式除外)
        !fullHeight && 'max-h-[70vh]',
        // Nothing.tech 精密極簡風格
        !readOnly && 'hover:-translate-y-0.5 hover:shadow-card-hover',
        // CRITICAL: 左側紅色粗邊框 (乾淨、無光害)
        isCritical && 'border-l-4 border-l-status-critical',
        // MEDIUM: 左側黃色邊框
        request.riskLevel === 'medium' && 'border-l-4 border-l-status-warning',
        // LOW: 左側綠色邊框
        request.riskLevel === 'low' && 'border-l-4 border-l-status-healthy',
        // 處理中狀態
        isProcessing && 'opacity-70 pointer-events-none',
        // 滑出動畫
        isExiting && 'translate-x-full opacity-0',
        // 唯讀模式 (歷史紀錄)
        readOnly && 'opacity-80 bg-nothing-gray-50',
        className
      )}
      aria-label={`${request.action} - ${riskLabel}`}
    >
      {/* 可滾動的內容區域 */}
      <div className="flex-1 overflow-y-auto p-6 pb-0">
      {/* 歷史紀錄 - 最終狀態 Badge */}
      {readOnly && finalStatus && (
        <div className={cn(
          'absolute top-3 right-3 flex items-center gap-1.5 px-2.5 py-1 rounded-lg',
          'font-body text-xs font-bold uppercase',
          finalStatus === 'executed' && 'bg-status-healthy/10 text-status-healthy border border-status-healthy/20',
          finalStatus === 'approved' && 'bg-claw-blue/10 text-claw-blue border border-claw-blue/20',
          finalStatus === 'rejected' && 'bg-nothing-gray-100 text-nothing-gray-500 border border-nothing-gray-200',
          finalStatus === 'failed' && 'bg-status-critical/10 text-status-critical border border-status-critical/20',
        )}>
          {finalStatus === 'executed' && <CheckCircle2 className="w-3 h-3" />}
          {finalStatus === 'approved' && <Shield className="w-3 h-3" />}
          {finalStatus === 'rejected' && <XCircle className="w-3 h-3" />}
          {finalStatus === 'failed' && <AlertTriangle className="w-3 h-3" />}
          {finalStatus === 'executed' ? '執行成功' :
           finalStatus === 'approved' ? '已核准' :
           finalStatus === 'rejected' ? '已拒絕' : '執行失敗'}
        </div>
      )}

      {/* Header */}
      <GlassCardHeader>
        <div className="flex items-center gap-3">
          <StatusOrb
            status={orbStatus}
            size="md"
            glow={isCritical}
            pulse={isCritical}
          />
          {/* Risk Badge - 乾淨無光害 */}
          <div
            className={cn(
              'inline-flex items-center gap-2 px-3 py-1.5 rounded-lg',
              'font-body text-xs font-semibold tracking-wide uppercase',
              isCritical
                ? 'bg-status-critical/10 text-status-critical border border-status-critical/30'
                : request.riskLevel === 'high'
                  ? 'bg-status-warning/10 text-status-warning border border-status-warning/30'
                  : request.riskLevel === 'medium'
                    ? 'bg-status-warning/10 text-status-warning border border-status-warning/30'
                    : 'bg-status-healthy/10 text-status-healthy border border-status-healthy/30'
            )}
          >
            {isCritical ? (
              <AlertTriangle className="w-3.5 h-3.5" />
            ) : request.riskLevel === 'low' ? (
              <CheckCircle2 className="w-3.5 h-3.5" />
            ) : (
              <Zap className="w-3.5 h-3.5" />
            )}
            {riskLabel}
          </div>

          {/* 戰略 B: 告警聚合次數 Badge (Nothing.tech VT323 風格) */}
          {request.hitCount && request.hitCount > 1 && (
            <div
              className={cn(
                'inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg',
                'font-heading text-sm font-bold tracking-wide', // VT323 點陣字體
                'bg-nothing-gray-900/10 text-nothing-gray-700',
                'border border-nothing-gray-300',
                'animate-pulse-subtle', // 微妙脈動提示有新告警聚合
              )}
              title={`相同指紋告警已觸發 ${request.hitCount} 次`}
            >
              <span className="text-nothing-gray-500">×</span>
              <span className="tabular-nums">{request.hitCount}</span>
              <span className="text-[10px] text-nothing-gray-500 uppercase">次</span>
            </div>
          )}
        </div>

        {/* Multi-Sig Counter + Progress - Enhanced */}
        <div className="text-right">
          <div className="text-[10px] text-nothing-gray-500 font-body uppercase tracking-wider mb-1">
            {t('signatures')}
          </div>
          <div
            className={cn(
              'text-2xl font-body font-bold tabular-nums',
              'transition-colors duration-200',
              needsMoreSignatures ? 'text-status-warning' : 'text-status-healthy'
            )}
          >
            {request.currentSignatures}
            <span className="text-nothing-gray-400">/</span>
            {request.requiredSignatures}
          </div>
          {/* 簽核進度條 */}
          <div className="mt-2 w-20 h-1.5 bg-nothing-gray-200 rounded-full overflow-hidden">
            <div
              className={cn(
                'h-full rounded-full transition-all duration-500',
                needsMoreSignatures ? 'bg-status-warning' : 'bg-status-healthy'
              )}
              style={{ width: `${(request.currentSignatures / request.requiredSignatures) * 100}%` }}
            />
          </div>
        </div>
      </GlassCardHeader>

      {/* 已簽核人員列表 (有簽名時顯示) */}
      {signatures && signatures.length > 0 && (
        <div className="px-6 -mt-2 mb-4">
          <div className="flex items-center gap-2 text-[10px] text-nothing-gray-500 font-body">
            <Shield className="w-3 h-3" />
            <span>已簽核:</span>
            {signatures.map((sig, idx) => (
              <span key={sig.id} className="inline-flex items-center gap-1">
                <span className="px-1.5 py-0.5 bg-status-healthy/10 text-status-healthy rounded text-[10px] font-semibold">
                  {sig.signerName}
                </span>
                {idx < signatures.length - 1 && <span className="text-nothing-gray-300">·</span>}
              </span>
            ))}
          </div>
        </div>
      )}

      {/* Title & Description - UX 優化: 分離標題與命令 */}
      <div className="mb-5">
        {/* 主標題: 只顯示 | 前的動作描述 */}
        <GlassCardTitle className="text-nothing-gray-900 mb-2">
          {request.action.includes('|')
            ? request.action.split('|')[0].trim()
            : request.action}
        </GlassCardTitle>

        {/* kubectl 命令: 獨立顯示，可複製 */}
        {request.action.includes('|') && (
          <code className="block mb-3 px-3 py-2 bg-nothing-gray-100 rounded-lg text-xs font-body text-nothing-gray-700 break-all border border-nothing-gray-200">
            {request.action.split('|')[1].trim()}
          </code>
        )}

        {/* 描述: 清理 AI provider 標籤 */}
        <p className="text-sm text-nothing-gray-600">
          {request.description
            .replace(/\[AI:\s*\w+\]\s*/g, '')  // 移除 [AI: xxx]
            .replace(/🤖\s*AI\s*仲裁:\s*/g, '')  // 移除 AI 仲裁前綴
            .trim()}
        </p>
      </div>

      <GlassCardContent>
        {/* Blast Radius - 可折疊面板 */}
        <details className="mb-4 group" open={isCritical || isDestructive}>
          <summary className="flex items-center justify-between cursor-pointer select-none py-2 px-3 -mx-3 rounded-lg hover:bg-nothing-gray-50 transition-colors">
            <h4 className="text-[10px] font-body text-nothing-gray-500 uppercase tracking-widest flex items-center gap-2">
              <Zap className="w-3 h-3" />
              {tBlast('title')}
              {/* 摘要預覽 */}
              <span className="text-nothing-gray-400 normal-case">
                ({request.blastRadius?.affectedPods ?? 0} pods)
              </span>
            </h4>
            <ChevronDown className="w-4 h-4 text-nothing-gray-400 transition-transform group-open:rotate-180" />
          </summary>
          {request.blastRadius && (
            <div className="grid grid-cols-2 gap-3 mt-3 animate-in slide-in-from-top-2 duration-200">
              <MetricBox
                label={tBlast('affectedPods')}
                value={String(request.blastRadius.affectedPods ?? 0)}
                highlight={(request.blastRadius.affectedPods ?? 0) > 5}
              />
              <MetricBox
                label={tBlast('estimatedDowntime')}
                value={request.blastRadius.estimatedDowntime ?? '0'}
                highlight={request.blastRadius.estimatedDowntime !== '0'}
              />
              <div className="col-span-2">
                <div className="bg-nothing-gray-50 rounded-lg p-3 border border-nothing-gray-200">
                  <div className="text-[10px] text-nothing-gray-500 font-body uppercase tracking-wider mb-2">
                    {tBlast('relatedServices')}
                  </div>
                  <div className="flex flex-wrap gap-1.5">
                    {(request.blastRadius.relatedServices ?? []).map((svc) => (
                      <span
                        key={svc}
                        className="px-2 py-0.5 rounded text-xs font-body bg-white border border-nothing-gray-200 text-nothing-gray-700"
                      >
                        {svc}
                      </span>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          )}
        </details>

        {/* Data Impact */}
        {isDestructive && (
          <div className="mb-5 p-4 bg-status-critical/5 border border-status-critical/20 rounded-lg">
            <div className="flex items-center gap-2">
              <StatusOrb status="critical" size="sm" pulse />
              <span className="text-sm font-body text-status-critical font-semibold">
                {tBlast('dataImpact')}: {dataImpactLabel}
              </span>
            </div>
          </div>
        )}

        {/* Dry-Run Checks - 可折疊面板 (預設收合) */}
        <details className="mb-4 group">
          <summary className="flex items-center justify-between cursor-pointer select-none py-2 px-3 -mx-3 rounded-lg hover:bg-nothing-gray-50 transition-colors">
            <h4 className="text-[10px] font-body text-nothing-gray-500 uppercase tracking-widest flex items-center gap-2">
              <Clock className="w-3 h-3" />
              {tDryRun('validation')}
              {/* 通過/失敗摘要 */}
              <span className={cn(
                'text-[10px] font-body px-1.5 py-0.5 rounded',
                allChecksPassed
                  ? 'bg-status-healthy/10 text-status-healthy'
                  : 'bg-status-critical/10 text-status-critical'
              )}>
                {(request.dryRunChecks ?? []).filter(c => c.passed).length}/{(request.dryRunChecks ?? []).length}
              </span>
            </h4>
            <ChevronDown className="w-4 h-4 text-nothing-gray-400 transition-transform group-open:rotate-180" />
          </summary>
          <div className="space-y-2 mt-3 animate-in slide-in-from-top-2 duration-200">
            {(request.dryRunChecks ?? []).map((check) => (
              <div
                key={check.name}
                className={cn(
                  'flex items-center justify-between rounded-lg px-3 py-2.5',
                  'transition-all duration-200',
                  check.passed
                    ? 'bg-status-healthy/5 border border-status-healthy/10 hover:border-status-healthy/20'
                    : 'bg-status-critical/5 border border-status-critical/10 hover:border-status-critical/20'
                )}
              >
                <div className="flex items-center gap-2.5">
                  {check.passed ? (
                    <CheckCircle2 className="w-4 h-4 text-status-healthy" />
                  ) : (
                    <XCircle className="w-4 h-4 text-status-critical" />
                  )}
                  <span className="text-sm text-nothing-gray-800 font-body font-medium">
                    {check.name}
                  </span>
                </div>
                {check.message && (
                  <span className={cn(
                    'text-xs font-body px-2 py-0.5 rounded',
                    check.passed
                      ? 'bg-status-healthy/10 text-status-healthy'
                      : 'bg-status-critical/10 text-status-critical'
                  )}>
                    {check.message}
                  </span>
                )}
              </div>
            ))}
          </div>
        </details>
      </GlassCardContent>
      </div>
      {/* 結束可滾動區域 */}

      {/* Sticky Footer - 簽核按鈕永遠可見 */}
      <GlassCardFooter className="sticky bottom-0 bg-white border-t border-nothing-gray-100 p-4 mt-auto">
        {/* Meta */}
        <div className="flex items-center justify-between mb-4">
          <div className="text-xs text-nothing-gray-500 font-body">
            <span>{t('requestedBy')} </span>
            <span className="text-nothing-gray-700">{request.requestedBy}</span>
            <span className="mx-2">|</span>
            <span>{request.requestedAt}</span>
          </div>
        </div>

        {/* 處理中指示器 */}
        {isProcessing && (
          <div className="mb-4 p-4 bg-claw-blue/5 border border-claw-blue/20 rounded-lg">
            <div className="flex items-center justify-center gap-3">
              <svg className="w-5 h-5 text-claw-blue animate-spin" viewBox="0 0 24 24" fill="none">
                <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeDasharray="60" strokeDashoffset="20" />
              </svg>
              <span className="text-sm font-body text-claw-blue font-semibold">
                正在處理中...
              </span>
            </div>
          </div>
        )}

        {/* 唯讀模式 - 不顯示按鈕 */}
        {readOnly ? (
          <div className="text-center py-2">
            <p className="text-xs text-nothing-gray-400 font-body">
              此紀錄為歷史存檔，僅供稽核參考
            </p>
          </div>
        ) : (
          <>
            {/* Partial Signatures Notice */}
            {hasPartialSignatures && !isProcessing && (
              <div className="mb-4 p-3 bg-status-warning/10 border border-status-warning/30 rounded-lg">
                <div className="flex items-center gap-2">
                  <StatusOrb status="warning" size="sm" />
                  <span className="text-sm font-body text-status-warning">
                    {t('waitingSecondSig')}
                  </span>
                </div>
              </div>
            )}

            {/* Action Buttons - Enhanced */}
            {!isProcessing && (
              <>
                <div className="flex items-center gap-4">
                  <button
                    onClick={handleReject}
                    disabled={isLoading || isProcessing}
                    className={cn(
                      'flex-1 flex items-center justify-center gap-2',
                      'px-6 py-3.5 rounded-xl font-body text-sm font-semibold',
                      'bg-nothing-gray-50 border-2 border-nothing-gray-200 text-nothing-gray-600',
                      'hover:border-nothing-gray-300 hover:bg-nothing-gray-100 hover:text-nothing-gray-800',
                      'active:scale-[0.97]',
                      'transition-all duration-200',
                      (isLoading || isProcessing) && 'opacity-50 cursor-not-allowed'
                    )}
                  >
                    <XCircle className="w-4 h-4" />
                    {t('reject')}
                  </button>

                  <LongPressButton
                    onComplete={handleApprove}
                    disabled={!allChecksPassed || isLoading || isProcessing}
                    holdDuration={actualHoldDuration}
                    label={
                      isLoading
                        ? t('signing')
                        : needsMoreSignatures && request.currentSignatures === 0
                          ? t('holdToSign')
                          : hasPartialSignatures
                            ? t('holdToSign')
                            : isDestructive
                              ? t('holdToConfirm')
                              : t('holdToApprove')
                    }
                    labelHolding={t('signing')}
                    variant={isDestructive || isCritical ? 'danger' : 'approve'}
                    className="flex-1"
                  />
                </div>

                {/* Long Press Hint - Subtle */}
                <p className="mt-4 text-[11px] text-nothing-gray-400 text-center font-body tracking-wide">
                  {t('holdHint', {
                    seconds: holdSeconds,
                    action: hasPartialSignatures ? t('actionSign') : isDestructive ? t('actionConfirm') : t('actionApprove')
                  })}
                </p>
              </>
            )}
          </>
        )}
      </GlassCardFooter>
    </GlassCard>
  )
}

// =============================================================================
// Sub-components
// =============================================================================

interface MetricBoxProps {
  label: string
  value: string
  className?: string
  highlight?: boolean
}

function MetricBox({ label, value, className, highlight = false }: MetricBoxProps) {
  return (
    <div className={cn(
      'rounded-lg p-3 border bg-nothing-gray-50',
      highlight ? 'border-status-warning/30' : 'border-nothing-gray-200',
      className
    )}>
      <div className="text-[10px] text-nothing-gray-500 font-body uppercase tracking-wider mb-1">{label}</div>
      <div className={cn(
        'text-lg font-body font-bold tabular-nums',
        highlight ? 'text-status-warning' : 'text-nothing-gray-900'
      )}>
        {value}
      </div>
    </div>
  )
}

export { LongPressButton }
