import 'dart:async';

import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get_instance/src/extension_instance.dart';
import 'package:get/get_navigation/src/extension_navigation.dart';
import 'package:get/get_state_manager/src/rx_flutter/rx_obx_widget.dart';
import 'package:nearledaily/constants/color_constants.dart';
import 'package:nearledaily/features/dashboard/presentation/screens/voice_assistant_screen.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../../constants/font_constants.dart';
import '../../../../controllers/cart_controller/cart.dart';
import '../../../../controllers/dashboard_controller/dashboard_controller.dart';
import '../../../../domain/repository/authentication/auth_repository.dart';
import '../../../../modules/search_model/search_model.dart';
import '../../../../view/dashboard_view/searchScreen.dart';
import '../../../../view/home_view.dart';
import '../../../../view/product/product_details.dart';
import '../../../../view/product/products_list.dart' hide ProductItem;
import '../../../../widgets/text_widget.dart';
import '../../../Products/product_card.dart';
import 'ai_processing_screen.dart';
import 'camera_search.dart';
import 'daily_plan.dart' hide Product;
import '../../../../view/product/products_list.dart' as pl;


import '../../domain/repo/grocery_repository.dart';

// TODO: same path as in grocery_repository.dart — must point at the same
// `Product` class used by CartController.addToCart.
import '../../../../modules/product/product.dart';

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

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

