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


class AutoRefillDemo extends StatelessWidget {
  const AutoRefillDemo({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Auto Refill',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        fontFamily: 'SF Pro Display',
        scaffoldBackgroundColor: const Color(0xFFF5F5F7),
        colorScheme: ColorScheme.fromSeed(seedColor: primaryColor),
        useMaterial3: true,
      ),
      home: const RootNavigator(),
    );
  }
}

const Color primaryColor = Color(0xFF662582);

// ─── Data Models ───────────────────────────────────────────────

class Product {
  final int id;
  final String name;
  final String brand;
  final String days;
  final String nextLabel;
  final String nextDate;
  final String image;
  bool enabled;

  Product({
    required this.id,
    required this.name,
    required this.brand,
    required this.days,
    required this.nextLabel,
    required this.nextDate,
    required this.image,
    required this.enabled,
  });
}

class TopPick {
  final String name;
  final String qty;
  final String price;
  final String image;
  const TopPick({
    required this.name,
    required this.qty,
    required this.price,
    required this.image,
  });
}

final List<Product> sampleProducts = [
  Product(
    id: 1,
    name: 'Salt',
    brand: '1 Kg  •  Tata Salt',
    days: '2 days remaining',
    nextLabel: 'Next order:',
    nextDate: '15 Jul',
    image: 'https://images.unsplash.com/photo-1586201375761-83865001e31c?w=200',
    enabled: true,
  ),
  Product(
    id: 2,
    name: 'Milk',
    brand: '1 Litre  •  Amul',
    days: 'Tomorrow',
    nextLabel: 'Next delivery:',
    nextDate: 'Tomorrow, 7 AM',
    image: 'https://images.unsplash.com/photo-1550583724-b2692b85b150?w=200',
    enabled: true,
  ),
  Product(
    id: 3,
    name: 'Vitamin Tablets',
    brand: '60 Tablets  •  HealthVit',
    days: '5 days remaining',
    nextLabel: 'Next order:',
    nextDate: '18 Jul',
    image: 'https://images.unsplash.com/photo-1584308666744-24d5c474f2ae?w=200',
    enabled: true,
  ),
  Product(
    id: 4,
    name: 'Dog Food',
    brand: '3 Kg  •  Pedigree',
    days: '1 week remaining',
    nextLabel: 'Next order:',
    nextDate: '22 Jul',
    image: 'https://images.unsplash.com/photo-1589924691995-400dc9a36ab6?w=200',
    enabled: true,
  ),
];

const List<TopPick> topPicks = [
  TopPick(
    name: 'Sunflower Oil',
    qty: '1 Litre',
    price: '₹135',
    image: 'https://images.unsplash.com/photo-1474979266404-7eaacbcd87c5?w=200',
  ),
  TopPick(
    name: 'Toor Dal',
    qty: '1 Kg',
    price: '₹110',
    image: 'https://images.unsplash.com/photo-1585996989620-6d8e5e03a3b1?w=200',
  ),
  TopPick(
    name: 'India Gate Basmati Rice',
    qty: '5 Kg',
    price: '₹399',
    image: 'https://images.unsplash.com/photo-1536304993881-ff6e9eefa2a6?w=200',
  ),
  TopPick(
    name: 'Aashirvaad Atta',
    qty: '5 Kg',
    price: '₹249',
    image: 'https://images.unsplash.com/photo-1574323347407-f5e1ad6d020b?w=200',
  ),
];

// ─── Root Navigator ─────────────────────────────────────────────

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

  @override
  State<RootNavigator> createState() => _RootNavigatorState();
}

class _RootNavigatorState extends State<RootNavigator> {
  bool _showSetup = false;

  @override
  Widget build(BuildContext context) {
    return AnimatedSwitcher(
      duration: const Duration(milliseconds: 300),
      transitionBuilder: (child, anim) => SlideTransition(
        position: Tween<Offset>(
          begin: _showSetup ? const Offset(1, 0) : const Offset(-1, 0),
          end: Offset.zero,
        ).animate(CurvedAnimation(parent: anim, curve: Curves.easeOutCubic)),
        child: child,
      ),
      child: _showSetup
          ? AutoRefillSetupPage(
        key: const ValueKey('setup'),
        onBack: () => setState(() => _showSetup = false),
      )
          : ForYouPage(
        key: const ValueKey('home'),
        onSetupTap: () => setState(() => _showSetup = true),
      ),
    );
  }
}

