// lib/features/admin/tabs/messages/chat_conversation_panel.dart

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:file_picker/file_picker.dart';
import 'package:image_picker/image_picker.dart';

import '../../../../core/services/chat_media_service.dart';
import 'chat_message_bubble.dart';
import 'chat_models.dart';

const Color _rvGreen = Color.fromARGB(255, 2, 105, 48);
const Color _rvGold = Color.fromARGB(255, 204, 117, 4);
const Color _rvInk = Color(0xFF17231C);
const Color _rvMuted = Color(0xFF66756C);
const Color _rvBorder = Color(0xFFE0E8E3);
const Color _rvSurface = Color(0xFFF5F7F6);


class ChatConversationPanel extends StatefulWidget {
  final ChatContact chat;
  final bool isMobile;
  final VoidCallback? onBack;
  final String myEmail; 

  const ChatConversationPanel({
    super.key, 
    required this.chat, 
    required this.isMobile, 
    this.onBack,
    required this.myEmail,
  });

  @override
  State<ChatConversationPanel> createState() => _ChatConversationPanelState();
}

class _ChatConversationPanelState extends State<ChatConversationPanel> {
  final TextEditingController _msgController = TextEditingController();
  final ScrollController _scrollController = ScrollController();

  late Stream<QuerySnapshot> _messagesStream;

  bool _showInfoPanel = false;
  String _infoName = '';
  String _infoEmail = '';
  String? _infoPic;

  String? _replyingToText;
  String? _replyingToSender;
  String? _replyingToEmail;

  Timer? _typingTimer;
  bool _isTyping = false;
  bool _isUploading = false;

  @override
  void initState() {
    super.initState();
    _initStream();
    _markChatAsRead();
  }

