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

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

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

const Color _green = Color.fromARGB(255, 2, 105, 48);
const Color _gold = Color.fromARGB(255, 204, 117, 4);
const Color _pageBg = Color(0xFFF3F5F7);
const Color _border = Color(0xFFE3E8EE);
const Color _dark = Color(0xFF182632);
const Color _muted = Color(0xFF66727E);

class AnnouncementFeedView extends StatefulWidget {
  final bool allowCreate;

  const AnnouncementFeedView({super.key, this.allowCreate = true});

  @override
  State<AnnouncementFeedView> createState() => _AnnouncementFeedViewState();
}

class _AnnouncementFeedViewState extends State<AnnouncementFeedView> {
  final ScrollController _scrollController = ScrollController();
  final TextEditingController _searchController = TextEditingController();
  final List<CampusAnnouncement> _items = [];
  List<String> _campuses = [];
  List<CampusAnnouncementNotification> _notifications = [];
  String _selectedCampus = 'All Campuses';
  String _selectedCategory = 'All Categories';
  bool _loading = true;
  bool _loadingMore = false;
  bool _hasMore = true;
  String? _error;
  int _page = 1;
  int _unread = 0;
  Timer? _liveTimer;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_onScroll);
    _loadInitial();
    _liveTimer = Timer.periodic(const Duration(seconds: 15), (_) => _silentRefresh());
  }

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

  Future<void> _loadInitial() async {
    setState(() {
      _loading = true;
      _error = null;
      _page = 1;
      _hasMore = true;
    });
    try {
      final result = await Future.wait<dynamic>([
        CampusAnnouncementsService.getCampuses(),
        CampusAnnouncementsService.getAnnouncements(
          scope: 'active',
          campus: _selectedCampus,
          category: _selectedCategory,
          search: _searchController.text,
          page: 1,
          limit: 8,
        ),
        CampusAnnouncementsService.getNotifications(limit: 50),
      ]);
      if (!mounted) return;
      final page = result[1] as CampusAnnouncementPage;
      final notifications = result[2] as CampusAnnouncementNotificationPage;
      setState(() {
        _campuses = List<String>.from(result[0] as List);
        _items
          ..clear()
          ..addAll(page.announcements);
        _hasMore = page.hasMore;
        _notifications = notifications.items;
        _unread = notifications.unreadCount;
        _loading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _loading = false;
        _error = _cleanError(e);
      });
    }
  }

  Future<void> _silentRefresh() async {
    if (!mounted || _loading || _loadingMore) return;
    if (_scrollController.hasClients && _scrollController.offset > 260) return;
    try {
      final result = await Future.wait<dynamic>([
        CampusAnnouncementsService.getAnnouncements(
          scope: 'active',
          campus: _selectedCampus,
          category: _selectedCategory,
          search: _searchController.text,
          page: 1,
          limit: 8,
        ),
        CampusAnnouncementsService.getNotifications(limit: 50),
      ]);
      if (!mounted) return;
      final page = result[0] as CampusAnnouncementPage;
      final notifications = result[1] as CampusAnnouncementNotificationPage;
      final seen = <int>{};
      final merged = <CampusAnnouncement>[];
      for (final item in [...page.announcements, ..._items]) {
        if (seen.add(item.id)) merged.add(item);
      }
      setState(() {
        _items
          ..clear()
          ..addAll(merged);
        _notifications = notifications.items;
        _unread = notifications.unreadCount;
      });
    } catch (_) {}
  }

  Future<void> _loadMore() async {
    if (_loading || _loadingMore || !_hasMore) return;
    setState(() => _loadingMore = true);
    try {
      final next = _page + 1;
      final page = await CampusAnnouncementsService.getAnnouncements(
        scope: 'active',
        campus: _selectedCampus,
        category: _selectedCategory,
        search: _searchController.text,
        page: next,
        limit: 8,
      );
      if (!mounted) return;
      setState(() {
        _items.addAll(page.announcements);
        _page = next;
        _hasMore = page.hasMore;
        _loadingMore = false;
      });
    } catch (_) {
      if (mounted) setState(() => _loadingMore = false);
    }
  }

  void _onScroll() {
    if (!_scrollController.hasClients) return;
    if (_scrollController.position.pixels >= _scrollController.position.maxScrollExtent - 420) {
      _loadMore();
    }
  }

  Future<void> _create() async {
    final result = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (_) => const AnnouncementComposerDialog(),
    );
    if (result == true) await _loadInitial();
  }

  Future<void> _toggleLike(int index) async {
    final original = _items[index];
    setState(() {
      _items[index] = original.copyWith(
        likedByMe: !original.likedByMe,
        likeCount: original.likeCount + (original.likedByMe ? -1 : 1),
      );
    });
    try {
      final result = await CampusAnnouncementsService.toggleLike(original.id);
      if (!mounted) return;
      setState(() {
        _items[index] = _items[index].copyWith(
          likedByMe: _bool(result['liked']),
          likeCount: int.tryParse('${result['like_count'] ?? 0}') ?? 0,
        );
      });
      await _refreshNotifications();
    } catch (e) {
      if (!mounted) return;
      setState(() => _items[index] = original);
      _snack(_cleanError(e), error: true);
    }
  }

  Future<void> _openConversation(int index) async {
    final result = await showDialog<CampusAnnouncement>(
      context: context,
      builder: (_) => AnnouncementConversationDialog(announcement: _items[index]),
    );
    if (result != null && mounted) {
      setState(() => _items[index] = result);
      await _refreshNotifications();
    }
  }

  Future<void> _share(CampusAnnouncement item) async {
    await Clipboard.setData(ClipboardData(text: '${item.title}\n\n${item.body}'));
    if (mounted) _snack('Announcement copied.');
  }

  Future<void> _refreshNotifications() async {
    try {
      final data = await CampusAnnouncementsService.getNotifications(limit: 50);
      if (!mounted) return;
      setState(() {
        _notifications = data.items;
        _unread = data.unreadCount;
      });
    } catch (_) {}
  }

  Future<void> _openNotifications() async {
    await showModalBottomSheet<void>(
      context: context,
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      builder: (_) => _AnnouncementNotificationsSheet(
        items: _notifications,
        unread: _unread,
        onRead: (item) async {
          if (!item.isRead) await CampusAnnouncementsService.markNotificationRead(item.id);
          await _refreshNotifications();
        },
        onReadAll: () async {
          await CampusAnnouncementsService.markAllNotificationsRead();
          await _refreshNotifications();
        },
      ),
    );
  }

  void _snack(String text, {bool error = false}) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
      content: Text(text),
      backgroundColor: error ? Colors.red.shade700 : _green,
      behavior: SnackBarBehavior.floating,
    ));
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: _pageBg,
      child: LayoutBuilder(builder: (context, constraints) {
        final desktop = constraints.maxWidth >= 1180;
        final tablet = constraints.maxWidth >= 860 && constraints.maxWidth < 1180;
        return Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (desktop) SizedBox(width: 220, child: _leftPanel()),
            if (desktop) const SizedBox(width: 14),
            Expanded(child: _mainFeed(compact: constraints.maxWidth < 700)),
            if (desktop || tablet) const SizedBox(width: 14),
            if (desktop) SizedBox(width: 255, child: _rightPanel()),
            if (tablet) SizedBox(width: 190, child: _rightPanel(compact: true)),
          ],
        );
      }),
    );
  }

  Widget _leftPanel() {
    return ListView(
      padding: const EdgeInsets.only(top: 12, bottom: 90),
      children: [
        Container(
          padding: const EdgeInsets.all(16),
          decoration: _panelDecoration(),
          child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            const Text('ANNOUNCEMENT CENTER', style: TextStyle(fontSize: 10.5, color: _green, fontWeight: FontWeight.w900, letterSpacing: .9)),
            const SizedBox(height: 13),
            if (widget.allowCreate)
              FilledButton.icon(
                onPressed: _create,
                style: FilledButton.styleFrom(
                  minimumSize: const Size(double.infinity, 46),
                  backgroundColor: _green,
                  foregroundColor: Colors.white,
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
                ),
                icon: const Icon(Icons.campaign_rounded),
                label: const Text('New notice', style: TextStyle(fontWeight: FontWeight.w900)),
              ),
            const SizedBox(height: 18),
            const Text('CAMPUS', style: TextStyle(fontSize: 9.5, color: _muted, fontWeight: FontWeight.w900, letterSpacing: .8)),
            const SizedBox(height: 7),
            DropdownButtonFormField<String>(
              value: _selectedCampus,
              isExpanded: true,
              decoration: _inputDecoration(),
              items: <String>['All Campuses', ..._campuses]
                  .map((item) => DropdownMenuItem(value: item, child: Text(item, overflow: TextOverflow.ellipsis)))
                  .toList(),
              onChanged: (value) {
                if (value == null) return;
                setState(() => _selectedCampus = value);
                _loadInitial();
              },
            ),
            const SizedBox(height: 14),
            const Text('CATEGORY', style: TextStyle(fontSize: 9.5, color: _muted, fontWeight: FontWeight.w900, letterSpacing: .8)),
            const SizedBox(height: 7),
            DropdownButtonFormField<String>(
              value: _selectedCategory,
              isExpanded: true,
              decoration: _inputDecoration(),
              items: <String>['All Categories', ...CampusAnnouncementsService.categories]
                  .map((item) => DropdownMenuItem(value: item, child: Text(item)))
                  .toList(),
              onChanged: (value) {
                if (value == null) return;
                setState(() => _selectedCategory = value);
                _loadInitial();
              },
            ),
            const SizedBox(height: 14),
            OutlinedButton.icon(
              onPressed: _loadInitial,
              style: OutlinedButton.styleFrom(minimumSize: const Size(double.infinity, 43), foregroundColor: _green),
              icon: const Icon(Icons.refresh_rounded),
              label: const Text('Refresh'),
            ),
          ]),
        ),
        const SizedBox(height: 12),
        Container(
          padding: const EdgeInsets.all(14),
          decoration: BoxDecoration(
            color: _green.withOpacity(.045),
            borderRadius: BorderRadius.circular(18),
            border: Border.all(color: _green.withOpacity(.14)),
          ),
          child: const Text(
            'Use priority, audience, scheduling and expiry controls to publish clear institutional notices without overcrowding the feed.',
            style: TextStyle(color: _muted, fontSize: 11.2, height: 1.5),
          ),
        ),
      ],
    );
  }

  Widget _rightPanel({bool compact = false}) {
    return ListView(
      padding: const EdgeInsets.only(top: 12, bottom: 90),
      children: [
        Container(
          padding: const EdgeInsets.all(14),
          decoration: _panelDecoration(),
          child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Row(children: [
              const Expanded(child: Text('Activity', style: TextStyle(fontWeight: FontWeight.w900))),
              _AnnouncementBell(unread: _unread, onTap: _openNotifications),
            ]),
            const SizedBox(height: 10),
            Text('$_unread unread notification${_unread == 1 ? '' : 's'}', style: const TextStyle(fontSize: 10.5, color: _muted)),
            if (!compact && _notifications.isNotEmpty) ...[
              const SizedBox(height: 10),
              const Divider(),
              ..._notifications.take(3).map((n) => Padding(
                    padding: const EdgeInsets.only(top: 8),
                    child: Text(n.title, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 10.5, fontWeight: FontWeight.w800)),
                  )),
            ],
            TextButton(onPressed: _openNotifications, child: const Text('View all')),
          ]),
        ),
        if (!compact) ...[
          const SizedBox(height: 12),
          Container(
            padding: const EdgeInsets.all(14),
            decoration: _panelDecoration(),
            child: const Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              Text('Professional workflow', style: TextStyle(fontWeight: FontWeight.w900)),
              SizedBox(height: 8),
              Text('Draft notices, schedule future publication, add expiry dates, pin important notices and keep discussions attached to the announcement.', style: TextStyle(color: _muted, fontSize: 11.2, height: 1.5)),
            ]),
          ),
        ],
      ],
    );
  }

  Widget _mainFeed({required bool compact}) {
    return RefreshIndicator(
      color: _green,
      onRefresh: _loadInitial,
      child: ListView(
        controller: _scrollController,
        physics: const AlwaysScrollableScrollPhysics(),
        padding: EdgeInsets.fromLTRB(compact ? 8 : 0, 12, compact ? 8 : 0, 100),
        children: [
          _header(compact),
          if (compact) ...[const SizedBox(height: 12), _mobileFilters()],
          const SizedBox(height: 14),
          if (_loading)
            const Padding(padding: EdgeInsets.symmetric(vertical: 120), child: Center(child: CircularProgressIndicator(color: _green)))
          else if (_error != null)
            _errorState()
          else if (_items.isEmpty)
            _emptyState()
          else
            ...List.generate(_items.length, (index) => Padding(
                  padding: const EdgeInsets.only(bottom: 13),
                  child: _AnnouncementCard(
                    announcement: _items[index],
                    onLike: () => _toggleLike(index),
                    onComment: () => _openConversation(index),
                    onShare: () => _share(_items[index]),
                  ),
                )),
          if (_loadingMore)
            const Padding(padding: EdgeInsets.all(18), child: Center(child: CircularProgressIndicator(color: _green))),
        ],
      ),
    );
  }

  Widget _header(bool compact) {
    return Container(
      padding: EdgeInsets.all(compact ? 14 : 17),
      decoration: _panelDecoration(radius: 22),
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Row(children: [
          const Expanded(
            child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              Text('Staff Announcements', style: TextStyle(fontSize: 22, fontWeight: FontWeight.w900, color: _dark)),
              SizedBox(height: 4),
              Text('Official notices, priority messages and staff conversations in one professional feed.', style: TextStyle(fontSize: 11.8, color: _muted, height: 1.45)),
            ]),
          ),
          if (compact) _AnnouncementBell(unread: _unread, onTap: _openNotifications),
          if (compact && widget.allowCreate) ...[
            const SizedBox(width: 8),
            IconButton.filled(
              onPressed: _create,
              style: IconButton.styleFrom(backgroundColor: _green, foregroundColor: Colors.white),
              icon: const Icon(Icons.add_rounded),
            ),
          ],
        ]),
        const SizedBox(height: 13),
        TextField(
          controller: _searchController,
          textInputAction: TextInputAction.search,
          onSubmitted: (_) => _loadInitial(),
          decoration: InputDecoration(
            hintText: 'Search announcements, authors or topics...',
            prefixIcon: const Icon(Icons.search_rounded, color: _green),
            suffixIcon: IconButton(onPressed: _loadInitial, icon: const Icon(Icons.arrow_forward_rounded, color: _green)),
            filled: true,
            fillColor: const Color(0xFFF7F9FB),
            border: OutlineInputBorder(borderRadius: BorderRadius.circular(15), borderSide: const BorderSide(color: _border)),
            enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(15), borderSide: const BorderSide(color: _border)),
            focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(15), borderSide: const BorderSide(color: _green, width: 1.3)),
          ),
        ),
      ]),
    );
  }

  Widget _mobileFilters() {
    return Container(
      padding: const EdgeInsets.all(11),
      decoration: _panelDecoration(radius: 18),
      child: Column(children: [
        DropdownButtonFormField<String>(
          value: _selectedCampus,
          isExpanded: true,
          decoration: _inputDecoration(),
          items: <String>['All Campuses', ..._campuses].map((item) => DropdownMenuItem(value: item, child: Text(item))).toList(),
          onChanged: (value) {
            if (value == null) return;
            setState(() => _selectedCampus = value);
            _loadInitial();
          },
        ),
        const SizedBox(height: 8),
        DropdownButtonFormField<String>(
          value: _selectedCategory,
          isExpanded: true,
          decoration: _inputDecoration(),
          items: <String>['All Categories', ...CampusAnnouncementsService.categories].map((item) => DropdownMenuItem(value: item, child: Text(item))).toList(),
          onChanged: (value) {
            if (value == null) return;
            setState(() => _selectedCategory = value);
            _loadInitial();
          },
        ),
      ]),
    );
  }

  Widget _errorState() => Container(
        padding: const EdgeInsets.all(28),
        decoration: _panelDecoration(radius: 22),
        child: Column(children: [
          Icon(Icons.cloud_off_rounded, size: 48, color: Colors.red.shade300),
          const SizedBox(height: 12),
          const Text('Announcements could not be loaded', style: TextStyle(fontSize: 17, fontWeight: FontWeight.w900)),
          const SizedBox(height: 7),
          Text(_error!, textAlign: TextAlign.center, style: const TextStyle(color: _muted, height: 1.45)),
          const SizedBox(height: 14),
          FilledButton.icon(onPressed: _loadInitial, style: FilledButton.styleFrom(backgroundColor: _green), icon: const Icon(Icons.refresh), label: const Text('Try again')),
        ]),
      );

  Widget _emptyState() => Container(
        padding: const EdgeInsets.symmetric(horizontal: 22, vertical: 64),
        decoration: _panelDecoration(radius: 22),
        child: Column(children: [
          Icon(Icons.campaign_outlined, size: 60, color: Colors.grey.shade300),
          const SizedBox(height: 12),
          const Text('No active announcements', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w900)),
          const SizedBox(height: 7),
          const Text('Create a notice or change the current filters.', textAlign: TextAlign.center, style: TextStyle(color: _muted)),
        ]),
      );
}

