Skip to content

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

55.9 KB
Raw Blame
import React, { useState, useEffect, useMemo, useRef } from 'react';
import {
  SessionHostInfo,
  CollabPeer,
  CollabRole,
  ConnectionStatus,
} from '../types/multiplayer';
import { parseCollabTarget } from '../services/multiplayerService';
import { MAX_WEBRTC_PEERS } from '../services/webrtcHostHub';
import {
  Users,
  Copy,
  Check,
  Power,
  Wifi,
  Shield,
  X,
  User,
  Globe,
  Loader2,
  Link2,
  LogOut,
  AlertTriangle,
  Ban,
  UserX,
  RefreshCw,
  Radio,
  Eye,
  Paintbrush,
} from 'lucide-react';
import { peerIdEquals } from '../utils/collabPermissions';
import { isImeComposing, t as translateStatic, useI18n } from '../i18n';

interface HostModalProps {
  isOpen: boolean;
  onClose: () => void;
  isHost: boolean;
  isConnected: boolean;
  connectionStatus?: ConnectionStatus;
  reconnectAttempt?: number;
  myRole?: CollabRole;
  hostInfo: SessionHostInfo | null;
  peers: CollabPeer[];
  bannedPeerIds?: string[];
  myPeer: CollabPeer;
  onUpdateMyName: (name: string) => void;
  onStartHosting: (
    roomName: string,
    port: number,
    hostNickname?: string,
    isGlobal?: boolean,
    onStatus?: (status: string) => void
  ) => Promise<any>;
  onStartWebRtcHosting?: (
    roomName: string,
    hostNickname?: string,
    onStatus?: (status: string) => void
  ) => Promise<any>;
  onStopHosting: () => void;
  onJoinByInviteUrl: (
    rawUrl: string,
    nickname?: string,
    persistName?: boolean,
    secretOverride?: string
  ) => Promise<boolean>;
  onLeaveRoom: () => void;
  onSetPeerRole?: (peerId: string | number, role: 'editor' | 'viewer') => void;
  onKickPeer?: (peerId: string | number) => void;
  onBanPeer?: (peerId: string | number) => void;
  onUnbanPeer?: (peerId: string | number) => void;
  followingPeerId?: string | number | null;
  onToggleFollowPeer?: (peerId: string | number) => void;
  grabbingPeerId?: string | number | null;
  onGrabPeerBrush?: (peerId: string | number) => void;
  showToast: (msg: string) => void;
}

function defaultStudioName(name: string): string {
  const clean = (name || '').trim();
  return clean
    ? translateStatic("{name}'s Studio", { name: clean })
    : translateStatic('Ink Studio Session');
}

