import 'dart:async';
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get_navigation/src/extension_navigation.dart';
import 'package:get/get_navigation/src/routes/transitions_type.dart';
import 'package:sleek_circular_slider/sleek_circular_slider.dart';

import '../../../../view/home_view.dart';

// =====================================================================
// Single-file version of the "AI is finding your order" processing
// screen + the detailed order tracker screen that follows it.
// Light theme: white background, white cards, primary color used only
// for borders / icons / accents. Processing takes 10 seconds.
// =====================================================================

enum StepStatus { done, active, pending }

// -----------------------------------------------------------------------
// Shared "moving" text — a soft highlight sweeps across the text on a
// loop so headline copy feels alive instead of static.
// -----------------------------------------------------------------------
class ShimmerText extends StatefulWidget {
  final String text;
  final TextStyle style;
  final Color baseColor;
  final Color highlightColor;
  final Duration duration;
  final TextAlign textAlign;

  const ShimmerText({
    super.key,
    required this.text,
    required this.style,
    this.baseColor = const Color(0xFF1A1A1A),
    this.highlightColor = const Color(0xFF662582),
    this.duration = const Duration(milliseconds: 2200),
    this.textAlign = TextAlign.center,
  });

  @override
  State<ShimmerText> createState() => _ShimmerTextState();
}

class _ShimmerTextState extends State<ShimmerText>
    with SingleTickerProviderStateMixin {
  late final AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(vsync: this, duration: widget.duration)
      ..repeat();
  }

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

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, child) {
        final t = _controller.value;
        final sweep = -2.0 + 4.0 * t;
        return ShaderMask(
          blendMode: BlendMode.srcIn,
          shaderCallback: (bounds) {
            return LinearGradient(
              colors: [
                widget.baseColor,
                widget.baseColor,
                widget.highlightColor,
                widget.baseColor,
                widget.baseColor,
              ],
              stops: const [0.0, 0.38, 0.5, 0.62, 1.0],
              begin: Alignment(sweep - 0.6, 0),
              end: Alignment(sweep + 0.6, 0),
            ).createShader(bounds);
          },
          child: Text(
            widget.text,
            textAlign: widget.textAlign,
            style: widget.style,
          ),
        );
      },
    );
  }
}

// =========================================================================
// SCREEN 1 — AI Assistant processing screen (10 seconds)
// =========================================================================

class ProcessingStep {
  final String title;
  final String subtitle;
  final IconData icon;
  const ProcessingStep(this.title, this.subtitle, this.icon);
}

class AIAssistantScreen extends StatefulWidget {
  const AIAssistantScreen({super.key});
  @override
  State<AIAssistantScreen> createState() => _AIAssistantScreenState();
}