class _AnnouncementCard extends StatelessWidget {
  final CampusAnnouncement announcement;
  final VoidCallback onLike;
  final VoidCallback onComment;
  final VoidCallback onShare;

  const _AnnouncementCard({required this.announcement, required this.onLike, required this.onComment, required this.onShare});

  @override
  Widget build(BuildContext context) {
    final compact = MediaQuery.of(context).size.width < 650;
    final images = announcement.images;
    return Container(
      decoration: _panelDecoration(radius: 22),
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        if (announcement.isPinned)
          Container(
            width: double.infinity,
            padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
            decoration: const BoxDecoration(color: Color(0xFFFFF8EA), borderRadius: BorderRadius.vertical(top: Radius.circular(22))),
            child: const Row(children: [
              Icon(Icons.push_pin_rounded, size: 15, color: _gold),
              SizedBox(width: 6),
              Text('PINNED ANNOUNCEMENT', style: TextStyle(fontSize: 9.5, color: _gold, fontWeight: FontWeight.w900, letterSpacing: .7)),
            ]),
          ),
        Padding(
          padding: EdgeInsets.fromLTRB(compact ? 13 : 16, 14, compact ? 13 : 16, 10),
          child: Row(children: [
            _AnnouncementAvatar(value: announcement.authorProfilePicture, size: 43),
            const SizedBox(width: 10),
            Expanded(
              child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                Row(children: [
                  Flexible(child: Text(announcement.authorName, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w900, color: _dark))),
                  const SizedBox(width: 5),
                  const Icon(Icons.verified_rounded, color: _green, size: 15),
                ]),
                const SizedBox(height: 3),
                Text('${announcement.campus.isEmpty ? 'Rockview University' : announcement.campus} • ${_timeAgo(announcement.publishedAt ?? announcement.createdAt)}', style: const TextStyle(color: _muted, fontSize: 10.5, fontWeight: FontWeight.w600)),
              ]),
            ),
            _PriorityChip(priority: announcement.priority),
          ]),
        ),
        Padding(
          padding: EdgeInsets.fromLTRB(compact ? 13 : 16, 0, compact ? 13 : 16, 13),
          child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Row(children: [
              _CategoryChip(label: announcement.category),
              const SizedBox(width: 7),
              _AudienceChip(label: announcement.audience),
            ]),
            const SizedBox(height: 10),
            Text(announcement.title, style: TextStyle(fontSize: compact ? 17 : 19, height: 1.25, fontWeight: FontWeight.w900, color: _dark)),
            const SizedBox(height: 8),
            Text(announcement.body, maxLines: compact ? 4 : 5, overflow: TextOverflow.ellipsis, style: const TextStyle(color: Color(0xFF53606D), fontSize: 12.5, height: 1.55)),
            if (announcement.expiresAt != null) ...[
              const SizedBox(height: 9),
              Text('Visible until ${_formatDateTime(announcement.expiresAt!)}', style: const TextStyle(fontSize: 10.5, color: _muted, fontWeight: FontWeight.w700)),
            ],
          ]),
        ),
        if (images.isNotEmpty) _AnnouncementImagePreview(images: images),
        if (announcement.video != null) ...[
          const SizedBox(height: 10),
          Padding(padding: EdgeInsets.symmetric(horizontal: compact ? 13 : 16), child: _InlineAnnouncementVideo(video: announcement.video!)),
        ],
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
          decoration: BoxDecoration(color: const Color(0xFFFBFCFB), border: Border(top: BorderSide(color: Colors.grey.shade200)), borderRadius: const BorderRadius.vertical(bottom: Radius.circular(22))),
          child: Row(children: [
            _SocialButton(icon: announcement.likedByMe ? Icons.favorite_rounded : Icons.favorite_border_rounded, label: announcement.likeCount == 0 ? 'Like' : '${announcement.likeCount}', active: announcement.likedByMe, onTap: onLike),
            const SizedBox(width: 2),
            _SocialButton(icon: Icons.mode_comment_outlined, label: announcement.commentCount == 0 ? 'Comment' : '${announcement.commentCount}', onTap: onComment),
            const Spacer(),
            _SocialButton(icon: Icons.ios_share_rounded, label: compact ? '' : 'Share', onTap: onShare),
          ]),
        ),
      ]),
    );
  }
}

