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

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../../../core/networks/api_client.dart';
import '../../../../core/services/connect_social_service.dart';
import 'chat_models.dart';
import 'settings_panel.dart';
import 'profile_panel.dart';

class ChatListPanel extends StatefulWidget {
  final Function(ChatContact) onChatSelected;
  final String? selectedChatId;
  final String myEmail;
  final String myName;
  final String? myPic;
  const ChatListPanel({
    super.key,
    required this.onChatSelected,
    this.selectedChatId,
    required this.myEmail,
    required this.myName,
    this.myPic,
  });

  @override
  State<ChatListPanel> createState() => _ChatListPanelState();
}
class _ChatListPanelState extends State<ChatListPanel> with SingleTickerProviderStateMixin {
  final PageController _pageController = PageController();
  final TextEditingController _searchController = TextEditingController();
  final TextEditingController _contactsSearchController = TextEditingController();

  String _searchQuery = '';

  String _contactsSearchQuery = '';

  String _activeFilter = 'All';
  bool _isViewingArchive = false;
  int _activeNavIndex = 0;
  bool _isSyncingUsers = false;
  int _postsUnread = 0;
  Timer? _postsUnreadTimer;
  late Stream<QuerySnapshot> _chatsStream;
  late Stream<QuerySnapshot> _firebaseContactsStream;
  late AnimationController _metaAnimController;
  final ChatContact _rockAiContact = ChatContact(id: 'rock_ai_assistant', name: 'Rock AI', lastMessage: '', time: DateTime.now(), otherUserEmail: 'system', isGroup: false, unreadCount: 0);
  final ChatContact _systemTicketsContact = ChatContact(id: 'system_tickets', name: 'Tickets', lastMessage: '', time: DateTime.now(), otherUserEmail: 'system', isGroup: false, unreadCount: 0);
  final ChatContact _systemPostsContact = ChatContact(id: 'system_posts', name: 'Posts', lastMessage: '', time: DateTime.now(), otherUserEmail: 'system', isGroup: false, unreadCount: 0);
  final ChatContact _systemGroupsContact = ChatContact(id: 'system_groups', name: 'Groups', lastMessage: '', time: DateTime.now(), otherUserEmail: 'system', isGroup: false, unreadCount: 0);

  @override
  void initState() {
    super.initState();
    _metaAnimController = AnimationController(vsync: this, duration: const Duration(seconds: 4))..repeat();
    _chatsStream = FirebaseFirestore.instance.collection('chats').where('participants', arrayContains: widget.myEmail).orderBy('lastMessageTime', descending: true).snapshots(includeMetadataChanges: true);
    _firebaseContactsStream = FirebaseFirestore.instance.collection('users').orderBy('name').snapshots(includeMetadataChanges: true);
    _syncPostgresToFirebaseInBackground();
    _refreshPostsUnread();
    _postsUnreadTimer = Timer.periodic(const Duration(seconds: 15), (_) => _refreshPostsUnread());
  }
  @override
  void dispose() {
    _postsUnreadTimer?.cancel();
    _pageController.dispose();
    _metaAnimController.dispose();
    _searchController.dispose();
    _contactsSearchController.dispose();
    super.dispose();
  }
  Future<void> _refreshPostsUnread() async {
    try {
      final count = await ConnectSocialService.getUnreadNotificationCount();
      if (mounted) setState(() => _postsUnread = count);
    } catch (_) {
      // Keep the previous count if the PHP social backend is temporarily unavailable.

    }
  }
  Future<void> _syncPostgresToFirebaseInBackground({bool forceSync = false}) async {
    if (!mounted || _isSyncingUsers) return;
    _isSyncingUsers = true;

    try {
      final prefs = await SharedPreferences.getInstance();
      final lastSyncValue = prefs.getString('last_contact_sync_${widget.myEmail}');
      final lastSync = lastSyncValue == null ? null : DateTime.tryParse(lastSyncValue);
      final syncIsDue = lastSync == null ||
          DateTime.now().difference(lastSync).inHours >= 24;

      if (!forceSync && !syncIsDue) return;

      final admins = await ApiClient.getAdmins();
      final staff = await ApiClient.getStaff();
      final allUsers = <Map<String, dynamic>>[...admins, ...staff];
      final usersByEmail = <String, Map<String, dynamic>>{};

      // Merge duplicate admin/staff records by email before writing contacts.
      for (final user in allUsers) {
        final email = (user['email'] ?? '').toString().trim().toLowerCase();
        if (email.isNotEmpty) usersByEmail[email] = user;
      }

      final firestore = FirebaseFirestore.instance;
      var batch = firestore.batch();
      var pendingWrites = 0;

      Future<void> commitBatch() async {
        if (pendingWrites == 0) return;
        await batch.commit();
        batch = firestore.batch();
        pendingWrites = 0;
      }

      for (final entry in usersByEmail.entries) {
        final email = entry.key;
        final user = entry.value;
        final name = (user['full_name'] ?? user['name'] ?? email).toString().trim();
        final role = (user['role'] ?? 'User').toString().trim();
        final contactData = <String, dynamic>{
          'email': email,
          'name': name.isEmpty ? email : name,
          'role': role.isEmpty ? 'User' : role,
          'last_synced': FieldValue.serverTimestamp(),
        };

        // Firestore should store a small image URL, never a Base64 image payload.
        final pictureUrl = _firestoreImageUrl(user['profile_picture']);
        if (pictureUrl != null) contactData['profile_picture'] = pictureUrl;

        final userRef = firestore.collection('users').doc(email);
        batch.set(userRef, contactData, SetOptions(merge: true));
        pendingWrites++;

        // Keep each batch below Firestore's 500-write limit.
        if (pendingWrites >= 400) await commitBatch();
      }

      await commitBatch();
      await prefs.setString(
        'last_contact_sync_${widget.myEmail}',
        DateTime.now().toIso8601String(),
      );
    } catch (error) {
      // Keep the panel running if the API or Firebase is temporarily unavailable.
      debugPrint('Contact sync failed: $error');
    } finally {
      _isSyncingUsers = false;
    }
  }

