Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

34.6 KB
Raw Blame
import React, { useState, useEffect, useRef } from 'react';
import {
  Users,
  MessageSquare,
  Eye,
  Paintbrush,
  Send,
  ChevronDown,
  ChevronUp,
  Settings2,
  X,
  Loader2,
  BookmarkPlus,
  Share2,
} from 'lucide-react';
import type { BrushSettings } from '../types/editor';
import type {
  CollabChatMessage,
  CollabDiagnostics,
  CollabPeer,
  CollabRole,
  CollabSharedBrushSnapshot,
  ConnectionStatus,
  SessionHostInfo,
} from '../types/multiplayer';
import { peerIdEquals } from '../utils/collabPermissions';
import { isImeComposing, t as translateStatic, useI18n } from '../i18n';

export interface CollabRoomOverlayProps {
  isConnected: boolean;
  isReconnecting?: boolean;
  connectionStatus?: ConnectionStatus;
  myRole?: CollabRole;
  hostInfo: SessionHostInfo | null;
  myPeer: CollabPeer;
  peers: CollabPeer[];
  chatMessages: CollabChatMessage[];
  unreadChatCount: number;
  onSendChatMessage: (text: string) => boolean;
  onChatVisibilityChange?: (visible: boolean) => void;
  followingPeerId: string | number | null;
  onToggleFollowPeer: (peerId: string | number) => void;
  onStopFollowing: () => void;
  grabbingPeerId: string | number | null;
  onGrabPeerBrush: (peerId: string | number) => void;
  onTrySharedBrush: (snapshot: Omit<CollabSharedBrushSnapshot, 'updatedAt'>) => void;
  onShareMyBrush: () => void;
  activeGrabbedBrush: {
    peerId: string | number;
    peerName: string;
    brushName: string;
    settings: BrushSettings;
  } | null;
  onSaveGrabbedBrush: () => void;
  onDismissGrabbedBrush: () => void;
  onOpenHostModal: () => void;
  diagnostics?: CollabDiagnostics | null;
  isWebtoonMode?: boolean;
}

function formatByteRate(bytesPerSec: number): string {
  if (!Number.isFinite(bytesPerSec) || bytesPerSec <= 0) return '0 B/s';
  if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  if (bytesPerSec < 1024 * 1024) return `${(bytesPerSec / 1024).toFixed(1)} KB/s`;
  return `${(bytesPerSec / (1024 * 1024)).toFixed(2)} MB/s`;
}

function buildDiagnosticsTooltip(
  diagnostics: CollabDiagnostics,
  hostInfo: SessionHostInfo | null
): string {
  const effectiveTransport =
    diagnostics.transport ?? (hostInfo?.transport === 'webrtc' ? 'webrtc' : 'ws');
  const transportLine =
    effectiveTransport === 'webrtc'
      ? translateStatic('Transport: WebRTC ({mode})', {
          mode:
            diagnostics.iceCandidateType === 'relay'
              ? translateStatic('TURN relay')
              : diagnostics.iceCandidateType
                ? `P2P · ${diagnostics.iceCandidateType}`
                : 'P2P',
        })
      : translateStatic('Transport: WebSocket');
  const pingLine =
    diagnostics.rttMs !== null
      ? translateStatic('Ping: {ms} ms', { ms: Math.round(diagnostics.rttMs) })
      : translateStatic('Ping: measuring...');
  const throughputLine = translateStatic(
    'TX: {txRate} ({txMsgs} msg/s) · RX: {rxRate} ({rxMsgs} msg/s)',
    {
      txRate: formatByteRate(diagnostics.txBytesPerSec),
      txMsgs: diagnostics.txMsgsPerSec.toFixed(1),
      rxRate: formatByteRate(diagnostics.rxBytesPerSec),
      rxMsgs: diagnostics.rxMsgsPerSec.toFixed(1),
    }
  );
  const queueLine = translateStatic('Tile queue: {queue} · Dropped ephemeral: {dropped}', {
    queue: diagnostics.tileQueueDepth,
    dropped: diagnostics.droppedEphemeralCount,
  });
  const lines = [transportLine, pingLine, throughputLine, queueLine];
  if (diagnostics.lastAuditAt !== null) {
    const auditLabel =
      diagnostics.lastAuditStatus === 'resyncing'
        ? translateStatic('Resyncing ({count})', { count: diagnostics.auditResyncCount })
        : diagnostics.auditResyncCount > 0
          ? translateStatic('OK ({count} healed)', { count: diagnostics.auditResyncCount })
          : translateStatic('OK');
    lines.push(translateStatic('Sync audit: {status}', { status: auditLabel }));
  }
  return lines.join('\n');
}

