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 '../../../../core/services/market_offline_service.dart';
import 'market_offline_widgets.dart';

const Color _green = Color.fromARGB(255, 2, 105, 48);
const Color _gold = Color.fromARGB(255, 204, 117, 4);
const Color _border = Color(0xFFE3E7EC);
const Color _ink = Color(0xFF1D2A34);
const Color _muted = Color(0xFF66727E);

class ActiveMarketSubTab extends StatefulWidget {
  final String currentUserName;

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

  @override
  State<ActiveMarketSubTab> createState() => _ActiveMarketSubTabState();
}

class _ActiveMarketSubTabState extends State<ActiveMarketSubTab> {
  final ScrollController _scrollController = ScrollController();
  final TextEditingController _searchController = TextEditingController();
  final List<MarketItem> _items = <MarketItem>[];

  Timer? _searchDebounce;
  int _requestVersion=0;
  bool _refreshing=false;
  final Set<int> _liking={};
  List<MarketNotification> _notifications = const <MarketNotification>[];
  int _unread = 0;
  bool _loading = true;
  bool _loadingMore = false;
  bool _hasMore = true;
  int _page = 1;
  String? _error;
  String _category = 'All Categories';
  String _campus = 'All Campuses';
  List<String> _campuses = const <String>[];

  static const int _pageSize = 12;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_onScroll);
    _loadInitial();
    MarketOfflineService.revision.addListener(_cacheChanged);
  }

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

  String? _loadedQuery;
  void _cacheChanged(){if(mounted&&!_loading&&!_refreshing)_silentRefresh();}
  Future<void> _loadInitial() async {
    if(!mounted)return;final request=++_requestVersion;
    final query='$_category|$_campus|${_searchController.text.trim()}';
    setState((){if(query!=_loadedQuery){_items.clear();_loadedQuery=query;}_loading=_items.isEmpty;_error=null;});
    try{
      final page=await MarketOfflineService.getItems(status:'active',category:_category,campus:_campus,search:_searchController.text,page:1,limit:_pageSize);
      if(!mounted||request!=_requestVersion)return;
      setState((){_items..clear()..addAll(page.items);_page=1;_hasMore=page.hasMore;_loading=false;});
    }catch(e){if(mounted&&request==_requestVersion)setState((){_loading=false;_error=_items.isEmpty?_cleanError(e):null;});}
    // A notification/profile failure never blocks saved marketplace listings.
    unawaited(_refreshNotifications());
    try{final campuses=await MarketOfflineService.getCampuses();if(mounted)setState(()=>_campuses=campuses); }catch(_){}
  }
  Future<void> _silentRefresh()async{
    if(!mounted||_loading||_loadingMore||_refreshing)return;
    if(_scrollController.hasClients&&_scrollController.offset>260)return;
    _refreshing=true;
    try{await _loadInitial();}finally{_refreshing=false;}
  }
  Future<void> _loadMore()async{
    if(_loading||_loadingMore||!_hasMore)return;
    final request=_requestVersion;setState(()=>_loadingMore=true);
    try{
      final next=_page+1;
      final page=await MarketOfflineService.getItems(status:'active',category:_category,campus:_campus,search:_searchController.text,page:next,limit:_pageSize);
      if(!mounted||request!=_requestVersion)return;
      setState((){final ids=_items.map((i)=>i.id).toSet();_items.addAll(page.items.where((i)=>ids.add(i.id)));_page=next;_hasMore=page.hasMore;});
    }catch(_){if(mounted)_snack('No more saved listings. Reconnect and refresh for more.');}
    finally{if(mounted)setState(()=>_loadingMore=false);}
  }
  Future<void> _refreshNow()async{await MarketOfflineService.sync(force:true);await _loadInitial();}

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

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

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

  Future<void> _openItem(int index) async {
    final result = await showDialog<MarketItem>(
      context: context,
      barrierDismissible: true,
      builder: (_) => MarketItemDialog(item: _items[index]),
    );
    if(result!=null&&mounted){final current=_items.indexWhere((i)=>i.id==result.id);if(current>=0)setState(()=>_items[current]=result);}
  }

  Future<void> _report(int index) async {
    final item = _items[index];
    final controller = TextEditingController();
    final reason = await showDialog<String>(
      context: context,
      builder: (context) => AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
        title: const Row(
          children: [
            Icon(Icons.flag_outlined, color: Colors.orange),
            SizedBox(width: 8),
            Text('Report listing'),
          ],
        ),
        content: TextField(
          controller: controller,
          minLines: 3,
          maxLines: 6,
          decoration: const InputDecoration(
            hintText: 'Explain why this listing should be reviewed...',
            border: OutlineInputBorder(),
          ),
        ),
        actions: [
          TextButton(onPressed: () => Navigator.pop(context), child: const Text('Cancel')),
          FilledButton(
            onPressed: () {
              final value = controller.text.trim();
              if (value.length >= 3) Navigator.pop(context, value);
            },
            style: FilledButton.styleFrom(backgroundColor: Colors.orange.shade800),
            child: const Text('Report'),
          ),
        ],
      ),
    );
    controller.dispose();
    if (reason == null) return;
    try {
      await MarketOfflineService.queueAction('report',item.id,{'reason':reason});
      if (!mounted) return;
      setState(() => _items.removeWhere((i)=>i.id==item.id));
      _snack('Report saved to outbox. Moderation starts after the server receives it.');
    } catch (e) {
      _snack(_cleanError(e), error: true);
    }
  }

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

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      floatingActionButton: FloatingActionButton.extended(
        onPressed: _openComposer,
        backgroundColor: _gold,
        foregroundColor: Colors.white,
        icon: const Icon(Icons.add_business_rounded),
        label: const Text('SELL ITEM', style: TextStyle(fontWeight: FontWeight.w900)),
      ),
      body: RefreshIndicator(
        color: _green,
        onRefresh: _refreshNow,
        child: CustomScrollView(
          controller: _scrollController,
          physics: const AlwaysScrollableScrollPhysics(),
          slivers: [
            const SliverToBoxAdapter(child: MarketSyncBar()),
            SliverToBoxAdapter(child: _buildHeader()),
            SliverToBoxAdapter(child: _buildFilters()),
            if (_loading)
              const SliverFillRemaining(
                hasScrollBody: false,
                child: Center(child: CircularProgressIndicator(color: _green)),
              )
            else if (_error != null)
              SliverFillRemaining(hasScrollBody: false, child: _buildError())
            else if (_items.isEmpty)
              SliverFillRemaining(hasScrollBody: false, child: _buildEmpty())
            else
              SliverPadding(
                padding: const EdgeInsets.fromLTRB(0, 14, 0, 100),
                sliver: SliverLayoutBuilder(
                  builder: (context, constraints) {
                    final width = constraints.crossAxisExtent;
                    final columns=width>=1080?4:width>=780?3:width>=520?2:1;
                    final scale=MediaQuery.textScalerOf(context).scale(1.0);
                    return SliverGrid(
                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: columns,
                        crossAxisSpacing: 10,
                        mainAxisSpacing: 10,
                        mainAxisExtent: (290 + (scale-1).clamp(0.0,2.0)*130).toDouble(),
                      ),
                      delegate: SliverChildBuilderDelegate(
                        (context, index) {
                          final item = _items[index];
                          return _MarketCard(
                            item: item,
                            onOpen: () => _openItem(index),
                            onLike: () => _toggleLike(index),
                            onReport: () => _report(index),
                          );
                        },
                        childCount: _items.length,
                      ),
                    );
                  },
                ),
              ),
            if (_loadingMore)
              const SliverToBoxAdapter(
                child: Padding(
                  padding: EdgeInsets.all(20),
                  child: Center(child: CircularProgressIndicator(color: _green)),
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildHeader() {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(18),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(24),
        border: Border.all(color: _border),
      ),
      child: Row(
        children: [
          Container(
            width: 48,
            height: 48,
            decoration: BoxDecoration(
              color: _green.withOpacity(0.08),
              borderRadius: BorderRadius.circular(16),
            ),
            child: const Icon(Icons.storefront_rounded, color: _green),
          ),
          const SizedBox(width: 13),
          const Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('Staff Marketplace', style: TextStyle(fontSize: 22, fontWeight: FontWeight.w900, color: _ink)),
                SizedBox(height: 4),
                Text(
                  'Buy and sell goods securely within the Rockview community.',
                  style: TextStyle(fontSize: 12, color: _muted, height: 1.45),
                ),
              ],
            ),
          ),
          _NotificationBell(unreadCount: _unread, onTap: _openNotifications),
        ],
      ),
    );
  }

  Widget _buildFilters() {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(22),
        border: Border.all(color: _border),
      ),
      child: Wrap(
        spacing: 10,
        runSpacing: 10,
        crossAxisAlignment: WrapCrossAlignment.center,
        children: [
          SizedBox(
            width: 300,
            child: TextField(
              controller: _searchController,
              onChanged:(_){_searchDebounce?.cancel();_searchDebounce=Timer(const Duration(milliseconds:300),_loadInitial);},
              onSubmitted: (_) => _loadInitial(),
              decoration: InputDecoration(
                hintText: 'Search items, category or seller...',
                prefixIcon: const Icon(Icons.search_rounded, color: _green),
                suffixIcon: IconButton(onPressed: _loadInitial, icon: const Icon(Icons.arrow_forward_rounded)),
                filled: true,
                fillColor: const Color(0xFFF7F9FA),
                border: OutlineInputBorder(borderRadius: BorderRadius.circular(14), borderSide: BorderSide.none),
              ),
            ),
          ),
          SizedBox(
            width: 190,
            child: DropdownButtonFormField<String>(
              value: _category,
              isExpanded: true,
              decoration: _filterDecoration('Category'),
              items: <String>['All Categories', ...MarketOfflineService.categories]
                  .map((e) => DropdownMenuItem(value: e, child: Text(e, overflow: TextOverflow.ellipsis)))
                  .toList(),
              onChanged: (value) {
                if (value == null) return;
                setState(() => _category = value);
                _loadInitial();
              },
            ),
          ),
          SizedBox(
            width: 185,
            child: DropdownButtonFormField<String>(
              value: _campus,
              isExpanded: true,
              decoration: _filterDecoration('Campus'),
              items: <String>['All Campuses', ..._campuses]
                  .map((e) => DropdownMenuItem(value: e, child: Text(e, overflow: TextOverflow.ellipsis)))
                  .toList(),
              onChanged: (value) {
                if (value == null) return;
                setState(() => _campus = value);
                _loadInitial();
              },
            ),
          ),
          OutlinedButton.icon(
            onPressed: _refreshNow,
            style: OutlinedButton.styleFrom(foregroundColor: _green, padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 15)),
            icon: const Icon(Icons.refresh_rounded),
            label: const Text('Refresh'),
          ),
        ],
      ),
    );
  }

  InputDecoration _filterDecoration(String label) => InputDecoration(
        labelText: label,
        filled: true,
        fillColor: const Color(0xFFF7F9FA),
        contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
        border: OutlineInputBorder(borderRadius: BorderRadius.circular(14), borderSide: BorderSide.none),
      );

  Widget _buildError() => Center(
        child: Container(
          constraints: const BoxConstraints(maxWidth: 560),
          padding: const EdgeInsets.all(28),
          decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(24), border: Border.all(color: Colors.red.shade200)),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(Icons.cloud_off_rounded, size: 48, color: Colors.red.shade300),
              const SizedBox(height: 12),
              const Text('Marketplace could not be loaded', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w900)),
              const SizedBox(height: 8),
              Text(_error!, textAlign: TextAlign.center, style: const TextStyle(color: _muted)),
              const SizedBox(height: 14),
              FilledButton.icon(onPressed: _loadInitial, style: FilledButton.styleFrom(backgroundColor: _green), icon: const Icon(Icons.refresh), label: const Text('Try again')),
            ],
          ),
        ),
      );

  Widget _buildEmpty() => Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(Icons.store_mall_directory_outlined, size: 60, color: Colors.grey.shade300),
            const SizedBox(height: 12),
            const Text('No active listings', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w900)),
            const SizedBox(height: 6),
            const Text('Change the filters or post the first item.', style: TextStyle(color: _muted)),
            const SizedBox(height: 16),
            FilledButton.icon(onPressed: _openComposer, style: FilledButton.styleFrom(backgroundColor: _green), icon: const Icon(Icons.add_business), label: const Text('Sell an item')),
          ],
        ),
      );
}

