import 'package:flutter/material.dart';
import 'package:intl/intl.dart';


// ─────────────────────────────────────────
// MODELS
// ─────────────────────────────────────────

class Product {
  final String id;
  final String name;
  final String quantity;
  final double price;
  final String emoji;
  final String category;
  final bool isPopular;
  int count;
  bool isSelected;

  Product({
    required this.id,
    required this.name,
    required this.quantity,
    required this.price,
    required this.emoji,
    required this.category,
    this.isPopular = false,
    this.count = 0,
    this.isSelected = false,
  });
}

class Store {
  final String name;
  final double rating;
  final String deliveryTime;
  final String distance;
  final Color color;

  const Store({
    required this.name,
    required this.rating,
    required this.deliveryTime,
    required this.distance,
    required this.color,
  });
}

// ─────────────────────────────────────────
// DATA
// ─────────────────────────────────────────

final List<Store> availableStores = [
  Store(name: 'Fresh Mart', rating: 4.8, deliveryTime: '20-30 mins', distance: '2.1 km away', color: Color(0xFF1A7A3C)),
  Store(name: 'Green Basket', rating: 4.5, deliveryTime: '25-35 mins', distance: '3.4 km away', color: Color(0xFF2E7D32)),
  Store(name: 'Daily Needs', rating: 4.3, deliveryTime: '30-45 mins', distance: '1.8 km away', color: Color(0xFF1565C0)),
  Store(name: 'Super Saver', rating: 4.6, deliveryTime: '15-25 mins', distance: '4.0 km away', color: Color(0xFFE65100)),
];

List<Product> getFrequentProducts() => [
  Product(id: 'milk', name: 'Milk', quantity: '1 Litre', price: 56, emoji: '🥛', category: 'Milk & Dairy', isPopular: true, count: 1, isSelected: true),
  Product(id: 'eggs', name: 'Eggs', quantity: '6 Pieces', price: 36, emoji: '🥚', category: 'Milk & Dairy', isPopular: true, count: 1, isSelected: true),
  Product(id: 'bread', name: 'Bread', quantity: '1 Pack', price: 30, emoji: '🍞', category: 'Bakery', count: 0, isSelected: false),
  Product(id: 'banana', name: 'Banana', quantity: '6 Pieces', price: 28, emoji: '🍌', category: 'Fruits', count: 1, isSelected: true),
  Product(id: 'oats', name: 'Oats', quantity: '500 g', price: 80, emoji: '🌾', category: 'Staples', count: 0, isSelected: false),
];

Map<String, List<Product>> getAllProducts() => {
  'Milk & Dairy': [
    Product(id: 'fresh_milk', name: 'Fresh Milk', quantity: '1 Litre', price: 56, emoji: '🥛', category: 'Milk & Dairy', isPopular: true),
    Product(id: 'curd', name: 'Curd', quantity: '500 g', price: 28, emoji: '🫙', category: 'Milk & Dairy', isPopular: true),
    Product(id: 'butter', name: 'Butter', quantity: '100 g', price: 62, emoji: '🧈', category: 'Milk & Dairy'),
    Product(id: 'cheese', name: 'Cheese', quantity: '200 g', price: 110, emoji: '🧀', category: 'Milk & Dairy'),
    Product(id: 'paneer', name: 'Paneer', quantity: '200 g', price: 90, emoji: '🟨', category: 'Milk & Dairy'),
    Product(id: 'dahi', name: 'Dahi', quantity: '200 g', price: 22, emoji: '🫙', category: 'Milk & Dairy'),
    Product(id: 'buttermilk', name: 'Buttermilk', quantity: '500 ml', price: 18, emoji: '🥛', category: 'Milk & Dairy'),
    Product(id: 'fresh_cream', name: 'Fresh Cream', quantity: '200 ml', price: 45, emoji: '🍦', category: 'Milk & Dairy'),
  ],
  'Vegetables': [
    Product(id: 'tomato', name: 'Tomato', quantity: '500 g', price: 25, emoji: '🍅', category: 'Vegetables', isPopular: true),
    Product(id: 'onion', name: 'Onion', quantity: '1 kg', price: 35, emoji: '🧅', category: 'Vegetables'),
    Product(id: 'potato', name: 'Potato', quantity: '1 kg', price: 30, emoji: '🥔', category: 'Vegetables', isPopular: true),
    Product(id: 'spinach', name: 'Spinach', quantity: '250 g', price: 20, emoji: '🥬', category: 'Vegetables'),
    Product(id: 'carrot', name: 'Carrot', quantity: '500 g', price: 30, emoji: '🥕', category: 'Vegetables'),
    Product(id: 'capsicum', name: 'Capsicum', quantity: '250 g', price: 28, emoji: '🫑', category: 'Vegetables'),
  ],
  'Fruits': [
    Product(id: 'apple', name: 'Apple', quantity: '4 Pieces', price: 80, emoji: '🍎', category: 'Fruits', isPopular: true),
    Product(id: 'banana_f', name: 'Banana', quantity: '6 Pieces', price: 28, emoji: '🍌', category: 'Fruits', isPopular: true),
    Product(id: 'mango', name: 'Mango', quantity: '2 Pieces', price: 60, emoji: '🥭', category: 'Fruits'),
    Product(id: 'grapes', name: 'Grapes', quantity: '500 g', price: 70, emoji: '🍇', category: 'Fruits'),
    Product(id: 'orange', name: 'Orange', quantity: '4 Pieces', price: 55, emoji: '🍊', category: 'Fruits'),
  ],
  'Staples': [
    Product(id: 'rice', name: 'Rice', quantity: '1 kg', price: 55, emoji: '🍚', category: 'Staples', isPopular: true),
    Product(id: 'dal', name: 'Dal', quantity: '500 g', price: 65, emoji: '🫘', category: 'Staples'),
    Product(id: 'oats_s', name: 'Oats', quantity: '500 g', price: 80, emoji: '🌾', category: 'Staples'),
    Product(id: 'atta', name: 'Atta', quantity: '1 kg', price: 45, emoji: '🌾', category: 'Staples'),
  ],
  'Snacks': [
    Product(id: 'chips', name: 'Chips', quantity: '100 g', price: 20, emoji: '🥨', category: 'Snacks'),
    Product(id: 'biscuits', name: 'Biscuits', quantity: '200 g', price: 35, emoji: '🍪', category: 'Snacks'),
    Product(id: 'namkeen', name: 'Namkeen', quantity: '200 g', price: 40, emoji: '🫘', category: 'Snacks'),
  ],
  'Beverages': [
    Product(id: 'tea', name: 'Tea', quantity: '250 g', price: 70, emoji: '🍵', category: 'Beverages', isPopular: true),
    Product(id: 'coffee', name: 'Coffee', quantity: '100 g', price: 120, emoji: '☕', category: 'Beverages'),
    Product(id: 'juice', name: 'Juice', quantity: '1 L', price: 85, emoji: '🧃', category: 'Beverages'),
  ],
  'Bakery': [
    Product(id: 'bread_b', name: 'Bread', quantity: '1 Pack', price: 30, emoji: '🍞', category: 'Bakery', isPopular: true),
    Product(id: 'bun', name: 'Bun', quantity: '6 Pieces', price: 25, emoji: '🥐', category: 'Bakery'),
  ],
};

