import 'dart:async';

import 'package:flutter/material.dart';

const Color _assistantGreen = Color(0xFF026930);
const Color _assistantGold = Color(0xFFCC7504);
const Color _assistantInk = Color(0xFF17251E);
const Color _assistantCanvas = Color(0xFFF4F7F5);

class _ModuleInfo {
  final String name;
  final IconData icon;
  final String summary;
  final List<String> features;
  final String access;

  const _ModuleInfo(this.name, this.icon, this.summary, this.features, this.access);

  /// A consistent, detailed guide tailored to this module's purpose, features,
  /// and access rules. Each module exposes more than 15 practical steps.
  List<String> get guidelines => [
        'Open $name from the application navigation and confirm you are in the correct workspace.',
        'Read the module purpose: $summary',
        'Check that your signed-in account is the one you intend to use.',
        'Use only the actions enabled for your account. $access',
        'Review the current screen and its status labels before taking action.',
        'Use the module search or filters, when available, to find the right record.',
        'Open a record and verify its identity and details before changing it.',
        'For ${features[0]}, follow the on-screen fields and complete required information.',
        'For ${features.length > 1 ? features[1] : features[0]}, check the related record before proceeding.',
        'Enter accurate information and keep names, dates, and identifiers consistent.',
        'Save changes using the module action and wait for the success confirmation.',
        'If the app is offline, treat unsynchronized changes as pending until confirmed.',
        'Use Refresh to check for recent server updates when the screen provides it.',
        'After saving, reopen or review the record to confirm the displayed values.',
        'Before removing or submitting a record, read the confirmation and its consequences.',
        'Do not share passwords, private records, or confidential files through this module.',
        'If information is missing, check your filters, account permissions, and connection status.',
        'For access problems or unexpected errors, record the module, action, and error message.',
        'Ask the appropriate administrator to review permission settings; do not bypass them.',
        'Leave the module only after confirming that important work is saved or clearly pending.',
      ];
}