class _AIAssistantScreenState extends State<AIAssistantScreen>
    with TickerProviderStateMixin {
  // Primary brand color used only for borders, icons, and accent text.
  static const primary = Color(0xFF662582);
  static const ink = Color(0xFF1A1A1A);
  static const inkFaint = Color(0xFF8A8A8F);
  static const bg = Color(0xFFFFFFFF);
  static const cardBg = Color(0xFFFFFFFF);
  static const cardBorder = Color(0xFFEDEDF2);

  late final AnimationController _progressController;
  late final AnimationController _glowController;
  double get _progress => _progressController.value * 100;

  final List<ProcessingStep> _steps = const [
    ProcessingStep('Understanding your request', 'Analyzing your preferences',
        Icons.psychology_alt_outlined),
    ProcessingStep('Finding nearby restaurants', 'Scanning 120+ restaurants',
        Icons.travel_explore),
    ProcessingStep('Comparing ratings & prices', 'Checking reviews and prices',
        Icons.compare_arrows),
    ProcessingStep('Choosing the best option', 'Selecting top choice for you',
        Icons.workspace_premium_outlined),
    ProcessingStep('Placing your order', 'Confirming and placing order',
        Icons.check_circle_outline),
  ];

  bool _navigated = false;

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

    // Whole flow completes in exactly 10 seconds.
    _progressController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 10000),
    )..addListener(() => setState(() {}));

    _glowController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 1400),
    )..repeat(reverse: true);

    _progressController.forward();
    _progressController.addStatusListener((status) {
      if (status == AnimationStatus.completed && !_navigated) {
        _navigated = true;
        Future.delayed(const Duration(milliseconds: 550), () {
          if (!mounted) return;
          Get.off(
                () => const OrderTrackerScreen(),
            transition: Transition.rightToLeftWithFade,
            duration: const Duration(milliseconds: 450),
          );
        });
      }
    });
  }

  @override
  void dispose() {
    _progressController.dispose();
    _glowController.dispose();
    super.dispose();
  }

  int get _activeIndex {
    final segment = 100 / _steps.length;
    final idx = (_progress / segment).floor();
    return idx.clamp(0, _steps.length - 1);
  }

  StepStatus _statusFor(int index) {
    if (_progress >= 100) return StepStatus.done;
    if (index < _activeIndex) return StepStatus.done;
    if (index == _activeIndex) return StepStatus.active;
    return StepStatus.pending;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: bg,
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildTopBar(),
              const SizedBox(height: 26),
              Center(child: _buildRing()),
              const SizedBox(height: 24),
              Center(
                child: ShimmerText(
                  text: 'Ordering biriyani for you...',
                  style: const TextStyle(
                    fontSize: 22,
                    fontWeight: FontWeight.bold,
                    color: ink,
                  ),
                ),
              ),
              const SizedBox(height: 8),
              Center(
                child: Text(
                  'Finding the best options with great taste\nand best price',
                  textAlign: TextAlign.center,
                  style: TextStyle(color: inkFaint, fontSize: 14, height: 1.4),
                ),
              ),
              const SizedBox(height: 24),
              _buildStepsCard(),
              const SizedBox(height: 16),
              _buildStatsCard(),
              const SizedBox(height: 16),
              _buildFooterBanner(),
              const SizedBox(height: 12),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildTopBar() {
    return Row(
      children: [
        IconButton(
          onPressed: () => Get.offAll(() => BottomNavigation()),
          icon: const Icon(Icons.arrow_back_ios_new, color: ink, size: 20),
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 6),
            Row(
              children: [
                const Text('Nearle AI',
                    style: TextStyle(
                        color: ink, fontWeight: FontWeight.bold, fontSize: 16)),
                const SizedBox(width: 6),
                Container(
                  padding:
                  const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    border: Border.all(color: primary, width: 1),
                    borderRadius: BorderRadius.circular(6),
                  ),
                  child: const Text('AI',
                      style: TextStyle(
                          color: primary,
                          fontSize: 9,
                          fontWeight: FontWeight.bold)),
                ),
              ],
            ),
            Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                AnimatedBuilder(
                  animation: _glowController,
                  builder: (context, _) => Container(
                    width: 6,
                    height: 6,
                    decoration: BoxDecoration(
                      color: Colors.green
                          .withOpacity(0.5 + 0.5 * _glowController.value),
                      shape: BoxShape.circle,
                    ),
                  ),
                ),
                const SizedBox(width: 4),
                Text('Processing your request',
                    style: TextStyle(color: inkFaint, fontSize: 12)),
              ],
            ),
          ],
        ),
        const Spacer(),
        const Icon(Icons.more_vert, color: ink, size: 20),
      ],
    );
  }

  Widget _buildRing() {
    return _AiRing(
      progress: _progress,
      primary: primary,
      centerBuilder: (value) => _buildCenter(value),
    );
  }
  Widget _buildCenter(double value) {
    final done = value >= 100;
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        TweenAnimationBuilder<double>(
          tween: Tween(begin: 0.9, end: done ? 1.15 : 1.0),
          duration: const Duration(milliseconds: 350),
          curve: Curves.easeOutBack,
          builder: (context, scale, child) =>
              Transform.scale(scale: scale, child: child),
          child: Text(done ? '🎉' : '🍚', style: const TextStyle(fontSize: 56)),
        ),
        const SizedBox(height: 8),
        RichText(
          text: TextSpan(
            children: [
              TextSpan(
                text: '${value.toInt()}',
                style: const TextStyle(
                    fontSize: 40, fontWeight: FontWeight.bold, color: ink),
              ),
              const TextSpan(
                text: '%',
                style: TextStyle(
                    fontSize: 22, fontWeight: FontWeight.bold, color: primary),
              ),
            ],
          ),
        ),
        Text(done ? 'Order placed!' : 'Processing...',
            style: const TextStyle(color: inkFaint)),
      ],
    );
  }

  Widget _buildStepsCard() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: cardBg,
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: cardBorder),
      ),
      child: Column(
        children: List.generate(_steps.length, (i) {
          return _buildStepRow(_steps[i], _statusFor(i), i == _steps.length - 1);
        }),
      ),
    );
  }

  Widget _buildStepRow(ProcessingStep step, StepStatus status, bool isLast) {
    Color circleColor;
    Widget icon;
    switch (status) {
      case StepStatus.done:
        circleColor = primary;
        icon = const Icon(Icons.check, color: Colors.white, size: 16);
        break;
      case StepStatus.active:
        circleColor = Colors.white;
        icon = Icon(step.icon, color: primary, size: 16);
        break;
      case StepStatus.pending:
        circleColor = Colors.white;
        icon = Icon(step.icon, color: inkFaint.withOpacity(0.6), size: 14);
        break;
    }

    return IntrinsicHeight(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Column(
            children: [
              AnimatedBuilder(
                animation: _glowController,
                builder: (context, child) {
                  final pulse = status == StepStatus.active
                      ? 1.0 + 0.12 * _glowController.value
                      : 1.0;
                  return Transform.scale(scale: pulse, child: child);
                },
                child: AnimatedContainer(
                  duration: const Duration(milliseconds: 300),
                  width: 30,
                  height: 30,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: circleColor,
                    border: status == StepStatus.active
                        ? Border.all(color: primary, width: 2)
                        : status == StepStatus.pending
                        ? Border.all(color: cardBorder, width: 1.5)
                        : null,
                  ),
                  child: Center(
                    child: AnimatedSwitcher(
                      duration: const Duration(milliseconds: 250),
                      child: KeyedSubtree(key: ValueKey(status), child: icon),
                    ),
                  ),
                ),
              ),
              if (!isLast)
                Expanded(
                  child: AnimatedContainer(
                    duration: const Duration(milliseconds: 300),
                    width: 2,
                    color: status == StepStatus.done ? primary : cardBorder,
                  ),
                ),
            ],
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.only(bottom: 24),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(step.title,
                            style: TextStyle(
                                color: status == StepStatus.pending
                                    ? inkFaint
                                    : ink,
                                fontWeight: FontWeight.w600,
                                fontSize: 15)),
                        const SizedBox(height: 4),
                        Text(step.subtitle,
                            style: TextStyle(color: inkFaint, fontSize: 13)),
                      ],
                    ),
                  ),
                  if (status == StepStatus.done)
                    _buildBadge('Done', Colors.green, Colors.green.withOpacity(0.08)),
                  if (status == StepStatus.active)
                    _buildBadge('${_progress.toInt()}%', primary,
                        primary.withOpacity(0.08)),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBadge(String text, Color textColor, Color bgColor) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: textColor.withOpacity(0.3)),
      ),
      child: Text(text,
          style: TextStyle(
              color: textColor, fontSize: 12, fontWeight: FontWeight.w600)),
    );
  }

  Widget _buildStatsCard() {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 18, horizontal: 8),
      decoration: BoxDecoration(
        color: cardBg,
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: cardBorder),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          _buildStat(Icons.storefront, '120+', 'Restaurants\nScanned'),
          _buildStat(Icons.star, '4.6+', 'Average\nRating'),
          _buildStat(Icons.credit_card, '\u20b9120 - \u20b9450', 'Price\nRange'),
        ],
      ),
    );
  }

  Widget _buildStat(IconData icon, String value, String label) {
    return Column(
      children: [
        Container(
          padding: const EdgeInsets.all(10),
          decoration: BoxDecoration(
              color: Colors.white,
              border: Border.all(color: primary.withOpacity(0.4)),
              borderRadius: BorderRadius.circular(12)),
          child: Icon(icon, color: primary, size: 20),
        ),
        const SizedBox(height: 8),
        Text(value,
            style: const TextStyle(
                color: ink, fontWeight: FontWeight.bold, fontSize: 14)),
        const SizedBox(height: 2),
        Text(label,
            textAlign: TextAlign.center,
            style: const TextStyle(color: inkFaint, fontSize: 11)),
      ],
    );
  }

  Widget _buildFooterBanner() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.symmetric(vertical: 14),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(30),
        border: Border.all(color: primary.withOpacity(0.5)),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          AnimatedBuilder(
            animation: _glowController,
            builder: (context, child) => Transform.rotate(
              angle: _glowController.value * 0.6,
              child: child,
            ),
            child: const Icon(Icons.auto_awesome, color: primary, size: 18),
          ),
          const SizedBox(width: 8),
          Text(
            _progress >= 100
                ? 'All set! Redirecting to your order...'
                : 'This will only take a moment...',
            style: const TextStyle(color: primary, fontWeight: FontWeight.w500),
          ),
        ],
      ),
    );
  }
}

