import 'dart:async';
import 'dart:typed_data';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';

import '../../../../core/services/campus_support_service.dart';

const Color _supportGreen = Color.fromARGB(255, 2, 105, 48);
const Color _supportGold = Color.fromARGB(255, 204, 117, 4);
const Color _supportBg = Color(0xFFF3F6F5);
const Color _supportBorder = Color(0xFFE1E7E4);
const Color _supportInk = Color(0xFF1B2B24);
const Color _supportMuted = Color(0xFF68756F);

// -----------------------------------------------------------------------------
// FILE PICKER COMPATIBILITY
// -----------------------------------------------------------------------------
// file_picker v13 returns a list directly; pickFiles supports multiple selection.
Future<List<PlatformFile>> _pickSupportDocuments({required int limit}) async {
  if (limit <= 0) return const <PlatformFile>[];

  final files = await FilePicker.pickFiles(
    allowedExtensions: const <String>['pdf', 'txt', 'doc', 'docx', 'xls', 'xlsx'],
    type: FileType.custom,
  );

  return files.take(limit).toList();
}

Future<int?> _supportDocumentSize(PlatformFile file) async {
  final dynamic dynamicFile = file;

  // Prefer the real selected path. XFile.length() keeps this view independent
  // from dart:io and works for the Windows/mobile targets used by this project.
  try {
    final dynamic rawPath = dynamicFile.path;
    final String path = rawPath?.toString().trim() ?? '';
    if (path.isNotEmpty) {
      return await XFile(path).length();
    }
  } catch (_) {}

  // Compatibility fallback for file_picker releases that keep bytes in memory.
  // Dynamic access prevents an undefined_getter compile error on older versions.
  try {
    final dynamic rawBytes = dynamicFile.bytes;
    if (rawBytes is Uint8List) return rawBytes.length;
    if (rawBytes is List<int>) return rawBytes.length;
  } catch (_) {}

  return null;
}

Future<String?> _validateSupportDocuments(List<PlatformFile> files) async {
  const int maxBytes = 10 * 1024 * 1024;

  for (final file in files) {
    final int? size = await _supportDocumentSize(file);
    if (size == null) {
      return 'Unable to read ${file.name}. Please select the file again.';
    }
    if (size > maxBytes) {
      return '${file.name} is larger than 10 MB.';
    }
  }

  return null;
}

class SupportConversationList extends StatefulWidget {
  final String scope;
  final bool allowCreate;
  final bool adminMode;
  final String currentUserName;

  const SupportConversationList({
    super.key,
    required this.scope,
    required this.allowCreate,
    required this.adminMode,
    required this.currentUserName,
  });

  @override
  State<SupportConversationList> createState() => _SupportConversationListState();
}

class _SupportConversationListState extends State<SupportConversationList> {
  final TextEditingController _searchController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  final List<SupportThread> _threads = <SupportThread>[];

  Timer? _timer;
  bool _loading = true;
  bool _refreshing = false;
  String? _error;
  int _total = 0;
  int _unread = 0;
  String _adminStatus = 'all';

  @override
  void initState() {
    super.initState();
    _load();
    _timer = Timer.periodic(const Duration(seconds: 15), (_) => _silentRefresh());
  }

  @override
  void dispose() {
    _timer?.cancel();
    _searchController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  Future<void> _load() async {
    if (!mounted) return;
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final page = await CampusSupportService.getThreads(
        scope: widget.adminMode ? 'all' : widget.scope,
        status: widget.adminMode ? _adminStatus : null,
        search: _searchController.text,
        limit: 100,
      );
      if (!mounted) return;
      setState(() {
        _threads
          ..clear()
          ..addAll(page.threads);
        _total = page.total;
        _unread = page.unreadTotal;
        _loading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _loading = false;
        _error = _cleanError(e);
      });
    }
  }

  Future<void> _refresh() async {
    if (_refreshing) return;
    setState(() => _refreshing = true);
    try {
      final page = await CampusSupportService.getThreads(
        scope: widget.adminMode ? 'all' : widget.scope,
        status: widget.adminMode ? _adminStatus : null,
        search: _searchController.text,
        limit: 100,
      );
      if (!mounted) return;
      setState(() {
        _threads
          ..clear()
          ..addAll(page.threads);
        _total = page.total;
        _unread = page.unreadTotal;
        _error = null;
      });
    } catch (e) {
      if (mounted) setState(() => _error = _cleanError(e));
    } finally {
      if (mounted) setState(() => _refreshing = false);
    }
  }

  Future<void> _silentRefresh() async {
    if (!mounted || _loading || _refreshing) return;
    try {
      final page = await CampusSupportService.getThreads(
        scope: widget.adminMode ? 'all' : widget.scope,
        status: widget.adminMode ? _adminStatus : null,
        search: _searchController.text,
        limit: 100,
      );
      if (!mounted) return;
      setState(() {
        _threads
          ..clear()
          ..addAll(page.threads);
        _total = page.total;
        _unread = page.unreadTotal;
      });
    } catch (_) {}
  }

