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/news_offline_service.dart';
import 'news_offline_widgets.dart';
import 'news_video_poster.dart';
import 'news_video_source.dart';

const Color _standardGold = Color.fromARGB(255, 204, 117, 4);
const Color _darkGreen = Color.fromARGB(255, 2, 105, 48);
const Color _pageBackground = Color(0xFFF4F6F5);
const Color _panelBorder = Color(0xFFE2E7E4);
const Color _textStrong = Color(0xFF17211B);

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

  @override
  State<PublishedNewsSubTab> createState() => _PublishedNewsSubTabState();
}

class _PublishedNewsSubTabState extends State<PublishedNewsSubTab> {
  final ScrollController _scrollController = ScrollController();
  final TextEditingController _searchController = TextEditingController();

  final List<CampusNewsArticle> _articles = [];
  List<String> _campuses = const [];
  String _selectedCampus = 'All Campuses';
  String _selectedCategory = 'All Categories';

  bool _loading = true;
  bool _loadingMore = false;
  bool _hasMore = true;
  bool _silentSyncInProgress = false;
  String? _error;
  int _page = 1;
  Timer? _searchDebounce;
  int _requestVersion=0;
  String? _queryKey;
  final Set<int> _likingIds={};
  static const int _pageSize = 8;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_onScroll);
    _loadInitial();

    NewsOfflineService.revision.addListener(_syncNewestPosts);
  }

  @override
  void dispose() {
    _searchDebounce?.cancel();
    NewsOfflineService.revision.removeListener(_syncNewestPosts);
    _scrollController.dispose();
    _searchController.dispose();
    super.dispose();
  }

  Future<void> _loadInitial() async {
    await _reloadFeed();
    try{final campuses=await NewsOfflineService.getCampuses();if(mounted)setState(()=>_campuses=campuses);}catch(_){}
  }
  Future<void> _refreshNow() async {await NewsOfflineService.sync(force:true);await _loadInitial();}
  Future<void> _reloadFeed() async {
    if(!mounted)return;
    final request=++_requestVersion;
    final query='$_selectedCampus|$_selectedCategory|${_searchController.text.trim()}';
    setState((){if(query!=_queryKey){_articles.clear();_queryKey=query;}_loading=_articles.isEmpty;_error=null;});
    try{
      final page=await NewsOfflineService.getNews(status:'published',campus:_selectedCampus,category:_selectedCategory,search:_searchController.text,page:1,limit:_pageSize);
      if(!mounted||request!=_requestVersion)return;
      setState((){_articles..clear()..addAll(page.articles);_sortNewestFirst();_hasMore=page.hasMore;_page=1;_loading=false;});
    }catch(e){if(mounted&&request==_requestVersion)setState((){_loading=false;_error=_articles.isEmpty?_cleanError(e):null;});}
  }

  DateTime _articleFeedTime(CampusNewsArticle article) {
    return (article.publishedAt ?? article.createdAt).toLocal();
  }

  void _sortNewestFirst() {
    _articles.sort((a, b) {
      final timeCompare = _articleFeedTime(b).compareTo(_articleFeedTime(a));
      if (timeCompare != 0) return timeCompare;
      return b.id.compareTo(a.id);
    });
  }

  void _mergeArticles(Iterable<CampusNewsArticle> incoming) {
    final byId = <int, CampusNewsArticle>{
      for (final article in _articles) article.id: article,
    };

    for (final article in incoming) {
      byId[article.id] = article;
    }

    _articles
      ..clear()
      ..addAll(byId.values);
    _sortNewestFirst();
  }

  Future<void> _syncNewestPosts() async {
    if(!mounted||_loading||_loadingMore||_silentSyncInProgress)return;
    if(_scrollController.hasClients&&_scrollController.offset>260)return;
    _silentSyncInProgress=true;
    try{await _reloadFeed();}finally{_silentSyncInProgress=false;}
  }

  Future<void> _loadMore() async {
    if (_loading || _loadingMore || !_hasMore) return;
    setState(() => _loadingMore = true);
    final nextPage = _page + 1;final request=_requestVersion;
    try {
      final page = await NewsOfflineService.getNews(
        status: 'published',
        campus: _selectedCampus,
        category: _selectedCategory,
        search: _searchController.text,
        page: nextPage,
        limit: _pageSize,
      );
      if (!mounted||request!=_requestVersion){if(mounted)setState(()=>_loadingMore=false);return;}
      setState(() {
        _mergeArticles(page.articles);
        _hasMore = page.hasMore;
        _page = nextPage;
        _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> _openComposer() async {
    final result = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (_) => const NewsAccountGuard(child:CampusNewsComposerDialog()),
    );
    if (result == true) await _reloadFeed();
  }

  Future<void> _toggleLike(int index) async {
    if(index<0||index>=_articles.length)return;
    final article=_articles[index];if(!_likingIds.add(article.id))return;
    try{
      final result=await NewsOfflineService.toggleLike(article.id);
      if(!mounted)return;final current=_articles.indexWhere((a)=>a.id==article.id);
      if(current>=0)setState(()=>_articles[current]=_articles[current].copyWith(likedByMe:_bool(result['liked']),likeCount:int.tryParse('${result['like_count']??0}')??0));
    }catch(e){if(mounted)_showSnack(_cleanError(e),isError:true);}finally{_likingIds.remove(article.id);}
  }

  Future<void> _openConversation(int index) async {
    if (index < 0 || index >= _articles.length) return;
    final result = await showDialog<CampusNewsArticle>(
      context: context,
      barrierDismissible: true,
      builder: (_) => NewsAccountGuard(child:NewsConversationDialog(article: _articles[index])),
    );
    if(result!=null&&mounted){final current=_articles.indexWhere((a)=>a.id==result.id);if(current>=0)setState(()=>_articles[current]=result);}
  }

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

  Widget _centered(Widget child, {double maxWidth = 720}) {
    return Center(
      child: ConstrainedBox(
        constraints: BoxConstraints(maxWidth: maxWidth),
        child: child,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final compact = MediaQuery.sizeOf(context).width < 720;
    return Scaffold(
      backgroundColor: Colors.transparent,
      floatingActionButton: compact
          ? FloatingActionButton(
              onPressed: _openComposer,
              backgroundColor: _standardGold,
              foregroundColor: Colors.white,
              elevation: 3,
              child: const Icon(Icons.edit_rounded),
            )
          : FloatingActionButton.extended(
              onPressed: _openComposer,
              backgroundColor: _standardGold,
              foregroundColor: Colors.white,
              elevation: 3,
              icon: const Icon(Icons.edit_rounded),
              label: const Text(
                'WRITE NEWS',
                style: TextStyle(fontWeight: FontWeight.w900, letterSpacing: 0.5),
              ),
            ),
      body: RefreshIndicator(
        color: _darkGreen,
        onRefresh: _refreshNow,
        child: CustomScrollView(
          // Render the next card just before it enters view; the byte cache
          // makes this a cheap prefetch on repeat visits.
          controller:_scrollController,cacheExtent:420,physics:const AlwaysScrollableScrollPhysics(),
          slivers:[SliverPadding(padding:EdgeInsets.fromLTRB(compact?10:18,12,compact?10:18,96),sliver:SliverMainAxisGroup(slivers:[
            SliverToBoxAdapter(child:_centered(Column(children:[_buildFeedHeading(),const SizedBox(height:8),const NewsSyncBar(),const SizedBox(height:8),_buildFilterBar(),const SizedBox(height:12)]))),
            if(_loading)const SliverToBoxAdapter(child:Padding(padding:EdgeInsets.all(64),child:Center(child:CircularProgressIndicator(color:_darkGreen))))
            else if(_error!=null)SliverToBoxAdapter(child:_centered(_buildErrorState()))
            else if(_articles.isEmpty)SliverToBoxAdapter(child:_centered(_buildEmptyState()))
            else SliverList(delegate:SliverChildBuilderDelegate((context,index){
              final article=_articles[index];
              return Padding(key:ValueKey(article.id),padding:const EdgeInsets.only(bottom:12),child:_centered(_NewsFeedCard(
                article:article,onLike:()=>_toggleLike(index),onComment:()=>_openConversation(index),onOpen:()=>_openConversation(index),
                onShare:()async{await Clipboard.setData(ClipboardData(text:'${article.title}\n\n${article.body}'));if(mounted)_showSnack('News story copied to clipboard.');},
              )));
            },childCount:_articles.length)),
            if(_loadingMore)const SliverToBoxAdapter(child:Padding(padding:EdgeInsets.all(20),child:Center(child:CircularProgressIndicator(color:_darkGreen)))),
            if(!_hasMore&&!_loading)const SliverToBoxAdapter(child:Center(child:Text('End of saved results',style:TextStyle(color:Color(0xFF748079),fontSize:11)))),
          ]))],
        ),
      ),
    );
  }

  Widget _buildFeedHeading() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(color: _panelBorder),
        borderRadius: BorderRadius.circular(14),
      ),
      child: Row(
        children: [
          Container(
            width: 36,
            height: 36,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: _darkGreen.withOpacity(0.08),
              borderRadius: BorderRadius.circular(10),
            ),
            child: const Icon(Icons.dynamic_feed_rounded, color: _darkGreen, size: 19),
          ),
          const SizedBox(width: 11),
          const Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'Campus feed',
                  style: TextStyle(
                    color: _textStrong,
                    fontSize: 15,
                    fontWeight: FontWeight.w900,
                  ),
                ),
                SizedBox(height: 2),
                Text(
                  'Official updates and community stories',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: Color(0xFF6A746E), fontSize: 10.5),
                ),
              ],
            ),
          ),
          const SizedBox(width: 8),
          IconButton(
            tooltip: 'Refresh feed',
            onPressed: _refreshNow,
            icon: const Icon(Icons.refresh_rounded, color: _darkGreen, size: 20),
            visualDensity: VisualDensity.compact,
          ),
        ],
      ),
    );
  }

  Widget _buildFilterBar() {
    final campusItems = <String>['All Campuses', ..._campuses];
    final categoryItems = <String>['All Categories', ...NewsOfflineService.categories];

    return Container(
      padding: const EdgeInsets.all(10),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(color: _panelBorder),
        borderRadius: BorderRadius.circular(14),
      ),
      child: LayoutBuilder(
        builder: (context, constraints) {
          final compact = constraints.maxWidth < 620;
          final search = TextField(
            controller: _searchController,
            textInputAction: TextInputAction.search,
            onChanged:(_){setState((){});_searchDebounce?.cancel();_searchDebounce=Timer(const Duration(milliseconds:300),_reloadFeed);},
            onSubmitted: (_) => _reloadFeed(),
            style: const TextStyle(fontSize: 12.5),
            decoration: InputDecoration(
              hintText: 'Search news...',
              prefixIcon: const Icon(Icons.search_rounded, color: _darkGreen, size: 19),
              suffixIcon: _searchController.text.isEmpty
                  ? null
                  : IconButton(
                      icon: const Icon(Icons.close_rounded, size: 18),
                      onPressed: () {
                        _searchController.clear();
                        setState(() {});
                        _reloadFeed();
                      },
                    ),
              isDense: true,
              filled: true,
              fillColor: const Color(0xFFF7F9F8),
              contentPadding: const EdgeInsets.symmetric(vertical: 12),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(10),
                borderSide: BorderSide(color: Colors.grey.shade300),
              ),
              enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(10),
                borderSide: BorderSide(color: Colors.grey.shade300),
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(10),
                borderSide: const BorderSide(color: _darkGreen, width: 1.3),
              ),
            ),
          );

          final campus = _filterDropdown(
            value: _selectedCampus,
            items: campusItems,
            icon: Icons.domain_rounded,
            onChanged: (value) {
              if (value == null) return;
              setState(() => _selectedCampus = value);
              _reloadFeed();
            },
          );

          final category = _filterDropdown(
            value: _selectedCategory,
            items: categoryItems,
            icon: Icons.category_outlined,
            onChanged: (value) {
              if (value == null) return;
              setState(() => _selectedCategory = value);
              _reloadFeed();
            },
          );

          if (compact) {
            return Column(
              children: [
                search,
                const SizedBox(height: 8),
                Row(
                  children: [
                    Expanded(child: campus),
                    const SizedBox(width: 8),
                    Expanded(child: category),
                  ],
                ),
              ],
            );
          }

          return Row(
            children: [
              Expanded(flex: 5, child: search),
              const SizedBox(width: 8),
              Expanded(flex: 3, child: campus),
              const SizedBox(width: 8),
              Expanded(flex: 3, child: category),
            ],
          );
        },
      ),
    );
  }

  Widget _filterDropdown({
    required String value,
    required List<String> items,
    required IconData icon,
    required ValueChanged<String?> onChanged,
  }) {
    final safeValue = items.contains(value) ? value : items.first;
    return DropdownButtonFormField<String>(
      value: safeValue,
      isExpanded: true,
      style: const TextStyle(
        color: _textStrong,
        fontSize: 11.5,
        fontWeight: FontWeight.w700,
      ),
      decoration: InputDecoration(
        prefixIcon: Icon(icon, color: _darkGreen, size: 17),
        isDense: true,
        filled: true,
        fillColor: const Color(0xFFF7F9F8),
        contentPadding: const EdgeInsets.symmetric(vertical: 10),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
          borderSide: BorderSide(color: Colors.grey.shade300),
        ),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
          borderSide: BorderSide(color: Colors.grey.shade300),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
          borderSide: const BorderSide(color: _darkGreen),
        ),
      ),
      items: items
          .map(
            (item) => DropdownMenuItem<String>(
              value: item,
              child: Text(item, overflow: TextOverflow.ellipsis),
            ),
          )
          .toList(),
      onChanged: onChanged,
    );
  }

  Widget _buildErrorState() {
    return Container(
      padding: const EdgeInsets.all(26),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(color: Colors.red.shade100),
        borderRadius: BorderRadius.circular(14),
      ),
      child: Column(
        children: [
          Icon(Icons.cloud_off_rounded, size: 44, color: Colors.red.shade300),
          const SizedBox(height: 12),
          const Text(
            'Campus News could not be loaded',
            style: TextStyle(fontSize: 16, fontWeight: FontWeight.w900),
          ),
          const SizedBox(height: 7),
          Text(
            _error ?? 'Unknown error',
            textAlign: TextAlign.center,
            style: TextStyle(color: Colors.grey.shade600, height: 1.45, fontSize: 12),
          ),
          const SizedBox(height: 15),
          OutlinedButton.icon(
            onPressed: _refreshNow,
            icon: const Icon(Icons.refresh_rounded),
            label: const Text('TRY AGAIN'),
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyState() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 22, vertical: 52),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(color: _panelBorder),
        borderRadius: BorderRadius.circular(14),
      ),
      child: Column(
        children: [
          Icon(Icons.newspaper_outlined, size: 54, color: Colors.grey.shade300),
          const SizedBox(height: 14),
          const Text(
            'No news found',
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.w900),
          ),
          const SizedBox(height: 7),
          Text(
            'Publish the first campus story or change the current filters.',
            textAlign: TextAlign.center,
            style: TextStyle(color: Colors.grey.shade600, fontSize: 12),
          ),
          const SizedBox(height: 18),
          ElevatedButton.icon(
            onPressed: _openComposer,
            style: ElevatedButton.styleFrom(
              backgroundColor: _darkGreen,
              foregroundColor: Colors.white,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
            ),
            icon: const Icon(Icons.edit_rounded),
            label: const Text('WRITE NEWS'),
          ),
        ],
      ),
    );
  }
}

