import { useState, useRef, useEffect } from 'react';
import { useSelector } from 'react-redux';
import { RootState } from '@/store';
import { useParams, useLocation, useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { toast } from 'sonner';
import {
  ArrowLeft,
  Send,
  Paperclip,
  Smile,
  Image as ImageIcon,
  MessageSquare,
  FileText,
  File as FileIcon,
  X,
  RefreshCcw,
  Users,
  Search,
  ChevronRight,
  Info,
  Clock as ClockIcon,
  Activity,
  UserX,
} from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { cn } from '@/components/ui/utils';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { worknoteService } from '@/services/worknote.service';
import { onboardingService } from '@/services/onboarding.service';
import { useSocket } from '@/context/SocketContext';

interface Attachment {
  id: string;
  fileName: string;
  filePath: string;
  mimeType: string;
}

interface WorkNote {
  id: string;
  noteText: string;
  noteType: string;
  createdAt: string;
  userId?: string;
  author: {
    name: string;
    email: string;
    role: string;
  };
  attachments?: Attachment[];
}

const sortNotesChronological = (arr: WorkNote[]) =>
  [...arr].sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());

const normalizeWorknoteAuthor = (n: any): WorkNote['author'] => ({
  name: n?.author?.name || n?.author?.fullName || 'System',
  email: n?.author?.email || '',
  role: String(n?.author?.role || n?.author?.roleCode || '')
});

/** Workflow-generated rows (approvals, send-back, revoke, etc.) — not composer messages. */
const ACTIVITY_NOTE_TYPES = new Set(['internal', 'workflow', 'system', 'audit', 'status']);

const isActivityLogNote = (note: WorkNote) =>
  ACTIVITY_NOTE_TYPES.has(String(note.noteType || '').toLowerCase());

const activityLogBadgeLabel = (note: WorkNote) => {
  const t = String(note.noteType || '').toLowerCase();
  if (t === 'workflow') return 'Workflow activity';
  if (t === 'internal') return 'Review / approval';
  if (t === 'system') return 'System';
  if (t === 'audit') return 'Audit';
  if (t === 'status') return 'Status update';
  return 'Activity';
};

/** Short label for compact activity row */
/** Uppercase pill label (e.g. APPROVAL) — matches relocation-style worknote activity rows. */
const activityLogPillCategoryUpper = (note: WorkNote) => {
  const t = String(note.noteType || '').toLowerCase();
  if (t === 'internal') return 'APPROVAL';
  if (t === 'workflow') return 'WORKFLOW';
  if (t === 'system') return 'SYSTEM';
  if (t === 'audit') return 'AUDIT';
  if (t === 'status') return 'STATUS';
  return 'ACTIVITY';
};

const formatNoteTimestamp = (createdAt: string) =>
  createdAt
    ? new Date(createdAt).toLocaleString(undefined, {
        month: 'short',
        day: 'numeric',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      })
    : '';

// Participant interface for mentions

interface WorkNotesPageProps {
  requestId: string;
  requestType?: 'application' | 'relocation' | 'constitutional' | 'resignation' | 'termination' | 'fnf';
  mode?: 'page' | 'modal';
  applicationName: string;
  registrationNumber: string;
  onBack: () => void;
  initialNotes?: any[];
  participants?: any[];
}

interface ParticipantUI {
  id: string;
  name: string;
  email: string;
  initials: string;
  color: string;
  role?: string;
  isOnline?: boolean;
  recordId: string;
  revokedAt?: string;
}

const BACKEND_URL = (import.meta as any).env?.VITE_API_URL?.replace('/api', '') || 'http://localhost:5000';

