import { Avatar } from '@discord-clone/ui';
import { useOnlineUsers } from '../../contexts/PresenceContext';
import styles from './DMListItem.module.css';

interface DMRow {
	channel_id: string;
	channel_name: string;
	other_user_id: string;
	other_username: string;
	other_displayName: string | null;
	other_user_status?: string;
	other_user_avatar_url?: string | null;
}

interface DMListItemProps {
	dm: DMRow;
	selected: boolean;
	onClick: () => void;
}

export function DMListItem({ dm, selected, onClick }: DMListItemProps) {
	// Always show the real `username` in the DM list — it's the
	// stable identifier across the whole app. Display names / server
	// nicknames go in member lists where context makes them
	// unambiguous, but in the DM sidebar we want users to see the
	// account they're talking to.
	const name = dm.other_username || dm.other_displayName || 'User';
	const { resolveStatus } = useOnlineUsers();
	const liveStatus = resolveStatus(
		dm.other_user_status || 'offline',
		dm.other_user_id,
	);
	return (
		<button
			type="button"
			className={`${styles.item} ${selected ? styles.itemSelected : ''}`}
			onClick={onClick}
		>
			<Avatar
				src={dm.other_user_avatar_url || null}
				size={32}
				fallback={name}
				status={liveStatus as any}
			/>
			<div className={styles.info}>
				<span className={styles.name}>{name}</span>
			</div>
		</button>
	);
}
