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_events_service.dart';

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

class CampusEventsFeedView extends StatefulWidget {
  final String scope;
  final bool allowCreate;

  const CampusEventsFeedView({
    super.key,
    required this.scope,
    required this.allowCreate,
  });

  @override
  State<CampusEventsFeedView> createState() => _CampusEventsFeedViewState();
}

class _CampusEventsFeedViewState extends State<CampusEventsFeedView> {
  final ScrollController _scrollController = ScrollController();
  final TextEditingController _searchController = TextEditingController();

  final List<CampusEvent> _events = <CampusEvent>[];
  List<String> _campuses = const <String>[];
  List<CampusEventNotification> _notifications = const <CampusEventNotification>[];

  String _selectedCampus = 'All Campuses';
  bool _loading = true;
  bool _loadingMore = false;
  bool _hasMore = true;
  String? _error;
  int _page = 1;
  int _unread = 0;
  Timer? _refreshTimer;

  static const int _pageSize = 8;

  bool get _isPast => widget.scope == 'past';

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

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

  Future<void> _loadInitial() async {
    setState(() {
      _loading = true;
      _error = null;
      _page = 1;
      _hasMore = true;
      _events.clear();
    });

    try {
      final results = await Future.wait<dynamic>(<Future<dynamic>>[
        CampusEventsService.getCampuses(),
        CampusEventsService.getEvents(
          scope: widget.scope,
          campus: _selectedCampus,
          search: _searchController.text,
          page: 1,
          limit: _pageSize,
        ),
        CampusEventsService.getNotifications(limit: 30),
      ]);

      if (!mounted) return;
      final page = results[1] as CampusEventPage;
      final notifications = results[2] as CampusEventNotificationPage;
      setState(() {
        _campuses = List<String>.from(results[0] as List);
        _events.addAll(page.events);
        _hasMore = page.hasMore;
        _notifications = notifications.items;
        _unread = notifications.unreadCount;
        _loading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _loading = false;
        _error = _cleanError(e);
      });
    }
  }

  Future<void> _refresh() async {
    try {
      final results = await Future.wait<dynamic>(<Future<dynamic>>[
        CampusEventsService.getEvents(
          scope: widget.scope,
          campus: _selectedCampus,
          search: _searchController.text,
          page: 1,
          limit: _pageSize,
        ),
        CampusEventsService.getNotifications(limit: 30),
      ]);
      if (!mounted) return;
      final page = results[0] as CampusEventPage;
      final notifications = results[1] as CampusEventNotificationPage;
      setState(() {
        _events
          ..clear()
          ..addAll(page.events);
        _hasMore = page.hasMore;
        _page = 1;
        _notifications = notifications.items;
        _unread = notifications.unreadCount;
        _error = null;
        _loading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() => _error = _cleanError(e));
    }
  }

  Future<void> _silentRefresh() async {
    if (!mounted || _loading || _loadingMore) return;
    if (_scrollController.hasClients && _scrollController.offset > 260) return;
    try {
      final page = await CampusEventsService.getEvents(
        scope: widget.scope,
        campus: _selectedCampus,
        search: _searchController.text,
        page: 1,
        limit: _pageSize,
      );
      final notifications = await CampusEventsService.getNotifications(limit: 30);
      if (!mounted) return;
      final oldById = <int, CampusEvent>{for (final item in _events) item.id: item};
      for (final incoming in page.events) {
        oldById[incoming.id] = incoming;
      }
      final merged = oldById.values.toList();
      if (_isPast) {
        merged.sort((a, b) => b.eventDate.compareTo(a.eventDate));
      } else {
        merged.sort((a, b) => b.createdAt.compareTo(a.createdAt));
      }
      setState(() {
        _events
          ..clear()
          ..addAll(merged);
        _notifications = notifications.items;
        _unread = notifications.unreadCount;
      });
    } catch (_) {}
  }

  Future<void> _loadMore() async {
    if (_loading || _loadingMore || !_hasMore) return;
    setState(() => _loadingMore = true);
    final next = _page + 1;
    try {
      final page = await CampusEventsService.getEvents(
        scope: widget.scope,
        campus: _selectedCampus,
        search: _searchController.text,
        page: next,
        limit: _pageSize,
      );
      if (!mounted) return;
      setState(() {
        _events.addAll(page.events);
        _hasMore = page.hasMore;
        _page = next;
        _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> _createEvent() async {
    final result = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (_) => const EventComposerDialog(),
    );
    if (result == true) await _refresh();
  }

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

  Future<void> _openConversation(int index) async {
    final result = await showDialog<CampusEvent>(
      context: context,
      barrierDismissible: true,
      builder: (_) => EventConversationDialog(event: _events[index]),
    );
    if (result != null && mounted) {
      setState(() => _events[index] = result);
      _refreshNotifications();
    }
  }

  Future<void> _share(CampusEvent event) async {
    final text = '${event.title}\n${_formatDate(event.eventDate)}\n${event.location}\n\n${event.description}';
    await Clipboard.setData(ClipboardData(text: text));
    if (mounted) _snack('Event details copied.');
  }

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

  Future<void> _openNotifications() async {
    await showModalBottomSheet<void>(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (_) => _EventNotificationsSheet(
        notifications: _notifications,
        unreadCount: _unread,
        onRead: (item) async {
          if (!item.isRead) {
            await CampusEventsService.markNotificationRead(item.id);
            await _refreshNotifications();
          }
        },
        onMarkAll: () async {
          await CampusEventsService.markAllNotificationsRead();
          await _refreshNotifications();
        },
      ),
    );
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      floatingActionButton: widget.allowCreate
          ? FloatingActionButton.extended(
              onPressed: _createEvent,
              backgroundColor: _gold,
              foregroundColor: Colors.white,
              icon: const Icon(Icons.add_rounded),
              label: const Text('CREATE EVENT', style: TextStyle(fontWeight: FontWeight.w900)),
            )
          : null,
      body: LayoutBuilder(builder: (context, constraints) {
        final desktop = constraints.maxWidth >= 1180;
        final tablet = constraints.maxWidth >= 860 && constraints.maxWidth < 1180;
        return Container(
          color: _pageBg,
          child: 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: 250, child: _rightPanel()),
              if (tablet) SizedBox(width: 205, child: _tabletPanel()),
            ],
          ),
        );
      }),
    );
  }

