// lib/features/admin/screens/admin_home_screen.dart
// ignore_for_file: unused_field, unused_import

import 'dart:async'; 
import 'dart:io';
import 'dart:convert'; 
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http; 
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:cloud_firestore/cloud_firestore.dart'; 

import '../../../core/constants/app_colors.dart';
import '../../../core/services/database_service.dart';
import '../../../core/models/user.dart';  
import '../../../core/networks/api_client.dart';  
import '../../auth/reconnection_screen.dart'; 

// -----------------------------------------------------------
// ADMIN TABS 
// -----------------------------------------------------------
import '../tabs/admin_home_feed_tab.dart'; 
import '../tabs/positions/admin_positions_main_tab.dart';
import '../tabs/leave/leave_main_tab.dart';
import '../tabs/admin_announcements_tab.dart'; 
import '../tabs/admin_events_tab.dart';
import '../tabs/qa/admin_qa_main_tab.dart';
import '../tabs/cv/employee_cv_tab.dart';
import '../tabs/clubs/admin_clubs_main_tab.dart'; 
import '../tabs/market/admin_market_main_tab.dart'; 
import '../tabs/housing/admin_housing_main_tab.dart'; 
import '../tabs/admin_alumni_tab.dart'; 
import '../tabs/faq/admin_faq_main_tab.dart'; 
import '../tabs/admin_about_us_tab.dart'; 
import '../tabs/admin_about_campuses_tab.dart'; 
import '../tabs/KPI/admin_kpi_dashboard_tab.dart'; 
import '../tabs/library/library_dashboard_tab.dart';
import '../tabs/business/business_department_tab.dart';
import '../tabs/agriculture/agriculture_department_tab.dart';
import '../tabs/marketing/marketing_department_tab.dart';
import '../tabs/ict/ict_department_tab.dart';
import '../tabs/hr/hr_department_tab.dart';

// 🚀 NEW: FEED AI & UNANSWERED QUESTIONS IMPORTS
import '../tabs/feed_ai_tab.dart';
import '../tabs/unanswered_questions_tab.dart';

// --- NEW TABS ADDED ---
import '../tabs/examination/student_performance_main_tab.dart';
import '../tabs/requests/requests_main_tab.dart';
import '../tabs/accounts/accounts_main_tab.dart';
import '../tabs/asset_management/asset_main_tab.dart';
import '../tabs/asset_management/assigned_assets_tab.dart';
import '../tabs/education/education_department_tab.dart';
import '../tabs/IT_support/it_support_main_tab.dart';

// 🚀 NEW: MESSAGES TAB IMPORT
import '../tabs/messages/admin_messages_main_tab.dart';

// --- NEW STAFFS TABS ADDED ---
import '../tabs/staff_announcements/staff_announcements_main_tab.dart'; 
import '../tabs/staff_events/staff_events_main_tab.dart';
import '../tabs/staff_lectures/staff_lectures_main_tab.dart';
import '../tabs/staff_news/staff_news_main_tab.dart';
import '../tabs/staff_qa/staff_qa_main_tab.dart';
import '../tabs/staff_clubs/staff_clubs_main_tab.dart'; 
import '../tabs/staff_market/staff_market_main_tab.dart'; 
import '../tabs/files/files_main_tab.dart'; 
import '../tabs/staff_faq/staff_faq_main_tab.dart'; 
import '../tabs/cv/my_cv_tab.dart';
import 'module_assistant_screen.dart';

// =====================================================================
// STANDARD COLOR PALETTE
// =====================================================================
const Color _standardGold = Color.fromARGB(255, 204, 117, 4);
const Color _darkGreen = Color.fromARGB(255, 2, 105, 48);

final CacheManager customAdminCacheManager = CacheManager(
  Config('adminProfileImageCache', stalePeriod: const Duration(days: 30), maxNrOfCacheObjects: 100),
);

ImageProvider? getSmartImageProvider(String? imageString) {
  if (imageString == null || imageString.trim().isEmpty) return null;
  if (imageString.startsWith('http://') || imageString.startsWith('https://')) {
    return CachedNetworkImageProvider(imageString, cacheManager: customAdminCacheManager);
  } else if (imageString.startsWith('/data') || imageString.startsWith('C:\\') || imageString.startsWith('storage')) {
    final file = File(imageString);
    if (file.existsSync()) return FileImage(file);
  } else {
    try {
      String cleanBase64 = imageString;
      if (cleanBase64.contains(',')) cleanBase64 = cleanBase64.split(',').last;
      cleanBase64 = cleanBase64.replaceAll(RegExp(r'\s+'), '');
      return MemoryImage(base64Decode(cleanBase64));
    } catch (e) {
      debugPrint('Error decoding base64 image: $e');
    }
  }
  return null;
}

// =====================================================================
// DYNAMIC MODULE CLASS
// =====================================================================
class AdminModule {
  final String title;
  final IconData icon;
  final Widget Function(LocalUser?) screenBuilder;

  AdminModule(this.title, this.icon, this.screenBuilder);
}

// =====================================================================
// HOVER WRAPPER WIDGET
// =====================================================================
class HoverClickable extends StatefulWidget {
  final Widget Function(bool isHovered) builder;
  final VoidCallback? onTap;

  const HoverClickable({super.key, required this.builder, this.onTap});

  @override
  State<HoverClickable> createState() => _HoverClickableState();
}

class _HoverClickableState extends State<HoverClickable> {
  bool _isHovered = false;

  @override
  Widget build(BuildContext context) {
    return MouseRegion(
      onEnter: (_) => setState(() => _isHovered = true),
      onExit: (_) => setState(() => _isHovered = false),
      cursor: widget.onTap != null ? SystemMouseCursors.click : SystemMouseCursors.basic,
      child: GestureDetector(
        onTap: widget.onTap,
        child: widget.builder(_isHovered),
      ),
    );
  }
}

class AdminHomeScreen extends StatefulWidget {
  const AdminHomeScreen({super.key});

  @override
  State<AdminHomeScreen> createState() => _AdminHomeScreenState();
}

class _AdminHomeScreenState extends State<AdminHomeScreen> with TickerProviderStateMixin {
  int _bottomNavIndex = 0;
  TabController? _topTabController;
  Timer? _liveSyncTimer; 
  Timer? _moduleBadgeTimer;

  // Module shortcuts stay visible by default. The existing visibility toggle is preserved.
  bool _showTopTabs = true; 
  bool _showBottomBar = false; 
  bool _isMenuOpen = false; 
  bool _isLeftPanelVisible = false; 
  
  LocalUser? _currentAdmin;

  bool _isSwitchingAccount = false;
  String _switchStatus = '';

  // 🚀 Track Unread Messages & Wave Animation
  int _totalUnreadMessages = 0;
  StreamSubscription<QuerySnapshot>? _chatSubscription;
  late AnimationController _waveController; // Added for badge animation

  // Lightweight badge counts for the social/admin modules already in the system.
  // These are presentation-only and do not change any module functionality.
  final Map<String, int> _moduleBadgeCounts = <String, int>{};
  bool _moduleBadgeSyncInFlight = false;

  // 🚀 SEARCH BAR CONTROLLERS
  final TextEditingController _searchController = TextEditingController();
  String _searchQuery = '';