const List<_ModuleInfo> _moduleCatalog = [
  _ModuleInfo('University Dashboard', Icons.dashboard_rounded, 'A central overview of university activity and the modules available to your account.', ['Review dashboard summaries and recent activity', 'Open the main administrative work areas'], 'Access follows the signed-in account and its assigned permissions.'),
  _ModuleInfo('Library Management', Icons.local_library_rounded, 'Manage the library catalogue, student directory and book circulation.', ['Browse books and library students', 'Issue and return books', 'Review borrowing activity and campus summaries'], 'Library actions require the appropriate library or administrator permissions.'),
  _ModuleInfo('Manage Operations', Icons.badge_rounded, 'Maintain university structures, positions, staff and administrator access.', ['Manage campuses, schools and departments', 'Maintain staff and administrator directories', 'Assign positions and review access levels'], 'Administrative operations are permission controlled.'),
  _ModuleInfo('Request For Leave', Icons.event_busy_rounded, 'Submit, review and track staff leave requests.', ['Create leave requests', 'Review request status and decisions'], 'Employees see their requests; authorized reviewers manage decisions.'),
  _ModuleInfo('Manage Announcements', Icons.campaign_rounded, 'Create and maintain official university announcements.', ['Publish announcements', 'Edit or remove managed notices'], 'Publishing is limited to authorized administrators.'),
  _ModuleInfo('Manage Uni Events', Icons.calendar_month_rounded, 'Manage university events and event information.', ['Create and update events', 'Review event details and schedules'], 'Management actions depend on assigned permissions.'),
  _ModuleInfo('Help Community Mgt', Icons.forum_rounded, 'Moderate and support the university question and answer community.', ['Review community questions', 'Manage answers and moderation'], 'Moderation tools require community management access.'),
  _ModuleInfo('Business Department', Icons.business_center_rounded, 'Review business department and student performance information.', ['Explore academic and enrolment views', 'Review reports and analytics'], 'Some views depend on department permissions.'),
  _ModuleInfo('Manage Marketplace', Icons.storefront_rounded, 'Manage marketplace listings and related activity.', ['Review listings', 'Maintain marketplace records'], 'Management tools require the relevant permission.'),
  _ModuleInfo('Agriculture Department', Icons.agriculture_rounded, 'Access agriculture department work areas and records.', ['Review departmental information', 'Open agriculture tools'], 'Access depends on role and department permissions.'),
  _ModuleInfo('ICT Department', Icons.computer_rounded, 'Access ICT department information and administration tools.', ['Review ICT work areas', 'Manage supported departmental records'], 'Access depends on role and department permissions.'),
  _ModuleInfo('HR Department', Icons.groups_rounded, 'Access human resources department functions and staff information.', ['Review HR records', 'Open HR management tools'], 'Sensitive HR actions are permission controlled.'),
  _ModuleInfo('Employee CVs', Icons.assignment_ind_rounded, 'Review employee CV submissions and professional profiles.', ['Browse employee CV records', 'Open available profile details'], 'CV visibility follows staff and administrator permissions.'),
  _ModuleInfo('My CV', Icons.contact_page_rounded, 'Create and maintain your own professional CV profile.', ['Update personal and professional details', 'Review your submitted profile'], 'Users manage their own CV; restricted fields may be administrator controlled.'),
  _ModuleInfo('Feed Rockview Assistant', Icons.smart_toy_rounded, 'Maintain the knowledge entries used by the feed assistant.', ['Add question and answer knowledge', 'Review and remove knowledge entries'], 'Knowledge-base editing is available to authorized staff.'),
  _ModuleInfo('Help Rockview Assistant', Icons.help_center_rounded, 'Review questions that need help or an administrator response.', ['Find unanswered questions', 'Provide follow-up support'], 'Response and moderation rights depend on assigned access.'),
  _ModuleInfo('Student Performance', Icons.analytics_rounded, 'Review student performance information and academic summaries.', ['Browse performance records', 'Review available academic summaries'], 'Student records are limited to authorized users.'),
  _ModuleInfo('Manage Uni Requests', Icons.pending_actions_rounded, 'Review university requests and follow their progress.', ['Browse submitted requests', 'Update request handling and status'], 'Request actions are permission controlled.'),
  _ModuleInfo('Manage Uni Asset', Icons.inventory_2_rounded, 'Maintain university asset records and administration.', ['Review asset inventory', 'Manage asset records and assignments'], 'Asset changes require the relevant management role.'),
  _ModuleInfo('Education Department', Icons.school_rounded, 'Access education department information and tools.', ['Review departmental records', 'Open education work areas'], 'Access depends on role and department permissions.'),
  _ModuleInfo('Manage IT Support', Icons.support_agent_rounded, 'Manage IT support requests and service activity.', ['Review support tickets', 'Track service status and follow-up'], 'Ticket management requires support permissions.'),
  _ModuleInfo('Uni Announcements', Icons.campaign_rounded, 'Read university announcements relevant to staff and community members.', ['Browse published notices', 'Open announcement details'], 'Displayed information follows the signed-in user’s access.'),
  _ModuleInfo('Management Events', Icons.event_rounded, 'View university events and management schedules.', ['Browse event listings', 'Review event details'], 'Event visibility follows the account’s access.'),
  _ModuleInfo('Members of Staff', Icons.groups_rounded, 'Browse staff information and member profiles.', ['Search or review staff directory details', 'Open available staff information'], 'Private staff fields remain permission controlled.'),
  _ModuleInfo('Management News', Icons.newspaper_rounded, 'Read university news and institutional updates.', ['Browse published news', 'Open full news details'], 'Published news is available according to account access.'),
  _ModuleInfo('Need Help? Ask', Icons.support_agent_rounded, 'Ask questions and follow community support responses.', ['Submit a help question', 'Review responses and follow-up'], 'Users can access their questions; moderation is restricted.'),
  _ModuleInfo('Clubs Management', Icons.diversity_3_rounded, 'Manage or review university clubs and club activity.', ['Browse clubs', 'Review club information and activity'], 'Administrative changes require club management access.'),
  _ModuleInfo('Management Market', Icons.storefront_rounded, 'Browse marketplace content available to staff users.', ['Review marketplace listings', 'Open listing details'], 'Actions are limited by role and permissions.'),
  _ModuleInfo('File Management', Icons.folder_shared_rounded, 'Browse, upload and manage files available to your account.', ['Review accessible files', 'Upload or organize files where permitted', 'Respect file-level access and sharing permissions'], 'Access depends on account permissions and the file’s sharing rules.'),
  _ModuleInfo('Check Assigned Assets', Icons.assignment_turned_in_rounded, 'Review assets assigned to you or your account.', ['Browse assigned asset records', 'Review assignment details'], 'Only assignments available to your account are shown.'),
  _ModuleInfo('Marketing Department', Icons.campaign_rounded, 'Access marketing department work areas and information.', ['Review departmental records', 'Open marketing tools'], 'Access depends on role and department permissions.'),
];

