import 'package:dio/dio.dart';
import 'package:flutter/material.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);
  // Gas service accent (design.json service_accent_colors.gas)
  static const gasAccent = Color(0xFFFF9500);
  static const gasGlow = Color(0x33FF9500);

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

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

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

  final VoidCallback onUnauthorized;
  final VoidCallback? onOrderCreated;

  @override
  State<GasFlowScreen> createState() => _GasFlowScreenState();
}

class _GasFlowScreenState extends State<GasFlowScreen> {
  late Dio _dio;
  List<dynamic> _providers = [];
  List<dynamic> _gasSizes = [];
  List<dynamic> _addresses = [];
  List<dynamic> _kitAddons = [];
  List<Map<String, dynamic>> _selectedKitAddons = [];
  Map? _config;
  int _step = 0;
  Map? _selectedProvider;
  String _refillOrKit = 'refill';
  Map? _selectedSize;
  Map? _selectedAddress;
  Map? _user;
  int _pointsToUse = 0;
  bool _loading = false;
  String? _error;

  int get _totalSteps => _refillOrKit == 'new_kit' ? 6 : 5;

  @override
  void initState() {
    super.initState();
    _dio = createApiClient(() => widget.onUnauthorized());
    _loadInitial();
  }

  Future<void> _loadInitial() async {
    setState(() => _loading = true);
    try {
      final r = await Future.wait([
        _dio.get('/api/providers?type=gas'),
        _dio.get('/api/addresses'),
        _dio.get('/api/config'),
        _dio.get('/api/gas-kit-addons'),
        _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;
        _kitAddons = (r[3].data is Map && r[3].data['data'] is List) ? List.from(r[3].data['data'] as List) : [];
        _user = (r[4].data is Map && r[4].data['data'] != null) ? r[4].data['data'] as Map : null;
        _loading = false;
      });
      if (_selectedProvider != null) _loadGasSizes();
    } catch (e) {
      if (e is DioException && e.response?.statusCode == 401) widget.onUnauthorized();
      if (mounted) setState(() => _loading = false);
    }
  }

