import type { ReactNode } from 'react'

interface StatCardProps {
  label: string
  value: string | number
  unit?: string
  variant?: 'default' | 'us' | 'iran' | 'accent'
  icon?: ReactNode
  className?: string
  /** 资产/人员用 base 适配百万位，海军/航空用 lg 适配万位 */
  valueSize?: 'base' | 'lg'
}

const variantStyles = {
  default: 'border-military-border text-military-text-primary',
  us: 'border-military-us/50 text-military-us',
  iran: 'border-military-iran/50 text-military-iran',
  accent: 'border-military-accent/50 text-military-accent',
}

/** 根据数字位数返回字体大小类，百万位及以上缩小字体避免溢出 */
function getValueSizeClass(value: string | number, baseSize: 'base' | 'lg'): string {
  const s = String(value).replace(/[^\d]/g, '')
  const len = s.length
  const base = baseSize === 'base' ? 'text-sm' : 'text-base'
  if (len >= 9) return 'text-[10px]'
  if (len >= 7) return 'text-xs'
  if (len >= 6) return baseSize === 'base' ? 'text-xs' : 'text-sm'
  return base
}

export function StatCard({
  label,
  value,
  unit = '',
  variant = 'default',
  icon,
  className = '',
  valueSize = 'lg',
}: StatCardProps) {
  const valueClass = getValueSizeClass(value, valueSize)

  return (
    <div
      className={`
        flex min-w-0 flex-col rounded border px-2 py-1.5 font-orbitron
        bg-military-panel/80 backdrop-blur-sm
        ${variantStyles[variant]}
        ${className}
      `}
    >
      <div className="flex min-w-0 items-center gap-1 text-[9px] uppercase tracking-wider opacity-80">
        {icon}
        <span className="truncate">{label}</span>
      </div>
      <div className={`mt-1 min-w-0 overflow-hidden font-bold tabular-nums leading-tight ${valueClass}`} title={String(value)}>
        <span className="block min-w-0">
          {value}
          {unit && <span className="ml-0.5 shrink-0 text-xs font-normal opacity-80">{unit}</span>}
        </span>
      </div>
    </div>
  )
}
