import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../api_client.dart';
import '../widgets/payment_overview.dart';
import '../widgets/payment_bottom_sheet.dart' show showPaymentBottomSheet, showTransactionStatusDialog;

// ── Design tokens (design.json) ──────────────────────────────────────────────
class _Brand {
  static const bg = Color(0xFF0F1114);
  static const card = Color(0xFF21252D);
  static const amber = Color(0xFFFF9500);
  static const amberGlow = Color(0x33FF9500);
  static const textPrimary = Color(0xFFF2F2F2);
  static const textMuted = Color(0xFF8A8F99);
  static const divider = Color(0xFF2C3040);
  static const red = Color(0xFFFF4545);
  // Fuel service accent (design.json service_accent_colors.fuel)
  static const fuelAccent = Color(0xFF0A84FF);
  static const fuelGlow = Color(0x220A84FF);

  static const screenPadding = 20.0;
  static const sectionGap = 24.0;
  static const cardRadius = 16.0;
  static const buttonRadius = 12.0;
  static const inputRadius = 12.0;
  static const iconBadgeRadius = 9.0;
}

// ─────────────────────────────────────────────────────────────────────────────

class FuelFlowScreen extends StatefulWidget {
  const FuelFlowScreen({super.key, required this.onUnauthorized, this.onOrderCreated});

  final VoidCallback onUnauthorized;
  final VoidCallback? onOrderCreated;

  @override
  State<FuelFlowScreen> createState() => _FuelFlowScreenState();
}

class _FuelFlowScreenState extends State<FuelFlowScreen> {
  late Dio _dio;
  List<dynamic> _providers = [];
  List<dynamic> _addresses = [];
  Map? _config;
  int _step = 0;
  Map? _selectedProvider;
  Map? _selectedFuelType;
  int _liters = 1;
  String _carPlate = '';
  Map? _selectedAddress;
  Map? _user;
  int _pointsToUse = 0;
  bool _loading = false;
  String? _error;
  late final TextEditingController _litersController;
  late final TextEditingController _carPlateController;

  List<Map<String, dynamic>> get _fuelTypes {
    if (_selectedProvider == null) return [];
    final items = _selectedProvider!['items'] as List? ?? [];
    final list = <Map<String, dynamic>>[];
    for (final x in items) {
      if (x is! Map) continue;
      final m = Map<String, dynamic>.from(x);
      if ((m['item_type'] ?? 'fuel') == 'fuel') list.add(m);
    }
    return list;
  }

  double get _pricePerLiter => _selectedFuelType != null
      ? (double.tryParse(_selectedFuelType!['price'].toString()) ?? 0)
      : 0.0;

  @override
  void initState() {
    super.initState();
    _litersController = TextEditingController(text: '1');
    _carPlateController = TextEditingController();
    _dio = createApiClient(() => widget.onUnauthorized());
    _loadInitial();
  }

  @override
  void dispose() {
    _litersController.dispose();
    _carPlateController.dispose();
    super.dispose();
  }

  Future<void> _loadInitial() async {
    setState(() => _loading = true);
    try {
      final r = await Future.wait([
        _dio.get('/api/providers?type=fuel'),
        _dio.get('/api/addresses'),
        _dio.get('/api/config'),
        _dio.get('/api/auth/me'),
      ]);
      if (!mounted) return;
      setState(() {
        _providers = (r[0].data is Map && r[0].data['data'] is List) ? List.from(r[0].data['data'] as List) : [];
        _addresses = (r[1].data is Map && r[1].data['data'] is List) ? List.from(r[1].data['data'] as List) : [];
        _config = (r[2].data is Map && r[2].data['data'] != null) ? r[2].data['data'] as Map : null;
        _user = (r[3].data is Map && r[3].data['data'] != null) ? r[3].data['data'] as Map : null;
        _loading = false;
      });
    } catch (e) {
      if (e is DioException && e.response?.statusCode == 401) widget.onUnauthorized();
      if (mounted) setState(() => _loading = false);
    }
  }