class _NewsFeedCard extends StatelessWidget {
  final CampusNewsArticle article;
  final VoidCallback onLike;
  final VoidCallback onComment;
  final VoidCallback onOpen;
  final VoidCallback onShare;

  const _NewsFeedCard({
    required this.article,
    required this.onLike,
    required this.onComment,
    required this.onOpen,
    required this.onShare,
  });

  @override
  Widget build(BuildContext context) {
    final compact = MediaQuery.sizeOf(context).width < 600;
    return Material(
      color: Colors.white,
      elevation: 0,
      borderRadius: BorderRadius.circular(16),
      clipBehavior: Clip.antiAlias,
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border.all(color: _panelBorder),
          borderRadius: BorderRadius.circular(16),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.025),
              blurRadius: 12,
              offset: const Offset(0, 4),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            InkWell(
              onTap: onOpen,
              child: Padding(
                padding: EdgeInsets.fromLTRB(compact ? 13 : 16, 14, compact ? 13 : 16, 11),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _ProfileAvatar(value: article.authorProfilePicture, size: 36),
                    const SizedBox(width: 10),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              Flexible(
                                child: Text(
                                  article.authorName,
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                  style: const TextStyle(
                                    fontSize: 13,
                                    fontWeight: FontWeight.w900,
                                    color: _textStrong,
                                  ),
                                ),
                              ),
                              const SizedBox(width: 5),
                              const Icon(Icons.verified_rounded, color: _darkGreen, size: 15),
                            ],
                          ),
                          const SizedBox(height: 3),
                          Text(
                            '${_roleLabel(article.authorRole)} • ${article.campus.isEmpty ? 'Rockview University' : article.campus}',
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                              color: Colors.grey.shade600,
                              fontSize: 10.5,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                          const SizedBox(height: 2),
                          Text(
                            _timeAgo(article.publishedAt ?? article.createdAt),
                            style: TextStyle(color: Colors.grey.shade500, fontSize: 9.5),
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(width: 8),
                    _CategoryChip(label: article.category),
                  ],
                ),
              ),
            ),
            InkWell(
              onTap: onOpen,
              child: Padding(
                padding: EdgeInsets.fromLTRB(compact ? 13 : 16, 2, compact ? 13 : 16, 13),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    if (article.isTrending) ...[
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                        decoration: BoxDecoration(color: const Color(0xFFFFF2E8), borderRadius: BorderRadius.circular(20)),
                        child: Row(mainAxisSize: MainAxisSize.min, children: [
                          Icon(Icons.local_fire_department_rounded, color: Colors.deepOrange.shade600, size: 13),
                          const SizedBox(width: 4),
                          Text('TRENDING', style: TextStyle(color: Colors.deepOrange.shade700, fontSize: 9, fontWeight: FontWeight.w900, letterSpacing: .5)),
                        ]),
                      ),
                      const SizedBox(height: 7),
                    ],
                    Text(
                      article.title,
                      maxLines:2,overflow:TextOverflow.ellipsis,
                      style: TextStyle(
                        fontSize: compact ? 15 : 16,
                        height: 1.25,
                        fontWeight: FontWeight.w900,
                        color: _textStrong,
                      ),
                    ),
                    const SizedBox(height: 7),
                    Text(
                      article.body,
                      maxLines: 3,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        color: Colors.grey.shade800,
                        fontSize: 12.2,
                        height: 1.5,
                      ),
                    ),
                  ],
                ),
              ),
            ),
            if (article.images.isNotEmpty && article.video == null)
              InkWell(
                onTap: onOpen,
                child: _NewsImageGallery(images: article.images),
              ),
            if (article.video != null)
              _LazyNewsVideoPreview(key:ValueKey(article.video!.path),video: article.video!),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
              decoration: BoxDecoration(
                color: const Color(0xFFFBFCFB),
                border: Border(top: BorderSide(color: Colors.grey.shade200)),
              ),
              child: Row(
                children: [
                  _SocialButton(
                    icon: article.likedByMe
                        ? Icons.favorite_rounded
                        : Icons.favorite_border_rounded,
                    label: article.likeCount == 0 ? 'Like' : '${article.likeCount}',
                    active: article.likedByMe,
                    onTap: onLike,
                  ),
                  const SizedBox(width: 2),
                  _SocialButton(
                    icon: Icons.mode_comment_outlined,
                    label: article.commentCount == 0 ? 'Comment' : '${article.commentCount}',
                    onTap: onComment,
                  ),
                  const Spacer(),
                  _SocialButton(
                    icon: Icons.ios_share_rounded,
                    label: compact ? '' : 'Share',
                    onTap: onShare,
                  ),
                  if (article.images.isNotEmpty || article.video != null)
                    PopupMenuButton<String>(
                      tooltip: 'Download media',
                      icon: const Icon(Icons.download_rounded, size: 20, color: _darkGreen),
                      onSelected: (value) async {
                        try {
                          if (value == 'photos') {
                            await NewsOfflineService.downloadPhotos(article.id);
                          } else if (value == 'video') {
                            await NewsOfflineService.downloadVideo(article.id);
                          }
                        } catch (e) {
                          if (context.mounted) {
                            ScaffoldMessenger.of(context).showSnackBar(
                              SnackBar(
                                content: Text(_cleanError(e)),
                                backgroundColor: Colors.red.shade700,
                              ),
                            );
                          }
                        }
                      },
                      itemBuilder: (_) => [
                        if (article.images.isNotEmpty)
                          const PopupMenuItem(
                            value: 'photos',
                            child: ListTile(
                              dense: true,
                              leading: Icon(Icons.photo_library_outlined),
                              title: Text('Download pictures'),
                            ),
                          ),
                        if (article.video != null)
                          const PopupMenuItem(
                            value: 'video',
                            child: ListTile(
                              dense: true,
                              leading: Icon(Icons.video_file_outlined),
                              title: Text('Download video'),
                            ),
                          ),
                      ],
                    ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _NewsImageGallery extends StatelessWidget {
  final List<CampusNewsImage> images;

  const _NewsImageGallery({required this.images});

  @override
  Widget build(BuildContext context) {
    if (images.isEmpty) return const SizedBox.shrink();
    final extra = images.length - 1;
    return SizedBox(
      height: 215,
      child: Stack(
        fit: StackFit.expand,
        children: [
          _NetworkNewsImage(path: images.first.previewPath, cacheWidth: 800),
          if (extra > 0)
            Positioned(
              right: 12,
              bottom: 12,
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.72),
                  borderRadius: BorderRadius.circular(10),
                  border: Border.all(color: Colors.white.withOpacity(0.18)),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    const Icon(Icons.photo_library_outlined, color: Colors.white, size: 16),
                    const SizedBox(width: 6),
                    Text(
                      '+$extra',
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 15,
                        fontWeight: FontWeight.w900,
                      ),
                    ),
                  ],
                ),
              ),
            ),
        ],
      ),
    );
  }
}