class _MarketCard extends StatelessWidget {
  final MarketItem item;
  final VoidCallback onOpen,onLike,onReport;
  const _MarketCard({required this.item,required this.onOpen,required this.onLike,required this.onReport});
  @override Widget build(BuildContext context)=>Material(
    color:Colors.white,clipBehavior:Clip.antiAlias,
    shape:RoundedRectangleBorder(borderRadius:BorderRadius.circular(12),side:const BorderSide(color:_border)),
    child:InkWell(onTap:onOpen,child:Column(crossAxisAlignment:CrossAxisAlignment.stretch,children:[
      SizedBox(height:118,child:Stack(fit:StackFit.expand,children:[
        _MarketItemImage(item:item),
        Positioned(top:7,left:7,child:Container(padding:const EdgeInsets.symmetric(horizontal:7,vertical:4),
          decoration:BoxDecoration(color:Colors.white.withOpacity(.95),borderRadius:BorderRadius.circular(6)),
          child:Text(item.condition,style:const TextStyle(fontSize:10,fontWeight:FontWeight.w700)))),
        if(_imageCount(item)>1)Positioned(right:7,bottom:7,child:Container(
          padding:const EdgeInsets.symmetric(horizontal:7,vertical:4),decoration:BoxDecoration(color:Colors.black54,borderRadius:BorderRadius.circular(6)),
          child:Text('+${_imageCount(item)-1}',style:const TextStyle(color:Colors.white,fontSize:11,fontWeight:FontWeight.w700)))),
      ])),
      Expanded(child:Padding(padding:const EdgeInsets.fromLTRB(10,6,8,6),child:Column(crossAxisAlignment:CrossAxisAlignment.start,children:[
        Row(children:[Expanded(child:Text(item.title,maxLines:2,overflow:TextOverflow.ellipsis,
          style:const TextStyle(fontSize:13,fontWeight:FontWeight.w800,color:_ink,height:1.2))),
          SizedBox(width:32,height:32,child:PopupMenuButton<String>(padding:EdgeInsets.zero,tooltip:'Listing options',
            onSelected:(v){if(v=='report')onReport();},itemBuilder:(_)=>const[PopupMenuItem(value:'report',child:Text('Report listing'))],
            icon:const Icon(Icons.more_horiz,size:19)))]),
        Text(_price(item.price),style:const TextStyle(fontSize:17,fontWeight:FontWeight.w800,color:_green)),
        const SizedBox(height:3),
        Text(item.sellerName,maxLines:1,overflow:TextOverflow.ellipsis,style:const TextStyle(fontSize:11,color:_muted)),
        Text(item.campus.isEmpty?item.location:item.campus,maxLines:1,overflow:TextOverflow.ellipsis,style:const TextStyle(fontSize:10,color:_muted)),
        const Spacer(),
        Row(children:[
          _CompactAction(icon:item.likedByMe?Icons.favorite:Icons.favorite_border,label:'${item.likeCount}',active:item.likedByMe,onTap:onLike),
          const SizedBox(width:6),_CompactAction(icon:Icons.chat_bubble_outline,label:'${item.commentCount}',onTap:onOpen),
          const Spacer(),Text(_timeAgo(item.createdAt),style:const TextStyle(fontSize:9,color:_muted)),
        ]),
      ]))),
    ])),
  );
}

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

  @override
  State<MarketListingComposerDialog> createState() => _MarketListingComposerDialogState();
}