  double get _serviceFee => (_config != null && _config!['service_fee'] != null) ? (double.tryParse(_config!['service_fee'].toString()) ?? 0) : 0;
  double get _deliveryFee => (_config != null && _config!['delivery_fee'] != null) ? (double.tryParse(_config!['delivery_fee'].toString()) ?? 0) : 0;
  double get _subtotal => _pricePerLiter * _liters;
  double get _total => _subtotal + _serviceFee + _deliveryFee;

  int get _pointsBalance =>
      (_user != null && _user!['points_balance'] != null)
          ? (int.tryParse(_user!['points_balance'].toString()) ?? 0)
          : 0;
  int get _maxRedeemablePoints {
    final totalInt = _total.floor();
    if (totalInt <= 0 || _pointsBalance <= 0) return 0;
    return totalInt.clamp(0, _pointsBalance);
  }
  double get _amountAfterPoints {
    final use = _pointsToUse.clamp(0, _maxRedeemablePoints);
    return (_total - use).clamp(0.0, double.infinity);
  }

  static const _totalSteps = 5; // Brand → Fuel type → (quantity in sheet) → Number plate → Address → Payment

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: _Brand.bg,
      appBar: AppBar(
        backgroundColor: _Brand.bg,
        elevation: 0,
        scrolledUnderElevation: 0,
        title: const Text(
          'FUEL',
          style: TextStyle(
            fontFamily: 'RobotoMono',
            fontSize: 15,
            fontWeight: FontWeight.w700,
            letterSpacing: 3,
            color: _Brand.textPrimary,
          ),
        ),
        leading: Padding(
          padding: const EdgeInsets.only(left: 12),
          child: GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Container(
              padding: const EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: _Brand.card,
                borderRadius: BorderRadius.circular(_Brand.iconBadgeRadius),
                border: Border.all(color: _Brand.divider),
              ),
              child: const Icon(
                Icons.arrow_back_ios_new,
                size: 13,
                color: _Brand.textMuted,
              ),
            ),
          ),
        ),
        leadingWidth: 56,
      ),
      body: _loading && _providers.isEmpty
          ? const Center(
              child: SizedBox(
                width: 32,
                height: 32,
                child: CircularProgressIndicator(
                  strokeWidth: 2.5,
                  valueColor: AlwaysStoppedAnimation(_Brand.amber),
                ),
              ),
            )
          : SingleChildScrollView(
              padding: const EdgeInsets.fromLTRB(
                _Brand.screenPadding,
                8,
                _Brand.screenPadding,
                40,
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  Text(
                    'STEP ${_step + 1} OF $_totalSteps',
                    style: const TextStyle(
                      fontSize: 10,
                      fontWeight: FontWeight.w700,
                      letterSpacing: 2.5,
                      color: _Brand.amber,
                    ),
                  ),
                  const SizedBox(height: 12),
                  if (_error != null) ...[
                    _ErrorBanner(_error!),
                    const SizedBox(height: _Brand.sectionGap),
                  ],
                  if (_step == 0) _buildProviderStep(),
                  if (_step == 1) _buildFuelTypeStep(),
                  if (_step == 2) _buildCarPlateStep(),
                  if (_step == 3) _buildAddressStep(),
                  if (_step == 4) _buildPaymentStep(),
                ],
              ),
            ),
    );
  }

  Widget _buildProviderStep() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        const _SectionLabel('SELECT FUEL BRAND'),
        const SizedBox(height: 12),
        ..._providers.map<Widget>((p) {
          final m = p is Map ? p : {};
          final name = m['name']?.toString() ?? '';
          final logoUrl = m['logo_url']?.toString();
          final selected = _selectedProvider == m;
          return Padding(
            padding: const EdgeInsets.only(bottom: 12),
            child: _SelectableTile(
              selected: selected,
              accentColor: _Brand.fuelAccent,
              glowColor: _Brand.fuelGlow,
              onTap: () => setState(() {
                _selectedProvider = m;
                _selectedFuelType = null;
              }),
              imageUrl: logoUrl != null && logoUrl.isNotEmpty ? logoUrl : null,
              leadingIcon: Icons.local_gas_station_rounded,
              title: name,
              subtitle: 'Next: choose fuel type & price',
            ),
          );
        }),
        const SizedBox(height: _Brand.sectionGap),
        _PrimaryButton(
          label: 'NEXT',
          onPressed: _selectedProvider == null ? null : () => setState(() => _step = 1),
        ),
      ],
    );
  }

  Widget _buildFuelTypeStep() {
    final types = _fuelTypes;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        const _SectionLabel('SELECT FUEL TYPE'),
        const SizedBox(height: 8),
        Text(
          '${_selectedProvider?['name'] ?? 'Brand'} — price per liter',
          style: TextStyle(color: _Brand.textMuted, fontSize: 12),
        ),
        const SizedBox(height: 12),
        if (types.isEmpty)
          const Text(
            'No fuel types for this brand. Add items under Providers.',
            style: TextStyle(color: _Brand.textMuted, fontSize: 13),
          )
        else
          ...types.map<Widget>((item) {
            final name = item['item_name']?.toString() ?? 'Fuel';
            final price = double.tryParse(item['price'].toString()) ?? 0;
            final selected = _selectedFuelType != null &&
                item['id'] == _selectedFuelType!['id'];
            return Padding(
              padding: const EdgeInsets.only(bottom: 10),
              child: InkWell(
                onTap: () => setState(() => _selectedFuelType = item),
                borderRadius: BorderRadius.circular(_Brand.cardRadius),
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
                  decoration: BoxDecoration(
                    color: _Brand.card,
                    borderRadius: BorderRadius.circular(_Brand.cardRadius),
                    border: Border.all(
                      color: selected ? _Brand.fuelAccent : _Brand.divider,
                      width: selected ? 1.5 : 1,
                    ),
                  ),
                  child: Row(
                    children: [
                      Icon(
                        selected ? Icons.check_circle : Icons.radio_button_unchecked,
                        color: selected ? _Brand.fuelAccent : _Brand.textMuted,
                        size: 22,
                      ),
                      const SizedBox(width: 12),
                      Expanded(
                        child: Text(
                          name,
                          style: const TextStyle(
                            color: _Brand.textPrimary,
                            fontSize: 15,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),
                      Text(
                        '${_fmt(price)} /L',
                        style: const TextStyle(
                          fontFamily: 'RobotoMono',
                          fontSize: 13,
                          fontWeight: FontWeight.w700,
                          color: _Brand.fuelAccent,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            );
          }),
        const SizedBox(height: _Brand.sectionGap),
        _PrimaryButton(
          label: 'NEXT',
          onPressed: types.isEmpty || _selectedFuelType == null
              ? null
              : () => _showQuantityBottomSheet(),
        ),
      ],
    );
  }

  void _showQuantityBottomSheet() {
    showModalBottomSheet<void>(
      context: context,
      isScrollControlled: true,
      backgroundColor: _Brand.card,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (ctx) => _FuelQuantitySheetContent(
        pricePerLiter: _pricePerLiter,
        initialLiters: _liters,
        fmt: _fmt,
        onConfirm: (liters) {
          Navigator.of(ctx).pop();
          setState(() {
            _liters = liters;
            _litersController.text = liters.toString();
            _step = 2;
          });
        },
      ),
    );
  }

  Widget _buildCarPlateStep() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        const _SectionLabel('CAR NUMBER PLATE'),
        const SizedBox(height: 8),
        Text(
          'So the driver can easily locate your vehicle',
          style: TextStyle(color: _Brand.textMuted, fontSize: 12),
        ),
        const SizedBox(height: 12),
        TextField(
          controller: _carPlateController,
          textCapitalization: TextCapitalization.characters,
          style: const TextStyle(
            fontFamily: 'RobotoMono',
            fontSize: 18,
            letterSpacing: 2,
            color: _Brand.textPrimary,
          ),
          decoration: InputDecoration(
            hintText: 'e.g. UAB 123A',
            hintStyle: TextStyle(color: _Brand.textMuted, fontSize: 16, letterSpacing: 2),
            filled: true,
            fillColor: _Brand.card,
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(_Brand.inputRadius),
              borderSide: const BorderSide(color: _Brand.divider),
            ),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(_Brand.inputRadius),
              borderSide: const BorderSide(color: _Brand.divider, width: 1.5),
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(_Brand.inputRadius),
              borderSide: const BorderSide(color: _Brand.amber, width: 1.5),
            ),
            contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
          ),
          onChanged: (v) => setState(() => _carPlate = v.trim()),
        ),
        const SizedBox(height: _Brand.sectionGap),
        _PrimaryButton(
          label: 'NEXT',
          onPressed: () => setState(() {
            _carPlate = _carPlateController.text.trim();
            _step = 3;
          }),
        ),
      ],
    );
  }

  Widget _buildAddressStep() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        const _SectionLabel('DELIVERY ADDRESS'),
        const SizedBox(height: 12),
        if (_addresses.isEmpty)
          const Text(
            'No addresses. Add one in Settings.',
            style: TextStyle(color: _Brand.textMuted, fontSize: 13),
          )
        else
          ..._addresses.map<Widget>((a) {
            final m = a is Map ? a : {};
            final selected = _selectedAddress == m;
            return Padding(
              padding: const EdgeInsets.only(bottom: 12),
              child: _SelectableTile(
                selected: selected,
                accentColor: _Brand.amber,
                glowColor: _Brand.amberGlow,
                onTap: () => setState(() => _selectedAddress = m),
                leading: Container(
                  width: 40,
                  height: 40,
                  decoration: BoxDecoration(
                    color: _Brand.amberGlow,
                    borderRadius: BorderRadius.circular(_Brand.iconBadgeRadius),
                    border: Border.all(color: _Brand.amber.withOpacity(0.35)),
                  ),
                  child: const Icon(Icons.location_on_rounded, color: _Brand.amber, size: 20),
                ),
                title: m['address_name']?.toString() ?? 'Saved location',
                subtitle: (m['plus_code']?.toString()?.isNotEmpty == true)
                    ? m['plus_code'].toString()
                    : '${m['latitude']}, ${m['longitude']}',
              ),
            );
          }),
        const SizedBox(height: _Brand.sectionGap),
        _PrimaryButton(
          label: 'NEXT',
          onPressed: _addresses.isEmpty || _selectedAddress == null ? null : () => setState(() => _step = 4),
        ),
      ],
    );
  }

  String get _fuelTypeName => _selectedFuelType != null
      ? (_selectedFuelType!['item_name']?.toString() ?? 'Fuel')
      : '';

  Widget _buildPaymentStep() {
    final addr = _selectedAddress != null
        ? (_selectedAddress!['address_name']?.toString() ??
            _selectedAddress!['plus_code']?.toString() ??
            '${_selectedAddress!['latitude']}, ${_selectedAddress!['longitude']}')
        : '';
    final svc = 'Fuel ${_selectedProvider?['name']} — $_fuelTypeName — $_liters L @ ${_fmt(_pricePerLiter)}/L';
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        const _SectionLabel('JAMBO POINTS'),
        const SizedBox(height: 12),
        PointsRedeemSection(
          pointsBalance: _pointsBalance,
          maxRedeemable: _maxRedeemablePoints,
          pointsToUse: _pointsToUse,
          totalUgx: _total,
          onChanged: (v) => setState(() => _pointsToUse = v),
        ),
        const SizedBox(height: _Brand.sectionGap),
        PaymentOverview(
          data: PaymentOverviewData(
            addressSummary: addr,
            serviceSummary: svc,
            subtotal: _subtotal,
            serviceFee: _serviceFee,
            deliveryFee: _deliveryFee,
            total: _amountAfterPoints,
            pointsDiscount: _pointsToUse.toDouble(),
            pointsUsed: _pointsToUse,
          ),
          onMakePayment: () => showPaymentBottomSheet(
            context,
            amount: _amountAfterPoints,
            dio: _dio,
            callbackBaseUrl: baseUrl,
            onSuccess: () {
              _createOrder().then((success) {
                if (!mounted) return;
                showTransactionStatusDialog(
                  context,
                  success: success,
                  onDone: () {
                    Navigator.pop(context, true);
                    widget.onOrderCreated?.call();
                  },
                );
              });
            },
          ),
          onCompleteOrder: _amountAfterPoints <= 0
              ? () {
                  _createOrder().then((success) {
                    if (!mounted) return;
                    showTransactionStatusDialog(
                      context,
                      success: success,
                      onDone: () {
                        Navigator.pop(context, true);
                        widget.onOrderCreated?.call();
                      },
                    );
                  });
                }
              : null,
        ),
      ],
    );
  }

  String _fmt(double v) {
    final parts = v.toStringAsFixed(0).split('');
    final buf = StringBuffer();
    for (int i = 0; i < parts.length; i++) {
      if (i > 0 && (parts.length - i) % 3 == 0) buf.write(',');
      buf.write(parts[i]);
    }
    return '${buf.toString()} UGX';
  }

  Future<bool> _createOrder() async {
    final inventoryId = _selectedFuelType != null ? _selectedFuelType!['id'] : null;
    if (inventoryId == null) return false;
    setState(() { _loading = true; _error = null; });
    try {
      await _dio.post('/api/orders', data: {
        'order_type': 'fuel',
        'location_id': _selectedAddress!['id'],
        'order_meta': {
          'inventory_id': inventoryId,
          'liters': _liters,
          if (_carPlate.isNotEmpty) 'car_plate': _carPlate,
        },
        'total_amount': _total,
        'points_used': _pointsToUse,
      });
      // Order created — always report success so dialog is correct even if setState fails
      if (!mounted) return false;
      try {
        if (mounted) setState(() => _loading = false);
      } catch (_) {}
      return true;
    } catch (e) {
      if (e is DioException && e.response?.statusCode == 401) widget.onUnauthorized();
      if (mounted) setState(() {
        _loading = false;
        _error = e is DioException ? (e.response?.data is Map ? e.response?.data['message']?.toString() : null) ?? 'Failed' : 'Failed';
      });
      return false;
    }
  }
}