  Future<void> _newQuestion() async {
    final created = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (_) => NewSupportQuestionDialog(
        currentUserName: widget.currentUserName,
      ),
    );
    if (created == true) await _refresh();
  }

  Future<void> _openThread(SupportThread thread) async {
    await showDialog<bool>(
      context: context,
      barrierDismissible: true,
      builder: (_) => SupportConversationDialog(
        threadId: thread.id,
        adminMode: widget.adminMode,
      ),
    );
    if (mounted) await _refresh();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: _supportBg,
      child: LayoutBuilder(
        builder: (context, constraints) {
          final compact = constraints.maxWidth < 720;
          return Column(
            children: [
              _buildHeader(compact),
              Expanded(
                child: RefreshIndicator(
                  color: _supportGreen,
                  onRefresh: _refresh,
                  child: ListView(
                    controller: _scrollController,
                    physics: const AlwaysScrollableScrollPhysics(),
                    padding: EdgeInsets.fromLTRB(
                      compact ? 10 : 24,
                      16,
                      compact ? 10 : 24,
                      80,
                    ),
                    children: [
                      if (_loading)
                        const Padding(
                          padding: EdgeInsets.symmetric(vertical: 130),
                          child: Center(
                            child: CircularProgressIndicator(color: _supportGreen),
                          ),
                        )
                      else if (_error != null)
                        _errorCard()
                      else if (_threads.isEmpty)
                        _emptyCard()
                      else
                        ..._threads.map(
                          (thread) => Padding(
                            padding: const EdgeInsets.only(bottom: 12),
                            child: _SupportThreadCard(
                              thread: thread,
                              adminMode: widget.adminMode,
                              onTap: () => _openThread(thread),
                            ),
                          ),
                        ),
                    ],
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  Widget _buildHeader(bool compact) {
    final title = widget.adminMode
        ? 'Staff Support Inbox'
        : widget.scope == 'resolved'
            ? 'Resolved Conversations'
            : 'Support Conversations';
    final subtitle = widget.adminMode
        ? 'Review staff questions, reply in real time and close resolved conversations.'
        : widget.scope == 'resolved'
            ? 'Review completed conversations or reopen an issue when more help is required.'
            : 'Ask administration a question and continue the discussion like a real conversation.';

    return Container(
      width: double.infinity,
      padding: EdgeInsets.fromLTRB(
        compact ? 14 : 28,
        compact ? 16 : 22,
        compact ? 14 : 28,
        compact ? 14 : 20,
      ),
      decoration: const BoxDecoration(
        color: Colors.white,
        border: Border(bottom: BorderSide(color: _supportBorder)),
      ),
      child: Center(
        child: ConstrainedBox(
          constraints: const BoxConstraints(maxWidth: 1180),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              if (compact)
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _headerTitle(title, subtitle),
                    if (widget.allowCreate) ...[
                      const SizedBox(height: 12),
                      SizedBox(
                        width: double.infinity,
                        child: _askButton(),
                      ),
                    ],
                  ],
                )
              else
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Expanded(child: _headerTitle(title, subtitle)),
                    const SizedBox(width: 20),
                    if (widget.allowCreate) _askButton(),
                  ],
                ),
              const SizedBox(height: 16),
              if (compact)
                Column(
                  children: [
                    _searchBox(),
                    if (widget.adminMode) ...[
                      const SizedBox(height: 10),
                      _statusFilter(),
                    ],
                    const SizedBox(height: 10),
                    Row(
                      children: [
                        Expanded(child: _metric(Icons.forum_rounded, '$_total', 'Conversations')),
                        const SizedBox(width: 8),
                        Expanded(child: _metric(Icons.mark_chat_unread_rounded, '$_unread', 'Unread')),
                      ],
                    ),
                  ],
                )
              else
                Row(
                  children: [
                    Expanded(child: _searchBox()),
                    if (widget.adminMode) ...[
                      const SizedBox(width: 10),
                      SizedBox(width: 190, child: _statusFilter()),
                    ],
                    const SizedBox(width: 12),
                    _metric(Icons.forum_rounded, '$_total', 'Conversations'),
                    const SizedBox(width: 8),
                    _metric(Icons.mark_chat_unread_rounded, '$_unread', 'Unread'),
                  ],
                ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _headerTitle(String title, String subtitle) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Container(
              width: 42,
              height: 42,
              decoration: BoxDecoration(
                color: _supportGreen.withOpacity(.08),
                borderRadius: BorderRadius.circular(13),
              ),
              child: const Icon(Icons.support_agent_rounded, color: _supportGreen),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Text(
                title,
                style: const TextStyle(
                  fontSize: 22,
                  fontWeight: FontWeight.w900,
                  color: _supportInk,
                ),
              ),
            ),
          ],
        ),
        const SizedBox(height: 7),
        Text(
          subtitle,
          style: const TextStyle(
            color: _supportMuted,
            fontSize: 12.5,
            height: 1.45,
          ),
        ),
      ],
    );
  }

  Widget _askButton() {
    return FilledButton.icon(
      onPressed: _newQuestion,
      style: FilledButton.styleFrom(
        backgroundColor: _supportGreen,
        foregroundColor: Colors.white,
        padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 15),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(13)),
      ),
      icon: const Icon(Icons.add_comment_rounded, size: 19),
      label: const Text(
        'Ask Administration',
        style: TextStyle(fontWeight: FontWeight.w800),
      ),
    );
  }

  Widget _searchBox() {
    return TextField(
      controller: _searchController,
      onSubmitted: (_) => _load(),
      decoration: InputDecoration(
        hintText: widget.adminMode
            ? 'Search subject, staff member, campus or message...'
            : 'Search your conversations...',
        prefixIcon: const Icon(Icons.search_rounded, color: _supportGreen),
        suffixIcon: IconButton(
          tooltip: 'Search',
          onPressed: _load,
          icon: const Icon(Icons.arrow_forward_rounded, color: _supportGreen),
        ),
        filled: true,
        fillColor: const Color(0xFFF8FAF9),
        contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 13),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(13),
          borderSide: const BorderSide(color: _supportBorder),
        ),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(13),
          borderSide: const BorderSide(color: _supportBorder),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(13),
          borderSide: const BorderSide(color: _supportGreen, width: 1.3),
        ),
      ),
    );
  }

  Widget _statusFilter() {
    return DropdownButtonFormField<String>(
      value: _adminStatus,
      isExpanded: true,
      decoration: InputDecoration(
        filled: true,
        fillColor: const Color(0xFFF8FAF9),
        contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(13),
          borderSide: const BorderSide(color: _supportBorder),
        ),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(13),
          borderSide: const BorderSide(color: _supportBorder),
        ),
      ),
      items: const [
        DropdownMenuItem(value: 'all', child: Text('All statuses')),
        DropdownMenuItem(value: 'waiting_admin', child: Text('Needs admin reply')),
        DropdownMenuItem(value: 'waiting_staff', child: Text('Waiting for staff')),
        DropdownMenuItem(value: 'resolved', child: Text('Resolved')),
      ],
      onChanged: (value) {
        if (value == null) return;
        setState(() => _adminStatus = value);
        _load();
      },
    );
  }

  Widget _metric(IconData icon, String value, String label) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 13, vertical: 9),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: _supportBorder),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 17, color: _supportGreen),
          const SizedBox(width: 7),
          Text(value, style: const TextStyle(fontWeight: FontWeight.w900, color: _supportInk)),
          const SizedBox(width: 5),
          Text(label, style: const TextStyle(fontSize: 10.5, color: _supportMuted)),
        ],
      ),
    );
  }

  Widget _errorCard() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 58),
      decoration: _panelDecoration(),
      child: Column(
        children: [
          Icon(Icons.cloud_off_rounded, size: 52, color: Colors.red.shade300),
          const SizedBox(height: 12),
          const Text(
            'Support conversations could not be loaded',
            style: TextStyle(fontWeight: FontWeight.w900, fontSize: 17),
          ),
          const SizedBox(height: 8),
          Text(
            _error!,
            textAlign: TextAlign.center,
            style: const TextStyle(color: _supportMuted),
          ),
          const SizedBox(height: 14),
          FilledButton.icon(
            onPressed: _load,
            style: FilledButton.styleFrom(backgroundColor: _supportGreen),
            icon: const Icon(Icons.refresh_rounded),
            label: const Text('Try again'),
          ),
        ],
      ),
    );
  }

  Widget _emptyCard() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 22, vertical: 76),
      decoration: _panelDecoration(),
      child: Column(
        children: [
          Icon(Icons.chat_bubble_outline_rounded, size: 62, color: Colors.grey.shade300),
          const SizedBox(height: 14),
          Text(
            widget.scope == 'resolved' ? 'No resolved conversations' : 'No support conversations yet',
            style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w900, color: _supportInk),
          ),
          const SizedBox(height: 7),
          Text(
            widget.allowCreate
                ? 'Ask administration a question and the conversation will appear here.'
                : 'There is nothing to display in this section yet.',
            textAlign: TextAlign.center,
            style: const TextStyle(color: _supportMuted),
          ),
          if (widget.allowCreate) ...[
            const SizedBox(height: 16),
            _askButton(),
          ],
        ],
      ),
    );
  }
}

