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

import 'package:flutter/material.dart';

import '../../../../core/services/news_offline_service.dart';
import 'news_offline_widgets.dart';
import 'draft_news_sub_tab.dart';
import 'published_news_sub_tab.dart';

const Color _standardGold = Color.fromARGB(255, 204, 117, 4);
const Color _darkGreen = Color.fromARGB(255, 2, 105, 48);
const Color _shellBackground = Color(0xFFF3F5F4);
const Color _shellBorder = Color(0xFFE1E6E3);
const Color _shellText = Color(0xFF18221C);

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

  @override
  State<StaffNewsMainTab> createState() => _StaffNewsMainTabState();
}

class _StaffNewsMainTabState extends State<StaffNewsMainTab> with WidgetsBindingObserver {
  int _currentViewIndex = 0;
  bool _mobileNavigationOpen = false;
  bool _notificationsLoading = false;
  int _unreadNotifications = 0;
  List<CampusNewsNotification> _notifications = const [];
  List<CampusNewsArticle> _trendingArticles = const [];
  bool _trendingLoading = false;
  DateTime? _lastTrendingRefresh;
  Map<String, dynamic>? _me;
  final Set<int> _visited={0};
  bool _headerExpanded=false;

  final List<_NewsMenuItem> _items = const [
    _NewsMenuItem(
      title: 'Campus News',
      subtitle: 'Stories and conversations',
      icon: Icons.dynamic_feed_rounded,
    ),
    _NewsMenuItem(
      title: 'My Drafts',
      subtitle: 'Prepare and publish stories',
      icon: Icons.edit_note_rounded,
    ),
  ];

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    NewsOfflineService.revision.addListener(_loadShellData);
    NewsOfflineService.accountScope.addListener(_accountChanged);
    NewsOfflineService.start().then((_)=>_loadShellData()).catchError((Object _){});

  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    NewsOfflineService.revision.removeListener(_loadShellData);
    NewsOfflineService.accountScope.removeListener(_accountChanged);
    NewsOfflineService.stop();
    super.dispose();
  }

  void _accountChanged(){if(mounted)setState((){_me=null;_notifications=[];_trendingArticles=[];_unreadNotifications=0;_currentViewIndex=0;});}
  @override void didChangeAppLifecycleState(AppLifecycleState state){final active=state==AppLifecycleState.resumed;NewsOfflineService.setForeground(active);if(active)NewsOfflineService.sync();}
  Future<void> _loadShellData() async {
    await Future.wait<void>([
      _loadCurrentUser(),
      _loadNotifications(silent: true),
      _loadTrendingNews(),
    ]);
  }

  Future<void> _loadTrendingNews({bool force=false})async{
    if(_trendingLoading)return;
    final last=_lastTrendingRefresh;
    if(!force&&last!=null&&DateTime.now().difference(last)<const Duration(seconds:20))return;
    _trendingLoading=true;
    try{
      final page=await NewsOfflineService.getNews(
        status:'published',campus:'All Campuses',category:'All Categories',
        search:'',page:1,limit:40,
      );
      final stories=List<CampusNewsArticle>.from(page.articles.where((article)=>article.isTrending));
      stories.sort((a,b){
        final scoreA=a.likeCount+(a.commentCount*2);
        final scoreB=b.likeCount+(b.commentCount*2);
        final byEngagement=scoreB.compareTo(scoreA);
        return byEngagement!=0?byEngagement:b.createdAt.compareTo(a.createdAt);
      });
      if(mounted)setState(()=>_trendingArticles=stories.take(5).toList());
      _lastTrendingRefresh=DateTime.now();
    }catch(_){/* Keep the last offline-first trending list visible. */}
    finally{_trendingLoading=false;}
  }

  Future<void> _openTrendingArticle(CampusNewsArticle article,{bool closePanel=false})async{
    if(closePanel)Navigator.of(context).pop();
    await Future<void>.delayed(const Duration(milliseconds:100));
    if(!mounted)return;
    await showDialog<CampusNewsArticle>(
      context:context,
      builder:(_)=>NewsAccountGuard(child:NewsConversationDialog(article:article)),
    );
  }

  Future<void> _openTrendingPanel()async{
    await _loadTrendingNews(force:true);
    if(!mounted)return;
    await showModalBottomSheet<void>(
      context:context,
      isScrollControlled:true,
      backgroundColor:Colors.transparent,
      builder:(_)=>DraggableScrollableSheet(
        initialChildSize:.72,minChildSize:.4,maxChildSize:.94,
        builder:(context,controller)=>Container(
          decoration:const BoxDecoration(color:Colors.white,borderRadius:BorderRadius.vertical(top:Radius.circular(22))),
          child:SafeArea(top:false,child:ListView(
            controller:controller,
            padding:const EdgeInsets.fromLTRB(16,10,16,22),
            children:[_trendingPanelContent(compact:true)],
          )),
        ),
      ),
    );
  }

  Future<void> _loadCurrentUser() async {
    try {
      final user = await NewsOfflineService.getCurrentUser();
      if (!mounted) return;
      setState(() => _me = user);
    } catch (_) {
      // The feed remains usable even if the compact profile panel cannot load.
    }
  }

  Future<void> _loadNotifications({bool silent = false}) async {
    if (_notificationsLoading) return;
    if(mounted)setState(()=>_notificationsLoading=true);
    try {
      final page = await NewsOfflineService.getNotifications(limit: 50);
      if (!mounted) return;
      setState(() {
        _notifications = page.notifications;
        _unreadNotifications = page.unreadCount;
        _notificationsLoading = false;
      });
    } catch (_) {
      if (!mounted) return;
      setState(() => _notificationsLoading = false);
    }
  }

  void _switchTab(int index) {
    setState(() {
      _currentViewIndex = index;
      _visited.add(index);
      _mobileNavigationOpen = false;
    });
  }

  Widget _currentTab()=>ValueListenableBuilder<String>(valueListenable:NewsOfflineService.accountScope,builder:(context,scope,_)=>scope.isEmpty
    ?const Center(child:Text('Sign in to open saved campus news.'))
    :IndexedStack(key:ValueKey(scope),index:_currentViewIndex,children:[
      TickerMode(enabled:_currentViewIndex==0,child:const PublishedNewsSubTab(key:ValueKey('news-feed'))),
      if(_visited.contains(1))TickerMode(enabled:_currentViewIndex==1,child:const DraftNewsSubTab(key:ValueKey('news-drafts')))else const SizedBox.shrink(),
    ]));

  Future<void> _openNotifications() async {
    await _loadNotifications();
    if (!mounted) return;

    final compact = MediaQuery.sizeOf(context).width < 700;
    if (compact) {
      await showModalBottomSheet<void>(
        context: context,
        isScrollControlled: true,
        backgroundColor: Colors.transparent,
        builder: (_) => FractionallySizedBox(
          heightFactor: 0.82,
          child: _NotificationPanel(
            notifications: _notifications,
            unreadCount: _unreadNotifications,
            loading: _notificationsLoading,
            onRefresh: _loadNotifications,
            onRead: _readNotification,
            onReadAll: _readAllNotifications,
          ),
        ),
      );
      return;
    }

    await showDialog<void>(
      context: context,
      builder: (_) => Dialog(
        alignment: Alignment.topRight,
        insetPadding: const EdgeInsets.fromLTRB(20, 78, 28, 24),
        backgroundColor: Colors.transparent,
        child: SizedBox(
          width: 430,
          height: 610,
          child: _NotificationPanel(
            notifications: _notifications,
            unreadCount: _unreadNotifications,
            loading: _notificationsLoading,
            onRefresh: _loadNotifications,
            onRead: _readNotification,
            onReadAll: _readAllNotifications,
          ),
        ),
      ),
    );
  }

  Future<void> _readNotification(CampusNewsNotification notification) async {
    if (!notification.isRead) {
      setState(() {
        _notifications = _notifications
            .map(
              (item) => item.id == notification.id
                  ? item.copyWith(isRead: true)
                  : item,
            )
            .toList();
        _unreadNotifications =
            (_unreadNotifications - 1).clamp(0, 999).toInt();
      });
      try {
        await NewsOfflineService.markNotificationRead(notification.id);
      } catch (_) {
        _loadNotifications(silent: true);
      }
    }

    CampusNewsArticle? article;
    try {
      article = await NewsOfflineService.getArticle(notification.newsId);
    } catch (_) {}

    if (!mounted) return;
    Navigator.of(context, rootNavigator: true).maybePop();
    _switchTab(0);

    if (article != null) {
      await Future<void>.delayed(const Duration(milliseconds: 120));
      if (!mounted) return;
      await showDialog<CampusNewsArticle>(
        context: context,
        builder: (_) => NewsAccountGuard(child:NewsConversationDialog(article: article!)),
      );
    }
  }

  Future<void> _readAllNotifications() async {
    if (_unreadNotifications == 0) return;
    setState(() {
      _unreadNotifications = 0;
      _notifications = _notifications
          .map((item) => item.copyWith(isRead: true))
          .toList();
    });
    try {
      await NewsOfflineService.markAllNotificationsRead();
    } catch (_) {
      _loadNotifications(silent: true);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: _shellBackground,
      body: LayoutBuilder(
        builder: (context, constraints) {
          final width = constraints.maxWidth;
          final desktop = width >= 1180;
          final tablet = width >= 820 && width < 1180;
          final mobile = width < 820;

          return Stack(
            children: [
              Column(
                children: [
                  if(_headerExpanded)_buildHeader(mobile: mobile),
                  SafeArea(bottom:false,child:Padding(padding:const EdgeInsets.symmetric(horizontal:12),child:Row(children:[
                    if(mobile)IconButton(tooltip:'News navigation',onPressed:()=>setState(()=>_mobileNavigationOpen=true),icon:const Icon(Icons.menu_rounded,color:_darkGreen)),
                    const Expanded(child:Text('Campus News',style:TextStyle(fontWeight:FontWeight.w800,color:_darkGreen))),
                    IconButton(tooltip:'Trending campus news',onPressed:_openTrendingPanel,icon:const Icon(Icons.trending_up_rounded,color:_standardGold)),
                    IconButton(tooltip:'Sync news',onPressed:()=>NewsOfflineService.sync(force:true),icon:const Icon(Icons.refresh_rounded,color:_darkGreen)),
                    IconButton(tooltip:_headerExpanded?'Collapse header':'Expand header',onPressed:()=>setState(()=>_headerExpanded=!_headerExpanded),icon:Icon(_headerExpanded?Icons.unfold_less_rounded:Icons.unfold_more_rounded,color:_darkGreen)),
                    _NotificationBell(count:_unreadNotifications,loading:_notificationsLoading,onTap:_openNotifications),
                  ]))),
                  Expanded(
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        if (!mobile)
                          SizedBox(
                            width: desktop ? 210 : 78,
                            child: _buildLeftPanel(compact: tablet),
                          ),
                        if (!mobile)
                          const VerticalDivider(width: 1, color: _shellBorder),
                        Expanded(
                          child: _currentTab(),
                        ),
                        if(desktop)...[
                          const VerticalDivider(width:1,color:_shellBorder),
                          SizedBox(width:270,child:_buildRightPanel()),
                        ],

                      ],
                    ),
                  ),
                ],
              ),
              if (_mobileNavigationOpen) ...[
                Positioned.fill(
                  child: GestureDetector(
                    onTap: () => setState(() => _mobileNavigationOpen = false),
                    child: Container(color: Colors.black.withOpacity(0.34)),
                  ),
                ),
                Positioned(
                  top: 0,
                  bottom: 0,
                  left: 0,
                  child: Material(
                    elevation: 14,
                    color: Colors.white,
                    child: SizedBox(
                      width: 286,
                      child: SafeArea(child: _buildLeftPanel(compact: false, mobileDrawer: true)),
                    ),
                  ),
                ),
              ],
            ],
          );
        },
      ),
    );
  }

  Widget _buildHeader({required bool mobile}) {
    return SafeArea(
      bottom: false,
      child: Container(
        height: mobile ? 62 : 68,
        padding: EdgeInsets.symmetric(horizontal: mobile ? 12 : 18),
        decoration: const BoxDecoration(
          color: Colors.white,
          border: Border(bottom: BorderSide(color: _shellBorder)),
        ),
        child: Row(
          children: [
            if (mobile) ...[
              _ShellIconButton(
                icon: Icons.menu_rounded,
                tooltip: 'Open news navigation',
                onTap: () => setState(() => _mobileNavigationOpen = true),
              ),
              const SizedBox(width: 10),
            ],
            Container(
              width: 34,
              height: 34,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: _darkGreen,
                borderRadius: BorderRadius.circular(10),
              ),
              child: const Icon(Icons.newspaper_rounded, color: Colors.white, size: 19),
            ),
            const SizedBox(width: 10),
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  RichText(
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    text: TextSpan(
                      children: [
                        TextSpan(
                          text: 'ROCKVIEW ',
                          style: TextStyle(
                            color: _darkGreen,
                            fontSize: mobile ? 15 : 17,
                            fontWeight: FontWeight.w900,
                            letterSpacing: 0.7,
                          ),
                        ),
                        TextSpan(
                          text: 'CAMPUS NEWS',
                          style: TextStyle(
                            color: _standardGold,
                            fontSize: mobile ? 15 : 17,
                            fontWeight: FontWeight.w800,
                            letterSpacing: 0.7,
                          ),
                        ),
                      ],
                    ),
                  ),
                  if (!mobile) ...[
                    const SizedBox(height: 2),
                    Text(
                      'Campus stories, updates and community conversation',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: Colors.grey.shade600, fontSize: 10.5),
                    ),
                  ],
                ],
              ),
            ),
            const SizedBox(width: 8),
            _NotificationBell(
              count: _unreadNotifications,
              loading: _notificationsLoading,
              onTap: _openNotifications,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildLeftPanel({required bool compact, bool mobileDrawer = false}) {
    return ColoredBox(
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          if (!compact)
            Padding(
              padding: EdgeInsets.fromLTRB(18, mobileDrawer ? 14 : 20, 14, 14),
              child: Row(
                children: [
                  const Expanded(
                    child: Text(
                      'NEWSROOM',
                      style: TextStyle(
                        color: Color(0xFF68716B),
                        fontSize: 10,
                        fontWeight: FontWeight.w900,
                        letterSpacing: 1.2,
                      ),
                    ),
                  ),
                  if (mobileDrawer)
                    IconButton(
                      onPressed: () => setState(() => _mobileNavigationOpen = false),
                      icon: const Icon(Icons.close_rounded, size: 20),
                      visualDensity: VisualDensity.compact,
                    ),
                ],
              ),
            ),
          Expanded(
            child: ListView.separated(
              padding: EdgeInsets.fromLTRB(compact ? 9 : 10, compact ? 14 : 4, compact ? 9 : 10, 12),
              itemCount: _items.length,
              separatorBuilder: (_, __) => const SizedBox(height: 6),
              itemBuilder: (context, index) {
                final item = _items[index];
                final selected = _currentViewIndex == index;
                if (compact) {
                  return Tooltip(
                    message: item.title,
                    child: InkWell(
                      onTap: () => _switchTab(index),
                      borderRadius: BorderRadius.circular(12),
                      child: AnimatedContainer(
                        duration: const Duration(milliseconds: 160),
                        height: 54,
                        decoration: BoxDecoration(
                          color: selected ? _darkGreen.withOpacity(0.08) : Colors.transparent,
                          borderRadius: BorderRadius.circular(12),
                          border: Border.all(
                            color: selected ? _darkGreen.withOpacity(0.15) : Colors.transparent,
                          ),
                        ),
                        alignment: Alignment.center,
                        child: Icon(
                          item.icon,
                          color: selected ? _darkGreen : Colors.grey.shade500,
                          size: 23,
                        ),
                      ),
                    ),
                  );
                }

                return InkWell(
                  onTap: () => _switchTab(index),
                  borderRadius: BorderRadius.circular(12),
                  child: AnimatedContainer(
                    duration: const Duration(milliseconds: 160),
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 11),
                    decoration: BoxDecoration(
                      color: selected ? _darkGreen.withOpacity(0.065) : Colors.transparent,
                      borderRadius: BorderRadius.circular(12),
                      border: Border.all(
                        color: selected ? _darkGreen.withOpacity(0.13) : Colors.transparent,
                      ),
                    ),
                    child: Row(
                      children: [
                        Container(
                          width: 34,
                          height: 34,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            color: selected ? Colors.white : const Color(0xFFF5F7F6),
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: Icon(
                            item.icon,
                            size: 19,
                            color: selected ? _darkGreen : Colors.grey.shade600,
                          ),
                        ),
                        const SizedBox(width: 10),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                item.title,
                                style: TextStyle(
                                  color: selected ? _darkGreen : _shellText,
                                  fontSize: 12.5,
                                  fontWeight: FontWeight.w900,
                                ),
                              ),
                              const SizedBox(height: 2),
                              Text(
                                item.subtitle,
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                  color: Colors.grey.shade600,
                                  fontSize: 9.5,
                                  height: 1.25,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
          ),
          if (!compact)
            Container(
              margin: const EdgeInsets.all(10),
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: const Color(0xFFF7F9F8),
                borderRadius: BorderRadius.circular(12),
                border: Border.all(color: _shellBorder),
              ),
              child: const Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Icon(Icons.verified_user_rounded, color: _darkGreen, size: 17),
                  SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      'Authenticated Rockview campus community',
                      style: TextStyle(
                        color: Color(0xFF55605A),
                        fontSize: 9.5,
                        height: 1.35,
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                  ),
                ],
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildRightPanel() {
    final name = '${_me?['full_name'] ?? 'Rockview User'}';
    final role = _roleLabel('${_me?['role'] ?? 'user'}');
    final campus = '${_me?['campus'] ?? 'University Wide'}';
    final photo = '${_me?['profile_picture'] ?? ''}';

    return ColoredBox(
      color: Colors.white,
      child: ListView(
        padding: const EdgeInsets.all(14),
        children: [
          const Text(
            'YOUR NEWSROOM',
            style: TextStyle(
              color: Color(0xFF68716B),
              fontSize: 10,
              fontWeight: FontWeight.w900,
              letterSpacing: 1.2,
            ),
          ),
          const SizedBox(height: 10),
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: const Color(0xFFF8FAF9),
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: _shellBorder),
            ),
            child: Row(
              children: [
                _ShellAvatar(value: photo, size: 40),
                const SizedBox(width: 10),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        name,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: const TextStyle(fontSize: 11.5, fontWeight: FontWeight.w900),
                      ),
                      const SizedBox(height: 2),
                      Text(
                        role,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: const TextStyle(color: _darkGreen, fontSize: 9.5, fontWeight: FontWeight.w800),
                      ),
                      const SizedBox(height: 2),
                      Text(
                        campus,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(color: Colors.grey.shade600, fontSize: 9),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 18),
          _RightPanelRow(
            icon: Icons.notifications_none_rounded,
            title: 'Activity',
            subtitle: _unreadNotifications == 0
                ? 'No unread notifications'
                : '$_unreadNotifications unread notification${_unreadNotifications == 1 ? '' : 's'}',
            trailing: _unreadNotifications == 0 ? null : '$_unreadNotifications',
            onTap: _openNotifications,
          ),
          const SizedBox(height: 7),
          _RightPanelRow(
            icon: Icons.edit_note_rounded,
            title: 'Draft workspace',
            subtitle: 'Continue stories before publishing',
            onTap: () => _switchTab(1),
          ),
          const SizedBox(height:16),
          _trendingPanelContent(compact:false),
          const SizedBox(height: 18),
          const Text(
            'POST CATEGORIES',
            style: TextStyle(
              color: Color(0xFF68716B),
              fontSize: 10,
              fontWeight: FontWeight.w900,
              letterSpacing: 1.2,
            ),
          ),
          const SizedBox(height: 9),
          Wrap(
            spacing: 6,
            runSpacing: 6,
            children: NewsOfflineService.categories
                .take(6)
                .map(
                  (category) => Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
                    decoration: BoxDecoration(
                      color: _standardGold.withOpacity(0.07),
                      borderRadius: BorderRadius.circular(999),
                      border: Border.all(color: _standardGold.withOpacity(0.22)),
                    ),
                    child: Text(
                      category,
                      style: const TextStyle(
                        color: Color(0xFF81500B),
                        fontSize: 8.8,
                        fontWeight: FontWeight.w800,
                      ),
                    ),
                  ),
                )
                .toList(),
          ),
          const SizedBox(height: 18),
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: _darkGreen.withOpacity(0.045),
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: _darkGreen.withOpacity(0.12)),
            ),
            child: const Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Icon(Icons.forum_outlined, color: _darkGreen, size: 17),
                    SizedBox(width: 7),
                    Text(
                      'Community standard',
                      style: TextStyle(color: _darkGreen, fontSize: 10.5, fontWeight: FontWeight.w900),
                    ),
                  ],
                ),
                SizedBox(height: 7),
                Text(
                  'Keep posts accurate, respectful and useful. Replies and mentions should support constructive campus discussion.',
                  style: TextStyle(color: Color(0xFF5D6861), fontSize: 9.5, height: 1.45),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _trendingPanelContent({required bool compact}){
    final stories=_trendingArticles;
    return Container(
      padding:EdgeInsets.all(compact?14:11),
      decoration:BoxDecoration(
        color:const Color(0xFFFFFAF0),
        borderRadius:BorderRadius.circular(15),
        border:Border.all(color:_standardGold.withOpacity(.23)),
      ),
      child:Column(
        crossAxisAlignment:CrossAxisAlignment.start,
        mainAxisSize:MainAxisSize.min,
        children:[
          Row(children:[
            Container(width:30,height:30,decoration:BoxDecoration(color:_standardGold.withOpacity(.14),borderRadius:BorderRadius.circular(9)),
              child:const Icon(Icons.trending_up_rounded,color:_standardGold,size:19)),
            const SizedBox(width:8),
            const Expanded(child:Text('TRENDING NOW',style:TextStyle(color:_darkGreen,fontSize:10.5,fontWeight:FontWeight.w900,letterSpacing:.8))),
            if(stories.isNotEmpty)Text('${stories.length}',style:TextStyle(color:Colors.grey.shade600,fontSize:9,fontWeight:FontWeight.w800)),
          ]),
          const SizedBox(height:5),
          Text('Officially featured campus news',style:TextStyle(color:Colors.grey.shade600,fontSize:9.5,height:1.35)),
          if(stories.isEmpty)
            Padding(padding:const EdgeInsets.symmetric(vertical:18),child:Center(child:Column(children:[
              Icon(Icons.local_fire_department_outlined,color:Colors.orange.shade300,size:25),
              const SizedBox(height:5),Text('Featured news will appear here',textAlign:TextAlign.center,style:TextStyle(color:Colors.grey,fontSize:10)),
            ])))
          else ...[
            const SizedBox(height:9),
            for(var index=0;index<stories.length;index++)
              _TrendingStoryLink(
                rank:index+1,
                article:stories[index],
                onTap:()=>_openTrendingArticle(stories[index],closePanel:compact),
              ),
          ],
        ],
      ),
    );
  }
}

class _TrendingStoryLink extends StatelessWidget{
  final int rank;
  final CampusNewsArticle article;
  final VoidCallback onTap;
  const _TrendingStoryLink({required this.rank,required this.article,required this.onTap});
  @override Widget build(BuildContext context){
    final image=article.images.isEmpty?'':article.images.first.previewPath;
    return Padding(
      padding:const EdgeInsets.only(top:6),
      child:Material(
        color:Colors.white,
        borderRadius:BorderRadius.circular(11),
        child:InkWell(
          borderRadius:BorderRadius.circular(11),
          onTap:onTap,
          child:Padding(
            padding:const EdgeInsets.all(7),
            child:Row(children:[
              SizedBox(width:54,height:48,child:ClipRRect(
                borderRadius:BorderRadius.circular(8),
                child:image.isEmpty
                  ?const ColoredBox(color:Color(0xFFF0F3F1),child:Icon(Icons.newspaper_rounded,color:_darkGreen,size:20))
                  :NewsCachedImage(url:NewsOfflineService.mediaUrl(image),decodeWidth:120),
              )),
              const SizedBox(width:8),
              Expanded(child:Column(crossAxisAlignment:CrossAxisAlignment.start,children:[
                Row(children:[Icon(Icons.local_fire_department_rounded,color:Colors.deepOrange.shade600,size:12),const SizedBox(width:3),
                  Text('TRENDING $rank',style:TextStyle(color:Colors.deepOrange.shade700,fontSize:8,fontWeight:FontWeight.w900,letterSpacing:.3))]),
                const SizedBox(height:3),
                Text(article.title,maxLines:2,overflow:TextOverflow.ellipsis,style:const TextStyle(color:_shellText,fontSize:10,fontWeight:FontWeight.w800,height:1.25)),
                const SizedBox(height:3),
                Text('${article.likeCount} likes · ${article.commentCount} comments',maxLines:1,overflow:TextOverflow.ellipsis,style:TextStyle(color:Colors.grey.shade600,fontSize:8.5)),
              ])),
              const SizedBox(width:4),
              Icon(Icons.chevron_right_rounded,color:Colors.grey.shade500,size:17),
            ]),
          ),
        ),
      ),
    );
  }
}

class _NotificationPanel extends StatelessWidget {
  final List<CampusNewsNotification> notifications;
  final int unreadCount;
  final bool loading;
  final Future<void> Function({bool silent}) onRefresh;
  final ValueChanged<CampusNewsNotification> onRead;
  final VoidCallback onReadAll;

  const _NotificationPanel({
    required this.notifications,
    required this.unreadCount,
    required this.loading,
    required this.onRefresh,
    required this.onRead,
    required this.onReadAll,
  });

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.white,
      borderRadius: const BorderRadius.vertical(top: Radius.circular(18), bottom: Radius.circular(18)),
      clipBehavior: Clip.antiAlias,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Container(
            padding: const EdgeInsets.fromLTRB(16, 13, 8, 13),
            decoration: const BoxDecoration(
              color: _darkGreen,
              border: Border(bottom: BorderSide(color: _standardGold, width: 3)),
            ),
            child: Row(
              children: [
                const Icon(Icons.notifications_rounded, color: Colors.white, size: 20),
                const SizedBox(width: 9),
                Expanded(
                  child: Text(
                    unreadCount == 0 ? 'Notifications' : 'Notifications • $unreadCount unread',
                    style: const TextStyle(color: Colors.white, fontSize: 13, fontWeight: FontWeight.w900),
                  ),
                ),
                if (unreadCount > 0)
                  TextButton(
                    onPressed: onReadAll,
                    style: TextButton.styleFrom(foregroundColor: Colors.white),
                    child: const Text('MARK ALL READ', style: TextStyle(fontSize: 9, fontWeight: FontWeight.w900)),
                  ),
                IconButton(
                  tooltip: 'Close',
                  onPressed: () => Navigator.pop(context),
                  icon: const Icon(Icons.close_rounded, color: Colors.white, size: 20),
                ),
              ],
            ),
          ),
          Expanded(
            child: loading && notifications.isEmpty
                ? const Center(child: CircularProgressIndicator(color: _darkGreen))
                : notifications.isEmpty
                    ? Center(
                        child: Padding(
                          padding: const EdgeInsets.all(26),
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Icon(Icons.notifications_none_rounded, size: 46, color: Colors.grey.shade300),
                              const SizedBox(height: 10),
                              const Text('No activity yet', style: TextStyle(fontWeight: FontWeight.w900)),
                              const SizedBox(height: 5),
                              Text(
                                'Likes, comments, replies and mentions on your news will appear here.',
                                textAlign: TextAlign.center,
                                style: TextStyle(color: Colors.grey.shade600, fontSize: 11.5, height: 1.4),
                              ),
                            ],
                          ),
                        ),
                      )
                    : RefreshIndicator(
                        color: _darkGreen,
                        onRefresh: () => onRefresh(silent: false),
                        child: ListView.separated(
                          physics: const AlwaysScrollableScrollPhysics(),
                          padding: const EdgeInsets.symmetric(vertical: 6),
                          itemCount: notifications.length,
                          separatorBuilder: (_, __) => Divider(height: 1, color: Colors.grey.shade200),
                          itemBuilder: (context, index) {
                            final item = notifications[index];
                            return _NotificationTile(
                              notification: item,
                              onTap: () => onRead(item),
                            );
                          },
                        ),
                      ),
          ),
        ],
      ),
    );
  }
}