// ── Quantity bottom sheet (owns controller, disposes on unmount; scrollable to avoid overflow)
class _FuelQuantitySheetContent extends StatefulWidget {
  const _FuelQuantitySheetContent({
    required this.pricePerLiter,
    required this.initialLiters,
    required this.fmt,
    required this.onConfirm,
  });
  final double pricePerLiter;
  final int initialLiters;
  final String Function(double) fmt;
  final void Function(int) onConfirm;

  @override
  State<_FuelQuantitySheetContent> createState() => _FuelQuantitySheetContentState();
}

class _FuelQuantitySheetContentState extends State<_FuelQuantitySheetContent> {
  late final TextEditingController _controller;
  late int _sheetLiters;
  static const _quickAmounts = [2, 3, 5, 10, 20, 50, 60];

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController(text: widget.initialLiters.toString());
    _sheetLiters = widget.initialLiters;
  }

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

  @override
  Widget build(BuildContext context) {
    final subtotal = widget.pricePerLiter * _sheetLiters;
    return Padding(
      padding: EdgeInsets.only(
        left: _Brand.screenPadding,
        right: _Brand.screenPadding,
        top: 20,
        bottom: MediaQuery.of(context).viewInsets.bottom + 24,
      ),
      child: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Text(
              'Quantity (liters)',
              style: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.w600,
                letterSpacing: 1.5,
                color: _Brand.textMuted,
              ),
            ),
            const SizedBox(height: 10),
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: _quickAmounts.map((q) {
                final selected = _sheetLiters == q;
                return ChoiceChip(
                  label: Text('$q L'),
                  selected: selected,
                  onSelected: (_) {
                    setState(() {
                      _sheetLiters = q;
                      _controller.text = '$q';
                    });
                  },
                  selectedColor: _Brand.fuelAccent.withOpacity(0.3),
                  side: BorderSide(
                    color: selected ? _Brand.fuelAccent : _Brand.divider,
                  ),
                );
              }).toList(),
            ),
            const SizedBox(height: 14),
            TextField(
              controller: _controller,
              keyboardType: TextInputType.number,
              style: const TextStyle(
                fontFamily: 'RobotoMono',
                fontSize: 18,
                letterSpacing: 2,
                color: _Brand.textPrimary,
              ),
              decoration: InputDecoration(
                hintText: 'Or enter liters',
                hintStyle: TextStyle(color: _Brand.textMuted),
                filled: true,
                fillColor: _Brand.bg,
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(_Brand.inputRadius),
                  borderSide: const BorderSide(color: _Brand.divider),
                ),
                contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
              ),
              inputFormatters: [FilteringTextInputFormatter.digitsOnly],
              onChanged: (v) {
                final n = int.tryParse(v) ?? 1;
                setState(() => _sheetLiters = n < 1 ? 1 : n);
              },
            ),
            const SizedBox(height: 16),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
              decoration: BoxDecoration(
                color: _Brand.fuelGlow,
                borderRadius: BorderRadius.circular(10),
                border: Border.all(color: _Brand.fuelAccent.withOpacity(0.3)),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '$_sheetLiters L × ${widget.fmt(widget.pricePerLiter)}',
                    style: const TextStyle(color: _Brand.textMuted, fontSize: 13),
                  ),
                  Text(
                    widget.fmt(subtotal),
                    style: const TextStyle(
                      fontFamily: 'RobotoMono',
                      fontSize: 16,
                      fontWeight: FontWeight.w700,
                      color: _Brand.fuelAccent,
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 20),
            SizedBox(
              height: 48,
              child: ElevatedButton(
                onPressed: () {
                  final n = int.tryParse(_controller.text) ?? 1;
                  widget.onConfirm(n < 1 ? 1 : n);
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: _Brand.fuelAccent,
                  foregroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(_Brand.buttonRadius),
                  ),
                ),
                child: const Text('CONFIRM QUANTITY'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// ── Section label (design.json) ───────────────────────────────────────────────
class _SectionLabel extends StatelessWidget {
  final String text;
  const _SectionLabel(this.text);

  @override
  Widget build(BuildContext context) {
    return Text(
      text,
      style: const TextStyle(
        fontSize: 10,
        fontWeight: FontWeight.w600,
        letterSpacing: 2.5,
        color: _Brand.textMuted,
      ),
    );
  }
}

// ── Error banner (design.json) ────────────────────────────────────────────────
class _ErrorBanner extends StatelessWidget {
  final String message;
  const _ErrorBanner(this.message);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
      decoration: BoxDecoration(
        color: _Brand.red.withOpacity(0.12),
        borderRadius: BorderRadius.circular(10),
        border: Border.all(color: _Brand.red.withOpacity(0.4)),
      ),
      child: Row(
        children: [
          const Icon(Icons.warning_amber_rounded, color: _Brand.red, size: 18),
          const SizedBox(width: 10),
          Expanded(
            child: Text(
              message,
              style: const TextStyle(color: _Brand.red, fontSize: 13, height: 1.4),
            ),
          ),
        ],
      ),
    );
  }
}

// ── Selectable tile (custom, no RadioListTile) ─────────────────────────────────
// When imageUrl is set: brand-card layout (icon left, title/subtitle, image right with round mask). No arrow.
// When leading is set: simple row (leading + title + subtitle).
class _SelectableTile extends StatelessWidget {
  final bool selected;
  final Color accentColor;
  final Color glowColor;
  final VoidCallback onTap;
  final Widget? leading;
  final String title;
  final String subtitle;
  final String? imageUrl;
  final IconData? leadingIcon;

  const _SelectableTile({
    required this.selected,
    required this.accentColor,
    required this.glowColor,
    required this.onTap,
    this.leading,
    required this.title,
    required this.subtitle,
    this.imageUrl,
    this.leadingIcon,
  });

  @override
  Widget build(BuildContext context) {
    final isBrandCard = imageUrl != null || leadingIcon != null;

    if (isBrandCard) {
      return GestureDetector(
        onTap: onTap,
        child: Container(
          height: 100,
          decoration: BoxDecoration(
            color: _Brand.card,
            borderRadius: BorderRadius.circular(18),
            border: Border.all(
              color: selected ? accentColor.withOpacity(0.4) : _Brand.divider,
              width: selected ? 1.5 : 1,
            ),
          ),
          clipBehavior: Clip.antiAlias,
          child: Row(
            children: [
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.all(18),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Row(
                        children: [
                          Container(
                            width: 36,
                            height: 36,
                            decoration: BoxDecoration(
                              color: glowColor,
                              borderRadius: BorderRadius.circular(9),
                              border: Border.all(color: accentColor.withOpacity(0.35)),
                            ),
                            child: Icon(leadingIcon ?? Icons.local_gas_station_rounded, color: accentColor, size: 18),
                          ),
                          const SizedBox(width: 12),
                          Expanded(
                            child: Text(
                              title,
                              style: const TextStyle(
                                color: _Brand.textPrimary,
                                fontSize: 16,
                                fontWeight: FontWeight.w700,
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 8),
                      Text(
                        subtitle,
                        style: const TextStyle(
                          color: _Brand.textMuted,
                          fontSize: 11,
                          fontFamily: 'RobotoMono',
                          height: 1.3,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ),
                ),
              ),
              SizedBox(
                width: 100,
                height: 100,
                child: ClipRRect(
                  borderRadius: const BorderRadius.only(
                    topRight: Radius.circular(18),
                    bottomRight: Radius.circular(18),
                  ),
                  child: Stack(
                    fit: StackFit.expand,
                    children: [
                      if (imageUrl != null && imageUrl!.isNotEmpty)
                        Image.network(
                          imageUrl!,
                          fit: BoxFit.cover,
                          errorBuilder: (_, __, ___) => _BrandImagePlaceholder(accentColor: accentColor, glowColor: glowColor, icon: leadingIcon ?? Icons.local_gas_station_rounded),
                        )
                      else
                        _BrandImagePlaceholder(accentColor: accentColor, glowColor: glowColor, icon: leadingIcon ?? Icons.local_gas_station_rounded),
                      DecoratedBox(
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            begin: Alignment.centerLeft,
                            end: Alignment.centerRight,
                            colors: [_Brand.card, _Brand.card.withOpacity(0)],
                            stops: const [0.0, 0.5],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      );
    }

    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.all(18),
        decoration: BoxDecoration(
          color: _Brand.card,
          borderRadius: BorderRadius.circular(_Brand.cardRadius),
          border: Border.all(
            color: selected ? accentColor.withOpacity(0.4) : _Brand.divider,
            width: selected ? 1.5 : 1,
          ),
        ),
        child: Row(
          children: [
            leading!,
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: const TextStyle(
                      color: _Brand.textPrimary,
                      fontSize: 15,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    subtitle,
                    style: const TextStyle(
                      color: _Brand.textMuted,
                      fontSize: 12,
                      fontFamily: 'RobotoMono',
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _BrandImagePlaceholder extends StatelessWidget {
  final Color accentColor;
  final Color glowColor;
  final IconData icon;

  const _BrandImagePlaceholder({required this.accentColor, required this.glowColor, required this.icon});

  @override
  Widget build(BuildContext context) {
    return Container(
      color: glowColor,
      child: Center(
        child: Opacity(
          opacity: 0.25,
          child: Icon(icon, color: accentColor, size: 48),
        ),
      ),
    );
  }
}

// ── Primary button (design.json primary_button) ───────────────────────────────
class _PrimaryButton extends StatelessWidget {
  final String label;
  final VoidCallback? onPressed;

  const _PrimaryButton({required this.label, required this.onPressed});

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 54,
      width: double.infinity,
      child: FilledButton(
        onPressed: onPressed,
        style: FilledButton.styleFrom(
          backgroundColor: onPressed == null ? _Brand.amber.withOpacity(0.4) : _Brand.amber,
          foregroundColor: Colors.black,
          elevation: 0,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(_Brand.buttonRadius),
          ),
        ),
        child: Text(
          label,
          style: const TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w800,
            letterSpacing: 2,
          ),
        ),
      ),
    );
  }
}
