'use client';

import { useState, useRef, useEffect, useCallback } from 'react';
import { useAppStore } from '@/lib/store';
import { t } from '@/lib/i18n';
import { mockConversations, mockChatMessages } from '@/lib/mock-data';
import { toast } from '@/hooks/use-toast';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Separator } from '@/components/ui/separator';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuSeparator,
} from '@/components/ui/dropdown-menu';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import {
  Search,
  ArrowLeft,
  Send,
  Paperclip,
  Check,
  CheckCheck,
  Phone,
  MoreVertical,
  Image as ImageIcon,
  Smile,
  Eye,
  EyeOff,
  Mic,
  MicOff,
  Square,
  X,
  FileText,
  Film,
  Music,
  Play,
  Pause,
  Camera,
  Download,
  UserCircle,
  SearchIcon,
  BellOff,
  Ban,
  Trash2,
  Flag,
  Volume2,
} from 'lucide-react';

// ─── Emoji Data ───
const emojiCategories = [
  {
    name: 'Smileys',
    emojis: '😀😁😂🤣😃😄😅😆😉😊😋😎😍🥰😘😗😙😚🙂🤗🤩🤔🤨😐😑😶🙄😏😣😥😮🤐😯😪😫🥱😴😌😛😜😝🤤😒😓😔😕🙃🤑😲🙁😖😞😟😤😢😭😦😧😨😩🤯😬😰😱🥵🥶😳🤪😵😡😠🤬'.split(''),
  },
  {
    name: 'Gestures',
    emojis: '👋🤚🖐✋🖖👌🤌🤏✌🤞🤟🤘🤙👈👉👆🖕👇☝👍👎✊👊🤛🤜👏🙌👐🤲🤝🙏'.split(''),
  },
  {
    name: 'Hearts',
    emojis: ['❤️', '🧡', '💛', '💚', '💙', '💜', '🖤', '🤍', '🤎', '💔', '❣️', '💕', '💞', '💓', '💗', '💖', '💘', '💝'],
  },
  {
    name: 'Objects',
    emojis: ['🎉', '🎊', '🎈', '🎁', '🏆', '⭐', '🔥', '💯', '✅', '❌', '⚡', '💡', '🔔', '🎵', '🎶'],
  },
];

// ─── Types ───
type ChatMessage = {
  id: string;
  senderId: string;
  content: string;
  time: string;
  isMe: boolean;
  date: string;
  type?: 'text' | 'image' | 'video' | 'voice' | 'file';
  fileUrl?: string;
  fileName?: string;
  fileSize?: number;
  isRead?: boolean;
};

type Conversation = (typeof mockConversations)[number];

// ─── Helpers ───
function getInitials(name: string): string {
  return name
    .split(' ')
    .map((n) => n[0])
    .join('')
    .toUpperCase()
    .slice(0, 2);
}

const avatarColors = [
  'bg-orange-500',
  'bg-emerald-500',
  'bg-amber-500',
  'bg-rose-500',
  'bg-orange-600',
  'bg-amber-500',
  'bg-orange-500',
  'bg-pink-500',
];

function getAvatarColor(name: string): string {
  let hash = 0;
  for (let i = 0; i < name.length; i++) {
    hash = name.charCodeAt(i) + ((hash << 5) - hash);
  }
  return avatarColors[Math.abs(hash) % avatarColors.length];
}

function formatFileSize(bytes: number): string {
  if (bytes < 1024) return bytes + ' B';
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
  return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
}

function formatRecordingTime(seconds: number): string {
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}

// ─── Extended Messages ───
const extendedMessages: ChatMessage[] = [
  { id: 'm0', senderId: 'c1', content: 'Hello! I saw your listing for the Dhanmondi flat.', time: '10:30 AM', isMe: true, date: 'Today', type: 'text' },
  { id: 'm1', senderId: 'c1', content: 'Hi! Yes, the flat is available. Are you interested?', time: '10:32 AM', isMe: false, date: 'Today', type: 'text' },
  { id: 'm2', senderId: 'c1', content: 'Yes, definitely! Can you tell me more about the amenities? Is there parking available?', time: '10:33 AM', isMe: true, date: 'Today', type: 'text' },
  { id: 'm3', senderId: 'c1', content: 'Of course! The flat comes with 1 dedicated parking spot, 24/7 security, generator backup, and rooftop access. Water and gas are included in the rent.', time: '10:35 AM', isMe: false, date: 'Today', type: 'text' },
  { id: 'm4', senderId: 'c1', content: 'That sounds great! What about the nearby facilities?', time: '10:36 AM', isMe: true, date: 'Today', type: 'text' },
  { id: 'm5', senderId: 'c1', content: "You'll love the location! Dhanmondi Lake is a 5-minute walk, there are several supermarkets, restaurants, and a hospital nearby.", time: '10:38 AM', isMe: false, date: 'Today', type: 'text' },
  { id: 'm6', senderId: 'c1', content: 'Yes, I would like to visit. Is this weekend okay?', time: '10:40 AM', isMe: true, date: 'Today', type: 'text' },
  { id: 'm7', senderId: 'c1', content: 'The flat is still available. When can you visit?', time: '10:42 AM', isMe: false, date: 'Today', type: 'text' },
];

