All files / src/pages CollabWorkspace.tsx

0% Statements 0/169
0% Branches 0/129
0% Functions 0/44
0% Lines 0/159

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
import { useState, useEffect } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { useToast } from '../components/ui/Toast';
import { Badge } from '../components/ui/Badge';
import { Tabs } from '../components/ui/Tabs';
import type { Tab } from '../components/ui/Tabs';
import { collabApi } from '../api/collab';
import type { ChapterTaskResponse, CommentResponse } from '../api/types';
import { LANGUAGE_CODES } from '../api/types';
import {
  ArrowLeft,
  BookOpen,
  Send,
  MessageSquare,
  BookMarked,
  Settings,
  Copy,
  Trash2,
  Save,
  Clock,
  Languages,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
 
const STATUS_COLORS: Record<string, Parameters<typeof Badge>[0]['color']> = {
  UNASSIGNED: 'gray',
  TRANSLATING: 'blue',
  SUBMITTED: 'yellow',
  REVIEWING: 'purple',
  APPROVED: 'green',
  REJECTED: 'red',
  COMPLETED: 'green',
};
 
function getLangName(t: ReturnType<typeof useTranslation>['t'], code: string): string {
  return t(`common.languages.${code}`, { defaultValue: code });
}
 
// ==================== CommentItem (reused from CollabPage) ====================
function CommentItem({ comment, depth }: { comment: CommentResponse; depth: number }) {
  const indentClass = depth > 0 ? 'ml-8 border-l-2 border-border pl-4' : '';
 
  return (
    <div className={`${indentClass}`}>
      <div className="flex items-start gap-2">
        <div className="w-7 h-7 rounded-full bg-accent/20 text-accent flex items-center justify-center text-xs font-semibold flex-shrink-0">
          {comment.username?.slice(0, 1).toUpperCase() || 'U'}
        </div>
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium text-text-primary">{comment.username}</span>
            <span className="text-xs text-text-tertiary">{comment.createTime}</span>
            {comment.resolved && (
              <span className="text-xs text-green">已解决</span>
            )}
          </div>
          {comment.sourceText && (
            <div className="mt-1 text-xs text-text-tertiary bg-surface-secondary px-2 py-1 rounded">
              原文: {comment.sourceText}
            </div>
          )}
          <p className="mt-1 text-sm text-text-secondary whitespace-pre-wrap">{comment.content}</p>
        </div>
      </div>
      {comment.replies?.map(reply => (
        <CommentItem key={reply.id} comment={reply} depth={depth + 1} />
      ))}
    </div>
  );
}
 
// ==================== Main Component ====================
function CollabWorkspace() {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const { success, error: toastError } = useToast();
  const { t } = useTranslation();
 
  const chapterId = Number(searchParams.get('chapterId'));
  const [targetLang, setTargetLang] = useState(searchParams.get('targetLang') || 'zh');
  const [chapter, setChapter] = useState<ChapterTaskResponse | null>(null);
  const [loading, setLoading] = useState(true);
 
  // Editor state
  const [sourceText, setSourceText] = useState('');
  const [editorText, setEditorText] = useState('');
  const [isDirty, setIsDirty] = useState(false);
  const [lastSaved, setLastSaved] = useState<Date | null>(null);
  const [saving, setSaving] = useState(false);
 
  // Sidebar state
  const [sidebarTab, setSidebarTab] = useState<'comments' | 'reference' | 'settings'>('comments');
  const [comments, setComments] = useState<CommentResponse[]>([]);
  const [commentPage, setCommentPage] = useState(1);
  const [commentTotalPages, setCommentTotalPages] = useState(0);
  const [commentInput, setCommentInput] = useState('');
  const [anchoredSourceText, setAnchoredSourceText] = useState<string | null>(null);
 
  // Load chapter data
  useEffect(() => {
    if (!chapterId) {
      navigate('/collab');
      return;
    }
    loadChapter();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [chapterId]);
 
  const loadChapter = async () => {
    setLoading(true);
    try {
      const res = await collabApi.getChapter(chapterId);
      setChapter(res.data);
      // Pre-fill source text
      const initialSource = res.data.sourceText || '';
      setSourceText(initialSource);
      // Pre-fill editor from chapter translatedText
      const initialText = res.data.translatedText || '';
      setEditorText(initialText);
      // Load draft from localStorage
      const draft = localStorage.getItem(`collab_draft_${chapterId}`);
      if (draft && !initialText) {
        setEditorText(draft);
      }
      // Load comments
      loadComments();
    } catch {
      toastError('加载章节失败');
      navigate('/collab');
    } finally {
      setLoading(false);
    }
  };
 
  const loadComments = async (page = 1) => {
    try {
      const res = await collabApi.listComments(chapterId, page);
      const pageData = res.data;
      setComments(pageData.list || []);
      setCommentPage(page);
      setCommentTotalPages(pageData.totalPages || 0);
    } catch {
      // Silent fail — comments may not exist yet
    }
  };
 
  const goToCommentPage = (page: number) => {
    if (page === commentPage) return;
    loadComments(page);
  };
 
  // Draft auto-save (every 30 seconds)
  useEffect(() => {
    if (!chapterId || !isDirty) return;
    const interval = setInterval(() => {
      localStorage.setItem(`collab_draft_${chapterId}`, editorText);
      setLastSaved(new Date());
      setIsDirty(false);
    }, 30000);
    return () => clearInterval(interval);
  }, [chapterId, isDirty, editorText]);
 
  // Save draft on unmount
  useEffect(() => {
    return () => {
      if (chapterId && isDirty && editorText) {
        localStorage.setItem(`collab_draft_${chapterId}`, editorText);
      }
    };
  }, [chapterId, isDirty, editorText]);
 
  // Save draft on beforeunload
  useEffect(() => {
    const handler = () => {
      if (chapterId && isDirty && editorText) {
        localStorage.setItem(`collab_draft_${chapterId}`, editorText);
      }
    };
    window.addEventListener('beforeunload', handler);
    return () => window.removeEventListener('beforeunload', handler);
  }, [chapterId, isDirty, editorText]);
 
  // ==================== Handlers ====================
 
  const handleEditorChange = (value: string) => {
    setEditorText(value);
    setIsDirty(true);
  };
 
  const handleSaveDraft = () => {
    if (!chapterId) return;
    localStorage.setItem(`collab_draft_${chapterId}`, editorText);
    setLastSaved(new Date());
    setIsDirty(false);
    success('草稿已保存');
  };
 
  const handleSubmit = async () => {
    if (!chapter) return;
    if (!editorText.trim()) {
      toastError('译文不能为空');
      return;
    }
    setSaving(true);
    try {
      await collabApi.submitChapter(chapter.id, { translatedText: editorText });
      success('翻译已提交');
      // Clear draft
      localStorage.removeItem(`collab_draft_${chapterId}`);
      // Refresh and go back
      await loadChapter();
    } catch (e) {
      toastError(e instanceof Error ? e.message : '提交失败');
    } finally {
      setSaving(false);
    }
  };
 
  const handleCopyEditor = async () => {
    try {
      await navigator.clipboard.writeText(editorText);
      success('已复制到剪贴板');
    } catch {
      toastError('复制失败');
    }
  };
 
  const handleClearEditor = () => {
    setEditorText('');
    setIsDirty(true);
  };
 
  const handleSourceSelect = () => {
    const sel = window.getSelection();
    if (!sel) return;
    const text = sel.toString().trim();
    if (text.length >= 3 && text.length <= 200) {
      setAnchoredSourceText(text);
      setSidebarTab('comments');
    }
  };
 
  const handleClearAnchor = () => {
    setAnchoredSourceText(null);
    window.getSelection()?.removeAllRanges();
  };
 
  const handleSendComment = async () => {
    if (!commentInput.trim() || !chapter) return;
    try {
      const res = await collabApi.createComment(chapter.id, {
        content: commentInput,
        sourceText: anchoredSourceText || undefined,
      });
      // 立即追加到列表头部,确保用户能看到新评论
      setComments(prev => [res.data, ...prev]);
      setCommentInput('');
      setAnchoredSourceText(null);
      // 从服务端刷新以获取准确的分页数据
      loadComments();
      success('评论已发送');
    } catch (e) {
      toastError(e instanceof Error ? e.message : '评论失败');
    }
  };
 
  const handleCopySource = async () => {
    if (!sourceText) return;
    try {
      await navigator.clipboard.writeText(sourceText);
      success('原文已复制');
    } catch {
      toastError('复制失败');
    }
  };
 
  // ==================== Derived values ====================
  const sourceChars = sourceText.length;
  const translatedChars = editorText.length;
  const progressPercent = sourceChars > 0
    ? Math.min(100, Math.round((translatedChars / sourceChars) * 100))
    : 0;
  const sourceWords = sourceText.split(/\s+/).filter(Boolean).length;
  const translatedWords = editorText.split(/\s+/).filter(Boolean).length;
 
  const sidebarTabs: Tab[] = [
    { key: 'comments', label: '评论' },
    { key: 'reference', label: '参考' },
    { key: 'settings', label: '设置' },
  ];
 
  if (loading || !chapter) {
    return (
      <div className="flex items-center justify-center py-24">
        <div className="text-text-tertiary">加载中...</div>
      </div>
    );
  }
 
  return (
    <div className="py-8">
      <div className="flex flex-col" style={{ minHeight: 'calc(100vh - 140px)' }}>
      {/* ==================== Top Toolbar ==================== */}
      <div className="flex items-center justify-between px-4 py-3 border-b border-border bg-surface-secondary">
        <div className="flex items-center gap-3">
          <button
            onClick={() => navigate('/collab')}
            className="p-1.5 rounded-full hover:bg-surface-secondary transition-button text-text-secondary"
          >
            <ArrowLeft className="w-4 h-4" />
          </button>
          <div className="flex items-center gap-2">
            <BookOpen className="w-4 h-4 text-text-tertiary" />
            <span className="text-sm font-medium text-text-primary">
              第{chapter.chapterNumber}章
            </span>
            {chapter.title && (
              <span className="text-sm text-text-secondary truncate max-w-64">
                {chapter.title}
              </span>
            )}
          </div>
          <Badge color={STATUS_COLORS[chapter.status] || 'gray'}>
            {t(`collab.taskStatus.${chapter.status.toLowerCase()}`, { defaultValue: chapter.status })}
          </Badge>
        </div>
 
        <div className="flex items-center gap-4">
          <div className="hidden sm:flex items-center gap-2 text-xs text-text-tertiary">
            <Languages className="w-3.5 h-3.5" />
            <span className="text-text-placeholder">{t('common.languages.auto')} →</span>
            <select
              value={targetLang}
              onChange={e => setTargetLang(e.target.value)}
              className="bg-transparent text-text-primary text-xs border-none focus:outline-none cursor-pointer"
            >
              {LANGUAGE_CODES.filter(c => c !== 'auto').map(code => (
                <option key={code} value={code}>{t(`common.languages.${code}`)}</option>
              ))}
            </select>
          </div>
          <div className="hidden sm:flex items-center gap-3 text-xs text-text-tertiary">
            <span>{t('workspace.sourceChars', { defaultValue: '原文' })}: {sourceText.length.toLocaleString()} {t('workspace.chars', { defaultValue: '字符' })}</span>
            <span>{t('workspace.targetChars', { defaultValue: '译文' })}: {editorText.length.toLocaleString()} {t('workspace.chars', { defaultValue: '字符' })}</span>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={handleSaveDraft}
              disabled={!isDirty}
              className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-text-primary border border-border rounded-button hover:bg-surface-secondary transition-button disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <Save className="w-3.5 h-3.5" /> 保存
            </button>
            <button
              onClick={handleSubmit}
              disabled={saving || !editorText.trim()}
              className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-white bg-accent rounded-button hover:bg-accent-hover transition-button disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <Send className="w-3.5 h-3.5" /> {saving ? '提交中...' : '提交'}
            </button>
          </div>
        </div>
      </div>
 
      {/* ==================== Main 3-Panel Layout ==================== */}
      <div className="flex flex-1 overflow-hidden">
        {/* ===== Left Panel: Source Text ===== */}
        <div className="hidden md:flex md:flex-col md:w-[35%] lg:w-[35%] border-r border-border bg-surface overflow-hidden">
          <div className="flex items-center justify-between px-4 py-2 border-b border-border bg-surface-secondary/50">
            <span className="text-xs font-medium text-text-secondary">原文</span>
            <button
              onClick={handleCopySource}
              className="p-1 rounded text-text-tertiary hover:text-text-primary transition-button"
              title="复制原文"
            >
              <Copy className="w-3.5 h-3.5" />
            </button>
          </div>
 
          <div
            className="flex-1 overflow-y-auto px-4 py-3"
            onMouseUp={handleSourceSelect}
          >
            <textarea
              value={sourceText}
              onChange={e => setSourceText(e.target.value)}
              placeholder="粘贴原文内容,或等待所有者添加..."
              className="w-full h-full resize-none bg-transparent text-sm text-text-primary placeholder:text-text-placeholder focus:outline-none whitespace-pre-wrap font-sans leading-relaxed select-text"
              style={{ minHeight: '200px' }}
            />
          </div>
 
          {/* Source panel footer */}
          <div className="px-4 py-2 border-t border-border bg-surface-secondary/50">
            <div className="flex items-center justify-between text-xs text-text-tertiary">
              <span>{sourceText.length.toLocaleString()} 字符 · {sourceText.split(/\s+/).filter(Boolean).length.toLocaleString()} 词</span>
              <span className="text-text-placeholder">翻译由团队模式自动完成</span>
            </div>
          </div>
        </div>
 
        {/* ===== Center Panel: Translation Editor ===== */}
        <div className="flex flex-col flex-1 overflow-hidden bg-surface">
          <div className="flex items-center justify-between px-4 py-2 border-b border-border bg-surface-secondary/50">
            <span className="text-xs font-medium text-text-secondary">译文</span>
            <div className="flex items-center gap-2">
              {isDirty && (
                <span className="text-xs text-yellow flex items-center gap-1">
                  <Clock className="w-3 h-3" /> 未保存
                </span>
              )}
              {lastSaved && (
                <span className="text-xs text-text-tertiary">
                  已保存 {lastSaved.toLocaleTimeString()}
                </span>
              )}
              <button
                onClick={handleCopyEditor}
                disabled={!editorText}
                className="p-1 rounded text-text-tertiary hover:text-text-primary transition-button disabled:opacity-30"
                title="复制译文"
              >
                <Copy className="w-3.5 h-3.5" />
              </button>
              <button
                onClick={handleClearEditor}
                disabled={!editorText}
                className="p-1 rounded text-text-tertiary hover:text-red transition-button disabled:opacity-30"
                title="清空"
              >
                <Trash2 className="w-3.5 h-3.5" />
              </button>
            </div>
          </div>
 
          {/* Editor textarea */}
          <div className="flex-1 relative overflow-hidden">
            <textarea
              value={editorText}
              onChange={e => handleEditorChange(e.target.value)}
              placeholder="输入翻译结果,或等待团队模式自动翻译..."
              className="w-full h-full resize-none bg-transparent text-text-primary text-[15px] leading-relaxed placeholder:text-text-placeholder focus:outline-none px-4 py-3"
              style={{ fontFamily: 'var(--font-sans)' }}
            />
          </div>
 
          {/* Editor footer */}
          <div className="px-4 py-2 border-t border-border bg-surface-secondary/50">
            <div className="flex items-center justify-between text-xs text-text-tertiary">
              <div className="flex items-center gap-4">
                <span>{translatedChars.toLocaleString()} 字符 · {translatedWords.toLocaleString()} 词</span>
                {sourceChars > 0 && (
                  <span>进度 {progressPercent}%</span>
                )}
              </div>
            </div>
            {/* Progress bar */}
            {sourceChars > 0 && (
              <div className="mt-2 w-full h-1 bg-surface-secondary rounded-full overflow-hidden">
                <div
                  className="h-full bg-gradient-brand transition-all duration-300"
                  style={{ width: `${progressPercent}%` }}
                />
              </div>
            )}
          </div>
        </div>
 
        {/* ===== Right Panel: Sidebar (Comments/Reference/Settings) ===== */}
        <div className="hidden md:flex md:flex-col md:w-[25%] lg:w-[20%] border-l border-border bg-surface overflow-hidden">
          {/* Tab switcher */}
          <div className="px-3 pt-3 border-b border-border">
            <Tabs tabs={sidebarTabs} activeTab={sidebarTab} onChange={v => setSidebarTab(v as typeof sidebarTab)} />
          </div>
 
          {/* Anchored source text indicator */}
          {anchoredSourceText && (
            <div className="px-3 py-2 border-b border-border bg-accent-bg">
              <div className="flex items-center justify-between">
                <span className="text-xs text-accent">已锚定原文</span>
                <button onClick={handleClearAnchor} className="text-xs text-text-tertiary hover:text-text-primary">
                  清除
                </button>
              </div>
              <p className="text-xs text-text-secondary mt-1 line-clamp-2">{anchoredSourceText}</p>
            </div>
          )}
 
          {/* Tab content */}
          <div className="flex-1 overflow-y-auto">
            {/* Comments Tab */}
            {sidebarTab === 'comments' && (
              <div className="flex flex-col h-full">
                <div className="flex-1 overflow-y-auto px-3 py-3 space-y-3">
                  {comments.length === 0 ? (
                    <div className="flex flex-col items-center justify-center py-12 text-text-tertiary">
                      <MessageSquare className="w-8 h-8 mb-2" />
                      <p className="text-xs">暂无评论</p>
                      <p className="text-xs mt-1">选中原文可锚定评论</p>
                    </div>
                  ) : (
                    <>
                      {comments.map(comment => (
                        <CommentItem key={comment.id} comment={comment} depth={0} />
                      ))}
                      {/* Numbered pagination */}
                      {commentTotalPages > 0 && (
                        <div className="flex items-center justify-center gap-1 pt-2">
                          {Array.from({ length: commentTotalPages }, (_, i) => i + 1).map(page => (
                            <button
                              key={page}
                              onClick={() => goToCommentPage(page)}
                              className={`min-w-7 h-7 text-xs rounded transition-colors ${
                                page === commentPage
                                  ? 'bg-accent text-white font-medium'
                                  : 'text-text-secondary hover:bg-surface-secondary'
                              }`}
                            >
                              {page}
                            </button>
                          ))}
                        </div>
                      )}
                    </>
                  )}
                </div>
                {/* Comment input */}
                <div className="px-3 py-2 border-t border-border">
                  <div className="flex gap-2">
                    <input
                      value={commentInput}
                      onChange={e => setCommentInput(e.target.value)}
                      placeholder="输入评论..."
                      className="flex-1 px-2 py-1.5 text-xs border border-border rounded bg-white focus:outline-none focus:border-accent"
                      onKeyDown={e => {
                        if (e.key === 'Enter' && !e.shiftKey) {
                          e.preventDefault();
                          handleSendComment();
                        }
                      }}
                    />
                    <button
                      onClick={handleSendComment}
                      disabled={!commentInput.trim()}
                      className="px-2 py-1.5 text-xs font-medium text-white bg-accent rounded-button hover:bg-accent-hover transition-button disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      发送
                    </button>
                  </div>
                </div>
              </div>
            )}
 
            {/* Reference Tab */}
            {sidebarTab === 'reference' && (
              <div className="px-3 py-4">
                <div className="flex flex-col items-center justify-center py-12 text-text-tertiary">
                  <BookMarked className="w-8 h-8 mb-2" />
                  <p className="text-xs">术语参考</p>
                  <p className="text-xs mt-1 text-center">项目术语表将显示在这里</p>
                </div>
              </div>
            )}
 
            {/* Settings Tab */}
            {sidebarTab === 'settings' && (
              <div className="px-3 py-4 space-y-4">
                {/* Language info */}
                <div>
                  <h4 className="text-xs font-medium text-text-primary mb-2">语言设置</h4>
                  <div className="space-y-2">
                    <div className="flex items-center justify-between text-xs">
                      <span className="text-text-tertiary">源语言</span>
                      <span className="text-text-primary">自动检测</span>
                    </div>
                    <div className="flex items-center justify-between text-xs">
                      <span className="text-text-tertiary">目标语言</span>
                      <span className="text-text-primary">{getLangName(t, targetLang)}</span>
                    </div>
                  </div>
                </div>
 
                {/* Progress */}
                <div>
                  <h4 className="text-xs font-medium text-text-primary mb-2">翻译进度</h4>
                  <div className="space-y-2">
                    <div className="flex items-center justify-between text-xs">
                      <span className="text-text-tertiary">状态</span>
                      <Badge color={STATUS_COLORS[chapter.status] || 'gray'}>
                        {t(`collab.taskStatus.${chapter.status.toLowerCase()}`, { defaultValue: chapter.status })}
                      </Badge>
                    </div>
                    <div className="flex items-center justify-between text-xs">
                      <span className="text-text-tertiary">完成度</span>
                      <span className="text-text-primary font-mono">{progressPercent}%</span>
                    </div>
                    <div className="w-full h-1.5 bg-surface-secondary rounded-full overflow-hidden">
                      <div
                        className="h-full bg-accent transition-all duration-300"
                        style={{ width: `${progressPercent}%` }}
                      />
                    </div>
                  </div>
                </div>
 
                {/* Stats */}
                <div>
                  <h4 className="text-xs font-medium text-text-primary mb-2">统计</h4>
                  <div className="space-y-2">
                    <div className="flex items-center justify-between text-xs">
                      <span className="text-text-tertiary">原文字符</span>
                      <span className="text-text-primary font-mono">{sourceChars.toLocaleString()}</span>
                    </div>
                    <div className="flex items-center justify-between text-xs">
                      <span className="text-text-tertiary">原文词数</span>
                      <span className="text-text-primary font-mono">{sourceWords.toLocaleString()}</span>
                    </div>
                    <div className="flex items-center justify-between text-xs">
                      <span className="text-text-tertiary">译文字符</span>
                      <span className="text-text-primary font-mono">{translatedChars.toLocaleString()}</span>
                    </div>
                    <div className="flex items-center justify-between text-xs">
                      <span className="text-text-tertiary">译文词数</span>
                      <span className="text-text-primary font-mono">{translatedWords.toLocaleString()}</span>
                    </div>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
 
      {/* ==================== Mobile Bottom Tab Bar ==================== */}
      <div className="md:hidden flex items-center border-t border-border bg-surface-secondary">
        {sidebarTabs.map(tab => (
          <button
            key={tab.key}
            onClick={() => setSidebarTab(tab.key as typeof sidebarTab)}
            className={`flex-1 flex flex-col items-center gap-0.5 py-2 text-xs transition-colors ${
              sidebarTab === tab.key ? 'text-accent' : 'text-text-tertiary'
            }`}
          >
            {tab.key === 'comments' && <MessageSquare className="w-4 h-4" />}
            {tab.key === 'reference' && <BookMarked className="w-4 h-4" />}
            {tab.key === 'settings' && <Settings className="w-4 h-4" />}
            <span>{tab.label}</span>
          </button>
        ))}
      </div>
 
      {/* ==================== Mobile Sidebar Overlay ==================== */}
      <div className="md:hidden fixed bottom-0 left-0 right-0 z-50 bg-surface border-t border-border">
        {/* Mobile comment input area shown when comments tab is active */}
        {sidebarTab === 'comments' && (
          <div className="px-3 py-2">
            <div className="flex gap-2">
              <input
                value={commentInput}
                onChange={e => setCommentInput(e.target.value)}
                placeholder="输入评论..."
                className="flex-1 px-2 py-1.5 text-xs border border-border rounded bg-white focus:outline-none focus:border-accent"
                onKeyDown={e => {
                  if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    handleSendComment();
                  }
                }}
              />
              <button
                onClick={handleSendComment}
                disabled={!commentInput.trim()}
                className="px-2 py-1.5 text-xs font-medium text-white bg-accent rounded-button disabled:opacity-50"
              >
                发送
              </button>
            </div>
            {/* Comment list */}
            <div className="max-h-48 overflow-y-auto mt-2 space-y-2">
              {comments.length === 0 ? (
                <p className="text-center text-xs text-text-tertiary py-4">暂无评论</p>
              ) : (
                comments.map(comment => (
                  <CommentItem key={comment.id} comment={comment} depth={0} />
                ))
              )}
            </div>
          </div>
        )}
 
        {sidebarTab === 'reference' && (
          <div className="px-3 py-6 text-center text-xs text-text-tertiary">
            <BookMarked className="w-6 h-6 mx-auto mb-2" />
            术语参考功能即将上线
          </div>
        )}
 
        {sidebarTab === 'settings' && (
          <div className="px-3 py-4 space-y-3">
            <div className="flex items-center justify-between text-xs">
              <span className="text-text-tertiary">源语言</span>
              <span className="text-text-primary">自动检测</span>
            </div>
            <div className="flex items-center justify-between text-xs">
              <span className="text-text-tertiary">目标语言</span>
              <span className="text-text-primary">{getLangName(t, targetLang)}</span>
            </div>
            <div className="flex items-center justify-between text-xs">
              <span className="text-text-tertiary">状态</span>
              <Badge color={STATUS_COLORS[chapter.status] || 'gray'}>
                {t(`collab.taskStatus.${chapter.status.toLowerCase()}`, { defaultValue: chapter.status })}
              </Badge>
            </div>
            <div className="flex items-center justify-between text-xs">
              <span className="text-text-tertiary">进度</span>
              <span className="text-text-primary font-mono">{progressPercent}%</span>
            </div>
          </div>
        )}
      </div>
    </div>
    </div>
  );
}
 
export { CollabWorkspace };