class _AnnouncementImagePreview extends StatelessWidget {
  final List<CampusAnnouncementMedia> images;
  const _AnnouncementImagePreview({required this.images});

  @override
  Widget build(BuildContext context) {
    final extra = images.length - 1;
    final first = images.first.thumbnailPath.isNotEmpty ? images.first.thumbnailPath : images.first.path;
    return AspectRatio(
      aspectRatio: 16 / 9,
      child: Stack(fit: StackFit.expand, children: [
        _AnnouncementNetworkImage(path: first),
        if (extra > 0)
          Positioned(
            right: 12,
            bottom: 12,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 9),
              decoration: BoxDecoration(color: Colors.black.withOpacity(.7), borderRadius: BorderRadius.circular(13)),
              child: Text('+$extra', style: const TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.w900)),
            ),
          ),
      ]),
    );
  }
}

class _InlineAnnouncementVideo extends StatefulWidget {
  final CampusAnnouncementMedia video;
  const _InlineAnnouncementVideo({required this.video});

  @override
  State<_InlineAnnouncementVideo> createState() => _InlineAnnouncementVideoState();
}

class _InlineAnnouncementVideoState extends State<_InlineAnnouncementVideo> {
  static VideoPlayerController? _active;
  VideoPlayerController? _controller;
  bool _loading = false;
  String? _error;

  Future<void> _toggle() async {
    if (_controller != null) {
      if (_controller!.value.isPlaying) {
        await _controller!.pause();
      } else {
        if (_active != null && _active != _controller) await _active!.pause();
        _active = _controller;
        await _controller!.play();
      }
      if (mounted) setState(() {});
      return;
    }
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final controller = VideoPlayerController.networkUrl(Uri.parse(CampusAnnouncementsService.mediaUrl(widget.video.path)));
      await controller.initialize();
      await controller.setLooping(false);
      if (_active != null && _active != controller) await _active!.pause();
      _active = controller;
      await controller.play();
      if (!mounted) {
        controller.dispose();
        return;
      }
      setState(() {
        _controller = controller;
        _loading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _loading = false;
        _error = _cleanError(e);
      });
    }
  }

  @override
  void dispose() {
    if (_active == _controller) _active = null;
    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(16),
      child: AspectRatio(
        aspectRatio: 16 / 9,
        child: Container(
          color: const Color(0xFF121416),
          child: Stack(fit: StackFit.expand, children: [
            if (_controller != null && _controller!.value.isInitialized)
              FittedBox(
                fit: BoxFit.contain,
                child: SizedBox(width: _controller!.value.size.width, height: _controller!.value.size.height, child: VideoPlayer(_controller!)),
              )
            else
              const Center(child: Icon(Icons.videocam_outlined, size: 54, color: Colors.white30)),
            if (_error != null) Center(child: Padding(padding: const EdgeInsets.all(16), child: Text(_error!, textAlign: TextAlign.center, style: const TextStyle(color: Colors.white70, fontSize: 11)))),
            if (_loading)
              const Center(child: CircularProgressIndicator(color: Colors.white))
            else
              Center(
                child: InkWell(
                  onTap: _toggle,
                  borderRadius: BorderRadius.circular(999),
                  child: Container(
                    width: 58,
                    height: 58,
                    decoration: BoxDecoration(color: Colors.black.withOpacity(.62), shape: BoxShape.circle),
                    child: Icon(_controller?.value.isPlaying == true ? Icons.pause_rounded : Icons.play_arrow_rounded, color: Colors.white, size: 36),
                  ),
                ),
              ),
            const Positioned(left: 10, bottom: 9, child: Text('VIDEO • TAP TO PLAY INLINE', style: TextStyle(color: Colors.white70, fontSize: 8.5, fontWeight: FontWeight.w900))),
          ]),
        ),
      ),
    );
  }
}

