import { useApp } from '../context/AppContext'
import { colorToCss } from '../utils/color'

export default function ConnectionItem({ conn }) {
  const { state, selectConnection, userId } = useApp()
  const otherId = conn.requestorId === userId ? conn.recipientId : conn.requestorId
  const other = state.userMap[otherId]
  const unread = state.unread[conn.id] || 0
  const isSelected = state.selectedId === conn.id
  const isFriend = conn.state === 1

  return (
    <button
      onClick={() => selectConnection(conn.id)}
      className={`w-full flex items-center gap-3 px-3 py-2 rounded-md text-left transition-colors
        ${isSelected ? 'bg-gray-700' : 'hover:bg-gray-700/50'}`}
    >
      <div
        className="w-9 h-9 rounded-full flex items-center justify-center text-white text-sm font-semibold shrink-0"
        style={{ backgroundColor: colorToCss(other?.color) }}
      >
        {other?.name?.[0]?.toUpperCase() ?? '?'}
      </div>

      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-1 min-w-0">
          <span className="text-sm font-medium text-gray-100 truncate min-w-0">
            {other?.name ?? otherId.slice(0, 8)}
          </span>
          {isFriend && (
            <span className="text-[10px] text-green-400 shrink-0">● friend</span>
          )}
        </div>
        {other?.pronouns && (
          <span className="text-xs text-gray-500 truncate block">{other.pronouns}</span>
        )}
      </div>

      {unread > 0 && (
        <span className="shrink-0 bg-red-500 text-white text-xs font-bold rounded-full min-w-[18px] h-[18px] flex items-center justify-center px-1">
          {unread > 99 ? '99+' : unread}
        </span>
      )}
    </button>
  )
}
