import React from 'react'
import LevelBadge from '../xp/LevelBadge'

const ROLE_STYLES = {
  admin:     'bg-red-500/15 text-red-300',
  moderator: 'bg-amber-500/15 text-amber-300',
  member:    'bg-sky-500/15 text-sky-300',
}

const ROLE_LABELS = {
  admin:     'Admin',
  moderator: 'Moderator',
  member:    'Member',
}

export default function AuthorBadge({ user, size = 'md' }) {
  const name   = user?.name ?? 'Anonymous'
  const avatar = user?.avatar_url ?? '/default/avatar_default.webp'
  const role   = (user?.role ?? 'member').toLowerCase()
  const cls    = ROLE_STYLES[role] ?? ROLE_STYLES.member
  const label  = ROLE_LABELS[role] ?? 'Member'
  const level  = Number(user?.level ?? 0)
  const rank   = user?.rank ?? null

  const imgSize = size === 'sm' ? 'h-8 w-8' : 'h-10 w-10'

  return (
    <div className="flex items-center gap-3">
      <img
        src={avatar}
        alt={`${name} avatar`}
        loading="lazy"
        decoding="async"
        className={`${imgSize} rounded-full border border-white/10 object-cover`}
      />
      <div className="min-w-0">
        <div className="truncate text-sm font-semibold text-zinc-100">{name}</div>
        <div className="mt-1 flex flex-wrap gap-1.5">
          <span className={`inline-flex rounded-full px-2 py-0.5 text-[11px] font-medium ${cls}`}>
            {label}
          </span>
          {rank && level > 0 ? <LevelBadge level={level} rank={rank} compact /> : null}
        </div>
      </div>
    </div>
  )
}