class _MarketListingComposerDialogState extends State<MarketListingComposerDialog> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final TextEditingController _title = TextEditingController();
  final TextEditingController _price = TextEditingController();
  final TextEditingController _phone = TextEditingController();
  final TextEditingController _location = TextEditingController();
  final TextEditingController _description = TextEditingController();
  final TextEditingController _quantity = TextEditingController(text: '1');
  final ImagePicker _picker = ImagePicker();
  final List<_PickedImage> _images = <_PickedImage>[];

  String _category = MarketOfflineService.categories.first;
  String _condition = MarketOfflineService.conditions[2];
  bool _saving = false;
  bool _loadingUser = true;
  Map<String, dynamic>? _me;
  String? _userError;

  @override
  void initState() {
    super.initState();
    _loadUser();
  }

  @override
  void dispose() {
    _title.dispose();
    _price.dispose();
    _phone.dispose();
    _location.dispose();
    _description.dispose();
    _quantity.dispose();
    super.dispose();
  }

  Future<void> _loadUser() async {
    try {
      final me = await MarketOfflineService.getCurrentUser();
      if (!mounted) return;
      setState(() {
        _me = me;
        _phone.text = '${me['phone'] ?? ''}'.trim();
        _location.text = '${me['campus'] ?? ''}'.trim();
        _loadingUser = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _loadingUser = false;
        _userError = _cleanError(e);
      });
    }
  }

  Future<void> _pickImages() async {
    final remaining = 6 - _images.length;
    if (remaining <= 0) return;
    try {
      final files = await _picker.pickMultiImage(imageQuality: 72, maxWidth: 1280, maxHeight: 1280);
      if (files.isEmpty) return;
      for (final file in files.take(remaining)) {
        final bytes = await file.readAsBytes();
        _images.add(_PickedImage(file: file, bytes: bytes));
      }
      if (mounted) setState(() {});
    } catch (e) {
      _snack('Unable to select pictures: ${_cleanError(e)}', error: true);
    }
  }

  Future<void> _submit() async {
    if (_saving || _me == null) return;
    if (!(_formKey.currentState?.validate() ?? false)) return;
    if (_images.isEmpty) {
      _snack('Add at least one clear picture of the item.', error: true);
      return;
    }
    setState(() => _saving = true);
    try {
      await MarketOfflineService.queueListing({
        'title':_title.text.trim(),'description':_description.text.trim(),
        'price':double.parse(_price.text.trim()),'category':_category,'condition':_condition,
        'quantity':int.tryParse(_quantity.text.trim())??1,'sellerPhone':_phone.text.trim(),'location':_location.text.trim(),
      },_images.map((e)=>e.file).toList());
      if(!mounted)return;
      _snack('Listing saved on this device. Check Outbox for delivery status.');
      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 : _green));
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      insetPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 16),
      backgroundColor: Colors.transparent,
      child: Container(
        constraints: BoxConstraints(maxWidth: 900, maxHeight: MediaQuery.of(context).size.height * 0.94),
        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(26)),
        child: Column(
          children: [
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 14),
              decoration: const BoxDecoration(color: _green, borderRadius: BorderRadius.vertical(top: Radius.circular(26))),
              child: Row(
                children: [
                  const Icon(Icons.add_business_rounded, color: Colors.white),
                  const SizedBox(width: 10),
                  const Expanded(child: Text('Sell an item', style: TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.w900))),
                  IconButton(onPressed: _saving ? null : () => Navigator.pop(context, false), icon: const Icon(Icons.close, color: Colors.white)),
                ],
              ),
            ),
            Expanded(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(20),
                child: Form(
                  key: _formKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _section('Seller'),
                      const SizedBox(height: 10),
                      _sellerPanel(),
                      const SizedBox(height: 22),
                      _section('Pictures'),
                      const SizedBox(height: 8),
                      const Text('Add up to 6 pictures. The marketplace card will show one lead image and +N for the rest.', style: TextStyle(color: _muted, fontSize: 11.5, height: 1.5)),
                      const SizedBox(height: 10),
                      if (_images.isNotEmpty)
                        Wrap(
                          spacing: 8,
                          runSpacing: 8,
                          children: _images.asMap().entries.map((entry) {
                            return SizedBox(
                              width: 132,
                              height: 96,
                              child: Stack(
                                fit: StackFit.expand,
                                children: [
                                  ClipRRect(borderRadius: BorderRadius.circular(14), child: Image.memory(entry.value.bytes, fit: BoxFit.cover)),
                                  Positioned(
                                    top: 5,
                                    right: 5,
                                    child: InkWell(
                                      onTap: _saving ? null : () => setState(() => _images.removeAt(entry.key)),
                                      child: Container(padding: const EdgeInsets.all(5), decoration: const BoxDecoration(color: Colors.black54, shape: BoxShape.circle), child: const Icon(Icons.close, color: Colors.white, size: 15)),
                                    ),
                                  ),
                                ],
                              ),
                            );
                          }).toList(),
                        ),
                      if (_images.isNotEmpty) const SizedBox(height: 10),
                      OutlinedButton.icon(onPressed: _saving || _images.length >= 6 ? null : _pickImages, icon: const Icon(Icons.add_photo_alternate_outlined), label: Text(_images.isEmpty ? 'Add pictures' : 'Add pictures (${_images.length}/6)')),
                      const SizedBox(height: 22),
                      _section('Item details'),
                      const SizedBox(height: 12),
                      TextFormField(controller: _title, maxLength: 180, decoration: _input('Item title', Icons.shopping_bag_outlined), validator: (v) => (v == null || v.trim().length < 3) ? 'Enter the item title.' : null),
                      const SizedBox(height: 12),
                      LayoutBuilder(builder: (context, constraints) {
                        final narrow = constraints.maxWidth < 620;
                        final priceField = TextFormField(controller: _price, keyboardType: const TextInputType.numberWithOptions(decimal: true), decoration: _input('Price (K)', Icons.payments_outlined), validator: (v) => double.tryParse(v?.trim() ?? '') == null ? 'Enter a valid price.' : null);
                        final quantityField = TextFormField(controller: _quantity, keyboardType: TextInputType.number, decoration: _input('Quantity', Icons.inventory_2_outlined), validator: (v) => (int.tryParse(v?.trim() ?? '') ?? 0) < 1 ? 'Quantity must be at least 1.' : null);
                        if (!narrow) return Row(children: [Expanded(child: priceField), const SizedBox(width: 10), Expanded(child: quantityField)]);
                        return Column(children: [priceField, const SizedBox(height: 10), quantityField]);
                      }),
                      const SizedBox(height: 12),
                      LayoutBuilder(builder: (context, constraints) {
                        final narrow = constraints.maxWidth < 620;
                        final category = DropdownButtonFormField<String>(value: _category, isExpanded: true, decoration: _input('Category', Icons.category_outlined), items: MarketOfflineService.categories.map((e) => DropdownMenuItem(value: e, child: Text(e))).toList(), onChanged: _saving ? null : (v) { if (v != null) setState(() => _category = v); });
                        final condition = DropdownButtonFormField<String>(value: _condition, isExpanded: true, decoration: _input('Condition', Icons.verified_outlined), items: MarketOfflineService.conditions.map((e) => DropdownMenuItem(value: e, child: Text(e))).toList(), onChanged: _saving ? null : (v) { if (v != null) setState(() => _condition = v); });
                        if (!narrow) return Row(children: [Expanded(child: category), const SizedBox(width: 10), Expanded(child: condition)]);
                        return Column(children: [category, const SizedBox(height: 10), condition]);
                      }),
                      const SizedBox(height: 12),
                      TextFormField(controller: _phone, keyboardType: TextInputType.phone, decoration: _input('Contact phone', Icons.phone_outlined), validator: (v) => (v == null || v.trim().isEmpty) ? 'Provide a contact number.' : null),
                      const SizedBox(height: 12),
                      TextFormField(controller: _location, decoration: _input('Pickup location', Icons.location_on_outlined), validator: (v) => (v == null || v.trim().isEmpty) ? 'Provide the pickup location.' : null),
                      const SizedBox(height: 12),
                      TextFormField(controller: _description, minLines: 5, maxLines: 10, maxLength: 10000, decoration: _input('Description', Icons.notes_rounded).copyWith(alignLabelWithHint: true, hintText: 'Describe the item clearly, including important defects or included accessories.'), validator: (v) => (v == null || v.trim().length < 5) ? 'Add a useful description.' : null),
                    ],
                  ),
                ),
              ),
            ),
            Container(
              padding: const EdgeInsets.all(16),
              decoration: const BoxDecoration(color: Color(0xFFF7F9FA), borderRadius: BorderRadius.vertical(bottom: Radius.circular(26))),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  TextButton(onPressed: _saving ? null : () => Navigator.pop(context, false), child: const Text('Cancel')),
                  const SizedBox(width: 10),
                  FilledButton.icon(
                    onPressed: _saving || _me == null ? null : _submit,
                    style: FilledButton.styleFrom(backgroundColor: _green, padding: const EdgeInsets.symmetric(horizontal: 22, vertical: 16)),
                    icon: _saving ? const SizedBox(width: 17, height: 17, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white)) : const Icon(Icons.storefront_rounded),
                    label: Text(_saving ? 'Submitting...' : 'Save to outbox'),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _sellerPanel() {
    if (_loadingUser) return const Center(child: CircularProgressIndicator(color: _green));
    if (_userError != null || _me == null) return Text(_userError ?? 'Unable to load your account.', style: const TextStyle(color: Colors.red));
    return Container(
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(color: _green.withOpacity(0.05), borderRadius: BorderRadius.circular(16), border: Border.all(color: _green.withOpacity(0.15))),
      child: Row(
        children: [
          _Avatar(value: '${_me!['profile_picture'] ?? ''}', size: 45),
          const SizedBox(width: 11),
          Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text('${_me!['full_name'] ?? 'Rockview Member'}', style: const TextStyle(fontWeight: FontWeight.w900)), const SizedBox(height: 3), Text('${_me!['campus'] ?? 'Rockview University'}', style: const TextStyle(color: _green, fontSize: 11, fontWeight: FontWeight.w700))])),
          const Icon(Icons.lock_outline, color: _green, size: 19),
        ],
      ),
    );
  }

  Widget _section(String text) => Row(children: [Container(width: 5, height: 18, decoration: BoxDecoration(color: _gold, borderRadius: BorderRadius.circular(99))), const SizedBox(width: 8), Text(text, style: const TextStyle(fontWeight: FontWeight.w900, color: _ink))]);

  InputDecoration _input(String label, IconData icon) => InputDecoration(labelText: label, prefixIcon: Icon(icon, color: _green), filled: true, fillColor: const Color(0xFFF7F9FA), border: OutlineInputBorder(borderRadius: BorderRadius.circular(15), borderSide: const BorderSide(color: _border)));
}