class AnnouncementComposerDialog extends StatefulWidget {
  final CampusAnnouncement? announcement;
  const AnnouncementComposerDialog({super.key, this.announcement});

  @override
  State<AnnouncementComposerDialog> createState() => _AnnouncementComposerDialogState();
}

class _AnnouncementComposerDialogState extends State<AnnouncementComposerDialog> {
  final _formKey = GlobalKey<FormState>();
  final ImagePicker _picker = ImagePicker();
  late final TextEditingController _title;
  late final TextEditingController _body;
  String _category = 'General';
  String _priority = 'Normal';
  String _audience = 'All Staff';
  bool _pinned = false;
  DateTime? _scheduledAt;
  DateTime? _expiresAt;
  Map<String, dynamic>? _me;
  String? _accountError;
  bool _loadingAccount = true;
  bool _saving = false;
  final List<PickedAnnouncementImage> _images = [];
  XFile? _video;
  String _videoLabel = '';

  @override
  void initState() {
    super.initState();
    final a = widget.announcement;
    _title = TextEditingController(text: a?.title ?? '');
    _body = TextEditingController(text: a?.body ?? '');
    _category = a?.category ?? 'General';
    _priority = a?.priority ?? 'Normal';
    _audience = a?.audience ?? 'All Staff';
    _pinned = a?.isPinned ?? false;
    _scheduledAt = a?.scheduledAt;
    _expiresAt = a?.expiresAt;
    _loadAccount();
  }

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

  Future<void> _loadAccount() async {
    try {
      final me = await CampusAnnouncementsService.getCurrentUser();
      if (!mounted) return;
      setState(() {
        _me = me;
        _loadingAccount = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _loadingAccount = false;
        _accountError = _cleanError(e);
      });
    }
  }

  Future<DateTime?> _pickDateTime(DateTime initial) async {
    final date = await showDatePicker(
      context: context,
      initialDate: initial,
      firstDate: DateTime.now().subtract(const Duration(days: 1)),
      lastDate: DateTime.now().add(const Duration(days: 3650)),
    );
    if (date == null || !mounted) return null;
    final time = await showTimePicker(context: context, initialTime: TimeOfDay.fromDateTime(initial));
    if (time == null) return null;
    return DateTime(date.year, date.month, date.day, time.hour, time.minute);
  }

  Future<void> _pickImages() async {
    final remaining = 6 - _images.length;
    if (remaining <= 0) return;
    final files = await _picker.pickMultiImage(imageQuality: 82, maxWidth: 1800, maxHeight: 1800);
    if (files.isEmpty) return;
    final selected = files.take(remaining).toList();
    final bytes = await Future.wait<Uint8List>(selected.map((f) => f.readAsBytes()));
    if (!mounted) return;
    setState(() {
      for (var i = 0; i < selected.length; i++) {
        _images.add(PickedAnnouncementImage(file: selected[i], bytes: bytes[i]));
      }
    });
  }

  Future<void> _pickVideo() async {
    final file = await _picker.pickVideo(source: ImageSource.gallery, maxDuration: const Duration(minutes: 10));
    if (file == null) return;
    final bytes = await file.length();
    if (bytes > 10 * 1024 * 1024) {
      _show('Video must not exceed 10 MB.', error: true);
      return;
    }
    if (!mounted) return;
    setState(() {
      _video = file;
      _videoLabel = '${file.name} • ${formatBytes(bytes)}';
    });
  }

  Future<void> _save(String status) async {
    if (_saving || _me == null || !(_formKey.currentState?.validate() ?? false)) return;
    if (status == 'scheduled' && _scheduledAt == null) {
      _show('Choose a publication date and time before scheduling.', error: true);
      return;
    }
    setState(() => _saving = true);
    try {
      int id;
      if (widget.announcement == null) {
        id = await CampusAnnouncementsService.createAnnouncement(
          title: _title.text,
          body: _body.text,
          category: _category,
          priority: _priority,
          audience: _audience,
          status: status,
          isPinned: _pinned,
          scheduledAt: status == 'scheduled' ? _scheduledAt : null,
          expiresAt: _expiresAt,
        );
      } else {
        id = widget.announcement!.id;
        await CampusAnnouncementsService.updateAnnouncement(id, <String, dynamic>{
          'title': _title.text.trim(),
          'body': _body.text.trim(),
          'category': _category,
          'priority': _priority,
          'audience': _audience,
          'status': status,
          'is_pinned': _pinned,
          'scheduled_at': status == 'scheduled' ? _scheduledAt?.toUtc().toIso8601String() : null,
          'expires_at': _expiresAt?.toUtc().toIso8601String(),
        });
      }
      if (_images.isNotEmpty) await CampusAnnouncementsService.uploadImages(id, _images.map((e) => e.file).toList());
      if (_video != null) await CampusAnnouncementsService.uploadVideo(id, _video!);
      if (!mounted) return;
      Navigator.pop(context, true);
    } catch (e) {
      _show(_cleanError(e), error: true);
    } finally {
      if (mounted) setState(() => _saving = false);
    }
  }