final products = [
  // ── Food Delivery ──
  ProductItem(
    name: 'Chicken Biryani',
    category: 'Food Delivery · HotPot',
    price: '₹189',
    originalPrice: '₹240',
    image: 'https://images.unsplash.com/photo-1563379091339-03b21ab4a4f8?w=300&fit=crop',
    rating: 4.8,
    reviewCount: 320,
  ),
  ProductItem(
    name: 'Margherita Pizza',
    category: 'Food Delivery · Dominos',
    price: '₹149',
    originalPrice: '₹199',
    image: 'https://images.unsplash.com/photo-1565299624946-b28f40a0ae38?w=300&fit=crop',
    rating: 4.6,
    reviewCount: 512,
  ),
  ProductItem(
    name: 'Paneer Butter Masala',
    category: 'Food Delivery · Behrouz',
    price: '₹220',
    originalPrice: '₹280',
    image: 'https://images.unsplash.com/photo-1631452180519-c014fe946bc7?w=300&fit=crop',
    rating: 4.7,
    reviewCount: 210,
  ),
  ProductItem(
    name: 'Mango Smoothie',
    category: 'Food Delivery · Juice Bar',
    price: '₹89',
    originalPrice: '₹120',
    image: 'https://images.unsplash.com/photo-1623065422902-30a2d299bbe4?w=300&fit=crop',
    rating: 4.4,
    reviewCount: 67,
  ),

  // ── Grocery · Vegetables ──
  ProductItem(
    name: 'Fresh Veggie Basket',
    category: 'Grocery · Vegetables',
    price: '₹299',
    originalPrice: '₹420',
    image: 'https://images.unsplash.com/photo-1512621776951-a57141f2eefd?w=300&fit=crop',
    rating: 4.5,
    reviewCount: 180,
  ),
  ProductItem(
    name: 'Fresh Tomatoes 1kg',
    category: 'Grocery · Vegetables',
    price: '₹40',
    originalPrice: '₹50',
    image: 'https://images.unsplash.com/photo-1546470427-e26264be0b0d?w=300&fit=crop',
    rating: 4.3,
    reviewCount: 96,
  ),
  ProductItem(
    name: 'Onion 1kg',
    category: 'Grocery · Vegetables',
    price: '₹35',
    originalPrice: '₹45',
    image: 'https://images.unsplash.com/photo-1580201092675-a0a6a6cafbb1?w=300&fit=crop',
    rating: 4.2,
    reviewCount: 74,
  ),
  ProductItem(
    name: 'Green Capsicum 500g',
    category: 'Grocery · Vegetables',
    price: '₹30',
    originalPrice: '₹40',
    image: 'https://images.unsplash.com/photo-1563565375-f3fdfdbefa83?w=300&fit=crop',
    rating: 4.1,
    reviewCount: 41,
  ),

  // ── Grocery · Fruits ──
  ProductItem(
    name: 'Fresh Apples 1kg',
    category: 'Grocery · Fruits',
    price: '₹180',
    originalPrice: '₹220',
    image: 'https://images.unsplash.com/photo-1560806887-1e4cd0b6cbd6?w=300&fit=crop',
    rating: 4.6,
    reviewCount: 130,
  ),
  ProductItem(
    name: 'Banana Dozen',
    category: 'Grocery · Fruits',
    price: '₹50',
    originalPrice: '₹60',
    image: 'https://images.unsplash.com/photo-1571771894821-ce9b6c11b08e?w=300&fit=crop',
    rating: 4.5,
    reviewCount: 210,
  ),
  ProductItem(
    name: 'Alphonso Mango Box',
    category: 'Grocery · Fruits',
    price: '₹399',
    originalPrice: '₹499',
    image: 'https://images.unsplash.com/photo-1591073113125-e46713c829ed?w=300&fit=crop',
    rating: 4.8,
    reviewCount: 88,
  ),
  ProductItem(
    name: 'Pomegranate 1kg',
    category: 'Grocery · Fruits',
    price: '₹120',
    originalPrice: '₹150',
    image: 'https://images.unsplash.com/photo-1541344999736-83eca272f6fc?w=300&fit=crop',
    rating: 4.4,
    reviewCount: 57,
  ),

  // ── Grocery · Dairy & Eggs ──
  ProductItem(
    name: 'Toned Milk 1L',
    category: 'Grocery · Dairy & Eggs',
    price: '₹58',
    originalPrice: '₹64',
    image: 'https://images.unsplash.com/photo-1550583724-b2692b85b150?w=300&fit=crop',
    rating: 4.7,
    reviewCount: 300,
  ),
  ProductItem(
    name: 'Farm Fresh Eggs (12 pcs)',
    category: 'Grocery · Dairy & Eggs',
    price: '₹84',
    originalPrice: '₹96',
    image: 'https://images.unsplash.com/photo-1518569656558-1f25e69d93d7?w=300&fit=crop',
    rating: 4.6,
    reviewCount: 145,
  ),
  ProductItem(
    name: 'Paneer 200g',
    category: 'Grocery · Dairy & Eggs',
    price: '₹90',
    originalPrice: '₹110',
    image: 'https://images.unsplash.com/photo-1631452180519-c014fe946bc7?w=300&fit=crop',
    rating: 4.5,
    reviewCount: 92,
  ),
  ProductItem(
    name: 'Fresh Curd 400g',
    category: 'Grocery · Dairy & Eggs',
    price: '₹45',
    originalPrice: '₹55',
    image: 'https://images.unsplash.com/photo-1571212515416-fca988083b28?w=300&fit=crop',
    rating: 4.4,
    reviewCount: 60,
  ),

  // ── Grocery · Staples & Grains ──
  ProductItem(
    name: 'Gold Winner Sunflower Refined Oil',
    category: 'Grocery · Staples & Grains',
    price: '₹89',
    originalPrice: '₹111',
    image: 'https://images.unsplash.com/photo-1474979266404-7eaacbcd87c5?w=300&fit=crop',
    rating: 4.2,
    reviewCount: 95,
  ),
  ProductItem(
    name: 'Basmati Rice 1kg',
    category: 'Grocery · Staples & Grains',
    price: '₹120',
    originalPrice: '₹150',
    image: 'https://images.unsplash.com/photo-1586201375761-83865001e31c?w=300&fit=crop',
    rating: 4.5,
    reviewCount: 110,
  ),
  ProductItem(
    name: 'Whole Wheat Atta 5kg',
    category: 'Grocery · Staples & Grains',
    price: '₹249',
    originalPrice: '₹289',
    image: 'https://images.unsplash.com/photo-1509440159596-0249088772ff?w=300&fit=crop',
    rating: 4.6,
    reviewCount: 132,
  ),

  // ── Grocery · Snacks & Beverages ──
  ProductItem(
    name: 'Kurkure Namkeen Masala Munch',
    category: 'Grocery · Snacks & Beverages',
    price: '₹54',
    originalPrice: '₹60',
    image: 'https://images.unsplash.com/photo-1600952841320-db92ec4047ca?w=300&fit=crop',
    rating: 4.3,
    reviewCount: 210,
  ),
  ProductItem(
    name: 'Cola 750ml',
    category: 'Grocery · Snacks & Beverages',
    price: '₹40',
    originalPrice: '₹45',
    image: 'https://images.unsplash.com/photo-1554866585-cd94860890b7?w=300&fit=crop',
    rating: 4.1,
    reviewCount: 88,
  ),
  ProductItem(
    name: 'Classic Potato Chips',
    category: 'Grocery · Snacks & Beverages',
    price: '₹20',
    originalPrice: '₹25',
    image: 'https://images.unsplash.com/photo-1566478989037-eec170784d0b?w=300&fit=crop',
    rating: 4.2,
    reviewCount: 76,
  ),

  // ── Wellness ──
  ProductItem(
    name: 'Multivitamin Tablets',
    category: 'Wellness · HealthKart',
    price: '₹399',
    originalPrice: '₹549',
    image: 'https://images.unsplash.com/photo-1584017911766-d451b3d0e843?w=300&fit=crop',
    rating: 4.6,
    reviewCount: 88,
  ),
  ProductItem(
    name: 'Yoga Mat Premium',
    category: 'Wellness · FitZone',
    price: '₹699',
    originalPrice: '₹999',
    image: 'https://images.unsplash.com/photo-1601925260368-ae2f83cf8b7f?w=300&fit=crop',
    rating: 4.5,
    reviewCount: 54,
  ),
  ProductItem(
    name: 'Full Body Checkup',
    category: 'Wellness · MediCare',
    price: '₹1499',
    originalPrice: '₹1999',
    image: 'https://images.unsplash.com/photo-1576091160399-112ba8d25d1d?w=300&fit=crop',
    rating: 4.7,
    reviewCount: 210,
  ),

  // ── Electronics ──
  ProductItem(
    name: 'Wireless Earbuds',
    category: 'Electronics · SoundWave',
    price: '₹1299',
    originalPrice: '₹1999',
    image: 'https://images.unsplash.com/photo-1590658268037-6bf12165a8df?w=300&fit=crop',
    rating: 4.5,
    reviewCount: 340,
  ),
  ProductItem(
    name: 'Smart Watch',
    category: 'Electronics · TimeTech',
    price: '₹2199',
    originalPrice: '₹2999',
    image: 'https://images.unsplash.com/photo-1523275335684-37898b6baf30?w=300&fit=crop',
    rating: 4.6,
    reviewCount: 198,
  ),
  ProductItem(
    name: 'Bluetooth Speaker',
    category: 'Electronics · SoundWave',
    price: '₹999',
    originalPrice: '₹1499',
    image: 'https://images.unsplash.com/photo-1608043152269-423dbba4e7e1?w=300&fit=crop',
    rating: 4.4,
    reviewCount: 150,
  ),

  // ── Offers ──
  ProductItem(
    name: 'Combo Pack Snacks',
    category: 'Offers · Deal Zone',
    price: '₹199',
    originalPrice: '₹349',
    image: 'https://images.unsplash.com/photo-1621939514649-280e2ee25f60?w=300&fit=crop',
    rating: 4.2,
    reviewCount: 60,
  ),
  ProductItem(
    name: 'Buy 1 Get 1 Sunflower Oil',
    category: 'Offers · Grocery Deals',
    price: '₹99',
    originalPrice: '₹198',
    image: 'https://images.unsplash.com/photo-1474979266404-7eaacbcd87c5?w=300&fit=crop',
    rating: 4.3,
    reviewCount: 75,
  ),
  ProductItem(
    name: 'Flat 40% Off Earbuds',
    category: 'Offers · Electronics Deals',
    price: '₹799',
    originalPrice: '₹1299',
    image: 'https://images.unsplash.com/photo-1590658268037-6bf12165a8df?w=300&fit=crop',
    rating: 4.4,
    reviewCount: 220,
  ),
];