class _NetworkNewsImage extends StatelessWidget {
  final String path;final int cacheWidth;
  const _NetworkNewsImage({required this.path,this.cacheWidth=800});
  @override Widget build(BuildContext context)=>NewsCachedImage(url:NewsOfflineService.mediaUrl(path),decodeWidth:cacheWidth);
}

class _NewsVideoPlaybackCoordinator {
  static VideoPlayerController? _activeController;

  static Future<void> activate(VideoPlayerController controller) async {
    final previous = _activeController;
    if (previous != null && previous != controller) {
      try {
        if (previous.value.isInitialized && previous.value.isPlaying) {
          await previous.pause();
        }
      } catch (_) {
        // The previous controller may already have been disposed.
      }
    }
    _activeController = controller;
  }

  static void release(VideoPlayerController controller) {
    if (identical(_activeController, controller)) {
      _activeController = null;
    }
  }
}

/// A cached full-colour poster remains visible until playback starts.
class _LazyNewsVideoPreview extends StatefulWidget {
  final CampusNewsVideo video;final bool detailed;
  const _LazyNewsVideoPreview({super.key,required this.video,this.detailed=false});
  @override State<_LazyNewsVideoPreview> createState()=>_LazyNewsVideoPreviewState();
}
class _LazyNewsVideoPreviewState extends State<_LazyNewsVideoPreview> with WidgetsBindingObserver {
  VideoPlayerController? _controller;
  String? _temporaryPlaybackUrl;
  bool _requiresPlayTap = false;
  bool _initializing=false,_enabled=true,_foreground=true;
  String? _error;
  int _generation=0;
  @override void initState(){super.initState();WidgetsBinding.instance.addObserver(this);}
  @override void didChangeDependencies(){super.didChangeDependencies();_enabled=TickerMode.of(context);if(!_enabled)_controller?.pause();}
  @override void didChangeAppLifecycleState(AppLifecycleState state){_foreground=state==AppLifecycleState.resumed;if(!_foreground)_controller?.pause();}
  @override void didUpdateWidget(covariant _LazyNewsVideoPreview old){super.didUpdateWidget(old);if(old.video.path!=widget.video.path){_release();_error=null;}}
  void _release(){
    _generation++;final c=_controller;_controller=null;_initializing=false;
    final temporaryUrl=_temporaryPlaybackUrl;_temporaryPlaybackUrl=null;_requiresPlayTap=false;
    if(c!=null){
      _NewsVideoPlaybackCoordinator.release(c);c.removeListener(_changed);
      c.dispose().whenComplete(()=>releaseNewsVideoSource(temporaryUrl));
    }else{releaseNewsVideoSource(temporaryUrl);}
  }
  @override void dispose(){WidgetsBinding.instance.removeObserver(this);_release();super.dispose();}
  bool _lastPlaying=false,_lastBuffering=false;
  void _changed(){
    final c=_controller;if(!mounted||c==null)return;
    if(c.value.isPlaying!=_lastPlaying||c.value.isBuffering!=_lastBuffering||c.value.hasError){
      _lastPlaying=c.value.isPlaying;_lastBuffering=c.value.isBuffering;
      setState((){if(c.value.hasError)_error='Video unavailable. Check your connection and try again.';});
    }
  }
  Future<void> _toggle() async {
    if(_initializing)return;
    final existing=_controller;
    if(existing!=null&&existing.value.isInitialized&&_error==null){
      try{
        if(existing.value.isPlaying){await existing.pause();}
        else{
          if(existing.value.position>=existing.value.duration)await existing.seekTo(Duration.zero);
          if(!_enabled||!_foreground)return;
          await _NewsVideoPlaybackCoordinator.activate(existing);await existing.play();
        }
      }catch(_){if(mounted)setState(()=>_error='Playback interrupted. Tap to retry.');}
      return;
    }
    _release();final generation=_generation;
    setState((){_initializing=true;_error=null;});
    try{
      final url=NewsOfflineService.mediaUrl(widget.video.path);
      final headers=await NewsOfflineService.mediaHeaders(url);
      final source=await prepareNewsVideoSource(url,headers);
      final playbackUrl=source['url']! as String;
      final temporary=source['temporary']==true;
      final playbackHeaders=Map<String,String>.from(source['headers'] as Map);
      final preparedController=source['controller'];
      if(!mounted||generation!=_generation){
        if(preparedController is VideoPlayerController)await preparedController.dispose();
        if(temporary)releaseNewsVideoSource(playbackUrl);
        return;
      }
      _requiresPlayTap=source['requiresTap']==true;
      if(temporary)_temporaryPlaybackUrl=playbackUrl;
      final c=preparedController is VideoPlayerController
          ? preparedController
          : VideoPlayerController.networkUrl(Uri.parse(playbackUrl),httpHeaders:playbackHeaders,videoPlayerOptions:VideoPlayerOptions(mixWithOthers:true));
      _controller=c;c.addListener(_changed);
      await c.initialize().timeout(const Duration(seconds:25));
      if(!mounted||generation!=_generation)return;
      await c.setLooping(false);
      if(_enabled&&_foreground&&!_requiresPlayTap){await _NewsVideoPlaybackCoordinator.activate(c);await c.play();}
      if(mounted&&generation==_generation)setState(()=>_initializing=false);
    }catch(_){
      if(!mounted||generation!=_generation)return;
      _release();setState(()=>_error='Unable to play. Reconnect and tap to retry.');
    }
  }
  @override Widget build(BuildContext context){
    final c=_controller;final ready=c!=null&&c.value.isInitialized;
    return LayoutBuilder(builder:(context,constraints){
      // Give portrait clips enough vertical room in the feed while keeping
      // their original aspect ratio inside the card.
      final height=(constraints.maxWidth*0.72).clamp(300.0,widget.detailed?620.0:520.0).toDouble();
      return ClipRRect(borderRadius:BorderRadius.circular(12),child:SizedBox(height:height,child:Stack(fit:StackFit.expand,children:[
        NewsVideoPoster(key:ValueKey(widget.video.path),video:widget.video),
        if(ready)Center(child:AspectRatio(aspectRatio:c.value.aspectRatio>0?c.value.aspectRatio:16/9,child:VideoPlayer(c))),
        // Poster fills letterboxing too; no opaque black surface behind the player.
        Material(color:Colors.transparent,child:InkWell(onTap:_toggle,child:const SizedBox.expand())),
        if(_initializing||(ready&&c.value.isBuffering))const Center(child:CircularProgressIndicator(color:Color(0xFFCC7504)))
        else if(!ready||!c.value.isPlaying||_error!=null)Center(child:IgnorePointer(child:Container(width:54,height:54,
          decoration:BoxDecoration(color:Colors.white.withOpacity(.95),shape:BoxShape.circle,boxShadow:[BoxShadow(color:Colors.black.withOpacity(.12),blurRadius:16)]),
          child:Icon(_error==null?Icons.play_arrow_rounded:Icons.refresh_rounded,color:_darkGreen,size:34)))),
        Positioned(top:10,left:10,child:Container(padding:const EdgeInsets.symmetric(horizontal:8,vertical:5),
          decoration:BoxDecoration(color:Colors.white.withOpacity(.93),borderRadius:BorderRadius.circular(7)),
          child:const Text('CAMPUS VIDEO',style:TextStyle(color:_darkGreen,fontSize:9,fontWeight:FontWeight.w800,letterSpacing:.6)))),
        Positioned(left:10,right:10,bottom:ready?24:10,child:IgnorePointer(child:Container(
          padding:const EdgeInsets.symmetric(horizontal:9,vertical:6),decoration:BoxDecoration(color:Colors.white.withOpacity(.92),borderRadius:BorderRadius.circular(8)),
          child:Row(children:[const Icon(Icons.videocam_outlined,color:_darkGreen,size:16),const SizedBox(width:6),
            Expanded(child:Text(_error??widget.video.fileName,maxLines:2,overflow:TextOverflow.ellipsis,style:const TextStyle(color:Color(0xFF263B2F),fontSize:10,fontWeight:FontWeight.w600))),
            const SizedBox(width:8),Text(widget.video.formattedSize,style:const TextStyle(color:Color(0xFF566A5C),fontSize:9)),
          ])))),
        if(ready)Positioned(left:10,right:10,bottom:8,child:VideoProgressIndicator(c,allowScrubbing:true,colors:const VideoProgressColors(playedColor:_standardGold,bufferedColor:Color(0xFF9FC4AC),backgroundColor:Color(0xFFE2EBE4)))),
      ])));
    });
  }
}