class _SupportThreadCard extends StatelessWidget {
  final SupportThread thread;
  final bool adminMode;
  final VoidCallback onTap;

  const _SupportThreadCard({
    required this.thread,
    required this.adminMode,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.white,
      borderRadius: BorderRadius.circular(18),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(18),
        child: Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(18),
            border: Border.all(
              color: thread.unreadCount > 0
                  ? _supportGreen.withOpacity(.30)
                  : _supportBorder,
              width: thread.unreadCount > 0 ? 1.3 : 1,
            ),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(.025),
                blurRadius: 12,
                offset: const Offset(0, 4),
              ),
            ],
          ),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Stack(
                clipBehavior: Clip.none,
                children: [
                  _SupportAvatar(
                    image: thread.authorProfilePicture,
                    name: thread.authorName,
                    size: 46,
                  ),
                  if (thread.unreadCount > 0)
                    Positioned(
                      right: -3,
                      top: -4,
                      child: Container(
                        constraints: const BoxConstraints(minWidth: 20, minHeight: 20),
                        padding: const EdgeInsets.symmetric(horizontal: 5),
                        alignment: Alignment.center,
                        decoration: const BoxDecoration(
                          color: _supportGold,
                          shape: BoxShape.circle,
                        ),
                        child: Text(
                          thread.unreadCount > 99 ? '99+' : '${thread.unreadCount}',
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 9,
                            fontWeight: FontWeight.w900,
                          ),
                        ),
                      ),
                    ),
                ],
              ),
              const SizedBox(width: 13),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Expanded(
                          child: Text(
                            thread.title,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                              fontSize: 15.5,
                              fontWeight: thread.unreadCount > 0 ? FontWeight.w900 : FontWeight.w800,
                              color: _supportInk,
                            ),
                          ),
                        ),
                        const SizedBox(width: 8),
                        _StatusBadge(thread: thread),
                      ],
                    ),
                    const SizedBox(height: 5),
                    Wrap(
                      spacing: 8,
                      runSpacing: 5,
                      children: [
                        if (adminMode)
                          _smallMeta(Icons.person_outline_rounded, thread.authorName),
                        if (thread.campus.trim().isNotEmpty)
                          _smallMeta(Icons.apartment_rounded, thread.campus),
                        _smallMeta(Icons.sell_outlined, thread.category),
                        _PriorityBadge(priority: thread.priority),
                      ],
                    ),
                    const SizedBox(height: 10),
                    Text(
                      thread.lastMessage.trim().isEmpty
                          ? 'Attachment sent'
                          : thread.lastMessage,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        color: thread.unreadCount > 0 ? const Color(0xFF46544E) : _supportMuted,
                        fontSize: 12.3,
                        height: 1.4,
                        fontWeight: thread.unreadCount > 0 ? FontWeight.w600 : FontWeight.w400,
                      ),
                    ),
                    const SizedBox(height: 10),
                    Row(
                      children: [
                        Icon(Icons.schedule_rounded, size: 14, color: Colors.grey.shade500),
                        const SizedBox(width: 5),
                        Text(
                          _timeAgo(thread.lastMessageAt ?? thread.updatedAt),
                          style: const TextStyle(fontSize: 10.5, color: _supportMuted),
                        ),
                        const SizedBox(width: 12),
                        Icon(Icons.chat_bubble_outline_rounded, size: 14, color: Colors.grey.shade500),
                        const SizedBox(width: 4),
                        Text('${thread.messageCount}', style: const TextStyle(fontSize: 10.5, color: _supportMuted)),
                        if (thread.attachmentCount > 0) ...[
                          const SizedBox(width: 12),
                          Icon(Icons.attach_file_rounded, size: 14, color: Colors.grey.shade500),
                          Text('${thread.attachmentCount}', style: const TextStyle(fontSize: 10.5, color: _supportMuted)),
                        ],
                        const Spacer(),
                        const Icon(Icons.chevron_right_rounded, color: _supportGreen),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _smallMeta(IconData icon, String value) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(icon, size: 13, color: _supportMuted),
        const SizedBox(width: 3),
        Text(
          value,
          style: const TextStyle(fontSize: 10.5, color: _supportMuted, fontWeight: FontWeight.w600),
        ),
      ],
    );
  }
}

class NewSupportQuestionDialog extends StatefulWidget {
  final String currentUserName;

  const NewSupportQuestionDialog({
    super.key,
    required this.currentUserName,
  });

  @override
  State<NewSupportQuestionDialog> createState() => _NewSupportQuestionDialogState();
}

class _NewSupportQuestionDialogState extends State<NewSupportQuestionDialog> {
  final _formKey = GlobalKey<FormState>();
  final ImagePicker _picker = ImagePicker();
  final TextEditingController _title = TextEditingController();
  final TextEditingController _body = TextEditingController();
  final List<_PickedImage> _images = <_PickedImage>[];
  final List<PlatformFile> _documents = <PlatformFile>[];

  String _category = CampusSupportService.categories.first;
  String _priority = CampusSupportService.priorities.first;
  bool _saving = false;

  @override
  void dispose() {
    _title.dispose();
    _body.dispose();
    super.dispose();
  }

  Future<void> _pickImages() async {
    final remaining = 5 - _images.length - _documents.length;
    if (remaining <= 0) {
      _snack('A message can contain at most 5 attachments.', error: true);
      return;
    }
    final picked = await _picker.pickMultiImage(
      imageQuality: 82,
      maxWidth: 1800,
      maxHeight: 1800,
    );
    if (picked.isEmpty) return;
    final selected = picked.take(remaining).toList();
    final bytes = await Future.wait<Uint8List>(selected.map((e) => e.readAsBytes()));
    if (!mounted) return;
    setState(() {
      for (var i = 0; i < selected.length; i++) {
        _images.add(_PickedImage(file: selected[i], bytes: bytes[i]));
      }
    });
  }

  Future<void> _pickDocuments() async {
    final remaining = 5 - _images.length - _documents.length;
    if (remaining <= 0) {
      _snack('A message can contain at most 5 attachments.', error: true);
      return;
    }

    try {
      final files = await _pickSupportDocuments(limit: remaining);
      if (files.isEmpty) return;

      final validationError = await _validateSupportDocuments(files);
      if (validationError != null) {
        _snack(validationError, error: true);
        return;
      }

      if (!mounted) return;
      setState(() => _documents.addAll(files));
    } catch (e) {
      _snack('Unable to select documents: ${_cleanError(e)}', error: true);
    }
  }

  Future<void> _submit() async {
    if (_saving || !(_formKey.currentState?.validate() ?? false)) return;
    setState(() => _saving = true);
    try {
      final result = await CampusSupportService.createThread(
        title: _title.text,
        category: _category,
        priority: _priority,
        body: _body.text,
      );
      if (_images.isNotEmpty || _documents.isNotEmpty) {
        await CampusSupportService.uploadAttachments(
          messageId: result.messageId,
          images: _images.map((e) => e.file).toList(),
          documents: _documents,
        );
      }
      if (!mounted) return;
      Navigator.pop(context, true);
    } catch (e) {
      _snack(_cleanError(e), error: true);
    } finally {
      if (mounted) setState(() => _saving = false);
    }
  }