  void _show(String text, {bool error = false}) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(text), backgroundColor: error ? Colors.red.shade700 : _green));
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      insetPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 16),
      backgroundColor: Colors.transparent,
      child: Container(
        constraints: BoxConstraints(maxWidth: 900, maxHeight: MediaQuery.of(context).size.height * .94),
        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(26)),
        child: Column(children: [
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 15),
            decoration: const BoxDecoration(color: _green, borderRadius: BorderRadius.vertical(top: Radius.circular(26))),
            child: Row(children: [
              const Icon(Icons.campaign_rounded, color: Colors.white),
              const SizedBox(width: 10),
              Expanded(child: Text(widget.announcement == null ? 'Create Announcement' : 'Edit Announcement', style: const TextStyle(color: Colors.white, fontSize: 17, fontWeight: FontWeight.w900))),
              IconButton(onPressed: _saving ? null : () => Navigator.pop(context, false), icon: const Icon(Icons.close_rounded, color: Colors.white)),
            ]),
          ),
          Expanded(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(20),
              child: Form(
                key: _formKey,
                child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                  _section('AUTHOR & CAMPUS'),
                  const SizedBox(height: 10),
                  _authorPanel(),
                  const SizedBox(height: 20),
                  _section('ANNOUNCEMENT DETAILS'),
                  const SizedBox(height: 10),
                  TextFormField(
                    controller: _title,
                    maxLength: 180,
                    decoration: _fieldDecoration('Announcement title', Icons.title_rounded),
                    validator: (value) => value == null || value.trim().length < 4 ? 'Enter a clear title.' : null,
                  ),
                  const SizedBox(height: 10),
                  LayoutBuilder(builder: (context, constraints) {
                    final compact = constraints.maxWidth < 650;
                    final fields = <Widget>[
                      DropdownButtonFormField<String>(value: _category, decoration: _fieldDecoration('Category', Icons.category_outlined), items: CampusAnnouncementsService.categories.map((e) => DropdownMenuItem(value: e, child: Text(e))).toList(), onChanged: (v) => setState(() => _category = v ?? _category)),
                      DropdownButtonFormField<String>(value: _priority, decoration: _fieldDecoration('Priority', Icons.priority_high_rounded), items: CampusAnnouncementsService.priorities.map((e) => DropdownMenuItem(value: e, child: Text(e))).toList(), onChanged: (v) => setState(() => _priority = v ?? _priority)),
                      DropdownButtonFormField<String>(value: _audience, decoration: _fieldDecoration('Audience', Icons.groups_2_outlined), items: CampusAnnouncementsService.audiences.map((e) => DropdownMenuItem(value: e, child: Text(e))).toList(), onChanged: (v) => setState(() => _audience = v ?? _audience)),
                    ];
                    if (compact) return Column(children: [fields[0], const SizedBox(height: 10), fields[1], const SizedBox(height: 10), fields[2]]);
                    return Row(children: [Expanded(child: fields[0]), const SizedBox(width: 10), Expanded(child: fields[1]), const SizedBox(width: 10), Expanded(child: fields[2])]);
                  }),
                  const SizedBox(height: 10),
                  TextFormField(
                    controller: _body,
                    minLines: 7,
                    maxLines: 14,
                    maxLength: 20000,
                    decoration: _fieldDecoration('Announcement message', Icons.notes_rounded).copyWith(alignLabelWithHint: true, hintText: 'Write the full notice clearly and professionally...'),
                    validator: (value) => value == null || value.trim().length < 10 ? 'Write a meaningful announcement.' : null,
                  ),
                  const SizedBox(height: 14),
                  SwitchListTile.adaptive(
                    value: _pinned,
                    contentPadding: EdgeInsets.zero,
                    title: const Text('Pin this announcement', style: TextStyle(fontWeight: FontWeight.w800)),
                    subtitle: const Text('Pinned notices stay above normal announcements.'),
                    activeColor: _green,
                    onChanged: (value) => setState(() => _pinned = value),
                  ),
                  const SizedBox(height: 8),
                  _section('SCHEDULING & EXPIRY'),
                  const SizedBox(height: 10),
                  Wrap(spacing: 10, runSpacing: 10, children: [
                    OutlinedButton.icon(
                      onPressed: () async {
                        final value = await _pickDateTime(_scheduledAt ?? DateTime.now().add(const Duration(hours: 1)));
                        if (value != null) setState(() => _scheduledAt = value);
                      },
                      icon: const Icon(Icons.schedule_rounded),
                      label: Text(_scheduledAt == null ? 'Set schedule' : _formatDateTime(_scheduledAt!)),
                    ),
                    if (_scheduledAt != null) IconButton(onPressed: () => setState(() => _scheduledAt = null), icon: const Icon(Icons.close_rounded)),
                    OutlinedButton.icon(
                      onPressed: () async {
                        final value = await _pickDateTime(_expiresAt ?? DateTime.now().add(const Duration(days: 7)));
                        if (value != null) setState(() => _expiresAt = value);
                      },
                      icon: const Icon(Icons.timer_outlined),
                      label: Text(_expiresAt == null ? 'Set expiry' : _formatDateTime(_expiresAt!)),
                    ),
                    if (_expiresAt != null) IconButton(onPressed: () => setState(() => _expiresAt = null), icon: const Icon(Icons.close_rounded)),
                  ]),
                  const SizedBox(height: 18),
                  _section('MEDIA'),
                  const SizedBox(height: 8),
                  const Text('Attach up to 6 pictures and one optional video up to 10 MB. The feed shows one lead picture with +N for additional images.', style: TextStyle(fontSize: 11.3, color: _muted, height: 1.5)),
                  const SizedBox(height: 10),
                  if (_images.isNotEmpty)
                    Wrap(spacing: 8, runSpacing: 8, children: _images.asMap().entries.map((entry) => SizedBox(
                      width: 125,
                      height: 90,
                      child: Stack(fit: StackFit.expand, children: [
                        ClipRRect(borderRadius: BorderRadius.circular(13), child: Image.memory(entry.value.bytes, fit: BoxFit.cover)),
                        Positioned(top: 5, right: 5, child: InkWell(onTap: () => setState(() => _images.removeAt(entry.key)), child: Container(padding: const EdgeInsets.all(4), decoration: const BoxDecoration(color: Colors.black54, shape: BoxShape.circle), child: const Icon(Icons.close, color: Colors.white, size: 14)))),
                      ]),
                    )).toList()),
                  if (_images.isNotEmpty) const SizedBox(height: 10),
                  Wrap(spacing: 10, runSpacing: 10, children: [
                    OutlinedButton.icon(onPressed: _images.length >= 6 ? null : _pickImages, icon: const Icon(Icons.add_photo_alternate_outlined), label: Text('Add photos (${_images.length}/6)')),
                    OutlinedButton.icon(onPressed: _video == null ? _pickVideo : null, icon: const Icon(Icons.video_library_outlined), label: Text(_video == null ? 'Add video' : _videoLabel)),
                    if (_video != null) IconButton(onPressed: () => setState(() { _video = null; _videoLabel = ''; }), icon: const Icon(Icons.close_rounded)),
                  ]),
                ]),
              ),
            ),
          ),
          Container(
            padding: const EdgeInsets.all(14),
            decoration: const BoxDecoration(color: Color(0xFFF7F9FB), borderRadius: BorderRadius.vertical(bottom: Radius.circular(26))),
            child: LayoutBuilder(builder: (context, constraints) {
              final compact = constraints.maxWidth < 650;
              final buttons = <Widget>[
                OutlinedButton.icon(onPressed: _saving || _me == null ? null : () => _save('draft'), icon: const Icon(Icons.save_outlined), label: const Text('Save draft')),
                OutlinedButton.icon(onPressed: _saving || _me == null || _scheduledAt == null ? null : () => _save('scheduled'), icon: const Icon(Icons.schedule_send_rounded), label: const Text('Schedule')),
                FilledButton.icon(onPressed: _saving || _me == null ? null : () => _save('published'), style: FilledButton.styleFrom(backgroundColor: _green), icon: _saving ? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white)) : const Icon(Icons.campaign_rounded), label: const Text('Publish')),
              ];
              if (compact) return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [buttons[0], const SizedBox(height: 8), buttons[1], const SizedBox(height: 8), buttons[2]]);
              return Row(mainAxisAlignment: MainAxisAlignment.end, children: [buttons[0], const SizedBox(width: 8), buttons[1], const SizedBox(width: 8), buttons[2]]);
            }),
          ),
        ]),
      ),
    );
  }

  Widget _authorPanel() {
    if (_loadingAccount) return const Center(child: CircularProgressIndicator(color: _green));
    if (_accountError != null || _me == null) {
      return Container(
        padding: const EdgeInsets.all(13),
        decoration: BoxDecoration(color: Colors.red.shade50, borderRadius: BorderRadius.circular(15)),
        child: Row(children: [const Icon(Icons.error_outline, color: Colors.red), const SizedBox(width: 10), Expanded(child: Text(_accountError ?? 'Unable to identify account.')), TextButton(onPressed: _loadAccount, child: const Text('Retry'))]),
      );
    }
    return Container(
      padding: const EdgeInsets.all(13),
      decoration: BoxDecoration(color: _green.withOpacity(.05), borderRadius: BorderRadius.circular(16), border: Border.all(color: _green.withOpacity(.16))),
      child: Row(children: [
        _AnnouncementAvatar(value: '${_me!['profile_picture'] ?? ''}', size: 46),
        const SizedBox(width: 11),
        Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Text('${_me!['full_name'] ?? 'Rockview User'}', style: const TextStyle(fontWeight: FontWeight.w900)),
          const SizedBox(height: 3),
          Text('${_me!['campus'] ?? 'University Wide'}', style: const TextStyle(color: _green, fontWeight: FontWeight.w800)),
        ])),
        const Icon(Icons.lock_outline_rounded, color: _green),
      ]),
    );
  }

  Widget _section(String text) => Row(children: [Container(width: 5, height: 17, decoration: BoxDecoration(color: _gold, borderRadius: BorderRadius.circular(999))), const SizedBox(width: 7), Text(text, style: const TextStyle(fontSize: 10.5, color: _dark, fontWeight: FontWeight.w900, letterSpacing: .8))]);
}