class _NotificationTile extends StatelessWidget {
  final CampusNewsNotification notification;
  final VoidCallback onTap;

  const _NotificationTile({required this.notification, required this.onTap});

  @override
  Widget build(BuildContext context) {
    final icon = switch (notification.type) {
      'like' => Icons.favorite_rounded,
      'trending' => Icons.local_fire_department_rounded,
      'reply' => Icons.reply_rounded,
      'mention' => Icons.alternate_email_rounded,
      _ => Icons.mode_comment_rounded,
    };
    final action = switch (notification.type) {
      'like' => 'liked your news',
      'trending' => 'featured a trending news story',
      'reply' => 'replied to your comment',
      'mention' => 'mentioned you in a comment',
      _ => 'commented on your news',
    };

    return InkWell(
      onTap: onTap,
      child: Container(
        color: notification.isRead ? Colors.white : _darkGreen.withOpacity(0.045),
        padding: const EdgeInsets.fromLTRB(13, 11, 12, 11),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Stack(
              clipBehavior: Clip.none,
              children: [
                _ShellAvatar(value: notification.actorProfilePicture, size: 38),
                Positioned(
                  right: -3,
                  bottom: -2,
                  child: Container(
                    width: 18,
                    height: 18,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: notification.type == 'like' ? Colors.red.shade600 : notification.type == 'trending' ? Colors.deepOrange.shade600 : _darkGreen,
                      shape: BoxShape.circle,
                      border: Border.all(color: Colors.white, width: 1.5),
                    ),
                    child: Icon(icon, color: Colors.white, size: 10),
                  ),
                ),
              ],
            ),
            const SizedBox(width: 11),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text.rich(
                    TextSpan(
                      style: const TextStyle(color: _shellText, fontSize: 11.5, height: 1.35),
                      children: [
                        TextSpan(
                          text: notification.actorName,
                          style: const TextStyle(fontWeight: FontWeight.w900),
                        ),
                        TextSpan(text: ' $action'),
                      ],
                    ),
                  ),
                  if (notification.articleTitle.isNotEmpty) ...[
                    const SizedBox(height: 3),
                    Text(
                      notification.articleTitle,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: const TextStyle(color: _darkGreen, fontSize: 10.2, fontWeight: FontWeight.w800),
                    ),
                  ],
                  if (notification.commentPreview.isNotEmpty && notification.type != 'like') ...[
                    const SizedBox(height: 4),
                    Text(
                      notification.commentPreview,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: Colors.grey.shade600, fontSize: 9.8, height: 1.35),
                    ),
                  ],
                  const SizedBox(height: 4),
                  Text(
                    _timeAgo(notification.createdAt),
                    style: TextStyle(color: Colors.grey.shade500, fontSize: 8.7),
                  ),
                ],
              ),
            ),
            if (!notification.isRead)
              Container(
                width: 7,
                height: 7,
                margin: const EdgeInsets.only(top: 4),
                decoration: const BoxDecoration(color: _standardGold, shape: BoxShape.circle),
              ),
          ],
        ),
      ),
    );
  }
}