  Widget _leftPanel() {
    return ListView(
      padding: const EdgeInsets.only(top: 12, bottom: 96),
      children: [
        Container(
          padding: const EdgeInsets.all(16),
          decoration: _panelDecoration(),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(_isPast ? 'EVENT ARCHIVE' : 'EVENTS HUB', style: const TextStyle(color: _green, fontSize: 11, fontWeight: FontWeight.w900, letterSpacing: 1.2)),
              if (widget.allowCreate) ...[
                const SizedBox(height: 14),
                FilledButton.icon(
                  onPressed: _createEvent,
                  style: FilledButton.styleFrom(
                    minimumSize: const Size(double.infinity, 46),
                    backgroundColor: _green,
                    foregroundColor: Colors.white,
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
                  ),
                  icon: const Icon(Icons.add_rounded),
                  label: const Text('Create Event', style: TextStyle(fontWeight: FontWeight.w900)),
                ),
              ],
              const SizedBox(height: 20),
              const Text('CAMPUS', style: TextStyle(fontSize: 10, color: _muted, fontWeight: FontWeight.w900, letterSpacing: .8)),
              const SizedBox(height: 8),
              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),
              OutlinedButton.icon(
                onPressed: _loadInitial,
                style: OutlinedButton.styleFrom(minimumSize: const Size(double.infinity, 44), foregroundColor: _green),
                icon: const Icon(Icons.refresh_rounded),
                label: const Text('Refresh'),
              ),
            ],
          ),
        ),
        const SizedBox(height: 12),
        Container(
          padding: const EdgeInsets.all(15),
          decoration: BoxDecoration(
            color: _green.withOpacity(.045),
            borderRadius: BorderRadius.circular(20),
            border: Border.all(color: _green.withOpacity(.14)),
          ),
          child: Text(
            _isPast
                ? 'Past events remain available for discussion, likes and replies.'
                : 'Publish professional campus events and keep the community engaged in one place.',
            style: const TextStyle(color: _muted, fontSize: 11.5, height: 1.55),
          ),
        ),
      ],
    );
  }

  Widget _rightPanel() {
    return ListView(
      padding: const EdgeInsets.only(top: 12, bottom: 96),
      children: [
        Container(
          padding: const EdgeInsets.all(15),
          decoration: _panelDecoration(),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(children: [
                const Expanded(child: Text('Event activity', style: TextStyle(fontWeight: FontWeight.w900))),
                _EventBell(unread: _unread, onTap: _openNotifications),
              ]),
              const SizedBox(height: 12),
              Text(_unread == 1 ? '1 unread notification' : '$_unread unread notifications', style: const TextStyle(color: _muted, fontSize: 11)),
              if (_notifications.isNotEmpty) ...[
                const SizedBox(height: 12),
                const Divider(),
                ..._notifications.take(3).map((item) => Padding(
                      padding: const EdgeInsets.only(top: 10),
                      child: Text(item.title, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 10.8, fontWeight: FontWeight.w800)),
                    )),
              ],
              const SizedBox(height: 8),
              TextButton(onPressed: _openNotifications, child: const Text('View all')),
            ],
          ),
        ),
        const SizedBox(height: 12),
        Container(
          padding: const EdgeInsets.all(15),
          decoration: _panelDecoration(),
          child: const Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('Community features', style: TextStyle(fontWeight: FontWeight.w900)),
              SizedBox(height: 8),
              Text('Members can like events, comment, reply to comments and mention other users.', style: TextStyle(fontSize: 11.5, color: _muted, height: 1.55)),
            ],
          ),
        ),
      ],
    );
  }

  Widget _tabletPanel() {
    return ListView(
      padding: const EdgeInsets.only(top: 12, bottom: 96),
      children: [
        Container(
          padding: const EdgeInsets.all(14),
          decoration: _panelDecoration(),
          child: Column(children: [
            _EventBell(unread: _unread, onTap: _openNotifications),
            const SizedBox(height: 8),
            Text('$_unread unread', style: const TextStyle(fontWeight: FontWeight.w900)),
            TextButton(onPressed: _openNotifications, child: const Text('Open alerts')),
          ]),
        ),
      ],
    );
  }

  Widget _mainFeed({required bool compact}) {
    return RefreshIndicator(
      color: _green,
      onRefresh: _refresh,
      child: ListView(
        controller: _scrollController,
        physics: const AlwaysScrollableScrollPhysics(),
        padding: EdgeInsets.fromLTRB(compact ? 8 : 0, 12, compact ? 8 : 0, 100),
        children: [
          _header(compact),
          const SizedBox(height: 12),
          if (compact) _mobileFilters(),
          if (compact) const SizedBox(height: 12),
          if (_loading)
            const Padding(padding: EdgeInsets.symmetric(vertical: 120), child: Center(child: CircularProgressIndicator(color: _green)))
          else if (_error != null)
            _errorState()
          else if (_events.isEmpty)
            _emptyState()
          else
            ...List<Widget>.generate(_events.length, (index) => Padding(
                  padding: const EdgeInsets.only(bottom: 12),
                  child: _EventCard(
                    event: _events[index],
                    isPast: _isPast,
                    onLike: () => _toggleLike(index),
                    onComment: () => _openConversation(index),
                    onShare: () => _share(_events[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: [
            Expanded(
              child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                Text(_isPast ? 'Past Events' : 'Upcoming Events', style: const TextStyle(fontSize: 22, fontWeight: FontWeight.w900, color: _dark)),
                const SizedBox(height: 4),
                Text(
                  _isPast ? 'A professional archive of completed Rockview events.' : 'Discover and engage with the latest Rockview campus events.',
                  style: const TextStyle(fontSize: 11.8, color: _muted, height: 1.45),
                ),
              ]),
            ),
            if (compact) _EventBell(unread: _unread, onTap: _openNotifications),
            if (compact && widget.allowCreate) ...[
              const SizedBox(width: 8),
              IconButton.filled(
                onPressed: _createEvent,
                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 events, locations or speakers...',
              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: 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();
        },
      ),
    );
  }

  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('Events 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(_isPast ? Icons.history_rounded : Icons.event_available_outlined, size: 60, color: Colors.grey.shade300),
          const SizedBox(height: 12),
          Text(_isPast ? 'No past events found' : 'No upcoming events found', style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w900)),
          const SizedBox(height: 7),
          const Text('Try another campus or refresh the event feed.', textAlign: TextAlign.center, style: TextStyle(color: _muted)),
        ]),
      );
}

class _EventCard extends StatelessWidget {
  final CampusEvent event;
  final bool isPast;
  final VoidCallback onLike;
  final VoidCallback onComment;
  final VoidCallback onShare;

  const _EventCard({
    required this.event,
    required this.isPast,
    required this.onLike,
    required this.onComment,
    required this.onShare,
  });

  @override
  Widget build(BuildContext context) {
    final compact = MediaQuery.of(context).size.width < 650;
    final images = event.images;
    return Container(
      padding: EdgeInsets.all(compact ? 14 : 16),
      decoration: _panelDecoration(radius: 22),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(children: [
            _EventAvatar(value: event.authorProfilePicture, size: 43),
            const SizedBox(width: 10),
            Expanded(
              child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                Row(children: [
                  Flexible(child: Text(event.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('${event.campus.isEmpty ? 'Rockview University' : event.campus} • ${_timeAgo(event.createdAt)}', style: const TextStyle(color: _muted, fontSize: 10.5, fontWeight: FontWeight.w600)),
              ]),
            ),
            _EventCategoryChip(label: event.category),
          ]),
          const SizedBox(height: 13),
          Text(event.title, style: TextStyle(fontSize: compact ? 17 : 19, fontWeight: FontWeight.w900, color: _dark, height: 1.25)),
          const SizedBox(height: 8),
          Text(event.description, maxLines: compact ? 4 : 5, overflow: TextOverflow.ellipsis, style: const TextStyle(color: Color(0xFF53606D), fontSize: 12.5, height: 1.55)),
          const SizedBox(height: 11),
          Wrap(
            spacing: 8,
            runSpacing: 8,
            children: [
              _EventInfoPill(icon: Icons.calendar_month_rounded, text: _formatDate(event.eventDate)),
              _EventInfoPill(icon: Icons.location_on_outlined, text: event.location.isEmpty ? 'Location TBA' : event.location),
              if (event.speakers.trim().isNotEmpty) _EventInfoPill(icon: Icons.mic_none_rounded, text: event.speakers),
              if (isPast) const _EventInfoPill(icon: Icons.history_rounded, text: 'Completed'),
            ],
          ),
          if (images.isNotEmpty) ...[
            const SizedBox(height: 13),
            _EventImagePreview(images: images),
          ] else if (event.legacyImageUrl.trim().isNotEmpty) ...[
            const SizedBox(height: 13),
            ClipRRect(
              borderRadius: BorderRadius.circular(18),
              child: AspectRatio(
                aspectRatio: 16 / 9,
                child: _LegacyEventImage(value: event.legacyImageUrl),
              ),
            ),
          ],
          if (event.video != null) ...[
            const SizedBox(height: 12),
            _InlineEventVideo(video: event.video!),
          ],
          const SizedBox(height: 11),
          Row(children: [
            _EventSocialButton(
              icon: event.likedByMe ? Icons.favorite_rounded : Icons.favorite_border_rounded,
              label: '${event.likeCount}',
              active: event.likedByMe,
              onTap: onLike,
            ),
            const SizedBox(width: 7),
            _EventSocialButton(icon: Icons.mode_comment_outlined, label: '${event.commentCount}', onTap: onComment),
            const Spacer(),
            if (!compact)
              _EventSocialButton(icon: Icons.ios_share_rounded, label: 'Share', onTap: onShare)
            else
              IconButton(onPressed: onShare, icon: const Icon(Icons.ios_share_rounded, size: 18)),
          ]),
        ],
      ),
    );
  }
}

class _EventImagePreview extends StatelessWidget {
  final List<CampusEventMedia> images;

  const _EventImagePreview({required this.images});

  @override
  Widget build(BuildContext context) {
    final remaining = images.length - 1;
    final source = images.first.thumbnailPath.isNotEmpty ? images.first.thumbnailPath : images.first.path;
    return ClipRRect(
      borderRadius: BorderRadius.circular(18),
      child: Stack(children: [
        AspectRatio(aspectRatio: 16 / 9, child: _EventNetworkImage(path: source)),
        if (remaining > 0)
          Positioned(
            right: 11,
            bottom: 11,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
              decoration: BoxDecoration(color: Colors.black.withOpacity(.67), borderRadius: BorderRadius.circular(13)),
              child: Text('+$remaining', style: const TextStyle(color: Colors.white, fontSize: 17, fontWeight: FontWeight.w900)),
            ),
          ),
        Positioned(
          left: 10,
          top: 10,
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
            decoration: BoxDecoration(color: Colors.white.withOpacity(.93), borderRadius: BorderRadius.circular(11)),
            child: Text('${images.length} photo${images.length == 1 ? '' : 's'}', style: const TextStyle(fontSize: 9.5, fontWeight: FontWeight.w900)),
          ),
        ),
      ]),
    );
  }
}