// ─── For You Page ───────────────────────────────────────────────

class ForYouPage extends StatefulWidget {
  final VoidCallback onSetupTap;
  const ForYouPage({super.key, required this.onSetupTap});

  @override
  State<ForYouPage> createState() => _ForYouPageState();
}

class _ForYouPageState extends State<ForYouPage> {
  late List<Product> _products;

  @override
  void initState() {
    super.initState();
    _products = List.from(sampleProducts);
  }

  void _toggle(int id) {
    setState(() {
      final p = _products.firstWhere((e) => e.id == id);
      p.enabled = !p.enabled;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F7),
      appBar: AppBar(
        backgroundColor: const Color(0xFFF5F5F7),
        elevation: 0,
        surfaceTintColor: Colors.transparent,
        title: const Text(
          'For You',
          style: TextStyle(fontWeight: FontWeight.w800, fontSize: 20, color: Color(0xFF111111)),
        ),

      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.fromLTRB(16, 4, 16, 32),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _HeroCard(),
            const SizedBox(height: 24),
            _SectionHeader(title: 'You may need soon', onViewAll: () {}),
            const SizedBox(height: 14),
            ..._products.map(
                  (p) => Padding(
                padding: const EdgeInsets.only(bottom: 12),
                child: _ProductCard(product: p, onToggle: () => _toggle(p.id)),
              ),
            ),
            const SizedBox(height: 10),
            _SectionHeader(title: 'Top picks for you', onViewAll: () {}),
            const SizedBox(height: 14),
            SizedBox(
              height: 210,
              child: ListView.separated(
                scrollDirection: Axis.horizontal,
                itemCount: topPicks.length,
                separatorBuilder: (_, __) => const SizedBox(width: 10),
                itemBuilder: (_, i) => _TopPickCard(pick: topPicks[i]),
              ),
            ),
            const SizedBox(height: 18),
            _NeverRunOutBanner(onSetupTap: widget.onSetupTap),
          ],
        ),
      ),
    );
  }
}

// ─── Hero Card ──────────────────────────────────────────────────

class _HeroCard extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.fromLTRB(20, 22, 20, 24),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(26),
        gradient: const LinearGradient(
          colors: [Color(0xFF5a1f72), primaryColor, Color(0xFF8b3ab0)],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            'For You',
            style: TextStyle(
              color: Colors.white,
              fontSize: 28,
              fontWeight: FontWeight.w800,
              letterSpacing: -0.5,
            ),
          ),
          const SizedBox(height: 4),
          const Text(
            'AI picks what matters for you',
            style: TextStyle(color: Colors.white70, fontSize: 13),
          ),
          const SizedBox(height: 22),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: const [
              _StatItem(icon: Icons.shopping_bag_outlined, value: '5', label: 'Items to\nreorder'),
              _StatItem(icon: Icons.calendar_today_outlined, value: '2', label: 'Upcoming\norders'),
              _StatItem(icon: Icons.inventory_2_outlined, value: '1', label: 'Active\nsubscribed'),
              _StatItem(icon: Icons.currency_rupee, value: '₹1,245', label: 'Est. spend\nthis month', smallValue: true),
            ],
          ),
        ],
      ),
    );
  }
}

class _StatItem extends StatelessWidget {
  final IconData icon;
  final String value;
  final String label;
  final bool smallValue;

  const _StatItem({
    required this.icon,
    required this.value,
    required this.label,
    this.smallValue = false,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          width: 42,
          height: 42,
          decoration: BoxDecoration(
            color: Colors.white.withOpacity(0.18),
            borderRadius: BorderRadius.circular(13),
          ),
          child: Icon(icon, color: Colors.white, size: 20),
        ),
        const SizedBox(height: 8),
        Text(
          value,
          style: TextStyle(
            color: Colors.white,
            fontSize: smallValue ? 15 : 18,
            fontWeight: FontWeight.w800,
          ),
        ),
        const SizedBox(height: 3),
        Text(
          label,
          textAlign: TextAlign.center,
          style: const TextStyle(
            color: Colors.white70,
            fontSize: 10,
            height: 1.35,
          ),
        ),
      ],
    );
  }
}