class _HomeScreenState extends State<HomeScreen>
    with SingleTickerProviderStateMixin {
  final DashboardController controller = Get.put(DashboardController());

  // ─── CART ────────────────────────────────────────────────────────────────
  final CartController cartController = Get.put(CartController());
  // Set this to true (e.g. from a scroll listener) to slide the cart bar
  // down and fade it out. Left false = always visible while cart has items.
  bool _hideCartBar = false;

  // ─── GROCERY (fetched live) ─────────────────────────────────────────────
  final GroceryRepository _groceryRepository = GroceryRepository();
  List<GrocerySubcategorySection> _grocerySections = [];
  bool _isLoadingGrocery = false;
  String? _groceryError;

  // TODO: source these from wherever the app tracks the selected
  // store/tenant and delivery location instead of hardcoding them.
  static const int _groceryCategoryId = 2;
  static const int _tenantId = 1087;
  static const int _locationId = 1135;


  Future<void> _fetchGroceryProducts() async {
    setState(() {
      _isLoadingGrocery = true;
      _groceryError = null;
    });
    try {
      final sections = await _groceryRepository.fetchGroceryProducts(
        categoryId: _groceryCategoryId,
        tenantId: _tenantId,
        locationId: _locationId,
      );
      if (!mounted) return;
      setState(() {
        _grocerySections = sections;
        _isLoadingGrocery = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _groceryError = e.toString().replaceFirst('Exception: ', '');
        _isLoadingGrocery = false;
      });
    }
  }

  String Name = '';
  String Adress = '';
  String Profile = '';

  // Currently active top-bar tab. Defaults to the first tab.
  String _selectedCategory = 'Grocery';

  // ─── SHIMMER-ON-TAB-SWITCH STATE ───────────────────────────────────────
  bool _isTabSwitching = false;
  Timer? _shimmerTimer;
  late final AnimationController _shimmerController = AnimationController(
    vsync: this,
    duration: const Duration(milliseconds: 1200),
  )..repeat();

  static const _kName    = 'cached_name';
  static const _kAddress = 'cached_address';
  static const _kProfile = 'cached_profile';

  Future<void> _loadProfile() async {
    final prefs = await SharedPreferences.getInstance();
    final int? id = prefs.getInt('customerId');

    if (id == null) {
      Get.snackbar("Error", "Customer ID not found");
      return;
    }

    final cachedName    = prefs.getString(_kName)    ?? '';
    final cachedAddress = prefs.getString(_kAddress) ?? '';
    final cachedProfile = prefs.getString(_kProfile) ?? '';

    if (cachedName.isNotEmpty || cachedAddress.isNotEmpty) {
      setState(() {
        Name    = cachedName;
        Adress  = cachedAddress;
        Profile = cachedProfile;
      });
    }

    final repo = LoginRepository();
    final fetchedProfile = await repo.fetchProfile(id.toString());

    if (fetchedProfile != null) {
      final newName    = fetchedProfile.firstname    ?? '';
      final newProfile = fetchedProfile.profileimage ?? '';
      final newAddress = fetchedProfile.address      ?? '';

      if (Name != newName || Profile != newProfile || Adress != newAddress) {
        setState(() {
          Name    = newName;
          Profile = newProfile;
          Adress  = newAddress;
        });

        await prefs.setString(_kName,    newName);
        await prefs.setString(_kAddress, newAddress);
        await prefs.setString(_kProfile, newProfile);
      } else {
        print("Profile unchanged, no UI update");
      }
    }
  }

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

    _loadProfile();
    _fetchGroceryProducts();
  }

  @override
  void dispose() {
    _shimmerTimer?.cancel();
    _shimmerController.dispose();
    super.dispose();
  }

  String getGreeting() {
    final hour = DateTime.now().hour;
    if (hour < 12) return "Good Morning";
    else if (hour < 17) return "Good Afternoon";
    else return "Good Evening";
  }

  // ─── TAB SWITCH → TRIGGER 2s FULL-BODY SHIMMER ─────────────────────────
  void _onTopTabSelected(String title) {
    if (title == _selectedCategory) return;
    setState(() {
      _selectedCategory = title;
      _isTabSwitching = true;
    });
    _shimmerTimer?.cancel();
    _shimmerTimer = Timer(const Duration(seconds: 2), () {
      if (mounted) setState(() => _isTabSwitching = false);
    });
  }

  // ─── FILTERING LOGIC (non-Grocery tabs) ────────────────────────────────
  // Filters `products` whose `category` field contains the selected tab's
  // name (case-insensitive), e.g. "Wellness" matches "Wellness · HealthKart".
  List<ProductItem> get _filteredProducts {
    final keyword = _selectedCategory.toLowerCase();
    return products
        .where((p) => p.category.toLowerCase().contains(keyword))
        .toList();
  }

  // ─── GROCERY SECTIONS (fetched live), REORDERED SO THE TAPPED ──────────
  // quick-category is first — e.g. tapping "Vegetables & Fruits" in Shop-by-
  // Category moves that row to the top; everything else keeps its order.
  List<GrocerySubcategorySection> get _orderedGrocerySections {
    final sections =
    _grocerySections.where((s) => s.products.isNotEmpty).toList();

    final selected = _selectedGrocerySubcategory;
    if (selected != null) {
      sections.sort((a, b) {
        final aMatch = a.subcategoryName == selected;
        final bMatch = b.subcategoryName == selected;
        if (aMatch == bMatch) return 0;
        return aMatch ? -1 : 1;
      });
    }
    return sections;
  }

  @override
  Widget build(BuildContext context) {
    final isGrocery = _selectedCategory == 'Grocery';
    final filtered = _filteredProducts;

    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: Stack(
          children: [
            Column(
              children: [
                // ── Top bar + search bar are ALWAYS real, never shimmered ──
                _buildTopBar(),
                _buildSearchBar(),
                _buildExploreMore(),
                Expanded(
                  child: SingleChildScrollView(
                    child: _isTabSwitching
                        ? _buildShimmerSkeleton()
                        : Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [


                        // ── Banner + quick category strip: Grocery tab only ──
                        if (isGrocery) ...[
                          if (_orderedGrocerySections.isNotEmpty) ...[
                            _banner(),
                            const SizedBox(height: 10),
                          ],

                          _buildShopByCategory(),
                        ],

                        if (isGrocery) ...[
                          // ── Grocery: loading / error / data states ──
                          if (_isLoadingGrocery)
                            const Padding(
                              padding: EdgeInsets.symmetric(vertical: 60),
                              child: Center(child: CircularProgressIndicator()),
                            )
                          else if (_groceryError != null)
                            Padding(
                              padding: const EdgeInsets.symmetric(
                                  horizontal: 16, vertical: 40),
                              child: Center(
                                child: Column(
                                  children: [
                                    Icon(Icons.wifi_off_rounded,
                                        size: 36, color: Colors.grey.shade400),
                                    const SizedBox(height: 8),
                                    Text(
                                      _groceryError!,
                                      textAlign: TextAlign.center,
                                      style: TextStyle(
                                          color: Colors.grey.shade600,
                                          fontSize: 13),
                                    ),
                                    const SizedBox(height: 12),
                                    OutlinedButton(
                                      onPressed: _fetchGroceryProducts,
                                      child: const Text('Retry'),
                                    ),
                                  ],
                                ),
                              ),
                            )
                          else if (_orderedGrocerySections.isEmpty)
                              Padding(
                                padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 40),
                                child: Center(
                                  child: Column(
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      Image.network(
                                        'https://cdn-icons-png.flaticon.com/512/6134/6134065.png',
                                        height: 140,
                                        errorBuilder: (context, error, stackTrace) {
                                          return const Icon(
                                            Icons.location_off_rounded,
                                            size: 90,
                                            color: Colors.grey,
                                          );
                                        },
                                      ),
                                      const SizedBox(height: 20),
                                      const Text(
                                        "We're not delivering here yet",
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                          fontSize: 18,
                                          fontWeight: FontWeight.w600,
                                        ),
                                      ),
                                      const SizedBox(height: 8),
                                      Text(
                                        "We're expanding to new locations. Stay tuned—we'll be serving your area soon!",
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                          color: Colors.grey.shade600,
                                          fontSize: 14,
                                          height: 1.5,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              )
                            else
                              ..._orderedGrocerySections.map((s) =>
                                  _buildGrocerySection(
                                      s.subcategoryName, s.products)),
                        ] else ...[
                          // ── Other tabs: single header + grid ──
                          Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 16,vertical: 12),
                            child: Text(
                              _selectedCategory,
                              style: const TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: 16,
                              ),
                            ),
                          ),
                          const SizedBox(height: 8),
                          if (filtered.isEmpty)
                            Padding(
                              padding: const EdgeInsets.symmetric(
                                  horizontal: 16, vertical: 40),
                              child: Center(
                                child: Column(
                                  children: [
                                    Icon(Icons.inventory_2_outlined,
                                        size: 40, color: Colors.grey.shade400),
                                    const SizedBox(height: 8),
                                    Text(
                                      'No items in this category yet',
                                      style: TextStyle(
                                          color: Colors.grey.shade600,
                                          fontSize: 13),
                                    ),
                                  ],
                                ),
                              ),
                            )
                          else
                            Padding(
                              padding: const EdgeInsets.fromLTRB(16, 14, 16, 24),
                              child: GridView.builder(
                                shrinkWrap: true,
                                physics: const NeverScrollableScrollPhysics(),
                                gridDelegate:
                                const SliverGridDelegateWithFixedCrossAxisCount(
                                  crossAxisCount: 3,
                                  crossAxisSpacing: 10,
                                  mainAxisSpacing: 10,
                                  mainAxisExtent: 270,
                                ),
                                itemCount: filtered.length,
                                itemBuilder: (context, index) {
                                  final item = filtered[index];
                                  return GestureDetector(
                                    onTap: () => _openProduct(context, item),
                                    child: ProductCard(item: item),
                                  );
                                },
                              ),
                            ),
                        ],

                        // const SizedBox(height: 16),
                        // _buildCreatedDailyPlans(),
                        const SizedBox(height: 16),
                        // Extra bottom padding so content doesn't sit behind
                        // the floating cart bar.
                        const SizedBox(height: 90),
                        Image.asset(
                            'assets/images/nearle_copyrights.png'),
                      ],
                    ),
                  ),
                ),
              ],
            ),

            // ── Floating "view cart" bar, overlaid above everything ──
            _buildFloatingCartBar(),
          ],
        ),
      ),
    );
  }

  // ─── SHARED: open product sheet ─────────────────────────────────────────
  void _openProduct(BuildContext context, ProductItem item) {
    showProductSheet(
      context,
      pl.ProductItem(

        name: item.name,
        category: item.category,
        price: item.price,
        originalPrice: item.originalPrice,
        imageUrl: item.image,
        bgColor: const Color(0xFFFCE4EC),
        rating: item.rating,
        reviewCount: item.reviewCount,
        tag: item.category.split('·').first.trim(),

      ),
    );
  }

  // ─── GROCERY SUBCATEGORY SECTION (Vegetables / Fruits / Dairy & Eggs…) ──
  Widget _buildGrocerySection(String title, List<Product> items) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _sectionHeader(title),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16),
          child: GridView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 4,
              crossAxisSpacing: 10,
              mainAxisSpacing: 10,
              mainAxisExtent: 230,
            ),
            itemCount: items.length,
            itemBuilder: (context, index) {
              final product = items[index];
              return Obx(() {
                final cartItem = _findCartItem(product);
                final qty = cartItem?.quantity ?? 0;

                return GestureDetector(
                  onTap: () => _openGroceryProduct(context, product),
                  child: ProductCard(
                    item: _groceryDisplayItem(product),
                    quantity: qty,
                    onAddTap: () => _addGroceryToCart(product),
                    onIncrementTap: () {
                      if (cartItem != null) cartController.increaseQty(cartItem);
                    },
                    onDecrementTap: () {
                      if (cartItem != null) cartController.decreaseQty(cartItem);
                    },
                  ),
                );
              });
            },
          ),
        ),
        const SizedBox(height: 16),
      ],
    );
  }


  ProductItem _groceryDisplayItem(Product p) {
    final num cost = p.productcost ?? 0;
    final num discount = p.discount ?? 0;
    final num original = discount > 0 ? cost + discount : cost;

    return ProductItem(
      name: p.productname ?? 'Product',
      category: 'Grocery · ${p.subcategoryname ?? ''}',
      price: _formatRupees(cost),
      originalPrice: _formatRupees(original),
      image: (p.productimage != null && p.productimage!.isNotEmpty)
          ? p.productimage!
          : 'https://via.placeholder.com/300?text=No+Image',
      rating: 4.0,
      reviewCount: 0,
    );
  }

  String _formatRupees(num value) {
    final isWhole = value == value.roundToDouble();
    return '₹${isWhole ? value.toStringAsFixed(0) : value.toStringAsFixed(2)}';
  }

  // ─── GROCERY: ADD TO CART ────────────────────────────────────────────────
  void _addGroceryToCart(Product product) {
    cartController.addToCart(
      product,
      qty: 1,
      locationId: _locationId.toString(),
    );
  }

  void _openGroceryProduct(BuildContext context, Product product) {
    final display = _groceryDisplayItem(product);
    showProductSheet(
      context,
      pl.ProductItem(
        name: display.name,
        category: display.category,
        price: display.price,
        originalPrice: display.originalPrice,
        imageUrl: display.image,
        bgColor: const Color(0xFFFCE4EC),
        rating: display.rating,
        reviewCount: display.reviewCount,
        tag: display.category.split('·').first.trim(),
      ),
    );
  }

  // ─── TOP BAR ───────────────────────────────────────────────────────────────
  Widget _buildTopBar() {
    return Container(
      color: const Color(0xFFDCE3F7),
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
      child: Row(
        children: [
          const SizedBox(width: 4),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ReusableTextWidget(
                text: "${getGreeting()}, ${Name.isNotEmpty ? Name : 'User'}",
                color: Colors.black87,
                fontFamily: FontConstants.fontFamily,
                fontSize: 15,
                fontWeight: FontWeight.w600,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
              GestureDetector(
                onTap: () {
                  controller.location();
                },
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Flexible(
                      child: ReusableTextWidget(
                        text: (Adress != null && Adress.trim().isNotEmpty)
                            ? (Adress.length > 25
                            ? "${Adress.substring(0, 25)}..."
                            : Adress)
                            : "No Address",
                        color: Colors.grey[700]!,
                        fontFamily: FontConstants.fontFamily,
                        fontSize: 13,
                        fontWeight: FontWeight.w500,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    const SizedBox(width: 2),
                    const Icon(
                      Icons.keyboard_arrow_down,
                      size: 18,
                      color: Colors.grey,
                    ),
                  ],
                ),
              ),
            ],
          ),
          const Spacer(),
          const SizedBox(width: 12),
          GestureDetector(

            onTap: () {
              final navController = Get.find<BottomNavController>();
              navController.currentIndex.value = 4;
            },
            child: Container(
              height: 42,
              width: 42,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.10),
                    blurRadius: 4,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: CircleAvatar(
                backgroundColor: Colors.white,
                backgroundImage: Profile.isNotEmpty
                    ? NetworkImage(Profile)
                    : null,
                child: Profile.isEmpty
                    ? const Icon(
                  Icons.person,
                  color: Colors.black54,
                  size: 22,
                )
                    : null,
              ),
            ),
          ),

          const SizedBox(width: 8),
        ],
      ),
    );
  }

  // ─── SEARCH BAR ────────────────────────────────────────────────────────────
  Widget _buildSearchBar() {
    return Container(
      color: const Color(0xFFDCE3F7),
      padding: const EdgeInsets.fromLTRB(16, 4, 16, 12),
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
        ),
        child: Row(
          children: [
            const SizedBox(width: 12),
            const Icon(Icons.search, color: Colors.grey),
            const SizedBox(width: 8),
            Expanded(
              child: GestureDetector(
                onTap: () {
                  Get.to(() => const SearchScreen());
                },
                child: AbsorbPointer(
                  absorbing: true,
                  child: TextField(
                    decoration: const InputDecoration(
                      hintText: 'Search "milk", "eggs", "dosa", "plumber"...',
                      hintStyle: TextStyle(color: Colors.grey, fontSize: 13),
                      border: InputBorder.none,
                      isDense: true,
                      contentPadding: EdgeInsets.symmetric(vertical: 12),
                    ),
                  ),
                ),
              ),
            ),
            IconButton(onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (_) => const VoiceAssistantScreen()),
              );
            }, icon: const Icon(Icons.mic_none, color: Colors.grey)),
            const SizedBox(width: 12),
            GestureDetector(
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (_) => const LensSearchScreen()),
                );
              },
              child: const Icon(Icons.camera_alt_outlined, color: Colors.grey),
            ),
            const SizedBox(width: 12),
          ],
        ),
      ),
    );
  }

  // ─── EXPLORE MORE / TOP CATEGORY TABS (Blinkit-style) ──────────────────────
  Widget _buildExploreMore() {
    final items = [
      {'title': 'Grocery', 'icon': Icons.shopping_basket_outlined},
      {'title': 'Food Delivery', 'icon': Icons.delivery_dining},
      {'title': 'Wellness', 'icon': Icons.favorite_border},
      {'title': 'Electronics', 'icon': Icons.headphones},
      {'title': 'Offers', 'icon': Icons.local_offer_outlined},
    ];

    return LayoutBuilder(
      builder: (context, constraints) {
        final screenWidth = MediaQuery.of(context).size.width;

        final scale = (screenWidth / 375).clamp(0.8, 1.15);

        final iconSize = 22.0 * scale;       // was 26
        final fontSize = 10.5 * scale;       // was 12
        final horizontalPadding = 14.0 * scale;  // was 16
        final itemSpacing = 18.0 * scale;    // was 22
        final containerHeight = 62.0 * scale; // was 72
        final underlineWidth = 22.0 * scale; // was 28

        return Container(
          color: const Color(0xFFDCE3F7),
          padding: const EdgeInsets.only(top: 4),
          child: SizedBox(
            height: containerHeight,
            child: ListView.separated(
              scrollDirection: Axis.horizontal,
              padding: EdgeInsets.symmetric(horizontal: horizontalPadding),
              itemCount: items.length,
              separatorBuilder: (_, __) => SizedBox(width: itemSpacing),
              itemBuilder: (_, i) {
                final item = items[i];
                final title = item['title'] as String;
                final isSelected = _selectedCategory == title;
                final color = isSelected
                    ? const Color(0xFF1A2B6D)
                    : const Color(0xFF5B6BAE);

                return GestureDetector(
                  onTap: () => _onTopTabSelected(title),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(item['icon'] as IconData, size: iconSize, color: color),
                      SizedBox(height: 4 * scale),
                      Text(
                        title,
                        style: TextStyle(
                          fontSize: fontSize,
                          fontWeight: isSelected ? FontWeight.w700 : FontWeight.w500,
                          color: color,
                        ),
                      ),
                      SizedBox(height: 4 * scale),
                      Container(
                        height: 2 * scale,
                        width: underlineWidth,
                        decoration: BoxDecoration(
                          color: isSelected ? const Color(0xFF1A2B6D) : Colors.transparent,
                          borderRadius: BorderRadius.circular(4),
                        ),
                      ),
                    ],
                  ),
                );
              },
            ),
          ),
        );
      },
    );
  }
  // ─── SHOP BY CATEGORY (quick jump icons — Grocery tab only) ────────────────
  // Built from the live subcategories returned by the API (uses each
  // section's own `image`), rather than a hardcoded icon set.
  Widget _buildShopByCategory() {
    final sections =
    _grocerySections.where((s) => s.products.isNotEmpty).toList();

    if (sections.isEmpty) return const SizedBox();

    return Container(
      decoration: BoxDecoration(

        border: Border(
          top: BorderSide(color: Colors.grey.shade300, width: 0.5),
          bottom: BorderSide(color: Colors.grey.shade300, width: 0.5),
        ),
      ),
      child: Column(
        children: [
          _sectionHeader('Category'),
          const SizedBox(height: 8),
          SizedBox(
            height: 90,
            child: ListView.separated(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              scrollDirection: Axis.horizontal,
              itemCount: sections.length,
              separatorBuilder: (_, __) => const SizedBox(width: 12),
              itemBuilder: (_, index) {
                final section = sections[index];
                final label = section.subcategoryName;
                final isSelected = label == _selectedGrocerySubcategory;

                return GestureDetector(
                  onTap: () => _scrollToGrocerySubcategory(label),
                  child: SizedBox(
                    width: 66,
                    child: Column(
                      children: [
                        Container(
                          width: 46,
                          height: 46,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            color: isSelected
                                ? const Color(0xFFEAF8EC)
                                : const Color(0xFFF5F5F5),
                          ),
                          child: ClipOval(
                            child: section.image.isNotEmpty
                                ? Image.network(
                              section.image,
                              fit: BoxFit.cover,
                              errorBuilder: (_, __, ___) => const Icon(
                                  Icons.shopping_basket_outlined,
                                  size: 20),
                            )
                                : const Icon(Icons.shopping_basket_outlined,
                                size: 20),
                          ),
                        ),
                        const SizedBox(height: 4),
                        Text(
                          label,
                          textAlign: TextAlign.center,
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            fontSize: 9,
                            height: 1.15,
                            fontWeight:
                            isSelected ? FontWeight.w600 : FontWeight.w500,
                            color: isSelected
                                ? ColorConstants.ratingColor
                                : Colors.black87,
                          ),
                        ),
                        const Spacer(),
                        if (isSelected)
                          Container(
                            width: 22,
                            height: 2,
                            decoration: BoxDecoration(
                              color: ColorConstants.ratingColor,
                              borderRadius: BorderRadius.circular(10),
                            ),
                          ),
                      ],
                    ),
                  ),
                );
              },
            ),
          )
        ],
      ),
    );
  }

  // Highlight state for the quick-jump icon row above. Selecting a
  // subcategory here also reorders `_orderedGrocerySections` so that
  // section's row renders first.
  String? _selectedGrocerySubcategory;

  void _scrollToGrocerySubcategory(String label) {
    setState(() {
      // Toggle off if tapping the same one again, restoring default order.
      _selectedGrocerySubcategory =
      _selectedGrocerySubcategory == label ? null : label;
    });
  }

  Widget _banner() {
    final List<String> bannerImages = [
      'https://img.magnific.com/free-vector/gradient-shopping-discount-horizontal-sale-banner_23-2150321996.jpg?semt=ais_hybrid&w=740&q=80',
    ];

    return Column(
      children: [
        CarouselSlider(
          options: CarouselOptions(
            height: 180,
            autoPlay: true,
            enlargeCenterPage: false,
            viewportFraction: 1.0,
          ),
          items: bannerImages.map((url) {
            return GestureDetector(
              onTap: () {
                // Navigator.push(
                //   context,
                //   MaterialPageRoute(builder: (_) => const AIAssistantScreen()),
                // );
              },
              child: ClipRRect(
                child: Image.network(
                  url,
                  height: 180,
                  width: double.infinity,
                  fit: BoxFit.cover,

                  loadingBuilder: (context, child, loadingProgress) {
                    if (loadingProgress == null) return child;
                    return const SizedBox.shrink();
                  },
                  errorBuilder: (context, error, stackTrace) => Container(
                    height: 180,
                    decoration: BoxDecoration(
                      color: Colors.grey.shade200,
                    ),
                    child: const Center(child: Icon(Icons.broken_image, size: 40)),
                  ),
                ),
              ),
            );
          }).toList(),
        ),
      ],
    );
  }

  // ─── CREATED DAILY PLANS ───────────────────────────────────────────────────
  Widget _buildCreatedDailyPlans() {
    final plans = [
      {'title': 'Breakfast Essentials', 'items': '14 items', 'next': 'Next delivery: Tomorrow', 'color': const Color(0xFFE8F5E9)},
      {'title': 'Home Essentials', 'items': '12 items', 'next': 'Next delivery: 25 May', 'color': const Color(0xFFE3F2FD)},
      {'title': 'Monthly Staples', 'items': '28 items', 'next': 'Next delivery: 1 Jun', 'color': const Color(0xFFFFF8E1)},
    ];

    return Column(
      children: [
        _sectionHeader('Created Daily Plans'),
        SizedBox(
          height: 100,
          child: ListView(
            scrollDirection: Axis.horizontal,
            padding: const EdgeInsets.symmetric(horizontal: 16),
            children: [
              ...plans.map((p) => Container(
                width: 150,
                margin: const EdgeInsets.only(right: 10),
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: p['color'] as Color,
                  borderRadius: BorderRadius.circular(14),
                  border: Border.all(color: Colors.grey.shade200),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        const Icon(Icons.calendar_month,
                            size: 16, color: Color(0xFF1DB954)),
                        const SizedBox(width: 4),
                        Expanded(
                          child: Text(p['title'] as String,
                              style: const TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 11)),
                        )
                      ],
                    ),
                    const SizedBox(height: 4),
                    Text(p['items'] as String,
                        style: const TextStyle(
                            color: Colors.black54, fontSize: 10)),
                    const Spacer(),
                    Text(p['next'] as String,
                        style: const TextStyle(
                            color: Colors.black54, fontSize: 9)),
                  ],
                ),
              )),
              GestureDetector(
                onTap: () {
                  Get.to(() => const CreateDailyPlanScreen());
                },
                child: Container(
                  width: 130,
                  margin: const EdgeInsets.only(right: 10),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(14),
                    border:
                    Border.all(color: Colors.grey.shade300, style: BorderStyle.solid),
                  ),
                  child: const Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.add, size: 28, color: Color(0xFF1DB954)),
                      SizedBox(height: 4),
                      Text('Create New Plan',
                          style: TextStyle(
                              color: Color(0xFF1DB954),
                              fontWeight: FontWeight.bold,
                              fontSize: 12)),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  // ─── FLOATING CART BAR ──────────────────────────────────────────────────
  Widget _buildFloatingCartBar() {
    return Obx(() {
      if (cartController.cartItems.isEmpty) return const SizedBox();
      final tenant = cartController.currentTenant.value;
      final tenantImage1 = tenant?.tenantimage ?? '';
      final tenantName1 = tenant?.tenantname ?? 'Unknown Store';

      return AnimatedPositioned(
        duration: const Duration(milliseconds: 480),
        curve: Curves.easeInOut,
        left: 0,
        right: 0,
        bottom: _hideCartBar ? -90 : 16,
        child: IgnorePointer(
          ignoring: _hideCartBar,
          child: AnimatedOpacity(
            duration: const Duration(milliseconds: 380),
            opacity: _hideCartBar ? 0 : 1,
            child: Center(
              child: Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: const Color(0xFF662582),
                  borderRadius: BorderRadius.circular(50),
                  boxShadow: [
                    BoxShadow(
                      color: const Color(0xFF662582).withOpacity(0.4),
                      blurRadius: 20,
                      offset: const Offset(0, 8),
                    ),
                  ],
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    // Store avatar
                    Container(
                      width: 42,
                      height: 42,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: Colors.white.withOpacity(0.2),
                      ),
                      child: ClipOval(
                        child: tenantImage1.isNotEmpty
                            ? Image.network(tenantImage1, fit: BoxFit.cover)
                            : const Icon(Icons.store_rounded, size: 20, color: Colors.white),
                      ),
                    ),

                    const SizedBox(width: 10),

                    // Store name + item count
                    ConstrainedBox(
                      constraints: const BoxConstraints(maxWidth: 160),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text(
                            tenantName1,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: const TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w600,
                              color: Colors.white,
                              letterSpacing: 0.1,
                            ),
                          ),
                          const SizedBox(height: 1),
                          Text(
                            "${cartController.totalItems} item${cartController.totalItems > 1 ? 's' : ''}",
                            style: TextStyle(
                              fontSize: 11,
                              color: Colors.white.withOpacity(0.7),
                              fontWeight: FontWeight.w400,
                            ),
                          ),
                        ],
                      ),
                    ),

                    const SizedBox(width: 10),

                    // View button — white pill
                    GestureDetector(
                      onTap: () {
                        final navController = Get.find<BottomNavController>();
                        navController.currentIndex.value = 3;
                      },
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(40),
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: const [
                            Text(
                              "View",
                              style: TextStyle(
                                fontSize: 13,
                                fontWeight: FontWeight.w700,
                                color: Color(0xFF662582),
                                letterSpacing: 0.2,
                              ),
                            ),
                            SizedBox(width: 4),
                            Icon(Icons.arrow_forward_rounded, size: 14, color: Color(0xFF662582)),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      );
    });
  }

  // ─── HELPERS ───────────────────────────────────────────────────────────────
  Widget _sectionHeader(String title) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(title,
              style: const TextStyle(
                  fontWeight: FontWeight.bold, fontSize: 16)),

        ],
      ),
    );
  }

  // ─── SHIMMER SKELETON (shown for 2s whenever the top tab changes) ─────────
  Widget _shimmerBox({double? width, double? height, double radius = 8}) {
    return AnimatedBuilder(
      animation: _shimmerController,
      builder: (context, _) {
        final t = _shimmerController.value; // 0..1
        return Container(
          width: width,
          height: height,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(radius),
            gradient: LinearGradient(
              begin: Alignment(-1 + t * 3, 0),
              end: Alignment(0 + t * 3, 0),
              colors: [
                Colors.grey.shade300,
                Colors.grey.shade100,
                Colors.grey.shade300,
              ],
              stops: const [0.1, 0.5, 0.9],
            ),
          ),
        );
      },
    );
  }

  Widget _buildShimmerSkeleton() {
    // Note: top bar + search bar are rendered for real above this widget
    // (see build()); this skeleton only covers everything below them.
    return Padding(
      padding: const EdgeInsets.fromLTRB(16, 12, 16, 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // top tabs placeholder

          const SizedBox(height: 20),
          // banner placeholder
          _shimmerBox(height: 180, radius: 14, width: double.infinity),
          const SizedBox(height: 20),
          // category icons placeholder
          Row(
            children: List.generate(
              5,
                  (i) => Padding(
                padding: const EdgeInsets.only(right: 12),
                child: Column(
                  children: [
                    _shimmerBox(width: 46, height: 46, radius: 23),
                    const SizedBox(height: 6),
                    _shimmerBox(width: 40, height: 8),
                  ],
                ),
              ),
            ),
          ),
          const SizedBox(height: 20),
          // section header + product row placeholder
          _shimmerBox(width: 120, height: 16),
          const SizedBox(height: 12),
          SizedBox(
            height: 210,
            child: ListView.separated(
              scrollDirection: Axis.horizontal,
              physics: const NeverScrollableScrollPhysics(),
              itemCount: 4,
              separatorBuilder: (_, __) => const SizedBox(width: 10),
              itemBuilder: (_, __) => _shimmerBox(
                width: 120,
                height: 210,
                radius: 12,
              ),
            ),
          ),
          const SizedBox(height: 20),
          _shimmerBox(width: 120, height: 16),
          const SizedBox(height: 12),
          SizedBox(
            height: 210,
            child: ListView.separated(
              scrollDirection: Axis.horizontal,
              physics: const NeverScrollableScrollPhysics(),
              itemCount: 4,
              separatorBuilder: (_, __) => const SizedBox(width: 10),
              itemBuilder: (_, __) => _shimmerBox(
                width: 120,
                height: 210,
                radius: 12,
              ),
            ),
          ),
        ],
      ),
    );
  }

  CartItem? _findCartItem(Product product) {
    for (final c in cartController.cartItems) {
      if (c.product.productid == product.productid) return c;
    }
    return null;
  }
}