class _InlineEventVideo extends StatefulWidget {
  final CampusEventMedia video;
  const _InlineEventVideo({required this.video});

  @override
  State<_InlineEventVideo> createState() => _InlineEventVideoState();
}

class _InlineEventVideoState extends State<_InlineEventVideo> {
  VideoPlayerController? _controller;
  bool _loading = false;
  String? _error;
  static VideoPlayerController? _activeController;

  Future<void> _start() async {
    if (_controller != null) {
      if (_controller!.value.isPlaying) {
        await _controller!.pause();
      } else {
        if (_activeController != null && _activeController != _controller) await _activeController!.pause();
        _activeController = _controller;
        await _controller!.play();
      }
      if (mounted) setState(() {});
      return;
    }
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final controller = VideoPlayerController.networkUrl(Uri.parse(CampusEventsService.mediaUrl(widget.video.path)));
      await controller.initialize();
      await controller.setLooping(false);
      if (_activeController != null && _activeController != controller) await _activeController!.pause();
      _activeController = 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 (_activeController == _controller) _activeController = null;
    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(17),
      child: AspectRatio(
        aspectRatio: 16 / 9,
        child: Container(
          color: const Color(0xFF111315),
          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, color: Colors.white38, size: 56)),
              if (_error != null)
                Center(child: Padding(padding: const EdgeInsets.all(18), 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: _start,
                    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),
                    ),
                  ),
                ),
              Positioned(
                left: 10,
                bottom: 9,
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 5),
                  decoration: BoxDecoration(color: Colors.black54, borderRadius: BorderRadius.circular(10)),
                  child: const Text('VIDEO • TAP TO PLAY INLINE', style: TextStyle(color: Colors.white, fontSize: 8.5, fontWeight: FontWeight.w900)),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class EventComposerDialog extends StatefulWidget {
  final CampusEvent? event;
  const EventComposerDialog({super.key, this.event});

  @override
  State<EventComposerDialog> createState() => _EventComposerDialogState();
}