  void _snack(String message, {bool error = false}) {
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: error ? Colors.red.shade700 : _supportGreen,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final compact = MediaQuery.of(context).size.width < 680;
    return Dialog(
      insetPadding: EdgeInsets.symmetric(
        horizontal: compact ? 10 : 28,
        vertical: compact ? 14 : 24,
      ),
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(22)),
      child: ConstrainedBox(
        constraints: const BoxConstraints(maxWidth: 760, maxHeight: 760),
        child: Column(
          children: [
            _dialogHeader(
              icon: Icons.add_comment_rounded,
              title: 'Ask Administration',
              subtitle: 'Start a private support conversation with Rockview administration.',
              onClose: _saving ? null : () => Navigator.pop(context),
            ),
            Expanded(
              child: SingleChildScrollView(
                padding: EdgeInsets.all(compact ? 16 : 24),
                child: Form(
                  key: _formKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        padding: const EdgeInsets.all(14),
                        decoration: BoxDecoration(
                          color: _supportGreen.withOpacity(.05),
                          borderRadius: BorderRadius.circular(14),
                          border: Border.all(color: _supportGreen.withOpacity(.13)),
                        ),
                        child: Row(
                          children: [
                            _SupportAvatar(image: '', name: widget.currentUserName, size: 42),
                            const SizedBox(width: 11),
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(widget.currentUserName, style: const TextStyle(fontWeight: FontWeight.w900)),
                                  const SizedBox(height: 2),
                                  const Text(
                                    'Your authenticated account and campus are attached automatically.',
                                    style: TextStyle(fontSize: 10.8, color: _supportMuted),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 18),
                      TextFormField(
                        controller: _title,
                        maxLength: 180,
                        validator: (value) => value == null || value.trim().isEmpty
                            ? 'Enter a clear subject.'
                            : null,
                        decoration: _fieldDecoration(
                          'Subject',
                          'E.g. September payroll clarification',
                          Icons.subject_rounded,
                        ),
                      ),
                      const SizedBox(height: 12),
                      if (compact)
                        Column(
                          children: [
                            _categoryField(),
                            const SizedBox(height: 12),
                            _priorityField(),
                          ],
                        )
                      else
                        Row(
                          children: [
                            Expanded(child: _categoryField()),
                            const SizedBox(width: 12),
                            Expanded(child: _priorityField()),
                          ],
                        ),
                      const SizedBox(height: 14),
                      TextFormField(
                        controller: _body,
                        minLines: 5,
                        maxLines: 9,
                        maxLength: 8000,
                        validator: (value) => value == null || value.trim().isEmpty
                            ? 'Explain what you need help with.'
                            : null,
                        decoration: _fieldDecoration(
                          'Message',
                          'Describe the issue clearly. You can continue replying after administration responds.',
                          Icons.notes_rounded,
                        ),
                      ),
                      const SizedBox(height: 10),
                      _AttachmentPickerBar(
                        onImages: _pickImages,
                        onDocuments: _pickDocuments,
                        count: _images.length + _documents.length,
                      ),
                      if (_images.isNotEmpty || _documents.isNotEmpty) ...[
                        const SizedBox(height: 12),
                        _SelectedAttachments(
                          images: _images,
                          documents: _documents,
                          onRemoveImage: (index) => setState(() => _images.removeAt(index)),
                          onRemoveDocument: (index) => setState(() => _documents.removeAt(index)),
                        ),
                      ],
                    ],
                  ),
                ),
              ),
            ),
            Container(
              padding: const EdgeInsets.fromLTRB(18, 13, 18, 18),
              decoration: const BoxDecoration(
                border: Border(top: BorderSide(color: _supportBorder)),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  TextButton(
                    onPressed: _saving ? null : () => Navigator.pop(context),
                    child: const Text('Cancel'),
                  ),
                  const SizedBox(width: 10),
                  FilledButton.icon(
                    onPressed: _saving ? null : _submit,
                    style: FilledButton.styleFrom(
                      backgroundColor: _supportGreen,
                      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14),
                    ),
                    icon: _saving
                        ? const SizedBox(
                            width: 17,
                            height: 17,
                            child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white),
                          )
                        : const Icon(Icons.send_rounded, size: 18),
                    label: Text(_saving ? 'Sending...' : 'Start Conversation'),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _categoryField() {
    return DropdownButtonFormField<String>(
      value: _category,
      isExpanded: true,
      decoration: _fieldDecoration('Category', null, Icons.category_outlined),
      items: CampusSupportService.categories
          .map((value) => DropdownMenuItem(value: value, child: Text(value)))
          .toList(),
      onChanged: (value) {
        if (value != null) setState(() => _category = value);
      },
    );
  }

  Widget _priorityField() {
    return DropdownButtonFormField<String>(
      value: _priority,
      isExpanded: true,
      decoration: _fieldDecoration('Priority', null, Icons.flag_outlined),
      items: CampusSupportService.priorities
          .map((value) => DropdownMenuItem(value: value, child: Text(value)))
          .toList(),
      onChanged: (value) {
        if (value != null) setState(() => _priority = value);
      },
    );
  }
}

class SupportConversationDialog extends StatefulWidget {
  final int threadId;
  final bool adminMode;

  const SupportConversationDialog({
    super.key,
    required this.threadId,
    required this.adminMode,
  });

  @override
  State<SupportConversationDialog> createState() => _SupportConversationDialogState();
}

class _SupportConversationDialogState extends State<SupportConversationDialog> {
  final TextEditingController _composer = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  final ImagePicker _picker = ImagePicker();
  final List<_PickedImage> _images = <_PickedImage>[];
  final List<PlatformFile> _documents = <PlatformFile>[];

  SupportThread? _thread;
  List<SupportMessage> _messages = <SupportMessage>[];
  Timer? _timer;
  bool _loading = true;
  bool _sending = false;
  bool _statusBusy = false;
  String? _error;

  @override
  void initState() {
    super.initState();
    _load(initial: true);
    _timer = Timer.periodic(const Duration(seconds: 7), (_) => _silentLoad());
  }

  @override
  void dispose() {
    _timer?.cancel();
    _composer.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  Future<void> _load({bool initial = false}) async {
    if (initial && mounted) {
      setState(() {
        _loading = true;
        _error = null;
      });
    }
    try {
      final results = await Future.wait<dynamic>([
        CampusSupportService.getThread(widget.threadId),
        CampusSupportService.getMessages(widget.threadId),
      ]);
      if (!mounted) return;
      setState(() {
        _thread = results[0] as SupportThread;
        _messages = List<SupportMessage>.from(results[1] as List);
        _loading = false;
        _error = null;
      });
      _scrollToBottom();
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _loading = false;
        _error = _cleanError(e);
      });
    }
  }

  Future<void> _silentLoad() async {
    if (!mounted || _sending || _statusBusy) return;
    try {
      final messages = await CampusSupportService.getMessages(widget.threadId);
      final thread = await CampusSupportService.getThread(widget.threadId);
      if (!mounted) return;
      final changed = messages.length != _messages.length ||
          (_messages.isNotEmpty && messages.isNotEmpty && messages.last.id != _messages.last.id);
      setState(() {
        _messages = messages;
        _thread = thread;
      });
      if (changed) _scrollToBottom();
    } catch (_) {}
  }

  Future<void> _pickImages() async {
    final remaining = 5 - _images.length - _documents.length;
    if (remaining <= 0) {
      _snack('A message can contain at most 5 attachments.', error: true);
      return;
    }
    final picked = await _picker.pickMultiImage(
      imageQuality: 82,
      maxWidth: 1800,
      maxHeight: 1800,
    );
    if (picked.isEmpty) return;
    final selected = picked.take(remaining).toList();
    final bytes = await Future.wait<Uint8List>(selected.map((e) => e.readAsBytes()));
    if (!mounted) return;
    setState(() {
      for (var i = 0; i < selected.length; i++) {
        _images.add(_PickedImage(file: selected[i], bytes: bytes[i]));
      }
    });
  }

  Future<void> _pickDocuments() async {
    final remaining = 5 - _images.length - _documents.length;
    if (remaining <= 0) {
      _snack('A message can contain at most 5 attachments.', error: true);
      return;
    }

    try {
      final files = await _pickSupportDocuments(limit: remaining);
      if (files.isEmpty) return;

      final validationError = await _validateSupportDocuments(files);
      if (validationError != null) {
        _snack(validationError, error: true);
        return;
      }

      if (!mounted) return;
      setState(() => _documents.addAll(files));
    } catch (e) {
      _snack('Unable to select documents: ${_cleanError(e)}', error: true);
    }
  }

  Future<void> _send() async {
    if (_sending || _thread?.isResolved == true) return;
    final text = _composer.text.trim();
    if (text.isEmpty && _images.isEmpty && _documents.isEmpty) return;
    setState(() => _sending = true);
    try {
      final message = await CampusSupportService.sendMessage(
        widget.threadId,
        text.isEmpty ? 'Attachment' : text,
      );
      if (_images.isNotEmpty || _documents.isNotEmpty) {
        await CampusSupportService.uploadAttachments(
          messageId: message.id,
          images: _images.map((e) => e.file).toList(),
          documents: _documents,
        );
      }
      _composer.clear();
      if (mounted) {
        setState(() {
          _images.clear();
          _documents.clear();
        });
      }
      await _load();
    } catch (e) {
      _snack(_cleanError(e), error: true);
    } finally {
      if (mounted) setState(() => _sending = false);
    }
  }

  Future<void> _setStatus(String status) async {
    if (_statusBusy) return;
    setState(() => _statusBusy = true);
    try {
      await CampusSupportService.setStatus(widget.threadId, status);
      await _load();
      _snack(status == 'resolved' ? 'Conversation marked as resolved.' : 'Conversation reopened.');
    } catch (e) {
      _snack(_cleanError(e), error: true);
    } finally {
      if (mounted) setState(() => _statusBusy = false);
    }
  }

  void _scrollToBottom() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!_scrollController.hasClients) return;
      _scrollController.animateTo(
        _scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 280),
        curve: Curves.easeOut,
      );
    });
  }

  void _snack(String text, {bool error = false}) {
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(text),
        backgroundColor: error ? Colors.red.shade700 : _supportGreen,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final compact = size.width < 760;
    return Dialog(
      insetPadding: EdgeInsets.symmetric(
        horizontal: compact ? 6 : 22,
        vertical: compact ? 8 : 18,
      ),
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(compact ? 12 : 22)),
      child: ConstrainedBox(
        constraints: BoxConstraints(
          maxWidth: 1050,
          maxHeight: size.height * .94,
        ),
        child: _loading
            ? const Center(child: CircularProgressIndicator(color: _supportGreen))
            : _error != null
                ? _conversationError()
                : _conversationBody(compact),
      ),
    );
  }

  Widget _conversationError() {
    return Padding(
      padding: const EdgeInsets.all(34),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(Icons.error_outline_rounded, size: 48, color: Colors.red.shade300),
          const SizedBox(height: 12),
          Text(_error!, textAlign: TextAlign.center),
          const SizedBox(height: 14),
          FilledButton.icon(
            onPressed: () => _load(initial: true),
            style: FilledButton.styleFrom(backgroundColor: _supportGreen),
            icon: const Icon(Icons.refresh_rounded),
            label: const Text('Try again'),
          ),
        ],
      ),
    );
  }

  Widget _conversationBody(bool compact) {
    final thread = _thread!;
    return Column(
      children: [
        Container(
          padding: EdgeInsets.fromLTRB(compact ? 13 : 20, 14, 10, 14),
          decoration: const BoxDecoration(
            border: Border(bottom: BorderSide(color: _supportBorder)),
          ),
          child: Row(
            children: [
              _SupportAvatar(
                image: thread.authorProfilePicture,
                name: thread.authorName,
                size: 43,
              ),
              const SizedBox(width: 11),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      thread.title,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w900, color: _supportInk),
                    ),
                    const SizedBox(height: 3),
                    Text(
                      widget.adminMode
                          ? '${thread.authorName} • ${thread.campus.isEmpty ? 'Campus not assigned' : thread.campus}'
                          : '${thread.category} • ${thread.priority} priority',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: const TextStyle(fontSize: 10.8, color: _supportMuted),
                    ),
                  ],
                ),
              ),
              const SizedBox(width: 8),
              if (!compact) _StatusBadge(thread: thread),
              if (!compact) const SizedBox(width: 8),
              if (thread.isResolved)
                TextButton.icon(
                  onPressed: _statusBusy ? null : () => _setStatus('waiting_admin'),
                  icon: const Icon(Icons.refresh_rounded, size: 17),
                  label: const Text('Reopen'),
                )
              else if (widget.adminMode)
                FilledButton.icon(
                  onPressed: _statusBusy ? null : () => _setStatus('resolved'),
                  style: FilledButton.styleFrom(backgroundColor: _supportGreen),
                  icon: const Icon(Icons.task_alt_rounded, size: 17),
                  label: const Text('Resolve'),
                ),
              IconButton(
                tooltip: 'Close',
                onPressed: () => Navigator.pop(context, true),
                icon: const Icon(Icons.close_rounded),
              ),
            ],
          ),
        ),
        Container(
          width: double.infinity,
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
          color: const Color(0xFFF8FAF9),
          child: Wrap(
            spacing: 8,
            runSpacing: 6,
            children: [
              _infoChip(Icons.category_outlined, thread.category),
              _infoChip(Icons.flag_outlined, thread.priority),
              _infoChip(Icons.chat_bubble_outline_rounded, '${thread.messageCount} messages'),
              if (thread.attachmentCount > 0)
                _infoChip(Icons.attach_file_rounded, '${thread.attachmentCount} attachments'),
              if (compact) _StatusBadge(thread: thread),
            ],
          ),
        ),
        Expanded(
          child: Container(
            color: const Color(0xFFF4F7F5),
            child: _messages.isEmpty
                ? const Center(child: Text('No messages yet.'))
                : ListView.builder(
                    controller: _scrollController,
                    padding: EdgeInsets.fromLTRB(compact ? 10 : 22, 18, compact ? 10 : 22, 18),
                    itemCount: _messages.length,
                    itemBuilder: (context, index) {
                      final message = _messages[index];
                      return _MessageBubble(
                        message: message,
                        adminMode: widget.adminMode,
                        onOpenImage: _openImage,
                        onCopyDocument: _copyDocumentLink,
                      );
                    },
                  ),
          ),
        ),
        if (thread.isResolved)
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(14),
            decoration: BoxDecoration(
              color: _supportGreen.withOpacity(.055),
              border: const Border(top: BorderSide(color: _supportBorder)),
            ),
            child: Row(
              children: [
                const Icon(Icons.task_alt_rounded, color: _supportGreen),
                const SizedBox(width: 9),
                const Expanded(
                  child: Text(
                    'This conversation is resolved. Reopen it if more assistance is required.',
                    style: TextStyle(fontSize: 11.5, color: _supportMuted, fontWeight: FontWeight.w600),
                  ),
                ),
                TextButton(
                  onPressed: _statusBusy ? null : () => _setStatus('waiting_admin'),
                  child: const Text('REOPEN'),
                ),
              ],
            ),
          )
        else
          _composerBox(compact),
      ],
    );
  }

  Widget _composerBox(bool compact) {
    return Container(
      padding: EdgeInsets.fromLTRB(compact ? 10 : 16, 10, compact ? 10 : 16, 13),
      decoration: const BoxDecoration(
        color: Colors.white,
        border: Border(top: BorderSide(color: _supportBorder)),
      ),
      child: Column(
        children: [
          if (_images.isNotEmpty || _documents.isNotEmpty) ...[
            _SelectedAttachments(
              images: _images,
              documents: _documents,
              onRemoveImage: (index) => setState(() => _images.removeAt(index)),
              onRemoveDocument: (index) => setState(() => _documents.removeAt(index)),
            ),
            const SizedBox(height: 9),
          ],
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              PopupMenuButton<String>(
                tooltip: 'Attach',
                icon: const Icon(Icons.add_circle_outline_rounded, color: _supportGreen, size: 26),
                onSelected: (value) {
                  if (value == 'images') _pickImages();
                  if (value == 'documents') _pickDocuments();
                },
                itemBuilder: (_) => const [
                  PopupMenuItem(
                    value: 'images',
                    child: ListTile(
                      dense: true,
                      leading: Icon(Icons.photo_library_outlined),
                      title: Text('Pictures'),
                    ),
                  ),
                  PopupMenuItem(
                    value: 'documents',
                    child: ListTile(
                      dense: true,
                      leading: Icon(Icons.attach_file_rounded),
                      title: Text('Document'),
                    ),
                  ),
                ],
              ),
              const SizedBox(width: 7),
              Expanded(
                child: TextField(
                  controller: _composer,
                  minLines: 1,
                  maxLines: 5,
                  textInputAction: TextInputAction.newline,
                  decoration: InputDecoration(
                    hintText: widget.adminMode
                        ? 'Write an official response...'
                        : 'Reply to administration...',
                    filled: true,
                    fillColor: const Color(0xFFF7F9F8),
                    contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(17),
                      borderSide: const BorderSide(color: _supportBorder),
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(17),
                      borderSide: const BorderSide(color: _supportBorder),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(17),
                      borderSide: const BorderSide(color: _supportGreen, width: 1.2),
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 8),
              SizedBox(
                width: 46,
                height: 46,
                child: FilledButton(
                  onPressed: _sending ? null : _send,
                  style: FilledButton.styleFrom(
                    backgroundColor: _supportGreen,
                    padding: EdgeInsets.zero,
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
                  ),
                  child: _sending
                      ? const SizedBox(
                          width: 17,
                          height: 17,
                          child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white),
                        )
                      : const Icon(Icons.send_rounded, size: 20),
                ),
              ),
            ],
          ),
          const SizedBox(height: 6),
          const Align(
            alignment: Alignment.centerLeft,
            child: Text(
              'Pictures and documents up to 10 MB each • Maximum 5 attachments per message',
              style: TextStyle(fontSize: 9.5, color: _supportMuted),
            ),
          ),
        ],
      ),
    );
  }

  Widget _infoChip(IconData icon, String label) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 5),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: _supportBorder),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 13, color: _supportMuted),
          const SizedBox(width: 4),
          Text(label, style: const TextStyle(fontSize: 9.8, color: _supportMuted, fontWeight: FontWeight.w600)),
        ],
      ),
    );
  }

  void _openImage(SupportAttachment attachment) {
    final url = CampusSupportService.mediaUrl(attachment.path);
    showDialog(
      context: context,
      builder: (_) => Dialog(
        backgroundColor: Colors.black,
        insetPadding: const EdgeInsets.all(14),
        child: Stack(
          children: [
            InteractiveViewer(
              minScale: .8,
              maxScale: 5,
              child: Center(
                child: Image.network(
                  url,
                  fit: BoxFit.contain,
                  errorBuilder: (_, __, ___) => const Padding(
                    padding: EdgeInsets.all(40),
                    child: Text('Unable to load image.', style: TextStyle(color: Colors.white)),
                  ),
                ),
              ),
            ),
            Positioned(
              right: 8,
              top: 8,
              child: IconButton.filled(
                onPressed: () => Navigator.pop(context),
                style: IconButton.styleFrom(backgroundColor: Colors.black54, foregroundColor: Colors.white),
                icon: const Icon(Icons.close_rounded),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _copyDocumentLink(SupportAttachment attachment) async {
    final url = CampusSupportService.mediaUrl(attachment.path);
    await Clipboard.setData(ClipboardData(text: url));
    _snack('Attachment link copied.');
  }
}

class _MessageBubble extends StatelessWidget {
  final SupportMessage message;
  final bool adminMode;
  final ValueChanged<SupportAttachment> onOpenImage;
  final ValueChanged<SupportAttachment> onCopyDocument;

  const _MessageBubble({
    required this.message,
    required this.adminMode,
    required this.onOpenImage,
    required this.onCopyDocument,
  });

  @override
  Widget build(BuildContext context) {
    final mine = message.sentByMe;
    final senderAdmin = _isAdminRole(message.senderRole);
    final bubbleColor = mine
        ? _supportGreen
        : senderAdmin
            ? const Color(0xFFFFF7E8)
            : Colors.white;
    final foreground = mine ? Colors.white : _supportInk;
    final maxWidth = MediaQuery.of(context).size.width < 700 ? 330.0 : 590.0;

    return Padding(
      padding: const EdgeInsets.only(bottom: 13),
      child: Row(
        mainAxisAlignment: mine ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          if (!mine) ...[
            _SupportAvatar(
              image: message.senderProfilePicture,
              name: message.senderName,
              size: 34,
            ),
            const SizedBox(width: 7),
          ],
          Flexible(
            child: ConstrainedBox(
              constraints: BoxConstraints(maxWidth: maxWidth),
              child: Column(
                crossAxisAlignment: mine ? CrossAxisAlignment.end : CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 3),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text(
                          mine ? 'You' : message.senderName,
                          style: const TextStyle(fontSize: 9.8, color: _supportMuted, fontWeight: FontWeight.w800),
                        ),
                        if (!mine && senderAdmin) ...[
                          const SizedBox(width: 4),
                          const Icon(Icons.verified_rounded, size: 12, color: _supportGold),
                          const SizedBox(width: 2),
                          const Text('ADMIN', style: TextStyle(fontSize: 8.5, fontWeight: FontWeight.w900, color: _supportGold)),
                        ],
                      ],
                    ),
                  ),
                  const SizedBox(height: 4),
                  Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: bubbleColor,
                      borderRadius: BorderRadius.only(
                        topLeft: const Radius.circular(17),
                        topRight: const Radius.circular(17),
                        bottomLeft: Radius.circular(mine ? 17 : 4),
                        bottomRight: Radius.circular(mine ? 4 : 17),
                      ),
                      border: mine
                          ? null
                          : Border.all(
                              color: senderAdmin
                                  ? _supportGold.withOpacity(.18)
                                  : _supportBorder,
                            ),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        if (message.body.trim().isNotEmpty &&
                            !(message.body == 'Attachment' && message.attachments.isNotEmpty))
                          Text(
                            message.body,
                            style: TextStyle(
                              color: foreground,
                              fontSize: 12.7,
                              height: 1.48,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        if (message.attachments.isNotEmpty) ...[
                          if (message.body.trim().isNotEmpty &&
                              !(message.body == 'Attachment' && message.attachments.isNotEmpty))
                            const SizedBox(height: 9),
                          _MessageAttachments(
                            attachments: message.attachments,
                            mine: mine,
                            onOpenImage: onOpenImage,
                            onCopyDocument: onCopyDocument,
                          ),
                        ],
                      ],
                    ),
                  ),
                  const SizedBox(height: 4),
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 3),
                    child: Text(
                      _messageTime(message.createdAt),
                      style: const TextStyle(fontSize: 9.2, color: _supportMuted),
                    ),
                  ),
                ],
              ),
            ),
          ),
          if (mine) const SizedBox(width: 4),
        ],
      ),
    );
  }
}

