import React from 'react'
import applicationIcon from '../assets/application.svg'

/** 渐变色库 [左上深, 右下浅]，135deg，共 20 组（与 Vue 端一致） */
export const AVATAR_GRADIENT_PAIRS: [string, string][] = [
  ['#1e3a8a', '#93c5fd'],
  ['#166534', '#86efac'],
  ['#c2410c', '#fdba74'],
  ['#b91c1c', '#fca5a5'],
  ['#5b21b6', '#c4b5fd'],
  ['#0f766e', '#5eead4'],
  ['#3730a3', '#a5b4fc'],
  ['#0d9488', '#2dd4bf'],
  ['#b45309', '#fcd34d'],
  ['#be123c', '#fda4af'],
  ['#0369a1', '#7dd3fc'],
  ['#4d7c0f', '#bef264'],
  ['#86198f', '#e879f9'],
  ['#db2777', '#fbcfe8'],
  ['#047857', '#6ee7b7'],
  ['#6d28d9', '#ddd6fe'],
  ['#1e40af', '#93c5fd'],
  ['#ea580c', '#fed7aa'],
  ['#0e7490', '#99f6e4'],
  ['#881337', '#fbcfe8']
]

export function getAvatarText(name: string): string {
  const n = String(name || '').trim()
  if (!n) return '?'
  const cjkCount = (n.match(/[\u4e00-\u9fff\u3400-\u4dbf]/g) || []).length
  const letterCount = n.replace(/\s/g, '').length
  const isCJK = letterCount > 0 && cjkCount >= letterCount / 2
  if (isCJK) {
    if (n.length <= 2) return n
    return n.slice(-2)
  }
  const words = n.split(/\s+/).filter(Boolean)
  if (words.length >= 2) {
    const a = (words[0][0] || '').toUpperCase()
    const b = (words[1][0] || '').toUpperCase()
    return a + b || '?'
  }
  if (words.length === 1 && words[0].length >= 2) return words[0].slice(0, 2).toUpperCase()
  if (words.length === 1 && words[0].length === 1) return words[0].toUpperCase()
  return '?'
}

/**
 * 联系人/用户文字头像：id 优先，再 name（与改应用规则前一致）。
 */
export function getGradientIndex(id: string | number, name: string): number {
  const s = String(id || '').trim() || String(name || '').trim()
  let hash = 0
  for (let i = 0; i < s.length; i++) {
    hash = ((hash << 5) - hash + s.charCodeAt(i)) | 0
  }
  return Math.abs(hash) % AVATAR_GRADIENT_PAIRS.length
}

/**
 * 应用图标（application.svg）：仅按展示名 String(name).trim()，空则用 `SYSTEM`；再哈希 % 20 组渐变。
 */
export function getApplicationGradientIndex(name: string): number {
  const s = String(name || '').trim() || 'SYSTEM'
  let hash = 0
  for (let i = 0; i < s.length; i++) {
    hash = ((hash << 5) - hash + s.charCodeAt(i)) | 0
  }
  return Math.abs(hash) % AVATAR_GRADIENT_PAIRS.length
}

export interface DefaultAvatarOptions {
  sizePx?: number
}

/** 占位内容：`text` 为姓名缩写；`applicationIcon` 为应用中心统一 SVG，仍为同一套渐变底 */
export type AvatarPlaceholderVariant = 'text' | 'applicationIcon'

/** 应用类 SVG 占位：`roundedSquare` 为方形圆角（应用中心）；默认圆形（会话列表等） */
export type ApplicationIconShape = 'circle' | 'roundedSquare'

export function getAvatarPlaceholder(
  displayName: string,
  identityKey: string | number,
  sizePx: number,
  extraStyle?: React.CSSProperties,
  variant: AvatarPlaceholderVariant = 'text',
  applicationIconShape: ApplicationIconShape = 'circle'
): React.ReactNode {
  const idx =
    variant === 'applicationIcon'
      ? getApplicationGradientIndex(displayName)
      : getGradientIndex(identityKey, displayName)
  const [c1, c2] = AVATAR_GRADIENT_PAIRS[idx]
  const fontSize = sizePx * 0.4
  const iconSize = Math.max(14, Math.round(sizePx * 0.55))

  const borderRadius =
    variant === 'applicationIcon' && applicationIconShape === 'roundedSquare'
      ? Math.round(sizePx * 0.22)
      : '50%'

  const base: React.CSSProperties = {
    width: sizePx,
    height: sizePx,
    minWidth: sizePx,
    minHeight: sizePx,
    borderRadius,
    overflow: 'hidden',
    backgroundColor: c1,
    backgroundImage: `linear-gradient(135deg, ${c1}, ${c2})`,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    userSelect: 'none',
    flexShrink: 0,
    boxSizing: 'border-box',
    ...extraStyle
  }

  if (variant === 'applicationIcon') {
    return (
      <div style={base}>
        <img
          src={applicationIcon}
          alt=""
          draggable={false}
          style={{ width: iconSize, height: iconSize, display: 'block' }}
        />
      </div>
    )
  }

  const text = getAvatarText(displayName)
  return (
    <div
      style={{
        ...base,
        color: '#ffffff',
        fontSize,
        fontWeight: 500,
        fontFamily: "'PingFang SC', 'Roboto', -apple-system, sans-serif",
        lineHeight: 1,
        whiteSpace: 'nowrap'
      }}
    >
      {text}
    </div>
  )
}

export function getChineseChars(name: string): string {
  return getAvatarText(name)
}

export function getBackgroundColor(name: string): string {
  const idx = getGradientIndex(name, name)
  return AVATAR_GRADIENT_PAIRS[idx][0]
}

export function getDefaultAvatar(
  contactId: number,
  contactName?: string,
  options?: DefaultAvatarOptions
): React.ReactNode {
  const displayName = contactName?.trim() ? contactName : `用户${contactId}`
  const sizePx = options?.sizePx ?? 40
  return getAvatarPlaceholder(displayName, contactId, sizePx)
}

/**
 * 消息中心 / 会话列表头像：负 id 为应用系统通知会话（-app_id），与 Web 约定一致，使用渐变 + application.svg。
 */
export function getSessionAvatar(
  contactId: number,
  contactName: string | undefined,
  sizePx: number,
  extraStyle?: React.CSSProperties
): React.ReactNode {
  const displayName =
    contactName?.trim() ||
    (contactId < 0 ? '系统通知' : `用户${contactId}`)
  const variant: AvatarPlaceholderVariant = contactId < 0 ? 'applicationIcon' : 'text'
  return getAvatarPlaceholder(displayName, contactId, sizePx, extraStyle, variant)
}
