import { formatRelative } from "@utils/format.js";
import clsx from "clsx";
import { CheckCheck } from "lucide-react";

function ConversationRow({
  conversation,
  conversationId,
  lastUpdated,
  typing,
  currentUserId,
  onOpen,
}) {
  const participant = conversation?.participant;
  const lastMessage = conversation?.lastMessage;
  const unreadCount = conversation?.unreadCount ?? 0;
  const hasUnread = unreadCount > 0;

  const isTyping = typing?.userId === participant?.id;
  const isSentByMe = !!lastMessage && lastMessage.senderId === currentUserId;

  const title = participant?.name || `Chat ${conversationId.slice(0, 8)}`;
  const preview = isTyping
    ? `${participant?.name ?? "Someone"} is typing…`
    : lastMessage?.content || "Start a conversation";

  return (
    <button
      type="button"
      onClick={() => onOpen(conversationId)}
      className="w-full text-left bg-transparent border-0 cursor-pointer px-4 py-3 flex items-center gap-3 transition-colors duration-normal ease-out-expo hover:bg-hover"
    >
      <Avatar name={participant?.name} size={44} online={hasUnread} />

      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2 mb-0.5">
          <span className="text-sm font-semibold text-fg tracking-[-0.01em] truncate">{title}</span>
          <span
            className={clsx(
              "ml-auto text-[11px] font-mono tracking-[-0.02em] flex-shrink-0",
              hasUnread ? "text-accent" : "text-fg-tertiary"
            )}
          >
            {formatRelative(lastUpdated)}
          </span>
        </div>

        <div className="flex items-center gap-1.5">
          <div
            className={clsx(
              "flex items-center gap-1 flex-1 min-w-0 text-[13px] leading-[1.35]",
              isTyping ? "text-accent italic" : hasUnread ? "text-fg" : "text-fg-secondary"
            )}
          >
            {!isTyping && isSentByMe && !hasUnread && (
              <CheckCheck size={13} strokeWidth={1.75} className="text-accent flex-shrink-0" />
            )}
            <span className="truncate">{preview}</span>
          </div>
          {hasUnread && (
            <span className="min-w-[20px] h-5 px-1.5 rounded-full bg-accent text-accent-fg text-[11px] font-semibold inline-flex items-center justify-center flex-shrink-0">
              {unreadCount}
            </span>
          )}
        </div>
      </div>
    </button>
  );
}

window.ConversationRow = ConversationRow;