class _PickedImage {
  final XFile file;
  final Uint8List bytes;

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

class MarketItemDialog extends StatefulWidget {
  final MarketItem item;

  const MarketItemDialog({super.key, required this.item});

  @override
  State<MarketItemDialog> createState() => _MarketItemDialogState();
}

class _MarketItemDialogState extends State<MarketItemDialog> {
  late MarketItem _item;
  final TextEditingController _comment = TextEditingController();
  final TextEditingController _inquiry = TextEditingController();
  List<MarketComment> _comments = const <MarketComment>[];
  List<MarketMentionableUser> _mentionUsers = const <MarketMentionableUser>[];
  final Map<int, MarketMentionableUser> _mentions = <int, MarketMentionableUser>{};
  MarketComment? _replyingTo;
  bool _loading = true;
  bool _posting = false;
  bool _readingComments=false;
  bool _likeBusy=false;

  @override
  void initState() {
    super.initState();
    _item = widget.item;
    _load();
    MarketOfflineService.revision.addListener(_load);
  }

  @override
  void dispose() {
    MarketOfflineService.revision.removeListener(_load);
    _comment.dispose();
    _inquiry.dispose();
    super.dispose();
  }

  Future<void> _load() async {
    if(_readingComments)return;_readingComments=true;
    try {
      final results = await Future.wait<dynamic>([
        MarketOfflineService.getComments(_item.id),
        MarketOfflineService.getMentionableUsers(_item.id).catchError((_) => <MarketMentionableUser>[]),
      ]);
      if (!mounted) return;
      setState(() {
        _comments = results[0] as List<MarketComment>;
        _mentionUsers = results[1] as List<MarketMentionableUser>;
        _item = _item.copyWith(commentCount: _comments.length);
        _loading = false;
      });
    } catch (_) {
      if (mounted) setState(() => _loading = false);
    }finally{_readingComments=false;}
  }

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

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