// ─── Section Header ─────────────────────────────────────────────

class _SectionHeader extends StatelessWidget {
  final String title;
  final VoidCallback onViewAll;

  const _SectionHeader({required this.title, required this.onViewAll});

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          title,
          style: const TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w700,
            color: Color(0xFF111111),
          ),
        ),
        GestureDetector(
          onTap: onViewAll,
          child: const Text(
            'View All  ›',
            style: TextStyle(color: primaryColor, fontSize: 13, fontWeight: FontWeight.w600),
          ),
        ),
      ],
    );
  }
}

// ─── Product Card ───────────────────────────────────────────────

class _ProductCard extends StatelessWidget {
  final Product product;
  final VoidCallback onToggle;

  const _ProductCard({required this.product, required this.onToggle});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.fromLTRB(12, 12, 14, 12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(color: Colors.black.withOpacity(0.04), blurRadius: 6, offset: const Offset(0, 2)),
        ],
      ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(16),
              child: Image.network(
                product.image,
                width: 85,
                height: 85,
                fit: BoxFit.cover,
              ),
            ),

            const SizedBox(width: 14),

            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    product.name,
                    style: const TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),

                  const SizedBox(height: 12),

                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          "ID: ${product.id}",
                          style: const TextStyle(
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                      Expanded(
                        child: Text(
                          "Next: ${product.nextDate}",
                          style: const TextStyle(
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    ],
                  ),

                  const SizedBox(height: 8),

                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          "Days: ${product.days}",
                          style: const TextStyle(
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                      Expanded(
                        child: RichText(
                          text: const TextSpan(
                            children: [
                              TextSpan(
                                text: "Status: ",
                                style: TextStyle(
                                  color: Colors.black87,
                                ),
                              ),
                              TextSpan(
                                text: "Active",
                                style: TextStyle(
                                  color: Colors.green,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            )
          ],
        )
    );
  }
}

// ─── iOS Toggle ─────────────────────────────────────────────────

class _IOSToggle extends StatelessWidget {
  final bool value;
  final ValueChanged<bool> onChanged;

  const _IOSToggle({required this.value, required this.onChanged});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => onChanged(!value),
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 250),
        curve: Curves.easeInOut,
        width: 51,
        height: 31,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(31),
          color: value ? primaryColor : const Color(0xFFE5E5EA),
          boxShadow: value
              ? []
              : [BoxShadow(color: Colors.black.withOpacity(0.08), blurRadius: 0, spreadRadius: 1)],
        ),
        child: Padding(
          padding: const EdgeInsets.all(2),
          child: AnimatedAlign(
            duration: const Duration(milliseconds: 250),
            curve: Curves.easeInOut,
            alignment: value ? Alignment.centerRight : Alignment.centerLeft,
            child: Container(
              width: 27,
              height: 27,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Colors.white,
                boxShadow: [
                  BoxShadow(color: Colors.black.withOpacity(0.2), blurRadius: 6, offset: const Offset(0, 2)),
                  BoxShadow(color: Colors.black.withOpacity(0.1), blurRadius: 1, offset: const Offset(0, 0.5)),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

// ─── Top Pick Card ──────────────────────────────────────────────

class _TopPickCard extends StatelessWidget {
  final TopPick pick;
  const _TopPickCard({required this.pick});

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 118,
      padding: const EdgeInsets.fromLTRB(10, 10, 10, 12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(18),
        boxShadow: [
          BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 6, offset: const Offset(0, 2)),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(12),
            child: Image.network(
              pick.image,
              width: double.infinity,
              height: 82,
              fit: BoxFit.cover,
              errorBuilder: (_, __, ___) => Container(
                height: 82,
                color: const Color(0xFFF0F0F0),
                child: const Icon(Icons.image_not_supported_outlined, color: Colors.grey),
              ),
            ),
          ),
          const SizedBox(height: 9),
          Text(
            pick.name,
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
            style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w700, color: Color(0xFF111111), height: 1.35),
          ),
          const SizedBox(height: 2),
          Text(pick.qty, style: const TextStyle(fontSize: 11, color: Color(0xFFAAAAAA))),
          const SizedBox(height: 5),
          Text(pick.price, style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w800, color: Color(0xFF111111))),
          const SizedBox(height: 9),
          GestureDetector(
            onTap: () {},
            child: Container(
              width: double.infinity,
              padding: const EdgeInsets.symmetric(vertical: 6),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(9),
                border: Border.all(color: primaryColor, width: 1.5),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Text('Add', style: TextStyle(fontSize: 12, fontWeight: FontWeight.w700, color: primaryColor)),
                  const SizedBox(width: 5),
                  Container(
                    width: 18,
                    height: 18,
                    decoration: const BoxDecoration(color: primaryColor, shape: BoxShape.circle),
                    child: const Icon(Icons.add, color: Colors.white, size: 13),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

// ─── Never Run Out Banner ───────────────────────────────────────

class _NeverRunOutBanner extends StatelessWidget {
  final VoidCallback onSetupTap;
  const _NeverRunOutBanner({required this.onSetupTap});

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.fromLTRB(18, 20, 18, 22),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(24),
        boxShadow: [
          BoxShadow(color: Colors.black.withOpacity(0.04), blurRadius: 6, offset: const Offset(0, 2)),
        ],
      ),
      child: Column(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                width: 54,
                height: 54,
                decoration: BoxDecoration(
                  color: primaryColor.withOpacity(0.12),
                  shape: BoxShape.circle,
                ),
                child: const Icon(Icons.autorenew_rounded, color: primaryColor, size: 26),
              ),
              const SizedBox(width: 14),
              const Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'Never run out of essentials',
                      style: TextStyle(fontSize: 16, fontWeight: FontWeight.w800, color: Color(0xFF111111)),
                    ),
                    SizedBox(height: 4),
                    Text(
                      'We predict your needs and automatically reorder before you run out.',
                      style: TextStyle(fontSize: 12, color: Color(0xFF999999), height: 1.5),
                    ),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          const Divider(color: Color(0xFFF2F2F2), height: 1),
          const SizedBox(height: 14),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: const [
              _FeatureChip(icon: '✨', label: 'Smart prediction'),
              _FeatureChip(icon: '🚚', label: 'Timely delivery'),
              _FeatureChip(icon: '🔒', label: 'Secure auto pay'),
            ],
          ),
          const SizedBox(height: 16),
          SizedBox(
            width: double.infinity,
            height: 52,
            child: ElevatedButton(
              onPressed: onSetupTap,
              style: ElevatedButton.styleFrom(
                backgroundColor: primaryColor,
                foregroundColor: Colors.white,
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
                elevation: 0,
              ),
              child: const Text(
                'Setup Auto Refill',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700, letterSpacing: 0.2),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _FeatureChip extends StatelessWidget {
  final String icon;
  final String label;
  const _FeatureChip({required this.icon, required this.label});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text(icon, style: const TextStyle(fontSize: 18)),
        const SizedBox(height: 4),
        Text(label, style: const TextStyle(fontSize: 11, color: Color(0xFF666666))),
      ],
    );
  }
}

// ─── Auto Refill Setup Page ─────────────────────────────────────

class AutoRefillSetupPage extends StatefulWidget {
  final VoidCallback onBack;
  const AutoRefillSetupPage({super.key, required this.onBack});

  @override
  State<AutoRefillSetupPage> createState() => _AutoRefillSetupPageState();
}

class _AutoRefillSetupPageState extends State<AutoRefillSetupPage> {
  String _choice = 'auto';
  bool _autoPay = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        surfaceTintColor: Colors.transparent,
        leading: IconButton(
          icon: const Icon(Icons.chevron_left, size: 28, color: Color(0xFF222222)),
          onPressed: widget.onBack,
        ),
        title: const Text(
          'Auto Refill Setup',
          style: TextStyle(fontWeight: FontWeight.w700, fontSize: 17, color: Color(0xFF111111)),
        ),
        centerTitle: true,
        actions: [
          Padding(
            padding: const EdgeInsets.only(right: 16),
            child: Container(
              width: 32,
              height: 32,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(color: const Color(0xFFDDDDDD), width: 1.5),
              ),
              child: const Center(
                child: Text('?', style: TextStyle(fontWeight: FontWeight.w700, color: Color(0xFF888888), fontSize: 14)),
              ),
            ),
          ),
        ],
        bottom: const PreferredSize(
          preferredSize: Size.fromHeight(1),
          child: Divider(color: Color(0xFFF5F5F5), height: 1),
        ),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.fromLTRB(16, 0, 16, 120),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Product row
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 18),
              child: Row(
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(16),
                    child: Image.network(
                      'https://images.unsplash.com/photo-1586201375761-83865001e31c?w=200',
                      width: 74,
                      height: 74,
                      fit: BoxFit.cover,
                    ),
                  ),
                  const SizedBox(width: 14),
                  const Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('Salt', style: TextStyle(fontSize: 24, fontWeight: FontWeight.w800, color: Color(0xFF111111), height: 1)),
                      SizedBox(height: 5),
                      Text('1 Kg  •  Tata Salt', style: TextStyle(fontSize: 13, color: Color(0xFF999999))),
                      SizedBox(height: 8),
                      Text('₹20', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w800, color: Color(0xFF111111))),
                    ],
                  ),
                ],
              ),
            ),
            const Divider(color: Color(0xFFF0F0F0), height: 1),
            const SizedBox(height: 22),

            // Step 1
            _StepLabel(step: 'Step 1:', label: 'Choose Refill Preference'),
            const SizedBox(height: 14),
            _RefillOption(
              selected: _choice == 'auto',
              onTap: () => setState(() => _choice = 'auto'),
              title: 'Auto Refill (Recommended)',
              subtitle: "We'll monitor your usage and reorder automatically before you run out.",
              badge: 'Most popular',
              trailing: null,
            ),
            const SizedBox(height: 10),
            _RefillOption(
              selected: _choice == 'reminder',
              onTap: () => setState(() => _choice = 'reminder'),
              title: 'Reminder Only',
              subtitle: "We'll remind you when it's time to reorder.",
              badge: null,
              trailing: const Icon(Icons.notifications_outlined, size: 24, color: primaryColor),
            ),
            const SizedBox(height: 24),

            // Step 2
            _StepLabel(step: 'Step 2:', label: 'Set Preferences'),
            const SizedBox(height: 6),
            _PrefRow(icon: Icons.calendar_today_outlined, label: 'Order Frequency', value: 'Every 30 days'),
            _PrefRow(icon: Icons.inventory_2_outlined, label: 'Quantity', value: '1 Kg'),
            _PrefRow(icon: Icons.local_offer_outlined, label: 'Preferred Brand', value: 'Tata Salt'),
            _PrefRowWithAction(
              icon: Icons.store_outlined,
              label: 'Preferred Store',
              value: 'Zepto',
              action: TextButton(
                onPressed: () {},
                style: TextButton.styleFrom(
                  backgroundColor: primaryColor.withOpacity(0.12),
                  padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 5),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)),
                  minimumSize: Size.zero,
                  tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                ),
                child: const Text('Change', style: TextStyle(color: primaryColor, fontWeight: FontWeight.w700, fontSize: 12)),
              ),
            ),
            const SizedBox(height: 24),

            // Step 3
            _StepLabel(step: 'Step 3:', label: 'Payment'),
            const SizedBox(height: 14),

            // Auto Pay card
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: const Color(0xFFF8F8F8),
                borderRadius: BorderRadius.circular(16),
              ),
              child: Row(
                children: [
                  Container(
                    width: 40,
                    height: 40,
                    decoration: BoxDecoration(
                      color: primaryColor.withOpacity(0.15),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: const Icon(Icons.shield_outlined, color: primaryColor, size: 20),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            const Text('Auto Pay', style: TextStyle(fontWeight: FontWeight.w700, fontSize: 15, color: Color(0xFF111111))),
                            const SizedBox(width: 8),
                            Container(
                              padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 2),
                              decoration: BoxDecoration(color: const Color(0xFF00C853), borderRadius: BorderRadius.circular(20)),
                              child: const Text('Secure', style: TextStyle(color: Colors.white, fontSize: 10, fontWeight: FontWeight.w700)),
                            ),
                          ],
                        ),
                        const SizedBox(height: 3),
                        const Text(
                          'Amount will be automatically paid using your saved payment method.',
                          style: TextStyle(fontSize: 11, color: Color(0xFF999999), height: 1.5),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(width: 10),
                  _IOSToggle(value: _autoPay, onChanged: (v) => setState(() => _autoPay = v)),
                ],
              ),
            ),
            const SizedBox(height: 10),

            // UPI row
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: const Color(0xFFF8F8F8),
                borderRadius: BorderRadius.circular(16),
              ),
              child: Row(
                children: [
                  Container(
                    width: 40,
                    height: 40,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(12),
                      boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.08), blurRadius: 4)],
                    ),
                    child: const Center(child: Text('🏦', style: TextStyle(fontSize: 20))),
                  ),
                  const SizedBox(width: 12),
                  const Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text('UPI - AutoPay', style: TextStyle(fontWeight: FontWeight.w700, fontSize: 14, color: Color(0xFF111111))),
                        SizedBox(height: 2),
                        Text('rahul@okaxis', style: TextStyle(fontSize: 12, color: Color(0xFF999999))),
                      ],
                    ),
                  ),
                  const Text('Change  ›', style: TextStyle(color: primaryColor, fontSize: 13, fontWeight: FontWeight.w700)),
                ],
              ),
            ),
            const SizedBox(height: 22),

            // How it works
            Container(
              padding: const EdgeInsets.all(18),
              decoration: BoxDecoration(
                color: primaryColor.withOpacity(0.06),
                borderRadius: BorderRadius.circular(18),
                border: Border.all(color: primaryColor.withOpacity(0.2), width: 1.5),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    'How Auto Refill Works',
                    style: TextStyle(fontWeight: FontWeight.w800, fontSize: 14, color: primaryColor),
                  ),
                  const SizedBox(height: 16),
                  ...[
                    _HowItWorksData(Icons.calendar_today_outlined, 'We track your usage', 'Our AI monitors how quickly you use the product.'),
                    _HowItWorksData(Icons.auto_awesome_outlined, 'Predict & notify', "We predict when you'll run out and notify you."),
                    _HowItWorksData(Icons.shopping_cart_outlined, 'Auto order', 'We place the order before you run out.'),
                    _HowItWorksData(Icons.local_shipping_outlined, 'Auto pay & deliver', 'Payment is automatic and we deliver to you.'),
                  ].asMap().entries.map(
                        (entry) => Padding(
                      padding: EdgeInsets.only(bottom: entry.key < 3 ? 16 : 0),
                      child: _HowItWorksRow(data: entry.value),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),

      // Sticky CTA
      bottomSheet: Container(
        color: Colors.white,
        padding: const EdgeInsets.fromLTRB(16, 14, 16, 28),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            SizedBox(
              width: double.infinity,
              height: 54,
              child: ElevatedButton(
                onPressed: () {},
                style: ElevatedButton.styleFrom(
                  backgroundColor: primaryColor,
                  foregroundColor: Colors.white,
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
                  elevation: 0,
                ),
                child: const Text(
                  'Enable Auto Refill',
                  style: TextStyle(fontSize: 17, fontWeight: FontWeight.w800, letterSpacing: 0.2),
                ),
              ),
            ),
            const SizedBox(height: 10),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: const [
                Icon(Icons.lock_outline, size: 13, color: Color(0xFFAAAAAA)),
                SizedBox(width: 5),
                Text(
                  'You can pause or cancel anytime',
                  style: TextStyle(fontSize: 12, color: Color(0xFFAAAAAA)),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

// ─── Setup Page Sub-widgets ─────────────────────────────────────

class _StepLabel extends StatelessWidget {
  final String step;
  final String label;
  const _StepLabel({required this.step, required this.label});

  @override
  Widget build(BuildContext context) {
    return RichText(
      text: TextSpan(
        style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: Color(0xFF111111)),
        children: [
          TextSpan(text: step, style: const TextStyle(color: primaryColor)),
          TextSpan(text: ' $label'),
        ],
      ),
    );
  }
}

class _RefillOption extends StatelessWidget {
  final bool selected;
  final VoidCallback onTap;
  final String title;
  final String subtitle;
  final String? badge;
  final Widget? trailing;

  const _RefillOption({
    required this.selected,
    required this.onTap,
    required this.title,
    required this.subtitle,
    this.badge,
    this.trailing,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        padding: const EdgeInsets.all(15),
        decoration: BoxDecoration(
          color: selected ? primaryColor.withOpacity(0.05) : Colors.white,
          borderRadius: BorderRadius.circular(16),
          border: Border.all(
            color: selected ? primaryColor : const Color(0xFFEEEEEE),
            width: 2,
          ),
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            AnimatedContainer(
              duration: const Duration(milliseconds: 200),
              width: 22,
              height: 22,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(
                  color: selected ? primaryColor : const Color(0xFFCCCCCC),
                  width: 2.5,
                ),
                color: selected ? primaryColor : Colors.white,
              ),
              child: selected
                  ? const Center(
                child: CircleAvatar(radius: 4, backgroundColor: Colors.white),
              )
                  : null,
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Wrap(
                    spacing: 8,
                    crossAxisAlignment: WrapCrossAlignment.center,
                    children: [
                      Text(title, style: const TextStyle(fontWeight: FontWeight.w700, fontSize: 14, color: Color(0xFF111111))),
                      if (badge != null)
                        Container(
                          padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 2),
                          decoration: BoxDecoration(
                            color: primaryColor.withOpacity(0.13),
                            borderRadius: BorderRadius.circular(20),
                          ),
                          child: Text(badge!, style: const TextStyle(color: primaryColor, fontSize: 10, fontWeight: FontWeight.w700)),
                        ),
                    ],
                  ),
                  const SizedBox(height: 5),
                  Text(subtitle, style: const TextStyle(fontSize: 12, color: Color(0xFF999999), height: 1.5)),
                ],
              ),
            ),
            if (trailing != null) ...[const SizedBox(width: 8), trailing!],
          ],
        ),
      ),
    );
  }
}