  String? _firestoreImageUrl(Object? value) {
    final image = value?.toString().trim() ?? '';
    if (image.isEmpty || image.length > 4096) return null;
    final uri = Uri.tryParse(image);
    if (uri == null || !uri.hasAuthority) return null;
    if (uri.scheme != 'http' && uri.scheme != 'https') return null;
    return image;
  }

  void _openContactsPanel() => _pageController.jumpToPage(1);

  void _closeContactsPanel() => _pageController.jumpToPage(0);

  Future<void> _toggleArchive(String chatId, bool isArchiving) async {
    await FirebaseFirestore.instance.collection('chats').doc(chatId).update({'archivedBy': isArchiving ? FieldValue.arrayUnion([widget.myEmail]) : FieldValue.arrayRemove([widget.myEmail])});
  }
  Future<void> _startChatWithUser(String targetEmail, String name, String? profilePic) async {
    if (targetEmail.isEmpty || targetEmail == widget.myEmail) return;
    _closeContactsPanel();
    final query = await FirebaseFirestore.instance.collection('chats').where('participants', arrayContains: widget.myEmail).get(const GetOptions(source: Source.cache));
    String? existingChatId;
    for (var doc in query.docs) {
      if (List<String>.from(doc['participants']).contains(targetEmail) && doc['isGroup'] != true) {
        existingChatId = doc.id;
        break;
      }
    }
    if (existingChatId != null) {
      widget.onChatSelected(ChatContact(id: existingChatId, name: name, lastMessage: '', time: DateTime.now(), otherUserEmail: targetEmail, profilePicture: profilePic));
    } else {
      final chatRef = FirebaseFirestore.instance.collection('chats').doc();
      await chatRef.set({
        'participants': [widget.myEmail, targetEmail],
        'participantNames': { widget.myEmail: widget.myName, targetEmail: name },
        'participantPics': {
          widget.myEmail: _firestoreImageUrl(widget.myPic) ?? '',
          targetEmail: _firestoreImageUrl(profilePic) ?? '',
        },
        'lastMessage': 'Chat created',
        'lastMessageTime': Timestamp.now(),
        'unreadCounts': { widget.myEmail: 0, targetEmail: 0 },
        'isGroup': false,
        'archivedBy': [],
        'mentions': []
      }, SetOptions(merge: true));
      widget.onChatSelected(ChatContact(id: chatRef.id, name: name, lastMessage: 'Chat created', time: DateTime.now(), otherUserEmail: targetEmail, profilePicture: profilePic));
    }
  }
  String _formatTime(DateTime? date) {
    if (date == null) return '';
    final now = DateTime.now();
    final diff = now.difference(date);
    if (diff.inDays == 0 && now.day == date.day) {
      return "${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}";
    } else if (diff.inDays == 1) return "Yesterday";
    else if (diff.inDays < 7) return ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'][date.weekday - 1];
    return "${date.day}/${date.month}/${date.year}";
  }
  ImageProvider? _getAvatarProvider(String? imageString) {
    final image = imageString?.trim() ?? '';
    if (image.isEmpty) return null;

    final uri = Uri.tryParse(image);
    if (uri != null && uri.hasAuthority &&
        (uri.scheme == 'http' || uri.scheme == 'https')) {
      return NetworkImage(image);
    }

    final payload = image.startsWith('data:image/') && image.contains(',')
        ? image.substring(image.indexOf(',') + 1)
        : image;
    if (payload.length > 1400000 ||
        !RegExp(r'^[A-Za-z0-9+/=\s]+$').hasMatch(payload)) {
      return null; // Relative file paths and malformed image data are not Base64.
    }

    try {
      return MemoryImage(base64Decode(payload.replaceAll(RegExp(r'\s+'), '')));
    } on FormatException {
      return null;
    }
  }