  @override
  void didUpdateWidget(covariant ChatConversationPanel oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.chat.id != widget.chat.id) {
      _initStream();
      _markChatAsRead();
      setState(() {
        _showInfoPanel = false;
        _replyingToText = null; 
      });
    }
  }

  @override
  void dispose() {
    _typingTimer?.cancel();
    _scrollController.dispose();
    _msgController.dispose();
    super.dispose();
  }

  void _initStream() {
    _messagesStream = FirebaseFirestore.instance
        .collection('chats')
        .doc(widget.chat.id)
        .collection('messages')
        .orderBy('timestamp', descending: false)
        .snapshots();
  }

  Future<void> _markChatAsRead() async {
    FirebaseFirestore.instance.collection('chats').doc(widget.chat.id).update({
      FieldPath(['unreadCounts', widget.myEmail]): 0,
      'mentions': FieldValue.arrayRemove([widget.myEmail]),
    }).catchError((_) {}); 

    final messagesRef = FirebaseFirestore.instance.collection('chats').doc(widget.chat.id).collection('messages');
    final msgs = await messagesRef.orderBy('timestamp', descending: true).limit(30).get();
    
    final batch = FirebaseFirestore.instance.batch();
    bool hasUpdates = false;
    
    for (var doc in msgs.docs) {
      final data = doc.data();
      if (data['senderId'] == widget.myEmail) continue; 
      
      final readBy = List<String>.from(data['readBy'] ?? []);
      if (!readBy.contains(widget.myEmail)) {
        batch.update(doc.reference, {
          'readBy': FieldValue.arrayUnion([widget.myEmail])
        });
        hasUpdates = true;
      }
    }
    if (hasUpdates) await batch.commit();
  }

  void _handleTyping() {
    if (!_isTyping) {
      _isTyping = true;
      FirebaseFirestore.instance.collection('chats').doc(widget.chat.id).set({
        'typing': FieldValue.arrayUnion([widget.myEmail])
      }, SetOptions(merge: true));
    }
    
    _typingTimer?.cancel();
    _typingTimer = Timer(const Duration(seconds: 2), () {
      _isTyping = false;
      FirebaseFirestore.instance.collection('chats').doc(widget.chat.id).set({
        'typing': FieldValue.arrayRemove([widget.myEmail])
      }, SetOptions(merge: true));
    });
  }

  void _startReply(String text, String senderName, String senderEmail) {
    setState(() {
      _replyingToText = text;
      _replyingToSender = senderName;
      _replyingToEmail = senderEmail;
    });
  }

  void _forwardMessage(String text) {
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Forwarding feature ready.')));
  }

  // 🚀 RIGHT CLICK CONTEXT MENU FUNCTION
  void _showContextMenu(BuildContext context, Offset position) {
    showMenu(
      context: context,
      position: RelativeRect.fromLTRB(position.dx, position.dy, position.dx + 1, position.dy + 1),
      elevation: 8,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      items: [
        const PopupMenuItem(
          value: 'close',
          child: Row(
            children: [
              Icon(Icons.close_rounded, color: Colors.redAccent, size: 20),
              SizedBox(width: 12),
              Text('Close chat', style: TextStyle(color: Colors.redAccent, fontWeight: FontWeight.w600)),
            ],
          ),
        ),
      ],
    ).then((value) {
      if (value == 'close' && widget.onBack != null) {
        widget.onBack!(); // Closes the chat panel
      }
    });
  }

  // PHP/XAMPP stores the binary attachment. Firebase stores only the message
  // and the PHP media reference so conversations stay realtime.
  Future<void> _pickAndUploadFile(FileType type) async {
    try {
      final PlatformFile? result = await FilePicker.pickFile(type: type);
      if (result == null || result.path == null || result.path!.trim().isEmpty) {
        return;
      }
      await _uploadAttachment(
        File(result.path!),
        fileName: result.name,
      );
    } catch (e) {
      if (!mounted) return;
      setState(() => _isUploading = false);
      _showMediaError(e);
    }
  }

  Future<void> _pickCameraImage() async {
    try {
      // Desktop devices normally do not expose a camera through image_picker.
      // Fall back to choosing a photo so the attachment action remains useful.
      try {
        if (Platform.isWindows || Platform.isLinux || Platform.isMacOS) {
          await _pickAndUploadFile(FileType.image);
          return;
        }
      } catch (_) {}

      final XFile? image = await ImagePicker().pickImage(
        source: ImageSource.camera,
        imageQuality: 86,
      );
      if (image == null) return;
      await _uploadAttachment(
        File(image.path),
        fileName: image.name.isEmpty ? 'camera_photo.jpg' : image.name,
      );
    } catch (e) {
      if (!mounted) return;
      setState(() => _isUploading = false);
      _showMediaError(e);
    }
  }

  Future<void> _uploadAttachment(
    File file, {
    required String fileName,
  }) async {
    if (_isUploading) return;
    if (!mounted) return;
    setState(() => _isUploading = true);

    ChatMediaUpload? upload;
    try {
      upload = await ChatMediaService.uploadFile(
        chatId: widget.chat.id,
        file: file,
        fileName: fileName,
      );

      String messageText;
      if (upload.fileType == 'image') {
        messageText = '📷 Photo';
      } else if (upload.fileType == 'video') {
        messageText = '🎥 Video: ${upload.fileName}';
      } else if (upload.fileType == 'audio') {
        messageText = '🎵 Audio: ${upload.fileName}';
      } else {
        messageText = '📄 Document: ${upload.fileName}';
      }

      await _sendMessage(
        text: messageText,
        fileUrl: upload.fileUrl,
        fileName: upload.fileName,
        fileType: upload.fileType,
        mediaId: upload.id,
        mimeType: upload.mimeType,
        fileSizeBytes: upload.sizeBytes,
        downloadUrl: upload.downloadUrl,
      );
    } catch (_) {
      // If Firebase rejects the message after PHP has already stored the file,
      // remove the orphaned upload before surfacing the original error.
      if (upload != null && upload.token.isNotEmpty) {
        try {
          await ChatMediaService.deleteMedia(upload.token);
        } catch (_) {}
      }
      rethrow;
    } finally {
      if (mounted) setState(() => _isUploading = false);
    }
  }

  void _showMediaError(Object error) {
    var message = error.toString().trim();
    if (message.startsWith('Exception: ')) {
      message = message.substring('Exception: '.length);
    }
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message.isEmpty ? 'Unable to upload attachment.' : message),
        backgroundColor: Colors.red.shade700,
        behavior: SnackBarBehavior.floating,
      ),
    );
  }

  void _showAttachmentMenu(BuildContext context) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      builder: (sheetContext) {
        return SafeArea(
          top: false,
          child: Container(
            margin: const EdgeInsets.all(12),
            padding: const EdgeInsets.fromLTRB(16, 12, 16, 18),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(22),
              border: Border.all(color: _rvBorder),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(.08),
                  blurRadius: 28,
                  offset: const Offset(0, 10),
                ),
              ],
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Center(
                  child: Container(
                    width: 42,
                    height: 4,
                    decoration: BoxDecoration(
                      color: const Color(0xFFD6DEDA),
                      borderRadius: BorderRadius.circular(20),
                    ),
                  ),
                ),
                const SizedBox(height: 14),
                const Text(
                  'Add to conversation',
                  style: TextStyle(
                    color: _rvInk,
                    fontSize: 16,
                    fontWeight: FontWeight.w900,
                  ),
                ),
                const SizedBox(height: 4),
                const Text(
                  'Choose the type of attachment you want to share.',
                  style: TextStyle(color: _rvMuted, fontSize: 12),
                ),
                const SizedBox(height: 16),
                LayoutBuilder(
                  builder: (context, constraints) {
                    final itemWidth = constraints.maxWidth < 360
                        ? (constraints.maxWidth - 12) / 2
                        : (constraints.maxWidth - 24) / 3;
                    return Wrap(
                      spacing: 12,
                      runSpacing: 12,
                      children: [
                        _attachmentOption(
                          width: itemWidth,
                          icon: Icons.insert_drive_file_outlined,
                          color: _rvGreen,
                          title: 'Document',
                          onTap: () {
                            Navigator.pop(sheetContext);
                            _pickAndUploadFile(FileType.any);
                          },
                        ),
                        _attachmentOption(
                          width: itemWidth,
                          icon: Icons.photo_library_outlined,
                          color: _rvGold,
                          title: 'Gallery',
                          onTap: () {
                            Navigator.pop(sheetContext);
                            _pickAndUploadFile(FileType.image);
                          },
                        ),
                        _attachmentOption(
                          width: itemWidth,
                          icon: Icons.camera_alt_outlined,
                          color: const Color(0xFF8C5A9E),
                          title: 'Camera',
                          onTap: () {
                            Navigator.pop(sheetContext);
                            _pickCameraImage();
                          },
                        ),
                      ],
                    );
                  },
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _attachmentOption({
    required double width,
    required IconData icon,
    required Color color,
    required String title,
    required VoidCallback onTap,
  }) {
    return SizedBox(
      width: width,
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: onTap,
          borderRadius: BorderRadius.circular(16),
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 14),
            decoration: BoxDecoration(
              color: color.withOpacity(.07),
              borderRadius: BorderRadius.circular(16),
              border: Border.all(color: color.withOpacity(.14)),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  width: 42,
                  height: 42,
                  decoration: BoxDecoration(
                    color: color.withOpacity(.12),
                    borderRadius: BorderRadius.circular(13),
                  ),
                  child: Icon(icon, size: 22, color: color),
                ),
                const SizedBox(height: 9),
                Text(
                  title,
                  textAlign: TextAlign.center,
                  style: const TextStyle(
                    color: _rvInk,
                    fontSize: 12,
                    fontWeight: FontWeight.w800,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Future<void> _sendMessage({
    String? text,
    String? fileUrl,
    String? fileName,
    String? fileType,
    String? localPath,
    int? mediaId,
    String? mimeType,
    int? fileSizeBytes,
    String? downloadUrl,
  }) async {
    final msgText = text ?? _msgController.text.trim();
    if (msgText.isEmpty && fileUrl == null && localPath == null) return;

    if (text == null) _msgController.clear();
    final timestamp = FieldValue.serverTimestamp();

    _typingTimer?.cancel();
    _isTyping = false;

    final chatDoc = await FirebaseFirestore.instance.collection('chats').doc(widget.chat.id).get();
    final data = chatDoc.data();
    final myName = data?['participantNames']?[widget.myEmail] ?? 'Me';
    final myPic = data?['participantPics']?[widget.myEmail] ?? '';

    final batch = FirebaseFirestore.instance.batch();
    final messageRef = FirebaseFirestore.instance.collection('chats').doc(widget.chat.id).collection('messages').doc();
    
    batch.set(messageRef, {
      'text': msgText,
      'senderId': widget.myEmail,
      'senderName': myName,
      'senderPic': myPic,
      'timestamp': timestamp,
      'replyToText': _replyingToText,
      'replyToSender': _replyingToSender,
      'readBy': [widget.myEmail],
      if (fileUrl != null) 'fileUrl': fileUrl,
      if (fileName != null) 'fileName': fileName,
      if (fileType != null) 'fileType': fileType,
      if (localPath != null) 'localPath': localPath,
      if (mediaId != null) 'mediaId': mediaId,
      if (mimeType != null) 'mimeType': mimeType,
      if (fileSizeBytes != null) 'fileSizeBytes': fileSizeBytes,
      if (downloadUrl != null) 'downloadUrl': downloadUrl,
    });

    final chatRef = FirebaseFirestore.instance.collection('chats').doc(widget.chat.id);
    final formattedLastMessage = widget.chat.isGroup ? "$myName: $msgText" : msgText;

    Map<Object, dynamic> updates = {
      'lastMessage': formattedLastMessage,
      'lastMessageTime': timestamp,
      'typing': FieldValue.arrayRemove([widget.myEmail]),
    };

    if (data != null && data['participants'] != null) {
      for (String email in data['participants']) {
        if (email != widget.myEmail) {
          updates[FieldPath(['unreadCounts', email])] = FieldValue.increment(1);
        }
      }
    }

    if (_replyingToEmail != null && _replyingToEmail != widget.myEmail) {
      updates['mentions'] = FieldValue.arrayUnion([_replyingToEmail]);
    }

    batch.update(chatRef, updates);
    await batch.commit();

    if (!mounted) return;
    setState(() {
      _replyingToText = null;
      _replyingToSender = null;
      _replyingToEmail = null;
    });
    
    // Auto-scroll on send
    _scrollToBottom();
  }

  void _scrollToBottom() {
    if (_scrollController.hasClients) {
      _scrollController.animateTo(_scrollController.position.maxScrollExtent, duration: const Duration(milliseconds: 300), curve: Curves.easeOut);
    }
  }

  void _openContactInfo(String name, String email, String? pic) {
    final renderObject = context.findRenderObject();
    final panelWidth = renderObject is RenderBox
        ? renderObject.size.width
        : MediaQuery.of(context).size.width;

    if (widget.isMobile || panelWidth < 900) {
      showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        backgroundColor: Colors.transparent,
        builder: (ctx) {
          final height = MediaQuery.of(ctx).size.height;
          return SafeArea(
            top: false,
            child: Container(
              height: height * .78,
              margin: const EdgeInsets.fromLTRB(10, 24, 10, 10),
              clipBehavior: Clip.antiAlias,
              decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.vertical(top: Radius.circular(24), bottom: Radius.circular(18)),
              ),
              child: Column(
                children: [
                  const SizedBox(height: 10),
                  Container(
                    width: 42,
                    height: 4,
                    decoration: BoxDecoration(
                      color: const Color(0xFFD4DDD8),
                      borderRadius: BorderRadius.circular(20),
                    ),
                  ),
                  Expanded(child: _buildInfoPanelContent(name, email, pic)),
                ],
              ),
            ),
          );
        },
      );
    } else {
      setState(() {
        _infoName = name;
        _infoEmail = email;
        _infoPic = pic;
        _showInfoPanel = true;
      });
    }
  }

  String _formatTime(Timestamp? timestamp) {
    if (timestamp == null) return '...';
    final date = timestamp.toDate();
    return "${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}";
  }

  ImageProvider? _getAvatarProvider(String? imageString) {
    if (imageString == null || imageString.trim().isEmpty) return null;
    final value = imageString.trim();
    if (value.startsWith('http://') || value.startsWith('https://')) {
      return NetworkImage(value);
    }
    try {
      final clean = value.contains(',') ? value.split(',').last : value;
      return MemoryImage(base64Decode(clean.replaceAll(RegExp(r'\s+'), '')));
    } catch (_) {
      return null;
    }
  }

  Widget _buildTypingIndicator(List<String> othersTyping, Map<String, dynamic> names) {
    var text = 'Someone is typing...';
    if (othersTyping.length == 1) {
      text = "${names[othersTyping.first] ?? 'User'} is typing...";
    }

    return Align(
      alignment: Alignment.centerLeft,
      child: Container(
        margin: const EdgeInsets.fromLTRB(12, 4, 12, 8),
        padding: const EdgeInsets.symmetric(horizontal: 13, vertical: 9),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          border: Border.all(color: _rvBorder),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            const SizedBox(
              width: 13,
              height: 13,
              child: CircularProgressIndicator(strokeWidth: 2, color: _rvGreen),
            ),
            const SizedBox(width: 9),
            Flexible(
              child: Text(
                text,
                overflow: TextOverflow.ellipsis,
                style: const TextStyle(
                  fontSize: 11.5,
                  color: _rvMuted,
                  fontStyle: FontStyle.italic,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildRightInfoPanel() {
    return Container(
      decoration: const BoxDecoration(
        color: Colors.white,
        border: Border(left: BorderSide(color: _rvBorder)),
      ),
      child: Column(
        children: [
          Container(
            height: 66,
            padding: const EdgeInsets.symmetric(horizontal: 10),
            decoration: const BoxDecoration(
              color: Colors.white,
              border: Border(bottom: BorderSide(color: _rvBorder)),
            ),
            child: Row(
              children: [
                IconButton(
                  tooltip: 'Close contact info',
                  icon: const Icon(Icons.close_rounded, color: _rvMuted),
                  onPressed: () => setState(() => _showInfoPanel = false),
                ),
                const SizedBox(width: 6),
                const Expanded(
                  child: Text(
                    'Conversation details',
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      fontSize: 15,
                      fontWeight: FontWeight.w900,
                      color: _rvInk,
                    ),
                  ),
                ),
              ],
            ),
          ),
          Expanded(child: _buildInfoPanelContent(_infoName, _infoEmail, _infoPic)),
        ],
      ),
    );
  }

  Widget _buildInfoPanelContent(String name, String email, String? pic) {
    final avatar = _getAvatarProvider(pic);
    return ListView(
      physics: const BouncingScrollPhysics(),
      padding: const EdgeInsets.fromLTRB(18, 24, 18, 26),
      children: [
        Center(
          child: Container(
            padding: const EdgeInsets.all(4),
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(color: _rvGold, width: 2),
            ),
            child: CircleAvatar(
              radius: 58,
              backgroundColor: const Color(0xFFE7ECE9),
              backgroundImage: avatar,
              child: avatar == null
                  ? Icon(widget.chat.isGroup ? Icons.groups_rounded : Icons.person_rounded, size: 54, color: _rvGreen)
                  : null,
            ),
          ),
        ),
        const SizedBox(height: 18),
        Text(
          name,
          textAlign: TextAlign.center,
          maxLines: 2,
          overflow: TextOverflow.ellipsis,
          style: const TextStyle(
            fontSize: 20,
            color: _rvInk,
            fontWeight: FontWeight.w900,
          ),
        ),
        const SizedBox(height: 6),
        Text(
          email,
          textAlign: TextAlign.center,
          maxLines: 2,
          overflow: TextOverflow.ellipsis,
          style: const TextStyle(fontSize: 12.5, color: _rvMuted),
        ),
        const SizedBox(height: 24),
        Container(
          decoration: BoxDecoration(
            color: _rvSurface,
            borderRadius: BorderRadius.circular(16),
            border: Border.all(color: _rvBorder),
          ),
          child: Column(
            children: [
              _buildInfoTile(Icons.star_border_rounded, 'Starred messages'),
              const Divider(height: 1, color: _rvBorder),
              _buildInfoTile(Icons.notifications_none_rounded, 'Notification settings'),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildInfoTile(IconData icon, String title) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14),
      child: Row(
        children: [
          Icon(icon, color: _rvGreen, size: 21),
          const SizedBox(width: 12),
          Expanded(
            child: Text(
              title,
              style: const TextStyle(fontSize: 13, color: _rvInk, fontWeight: FontWeight.w700),
            ),
          ),
          const Icon(Icons.chevron_right_rounded, color: _rvMuted, size: 19),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final panelWidth = constraints.maxWidth;
        final compact = panelWidth < 560;
        final veryCompact = panelWidth < 390;
        final inlineInfo = _showInfoPanel && !widget.isMobile && panelWidth >= 900;
        final infoWidth = panelWidth >= 1180 ? 350.0 : 310.0;

        return GestureDetector(
          onSecondaryTapDown: (details) => _showContextMenu(context, details.globalPosition),
          child: Row(
            children: [
              Expanded(
                child: StreamBuilder<DocumentSnapshot>(
                  stream: FirebaseFirestore.instance
                      .collection('chats')
                      .doc(widget.chat.id)
                      .snapshots(),
                  builder: (context, chatSnapshot) {
                    final chatData = chatSnapshot.data?.data() as Map<String, dynamic>?;
                    final typingList = chatData?['typing'] as List<dynamic>? ?? [];
                    final participants = chatData?['participants'] as List<dynamic>? ?? [];
                    final namesMap = chatData?['participantNames'] as Map<String, dynamic>? ?? {};

                    final othersTyping = typingList
                        .where((e) => e != widget.myEmail)
                        .map((e) => e.toString())
                        .toList();
                    final totalParticipants = participants.length;
                    final avatar = _getAvatarProvider(widget.chat.profilePicture);

                    return Column(
                      children: [
                        Container(
                          height: 66,
                          padding: EdgeInsets.symmetric(horizontal: compact ? 8 : 12),
                          decoration: const BoxDecoration(
                            color: Colors.white,
                            border: Border(bottom: BorderSide(color: _rvBorder)),
                          ),
                          child: Row(
                            children: [
                              if (widget.isMobile)
                                IconButton(
                                  tooltip: 'Back to chats',
                                  icon: const Icon(Icons.arrow_back_rounded, color: _rvInk),
                                  onPressed: widget.onBack,
                                ),
                              Expanded(
                                child: InkWell(
                                  onTap: () => _openContactInfo(
                                    widget.chat.name,
                                    widget.chat.isGroup ? 'Group conversation' : widget.chat.otherUserEmail,
                                    widget.chat.profilePicture,
                                  ),
                                  borderRadius: BorderRadius.circular(12),
                                  child: Padding(
                                    padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 5),
                                    child: Row(
                                      children: [
                                        CircleAvatar(
                                          radius: compact ? 18 : 20,
                                          backgroundColor: const Color(0xFFE7ECE9),
                                          backgroundImage: avatar,
                                          child: avatar == null
                                              ? Icon(
                                                  widget.chat.isGroup ? Icons.groups_rounded : Icons.person_rounded,
                                                  color: _rvGreen,
                                                  size: compact ? 19 : 21,
                                                )
                                              : null,
                                        ),
                                        const SizedBox(width: 10),
                                        Expanded(
                                          child: Column(
                                            mainAxisAlignment: MainAxisAlignment.center,
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              Text(
                                                widget.chat.name,
                                                maxLines: 1,
                                                overflow: TextOverflow.ellipsis,
                                                style: TextStyle(
                                                  fontWeight: FontWeight.w900,
                                                  fontSize: compact ? 14 : 15.5,
                                                  color: _rvInk,
                                                ),
                                              ),
                                              const SizedBox(height: 2),
                                              Text(
                                                othersTyping.isNotEmpty
                                                    ? 'typing...'
                                                    : (widget.chat.isGroup
                                                        ? 'Open group information'
                                                        : widget.chat.otherUserEmail),
                                                maxLines: 1,
                                                overflow: TextOverflow.ellipsis,
                                                style: TextStyle(
                                                  fontSize: 11.5,
                                                  color: othersTyping.isNotEmpty ? _rvGreen : _rvMuted,
                                                  fontStyle: othersTyping.isNotEmpty
                                                      ? FontStyle.italic
                                                      : FontStyle.normal,
                                                  fontWeight: othersTyping.isNotEmpty
                                                      ? FontWeight.w700
                                                      : FontWeight.w500,
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                              if (!veryCompact)
                                IconButton(
                                  tooltip: 'Search conversation',
                                  icon: const Icon(Icons.search_rounded, color: _rvMuted, size: 21),
                                  onPressed: () {},
                                ),
                              PopupMenuButton<String>(
                                tooltip: 'Conversation options',
                                icon: const Icon(Icons.more_vert_rounded, color: _rvMuted, size: 21),
                                color: Colors.white,
                                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
                                onSelected: (val) {
                                  if (val == 'info') {
                                    _openContactInfo(
                                      widget.chat.name,
                                      widget.chat.isGroup ? 'Group conversation' : widget.chat.otherUserEmail,
                                      widget.chat.profilePicture,
                                    );
                                  }
                                  if (val == 'close' && widget.onBack != null) widget.onBack!();
                                },
                                itemBuilder: (context) => [
                                  const PopupMenuItem(
                                    value: 'info',
                                    child: Row(
                                      children: [
                                        Icon(Icons.info_outline_rounded, color: _rvGreen, size: 20),
                                        SizedBox(width: 11),
                                        Text('Conversation info'),
                                      ],
                                    ),
                                  ),
                                  if (widget.onBack != null)
                                    const PopupMenuItem(
                                      value: 'close',
                                      child: Row(
                                        children: [
                                          Icon(Icons.close_rounded, color: Colors.redAccent, size: 20),
                                          SizedBox(width: 11),
                                          Text('Close chat', style: TextStyle(color: Colors.redAccent)),
                                        ],
                                      ),
                                    ),
                                ],
                              ),
                            ],
                          ),
                        ),
                        Expanded(
                          child: Container(
                            color: const Color(0xFFF2F6F3),
                            child: Column(
                              children: [
                                Expanded(
                                  child: StreamBuilder<QuerySnapshot>(
                                    stream: _messagesStream,
                                    builder: (context, snapshot) {
                                      if (snapshot.connectionState == ConnectionState.waiting) {
                                        return const Center(
                                          child: CircularProgressIndicator(color: _rvGreen, strokeWidth: 2.4),
                                        );
                                      }

                                      if (snapshot.hasData && snapshot.data!.docs.isNotEmpty) {
                                        final lastDocData = snapshot.data!.docs.last.data()
                                            as Map<String, dynamic>;
                                        final readBy = List<String>.from(lastDocData['readBy'] ?? []);
                                        if (lastDocData['senderId'] != widget.myEmail &&
                                            !readBy.contains(widget.myEmail)) {
                                          WidgetsBinding.instance.addPostFrameCallback((_) {
                                            if (mounted) _markChatAsRead();
                                          });
                                        }
                                      }

                                      final messages = snapshot.data?.docs ?? [];
                                      return ListView.builder(
                                        controller: _scrollController,
                                        padding: EdgeInsets.fromLTRB(
                                          compact ? 8 : 16,
                                          18,
                                          compact ? 8 : 16,
                                          18,
                                        ),
                                        physics: const BouncingScrollPhysics(),
                                        itemCount: messages.length + 1,
                                        itemBuilder: (context, index) {
                                          if (index == 0) {
                                            return Center(
                                              child: Container(
                                                margin: const EdgeInsets.only(bottom: 18),
                                                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 7),
                                                decoration: BoxDecoration(
                                                  color: Colors.white.withOpacity(.94),
                                                  borderRadius: BorderRadius.circular(30),
                                                  border: Border.all(color: _rvBorder),
                                                ),
                                                child: const Row(
                                                  mainAxisSize: MainAxisSize.min,
                                                  children: [
                                                    Icon(Icons.cloud_done_outlined, color: _rvGreen, size: 15),
                                                    SizedBox(width: 6),
                                                    Flexible(
                                                      child: Text(
                                                        'Live conversation synchronized through Firebase',
                                                        textAlign: TextAlign.center,
                                                        style: TextStyle(
                                                          fontSize: 10.5,
                                                          color: _rvMuted,
                                                          fontWeight: FontWeight.w600,
                                                        ),
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                            );
                                          }

                                          final msgData = messages[index - 1].data()
                                              as Map<String, dynamic>;
                                          final isMe = msgData['senderId'] == widget.myEmail;
                                          final readByList = List<String>.from(msgData['readBy'] ?? []);
                                          final isReadByOthers = totalParticipants > 0
                                              ? readByList.length >= totalParticipants
                                              : readByList.length > 1;

                                          return ChatMessageBubble(
                                            text: msgData['text'] ?? '',
                                            time: _formatTime(msgData['timestamp'] as Timestamp?),
                                            isMe: isMe,
                                            isRead: isReadByOthers,
                                            isGroup: widget.chat.isGroup,
                                            senderName: msgData['senderName'],
                                            senderPic: msgData['senderPic'],
                                            replyToText: msgData['replyToText'],
                                            replyToSender: msgData['replyToSender'],
                                            fileUrl: msgData['fileUrl'],
                                            fileName: msgData['fileName'],
                                            fileType: msgData['fileType'],
                                            downloadUrl: msgData['downloadUrl'],
                                            fileSizeBytes: msgData['fileSizeBytes'] is int
                                                ? msgData['fileSizeBytes'] as int
                                                : int.tryParse(msgData['fileSizeBytes']?.toString() ?? ''),
                                            localPath: msgData['localPath'],
                                            onAvatarTap: () => _openContactInfo(
                                              msgData['senderName'] ?? 'Unknown',
                                              msgData['senderId'] ?? '',
                                              msgData['senderPic'],
                                            ),
                                            onReply: () => _startReply(
                                              msgData['text'] ?? '',
                                              msgData['senderName'] ?? 'User',
                                              msgData['senderId'] ?? '',
                                            ),
                                            onForward: () => _forwardMessage(msgData['text'] ?? ''),
                                          );
                                        },
                                      );
                                    },
                                  ),
                                ),
                                if (othersTyping.isNotEmpty)
                                  _buildTypingIndicator(othersTyping, namesMap),
                              ],
                            ),
                          ),
                        ),
                        if (_replyingToText != null)
                          Container(
                            color: Colors.white,
                            padding: const EdgeInsets.fromLTRB(12, 8, 12, 0),
                            child: Container(
                              padding: const EdgeInsets.fromLTRB(12, 9, 7, 9),
                              decoration: BoxDecoration(
                                color: _rvSurface,
                                borderRadius: BorderRadius.circular(12),
                                border: const Border(
                                  left: BorderSide(color: _rvGreen, width: 4),
                                ),
                              ),
                              child: Row(
                                children: [
                                  Expanded(
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          _replyingToSender ?? 'User',
                                          style: const TextStyle(
                                            fontWeight: FontWeight.w900,
                                            color: _rvGreen,
                                            fontSize: 12,
                                          ),
                                        ),
                                        const SizedBox(height: 2),
                                        Text(
                                          _replyingToText!,
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                          style: const TextStyle(color: _rvMuted, fontSize: 12),
                                        ),
                                      ],
                                    ),
                                  ),
                                  IconButton(
                                    tooltip: 'Cancel reply',
                                    icon: const Icon(Icons.close_rounded, size: 18, color: _rvMuted),
                                    onPressed: () => setState(() {
                                      _replyingToText = null;
                                      _replyingToSender = null;
                                      _replyingToEmail = null;
                                    }),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        SafeArea(
                          top: false,
                          child: Container(
                            padding: EdgeInsets.fromLTRB(
                              compact ? 7 : 12,
                              8,
                              compact ? 7 : 12,
                              8,
                            ),
                            decoration: const BoxDecoration(
                              color: Colors.white,
                              border: Border(top: BorderSide(color: _rvBorder)),
                            ),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.end,
                              children: [
                                IconButton(
                                  tooltip: 'Attach',
                                  icon: const Icon(Icons.add_circle_outline_rounded, color: _rvGreen, size: 25),
                                  onPressed: _isUploading ? null : () => _showAttachmentMenu(context),
                                ),
                                const SizedBox(width: 3),
                                Expanded(
                                  child: Container(
                                    constraints: const BoxConstraints(minHeight: 44, maxHeight: 120),
                                    decoration: BoxDecoration(
                                      color: _rvSurface,
                                      borderRadius: BorderRadius.circular(22),
                                      border: Border.all(color: _rvBorder),
                                    ),
                                    child: TextField(
                                      controller: _msgController,
                                      onChanged: (_) => _handleTyping(),
                                      onSubmitted: (_) => _sendMessage(),
                                      minLines: 1,
                                      maxLines: 4,
                                      textInputAction: TextInputAction.send,
                                      decoration: InputDecoration(
                                        hintText: _isUploading ? 'Uploading attachment...' : 'Type a message',
                                        hintStyle: const TextStyle(color: _rvMuted, fontSize: 13),
                                        contentPadding: const EdgeInsets.symmetric(horizontal: 15, vertical: 11),
                                        border: InputBorder.none,
                                      ),
                                    ),
                                  ),
                                ),
                                const SizedBox(width: 5),
                                if (_isUploading)
                                  const Padding(
                                    padding: EdgeInsets.all(11),
                                    child: SizedBox(
                                      width: 21,
                                      height: 21,
                                      child: CircularProgressIndicator(strokeWidth: 2.2, color: _rvGreen),
                                    ),
                                  )
                                else
                                  Material(
                                    color: _rvGreen,
                                    shape: const CircleBorder(),
                                    child: InkWell(
                                      customBorder: const CircleBorder(),
                                      onTap: () => _sendMessage(),
                                      child: const Padding(
                                        padding: EdgeInsets.all(11),
                                        child: Icon(Icons.send_rounded, color: Colors.white, size: 20),
                                      ),
                                    ),
                                  ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    );
                  },
                ),
              ),
              AnimatedContainer(
                duration: const Duration(milliseconds: 220),
                curve: Curves.easeOutCubic,
                width: inlineInfo ? infoWidth : 0,
                child: inlineInfo ? _buildRightInfoPanel() : const SizedBox.shrink(),
              ),
            ],
          ),
        );
      },
    );
  }

}