class _EventComposerDialogState extends State<EventComposerDialog> {
  final _formKey = GlobalKey<FormState>();
  final ImagePicker _picker = ImagePicker();
  late final TextEditingController _title;
  late final TextEditingController _description;
  late final TextEditingController _location;
  late final TextEditingController _speakers;
  String _category = 'General';
  DateTime _eventDate = DateTime.now().add(const Duration(days: 1));
  Map<String, dynamic>? _me;
  String? _accountError;
  bool _loadingAccount = true;
  bool _saving = false;
  final List<_PickedEventImage> _images = <_PickedEventImage>[];
  XFile? _video;
  String _videoLabel = '';

  @override
  void initState() {
    super.initState();
    final event = widget.event;
    _title = TextEditingController(text: event?.title ?? '');
    _description = TextEditingController(text: event?.description ?? '');
    _location = TextEditingController(text: event?.location ?? '');
    _speakers = TextEditingController(text: event?.speakers ?? '');
    _category = event?.category ?? 'General';
    _eventDate = event?.eventDate ?? DateTime.now().add(const Duration(days: 1));
    _loadAccount();
  }

  @override
  void dispose() {
    _title.dispose();
    _description.dispose();
    _location.dispose();
    _speakers.dispose();
    super.dispose();
  }

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