class AnnouncementConversationDialog extends StatefulWidget {
  final CampusAnnouncement announcement;
  const AnnouncementConversationDialog({super.key, required this.announcement});

  @override
  State<AnnouncementConversationDialog> createState() => _AnnouncementConversationDialogState();
}

class _AnnouncementConversationDialogState extends State<AnnouncementConversationDialog> {
  final TextEditingController _controller = TextEditingController();
  late CampusAnnouncement _announcement;
  List<CampusAnnouncementComment> _comments = [];
  List<AnnouncementMentionableUser> _mentionUsers = [];
  final Map<int, AnnouncementMentionableUser> _selectedMentions = {};
  CampusAnnouncementComment? _replyingTo;
  bool _loading = true;
  bool _posting = false;
  String? _error;

  @override
  void initState() {
    super.initState();
    _announcement = widget.announcement;
    _load();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  Future<void> _load() async {
    try {
      final result = await Future.wait<dynamic>([
        CampusAnnouncementsService.getComments(_announcement.id),
        CampusAnnouncementsService.getMentionableUsers(_announcement.id),
      ]);
      if (!mounted) return;
      final comments = List<CampusAnnouncementComment>.from(result[0] as List);
      setState(() {
        _comments = comments;
        _mentionUsers = List<AnnouncementMentionableUser>.from(result[1] as List);
        _announcement = _announcement.copyWith(commentCount: comments.length);
        _loading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _loading = false;
        _error = _cleanError(e);
      });
    }
  }

  Future<void> _pickMention() async {
    final user = await showModalBottomSheet<AnnouncementMentionableUser>(
      context: context,
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      builder: (_) => _MentionPicker(users: _mentionUsers),
    );
    if (user == null) return;
    final next = '${_controller.text}${_controller.text.isEmpty ? '' : ' '}@${user.fullName} ';
    _controller.value = TextEditingValue(text: next, selection: TextSelection.collapsed(offset: next.length));
    setState(() => _selectedMentions[user.id] = user);
  }

  Future<void> _post() async {
    final text = _controller.text.trim();
    if (text.isEmpty || _posting) return;
    setState(() => _posting = true);
    try {
      final parentId = _replyingTo == null ? null : (_replyingTo!.parentCommentId ?? _replyingTo!.id);
      final created = await CampusAnnouncementsService.addComment(
        _announcement.id,
        text,
        parentCommentId: parentId,
        mentionUserIds: _selectedMentions.keys.toList(),
      );
      if (!mounted) return;
      setState(() {
        _comments.add(created);
        _announcement = _announcement.copyWith(commentCount: _comments.length);
        _controller.clear();
        _replyingTo = null;
        _selectedMentions.clear();
        _posting = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() => _posting = false);
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(_cleanError(e)), backgroundColor: Colors.red.shade700));
    }
  }

  @override
  Widget build(BuildContext context) {
    final parents = _comments.where((c) => c.parentCommentId == null).toList();
    final replies = <int, List<CampusAnnouncementComment>>{};
    for (final c in _comments.where((c) => c.parentCommentId != null)) {
      replies.putIfAbsent(c.parentCommentId!, () => []).add(c);
    }

    return Dialog(
      insetPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 14),
      backgroundColor: Colors.transparent,
      child: Container(
        constraints: BoxConstraints(maxWidth: 1000, maxHeight: MediaQuery.of(context).size.height * .94),
        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(26)),
        child: Column(children: [
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 17, vertical: 13),
            decoration: const BoxDecoration(color: _green, borderRadius: BorderRadius.vertical(top: Radius.circular(26))),
            child: Row(children: [const Icon(Icons.forum_rounded, color: Colors.white), const SizedBox(width: 9), const Expanded(child: Text('Announcement Discussion', style: TextStyle(color: Colors.white, fontWeight: FontWeight.w900))), IconButton(onPressed: () => Navigator.pop(context, _announcement), icon: const Icon(Icons.close_rounded, color: Colors.white))]),
          ),
          Expanded(
            child: LayoutBuilder(builder: (context, constraints) {
              final wide = constraints.maxWidth >= 820;
              final commentsPane = Column(children: [
                Expanded(
                  child: _loading
                      ? const Center(child: CircularProgressIndicator(color: _green))
                      : _error != null
                          ? Center(child: Padding(padding: const EdgeInsets.all(20), child: Text(_error!, textAlign: TextAlign.center)))
                          : parents.isEmpty
                              ? const Center(child: Text('No comments yet.\nStart the discussion.', textAlign: TextAlign.center, style: TextStyle(color: _muted)))
                              : ListView.separated(
                                  padding: const EdgeInsets.all(12),
                                  itemCount: parents.length,
                                  separatorBuilder: (_, __) => const SizedBox(height: 10),
                                  itemBuilder: (_, index) {
                                    final parent = parents[index];
                                    return _CommentThread(comment: parent, replies: replies[parent.id] ?? const [], onReply: (c) => setState(() => _replyingTo = c));
                                  },
                                ),
                ),
                if (_replyingTo != null)
                  Container(
                    margin: const EdgeInsets.fromLTRB(10, 0, 10, 7),
                    padding: const EdgeInsets.symmetric(horizontal: 11, vertical: 8),
                    decoration: BoxDecoration(color: _green.withOpacity(.06), borderRadius: BorderRadius.circular(13)),
                    child: Row(children: [Expanded(child: Text('Replying to ${_replyingTo!.authorName}', style: const TextStyle(color: _green, fontWeight: FontWeight.w800))), IconButton(onPressed: () => setState(() => _replyingTo = null), icon: const Icon(Icons.close, size: 17))]),
                  ),
                Container(
                  padding: const EdgeInsets.all(10),
                  decoration: BoxDecoration(border: Border(top: BorderSide(color: Colors.grey.shade200))),
                  child: Column(children: [
                    if (_selectedMentions.isNotEmpty)
                      Align(alignment: Alignment.centerLeft, child: Wrap(spacing: 6, children: _selectedMentions.values.map((u) => Chip(label: Text('@${u.fullName}', style: const TextStyle(fontSize: 10)), onDeleted: () => setState(() => _selectedMentions.remove(u.id)))).toList())),
                    if (_selectedMentions.isNotEmpty) const SizedBox(height: 6),
                    Row(crossAxisAlignment: CrossAxisAlignment.end, children: [
                      Expanded(child: TextField(controller: _controller, minLines: 1, maxLines: 4, maxLength: 1000, decoration: InputDecoration(counterText: '', hintText: _replyingTo == null ? 'Write a comment...' : 'Write your reply...', filled: true, fillColor: const Color(0xFFF7F9FB), border: OutlineInputBorder(borderRadius: BorderRadius.circular(14), borderSide: const BorderSide(color: _border))))),
                      const SizedBox(width: 7),
                      SizedBox(width: 44, height: 46, child: OutlinedButton(onPressed: _pickMention, style: OutlinedButton.styleFrom(padding: EdgeInsets.zero, foregroundColor: _green), child: const Text('@', style: TextStyle(fontWeight: FontWeight.w900, fontSize: 18)))),
                      const SizedBox(width: 7),
                      SizedBox(width: 48, height: 46, child: FilledButton(onPressed: _posting ? null : _post, style: FilledButton.styleFrom(backgroundColor: _green, padding: EdgeInsets.zero), child: _posting ? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white)) : const Icon(Icons.send_rounded))),
                    ]),
                  ]),
                ),
              ]);
              if (!wide) return commentsPane;
              return Row(children: [
                Expanded(
                  flex: 6,
                  child: SingleChildScrollView(
                    padding: const EdgeInsets.all(20),
                    child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                      Row(children: [
                        _AnnouncementAvatar(value: _announcement.authorProfilePicture, size: 46),
                        const SizedBox(width: 10),
                        Expanded(child: Text(_announcement.authorName, style: const TextStyle(fontWeight: FontWeight.w900))),
                        _PriorityChip(priority: _announcement.priority),
                      ]),
                      const SizedBox(height: 16),
                      Text(_announcement.title, style: const TextStyle(fontSize: 22, fontWeight: FontWeight.w900, height: 1.25)),
                      const SizedBox(height: 10),
                      Text(_announcement.body, style: const TextStyle(fontSize: 13.2, color: Color(0xFF4F5C69), height: 1.65)),
                    ]),
                  ),
                ),
                VerticalDivider(width: 1, color: Colors.grey.shade300),
                Expanded(flex: 5, child: commentsPane),
              ]);
            }),
          ),
        ]),
      ),
    );
  }
}