class _MessageAttachments extends StatelessWidget {
  final List<SupportAttachment> attachments;
  final bool mine;
  final ValueChanged<SupportAttachment> onOpenImage;
  final ValueChanged<SupportAttachment> onCopyDocument;

  const _MessageAttachments({
    required this.attachments,
    required this.mine,
    required this.onOpenImage,
    required this.onCopyDocument,
  });

  @override
  Widget build(BuildContext context) {
    final images = attachments.where((e) => e.isImage).toList();
    final files = attachments.where((e) => e.isDocument).toList();
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (images.isNotEmpty)
          Wrap(
            spacing: 6,
            runSpacing: 6,
            children: images.map((attachment) {
              final source = attachment.thumbnailPath.trim().isNotEmpty
                  ? attachment.thumbnailPath
                  : attachment.path;
              return InkWell(
                onTap: () => onOpenImage(attachment),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(11),
                  child: SizedBox(
                    width: images.length == 1 ? 250 : 120,
                    height: images.length == 1 ? 165 : 100,
                    child: Image.network(
                      CampusSupportService.mediaUrl(source),
                      fit: BoxFit.cover,
                      errorBuilder: (_, __, ___) => Container(
                        color: Colors.black12,
                        child: const Icon(Icons.broken_image_outlined),
                      ),
                    ),
                  ),
                ),
              );
            }).toList(),
          ),
        if (images.isNotEmpty && files.isNotEmpty) const SizedBox(height: 7),
        ...files.map(
          (attachment) => Padding(
            padding: const EdgeInsets.only(bottom: 5),
            child: InkWell(
              onTap: () => onCopyDocument(attachment),
              borderRadius: BorderRadius.circular(10),
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 9),
                decoration: BoxDecoration(
                  color: mine ? Colors.white.withOpacity(.12) : Colors.black.withOpacity(.025),
                  borderRadius: BorderRadius.circular(10),
                  border: Border.all(
                    color: mine ? Colors.white.withOpacity(.18) : _supportBorder,
                  ),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(Icons.description_outlined, size: 18, color: mine ? Colors.white : _supportGreen),
                    const SizedBox(width: 7),
                    Flexible(
                      child: Text(
                        attachment.originalName,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          color: mine ? Colors.white : _supportInk,
                          fontSize: 10.5,
                          fontWeight: FontWeight.w700,
                        ),
                      ),
                    ),
                    const SizedBox(width: 7),
                    Icon(Icons.link_rounded, size: 15, color: mine ? Colors.white70 : _supportMuted),
                  ],
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }
}