  Future<void> _pickDateTime() async {
    final date = await showDatePicker(
      context: context,
      initialDate: _eventDate,
      firstDate: DateTime.now().subtract(const Duration(days: 365)),
      lastDate: DateTime.now().add(const Duration(days: 3650)),
    );
    if (date == null || !mounted) return;
    final time = await showTimePicker(context: context, initialTime: TimeOfDay.fromDateTime(_eventDate));
    if (time == null) return;
    setState(() {
      _eventDate = 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((file) => file.readAsBytes()));
    if (!mounted) return;
    setState(() {
      for (var i = 0; i < selected.length; i++) {
        _images.add(_PickedEventImage(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() async {
    if (_saving || _me == null || !(_formKey.currentState?.validate() ?? false)) return;
    setState(() => _saving = true);
    try {
      int id;
      if (widget.event == null) {
        id = await CampusEventsService.createEvent(
          title: _title.text,
          description: _description.text,
          category: _category,
          eventDate: _eventDate,
          location: _location.text,
          speakers: _speakers.text,
        );
      } else {
        id = widget.event!.id;
        await CampusEventsService.updateEvent(id, <String, dynamic>{
          'title': _title.text.trim(),
          'description': _description.text.trim(),
          'category': _category,
          'event_date': _eventDate.toUtc().toIso8601String(),
          'location': _location.text.trim(),
          'speakers': _speakers.text.trim(),
        });
      }
      if (_images.isNotEmpty) await CampusEventsService.uploadImages(id, _images.map((item) => item.file).toList());
      if (_video != null) await CampusEventsService.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}) {
    if (!mounted) return;
    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.event_note_rounded, color: Colors.white),
              const SizedBox(width: 10),
              Expanded(child: Text(widget.event == null ? 'Create Campus Event' : 'Edit Campus Event', 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: [
                  const _SectionTitle('Organizer & Campus'),
                  const SizedBox(height: 10),
                  _accountPanel(),
                  const SizedBox(height: 22),
                  const _SectionTitle('Event Details'),
                  const SizedBox(height: 10),
                  TextFormField(
                    controller: _title,
                    maxLength: 180,
                    decoration: _formDecoration('Event title', Icons.title_rounded),
                    validator: (value) => value == null || value.trim().length < 4 ? 'Enter a clear event title.' : null,
                  ),
                  const SizedBox(height: 10),
                  DropdownButtonFormField<String>(
                    value: _category,
                    decoration: _formDecoration('Category', Icons.category_outlined),
                    items: CampusEventsService.categories.map((item) => DropdownMenuItem(value: item, child: Text(item))).toList(),
                    onChanged: _saving ? null : (value) => setState(() => _category = value ?? 'General'),
                  ),
                  const SizedBox(height: 10),
                  InkWell(
                    onTap: _saving ? null : _pickDateTime,
                    borderRadius: BorderRadius.circular(15),
                    child: InputDecorator(
                      decoration: _formDecoration('Date & time', Icons.schedule_rounded),
                      child: Text(_formatDate(_eventDate), style: const TextStyle(fontWeight: FontWeight.w700)),
                    ),
                  ),
                  const SizedBox(height: 10),
                  TextFormField(
                    controller: _location,
                    decoration: _formDecoration('Location', Icons.location_on_outlined),
                    validator: (value) => value == null || value.trim().isEmpty ? 'Enter the event location.' : null,
                  ),
                  const SizedBox(height: 10),
                  TextFormField(controller: _speakers, decoration: _formDecoration('Speakers / hosts', Icons.mic_none_rounded)),
                  const SizedBox(height: 10),
                  TextFormField(
                    controller: _description,
                    minLines: 6,
                    maxLines: 12,
                    maxLength: 12000,
                    decoration: _formDecoration('Event description', Icons.notes_rounded).copyWith(alignLabelWithHint: true),
                    validator: (value) => value == null || value.trim().length < 10 ? 'Write a meaningful event description.' : null,
                  ),
                  const SizedBox(height: 18),
                  const _SectionTitle('Event Media'),
                  const SizedBox(height: 7),
                  const Text('Attach up to 6 pictures and one optional video of not more than 10 MB. Videos load only when a user presses Play.', style: TextStyle(color: _muted, fontSize: 11.5, height: 1.5)),
                  const SizedBox(height: 11),
                  if (_images.isNotEmpty)
                    Wrap(
                      spacing: 8,
                      runSpacing: 8,
                      children: _images.asMap().entries.map((entry) => SizedBox(
                            width: 120,
                            height: 88,
                            child: Stack(fit: StackFit.expand, children: [
                              ClipRRect(borderRadius: BorderRadius.circular(13), child: Image.memory(entry.value.bytes, fit: BoxFit.cover)),
                              Positioned(
                                top: 4,
                                right: 4,
                                child: InkWell(
                                  onTap: () => setState(() => _images.removeAt(entry.key)),
                                  child: const CircleAvatar(radius: 12, backgroundColor: Colors.black54, child: Icon(Icons.close, color: Colors.white, size: 14)),
                                ),
                              ),
                            ]),
                          )).toList(),
                    ),
                  if (_images.isNotEmpty) const SizedBox(height: 10),
                  Wrap(spacing: 9, runSpacing: 9, children: [
                    OutlinedButton.icon(onPressed: _images.length >= 6 || _saving ? null : _pickImages, icon: const Icon(Icons.add_photo_alternate_outlined), label: Text('Add Photos (${_images.length}/6)')),
                    OutlinedButton.icon(onPressed: _saving ? null : _pickVideo, icon: const Icon(Icons.video_library_outlined), label: Text(_video == null ? 'Add Video' : 'Change Video')),
                  ]),
                  if (_video != null) ...[
                    const SizedBox(height: 10),
                    Container(
                      padding: const EdgeInsets.all(11),
                      decoration: BoxDecoration(color: const Color(0xFFF7F9FB), borderRadius: BorderRadius.circular(13), border: Border.all(color: _border)),
                      child: Row(children: [
                        const Icon(Icons.videocam_rounded, color: _green),
                        const SizedBox(width: 9),
                        Expanded(child: Text(_videoLabel, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 11.5, fontWeight: FontWeight.w700))),
                        IconButton(onPressed: () => setState(() { _video = null; _videoLabel = ''; }), icon: const Icon(Icons.close, size: 18)),
                      ]),
                    ),
                  ],
                ]),
              ),
            ),
          ),
          Container(
            padding: const EdgeInsets.all(15),
            decoration: const BoxDecoration(color: Color(0xFFF7F9FB), borderRadius: BorderRadius.vertical(bottom: Radius.circular(26))),
            child: Row(mainAxisAlignment: MainAxisAlignment.end, children: [
              OutlinedButton(onPressed: _saving ? null : () => Navigator.pop(context, false), child: const Text('Cancel')),
              const SizedBox(width: 9),
              FilledButton.icon(
                onPressed: _saving || _me == null ? null : _save,
                style: FilledButton.styleFrom(backgroundColor: _green, foregroundColor: Colors.white, padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 15)),
                icon: _saving ? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white)) : const Icon(Icons.publish_rounded),
                label: Text(_saving ? 'Publishing...' : 'Publish Event'),
              ),
            ]),
          ),
        ]),
      ),
    );
  }

  Widget _accountPanel() {
    if (_loadingAccount) return const Padding(padding: EdgeInsets.all(18), child: 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(14)),
        child: Row(children: [
          Icon(Icons.error_outline, color: Colors.red.shade700),
          const SizedBox(width: 9),
          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(.045), borderRadius: BorderRadius.circular(15), border: Border.all(color: _green.withOpacity(.14))),
      child: Row(children: [
        _EventAvatar(value: '${_me!['profile_picture'] ?? ''}', size: 47),
        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 SizedBox(height: 2),
          const Text('Organizer identity and campus are taken from the signed-in account.', style: TextStyle(color: _muted, fontSize: 10.5)),
        ])),
        const Icon(Icons.lock_outline_rounded, color: _green, size: 19),
      ]),
    );
  }
}

class EventConversationDialog extends StatefulWidget {
  final CampusEvent event;
  const EventConversationDialog({super.key, required this.event});

  @override
  State<EventConversationDialog> createState() => _EventConversationDialogState();
}

class _EventConversationDialogState extends State<EventConversationDialog> {
  final TextEditingController _controller = TextEditingController();
  late CampusEvent _event;
  List<CampusEventComment> _comments = <CampusEventComment>[];
  List<EventMentionableUser> _mentionUsers = <EventMentionableUser>[];
  final Map<int, EventMentionableUser> _mentions = <int, EventMentionableUser>{};
  CampusEventComment? _replyingTo;
  bool _loading = true;
  bool _posting = false;
  bool _liking = false;
  String? _error;