  Future<void> _postComment() async {
    final text = _comment.text.trim();
    if (text.isEmpty || _posting) return;
    setState(() => _posting = true);
    try {
      final parentId = _replyingTo == null ? null : (_replyingTo!.parentCommentId ?? _replyingTo!.id);
      await MarketOfflineService.queueAction('comment',_item.id,{'text':text,'parent':parentId,'mentions':_mentions.keys.toList()});
      if(!mounted)return;
      setState((){_comment.clear();_replyingTo=null;_mentions.clear();_posting=false;});
      _snack('Comment saved to outbox. It appears in the discussion after delivery.');
    } catch (e) {
      if (!mounted) return;
      setState(() => _posting = false);
      _snack(_cleanError(e), error: true);
    }
  }

  Future<void> _contactSeller() async {
    _inquiry.text = 'Hello ${_item.sellerName}, I am interested in "${_item.title}". Is it still available?';
    final result = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
        title: const Text('Contact seller'),
        content: SizedBox(
          width: 520,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              if (_item.sellerPhone.isNotEmpty)
                Row(children: [const Icon(Icons.phone_outlined, color: _green), const SizedBox(width: 8), Expanded(child: Text(_item.sellerPhone, style: const TextStyle(fontWeight: FontWeight.w800))), TextButton(onPressed: () async { await Clipboard.setData(ClipboardData(text: _item.sellerPhone)); if (context.mounted) ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Phone number copied.'))); }, child: const Text('Copy'))]),
              const SizedBox(height: 12),
              TextField(controller: _inquiry, minLines: 4, maxLines: 7, decoration: const InputDecoration(labelText: 'Message to seller', border: OutlineInputBorder())),
            ],
          ),
        ),
        actions: [
          TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('Cancel')),
          FilledButton(onPressed: () => Navigator.pop(context, true), style: FilledButton.styleFrom(backgroundColor: _green), child: const Text('Send')),
        ],
      ),
    );
    if (result != true) return;
    try {
      await MarketOfflineService.queueAction('inquiry',_item.id,{'text':_inquiry.text});
      if (!mounted) return;

      _snack('Message saved to outbox. Delivery status is shown there.');
    } catch (e) {
      _snack(_cleanError(e), error: true);
    }
  }

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

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