class _CommentThread extends StatelessWidget {
  final CampusAnnouncementComment comment;
  final List<CampusAnnouncementComment> replies;
  final ValueChanged<CampusAnnouncementComment> onReply;
  const _CommentThread({required this.comment, required this.replies, required this.onReply});

  @override
  Widget build(BuildContext context) {
    return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      _CommentBubble(comment: comment, onReply: () => onReply(comment)),
      if (replies.isNotEmpty)
        Padding(
          padding: const EdgeInsets.only(left: 28, top: 8),
          child: Column(children: replies.map((reply) => Padding(padding: const EdgeInsets.only(bottom: 8), child: _CommentBubble(comment: reply, onReply: () => onReply(reply)))).toList()),
        ),
    ]);
  }
}

class _CommentBubble extends StatelessWidget {
  final CampusAnnouncementComment comment;
  final VoidCallback onReply;
  const _CommentBubble({required this.comment, required this.onReply});

  @override
  Widget build(BuildContext context) {
    return Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
      _AnnouncementAvatar(value: comment.authorProfilePicture, size: 35),
      const SizedBox(width: 8),
      Expanded(
        child: Container(
          padding: const EdgeInsets.all(10),
          decoration: BoxDecoration(color: const Color(0xFFF7F9FB), borderRadius: BorderRadius.circular(14), border: Border.all(color: _border)),
          child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Row(children: [Expanded(child: Text(comment.authorName, style: const TextStyle(fontSize: 11.5, fontWeight: FontWeight.w900))), Text(_timeAgo(comment.createdAt), style: const TextStyle(fontSize: 9, color: Color(0xFF98A2AD)))]),
            const SizedBox(height: 5),
            _MentionText(text: comment.comment),
            const SizedBox(height: 6),
            TextButton.icon(onPressed: onReply, style: TextButton.styleFrom(padding: EdgeInsets.zero, minimumSize: Size.zero, tapTargetSize: MaterialTapTargetSize.shrinkWrap, foregroundColor: _green), icon: const Icon(Icons.reply_rounded, size: 14), label: const Text('Reply', style: TextStyle(fontSize: 10.5, fontWeight: FontWeight.w800))),
          ]),
        ),
      ),
    ]);
  }
}

class _MentionPicker extends StatefulWidget {
  final List<AnnouncementMentionableUser> users;
  const _MentionPicker({required this.users});

  @override
  State<_MentionPicker> createState() => _MentionPickerState();
}

class _MentionPickerState extends State<_MentionPicker> {
  final TextEditingController _search = TextEditingController();
  late List<AnnouncementMentionableUser> _filtered;

  @override
  void initState() {
    super.initState();
    _filtered = widget.users;
    _search.addListener(_filter);
  }

  void _filter() {
    final q = _search.text.trim().toLowerCase();
    setState(() => _filtered = widget.users.where((u) => u.fullName.toLowerCase().contains(q) || u.campus.toLowerCase().contains(q)).toList());
  }

  @override
  void dispose() {
    _search.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Container(
        height: MediaQuery.of(context).size.height * .68,
        decoration: const BoxDecoration(color: Colors.white, borderRadius: BorderRadius.vertical(top: Radius.circular(26))),
        child: Column(children: [
          const SizedBox(height: 10),
          Container(width: 44, height: 5, decoration: BoxDecoration(color: const Color(0xFFD8DEE7), borderRadius: BorderRadius.circular(999))),
          const Padding(padding: EdgeInsets.all(18), child: Align(alignment: Alignment.centerLeft, child: Text('Mention Member', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w900)))),
          Padding(padding: const EdgeInsets.symmetric(horizontal: 18), child: TextField(controller: _search, decoration: InputDecoration(hintText: 'Search member...', prefixIcon: const Icon(Icons.search), border: OutlineInputBorder(borderRadius: BorderRadius.circular(14))))),
          const SizedBox(height: 10),
          Expanded(child: ListView.separated(
            padding: const EdgeInsets.all(18),
            itemCount: _filtered.length,
            separatorBuilder: (_, __) => const SizedBox(height: 7),
            itemBuilder: (_, index) {
              final user = _filtered[index];
              return ListTile(
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14), side: const BorderSide(color: _border)),
                leading: _AnnouncementAvatar(value: user.profilePicture, size: 40),
                title: Text(user.fullName, style: const TextStyle(fontWeight: FontWeight.w800)),
                subtitle: Text('${_roleLabel(user.role)} • ${user.campus}'),
                onTap: () => Navigator.pop(context, user),
              );
            },
          )),
        ]),
      ),
    );
  }
}

class _AnnouncementNotificationsSheet extends StatelessWidget {
  final List<CampusAnnouncementNotification> items;
  final int unread;
  final Future<void> Function(CampusAnnouncementNotification) onRead;
  final Future<void> Function() onReadAll;
  const _AnnouncementNotificationsSheet({required this.items, required this.unread, required this.onRead, required this.onReadAll});

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Container(
        height: MediaQuery.of(context).size.height * .82,
        decoration: const BoxDecoration(color: Colors.white, borderRadius: BorderRadius.vertical(top: Radius.circular(28))),
        child: Column(children: [
          const SizedBox(height: 10),
          Container(width: 44, height: 5, decoration: BoxDecoration(color: const Color(0xFFD8DEE7), borderRadius: BorderRadius.circular(999))),
          Padding(
            padding: const EdgeInsets.all(18),
            child: Row(children: [
              Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [const Text('Announcement Notifications', style: TextStyle(fontSize: 19, fontWeight: FontWeight.w900)), const SizedBox(height: 3), Text('$unread unread', style: const TextStyle(color: _muted, fontSize: 11))])),
              if (unread > 0) TextButton.icon(onPressed: () async { await onReadAll(); if (context.mounted) Navigator.pop(context); }, icon: const Icon(Icons.done_all), label: const Text('Mark all read')),
            ]),
          ),
          Expanded(
            child: items.isEmpty
                ? const Center(child: Text('No announcement notifications yet.'))
                : ListView.separated(
                    padding: const EdgeInsets.fromLTRB(16, 0, 16, 20),
                    itemCount: items.length,
                    separatorBuilder: (_, __) => const SizedBox(height: 8),
                    itemBuilder: (_, index) {
                      final item = items[index];
                      return InkWell(
                        onTap: () async { await onRead(item); if (context.mounted) Navigator.pop(context); },
                        borderRadius: BorderRadius.circular(16),
                        child: Container(
                          padding: const EdgeInsets.all(12),
                          decoration: BoxDecoration(color: item.isRead ? const Color(0xFFF9FAFB) : _green.withOpacity(.06), borderRadius: BorderRadius.circular(16), border: Border.all(color: _border)),
                          child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
                            _AnnouncementAvatar(value: item.actorProfilePicture, size: 40),
                            const SizedBox(width: 10),
                            Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text(item.title, style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w900)), const SizedBox(height: 4), Text(item.message, style: const TextStyle(fontSize: 11, color: _muted, height: 1.45)), const SizedBox(height: 4), Text(_timeAgo(item.createdAt), style: const TextStyle(fontSize: 9.5, color: Color(0xFF9AA4AF)))])),
                            if (!item.isRead) Container(width: 8, height: 8, decoration: const BoxDecoration(color: _gold, shape: BoxShape.circle)),
                          ]),
                        ),
                      );
                    },
                  ),
          ),
        ]),
      ),
    );
  }
}