  Widget _buildAvatar(
    String? imageString, {
    double radius = 24,
    double iconSize = 24,
    required Color backgroundColor,
    required Color fallbackColor,
  }) {
    final imageProvider = _getAvatarProvider(imageString);
    return CircleAvatar(
      radius: radius,
      backgroundColor: backgroundColor,
      backgroundImage: imageProvider,
      child: imageProvider == null
          ? Icon(Icons.person, size: iconSize, color: fallbackColor)
          : null,
    );
  }
  Widget _navIcon(IconData icon, String tooltip, {bool isActive = false, int count = 0, bool badgeDot = false, Color? color, VoidCallback? onTap}) {
    return Tooltip(
      message: tooltip, preferBelow: false, waitDuration: const Duration(milliseconds: 400),
      child: InkWell(
        onTap: onTap ?? () {},
        borderRadius: BorderRadius.circular(12),
        child: Stack(
          clipBehavior: Clip.none,
          children: [
            Container(padding: const EdgeInsets.all(10), decoration: BoxDecoration(color: isActive ? const Color(0xFFF0F2F5) : Colors.transparent, shape: BoxShape.circle), child: Icon(icon, color: color ?? const Color(0xFF54656F), size: 24)),
            if (count > 0) Positioned(right: -2, top: -2, child: Container(padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2), decoration: const ShapeDecoration(color: Color(0xFFCC7504), shape: StadiumBorder()), child: Text(count > 99 ? '99+' : count.toString(), style: const TextStyle(color: Colors.white, fontSize: 10, fontWeight: FontWeight.bold)))),
            if (badgeDot && count == 0) Positioned(right: 2, top: 2, child: Container(width: 8, height: 8, decoration: const BoxDecoration(color: Color(0xFFCC7504), shape: BoxShape.circle))),
          ],
        ),
      ),
    );
  }
  Widget _buildMetaAIIcon({bool isActive = false, bool isMobile = false}) {
    final animatedIcon = RotationTransition(
      turns: _metaAnimController,
      child: ShaderMask(
        shaderCallback: (bounds) => const SweepGradient(colors: [Color.fromARGB(255, 214, 160, 11), Color.fromARGB(255, 9, 131, 74), Color.fromARGB(255, 129, 87, 7), Color.fromARGB(255, 3, 112, 70)], stops: [0.0, 0.33, 0.66, 1.0]).createShader(bounds),
        child: Icon(Icons.blur_on, color: Colors.white, size: isMobile ? 26 : 30),
      ),
    );
    if (isMobile) return animatedIcon;
    return Tooltip(
      message: 'Rock AI', preferBelow: false,
      child: InkWell(
        onTap: () {
          setState(() => _activeNavIndex = 4);
          _pageController.jumpToPage(0);
          widget.onChatSelected(_rockAiContact);
        },
        borderRadius: BorderRadius.circular(20),
        child: Container(
          padding: const EdgeInsets.all(6),
          decoration: BoxDecoration(color: isActive ? const Color(0xFFF0F2F5) : Colors.transparent, shape: BoxShape.circle),
          child: animatedIcon,
        ),
      ),
    );
  }
  Widget _buildFilterChip(String label, {int? count}) {
    final isSelected = _activeFilter == label;
    final displayLabel = count != null && count > 0 ? '$label $count' : label;
    return GestureDetector(
      onTap: () => setState(() => _activeFilter = label),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        decoration: BoxDecoration(color: isSelected ? const Color(0xFFD8FDD2) : const Color(0xFFF0F2F5), borderRadius: BorderRadius.circular(24)),
        child: Text(displayLabel, style: TextStyle(color: isSelected ? const Color(0xFF026930) : const Color(0xFF54656F), fontWeight: isSelected ? FontWeight.w600 : FontWeight.w500, fontSize: 13)),
      ),
    );
  }
  PopupMenuItem<String> _buildMenuItem(String title, IconData icon) {
    return PopupMenuItem(
      value: title,
      child: Row(children: [Icon(icon, color: const Color(0xFF111B21), size: 20), const SizedBox(width: 12), Text(title, style: const TextStyle(fontSize: 15, color: Color(0xFF111B21)))]),
    );
  }
  Widget _buildActiveChatsView(List<DocumentSnapshot> mainChats, List<DocumentSnapshot> archivedChats, int totalGroups, int totalMainUnread, int totalArchiveUnread, bool isMobile) {
    return Container(
      color: Colors.white,
      child: Column(
        children: [
          Container(
            height: 60, padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                if (_isViewingArchive) Row(children: [ Tooltip(message: 'Back', child: IconButton(icon: const Icon(Icons.arrow_back_rounded, color: Color(0xFF026930)), onPressed: () => setState(() => _isViewingArchive = false))), const SizedBox(width: 8), const Text('Archived', style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: Color(0xFF111B21))) ])
                else const Text('Chats', style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: Color(0xFF111B21))),
                if (!_isViewingArchive)
                  Row(
                    children: [
                      Tooltip(message: 'New chat', child: IconButton(icon: const Icon(Icons.add_box_outlined, color: Color(0xFF54656F)), onPressed: _openContactsPanel)),
                      Tooltip(
                        message: 'Menu',
                        child: PopupMenuButton<String>(
                          icon: const Icon(Icons.more_vert_rounded, color: Color(0xFF54656F)), color: Colors.white, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), elevation: 4, offset: const Offset(0, 40),
                          onSelected: (val) {
                            if (val == 'New group') _openContactsPanel();
                            if (val == 'Settings') { setState(() => _activeNavIndex = 5); _pageController.jumpToPage(2); }
                          },
                          itemBuilder: (context) => [ _buildMenuItem('New group', Icons.group_add_outlined), _buildMenuItem('Starred messages', Icons.star_border_rounded), _buildMenuItem('Select chats', Icons.check_box_outlined), _buildMenuItem('Mark all as read', Icons.mark_chat_read), const PopupMenuDivider(), if (isMobile) _buildMenuItem('Settings', Icons.settings_outlined), _buildMenuItem('App lock', Icons.lock_outline_rounded), _buildMenuItem('Log out', Icons.logout_rounded) ],
                        ),
                      ),
                    ],
                  )
              ],
            ),
          ),
          if (!_isViewingArchive)
            Column(
              children: [
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                  child: Container(
                    height: 38, decoration: BoxDecoration(color: const Color(0xFFF0F2F5), borderRadius: BorderRadius.circular(24)),
                    child: TextField(
                      controller: _searchController, onChanged: (val) => setState(() => _searchQuery = val),
                      decoration: InputDecoration(prefixIcon: const Icon(Icons.search_rounded, color: Color(0xFF54656F), size: 20), hintText: 'Search or start a new chat', hintStyle: const TextStyle(fontSize: 14, color: Color(0xFF54656F)), border: InputBorder.none, contentPadding: const EdgeInsets.symmetric(vertical: 10), suffixIcon: _searchQuery.isNotEmpty ? IconButton(icon: const Icon(Icons.close, size: 16, color: Color(0xFF54656F)), onPressed: () { _searchController.clear(); setState(() => _searchQuery = ''); }) : null),
                    ),
                  ),
                ),
                SingleChildScrollView(scrollDirection: Axis.horizontal, padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), child: Row(children: [ _buildFilterChip('All'), const SizedBox(width: 8), _buildFilterChip('Unread', count: totalMainUnread), const SizedBox(width: 8), _buildFilterChip('Favorites'), const SizedBox(width: 8), _buildFilterChip('Groups'), const SizedBox(width: 8), _buildFilterChip('Students')])),
                const SizedBox(height: 8),
              ],
            ),
          Expanded(
            child: Builder(
              builder: (context) {
                final targetList = _isViewingArchive ? archivedChats : mainChats.where((doc) {
                  final data = doc.data() as Map<String, dynamic>;
                  if (_searchQuery.isNotEmpty) {
                    final name = (data['isGroup'] == true ? data['groupName'] : data['participantNames']?[widget.myEmail])?.toString().toLowerCase() ?? '';
                    if (!name.contains(_searchQuery.toLowerCase())) return false;
                  }
                  if (_activeFilter == 'Unread') return (data['unreadCounts']?[widget.myEmail] ?? 0) > 0;
                  if (_activeFilter == 'Groups') return data['isGroup'] == true;
                  return true;
                }).toList();
                final showArchiveButton = !_isViewingArchive && archivedChats.isNotEmpty && _activeFilter == 'All' && _searchQuery.isEmpty;
                final bool showAiContact = !_isViewingArchive && _activeFilter == 'All' && (_searchQuery.isEmpty || 'rock ai'.contains(_searchQuery.toLowerCase()));
                final itemCount = targetList.length + (showArchiveButton ? 1 : 0) + (showAiContact ? 1 : 0);
                if (itemCount == 0) return Center(child: Text(_isViewingArchive ? 'No archived chats.' : 'No active chats.', style: const TextStyle(color: Color(0xFF54656F))));
                return ListView.builder(
                  physics: const BouncingScrollPhysics(), itemCount: itemCount,
                  itemBuilder: (context, index) {
                    int currentIdx = index;
                    if (showArchiveButton) {
                      if (currentIdx == 0) {
                        return Tooltip(
                          message: 'Archived chats',
                          child: InkWell(
                            onTap: () => setState(() => _isViewingArchive = true),
                            child: Container(padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16), decoration: BoxDecoration(border: Border(bottom: BorderSide(color: Colors.grey.shade200))), child: Row(children: [ const Icon(Icons.archive_outlined, color: Color(0xFF54656F), size: 24), const SizedBox(width: 24), const Expanded(child: Text('Archived', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Color(0xFF111B21)))), if (totalArchiveUnread > 0) Container(padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), decoration: BoxDecoration(color: const Color(0xFFCC7504), borderRadius: BorderRadius.circular(12)), child: Text(totalArchiveUnread.toString(), style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 12)))])),
                          ),
                        );
                      }
                      currentIdx--;
                    }
                    if (showAiContact) {
                      if (currentIdx == 0) {
                        return _HoverableChatListItem(
                          chat: _rockAiContact,
                          isSelected: widget.selectedChatId == _rockAiContact.id,
                          isViewingArchive: false,
                          isMobile: isMobile,
                          isAiContact: true,
                          onTap: () {
                            setState(() => _activeNavIndex = 4);
                            _pageController.jumpToPage(0);
                            widget.onChatSelected(_rockAiContact);
                          },
                          onArchive: () {},
                          avatarProvider: null,
                          formattedTime: '',
                        );
                      }
                      currentIdx--;
                    }
                    final doc = targetList[currentIdx];
                    final data = doc.data() as Map<String, dynamic>;
                    final isGroup = data['isGroup'] == true;

                    String chatName = isGroup ? (data['groupName'] ?? 'Group Chat') : '';
                    String? chatPic;

                    String otherUserEmail = "group";
                    if (!isGroup) {
                      final participants = data['participants'] as List<dynamic>? ?? [];
                      otherUserEmail = participants.firstWhere((p) => p != widget.myEmail, orElse: () => 'Unknown');
                      chatName = data['participantNames']?[otherUserEmail] ?? otherUserEmail;
                      chatPic = data['participantPics']?[otherUserEmail];
                    }
                    final mentionsList = data['mentions'] as List<dynamic>? ?? [];
                    final amIMentioned = mentionsList.contains(widget.myEmail);
                    final chat = ChatContact(id: doc.id, name: chatName, lastMessage: data['lastMessage'] ?? '', time: (data['lastMessageTime'] as Timestamp?)?.toDate(), unreadCount: data['unreadCounts']?[widget.myEmail] ?? 0, otherUserEmail: otherUserEmail, profilePicture: chatPic, isGroup: isGroup, isArchived: _isViewingArchive, hasMention: amIMentioned);
                    return _HoverableChatListItem(chat: chat, isSelected: chat.id == widget.selectedChatId, isViewingArchive: _isViewingArchive, isMobile: isMobile, isAiContact: false, onTap: () => widget.onChatSelected(chat), onArchive: () => _toggleArchive(chat.id, !_isViewingArchive), avatarProvider: _getAvatarProvider(chat.profilePicture), formattedTime: _formatTime(chat.time));
                  },
                );
              }
            ),
          )
        ],
      ),
    );
  }
  Widget _buildNewChatActionRow(IconData icon, String title) {
    return Tooltip(
      message: title,
      child: InkWell(
        onTap: () {},
        child: Padding(padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), child: Row(children: [ Container(width: 48, height: 48, decoration: const BoxDecoration(color: Color(0xFFCC7504), shape: BoxShape.circle), child: Icon(icon, color: Colors.white, size: 24)), const SizedBox(width: 16), Text(title, style: const TextStyle(fontSize: 16, color: Color(0xFF111B21), fontWeight: FontWeight.w500)) ])),
      ),
    );
  }
  Widget _buildContactsView() {
    return Container(
      color: Colors.white,
      child: Column(
        children: [
          Container(height: 60, padding: const EdgeInsets.symmetric(horizontal: 16), child: Row(children: [ Tooltip(message: 'Back', child: IconButton(icon: const Icon(Icons.arrow_back, color: Color(0xFF111B21)), onPressed: _closeContactsPanel)), const SizedBox(width: 16), const Text('New chat', style: TextStyle(color: Color(0xFF111B21), fontSize: 20, fontWeight: FontWeight.bold)) ])),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            child: Container(
              height: 42, decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(24), border: Border.all(color: const Color(0xFFCC7504), width: 1.5)),
              child: TextField(
                controller: _contactsSearchController, onChanged: (val) => setState(() => _contactsSearchQuery = val),
                decoration: const InputDecoration(prefixIcon: Icon(Icons.search_rounded, color: Colors.grey, size: 20), hintText: 'Search name, number or @username', hintStyle: TextStyle(fontSize: 14, color: Colors.grey), border: InputBorder.none, contentPadding: EdgeInsets.symmetric(vertical: 12)),
              ),
            ),
          ),
          Expanded(
            child: StreamBuilder<QuerySnapshot>(
              stream: _firebaseContactsStream,
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting && !snapshot.hasData) return const Center(child: CircularProgressIndicator(color: Color(0xFF026930)));
                final docs = snapshot.data?.docs ?? [];
                final users = docs.where((d) {
                  final data = d.data() as Map<String, dynamic>;
                  if (data['email'] == widget.myEmail) return false;
                  if (_contactsSearchQuery.isNotEmpty) return (data['name'] ?? '').toString().toLowerCase().contains(_contactsSearchQuery.toLowerCase());
                  return true;
                }).toList();
                final int staticItemsCount = _contactsSearchQuery.isEmpty ? 5 : 0;
                final int totalItems = staticItemsCount + users.length;
                return ListView.builder(
                  physics: const BouncingScrollPhysics(), itemCount: totalItems,
                  itemBuilder: (context, index) {
                    if (_contactsSearchQuery.isEmpty) {
                      if (index == 0) return _buildNewChatActionRow(Icons.group_add_rounded, 'New chat group');
                      if (index == 1) return _buildNewChatActionRow(Icons.person_add_alt_1_rounded, 'New contact');
                      if (index == 2) return _buildNewChatActionRow(Icons.groups_rounded, 'New group');
                      if (index == 3) {
                        return Tooltip(
                          message: 'Message yourself',
                          child: InkWell(
                            onTap: () {},
                            child: Padding(padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), child: Row(children: [ _buildAvatar(widget.myPic, backgroundColor: Colors.grey.shade300, fallbackColor: Colors.white), const SizedBox(width: 16), Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('${widget.myName} (You)', style: const TextStyle(fontWeight: FontWeight.w600, fontSize: 16, color: Color(0xFF111B21))), const SizedBox(height: 2), const Text('Message yourself', style: TextStyle(fontSize: 13, color: Color(0xFF54656F))) ])) ])),
                          ),
                        );
                      }
                      if (index == 4) return const Padding(padding: EdgeInsets.fromLTRB(24, 16, 16, 8), child: Text('#', style: TextStyle(color: Color(0xFF54656F), fontWeight: FontWeight.bold, fontSize: 16)));
                    }
                    final userIndex = index - staticItemsCount;
                    final data = users[userIndex].data() as Map<String, dynamic>;
                    return Tooltip(
                      message: 'Chat with ${data['name']}',
                      child: InkWell(
                        onTap: () => _startChatWithUser(data['email'] ?? '', data['name'] ?? 'User', data['profile_picture']),
                        child: Padding(padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), child: Row(children: [ _buildAvatar(data['profile_picture']?.toString(), backgroundColor: Colors.grey.shade200, fallbackColor: Colors.grey), const SizedBox(width: 16), Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(data['name'] ?? 'User', style: const TextStyle(fontWeight: FontWeight.w600, fontSize: 16, color: Color(0xFF111B21))), const SizedBox(height: 2), Text((data['role'] ?? 'User').toString().toUpperCase(), style: const TextStyle(fontSize: 12, color: Color(0xFF54656F), fontWeight: FontWeight.bold))])) ])),
                      ),
                    );
                  },
                );
              }
            ),
          )
        ],
      ),
    );
  }
  @override
  Widget build(BuildContext context) {
    // The parent messaging shell uses a single-pane experience below 1100px.

    // Match that breakpoint so phones/tablets get the compact bottom navigation,

    // while the desktop master pane keeps its slim navigation rail.

    final isMobile = MediaQuery.of(context).size.width < 1100;
    return StreamBuilder<QuerySnapshot>(
      stream: _chatsStream,
      builder: (context, snapshot) {
        int totalMainUnread = 0;
        int totalArchiveUnread = 0;
        int totalGroups = 0;
        List<DocumentSnapshot> mainChats = [];
        List<DocumentSnapshot> archivedChats = [];
        if (snapshot.hasData) {
          for (var doc in snapshot.data!.docs) {
            final data = doc.data() as Map<String, dynamic>;
            final isArchived = (data['archivedBy'] as List<dynamic>? ?? []).contains(widget.myEmail);
            final unreads = (data['unreadCounts']?[widget.myEmail] ?? 0) as int;
            if (isArchived) { archivedChats.add(doc); totalArchiveUnread += unreads; }
            else { mainChats.add(doc); totalMainUnread += unreads; if (data['isGroup'] == true) totalGroups++; }
          }
        }
        return Scaffold(
          backgroundColor: Colors.white,
          bottomNavigationBar: isMobile && _activeNavIndex <= 4
            ? BottomNavigationBar(
                type: BottomNavigationBarType.fixed, selectedItemColor: const Color(0xFF026930), unselectedItemColor: const Color(0xFF54656F), backgroundColor: Colors.white, selectedFontSize: 12, unselectedFontSize: 12, elevation: 16,
                currentIndex: (_activeNavIndex >= 0 && _activeNavIndex <= 4) ? _activeNavIndex : 0,
                onTap: (index) {
                  setState(() => _activeNavIndex = index);
                  if (index == 0) { _pageController.jumpToPage(0); }
                  if (index == 1) widget.onChatSelected(_systemTicketsContact);
                  if (index == 2) {
                    widget.onChatSelected(_systemPostsContact);
                    _refreshPostsUnread();
                  }
                  if (index == 3) widget.onChatSelected(_systemGroupsContact);
                  if (index == 4) widget.onChatSelected(_rockAiContact);
                },
                items: [
                  BottomNavigationBarItem(icon: Stack(clipBehavior: Clip.none, children: [ const Icon(Icons.chat_rounded), if (totalMainUnread > 0) Positioned(right: -8, top: -4, child: Container(padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2), decoration: const ShapeDecoration(color: Color(0xFFCC7504), shape: StadiumBorder()), child: Text(totalMainUnread.toString(), style: const TextStyle(color: Colors.white, fontSize: 9, fontWeight: FontWeight.bold)))) ]), label: 'Chats'),
                  const BottomNavigationBarItem(icon: Icon(Icons.confirmation_number_outlined), label: 'Tickets'),
                  BottomNavigationBarItem(
                    icon: Stack(
                      clipBehavior: Clip.none,
                      children: [
                        const Icon(Icons.article_outlined),
                        if (_postsUnread > 0)
                          Positioned(
                            right: -9,
                            top: -5,
                            child: Container(
                              constraints: const BoxConstraints(minWidth: 17, minHeight: 17),
                              padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
                              decoration: const ShapeDecoration(color: Color(0xFFD93025), shape: StadiumBorder()),
                              child: Text(_postsUnread > 99 ? '99+' : '$_postsUnread', style: const TextStyle(color: Colors.white, fontSize: 9, fontWeight: FontWeight.w900)),
                            ),
                          ),
                      ],
                    ),
                    label: 'Posts',
                  ),
                  const BottomNavigationBarItem(icon: Icon(Icons.groups_outlined), label: 'Groups'),
                  BottomNavigationBarItem(icon: _buildMetaAIIcon(isMobile: true), label: 'Rock AI'),
                ],
              )
            : null,
          body: Row(
            children: [
              if (!isMobile)
                Container(
                  width: 64, color: Colors.white,
                  child: LayoutBuilder(
                    builder: (context, constraints) {
                      return SingleChildScrollView(
                        child: ConstrainedBox(
                          constraints: BoxConstraints(minHeight: constraints.maxHeight),
                          child: IntrinsicHeight(
                            child: Padding(
                              padding: const EdgeInsets.symmetric(vertical: 16),
                              child: Column(
                                children: [
                                  _navIcon(Icons.chat_rounded, 'Chats', isActive: _activeNavIndex == 0, count: totalMainUnread, onTap: () { setState(() => _activeNavIndex = 0); _pageController.jumpToPage(0); }),
                                  const SizedBox(height: 24),
                                  _navIcon(Icons.confirmation_number_outlined, 'Tickets', isActive: _activeNavIndex == 1, badgeDot: true, onTap: () { setState(() => _activeNavIndex = 1); widget.onChatSelected(_systemTicketsContact); }),
                                  const SizedBox(height: 24),
                                  _navIcon(
                                    Icons.article_outlined,
                                    'Posts',
                                    isActive: _activeNavIndex == 2,
                                    count: _postsUnread,
                                    onTap: () {
                                      setState(() => _activeNavIndex = 2);
                                      widget.onChatSelected(_systemPostsContact);
                                      _refreshPostsUnread();
                                    },
                                  ),
                                  const SizedBox(height: 24),
                                  _navIcon(Icons.groups_outlined, 'Groups', isActive: _activeNavIndex == 3, onTap: () { setState(() => _activeNavIndex = 3); widget.onChatSelected(_systemGroupsContact); }),
                                  const SizedBox(height: 24),
                                  _buildMetaAIIcon(isActive: widget.selectedChatId == _rockAiContact.id),
                                  const Spacer(),
                                  _navIcon(Icons.archive_outlined, 'Archived', count: totalArchiveUnread, onTap: () => setState(() { _isViewingArchive = true; _activeNavIndex = 0; _pageController.jumpToPage(0); })),
                                  const SizedBox(height: 24),
                                  _navIcon(Icons.settings_outlined, 'Settings', isActive: _activeNavIndex == 5, onTap: () { setState(() => _activeNavIndex = 5); _pageController.jumpToPage(2); }),
                                  const SizedBox(height: 24),
                                  Tooltip(message: 'Profile', child: InkWell(onTap: () { setState(() => _activeNavIndex = 6); _pageController.jumpToPage(3); }, child: _buildAvatar(widget.myPic, radius: 14, iconSize: 18, backgroundColor: Colors.grey.shade300, fallbackColor: Colors.white))),
                                ],
                              ),
                            ),
                          ),
                        ),
                      );
                    }
                  ),
                ),
              if (!isMobile) VerticalDivider(width: 1, thickness: 1, color: Colors.grey.shade200),
              Expanded(
                child: PageView(
                  controller: _pageController,
                  physics: const NeverScrollableScrollPhysics(),
                  children: [
                    _buildActiveChatsView(mainChats, archivedChats, totalGroups, totalMainUnread, totalArchiveUnread, isMobile), // Index 0: Main Chat List
                    _buildContactsView(), // Index 1: Contacts
                    SettingsPanel(
                      onBack: () { setState(() => _activeNavIndex = 0); _pageController.jumpToPage(0); },
                      onProfileTap: () { setState(() => _activeNavIndex = 6); _pageController.jumpToPage(3); },
                      myName: widget.myName,
                      myPic: widget.myPic
                    ), // Index 2: Settings
                    // 🚀 REMOVED THE onStartChat PARAMETER HERE

                    ProfilePanel(
                      onBack: () { setState(() => _activeNavIndex = 0); _pageController.jumpToPage(0); },
                      myName: widget.myName,
                      myPic: widget.myPic,
                    ), // Index 3: Profile
                  ],
                ),
              ),
            ],
          ),
        );
      }
    );
  }
}
class _HoverableChatListItem extends StatefulWidget {
  final ChatContact chat;
  final bool isSelected;
  final bool isViewingArchive;
  final bool isMobile;
  final bool isAiContact;
  final VoidCallback onTap;
  final VoidCallback onArchive;
  final ImageProvider? avatarProvider;
  final String formattedTime;
  const _HoverableChatListItem({required this.chat, required this.isSelected, required this.isViewingArchive, required this.isMobile, required this.isAiContact, required this.onTap, required this.onArchive, required this.avatarProvider, required this.formattedTime});