    return Dialog(
      insetPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 14),
      backgroundColor: Colors.transparent,
      child: Container(
        constraints: BoxConstraints(maxWidth: 1080, maxHeight: MediaQuery.of(context).size.height * 0.94),
        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(26)),
        child: Column(
          children: [
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 13),
              decoration: const BoxDecoration(color: _green, borderRadius: BorderRadius.vertical(top: Radius.circular(26))),
              child: Row(children: [const Icon(Icons.shopping_bag_rounded, color: Colors.white), const SizedBox(width: 10), Expanded(child: Text(_item.title, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w900, fontSize: 16))), IconButton(onPressed: () => Navigator.pop(context, _item), icon: const Icon(Icons.close, color: Colors.white))]),
            ),
            Expanded(
              child: LayoutBuilder(
                builder: (context, constraints) {
                  final wide = constraints.maxWidth >= 850;
                  if (wide) {
                    return Row(children: [Expanded(flex: 6, child: _detailPane()), VerticalDivider(width: 1, color: Colors.grey.shade200), Expanded(flex: 5, child: _conversationPane(parents, replies))]);
                  }
                  return _conversationPane(parents, replies, includeSummary: true);
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _detailPane() {
    final pictures = _item.images;
    return SingleChildScrollView(
      padding: const EdgeInsets.all(20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (pictures.isNotEmpty)
            ...pictures.map((m) => Padding(padding: const EdgeInsets.only(bottom: 9), child: ClipRRect(borderRadius: BorderRadius.circular(18), child: AspectRatio(aspectRatio: 16 / 9, child: MarketCachedImage(url: MarketOfflineService.mediaUrl(m.path))))))
          else if (_item.legacyImageUrl.isNotEmpty)
            ClipRRect(borderRadius: BorderRadius.circular(18), child: AspectRatio(aspectRatio: 16 / 9, child: _LegacyOrNetworkImage(value: _item.legacyImageUrl))),
          const SizedBox(height: 14),
          Text(_item.title, style: const TextStyle(fontSize: 23, fontWeight: FontWeight.w900, color: _ink)),
          const SizedBox(height: 7),
          Text(_price(_item.price), style: const TextStyle(fontSize: 25, fontWeight: FontWeight.w900, color: _green)),
          const SizedBox(height: 12),
          Wrap(spacing: 8, runSpacing: 8, children: [_Pill(_item.category), _Pill(_item.condition), _Pill('Qty ${_item.quantity}')]),
          const SizedBox(height: 15),
          Text(_item.description, style: const TextStyle(fontSize: 13, height: 1.65, color: Color(0xFF53606D))),
          const SizedBox(height: 18),
          Container(
            padding: const EdgeInsets.all(14),
            decoration: BoxDecoration(color: const Color(0xFFF7F9FA), borderRadius: BorderRadius.circular(17), border: Border.all(color: _border)),
            child: Row(children: [_Avatar(value: _item.sellerProfilePicture, size: 44), const SizedBox(width: 10), Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text(_item.sellerName, style: const TextStyle(fontWeight: FontWeight.w900)), const SizedBox(height: 3), Text(_item.campus.isEmpty ? 'Rockview University' : _item.campus, style: const TextStyle(color: _muted, fontSize: 11))])), FilledButton.icon(onPressed: _contactSeller, style: FilledButton.styleFrom(backgroundColor: _green), icon: const Icon(Icons.chat_rounded, size: 17), label: const Text('Contact'))]),
          ),
        ],
      ),
    );
  }

  Widget _conversationPane(List<MarketComment> parents, Map<int, List<MarketComment>> replies, {bool includeSummary = false}) {
    return Column(
      children: [
        if (includeSummary)
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(border: Border(bottom: BorderSide(color: Colors.grey.shade200))),
            child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              ClipRRect(borderRadius: BorderRadius.circular(15), child: AspectRatio(aspectRatio: 16 / 9, child: _MarketItemImage(item: _item))),
              const SizedBox(height: 10),
              Row(children: [Expanded(child: Text(_item.title, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle(fontWeight: FontWeight.w900))), const SizedBox(width: 8), Text(_price(_item.price), style: const TextStyle(color: _green, fontWeight: FontWeight.w900))]),
              const SizedBox(height: 6),
              Text(_item.description, maxLines: 3, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _muted, fontSize: 11.5, height: 1.45)),
            ]),
          ),
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 9),
          decoration: const BoxDecoration(color: Color(0xFFF7F9FA)),
          child: Row(children: [_CompactAction(icon: _item.likedByMe ? Icons.favorite : Icons.favorite_border, label: '${_item.likeCount}', active: _item.likedByMe, onTap: _toggleLike), const SizedBox(width: 8), Text('${_item.commentCount} comments', style: const TextStyle(color: _muted, fontWeight: FontWeight.w700)), const Spacer(), TextButton.icon(onPressed: _contactSeller, icon: const Icon(Icons.shopping_cart_checkout_rounded, size: 17), label: const Text('Interested'))]),
        ),
        Expanded(
          child: _loading
              ? const Center(child: CircularProgressIndicator(color: _green))
              : parents.isEmpty
                  ? const Center(child: Text('No comments yet. Ask about the item or start a discussion.', textAlign: TextAlign.center, style: TextStyle(color: _muted)))
                  : ListView.separated(
                      padding: const EdgeInsets.all(12),
                      itemCount: parents.length,
                      separatorBuilder: (_, __) => const SizedBox(height: 10),
                      itemBuilder: (context, index) {
                        final parent = parents[index];
                        return _CommentThread(comment: parent, replies: replies[parent.id] ?? const <MarketComment>[], onReply: (comment) => setState(() => _replyingTo = comment));
                      },
                    ),
        ),
        if (_replyingTo != null)
          Container(
            margin: const EdgeInsets.fromLTRB(10, 0, 10, 8),
            padding: const EdgeInsets.symmetric(horizontal: 11, vertical: 7),
            decoration: BoxDecoration(color: _green.withOpacity(0.06), borderRadius: BorderRadius.circular(13)),
            child: Row(children: [Expanded(child: Text('Replying to ${_replyingTo!.authorName}', style: const TextStyle(color: _green, fontWeight: FontWeight.w800, fontSize: 11))), IconButton(onPressed: () => setState(() => _replyingTo = null), icon: const Icon(Icons.close, size: 17))]),
          ),
        Container(
          padding: const EdgeInsets.all(10),
          decoration: BoxDecoration(color: Colors.white, border: Border(top: BorderSide(color: Colors.grey.shade200))),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Expanded(child: TextField(controller: _comment, minLines: 1, maxLines: 4, maxLength: 1000, decoration: InputDecoration(counterText: '', hintText: _replyingTo == null ? 'Comment on this item...' : 'Write a reply...', filled: true, fillColor: const Color(0xFFF7F9FA), border: OutlineInputBorder(borderRadius: BorderRadius.circular(14), borderSide: BorderSide.none)))),
              const SizedBox(width: 7),
              SizedBox(width: 45, height: 46, child: OutlinedButton(onPressed: _chooseMention, style: OutlinedButton.styleFrom(padding: EdgeInsets.zero, foregroundColor: _green), child: const Text('@', style: TextStyle(fontWeight: FontWeight.w900, fontSize: 18)))),
              const SizedBox(width: 7),
              SizedBox(width: 48, height: 46, child: FilledButton(onPressed: _posting ? null : _postComment, style: FilledButton.styleFrom(backgroundColor: _green, padding: EdgeInsets.zero), child: _posting ? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white)) : const Icon(Icons.send_rounded))),
            ],
          ),
        ),
      ],
    );
  }
}