  // --- MASTER LIST OF ALL MODULES ---
  late final List<AdminModule> _masterModules = [
    AdminModule('University Dashboard', Icons.dashboard_rounded, (c) => const AdminHomeFeedTab()),
    //AdminModule('Manage KPI Dashboard', Icons.insights_rounded, (c) => const AdminKpiDashboardTab()),
    AdminModule('Library Management', Icons.local_library_rounded, (c) => LibraryDashboardTab(currentUser: c)),
    AdminModule('Manage Operations', Icons.work_rounded, (c) => const AdminPositionsMainTab()),
    AdminModule('Request For Leave', Icons.security_rounded, (c) => const LeaveMainTab()),
    AdminModule('Manage Announcements', Icons.campaign_rounded, (c) => AdminAnnouncementsTab(adminName: c?.fullName ?? 'System Administrator')),
    AdminModule('Manage Uni Events', Icons.event_available_rounded, (c) => const AdminEventsTab()),
    AdminModule('Help Community Mgt', Icons.forum_rounded, (c) => const AdminQAMainTab()),
    AdminModule('Business Department', Icons.groups_rounded, (c) => const BusinessDepartmentTab()),
    AdminModule('Manage Marketplace', Icons.storefront_rounded, (c) => const AdminMarketMainTab()),
    AdminModule('Agriculture Department', Icons.local_florist_rounded, (c) => const AgricultureDepartmentTab()),
    AdminModule('ICT Department', Icons.local_florist_rounded, (c) => const ICTDepartmentTab()),
    AdminModule('HR Department', Icons.local_florist_rounded, (c) => const HRDepartmentTab()),
    //AdminModule('Manage Accommodation', Icons.apartment_rounded, (c) => const AdminHousingMainTab()),
    AdminModule('Employee CVs', Icons.help_outline_rounded, (c) => const EmployeeCvTab()),
    AdminModule('My CV', Icons.info_outline_rounded, (c) => const MyCvTab()),
    
    // 🚀 NEW TABS ADDED
    AdminModule('Feed Rockview Assistant', Icons.smart_toy_rounded, (c) => const FeedAiTab()),
    AdminModule('Help Rockview Assistant', Icons.question_answer_rounded, (c) => const UnansweredQuestionsTab()),
    AdminModule('Module Assistant', Icons.auto_awesome_rounded, (c) => _buildAssistantScreen()),

    // --- NEW MODULES ---
    AdminModule('Student Performance', Icons.assignment_rounded, (c) => const StudentPerformanceMainTab()),
    AdminModule('Manage Uni Requests', Icons.pending_actions_rounded, (c) => RequestsMainTab(currentUser: c)),
    //AdminModule('Manage Accounts', Icons.account_balance_wallet_rounded, (c) => const AccountsMainTab()),
    AdminModule('Manage Uni Asset', Icons.inventory_2_rounded, (c) => const AssetMainTab()),
    AdminModule('Education Department', Icons.inventory_2_rounded, (c) => const EducationDepartmentTab()),
    AdminModule('Manage IT Support', Icons.computer_rounded, (c) => const ITSupportMainTab()),

    // --- NEW STAFF MODULES ---
    AdminModule('Uni Announcements', Icons.campaign_rounded, (c) => const StaffAnnouncementsMainTab()),
    AdminModule('Management Events', Icons.event_available_rounded, (c) => const StaffEventsMainTab()),
    AdminModule('Members of Staff', Icons.event_note_rounded, (c) => const StaffLecturesMainTab()),
    AdminModule('Management News', Icons.newspaper_rounded, (c) => const StaffNewsMainTab()),
    AdminModule('Need Help? Ask', Icons.forum_rounded, (c) => const StaffQaMainTab()),
    AdminModule('Clubs Management', Icons.groups_rounded, (c) => const StaffClubsMainTab()),
    AdminModule('Management Market', Icons.storefront_rounded, (c) => const StaffMarketMainTab()),
    AdminModule('File Management', Icons.apartment_rounded, (c) => const FilesMainTab()),
    AdminModule('Check Assigned Assets', Icons.help_outline_rounded, (c) => const AssignedAssetsTab()),
    AdminModule('Marketing Department', Icons.help_outline_rounded, (c) => const MarketingDepartmentTab()),
  ];

  List<AdminModule> _allowedModules = [];

  // 🚀 DYNAMIC GETTER FOR FILTERED MODULES
  List<AdminModule> get _filteredModules {
    if (_searchQuery.isEmpty) return _allowedModules;
    return _allowedModules
        .where((m) => m.title.toLowerCase().contains(_searchQuery.toLowerCase()))
        .toList();
  }

  @override
  void initState() {
    super.initState();
    _allowedModules = List.from(_masterModules);
    
    // Initialize the beautiful wave ripple animation
    _waveController = AnimationController(
      vsync: this, 
      duration: const Duration(milliseconds: 2000)
    )..repeat();

    _fetchLocalProfile(); 
    
    // Checks permissions in background every 5 seconds
    _liveSyncTimer = Timer.periodic(const Duration(seconds: 5), (_) => _syncLivePermissions());

    // Badge counts are intentionally refreshed less frequently than permissions.
    // This keeps the header feeling live without making the dashboard heavy.
    _moduleBadgeTimer = Timer.periodic(
      const Duration(seconds: 10),
      (_) => _syncModuleBadges(),
    );
  }

  void _onTabChanged() {
    if (mounted) {
      setState(() {
        _bottomNavIndex = 0; 
      });
    }
  }

  @override
  void dispose() {
    _searchController.dispose();
    _waveController.dispose(); // Clean up wave animation
    _chatSubscription?.cancel();
    _liveSyncTimer?.cancel(); 
    _moduleBadgeTimer?.cancel();
    _topTabController?.removeListener(_onTabChanged);
    _topTabController?.dispose();
    super.dispose();
  }

  Future<void> _fetchLocalProfile() async {
    try {
      final user = await DatabaseService.getLocalUser(); 
      if (!mounted) return;

      setState(() => _currentAdmin = user);

      dynamic dynamicUser = user;
      _applyPermissions(dynamicUser?.permissions);
      
      _syncLivePermissions();
      _listenForUnreadMessages(); 
      _syncModuleBadges();
    } catch (e) {
      debugPrint('Error fetching local admin profile: $e');
    }
  }

  // 🚀 LISTENS FOR UNREAD MESSAGES ACROSS ALL CHATS
  void _listenForUnreadMessages() {
    if (_currentAdmin == null || _currentAdmin!.email.isEmpty) return;
    
    final myEmail = _currentAdmin!.email.toLowerCase();
    
    _chatSubscription = FirebaseFirestore.instance
        .collection('chats')
        .where('participants', arrayContains: myEmail)
        .snapshots()
        .listen((snapshot) {
      
      int totalUnread = 0;
      for (var doc in snapshot.docs) {
        final data = doc.data();
        final isArchived = (data['archivedBy'] as List<dynamic>? ?? []).contains(myEmail);
        
        if (!isArchived) {
          final unreads = (data['unreadCounts']?[myEmail] ?? 0) as int;
          totalUnread += unreads;
        }
      }
      
      if (mounted) {
        setState(() {
          _totalUnreadMessages = totalUnread;
        });
      }
    });
  }

  int _safeInt(dynamic value, [int fallback = 0]) {
    if (value is int) return value;
    if (value is num) return value.toInt();
    return int.tryParse('${value ?? ''}') ?? fallback;
  }

  Map<String, dynamic>? _asJsonMap(String body) {
    try {
      final decoded = jsonDecode(body);
      if (decoded is Map) {
        return decoded.map((key, value) => MapEntry(key.toString(), value));
      }
    } catch (_) {}
    return null;
  }

  Future<Map<String, dynamic>?> _badgeGet(String relativeUrl) async {
    try {
      final response = await http
          .get(
            Uri.parse('${ApiClient.baseUrl}$relativeUrl'),
            headers: await ApiClient.getHeaders(),
          )
          .timeout(const Duration(seconds: 8));

      // Badge refresh is background-only. Do not redirect the user or interrupt
      // an open module when one optional badge endpoint is unavailable.
      if (response.statusCode != 200) return null;
      return _asJsonMap(response.body);
    } catch (_) {
      return null;
    }
  }

  Future<int?> _fetchUnreadBadge(String relativeUrl) async {
    final data = await _badgeGet(relativeUrl);
    if (data == null) return null;
    return _safeInt(data['unread_count']);
  }

  Future<int?> _fetchPaginationTotal(String relativeUrl) async {
    final data = await _badgeGet(relativeUrl);
    if (data == null) return null;
    final pagination = data['pagination'];
    if (pagination is Map) return _safeInt(pagination['total']);
    return null;
  }

  Future<int?> _fetchSupportUnreadForStaff() async {
    final data = await _badgeGet('/api/support_threads.php?scope=open&page=1&limit=50');
    if (data == null) return null;
    return _safeInt(data['unread_total']);
  }

  Future<int?> _fetchAdminSupportQueue() async {
    final modern = await _badgeGet(
      '/api/support_threads.php?scope=all&status=waiting_admin&page=1&limit=1',
    );
    if (modern != null) {
      final pagination = modern['pagination'];
      if (pagination is Map) return _safeInt(pagination['total']);
    }

    // Compatibility fallback for installations that still use the original
    // Q&A route. No data is modified; this only counts unresolved questions.
    try {
      final response = await http
          .get(
            Uri.parse('${ApiClient.baseUrl}/admin/qna/questions'),
            headers: await ApiClient.getHeaders(),
          )
          .timeout(const Duration(seconds: 8));
      if (response.statusCode != 200) return null;
      final decoded = jsonDecode(response.body);
      final dynamic rows = decoded is Map ? decoded['data'] : decoded;
      if (rows is! List) return null;
      int count = 0;
      for (final raw in rows) {
        if (raw is! Map) continue;
        final value = raw['is_resolved'];
        final resolved = value == true || value == 1 || value == '1' || value == 't' || value == 'true';
        if (!resolved) count++;
      }
      return count;
    } catch (_) {
      return null;
    }
  }