  @override
  void initState() {
    super.initState();
    _event = widget.event;
    _load();
  }

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

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

  Future<void> _toggleLike() async {
    if (_liking) return;
    setState(() => _liking = true);
    try {
      final result = await CampusEventsService.toggleLike(_event.id);
      if (!mounted) return;
      setState(() {
        _event = _event.copyWith(
          likedByMe: _bool(result['liked']),
          likeCount: int.tryParse('${result['like_count'] ?? 0}') ?? _event.likeCount,
        );
        _liking = false;
      });
    } catch (_) {
      if (mounted) setState(() => _liking = false);
    }
  }

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

  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 CampusEventsService.addComment(
        _event.id,
        text,
        parentCommentId: parentId,
        mentionUserIds: _mentions.keys.toList(),
      );
      if (!mounted) return;
      setState(() {
        _comments.add(created);
        _event = _event.copyWith(commentCount: _comments.length);
        _controller.clear();
        _replyingTo = null;
        _mentions.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) {
    return Dialog(
      insetPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 14),
      backgroundColor: Colors.transparent,
      child: Container(
        constraints: BoxConstraints(maxWidth: 1040, 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: 18, 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('Event Discussion', style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w900))),
              IconButton(onPressed: () => Navigator.pop(context, _event), icon: const Icon(Icons.close_rounded, color: Colors.white)),
            ]),
          ),
          Expanded(child: LayoutBuilder(builder: (context, constraints) {
            final wide = constraints.maxWidth >= 840;
            if (wide) {
              return Row(children: [
                Expanded(flex: 6, child: _eventDetails()),
                VerticalDivider(width: 1, color: Colors.grey.shade300),
                Expanded(flex: 5, child: _commentsPane()),
              ]);
            }
            return _commentsPane();
          })),
        ]),
      ),
    );
  }

  Widget _eventDetails() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(20),
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Row(children: [
          _EventAvatar(value: _event.authorProfilePicture, size: 47),
          const SizedBox(width: 10),
          Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Text(_event.authorName, style: const TextStyle(fontWeight: FontWeight.w900)),
            const SizedBox(height: 3),
            Text(_event.campus, style: const TextStyle(color: _muted, fontSize: 10.5)),
          ])),
          _EventCategoryChip(label: _event.category),
        ]),
        const SizedBox(height: 17),
        Text(_event.title, style: const TextStyle(fontSize: 23, fontWeight: FontWeight.w900, height: 1.25)),
        const SizedBox(height: 11),
        Wrap(spacing: 8, runSpacing: 8, children: [
          _EventInfoPill(icon: Icons.schedule_rounded, text: _formatDate(_event.eventDate)),
          _EventInfoPill(icon: Icons.location_on_outlined, text: _event.location),
          if (_event.speakers.trim().isNotEmpty) _EventInfoPill(icon: Icons.mic_none_rounded, text: _event.speakers),
        ]),
        const SizedBox(height: 14),
        Text(_event.description, style: const TextStyle(fontSize: 13.5, height: 1.7, color: Color(0xFF4F5C69))),
        if (_event.images.isNotEmpty) ...[
          const SizedBox(height: 17),
          ..._event.images.map((image) => Padding(
                padding: const EdgeInsets.only(bottom: 9),
                child: ClipRRect(borderRadius: BorderRadius.circular(16), child: AspectRatio(aspectRatio: 16 / 9, child: _EventNetworkImage(path: image.path))),
              )),
        ] else if (_event.legacyImageUrl.trim().isNotEmpty) ...[
          const SizedBox(height: 17),
          ClipRRect(
            borderRadius: BorderRadius.circular(16),
            child: AspectRatio(aspectRatio: 16 / 9, child: _LegacyEventImage(value: _event.legacyImageUrl)),
          ),
        ],
        if (_event.video != null) ...[
          const SizedBox(height: 12),
          _InlineEventVideo(video: _event.video!),
        ],
      ]),
    );
  }

  Widget _commentsPane() {
    final parents = _comments.where((item) => item.parentCommentId == null).toList();
    final replies = <int, List<CampusEventComment>>{};
    for (final comment in _comments.where((item) => item.parentCommentId != null)) {
      replies.putIfAbsent(comment.parentCommentId!, () => <CampusEventComment>[]).add(comment);
    }
    return Column(children: [
      Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 9),
        decoration: BoxDecoration(color: const Color(0xFFF7F9FB), border: Border(bottom: BorderSide(color: Colors.grey.shade200))),
        child: Row(children: [
          _EventSocialButton(
            icon: _event.likedByMe ? Icons.favorite_rounded : Icons.favorite_border_rounded,
            label: '${_event.likeCount}',
            active: _event.likedByMe,
            onTap: _toggleLike,
          ),
          const SizedBox(width: 8),
          Text('${_event.commentCount} comments', style: const TextStyle(color: _muted, fontWeight: FontWeight.w800)),
        ]),
      ),
      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 event conversation.', textAlign: TextAlign.center, style: TextStyle(color: _muted)))
                    : ListView.separated(
                        padding: const EdgeInsets.all(12),
                        itemCount: parents.length,
                        separatorBuilder: (_, __) => const SizedBox(height: 11),
                        itemBuilder: (context, index) {
                          final parent = parents[index];
                          return _EventCommentThread(
                            comment: parent,
                            replies: replies[parent.id] ?? const <CampusEventComment>[],
                            onReply: (comment) => setState(() => _replyingTo = comment),
                          );
                        },
                      ),
      ),
      if (_replyingTo != null)
        Container(
          margin: const EdgeInsets.fromLTRB(10, 0, 10, 7),
          padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 7),
          decoration: BoxDecoration(color: _green.withOpacity(.06), borderRadius: BorderRadius.circular(12)),
          child: Row(children: [
            Expanded(child: Text('Replying to ${_replyingTo!.authorName}', style: const TextStyle(color: _green, fontWeight: FontWeight.w800, fontSize: 11))),
            IconButton(onPressed: () => setState(() => _replyingTo = null), icon: const Icon(Icons.close, size: 17)),
          ]),
        ),
      Container(
        padding: const EdgeInsets.all(10),
        decoration: BoxDecoration(color: Colors.white, border: Border(top: BorderSide(color: Colors.grey.shade200))),
        child: Column(children: [
          if (_mentions.isNotEmpty)
            Align(
              alignment: Alignment.centerLeft,
              child: Wrap(
                spacing: 5,
                runSpacing: 5,
                children: _mentions.values.map((user) => Chip(
                      visualDensity: VisualDensity.compact,
                      label: Text('@${user.fullName}', style: const TextStyle(fontSize: 9.5)),
                      onDeleted: () => setState(() => _mentions.remove(user.id)),
                    )).toList(),
              ),
            ),
          if (_mentions.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(13), borderSide: const BorderSide(color: _border)),
                ),
              ),
            ),
            const SizedBox(width: 6),
            SizedBox(width: 43, height: 45, child: OutlinedButton(onPressed: _mention, style: OutlinedButton.styleFrom(padding: EdgeInsets.zero, foregroundColor: _green), child: const Text('@', style: TextStyle(fontWeight: FontWeight.w900, fontSize: 17)))),
            const SizedBox(width: 6),
            SizedBox(
              width: 47,
              height: 45,
              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),
              ),
            ),
          ]),
        ]),
      ),
    ]);
  }
}