class _CommentThread extends StatelessWidget {
  final MarketComment comment;
  final List<MarketComment> replies;
  final ValueChanged<MarketComment> onReply;

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

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

class _CommentBubble extends StatelessWidget {
  final MarketComment comment;
  final VoidCallback onReply;

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

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

class _MentionSheet extends StatefulWidget {
  final List<MarketMentionableUser> users;

  const _MentionSheet({required this.users});

  @override
  State<_MentionSheet> createState() => _MentionSheetState();
}

class _MentionSheetState extends State<_MentionSheet> {
  final TextEditingController _search = TextEditingController();
  late List<MarketMentionableUser> _filtered;

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

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

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

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

class _MarketNotificationsSheet extends StatelessWidget {
  final List<MarketNotification> notifications;
  final int unreadCount;
  final Future<void> Function() onMarkAllRead;
  final Future<void> Function(MarketNotification) onRead;

  const _MarketNotificationsSheet({required this.notifications, required this.unreadCount, required this.onMarkAllRead, required this.onRead});

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

class _NotificationBell extends StatelessWidget {
  final int unreadCount;
  final VoidCallback onTap;

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

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

class _CompactAction extends StatelessWidget {
  final IconData icon;
  final String label;
  final VoidCallback onTap;
  final bool active;

  const _CompactAction({required this.icon, required this.label, required this.onTap, this.active = false});