class _AttachmentPickerBar extends StatelessWidget {
  final VoidCallback onImages;
  final VoidCallback onDocuments;
  final int count;

  const _AttachmentPickerBar({
    required this.onImages,
    required this.onDocuments,
    required this.count,
  });

  @override
  Widget build(BuildContext context) {
    return Wrap(
      spacing: 8,
      runSpacing: 8,
      crossAxisAlignment: WrapCrossAlignment.center,
      children: [
        OutlinedButton.icon(
          onPressed: onImages,
          icon: const Icon(Icons.photo_library_outlined, size: 18),
          label: const Text('Pictures'),
        ),
        OutlinedButton.icon(
          onPressed: onDocuments,
          icon: const Icon(Icons.attach_file_rounded, size: 18),
          label: const Text('Documents'),
        ),
        Text(
          '$count/5 attachments',
          style: const TextStyle(fontSize: 10.5, color: _supportMuted),
        ),
      ],
    );
  }
}

class _SelectedAttachments extends StatelessWidget {
  final List<_PickedImage> images;
  final List<PlatformFile> documents;
  final ValueChanged<int> onRemoveImage;
  final ValueChanged<int> onRemoveDocument;

  const _SelectedAttachments({
    required this.images,
    required this.documents,
    required this.onRemoveImage,
    required this.onRemoveDocument,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(10),
      decoration: BoxDecoration(
        color: const Color(0xFFF7F9F8),
        borderRadius: BorderRadius.circular(13),
        border: Border.all(color: _supportBorder),
      ),
      child: Wrap(
        spacing: 8,
        runSpacing: 8,
        children: [
          ...List<Widget>.generate(images.length, (index) {
            return Stack(
              clipBehavior: Clip.none,
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(10),
                  child: Image.memory(
                    images[index].bytes,
                    width: 78,
                    height: 70,
                    fit: BoxFit.cover,
                  ),
                ),
                Positioned(
                  right: -5,
                  top: -5,
                  child: InkWell(
                    onTap: () => onRemoveImage(index),
                    child: Container(
                      width: 20,
                      height: 20,
                      decoration: const BoxDecoration(color: Colors.red, shape: BoxShape.circle),
                      child: const Icon(Icons.close, size: 13, color: Colors.white),
                    ),
                  ),
                ),
              ],
            );
          }),
          ...List<Widget>.generate(documents.length, (index) {
            final file = documents[index];
            return Container(
              constraints: const BoxConstraints(maxWidth: 230),
              padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 8),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(10),
                border: Border.all(color: _supportBorder),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  const Icon(Icons.description_outlined, size: 18, color: _supportGreen),
                  const SizedBox(width: 6),
                  Flexible(
                    child: Text(
                      file.name,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: const TextStyle(fontSize: 10.5, fontWeight: FontWeight.w700),
                    ),
                  ),
                  const SizedBox(width: 5),
                  InkWell(
                    onTap: () => onRemoveDocument(index),
                    child: const Icon(Icons.close_rounded, size: 16, color: Colors.redAccent),
                  ),
                ],
              ),
            );
          }),
        ],
      ),
    );
  }
}