  Future<void> _syncModuleBadges() async {
    if (_moduleBadgeSyncInFlight || !mounted || _currentAdmin == null) return;
    _moduleBadgeSyncInFlight = true;

    try {
      final role = _currentAdmin!.role.toLowerCase();
      final isAdmin = role.contains('admin') || role.contains('super');

      final results = await Future.wait<int?>([
        _fetchUnreadBadge('/api/news_notifications.php?limit=1'),
        _fetchUnreadBadge('/api/announcement_notifications.php?limit=1'),
        _fetchUnreadBadge('/api/event_notifications.php?limit=1'),
        _fetchUnreadBadge('/api/market_notifications.php?limit=1'),
        isAdmin
            ? _fetchPaginationTotal('/api/market_feed.php?moderation=true&page=1&limit=1')
            : Future<int?>.value(null),
        isAdmin ? _fetchAdminSupportQueue() : Future<int?>.value(null),
        _fetchSupportUnreadForStaff(),

        // Official request workflow notifications. Every authenticated hand-off
        // creates an unread notification for the next office and/or requester,
        // so this count is the canonical badge for the Requests module.
        _fetchUnreadBadge('/api/request_notifications.php?action=count'),
      ]);

      if (!mounted) return;

      final next = Map<String, int>.from(_moduleBadgeCounts);

      void apply(List<String> titles, int? value) {
        if (value == null) return;
        final clean = value < 0 ? 0 : value;
        for (final title in titles) {
          next[title] = clean;
        }
      }

      apply(const ['Management News'], results[0]);
      apply(const ['Manage Announcements', 'Global Announcements'], results[1]);
      apply(const ['Manage Events', 'Management Events'], results[2]);
      apply(const ['Management Market'], results[3]);
      apply(const ['Manage Marketplace'], results[4]);
      apply(const ['Help Management'], results[5]);
      apply(const ['Need Help? Ask'], results[6]);
      apply(const ['Manage Requests'], results[7]);

      setState(() {
        _moduleBadgeCounts
          ..clear()
          ..addAll(next);
      });
    } finally {
      _moduleBadgeSyncInFlight = false;
    }
  }

  int _moduleBadgeCount(AdminModule module) => _moduleBadgeCounts[module.title] ?? 0;

  String _badgeText(int count) => count > 99 ? '99+' : '$count';