class _MediaDownloadBar extends StatelessWidget {
  final CampusNewsArticle article;

  const _MediaDownloadBar({required this.article});

  @override
  Widget build(BuildContext context) {
    Future<void> run(Future<void> Function() action) async {
      try {
        await action();
        if (context.mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('Download opened in the system download handler.')),
          );
        }
      } catch (e) {
        if (context.mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(_cleanError(e)), backgroundColor: Colors.red.shade700),
          );
        }
      }
    }

    return Wrap(
      spacing: 8,
      runSpacing: 8,
      children: [
        if (article.images.isNotEmpty)
          OutlinedButton.icon(
            onPressed: () => run(() => NewsOfflineService.downloadPhotos(article.id)),
            icon: const Icon(Icons.download_rounded, size: 17),
            label: Text(article.images.length == 1 ? 'Download picture' : 'Download ${article.images.length} pictures'),
          ),
        if (article.video != null)
          OutlinedButton.icon(
            onPressed: () => run(() => NewsOfflineService.downloadVideo(article.id)),
            icon: const Icon(Icons.video_file_outlined, size: 17),
            label: const Text('Download video'),
          ),
      ],
    );
  }
}

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 Material(
      color: Colors.transparent,
      borderRadius: BorderRadius.circular(9),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(9),
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 7),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                icon,
                size: 18,
                color: active ? Colors.red.shade600 : Colors.grey.shade600,
              ),
              if (label.isNotEmpty) ...[
                const SizedBox(width: 6),
                Text(
                  label,
                  style: TextStyle(
                    color: active ? Colors.red.shade700 : Colors.grey.shade700,
                    fontSize: 11,
                    fontWeight: FontWeight.w800,
                  ),
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }
}

class _CategoryChip extends StatelessWidget {
  final String label;

  const _CategoryChip({required this.label});

  @override
  Widget build(BuildContext context) {
    return Container(
      constraints: const BoxConstraints(maxWidth: 112),
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
      decoration: BoxDecoration(
        color: _standardGold.withOpacity(0.08),
        borderRadius: BorderRadius.circular(999),
        border: Border.all(color: _standardGold.withOpacity(0.32)),
      ),
      child: Text(
        label.toUpperCase(),
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
        style: const TextStyle(
          color: _standardGold,
          fontSize: 8.2,
          fontWeight: FontWeight.w900,
          letterSpacing: 0.45,
        ),
      ),
    );
  }
}

class _ProfileAvatar extends StatelessWidget {
  final String value;
  final double size;

  const _ProfileAvatar({required this.value, required this.size});

  @override
  Widget build(BuildContext context) {
    Widget child;
    final trimmed = value.trim();
    if (trimmed.isEmpty) {
      child = _avatarFallback();
    } else if (trimmed.startsWith('http://') ||
        trimmed.startsWith('https://') ||
        NewsOfflineService.isStoredMediaPath(trimmed)) {
      child = NewsCachedImage(url:NewsOfflineService.mediaUrl(trimmed),decodeWidth:120);
    } 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: (_, __, ___) => _avatarFallback(),
        );
      } catch (_) {
        child = _avatarFallback();
      }
    }

    return Container(
      width: size,
      height: size,
      clipBehavior: Clip.antiAlias,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        color: Colors.grey.shade100,
        border: Border.all(color: _standardGold.withOpacity(0.55), width: 1.5),
      ),
      child: child,
    );
  }

  Widget _avatarFallback() {
    return Container(
      color: Colors.grey.shade100,
      alignment: Alignment.center,
      child: Icon(Icons.person_rounded, color: Colors.grey.shade400, size: size * 0.55),
    );
  }
}
class CampusNewsComposerDialog extends StatefulWidget {
  final CampusNewsArticle? article;

  const CampusNewsComposerDialog({super.key, this.article});

  @override
  State<CampusNewsComposerDialog> createState() => _CampusNewsComposerDialogState();
}

class _CampusNewsComposerDialogState extends State<CampusNewsComposerDialog> {
  final _formKey = GlobalKey<FormState>();
  late final TextEditingController _titleController;
  late final TextEditingController _bodyController;
  final ImagePicker _picker = ImagePicker();

  final List<_PickedNewsImage> _newImages = [];
  late List<CampusNewsImage> _existingImages;
  _PickedNewsVideo? _newVideo;
  CampusNewsVideo? _existingVideo;
  String _category = 'Announcement';
  bool _isTrending = false;
  Map<String, dynamic>? _me;
  String? _accountError;
  bool _loadingAccount = true;
  bool _saving = false;

  @override
  void initState() {
    super.initState();
    _titleController = TextEditingController(text: widget.article?.title ?? '');
    _bodyController = TextEditingController(text: widget.article?.body ?? '');
    _category = widget.article?.category ?? 'Announcement';
    _isTrending = widget.article?.isTrending ?? false;
    if (!NewsOfflineService.categories.contains(_category)) _category = 'General';
    _existingImages = List<CampusNewsImage>.from(widget.article?.images ?? const []);
    _existingVideo = widget.article?.video;
    _loadAccount();
  }

  @override
  void dispose() {
    _titleController.dispose();
    _bodyController.dispose();
    super.dispose();
  }

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

  Future<void> _pickImages() async {
    if (_existingImages.length + _newImages.length >= 6) {
      _snack('A story can contain a maximum of 6 images.', error: true);
      return;
    }
    try {
      final files = await _picker.pickMultiImage(
        imageQuality: 72,
        maxWidth: 1280,
        maxHeight: 1800,
      );
      if (files.isEmpty) return;
      final remaining = 6 - (_existingImages.length + _newImages.length);
      for (final file in files.take(remaining)) {
        final bytes = await file.readAsBytes();
        _newImages.add(_PickedNewsImage(file: file, bytes: bytes));
      }
      if (mounted) setState(() {});
    } catch (e) {
      _snack('Unable to select images: ${_cleanError(e)}', error: true);
    }
  }

  Future<void> _removeExistingImage(CampusNewsImage image) async {
    try {
      await NewsOfflineService.deleteImage(image.id);
      if (!mounted) return;
      setState(() => _existingImages.removeWhere((item) => item.id == image.id));
    } catch (e) {
      _snack(_cleanError(e), error: true);
    }
  }