class _AnnouncementBell extends StatelessWidget {
  final int unread;
  final VoidCallback onTap;
  const _AnnouncementBell({required this.unread, required this.onTap});

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(14),
      child: Container(
        width: 46,
        height: 46,
        decoration: BoxDecoration(color: const Color(0xFFF7F9FB), borderRadius: BorderRadius.circular(14), border: Border.all(color: _border)),
        child: Stack(clipBehavior: Clip.none, children: [
          const Center(child: Icon(Icons.notifications_none_rounded, color: _green)),
          if (unread > 0)
            Positioned(top: -4, right: -4, child: Container(constraints: const BoxConstraints(minWidth: 20, minHeight: 20), padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2), decoration: BoxDecoration(color: Colors.red.shade600, borderRadius: BorderRadius.circular(999)), child: Text(unread > 99 ? '99+' : '$unread', textAlign: TextAlign.center, style: const TextStyle(color: Colors.white, fontSize: 9, fontWeight: FontWeight.w900)))),
        ]),
      ),
    );
  }
}

class _SocialButton extends StatelessWidget {
  final IconData icon;
  final String label;
  final bool active;
  final VoidCallback onTap;
  const _SocialButton({required this.icon, required this.label, required this.onTap, this.active = false});

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(999),
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 8),
        child: Row(mainAxisSize: MainAxisSize.min, children: [Icon(icon, size: 17, color: active ? Colors.red.shade600 : _muted), if (label.isNotEmpty) ...[const SizedBox(width: 5), Text(label, style: TextStyle(fontSize: 10.8, fontWeight: FontWeight.w800, color: active ? Colors.red.shade700 : _muted))]]),
      ),
    );
  }
}

class _PriorityChip extends StatelessWidget {
  final String priority;
  const _PriorityChip({required this.priority});

  @override
  Widget build(BuildContext context) {
    final p = priority.toLowerCase();
    final color = p == 'urgent' ? Colors.red.shade700 : p == 'important' ? Colors.orange.shade700 : _green;
    return Container(padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5), decoration: BoxDecoration(color: color.withOpacity(.09), borderRadius: BorderRadius.circular(999), border: Border.all(color: color.withOpacity(.2))), child: Text(priority.toUpperCase(), style: TextStyle(color: color, fontSize: 8.5, fontWeight: FontWeight.w900, letterSpacing: .6)));
  }
}

class _CategoryChip extends StatelessWidget {
  final String label;
  const _CategoryChip({required this.label});
  @override
  Widget build(BuildContext context) => Container(padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5), decoration: BoxDecoration(color: _gold.withOpacity(.1), borderRadius: BorderRadius.circular(999)), child: Text(label.toUpperCase(), style: const TextStyle(color: _gold, fontSize: 8.5, fontWeight: FontWeight.w900, letterSpacing: .5)));
}

class _AudienceChip extends StatelessWidget {
  final String label;
  const _AudienceChip({required this.label});
  @override
  Widget build(BuildContext context) => Container(padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5), decoration: BoxDecoration(color: const Color(0xFFF4F6F8), borderRadius: BorderRadius.circular(999)), child: Text(label, style: const TextStyle(color: _muted, fontSize: 8.8, fontWeight: FontWeight.w800)));
}

class _AnnouncementAvatar extends StatelessWidget {
  final String value;
  final double size;
  const _AnnouncementAvatar({required this.value, required this.size});

  @override
  Widget build(BuildContext context) {
    final trimmed = value.trim();
    Widget child;
    if (trimmed.isEmpty) {
      child = _fallback();
    } else if (trimmed.startsWith('http://') || trimmed.startsWith('https://') || CampusAnnouncementsService.isStoredMediaPath(trimmed)) {
      child = Image.network(CampusAnnouncementsService.mediaUrl(trimmed), fit: BoxFit.cover, errorBuilder: (_, __, ___) => _fallback());
    } else {
      try {
        var raw = trimmed;
        if (raw.startsWith('data:image') && raw.contains(',')) raw = raw.substring(raw.indexOf(',') + 1);
        child = Image.memory(base64Decode(raw), fit: BoxFit.cover, errorBuilder: (_, __, ___) => _fallback());
      } catch (_) {
        child = _fallback();
      }
    }
    return Container(width: size, height: size, clipBehavior: Clip.antiAlias, decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: _gold.withOpacity(.45), width: 1.5)), child: child);
  }

  Widget _fallback() => Container(color: const Color(0xFFF1F3F5), alignment: Alignment.center, child: Icon(Icons.person_rounded, size: size * .52, color: Colors.grey.shade400));
}

class _AnnouncementNetworkImage extends StatelessWidget {
  final String path;
  const _AnnouncementNetworkImage({required this.path});
  @override
  Widget build(BuildContext context) => Image.network(
        CampusAnnouncementsService.mediaUrl(path),
        fit: BoxFit.cover,
        cacheWidth: 1200,
        loadingBuilder: (_, child, loading) => loading == null ? child : Container(color: const Color(0xFFF0F2F4), alignment: Alignment.center, child: const CircularProgressIndicator(color: _green, strokeWidth: 2)),
        errorBuilder: (_, __, ___) => Container(color: const Color(0xFFF0F2F4), alignment: Alignment.center, child: const Icon(Icons.broken_image_outlined, color: Colors.grey)),
      );
}

class _MentionText extends StatelessWidget {
  final String text;
  const _MentionText({required this.text});
  @override
  Widget build(BuildContext context) {
    final words = text.split(' ');
    return Wrap(spacing: 3, runSpacing: 2, children: words.map((word) => Text(word, style: TextStyle(fontSize: 11.5, height: 1.4, color: word.startsWith('@') ? _green : const Color(0xFF42515F), fontWeight: word.startsWith('@') ? FontWeight.w900 : FontWeight.normal))).toList());
  }
}

BoxDecoration _panelDecoration({double radius = 20}) => BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(radius), border: Border.all(color: _border), boxShadow: [BoxShadow(color: Colors.black.withOpacity(.025), blurRadius: 10, offset: const Offset(0, 4))]);

InputDecoration _inputDecoration() => InputDecoration(filled: true, fillColor: const Color(0xFFF7F9FB), contentPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 11), border: OutlineInputBorder(borderRadius: BorderRadius.circular(13), borderSide: const BorderSide(color: _border)), enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(13), borderSide: const BorderSide(color: _border)));

InputDecoration _fieldDecoration(String label, IconData icon) => InputDecoration(labelText: label, prefixIcon: Icon(icon, color: _green), filled: true, fillColor: const Color(0xFFF7F9FB), border: OutlineInputBorder(borderRadius: BorderRadius.circular(15), borderSide: const BorderSide(color: _border)), enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(15), borderSide: const BorderSide(color: _border)), focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(15), borderSide: const BorderSide(color: _green, width: 1.3)));

String _timeAgo(DateTime value) {
  final diff = DateTime.now().difference(value.toLocal());
  if (diff.inMinutes < 1) return 'just now';
  if (diff.inHours < 1) return '${diff.inMinutes}m ago';
  if (diff.inDays < 1) return '${diff.inHours}h ago';
  if (diff.inDays < 7) return '${diff.inDays}d ago';
  return _formatDateTime(value);
}

String _formatDateTime(DateTime value) {
  final d = value.toLocal();
  return '${d.day.toString().padLeft(2, '0')}/${d.month.toString().padLeft(2, '0')}/${d.year} ${d.hour.toString().padLeft(2, '0')}:${d.minute.toString().padLeft(2, '0')}';
}

String _roleLabel(String role) {
  final v = role.trim().toLowerCase().replaceAll('_', ' ');
  if (v.isEmpty) return 'Member';
  return v.split(' ').where((p) => p.isNotEmpty).map((p) => '${p[0].toUpperCase()}${p.substring(1)}').join(' ');
}

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

bool _bool(dynamic value) {
  if (value is bool) return value;
  if (value is num) return value != 0;
  final text = '${value ?? ''}'.trim().toLowerCase();
  return text == '1' || text == 'true' || text == 't' || text == 'yes';
}