  Widget _badgeBubble(int count, {double fontSize = 9.5}) {
    if (count <= 0) return const SizedBox.shrink();
    return Container(
      constraints: const BoxConstraints(minWidth: 18, minHeight: 18),
      padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),
      decoration: BoxDecoration(
        color: Colors.redAccent,
        borderRadius: BorderRadius.circular(999),
        border: Border.all(color: Colors.white, width: 1.4),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.18),
            blurRadius: 5,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      alignment: Alignment.center,
      child: Text(
        _badgeText(count),
        style: TextStyle(
          color: Colors.white,
          fontSize: fontSize,
          fontWeight: FontWeight.w900,
          height: 1,
        ),
      ),
    );
  }

  Widget _moduleIconWithBadge(
    AdminModule module, {
    double iconSize = 22,
    Color? iconColor,
  }) {
    final count = _moduleBadgeCount(module);
    return Stack(
      clipBehavior: Clip.none,
      children: [
        Icon(module.icon, size: iconSize, color: iconColor),
        if (count > 0)
          Positioned(
            top: -9,
            right: -12,
            child: _badgeBubble(count, fontSize: 8.5),
          ),
      ],
    );
  }

  Future<void> _syncLivePermissions() async {
    if (_currentAdmin == null || _currentAdmin!.email.isEmpty || !mounted) return;

    try {
      List<dynamic> serverUsers = [];
      final String currentRole = _currentAdmin!.role.toLowerCase();

      if (ApiClient.bearerToken == null || ApiClient.bearerToken!.isEmpty) {
        debugPrint("⚠️ LIVE SYNC: Bearer token is missing. Skipping network sync.");
        return;
      } 

      if (currentRole.contains('staff')) {
        serverUsers = await ApiClient.getStaff(); 
      } else {
        serverUsers = await ApiClient.getAdmins(); 
      }

      Map<String, dynamic>? liveProfile;
      for (var u in serverUsers) {
        if ((u['email'] ?? '').toString().toLowerCase() == _currentAdmin!.email.toLowerCase()) {
          liveProfile = u;
          break;
        }
      }

      if (liveProfile != null && mounted) {
        String livePermissions = liveProfile['permissions']?.toString() ?? '';
        String localPermissions = _currentAdmin!.permissions?.toString() ?? '';
        
        if (livePermissions != localPermissions) {
          debugPrint("🔄 LIVE SYNC: Permissions changed for ${_currentAdmin!.email}!");
          
          setState(() {
            _currentAdmin!.permissions = livePermissions;
            _applyPermissions(livePermissions);
          });
          
          await DatabaseService.saveLocalUser(_currentAdmin!);
        }
      } else {
        debugPrint("⚠️ LIVE SYNC WARNING: Could not find user ${_currentAdmin!.email} in the live database.");
      }
    } catch (e) {
      debugPrint("🛑 LIVE SYNC ERROR: $e");
      
      if (e.toString().contains('Unauthorized') || e.toString().contains('Session Expired')) {
        _liveSyncTimer?.cancel();
        if (mounted) {
          Navigator.pushAndRemoveUntil(
            context, 
            MaterialPageRoute(builder: (context) => const ReconnectionScreen()), 
            (route) => false,
          );
        }
      }
    }
  }

  void _applyPermissions(dynamic permissionsData) {
    final String currentRole = _currentAdmin?.role.toLowerCase() ?? '';
    List<AdminModule> newAllowed = [];
    List<String> grantedModules = [];
    bool hasValidPermissionsConfig = false;

    try {
      if (permissionsData != null) {
        String permStr = permissionsData.toString().trim();
        if (permStr.startsWith('[')) {
          hasValidPermissionsConfig = true;
          if (permissionsData is String) {
            grantedModules = List<String>.from(json.decode(permissionsData));
          } else if (permissionsData is List) {
            grantedModules = List<String>.from(permissionsData);
          }
        }
      }
    } catch (e) {
      debugPrint('Error decoding JSON permissions: $e');
    }

    if (hasValidPermissionsConfig) {
      newAllowed = _masterModules.where((m) => grantedModules.contains(m.title)).toList();
    } else if (currentRole.contains('super')) {
      newAllowed = List.from(_masterModules);
    } else {
      newAllowed = [];
    }

    if (newAllowed.isEmpty) {
      newAllowed = [_masterModules[0]]; 
    }
    final assistantModule = _masterModules.firstWhere(
      (module) => module.title == 'Module Assistant',
    );
    if (!newAllowed.any((module) => module.title == assistantModule.title)) {
      newAllowed.add(assistantModule);
    }
    
    bool hasChanged = false;
    if (_allowedModules.length != newAllowed.length) {
      hasChanged = true;
    } else {
      for (int i = 0; i < newAllowed.length; i++) {
        if (_allowedModules[i].title != newAllowed[i].title) {
          hasChanged = true;
          break;
        }
      }
    }

    if (hasChanged || _topTabController == null) {
      _allowedModules = newAllowed;
      int newLength = _allowedModules.length;
      int currentIndex = _topTabController?.index ?? 0;

      _topTabController?.removeListener(_onTabChanged);
      _topTabController?.dispose();
      _topTabController = TabController(length: newLength, vsync: this);
      _topTabController!.addListener(_onTabChanged);
      
      if (currentIndex >= newLength) {
        _topTabController!.index = 0; 
      } else {
        _topTabController!.index = currentIndex;
      }
      
      if (mounted) setState(() {}); 
    }
  }

  void _toggleTabMenu() {
    final isDesktop = MediaQuery.of(context).size.width > 1200;
    setState(() {
      if (isDesktop) {
        _isLeftPanelVisible = !_isLeftPanelVisible;
      } else {
        _isMenuOpen = !_isMenuOpen;
      }
    });
  }

  Future<void> _performLogout() async {
    await DatabaseService.cleanEntireDatabase();
    ApiClient.bearerToken = '';
    if (!mounted) return;
    Navigator.pushAndRemoveUntil(
      context,
      MaterialPageRoute(builder: (context) => const ReconnectionScreen()),
      (route) => false,
    );
  }

  void _performAccountSwitch() async {
    if (_currentAdmin == null || _currentAdmin!.email.isEmpty) return;

    setState(() {
      _isSwitchingAccount = true;
      _switchStatus = 'Fetching User Profile...';
    });

    try {
      final url = Uri.parse('${ApiClient.baseUrl}/users/switch-session'); 
      final response = await http.post(
        url,
        headers: {
          'Content-Type': 'application/json',
          if (ApiClient.bearerToken != null) 'Authorization': 'Bearer ${ApiClient.bearerToken}', 
        },
        body: jsonEncode({'email': _currentAdmin!.email}),
      ).timeout(const Duration(seconds: 10));

      if (!mounted) return;

      if (response.statusCode == 200) {
        final Map<String, dynamic> responseData = json.decode(response.body);

        if (responseData.containsKey('token') && responseData['token'].isNotEmpty) {
          ApiClient.bearerToken = responseData['token'];
        }

        final Map<String, dynamic> userJson = responseData.containsKey('user') 
            ? responseData['user'] 
            : responseData;
            
        final switchedUser = LocalUser.fromJson(userJson);
        await DatabaseService.saveLocalUser(switchedUser);

        setState(() {
          _switchStatus = 'Access Granted. Redirecting...';
        });
        
        await Future.delayed(const Duration(milliseconds: 800));

        if (mounted) {
           // Insert routing logic to Student dashboard if needed
        }
      } else {
        throw Exception('Server rejected the switch request.');
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _switchStatus = 'Error. Failed to switch panel.';
        });
        debugPrint('Switch Error: $e');
        await Future.delayed(const Duration(milliseconds: 2500));
        setState(() {
          _isSwitchingAccount = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_topTabController == null) {
      return const Scaffold(backgroundColor: Colors.white, body: Center(child: CircularProgressIndicator(color: _darkGreen)));
    }

    final double screenWidth = MediaQuery.of(context).size.width;
    final bool isWideScreen = screenWidth > 1200;
    final bool showBottomNavText = screenWidth > 800;

    final String adminName = _currentAdmin?.fullName ?? 'System Admin';
    final String adminTitle = _currentAdmin?.role ?? 'Administrator';
    final ImageProvider? imageProvider = getSmartImageProvider(_currentAdmin?.profilePicture);

    Widget appScaffold = Scaffold(
      backgroundColor: const Color(0xFFF4F7F5), 
      body: Stack(
        children: [
          Column(
            children: [
              // 🚀 THE TOP HEADER IS NOW ALWAYS VISIBLE
              _buildTopAppBar(isWideScreen, adminName, adminTitle, imageProvider),
              
              Expanded(
                child: IndexedStack(
                  index: _bottomNavIndex,
                  children: [
                    _buildHomeFeedSection(), 
                    const AdminMessagesMainTab(),            
                    _buildHomeFeedSection(),
                    _buildAssistantScreen(),
                  ],
                ),
              ),

              AnimatedSize(
                duration: const Duration(milliseconds: 400),
                curve: Curves.fastOutSlowIn,
                alignment: Alignment.bottomCenter,
                child: (!isWideScreen && _isMenuOpen)
                  ? SizedBox(
                      width: double.infinity,
                      height: MediaQuery.of(context).size.height * 0.65, 
                      child: _buildInlineTabMenu(),
                    )
                  : const SizedBox(width: double.infinity, height: 0.0),
              ),
              
              AnimatedSize(
                duration: const Duration(milliseconds: 600),
                curve: Curves.fastOutSlowIn,
                alignment: Alignment.bottomCenter,
                child: SizedBox(
                  height: _showBottomBar ? null : 0.0,
                  width: double.infinity,
                  child: _buildBottomNavBar(showBottomNavText), 
                ),
              ),
            ],
          ),
            
          // Floating Chevron for the bottom bar
          if (!_showBottomBar && !_isMenuOpen) 
            Positioned(
              bottom: 16,
              right: 16, 
              child: _buildChevron(isTop: false, onTap: () => setState(() => _showBottomBar = true)),
            ),
        ],
      ),
    );

    Widget rootWidget;

    if (isWideScreen) {
      rootWidget = Scaffold(
        backgroundColor: const Color(0xFFF1F5F2),
        body: Row(
          children: [
            AnimatedContainer(
              duration: const Duration(milliseconds: 300),
              curve: Curves.easeInOut,
              width: _isLeftPanelVisible ? 280 : 0,
              decoration: BoxDecoration(
                color: const Color(0xFFFBFCFB),
                border: const Border(right: BorderSide(color: Color(0xFFE4EBE6), width: 1)),
                boxShadow: [
                  BoxShadow(color: _darkGreen.withOpacity(.035), blurRadius: 16, offset: const Offset(3, 0)),
                ],
              ),
              child: ClipRect(
                child: OverflowBox(
                  alignment: Alignment.topLeft,
                  maxWidth: 280,
                  minWidth: 280,
                  child: _buildDesktopLeftSidebar(),
                ),
              ),
            ),
            Expanded(child: appScaffold),
          ],
        ),
      );
    } else {
      rootWidget = appScaffold;
    }

    return Stack(
      children: [
        rootWidget,

        // Shared across all dashboard tabs; keeps the existing message state.
        if (!_isSwitchingAccount)
          Positioned(
            right: 20 + MediaQuery.of(context).padding.right,
            bottom: MediaQuery.of(context).viewInsets.bottom > 0
                ? MediaQuery.of(context).viewInsets.bottom + 16
                : 96 + MediaQuery.of(context).padding.bottom,
            child: _buildFloatingMessageButton(),
          ),
        
        if (_isSwitchingAccount)
          Positioned.fill(
            child: Material(
              color: Colors.transparent,
              child: Container(
                color: Colors.black.withOpacity(0.8), 
                child: Center(
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      CircularProgressIndicator(
                        color: _switchStatus.contains('Error') ? Colors.redAccent : _standardGold, 
                        strokeWidth: 4, 
                      ),
                      const SizedBox(height: 24),
                      Text(
                        _switchStatus,
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: _switchStatus.contains('Error') ? Colors.redAccent : Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                          letterSpacing: 1.0,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
      ],
    );
  }

  // Uses the same destination and live unread count as the bottom message icon.
  Widget _buildFloatingMessageButton() {
    final selected = _bottomNavIndex == 1;
    final count = _totalUnreadMessages;
    final label = count > 0
        ? 'Messages, $count unread. Open messages'
        : 'Open messages';

    return RepaintBoundary(
      child: Semantics(
        button: true,
        selected: selected,
        label: label,
        child: Tooltip(
          message: label,
          excludeFromSemantics: true,
          child: SizedBox(
            width: 72,
            height: 72,
            child: Stack(
              clipBehavior: Clip.none,
              children: [
                Positioned.fill(
                  child: Padding(
                    padding: const EdgeInsets.all(5),
                    child: DecoratedBox(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.zero,
                        boxShadow: [
                          BoxShadow(
                            color: _darkGreen.withOpacity(.24),
                            blurRadius: 20,
                            offset: const Offset(0, 7),
                          ),
                        ],
                      ),
                      child: Material(
                        color: _darkGreen,
                        borderRadius: BorderRadius.zero,
                        clipBehavior: Clip.antiAlias,
                        child: Ink(
                          decoration: BoxDecoration(
                            gradient: const LinearGradient(
                              begin: Alignment.topLeft,
                              end: Alignment.bottomRight,
                              colors: [Color(0xFF138653), _darkGreen, Color(0xFF034727)],
                            ),
                            borderRadius: BorderRadius.zero,
                            border: Border.all(
                              color: selected ? _standardGold : const Color(0xFFE6B968),
                              width: selected ? 2.5 : 1.5,
                            ),
                          ),
                          child: InkWell(
                            onTap: () {
                              setState(() {
                                if (_isMenuOpen) _toggleTabMenu();
                                _bottomNavIndex = 1;
                              });
                            },
                            hoverColor: Colors.white.withOpacity(.12),
                            splashColor: _standardGold.withOpacity(.25),
                            child: const Center(
                              child: Icon(
                                Icons.forum_rounded,
                                color: Colors.white,
                                size: 29,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
                if (count > 0)
                  Positioned(
                    top: 0,
                    right: 0,
                    child: IgnorePointer(
                      child: ExcludeSemantics(
                        child: Container(
                          constraints: const BoxConstraints(minWidth: 25, minHeight: 25),
                          padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 3),
                          decoration: BoxDecoration(
                            color: const Color(0xFFD93444),
                            borderRadius: BorderRadius.circular(20),
                            border: Border.all(color: Colors.white, width: 2),
                            boxShadow: [
                              BoxShadow(
                                color: Colors.black.withOpacity(.12),
                                blurRadius: 6,
                                offset: const Offset(0, 2),
                              ),
                            ],
                          ),
                          child: Text(
                            _badgeText(count),
                            textAlign: TextAlign.center,
                            style: const TextStyle(
                              color: Colors.white,
                              fontSize: 11,
                              fontWeight: FontWeight.w800,
                              height: 1.2,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildHomeFeedSection() {
    return TabBarView(
      controller: _topTabController,
      physics: const NeverScrollableScrollPhysics(), 
      children: _allowedModules.map((module) => RepaintBoundary(
        key: ValueKey<String>('admin-module-${module.title}'),
        child: module.screenBuilder(_currentAdmin),
      )).toList(),
    );
  }

  Widget _buildAssistantScreen() {
    final availableModules = _allowedModules
        .where((module) => module.title != 'Module Assistant')
        .map((module) => module.title)
        .toList(growable: false);
    return ModuleAssistantScreen(
      embedded: true,
      modules: availableModules,
    );
  }

  void _openModuleAssistant() {
    final moduleIndex = _allowedModules.indexWhere(
      (module) => module.title == 'Module Assistant',
    );
    final controller = _topTabController;
    if (moduleIndex < 0 || controller == null || moduleIndex >= controller.length) return;

    setState(() {
      _bottomNavIndex = 0;
      _isMenuOpen = false;
    });
    controller.animateTo(moduleIndex);
  }

  Widget _buildChevron({required bool isTop, required VoidCallback onTap}) {
    return HoverClickable(
      onTap: onTap,
      builder: (isHovered) => AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        curve: Curves.easeOut,
        width: 36, 
        height: 36, 
        decoration: BoxDecoration(
          color: isHovered ? _standardGold : Colors.white,
          shape: BoxShape.circle, 
          border: Border.all(color: _standardGold, width: 2),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.15),
              blurRadius: 8,
              offset: Offset(0, isTop ? 2 : -2),
            ),
          ],
        ),
        child: Icon(
          isTop ? Icons.keyboard_arrow_down_rounded : Icons.keyboard_arrow_up_rounded,
          color: isHovered ? Colors.white : _darkGreen,
          size: 22
        ),
      ),
    );
  }

  Widget _buildCircularCollapseButton({required bool isTop, required VoidCallback onTap}) {
    return HoverClickable(
      onTap: onTap,
      builder: (isHovered) => AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        margin: const EdgeInsets.symmetric(horizontal: 8),
        width: 32, 
        height: 32, 
        decoration: BoxDecoration(
          color: isHovered ? _standardGold : Colors.transparent,
          shape: BoxShape.circle, 
          border: Border.all(color: _standardGold, width: 1.5),
        ),
        child: Icon(
          isTop ? Icons.keyboard_arrow_up_rounded : Icons.keyboard_arrow_down_rounded,
          color: isHovered ? Colors.white : _standardGold,
          size: 18 
        ),
      ),
    );
  }

  // 🚀 PURE SEARCH BAR FOR MODULES
  Widget _buildSearchBar() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(24, 0, 24, 16),
      child: Container(
        decoration: BoxDecoration(
          color: const Color(0xFFF5F8F6),
          borderRadius: BorderRadius.circular(16),
          border: Border.all(color: const Color(0xFFE1E9E4)),
        ),
        child: TextField(
          controller: _searchController,
          onChanged: (val) => setState(() => _searchQuery = val),
          style: TextStyle(fontSize: 14, color: Colors.grey.shade800),
          decoration: InputDecoration(
            hintText: 'Search modules...',
            hintStyle: TextStyle(color: Colors.grey.shade500, fontSize: 14),
            prefixIcon: const Icon(Icons.search_rounded, color: Color(0xFF648071), size: 20),
            suffixIcon: _searchQuery.isNotEmpty 
                ? IconButton(
                    icon: Icon(Icons.clear_rounded, color: Colors.grey.shade500, size: 18),
                    onPressed: () {
                      _searchController.clear();
                      setState(() => _searchQuery = '');
                    },
                  )
                : null,
            border: InputBorder.none,
            contentPadding: const EdgeInsets.symmetric(vertical: 14),
          ),
        ),
      ),
    );
  }

  Widget _buildDesktopLeftSidebar() {
    return Column(
      children: [
        Container(
          width: double.infinity,
          padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 32),
          decoration: const BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [Color(0xFF087344), _darkGreen, Color(0xFF064A2C)],
            ),
            border: Border(bottom: BorderSide(color: _standardGold, width: 3)),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                height: 85,
                width: 85,
                decoration: BoxDecoration(
                  color: Colors.white,
                  shape: BoxShape.circle, 
                  border: Border.all(color: const Color(0xFFD8B56A), width: 2), 
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.3),
                      blurRadius: 15,
                      offset: const Offset(0, 8),
                    ),
                  ],
                ),
                child: ClipOval(
                  child: Image.asset(
                    'assets/logo.png', 
                    fit: BoxFit.contain, 
                  ),
                ),
              ),
              const SizedBox(height: 20),
              const Text(
                'INTRANET SYSTEM', 
                textAlign: TextAlign.center,
                style: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.w900, letterSpacing: 1.5)
              ),
              const SizedBox(height: 4),
              const Text(
                'Powered by: Rockview technologies', 
                textAlign: TextAlign.center,
                style: TextStyle(color: _standardGold, fontSize: 13, fontWeight: FontWeight.w500)
              ),
            ],
          ),
        ),
        const SizedBox(height: 16),
        _buildSearchBar(), // 🚀 Search Bar Added Here
        Expanded(
          child: ListView.builder(
            padding: const EdgeInsets.only(bottom: 16),
            itemCount: _filteredModules.length,
            itemBuilder: (context, index) {
              final module = _filteredModules[index];
              final originalIndex = _allowedModules.indexOf(module);
              final isSelected = _topTabController!.index == originalIndex;

              return HoverClickable(
                onTap: () {
                  _topTabController!.animateTo(originalIndex);
                  setState(() {}); 
                },
                builder: (isHovered) {
                  final showHighlight = isHovered || isSelected;
                  return AnimatedContainer(
                    duration: const Duration(milliseconds: 180),
                    margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 3),
                    padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 14),
                    decoration: BoxDecoration(
                      color: isSelected
                          ? const Color(0xFFEAF3ED)
                          : (isHovered ? const Color(0xFFF4F8F5) : Colors.transparent),
                      borderRadius: BorderRadius.zero,
                      border: Border.all(
                        color: isSelected ? const Color(0xFFD5E5D9) : Colors.transparent,
                      ),
                    ),
                    child: Row(
                      children: [
                        _moduleIconWithBadge(
                          module,
                          iconSize: 22,
                          iconColor: isSelected
                              ? _darkGreen
                              : (isHovered ? Colors.grey.shade800 : Colors.grey.shade500),
                        ),
                        const SizedBox(width: 16),
                        Expanded(
                          child: Text(
                            module.title,
                            style: TextStyle(
                              fontSize: 14,
                              fontWeight: isSelected ? FontWeight.bold : FontWeight.w600,
                              color: isSelected ? _darkGreen : (isHovered ? Colors.grey.shade900 : Colors.grey.shade700),
                              letterSpacing: 0.5,
                            ),
                          ),
                        ),
                        if (showHighlight) Icon(Icons.arrow_forward_ios_rounded, color: isSelected ? _standardGold : const Color(0xFF91A399), size: 13),
                      ],
                    ),
                  );
                }
              );
            },
          ),
        ),
      ],
    );
  }

  // 🚀 REFACTORED APP BAR (HEADER ALWAYS VISIBLE, TABS TOGGLEABLE)
  // 🚀 REFACTORED APP BAR (HEADER ALWAYS VISIBLE, TABS TOGGLEABLE)
  Widget _buildTopAppBar(bool isWideScreen, String adminName, String adminTitle, ImageProvider? imageProvider) {
    final bool menuActive = isWideScreen ? _isLeftPanelVisible : _isMenuOpen;
    final IconData menuIcon = isWideScreen
        ? (_isLeftPanelVisible ? Icons.menu_open_rounded : Icons.menu_rounded)
        : (_isMenuOpen ? Icons.close_rounded : Icons.menu_open_rounded);

    final double screenWidth = MediaQuery.of(context).size.width;
    final bool compactMobile = screenWidth < 560;
    final double titleFontSize = screenWidth < 380 ? 14 : (screenWidth < 600 ? 17 : 22);
    final bool showTabsText = screenWidth >= 720;

    return Container(
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [Color(0xFF087344), _darkGreen, Color(0xFF075332)],
        ),
        border: const Border(bottom: BorderSide(color: _standardGold, width: 2)),
        boxShadow: [
          BoxShadow(
            color: _darkGreen.withOpacity(0.12),
            blurRadius: 16,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: SafeArea(
        bottom: false,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            SizedBox(
              height: compactMobile ? 58 : kToolbarHeight,
              child: Row(
                children: [
                  const SizedBox(width: 4),
                  Tooltip(
                    message: menuActive ? 'Close Menu' : 'Open Menu',
                    child: HoverClickable(
                      onTap: _toggleTabMenu,
                      builder: (isHovered) => AnimatedContainer(
                        duration: const Duration(milliseconds: 180),
                        margin: const EdgeInsets.symmetric(horizontal: 5),
                        decoration: BoxDecoration(
                          color: menuActive
                              ? Colors.white24
                              : (isHovered ? _standardGold.withOpacity(.18) : Colors.transparent),
                          borderRadius: BorderRadius.zero,
                        ),
                        child: IconButton(
                          visualDensity: compactMobile ? VisualDensity.compact : VisualDensity.standard,
                          icon: Icon(
                            menuIcon,
                            color: menuActive
                                ? Colors.white
                                : (isHovered ? _standardGold : Colors.white70),
                          ),
                          onPressed: _toggleTabMenu,
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(width: 3),
                  Expanded(
                    child: Row(
                      children: [
                        Flexible(
                          child: RichText(
                            overflow: TextOverflow.ellipsis,
                            maxLines: 1,
                            text: TextSpan(
                              children: [
                                TextSpan(
                                  text: 'INTRANET ',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: titleFontSize,
                                    fontWeight: FontWeight.w900,
                                    letterSpacing: compactMobile ? .7 : 1.5,
                                  ),
                                ),
                                TextSpan(
                                  text: 'SYSTEM',
                                  style: TextStyle(
                                    color: _standardGold,
                                    fontSize: titleFontSize,
                                    fontWeight: FontWeight.w500,
                                    letterSpacing: compactMobile ? .7 : 1.5,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                        if (!compactMobile && screenWidth > 760) ...[
                          const SizedBox(width: 12),
                          Container(
                            width: 1,
                            height: 24,
                            color: Colors.white.withOpacity(.16),
                          ),
                          const SizedBox(width: 12),
                          Flexible(
                            child: Text(
                              adminName,
                              overflow: TextOverflow.ellipsis,
                              style: const TextStyle(
                                color: Colors.white70,
                                fontSize: 11.5,
                                fontWeight: FontWeight.w700,
                              ),
                            ),
                          ),
                        ],
                      ],
                    ),
                  ),
                  Tooltip(
                    message: _showTopTabs ? 'Hide module shortcuts' : 'Show module shortcuts',
                    child: HoverClickable(
                      onTap: () => setState(() => _showTopTabs = !_showTopTabs),
                      builder: (isHovered) => AnimatedContainer(
                        duration: const Duration(milliseconds: 180),
                        margin: const EdgeInsets.only(right: 5),
                        padding: EdgeInsets.symmetric(
                          horizontal: showTabsText ? 12 : 9,
                          vertical: 7,
                        ),
                        decoration: BoxDecoration(
                          color: _showTopTabs
                              ? _standardGold.withOpacity(.16)
                              : (isHovered ? Colors.white.withOpacity(.12) : Colors.white.withOpacity(.07)),
                          borderRadius: BorderRadius.zero,
                          border: Border.all(
                            color: _standardGold.withOpacity(_showTopTabs || isHovered ? .85 : .35),
                          ),
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(
                              _showTopTabs ? Icons.apps_rounded : Icons.apps_outlined,
                              color: _showTopTabs ? _standardGold : Colors.white,
                              size: 18,
                            ),
                            if (showTabsText) ...[
                              const SizedBox(width: 7),
                              Text(
                                'Modules',
                                style: TextStyle(
                                  color: _showTopTabs ? _standardGold : Colors.white,
                                  fontWeight: FontWeight.w700,
                                  fontSize: 12,
                                ),
                              ),
                            ],
                          ],
                        ),
                      ),
                    ),
                  ),
                  if (compactMobile)
                    _buildMobileAccountMenu(adminName, adminTitle, imageProvider)
                  else ...[
                    if (screenWidth > 600) ...[
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.end,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            adminTitle,
                            style: const TextStyle(
                              color: _standardGold,
                              fontSize: 10.5,
                              fontWeight: FontWeight.w700,
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(width: 8),
                      CircleAvatar(
                        radius: 17,
                        backgroundColor: Colors.white24,
                        backgroundImage: imageProvider,
                        child: imageProvider == null
                            ? Text(
                                adminName.isNotEmpty ? adminName[0].toUpperCase() : 'U',
                                style: const TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 13,
                                ),
                              )
                            : null,
                      ),
                      const SizedBox(width: 5),
                    ],
                    Tooltip(message: 'Module assistant', child: _buildAppBarAction(Icons.auto_awesome_rounded, _openModuleAssistant)),
                    _buildAppBarAction(Icons.switch_account_rounded, _performAccountSwitch),
                    _buildAppBarAction(Icons.logout_rounded, _performLogout),
                  ],
                  const SizedBox(width: 3),
                ],
              ),
            ),

            AnimatedSize(
              duration: const Duration(milliseconds: 300),
              curve: Curves.easeOutCubic,
              alignment: Alignment.topCenter,
              child: SizedBox(
                height: _showTopTabs ? null : 0,
                child: _buildModuleShortcutBar(screenWidth),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildMobileAccountMenu(
    String adminName,
    String adminTitle,
    ImageProvider? imageProvider,
  ) {
    return PopupMenuButton<String>(
      tooltip: 'Account',
      color: Colors.white,
      elevation: 12,
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
      onSelected: (value) {
        if (value == 'assistant') {
          _openModuleAssistant();
        } else if (value == 'switch') {
          _performAccountSwitch();
        } else if (value == 'logout') {
          _performLogout();
        }
      },
      itemBuilder: (_) => [
        PopupMenuItem<String>(
          enabled: false,
          child: SizedBox(
            width: 220,
            child: Row(
              children: [
                CircleAvatar(
                  radius: 20,
                  backgroundColor: _darkGreen.withOpacity(.12),
                  backgroundImage: imageProvider,
                  child: imageProvider == null
                      ? Text(
                          adminName.isNotEmpty ? adminName[0].toUpperCase() : 'U',
                          style: const TextStyle(
                            color: _darkGreen,
                            fontWeight: FontWeight.w900,
                          ),
                        )
                      : null,
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        adminName,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: const TextStyle(
                          color: Color(0xFF1F2D28),
                          fontWeight: FontWeight.w900,
                        ),
                      ),
                      Text(
                        adminTitle,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          color: Colors.grey.shade600,
                          fontSize: 11,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
        const PopupMenuDivider(),
        const PopupMenuItem<String>(
          value: 'assistant',
          child: Row(
            children: [
              Icon(Icons.auto_awesome_rounded, color: _darkGreen),
              SizedBox(width: 12),
              Text('Module assistant'),
            ],
          ),
        ),
        const PopupMenuItem<String>(
          value: 'switch',
          child: Row(
            children: [
              Icon(Icons.switch_account_rounded, color: _darkGreen),
              SizedBox(width: 12),
              Text('Switch account'),
            ],
          ),
        ),
        const PopupMenuItem<String>(
          value: 'logout',
          child: Row(
            children: [
              Icon(Icons.logout_rounded, color: Colors.redAccent),
              SizedBox(width: 12),
              Text('Sign out'),
            ],
          ),
        ),
      ],
      child: Padding(
        padding: const EdgeInsets.only(right: 7),
        child: CircleAvatar(
          radius: 18,
          backgroundColor: Colors.white24,
          backgroundImage: imageProvider,
          child: imageProvider == null
              ? Text(
                  adminName.isNotEmpty ? adminName[0].toUpperCase() : 'U',
                  style: const TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.w900,
                    fontSize: 13,
                  ),
                )
              : null,
        ),
      ),
    );
  }

  int _moduleShortcutCapacity(double width) {
    if (width < 360) return 4;
    if (width < 430) return 5;
    if (width < 600) return 6;
    if (width < 850) return 7;
    if (width < 1100) return 8;
    if (width < 1400) return 10;
    return 12;
  }

  Widget _buildModuleShortcutBar(double width) {
    if (_allowedModules.isEmpty || _topTabController == null) {
      return const SizedBox.shrink();
    }

    final capacity = _moduleShortcutCapacity(width);
    final selectedIndex = _topTabController!.index.clamp(0, _allowedModules.length - 1).toInt();
    final hasOverflow = _allowedModules.length > capacity;
    final visibleSlots = hasOverflow ? (capacity - 1).clamp(1, capacity).toInt() : capacity;

    final visibleIndices = <int>[];
    for (int i = 0; i < _allowedModules.length && visibleIndices.length < visibleSlots; i++) {
      visibleIndices.add(i);
    }

    if (!visibleIndices.contains(selectedIndex) && visibleIndices.isNotEmpty) {
      visibleIndices[visibleIndices.length - 1] = selectedIndex;
      visibleIndices.sort();
    }

    final hiddenIndices = <int>[
      for (int i = 0; i < _allowedModules.length; i++)
        if (!visibleIndices.contains(i)) i,
    ];

    final compact = width < 600;
    final hiddenBadgeTotal = hiddenIndices.fold<int>(
      0,
      (sum, index) => sum + _moduleBadgeCount(_allowedModules[index]),
    );

    return Container(
      width: double.infinity,
      padding: EdgeInsets.fromLTRB(compact ? 6 : 12, 7, compact ? 6 : 12, 8),
      decoration: BoxDecoration(
        color: Colors.black.withOpacity(.07),
        border: Border(top: BorderSide(color: Colors.white.withOpacity(.10))),
      ),
      child: Row(
        children: [
          ...visibleIndices.map((index) {
            final module = _allowedModules[index];
            return Expanded(
              child: _buildModuleShortcut(
                module,
                index,
                compact: compact,
              ),
            );
          }),
          if (hiddenIndices.isNotEmpty)
            SizedBox(
              width: compact ? 52 : 64,
              child: _buildMoreModulesButton(
                hiddenIndices,
                hiddenBadgeTotal,
                compact: compact,
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildModuleShortcut(
    AdminModule module,
    int index, {
    required bool compact,
  }) {
    final selected = _topTabController!.index == index;
    final count = _moduleBadgeCount(module);

    return Tooltip(
      message: module.title,
      child: HoverClickable(
        onTap: () {
          _topTabController!.animateTo(index);
          setState(() {
            _bottomNavIndex = 0;
            if (_isMenuOpen) _isMenuOpen = false;
          });
        },
        builder: (isHovered) => AnimatedContainer(
          duration: const Duration(milliseconds: 180),
          height: compact ? 46 : 50,
          margin: EdgeInsets.symmetric(horizontal: compact ? 2 : 4),
          padding: EdgeInsets.symmetric(horizontal: compact ? 3 : 7, vertical: 5),
          decoration: BoxDecoration(
            color: selected
                ? Colors.white.withOpacity(.19)
                : (isHovered ? Colors.white.withOpacity(.10) : Colors.transparent),
            borderRadius: BorderRadius.zero,
            border: Border.all(
              color: selected ? _standardGold.withOpacity(.92) : Colors.white.withOpacity(.08),
            ),
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Stack(
                clipBehavior: Clip.none,
                children: [
                  Icon(
                    module.icon,
                    size: compact ? 21 : 23,
                    color: selected ? _standardGold : Colors.white.withOpacity(.90),
                  ),
                  if (count > 0)
                    Positioned(
                      top: -9,
                      right: -13,
                      child: _badgeBubble(count, fontSize: 8),
                    ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  String _shortModuleTitle(String title) {
    const replacements = <String, String>{
      'Manage Announcements': 'Notices',
      'Global Announcements': 'Notices',
      'Manage Events': 'Events',
      'Management Events': 'Events',
      'Manage Marketplace': 'Market',
      'Management Market': 'Market',
      'Management News': 'News',
      'Help Management': 'Support',
      'Need Help? Ask': 'Support',
      'Manage KPI Dashboard': 'KPI',
      'Library Management': 'Library',
      'Manage Operations': 'Operations',
      'Manage Staff Posts': 'Posts',
      'Members of Staff': 'Staff',
      'Manage Examinations': 'Exams',
      'Manage Requests': 'Requests',
      'Human Resource': 'HR',
      'Manage Accounts': 'Accounts',
      'Asset Management': 'Assets',
      'Manage IT Support': 'IT Support',
      'Manage Accommodation': 'Housing',
      'Accommodation': 'Housing',
      'Unanswered Questions': 'Questions',
      'About Rockview': 'About',
    };
    return replacements[title] ?? title.replaceFirst('Manage ', '');
  }

  Widget _buildMoreModulesButton(
    List<int> hiddenIndices,
    int hiddenBadgeTotal, {
    required bool compact,
  }) {
    return Tooltip(
      message: 'More modules',
      child: HoverClickable(
        onTap: () => _showMoreModules(hiddenIndices),
        builder: (isHovered) => AnimatedContainer(
          duration: const Duration(milliseconds: 180),
          height: compact ? 46 : 50,
          margin: const EdgeInsets.symmetric(horizontal: 2),
          decoration: BoxDecoration(
            color: isHovered ? Colors.white.withOpacity(.10) : Colors.white.withOpacity(.05),
            borderRadius: BorderRadius.zero,
            border: Border.all(color: _standardGold.withOpacity(.32)),
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Stack(
                clipBehavior: Clip.none,
                children: [
                  const Icon(Icons.more_horiz_rounded, color: Colors.white, size: 25),
                  if (hiddenBadgeTotal > 0)
                    Positioned(
                      top: -9,
                      right: -14,
                      child: _badgeBubble(hiddenBadgeTotal, fontSize: 8),
                    ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _showMoreModules(List<int> hiddenIndices) async {
    if (hiddenIndices.isEmpty) return;

    await showModalBottomSheet<void>(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      barrierColor: Colors.black.withOpacity(.42),
      builder: (sheetContext) {
        final width = MediaQuery.of(sheetContext).size.width;
        final crossAxisCount = width < 430 ? 3 : (width < 760 ? 4 : 5);
        final height = MediaQuery.of(sheetContext).size.height * (width < 600 ? .68 : .56);

        return SafeArea(
          top: false,
          child: Container(
            height: height,
            decoration: const BoxDecoration(
              color: Color(0xFFF7F9F8),
              borderRadius: BorderRadius.vertical(top: Radius.circular(26)),
            ),
            child: Column(
              children: [
                const SizedBox(height: 10),
                Container(
                  width: 42,
                  height: 4,
                  decoration: BoxDecoration(
                    color: Colors.grey.shade300,
                    borderRadius: BorderRadius.circular(99),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(20, 16, 14, 12),
                  child: Row(
                    children: [
                      Container(
                        width: 42,
                        height: 42,
                        decoration: BoxDecoration(
                          color: _darkGreen.withOpacity(.08),
                          borderRadius: BorderRadius.circular(13),
                        ),
                        child: const Icon(Icons.apps_rounded, color: _darkGreen),
                      ),
                      const SizedBox(width: 12),
                      const Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              'More modules',
                              style: TextStyle(
                                color: Color(0xFF1D2A25),
                                fontSize: 18,
                                fontWeight: FontWeight.w900,
                              ),
                            ),
                            SizedBox(height: 2),
                            Text(
                              'Open any hidden workspace without leaving this screen.',
                              style: TextStyle(color: Color(0xFF738078), fontSize: 11.5),
                            ),
                          ],
                        ),
                      ),
                      IconButton(
                        onPressed: () => Navigator.pop(sheetContext),
                        icon: const Icon(Icons.close_rounded),
                      ),
                    ],
                  ),
                ),
                Divider(height: 1, color: Colors.grey.shade200),
                Expanded(
                  child: GridView.builder(
                    padding: const EdgeInsets.all(16),
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: crossAxisCount,
                      childAspectRatio: width < 430 ? .92 : 1.05,
                      crossAxisSpacing: 10,
                      mainAxisSpacing: 10,
                    ),
                    itemCount: hiddenIndices.length,
                    itemBuilder: (_, position) {
                      final index = hiddenIndices[position];
                      final module = _allowedModules[index];
                      final count = _moduleBadgeCount(module);
                      final selected = _topTabController!.index == index;

                      return Material(
                        color: Colors.transparent,
                        child: InkWell(
                          borderRadius: BorderRadius.zero,
                          onTap: () {
                            Navigator.pop(sheetContext);
                            _topTabController!.animateTo(index);
                            setState(() {
                              _bottomNavIndex = 0;
                              _isMenuOpen = false;
                            });
                          },
                          child: Container(
                            padding: const EdgeInsets.all(10),
                            decoration: BoxDecoration(
                              color: selected ? _darkGreen.withOpacity(.07) : Colors.white,
                              borderRadius: BorderRadius.zero,
                              border: Border.all(
                                color: selected ? _darkGreen.withOpacity(.28) : const Color(0xFFE4E9E6),
                              ),
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.black.withOpacity(.035),
                                  blurRadius: 10,
                                  offset: const Offset(0, 4),
                                ),
                              ],
                            ),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Stack(
                                  clipBehavior: Clip.none,
                                  children: [
                                    Container(
                                      width: 46,
                                      height: 46,
                                      decoration: BoxDecoration(
                                        color: _darkGreen.withOpacity(.08),
                                        borderRadius: BorderRadius.zero,
                                      ),
                                      child: Icon(module.icon, color: _darkGreen, size: 24),
                                    ),
                                    if (count > 0)
                                      Positioned(
                                        top: -7,
                                        right: -9,
                                        child: _badgeBubble(count),
                                      ),
                                  ],
                                ),
                                const SizedBox(height: 9),
                                Text(
                                  module.title,
                                  maxLines: 2,
                                  overflow: TextOverflow.ellipsis,
                                  textAlign: TextAlign.center,
                                  style: const TextStyle(
                                    color: Color(0xFF28342F),
                                    fontSize: 11,
                                    fontWeight: FontWeight.w800,
                                    height: 1.2,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      );
                    },
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildBottomNavBar(bool showText) {
    final items = [
      {'icon': Icons.home_rounded, 'label': 'Home'},
      {'icon': Icons.mail_rounded, 'label': 'Messages'},
      {'icon': Icons.menu_rounded, 'label': 'Menu'},
      {'icon': Icons.auto_awesome_rounded, 'label': 'Assistant'},
    ];

    return Container(
      height: showText ? 72 : 62,
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          top: BorderSide(color: _standardGold, width: 2),
          bottom: BorderSide(color: _darkGreen, width: 3),
        ),
        boxShadow: [
          BoxShadow(
            color: _darkGreen.withOpacity(0.07),
            blurRadius: 18,
            offset: const Offset(0, -5),
          )
        ],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          ...List.generate(items.length, (index) {
            final isSelected = _bottomNavIndex == index;
            
            return Expanded(
              child: HoverClickable(
                onTap: () {
                  if (index == 2) {
                    _toggleTabMenu();
                    return;
                  }
                  setState(() {
                    if (_isMenuOpen) _toggleTabMenu(); 
                    _bottomNavIndex = index;
                  });
                },
                builder: (isHovered) => AnimatedContainer(
                  duration: const Duration(milliseconds: 200),
                  margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
                  decoration: BoxDecoration(
                    color: isSelected
                        ? const Color(0xFFEAF3ED)
                        : (isHovered ? const Color(0xFFF4F8F5) : Colors.transparent),
                    borderRadius: BorderRadius.zero,
                    border: Border.all(
                      color: isSelected ? _darkGreen.withOpacity(.35) : Colors.transparent,
                      width: 1,
                    ),
                  ),
                  child: Stack(
                    clipBehavior: Clip.none,
                    alignment: Alignment.center,
                    children: [
                      Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          AnimatedScale(
                            scale: isSelected ? 1.1 : 1.0,
                            duration: const Duration(milliseconds: 200),
                            child: Icon(
                              items[index]['icon'] as IconData,
                              color: isSelected ? _darkGreen : (isHovered ? _darkGreen : const Color(0xFF8A9991)),
                              size: showText ? 24 : 28, 
                            ),
                          ),
                          
                          if (showText) ...[
                            const SizedBox(height: 4),
                            Text(
                              items[index]['label'] as String,
                              style: TextStyle(
                                color: isSelected ? _darkGreen : (isHovered ? _darkGreen : const Color(0xFF8A9991)),
                                fontWeight: isSelected ? FontWeight.bold : FontWeight.w500,
                                fontSize: 12,
                                letterSpacing: 0.5,
                              ),
                            )
                          ]
                        ],
                      ),

                      // 🚀 BEAUTIFUL ANIMATING WAVE BADGE FOR MESSAGES TAB
                      if (index == 1 && _totalUnreadMessages > 0)
                        Positioned(
                          top: showText ? -6 : -2,
                          right: showText ? null : 14,
                          child: AnimatedBuilder(
                            animation: _waveController,
                            builder: (context, child) {
                              return Stack(
                                alignment: Alignment.center,
                                children: [
                                  // 🌊 First expanding wave
                                  Transform.scale(
                                    scale: 1.0 + (_waveController.value * 0.6),
                                    child: Opacity(
                                      opacity: 1.0 - _waveController.value,
                                      child: Container(
                                        padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),
                                        decoration: const ShapeDecoration(
                                          color: Colors.redAccent,
                                          shape: StadiumBorder(),
                                        ),
                                        // Invisible text matches the exact shape of the badge!
                                        child: Text(
                                          _totalUnreadMessages > 99 ? '99+' : _totalUnreadMessages.toString(),
                                          style: const TextStyle(color: Colors.transparent, fontSize: 10),
                                        ),
                                      ),
                                    ),
                                  ),
                                  // 🌊 Second delayed expanding wave for ripple effect
                                  Transform.scale(
                                    scale: 1.0 + (((_waveController.value + 0.5) % 1.0) * 0.6),
                                    child: Opacity(
                                      opacity: 1.0 - ((_waveController.value + 0.5) % 1.0),
                                      child: Container(
                                        padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),
                                        decoration: const ShapeDecoration(
                                          color: Colors.redAccent,
                                          shape: StadiumBorder(),
                                        ),
                                        child: Text(
                                          _totalUnreadMessages > 99 ? '99+' : _totalUnreadMessages.toString(),
                                          style: const TextStyle(color: Colors.transparent, fontSize: 10),
                                        ),
                                      ),
                                    ),
                                  ),
                                  // ⭐ Solid, unmoving badge in the center
                                  Container(
                                    padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),
                                    decoration: const ShapeDecoration(
                                      color: Colors.redAccent, 
                                      shape: StadiumBorder(),
                                    ),
                                    child: Text(
                                      _totalUnreadMessages > 99 ? '99+' : _totalUnreadMessages.toString(),
                                      style: const TextStyle(color: Colors.white, fontSize: 10, fontWeight: FontWeight.bold),
                                    ),
                                  ),
                                ],
                              );
                            },
                          ),
                        ),
                    ],
                  ),
                ),
              ),
            );
          }),
          _buildCircularCollapseButton(isTop: false, onTap: () => setState(() => _showBottomBar = false)),
          const SizedBox(width: 8) 
        ],
      ),
    );
  }

  Widget _buildAppBarAction(IconData icon, VoidCallback onTap) {
    return HoverClickable(
      onTap: onTap,
      builder: (isHovered) => AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        margin: const EdgeInsets.only(right: 8, top: 8, bottom: 8),
        decoration: BoxDecoration(
          color: isHovered ? Colors.white24 : Colors.transparent, 
          borderRadius: BorderRadius.zero 
        ),
        child: Padding(padding: const EdgeInsets.all(10.0), child: Icon(icon, color: Colors.white, size: 20)),
      ),
    );
  }

  Widget _buildInlineTabMenu() {
    return Container(
      decoration: const BoxDecoration(
        color: Color(0xFFF7F9F8),
        border: Border(top: BorderSide(color: _standardGold, width: 2)),
      ),
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.fromLTRB(22, 18, 14, 12),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    const Icon(Icons.admin_panel_settings_rounded, color: _darkGreen, size: 28),
                    const SizedBox(width: 16),
                    Text('Administration Tools', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Colors.grey.shade900)),
                  ],
                ),
                HoverClickable(
                  onTap: _toggleTabMenu,
                  builder: (isHovered) => AnimatedContainer(
                    duration: const Duration(milliseconds: 200),
                    decoration: BoxDecoration(
                      color: isHovered ? Colors.grey.shade100 : Colors.transparent,
                      borderRadius: BorderRadius.zero 
                    ),
                    child: IconButton(icon: Icon(Icons.close_rounded, color: isHovered ? Colors.redAccent : Colors.grey.shade600), onPressed: _toggleTabMenu),
                  ),
                )
              ],
            ),
          ),
          _buildSearchBar(), // 🚀 Search Bar Added Here too
          Divider(color: Colors.grey.shade300, height: 1, thickness: 1),
          Expanded(
            child: ListView.separated(
              padding: const EdgeInsets.symmetric(vertical: 0),
              itemCount: _filteredModules.length,
              separatorBuilder: (context, index) => const SizedBox(height: 5),
              itemBuilder: (context, index) {
                final module = _filteredModules[index];
                final originalIndex = _allowedModules.indexOf(module);
                final isSelected = _topTabController!.index == originalIndex;

                return HoverClickable(
                  onTap: () {
                    _topTabController!.animateTo(originalIndex);
                    setState(() {}); 
                    _toggleTabMenu(); 
                  },
                  builder: (isHovered) {
                    final showHighlight = isHovered || isSelected;
                    return AnimatedContainer(
                      duration: const Duration(milliseconds: 150),
                      margin: const EdgeInsets.symmetric(horizontal: 12),
                      decoration: BoxDecoration(
                        color: isSelected
                            ? const Color(0xFFEAF3ED)
                            : (isHovered ? const Color(0xFFF1F6F3) : Colors.white),
                        borderRadius: BorderRadius.zero,
                        border: Border.all(
                          color: isSelected ? const Color(0xFFD5E5D9) : const Color(0xFFEDF1EE),
                        ),
                      ),
                      child: ListTile(
                        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 2),
                        leading: _moduleIconWithBadge(
                          module,
                          iconSize: 22,
                          iconColor: isSelected
                              ? _darkGreen
                              : (isHovered ? Colors.grey.shade800 : Colors.grey.shade500),
                        ),
                        title: Text(
                          module.title,
                          style: TextStyle(
                            fontSize: 15, 
                            fontWeight: isSelected ? FontWeight.bold : FontWeight.w600, 
                            color: isSelected ? _darkGreen : (isHovered ? Colors.grey.shade900 : Colors.grey.shade700),
                            letterSpacing: 0.5,
                          )
                        ),
                        trailing: isSelected 
                          ? const Icon(Icons.check_circle_rounded, color: _standardGold, size: 20) 
                          : AnimatedOpacity(
                              opacity: isHovered ? 1.0 : 0.0,
                              duration: const Duration(milliseconds: 150),
                              child: Icon(Icons.arrow_forward_ios_rounded, color: Colors.grey.shade400, size: 14),
                            ),
                      ),
                    );
                  }
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}