// ─── Voice Message Player Component ───
function VoiceMessagePlayer({ src, isMe }: { src: string; isMe: boolean }) {
  const audioRef = useRef<HTMLAudioElement>(null);
  const [playing, setPlaying] = useState(false);
  const [progress, setProgress] = useState(0);
  const [duration, setDuration] = useState(0);

  useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;

    const onLoaded = () => setDuration(audio.duration);
    const onTimeUpdate = () => {
      if (audio.duration) setProgress((audio.currentTime / audio.duration) * 100);
    };
    const onEnded = () => {
      setPlaying(false);
      setProgress(0);
    };

    audio.addEventListener('loadedmetadata', onLoaded);
    audio.addEventListener('timeupdate', onTimeUpdate);
    audio.addEventListener('ended', onEnded);

    return () => {
      audio.removeEventListener('loadedmetadata', onLoaded);
      audio.removeEventListener('timeupdate', onTimeUpdate);
      audio.removeEventListener('ended', onEnded);
    };
  }, []);

  const togglePlay = () => {
    const audio = audioRef.current;
    if (!audio) return;
    if (playing) {
      audio.pause();
    } else {
      audio.play();
    }
    setPlaying(!playing);
  };

  return (
    <div className="flex items-center gap-2 min-w-[180px]">
      <audio ref={audioRef} src={src} preload="metadata" />
      <button
        onClick={togglePlay}
        className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-full ${
          isMe ? 'bg-white/20 text-white' : 'bg-orange-500 text-white'
        }`}
      >
        {playing ? <Pause className="h-3.5 w-3.5" /> : <Play className="h-3.5 w-3.5 ml-0.5" />}
      </button>
      <div className="flex-1">
        {/* Waveform visualization */}
        <div className="flex items-center gap-[2px] h-6">
          {Array.from({ length: 24 }).map((_, i) => {
            const height = Math.abs(Math.sin(i * 0.8) * 16 + Math.random() * 6) + 4;
            const isFilled = (i / 24) * 100 < progress;
            return (
              <div
                key={i}
                className={`w-[3px] rounded-full transition-all ${
                  isFilled
                    ? isMe
                      ? 'bg-white/80'
                      : 'bg-orange-500'
                    : isMe
                    ? 'bg-white/30'
                    : 'bg-muted-foreground/30'
                }`}
                style={{ height: `${height}px` }}
              />
            );
          })}
        </div>
      </div>
      <span className={`text-[10px] shrink-0 ${isMe ? 'text-white/60' : 'text-muted-foreground'}`}>
        {duration ? `${Math.floor(duration / 60)}:${Math.floor(duration % 60).toString().padStart(2, '0')}` : '0:00'}
      </span>
    </div>
  );
}

// ─── Main Component ───
export default function MessagesModule() {
  const { language, openChatWith, setOpenChatWith, setCurrentSection } = useAppStore();
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedConversation, setSelectedConversation] = useState<Conversation | null>(null);
  const [messageInput, setMessageInput] = useState('');
  const [messages, setMessages] = useState<ChatMessage[]>(extendedMessages);
  const [sending, setSending] = useState(false);
  const [allConversations, setAllConversations] = useState<Conversation[]>([...mockConversations]);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  const messageAreaRef = useRef<HTMLDivElement>(null);
  const processedChatIdRef = useRef<string | null>(null);

  // Attachment states
  const [pendingImage, setPendingImage] = useState<{ url: string; file: File } | null>(null);
  const [pendingFile, setPendingFile] = useState<{ file: File; type: 'image' | 'video' | 'voice' | 'file' } | null>(null);

  // Recording states
  const [isRecording, setIsRecording] = useState(false);
  const [recordingTime, setRecordingTime] = useState(0);
  const [mediaRecorder, setMediaRecorder] = useState<MediaRecorder | null>(null);
  const recordingTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);
  const audioChunksRef = useRef<Blob[]>([]);

  // Menu states
  const [isMuted, setIsMuted] = useState(false);
  const [confirmDialog, setConfirmDialog] = useState<{
    open: boolean;
    type: 'block' | 'clear' | 'report' | null;
  }>({ open: false, type: null });

  // Popover states
  const [attachPopoverOpen, setAttachPopoverOpen] = useState(false);
  const [emojiPopoverOpen, setEmojiPopoverOpen] = useState(false);

  // Refs for file inputs
  const photoInputRef = useRef<HTMLInputElement>(null);
  const docInputRef = useRef<HTMLInputElement>(null);

  // Handle navigation from Contact Owner button
  useEffect(() => {
    if (!openChatWith) return;
    if (processedChatIdRef.current === openChatWith.id) return;
    processedChatIdRef.current = openChatWith.id;

    const chatTarget = { ...openChatWith };

    const timer = setTimeout(() => {
      const existingConv = allConversations.find(
        (c) => c.name.toLowerCase() === chatTarget.name.toLowerCase()
      );

      if (existingConv) {
        setSelectedConversation(existingConv);
        setMessages(extendedMessages);
        setOpenChatWith(null);
      } else {
        const newConv: Conversation = {
          id: chatTarget.id,
          name: chatTarget.name,
          lastMessage: chatTarget.listingTitle
            ? `Regarding: ${chatTarget.listingTitle}`
            : 'Start a conversation',
          time: 'Just now',
          unread: 0,
          online: true,
          avatar: null,
        };
        setAllConversations((prev) => [newConv, ...prev]);
        setSelectedConversation(newConv);
        setMessages([
          {
            id: `m-auto-${Date.now()}`,
            senderId: newConv.id,
            content: chatTarget.listingTitle
              ? `Hi! I'm interested in your listing: "${chatTarget.listingTitle}". Is it still available?`
              : 'Hi! I wanted to get in touch with you.',
            time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
            isMe: true,
            date: 'Today',
            type: 'text',
          },
        ]);
        setOpenChatWith(null);
      }
    }, 0);

    return () => clearTimeout(timer);
  }, [openChatWith, allConversations, setOpenChatWith]);

  // Filter conversations
  const filteredConversations = allConversations.filter(
    (conv) =>
      conv.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      conv.lastMessage.toLowerCase().includes(searchQuery.toLowerCase())
  );

  // Scroll to bottom
  const scrollToBottom = useCallback(() => {
    if (messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  }, []);

  useEffect(() => {
    scrollToBottom();
  }, [messages, selectedConversation, scrollToBottom]);

  // Focus input when conversation is opened
  useEffect(() => {
    if (selectedConversation && !isRecording) {
      setTimeout(() => inputRef.current?.focus(), 100);
    }
  }, [selectedConversation, isRecording]);

  // ─── Upload file helper ───
  const uploadFile = async (file: File, type: string): Promise<string | null> => {
    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('type', type);

      const res = await fetch('/api/upload', {
        method: 'POST',
        body: formData,
      });
      const data = await res.json();
      return data.url || null;
    } catch (err) {
      console.error('Upload failed:', err);
      return null;
    }
  };

  // ─── Send message (with file support) ───
  const handleSendMessage = useCallback(async (overrideContent?: string, overrideType?: ChatMessage['type'], overrideFileUrl?: string, overrideFileName?: string, overrideFileSize?: number) => {
    const content = overrideContent || messageInput.trim();
    const msgType = overrideType || 'text';

    if (!content && msgType === 'text') return;

    setSending(true);
    const newMessage: ChatMessage = {
      id: `m${Date.now()}`,
      senderId: selectedConversation?.id || 'c1',
      content: content,
      time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
      isMe: true,
      date: 'Today',
      type: msgType,
      fileUrl: overrideFileUrl,
      fileName: overrideFileName,
      fileSize: overrideFileSize,
      isRead: false,
    };

    setMessages((prev) => [...prev, newMessage]);
    setMessageInput('');
    setPendingImage(null);
    setPendingFile(null);
    setSending(false);

    // Simulate a reply
    const convId = selectedConversation?.id || 'c1';
    setTimeout(() => {
      const replies = [
        'Thank you for your message! I\'ll get back to you shortly.',
        'Sure, let me check and confirm.',
        'That works for me! See you then.',
        'I appreciate your interest. Let me find out more details.',
        'Got it! I\'ll look into this right away.',
        'Thanks for sharing! Let me review and get back to you.',
      ];
      const reply: ChatMessage = {
        id: `m${Date.now() + 1}`,
        senderId: convId,
        content: replies[Math.floor(Math.random() * replies.length)],
        time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
        isMe: false,
        date: 'Today',
        type: 'text',
      };
      setMessages((prev) => [...prev, reply]);
    }, 1500);
  }, [messageInput, selectedConversation]);

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      if (pendingImage || pendingFile) {
        handleSendPendingFile();
      } else {
        handleSendMessage();
      }
    }
  };

  const handleBack = () => {
    setSelectedConversation(null);
    setMessages(extendedMessages);
    setPendingImage(null);
    setPendingFile(null);
    cancelRecording();
  };

  // ─── Emoji handler ───
  const handleEmojiClick = (emoji: string) => {
    setMessageInput((prev) => prev + emoji);
    inputRef.current?.focus();
  };

  // ─── Image compression helper ───
  const compressImage = async (file: File, maxWidth = 1200, quality = 0.8): Promise<File> => {
    return new Promise((resolve) => {
      if (!file.type.startsWith('image/')) {
        resolve(file);
        return;
      }
      const img = new Image();
      const url = URL.createObjectURL(file);
      img.onload = () => {
        URL.revokeObjectURL(url);
        if (img.width <= maxWidth) {
          resolve(file);
          return;
        }
        const canvas = document.createElement('canvas');
        const ratio = maxWidth / img.width;
        canvas.width = maxWidth;
        canvas.height = img.height * ratio;
        const ctx = canvas.getContext('2d');
        if (!ctx) { resolve(file); return; }
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        canvas.toBlob(
          (blob) => {
            if (!blob) { resolve(file); return; }
            const compressedFile = new File([blob], file.name, { type: file.type });
            resolve(compressedFile);
          },
          file.type,
          quality
        );
      };
      img.onerror = () => {
        URL.revokeObjectURL(url);
        resolve(file);
      };
      img.src = url;
    });
  };

  // ─── File selection handlers ───
  const handlePhotoSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    if (file.type.startsWith('image/')) {
      const compressedFile = await compressImage(file);
      const url = URL.createObjectURL(compressedFile);
      setPendingImage({ url, file: compressedFile });
      setPendingFile({ file: compressedFile, type: 'image' });
    } else if (file.type.startsWith('video/')) {
      const url = URL.createObjectURL(file);
      setPendingImage({ url, file });
      setPendingFile({ file, type: 'video' });
    }
    // Reset input
    e.target.value = '';
  };

  const handleDocSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    if (file.type.startsWith('image/')) {
      const compressedFile = await compressImage(file);
      const url = URL.createObjectURL(compressedFile);
      setPendingImage({ url, file: compressedFile });
      setPendingFile({ file: compressedFile, type: 'image' });
    } else if (file.type.startsWith('video/')) {
      const url = URL.createObjectURL(file);
      setPendingImage({ url, file });
      setPendingFile({ file, type: 'video' });
    } else if (file.type.startsWith('audio/')) {
      setPendingFile({ file, type: 'voice' });
      setPendingImage(null);
    } else {
      setPendingFile({ file, type: 'file' });
      setPendingImage(null);
    }
    e.target.value = '';
  };

  // ─── Send pending file ───
  const handleSendPendingFile = useCallback(async () => {
    if (!pendingFile) return;

    const { file, type } = pendingFile;
    const fileUrl = await uploadFile(file, type === 'voice' ? 'voice' : type === 'file' ? 'document' : 'message');

    const content = type === 'image'
      ? '📷 Photo'
      : type === 'video'
      ? '🎥 Video'
      : type === 'voice'
      ? '🎤 Voice message'
      : `📄 ${file.name}`;

    handleSendMessage(content, type, fileUrl || undefined, file.name, file.size);
  }, [pendingFile, handleSendMessage]);

  // ─── Voice Recording ───
  const startRecording = async () => {
    // Check browser support
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
      toast({
        title: language === 'bn' ? 'রেকর্ডিং সমর্থিত নয়' : 'Recording not supported',
        description: language === 'bn' ? 'আপনার ব্রাউজার অডিও রেকর্ডিং সমর্থন করে না।' : 'Your browser does not support audio recording.',
        variant: 'destructive',
      });
      return;
    }

    if (typeof MediaRecorder === 'undefined') {
      toast({
        title: language === 'bn' ? 'রেকর্ডিং সমর্থিত নয়' : 'Recording not supported',
        description: language === 'bn' ? 'মিডিয়া রেকর্ডার আপনার ব্রাউজারে উপলব্ধ নয়।' : 'MediaRecorder is not available in your browser.',
        variant: 'destructive',
      });
      return;
    }

    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      // Determine supported MIME type
      const mimeType = MediaRecorder.isTypeSupported('audio/webm;codecs=opus')
        ? 'audio/webm;codecs=opus'
        : MediaRecorder.isTypeSupported('audio/webm')
        ? 'audio/webm'
        : 'audio/mp4';

      const recorder = new MediaRecorder(stream, { mimeType });
      audioChunksRef.current = [];

      recorder.ondataavailable = (e) => {
        if (e.data.size > 0) {
          audioChunksRef.current.push(e.data);
        }
      };

      recorder.onstop = async () => {
        const blob = new Blob(audioChunksRef.current, { type: mimeType });
        const ext = mimeType.includes('mp4') ? 'mp4' : 'webm';
        const file = new File([blob], `voice-${Date.now()}.${ext}`, { type: mimeType });

        // Upload and send
        const fileUrl = await uploadFile(file, 'voice');
        handleSendMessage('🎤 Voice message', 'voice', fileUrl || undefined, file.name, file.size);

        // Cleanup stream
        stream.getTracks().forEach((track) => track.stop());
      };

      recorder.start();
      setMediaRecorder(recorder);
      setIsRecording(true);
      setRecordingTime(0);
      setAttachPopoverOpen(false);

      recordingTimerRef.current = setInterval(() => {
        setRecordingTime((prev) => prev + 1);
      }, 1000);
    } catch (err) {
      console.error('Failed to start recording:', err);
      if (err instanceof DOMException && err.name === 'NotAllowedError') {
        toast({
          title: language === 'bn' ? 'মাইক্রোফোন অ্যাক্সেস অস্বীকৃত' : 'Microphone access denied',
          description: language === 'bn' ? 'ভয়েস মেসেজ রেকর্ড করতে মাইক্রোফোন অনুমতি দিন।' : 'Please allow microphone permission to record voice messages.',
          variant: 'destructive',
        });
      } else {
        toast({
          title: language === 'bn' ? 'রেকর্ডিং ব্যর্থ' : 'Recording failed',
          description: language === 'bn' ? 'ভয়েস রেকর্ডিং শুরু করা যায়নি।' : 'Could not start voice recording.',
          variant: 'destructive',
        });
      }
    }
  };

  const stopRecording = () => {
    if (mediaRecorder && mediaRecorder.state === 'recording') {
      mediaRecorder.stop();
    }
    setIsRecording(false);
    if (recordingTimerRef.current) {
      clearInterval(recordingTimerRef.current);
      recordingTimerRef.current = null;
    }
    setRecordingTime(0);
    setMediaRecorder(null);
  };

  const cancelRecording = () => {
    if (mediaRecorder && mediaRecorder.state === 'recording') {
      mediaRecorder.stream.getTracks().forEach((track) => track.stop());
      mediaRecorder.stop();
    }
    setIsRecording(false);
    if (recordingTimerRef.current) {
      clearInterval(recordingTimerRef.current);
      recordingTimerRef.current = null;
    }
    setRecordingTime(0);
    setMediaRecorder(null);
    audioChunksRef.current = [];
  };

  // ─── Three-dot menu actions ───
  const handleViewProfile = () => {
    if (selectedConversation) {
      toast({
        title: selectedConversation.name,
        description: language === 'bn'
          ? `${selectedConversation.name} এর প্রোফাইল দেখছেন`
          : `Viewing ${selectedConversation.name}'s profile`,
      });
    }
  };

  const handleMuteToggle = () => {
    setIsMuted((prev) => !prev);
    toast({
      title: isMuted
        ? (language === 'bn' ? 'নোটিফিকেশন চালু করা হয়েছে' : 'Notifications unmuted')
        : (language === 'bn' ? 'নোটিফিকেশন নিঃশব্দ করা হয়েছে' : 'Notifications muted'),
      description: isMuted
        ? (language === 'bn' ? `আপনি এখন ${selectedConversation?.name} থেকে নোটিফিকেশন পাবেন` : `You will now receive notifications from ${selectedConversation?.name}`)
        : (language === 'bn' ? `${selectedConversation?.name} থেকে নোটিফিকেশন নিঃশব্দ করা হয়েছে` : `Notifications from ${selectedConversation?.name} have been muted`),
    });
  };

  const handleBlockUser = () => {
    setConfirmDialog({ open: true, type: 'block' });
  };

  const handleClearChat = () => {
    setConfirmDialog({ open: true, type: 'clear' });
  };

  const handleReportUser = () => {
    setConfirmDialog({ open: true, type: 'report' });
  };

  const handleConfirmAction = () => {
    if (confirmDialog.type === 'block') {
      toast({
        title: language === 'bn' ? 'ব্যবহারকারী ব্লক করা হয়েছে' : 'User blocked',
        description: language === 'bn'
          ? `${selectedConversation?.name}-কে ব্লক করা হয়েছে`
          : `${selectedConversation?.name} has been blocked`,
      });
      handleBack();
    } else if (confirmDialog.type === 'clear') {
      setMessages([]);
      toast({
        title: language === 'bn' ? 'চ্যাট মুছে ফেলা হয়েছে' : 'Chat cleared',
        description: language === 'bn'
          ? 'সমস্ত মেসেজ মুছে ফেলা হয়েছে'
          : 'All messages have been deleted',
      });
    } else if (confirmDialog.type === 'report') {
      toast({
        title: language === 'bn' ? 'রিপোর্ট জমা হয়েছে' : 'Report submitted',
        description: language === 'bn'
          ? `${selectedConversation?.name}-কে রিপোর্ট করা হয়েছে। আমরা এই বিষয়ে তদন্ত করব।`
          : `${selectedConversation?.name} has been reported. We will investigate this matter.`,
      });
    }
    setConfirmDialog({ open: false, type: null });
  };

  // ─── Render message content based on type ───
  const renderMessageContent = (msg: ChatMessage, conv: Conversation) => {
    switch (msg.type) {
      case 'image':
        return (
          <div className="space-y-1">
            {msg.fileUrl && (
              <img
                src={msg.fileUrl}
                alt={msg.content || 'Shared image'}
                className="rounded-lg max-h-[200px] w-auto object-cover cursor-pointer hover:opacity-90 transition-opacity"
                onClick={() => window.open(msg.fileUrl, '_blank')}
                onError={(e) => {
                  (e.target as HTMLImageElement).style.display = 'none';
                }}
              />
            )}
            {msg.content && msg.content !== '📷 Photo' && (
              <p className="text-[13px] leading-relaxed whitespace-pre-wrap break-words">{msg.content}</p>
            )}
          </div>
        );

      case 'video':
        return (
          <div className="space-y-1">
            {msg.fileUrl ? (
              <video
                src={msg.fileUrl}
                controls
                className="rounded-lg max-h-[200px] w-auto"
                onError={(e) => {
                  (e.target as HTMLVideoElement).style.display = 'none';
                }}
              />
            ) : (
              <div className="flex items-center justify-center rounded-lg bg-black/10 dark:bg-white/10 h-[120px] w-[200px]">
                <Film className="h-8 w-8 text-muted-foreground/50" />
              </div>
            )}
            <div className="flex items-center gap-1.5">
              <Film className="h-3.5 w-3.5" />
              <span className="text-[12px]">{msg.fileName || msg.content || 'Video'}</span>
              {msg.fileSize && <span className="text-[10px] opacity-60">({formatFileSize(msg.fileSize)})</span>}
            </div>
          </div>
        );

      case 'voice':
        return (
          <div>
            <VoiceMessagePlayer src={msg.fileUrl || ''} isMe={msg.isMe} />
          </div>
        );

      case 'file':
        return (
          <div className="flex items-center gap-3 min-w-[200px]">
            <div className={`flex h-10 w-10 shrink-0 items-center justify-center rounded-lg ${
              msg.isMe ? 'bg-white/20' : 'bg-orange-100'
            }`}>
              <FileText className={`h-5 w-5 ${msg.isMe ? 'text-white' : 'text-orange-600'}`} />
            </div>
            <div className="min-w-0 flex-1">
              <p className="text-[13px] font-medium truncate">{msg.fileName || 'Document'}</p>
              <p className={`text-[11px] ${msg.isMe ? 'text-white/60' : 'text-muted-foreground'}`}>
                {msg.fileSize ? formatFileSize(msg.fileSize) : 'File'}
              </p>
            </div>
            {msg.fileUrl && (
              <a
                href={msg.fileUrl}
                download
                className={`shrink-0 p-1 rounded ${msg.isMe ? 'hover:bg-white/20' : 'hover:bg-accent'}`}
                onClick={(e) => e.stopPropagation()}
              >
                <Download className={`h-4 w-4 ${msg.isMe ? 'text-white/80' : 'text-muted-foreground'}`} />
              </a>
            )}
          </div>
        );

      default:
        return (
          <p className="text-[13px] leading-relaxed whitespace-pre-wrap break-words">{msg.content}</p>
        );
    }
  };

  // ─── Conversation List View ───
  const renderConversationList = () => (
    <div className="flex h-full flex-col">
      {/* Header */}
      <div className="border-b bg-background px-4 py-3">
        <div className="flex items-center gap-3">
          <Button
            variant="ghost"
            size="icon"
            onClick={() => setCurrentSection('home')}
            className="shrink-0 h-9 w-9"
          >
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <div>
            <h1 className="text-xl font-bold text-foreground">{t('msg.title', language)}</h1>
            <p className="mt-0.5 text-xs text-muted-foreground">
              {filteredConversations.length} {language === 'bn' ? 'কথোপকথন' : 'conversations'}
            </p>
          </div>
        </div>
      </div>

      {/* Search */}
      <div className="border-b px-4 py-3">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            placeholder={t('msg.search', language)}
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-9 h-9 bg-muted/50 border-0 focus-visible:ring-1 focus-visible:ring-primary/50"
          />
        </div>
      </div>

      {/* Conversations List */}
      <ScrollArea className="flex-1">
        <div className="divide-y">
          {filteredConversations.map((conv) => (
            <button
              key={conv.id}
              onClick={() => setSelectedConversation(conv)}
              className="flex w-full items-center gap-3 px-4 py-3 text-left transition-colors hover:bg-accent/50 active:bg-accent"
            >
              {/* Avatar with online indicator */}
              <div className="relative shrink-0">
                <Avatar className="h-12 w-12">
                  <AvatarFallback
                    className={`${getAvatarColor(conv.name)} text-sm font-semibold text-white`}
                  >
                    {getInitials(conv.name)}
                  </AvatarFallback>
                </Avatar>
                {conv.online && (
                  <span className="absolute bottom-0 right-0 h-3.5 w-3.5 rounded-full border-2 border-background bg-emerald-500" />
                )}
              </div>

              {/* Content */}
              <div className="min-w-0 flex-1">
                <div className="flex items-center justify-between gap-2">
                  <span
                    className={`truncate text-sm ${
                      conv.unread > 0 ? 'font-bold text-foreground' : 'font-medium text-foreground/80'
                    }`}
                  >
                    {conv.name}
                  </span>
                  <span className="shrink-0 text-[11px] text-muted-foreground">
                    {conv.time}
                  </span>
                </div>
                <div className="mt-0.5 flex items-center justify-between gap-2">
                  <p className="truncate text-xs text-muted-foreground">
                    {conv.lastMessage}
                  </p>
                  {conv.unread > 0 && (
                    <Badge className="h-5 min-w-5 shrink-0 rounded-full bg-primary px-1.5 text-[10px] font-bold text-primary-foreground">
                      {conv.unread}
                    </Badge>
                  )}
                </div>
              </div>
            </button>
          ))}

          {filteredConversations.length === 0 && (
            <div className="flex flex-col items-center justify-center py-16 text-center">
              <Search className="h-10 w-10 text-muted-foreground/40" />
              <p className="mt-3 text-sm text-muted-foreground">
                {t('common.noResults', language)}
              </p>
            </div>
          )}
        </div>
      </ScrollArea>
    </div>
  );

  // ─── Chat View ───
  const renderChatView = () => {
    const conv = selectedConversation!;

    // Group messages by date
    const groupedMessages: { date: string; messages: ChatMessage[] }[] = [];
    let currentDate = '';

    messages.forEach((msg) => {
      if (msg.date !== currentDate) {
        currentDate = msg.date;
        groupedMessages.push({ date: currentDate, messages: [msg] });
      } else {
        groupedMessages[groupedMessages.length - 1].messages.push(msg);
      }
    });

    return (
      <div className="flex h-full flex-col">
        {/* Chat Header */}
        <div className="flex items-center gap-3 border-b bg-background px-3 py-2.5 shadow-sm">
          <Button
            variant="ghost"
            size="icon"
            onClick={handleBack}
            className="h-9 w-9 shrink-0"
          >
            <ArrowLeft className="h-5 w-5" />
          </Button>

          <div className="relative shrink-0">
            <Avatar className="h-10 w-10">
              <AvatarFallback
                className={`${getAvatarColor(conv.name)} text-xs font-semibold text-white`}
              >
                {getInitials(conv.name)}
              </AvatarFallback>
            </Avatar>
            {conv.online && (
              <span className="absolute bottom-0 right-0 h-3 w-3 rounded-full border-2 border-background bg-emerald-500" />
            )}
          </div>

          <div className="min-w-0 flex-1">
            <h2 className="truncate text-sm font-semibold text-foreground">{conv.name}</h2>
            <p className={`text-[11px] ${isMuted ? 'text-muted-foreground' : 'text-emerald-500'}`}>
              {isMuted
                ? (language === 'bn' ? 'নিঃশব্দ করা হয়েছে' : 'Muted')
                : conv.online
                ? t('msg.online', language)
                : t('msg.offline', language)}
            </p>
          </div>

          <div className="flex items-center gap-1">
            <Button variant="ghost" size="icon" className="h-9 w-9 text-muted-foreground">
              <Phone className="h-4 w-4" />
            </Button>

            {/* Three-dot Menu */}
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="icon" className="h-9 w-9 text-muted-foreground">
                  <MoreVertical className="h-4 w-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-52">
                <DropdownMenuItem onSelect={handleViewProfile}>
                  <UserCircle className="h-4 w-4 mr-2" />
                  {language === 'bn' ? 'প্রোফাইল দেখুন' : 'View Profile'}
                </DropdownMenuItem>
                <DropdownMenuItem>
                  <SearchIcon className="h-4 w-4 mr-2" />
                  {language === 'bn' ? 'কথোপকথনে খুঁজুন' : 'Search in Conversation'}
                </DropdownMenuItem>
                <DropdownMenuItem onSelect={handleMuteToggle}>
                  {isMuted ? (
                    <>
                      <BellOff className="h-4 w-4 mr-2" />
                      {language === 'bn' ? 'নোটিফিকেশন চালু করুন' : 'Unmute Notifications'}
                    </>
                  ) : (
                    <>
                      <BellOff className="h-4 w-4 mr-2" />
                      {language === 'bn' ? 'নোটিফিকেশন নিঃশব্দ করুন' : 'Mute Notifications'}
                    </>
                  )}
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem onSelect={handleBlockUser} variant="destructive">
                  <Ban className="h-4 w-4 mr-2" />
                  {language === 'bn' ? 'ব্যবহারকারী ব্লক করুন' : 'Block User'}
                </DropdownMenuItem>
                <DropdownMenuItem onSelect={handleClearChat} variant="destructive">
                  <Trash2 className="h-4 w-4 mr-2" />
                  {language === 'bn' ? 'চ্যাট মুছুন' : 'Clear Chat'}
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem onSelect={handleReportUser} variant="destructive">
                  <Flag className="h-4 w-4 mr-2" />
                  {language === 'bn' ? 'ব্যবহারকারী রিপোর্ট করুন' : 'Report User'}
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>

        {/* Messages Area */}
        <div
          ref={messageAreaRef}
          className="flex-1 overflow-y-auto bg-muted/30 px-4 py-4"
          style={{
            scrollbarWidth: 'thin',
          }}
        >
          {groupedMessages.map((group) => (
            <div key={group.date}>
              <div className="my-4 flex justify-center">
                <span className="rounded-full bg-muted px-3 py-1 text-[11px] font-medium text-muted-foreground shadow-sm">
                  {group.date}
                </span>
              </div>

              {group.messages.map((msg, idx) => {
                const showAvatar =
                  !msg.isMe &&
                  (idx === group.messages.length - 1 ||
                    group.messages[idx + 1]?.isMe);

                return (
                  <div
                    key={msg.id}
                    className={`flex ${msg.isMe ? 'justify-end' : 'justify-start'} mb-1`}
                  >
                    <div className={`flex items-end gap-2 max-w-[80%] ${msg.isMe ? 'flex-row-reverse' : 'flex-row'}`}>
                      {/* Avatar placeholder for alignment */}
                      <div className="w-7 shrink-0">
                        {showAvatar && (
                          <Avatar className="h-7 w-7">
                            <AvatarFallback
                              className={`${getAvatarColor(conv.name)} text-[9px] font-semibold text-white`}
                            >
                              {getInitials(conv.name)}
                            </AvatarFallback>
                          </Avatar>
                        )}
                      </div>

                      {/* Message Bubble */}
                      <div
                        className={`rounded-2xl px-3.5 py-2 shadow-sm ${
                          msg.isMe
                            ? 'rounded-br-md bg-primary text-primary-foreground'
                            : 'rounded-bl-md bg-card text-card-foreground border border-border/50'
                        } ${
                          msg.type === 'image' || msg.type === 'video'
                            ? 'p-1.5'
                            : ''
                        }`}
                      >
                        {renderMessageContent(msg, conv)}
                        <div
                          className={`mt-1 flex items-center gap-1 ${
                            msg.isMe ? 'justify-end' : 'justify-start'
                          }`}
                        >
                          <span
                            className={`text-[10px] ${
                              msg.isMe ? 'text-primary-foreground/60' : 'text-muted-foreground'
                            }`}
                          >
                            {msg.time}
                          </span>
                          {msg.isMe && (
                            msg.isRead
                              ? <Eye className="h-3 w-3 text-primary-foreground/60" />
                              : <CheckCheck className="h-3 w-3 text-primary-foreground/60" />
                          )}
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          ))}
          <div ref={messagesEndRef} />
        </div>

        {/* Pending Image/Video Preview */}
        {pendingImage && (
          <div className="border-t bg-background px-4 py-2">
            <div className="flex items-center gap-3">
              <div className="relative">
                {pendingFile?.type === 'video' ? (
                  <div className="relative h-16 w-16 rounded-lg overflow-hidden border border-border bg-black/10">
                    <video
                      src={pendingImage.url}
                      className="h-full w-full object-cover"
                      muted
                    />
                    <div className="absolute inset-0 flex items-center justify-center">
                      <Play className="h-5 w-5 text-white drop-shadow-md" />
                    </div>
                  </div>
                ) : (
                  <img
                    src={pendingImage.url}
                    alt="Preview"
                    className="h-16 w-16 rounded-lg object-cover border border-border"
                  />
                )}
                <button
                  onClick={() => {
                    if (pendingImage?.url) URL.revokeObjectURL(pendingImage.url);
                    setPendingImage(null);
                    setPendingFile(null);
                  }}
                  className="absolute -top-2 -right-2 h-5 w-5 rounded-full bg-destructive text-destructive-foreground flex items-center justify-center shadow-sm hover:bg-destructive/90"
                >
                  <X className="h-3 w-3" />
                </button>
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-sm font-medium truncate">{pendingFile?.file.name}</p>
                <p className="text-xs text-muted-foreground">
                  {pendingFile?.file.size ? formatFileSize(pendingFile.file.size) : ''} • {pendingFile?.type === 'video' ? (language === 'bn' ? 'ভিডিও' : 'Video') : (language === 'bn' ? 'ছবি' : 'Image')}
                </p>
              </div>
              <Button
                size="sm"
                onClick={handleSendPendingFile}
                className="bg-primary text-primary-foreground hover:bg-primary/90 shrink-0"
              >
                <Send className="h-3.5 w-3.5 mr-1.5" />
                {language === 'bn' ? 'পাঠান' : 'Send'}
              </Button>
            </div>
          </div>
        )}

        {/* Pending File Preview (non-image) */}
        {pendingFile && !pendingImage && (
          <div className="border-t bg-background px-4 py-2">
            <div className="flex items-center gap-3">
              <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-orange-100 shrink-0">
                {pendingFile.type === 'video' ? (
                  <Film className="h-6 w-6 text-orange-600" />
                ) : pendingFile.type === 'voice' ? (
                  <Music className="h-6 w-6 text-orange-600" />
                ) : (
                  <FileText className="h-6 w-6 text-orange-600" />
                )}
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-sm font-medium truncate">{pendingFile.file.name}</p>
                <p className="text-xs text-muted-foreground">
                  {formatFileSize(pendingFile.file.size)} •{' '}
                  {pendingFile.type === 'video'
                    ? (language === 'bn' ? 'ভিডিও' : 'Video')
                    : pendingFile.type === 'voice'
                    ? (language === 'bn' ? 'ভয়েস' : 'Voice')
                    : (language === 'bn' ? 'ডকুমেন্ট' : 'Document')}
                </p>
              </div>
              <button
                onClick={() => setPendingFile(null)}
                className="h-8 w-8 rounded-full hover:bg-accent flex items-center justify-center shrink-0"
              >
                <X className="h-4 w-4 text-muted-foreground" />
              </button>
              <Button
                size="sm"
                onClick={handleSendPendingFile}
                disabled={sending}
                className="bg-primary text-primary-foreground hover:bg-primary/90 shrink-0"
              >
                {sending ? <span className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-primary-foreground border-t-transparent" /> : <Send className="h-3.5 w-3.5 mr-1.5" />}
                {language === 'bn' ? 'পাঠান' : 'Send'}
              </Button>
            </div>
          </div>
        )}

        {/* Recording UI */}
        {isRecording ? (
          <div className="border-t bg-background px-4 py-3">
            <div className="flex items-center gap-3">
              {/* Pulsing red dot */}
              <div className="relative flex items-center justify-center h-10 w-10 shrink-0">
                <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-red-400 opacity-40" />
                <span className="relative inline-flex h-4 w-4 rounded-full bg-red-500" />
              </div>

              {/* Timer */}
              <div className="flex-1">
                <p className="text-sm font-medium text-foreground">
                  {language === 'bn' ? 'রেকর্ড হচ্ছে...' : 'Recording...'}
                </p>
                <p className="text-lg font-mono font-bold text-red-500">
                  {formatRecordingTime(recordingTime)}
                </p>
              </div>

              {/* Cancel button */}
              <Button
                variant="ghost"
                size="icon"
                onClick={cancelRecording}
                className="h-10 w-10 shrink-0 text-muted-foreground hover:text-destructive"
              >
                <X className="h-5 w-5" />
              </Button>

              {/* Stop button */}
              <Button
                size="icon"
                onClick={stopRecording}
                className="h-10 w-10 shrink-0 rounded-full bg-red-500 text-white hover:bg-red-600 shadow-md"
              >
                <Square className="h-4 w-4" />
              </Button>
            </div>
          </div>
        ) : (
          /* Normal Input Area */
          <div className="border-t bg-background px-3 py-2.5">
            <div className="flex items-end gap-2">
              {/* Attach button with Popover */}
              <Popover open={attachPopoverOpen} onOpenChange={setAttachPopoverOpen}>
                <PopoverTrigger asChild>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-9 w-9 shrink-0 text-muted-foreground hover:text-primary"
                  >
                    <Paperclip className="h-5 w-5" />
                  </Button>
                </PopoverTrigger>
                <PopoverContent side="top" align="start" className="w-48 p-2" collisionPadding={8}>
                  <div className="space-y-1">
                    <button
                      onClick={() => {
                        setAttachPopoverOpen(false);
                        setTimeout(() => photoInputRef.current?.click(), 50);
                      }}
                      className="flex w-full items-center gap-3 rounded-md px-3 py-2.5 text-sm hover:bg-accent transition-colors"
                    >
                      <Camera className="h-4 w-4 text-orange-500" />
                      <span>{language === 'bn' ? 'ছবি/ভিডিও' : 'Photo/Video'}</span>
                    </button>
                    <button
                      onClick={() => {
                        setAttachPopoverOpen(false);
                        setTimeout(() => startRecording(), 50);
                      }}
                      className="flex w-full items-center gap-3 rounded-md px-3 py-2.5 text-sm hover:bg-accent transition-colors"
                    >
                      <Mic className="h-4 w-4 text-red-500" />
                      <span>{language === 'bn' ? 'ভয়েস মেসেজ' : 'Voice Message'}</span>
                    </button>
                    <button
                      onClick={() => {
                        setAttachPopoverOpen(false);
                        setTimeout(() => docInputRef.current?.click(), 50);
                      }}
                      className="flex w-full items-center gap-3 rounded-md px-3 py-2.5 text-sm hover:bg-accent transition-colors"
                    >
                      <FileText className="h-4 w-4 text-emerald-500" />
                      <span>{language === 'bn' ? 'ডকুমেন্ট' : 'Document'}</span>
                    </button>
                  </div>
                </PopoverContent>
              </Popover>

              {/* Hidden file inputs */}
              <input
                ref={photoInputRef}
                type="file"
                accept="image/*,video/*"
                className="hidden"
                onChange={handlePhotoSelect}
              />
              <input
                ref={docInputRef}
                type="file"
                className="hidden"
                onChange={handleDocSelect}
              />

              <div className="relative min-w-0 flex-1">
                <Input
                  ref={inputRef}
                  placeholder={t('msg.typeMessage', language)}
                  value={messageInput}
                  onChange={(e) => setMessageInput(e.target.value)}
                  onKeyDown={handleKeyDown}
                  className="h-10 rounded-full border-muted bg-muted/50 pr-10 text-sm focus-visible:ring-primary/50"
                />

                {/* Emoji Picker */}
                <Popover open={emojiPopoverOpen} onOpenChange={setEmojiPopoverOpen}>
                  <PopoverTrigger asChild>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="absolute right-1 top-1/2 z-10 h-7 w-7 -translate-y-1/2 text-muted-foreground hover:text-primary"
                    >
                      <Smile className="h-4 w-4" />
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent side="top" align="end" className="w-72 p-3" sideOffset={8} collisionPadding={8}>
                    <div className="space-y-3 max-h-[280px] overflow-y-auto" style={{ scrollbarWidth: 'thin' }}>
                      {emojiCategories.map((category) => (
                        <div key={category.name}>
                          <p className="text-xs font-semibold text-muted-foreground mb-1.5">{category.name}</p>
                          <div className="flex flex-wrap gap-0.5">
                            {category.emojis.map((emoji, i) => (
                              <button
                                key={`${category.name}-${i}`}
                                onClick={() => handleEmojiClick(emoji)}
                                className="h-8 w-8 flex items-center justify-center rounded-md text-lg hover:bg-accent transition-colors"
                              >
                                {emoji}
                              </button>
                            ))}
                          </div>
                        </div>
                      ))}
                    </div>
                  </PopoverContent>
                </Popover>
              </div>

              <Button
                size="icon"
                onClick={() => {
                  if (pendingImage || pendingFile) {
                    handleSendPendingFile();
                  } else {
                    handleSendMessage();
                  }
                }}
                disabled={(!messageInput.trim() && !pendingImage && !pendingFile) || sending}
                className="h-10 w-10 shrink-0 rounded-full bg-primary text-primary-foreground shadow-md hover:bg-primary/90 disabled:opacity-50"
              >
                <Send className="h-4 w-4" />
              </Button>
            </div>
          </div>
        )}

        {/* Confirmation Dialog */}
        <AlertDialog open={confirmDialog.open} onOpenChange={(open) => setConfirmDialog({ open, type: open ? confirmDialog.type : null })}>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>
                {confirmDialog.type === 'block'
                  ? (language === 'bn' ? 'ব্যবহারকারী ব্লক করবেন?' : 'Block User?')
                  : confirmDialog.type === 'report'
                  ? (language === 'bn' ? 'ব্যবহারকারী রিপোর্ট করবেন?' : 'Report User?')
                  : (language === 'bn' ? 'চ্যাট মুছে ফেলবেন?' : 'Clear Chat?')}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {confirmDialog.type === 'block'
                ? (language === 'bn'
                  ? `${conv.name}-কে ব্লক করলে তারা আপনাকে মেসেজ পাঠাতে পারবে না।`
                  : `Blocking ${conv.name} will prevent them from sending you messages.`)
                : confirmDialog.type === 'report'
                ? (language === 'bn'
                  ? `${conv.name}-কে রিপোর্ট করলে আমাদের টিম তদন্ত করবে। ভুল রিপোর্ট গুরুতর পরিণতি হতে পারে।`
                  : `Reporting ${conv.name} will trigger an investigation by our team. False reports may result in serious consequences.`)
                : (language === 'bn'
                  ? 'এই কথোপকথনের সমস্ত মেসেজ মুছে যাবে। এই কাজ পূর্বাবস্থায় ফেরানো যাবে না।'
                  : 'All messages in this conversation will be deleted. This action cannot be undone.')}
            </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel>{t('common.cancel', language)}</AlertDialogCancel>
              <AlertDialogAction onClick={handleConfirmAction} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
                {confirmDialog.type === 'block'
                  ? (language === 'bn' ? 'ব্লক করুন' : 'Block')
                  : confirmDialog.type === 'report'
                  ? (language === 'bn' ? 'রিপোর্ট করুন' : 'Report')
                  : (language === 'bn' ? 'মুছুন' : 'Clear')}
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      </div>
    );
  };

  return (
    <div className="flex h-[calc(100vh-8rem)] flex-col overflow-hidden">
      {selectedConversation ? renderChatView() : renderConversationList()}
    </div>
  );
}