class _PickedImage {
  final XFile file;
  final Uint8List bytes;

  const _PickedImage({required this.file, required this.bytes});
}

class _SupportAvatar extends StatelessWidget {
  final String image;
  final String name;
  final double size;

  const _SupportAvatar({
    required this.image,
    required this.name,
    required this.size,
  });

  @override
  Widget build(BuildContext context) {
    final url = image.trim().isEmpty ? '' : CampusSupportService.mediaUrl(image);
    final initials = name.trim().isEmpty
        ? 'R'
        : name
            .trim()
            .split(RegExp(r'\s+'))
            .take(2)
            .map((e) => e.isEmpty ? '' : e[0].toUpperCase())
            .join();
    return Container(
      width: size,
      height: size,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        color: _supportGreen.withOpacity(.10),
        border: Border.all(color: _supportGreen.withOpacity(.15)),
      ),
      clipBehavior: Clip.antiAlias,
      child: url.isEmpty
          ? Center(
              child: Text(
                initials,
                style: TextStyle(
                  color: _supportGreen,
                  fontWeight: FontWeight.w900,
                  fontSize: size * .32,
                ),
              ),
            )
          : Image.network(
              url,
              fit: BoxFit.cover,
              errorBuilder: (_, __, ___) => Center(
                child: Text(
                  initials,
                  style: TextStyle(
                    color: _supportGreen,
                    fontWeight: FontWeight.w900,
                    fontSize: size * .32,
                  ),
                ),
              ),
            ),
    );
  }
}