  @override
  Widget build(BuildContext context) {
    return InkWell(onTap: onTap, borderRadius: BorderRadius.circular(99), child: Container(padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 7), decoration: BoxDecoration(color: active ? Colors.red.withOpacity(0.07) : const Color(0xFFF4F6F8), borderRadius: BorderRadius.circular(99)), child: Row(mainAxisSize: MainAxisSize.min, children: [Icon(icon, size: 16, color: active ? Colors.red.shade600 : _muted), const SizedBox(width: 4), Text(label, style: TextStyle(fontSize: 10.5, fontWeight: FontWeight.w800, color: active ? Colors.red.shade700 : _muted))])));
  }
}

class _MarketItemImage extends StatelessWidget {
  final MarketItem item;

  const _MarketItemImage({required this.item});

  @override
  Widget build(BuildContext context) {
    if (item.images.isNotEmpty) {
      final media = item.images.first;
      final value = media.thumbnailPath.isNotEmpty ? media.thumbnailPath : media.path;
      return MarketCachedImage(url: MarketOfflineService.mediaUrl(value));
    }
    if (item.legacyImageUrl.isNotEmpty) return _LegacyOrNetworkImage(value: item.legacyImageUrl);
    return const _ImageFallback();
  }
}

class _LegacyOrNetworkImage extends StatelessWidget {
  final String value;

  const _LegacyOrNetworkImage({required this.value});

  @override
  Widget build(BuildContext context) {
    final text = value.trim();
    if (text.startsWith('http://') || text.startsWith('https://') || MarketOfflineService.isStoredPath(text)) {
      return MarketCachedImage(url: MarketOfflineService.mediaUrl(text));
    }
    try {
      var raw = text;
      if (raw.contains(',')) raw = raw.split(',').last;
      raw = raw.replaceAll(RegExp(r'\s+'), '');
      return Image.memory(base64Decode(raw), fit: BoxFit.cover, errorBuilder: (_, __, ___) => const _ImageFallback());
    } catch (_) {
      return const _ImageFallback();
    }
  }
}

class _ImageFallback extends StatelessWidget {
  const _ImageFallback();

  @override
  Widget build(BuildContext context) => Container(color: const Color(0xFFF0F2F4), alignment: Alignment.center, child: Icon(Icons.storefront_outlined, size: 48, color: Colors.grey.shade400));
}

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

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

  @override
  Widget build(BuildContext context) {
    final text = value.trim();
    Widget child;
    if (text.isEmpty) {
      child = _fallback();
    } else if (text.startsWith('http://') || text.startsWith('https://') || MarketOfflineService.isStoredPath(text)) {
      child = MarketCachedImage(url: MarketOfflineService.mediaUrl(text),decodeWidth:120);
    } else {
      try {
        var raw = text;
        if (raw.contains(',')) raw = raw.split(',').last;
        child = Image.memory(base64Decode(raw), fit: BoxFit.cover, errorBuilder: (_, __, ___) => _fallback());
      } catch (_) {
        child = _fallback();
      }
    }
    return Container(width: size, height: size, clipBehavior: Clip.antiAlias, decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: _gold.withOpacity(0.4))), child: child);
  }

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

class _Pill extends StatelessWidget {
  final String text;
  const _Pill(this.text);

  @override
  Widget build(BuildContext context) => Container(padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 7), decoration: BoxDecoration(color: _gold.withOpacity(0.10), borderRadius: BorderRadius.circular(99)), child: Text(text, style: const TextStyle(color: _gold, fontSize: 10, fontWeight: FontWeight.w900)));
}

class _MentionText extends StatelessWidget {
  final String text;
  const _MentionText({required this.text});

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

int _imageCount(MarketItem item) => item.images.isNotEmpty ? item.images.length : (item.legacyImageUrl.isNotEmpty ? 1 : 0);
String _price(double price) => 'K ${price.toStringAsFixed(2)}';
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 ?? ''}'.toLowerCase().trim(); return text == '1' || text == 'true' || text == 't' || text == 'yes'; }
String _timeAgo(DateTime value) { final d = DateTime.now().difference(value.toLocal()); if (d.isNegative || d.inSeconds < 60) return 'just now'; if (d.inMinutes < 60) return '${d.inMinutes}m ago'; if (d.inHours < 24) return '${d.inHours}h ago'; if (d.inDays < 7) return '${d.inDays}d ago'; return '${value.day.toString().padLeft(2,'0')}/${value.month.toString().padLeft(2,'0')}/${value.year}'; }