export const HostModal: React.FC<HostModalProps> = ({
  isOpen,
  onClose,
  isHost,
  isConnected,
  connectionStatus = isConnected ? 'connected' : 'disconnected',
  reconnectAttempt = 0,
  myRole = isHost ? 'host' : 'editor',
  hostInfo,
  peers,
  bannedPeerIds = [],
  myPeer,
  onUpdateMyName,
  onStartHosting,
  onStartWebRtcHosting,
  onStopHosting,
  onJoinByInviteUrl,
  onLeaveRoom,
  onSetPeerRole,
  onKickPeer,
  onBanPeer,
  onUnbanPeer,
  followingPeerId = null,
  onToggleFollowPeer,
  grabbingPeerId = null,
  onGrabPeerBrush,
  showToast,
}) => {
  const { t, td } = useI18n();
  const [activeTab, setActiveTab] = useState<'host' | 'join'>('host');
  const [nickname, setNickname] = useState(myPeer.name || 'Artist');
  const [roomName, setRoomName] = useState(() => defaultStudioName(myPeer.name));
  const [port, setPort] = useState(30303);
  const [hostMode, setHostMode] = useState<'p2p' | 'tunnel' | 'lan'>(() =>
    onStartWebRtcHosting ? 'p2p' : 'tunnel'
  );
  const [joinUrl, setJoinUrl] = useState('');
  const [manualSecret, setManualSecret] = useState('');
  const [copied, setCopied] = useState(false);
  const [copiedCode, setCopiedCode] = useState(false);
  const [copiedLocal, setCopiedLocal] = useState(false);
  const [isStarting, setIsStarting] = useState(false);
  const [isJoining, setIsJoining] = useState(false);
  const [startStatus, setStartStatus] = useState('');
  const [startError, setStartError] = useState<string | null>(null);

  const nicknameEditedRef = useRef(false);
  const roomNameEditedRef = useRef(false);

  const parsedJoinTarget = useMemo(() => {
    const trimmed = joinUrl.trim();
    if (!trimmed) return null;
    return parseCollabTarget(trimmed);
  }, [joinUrl]);

  const isP2pSession = hostInfo?.transport === 'webrtc';

  // Sync nickname & default room name when OS username resolves or Preferences changes
  useEffect(() => {
    if (!nicknameEditedRef.current && myPeer.name) {
      setNickname(myPeer.name);
    }
    if (!roomNameEditedRef.current && myPeer.name) {
      setRoomName(defaultStudioName(myPeer.name));
    }
  }, [myPeer.name]);

  // Reset transient error and default to P2P mode whenever modal opens
  useEffect(() => {
    if (isOpen) {
      setStartError(null);
      setHostMode(onStartWebRtcHosting ? 'p2p' : 'tunnel');
    }
  }, [isOpen, onStartWebRtcHosting]);

  // Escape key closes modal
  useEffect(() => {
    if (!isOpen) return;
    const handleKeyDown = (e: KeyboardEvent) => {
      if (isImeComposing(e)) return;
      if (e.key === 'Escape') {
        e.preventDefault();
        e.stopPropagation();
        onClose();
      }
    };
    window.addEventListener('keydown', handleKeyDown, true);
    return () => window.removeEventListener('keydown', handleKeyDown, true);
  }, [isOpen, onClose]);

  if (!isOpen) return 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 handleCopyLink = async () => {
    if (!hostInfo?.inviteUrl) return;
    try {
      await navigator.clipboard.writeText(hostInfo.inviteUrl);
      setCopied(true);
      showToast(t('Invite link copied.'));
      setTimeout(() => setCopied(false), 2000);
    } catch {
      showToast(t('Failed to copy to clipboard.'));
    }
  };

  const handleCopyCode = async () => {
    const code = hostInfo?.joinCode || hostInfo?.roomCode;
    if (!code) return;
    try {
      await navigator.clipboard.writeText(code);
      setCopiedCode(true);
      showToast(t('Room code copied.'));
      setTimeout(() => setCopiedCode(false), 2000);
    } catch {
      showToast(t('Failed to copy to clipboard.'));
    }
  };

  const handleCopyLocalLink = async () => {
    if (!hostInfo?.localInviteUrl) return;
    try {
      await navigator.clipboard.writeText(hostInfo.localInviteUrl);
      setCopiedLocal(true);
      showToast(t('Local LAN link copied.'));
      setTimeout(() => setCopiedLocal(false), 2000);
    } catch {
      showToast(t('Failed to copy to clipboard.'));
    }
  };

  const handleStart = async (overrideMode?: 'tunnel' | 'p2p' | 'lan') => {
    const mode = overrideMode ?? hostMode;
    setIsStarting(true);
    setStartError(null);
    setStartStatus(
      mode === 'p2p'
        ? t('Opening Quick P2P Room...')
        : mode === 'tunnel'
          ? t('Starting Worldwide Tunnel...')
          : t('Starting Local Server...')
    );
    try {
      const resolvedName = nickname.trim() || myPeer.name || 'Artist';
      if (nicknameEditedRef.current && resolvedName !== myPeer.name) {
        onUpdateMyName(resolvedName);
      }
      const resolvedRoom = roomName.trim() || defaultStudioName(resolvedName);
      if (mode === 'p2p') {
        if (!onStartWebRtcHosting) {
          throw new Error(t('Quick P2P hosting is unavailable in this context.'));
        }
        await onStartWebRtcHosting(resolvedRoom, resolvedName, (status) => {
          setStartStatus(status);
        });
      } else {
        await onStartHosting(resolvedRoom, port, resolvedName, mode === 'tunnel', (status) => {
          setStartStatus(status);
        });
      }
    } catch (err: any) {
      const msg = err?.message || (typeof err === 'string' ? err : t('Failed to start server'));
      setStartError(msg);
    } finally {
      setIsStarting(false);
      setStartStatus('');
    }
  };

  const handleJoinSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const trimmedUrl = joinUrl.trim();
    if (!trimmedUrl) {
      showToast(t('Enter a room code (INK-XXXX) or invite link first.'));
      return;
    }
    setIsJoining(true);
    try {
      const resolvedName = nickname.trim() || myPeer.name || 'Artist';
      if (nicknameEditedRef.current && resolvedName !== myPeer.name) {
        onUpdateMyName(resolvedName);
      }
      const extraSecret =
        parsedJoinTarget?.kind === 'p2p' && !parsedJoinTarget.roomSecret
          ? manualSecret.trim() || undefined
          : undefined;
      const ok = extraSecret
        ? await onJoinByInviteUrl(trimmedUrl, resolvedName, nicknameEditedRef.current, extraSecret)
        : await onJoinByInviteUrl(trimmedUrl, resolvedName, nicknameEditedRef.current);
      if (ok) {
        setJoinUrl('');
        setManualSecret('');
        onClose();
      }
    } finally {
      setIsJoining(false);
    }
  };

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-labelledby="host-modal-title"
      className="fixed inset-0 z-50 flex items-center justify-center bg-ui-overlay p-4 select-none"
      onClick={onClose}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        className="relative w-full max-w-md rounded-ui-lg border border-ui-default bg-ui-panel shadow-ui-popover text-ui-primary overflow-hidden"
      >
        {/* Header */}
        <div className="h-11 px-4 flex items-center justify-between border-b border-ui-subtle bg-ui-header">
          <div className="flex items-center gap-2.5 min-w-0">
            <Users className="w-4 h-4 text-ui-accent shrink-0" />
            <div className="min-w-0">
              <h3 id="host-modal-title" className="text-xs font-medium text-ui-primary leading-tight">
                {t('Collaborative Drawing')}
              </h3>
              <p className="text-[10px] text-ui-muted truncate tabular-nums">
                {connectionStatus === 'reconnecting'
                  ? t('Reconnecting (attempt {count})...', { count: reconnectAttempt || 1 })
                  : isConnected
                    ? isHost
                      ? t('Hosting active session')
                      : t('Connected as {role}', {
                          role: myRole === 'viewer' ? t('Viewer (Read-Only)') : t('Editor'),
                        })
                    : t('Host or join a live canvas session')}
              </p>
            </div>
          </div>
          <button
            type="button"
            onClick={onClose}
            aria-label={t('Close')}
            title={t('Cancel (Esc)')}
            className="w-6 h-6 rounded-ui-sm flex items-center justify-center text-ui-muted hover:bg-ui-control-hover hover:text-ui-primary transition-colors cursor-pointer shrink-0"
          >
            <X className="w-3.5 h-3.5" />
          </button>
        </div>

        {/* Content */}
        <div className="p-4 space-y-4">
          {connectionStatus === 'reconnecting' ? (
            <div className="space-y-4">
              <div className="rounded-ui-md border border-ui-warning/40 bg-ui-warning/15 p-3.5 flex items-start space-x-3">
                <RefreshCw className="w-4 h-4 text-ui-warning shrink-0 mt-0.5 animate-spin" />
                <div className="flex-1 min-w-0">
                  <div className="text-xs font-medium text-ui-warning">
                    {t('Reconnecting to Session...')}
                  </div>
                  <div className="text-[11px] text-ui-secondary mt-0.5 truncate tabular-nums">
                    {t('Room: {room} (attempt {count})', {
                      room: hostInfo?.roomName || t('Studio'),
                      count: reconnectAttempt || 1,
                    })}
                  </div>
                  <div className="text-[10px] text-ui-muted mt-1">
                    {t('Session state is preserved. Missed tiles and layer updates will catch up automatically.')}
                  </div>
                </div>
              </div>
              <button
                type="button"
                onClick={() => {
                  if (isHost) {
                    onStopHosting();
                  } else {
                    onLeaveRoom();
                  }
                  onClose();
                }}
                className="w-full flex items-center justify-center gap-2 rounded-ui-sm border border-ui-danger/35 bg-ui-danger/15 hover:bg-ui-danger/25 py-2 text-xs font-medium text-ui-danger transition-colors cursor-pointer"
              >
                <LogOut className="w-3.5 h-3.5" />
                <span>{isHost ? t('Stop Session') : t('Cancel & Leave')}</span>
              </button>
            </div>
          ) : isConnected && isHost ? (
            // Active Host View
            <div className="space-y-4">
              {isP2pSession ? (
                <div className="rounded-ui-md border border-ui-success/35 bg-ui-success/10 p-3.5 flex items-start gap-3">
                  <Radio className="w-4 h-4 text-ui-success shrink-0 mt-0.5" />
                  <div className="flex-1 min-w-0">
                    <div className="text-xs font-medium text-ui-success">
                      {t('Quick P2P Room Active (WebRTC)')}
                    </div>
                    <div className="text-[11px] text-ui-secondary mt-0.5 tabular-nums">
                      {t(
                        'Room: {room} — Android tablets & PCs can join worldwide with the short code below (up to {max} guests).',
                        { room: hostInfo?.roomName || '', max: MAX_WEBRTC_PEERS }
                      )}
                    </div>
                  </div>
                </div>
              ) : hostInfo?.isGlobal ? (
                <div className="rounded-ui-md border border-ui-accent-border bg-ui-header p-3.5 flex items-start gap-3">
                  <Globe className="w-4 h-4 text-ui-accent shrink-0 mt-0.5" />
                  <div className="flex-1 min-w-0">
                    <div className="text-xs font-medium text-ui-primary">
                      {t('Worldwide Cloudflare Tunnel Active')}
                    </div>
                    <div className="text-[11px] text-ui-muted mt-0.5">
                      {t(
                        'Room: {room} — anyone on any network can join via link in browser or desktop app.',
                        { room: hostInfo?.roomName || '' }
                      )}
                    </div>
                  </div>
                </div>
              ) : (
                <div className="rounded-ui-md border border-ui-success/35 bg-ui-success/10 p-3.5 flex items-start gap-3">
                  <Wifi className="w-4 h-4 text-ui-success shrink-0 mt-0.5" />
                  <div className="flex-1 min-w-0">
                    <div className="text-xs font-medium text-ui-success">
                      {t('Local Wi-Fi Server Active')}
                    </div>
                    <div className="text-[11px] text-ui-secondary mt-0.5 tabular-nums">
                      {t('Room: {room} (port {port})', {
                        room: hostInfo?.roomName || '',
                        port: hostInfo?.port ?? 30303,
                      })}
                    </div>
                  </div>
                </div>
              )}

              {/* Shareable Code / Link Box */}
              {isP2pSession ? (
                <div className="space-y-3">
                  <div>
                    <label className="text-[11px] font-medium text-ui-muted mb-1.5 flex items-center justify-between">
                      <span>{t('Quick P2P Room Code (Android & Desktop)')}</span>
                      <span className="text-[10px] text-ui-success font-ui-mono flex items-center gap-1">
                        <span className="w-1.5 h-1.5 rounded-full bg-ui-success animate-pulse" />
                        <span>WEBRTC P2P</span>
                      </span>
                    </label>
                    <div className="flex items-center gap-2">
                      <input
                        type="text"
                        readOnly
                        data-testid="host-p2p-join-code"
                        value={hostInfo?.joinCode || hostInfo?.roomCode || ''}
                        className="flex-1 rounded-ui-sm border border-ui-default bg-ui-input px-3 py-1.5 text-sm font-bold tracking-wider text-ui-primary font-ui-mono tabular-nums select-all focus:outline-hidden"
                      />
                      <button
                        type="button"
                        onClick={handleCopyCode}
                        className="flex items-center gap-1.5 rounded-ui-sm bg-ui-accent text-ui-accent-contrast hover:opacity-90 px-3 py-1.5 text-xs font-medium transition-opacity shrink-0 cursor-pointer"
                      >
                        {copiedCode ? (
                          <Check className="w-3.5 h-3.5" />
                        ) : (
                          <Copy className="w-3.5 h-3.5" />
                        )}
                        <span>{copiedCode ? t('Copied') : t('Copy Code')}</span>
                      </button>
                    </div>
                  </div>

                  {hostInfo?.inviteUrl && (
                    <div className="pt-2 border-t border-ui-subtle flex items-center justify-between text-[10px] text-ui-muted">
                      <span className="truncate">
                        {t('Invite Link: {url}', { url: hostInfo.inviteUrl })}
                      </span>
                      <button
                        type="button"
                        onClick={handleCopyLink}
                        className="text-ui-secondary hover:text-ui-primary underline cursor-pointer ml-2 shrink-0"
                      >
                        {copied ? t('Copied') : t('Copy Link')}
                      </button>
                    </div>
                  )}

                  <p className="text-[10px] text-ui-muted leading-relaxed">
                    {t('Share this Room Code with Android tablet or desktop users — no cloudflared required. Keep this app open while hosting.')}
                  </p>
                </div>
              ) : (
                <div>
                  <label className="text-[11px] font-medium text-ui-muted mb-1.5 flex items-center justify-between">
                    <span>
                      {hostInfo?.isGlobal
                        ? t('Worldwide Invite Link (Browser or Desktop App)')
                        : t('Local Wi-Fi Invite Link')}
                    </span>
                    {hostInfo?.isGlobal && (
                      <span className="text-[10px] text-ui-accent font-ui-mono flex items-center gap-1">
                        <span className="w-1.5 h-1.5 rounded-full bg-ui-success animate-pulse" />
                        <span>HTTPS + WSS</span>
                      </span>
                    )}
                  </label>
                  <div className="flex items-center gap-2">
                    <input
                      type="text"
                      readOnly
                      value={hostInfo?.inviteUrl || ''}
                      className="flex-1 rounded-ui-sm border border-ui-default bg-ui-input px-3 py-1.5 text-xs text-ui-primary font-ui-mono select-all focus:outline-hidden"
                    />
                    <button
                      type="button"
                      onClick={handleCopyLink}
                      className="flex items-center gap-1.5 rounded-ui-sm bg-ui-accent text-ui-accent-contrast hover:opacity-90 px-3 py-1.5 text-xs font-medium transition-opacity shrink-0 cursor-pointer"
                    >
                      {copied ? <Check className="w-3.5 h-3.5" /> : <Copy className="w-3.5 h-3.5" />}
                      <span>{copied ? t('Copied') : t('Copy')}</span>
                    </button>
                  </div>

                  {hostInfo?.isGlobal && hostInfo.localInviteUrl && (
                    <div className="mt-2 pt-2 border-t border-ui-subtle flex items-center justify-between text-[10px] text-ui-muted">
                      <span className="truncate">
                        {t('Local LAN: {url}', { url: hostInfo.localInviteUrl })}
                      </span>
                      <button
                        type="button"
                        onClick={handleCopyLocalLink}
                        className="text-ui-secondary hover:text-ui-primary underline cursor-pointer ml-2 shrink-0"
                      >
                        {copiedLocal ? t('Copied') : t('Copy Local')}
                      </button>
                    </div>
                  )}

                  <p className="text-[10px] text-ui-muted mt-1.5 leading-relaxed">
                    {t('Share this link to open directly in a browser or paste it into the Join tab in the desktop app.')}
                  </p>
                </div>
              )}

              {/* Connected Peers List */}
              <div>
                <div className="text-[11px] font-medium text-ui-muted mb-1.5 flex items-center justify-between tabular-nums">
                  <span>{t('Participants on Canvas ({count})', { count: peers.length + 1 })}</span>
                </div>
                <div className="rounded-ui-md border border-ui-subtle bg-ui-header max-h-36 overflow-y-auto divide-y divide-ui-subtle">
                  <div className="flex items-center justify-between px-3 py-2 text-xs">
                    <div className="flex items-center gap-2">
                      <div
                        className="w-2.5 h-2.5 rounded-full shrink-0"
                        style={{ backgroundColor: myPeer.color }}
                      />
                      <span className="font-medium text-ui-primary">
                        {t('{name} (You)', { name: myPeer.name })}
                      </span>
                    </div>
                    <span className="text-[10px] font-ui-mono px-1.5 py-0.5 rounded-ui-xs bg-ui-warning/15 text-ui-warning">
                      {t('Host')}
                    </span>
                  </div>

                  {peers.map((peer) => {
                    const peerRole = peer.role === 'viewer' ? 'viewer' : 'editor';
                    const isFollowing =
                      followingPeerId !== null && peerIdEquals(followingPeerId, peer.id);
                    const isGrabbing =
                      grabbingPeerId !== null && peerIdEquals(grabbingPeerId, peer.id);
                    return (
                      <div
                        key={peer.id}
                        className={`flex items-center justify-between gap-2 px-3 py-2 text-xs ${
                          isFollowing ? 'bg-ui-accent-subtle' : ''
                        }`}
                      >
                        <button
                          type="button"
                          data-testid={`host-modal-follow-peer-${peer.id}`}
                          onClick={() => {
                            if (!onToggleFollowPeer) return;
                            onToggleFollowPeer(peer.id);
                            if (!isFollowing) onClose();
                          }}
                          title={
                            isFollowing
                              ? t("Stop following {name}'s camera", { name: peer.name })
                              : t("Follow {name}'s camera", { name: peer.name })
                          }
                          className="flex items-center gap-2 min-w-0 flex-1 text-left rounded-ui-xs py-0.5 px-1 -ml-1 hover:bg-ui-control-hover/60 transition-colors cursor-pointer"
                        >
                          <div
                            className="w-2.5 h-2.5 rounded-full shrink-0"
                            style={{ backgroundColor: peer.color }}
                          />
                          <div className="min-w-0 flex-1">
                            <div className="flex items-center gap-1.5">
                              <span className="text-ui-primary truncate">{peer.name}</span>
                              {isFollowing && (
                                <Eye className="w-3 h-3 text-ui-accent shrink-0" />
                              )}
                            </div>
                            {peer.activeBrushName && (
                              <div className="text-[10px] text-ui-muted truncate">
                                {td(peer.activeBrushName)}
                              </div>
                            )}
                          </div>
                        </button>
                        <div className="flex items-center gap-1 shrink-0">
                          {onGrabPeerBrush && (
                            <button
                              type="button"
                              data-testid={`host-modal-grab-brush-${peer.id}`}
                              onClick={() => onGrabPeerBrush(peer.id)}
                              disabled={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-1.5 py-0.5 text-[10px] text-ui-secondary hover:text-ui-primary transition-colors 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>
                          )}
                          {onSetPeerRole ? (
                            <select
                              aria-label={t('Role for {name}', { name: peer.name })}
                              value={peerRole}
                              onChange={(e) =>
                                onSetPeerRole(
                                  peer.id,
                                  e.target.value === 'viewer' ? 'viewer' : 'editor'
                                )
                              }
                              className="rounded-ui-xs border border-ui-default bg-ui-input px-1.5 py-0.5 text-[10px] text-ui-primary focus:outline-hidden cursor-pointer"
                            >
                              <option value="editor">{t('Editor')}</option>
                              <option value="viewer">{t('Viewer')}</option>
                            </select>
                          ) : (
                            <span className="text-[10px] font-ui-mono px-1.5 py-0.5 rounded-ui-xs bg-ui-control text-ui-muted">
                              {formatRoleLabel(peerRole)}
                            </span>
                          )}
                          {onKickPeer && (
                            <button
                              type="button"
                              onClick={() => onKickPeer(peer.id)}
                              title={t('Kick {name}', { name: peer.name })}
                              className="p-1 rounded-ui-xs text-ui-muted hover:text-ui-warning hover:bg-ui-warning/15 transition-colors cursor-pointer"
                            >
                              <UserX className="w-3.5 h-3.5" />
                            </button>
                          )}
                          {onBanPeer && (
                            <button
                              type="button"
                              onClick={() => onBanPeer(peer.id)}
                              title={t('Ban {name}', { name: peer.name })}
                              className="p-1 rounded-ui-xs text-ui-muted hover:text-ui-danger hover:bg-ui-danger/15 transition-colors cursor-pointer"
                            >
                              <Ban className="w-3.5 h-3.5" />
                            </button>
                          )}
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>

              {bannedPeerIds.length > 0 && (
                <div>
                  <div className="text-[11px] font-medium text-ui-muted mb-1.5 tabular-nums">
                    {t('Banned Peers ({count})', { count: bannedPeerIds.length })}
                  </div>
                  <div className="rounded-ui-md border border-ui-subtle bg-ui-header max-h-24 overflow-y-auto divide-y divide-ui-subtle">
                    {bannedPeerIds.map((pid) => (
                      <div
                        key={pid}
                        className="flex items-center justify-between px-3 py-1.5 text-[11px]"
                      >
                        <span className="font-ui-mono text-ui-muted truncate">{pid}</span>
                        {onUnbanPeer && (
                          <button
                            type="button"
                            onClick={() => onUnbanPeer(pid)}
                            className="text-[10px] text-ui-accent hover:underline ml-2 shrink-0 cursor-pointer"
                          >
                            {t('Unban')}
                          </button>
                        )}
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Stop Button */}
              <div className="pt-1">
                <button
                  type="button"
                  onClick={() => {
                    onStopHosting();
                    onClose();
                  }}
                  className="w-full flex items-center justify-center gap-2 rounded-ui-sm border border-ui-danger/35 bg-ui-danger/15 hover:bg-ui-danger/25 py-2 text-xs font-medium text-ui-danger transition-colors cursor-pointer"
                >
                  <Power className="w-3.5 h-3.5" />
                  <span>{t('Stop Collaborative Session')}</span>
                </button>
              </div>
            </div>
          ) : isConnected ? (
            // Active Guest View
            <div className="space-y-4">
              <div className="rounded-ui-md border border-ui-accent-border bg-ui-header p-3.5 flex items-start gap-3">
                {isP2pSession ? (
                  <Radio className="w-4 h-4 text-ui-success shrink-0 mt-0.5" />
                ) : (
                  <Globe className="w-4 h-4 text-ui-accent shrink-0 mt-0.5" />
                )}
                <div className="flex-1 min-w-0">
                  <div className="text-xs font-medium text-ui-primary">
                    {isP2pSession ? t('Connected via WebRTC P2P') : t('Connected to Session')}
                  </div>
                  <div className="text-[11px] text-ui-muted mt-0.5 truncate">
                    {t('Room: {room}', { room: hostInfo?.roomName || t('Studio') })}
                  </div>
                  {isP2pSession && hostInfo?.roomCode ? (
                    <div className="text-[10px] text-ui-muted font-ui-mono tabular-nums truncate mt-0.5">
                      {t('Code: {code}', { code: hostInfo.joinCode || hostInfo.roomCode })}
                    </div>
                  ) : (
                    hostInfo?.localIp && (
                      <div className="text-[10px] text-ui-muted font-ui-mono tabular-nums truncate mt-0.5">
                        {hostInfo.localIp}
                      </div>
                    )
                  )}
                </div>
              </div>

              <div>
                <div className="text-[11px] font-medium text-ui-muted mb-1.5 tabular-nums">
                  {t('Participants on Canvas ({count})', { count: peers.length + 1 })}
                </div>
                <div className="rounded-ui-md border border-ui-subtle bg-ui-header max-h-40 overflow-y-auto divide-y divide-ui-subtle">
                  <div className="flex items-center justify-between px-3 py-2 text-xs">
                    <div className="flex items-center gap-2">
                      <div
                        className="w-2.5 h-2.5 rounded-full shrink-0"
                        style={{ backgroundColor: myPeer.color }}
                      />
                      <span className="font-medium text-ui-primary">
                        {t('{name} (You)', { name: myPeer.name })}
                      </span>
                    </div>
                    <span
                      className={`text-[10px] font-ui-mono px-1.5 py-0.5 rounded-ui-xs ${
                        myRole === 'viewer'
                          ? 'bg-ui-control text-ui-muted'
                          : 'bg-ui-success/15 text-ui-success'
                      }`}
                    >
                      {formatRoleLabel(myRole)}
                    </span>
                  </div>
                  {peers.map((peer) => {
                    const isFollowing =
                      followingPeerId !== null && peerIdEquals(followingPeerId, peer.id);
                    const isGrabbing =
                      grabbingPeerId !== null && peerIdEquals(grabbingPeerId, peer.id);
                    return (
                      <div
                        key={peer.id}
                        className={`flex items-center justify-between gap-2 px-3 py-2 text-xs ${
                          isFollowing ? 'bg-ui-accent-subtle' : ''
                        }`}
                      >
                        <button
                          type="button"
                          data-testid={`host-modal-follow-peer-${peer.id}`}
                          onClick={() => {
                            if (!onToggleFollowPeer) return;
                            onToggleFollowPeer(peer.id);
                            if (!isFollowing) onClose();
                          }}
                          title={
                            isFollowing
                              ? t("Stop following {name}'s camera", { name: peer.name })
                              : t("Follow {name}'s camera", { name: peer.name })
                          }
                          className="flex items-center gap-2 min-w-0 flex-1 text-left rounded-ui-xs py-0.5 px-1 -ml-1 hover:bg-ui-control-hover/60 transition-colors cursor-pointer"
                        >
                          <div
                            className="w-2.5 h-2.5 rounded-full shrink-0"
                            style={{ backgroundColor: peer.color }}
                          />
                          <div className="min-w-0 flex-1">
                            <div className="flex items-center gap-1.5">
                              <span className="text-ui-primary truncate">{peer.name}</span>
                              {isFollowing && (
                                <Eye className="w-3 h-3 text-ui-accent shrink-0" />
                              )}
                            </div>
                            {peer.activeBrushName && (
                              <div className="text-[10px] text-ui-muted truncate">
                                {td(peer.activeBrushName)}
                              </div>
                            )}
                          </div>
                        </button>
                        <div className="flex items-center gap-1.5 shrink-0">
                          {onGrabPeerBrush && (
                            <button
                              type="button"
                              data-testid={`host-modal-grab-brush-${peer.id}`}
                              onClick={() => onGrabPeerBrush(peer.id)}
                              disabled={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-1.5 py-0.5 text-[10px] text-ui-secondary hover:text-ui-primary transition-colors 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>
                          )}
                          <span className="text-[10px] font-ui-mono px-1.5 py-0.5 rounded-ui-xs bg-ui-control text-ui-muted">
                            {formatRoleLabel(peer.role, peer.isHost)}
                          </span>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>

              <div className="pt-1">
                <button
                  type="button"
                  onClick={() => {
                    onLeaveRoom();
                    onClose();
                  }}
                  className="w-full flex items-center justify-center gap-2 rounded-ui-sm border border-ui-danger/35 bg-ui-danger/15 hover:bg-ui-danger/25 py-2 text-xs font-medium text-ui-danger transition-colors cursor-pointer"
                >
                  <LogOut className="w-3.5 h-3.5" />
                  <span>{t('Leave Session')}</span>
                </button>
              </div>
            </div>
          ) : (
            // Disconnected: Host / Join Tabs
            <div className="space-y-4">
              <div className="grid grid-cols-2 rounded-ui-md border border-ui-subtle bg-ui-input p-0.5 gap-0.5">
                <button
                  type="button"
                  onClick={() => setActiveTab('host')}
                  className={`rounded-ui-sm py-1.5 text-xs font-medium transition-colors cursor-pointer ${
                    activeTab === 'host'
                      ? 'bg-ui-control-active text-ui-primary'
                      : 'text-ui-muted hover:text-ui-primary'
                  }`}
                >
                  {t('Host Session')}
                </button>
                <button
                  type="button"
                  onClick={() => setActiveTab('join')}
                  className={`rounded-ui-sm py-1.5 text-xs font-medium transition-colors cursor-pointer ${
                    activeTab === 'join'
                      ? 'bg-ui-control-active text-ui-primary'
                      : 'text-ui-muted hover:text-ui-primary'
                  }`}
                >
                  {t('Join Room')}
                </button>
              </div>

              <div>
                <label className="text-[11px] font-medium text-ui-secondary mb-1.5 flex items-center gap-1.5">
                  <User className="w-3.5 h-3.5 text-ui-icon-muted" />
                  <span>{t('Your Nickname')}</span>
                </label>
                <input
                  type="text"
                  value={nickname}
                  onChange={(e) => {
                    nicknameEditedRef.current = true;
                    setNickname(e.target.value);
                  }}
                  maxLength={40}
                  placeholder={t('Your name')}
                  className="w-full rounded-ui-sm border border-ui-default bg-ui-input px-3 py-2 text-xs text-ui-primary placeholder:text-ui-muted/60 focus:border-ui-focus focus:outline-hidden"
                />
              </div>

              {activeTab === 'host' ? (
                <>
                  <div>
                    <label className="block text-[11px] font-medium text-ui-secondary mb-1.5">
                      {t('Room / Canvas Name')}
                    </label>
                    <input
                      type="text"
                      value={roomName}
                      onChange={(e) => {
                        roomNameEditedRef.current = true;
                        setRoomName(e.target.value);
                      }}
                      placeholder={t('Ink Studio Session')}
                      className="w-full rounded-ui-sm border border-ui-default bg-ui-input px-3 py-2 text-xs text-ui-primary placeholder:text-ui-muted/60 focus:border-ui-focus focus:outline-hidden"
                    />
                  </div>

                  {/* Network Mode Switcher */}
                  <div>
                    <label className="block text-[11px] font-medium text-ui-secondary mb-1.5">
                      {t('Connection Mode')}
                    </label>
                    <div className="space-y-2">
                      {onStartWebRtcHosting && (
                        <button
                          type="button"
                          data-testid="host-mode-p2p-btn"
                          aria-pressed={hostMode === 'p2p'}
                          onClick={() => {
                            setHostMode('p2p');
                            setStartError(null);
                          }}
                          className={`w-full flex items-start gap-2.5 rounded-ui-md border p-2.5 text-left transition-colors cursor-pointer ${
                            hostMode === 'p2p'
                              ? 'border-ui-accent-border bg-ui-accent-subtle text-ui-primary'
                              : 'border-ui-subtle bg-ui-header text-ui-muted hover:border-ui-strong hover:text-ui-primary'
                          }`}
                        >
                          <Radio
                            className={`w-4 h-4 shrink-0 mt-0.5 ${hostMode === 'p2p' ? 'text-ui-accent' : 'text-ui-icon-muted'}`}
                          />
                          <div className="min-w-0 flex-1">
                            <div className="flex items-center gap-1.5 flex-wrap">
                              <span className="text-xs font-medium text-ui-primary">
                                {t('Worldwide P2P (Room Code)')}
                              </span>
                              <span className="text-[9px] font-medium px-1.5 py-0.5 rounded-ui-xs bg-ui-success/15 text-ui-success border border-ui-success/30 leading-none">
                                {t('Recommended')}
                              </span>
                            </div>
                            <div className="text-[10px] text-ui-muted mt-0.5">
                              {t('Fast direct INK-XXXX code for PC & Android tablets · No setup')}
                            </div>
                          </div>
                        </button>
                      )}

                      <div className="grid grid-cols-2 gap-2">
                        <button
                          type="button"
                          data-testid="host-mode-tunnel-btn"
                          aria-pressed={hostMode === 'tunnel'}
                          onClick={() => {
                            setHostMode('tunnel');
                            setStartError(null);
                          }}
                          className={`flex items-start gap-2 rounded-ui-md border p-2.5 text-left transition-colors cursor-pointer ${
                            hostMode === 'tunnel'
                              ? 'border-ui-accent-border bg-ui-accent-subtle text-ui-primary'
                              : 'border-ui-subtle bg-ui-header text-ui-muted hover:border-ui-strong hover:text-ui-primary'
                          }`}
                        >
                          <Globe
                            className={`w-4 h-4 shrink-0 mt-0.5 ${hostMode === 'tunnel' ? 'text-ui-accent' : 'text-ui-icon-muted'}`}
                          />
                          <div className="min-w-0">
                            <div className="text-xs font-medium text-ui-primary leading-tight">
                              {t('Web Link (Cloudflare Tunnel)')}
                            </div>
                            <div className="text-[10px] text-ui-muted mt-0.5">
                              {t('Browser guests & up to 16 peers')}
                            </div>
                          </div>
                        </button>

                        <button
                          type="button"
                          data-testid="host-mode-lan-btn"
                          aria-pressed={hostMode === 'lan'}
                          onClick={() => {
                            setHostMode('lan');
                            setStartError(null);
                          }}
                          className={`flex items-start gap-2 rounded-ui-md border p-2.5 text-left transition-colors cursor-pointer ${
                            hostMode === 'lan'
                              ? 'border-ui-accent-border bg-ui-accent-subtle text-ui-primary'
                              : 'border-ui-subtle bg-ui-header text-ui-muted hover:border-ui-strong hover:text-ui-primary'
                          }`}
                        >
                          <Wifi
                            className={`w-4 h-4 shrink-0 mt-0.5 ${hostMode === 'lan' ? 'text-ui-accent' : 'text-ui-icon-muted'}`}
                          />
                          <div className="min-w-0">
                            <div className="text-xs font-medium text-ui-primary leading-tight">
                              {t('Local Network (LAN)')}
                            </div>
                            <div className="text-[10px] text-ui-muted mt-0.5">
                              {t('Same Wi-Fi network')}
                            </div>
                          </div>
                        </button>
                      </div>
                    </div>
                  </div>

                  {hostMode === 'lan' && (
                    <div>
                      <label className="block text-[11px] font-medium text-ui-secondary mb-1.5">
                        {t('Local Port')}
                      </label>
                      <input
                        type="number"
                        value={port}
                        onChange={(e) => setPort(Number(e.target.value))}
                        className="w-full rounded-ui-sm border border-ui-default bg-ui-input px-3 py-2 text-xs text-ui-primary focus:border-ui-focus focus:outline-hidden font-ui-mono tabular-nums"
                      />
                      <p className="text-[10px] text-ui-muted mt-1">
                        {t('Default is 30303. Works over local Wi-Fi or virtual LAN (Tailscale).')}
                      </p>
                    </div>
                  )}

                  {startError && (
                    <div className="rounded-ui-md border border-ui-danger/40 bg-ui-danger/15 p-3 text-[11px] text-ui-danger space-y-2">
                      <div className="flex items-start gap-2">
                        <AlertTriangle className="w-4 h-4 shrink-0 mt-0.5 text-ui-danger" />
                        <span className="break-words">{startError}</span>
                      </div>
                      {hostMode === 'tunnel' && (
                        <div className="flex flex-wrap gap-3">
                          {onStartWebRtcHosting && (
                            <button
                              type="button"
                              onClick={() => {
                                setHostMode('p2p');
                                void handleStart('p2p');
                              }}
                              className="text-[11px] text-ui-primary underline hover:opacity-80 cursor-pointer"
                            >
                              {t('Start Quick P2P Room instead')}
                            </button>
                          )}
                          <button
                            type="button"
                            onClick={() => {
                              setHostMode('lan');
                              void handleStart('lan');
                            }}
                            className="text-[11px] text-ui-primary underline hover:opacity-80 cursor-pointer"
                          >
                            {t('Start Local Wi-Fi Server instead')}
                          </button>
                        </div>
                      )}
                    </div>
                  )}

                  <div className="rounded-ui-md border border-ui-subtle bg-ui-header p-3 text-[11px] text-ui-muted space-y-1">
                    <div className="flex items-center gap-1.5 text-ui-primary font-medium">
                      <Shield className="w-3.5 h-3.5 text-ui-icon-muted" />
                      <span>
                        {hostMode === 'p2p'
                          ? t('Direct Encrypted WebRTC P2P')
                          : hostMode === 'tunnel'
                            ? t('Encrypted Worldwide Tunnel')
                            : t('Local Wi-Fi Access')}
                      </span>
                    </div>
                    <p className="leading-relaxed">
                      {hostMode === 'p2p'
                        ? t(
                            'Generates a short Room Code (INK-XXXX-XXXXXX) with zero server setup or cloudflared download. Android tablets and desktop apps connect directly over WebRTC (up to {max} guests).',
                            { max: MAX_WEBRTC_PEERS }
                          )
                        : hostMode === 'tunnel'
                          ? t(
                              'Launches a Cloudflare HTTPS/WSS tunnel (HTTP/2 over port 443) so friends on any network can join in a browser or desktop app.'
                            )
                          : t(
                              'Reachable only by devices on the same Wi-Fi network or virtual LAN (e.g. Tailscale).'
                            )}
                    </p>
                  </div>

                  <button
                    type="button"
                    data-testid="host-start-btn"
                    disabled={isStarting}
                    onClick={() => void handleStart()}
                    className="w-full flex items-center justify-center gap-2 rounded-ui-sm bg-ui-accent text-ui-accent-contrast hover:opacity-90 py-2 text-xs font-medium transition-opacity disabled:opacity-50 cursor-pointer"
                  >
                    {isStarting ? (
                      <>
                        <Loader2 className="w-3.5 h-3.5 animate-spin" />
                        <span>
                          {startStatus ||
                            (hostMode === 'p2p'
                              ? t('Opening P2P Room...')
                              : hostMode === 'tunnel'
                                ? t('Starting Worldwide Tunnel...')
                                : t('Starting Server...'))}
                        </span>
                      </>
                    ) : (
                      <>
                        {hostMode === 'p2p' ? (
                          <Radio className="w-3.5 h-3.5" />
                        ) : hostMode === 'tunnel' ? (
                          <Globe className="w-3.5 h-3.5" />
                        ) : (
                          <Users className="w-3.5 h-3.5" />
                        )}
                        <span>
                          {hostMode === 'p2p'
                            ? t('Start Room & Copy Code')
                            : t('Start Server & Copy Link')}
                        </span>
                      </>
                    )}
                  </button>
                </>
              ) : (
                <form onSubmit={handleJoinSubmit} className="space-y-4">
                  <div>
                    <label className="text-[11px] font-medium text-ui-secondary mb-1.5 flex items-center gap-1.5">
                      <Link2 className="w-3.5 h-3.5 text-ui-icon-muted" />
                      <span>{t('Room Code (INK-XXXX...) or Invite Link')}</span>
                    </label>
                    <input
                      type="text"
                      data-testid="join-target-input"
                      value={joinUrl}
                      onChange={(e) => setJoinUrl(e.target.value)}
                      onKeyDown={(e) => {
                        if (isImeComposing(e) && e.key === 'Enter') e.preventDefault();
                      }}
                      placeholder={t(
                        'INK-7429-K8P2M9 or invite link (ws://, wss://, trycloudflare.com)'
                      )}
                      className="w-full rounded-ui-sm border border-ui-default bg-ui-input px-3 py-2 text-xs text-ui-primary placeholder:text-ui-muted/60 font-ui-mono focus:border-ui-focus focus:outline-hidden"
                    />
                    {parsedJoinTarget && (
                      <div
                        data-testid="join-target-badge"
                        className="mt-1.5 flex items-center gap-1.5 text-[10px] font-ui-mono text-ui-success"
                      >
                        {parsedJoinTarget.kind === 'p2p' ? (
                          <>
                            <Radio className="w-3 h-3 shrink-0" />
                            <span>
                              {t('WebRTC P2P Room detected ({code})', {
                                code: parsedJoinTarget.roomCode,
                              })}
                            </span>
                          </>
                        ) : (
                          <>
                            <Globe className="w-3 h-3 shrink-0" />
                            <span>
                              {parsedJoinTarget.isSecure
                                ? t('Secure WebSocket (WSS) detected ({host})', {
                                    host: parsedJoinTarget.host,
                                  })
                                : t('WebSocket (WS) detected ({host})', {
                                    host: parsedJoinTarget.host,
                                  })}
                            </span>
                          </>
                        )}
                      </div>
                    )}
                    <p className="text-[10px] text-ui-muted mt-1">
                      {t(
                        'Paste an Android/PC P2P Room Code (INK-XXXX-XXXXXX), P2P invite link, or Cloudflare / LAN WebSocket URL.'
                      )}
                    </p>
                  </div>

                  {parsedJoinTarget?.kind === 'p2p' && !parsedJoinTarget.roomSecret && (
                    <div>
                      <label className="block text-[11px] font-medium text-ui-secondary mb-1.5">
                        {t('Room Passcode (if separate)')}
                      </label>
                      <input
                        type="text"
                        value={manualSecret}
                        onChange={(e) => setManualSecret(e.target.value.toUpperCase())}
                        onKeyDown={(e) => {
                          if (isImeComposing(e) && e.key === 'Enter') e.preventDefault();
                        }}
                        placeholder={t('e.g. K8P2M9')}
                        className="w-full rounded-ui-sm border border-ui-default bg-ui-input px-3 py-2 text-xs text-ui-primary placeholder:text-ui-muted/60 font-ui-mono focus:border-ui-focus focus:outline-hidden"
                      />
                    </div>
                  )}

                  <button
                    type="submit"
                    disabled={isJoining || !joinUrl.trim()}
                    className="w-full flex items-center justify-center gap-2 rounded-ui-sm bg-ui-accent text-ui-accent-contrast hover:opacity-90 py-2 text-xs font-medium transition-opacity disabled:opacity-50 cursor-pointer"
                  >
                    {isJoining ? (
                      <>
                        <Loader2 className="w-3.5 h-3.5 animate-spin" />
                        <span>{t('Connecting...')}</span>
                      </>
                    ) : (
                      <>
                        {parsedJoinTarget?.kind === 'p2p' ? (
                          <Radio className="w-3.5 h-3.5" />
                        ) : (
                          <Link2 className="w-3.5 h-3.5" />
                        )}
                        <span>
                          {parsedJoinTarget?.kind === 'p2p'
                            ? t('Join P2P Room')
                            : t('Join Session')}
                        </span>
                      </>
                    )}
                  </button>
                </form>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};