class ModuleAssistantScreen extends StatefulWidget {
  /// Module names are supplied by the home screen so the picker respects the
  /// same module set and permission filtering as the navigation.
  final List<String> modules;
  final bool embedded;

  const ModuleAssistantScreen({super.key, required this.modules, this.embedded = false});

  @override
  State<ModuleAssistantScreen> createState() => _ModuleAssistantScreenState();
}

class _AssistantMessage {
  final String text;
  final bool fromUser;
  final String? module;
  const _AssistantMessage(this.text, this.fromUser, {this.module});
}

class _ModuleAssistantScreenState extends State<ModuleAssistantScreen> {
  final TextEditingController _composer = TextEditingController();
  final ScrollController _scroll = ScrollController();
  final List<_AssistantMessage> _messages = [
    const _AssistantMessage(
      'Hello! Mention a module with @ and I’ll explain its purpose, key features and access rules. Tap @ to choose from the module list.',
      false,
    ),
  ];
  Timer? _typingTimer;
  int? _typingMessageIndex;
  int _typedCharacters = 0;
  bool _showGuide = false;
  String? _mentionQuery;

  List<_ModuleInfo> get _visibleModules {
    final permitted = widget.modules.map((name) => name.toLowerCase()).toSet();
    return _moduleCatalog.where((item) => permitted.contains(item.name.toLowerCase())).toList();
  }

  @override
  void initState() {
    super.initState();
    _composer.addListener(_updateMentionSuggestions);
  }

  @override
  void dispose() {
    _typingTimer?.cancel();
    _composer.removeListener(_updateMentionSuggestions);
    _composer.dispose();
    _scroll.dispose();
    super.dispose();
  }

  void _updateMentionSuggestions() {
    final value = _composer.value;
    final cursor = value.selection.isValid ? value.selection.baseOffset : value.text.length;
    final beforeCursor = value.text.substring(0, cursor.clamp(0, value.text.length).toInt());
    final at = beforeCursor.lastIndexOf('@');
    String? query;
    if (at >= 0 && (at == 0 || beforeCursor[at - 1].trim().isEmpty)) {
      final candidate = beforeCursor.substring(at + 1);
      if (!candidate.contains('\n') && !candidate.contains('@')) query = candidate;
    }
    if (_mentionQuery != query && mounted) setState(() => _mentionQuery = query);
  }

  List<_ModuleInfo> get _suggestions {
    final query = (_mentionQuery ?? '').trim().toLowerCase();
    final modules = _visibleModules;
    if (query.isEmpty) return modules;
    return modules.where((item) => item.name.toLowerCase().contains(query)).toList();
  }

  void _selectModule(_ModuleInfo item) {
    final value = _composer.value;
    final cursor = value.selection.isValid ? value.selection.baseOffset : value.text.length;
    final before = value.text.substring(0, cursor.clamp(0, value.text.length).toInt());
    final at = before.lastIndexOf('@');
    final start = at >= 0 ? at : before.length;
    final after = value.text.substring(cursor.clamp(0, value.text.length).toInt());
    final nextText = '${value.text.substring(0, start)}@${item.name} $after';
    final nextCursor = start + item.name.length + 2;
    _composer.value = TextEditingValue(
      text: nextText,
      selection: TextSelection.collapsed(offset: nextCursor.clamp(0, nextText.length).toInt()),
    );
    setState(() => _mentionQuery = null);
  }