// ─────────────────────────────────────────
// CONSTANTS
// ─────────────────────────────────────────

const kGreen = Color(0xFF1A7A3C);
const kGreenLight = Color(0xFFE8F5EE);
const kBg = Color(0xFFF5F7F5);
const kText = Color(0xFF1C1C1C);

// ─────────────────────────────────────────
// APP
// ─────────────────────────────────────────



// ─────────────────────────────────────────
// SCREEN 1 — CREATE DAILY PLAN
// ─────────────────────────────────────────

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

  @override
  State<CreateDailyPlanScreen> createState() => _CreateDailyPlanScreenState();
}

class _CreateDailyPlanScreenState extends State<CreateDailyPlanScreen> {
  Store _store = availableStores[0];
  late List<Product> _frequentProducts;
  String _deliveryTime = 'Morning';
  Set<String> _deliveryDays = {'Mon', 'Tue', 'Wed', 'Thu', 'Fri'};
  String _selectedCategory = 'All';
  bool _agreedToTerms = false;

// Add these to your state variables:
  DateTime _startDate = DateTime.now();
  DateTime? _endDate;
  bool _noEndDate = false;
  final List<Map<String, dynamic>> _timeSlots = [
    {'label': 'Morning', 'time': '6 AM – 9 AM', 'icon': '🌅', 'popular': true},
    {'label': 'Forenoon', 'time': '9 AM – 12 PM', 'icon': '☀️', 'popular': false},
    {'label': 'Afternoon', 'time': '12 PM – 4 PM', 'icon': '🌤️', 'popular': false},
    {'label': 'Evening', 'time': '4 PM – 8 PM', 'icon': '🌇', 'popular': false},
    {'label': 'Night', 'time': '8 PM – 10 PM', 'icon': '🌙', 'popular': false},
  ];

  final List<String> _allDays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
  final List<String> _categoryTabs = ['All', 'Milk & Dairy', 'Vegetables', 'Fruits', 'Staples', 'Snacks', 'More'];

  @override
  void initState() {
    super.initState();
    _frequentProducts = getFrequentProducts();
  }

  double get _dailyTotal =>
      _frequentProducts.where((p) => p.count > 0).fold(0, (s, p) => s + p.price * p.count);