function formatChatTime(ts: number): string {
  try {
    const d = new Date(ts);
    const hh = String(d.getHours()).padStart(2, '0');
    const mm = String(d.getMinutes()).padStart(2, '0');
    return `${hh}:${mm}`;
  } catch {
    return '';
  }
}

export const CollabRoomOverlay: React.FC<CollabRoomOverlayProps> = React.memo(
  ({
    isConnected,
    isReconnecting = false,
    myRole = 'editor',
    hostInfo,
    myPeer,
    peers,
    chatMessages,
    unreadChatCount,
    onSendChatMessage,
    onChatVisibilityChange,
    followingPeerId,
    onToggleFollowPeer,
    onStopFollowing,
    grabbingPeerId,
    onGrabPeerBrush,
    onTrySharedBrush,
    onShareMyBrush,
    activeGrabbedBrush,
    onSaveGrabbedBrush,
    onDismissGrabbedBrush,
    onOpenHostModal,
    diagnostics = null,
    isWebtoonMode = false,
  }) => {
    const { t, td } = useI18n();
    const [isMinimized, setIsMinimized] = useState(false);
    const [activeTab, setActiveTab] = useState<'participants' | 'chat'>('participants');
    const [chatDraft, setChatDraft] = useState('');

    const chatEndRef = useRef<HTMLDivElement | null>(null);
    const chatInputRef = useRef<HTMLInputElement | null>(null);

    const isVisible = isConnected || isReconnecting;
    const isChatCurrentlyOpen = isVisible && !isMinimized && activeTab === 'chat';

    useEffect(() => {
      onChatVisibilityChange?.(isChatCurrentlyOpen);
      return () => {
        onChatVisibilityChange?.(false);
      };
    }, [isChatCurrentlyOpen, onChatVisibilityChange]);

    // Auto-scroll to newest chat message while chat tab is open
    useEffect(() => {
      if (isChatCurrentlyOpen && chatEndRef.current && typeof chatEndRef.current.scrollIntoView === 'function') {
        chatEndRef.current.scrollIntoView({ behavior: 'smooth', block: 'end' });
      }
    }, [chatMessages.length, isChatCurrentlyOpen]);

    if (!isVisible) return null;

    const followingPeer =
      followingPeerId !== null
        ? peers.find((p) => peerIdEquals(p.id, followingPeerId)) || null
        : null;

    const formatRoleLabel = (role?: string, isPeerHost?: boolean): string => {
      if (isPeerHost || role === 'host') return t('Host');
      if (role === 'viewer') return t('Viewer');
      return t('Editor');
    };

    const roomTitle = hostInfo?.roomName || t('Collab Room');
    const totalCount = peers.length + 1;
    const topOffsetClass = isWebtoonMode ? 'top-12' : 'top-3';

    const showNetworkPill = Boolean(diagnostics && isConnected);
    const networkTransportLabel =
      diagnostics?.transport === 'webrtc' ||
      (!diagnostics?.transport && hostInfo?.transport === 'webrtc')
        ? diagnostics?.iceCandidateType === 'relay'
          ? 'RELAY'
          : 'P2P'
        : 'WS';
    const networkPingLabel =
      diagnostics && diagnostics.rttMs !== null ? `${Math.round(diagnostics.rttMs)}ms` : '--';
    const networkQualityDotClass =
      !diagnostics || diagnostics.rttMs === null
        ? 'bg-ui-muted'
        : diagnostics.rttMs <= 80
          ? 'bg-ui-success'
          : diagnostics.rttMs <= 180
            ? 'bg-ui-warning'
            : 'bg-ui-danger';
    const networkTooltip =
      diagnostics ? buildDiagnosticsTooltip(diagnostics, hostInfo) : undefined;

    const handleSendSubmit = (e: React.FormEvent) => {
      e.preventDefault();
      const trimmed = chatDraft.trim();
      if (!trimmed || !isConnected) return;
      if (onSendChatMessage(trimmed)) {
        setChatDraft('');
      }
    };

    const handleChatInputKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
      if (isImeComposing(e)) {
        if (e.key === 'Enter') {
          e.preventDefault();
        }
        e.stopPropagation();
        return;
      }
      if (e.key === 'Escape') {
        e.preventDefault();
        e.stopPropagation();
        chatInputRef.current?.blur();
        return;
      }
      // Keep single-key drawing/navigation shortcuts from firing while typing in room chat
      e.stopPropagation();
    };

    return (
      <>
        {/* Subtle Viewport Frame Halo & Top-Center Banner while Following a Participant's Camera */}
        {followingPeer && (
          <>
            <div
              data-testid="collab-follow-frame"
              className="pointer-events-none absolute inset-0 z-30 border-2 transition-colors"
              style={{ borderColor: `${followingPeer.color}88` }}
            />
            <div
              data-testid="collab-follow-banner"
              className="absolute top-3 left-1/2 -translate-x-1/2 z-35 flex items-center gap-2 rounded-full border border-ui-default bg-ui-floating px-3 py-1.5 text-[11px] text-ui-primary shadow-ui-floating select-none"
              onPointerDown={(e) => e.stopPropagation()}
            >
              <span
                className="w-2 h-2 rounded-full shrink-0 animate-pulse"
                style={{ backgroundColor: followingPeer.color }}
              />
              <Eye className="w-3.5 h-3.5 text-ui-accent shrink-0" />
              <span className="font-medium whitespace-nowrap">
                {t("Following {name}'s camera", { name: followingPeer.name })}
              </span>
              <span className="text-[10px] text-ui-muted hidden sm:inline whitespace-nowrap">
                {t('· Pan/zoom to exit')}
              </span>
              <button
                type="button"
                data-testid="collab-stop-follow-btn"
                onClick={onStopFollowing}
                className="ml-1 rounded-full bg-ui-control hover:bg-ui-control-hover border border-ui-subtle px-2 py-0.5 text-[10px] font-medium text-ui-primary transition-colors cursor-pointer"
              >
                {t('Stop')}
              </button>
            </div>
          </>
        )}

        {/* Floating Room Overlay (Participants, Follow Camera, Grab Brush, Built-in Text Chat) */}
        <aside
          data-testid="collab-room-overlay"
          data-collab-overlay="true"
          onPointerDown={(e) => e.stopPropagation()}
          onContextMenu={(e) => e.stopPropagation()}
          className={`absolute ${topOffsetClass} right-3 z-35 select-none`}
        >
          {isMinimized ? (
            <div
              data-testid="collab-room-pill"
              className="flex items-center gap-1.5 rounded-full border border-ui-default bg-ui-floating px-2.5 py-1.5 text-[11px] text-ui-primary shadow-ui-floating"
            >
              <span
                className={`w-2 h-2 rounded-full shrink-0 ${
                  isReconnecting ? 'bg-ui-warning animate-pulse' : 'bg-ui-success'
                }`}
              />
              <button
                type="button"
                onClick={() => setIsMinimized(false)}
                className="max-w-28 truncate font-medium text-ui-primary hover:opacity-90 cursor-pointer"
                title={t('Expand Room Overlay')}
              >
                {roomTitle}
              </button>
              <button
                type="button"
                onClick={() => {
                  setActiveTab('participants');
                  setIsMinimized(false);
                }}
                title={t('Show Participants')}
                className="flex items-center gap-1 rounded-full bg-ui-control hover:bg-ui-control-hover border border-ui-subtle px-1.5 py-0.5 text-[10px] font-ui-mono tabular-nums text-ui-primary transition-colors cursor-pointer"
              >
                <Users className="w-3 h-3 text-ui-accent" />
                <span>{totalCount}</span>
              </button>
              <button
                type="button"
                data-testid="collab-pill-chat-btn"
                onClick={() => {
                  setActiveTab('chat');
                  setIsMinimized(false);
                }}
                title={t('Open Room Chat')}
                className="relative flex items-center gap-1 rounded-full bg-ui-control hover:bg-ui-control-hover border border-ui-subtle px-1.5 py-0.5 text-[10px] text-ui-primary transition-colors cursor-pointer"
              >
                <MessageSquare className="w-3 h-3" />
                {unreadChatCount > 0 && (
                  <span
                    data-testid="collab-unread-badge"
                    className="rounded-full bg-ui-accent text-ui-accent-contrast px-1 text-[9px] font-ui-mono tabular-nums font-bold leading-tight"
                  >
                    {unreadChatCount > 99 ? '99+' : unreadChatCount}
                  </span>
                )}
              </button>
              {showNetworkPill && (
                <span
                  data-testid="collab-network-pill"
                  title={networkTooltip}
                  className="inline-flex items-center gap-1 rounded-full bg-ui-control border border-ui-subtle px-1.5 py-0.5 text-[9px] font-ui-mono tabular-nums text-ui-muted"
                >
                  <span className={`w-1.5 h-1.5 rounded-full shrink-0 ${networkQualityDotClass}`} />
                  <span>{networkPingLabel}</span>
                </span>
              )}
              <button
                type="button"
                data-testid="collab-expand-btn"
                onClick={() => setIsMinimized(false)}
                aria-label={t('Expand Room Overlay')}
                title={t('Expand Room Overlay')}
                className="w-5 h-5 rounded-full flex items-center justify-center text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover transition-colors cursor-pointer"
              >
                <ChevronDown className="w-3.5 h-3.5" />
              </button>
            </div>
          ) : (
            <div className="w-72 rounded-ui-lg border border-ui-default bg-ui-floating text-ui-primary shadow-ui-popover overflow-hidden flex flex-col">
              {/* Overlay Header */}
              <div className="h-9 px-2.5 flex items-center justify-between gap-2 border-b border-ui-subtle bg-ui-header">
                <div className="flex items-center gap-2 min-w-0">
                  <span
                    className={`w-2 h-2 rounded-full shrink-0 ${
                      isReconnecting ? 'bg-ui-warning animate-pulse' : 'bg-ui-success'
                    }`}
                  />
                  <span className="text-[11px] font-semibold text-ui-primary truncate">
                    {isReconnecting ? t('Reconnecting...') : roomTitle}
                  </span>
                  <span className="text-[9px] font-ui-mono uppercase px-1.5 py-0.5 rounded-ui-xs bg-ui-control border border-ui-subtle text-ui-muted shrink-0">
                    {formatRoleLabel(myRole)}
                  </span>
                </div>
                <div className="flex items-center gap-0.5 shrink-0">
                  {showNetworkPill && (
                    <span
                      data-testid="collab-network-pill"
                      title={networkTooltip}
                      className="mr-0.5 inline-flex items-center gap-1 rounded-ui-xs bg-ui-control border border-ui-subtle px-1.5 py-0.5 text-[9px] font-ui-mono tabular-nums text-ui-muted"
                    >
                      <span
                        className={`w-1.5 h-1.5 rounded-full shrink-0 ${networkQualityDotClass}`}
                      />
                      <span>{networkTransportLabel}</span>
                      <span className="text-ui-primary">{networkPingLabel}</span>
                    </span>
                  )}
                  <button
                    type="button"
                    onClick={onOpenHostModal}
                    title={t('Room Settings & Invite Link')}
                    aria-label={t('Room Settings & Invite Link')}
                    className="w-6 h-6 rounded-ui-xs flex items-center justify-center text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover transition-colors cursor-pointer"
                  >
                    <Settings2 className="w-3.5 h-3.5" />
                  </button>
                  <button
                    type="button"
                    data-testid="collab-minimize-btn"
                    onClick={() => setIsMinimized(true)}
                    title={t('Minimize Room Overlay')}
                    aria-label={t('Minimize Room Overlay')}
                    className="w-6 h-6 rounded-ui-xs flex items-center justify-center text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover transition-colors cursor-pointer"
                  >
                    <ChevronUp className="w-3.5 h-3.5" />
                  </button>
                </div>
              </div>

              {/* Active Grabbed Brush Banner (1-Click Save to Custom Brushes) */}
              {activeGrabbedBrush && (
                <div
                  data-testid="collab-active-grabbed-brush"
                  className="px-2.5 py-1.5 bg-ui-accent-subtle border-b border-ui-accent-border flex items-center justify-between gap-2 text-[10px]"
                >
                  <div className="flex items-center gap-1.5 min-w-0">
                    <Paintbrush className="w-3 h-3 text-ui-accent shrink-0" />
                    <span className="truncate text-ui-primary">
                      {t("Trying {peerName}'s {brushName}", {
                        peerName: activeGrabbedBrush.peerName,
                        brushName: td(activeGrabbedBrush.brushName),
                      })}
                    </span>
                  </div>
                  <div className="flex items-center gap-1 shrink-0">
                    <button
                      type="button"
                      data-testid="collab-save-grabbed-brush-btn"
                      onClick={onSaveGrabbedBrush}
                      title={t('Save this brush permanently to your Custom Brushes')}
                      className="flex items-center gap-1 rounded-ui-xs bg-ui-accent text-ui-accent-contrast hover:opacity-90 px-1.5 py-0.5 text-[10px] font-medium transition-opacity cursor-pointer"
                    >
                      <BookmarkPlus className="w-3 h-3" />
                      <span>{t('Save')}</span>
                    </button>
                    <button
                      type="button"
                      onClick={onDismissGrabbedBrush}
                      aria-label={t('Dismiss grabbed brush banner')}
                      className="p-0.5 rounded-ui-xs text-ui-icon-muted hover:text-ui-primary cursor-pointer"
                    >
                      <X className="w-3 h-3" />
                    </button>
                  </div>
                </div>
              )}

              {/* Tab Bar: Participants & Built-in Text Chat */}
              <div className="grid grid-cols-2 border-b border-ui-subtle bg-ui-input p-0.5 gap-0.5">
                <button
                  type="button"
                  data-testid="collab-tab-participants"
                  onClick={() => setActiveTab('participants')}
                  className={`flex items-center justify-center gap-1.5 rounded-ui-xs py-1.5 text-[11px] font-medium transition-colors cursor-pointer ${
                    activeTab === 'participants'
                      ? 'bg-ui-control-active text-ui-primary'
                      : 'text-ui-muted hover:text-ui-primary'
                  }`}
                >
                  <Users className="w-3.5 h-3.5" />
                  <span className="tabular-nums">
                    {t('Participants ({count})', { count: totalCount })}
                  </span>
                </button>
                <button
                  type="button"
                  data-testid="collab-tab-chat"
                  onClick={() => setActiveTab('chat')}
                  className={`flex items-center justify-center gap-1.5 rounded-ui-xs py-1.5 text-[11px] font-medium transition-colors cursor-pointer ${
                    activeTab === 'chat'
                      ? 'bg-ui-control-active text-ui-primary'
                      : 'text-ui-muted hover:text-ui-primary'
                  }`}
                >
                  <MessageSquare className="w-3.5 h-3.5" />
                  <span>{t('Chat')}</span>
                  {unreadChatCount > 0 && (
                    <span
                      data-testid="collab-unread-badge"
                      className="rounded-full bg-ui-accent text-ui-accent-contrast px-1.5 text-[9px] font-ui-mono tabular-nums font-bold leading-4"
                    >
                      {unreadChatCount > 99 ? '99+' : unreadChatCount}
                    </span>
                  )}
                </button>
              </div>

              {/* Tab Content */}
              {activeTab === 'participants' ? (
                <div className="max-h-64 overflow-y-auto divide-y divide-ui-subtle">
                  {/* Local User Row + Quick Share Brush */}
                  <div className="flex items-center justify-between gap-2 px-2.5 py-2 bg-ui-panel">
                    <div className="flex items-center gap-2 min-w-0">
                      <span
                        className="w-2.5 h-2.5 rounded-full shrink-0"
                        style={{ backgroundColor: myPeer.color }}
                      />
                      <div className="min-w-0">
                        <div className="text-[11px] font-medium text-ui-primary truncate">
                          {t('{name} (You)', { name: myPeer.name })}
                        </div>
                        <div className="text-[9px] text-ui-muted">{formatRoleLabel(myRole)}</div>
                      </div>
                    </div>
                    <button
                      type="button"
                      data-testid="collab-share-my-brush-btn"
                      onClick={onShareMyBrush}
                      disabled={!isConnected}
                      title={t('Share your active brush (tip & texture) with everyone in the room')}
                      className="flex items-center gap-1 rounded-ui-xs border border-ui-default bg-ui-control hover:bg-ui-control-hover hover:border-ui-strong disabled:opacity-40 px-2 py-1 text-[10px] font-medium text-ui-primary transition-colors shrink-0 cursor-pointer"
                    >
                      <Share2 className="w-3 h-3 text-ui-accent" />
                      <span>{t('Share Brush')}</span>
                    </button>
                  </div>

                  {/* Remote Participants (Click to Follow Camera + 1-Click Grab Brush) */}
                  {peers.length === 0 ? (
                    <div className="px-3 py-5 text-center space-y-2">
                      <p className="text-[11px] text-ui-muted">
                        {t('Waiting for other artists to join...')}
                      </p>
                      <button
                        type="button"
                        onClick={onOpenHostModal}
                        className="rounded-ui-xs border border-ui-default bg-ui-control hover:bg-ui-control-hover px-2.5 py-1 text-[10px] font-medium text-ui-primary transition-colors cursor-pointer"
                      >
                        {t('Copy Invite Link / Code')}
                      </button>
                    </div>
                  ) : (
                    peers.map((peer) => {
                      const isFollowing =
                        followingPeerId !== null && peerIdEquals(followingPeerId, peer.id);
                      const isGrabbing =
                        grabbingPeerId !== null && peerIdEquals(grabbingPeerId, peer.id);
                      const peerRoleLabel = formatRoleLabel(peer.role, peer.isHost);

                      return (
                        <div
                          key={peer.id}
                          data-testid={`collab-participant-row-${peer.id}`}
                          className={`flex items-center justify-between gap-1.5 px-2.5 py-2 transition-colors ${
                            isFollowing ? 'bg-ui-accent-subtle' : 'hover:bg-ui-control-hover'
                          }`}
                        >
                          {/* Clicking participant toggles Follow Camera */}
                          <button
                            type="button"
                            data-testid={`collab-follow-peer-${peer.id}`}
                            onClick={() => onToggleFollowPeer(peer.id)}
                            disabled={!isConnected}
                            title={
                              isFollowing
                                ? t("Stop following {name}'s camera", { name: peer.name })
                                : t("Click to follow {name}'s camera in real time", {
                                    name: peer.name,
                                  })
                            }
                            className="flex-1 min-w-0 flex items-center gap-2 text-left rounded-ui-xs py-0.5 px-1 -ml-1 hover:bg-ui-control-hover transition-colors cursor-pointer disabled:opacity-50"
                          >
                            <div className="relative shrink-0">
                              <span
                                className="block w-2.5 h-2.5 rounded-full"
                                style={{ backgroundColor: peer.color }}
                              />
                              {peer.isDrawing && (
                                <span className="absolute -top-0.5 -right-0.5 w-1.5 h-1.5 rounded-full bg-ui-primary animate-ping" />
                              )}
                            </div>
                            <div className="min-w-0 flex-1">
                              <div className="flex items-center gap-1.5">
                                <span className="text-[11px] font-medium text-ui-primary truncate">
                                  {peer.name}
                                </span>
                                <span className="text-[9px] font-ui-mono text-ui-muted shrink-0">
                                  {peerRoleLabel}
                                </span>
                              </div>
                              <div className="flex items-center gap-1 text-[9px] truncate">
                                {isFollowing ? (
                                  <span className="text-ui-accent font-medium flex items-center gap-1">
                                    <Eye className="w-2.5 h-2.5 shrink-0" />
                                    <span>{t('Following camera')}</span>
                                  </span>
                                ) : peer.activeBrushName ? (
                                  <span className="text-ui-muted truncate">
                                    {t('{brush} · Click to follow', {
                                      brush: td(peer.activeBrushName),
                                    })}
                                  </span>
                                ) : (
                                  <span className="text-ui-muted flex items-center gap-1">
                                    <Eye className="w-2.5 h-2.5 shrink-0 opacity-70" />
                                    <span>{t('Follow camera')}</span>
                                  </span>
                                )}
                              </div>
                            </div>
                          </button>

                          {/* 1-Click "Try This User's Brush" Button */}
                          <button
                            type="button"
                            data-testid={`collab-grab-brush-${peer.id}`}
                            onClick={(e) => {
                              e.stopPropagation();
                              onGrabPeerBrush(peer.id);
                            }}
                            disabled={!isConnected || isGrabbing}
                            title={t("Try {name}'s Brush", { name: peer.name })}
                            aria-label={t("Try {name}'s Brush", { name: peer.name })}
                            className="flex items-center gap-1 rounded-ui-xs border border-ui-default bg-ui-control hover:bg-ui-control-hover hover:border-ui-accent-border disabled:opacity-50 px-2 py-1 text-[10px] font-medium text-ui-primary transition-colors shrink-0 cursor-pointer"
                          >
                            {isGrabbing ? (
                              <Loader2 className="w-3 h-3 animate-spin text-ui-accent" />
                            ) : (
                              <Paintbrush className="w-3 h-3 text-ui-accent" />
                            )}
                            <span>{t('Try Brush')}</span>
                          </button>
                        </div>
                      );
                    })
                  )}
                </div>
              ) : (
                /* Built-in Room Text Chat */
                <div className="flex flex-col">
                  <div
                    data-testid="collab-chat-messages"
                    className="h-56 overflow-y-auto px-2.5 py-2 space-y-2 bg-ui-input"
                  >
                    {chatMessages.length === 0 ? (
                      <div className="h-full flex flex-col items-center justify-center text-center px-4 text-ui-muted space-y-1">
                        <MessageSquare className="w-5 h-5 opacity-40" />
                        <p className="text-[11px]">{t('No messages yet')}</p>
                        <p className="text-[10px] text-ui-muted opacity-80">
                          {t('Chat with desktop & browser guests right here on the canvas.')}
                        </p>
                      </div>
                    ) : (
                      chatMessages.map((msg) => (
                        <div
                          key={msg.id}
                          data-testid="collab-chat-message-item"
                          className={`rounded-ui-md px-2.5 py-1.5 text-[11px] ${
                            msg.isLocal
                              ? 'bg-ui-accent-subtle border border-ui-accent-border'
                              : 'bg-ui-panel border border-ui-subtle'
                          }`}
                        >
                          <div className="flex items-center justify-between gap-2 mb-0.5">
                            <div className="flex items-center gap-1.5 min-w-0">
                              <span
                                className="w-2 h-2 rounded-full shrink-0"
                                style={{ backgroundColor: msg.senderColor }}
                              />
                              <span className="font-semibold text-[10px] text-ui-primary truncate">
                                {msg.isLocal
                                  ? t('{name} (You)', { name: msg.senderName })
                                  : msg.senderName}
                              </span>
                            </div>
                            <span className="text-[9px] font-ui-mono tabular-nums text-ui-muted shrink-0">
                              {formatChatTime(msg.timestamp)}
                            </span>
                          </div>
                          {msg.sharedBrush ? (
                            <div className="mt-1 flex items-center justify-between gap-2 rounded-ui-xs bg-ui-input border border-ui-subtle px-2 py-1.5">
                              <div className="flex items-center gap-1.5 min-w-0">
                                <Paintbrush className="w-3.5 h-3.5 text-ui-accent shrink-0" />
                                <span className="text-[11px] font-medium text-ui-primary truncate">
                                  {td(msg.sharedBrush.brushName)}
                                </span>
                              </div>
                              {!msg.isLocal && (
                                <button
                                  type="button"
                                  data-testid={`collab-chat-try-brush-${msg.id}`}
                                  onClick={() => onTrySharedBrush(msg.sharedBrush!)}
                                  className="rounded-ui-xs bg-ui-accent text-ui-accent-contrast hover:opacity-90 px-2 py-0.5 text-[10px] font-medium shrink-0 transition-opacity cursor-pointer"
                                >
                                  {t('Try Brush')}
                                </button>
                              )}
                            </div>
                          ) : (
                            <p className="text-ui-primary leading-snug break-words whitespace-pre-wrap select-text">
                              {msg.text}
                            </p>
                          )}
                        </div>
                      ))
                    )}
                    <div ref={chatEndRef} />
                  </div>

                  {/* Chat Composer */}
                  <form
                    onSubmit={handleSendSubmit}
                    className="p-2 border-t border-ui-subtle bg-ui-header flex items-center gap-1.5"
                  >
                    <input
                      ref={chatInputRef}
                      type="text"
                      data-testid="collab-chat-input"
                      value={chatDraft}
                      onChange={(e) => setChatDraft(e.target.value)}
                      onKeyDown={handleChatInputKeyDown}
                      disabled={!isConnected}
                      maxLength={1000}
                      placeholder={isConnected ? t('Message room...') : t('Reconnecting...')}
                      className="flex-1 min-w-0 rounded-ui-sm border border-ui-default bg-ui-input px-2.5 py-1.5 text-[11px] text-ui-primary placeholder:text-ui-muted focus:border-ui-focus focus:outline-hidden disabled:opacity-50"
                    />
                    <button
                      type="button"
                      onClick={onShareMyBrush}
                      disabled={!isConnected}
                      title={t('Share your current brush to chat')}
                      aria-label={t('Share your current brush to chat')}
                      className="w-7 h-7 rounded-ui-sm border border-ui-subtle bg-ui-control hover:bg-ui-control-hover disabled:opacity-40 flex items-center justify-center text-ui-icon-muted hover:text-ui-accent transition-colors shrink-0 cursor-pointer"
                    >
                      <Paintbrush className="w-3.5 h-3.5" />
                    </button>
                    <button
                      type="submit"
                      data-testid="collab-chat-send-btn"
                      disabled={!isConnected || !chatDraft.trim()}
                      title={t('Send message (Enter)')}
                      aria-label={t('Send message')}
                      className="w-7 h-7 rounded-ui-sm bg-ui-accent text-ui-accent-contrast hover:opacity-90 disabled:opacity-40 flex items-center justify-center transition-opacity shrink-0 cursor-pointer"
                    >
                      <Send className="w-3.5 h-3.5" />
                    </button>
                  </form>
                </div>
              )}
            </div>
          )}
        </aside>
      </>
    );
  }
);

CollabRoomOverlay.displayName = 'CollabRoomOverlay';