  @override
  State<_HoverableChatListItem> createState() => _HoverableChatListItemState();
}
class _HoverableChatListItemState extends State<_HoverableChatListItem> with SingleTickerProviderStateMixin {
  bool _isHovered = false;
  late AnimationController _spinController;

  @override
  void initState() {
    super.initState();
    _spinController = AnimationController(vsync: this, duration: const Duration(seconds: 4))..repeat();
  }
  @override
  void dispose() {
    _spinController.dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    final isNewChat = widget.chat.lastMessage == 'Chat created' || widget.chat.lastMessage == 'Group created';
    return MouseRegion(
      onEnter: (_) => setState(() => _isHovered = true),
      onExit: (_) => setState(() => _isHovered = false),
      cursor: SystemMouseCursors.click,
      child: GestureDetector(
        onTap: widget.onTap,
        onLongPress: () {
          if (widget.isMobile && !widget.isAiContact) {
            showModalBottomSheet(
              context: context, backgroundColor: Colors.white, shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(16))),
              builder: (ctx) => Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(margin: const EdgeInsets.symmetric(vertical: 12), width: 40, height: 5, decoration: BoxDecoration(color: Colors.grey.shade300, borderRadius: BorderRadius.circular(4))),
                  ListTile(leading: Icon(widget.isViewingArchive ? Icons.unarchive_outlined : Icons.archive_outlined, color: const Color(0xFF111B21)), title: Text(widget.isViewingArchive ? 'Unarchive chat' : 'Archive chat', style: const TextStyle(fontWeight: FontWeight.w500, fontSize: 16)), onTap: () { Navigator.pop(ctx); widget.onArchive(); }),
                  const SizedBox(height: 16),
                ]
              )
            );
          }
        },
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), decoration: BoxDecoration(color: widget.isSelected ? const Color(0xFFF0F2F5) : (_isHovered ? const Color(0xFFF5F6F6) : Colors.white)),
          child: Row(
            children: [
              if (widget.isAiContact)
                Container(
                  width: 48, height: 48,
                  decoration: BoxDecoration(color: Colors.grey.shade100, shape: BoxShape.circle),
                  child: RotationTransition(
                    turns: _spinController,
                    child: ShaderMask(
                      shaderCallback: (bounds) => const SweepGradient(colors: [Color.fromARGB(255, 214, 160, 11), Color.fromARGB(255, 9, 131, 74), Color.fromARGB(255, 129, 87, 7), Color.fromARGB(255, 3, 112, 70)], stops: [0.0, 0.33, 0.66, 1.0]).createShader(bounds),
                      child: const Icon(Icons.blur_on, color: Colors.white, size: 28),
                    ),
                  )
                )
              else
                CircleAvatar(radius: 24, backgroundColor: Colors.grey.shade200, backgroundImage: widget.avatarProvider, child: widget.avatarProvider == null ? Icon(widget.chat.isGroup ? Icons.groups : Icons.person, color: Colors.grey) : null),
              const SizedBox(width: 14),
              Expanded(
                child: Container(
                  decoration: BoxDecoration(border: Border(bottom: BorderSide(color: Colors.grey.shade100))), padding: const EdgeInsets.only(bottom: 12),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Expanded(child: Text(widget.chat.name, style: const TextStyle(fontWeight: FontWeight.w500, fontSize: 16, color: Color(0xFF111B21)), maxLines: 1, overflow: TextOverflow.ellipsis)),
                          Text(widget.formattedTime, style: TextStyle(fontSize: 12, color: widget.chat.unreadCount > 0 ? const Color(0xFFCC7504) : const Color(0xFF54656F), fontWeight: widget.chat.unreadCount > 0 ? FontWeight.bold : FontWeight.normal)),
                        ],
                      ),
                      const SizedBox(height: 4),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Expanded(child: isNewChat ? Text(widget.chat.isGroup ? 'Group initialized' : 'Start a conversation', style: const TextStyle(fontSize: 13, color: Color(0xFF54656F), fontStyle: FontStyle.italic)) : Text(widget.chat.lastMessage, style: const TextStyle(fontSize: 14, color: Color(0xFF54656F)), maxLines: 1, overflow: TextOverflow.ellipsis)),
                          Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              if (_isHovered && !widget.isMobile && !widget.isAiContact)
                                Tooltip(message: widget.isViewingArchive ? 'Unarchive chat' : 'Archive chat', child: Material(color: Colors.white, shape: const CircleBorder(), elevation: 2, shadowColor: Colors.black.withOpacity(0.4), child: InkWell(onTap: widget.onArchive, customBorder: const CircleBorder(), child: Padding(padding: const EdgeInsets.all(6), child: Icon(widget.isViewingArchive ? Icons.unarchive_outlined : Icons.keyboard_arrow_down_rounded, size: 18, color: const Color(0xFF54656F)))))),
                              if (widget.chat.hasMention) Container(margin: const EdgeInsets.only(left: 6), padding: const EdgeInsets.all(4), decoration: BoxDecoration(color: const Color(0xFFCC7504), shape: BoxShape.circle, boxShadow: [BoxShadow(color: Colors.greenAccent.withOpacity(0.4), blurRadius: 4, spreadRadius: 0)]), child: const Text('@', style: TextStyle(color: Colors.white, fontSize: 10, fontWeight: FontWeight.w900))),
                              if (widget.chat.unreadCount > 0) Container(margin: const EdgeInsets.only(left: 6), padding: const EdgeInsets.all(6), decoration: const BoxDecoration(color: Color(0xFFCC7504), shape: BoxShape.circle), child: Text(widget.chat.unreadCount.toString(), style: const TextStyle(color: Colors.white, fontSize: 10, fontWeight: FontWeight.bold)))
                            ],
                          )
                        ],
                      ),
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