  int get _selectedCount => _frequentProducts.where((p) => p.count > 0).length;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: kBg,
      body: SafeArea(
        child: Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _buildHeader(),
                    const SizedBox(height: 12),
                    _buildCard(_buildStoreSection()),
                    const SizedBox(height: 12),
                    _buildCard(_buildItemsSection()),
                    const SizedBox(height: 12),
                    _buildCard(_buildDeliveryTimeSection()),
                    const SizedBox(height: 12),
                    _buildCard(_buildDeliveryDaysSection()),
                    const SizedBox(height: 12),
                    _buildCard(_buildSummarySection()),
                    const SizedBox(height: 8),
                  ],
                ),
              ),
            ),
            _buildBottomBar(),
          ],
        ),
      ),
    );
  }

  Widget _buildHeader() {
    return Container(

      padding: const EdgeInsets.fromLTRB(16, 12, 16, 14),
      child: Row(
        children: [
          GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            child: const Icon(Icons.arrow_back, size: 22, color: kText),
          ),
          const SizedBox(width: 12),
          const Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('Create Daily Plan',
                    style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: kText)),
                Text('Set your everyday essentials, we\'ll deliver on time.',
                    style: TextStyle(fontSize: 12, color: Colors.grey)),
              ],
            ),
          ),
          const Text('🛒', style: TextStyle(fontSize: 34)),
        ],
      ),
    );
  }

  Widget _buildCard(Widget child) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.04), blurRadius: 8, offset: const Offset(0, 2))],
      ),
      child: child,
    );
  }

  // ── 1. Store section ──
  Widget _buildStoreSection() {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text('1. Choose Store',
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: kText)),
          const SizedBox(height: 12),
          Row(
            children: [
              Container(
                width: 52, height: 52,
                decoration: BoxDecoration(color: _store.color, borderRadius: BorderRadius.circular(12)),
                child: const Icon(Icons.shopping_basket, color: Colors.white, size: 26),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(_store.name,
                        style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16, color: kText)),
                    const SizedBox(height: 3),
                    Row(
                      children: [
                        const Icon(Icons.star, color: Color(0xFFFFB300), size: 14),
                        const SizedBox(width: 3),
                        Text('${_store.rating}',
                            style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: kText)),
                        const SizedBox(width: 5),
                        Container(width: 3, height: 3,
                            decoration: const BoxDecoration(color: Colors.grey, shape: BoxShape.circle)),
                        const SizedBox(width: 5),
                        Text(_store.deliveryTime,
                            style: const TextStyle(fontSize: 13, color: Colors.grey)),
                      ],
                    ),
                    Text(_store.distance, style: const TextStyle(fontSize: 12, color: Colors.grey)),
                  ],
                ),
              ),
              OutlinedButton(
                onPressed: _openChangeStore,
                style: OutlinedButton.styleFrom(
                  side: const BorderSide(color: kGreen),
                  foregroundColor: kGreen,
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                ),
                child: const Row(
                  children: [
                    Text('Change Store', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600)),
                    SizedBox(width: 4),
                    Icon(Icons.chevron_right, size: 16),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
            decoration: BoxDecoration(color: kGreenLight, borderRadius: BorderRadius.circular(10)),
            child: Row(
              children: [
                const Icon(Icons.info_outline, color: kGreen, size: 16),
                const SizedBox(width: 8),
                RichText(
                  text: const TextSpan(
                    style: TextStyle(fontSize: 12, color: Colors.black87),
                    children: [
                      TextSpan(text: 'Your daily plan will be created from this '),
                      TextSpan(text: 'store only.',
                          style: TextStyle(color: kGreen, fontWeight: FontWeight.w600)),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // ── 2. Items section ──
  Widget _buildItemsSection() {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text('2. Add items to your daily plan',
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: kText)),
          Text('Choose items you need regularly from ${_store.name}',
              style: const TextStyle(fontSize: 12, color: Colors.grey)),
          const SizedBox(height: 14),
          // Category tabs
          SizedBox(
            height: 70,
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: _categoryTabs.length,
              itemBuilder: (context, i) {
                final tab = _categoryTabs[i];
                final isSelected = tab == _selectedCategory;
                final emojis = {'All': '⊞', 'Milk & Dairy': '🥛', 'Vegetables': '🥦',
                  'Fruits': '🍎', 'Staples': '🫙', 'Snacks': '🍟', 'More': '›'};
                return GestureDetector(
                  onTap: () => setState(() => _selectedCategory = tab),
                  child: Container(
                    margin: const EdgeInsets.only(right: 16),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Container(
                          width: 44, height: 44,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            color: isSelected ? kGreenLight : const Color(0xFFF5F5F5),
                            border: isSelected ? Border.all(color: kGreen, width: 2) : null,
                          ),
                          child: Center(
                            child: Text(emojis[tab] ?? '📦',
                                style: const TextStyle(fontSize: 20)),
                          ),
                        ),
                        const SizedBox(height: 4),
                        Text(tab,
                            style: TextStyle(
                              fontSize: 10,
                              color: isSelected ? kGreen : Colors.grey[600],
                              fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                            )),
                      ],
                    ),
                  ),
                );
              },
            ),
          ),
          const SizedBox(height: 14),
          // Frequently Bought heading
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text('Your Frequently Bought from ${_store.name}',
                  style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14, color: kText)),
              GestureDetector(
                onTap: _openAddProducts,
                child: const Row(
                  children: [
                    Icon(Icons.add, color: kGreen, size: 16),
                    Text(' Add all', style: TextStyle(color: kGreen, fontSize: 13, fontWeight: FontWeight.w600)),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          // Products row
          SizedBox(
            height: 168,
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: _frequentProducts.length,
              itemBuilder: (context, i) => _buildFrequentProductCard(_frequentProducts[i]),
            ),
          ),
          const SizedBox(height: 12),
          // Smart suggestion bar
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
            decoration: BoxDecoration(
              color: const Color(0xFFF9F9F9),
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: const Color(0xFFEEEEEE)),
            ),
            child: Row(
              children: [
                const Text('🛒', style: TextStyle(fontSize: 22)),
                const SizedBox(width: 10),
                const Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('Smart Suggestion',
                          style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13, color: kText)),
                      Text('Based on your past orders, we\'ve suggested these essentials.',
                          style: TextStyle(fontSize: 11, color: Colors.grey)),
                    ],
                  ),
                ),
                GestureDetector(
                  onTap: _openAddProducts,
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 7),
                    decoration: BoxDecoration(
                      border: Border.all(color: const Color(0xFFDDDDDD)),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: const Text('View all',
                        style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: kText)),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFrequentProductCard(Product product) {
    final isAdded = product.count > 0;
    return Container(


      width: 120,
      margin: const EdgeInsets.only(right: 10),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(14),
        border: Border.all(color: isAdded ? kGreen : const Color(0xFFE0E0E0), width: isAdded ? 2 : 1),
        color: Colors.white,
      ),
      child: Stack(
        children: [
          Padding(
            padding: const EdgeInsets.fromLTRB(10, 10, 10, 8),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Center(child: Text(product.emoji, style: const TextStyle(fontSize: 42))),
                const SizedBox(height: 4),
                Row(
                  children: [
                    Text(product.name,
                        style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 10, color: kText)),
                    SizedBox(width: 7),
                    Text(product.quantity, style: const TextStyle(fontSize: 7, color: Colors.black54)),

                  ],
                ),
                const SizedBox(height: 2),
                Text('₹${product.price.toStringAsFixed(0)}',
                    style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 13, color: kText)),
                const SizedBox(height: 6),
                // Counter
                Container(
                  height: 20,
                  decoration: BoxDecoration(
                    border: Border.all(color: isAdded ? kGreen : const Color(0xFFDDDDDD)),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      _counterBtn(Icons.remove, () {
                        setState(() { if (product.count > 0) product.count--; });
                      }),
                      Text('${product.count}',
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 13,
                            color: isAdded ? kGreen : Colors.grey,
                          )),
                      _counterBtn(Icons.add, () {
                        setState(() => product.count++);
                      }),
                    ],
                  ),
                ),
              ],
            ),
          ),

        ],
      ),
    );
  }

  Widget _counterBtn(IconData icon, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 8),
        child: Icon(icon, size: 14, color: kGreen),
      ),
    );
  }

  // ── 3. Delivery time ──
  Widget _buildDeliveryTimeSection() {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text('3. Choose delivery time',
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: kText)),
          const Text('We\'ll deliver your items daily',
              style: TextStyle(fontSize: 12, color: Colors.grey)),
          const SizedBox(height: 14),
          SizedBox(
            height: 90, // ← reduced from 130
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: _timeSlots.length,
              itemBuilder: (context, i) {
                final slot = _timeSlots[i];
                final isSelected = slot['label'] == _deliveryTime;
                return GestureDetector(
                  onTap: () => setState(() => _deliveryTime = slot['label']),
                  child: Container(
                    width: 80, // ← reduced from 100
                    margin: const EdgeInsets.only(right: 8), // ← reduced from 10
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(10), // ← reduced from 12
                      border: Border.all(
                        color: isSelected ? kGreen : const Color(0xFFE0E0E0),
                        width: isSelected ? 2 : 1,
                      ),
                      color: isSelected ? kGreenLight : Colors.white,
                    ),
                    child: Padding(
                      padding: const EdgeInsets.all(6), // ← reduced from 10
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(slot['icon'], style: const TextStyle(fontSize: 18)), // ← reduced from 22
                          const SizedBox(height: 2),
                          Text(slot['label'],
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: 11, // ← reduced from 12
                                color: isSelected ? kGreen : kText,
                              )),
                          Text(slot['time'],
                              style: const TextStyle(fontSize: 8, color: Colors.grey), // ← reduced from 9
                              textAlign: TextAlign.center),
                        ],
                      ),
                    ),
                  ),
                );
              },
            ),
          ),
          const SizedBox(height: 10),
        ],
      ),
    );
  }
  // ── 4. Delivery days ──
  Widget _buildDeliveryDaysSection() {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '4. Select delivery days',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: kText,
            ),
          ),
          const Text(
            'On which days should we deliver?',
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey,
            ),
          ),
          const SizedBox(height: 14),

          // Days
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: _allDays.map((day) {
              final isSelected = _deliveryDays.contains(day);

              return GestureDetector(
                onTap: () {
                  setState(() {
                    if (isSelected) {
                      _deliveryDays.remove(day);
                    } else {
                      _deliveryDays.add(day);
                    }
                  });
                },
                child: Container(
                  width: 44,
                  height: 58,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),
                    color: isSelected
                        ? kGreenLight
                        : const Color(0xFFF5F5F5),
                    border: Border.all(
                      color: isSelected
                          ? kGreen
                          : Colors.transparent,
                      width: isSelected ? 1.5 : 0,
                    ),
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        day,
                        style: TextStyle(
                          fontSize: 13,
                          fontWeight: FontWeight.w700,
                          color: isSelected
                              ? kGreen
                              : Colors.grey[700],
                        ),
                      ),
                      const SizedBox(height: 4),
                      Icon(
                        isSelected
                            ? Icons.check_circle
                            : Icons.circle_outlined,
                        color: isSelected
                            ? kGreen
                            : Colors.grey[300],
                        size: 16,
                      ),
                    ],
                  ),
                ),
              );
            }).toList(),
          ),

          const SizedBox(height: 20),

          const Text(
            'Duration',
            style: TextStyle(
              fontSize: 13,
              fontWeight: FontWeight.w600,
              color: kText,
            ),
          ),

          const SizedBox(height: 10),

          Row(
            children: [
              Expanded(
                child: _buildDateField(
                  label: 'Start date',
                  date: _startDate,
                  onTap: () async {
                    final picked = await showDatePicker(
                      context: context,
                      initialDate: _startDate,
                      firstDate: DateTime.now(),
                      lastDate: DateTime(2100),
                    );

                    if (picked != null) {
                      setState(() {
                        _startDate = picked;

                        if (_endDate != null &&
                            _endDate!.isBefore(_startDate)) {
                          _endDate = _startDate
                              .add(const Duration(days: 30));
                        }
                      });
                    }
                  },
                ),
              ),

              const SizedBox(width: 12),

              Expanded(
                child: _buildDateField(
                  label: 'End date',
                  date: _noEndDate ? null : _endDate,
                  enabled: !_noEndDate,
                  onTap: _noEndDate
                      ? null
                      : () async {
                    final initialDate =
                    (_endDate != null &&
                        !_endDate!.isBefore(_startDate))
                        ? _endDate!
                        : _startDate.add(
                      const Duration(days: 30),
                    );

                    final picked = await showDatePicker(
                      context: context,
                      initialDate: initialDate,
                      firstDate: _startDate,
                      lastDate: DateTime(2100),
                    );

                    if (picked != null) {
                      setState(() {
                        _endDate = picked;
                      });
                    }
                  },
                ),
              ),
            ],
          ),

          const SizedBox(height: 12),

          GestureDetector(
            onTap: () {
              setState(() {
                _noEndDate = !_noEndDate;
              });
            },
            child: Container(
              padding: const EdgeInsets.symmetric(
                horizontal: 14,
                vertical: 12,
              ),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8),
                border: Border.all(
                  color: _noEndDate
                      ? kGreen
                      : Colors.grey.shade300,
                  width: _noEndDate ? 1.5 : 1,
                ),
                color: _noEndDate
                    ? kGreenLight
                    : Colors.white,
              ),
              child: Row(
                children: [
                  AnimatedContainer(
                    duration: const Duration(milliseconds: 150),
                    width: 20,
                    height: 20,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(4),
                      border: Border.all(
                        color: _noEndDate
                            ? kGreen
                            : Colors.grey.shade400,
                        width: 1.5,
                      ),
                      color: _noEndDate
                          ? kGreen
                          : Colors.white,
                    ),
                    child: _noEndDate
                        ? const Icon(
                      Icons.check,
                      size: 14,
                      color: Colors.white,
                    )
                        : null,
                  ),
                  const SizedBox(width: 10),
                  Column(
                    crossAxisAlignment:
                    CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          const Icon(
                            Icons.all_inclusive,
                            size: 16,
                            color: Colors.grey,
                          ),
                          const SizedBox(width: 4),
                          Text(
                            'No end date',
                            style: TextStyle(
                              fontSize: 13,
                              fontWeight: FontWeight.w600,
                              color: _noEndDate
                                  ? kGreen
                                  : kText,
                            ),
                          ),
                        ],
                      ),
                      const Text(
                        'Continue until you pause or cancel',
                        style: TextStyle(
                          fontSize: 11,
                          color: Colors.grey,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
// Helper — add this as a separate method in your widget class
  Widget _buildDateField({
    required String label,
    required DateTime? date,
    bool enabled = true,
    VoidCallback? onTap,
  }) {
    final formatter = DateFormat('d MMM yyyy'); // import 'package:intl/intl.dart'
    return GestureDetector(
      onTap: enabled ? onTap : null,
      child: Container(
        padding: const EdgeInsets.fromLTRB(12, 8, 10, 10),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          border: Border.all(color: enabled ? kGreen : Colors.grey[300]!, width: 1.5),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(label,
                style: TextStyle(
                  fontSize: 10,
                  color: enabled ? kGreen : Colors.grey,
                  fontWeight: FontWeight.w500,
                )),
            const SizedBox(height: 4),
            Row(
              children: [
                Icon(Icons.calendar_today_outlined, size: 14, color: Colors.grey[600]),
                const SizedBox(width: 6),
                Expanded(
                  child: Text(
                    date != null ? formatter.format(date) : '—',
                    style: TextStyle(
                      fontSize: 13,
                      fontWeight: FontWeight.w500,
                      color: enabled ? kText : Colors.grey[400],
                    ),
                  ),
                ),
                Icon(Icons.chevron_right, size: 16, color: Colors.grey[400]),
              ],
            ),
          ],
        ),
      ),
    );
  }  // ── Summary ──


  Widget _buildSummarySection() {
    final selectedDaysStr = _deliveryDays.join(', ');
    final timeSlot = _timeSlots.firstWhere((s) => s['label'] == _deliveryTime);
    return Padding(
      padding: const EdgeInsets.fromLTRB(16, 16, 16, 4),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text('Your Daily Plan Summary',
              style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold, color: kText)),
          const SizedBox(height: 12),
          Container(
            padding: const EdgeInsets.all(14),
            decoration: BoxDecoration(
              color: kGreenLight,
              borderRadius: BorderRadius.circular(12),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _summaryChip('🛒', '$_selectedCount Items'),
                _divider(),
                _summaryChip('🌅', '${timeSlot['label']}\n${timeSlot['time']}'),
                _divider(),
                _summaryChip('📅', selectedDaysStr),
              ],
            ),
          ),
          SizedBox(
            height: 20,
          )
        ],
      ),
    );
  }

  Widget _summaryChip(String emoji, String text) {
    return Expanded(
      child: Column(
        children: [
          Text(emoji, style: const TextStyle(fontSize: 20)),
          const SizedBox(height: 4),
          Text(text,
              textAlign: TextAlign.center,
              style: const TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: kText)),
        ],
      ),
    );
  }

  Widget _divider() => Container(height: 36, width: 1, color: kGreen.withOpacity(0.2));

  // ── Bottom bar ──
  Widget _buildBottomBar() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.fromLTRB(16, 10, 16, MediaQuery.of(context).padding.bottom + 10),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            children: [
              Checkbox(
                value: _agreedToTerms,
                onChanged: (v) => setState(() => _agreedToTerms = v ?? false),
                activeColor: kGreen,
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)),
              ),
              Flexible(
                child: RichText(
                  text: const TextSpan(
                    style: TextStyle(fontSize: 12, color: Colors.black87),
                    children: [
                      TextSpan(text: 'I agree to the Auto Daily Plan '),
                      TextSpan(text: 'terms and conditions',
                          style: TextStyle(color: kGreen, fontWeight: FontWeight.w600)),
                    ],
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: 6),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Text('Estimated daily total  ₹${_dailyTotal.toStringAsFixed(0)}',
                          style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 15, color: kText)),
                      const SizedBox(width: 4),
                      const Icon(Icons.info_outline, size: 14, color: Colors.grey),
                    ],
                  ),
                  const Text('You can edit anytime',
                      style: TextStyle(fontSize: 11, color: Colors.grey)),
                ],
              ),
              ElevatedButton(
                onPressed: _agreedToTerms ? () {} : null,
                style: ElevatedButton.styleFrom(
                  backgroundColor: kGreen,
                  disabledBackgroundColor: Colors.grey[300],
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                  elevation: 0,
                ),
                child: const Text('Create Daily Plan',
                    style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)),
              ),
            ],
          ),
        ],
      ),
    );
  }

  // ── Open sheets ──
  void _openChangeStore() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (_) => ChangeStoreSheet(
        selectedStore: _store,
        onStoreSelected: (s) => setState(() => _store = s),
      ),
    );
  }

  void _openAddProducts() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (_) => AddProductsSheet(
        selectedProducts: _frequentProducts.where((p) => p.isSelected).toList(),
        onProductsAdded: (products) => setState(() {
          // Merge selections back
          for (final p in products) {
            final existing = _frequentProducts.indexWhere((fp) => fp.id == p.id);
            if (existing == -1) {
              _frequentProducts.add(p..count = 1);
            } else {
              _frequentProducts[existing].isSelected = true;
              if (_frequentProducts[existing].count == 0) {
                _frequentProducts[existing].count = 1;
              }
            }
          }
        }),
      ),
    );
  }
}