  Future<void> _pickVideo() async {
    if (_existingVideo != null || _newVideo != null) {
      _snack('Only one video can be attached to a news story.', error: true);
      return;
    }

    try {
      final file = await _picker.pickVideo(source: ImageSource.gallery);
      if (file == null) return;

      final size = await file.length();
      if (size > NewsOfflineService.maxVideoBytes) {
        _snack(
          'Video must not exceed 10 MB. Selected file is ${NewsOfflineService.formatBytes(size)}.',
          error: true,
        );
        return;
      }

      if (!mounted) return;
      setState(() {
        _newVideo = _PickedNewsVideo(file: file, sizeBytes: size);
      });
    } catch (e) {
      _snack('Unable to select video: ${_cleanError(e)}', error: true);
    }
  }

  Future<void> _removeExistingVideo() async {
    final video = _existingVideo;
    if (video == null) return;
    try {
      await NewsOfflineService.deleteVideo(video.id);
      if (!mounted) return;
      setState(() => _existingVideo = null);
    } catch (e) {
      _snack(_cleanError(e), error: true);
    }
  }

  Future<void> _save(String status) async {
    if(_saving||_me==null||!(_formKey.currentState?.validate()??false))return;
    setState(()=>_saving=true);
    try{
      await NewsOfflineService.queueStory(id:widget.article?.id,payload:{'title':_titleController.text.trim(),'body':_bodyController.text.trim(),'category':_category,'status':status,'isTrending':_isTrending},images:_newImages.map((i)=>i.file).toList(),video:_newVideo?.file);
      if(!mounted)return;
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content:Text('Story saved to outbox. Publication waits for server confirmation.')));
      Navigator.pop(context,true);
    }catch(e){_snack(_cleanError(e),error:true);}finally{if(mounted)setState(()=>_saving=false);}
  }

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

  @override
  Widget build(BuildContext context) {
    final isEditing = widget.article != null;
    return Dialog(
      insetPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
      backgroundColor: Colors.white,
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
      child: ConstrainedBox(
        constraints: BoxConstraints(
          maxWidth: 900,
          maxHeight: MediaQuery.of(context).size.height * 0.92,
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 22, vertical: 18),
              decoration: const BoxDecoration(
                color: _darkGreen,
                border: Border(bottom: BorderSide(color: _standardGold, width: 4)),
              ),
              child: Row(
                children: [
                  const Icon(Icons.edit_document, color: Colors.white),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Text(
                      isEditing ? 'EDIT CAMPUS NEWS' : 'CREATE CAMPUS NEWS',
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 17,
                        fontWeight: FontWeight.w900,
                        letterSpacing: 1.0,
                      ),
                    ),
                  ),
                  IconButton(
                    onPressed: _saving ? null : () => Navigator.pop(context, false),
                    icon: const Icon(Icons.close_rounded, color: Colors.white),
                  ),
                ],
              ),
            ),
            Expanded(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(24),
                child: Form(
                  key: _formKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _sectionTitle('AUTHOR & CAMPUS'),
                      const SizedBox(height: 12),
                      _buildAuthorPanel(),
                      const SizedBox(height: 28),
                      _sectionTitle('NEWS STORY'),
                      const SizedBox(height: 12),
                      _field(
                        controller: _titleController,
                        label: 'Headline',
                        icon: Icons.title_rounded,
                        maxLength: 180,
                        validator: (value) {
                          if (value == null || value.trim().length < 4) {
                            return 'Enter a clear headline of at least 4 characters.';
                          }
                          return null;
                        },
                      ),
                      const SizedBox(height: 14),
                      DropdownButtonFormField<String>(
                        value: _category,
                        decoration: _inputDecoration(
                          'News Category',
                          Icons.category_outlined,
                        ),
                        items: NewsOfflineService.categories
                            .map((item) => DropdownMenuItem(value: item, child: Text(item)))
                            .toList(),
                        onChanged: _saving
                            ? null
                            : (value) {
                                if (value != null) setState(() => _category = value);
                              },
                      ),
                      const SizedBox(height: 14),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
                        decoration: BoxDecoration(
                          color: _isTrending ? const Color(0xFFFFF5E8) : Colors.grey.shade50,
                          border: Border.all(color: _isTrending ? _standardGold.withOpacity(.55) : Colors.grey.shade300),
                        ),
                        child: Row(
                          children: [
                            Icon(Icons.local_fire_department_rounded, color: _isTrending ? Colors.deepOrange.shade600 : Colors.grey.shade500),
                            const SizedBox(width: 10),
                            Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                              const Text('Feature in Trending News', style: TextStyle(fontWeight: FontWeight.w800, fontSize: 12)),
                              const SizedBox(height: 3),
                              Text('Readers will see it in the trending panel and receive a notification when it is published.', style: TextStyle(color: Colors.grey.shade600, fontSize: 10.5, height: 1.35)),
                            ])),
                            Switch(
                              value: _isTrending,
                              activeColor: _darkGreen,
                              onChanged: _saving ? null : (value) => setState(() => _isTrending = value),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 14),
                      TextFormField(
                        controller: _bodyController,
                        minLines: 8,
                        maxLines: 16,
                        maxLength: 20000,
                        decoration: _inputDecoration(
                          'Write the full campus story',
                          Icons.notes_rounded,
                        ).copyWith(
                          alignLabelWithHint: true,
                          hintText:
                              'Explain what happened, why it matters, who is involved and any useful details for the campus community...',
                        ),
                        validator: (value) {
                          if (value == null || value.trim().length < 10) {
                            return 'Write at least 10 characters for the news story.';
                          }
                          return null;
                        },
                      ),
                      const SizedBox(height: 24),
                      _sectionTitle('PHOTOS'),
                      const SizedBox(height: 8),
                      Text(
                        'Attach up to 6 JPEG, PNG or WebP images. Choose clear images to illustrate your story.',
                        style: TextStyle(color: Colors.grey.shade600, fontSize: 12, height: 1.5),
                      ),
                      const SizedBox(height: 12),
                      _buildImagePicker(),
                      const SizedBox(height: 24),
                      _sectionTitle('VIDEO (OPTIONAL)'),
                      const SizedBox(height: 8),
                      Text(
                        'Attach one MP4, WebM or MOV video up to 10 MB. A small preview frame is prepared for the feed; playback starts only when tapped.',
                        style: TextStyle(color: Colors.grey.shade600, fontSize: 12, height: 1.5),
                      ),
                      const SizedBox(height: 12),
                      _buildVideoPicker(),
                    ],
                  ),
                ),
              ),
            ),
            Container(
              padding: const EdgeInsets.fromLTRB(18, 14, 18, 16),
              decoration: BoxDecoration(
                color: Colors.grey.shade50,
                border: Border(top: BorderSide(color: Colors.grey.shade200)),
              ),
              child: LayoutBuilder(
                builder: (context, constraints) {
                  final compact = constraints.maxWidth < 600;
                  final buttons = [
                    OutlinedButton.icon(
                      onPressed: _saving || _me == null ? null : () => _save('draft'),
                      icon: const Icon(Icons.save_outlined),
                      label: const Text('SAVE DRAFT OFFLINE'),
                      style: OutlinedButton.styleFrom(
                        foregroundColor: _darkGreen,
                        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 18),
                        shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                      ),
                    ),
                    ElevatedButton.icon(
                      onPressed: _saving || _me == null ? null : () => _save('published'),
                      icon: _saving
                          ? const SizedBox(
                              width: 17,
                              height: 17,
                              child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white),
                            )
                          : const Icon(Icons.public_rounded),
                      label: Text(_saving ? 'SAVING...' : 'QUEUE TO PUBLISH'),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: _darkGreen,
                        foregroundColor: Colors.white,
                        padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 18),
                        shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                      ),
                    ),
                  ];
                  if (compact) {
                    return Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        buttons[0],
                        const SizedBox(height: 10),
                        buttons[1],
                      ],
                    );
                  }
                  return Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [buttons[0], const SizedBox(width: 12), buttons[1]],
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildAuthorPanel() {
    if (_loadingAccount) {
      return Container(
        padding: const EdgeInsets.all(18),
        decoration: BoxDecoration(
          color: Colors.grey.shade50,
          border: Border.all(color: Colors.grey.shade300),
        ),
        child: const Row(
          children: [
            SizedBox(
              width: 20,
              height: 20,
              child: CircularProgressIndicator(strokeWidth: 2, color: _darkGreen),
            ),
            SizedBox(width: 12),
            Text('Retrieving your signed-in campus profile...'),
          ],
        ),
      );
    }

    if (_accountError != null || _me == null) {
      return Container(
        padding: const EdgeInsets.all(16),
        color: Colors.red.shade50,
        child: Row(
          children: [
            Icon(Icons.error_outline_rounded, color: Colors.red.shade700),
            const SizedBox(width: 12),
            Expanded(child: Text(_accountError ?? 'Unable to identify your account.')),
            TextButton(onPressed: _loadAccount, child: const Text('RETRY')),
          ],
        ),
      );
    }

    final me = _me!;
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: _darkGreen.withOpacity(0.045),
        border: Border.all(color: _darkGreen.withOpacity(0.18)),
      ),
      child: Row(
        children: [
          _ProfileAvatar(value: '${me['profile_picture'] ?? ''}', size: 52),
          const SizedBox(width: 14),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '${me['full_name'] ?? 'Rockview User'}',
                  style: const TextStyle(fontWeight: FontWeight.w900, fontSize: 14),
                ),
                const SizedBox(height: 4),
                Text(
                  '${me['campus'] ?? 'University Wide'}',
                  style: const TextStyle(color: _darkGreen, fontWeight: FontWeight.w800),
                ),
                const SizedBox(height: 2),
                Text(
                  'Your identity and campus are attached automatically and cannot be changed in this form.',
                  style: TextStyle(color: Colors.grey.shade600, fontSize: 10.5),
                ),
              ],
            ),
          ),
          const Icon(Icons.lock_outline_rounded, color: _darkGreen, size: 20),
        ],
      ),
    );
  }

  Widget _buildImagePicker() {
    final total = _existingImages.length + _newImages.length;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (total > 0)
          Wrap(
            spacing: 10,
            runSpacing: 10,
            children: [
              ..._existingImages.map(
                (image) => _ComposerImageTile(
                  child: _NetworkNewsImage(path: image.path),
                  onRemove: _saving ? null : () => _removeExistingImage(image),
                ),
              ),
              ..._newImages.asMap().entries.map(
                    (entry) => _ComposerImageTile(
                      child: Image.memory(entry.value.bytes, fit: BoxFit.cover),
                      onRemove: _saving
                          ? null
                          : () => setState(() => _newImages.removeAt(entry.key)),
                    ),
                  ),
            ],
          ),
        if (total > 0) const SizedBox(height: 12),
        OutlinedButton.icon(
          onPressed: _saving || total >= 6 ? null : _pickImages,
          icon: const Icon(Icons.add_photo_alternate_outlined),
          label: Text(total == 0 ? 'ADD PHOTOS' : 'ADD MORE PHOTOS ($total/6)'),
          style: OutlinedButton.styleFrom(
            foregroundColor: _darkGreen,
            padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 15),
            shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
          ),
        ),
      ],
    );
  }

  Widget _buildVideoPicker() {
    final hasVideo = _existingVideo != null || _newVideo != null;
    final existing = _existingVideo;
    final selected = _newVideo;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (hasVideo)
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: const Color(0xFFF7F9F8),
              border: Border.all(color: Colors.grey.shade300),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Row(
              children: [
                Container(
                  width: 48,
                  height: 48,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    color: _darkGreen.withOpacity(0.08),
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: const Icon(Icons.video_file_rounded, color: _darkGreen, size: 25),
                ),
                const SizedBox(width: 11),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        existing?.fileName ?? selected!.file.name,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: const TextStyle(fontSize: 11.5, fontWeight: FontWeight.w900),
                      ),
                      const SizedBox(height: 3),
                      Text(
                        existing?.formattedSize ?? NewsOfflineService.formatBytes(selected!.sizeBytes),
                        style: TextStyle(color: Colors.grey.shade600, fontSize: 10),
                      ),
                    ],
                  ),
                ),
                IconButton(
                  tooltip: 'Remove video',
                  onPressed: _saving
                      ? null
                      : existing != null
                          ? _removeExistingVideo
                          : () => setState(() => _newVideo = null),
                  icon: const Icon(Icons.close_rounded),
                ),
              ],
            ),
          ),
        if (hasVideo) const SizedBox(height: 10),
        OutlinedButton.icon(
          onPressed: _saving || hasVideo ? null : _pickVideo,
          icon: const Icon(Icons.video_library_outlined),
          label: Text(hasVideo ? 'VIDEO ATTACHED' : 'ADD VIDEO (MAX 10 MB)'),
          style: OutlinedButton.styleFrom(
            foregroundColor: _darkGreen,
            padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 15),
            shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
          ),
        ),
      ],
    );
  }

  Widget _sectionTitle(String text) {
    return Row(
      children: [
        Container(width: 4, height: 18, color: _standardGold),
        const SizedBox(width: 8),
        Text(
          text,
          style: const TextStyle(
            color: Color(0xFF303833),
            fontSize: 12,
            fontWeight: FontWeight.w900,
            letterSpacing: 1.2,
          ),
        ),
      ],
    );
  }

  Widget _field({
    required TextEditingController controller,
    required String label,
    required IconData icon,
    int? maxLength,
    String? Function(String?)? validator,
  }) {
    return TextFormField(
      controller: controller,
      maxLength: maxLength,
      decoration: _inputDecoration(label, icon),
      validator: validator,
    );
  }

  InputDecoration _inputDecoration(String label, IconData icon) {
    return InputDecoration(
      labelText: label,
      prefixIcon: Icon(icon, color: _darkGreen),
      filled: true,
      fillColor: Colors.grey.shade50,
      border: OutlineInputBorder(
        borderRadius: BorderRadius.zero,
        borderSide: BorderSide(color: Colors.grey.shade300),
      ),
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.zero,
        borderSide: BorderSide(color: Colors.grey.shade300),
      ),
      focusedBorder: const OutlineInputBorder(
        borderRadius: BorderRadius.zero,
        borderSide: BorderSide(color: _darkGreen, width: 1.5),
      ),
    );
  }
}