export function WorkNotesPage(props: Partial<WorkNotesPageProps>) {
  const { user: currentUser } = useSelector((state: RootState) => state.auth);
  const { id, type } = useParams<{ id: string, type: string }>();
  const location = useLocation();
  const navigate = useNavigate();

  // Use props if provided (modal mode), otherwise use URL and state
  const requestId = props.requestId || id || '';
  const requestType = props.requestType || type || (location.state?.requestType as any) || 'application';
  const mode = props.mode || (location.state?.mode as any) || 'page';
  const [appName, setAppName] = useState(props.applicationName || location.state?.applicationName || 'Application');
  const [regNumber, setRegNumber] = useState(props.registrationNumber || location.state?.registrationNumber || '');
  const onBack = props.onBack || (() => navigate(-1));
  const externalParticipantsInit = props.participants || location.state?.participants || [];
  const [externalParticipants, setExternalParticipants] = useState<any[]>(externalParticipantsInit);
  const [notes, setNotes] = useState<WorkNote[]>([]);
  const [message, setMessage] = useState('');
  const [showMentionSuggestions, setShowMentionSuggestions] = useState(false);
  const [mentionQuery, setMentionQuery] = useState('');
  const [cursorPosition, setCursorPosition] = useState(0);
  const [isLoading, setIsLoading] = useState(true);
  const [isEmojiPickerOpen, setIsEmojiPickerOpen] = useState(false);
  const [attachedFiles, setAttachedFiles] = useState<Attachment[]>([]);
  const [isUploading, setIsUploading] = useState(false);
  const [isSidebarOpen, setIsSidebarOpen] = useState(true);
  const [participantSearch, setParticipantSearch] = useState('');
  const [messageSearch, setMessageSearch] = useState('');
  const [revokeConfirmParticipant, setRevokeConfirmParticipant] = useState<ParticipantUI | null>(null);
  const [revocationReason, setRevocationReason] = useState('');
  const [isRevoking, setIsRevoking] = useState(false);

  const { socket } = useSocket();
  const inputRef = useRef<HTMLInputElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [previewFile, setPreviewFile] = useState<Attachment | null>(null);

  const getFileIcon = (mimeType: string, filePath?: string) => {
    if (mimeType.startsWith('image/') && filePath) {
      return (
        <img
          src={`${BACKEND_URL}/${filePath.replace(/\\/g, '/')}`}
          className="w-full h-full object-cover rounded"
          alt="Thumbnail"
        />
      );
    }
    if (mimeType.startsWith('image/')) return <ImageIcon className="w-5 h-5 text-blue-500" />;
    if (mimeType === 'application/pdf') return <FileText className="w-5 h-5 text-red-500" />;
    return <FileIcon className="w-5 h-5 text-slate-500" />;
  };

  const COMMON_EMOJIS = [
    '😊', '😂', '🤣', '❤️', '👍', '🙏', '🔥', '✨',
    '😍', '🥰', '😎', '🤔', '😅', '🙌', '👏', '🎉',
    '✅', '❌', '📌', '📎', '📍', '💡', '🔔', '📢',
    '⭐', '🌟', '💪', '🚀', '👀', '💯', '🌈', '☀️',
    '😢', '😭', '😞', '😔', '😟', '😕', '😠', '😡',
    '🤬', '😤', '😲', '🙄', '🤨', '😓', '😩', '😫',
    '🤐', '😴', '🤢', '🤮', '😱', '🤡', '💀', '👻',
    '🤝', '👋', '✌️', '👌', '✋', '🍎', '🍕', '☕',
    '💻', '📱', '⌚', '📁', '📄', '📅', '🔒', '🔑',
    '🛠️', '⚙️', '💬', '💭', '🌊', '🍀', '✈️', '🏠'
  ];

  const getInitials = (name: string) => {
    return name
      .split(' ')
      .map(n => n[0])
      .join('')
      .toUpperCase()
      .substring(0, 2);
  };

  const getAvatarColor = (name: string) => {
    const colors = [
      'bg-green-600',
      'bg-blue-600',
      'bg-purple-600',
      'bg-amber-600',
      'bg-pink-600',
      'bg-indigo-600',
      'bg-teal-600',
    ];
    const index = name.length % colors.length;
    return colors[index];
  };

  // Map backend participants to the UI sub-format
  // Handles both nested structure { user: { id, fullName } } and flat { id, userId, name/fullName }
  // NOTE: p.id is the RequestParticipant record ID. p.userId or p.user?.id is the actual User ID.
  // Map backend participants to the UI sub-format and ensure uniqueness by User ID to avoid duplicates in mentions
  const participantsList: ParticipantUI[] = [];
  const seenIds = new Set<string>();

  externalParticipants.forEach((p: any) => {
    const userId = p.user?.id || p.userId || '';
    const recordId = p.id;
    if (userId && !seenIds.has(userId)) {
      seenIds.add(userId);
      const name = p.user?.fullName || p.user?.name || p.fullName || p.name || 'Unknown User';
      const email = p.user?.email || p.email || '';
      const role = p.user?.roleCode || p.roleCode || p.user?.role || p.role || 'Participant';
      participantsList.push({
        id: userId,
        recordId,
        name,
        email,
        initials: getInitials(name),
        color: getAvatarColor(name),
        role,
        isOnline: false,
        revokedAt: p.metadata?.revokedAt
      });
    }
  });

  const fetchNotes = async () => {
    try {
      setIsLoading(true);
      const res: any = await worknoteService.getWorknotes(requestId, requestType);
      if (res.success) {
        const mapped: WorkNote[] = res.data.map((n: any) => ({
          id: n.id,
          noteText: n.noteText,
          noteType: n.noteType,
          createdAt: n.createdAt,
          userId: n.userId,
          author: n.author ? normalizeWorknoteAuthor(n) : { name: 'System', email: '', role: 'system' },
          attachments: n.attachments || []
        }));
        setNotes(sortNotesChronological(mapped));
      }
    } catch (error) {
      console.error('Fetch notes error:', error);
      toast.error('Failed to load work notes');
    } finally {
      setIsLoading(false);
    }
  };

  // Fetch Notes on load and join socket room
  useEffect(() => {
    fetchNotes();

    if (socket) {
      socket.emit('join_room', requestId);

      socket.on('new_worknote', (raw: any) => {
        const newNote: WorkNote = {
          id: raw.id,
          noteText: raw.noteText,
          noteType: raw.noteType,
          createdAt: raw.createdAt,
          userId: raw.userId,
          author: raw.author ? normalizeWorknoteAuthor(raw) : { name: 'System', email: '', role: 'system' },
          attachments: raw.attachments || []
        };
        setNotes(prev => {
          const isDuplicate = prev.some(n => n.id === newNote.id);
          if (isDuplicate) return prev;

          const optimisticMatchIndex = prev.findIndex(n =>
            n.id.startsWith('temp-') &&
            n.noteText === newNote.noteText &&
            (n.author.email?.toLowerCase() === newNote.author.email?.toLowerCase())
          );

          if (optimisticMatchIndex !== -1) {
            const newNotes = [...prev];
            newNotes[optimisticMatchIndex] = newNote;
            return sortNotesChronological(newNotes);
          }

          return sortNotesChronological([...prev, newNote]);
        });
      });

      return () => {
        socket.emit('leave_room', requestId);
        socket.off('new_worknote');
      };
    }
  }, [requestId, requestType, socket]);

  // Fetch details if metadata or participants are missing (e.g. on refresh)
  useEffect(() => {
    if (!requestId || !requestType) return;

    const fetchDetails = async () => {
      try {
        let data: any = null;
        if (requestType === 'application') {
          data = await onboardingService.getApplicationById(requestId);
          if (data) {
             if (externalParticipants.length === 0 && data.participants) setExternalParticipants(data.participants);
             if (!appName || appName === 'Application') setAppName(data.companyName || 'Application');
             if (!regNumber) setRegNumber(data.registrationNumber || '');
          }
        } else if (requestType === 'termination') {
          const { API } = await import('@/api/API');
          const res: any = await API.getTerminationById(requestId);
          if (res.data?.success) {
            data = res.data.termination;
            if (externalParticipants.length === 0 && data.participants) setExternalParticipants(data.participants);
            if (!appName || appName === 'Application' || appName === 'Termination') setAppName(data.dealer?.businessName || 'Termination');
            if (!regNumber) setRegNumber(data.requestId || '');
          }
        } else if (requestType === 'constitutional' || requestType === 'constitutional-change') {
          const { API } = await import('@/api/API');
          const res: any = await API.getConstitutionalChangeById(requestId);
          if (res.data?.success) {
            data = res.data.request;
            if (externalParticipants.length === 0 && data.participants) setExternalParticipants(data.participants);
            if (!appName || appName === 'Application' || appName === 'Constitutional Change') setAppName(data.outlet?.name || 'Constitutional Change');
            if (!regNumber) setRegNumber(data.requestId || '');
          }
        } else if (requestType === 'resignation') {
          const { API } = await import('@/api/API');
          const res: any = await API.getResignationById(requestId);
          if (res.data?.success) {
            data = res.data.resignation;
            if (externalParticipants.length === 0 && data.participants) setExternalParticipants(data.participants);
            if (!appName || appName === 'Application' || appName === 'Resignation') setAppName(data.dealer?.businessName || 'Resignation');
            if (!regNumber) setRegNumber(data.resignationId || '');
          }
        } else if (requestType === 'fnf') {
          const { API } = await import('@/api/API');
          const res: any = await API.getFnFSettlementById(requestId);
          if (res.data?.success) {
            data = res.data.fnf;
            if (externalParticipants.length === 0 && data.participants) setExternalParticipants(data.participants || []);
            const dealerName = data.outlet?.dealer?.fullName || data.dealer?.fullName || "F&F Settlement";
            if (!appName || appName === 'Application' || appName === 'F&F Settlement') setAppName(dealerName);
            if (!regNumber) setRegNumber(data.settlementId || '');
          }
        }
      } catch (error) {
        console.error(`Failed to fetch ${requestType} details:`, error);
      }
    };
    
    fetchDetails();
  }, [requestId, requestType, externalParticipants.length, appName, regNumber]);

  // Auto-scroll logic
  const messagesEndRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  }, [notes]);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    const cursorPos = e.target.selectionStart || 0;

    setMessage(value);
    setCursorPosition(cursorPos);

    // Check if user is typing @ mention
    const textBeforeCursor = value.substring(0, cursorPos);
    const lastAtSymbol = textBeforeCursor.lastIndexOf('@');

    if (lastAtSymbol !== -1 && lastAtSymbol === textBeforeCursor.length - 1) {
      setShowMentionSuggestions(true);
      setMentionQuery('');
    } else if (lastAtSymbol !== -1) {
      const query = textBeforeCursor.substring(lastAtSymbol + 1);
      if (!query.includes(' ')) {
        setShowMentionSuggestions(true);
        setMentionQuery(query);
      } else {
        setShowMentionSuggestions(false);
      }
    } else {
      setShowMentionSuggestions(false);
    }
  };

  const handleMentionSelect = (participant: ParticipantUI) => {
    const textBeforeCursor = message.substring(0, cursorPosition);
    const lastAtSymbol = textBeforeCursor.lastIndexOf('@');
    const textAfterCursor = message.substring(cursorPosition);

    // Insert clean @Name into input
    const mentionText = `@${participant.name}`;
    const newMessage =
      message.substring(0, lastAtSymbol) +
      mentionText + ' ' +
      textAfterCursor;

    setMessage(newMessage);
    setShowMentionSuggestions(false);
    inputRef.current?.focus();
  };

  const handleEmojiSelect = (emoji: string) => {
    const start = inputRef.current?.selectionStart || message.length;
    const newMessage = message.substring(0, start) + emoji + message.substring(start);
    setMessage(newMessage);
    setIsEmojiPickerOpen(false);
    inputRef.current?.focus();
  };

  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files || files.length === 0) return;

    setIsUploading(true);
    try {
      for (const file of Array.from(files)) {
        const res: any = await worknoteService.uploadAttachment(file, requestId, requestType);
        if (res.success) {
          setAttachedFiles(prev => [...prev, res.data]);
        }
      }
    } catch (error) {
      console.error('File upload error:', error);
      toast.error('Failed to upload attachment');
    } finally {
      setIsUploading(false);
      if (fileInputRef.current) fileInputRef.current.value = '';
    }
  };

  const removeAttachment = (id: string) => {
    setAttachedFiles(prev => prev.filter(f => f.id !== id));
  };

  const handleSendMessage = async () => {
    if (!message.trim() && attachedFiles.length === 0) return;

    const optimisticMessage = message;
    const optimisticAttachments = attachedFiles;
    setMessage('');
    setAttachedFiles([]);

    // Convert clean @Name mentions to structured format: @[Name](user:Id)
    let processedMessage = optimisticMessage;
    const mentionedUserIds: string[] = [];

    participantsList.forEach(p => {
      if (p.id && p.name) {
        const escapedName = p.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        const mentionRegex = new RegExp(`@${escapedName}\\b`, 'gi');

        if (processedMessage.match(mentionRegex)) {
          mentionedUserIds.push(p.id);
          processedMessage = processedMessage.replace(mentionRegex, `@[${p.name}](user:${p.id})`);
        }
      }
    });

    try {
      // Optimistic update
      const tempId = `temp-${Date.now()}`;

      const tempNote: WorkNote = {
        id: tempId,
        noteText: processedMessage, // Structured text for proper rendering
        noteType: 'General',
        createdAt: new Date().toISOString(),
        userId: currentUser?.id,
        author: {
          name: currentUser?.name || 'You',
          email: currentUser?.email || '',
          role: currentUser?.role || ''
        },
        attachments: optimisticAttachments
      };

      setNotes(prev => sortNotesChronological([...prev, tempNote]));

      const res: any = await worknoteService.addWorknote({
        requestId: requestId,
        requestType: requestType,
        noteText: processedMessage,
        noteType: 'General',
        tags: mentionedUserIds,
        attachmentDocIds: optimisticAttachments.map(f => f.id)
      });

      if (res.success && res.data) {
        const saved = res.data;
        const normalized: WorkNote = {
          id: saved.id,
          noteText: saved.noteText,
          noteType: saved.noteType,
          createdAt: saved.createdAt,
          userId: saved.userId,
          author: saved.author ? normalizeWorknoteAuthor(saved) : { name: 'System', email: '', role: 'system' },
          attachments: saved.attachments || []
        };
        setNotes(prev => sortNotesChronological(prev.map(n => (n.id === tempId ? normalized : n))));
      }
    } catch (error) {
      console.error('Send message error:', error);
      toast.error('Failed to send message');
      // Revert optimistic update? (Optional, but good practice)
      // fetchNotes(); // or similar
    }
  };

  const handleRevokeConfirm = (participant: ParticipantUI) => {
    const authorizedRoles = ['DD Lead', 'DD Head', 'NBH', 'DD Admin', 'Super Admin'];
    if (!authorizedRoles.includes(currentUser?.roleCode || '')) {
      toast.error('Only authorized roles can revoke participants');
      return;
    }
    setRevokeConfirmParticipant(participant);
    setRevocationReason('');
  };

  const confirmRevocation = async () => {
    if (!revokeConfirmParticipant) return;

    setIsRevoking(true);
    try {
      const res: any = await worknoteService.revokeParticipant(revokeConfirmParticipant.recordId, revocationReason);
      if (res.success) {
        toast.success(res.message);
        setRevokeConfirmParticipant(null);
        // Refresh details to update UI state
        setExternalParticipants([]); // Triggers re-fetch in useEffect
      }
    } catch (error) {
      toast.error('Error revoking participant');
    } finally {
      setIsRevoking(false);
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  const renderMessageWithMentions = (text: string) => {
    if (!text) return '';

    // Regex matches the structured mention: @[Name](user:Id)
    const mentionRegex = /(@\[[^\]]+\]\([^\)]+\))/g;
    const parts = text.split(mentionRegex);

    return parts.map((part, index) => {
      const mentionMatch = part.match(/@\[([^\]]+)\]\(([^\)]+)\)/);
      if (mentionMatch) {
        const name = mentionMatch[1];
        return (
          <span key={index} className="text-blue-600 font-medium hover:underline cursor-pointer">
            @{name}
          </span>
        );
      }
      return part;
    });
  };

  const messageQuery = messageSearch.trim().toLowerCase();
  const displayNotes = messageQuery
    ? notes.filter(
        (n) =>
          (n.noteText || '').toLowerCase().includes(messageQuery) ||
          (n.author?.name || '').toLowerCase().includes(messageQuery) ||
          (n.noteType || '').toLowerCase().includes(messageQuery)
      )
    : notes;

  const filteredParticipants = participantsList.filter(p => {
    // Filter by name query
    const matchesQuery = p.name.toLowerCase().includes(mentionQuery.toLowerCase());

    // Filter out the current user by ID or Email (self-mention protection)
    const isSelf = (p.id && currentUser?.id && String(p.id) === String(currentUser.id)) ||
      (p.email && currentUser?.email && p.email.toLowerCase() === currentUser.email.toLowerCase());

    return matchesQuery && !isSelf;
  });

  return (
    <div className="h-full flex flex-col bg-slate-50 overflow-hidden">
      {/* Header - Stays fixed because it's a sibling of ScrollArea */}
      <div className="bg-white border-b border-slate-200 px-6 py-4 z-10" data-testid="onboarding-worknotes-header">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-4">
            <Button
              variant="ghost"
              size="icon"
              onClick={onBack}
              className="hover:bg-slate-100"
              data-testid="onboarding-worknotes-back-btn"
            >
              <ArrowLeft className="w-5 h-5" />
            </Button>

            <div className="w-12 h-12 bg-purple-600 rounded-lg flex items-center justify-center">
              <MessageSquare className="w-6 h-6 text-white" />
            </div>

            <div>
              <h1 className="text-slate-900" data-testid="onboarding-worknotes-title">Work Notes</h1>
              <div className="flex items-center gap-2 text-slate-600" data-testid="onboarding-worknotes-meta">
                <span data-testid="onboarding-worknotes-app-name">{appName}</span>
                <span className="text-slate-400">|</span>
                <span className="text-slate-500" data-testid="onboarding-worknotes-reg-num">{regNumber}</span>
              </div>
            </div>
          </div>

          {/* Participant Avatars & Refresh & Toggle Sidebar */}
          <div className="flex items-center gap-4">
            <div className="hidden sm:flex items-center -space-x-2 mr-2" data-testid="onboarding-worknotes-participant-avatars">
              {participantsList.slice(0, 3).map((participant, index) => (
                <Avatar
                  key={index}
                  className="w-8 h-8 border-2 border-white ring-1 ring-slate-100"
                  data-testid={`onboarding-worknotes-avatar-${index}`}
                >
                  <AvatarFallback className={`${participant.color} text-white text-[10px]`}>
                    {participant.initials}
                  </AvatarFallback>
                </Avatar>
              ))}
              {participantsList.length > 3 && (
                <div className="w-8 h-8 rounded-full bg-slate-100 border-2 border-white flex items-center justify-center ring-1 ring-slate-100" data-testid="onboarding-worknotes-avatar-more">
                  <span className="text-slate-600 text-[10px] font-bold">+{participantsList.length - 3}</span>
                </div>
              )}
            </div>

            <Button
              variant="ghost"
              size="sm"
              onClick={fetchNotes}
              className="text-slate-500 hover:text-blue-600 flex items-center gap-1.5 px-2 h-9 rounded-lg hover:bg-slate-50 transition-colors"
              disabled={isLoading}
              data-testid="onboarding-worknotes-sync-btn"
            >
              <RefreshCcw className={`w-4 h-4 ${isLoading ? 'animate-spin' : ''}`} />
              <span className="text-xs font-medium hidden md:inline">Sync</span>
            </Button>

            <Button
              variant={isSidebarOpen ? 'secondary' : 'ghost'}
              size="sm"
              onClick={() => setIsSidebarOpen(!isSidebarOpen)}
              className={`flex items-center gap-1.5 px-2 h-9 rounded-lg transition-all ${isSidebarOpen ? 'bg-blue-50 text-blue-600 hover:bg-blue-100' : 'text-slate-500 hover:bg-slate-50'}`}
              data-testid="onboarding-worknotes-toggle-sidebar-btn"
            >
              <Users className="w-4 h-4" />
              <span className="text-xs font-medium hidden md:inline">Participants</span>
            </Button>
          </div>
        </div>
      </div>

      <div className="flex-1 flex overflow-hidden">
        {/* Main Chat Engine */}
        <div className="flex-1 flex flex-col min-w-0 bg-white min-h-0 relative">
          <div className="flex-1 overflow-y-auto px-6 py-4 custom-scrollbar bg-slate-50 relative z-0" data-testid="onboarding-worknotes-chat-area">
            <div className={`max-w-4xl mx-auto flex flex-col py-4 gap-4 ${mode === 'modal' ? '' : 'px-4'}`}>
              <div className="sticky top-0 z-[1] -mx-1 px-1 pb-1 bg-slate-50/95 backdrop-blur-sm">
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400 pointer-events-none" />
                  <Input
                    type="search"
                    value={messageSearch}
                    onChange={(e) => setMessageSearch(e.target.value)}
                    placeholder="Search messages..."
                    className="pl-9 h-10 bg-white border-slate-200 rounded-xl text-sm shadow-sm"
                    aria-label="Search messages"
                    data-testid="onboarding-worknotes-search-input"
                  />
                </div>
              </div>

              {displayNotes.map((note, idx) => {
                if (isActivityLogNote(note)) {
                  const who = note.author?.name || 'System';
                  const role =
                    note.author?.role && note.author.role !== '0' && note.author.role !== ''
                      ? note.author.role
                      : '';
                  return (
                    <div key={note.id} className="flex w-full justify-center px-1 py-1 sm:px-2" data-testid={`onboarding-worknotes-activity-row-${idx}`}>
                      <div
                        role="status"
                        title={activityLogBadgeLabel(note)}
                        className="flex w-full max-w-[min(100%,42rem)] items-start gap-2.5 rounded-xl border border-slate-200/90 bg-slate-100/80 px-3 py-2.5 shadow-sm"
                      >
                        <Activity
                          className="mt-0.5 h-4 w-4 shrink-0 text-purple-600"
                          strokeWidth={2.5}
                          aria-hidden
                        />
                        <span className="shrink-0 pt-0.5 text-[10px] font-bold uppercase tracking-wide text-slate-600" data-testid={`onboarding-worknotes-activity-type-${idx}`}>
                          {activityLogPillCategoryUpper(note)}
                        </span>
                        <div className="min-w-0 flex-1 text-left">
                          <p className="text-sm leading-snug text-slate-800">
                            <span className="font-semibold text-slate-900" data-testid={`onboarding-worknotes-activity-who-${idx}`}>{who}</span>
                            {role ? (
                              <span className="text-xs font-normal text-slate-500"> · {role}</span>
                            ) : null}
                            <span className="font-normal text-slate-600"> — </span>
                            <span className="font-normal text-slate-700" data-testid={`onboarding-worknotes-activity-text-${idx}`}>{renderMessageWithMentions(note.noteText)}</span>
                          </p>
                        </div>
                        <time
                          className="shrink-0 whitespace-nowrap pt-0.5 text-right text-[10px] leading-tight text-slate-400 tabular-nums sm:text-[11px]"
                          dateTime={note.createdAt}
                          data-testid={`onboarding-worknotes-activity-time-${idx}`}
                        >
                          {formatNoteTimestamp(note.createdAt)}
                        </time>
                      </div>
                    </div>
                  );
                }

                const isMe =
                  (note?.author?.email &&
                    currentUser?.email &&
                    note.author.email.toLowerCase() === currentUser.email.toLowerCase()) ||
                  (note?.userId && currentUser?.id && String(note.userId) === String(currentUser.id)) ||
                  note.id.startsWith('temp-');

                return (
                  <div key={note.id} className={`flex w-full ${isMe ? 'justify-end' : 'justify-start'}`} data-testid={`onboarding-worknotes-message-row-${idx}`}>
                    <div className={`flex gap-3 max-w-[min(85%,36rem)] ${isMe ? 'flex-row-reverse' : ''}`}>
                      <Avatar className="w-10 h-10 flex-shrink-0 mt-1" data-testid={`onboarding-worknotes-message-avatar-${idx}`}>
                        <AvatarFallback className={`${getAvatarColor(note?.author?.name || 'System')} text-white`}>
                          {getInitials(note?.author?.name || 'S')}
                        </AvatarFallback>
                      </Avatar>

                      <div className={`flex flex-col min-w-0 ${isMe ? 'items-end' : 'items-start'}`}>
                        <div
                          className={`flex flex-wrap items-center gap-x-2 gap-y-0.5 mb-1 px-1 ${
                            isMe ? 'flex-row-reverse text-right' : 'text-left'
                          }`}
                        >
                          <span className="text-slate-900 font-medium text-sm" data-testid={`onboarding-worknotes-message-author-${idx}`}>
                            {isMe ? 'You' : note?.author?.name || 'Unknown'}
                          </span>
                          <span className="text-slate-400 text-[10px] uppercase tracking-wide">
                            {note?.author?.role && note.author.role !== '0' && note.author.role !== ''
                              ? `(${note.author.role})`
                              : ''}
                          </span>
                          <span className="text-slate-400 text-[10px] tabular-nums" data-testid={`onboarding-worknotes-message-time-${idx}`}>
                            {formatNoteTimestamp(note.createdAt)}
                          </span>
                        </div>

                        <div
                          className={`rounded-2xl border px-4 py-2.5 shadow-sm relative text-left ${
                            isMe
                              ? 'bg-blue-50 border-blue-100 text-slate-800 rounded-tr-none'
                              : 'bg-white border-slate-200 text-slate-700 rounded-tl-none'
                          }`}
                          data-testid={`onboarding-worknotes-message-bubble-${idx}`}
                        >
                          <p className="text-sm leading-relaxed whitespace-pre-wrap break-words" data-testid={`onboarding-worknotes-message-text-${idx}`}>
                            {renderMessageWithMentions(note.noteText)}
                          </p>

                          {note.attachments && note.attachments.length > 0 && (
                            <div className="mt-2 space-y-2 border-t border-slate-100 pt-2" data-testid={`onboarding-worknotes-message-attachments-${idx}`}>
                              {note.attachments.map((file, fIdx) => {
                                const isImage = file.mimeType.startsWith('image/');
                                return (
                                  <div key={file.id} className="flex items-center gap-2" data-testid={`onboarding-worknotes-message-attachment-${idx}-${fIdx}`}>
                                    {isImage ? (
                                      <div className="rounded-lg overflow-hidden border border-slate-100 max-w-[200px]">
                                        <img
                                          src={`${BACKEND_URL}/${file.filePath.replace(/\\/g, '/')}`}
                                          alt={file.fileName}
                                          className="w-full h-auto cursor-pointer"
                                          onClick={() => setPreviewFile(file)}
                                          data-testid={`onboarding-worknotes-message-attachment-img-${idx}-${fIdx}`}
                                        />
                                      </div>
                                    ) : file.mimeType === 'application/pdf' ? (
                                      <button
                                        type="button"
                                        onClick={() => setPreviewFile(file)}
                                        className="flex items-center gap-2 text-xs text-blue-600 hover:underline"
                                        data-testid={`onboarding-worknotes-message-attachment-preview-${idx}-${fIdx}`}
                                      >
                                        <Paperclip className="w-3 h-3" />
                                        {file.fileName} (Preview)
                                      </button>
                                    ) : (
                                      <a
                                        href={`${BACKEND_URL}/${file.filePath.replace(/\\/g, '/')}`}
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className="flex items-center gap-2 text-xs text-blue-600 hover:underline"
                                        data-testid={`onboarding-worknotes-message-attachment-link-${idx}-${fIdx}`}
                                      >
                                        <Paperclip className="w-3 h-3" />
                                        {file.fileName}
                                      </a>
                                    )}
                                  </div>
                                );
                              })}
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })}

          {notes.length === 0 && !isLoading && (
            <div className="flex flex-col items-center justify-center py-16 text-center" data-testid="onboarding-worknotes-empty-state">
              <MessageSquare className="w-16 h-16 text-slate-300 mb-4" />
              <h3 className="text-slate-900 mb-2">No messages yet</h3>
              <p className="text-slate-600">Start the conversation by sending a message below</p>
            </div>
          )}

          {notes.length > 0 && displayNotes.length === 0 && !isLoading && (
            <div className="flex flex-col items-center justify-center py-12 text-center text-slate-500 text-sm">
              No messages match &quot;{messageSearch.trim()}&quot;. Clear the search box to see the full thread.
            </div>
          )}

          {isLoading && (
            <div className="flex justify-center items-center py-8">
              <span className="text-slate-500">Loading notes...</span>
            </div>
          )}
          <div ref={messagesEndRef} />
            </div>
          </div>

          {/* Input Area */}
          <div className="bg-white border-t border-slate-100 px-6 py-4 shadow-[0_-4px_10px_-5px_rgba(0,0,0,0.05)]" data-testid="onboarding-worknotes-composer">
            <div className="max-w-4xl mx-auto space-y-4">

          {/* Attachment Previews */}
          {attachedFiles.length > 0 && (
            <div className="flex flex-wrap gap-3 mb-3" data-testid="onboarding-worknotes-attached-files">
              {attachedFiles.map((file, fIdx) => {
                const isPreviewable = file.mimeType.startsWith('image/') || file.mimeType === 'application/pdf';
                return (
                  <div
                    key={file.id}
                    className="flex items-center gap-3 p-2 bg-white rounded-xl border border-slate-200 shadow-sm hover:border-blue-300 transition-all group max-w-[200px]"
                    data-testid={`onboarding-worknotes-attached-file-${fIdx}`}
                  >
                    <div className="w-10 h-10 bg-slate-50 rounded-lg flex items-center justify-center flex-shrink-0 overflow-hidden">
                      {getFileIcon(file.mimeType, file.filePath)}
                    </div>
                    <div className="flex-1 min-w-0 pr-6 relative">
                      <p
                        className={`text-xs font-medium text-slate-700 truncate ${isPreviewable ? 'hover:text-blue-600 cursor-pointer hover:underline' : ''}`}
                        onClick={() => isPreviewable && setPreviewFile(file)}
                      >
                        {file.fileName}
                      </p>
                      <button
                        onClick={() => removeAttachment(file.id)}
                        className="absolute -top-1 -right-1 p-1 bg-white rounded-full border border-slate-100 text-slate-400 hover:text-red-500 shadow-sm opacity-0 group-hover:opacity-100 transition-opacity"
                        data-testid={`onboarding-worknotes-remove-attachment-${fIdx}`}
                      >
                        <X className="w-3 h-3" />
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          )}

          <div className="flex items-end gap-3 bg-white p-2.5 rounded-2xl border border-slate-200 shadow-sm focus-within:border-blue-400 focus-within:ring-1 focus-within:ring-blue-100 transition-all relative">
            {/* Mention Suggestions moved inside relative container */}
            {showMentionSuggestions && filteredParticipants.length > 0 && (
              <div className="absolute bottom-full left-0 mb-2 w-64 bg-white border border-slate-200 rounded-lg shadow-lg overflow-hidden max-h-48 overflow-y-auto z-50 custom-scrollbar" data-testid="onboarding-worknotes-mention-suggestions">
                {filteredParticipants.map((participant, pIdx) => (
                  <button
                    key={participant.id}
                    onClick={() => handleMentionSelect(participant)}
                    className="w-full flex items-center gap-3 px-4 py-2 hover:bg-slate-50 transition-colors text-left"
                    data-testid={`onboarding-worknotes-mention-item-${pIdx}`}
                  >
                    <Avatar className="w-8 h-8">
                      <AvatarFallback className={`${participant.color} text-white text-xs`}>
                        {participant.initials}
                      </AvatarFallback>
                    </Avatar>
                    <div className="flex flex-col">
                      <span className="text-slate-900 text-sm font-medium">{participant.name}</span>
                    </div>
                  </button>
                ))}
              </div>
            )}
            <div className="flex items-center gap-1 mb-1">
              <input
                type="file"
                ref={fileInputRef}
                className="hidden"
                multiple
                onChange={handleFileUpload}
              />
              <Button
                variant="ghost"
                size="icon"
                className="w-9 h-9 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-xl"
                onClick={() => fileInputRef.current?.click()}
                data-testid="onboarding-worknotes-attachment-btn"
              >
                <Paperclip className="w-5 h-5" />
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className={`w-9 h-9 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-xl relative ${isEmojiPickerOpen ? 'bg-blue-50 text-blue-600' : ''}`}
                onClick={() => setIsEmojiPickerOpen(!isEmojiPickerOpen)}
                data-testid="onboarding-worknotes-emoji-btn"
              >
                <Smile className="w-5 h-5" />
                {isEmojiPickerOpen && (
                  <div className="absolute bottom-12 left-0 z-50 bg-white border border-slate-200 rounded-xl shadow-2xl w-72 animate-in fade-in slide-in-from-bottom-2 overflow-hidden" data-testid="onboarding-worknotes-emoji-picker">
                    <div className="px-3 py-2 border-b border-slate-100 bg-slate-50 flex items-center justify-between">
                      <span className="text-xs font-semibold text-slate-500 uppercase tracking-wider">Emojis</span>
                      <button
                        onClick={() => setIsEmojiPickerOpen(false)}
                        className="text-slate-400 hover:text-slate-600 text-lg leading-none"
                      >
                        &times;
                      </button>
                    </div>
                    <div className="p-2 grid grid-cols-8 gap-1 max-h-60 overflow-y-auto custom-scrollbar">
                      {COMMON_EMOJIS.map((emoji, eIdx) => (
                        <button
                          key={emoji}
                          className="w-8 h-8 flex items-center justify-center hover:bg-blue-50 hover:scale-110 rounded-lg transition-all text-lg"
                          onClick={(e) => {
                            e.stopPropagation();
                            handleEmojiSelect(emoji);
                          }}
                          data-testid={`onboarding-worknotes-emoji-item-${eIdx}`}
                        >
                          {emoji}
                        </button>
                      ))}
                    </div>
                  </div>
                )}
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className="w-9 h-9 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-xl"
                onClick={() => fileInputRef.current?.click()}
              >
                <ImageIcon className="w-5 h-5" />
              </Button>
            </div>

            <div className="flex-1 relative">
              <Input
                ref={inputRef}
                type="text"
                placeholder="Type your message... Use @username to mention someone"
                value={message}
                onChange={handleInputChange}
                onKeyPress={handleKeyPress}
                className="w-full pr-4 border-none focus-visible:ring-0 px-0"
              />
            </div>

            <Button
              onClick={handleSendMessage}
              disabled={!message.trim() && attachedFiles.length === 0 || isUploading}
              className="bg-blue-600 hover:bg-blue-700 text-white rounded-xl h-10 w-10 p-0"
            >
              {isUploading ? (
                <div className="h-4 w-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
              ) : (
                <Send className="w-5 h-5" />
              )}
            </Button>
          </div>

          <p className="text-slate-400 text-[10px] px-1 flex items-center gap-1">
            <Info className="w-3 h-3" />
            <span>Press Enter to send • Use @ to mention • {isUploading ? 'Uploading files...' : 'Files attached appear above'}</span>
          </p>
        </div>
      </div>
        </div>

    {/* Right Sidebar - Participants */}
    {isSidebarOpen && (
      <div className={`w-[280px] lg:w-[320px] bg-slate-50 border-l border-slate-200 flex flex-col transition-all animate-in slide-in-from-right-full ${mode === 'modal' ? 'hidden lg:flex' : 'flex'}`}>
        <div className="p-4 border-b border-slate-200 bg-white">
          <div className="flex items-center justify-between mb-4">
            <h3 className="font-semibold text-slate-900 flex items-center gap-2">
              <Users className="w-4 h-4 text-blue-600" />
              Participants
              <Badge variant="secondary" className="bg-slate-100 text-slate-600 ml-1">
                {participantsList.length}
              </Badge>
            </h3>
            <Button variant="ghost" size="icon" className="h-8 w-8 text-slate-400 hover:text-slate-600" onClick={() => setIsSidebarOpen(false)}>
              <X className="w-4 h-4" />
            </Button>
          </div>

          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
            <Input
              type="text"
              placeholder="Search people..."
              value={participantSearch}
              onChange={(e) => setParticipantSearch(e.target.value)}
              className="pl-9 bg-slate-50 border-slate-200 h-9 text-sm rounded-lg focus-visible:bg-white transition-all"
            />
          </div>
        </div>

        <div className="flex-1 overflow-y-auto p-2 space-y-1 custom-scrollbar">
          {participantsList
            .filter(p => p.name.toLowerCase().includes(participantSearch.toLowerCase()) || p.role?.toLowerCase().includes(participantSearch.toLowerCase()))
            .map((participant) => {
              const isRevoked = !!participant.revokedAt;
              const canRevoke = ['DD Lead', 'DD Head', 'NBH', 'DD Admin', 'Super Admin'].includes(currentUser?.roleCode || '') && !isRevoked && participant.id !== currentUser?.id;

              return (
                <div 
                  key={participant.id} 
                  className={cn(
                    "group flex items-start gap-3 p-3 rounded-xl transition-all cursor-default border border-transparent",
                    isRevoked ? "opacity-50 bg-slate-100 grayscale-[0.5]" : "hover:bg-white hover:shadow-sm hover:border-slate-100"
                  )}
                >
                  <div className="relative">
                    <Avatar className={cn(
                      "w-10 h-10 ring-2 ring-transparent transition-all",
                      !isRevoked && "group-hover:ring-blue-100"
                    )}>
                      <AvatarFallback className={`${participant.color} text-white text-xs font-bold`}>
                        {participant.initials}
                      </AvatarFallback>
                    </Avatar>
                    {participant.isOnline && !isRevoked && (
                      <span className="absolute bottom-0 right-0 w-3 h-3 bg-green-500 border-2 border-slate-50 rounded-full shadow-sm"></span>
                    )}
                    {isRevoked && (
                      <span className="absolute -top-1 -right-1 bg-red-100 rounded-full p-0.5 border border-white">
                        <UserX className="w-2.5 h-2.5 text-red-600" />
                      </span>
                    )}
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center justify-between mb-0.5">
                      <div className="flex items-center gap-1.5 min-w-0">
                        <p className={cn("text-sm font-semibold truncate", isRevoked ? "text-slate-500 line-through" : "text-slate-900")}>
                          {participant.name}
                        </p>
                        {isRevoked && (
                          <Badge variant="outline" className="text-[8px] h-3.5 px-1 bg-red-50 text-red-600 border-red-100">Revoked</Badge>
                        )}
                      </div>
                      {participant.id === currentUser?.id && (
                        <Badge variant="outline" className="text-[9px] h-4 px-1 border-blue-200 text-blue-600 bg-blue-50">You</Badge>
                      )}
                    </div>
                    <p className="text-[11px] text-slate-500 font-medium uppercase tracking-wider mb-1">
                      {participant.role}
                    </p>
                    <p className="text-[11px] text-slate-400 truncate italic">
                      {participant.email}
                    </p>
                  </div>
                  
                  {canRevoke && (
                    <Button 
                      variant="ghost" 
                      size="sm" 
                      className="h-8 w-8 p-0 text-slate-300 hover:text-red-600 hover:bg-red-50 opacity-0 group-hover:opacity-100 transition-all self-center"
                      onClick={() => handleRevokeConfirm(participant)}
                    >
                      <UserX className="w-3.5 h-3.5" />
                    </Button>
                  )}
                  
                  {!canRevoke && !isRevoked && (
                    <ChevronRight className="w-4 h-4 text-slate-300 group-hover:text-slate-400 opacity-0 group-hover:opacity-100 transition-all self-center" />
                  )}
                </div>
              );
            })}
          
          {participantsList.length === 0 && (
            <div className="flex flex-col items-center justify-center py-12 text-center opacity-50">
              <Users className="w-8 h-8 text-slate-300 mb-2" />
              <p className="text-xs text-slate-500">No participants found</p>
            </div>
          )}
        </div>

        <div className="p-4 bg-white border-t border-slate-200">
          <div className="flex items-center gap-2 mb-3">
            <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
            <span className="text-[10px] font-bold text-slate-500 uppercase tracking-widest">Active Session</span>
          </div>
          <div className="flex items-center gap-3 p-2 rounded-lg bg-slate-50 border border-slate-100">
            <ClockIcon className="w-4 h-4 text-slate-400" />
            <div>
              <p className="text-[10px] text-slate-500 font-medium uppercase">Last Activity</p>
              <p className="text-xs text-slate-900 font-semibold">Just now</p>
            </div>
          </div>
        </div>
      </div>
    )}
  </div>

      {/* Preview Modal */}
      <Dialog open={!!previewFile} onOpenChange={(open) => !open && setPreviewFile(null)}>
        <DialogContent className="max-w-6xl h-[90vh] flex flex-col p-4">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              {previewFile && getFileIcon(previewFile.mimeType)}
              <span className="truncate">{previewFile?.fileName}</span>
            </DialogTitle>
          </DialogHeader>
          <div className="flex-1 overflow-hidden rounded-lg bg-slate-100 flex items-center justify-center p-4">
            {previewFile?.mimeType.startsWith('image/') ? (
              <img
                src={`${BACKEND_URL}/${previewFile.filePath.replace(/\\/g, '/')}`}
                className="max-w-full max-h-full object-contain"
                alt="Preview"
              />
            ) : previewFile?.mimeType === 'application/pdf' ? (
              <iframe
                src={`${BACKEND_URL}/${previewFile.filePath.replace(/\\/g, '/')}`}
                className="w-full h-full border-none"
                title="PDF Preview"
              />
            ) : (
              <div className="text-center">
                <FileIcon className="w-16 h-16 text-slate-300 mx-auto mb-4" />
                <p className="text-slate-500">Preview not available for this file type.</p>
                <a
                  href={`${BACKEND_URL}/${previewFile?.filePath.replace(/\\/g, '/')}`}
                  target="_blank"
                  rel="noreferrer"
                  className="text-blue-600 hover:underline text-sm"
                >
                  Open in new tab
                </a>
              </div>
            )}
          </div>
        </DialogContent>
      </Dialog>
      {/* Revocation Confirmation Modal */}
      <Dialog open={!!revokeConfirmParticipant} onOpenChange={(open) => !open && setRevokeConfirmParticipant(null)}>
        <DialogContent className="max-w-md p-0 overflow-hidden border-none shadow-2xl [&>button]:text-white [&>button]:opacity-100">
          <div className="bg-gradient-to-br from-red-600 to-red-700 p-6 text-white text-center">
            <div className="w-16 h-16 bg-white/20 rounded-full flex items-center justify-center mx-auto mb-4 border border-white/30 backdrop-blur-sm animate-pulse">
              <UserX className="w-8 h-8 text-white" />
            </div>
            <h3 className="text-xl font-bold mb-2">Revoke Participant Access?</h3>
            <p className="text-red-100 text-sm">
              You are about to revoke access for <span className="font-bold text-white">{revokeConfirmParticipant?.name}</span>. They will no longer be able to view or interact with this request.
            </p>
          </div>
          
          <div className="p-6 bg-white space-y-4">
             <div className="space-y-2">
                <label className="text-xs font-bold text-slate-500 uppercase tracking-widest">Reason for Revocation</label>
                <Input 
                   value={revocationReason}
                   onChange={(e) => setRevocationReason(e.target.value)}
                   placeholder="e.g. Roles changed, Case transferred..."
                   className="bg-slate-50 border-slate-200 focus:bg-white transition-all h-11"
                />
             </div>
             
             <div className="flex gap-3 pt-2">
                <Button 
                   variant="outline" 
                   className="flex-1 h-11 border-slate-200 text-slate-600 hover:bg-slate-50"
                   onClick={() => setRevokeConfirmParticipant(null)}
                >
                   Cancel
                </Button>
                <Button 
                   className="flex-1 h-11 bg-red-600 hover:bg-red-700 text-white font-bold shadow-lg shadow-red-200"
                   onClick={confirmRevocation}
                   disabled={isRevoking}
                >
                   {isRevoking ? <RefreshCcw className="w-4 h-4 animate-spin mr-2" /> : null}
                   Revoke Access
                </Button>
             </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}

export default WorkNotesPage;
