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

function MessageBubble({ msg, me, groupTop = true, groupBottom = true, showAvatar = true }) {
  const content = msg.content ?? "";
  const senderName = msg.sender?.name || msg.senderId;
  const mine = msg.senderId === me;

  return (
    <div
      className={clsx(
        "flex items-end gap-2 px-3 sm:px-4",
        groupTop ? "pt-1.5" : "pt-px",
        groupBottom ? "pb-1.5" : "pb-px",
        mine && "flex-row-reverse"
      )}
    >
      {!mine && (
        <div className="w-7 flex-shrink-0">
          {groupBottom && showAvatar && <Avatar name={senderName} size={28} />}
        </div>
      )}
      <div
        className={clsx(
          "min-w-0 max-w-[78%] sm:max-w-[70%] flex flex-col gap-0.5",
          mine ? "items-end" : "items-start"
        )}
      >
        {!mine && groupTop && (
          <div className="font-mono text-[11px] tracking-[-0.01em] text-fg-tertiary px-3">
            {senderName}
          </div>
        )}
        <div
          className={clsx(
            "max-w-full px-3 py-2 text-sm leading-[1.4] tracking-[-0.005em] whitespace-pre-wrap break-words [overflow-wrap:anywhere] rounded-[14px]",
            !mine && !groupTop && "rounded-tl-[4px]",
            mine && !groupTop && "rounded-tr-[4px]",
            !mine && !groupBottom && "rounded-bl-[4px]",
            mine && !groupBottom && "rounded-br-[4px]",
            mine ? "bg-accent text-accent-fg" : "bg-surface text-fg font-medium border border-line"
          )}
        >
          {content}
        </div>
        {groupBottom && (
          <div
            className={clsx(
              "flex items-center gap-1 px-2 font-mono text-[10px]",
              mine ? "text-fg-tertiary" : "text-fg-secondary"
            )}
          >
            <span>{formatTime(msg.createdAt)}</span>
            {mine && <CheckCheck size={11} strokeWidth={1.75} className="text-accent" />}
          </div>
        )}
      </div>
    </div>
  );
}

window.MessageBubble = MessageBubble;