  _ModuleInfo? _mentionedModule(String text) {
    final lower = text.toLowerCase();
    for (final module in _visibleModules) {
      final mention = '@${module.name}'.toLowerCase();
      if (lower.contains(mention)) return module;
    }
    return null;
  }

  String _answerFor(_ModuleInfo module, String question) {
    final cleanQuestion = question
        .replaceAll(RegExp('@${RegExp.escape(module.name)}', caseSensitive: false), '')
        .trim();
    final prompt = cleanQuestion.toLowerCase();
    String answer;
    if (prompt.isEmpty || prompt == '?' || prompt == 'help') {
      answer = '${module.summary}\n\nKey features:\n${module.features.map((feature) => '• $feature').join('\n')}\n\nAccess: ${module.access}';
    }
    else if (prompt.contains('permission') || prompt.contains('access') || prompt.contains('role')) {
      answer = 'For ${module.name}, ${module.access} The visible actions should match your assigned permissions. If an expected action is missing, ask your system administrator to review your account role and permissions.';
    }
    else if (prompt.contains('how') || prompt.contains('use') || prompt.contains('start') || prompt.contains('where')) {
      answer = 'To get started in ${module.name}, follow the detailed steps below.';
    }
    else if (prompt.contains('feature') || prompt.contains('do') || prompt.contains('purpose')) {
      answer = '${module.summary}\n\nYou can use it to:\n${module.features.map((feature) => '• $feature').join('\n')}';
    } else {
      answer = 'Here is what I know about ${module.name}: ${module.summary}\n\nKey features:\n${module.features.map((feature) => '• $feature').join('\n')}\n\n${module.access}';
    }
    final numberedGuidelines = module.guidelines
        .asMap()
        .entries
        .map((entry) => '${entry.key + 1}. ${entry.value}')
        .join('\n');
    return '$answer\n\nInstructions and guidelines for ${module.name}:\n$numberedGuidelines\n\nFor a more specific answer, ask about one of this module’s features or your access.';
  }

  void _send() {
    final text = _composer.text.trim();
    if (text.isEmpty) return;
    final module = _mentionedModule(text);
    final answer = module == null
        ? 'Please mention a module first. Type @ or tap the @ button, then choose a module from the list.'
        : _answerFor(module, text);
    final assistantIndex = _messages.length + 1;
    setState(() {
      _messages.add(_AssistantMessage(text, true, module: module?.name));
      _messages.add(_AssistantMessage(answer, false, module: module?.name));
      _mentionQuery = null;
      _composer.clear();
    });
    _startTypingReply(assistantIndex);
    _scrollToEnd();
  }