// ─────────────────────────────────────────
// SHEET — CHANGE STORE
// ─────────────────────────────────────────

class ChangeStoreSheet extends StatefulWidget {
  final Store selectedStore;
  final Function(Store) onStoreSelected;

  const ChangeStoreSheet({super.key, required this.selectedStore, required this.onStoreSelected});

  @override
  State<ChangeStoreSheet> createState() => _ChangeStoreSheetState();
}

class _ChangeStoreSheetState extends State<ChangeStoreSheet> {
  late Store _selected;
  final TextEditingController _searchCtrl = TextEditingController();
  List<Store> _filtered = availableStores;

  @override
  void initState() {
    super.initState();
    _selected = widget.selectedStore;
  }

  void _filter(String q) => setState(() {
    _filtered = availableStores.where((s) => s.name.toLowerCase().contains(q.toLowerCase())).toList();
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // Handle
          Container(
            margin: const EdgeInsets.only(top: 12),
            width: 40, height: 4,
            decoration: BoxDecoration(color: Colors.grey[300], borderRadius: BorderRadius.circular(2)),
          ),
          // Header
          Padding(
            padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text('Choose Store',
                    style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: kText)),
                GestureDetector(
                  onTap: () => Navigator.pop(context),
                  child: Container(
                    padding: const EdgeInsets.all(4),
                    decoration: BoxDecoration(color: Colors.grey[100], shape: BoxShape.circle),
                    child: const Icon(Icons.close, size: 20, color: Colors.black54),
                  ),
                ),
              ],
            ),
          ),
          // Search
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
            child: TextField(
              controller: _searchCtrl,
              onChanged: _filter,
              decoration: InputDecoration(
                hintText: 'Search stores...',
                hintStyle: TextStyle(color: Colors.grey[400], fontSize: 14),
                prefixIcon: const Icon(Icons.search, color: Colors.grey),
                filled: true,
                fillColor: const Color(0xFFF5F5F5),
                border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide.none),
                contentPadding: const EdgeInsets.symmetric(vertical: 12),
              ),
            ),
          ),
          // Store list
          ConstrainedBox(
            constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.45),
            child: ListView.builder(
              shrinkWrap: true,
              padding: const EdgeInsets.symmetric(horizontal: 16),
              itemCount: _filtered.length,
              itemBuilder: (context, i) {
                final store = _filtered[i];
                final isSel = store.name == _selected.name;
                return GestureDetector(
                  onTap: () => setState(() => _selected = store),
                  child: AnimatedContainer(
                    duration: const Duration(milliseconds: 180),
                    margin: const EdgeInsets.only(bottom: 10),
                    padding: const EdgeInsets.all(14),
                    decoration: BoxDecoration(
                      // color: isSel ? kGreenLight : Colors.white,
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(14),
                      // border: Border.all(color: isSel ? kGreen : const Color(0xFFE0E0E0), width: isSel ? 2 : 1),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.12),
                          blurRadius: 3,
                          offset: const Offset(0, 1),
                        ),
                        BoxShadow(
                          color: Colors.black.withOpacity(0.08),
                          blurRadius: 20,
                          offset: const Offset(0, 6),
                        ),
                      ],
                    ),
                    child: Row(
                      children: [
                        Container(
                          width: 50, height: 50,
                          decoration: BoxDecoration(color: store.color, borderRadius: BorderRadius.circular(12)),
                          child: const Icon(Icons.shopping_basket, color: Colors.white, size: 26),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(store.name,
                                  style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16, color: kText)),
                              const SizedBox(height: 4),
                              Row(
                                children: [
                                  const Icon(Icons.star, color: Color(0xFFFFB300), size: 14),
                                  const SizedBox(width: 3),
                                  Text('${store.rating}',
                                      style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: kText)),
                                  const SizedBox(width: 6),
                                  Container(width: 3, height: 3,
                                      decoration: BoxDecoration(color: Colors.grey[400], shape: BoxShape.circle)),
                                  const SizedBox(width: 6),
                                  Text(store.deliveryTime,
                                      style: TextStyle(fontSize: 13, color: Colors.grey[600])),
                                ],
                              ),
                              Row(
                                children: [
                                  Icon(Icons.location_on, size: 13, color: Colors.grey[500]),
                                  const SizedBox(width: 2),
                                  Text(store.distance,
                                      style: TextStyle(fontSize: 12, color: Colors.grey[500])),
                                ],
                              ),
                            ],
                          ),
                        ),
                        Container(
                          width: 22, height: 22,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            border: Border.all(color: isSel ? kGreen : Colors.grey[400]!, width: 2),
                          ),
                          child: isSel
                              ? Center(
                            child: Container(
                              width: 12, height: 12,
                              decoration: const BoxDecoration(color: kGreen, shape: BoxShape.circle),
                            ),
                          )
                              : null,
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
          ),
          // Confirm button
          Padding(
            padding: EdgeInsets.fromLTRB(16, 8, 16, MediaQuery.of(context).padding.bottom + 16),
            child: SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: () {
                  widget.onStoreSelected(_selected);
                  Navigator.pop(context);
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: kGreen,
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
                  elevation: 0,
                ),
                child: const Text('Confirm Store',
                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

// ─────────────────────────────────────────
// SHEET — ADD PRODUCTS
// ─────────────────────────────────────────

class AddProductsSheet extends StatefulWidget {
  final List<Product> selectedProducts;
  final Function(List<Product>) onProductsAdded;

  const AddProductsSheet({super.key, required this.selectedProducts, required this.onProductsAdded});

  @override
  State<AddProductsSheet> createState() => _AddProductsSheetState();
}

class _AddProductsSheetState extends State<AddProductsSheet> {
  String _selectedCategory = 'Milk & Dairy';
  final TextEditingController _searchCtrl = TextEditingController();
  late Map<String, List<Product>> _allProducts;
  late List<Product> _selected;
  String _searchQuery = '';

  final List<Map<String, dynamic>> _categories = [
    {'name': 'Milk & Dairy', 'emoji': '🥛'},
    {'name': 'Vegetables', 'emoji': '🥦'},
    {'name': 'Fruits', 'emoji': '🍎'},
    {'name': 'Staples', 'emoji': '🌾'},
    {'name': 'Snacks', 'emoji': '🍪'},
    {'name': 'Beverages', 'emoji': '🍵'},
    {'name': 'Bakery', 'emoji': '🍞'},
  ];

  @override
  void initState() {
    super.initState();
    _allProducts = getAllProducts();
    _selected = List.from(widget.selectedProducts);
    for (var catList in _allProducts.values) {
      for (var p in catList) {
        if (_selected.any((sp) => sp.id == p.id)) p.isSelected = true;
      }
    }
  }

  List<Product> get _displayed {
    final products = _allProducts[_selectedCategory] ?? [];
    if (_searchQuery.isEmpty) return products;
    return products.where((p) => p.name.toLowerCase().contains(_searchQuery.toLowerCase())).toList();
  }

  void _toggle(Product p) {
    setState(() {
      p.isSelected = !p.isSelected;
      if (p.isSelected) { _selected.add(p); } else { _selected.removeWhere((s) => s.id == p.id); }
    });
  }

  double get _total => _selected.fold(0.0, (s, p) => s + p.price);

  @override
  Widget build(BuildContext context) {
    return DraggableScrollableSheet(
      initialChildSize: 0.92,
      minChildSize: 0.6,
      maxChildSize: 0.95,
      expand: false,
      builder: (context, scroll) {
        return Container(
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
          ),
          child: Column(
            children: [
              // Handle
              Container(
                margin: const EdgeInsets.only(top: 10),
                width: 40, height: 4,
                decoration: BoxDecoration(color: Colors.grey[300], borderRadius: BorderRadius.circular(2)),
              ),
              // Header
              Padding(
                padding: const EdgeInsets.fromLTRB(16, 14, 16, 0),
                child: Row(
                  children: [
                    GestureDetector(
                      onTap: () => Navigator.pop(context),
                      child: const Icon(Icons.close, size: 24, color: kText),
                    ),
                    const SizedBox(width: 12),
                    const Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('Add products from Fresh Mart',
                              style: TextStyle(fontSize: 17, fontWeight: FontWeight.bold, color: kText)),
                          Text('Choose the items you need regularly',
                              style: TextStyle(fontSize: 12, color: Colors.grey)),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 12),
              // Search & Filter
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: Row(
                  children: [
                    Expanded(
                      child: TextField(
                        controller: _searchCtrl,
                        onChanged: (q) => setState(() => _searchQuery = q),
                        decoration: InputDecoration(
                          hintText: 'Search products...',
                          hintStyle: TextStyle(color: Colors.grey[400], fontSize: 14),
                          prefixIcon: const Icon(Icons.search, color: Colors.grey),
                          filled: true,
                          fillColor: const Color(0xFFF5F5F5),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(12),
                            borderSide: BorderSide.none,
                          ),
                          contentPadding: const EdgeInsets.symmetric(vertical: 12),
                        ),
                      ),
                    ),
                    const SizedBox(width: 10),
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
                      decoration: BoxDecoration(
                        border: Border.all(color: const Color(0xFFE0E0E0)),
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: const Row(
                        children: [
                          Icon(Icons.tune, color: kGreen, size: 18),
                          SizedBox(width: 6),
                          Text('Filter', style: TextStyle(color: kGreen, fontWeight: FontWeight.w600, fontSize: 14)),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 14),
              // Category row
              SizedBox(
                height: 86,

                child: ListView.builder(
                  scrollDirection: Axis.horizontal,
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  itemCount: _categories.length,
                  itemBuilder: (context, i) {
                    final cat = _categories[i];
                    final isSel = cat['name'] == _selectedCategory;
                    return GestureDetector(
                      onTap: () => setState(() => _selectedCategory = cat['name']),
                      child: Container(
                        margin: const EdgeInsets.only(right: 14),
                        child: Column(
                          children: [
                            Container(
                              width: 56, height: 56,
                              decoration: BoxDecoration(
                                color: isSel ? kGreenLight : const Color(0xFFF5F5F5),
                                shape: BoxShape.circle,
                                border: isSel ? Border.all(color: kGreen, width: 2) : null,
                              ),
                              child: Center(child: Text(cat['emoji'], style: const TextStyle(fontSize: 26))),
                            ),
                            const SizedBox(height: 4),
                            Text(cat['name'],
                                style: TextStyle(
                                  fontSize: 10,
                                  fontWeight: isSel ? FontWeight.bold : FontWeight.normal,
                                  color: isSel ? kGreen : Colors.grey[700],
                                )),
                          ],
                        ),
                      ),
                    );
                  },
                ),
              ),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: Divider(color: Colors.grey[200], height: 1),
              ),
              // Category title & sort
              Padding(
                padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text('$_selectedCategory (${_allProducts[_selectedCategory]?.length ?? 0})',
                        style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16, color: kText)),
                    const Row(
                      children: [
                        Text('Sort', style: TextStyle(color: kGreen, fontWeight: FontWeight.w600, fontSize: 14)),
                        SizedBox(width: 4),
                        Icon(Icons.sort, color: kGreen, size: 18),
                      ],
                    ),
                  ],
                ),
              ),
              // Grid
              Expanded(
                child: GridView.builder(
                  controller: scroll,
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 3,
                    childAspectRatio: 0.76,
                    crossAxisSpacing: 12,
                    mainAxisSpacing: 12,
                  ),
                  itemCount: _displayed.length + 1,
                  itemBuilder: (context, i) {
                    if (i == _displayed.length) return _browseAllCard();
                    return _productCard(_displayed[i]);
                  },
                ),
              ),
              // Bottom selected bar
              if (_selected.isNotEmpty) _selectedBar(context),
            ],
          ),
        );
      },
    );
  }

  Widget _productCard(Product p) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(11),
        border: Border.all(color: p.isSelected ? kGreen : const Color(0xFFE8E8E8), width: p.isSelected ? 2 : 1),
      ),
      child: Stack(
        children: [
          Padding(
            padding: const EdgeInsets.all(12),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(child: Center(child: Text(p.emoji, style: const TextStyle(fontSize: 50)))),
                if (p.isPopular)
                  Container(
                    margin: const EdgeInsets.only(bottom: 4),
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                    decoration: BoxDecoration(color: kGreenLight, borderRadius: BorderRadius.circular(6)),
                    child: const Text('Popular', style: TextStyle(fontSize: 11, color: kGreen, fontWeight: FontWeight.w600)),
                  ),
                Text(p.name, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14, color: kText)),
                Text(p.quantity, style: TextStyle(fontSize: 12, color: Colors.grey[500])),
                const SizedBox(height: 4),
                Text('₹${p.price.toStringAsFixed(0)}',
                    style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 15, color: kText)),
              ],
            ),
          ),
          Positioned(
            bottom: 8, right: 8,
            child: GestureDetector(
              onTap: () => _toggle(p),
              child: Container(
                width: 28, height: 28,
                decoration: BoxDecoration(
                  color: p.isSelected ? kGreen : Colors.white,
                  shape: BoxShape.circle,
                  border: Border.all(color: p.isSelected ? kGreen : const Color(0xFFD0D0D0), width: 1.5),
                ),
                child: Icon(p.isSelected ? Icons.check : Icons.add,
                    size: 16, color: p.isSelected ? Colors.white : kGreen),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _browseAllCard() {
    return Container(
      decoration: BoxDecoration(
        color: const Color(0xFFF9F9F9),
        borderRadius: BorderRadius.circular(14),
        border: Border.all(color: const Color(0xFFE8E8E8)),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(Icons.shopping_basket_outlined, color: kGreen, size: 36),
          const SizedBox(height: 8),
          const Text("Can't find what\nyou're looking for?",
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 12, color: kText, fontWeight: FontWeight.w600)),
          const SizedBox(height: 4),
          Text('Browse all 340+ products from Fresh Mart',
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 10, color: Colors.grey[500])),
          const SizedBox(height: 8),
          const Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text('Browse all', style: TextStyle(color: kGreen, fontWeight: FontWeight.bold, fontSize: 13)),
              Icon(Icons.chevron_right, color: kGreen, size: 18),
            ],
          ),
        ],
      ),
    );
  }

  Widget _selectedBar(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.08), blurRadius: 12, offset: const Offset(0, -4))],
      ),
      child: Column(
        children: [
          SizedBox(
            height: 54,
            child: ListView(
              scrollDirection: Axis.horizontal,
              padding: const EdgeInsets.fromLTRB(16, 8, 16, 4),
              children: _selected.map((p) => Container(
                margin: const EdgeInsets.only(right: 8),
                child: Stack(
                  children: [
                    Container(
                      width: 38, height: 38,
                      decoration: BoxDecoration(
                        color: const Color(0xFFF5F5F5),
                        borderRadius: BorderRadius.circular(8),
                        border: Border.all(color: const Color(0xFFE0E0E0)),
                      ),
                      child: Center(child: Text(p.emoji, style: const TextStyle(fontSize: 20))),
                    ),
                    Positioned(
                      top: -2, right: -2,
                      child: GestureDetector(
                        onTap: () => _toggle(p),
                        child: Container(
                          width: 16, height: 16,
                          decoration: BoxDecoration(color: Colors.grey[400], shape: BoxShape.circle),
                          child: const Icon(Icons.close, size: 10, color: Colors.white),
                        ),
                      ),
                    ),
                  ],
                ),
              )).toList(),
            ),
          ),
          Padding(
            padding: EdgeInsets.fromLTRB(16, 4, 16, MediaQuery.of(context).padding.bottom + 12),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('${_selected.length} items selected',
                        style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 15, color: kText)),
                    GestureDetector(
                      onTap: () => setState(() {
                        for (var catList in _allProducts.values) {
                          for (var p in catList) p.isSelected = false;
                        }
                        _selected.clear();
                      }),
                      child: const Text('Clear all',
                          style: TextStyle(color: kGreen, fontSize: 13, fontWeight: FontWeight.w500)),
                    ),
                  ],
                ),
                ElevatedButton(
                  onPressed: () {
                    widget.onProductsAdded(_selected);
                    Navigator.pop(context);
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: kGreen,
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14),
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                    elevation: 0,
                  ),
                  child: Row(
                    children: [
                      Text('Add ${_selected.length} items  ₹${_total.toStringAsFixed(0)}',
                          style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14)),
                      const SizedBox(width: 4),
                      const Icon(Icons.chevron_right, size: 18),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}