class _StatusBadge extends StatelessWidget {
  final SupportThread thread;

  const _StatusBadge({required this.thread});

  @override
  Widget build(BuildContext context) {
    late final Color color;
    late final String label;
    late final IconData icon;
    if (thread.isResolved) {
      color = _supportGreen;
      label = 'RESOLVED';
      icon = Icons.task_alt_rounded;
    } else if (thread.waitingForAdmin) {
      color = Colors.orange.shade700;
      label = 'ADMIN REPLY';
      icon = Icons.hourglass_top_rounded;
    } else {
      color = Colors.blue.shade700;
      label = 'YOUR REPLY';
      icon = Icons.reply_rounded;
    }
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
      decoration: BoxDecoration(
        color: color.withOpacity(.08),
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: color.withOpacity(.18)),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 12, color: color),
          const SizedBox(width: 4),
          Text(
            label,
            style: TextStyle(color: color, fontSize: 8.8, fontWeight: FontWeight.w900, letterSpacing: .35),
          ),
        ],
      ),
    );
  }
}

class _PriorityBadge extends StatelessWidget {
  final String priority;

  const _PriorityBadge({required this.priority});

  @override
  Widget build(BuildContext context) {
    final normalized = priority.toLowerCase();
    final color = normalized == 'urgent'
        ? Colors.red.shade700
        : normalized == 'important'
            ? _supportGold
            : _supportMuted;
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 3),
      decoration: BoxDecoration(
        color: color.withOpacity(.07),
        borderRadius: BorderRadius.circular(20),
      ),
      child: Text(
        priority.toUpperCase(),
        style: TextStyle(fontSize: 8.6, color: color, fontWeight: FontWeight.w900),
      ),
    );
  }
}

Widget _dialogHeader({
  required IconData icon,
  required String title,
  required String subtitle,
  required VoidCallback? onClose,
}) {
  return Container(
    padding: const EdgeInsets.fromLTRB(20, 16, 10, 16),
    decoration: const BoxDecoration(
      border: Border(bottom: BorderSide(color: _supportBorder)),
    ),
    child: Row(
      children: [
        Container(
          width: 42,
          height: 42,
          decoration: BoxDecoration(
            color: _supportGreen.withOpacity(.08),
            borderRadius: BorderRadius.circular(13),
          ),
          child: Icon(icon, color: _supportGreen),
        ),
        const SizedBox(width: 11),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w900, color: _supportInk)),
              const SizedBox(height: 2),
              Text(subtitle, style: const TextStyle(fontSize: 10.5, color: _supportMuted)),
            ],
          ),
        ),
        IconButton(onPressed: onClose, icon: const Icon(Icons.close_rounded)),
      ],
    ),
  );
}

InputDecoration _fieldDecoration(String label, String? hint, IconData icon) {
  return InputDecoration(
    labelText: label,
    hintText: hint,
    prefixIcon: Icon(icon, color: _supportGreen, size: 20),
    filled: true,
    fillColor: const Color(0xFFF9FAFA),
    counterText: '',
    contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14),
    border: OutlineInputBorder(
      borderRadius: BorderRadius.circular(13),
      borderSide: const BorderSide(color: _supportBorder),
    ),
    enabledBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(13),
      borderSide: const BorderSide(color: _supportBorder),
    ),
    focusedBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(13),
      borderSide: const BorderSide(color: _supportGreen, width: 1.3),
    ),
  );
}

BoxDecoration _panelDecoration() {
  return BoxDecoration(
    color: Colors.white,
    borderRadius: BorderRadius.circular(18),
    border: Border.all(color: _supportBorder),
  );
}

bool _isAdminRole(String role) {
  final value = role.toLowerCase().trim().replaceAll('-', '_');
  return value == 'admin' ||
      value == 'administrator' ||
      value == 'superadmin' ||
      value == 'super_admin' ||
      value == 'super admin' ||
      value == 'super admin';
}

String _cleanError(Object error) {
  var text = error.toString();
  if (text.startsWith('Exception: ')) text = text.substring(11);
  return text;
}

String _timeAgo(DateTime date) {
  final local = date.toLocal();
  final diff = DateTime.now().difference(local);
  if (diff.inSeconds < 45) return 'Just now';
  if (diff.inMinutes < 60) return '${diff.inMinutes}m ago';
  if (diff.inHours < 24) return '${diff.inHours}h ago';
  if (diff.inDays < 7) return '${diff.inDays}d ago';
  return '${local.day.toString().padLeft(2, '0')}/${local.month.toString().padLeft(2, '0')}/${local.year}';
}

String _messageTime(DateTime date) {
  final local = date.toLocal();
  final now = DateTime.now();
  final sameDay = local.year == now.year && local.month == now.month && local.day == now.day;
  final hour = local.hour == 0 ? 12 : local.hour > 12 ? local.hour - 12 : local.hour;
  final minute = local.minute.toString().padLeft(2, '0');
  final ampm = local.hour >= 12 ? 'PM' : 'AM';
  if (sameDay) return '$hour:$minute $ampm';
  return '${local.day}/${local.month}/${local.year} • $hour:$minute $ampm';
}