class _EventCommentThread extends StatelessWidget {
  final CampusEventComment comment;
  final List<CampusEventComment> replies;
  final ValueChanged<CampusEventComment> onReply;

  const _EventCommentThread({required this.comment, required this.replies, required this.onReply});

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

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

  @override
  Widget build(BuildContext context) {
    return Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
      _EventAvatar(value: comment.authorProfilePicture, size: 34),
      const SizedBox(width: 8),
      Expanded(
        child: Container(
          padding: const EdgeInsets.all(10),
          decoration: BoxDecoration(color: comment.isReply ? const Color(0xFFF7F9FB) : Colors.grey.shade50, borderRadius: BorderRadius.circular(13), border: Border.all(color: _border)),
          child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Row(children: [
              Expanded(child: Text(comment.authorName, style: const TextStyle(fontSize: 11, fontWeight: FontWeight.w900))),
              Text(_timeAgo(comment.createdAt), style: const TextStyle(fontSize: 8.8, color: Color(0xFF98A2AD))),
            ]),
            const SizedBox(height: 5),
            _MentionAwareText(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, fontWeight: FontWeight.w800)),
            ),
          ]),
        ),
      ),
    ]);
  }
}

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

  @override
  State<_EventMentionPicker> createState() => _EventMentionPickerState();
}

class _EventMentionPickerState extends State<_EventMentionPicker> {
  final TextEditingController _search = TextEditingController();
  late List<EventMentionableUser> _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((user) => user.fullName.toLowerCase().contains(q) || user.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(17), child: Align(alignment: Alignment.centerLeft, child: Text('Mention Member', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w900)))),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 17),
            child: TextField(controller: _search, decoration: InputDecoration(hintText: 'Search member...', prefixIcon: const Icon(Icons.search), border: OutlineInputBorder(borderRadius: BorderRadius.circular(13)))),
          ),
          const SizedBox(height: 9),
          Expanded(
            child: ListView.separated(
              padding: const EdgeInsets.all(17),
              itemCount: _filtered.length,
              separatorBuilder: (_, __) => const SizedBox(height: 7),
              itemBuilder: (context, index) {
                final user = _filtered[index];
                return ListTile(
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(13), side: const BorderSide(color: _border)),
                  leading: _EventAvatar(value: user.profilePicture, size: 39),
                  title: Text(user.fullName, style: const TextStyle(fontWeight: FontWeight.w800)),
                  subtitle: Text('${_roleLabel(user.role)} • ${user.campus}'),
                  onTap: () => Navigator.pop(context, user),
                );
              },
            ),
          ),
        ]),
      ),
    );
  }
}

class _EventNotificationsSheet extends StatelessWidget {
  final List<CampusEventNotification> notifications;
  final int unreadCount;
  final Future<void> Function(CampusEventNotification) onRead;
  final Future<void> Function() onMarkAll;

  const _EventNotificationsSheet({required this.notifications, required this.unreadCount, required this.onRead, required this.onMarkAll});

  @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(27))),
        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(17),
            child: Row(children: [
              Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                const Text('Event Notifications', style: TextStyle(fontSize: 19, fontWeight: FontWeight.w900)),
                const SizedBox(height: 3),
                Text('$unreadCount unread', style: const TextStyle(color: _muted, fontSize: 11)),
              ])),
              if (unreadCount > 0) TextButton.icon(onPressed: () async { await onMarkAll(); if (context.mounted) Navigator.pop(context); }, icon: const Icon(Icons.done_all), label: const Text('Mark all read')),
            ]),
          ),
          Expanded(
            child: notifications.isEmpty
                ? const Center(child: Text('No event notifications yet.', style: TextStyle(color: _muted)))
                : ListView.separated(
                    padding: const EdgeInsets.fromLTRB(15, 0, 15, 20),
                    itemCount: notifications.length,
                    separatorBuilder: (_, __) => const SizedBox(height: 8),
                    itemBuilder: (context, index) {
                      final item = notifications[index];
                      return InkWell(
                        onTap: () async { await onRead(item); if (context.mounted) Navigator.pop(context); },
                        borderRadius: BorderRadius.circular(15),
                        child: Container(
                          padding: const EdgeInsets.all(11),
                          decoration: BoxDecoration(color: item.isRead ? const Color(0xFFF9FAFB) : _green.withOpacity(.055), borderRadius: BorderRadius.circular(15), border: Border.all(color: _border)),
                          child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
                            _EventAvatar(value: item.actorProfilePicture, size: 39),
                            const SizedBox(width: 9),
                            Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                              Row(children: [
                                Expanded(child: Text(item.title, style: const TextStyle(fontSize: 11.5, fontWeight: FontWeight.w900))),
                                if (!item.isRead) Container(width: 8, height: 8, decoration: const BoxDecoration(color: _gold, shape: BoxShape.circle)),
                              ]),
                              const SizedBox(height: 4),
                              Text(item.message, style: const TextStyle(fontSize: 10.8, color: _muted, height: 1.45)),
                              const SizedBox(height: 4),
                              Text(_timeAgo(item.createdAt), style: const TextStyle(fontSize: 9, color: Color(0xFF98A2AD))),
                            ])),
                          ]),
                        ),
                      );
                    },
                  ),
          ),
        ]),
      ),
    );
  }
}