  Future<void> _loadGasSizes() async {
    final pid = _selectedProvider != null ? (_selectedProvider!['id'] as int?) : null;
    try {
      final r = await _dio.get(pid != null ? '/api/gas-sizes?provider_id=$pid' : '/api/gas-sizes');
      if (mounted) setState(() {
        _gasSizes = (r.data is Map && r.data['data'] is List) ? List.from(r.data['data'] as List) : [];
      });
    } catch (_) {}
  }

  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;
  /// Refill uses [price]; New kit uses [price_kit] when set, otherwise falls back to [price].
  double get _cylinderPrice {
    if (_selectedSize == null) return 0;
    final refillPrice = double.tryParse(_selectedSize!['price'].toString()) ?? 0;
    if (_refillOrKit == 'refill') return refillPrice;
    final kitPrice = _selectedSize!['price_kit'];
    if (kitPrice != null) {
      final p = double.tryParse(kitPrice.toString());
      if (p != null && p > 0) return p;
    }
    return refillPrice;
  }
  double get _kitAddonsTotal => _selectedKitAddons.fold(0.0, (s, a) => s + (double.tryParse(a['price'].toString()) ?? 0));
  double get _subtotal => _cylinderPrice + _kitAddonsTotal;
  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);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: _Brand.bg,
      appBar: AppBar(
        backgroundColor: _Brand.bg,
        elevation: 0,
        scrolledUnderElevation: 0,
        title: const Text(
          'GAS',
          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) _buildRefillStep(),
                  if (_step == 2) _buildSizeStep(),
                  if (_step == 3 && _refillOrKit == 'new_kit') _buildKitAddonsStep(),
                  if (_step == 3 && _refillOrKit == 'refill') _buildAddressStep(),
                  if (_step == 4 && _refillOrKit == 'new_kit') _buildAddressStep(),
                  if (_step == 4 && _refillOrKit == 'refill') _buildPaymentStep(),
                  if (_step == 5) _buildPaymentStep(),
                ],
              ),
            ),
    );
  }

  Widget _buildProviderStep() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        const _SectionLabel('SELECT GAS 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.gasAccent,
              glowColor: _Brand.gasGlow,
              onTap: () {
                setState(() {
                  _selectedProvider = m;
                  _gasSizes = [];
                });
                _loadGasSizes();
              },
              imageUrl: logoUrl != null && logoUrl.isNotEmpty ? logoUrl : null,
              leadingIcon: Icons.propane_tank_rounded,
              title: name,
              subtitle: 'Cylinder delivery',
            ),
          );
        }),
        const SizedBox(height: _Brand.sectionGap),
        _PrimaryButton(
          label: 'NEXT',
          onPressed: _selectedProvider == null ? null : () => setState(() => _step = 1),
        ),
      ],
    );
  }

  Widget _buildRefillStep() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        const _SectionLabel('REFILL OR NEW KIT'),
        const SizedBox(height: 12),
        Padding(
          padding: const EdgeInsets.only(bottom: 12),
          child: _SelectableTile(
            selected: _refillOrKit == 'refill',
            accentColor: _Brand.amber,
            glowColor: _Brand.amberGlow,
            onTap: () => setState(() => _refillOrKit = 'refill'),
            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.replay_rounded, color: _Brand.amber, size: 20),
            ),
            title: 'Refill',
            subtitle: 'Refill your existing cylinder',
          ),
        ),
        Padding(
          padding: const EdgeInsets.only(bottom: 12),
          child: _SelectableTile(
            selected: _refillOrKit == 'new_kit',
            accentColor: _Brand.amber,
            glowColor: _Brand.amberGlow,
            onTap: () => setState(() => _refillOrKit = 'new_kit'),
            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.inventory_2_rounded, color: _Brand.amber, size: 20),
            ),
            title: 'New Kit',
            subtitle: 'New cylinder with regulator',
          ),
        ),
        const SizedBox(height: _Brand.sectionGap),
        _PrimaryButton(label: 'NEXT', onPressed: () => setState(() => _step = 2)),
      ],
    );
  }

  Widget _buildSizeStep() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        const _SectionLabel('SELECT GAS SIZE'),
        const SizedBox(height: 12),
        ..._gasSizes.map<Widget>((s) {
          final m = s is Map ? s : {};
          final refillPrice = double.tryParse(m['price'].toString()) ?? 0;
          final priceKitRaw = m['price_kit'];
          final kitPrice = priceKitRaw != null ? (double.tryParse(priceKitRaw.toString())) : null;
          final displayPrice = _refillOrKit == 'new_kit' && kitPrice != null && kitPrice > 0 ? kitPrice : refillPrice;
          final imageUrl = m['image_url']?.toString();
          final selected = _selectedSize == m;
          return Padding(
            padding: const EdgeInsets.only(bottom: 12),
            child: _SelectableTile(
              selected: selected,
              accentColor: _Brand.amber,
              glowColor: _Brand.amberGlow,
              onTap: () => setState(() => _selectedSize = m),
              leading: imageUrl != null && imageUrl.isNotEmpty
                  ? ClipRRect(
                      borderRadius: BorderRadius.circular(6),
                      child: Image.network(
                        imageUrl,
                        width: 48,
                        height: 48,
                        fit: BoxFit.cover,
                        errorBuilder: (_, __, ___) => Container(
                          width: 48,
                          height: 48,
                          decoration: BoxDecoration(
                            color: _Brand.amberGlow,
                            borderRadius: BorderRadius.circular(_Brand.iconBadgeRadius),
                            border: Border.all(color: _Brand.amber.withOpacity(0.35)),
                          ),
                          child: const Icon(Icons.propane_tank_rounded, color: _Brand.amber, size: 24),
                        ),
                      ),
                    )
                  : Container(
                      width: 48,
                      height: 48,
                      decoration: BoxDecoration(
                        color: _Brand.amberGlow,
                        borderRadius: BorderRadius.circular(_Brand.iconBadgeRadius),
                        border: Border.all(color: _Brand.amber.withOpacity(0.35)),
                      ),
                      child: const Icon(Icons.propane_tank_rounded, color: _Brand.amber, size: 24),
                    ),
              title: m['item_name']?.toString() ?? m['name']?.toString() ?? '',
              subtitle: '${_fmt(displayPrice)} UGX',
            ),
          );
        }),
        if (_gasSizes.isEmpty)
          const Text(
            'Loading sizes…',
            style: TextStyle(color: _Brand.textMuted, fontSize: 13),
          ),
        const SizedBox(height: _Brand.sectionGap),
        _PrimaryButton(
          label: 'NEXT',
          onPressed: _gasSizes.isEmpty || _selectedSize == null ? null : () => setState(() => _step = 3),
        ),
      ],
    );
  }

  Widget _buildKitAddonsStep() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        const Text('Select add-ons for your new kit'),
        const SizedBox(height: 8),
        Text(
          'Add gas cooker, hose, regulator, grill or burner (each has its price).',
          style: TextStyle(color: _Brand.textMuted, fontSize: 12),
        ),
        const SizedBox(height: 16),
        ..._kitAddons.map<Widget>((a) {
          final m = a is Map ? a as Map<String, dynamic> : <String, dynamic>{};
          final id = m['id'];
          final name = m['name']?.toString() ?? '';
          final price = double.tryParse(m['price'].toString()) ?? 0;
          final selected = _selectedKitAddons.any((s) => s['id'] == id);
          return Padding(
            padding: const EdgeInsets.only(bottom: 10),
            child: InkWell(
              onTap: () {
                setState(() {
                  if (selected) {
                    _selectedKitAddons.removeWhere((s) => s['id'] == id);
                  } else {
                    _selectedKitAddons.add({'id': id, 'name': name, 'price': price});
                  }
                });
              },
              borderRadius: BorderRadius.circular(12),
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
                decoration: BoxDecoration(
                  color: _Brand.card,
                  borderRadius: BorderRadius.circular(12),
                  border: Border.all(
                    color: selected ? _Brand.amber : _Brand.divider,
                    width: selected ? 1.5 : 1,
                  ),
                ),
                child: Row(
                  children: [
                    Icon(
                      selected ? Icons.check_circle : Icons.add_circle_outline,
                      color: selected ? _Brand.amber : _Brand.textMuted,
                      size: 22,
                    ),
                    const SizedBox(width: 12),
                    Expanded(child: Text(name, style: const TextStyle(color: _Brand.textPrimary, fontSize: 14))),
                    Text(
                      _fmt(price),
                      style: const TextStyle(
                        fontFamily: 'RobotoMono',
                        fontSize: 13,
                        fontWeight: FontWeight.w600,
                        color: _Brand.amber,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        }),
        if (_kitAddons.isEmpty)
          const Padding(
            padding: EdgeInsets.symmetric(vertical: 12),
            child: Text('No add-ons available. You can proceed without any.'),
          ),
        const SizedBox(height: _Brand.sectionGap),
        _PrimaryButton(
          label: 'NEXT',
          onPressed: () => setState(() => _step = 4),
        ),
      ],
    );
  }

  String get _sizeName => _selectedSize != null ? (_selectedSize!['item_name']?.toString() ?? _selectedSize!['name']?.toString() ?? '') : '';

  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';
  }

  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)
                    ? m['plus_code'].toString()
                    : '${m['latitude']}, ${m['longitude']}',
              ),
            );
          }),
        const SizedBox(height: _Brand.sectionGap),
        _PrimaryButton(
          label: 'NEXT',
          onPressed: _addresses.isEmpty || _selectedAddress == null
            ? null
            : () => setState(() => _step = _refillOrKit == 'new_kit' ? 5 : 4),
        ),
      ],
    );
  }

  Widget _buildPaymentStep() {
    final addr = _selectedAddress != null
        ? (_selectedAddress!['address_name']?.toString() ??
            _selectedAddress!['plus_code']?.toString() ??
            '${_selectedAddress!['latitude']}, ${_selectedAddress!['longitude']}')
        : '';
    final svc = 'Gas ${_selectedProvider?['name']} - $_sizeName ($_refillOrKit)';
    List<PaymentOverviewLineItem>? lineItems;
    if (_refillOrKit == 'new_kit' && (_cylinderPrice > 0 || _selectedKitAddons.isNotEmpty)) {
      lineItems = [
        PaymentOverviewLineItem(label: 'Cylinder $_sizeName', amount: _cylinderPrice),
        ..._selectedKitAddons.map((a) => PaymentOverviewLineItem(
          label: a['name']?.toString() ?? 'Add-on',
          amount: (double.tryParse(a['price'].toString()) ?? 0),
        )),
      ];
    }
    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,
            lineItems: lineItems,
          ),
          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,
        ),
      ],
    );
  }

  Future<bool> _createOrder() async {
    setState(() { _loading = true; _error = null; });
    try {
      final orderMeta = <String, dynamic>{
          'gas_size_id': _selectedSize!['id'],
          'refill_or_kit': _refillOrKit,
        };
        if (_refillOrKit == 'new_kit' && _selectedKitAddons.isNotEmpty) {
          orderMeta['kit_addons'] = _selectedKitAddons.map((a) => {
            'id': a['id'],
            'name': a['name'],
            'price': a['price'],
          }).toList();
        }
        await _dio.post('/api/orders', data: {
          'order_type': 'gas',
          'location_id': _selectedAddress!['id'],
          'order_meta': orderMeta,
          '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;
    }
  }
}

// ── 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.propane_tank_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.propane_tank_rounded),
                        )
                      else
                        _BrandImagePlaceholder(accentColor: accentColor, glowColor: glowColor, icon: leadingIcon ?? Icons.propane_tank_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,
          ),
        ),
      ),
    );
  }
}