  void _startTypingReply(int messageIndex) {
    // Finish an older reply before animating the latest one.
    _typingTimer?.cancel();
    _typingMessageIndex = messageIndex;
    _typedCharacters = 0;
    final message = _messages[messageIndex];
    _typingTimer = Timer.periodic(const Duration(milliseconds: 18), (timer) {
      if (!mounted) {
        timer.cancel();
        return;
      }
      final stickToBottom = !_scroll.hasClients || _scroll.position.extentAfter < 100;
      setState(() {
        _typedCharacters = (_typedCharacters + 3).clamp(0, message.text.length).toInt();
        if (_typedCharacters >= message.text.length) {
          timer.cancel();
          _typingTimer = null;
          _typingMessageIndex = null;
        }
      });
      if (stickToBottom) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (_scroll.hasClients) _scroll.jumpTo(_scroll.position.maxScrollExtent);
        });
      }
    });
  }

  String _visibleMessageText(int index, _AssistantMessage message) {
    if (index != _typingMessageIndex) return message.text;
    return message.text.substring(0, _typedCharacters.clamp(0, message.text.length).toInt());
  }

  void _scrollToEnd() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_scroll.hasClients) _scroll.animateTo(
        _scroll.position.maxScrollExtent,
        duration: const Duration(milliseconds: 220),
        curve: Curves.easeOut,
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    final compact = MediaQuery.sizeOf(context).width < 700;
    final content = _showGuide ? _buildGuide(compact) : _buildChat(compact);
    return Scaffold(
      backgroundColor: _assistantCanvas,
      appBar: widget.embedded ? null : AppBar(
        backgroundColor: _assistantGreen,
        foregroundColor: Colors.white,
        elevation: 0,
        titleSpacing: compact ? 12 : 24,
        title: const Row(
          children: [
            CircleAvatar(backgroundColor: Colors.white, child: Icon(Icons.auto_awesome_rounded, color: _assistantGreen)),
            SizedBox(width: 12),
            Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [
              Text('Module Assistant', style: TextStyle(fontSize: 17, fontWeight: FontWeight.w800)),
              Text('Guidance based on your available modules', style: TextStyle(fontSize: 11, color: Colors.white70)),
            ])),
          ],
        ),
        actions: [
          if (compact)
            IconButton(
              tooltip: _showGuide ? 'Open chat' : 'Open module guide',
              onPressed: () => setState(() => _showGuide = !_showGuide),
              icon: Icon(_showGuide ? Icons.chat_bubble_outline_rounded : Icons.menu_book_rounded, color: Colors.white),
            )
          else
            TextButton.icon(
              onPressed: () => setState(() => _showGuide = !_showGuide),
              icon: Icon(_showGuide ? Icons.chat_bubble_outline_rounded : Icons.menu_book_rounded, color: Colors.white, size: 18),
              label: Text(_showGuide ? 'Chat' : 'Module guide', style: const TextStyle(color: Colors.white)),
            ),
          const SizedBox(width: 8),
        ],
      ),
      body: widget.embedded
          ? Column(children: [_buildEmbeddedHeader(compact), Expanded(child: content)])
          : content,
    );
  }

  Widget _buildEmbeddedHeader(bool compact) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(horizontal: compact ? 14 : 24, vertical: 10),
      decoration: const BoxDecoration(
        color: Colors.white,
        border: Border(bottom: BorderSide(color: Color(0xFFE2E9E4))),
      ),
      child: Row(children: [
        Container(
          width: 40,
          height: 40,
          decoration: BoxDecoration(color: _assistantGreen.withOpacity(.09), borderRadius: BorderRadius.circular(12)),
          child: const Icon(Icons.auto_awesome_rounded, color: _assistantGreen),
        ),
        const SizedBox(width: 12),
        const Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Text('Module Assistant', style: TextStyle(color: _assistantInk, fontWeight: FontWeight.w800, fontSize: 15)),
          Text('Guidance based on your available modules', style: TextStyle(color: Color(0xFF718077), fontSize: 11)),
        ])),
        if (compact)
          IconButton(
            tooltip: _showGuide ? 'Open chat' : 'Open module guide',
            onPressed: () => setState(() => _showGuide = !_showGuide),
            icon: Icon(_showGuide ? Icons.chat_bubble_outline_rounded : Icons.menu_book_rounded, color: _assistantGreen),
          )
        else
          TextButton.icon(
            onPressed: () => setState(() => _showGuide = !_showGuide),
            icon: Icon(_showGuide ? Icons.chat_bubble_outline_rounded : Icons.menu_book_rounded, color: _assistantGreen, size: 18),
            label: Text(_showGuide ? 'Chat' : 'Module guide', style: const TextStyle(color: _assistantGreen)),
          ),
      ]),
    );
  }

  Widget _buildGuide(bool compact) {
    final modules = _visibleModules;
    return Column(children: [
      Container(
        width: double.infinity,
        padding: EdgeInsets.fromLTRB(compact ? 16 : 28, 22, compact ? 16 : 28, 18),
        color: Colors.white,
        child: const Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Text('Your module guide', style: TextStyle(color: _assistantInk, fontSize: 22, fontWeight: FontWeight.w800)),
          SizedBox(height: 5),
          Text('Purpose, key features and access notes for each module available to you.', style: TextStyle(color: Color(0xFF66756D))),
        ]),
      ),
      Expanded(child: modules.isEmpty
          ? const Center(child: Text('No modules are currently available.'))
          : GridView.builder(
              padding: EdgeInsets.all(compact ? 14 : 24),
              gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                maxCrossAxisExtent: compact ? 420 : 520,
                mainAxisExtent: 224,
                crossAxisSpacing: 16,
                mainAxisSpacing: 16,
              ),
              itemCount: modules.length,
              itemBuilder: (context, index) {
                final module = modules[index];
                return Container(
                  padding: const EdgeInsets.all(18),
                  decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(16), border: Border.all(color: const Color(0xFFE2E9E4))),
                  child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                    Row(children: [
                      Container(width: 42, height: 42, decoration: BoxDecoration(color: _assistantGreen.withOpacity(.09), borderRadius: BorderRadius.circular(12)), child: Icon(module.icon, color: _assistantGreen)),
                      const SizedBox(width: 12),
                      Expanded(child: Text(module.name, style: const TextStyle(fontWeight: FontWeight.w800, color: _assistantInk, fontSize: 15))),
                    ]),
                    const SizedBox(height: 12),
                    Text(module.summary, maxLines: 3, overflow: TextOverflow.ellipsis, style: const TextStyle(height: 1.4, color: Color(0xFF53645A), fontSize: 12.5)),
                    const Spacer(),
                    Text(module.features.take(2).map((feature) => '• $feature').join('\n'), maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _assistantGreen, fontSize: 11.5, height: 1.4, fontWeight: FontWeight.w600)),
                    Align(
                      alignment: Alignment.centerRight,
                      child: TextButton.icon(
                        onPressed: () => _showModuleGuidelines(module),
                        icon: const Icon(Icons.menu_book_rounded, size: 16),
                        label: const Text('Read 20-step guide'),
                        style: TextButton.styleFrom(foregroundColor: _assistantGreen, visualDensity: VisualDensity.compact),
                      ),
                    ),
                  ]),
                );
              },
            )),
    ]);
  }

  void _showModuleGuidelines(_ModuleInfo module) {
    showDialog<void>(
      context: context,
      builder: (dialogContext) => AlertDialog(
        title: Row(children: [
          Icon(module.icon, color: _assistantGreen),
          const SizedBox(width: 10),
          Expanded(child: Text(module.name, style: const TextStyle(fontSize: 18))),
        ]),
        content: SizedBox(
          width: 520,
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(module.summary, style: const TextStyle(height: 1.45)),
                const SizedBox(height: 14),
                Text('Instructions and guidelines (${module.guidelines.length})', style: const TextStyle(fontWeight: FontWeight.w800, color: _assistantGreen)),
                const SizedBox(height: 8),
                ...module.guidelines.asMap().entries.map((entry) => Padding(
                      padding: const EdgeInsets.only(bottom: 10),
                      child: Text('${entry.key + 1}. ${entry.value}', style: const TextStyle(height: 1.4)),
                    )),
                const SizedBox(height: 6),
                Text('Access: ${module.access}', style: const TextStyle(fontWeight: FontWeight.w600)),
              ],
            ),
          ),
        ),
        actions: [TextButton(onPressed: () => Navigator.of(dialogContext).pop(), child: const Text('CLOSE'))],
      ),
    );
  }

  Widget _buildChat(bool compact) {
    return Column(children: [
      Expanded(child: ListView.builder(
        controller: _scroll,
        padding: EdgeInsets.symmetric(horizontal: compact ? 14 : 28, vertical: 22),
        itemCount: _messages.length,
        itemBuilder: (context, index) {
          final message = _messages[index];
          return Align(
            alignment: message.fromUser ? Alignment.centerRight : Alignment.centerLeft,
            child: Container(
              constraints: BoxConstraints(maxWidth: compact ? 340 : 620),
              margin: const EdgeInsets.only(bottom: 14),
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 13),
              decoration: BoxDecoration(
                color: message.fromUser ? _assistantGreen : Colors.white,
                borderRadius: BorderRadius.circular(16).copyWith(bottomRight: message.fromUser ? const Radius.circular(4) : null, bottomLeft: message.fromUser ? null : const Radius.circular(4)),
                border: message.fromUser ? null : Border.all(color: const Color(0xFFE3EAE5)),
                boxShadow: [BoxShadow(color: Colors.black.withOpacity(.025), blurRadius: 8, offset: const Offset(0, 2))],
              ),
              child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                if (message.module != null && !message.fromUser) ...[
                  Row(mainAxisSize: MainAxisSize.min, children: [const Icon(Icons.tag_rounded, color: _assistantGold, size: 15), Text(message.module!, style: const TextStyle(color: _assistantGold, fontWeight: FontWeight.w800, fontSize: 11))]),
                  const SizedBox(height: 6),
                ],
                SelectableText(_visibleMessageText(index, message), style: TextStyle(color: message.fromUser ? Colors.white : _assistantInk, height: 1.45, fontSize: 13.5)),
              ]),
            ),
          );
        },
      )),
      Container(
        color: Colors.white,
        padding: EdgeInsets.fromLTRB(compact ? 12 : 24, 10, compact ? 12 : 24, 12 + MediaQuery.paddingOf(context).bottom),
        child: Column(mainAxisSize: MainAxisSize.min, children: [
          if (_mentionQuery != null) _buildSuggestions(compact),
          Row(crossAxisAlignment: CrossAxisAlignment.end, children: [
            IconButton.filledTonal(
              tooltip: 'Mention a module',
              onPressed: () {
                final value = _composer.value;
                final pos = value.selection.isValid ? value.selection.baseOffset : value.text.length;
                final updated = '${value.text.substring(0, pos)}@${value.text.substring(pos)}';
                _composer.value = TextEditingValue(text: updated, selection: TextSelection.collapsed(offset: pos + 1));
                _composer.selection = TextSelection.collapsed(offset: pos + 1);
                // Updating the controller notifies its listener and opens the picker.
              },
              icon: const Icon(Icons.alternate_email_rounded, color: _assistantGreen),
            ),
            Expanded(child: TextField(
              controller: _composer,
              minLines: 1,
              maxLines: 4,
              textInputAction: TextInputAction.send,
              onSubmitted: (_) => _send(),
              decoration: InputDecoration(
                hintText: 'Ask about a module. Type @ to choose…',
                filled: true,
                fillColor: _assistantCanvas,
                contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                border: OutlineInputBorder(borderRadius: BorderRadius.circular(18), borderSide: BorderSide.none),
              ),
            )),
            const SizedBox(width: 8),
            IconButton.filled(
              tooltip: 'Send message',
              onPressed: _send,
              style: IconButton.styleFrom(backgroundColor: _assistantGreen, foregroundColor: Colors.white),
              icon: const Icon(Icons.send_rounded),
            ),
          ]),
          const SizedBox(height: 5),
          const Text('Choose a module with @ to get focused guidance.', style: TextStyle(color: Color(0xFF718077), fontSize: 10.5)),
        ]),
      ),
    ]);
  }

  Widget _buildSuggestions(bool compact) {
    final matches = _suggestions;
    return Container(
      constraints: const BoxConstraints(maxHeight: 220),
      margin: const EdgeInsets.only(bottom: 10),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(14), border: Border.all(color: const Color(0xFFDCE6DF)), boxShadow: [BoxShadow(color: Colors.black.withOpacity(.08), blurRadius: 15, offset: const Offset(0, 5))]),
      child: matches.isEmpty
          ? const Padding(padding: EdgeInsets.all(16), child: Text('No matching module. Keep typing or check your spelling.', style: TextStyle(color: Color(0xFF66756D), fontSize: 12)))
          : ListView.separated(
              shrinkWrap: true,
              itemCount: matches.length,
              separatorBuilder: (_, __) => const Divider(height: 1, indent: 12, endIndent: 12),
              itemBuilder: (context, index) {
                final module = matches[index];
                return ListTile(
                  dense: true,
                  leading: CircleAvatar(radius: 17, backgroundColor: _assistantGreen.withOpacity(.08), child: Icon(module.icon, color: _assistantGreen, size: 17)),
                  title: Text(module.name, style: const TextStyle(fontWeight: FontWeight.w700, fontSize: 13)),
                  subtitle: Text(module.summary, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 11)),
                  onTap: () => _selectModule(module),
                );
              },
            ),
    );
  }
}