// =========================================================================
// SCREEN 2 — Detailed order tracker
// =========================================================================

class RestaurantOption {
  final String name;
  final double rating;
  final int price;
  final String emoji;
  final bool chosen;
  final String reason;

  const RestaurantOption({
    required this.name,
    required this.rating,
    required this.price,
    required this.emoji,
    this.chosen = false,
    this.reason = '',
  });
}

enum TrackStage { placed, confirmed, preparing, pickedUp, onTheWay, delivered }

class _StageInfo {
  final TrackStage stage;
  final String title;
  final String subtitle;
  final IconData icon;
  const _StageInfo(this.stage, this.title, this.subtitle, this.icon);
}

class OrderTrackerScreen extends StatefulWidget {
  final String? orderId;
  final String dishName;
  final List<RestaurantOption>? compared;

  const OrderTrackerScreen({
    super.key,
    this.orderId,
    this.dishName = 'Chicken Biriyani (Full)',
    this.compared,
  });

  @override
  State<OrderTrackerScreen> createState() => _OrderTrackerScreenState();
}

class _OrderTrackerScreenState extends State<OrderTrackerScreen>
    with TickerProviderStateMixin {
  static const primary = Color(0xFF662582);
  static const ink = Color(0xFF1A1A1A);
  static const inkFaint = Color(0xFF8A8A8F);
  static const bg = Color(0xFFFFFFFF);
  static const cardBg = Color(0xFFFFFFFF);
  static const cardBorder = Color(0xFFEDEDF2);

  late final String _orderId;
  late final List<RestaurantOption> _compared;

  TrackStage _stage = TrackStage.confirmed;
  Timer? _stageTimer;
  late final AnimationController _riderController;
  late final AnimationController _pulseController;

  static const List<_StageInfo> _stages = [
    _StageInfo(TrackStage.placed, 'Order Placed', 'We received your order',
        Icons.receipt_long),
    _StageInfo(TrackStage.confirmed, 'Restaurant Confirmed',
        'They are getting started', Icons.storefront),
    _StageInfo(TrackStage.preparing, 'Food Being Prepared',
        'Cooked fresh, just for you', Icons.soup_kitchen),
    _StageInfo(TrackStage.pickedUp, 'Rider Picked Up',
        'Your rider has the order', Icons.delivery_dining),
    _StageInfo(TrackStage.onTheWay, 'On The Way', 'Speeding towards you',
        Icons.two_wheeler),
    _StageInfo(TrackStage.delivered, 'Delivered', 'Enjoy your meal!',
        Icons.celebration),
  ];

  @override
  void initState() {
    super.initState();
    _orderId = widget.orderId ?? 'NR${100000 + math.Random().nextInt(899999)}';
    _compared = widget.compared ??
        const [
          RestaurantOption(
              name: 'Paradise Biriyani House',
              rating: 4.8,
              price: 320,
              emoji: '🍛',
              chosen: true,
              reason: 'Highest rating + fastest prep time'),
          RestaurantOption(
              name: 'Hyderabad House', rating: 4.5, price: 350, emoji: '🍚'),
          RestaurantOption(
              name: 'Spice Route', rating: 4.3, price: 280, emoji: '🌶️'),
        ];

    _riderController =
    AnimationController(vsync: this, duration: const Duration(seconds: 2))
      ..repeat(reverse: true);
    _pulseController = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 1200))
      ..repeat(reverse: true);

    _stageTimer = Timer.periodic(const Duration(seconds: 4), (t) {
      final nextIndex = _stage.index + 1;
      if (nextIndex >= TrackStage.values.length) {
        t.cancel();
        return;
      }
      setState(() => _stage = TrackStage.values[nextIndex]);
      if (_stage == TrackStage.delivered) t.cancel();
    });
  }

  @override
  void dispose() {
    _stageTimer?.cancel();
    _riderController.dispose();
    _pulseController.dispose();
    super.dispose();
  }

  RestaurantOption get _chosen =>
      _compared.firstWhere((r) => r.chosen, orElse: () => _compared.first);

  bool get _delivered => _stage == TrackStage.delivered;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: bg,
      body: SafeArea(
        child: Column(
          children: [
            _buildTopBar(),
            Expanded(
              child: ListView(
                padding: const EdgeInsets.fromLTRB(20, 8, 20, 24),
                children: [
                  _buildHeroCard(),
                  const SizedBox(height: 20),
                  _buildTimelineCard(),
                  const SizedBox(height: 20),
                  _buildComparisonCard(),
                  const SizedBox(height: 20),
                  _buildRiderCard(),
                  const SizedBox(height: 20),
                  _buildOrderSummary(),
                  const SizedBox(height: 20),
                ],
              ),
            ),
          ],
        ),
      ),
      bottomNavigationBar: _buildBottomBar(),
    );
  }

  Widget _buildTopBar() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(12, 8, 20, 4),
      child: Row(
        children: [
          IconButton(
            onPressed: () => Get.offAll(() => BottomNavigation()),
            icon: const Icon(Icons.arrow_back_ios_new, color: ink, size: 20),
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text('Order Tracking',
                  style: TextStyle(
                      color: ink, fontWeight: FontWeight.bold, fontSize: 16)),
              Text('#$_orderId',
                  style: const TextStyle(color: inkFaint, fontSize: 12)),
            ],
          ),
          const Spacer(),
          _buildLiveChip(),
        ],
      ),
    );
  }

  Widget _buildLiveChip() {
    final color = _delivered ? Colors.green : primary;
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: color.withOpacity(0.5)),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          AnimatedBuilder(
            animation: _pulseController,
            builder: (context, _) => Container(
              width: 6,
              height: 6,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: color.withOpacity(0.4 + 0.6 * _pulseController.value),
              ),
            ),
          ),
          const SizedBox(width: 6),
          Text(_delivered ? 'Delivered' : 'Live',
              style: TextStyle(
                  color: color, fontSize: 11, fontWeight: FontWeight.w600)),
        ],
      ),
    );
  }

  Widget _buildHeroCard() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: cardBg,
        borderRadius: BorderRadius.circular(24),
        border: Border.all(color: primary.withOpacity(0.5)),
      ),
      child: Column(
        children: [
          ShimmerText(
            text: _delivered
                ? 'Your food has arrived!'
                : 'Arriving in ${18 - _stage.index * 3}-${22 - _stage.index * 3} mins',
            style: const TextStyle(
                fontSize: 20, fontWeight: FontWeight.bold, color: ink),
          ),
          const SizedBox(height: 4),
          Text(
            _stages[_stage.index].subtitle,
            style: const TextStyle(color: inkFaint, fontSize: 13),
          ),
          const SizedBox(height: 22),
          SizedBox(
            height: 46,
            child: LayoutBuilder(
              builder: (context, constraints) {
                return Stack(
                  alignment: Alignment.center,
                  children: [
                    CustomPaint(
                      size: Size(constraints.maxWidth, 2),
                      painter: _DashedLinePainter(color: cardBorder),
                    ),
                    const Align(
                      alignment: Alignment.centerLeft,
                      child: Text('🏪', style: TextStyle(fontSize: 22)),
                    ),
                    const Align(
                      alignment: Alignment.centerRight,
                      child: Text('🏠', style: TextStyle(fontSize: 22)),
                    ),
                    AnimatedBuilder(
                      animation: _riderController,
                      builder: (context, child) {
                        final stageProgress =
                        (_stage.index / (TrackStage.values.length - 1))
                            .clamp(0.05, 0.95);
                        final wobble = 0.04 * _riderController.value;
                        final x = (constraints.maxWidth - 34) *
                            (stageProgress + wobble).clamp(0.0, 1.0);
                        return Positioned(
                          left: x,
                          child: Container(
                            padding: const EdgeInsets.all(6),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              shape: BoxShape.circle,
                              border: Border.all(color: primary, width: 1.5),
                            ),
                            child: const Icon(Icons.delivery_dining,
                                color: primary, size: 18),
                          ),
                        );
                      },
                    ),
                  ],
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTimelineCard() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: cardBg,
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: cardBorder),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text('Order Timeline',
              style: TextStyle(
                  color: ink, fontWeight: FontWeight.bold, fontSize: 15)),
          const SizedBox(height: 16),
          ...List.generate(_stages.length, (i) {
            final info = _stages[i];
            final status = i < _stage.index
                ? StepStatus.done
                : i == _stage.index
                ? StepStatus.active
                : StepStatus.pending;
            return _buildTimelineRow(info, status, i == _stages.length - 1);
          }),
        ],
      ),
    );
  }

  Widget _buildTimelineRow(_StageInfo info, StepStatus status, bool isLast) {
    Color circleColor;
    Color iconColor;
    switch (status) {
      case StepStatus.done:
        circleColor = primary;
        iconColor = Colors.white;
        break;
      case StepStatus.active:
        circleColor = Colors.white;
        iconColor = primary;
        break;
      case StepStatus.pending:
        circleColor = Colors.white;
        iconColor = inkFaint.withOpacity(0.6);
        break;
    }

    return IntrinsicHeight(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Column(
            children: [
              AnimatedBuilder(
                animation: _pulseController,
                builder: (context, child) {
                  final scale = status == StepStatus.active
                      ? 1.0 + 0.1 * _pulseController.value
                      : 1.0;
                  return Transform.scale(scale: scale, child: child);
                },
                child: AnimatedContainer(
                  duration: const Duration(milliseconds: 300),
                  width: 32,
                  height: 32,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: circleColor,
                    border: status == StepStatus.pending
                        ? Border.all(color: cardBorder, width: 1.5)
                        : status == StepStatus.active
                        ? Border.all(color: primary, width: 2)
                        : null,
                  ),
                  child: Center(
                    child: status == StepStatus.done
                        ? const Icon(Icons.check, color: Colors.white, size: 16)
                        : Icon(info.icon, color: iconColor, size: 16),
                  ),
                ),
              ),
              if (!isLast)
                Expanded(
                  child: AnimatedContainer(
                    duration: const Duration(milliseconds: 300),
                    width: 2,
                    color: status == StepStatus.done ? primary : cardBorder,
                  ),
                ),
            ],
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.only(bottom: 22),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(info.title,
                      style: TextStyle(
                          color: status == StepStatus.pending ? inkFaint : ink,
                          fontWeight: FontWeight.w600,
                          fontSize: 14)),
                  const SizedBox(height: 3),
                  Text(info.subtitle,
                      style: const TextStyle(color: inkFaint, fontSize: 12)),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildComparisonCard() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: cardBg,
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: cardBorder),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.auto_awesome, color: primary, size: 16),
              const SizedBox(width: 6),
              const Text('Why we picked this for you',
                  style: TextStyle(
                      color: ink, fontWeight: FontWeight.bold, fontSize: 15)),
            ],
          ),
          const SizedBox(height: 4),
          Text(
              _chosen.reason.isEmpty
                  ? 'Best balance of rating and price nearby'
                  : _chosen.reason,
              style: const TextStyle(color: inkFaint, fontSize: 12)),
          const SizedBox(height: 16),
          ..._compared.map((r) => _buildCompareRow(r)),
        ],
      ),
    );
  }

  Widget _buildCompareRow(RestaurantOption r) {
    return Container(
      margin: const EdgeInsets.only(bottom: 10),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(14),
        border: Border.all(
            color: r.chosen ? primary : cardBorder, width: r.chosen ? 1.4 : 1),
      ),
      child: Row(
        children: [
          Text(r.emoji, style: const TextStyle(fontSize: 24)),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Flexible(
                      child: Text(r.name,
                          overflow: TextOverflow.ellipsis,
                          style: const TextStyle(
                              color: ink,
                              fontWeight: FontWeight.w600,
                              fontSize: 13)),
                    ),
                    if (r.chosen) ...[
                      const SizedBox(width: 6),
                      _buildBadge('Best Match', primary, primary.withOpacity(0.08)),
                    ],
                  ],
                ),
                const SizedBox(height: 4),
                Row(
                  children: [
                    const Icon(Icons.star, color: primary, size: 13),
                    const SizedBox(width: 3),
                    Text(r.rating.toStringAsFixed(1),
                        style: const TextStyle(color: inkFaint, fontSize: 12)),
                    const SizedBox(width: 12),
                    const Icon(Icons.currency_rupee, color: inkFaint, size: 13),
                    Text('${r.price}',
                        style: const TextStyle(color: inkFaint, fontSize: 12)),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBadge(String text, Color textColor, Color bgColor) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: textColor.withOpacity(0.35)),
      ),
      child: Text(text,
          style:
          TextStyle(color: textColor, fontSize: 10, fontWeight: FontWeight.w600)),
    );
  }

  Widget _buildRiderCard() {
    final showRider = _stage.index >= TrackStage.pickedUp.index;
    return AnimatedOpacity(
      opacity: showRider ? 1 : 0.4,
      duration: const Duration(milliseconds: 400),
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: cardBg,
          borderRadius: BorderRadius.circular(20),
          border: Border.all(color: cardBorder),
        ),
        child: Row(
          children: [
            Container(
              width: 46,
              height: 46,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Colors.white,
                border: Border.all(color: primary, width: 1.5),
              ),
              child: const Center(
                child: Text('RK',
                    style: TextStyle(
                        color: primary, fontWeight: FontWeight.bold, fontSize: 14)),
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text('Ravi Kumar',
                      style: TextStyle(
                          color: ink, fontWeight: FontWeight.w600, fontSize: 14)),
                  Text(
                    showRider
                        ? 'Your delivery partner · TN 07 AX 4521'
                        : 'Will be assigned once picked up',
                    style: const TextStyle(color: inkFaint, fontSize: 12),
                  ),
                ],
              ),
            ),
            _buildCircleIcon(Icons.call_outlined),
            const SizedBox(width: 8),
            _buildCircleIcon(Icons.chat_bubble_outline),
          ],
        ),
      ),
    );
  }

  Widget _buildCircleIcon(IconData icon) {
    return Container(
      padding: const EdgeInsets.all(9),
      decoration: BoxDecoration(
        color: Colors.white,
        shape: BoxShape.circle,
        border: Border.all(color: primary.withOpacity(0.5)),
      ),
      child: Icon(icon, color: primary, size: 16),
    );
  }

  Widget _buildOrderSummary() {
    const deliveryFee = 25;
    final total = _chosen.price + deliveryFee;
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: cardBg,
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: cardBorder),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text('Order Summary',
              style: TextStyle(
                  color: ink, fontWeight: FontWeight.bold, fontSize: 15)),
          const SizedBox(height: 14),
          Row(
            children: [
              Text(_chosen.emoji, style: const TextStyle(fontSize: 20)),
              const SizedBox(width: 10),
              Expanded(
                child: Text(widget.dishName,
                    style: const TextStyle(color: ink, fontSize: 13)),
              ),
              Text('\u20b9${_chosen.price}',
                  style: const TextStyle(color: inkFaint, fontSize: 13)),
            ],
          ),
          const SizedBox(height: 10),
          Row(
            children: [
              const Expanded(
                  child: Text('Delivery fee',
                      style: TextStyle(color: inkFaint, fontSize: 13))),
              Text('\u20b9$deliveryFee',
                  style: const TextStyle(color: inkFaint, fontSize: 13)),
            ],
          ),
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 12),
            child: Divider(color: cardBorder, height: 1),
          ),
          Row(
            children: [
              const Expanded(
                  child: Text('Total',
                      style: TextStyle(
                          color: ink, fontWeight: FontWeight.bold, fontSize: 15))),
              Text('\u20b9$total',
                  style: const TextStyle(
                      color: primary, fontWeight: FontWeight.bold, fontSize: 16)),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildBottomBar() {
    return SafeArea(
      child: Container(
        decoration: const BoxDecoration(
          color: Colors.white,
          border: Border(top: BorderSide(color: cardBorder)),
        ),
        padding: const EdgeInsets.fromLTRB(20, 12, 20, 12),
        child: Row(
          children: [
            Expanded(
              child: OutlinedButton.icon(
                onPressed: () {},
                icon: const Icon(Icons.support_agent, color: inkFaint, size: 18),
                label: const Text('Need help', style: TextStyle(color: inkFaint)),
                style: OutlinedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 14),
                  side: const BorderSide(color: cardBorder),
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(16)),
                ),
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: ElevatedButton.icon(
                onPressed: () {},
                icon: const Icon(Icons.call, size: 18),
                label: Text(_delivered ? 'Rate order' : 'Call rider'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: primary,
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(vertical: 14),
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(16)),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _DashedLinePainter extends CustomPainter {
  final Color color;
  const _DashedLinePainter({required this.color});

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = color
      ..strokeWidth = 2;
    const dashWidth = 6.0;
    const dashSpace = 5.0;
    double startX = 20;
    final endX = size.width - 20;
    while (startX < endX) {
      canvas.drawLine(
          Offset(startX, size.height / 2),
          Offset(math.min(startX + dashWidth, endX), size.height / 2),
          paint);
      startX += dashWidth + dashSpace;
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}



class _AiRing extends StatefulWidget {
  final double progress; // 0–100
  final Color primary;
  final Widget Function(double) centerBuilder;

  const _AiRing({
    required this.progress,
    required this.primary,
    required this.centerBuilder,
  });

  @override
  State<_AiRing> createState() => _AiRingState();
}

class _AiRingState extends State<_AiRing> with TickerProviderStateMixin {
  late final AnimationController _pulseController;
  late final AnimationController _rotateController;

  @override
  void initState() {
    super.initState();
    _pulseController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
    )..repeat(reverse: true);

    _rotateController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 6),
    )..repeat();
  }

  @override
  void dispose() {
    _pulseController.dispose();
    _rotateController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return TweenAnimationBuilder<double>(
      tween: Tween(begin: 0, end: widget.progress),
      duration: const Duration(milliseconds: 900),
      curve: Curves.easeOutCubic,
      builder: (context, animatedValue, _) {
        return AnimatedBuilder(
          animation: Listenable.merge([_pulseController, _rotateController]),
          builder: (context, _) {
            final glow = 0.35 + (_pulseController.value * 0.25);
            return SizedBox(
              width: 260,
              height: 260,
              child: Stack(
                alignment: Alignment.center,
                children: [
                  // Soft pulsing halo
                  Container(
                    width: 260,
                    height: 260,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,

                    ),
                  ),
                  // Slowly rotating gradient ring
                  Transform.rotate(
                    angle: _rotateController.value * 2 * math.pi,
                    child: CustomPaint(
                      size: const Size(260, 260),
                      painter: _RingPainter(
                        progress: animatedValue,
                        primary: widget.primary,
                      ),
                    ),
                  ),
                  widget.centerBuilder(animatedValue),
                ],
              ),
            );
          },
        );
      },
    );
  }
}

class _RingPainter extends CustomPainter {
  final double progress;
  final Color primary;

  _RingPainter({required this.progress, required this.primary});

  @override
  void paint(Canvas canvas, Size size) {
    final center = size.center(Offset.zero);
    final radius = size.width / 2 - 12;

    // Track
    final trackPaint = Paint()
      ..color = primary.withOpacity(0.08)
      ..strokeWidth = 10
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round;
    canvas.drawCircle(center, radius, trackPaint);

    final sweepAngle = 2 * math.pi * (progress / 100);
    final rect = Rect.fromCircle(center: center, radius: radius);

    final gradient = SweepGradient(
      startAngle: 0,
      endAngle: sweepAngle == 0 ? 0.001 : sweepAngle,
      colors: [
        primary.withOpacity(0.2),
        primary,
        Colors.pinkAccent.shade100,
        primary,
      ],
      stops: const [0.0, 0.4, 0.7, 1.0],
      transform: const GradientRotation(-math.pi / 2),
    );

    // Blurred glow pass
    final glowPaint = Paint()
      ..shader = gradient.createShader(rect)
      ..strokeWidth = 18
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round
      ..maskFilter = const MaskFilter.blur(BlurStyle.normal, 8);

    // Crisp pass on top
    final progressPaint = Paint()
      ..shader = gradient.createShader(rect)
      ..strokeWidth = 12
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round;

    canvas.drawArc(rect, -math.pi / 2, sweepAngle, false, glowPaint);
    canvas.drawArc(rect, -math.pi / 2, sweepAngle, false, progressPaint);

    // Leading "spark" dot
    if (progress > 0) {
      final dotAngle = -math.pi / 2 + sweepAngle;
      final dotOffset = Offset(
        center.dx + radius * math.cos(dotAngle),
        center.dy + radius * math.sin(dotAngle),
      );
      canvas.drawCircle(
        dotOffset,
        7,
        Paint()
          ..color = primary
          ..maskFilter = const MaskFilter.blur(BlurStyle.normal, 6),
      );
      canvas.drawCircle(dotOffset, 4, Paint()..color = Colors.white);
    }
  }

  @override
  bool shouldRepaint(covariant _RingPainter oldDelegate) {
    return oldDelegate.progress != progress || oldDelegate.primary != primary;
  }
}