class _PrefRow extends StatelessWidget {
  final IconData icon;
  final String label;
  final String value;
  const _PrefRow({required this.icon, required this.label, required this.value});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 14),
      decoration: const BoxDecoration(border: Border(bottom: BorderSide(color: Color(0xFFF2F2F2)))),
      child: Row(
        children: [
          Container(
            width: 34,
            height: 34,
            decoration: BoxDecoration(color: const Color(0xFFF5F5F7), borderRadius: BorderRadius.circular(10)),
            child: Icon(icon, size: 17, color: const Color(0xFF555555)),
          ),
          const SizedBox(width: 12),
          Expanded(child: Text(label, style: const TextStyle(fontSize: 14, color: Color(0xFF333333), fontWeight: FontWeight.w500))),
          Text(value, style: const TextStyle(fontSize: 13, color: Color(0xFF555555), fontWeight: FontWeight.w600)),
          const SizedBox(width: 6),
          const Icon(Icons.keyboard_arrow_down, color: Color(0xFFBBBBBB), size: 18),
        ],
      ),
    );
  }
}

class _PrefRowWithAction extends StatelessWidget {
  final IconData icon;
  final String label;
  final String value;
  final Widget action;
  const _PrefRowWithAction({required this.icon, required this.label, required this.value, required this.action});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 14),
      child: Row(
        children: [
          Container(
            width: 34,
            height: 34,
            decoration: BoxDecoration(color: const Color(0xFFF5F5F7), borderRadius: BorderRadius.circular(10)),
            child: Icon(icon, size: 17, color: const Color(0xFF555555)),
          ),
          const SizedBox(width: 12),
          Expanded(child: Text(label, style: const TextStyle(fontSize: 14, color: Color(0xFF333333), fontWeight: FontWeight.w500))),
          Text(value, style: const TextStyle(fontSize: 13, color: Color(0xFF555555), fontWeight: FontWeight.w600)),
          const SizedBox(width: 10),
          action,
        ],
      ),
    );
  }
}

class _HowItWorksData {
  final IconData icon;
  final String title;
  final String desc;
  const _HowItWorksData(this.icon, this.title, this.desc);
}

class _HowItWorksRow extends StatelessWidget {
  final _HowItWorksData data;
  const _HowItWorksRow({required this.data});

  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          width: 36,
          height: 36,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(10),
            boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.06), blurRadius: 4)],
          ),
          child: Icon(data.icon, size: 18, color: primaryColor),
        ),
        const SizedBox(width: 12),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(data.title, style: const TextStyle(fontWeight: FontWeight.w700, fontSize: 13, color: Color(0xFF111111))),
              const SizedBox(height: 3),
              Text(data.desc, style: const TextStyle(fontSize: 12, color: Color(0xFF888888), height: 1.5)),
            ],
          ),
        ),
      ],
    );
  }
}