class _EventBell extends StatelessWidget {
  final int unread;
  final VoidCallback onTap;
  const _EventBell({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(
              right: -4,
              top: -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: 8.5, fontWeight: FontWeight.w900)),
              ),
            ),
        ]),
      ),
    );
  }
}

class _EventSocialButton extends StatelessWidget {
  final IconData icon;
  final String label;
  final bool active;
  final VoidCallback onTap;
  const _EventSocialButton({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: Container(
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
        decoration: BoxDecoration(color: active ? Colors.red.withOpacity(.07) : const Color(0xFFF5F7F9), borderRadius: BorderRadius.circular(999)),
        child: Row(mainAxisSize: MainAxisSize.min, children: [
          Icon(icon, size: 16, color: active ? Colors.red.shade600 : _muted),
          const SizedBox(width: 5),
          Text(label, style: TextStyle(fontSize: 10.8, fontWeight: FontWeight.w800, color: active ? Colors.red.shade700 : _muted)),
        ]),
      ),
    );
  }
}

class _EventCategoryChip extends StatelessWidget {
  final String label;
  const _EventCategoryChip({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.3, fontWeight: FontWeight.w900, letterSpacing: .5)),
      );
}

class _EventInfoPill extends StatelessWidget {
  final IconData icon;
  final String text;
  const _EventInfoPill({required this.icon, required this.text});
  @override
  Widget build(BuildContext context) => Container(
        padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 7),
        decoration: BoxDecoration(color: const Color(0xFFF5F7F9), borderRadius: BorderRadius.circular(999)),
        child: Row(mainAxisSize: MainAxisSize.min, children: [
          Icon(icon, size: 13, color: _green),
          const SizedBox(width: 5),
          ConstrainedBox(constraints: const BoxConstraints(maxWidth: 220), child: Text(text, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _muted, fontSize: 10.5, fontWeight: FontWeight.w700))),
        ]),
      );
}

class _EventNetworkImage extends StatelessWidget {
  final String path;
  const _EventNetworkImage({required this.path});
  @override
  Widget build(BuildContext context) {
    return Image.network(
      CampusEventsService.mediaUrl(path),
      fit: BoxFit.cover,
      loadingBuilder: (context, child, progress) => progress == 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 _LegacyEventImage extends StatelessWidget {
  final String value;
  const _LegacyEventImage({required this.value});

  @override
  Widget build(BuildContext context) {
    final trimmed = value.trim();
    if (trimmed.startsWith('http://') ||
        trimmed.startsWith('https://') ||
        CampusEventsService.isStoredMediaPath(trimmed)) {
      return _EventNetworkImage(path: trimmed);
    }
    try {
      var raw = trimmed;
      if (raw.startsWith('data:image') && raw.contains(',')) {
        raw = raw.substring(raw.indexOf(',') + 1);
      }
      return Image.memory(
        base64Decode(raw),
        fit: BoxFit.cover,
        errorBuilder: (_, __, ___) => _legacyFallback(),
      );
    } catch (_) {
      return _legacyFallback();
    }
  }

  Widget _legacyFallback() => Container(
        color: const Color(0xFFF0F2F4),
        alignment: Alignment.center,
        child: const Icon(Icons.event_rounded, color: Colors.grey, size: 46),
      );
}

class _EventAvatar extends StatelessWidget {
  final String value;
  final double size;
  const _EventAvatar({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://') || CampusEventsService.isStoredMediaPath(trimmed)) {
      child = Image.network(CampusEventsService.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 _MentionAwareText extends StatelessWidget {
  final String text;
  const _MentionAwareText(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.3, height: 1.4, color: word.startsWith('@') ? _green : const Color(0xFF42515F), fontWeight: word.startsWith('@') ? FontWeight.w900 : FontWeight.normal))).toList(),
    );
  }
}

class _SectionTitle extends StatelessWidget {
  final String text;
  const _SectionTitle(this.text);
  @override
  Widget build(BuildContext context) => Row(children: [
        Container(width: 5, height: 18, decoration: BoxDecoration(color: _gold, borderRadius: BorderRadius.circular(999))),
        const SizedBox(width: 7),
        Text(text, style: const TextStyle(color: _dark, fontWeight: FontWeight.w900)),
      ]);
}

class _PickedEventImage {
  final XFile file;
  final Uint8List bytes;
  const _PickedEventImage({required this.file, required this.bytes});
}

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: 12, 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 _formDecoration(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 _formatDate(DateTime value) {
  final date = value.toLocal();
  const months = <String>['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  final hour = date.hour == 0 ? 12 : (date.hour > 12 ? date.hour - 12 : date.hour);
  final minute = date.minute.toString().padLeft(2, '0');
  final ampm = date.hour >= 12 ? 'PM' : 'AM';
  return '${months[date.month - 1]} ${date.day}, ${date.year} • $hour:$minute $ampm';
}

String _timeAgo(DateTime value) {
  final diff = DateTime.now().difference(value.toLocal());
  if (diff.inSeconds < 60) 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 '${(diff.inDays / 7).floor()}w ago';
}

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

String _formatBytes(int bytes) {
  if (bytes < 1024) return '$bytes B';
  if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
  return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
}

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';
}