class _PickedNewsImage {
  final XFile file;
  final Uint8List bytes;

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

class _PickedNewsVideo {
  final XFile file;
  final int sizeBytes;

  const _PickedNewsVideo({required this.file, required this.sizeBytes});
}

class _ComposerImageTile extends StatelessWidget {
  final Widget child;
  final VoidCallback? onRemove;

  const _ComposerImageTile({required this.child, this.onRemove});

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 150,
      height: 110,
      child: Stack(
        fit: StackFit.expand,
        children: [
          Container(
            clipBehavior: Clip.antiAlias,
            decoration: BoxDecoration(border: Border.all(color: Colors.grey.shade300)),
            child: child,
          ),
          Positioned(
            top: 6,
            right: 6,
            child: Material(
              color: Colors.black.withOpacity(0.7),
              child: InkWell(
                onTap: onRemove,
                child: const Padding(
                  padding: EdgeInsets.all(6),
                  child: Icon(Icons.close_rounded, color: Colors.white, size: 17),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}


class NewsConversationDialog extends StatefulWidget {
  final CampusNewsArticle article;

  const NewsConversationDialog({super.key, required this.article});

  @override
  State<NewsConversationDialog> createState() => _NewsConversationDialogState();
}

class _NewsConversationDialogState extends State<NewsConversationDialog> {
  final TextEditingController _commentController = TextEditingController();
  final FocusNode _commentFocus = FocusNode();
  late CampusNewsArticle _article;
  List<CampusNewsComment> _comments = [];
  CampusNewsComment? _replyTo;
  final Set<int> _mentionUserIds = <int>{};
  Timer? _mentionDebounce;
  List<_MentionCandidate> _remoteMentionCandidates = const [];
  bool _mentionSearching = false;
  bool _loading = true;
  bool _posting = false;
  bool _liking = false;
  bool _readingComments=false;
  bool _showMentions = false;
  String _mentionQuery = '';
  String? _error;

  @override
  void initState() {
    super.initState();
    _article = widget.article;
    _commentController.addListener(_handleMentionInput);
    NewsOfflineService.revision.addListener(_loadComments);
    _loadComments();
  }

  @override
  void dispose() {
    _mentionDebounce?.cancel();
    NewsOfflineService.revision.removeListener(_loadComments);
    _commentController.removeListener(_handleMentionInput);
    _commentController.dispose();
    _commentFocus.dispose();
    super.dispose();
  }

  Future<void> _loadComments() async {
    if(!mounted||_readingComments)return;_readingComments=true;
    setState(() {
      _loading = _comments.isEmpty;
      _error = null;
    });
    try {
      final comments = await NewsOfflineService.getComments(_article.id);
      if (!mounted) return;
      setState(() {
        _comments = comments;
        _article = _article.copyWith(commentCount: comments.length);
        _loading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _loading = false;
        _error = _cleanError(e);
      });
    }finally{_readingComments=false;}
  }

  List<_MentionCandidate> get _mentionCandidates {
    final map = <int, _MentionCandidate>{};
    if (_article.authorId > 0) {
      map[_article.authorId] = _MentionCandidate(
        userId: _article.authorId,
        name: _article.authorName,
        avatar: _article.authorProfilePicture,
      );
    }
    for (final comment in _comments) {
      if (comment.userId <= 0) continue;
      map[comment.userId] = _MentionCandidate(
        userId: comment.userId,
        name: comment.authorName,
        avatar: comment.authorProfilePicture,
      );
    }
    for (final candidate in _remoteMentionCandidates) {
      if (candidate.userId > 0) map[candidate.userId] = candidate;
    }
    return map.values.toList()
      ..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
  }

  List<_MentionCandidate> get _filteredMentionCandidates {
    final query = _mentionQuery.trim().toLowerCase();
    final candidates = _mentionCandidates;
    if (query.isEmpty) return candidates.take(6).toList();
    return candidates
        .where((item) => item.name.toLowerCase().contains(query))
        .take(6)
        .toList();
  }

  void _handleMentionInput() {
    if (!mounted) return;
    final value = _commentController.value;
    final cursor = value.selection.baseOffset;
    if (cursor < 0 || cursor > value.text.length) return;
    final before = value.text.substring(0, cursor);
    final at = before.lastIndexOf('@');
    if (at < 0) {
      if (_showMentions) setState(() => _showMentions = false);
      return;
    }
    final afterAt = before.substring(at + 1);
    final lastNewline = afterAt.lastIndexOf('\n');
    if (lastNewline >= 0 || afterAt.length > 36) {
      if (_showMentions) setState(() => _showMentions = false);
      return;
    }

    // A mention remains active until punctuation is entered. Spaces are allowed
    // so full names such as "Mary Banda" can be selected.
    if (RegExp(r'[,;:!?()]').hasMatch(afterAt)) {
      if (_showMentions) setState(() => _showMentions = false);
      return;
    }

    setState(() {
      _mentionQuery = afterAt;
      _showMentions = true;
    });
    _scheduleMentionSearch(afterAt);
  }

  void _scheduleMentionSearch(String query) {
    _mentionDebounce?.cancel();
    final clean = query.trim();
    if (clean.isEmpty) {
      if (_remoteMentionCandidates.isNotEmpty || _mentionSearching) {
        setState(() {
          _remoteMentionCandidates = const [];
          _mentionSearching = false;
        });
      }
      return;
    }

    _mentionDebounce = Timer(const Duration(milliseconds: 260), () async {
      if (!mounted) return;
      setState(() => _mentionSearching = true);
      try {
        final users = await NewsOfflineService.searchMentionUsers(clean);
        if (!mounted || _mentionQuery.trim() != clean) return;
        setState(() {
          _remoteMentionCandidates = users
              .map(
                (user) => _MentionCandidate(
                  userId: user.id,
                  name: user.fullName,
                  avatar: user.profilePicture,
                ),
              )
              .toList();
          _mentionSearching = false;
        });
      } catch (_) {
        if (!mounted) return;
        setState(() => _mentionSearching = false);
      }
    });
  }

  void _insertMention(_MentionCandidate candidate) {
    final value = _commentController.value;
    final cursor = value.selection.baseOffset < 0
        ? value.text.length
        : value.selection.baseOffset;
    final before = value.text.substring(0, cursor);
    final at = before.lastIndexOf('@');
    if (at < 0) return;
    final replacement = '@${candidate.name} ';
    final nextText = value.text.replaceRange(at, cursor, replacement);
    final nextCursor = at + replacement.length;
    _mentionUserIds.add(candidate.userId);
    _commentController.value = TextEditingValue(
      text: nextText,
      selection: TextSelection.collapsed(offset: nextCursor),
    );
    setState(() {
      _showMentions = false;
      _remoteMentionCandidates = const [];
    });
    _commentFocus.requestFocus();
  }

  void _startReply(CampusNewsComment comment) {
    setState(() {
      _replyTo = comment;
      _showMentions = false;
    });
    final prefix = '@${comment.authorName} ';
    final current = _commentController.text.trimLeft();
    if (!current.startsWith(prefix)) {
      _commentController.text = '$prefix${_commentController.text}';
      _commentController.selection = TextSelection.collapsed(
        offset: _commentController.text.length,
      );
    }
    _commentFocus.requestFocus();
  }

  void _cancelReply() {
    setState(() => _replyTo = null);
  }

  Future<void> _postComment() async {
    final text = _commentController.text.trim();
    if (text.isEmpty || _posting) return;
    setState(() => _posting = true);
    try {
      await NewsOfflineService.queueAction('comment',_article.id,{'text':text,'parent':_replyTo?.id,'mentions':_mentionUserIds.toList()});
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content:Text('Comment saved to outbox.')));
      setState(() {

        _mentionUserIds.clear();
        _replyTo = null;
        _showMentions = false;
        _remoteMentionCandidates = const [];
        _mentionSearching = false;
        _posting = false;
        _commentController.clear();
      });
    } catch (e) {
      if (!mounted) return;
      setState(() => _posting = false);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(_cleanError(e)),
          backgroundColor: Colors.red.shade700,
        ),
      );
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return Dialog(
      insetPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 12),
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      clipBehavior: Clip.antiAlias,
      child: ConstrainedBox(
        constraints: BoxConstraints(
          maxWidth: 1040,
          maxHeight: MediaQuery.of(context).size.height * 0.94,
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Container(
              height: 58,
              padding: const EdgeInsets.symmetric(horizontal: 17),
              decoration: const BoxDecoration(
                color: _darkGreen,
                border: Border(bottom: BorderSide(color: _standardGold, width: 3)),
              ),
              child: Row(
                children: [
                  const Icon(Icons.forum_rounded, color: Colors.white, size: 21),
                  const SizedBox(width: 10),
                  const Expanded(
                    child: Text(
                      'CAMPUS NEWS CONVERSATION',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 13,
                        fontWeight: FontWeight.w900,
                        letterSpacing: 0.8,
                      ),
                    ),
                  ),
                  IconButton(
                    onPressed: () => Navigator.pop(context, _article),
                    icon: const Icon(Icons.close_rounded, color: Colors.white),
                  ),
                ],
              ),
            ),
            Expanded(
              child: LayoutBuilder(
                builder: (context, constraints) {
                  final wide = constraints.maxWidth >= 820;
                  if (wide) {
                    return Row(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        Expanded(flex: 6, child: _buildArticlePane()),
                        VerticalDivider(width: 1, color: Colors.grey.shade300),
                        Expanded(flex: 4, child: _buildCommentsPane()),
                      ],
                    );
                  }

                  return DefaultTabController(
                    length: 2,
                    child: Column(
                      children: [
                        const Material(
                          color: Colors.white,
                          child: TabBar(
                            labelColor: _darkGreen,
                            unselectedLabelColor: Color(0xFF6E7771),
                            indicatorColor: _standardGold,
                            tabs: [
                              Tab(text: 'STORY'),
                              Tab(text: 'COMMENTS'),
                            ],
                          ),
                        ),
                        Expanded(
                          child: TabBarView(
                            children: [
                              _buildArticlePane(),
                              _buildCommentsPane(),
                            ],
                          ),
                        ),
                      ],
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildArticlePane() {
    return ColoredBox(
      color: Colors.white,
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                _ProfileAvatar(value: _article.authorProfilePicture, size: 46),
                const SizedBox(width: 11),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        _article.authorName,
                        style: const TextStyle(fontWeight: FontWeight.w900, fontSize: 13),
                      ),
                      const SizedBox(height: 3),
                      Text(
                        '${_article.campus.isEmpty ? 'Rockview University' : _article.campus} • ${_timeAgo(_article.publishedAt ?? _article.createdAt)}',
                        style: TextStyle(color: Colors.grey.shade600, fontSize: 10.5),
                      ),
                    ],
                  ),
                ),
                _CategoryChip(label: _article.category),
              ],
            ),
            const SizedBox(height: 18),
            Text(
              _article.title,
              style: const TextStyle(
                fontSize: 21,
                fontWeight: FontWeight.w900,
                height: 1.2,
                color: _textStrong,
              ),
            ),
            const SizedBox(height: 12),
            Text(
              _article.body,
              style: TextStyle(color: Colors.grey.shade800, fontSize: 13.5, height: 1.65),
            ),
            if (_article.images.isNotEmpty) ...[
              const SizedBox(height: 18),
              _ArticleImageViewer(images: _article.images),
            ],
            if (_article.video != null) ...[
              const SizedBox(height: 18),
              _LazyNewsVideoPreview(video: _article.video!, detailed: true),
            ],
            if (_article.images.isNotEmpty || _article.video != null) ...[
              const SizedBox(height: 12),
              _MediaDownloadBar(article: _article),
            ],
          ],
        ),
      ),
    );
  }