class _NotificationBell extends StatelessWidget {
  final int count;
  final bool loading;
  final VoidCallback onTap;

  const _NotificationBell({
    required this.count,
    required this.loading,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return Tooltip(
      message: 'Notifications',
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(11),
        child: SizedBox(
          width: 44,
          height: 44,
          child: Stack(
            clipBehavior: Clip.none,
            children: [
              Positioned.fill(
                child: Container(
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    color: const Color(0xFFF7F9F8),
                    borderRadius: BorderRadius.circular(11),
                    border: Border.all(color: _shellBorder),
                  ),
                  child: loading
                      ? const SizedBox(
                          width: 16,
                          height: 16,
                          child: CircularProgressIndicator(strokeWidth: 2, color: _darkGreen),
                        )
                      : const Icon(Icons.notifications_none_rounded, color: _darkGreen, size: 21),
                ),
              ),
              if (count > 0)
                Positioned(
                  right: -3,
                  top: -3,
                  child: Container(
                    constraints: const BoxConstraints(minWidth: 19, minHeight: 19),
                    padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),
                    decoration: BoxDecoration(
                      color: Colors.red.shade600,
                      borderRadius: BorderRadius.circular(999),
                      border: Border.all(color: Colors.white, width: 2),
                    ),
                    alignment: Alignment.center,
                    child: Text(
                      count > 99 ? '99+' : '$count',
                      style: const TextStyle(color: Colors.white, fontSize: 8.5, fontWeight: FontWeight.w900),
                    ),
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }
}

class _RightPanelRow extends StatelessWidget {
  final IconData icon;
  final String title;
  final String subtitle;
  final String? trailing;
  final VoidCallback onTap;

  const _RightPanelRow({
    required this.icon,
    required this.title,
    required this.subtitle,
    required this.onTap,
    this.trailing,
  });

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(11),
      child: Container(
        padding: const EdgeInsets.all(10),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(11),
          border: Border.all(color: _shellBorder),
        ),
        child: Row(
          children: [
            Container(
              width: 32,
              height: 32,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: _darkGreen.withOpacity(0.07),
                borderRadius: BorderRadius.circular(9),
              ),
              child: Icon(icon, color: _darkGreen, size: 17),
            ),
            const SizedBox(width: 9),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(title, style: const TextStyle(fontSize: 10.8, fontWeight: FontWeight.w900)),
                  const SizedBox(height: 2),
                  Text(
                    subtitle,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: Colors.grey.shade600, fontSize: 9, height: 1.25),
                  ),
                ],
              ),
            ),
            if (trailing != null)
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 4),
                decoration: BoxDecoration(
                  color: Colors.red.shade600,
                  borderRadius: BorderRadius.circular(999),
                ),
                child: Text(
                  trailing!,
                  style: const TextStyle(color: Colors.white, fontSize: 8, fontWeight: FontWeight.w900),
                ),
              )
            else
              Icon(Icons.chevron_right_rounded, color: Colors.grey.shade400, size: 18),
          ],
        ),
      ),
    );
  }
}

class _ShellIconButton extends StatelessWidget {
  final IconData icon;
  final String tooltip;
  final VoidCallback onTap;

  const _ShellIconButton({
    required this.icon,
    required this.tooltip,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return Tooltip(
      message: tooltip,
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(10),
        child: Container(
          width: 40,
          height: 40,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            color: const Color(0xFFF7F9F8),
            borderRadius: BorderRadius.circular(10),
            border: Border.all(color: _shellBorder),
          ),
          child: Icon(icon, color: _darkGreen, size: 21),
        ),
      ),
    );
  }
}

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

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

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

    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.5), width: 1.5),
      ),
      child: child,
    );
  }

  Widget _fallback() {
    return Container(
      color: Colors.grey.shade100,
      alignment: Alignment.center,
      child: Icon(Icons.person_rounded, color: Colors.grey.shade400, size: size * 0.55),
    );
  }
}

class _NewsMenuItem {
  final String title;
  final String subtitle;
  final IconData icon;

  const _NewsMenuItem({
    required this.title,
    required this.subtitle,
    required this.icon,
  });
}

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