  Widget _buildCommentsPane() {
    return Column(
      children: [
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 7),
          decoration: BoxDecoration(
            color: const Color(0xFFF8FAF9),
            border: Border(bottom: BorderSide(color: Colors.grey.shade200)),
          ),
          child: Row(
            children: [
              _SocialButton(
                icon: _article.likedByMe
                    ? Icons.favorite_rounded
                    : Icons.favorite_border_rounded,
                label: '${_article.likeCount}',
                active: _article.likedByMe,
                onTap: _toggleLike,
              ),
              const SizedBox(width: 4),
              const Icon(Icons.mode_comment_outlined, size: 17, color: Color(0xFF69726D)),
              const SizedBox(width: 6),
              Text(
                '${_article.commentCount} comments',
                style: TextStyle(
                  color: Colors.grey.shade700,
                  fontSize: 11.5,
                  fontWeight: FontWeight.w800,
                ),
              ),
            ],
          ),
        ),
        Expanded(child: _buildCommentList()),
        _buildCommentComposer(),
      ],
    );
  }

  Widget _buildCommentList() {
    if (_loading) {
      return const Center(child: CircularProgressIndicator(color: _darkGreen));
    }
    if (_error != null) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(Icons.error_outline, color: Colors.red.shade400),
              const SizedBox(height: 8),
              Text(_error!, textAlign: TextAlign.center),
              const SizedBox(height: 10),
              TextButton(onPressed: _loadComments, child: const Text('TRY AGAIN')),
            ],
          ),
        ),
      );
    }
    if (_comments.isEmpty) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.all(28),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(Icons.chat_bubble_outline_rounded, size: 42, color: Colors.grey.shade300),
              const SizedBox(height: 11),
              const Text('No comments yet', style: TextStyle(fontWeight: FontWeight.w900)),
              const SizedBox(height: 5),
              Text(
                'Start a respectful campus conversation.',
                textAlign: TextAlign.center,
                style: TextStyle(color: Colors.grey.shade600, fontSize: 12),
              ),
            ],
          ),
        ),
      );
    }

    final roots = _comments.where((comment) => comment.parentCommentId == null).toList();
    return ListView.builder(
      padding: const EdgeInsets.fromLTRB(12, 12, 12, 18),
      itemCount: roots.length,
      itemBuilder: (context, index) {
        return Padding(
          padding: const EdgeInsets.only(bottom: 12),
          child: _buildCommentBranch(roots[index], 0),
        );
      },
    );
  }

  Widget _buildCommentBranch(CampusNewsComment comment, int depth) {
    final children = _comments.where((item) => item.parentCommentId == comment.id).toList();
    final safeDepth = depth.clamp(0, 3).toInt();
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Padding(
          padding: EdgeInsets.only(left: safeDepth * 22.0),
          child: _CommentTile(
            comment: comment,
            depth: safeDepth,
            onReply: () => _startReply(comment),
          ),
        ),
        if (children.isNotEmpty)
          ...children.map(
            (child) => Padding(
              padding: const EdgeInsets.only(top: 8),
              child: _buildCommentBranch(child, depth + 1),
            ),
          ),
      ],
    );
  }

  Widget _buildCommentComposer() {
    final suggestions = _filteredMentionCandidates;
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(top: BorderSide(color: Colors.grey.shade300)),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          if (_replyTo != null)
            Container(
              width: double.infinity,
              padding: const EdgeInsets.fromLTRB(12, 8, 8, 8),
              color: _darkGreen.withOpacity(0.055),
              child: Row(
                children: [
                  const Icon(Icons.reply_rounded, size: 16, color: _darkGreen),
                  const SizedBox(width: 7),
                  Expanded(
                    child: Text(
                      'Replying to ${_replyTo!.authorName}',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: const TextStyle(
                        color: _darkGreen,
                        fontSize: 11,
                        fontWeight: FontWeight.w800,
                      ),
                    ),
                  ),
                  IconButton(
                    tooltip: 'Cancel reply',
                    visualDensity: VisualDensity.compact,
                    onPressed: _cancelReply,
                    icon: const Icon(Icons.close_rounded, size: 17),
                  ),
                ],
              ),
            ),
          if (_showMentions && suggestions.isNotEmpty)
            Container(
              constraints: const BoxConstraints(maxHeight: 165),
              decoration: BoxDecoration(
                color: Colors.white,
                border: Border(bottom: BorderSide(color: Colors.grey.shade200)),
              ),
              child: ListView.builder(
                shrinkWrap: true,
                padding: const EdgeInsets.symmetric(vertical: 4),
                itemCount: suggestions.length,
                itemBuilder: (context, index) {
                  final item = suggestions[index];
                  return InkWell(
                    onTap: () => _insertMention(item),
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 7),
                      child: Row(
                        children: [
                          _ProfileAvatar(value: item.avatar, size: 28),
                          const SizedBox(width: 9),
                          Expanded(
                            child: Text(
                              item.name,
                              style: const TextStyle(fontSize: 11.5, fontWeight: FontWeight.w800),
                            ),
                          ),
                          const Text(
                            'MENTION',
                            style: TextStyle(
                              color: _darkGreen,
                              fontSize: 8.5,
                              fontWeight: FontWeight.w900,
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            ),
          Padding(
            padding: const EdgeInsets.all(10),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Expanded(
                  child: TextField(
                    controller: _commentController,
                    focusNode: _commentFocus,
                    minLines: 1,
                    maxLines: 4,
                    maxLength: 1000,
                    style: const TextStyle(fontSize: 12.5),
                    decoration: InputDecoration(
                      hintText: 'Write a comment or type @ to mention...',
                      counterText: '',
                      filled: true,
                      fillColor: const Color(0xFFF7F9F8),
                      contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 11),
                      suffixIcon: IconButton(
                        tooltip: 'Mention someone',
                        onPressed: () {
                          final text = _commentController.text;
                          final prefix = text.isEmpty || text.endsWith(' ') ? '@' : ' @';
                          _commentController.text = '$text$prefix';
                          _commentController.selection = TextSelection.collapsed(
                            offset: _commentController.text.length,
                          );
                          _commentFocus.requestFocus();
                        },
                        icon: const Icon(Icons.alternate_email_rounded, color: _darkGreen, size: 19),
                      ),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(11),
                        borderSide: BorderSide(color: Colors.grey.shade300),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(11),
                        borderSide: BorderSide(color: Colors.grey.shade300),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(11),
                        borderSide: const BorderSide(color: _darkGreen),
                      ),
                    ),
                    onSubmitted: (_) => _postComment(),
                  ),
                ),
                const SizedBox(width: 7),
                SizedBox(
                  width: 46,
                  height: 46,
                  child: ElevatedButton(
                    onPressed: _posting ? null : _postComment,
                    style: ElevatedButton.styleFrom(
                      padding: EdgeInsets.zero,
                      backgroundColor: _darkGreen,
                      foregroundColor: Colors.white,
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(11)),
                    ),
                    child: _posting
                        ? const SizedBox(
                            width: 17,
                            height: 17,
                            child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white),
                          )
                        : const Icon(Icons.send_rounded, size: 20),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class _ArticleImageViewer extends StatefulWidget {
  final List<CampusNewsImage> images;

  const _ArticleImageViewer({required this.images});

  @override
  State<_ArticleImageViewer> createState() => _ArticleImageViewerState();
}

class _ArticleImageViewerState extends State<_ArticleImageViewer> {
  int _index = 0;

  @override
  Widget build(BuildContext context) {
    final images = widget.images;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ClipRRect(
          borderRadius: BorderRadius.circular(12),
          child: AspectRatio(
            aspectRatio: 16 / 9,
            child: _NetworkNewsImage(path: images[_index].path),
          ),
        ),
        if (images.length > 1) ...[
          const SizedBox(height: 9),
          SizedBox(
            height: 62,
            child: ListView.separated(
              scrollDirection: Axis.horizontal,
              itemCount: images.length,
              separatorBuilder: (_, __) => const SizedBox(width: 7),
              itemBuilder: (context, index) {
                final selected = index == _index;
                return InkWell(
                  onTap: () => setState(() => _index = index),
                  child: Container(
                    width: 82,
                    clipBehavior: Clip.antiAlias,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(
                        color: selected ? _standardGold : _panelBorder,
                        width: selected ? 2 : 1,
                      ),
                    ),
                    child: _NetworkNewsImage(path: images[index].previewPath, cacheWidth: 300),
                  ),
                );
              },
            ),
          ),
        ],
      ],
    );
  }
}

class _CommentTile extends StatelessWidget {
  final CampusNewsComment comment;
  final int depth;
  final VoidCallback onReply;

  const _CommentTile({
    required this.comment,
    required this.depth,
    required this.onReply,
  });

  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _ProfileAvatar(value: comment.authorProfilePicture, size: depth == 0 ? 34 : 30),
        const SizedBox(width: 8),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                width: double.infinity,
                padding: const EdgeInsets.fromLTRB(10, 9, 10, 9),
                decoration: BoxDecoration(
                  color: depth == 0 ? const Color(0xFFF6F8F7) : const Color(0xFFFAFBFA),
                  border: Border.all(color: Colors.grey.shade200),
                  borderRadius: BorderRadius.circular(11),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Expanded(
                          child: Text(
                            comment.authorName,
                            style: const TextStyle(fontWeight: FontWeight.w900, fontSize: 11.5),
                          ),
                        ),
                        Text(
                          _timeAgo(comment.createdAt),
                          style: TextStyle(color: Colors.grey.shade500, fontSize: 8.5),
                        ),
                      ],
                    ),
                    if (comment.replyToAuthorName.isNotEmpty) ...[
                      const SizedBox(height: 3),
                      Text(
                        'Replying to ${comment.replyToAuthorName}',
                        style: const TextStyle(
                          color: _darkGreen,
                          fontSize: 9.5,
                          fontWeight: FontWeight.w700,
                        ),
                      ),
                    ],
                    const SizedBox(height: 5),
                    Text(
                      comment.comment,
                      style: TextStyle(color: Colors.grey.shade800, fontSize: 11.5, height: 1.42),
                    ),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(left: 5, top: 2),
                child: TextButton.icon(
                  onPressed: onReply,
                  style: TextButton.styleFrom(
                    visualDensity: VisualDensity.compact,
                    padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),
                    foregroundColor: _darkGreen,
                  ),
                  icon: const Icon(Icons.reply_rounded, size: 14),
                  label: const Text(
                    'Reply',
                    style: TextStyle(fontSize: 10, fontWeight: FontWeight.w800),
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }
}

class _MentionCandidate {
  final int userId;
  final String name;
  final String avatar;

  const _MentionCandidate({
    required this.userId,
    required this.name,
    required this.avatar,
  });
}

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

String _timeAgo(DateTime date) {
  final now = DateTime.now();
  final local = date.toLocal();
  final diff = now.difference(local);
  if (diff.isNegative) return 'just now';
  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';
  if (diff.inDays < 30) return '${(diff.inDays / 7).floor()}w ago';
  return '${local.day.toString().padLeft(2, '0')}/${local.month.toString().padLeft(2, '0')}/${local.year}';
}

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