content: import 'dart:ui';
  
  import 'package:Satsails/helpers/asset_mapper.dart';
  import 'package:Satsails/helpers/bitcoin_formart_converter.dart';
  import 'package:Satsails/helpers/fiat_format_converter.dart';
  import 'package:Satsails/helpers/input_formatters/comma_text_input_formatter.dart';
  import 'package:Satsails/helpers/input_formatters/decimal_text_input_formatter.dart';
  import 'package:Satsails/helpers/string_extension.dart';
  import 'package:Satsails/providers/address_receive_provider.dart';
  import 'package:Satsails/providers/balance_provider.dart';
  import 'package:Satsails/providers/bitcoin_provider.dart';
  import 'package:Satsails/providers/currency_conversions_provider.dart';
  import 'package:Satsails/providers/liquid_provider.dart';
  import 'package:Satsails/providers/navigation_provider.dart';
  import 'package:Satsails/providers/send_tx_provider.dart';
  import 'package:Satsails/providers/settings_provider.dart';
  import 'package:Satsails/providers/sideswap_provider.dart';
  import 'package:Satsails/screens/shared/message_display.dart';
  import 'package:Satsails/screens/shared/transaction_modal.dart';
  import 'package:Satsails/translations/localizations.dart';
  import 'package:action_slider/action_slider.dart';
  import 'package:auto_size_text/auto_size_text.dart';
  import 'package:auto_size_text_field/auto_size_text_field.dart';
  import 'package:flutter/material.dart';
  import 'package:flutter_riverpod/flutter_riverpod.dart';
  import 'package:flutter_screenutil/flutter_screenutil.dart';
  import 'package:shimmer/shimmer.dart';
  
  enum SwapType {
    sideswapBtcToLbtc,
    sideswapLbtcToBtc,
    coinosLnToBTC,
    coinosLnToLBTC,
    coinosBtcToLn,
    coinosLbtcToLn,
    sideswapUsdtToLbtc,
    sideswapEuroxToLbtc,
    sideswapDepixToLbtc,
    sideswapLbtcToUsdt,
    sideswapLbtcToEurox,
    sideswapLbtcToDepix,
    sideswapEuroxToUsdt,
    sideswapUsdtToEurox,
    sideswapUsdtToDepix,
    sideswapDepixToUsdt,
  }
  
  const List<SwapType> fiatDisplayAllowedSwapTypes = [
    SwapType.sideswapLbtcToUsdt,
    SwapType.sideswapLbtcToEurox,
    SwapType.sideswapLbtcToDepix,
    SwapType.sideswapBtcToLbtc,
    SwapType.sideswapLbtcToBtc,
    SwapType.coinosLnToBTC,
    SwapType.coinosLnToLBTC,
    SwapType.coinosBtcToLn,
    SwapType.coinosLbtcToLn,
    SwapType.sideswapEuroxToUsdt,
    SwapType.sideswapUsdtToEurox,
    SwapType.sideswapUsdtToDepix,
    SwapType.sideswapDepixToUsdt,
  ];
  
  const List<String> fiatAssets = [
    'Liquid USDT',
    'Eurox',
    'Depix',
  ];
  
  
  List<String> getAssets(WidgetRef ref) {
    // this is hardcoded to false until we have spark
    final lightningAvailable = false; // Replace with actual logic to check if Lightning is available
  
    return [
      'Bitcoin',
      if (lightningAvailable) 'Lightning',
      'Liquid Bitcoin',
      'Liquid USDT',
      'Eurox',
      'Depix'
    ];
  }
  
  /// Helper widget for building a standard shimmer effect.
  Widget _buildShimmer({
    double width = double.infinity,
    double height = 20.0,
    double borderRadius = 8.0,
  }) {
    return Shimmer.fromColors(
      baseColor: Colors.grey[850]!,
      highlightColor: Colors.grey[700]!,
      child: Container(
        width: width,
        height: height,
        decoration: BoxDecoration(
          color: Colors.black.withOpacity(0.2),
          borderRadius: BorderRadius.circular(borderRadius),
        ),
      ),
    );
  }
  
  final swapTypeProvider = StateProvider.autoDispose<SwapType>((ref) {
    final fromAsset = ref.watch(fromAssetProvider);
    final toAsset = ref.watch(toAssetProvider);
    final combinedKey = '$fromAsset-$toAsset';
  
    switch (combinedKey) {
      case 'Bitcoin-Liquid Bitcoin':
        return SwapType.sideswapBtcToLbtc;
  
      case 'Liquid Bitcoin-Bitcoin':
        return SwapType.sideswapLbtcToBtc;
  
      case 'Lightning-Bitcoin':
        return SwapType.coinosLnToBTC;
  
      case 'Lightning-Liquid Bitcoin':
        return SwapType.coinosLnToLBTC;
  
      case 'Liquid USDT-Liquid Bitcoin':
        return SwapType.sideswapUsdtToLbtc;
  
      case 'Eurox-Liquid Bitcoin':
        return SwapType.sideswapEuroxToLbtc;
  
      case 'Depix-Liquid Bitcoin':
        return SwapType.sideswapDepixToLbtc;
  
      case 'Liquid Bitcoin-Liquid USDT':
        return SwapType.sideswapLbtcToUsdt;
  
      case 'Liquid Bitcoin-Eurox':
        return SwapType.sideswapLbtcToEurox;
  
      case 'Liquid Bitcoin-Depix':
        return SwapType.sideswapLbtcToDepix;
  
      case 'Liquid USDT-Depix':
        return SwapType.sideswapUsdtToDepix;
  
      case 'Depix-Liquid USDT':
        return SwapType.sideswapDepixToUsdt;
  
      case 'Eurox-Liquid USDT':
        return SwapType.sideswapEuroxToUsdt;
  
      case 'Liquid USDT-Eurox':
        return SwapType.sideswapUsdtToEurox;
  
      default:
        throw UnimplementedError('Swap type for $combinedKey is not supported.');
    }
  });
  
  class SwapTypeNotifier extends StateNotifier<void> {
    SwapTypeNotifier(this.ref) : super(null);
  
    final Ref ref;
  
    Future<void> updateProviders(SwapType? swapType) async {
      if (swapType == null) return;
  
      // Default settings for all swaps
      ref.read(inputInFiatProvider.notifier).state = false;
      ref.read(pegOutBlocksProvider.notifier).state = 2;
  
      switch (swapType) {
        case SwapType.sideswapUsdtToLbtc:
          ref.read(assetToSellProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.USD);
          ref.read(assetToPurchaseProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.LBTC);
          ref.read(sendTxProvider.notifier).updateAssetId(AssetMapper.reverseMapTicker(AssetId.USD));
          ref.read(sendBitcoinProvider.notifier).state = false;
          ref.read(fiatToFiatSwap.notifier).state = false;
          break;
  
        case SwapType.sideswapUsdtToDepix:
          ref.read(assetToSellProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.USD);
          ref.read(assetToPurchaseProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.BRL);
          ref.read(sendTxProvider.notifier).updateAssetId(AssetMapper.reverseMapTicker(AssetId.USD));
          ref.read(sendBitcoinProvider.notifier).state = false;
          ref.read(fiatToFiatSwap.notifier).state = true;
          break;
  
        case SwapType.sideswapUsdtToEurox:
          ref.read(assetToSellProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.USD);
          ref.read(assetToPurchaseProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.EUR);
          ref.read(sendTxProvider.notifier).updateAssetId(AssetMapper.reverseMapTicker(AssetId.USD));
          ref.read(sendBitcoinProvider.notifier).state = false;
          ref.read(fiatToFiatSwap.notifier).state = true;
          break;
  
        case SwapType.sideswapEuroxToLbtc:
          ref.read(assetToSellProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.EUR);
          ref.read(assetToPurchaseProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.LBTC);
          ref.read(sendTxProvider.notifier).updateAssetId(AssetMapper.reverseMapTicker(AssetId.EUR));
          ref.read(sendBitcoinProvider.notifier).state = false;
          ref.read(fiatToFiatSwap.notifier).state = false;
          break;
  
        case SwapType.sideswapEuroxToUsdt:
          ref.read(assetToSellProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.EUR);
          ref.read(assetToPurchaseProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.USD);
          ref.read(sendTxProvider.notifier).updateAssetId(AssetMapper.reverseMapTicker(AssetId.EUR));
          ref.read(sendBitcoinProvider.notifier).state = false;
          ref.read(fiatToFiatSwap.notifier).state = true;
          break;
  
        case SwapType.sideswapDepixToLbtc:
          ref.read(assetToSellProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.BRL);
          ref.read(assetToPurchaseProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.LBTC);
          ref.read(sendTxProvider.notifier).updateAssetId(AssetMapper.reverseMapTicker(AssetId.BRL));
          ref.read(sendBitcoinProvider.notifier).state = false;
          ref.read(fiatToFiatSwap.notifier).state = false;
          break;
  
        case SwapType.sideswapDepixToUsdt:
          ref.read(assetToSellProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.BRL);
          ref.read(assetToPurchaseProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.USD);
          ref.read(sendTxProvider.notifier).updateAssetId(AssetMapper.reverseMapTicker(AssetId.BRL));
          ref.read(sendBitcoinProvider.notifier).state = false;
          ref.read(fiatToFiatSwap.notifier).state = true;
          break;
  
        case SwapType.sideswapLbtcToUsdt:
          ref.read(assetToSellProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.LBTC);
          ref.read(assetToPurchaseProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.USD);
          ref.read(sendTxProvider.notifier).updateAssetId(AssetMapper.reverseMapTicker(AssetId.LBTC));
          ref.read(sendBitcoinProvider.notifier).state = true;
          ref.read(fiatToFiatSwap.notifier).state = false;
          break;
  
        case SwapType.sideswapLbtcToEurox:
          ref.read(assetToSellProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.LBTC);
          ref.read(assetToPurchaseProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.EUR);
          ref.read(sendTxProvider.notifier).updateAssetId(AssetMapper.reverseMapTicker(AssetId.LBTC));
          ref.read(sendBitcoinProvider.notifier).state = true;
          ref.read(fiatToFiatSwap.notifier).state = false;
          break;
  
        case SwapType.sideswapLbtcToDepix:
          ref.read(assetToSellProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.LBTC);
          ref.read(assetToPurchaseProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.BRL);
          ref.read(sendTxProvider.notifier).updateAssetId(AssetMapper.reverseMapTicker(AssetId.LBTC));
          ref.read(sendBitcoinProvider.notifier).state = true;
          ref.read(fiatToFiatSwap.notifier).state = false;
          break;
  
        case SwapType.sideswapBtcToLbtc:
          ref.read(assetToSellProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.LBTC);
          ref.read(assetToPurchaseProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.LBTC);
          ref.read(sendTxProvider.notifier).updateAssetId(AssetMapper.reverseMapTicker(AssetId.LBTC));
          ref.read(sendBitcoinProvider.notifier).state = true;
          ref.read(pegInProvider.notifier).state = true;
          ref.read(fiatToFiatSwap.notifier).state = false;
          final peg = await ref.read(sideswapPegProvider.future);
          ref.read(sendTxProvider.notifier).updateAddress(peg.pegAddr ?? ''); // Set peg address
          break;
  
        case SwapType.sideswapLbtcToBtc:
          ref.read(assetToSellProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.LBTC);
          ref.read(assetToPurchaseProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.LBTC);
          ref.read(sendTxProvider.notifier).updateAssetId(AssetMapper.reverseMapTicker(AssetId.LBTC));
          ref.read(sendBitcoinProvider.notifier).state = true;
          ref.read(pegInProvider.notifier).state = false;
          ref.read(fiatToFiatSwap.notifier).state = false;
          final peg = await ref.read(sideswapPegProvider.future);
          ref.read(sendTxProvider.notifier).updateAddress(peg.pegAddr ?? ''); // Set peg address
          break;
  
        case SwapType.coinosLnToBTC:
          ref.read(assetToSellProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.LBTC);
          ref.read(assetToPurchaseProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.LBTC);
          ref.read(sendTxProvider.notifier).updateAssetId(AssetMapper.reverseMapTicker(AssetId.LBTC));
          ref.read(sendBitcoinProvider.notifier).state = false;
          ref.read(fiatToFiatSwap.notifier).state = false;
          break;
  
        case SwapType.coinosLnToLBTC:
          ref.read(assetToSellProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.LBTC);
          ref.read(assetToPurchaseProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.LBTC);
          ref.read(sendTxProvider.notifier).updateAssetId(AssetMapper.reverseMapTicker(AssetId.LBTC));
          ref.read(sendBitcoinProvider.notifier).state = false;
          ref.read(fiatToFiatSwap.notifier).state = false;
          break;
  
        case SwapType.coinosBtcToLn:
          ref.read(assetToSellProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.LBTC);
          ref.read(assetToPurchaseProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.LBTC);
          ref.read(sendTxProvider.notifier).updateAssetId(AssetMapper.reverseMapTicker(AssetId.LBTC));
          ref.read(sendBitcoinProvider.notifier).state = true;
          ref.read(fiatToFiatSwap.notifier).state = false;
          break;
  
        case SwapType.coinosLbtcToLn:
          ref.read(assetToSellProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.LBTC);
          ref.read(assetToPurchaseProvider.notifier).state = AssetMapper.reverseMapTicker(AssetId.LBTC);
          ref.read(sendTxProvider.notifier).updateAssetId(AssetMapper.reverseMapTicker(AssetId.LBTC));
          ref.read(sendBitcoinProvider.notifier).state = true;
          ref.read(fiatToFiatSwap.notifier).state = false;
          break;
      }
    }
  }
  
  
  final swapTypeNotifierProvider = StateNotifierProvider.autoDispose<SwapTypeNotifier, void>((ref) {
    return SwapTypeNotifier(ref);
  });
  
  
  final balanceFromAssetProvider = StateProvider.autoDispose<String>((ref) {
    final fromAsset = ref.watch(swapTypeProvider);
    final balance = ref.watch(balanceNotifierProvider);
    final btcFormat = ref.watch(settingsProvider).btcFormat;
  
    switch (fromAsset) {
      case SwapType.sideswapBtcToLbtc:
      case SwapType.coinosBtcToLn:
        return btcInDenominationFormatted(balance.onChainBtcBalance, btcFormat);
      case SwapType.sideswapLbtcToBtc:
      case SwapType.coinosLbtcToLn:
      case SwapType.sideswapLbtcToDepix:
      case SwapType.sideswapLbtcToEurox:
      case SwapType.sideswapLbtcToUsdt:
        return btcInDenominationFormatted(balance.liquidBtcBalance, btcFormat);
      case SwapType.coinosLnToBTC:
      case SwapType.coinosLnToLBTC:
        return btcInDenominationFormatted(balance.sparkBitcoinbalance!.toInt(), btcFormat);
      case SwapType.sideswapUsdtToLbtc:
      case SwapType.sideswapUsdtToDepix:
      case SwapType.sideswapUsdtToEurox:
        return fiatInDenominationFormatted(balance.liquidUsdtBalance);
      case SwapType.sideswapEuroxToLbtc:
      case SwapType.sideswapEuroxToUsdt:
        return fiatInDenominationFormatted(balance.liquidEuroxBalance);
      case SwapType.sideswapDepixToLbtc:
      case SwapType.sideswapDepixToUsdt:
        return fiatInDenominationFormatted(balance.liquidDepixBalance);
      default:
        return '0';
    }
  });
  
  
  List<String> getAvailableSwaps(String asset, WidgetRef ref) {
    // this is hardcoded to false until we have spark
    final lightningAvailable = false;
  
    switch (asset) {
      case 'Bitcoin':
        return ['Liquid Bitcoin'];
      case 'Liquid Bitcoin':
        return ['Liquid USDT', 'Depix', 'Eurox', 'Bitcoin'];
      case 'Lightning':
        return [];
      case 'Liquid USDT':
        return ['Depix', 'Eurox', 'Liquid Bitcoin'];
      case 'Eurox':
        return ['Liquid USDT', 'Liquid Bitcoin'];
      case 'Depix':
        return ['Liquid USDT', 'Liquid Bitcoin'];
      default:
        return [];
    }
  }
  
  Widget getAssetImage(String? asset, {double? width, double? height}) {
    if (asset == null) return Container();
  
    switch (asset) {
      case 'Bitcoin':
        return Image.asset('lib/assets/bitcoin-logo.png', width: width ?? 28.0.sp, height: height ?? 28.0.sp);
      case 'Liquid Bitcoin':
      case 'L-BTC':
      case 'LBTC':
        return Image.asset('lib/assets/l-btc.png', width: width ?? 28.0.sp, height: height ?? 28.0.sp);
      case 'Liquid USDT':
      case 'USDT':
        return Image.asset('lib/assets/tether.png', width: width ?? 28.0.sp, height: height ?? 28.0.sp);
      case 'Eurox':
      case 'EUROX':
      case 'EURx':
        return Image.asset('lib/assets/eurx.png', width: width ?? 28.0.sp, height: height ?? 28.0.sp);
      case 'Depix':
      case 'DEPIX':
        return Image.asset('lib/assets/depix.png', width: width ?? 28.0.sp, height: height ?? 28.0.sp);
      case 'Lightning':
      case 'Lightning Bitcoin':
        return Image.asset('lib/assets/Bitcoin_lightning_logo.png', width: width ?? 28.0.sp, height: height ?? 28.0.sp);
      default:
        return Image.asset('lib/assets/bitcoin-logo.png', width: width ?? 28.0.sp, height: height ?? 28.0.sp);
    }
  }
  
  final transactionInProgressProvider = StateProvider.autoDispose<bool>((ref) => false);
  final fromAssetProvider = StateProvider.autoDispose<String>((ref) => 'Liquid Bitcoin');
  final fiatToFiatSwap = StateProvider<bool>((ref) =>  true);
  final toAssetProvider = StateProvider.autoDispose<String>((ref) => 'Bitcoin');
  final inputInFiatProvider = StateProvider.autoDispose<bool>((ref) => false);
  final bitcoinReceiveSpeedProvider = StateProvider.autoDispose<String>((ref) => 'Fastest');
  final precisionFiatValueProvider = StateProvider.autoDispose<String>((ref) => "0.00");
  final pegFee = StateProvider.autoDispose<String>((ref) => "0");
  final networkFee = StateProvider.autoDispose<String>((ref) => "0");
  final providerFee = StateProvider.autoDispose<String>((ref) => "0");
  
  Widget bitcoinFeeSlider(WidgetRef ref) {
    final feeRateAsyncValue = ref.watch(bitcoinFeeRatePerBlockProvider);
    final selectedBlockTarget = ref.watch(sendBlocksProvider);
  
    // Maps the slider's discrete value (0.0 to 4.0) to a block target (1 to 5)
    double sliderValueToBlockTarget(double value) {
      return 5 - value;
    }
  
    // Maps the block target (1 to 5) to the slider's value (0.0 to 4.0)
    double blockTargetToSliderValue(int blockTarget) {
      return (5 - blockTarget).toDouble();
    }
  
    return feeRateAsyncValue.when(
      data: (feeRate) {
        // Determine the current fee rate and label based on the selected block target
        String currentLabel = '';
        double currentFee = 0;
  
        switch (selectedBlockTarget) {
          case 1:
            currentLabel = '~10 min'.i18n;
            currentFee = feeRate.fastestFee;
            break;
          case 2:
            currentLabel = '~30 min'.i18n;
            currentFee = feeRate.halfHourFee;
            break;
          case 3:
            currentLabel = '~60 min'.i18n;
            currentFee = feeRate.hourFee;
            break;
          case 4:
            currentLabel = '~24 H'.i18n;
            currentFee = feeRate.economyFee;
            break;
          case 5:
            currentLabel = 'Weeks'.i18n;
            currentFee = feeRate.minimumFee;
            break;
        }
  
        return Column(
          children: [
            // Header row with title and current fee/label
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Flexible(
                  child: Text(
                    '$currentLabel: $currentFee sat/vB',
                    textAlign: TextAlign.end,
                    style: TextStyle(
                      color: Colors.white.withOpacity(0.8),
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ],
            ),
            SliderTheme(
              data: SliderThemeData(
                trackHeight: 8.h,
                activeTrackColor: Colors.orangeAccent,
                inactiveTrackColor: Colors.white.withOpacity(0.2),
                thumbColor: Colors.white,
                overlayColor: Colors.orangeAccent.withOpacity(0.2),
                thumbShape:
                RoundSliderThumbShape(enabledThumbRadius: 10.r),
                overlayShape:
                RoundSliderOverlayShape(overlayRadius: 20.r),
                trackShape: const RoundedRectSliderTrackShape(),
              ),
              child: Slider(
                value: blockTargetToSliderValue(selectedBlockTarget.toInt()),
                min: 0,
                max: 4,
                divisions: 4,
                onChanged: (value) {
                  ref.read(sendBlocksProvider.notifier).state =
                      sliderValueToBlockTarget(value);
                },
              ),
            ),
  
            // Labels for the slider ends
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 8.w),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    'Slow'.i18n,
                    style: TextStyle(
                        color: Colors.white70, fontSize: 13.sp),
                  ),
                  Text(
                    'Fast'.i18n,
                    style: TextStyle(
                        color: Colors.white70, fontSize: 13.sp),
                  ),
                ],
              ),
            ),
          ],
        );
      },
      loading: () => Center(
        child: _buildShimmer(height: 100.h, width: double.infinity),
      ),
      error: (e, _) => Text(
        'Error loading fees'.i18n,
        style: TextStyle(color: Colors.redAccent, fontSize: 14.sp),
      ),
    );
  }
  
  Widget buildBalanceCardWithSlider(WidgetRef ref, TextEditingController controller, BuildContext context) {
    final balanceString = ref.watch(balanceFromAssetProvider);
    final swapType = ref.watch(swapTypeProvider);
    final btcFormat = ref.watch(settingsProvider).btcFormat;
    final balanceState = ref.watch(balanceNotifierProvider);
    final fromAsset = ref.watch(fromAssetProvider);
    final currentAmount = ref.watch(sendTxProvider).amount;
  
    // Determine the raw maximum balance in the smallest unit (sats/cents)
    int maxBalance;
    switch (swapType) {
      case SwapType.sideswapBtcToLbtc:
      case SwapType.coinosBtcToLn:
        maxBalance = balanceState.onChainBtcBalance;
        break;
      case SwapType.sideswapLbtcToBtc:
      case SwapType.coinosLbtcToLn:
      case SwapType.sideswapLbtcToDepix:
      case SwapType.sideswapLbtcToEurox:
      case SwapType.sideswapLbtcToUsdt:
        maxBalance = balanceState.liquidBtcBalance;
        break;
      case SwapType.coinosLnToBTC:
      case SwapType.coinosLnToLBTC:
        maxBalance = balanceState.sparkBitcoinbalance?.toInt() ?? 0;
        break;
      case SwapType.sideswapUsdtToLbtc:
      case SwapType.sideswapUsdtToDepix:
      case SwapType.sideswapUsdtToEurox:
        maxBalance = balanceState.liquidUsdtBalance;
        break;
      case SwapType.sideswapEuroxToLbtc:
      case SwapType.sideswapEuroxToUsdt:
        maxBalance = balanceState.liquidEuroxBalance;
        break;
      case SwapType.sideswapDepixToLbtc:
      case SwapType.sideswapDepixToUsdt:
        maxBalance = balanceState.liquidDepixBalance;
        break;
      default:
        maxBalance = 0;
    }
  
    // Ensure slider doesn't crash if maxBalance is 0
    final sliderMax = maxBalance > 0 ? maxBalance.toDouble() : 1.0;
  
    final percentage = maxBalance > 0 ? (currentAmount / maxBalance * 100) : 0.0;
  
    return Padding(
      padding: EdgeInsets.only(top: 8.0.w),
      child: Card(
        color: const Color(0x00333333).withOpacity(0.4),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.r)),
        elevation: 4,
        child: Padding(
          padding: EdgeInsets.fromLTRB(16.w, 12.h, 16.w, 8.h),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'Available Balance'.i18n,
                        style: TextStyle(
                          color: Colors.grey,
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      SizedBox(height: 4.h),
                      AutoSizeText(
                        balanceString,
                        maxLines: 1,
                        minFontSize: 16,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 22.sp,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                  ElevatedButton(
                    onPressed: () async {
                      await handleMaxButtonPress(ref, swapType, controller, btcFormat);
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.white,
                      // You can now control the height with vertical padding
                      padding: EdgeInsets.symmetric(horizontal: 16.sp, vertical: 6.sp),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8.r),
                      ),
                      elevation: 4,
                      minimumSize: Size.zero,
                      tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                    ),
                    child: Text(
                      'Max',
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 16.sp,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ],
              ),
              SizedBox(height: 4.h),
              SliderTheme(
                data: SliderTheme.of(context).copyWith(
                  trackHeight: 6.h,
                  activeTrackColor: Colors.white,
                  inactiveTrackColor: Colors.white.withOpacity(0.3),
                  thumbColor: Colors.white,
                  overlayColor: Colors.white.withOpacity(0.2),
                  thumbShape: RoundSliderThumbShape(enabledThumbRadius: 8.r),
                  overlayShape: RoundSliderOverlayShape(overlayRadius: 16.r),
                  valueIndicatorColor: Colors.white, // Tooltip background color
                  valueIndicatorTextStyle: TextStyle(
                    color: Colors.black, // Tooltip text color
                    fontSize: 14.sp,
                  ),
                ),
                child: Slider(
                  value: currentAmount.toDouble().clamp(0.0, sliderMax),
                  min: 0,
                  max: sliderMax,
                  divisions: maxBalance > 0 ? 100 : null,
                  label: '${percentage.toStringAsFixed(0)}%',
                  onChanged: maxBalance == 0
                      ? null // Disable slider if there's no balance
                      : (newValue) {
                    final isFiat = fiatAssets.contains(fromAsset);
                    if (isFiat) {
                      controller.text = fiatInDenominationFormatted(newValue.toInt());
                    } else {
                      controller.text = btcInDenominationFormatted(newValue, btcFormat);
                    }
                    ref.read(sendTxProvider.notifier).updateDrain(false);
                    ref.read(sendTxProvider.notifier).updateAmountFromInput(controller.text, btcFormat);
                  },
                  onChangeEnd: (finalValue) {
                    if (maxBalance > 0 && finalValue.round() >= maxBalance) {
                      handleMaxButtonPress(ref, swapType, controller, btcFormat);
                    }
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
  
  
  Future<void> handleMaxButtonPress(
      WidgetRef ref,
      SwapType swapType,
      TextEditingController controller,
      String btcFormat,
      ) async {
    int balance;
  
    switch (swapType) {
      case SwapType.sideswapUsdtToLbtc:
      case SwapType.sideswapUsdtToDepix:
      case SwapType.sideswapUsdtToEurox:
        balance = ref.read(balanceNotifierProvider).liquidUsdtBalance;
        controller.text = fiatInDenominationFormatted(balance);
        ref.read(sendTxProvider.notifier).updateAssetId(AssetMapper.reverseMapTicker(AssetId.USD));
        ref.read(sendTxProvider.notifier).updateAmountFromInput(controller.text, btcFormat);
        ref.read(sendTxProvider.notifier).updateDrain(true);
        break;
  
      case SwapType.sideswapEuroxToLbtc:
      case SwapType.sideswapEuroxToUsdt:
        balance = ref.read(balanceNotifierProvider).liquidEuroxBalance;
        controller.text = fiatInDenominationFormatted(balance);
        ref.read(sendTxProvider.notifier).updateAssetId(AssetMapper.reverseMapTicker(AssetId.EUR));
        ref.read(sendTxProvider.notifier).updateAmountFromInput(controller.text, btcFormat);
        ref.read(sendTxProvider.notifier).updateDrain(true);
        break;
  
      case SwapType.sideswapDepixToLbtc:
      case SwapType.sideswapDepixToUsdt:
        balance = ref.read(balanceNotifierProvider).liquidDepixBalance;
        controller.text = fiatInDenominationFormatted(balance);
        ref.read(sendTxProvider.notifier).updateAssetId(AssetMapper.reverseMapTicker(AssetId.BRL));
        ref.read(sendTxProvider.notifier).updateAmountFromInput(controller.text, btcFormat);
        ref.read(sendTxProvider.notifier).updateDrain(true);
        break;
  
      case SwapType.sideswapLbtcToDepix:
      case SwapType.sideswapLbtcToEurox:
      case SwapType.sideswapLbtcToUsdt:
        balance = ref.read(balanceNotifierProvider).liquidBtcBalance;
        controller.text = btcInDenominationFormatted(balance.toDouble(), btcFormat);
        ref.read(inputInFiatProvider.notifier).state = false;
        ref.read(sendTxProvider.notifier).updateAssetId(AssetMapper.reverseMapTicker(AssetId.LBTC));
        ref.read(sendTxProvider.notifier).updateAmountFromInput(controller.text, btcFormat);
        ref.read(sendTxProvider.notifier).updateDrain(true);
        break;
  
      case SwapType.sideswapBtcToLbtc:
        await handlePegIn(ref, controller, btcFormat);
        break;
  
      case SwapType.sideswapLbtcToBtc:
        await handlePegOut(ref, controller, btcFormat);
        break;
      case SwapType.coinosLnToBTC:
        await handleLightningToAsset(ref, controller, btcFormat);
        break;
      case SwapType.coinosLnToLBTC:
        await handleLightningToAsset(ref, controller, btcFormat);
        break;
      default:
        throw UnsupportedError('Unsupported SwapType: $swapType');
    }
  }
  
  Future<void> handlePegIn(
      WidgetRef ref,
      TextEditingController controller,
      String btcFormat,
      ) async {
    final bitcoin = ref.watch(balanceNotifierProvider).onChainBtcBalance;
    ref.read(pegInProvider.notifier).state = true;
    final peg = await ref.watch(sideswapPegProvider.future);
  
    ref.read(inputInFiatProvider.notifier).state = false;
    ref.read(sendTxProvider.notifier).updateAddress(peg.pegAddr ?? '');
  
    final transactionBuilderParams = await ref
        .watch(bitcoinTransactionBuilderProvider(ref.watch(sendTxProvider).amount).future)
        .then((value) => value);
    final transaction = await ref
        .watch(buildDrainWalletBitcoinTransactionProvider(transactionBuilderParams).future)
        .then((value) => value);
  
    final fee = (transaction.$1.feeAmount() ?? BigInt.zero).toInt();
    final amountToSet = (bitcoin - fee);
  
    controller.text = btcInDenominationFormatted(amountToSet.toDouble(), btcFormat);
    ref.read(sendTxProvider.notifier).updateAmountFromInput(amountToSet.toString(), 'sats');
    ref.read(sendTxProvider.notifier).updateDrain(true);
  }
  
  Future<void> handlePegOut(
      WidgetRef ref,
      TextEditingController controller,
      String btcFormat,
      ) async {
    final liquid = ref.watch(balanceNotifierProvider).liquidBtcBalance;
    ref.read(pegInProvider.notifier).state = false;
    final peg = await ref.watch(sideswapPegProvider.future);
  
    ref.read(inputInFiatProvider.notifier).state = false;
    ref.read(sendTxProvider.notifier).updateAddress(peg.pegAddr ?? '');
  
    controller.text = btcInDenominationFormatted(liquid.toDouble(), btcFormat);
    ref.read(sendTxProvider.notifier).updateDrain(true);
    ref.read(sendTxProvider.notifier).updateAmountFromInput(controller.text, btcFormat);
  }
  
  Future<void> handleLightningToAsset(WidgetRef ref, TextEditingController controller, String btcFormat) async {
    ref.read(inputInFiatProvider.notifier).state = false;
    final balance = ref.read(balanceNotifierProvider).sparkBitcoinbalance;
    int maxAmount = (balance! * 0.995).toInt();
    controller.text = btcInDenominationFormatted(maxAmount, btcFormat);
    ref.read(sendTxProvider.notifier).updateAmountFromInput(controller.text, btcFormat);
  }
  
  void _showAdvancedOptionsSheet(BuildContext context, WidgetRef ref) {
    showModalBottomSheet(
      context: context,
      backgroundColor: const Color(0xFF212121), // Dark background
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20.r)),
      ),
      builder: (BuildContext context) {
        // Use a Consumer to access ref within the modal sheet's builder
        return SafeArea(
          bottom: true,
          child: Consumer(
            builder: (context, ref, child) {
              return SingleChildScrollView(
                child: Padding(
                  padding: EdgeInsets.all(20.w),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      Text(
                        'Transaction fees and limits'.i18n,
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 20.sp, // MODIFIED: Increased font size
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      SizedBox(height: 16.h),
                      // This was the content of the old ExpansionTile
                      Column(children: _getFeeRows(ref)),
                      SizedBox(height: 16.h),
                      // Also add the fee slider here
                      feeSelection(ref),
                      SizedBox(height: 20.h), // Some padding at the bottom
                    ],
                  ),
                ),
              );
            },
          ),
        );
      },
    );
  }
  
  Widget buildExchangeCard(BuildContext context, WidgetRef ref, TextEditingController controller) {
    final fromAsset = ref.watch(fromAssetProvider);
    final toAsset = ref.watch(toAssetProvider);
  
    return Card(
      color: const Color(0x00333333).withOpacity(0.4),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      elevation: 4,
      child: Padding(
        padding: EdgeInsets.all(12.0.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center, // Align items vertically
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'From Asset'.i18n,
                      style: TextStyle(color: Colors.grey, fontSize: 14.sp),
                    ),
                    SizedBox(height: 12.h),
                    DropdownButtonHideUnderline(
                      child: DropdownButton<String>(
                        value: fromAsset,
                        dropdownColor: const Color(0xFF212121),
                        borderRadius: const BorderRadius.all(Radius.circular(12.0)),
                        items: getAssets(ref)
                            .where((asset) => asset != toAsset)
                            .map((asset) => DropdownMenuItem(
                          value: asset,
                          child: Row(
                            children: [
                              getAssetImage(asset),
                              SizedBox(width: 8.w),
                              Text(
                                asset,
                                style: TextStyle(color: Colors.white, fontSize: 18.sp),
                              ),
                            ],
                          ),
                        ))
                            .toList(),
                        onChanged: (value) {
                          if (value != null) {
                            controller.text = '';
                            ref.read(sendTxProvider.notifier).resetToDefault();
                            ref.read(sendBlocksProvider.notifier).state = 1;
                            ref.read(fromAssetProvider.notifier).state = value;
                            final availableSwaps =
                            getAvailableSwaps(value, ref).where((swap) => swap != value).toList();
                            if (!availableSwaps.contains(toAsset)) {
                              ref.read(toAssetProvider.notifier).state = availableSwaps.first;
                            }
                            ref.read(swapTypeNotifierProvider.notifier).updateProviders(ref.watch(swapTypeProvider));
                          }
                        },
                        icon: Padding(
                          padding: EdgeInsets.only(left: 8.0.w),
                          child: Icon(
                            Icons.keyboard_arrow_down_sharp,
                            color: Colors.white,
                            size: 28.sp,
                          ),
                        ),
                        isDense: true,
                        style: TextStyle(color: Colors.white, fontSize: 18.sp),
                      ),
                    ),
                  ],
                ),
                Expanded(
                  child: Padding(
                    padding: EdgeInsets.only(left: 16.w),
                    child: assetLogic(ref, context, controller, receiveAsset: false),
                  ),
                ),
              ],
            ),
            SizedBox(height: 24.h),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 16.sp),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  const Expanded(
                    child: Divider(
                      color: Colors.grey,
                      thickness: 1,
                    ),
                  ),
                  SizedBox(width: 16.w),
                  GestureDetector(
                    onTap: () {
                      controller.text = '';
                      ref.read(sendTxProvider.notifier).resetToDefault();
                      ref.read(sendBlocksProvider.notifier).state = 1;
                      final temp = ref.read(fromAssetProvider);
                      ref.read(fromAssetProvider.notifier).state = ref.read(toAssetProvider);
                      ref.read(toAssetProvider.notifier).state = temp;
                      ref.read(swapTypeNotifierProvider.notifier).updateProviders(ref.watch(swapTypeProvider));
                    },
                    child: Container(
                      padding: EdgeInsets.all(8.w),
                      decoration: BoxDecoration(
                        color: Colors.grey.shade800,
                        shape: BoxShape.circle,
                      ),
                      child: Icon(
                        Icons.swap_vert,
                        color: Colors.white,
                        size: 24.sp,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(height: 24.h),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center, // Align items vertically
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'To Asset'.i18n,
                      style: TextStyle(color: Colors.grey, fontSize: 14.sp),
                    ),
                    SizedBox(height: 12.h),
                    DropdownButtonHideUnderline(
                      child: DropdownButton<String>(
                        value: toAsset,
                        dropdownColor: const Color(0xFF212121),
                        borderRadius: const BorderRadius.all(Radius.circular(12.0)),
                        items: getAvailableSwaps(fromAsset, ref)
                            .where((asset) => asset != fromAsset)
                            .map((asset) => DropdownMenuItem(
                          value: asset,
                          child: Row(
                            children: [
                              getAssetImage(asset),
                              SizedBox(width: 8.w),
                              Text(
                                asset,
                                style: TextStyle(color: Colors.white, fontSize: 18.sp),
                              ),
                            ],
                          ),
                        ))
                            .toList(),
                        onChanged: (value) {
                          if (value != null) {
                            ref.read(sendTxProvider.notifier).resetToDefault();
                            ref.read(sendBlocksProvider.notifier).state = 1;
                            controller.text = '';
                            ref.read(toAssetProvider.notifier).state = value;
                            final availableSwaps = getAssets(ref).where((swap) => swap != value).toList();
                            if (!availableSwaps.contains(fromAsset)) {
                              ref.read(fromAssetProvider.notifier).state = availableSwaps.first;
                            }
                            ref.read(swapTypeNotifierProvider.notifier).updateProviders(ref.watch(swapTypeProvider));
                          }
                        },
                        icon: Padding(
                          padding: EdgeInsets.only(left: 8.0.w),
                          child: Icon(
                            Icons.keyboard_arrow_down_sharp,
                            color: Colors.white,
                            size: 28.sp,
                          ),
                        ),
                        isDense: true,
                        style: TextStyle(color: Colors.white, fontSize: 18.sp),
                      ),
                    ),
                  ],
                ),
                Expanded(
                  child: Padding(
                    padding: EdgeInsets.only(left: 16.w),
                    child: assetLogic(ref, context, controller, receiveAsset: true),
                  ),
                ),
              ],
            ),
            SizedBox(height: 12.h),
            Center(
              child: TextButton(
                onPressed: () => _showAdvancedOptionsSheet(context, ref),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      'Transaction fees and limits'.i18n,
                      style: TextStyle(
                        color: Colors.grey,
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    Icon(Icons.keyboard_arrow_down_sharp,
                      color: Colors.grey,
                      size: 18.sp,
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  Widget assetLogic(
      WidgetRef ref,
      BuildContext context,
      TextEditingController controller, {
        bool receiveAsset = true,
      }) {
    final swapType = ref.watch(swapTypeProvider);
  
    // MODIFIED: Increased height from 85.0.h to 100.0.h for more vertical space.
    double widgetHeight = 100.0.h;
  
    Widget child;
    switch (swapType) {
      case SwapType.sideswapBtcToLbtc:
        child = buildBitcoinPeg(ref, receiveAsset, controller);
        break;
      case SwapType.sideswapLbtcToBtc:
        child = buildLiquidPeg(ref, receiveAsset, controller);
        break;
      case SwapType.coinosLnToBTC:
      case SwapType.coinosLnToLBTC:
        child = buildCoinosSwap(ref, context, controller, receiveAsset);
        break;
      case SwapType.coinosBtcToLn:
      case SwapType.coinosLbtcToLn:
        child = buildCoinosSwap(ref, context, controller, receiveAsset);
        break;
      case SwapType.sideswapUsdtToLbtc:
      case SwapType.sideswapEuroxToLbtc:
      case SwapType.sideswapDepixToLbtc:
      case SwapType.sideswapDepixToUsdt:
      case SwapType.sideswapUsdtToEurox:
      case SwapType.sideswapUsdtToDepix:
      case SwapType.sideswapEuroxToUsdt:
      case SwapType.sideswapLbtcToUsdt:
      case SwapType.sideswapLbtcToEurox:
      case SwapType.sideswapLbtcToDepix:
        child = buildSideswapInstantSwap(ref, context, controller, receiveAsset: receiveAsset);
        break;
      default:
        child = Container();
    }
  
    return SizedBox(
      height: widgetHeight,
      child: child,
    );
  }
  
  
  Widget buildCoinosSwap(
      WidgetRef ref,
      BuildContext context,
      TextEditingController controller,
      bool receiveAsset,
      ) {
    final btcFormat = ref.read(settingsProvider).btcFormat;
    final inputInFiat = ref.watch(inputInFiatProvider);
    final currency = ref.read(settingsProvider).currency;
    final currencyRate = ref.read(selectedCurrencyProvider(currency));
    final sideSwapStatus = ref.watch(sideswapStatusProvider);
  
    final valueToReceive = ref.watch(sendTxProvider).amount *
        (1 - (receiveAsset ? sideSwapStatus.serverFeePercentPegOut / 100 : 0.001));
  
    final formattedValueToReceive = btcInDenominationFormatted(valueToReceive, btcFormat);
    final formattedValueInBtc = btcInDenominationFormatted(valueToReceive, 'BTC');
    final valueInCurrency = currencyFormat(double.parse(formattedValueInBtc) * currencyRate, currency);
  
    return Column(
      crossAxisAlignment: CrossAxisAlignment.end,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        if (receiveAsset)
          if (double.parse(formattedValueToReceive) <= 0)
            AutoSizeText(
              "0",
              style: TextStyle(fontSize: 32.sp, color: Colors.grey),
              maxLines: 1,
            )
          else
            Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                AutoSizeText(
                  formattedValueToReceive,
                  style: TextStyle(fontSize: 32.sp, color: Colors.white),
                  maxLines: 1,
                  minFontSize: 18,
                ),
                SizedBox(height: 4.h),
                Text(
                  valueInCurrency,
                  style: TextStyle(fontSize: 16.sp, color: Colors.grey),
                ),
              ],
            )
        else
          Column(
            crossAxisAlignment: CrossAxisAlignment.end,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  DropdownButtonHideUnderline(
                    child: DropdownButton<String>(
                      value: inputInFiat ? currency : btcFormat,
                      dropdownColor: const Color(0xFF212121),
                      borderRadius: const BorderRadius.all(Radius.circular(12.0)),
                      items: [currency, btcFormat].map((option) {
                        return DropdownMenuItem(
                          value: option,
                          child: Text(
                            option.toUpperCase(),
                            style: TextStyle(color: Colors.white, fontSize: 16.sp),
                          ),
                        );
                      }).toList(),
                      onChanged: (newUnit) {
                        if (newUnit != null && newUnit != (inputInFiat ? currency : btcFormat)) {
                          final isSwitchingToFiat = newUnit == currency;
                          ref.read(inputInFiatProvider.notifier).state = isSwitchingToFiat;
                          if (isSwitchingToFiat) {
                            String fiatValue = calculateAmountInSelectedCurrency(
                              ref.watch(sendTxProvider).amount,
                              currency,
                              ref.watch(currencyNotifierProvider),
                            );
                            controller.text = double.parse(fiatValue) < 0.01
                                ? ''
                                : double.parse(fiatValue).toStringAsFixed(2);
                          } else {
                            String btcValue = btcInDenominationFormatted(
                              ref.watch(sendTxProvider).amount.toDouble(),
                              btcFormat,
                            );
                            controller.text = btcValue;
                          }
                        }
                      },
                      icon: Padding(
                        padding: EdgeInsets.only(left: 8.0.w),
                        child: const Icon(Icons.keyboard_arrow_down_sharp, color: Colors.white),
                      ),
                      isDense: true,
                      style: TextStyle(color: Colors.white, fontSize: 16.sp),
                    ),
                  ),
                ],
              ),
              AutoSizeTextField(
                controller: controller,
                keyboardType: const TextInputType.numberWithOptions(decimal: true),
                inputFormatters: inputInFiat
                    ? [
                  CommaTextInputFormatter(),
                  DecimalTextInputFormatter(decimalRange: 2, integerRange: 7),
                ]
                    : [
                  CommaTextInputFormatter(),
                  btcFormat == 'sats'
                      ? DecimalTextInputFormatter(decimalRange: 0)
                      : DecimalTextInputFormatter(decimalRange: 8, integerRange: 3),
                ],
                textAlign: TextAlign.right,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 32.sp,
                ),
                minFontSize: 18,
                maxLines: 1,
                decoration: InputDecoration(
                  border: InputBorder.none,
                  hintText: '0',
                  hintStyle: TextStyle(color: Colors.grey, fontSize: 32.sp),
                ),
                onChanged: (value) async {
                  if (inputInFiat) {
                    if (value.isEmpty) {
                      ref.read(sendTxProvider.notifier).updateAmountFromInput('0', btcFormat);
                      ref.read(sendTxProvider.notifier).updateDrain(false);
                    } else {
                      String send = btcFormat == 'sats'
                          ? calculateAmountToDisplayFromFiatInSats(
                        value,
                        currency,
                        ref.watch(currencyNotifierProvider),
                      )
                          : calculateAmountToDisplayFromFiat(
                        value,
                        currency,
                        ref.watch(currencyNotifierProvider),
                      );
                      ref.read(sendTxProvider.notifier).updateAmountFromInput(send, btcFormat);
                      ref.read(sendTxProvider.notifier).updateDrain(false);
                    }
                  } else {
                    if (value.isEmpty) {
                      ref.read(sendTxProvider.notifier).updateAmountFromInput('0', btcFormat);
                      ref.read(sendTxProvider.notifier).updateDrain(false);
                    } else {
                      ref.read(sendTxProvider.notifier).updateAmountFromInput(value, btcFormat);
                      ref.read(sendTxProvider.notifier).updateDrain(false);
                    }
                  }
                },
              ),
            ],
          ),
      ],
    );
  }
  
  Widget buildSideswapInstantSwap(
      WidgetRef ref,
      BuildContext context,
      TextEditingController controller, {
        bool receiveAsset = true,
      }) {
    final btcFormat = ref.read(settingsProvider).btcFormat;
    final currency = ref.read(settingsProvider).currency;
    final inputInFiat = ref.watch(inputInFiatProvider);
    final fromAsset = ref.watch(fromAssetProvider);
    final fiatToFiat = ref.watch(fiatToFiatSwap);
  
    String currentUnit = inputInFiat ? currency : btcFormat;
    List<String> options = fiatDisplayAllowedSwapTypes.contains(ref.watch(swapTypeProvider))
        ? [currency, btcFormat]
        : [];
  
    final quote = ref.watch(sideswapQuoteProvider);
  
    if (receiveAsset) {
      return Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          quote.status == 'Loading' || quote.status == 'Initial'
              ? Center(child: _buildShimmer(height: 40.h, width: 100.w))
              : _buildReceiveAmount(ref, quote),
        ],
      );
    } else {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.end,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          if (options.isNotEmpty && !fiatToFiat)
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                DropdownButtonHideUnderline(
                  child: DropdownButton<String>(
                    value: currentUnit,
                    dropdownColor: const Color(0xFF212121),
                    borderRadius: const BorderRadius.all(Radius.circular(12.0)),
                    items: options.map((option) {
                      return DropdownMenuItem(
                        value: option,
                        child: Text(
                          option.toUpperCase(),
                          style: TextStyle(color: Colors.white, fontSize: 16.sp),
                        ),
                      );
                    }).toList(),
                    onChanged: (newUnit) {
                      if (newUnit != null && newUnit != currentUnit) {
                        final isSwitchingToFiat = newUnit == currency;
                        ref.read(inputInFiatProvider.notifier).state = isSwitchingToFiat;
                        if (isSwitchingToFiat) {
                          String fiatValue = calculateAmountInSelectedCurrency(
                            ref.watch(sendTxProvider).amount,
                            currency,
                            ref.watch(currencyNotifierProvider),
                          );
                          controller.text = double.parse(fiatValue) < 0.01
                              ? ''
                              : double.parse(fiatValue).toStringAsFixed(2);
                        } else {
                          String btcValue = btcFormat == 'sats'
                              ? calculateAmountToDisplayFromFiatInSats(
                              controller.text, currency, ref.watch(currencyNotifierProvider))
                              : calculateAmountToDisplayFromFiat(
                              controller.text, currency, ref.watch(currencyNotifierProvider));
                          controller.text = btcFormat == 'sats'
                              ? btcInDenominationFormatted(double.parse(btcValue), btcFormat)
                              : btcValue;
                        }
                      }
                    },
                    icon: Padding(
                      padding: EdgeInsets.only(left: 8.0.w),
                      child: const Icon(Icons.keyboard_arrow_down_sharp, color: Colors.white),
                    ),
                    isDense: true,
                    style: TextStyle(color: Colors.white, fontSize: 16.sp),
                  ),
                ),
              ],
            )
          else
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Text(
                  fromAsset,
                  style: TextStyle(fontSize: 16.sp, color: Colors.grey),
                ),
              ],
            ),
          AutoSizeTextField(
            controller: controller,
            keyboardType: const TextInputType.numberWithOptions(decimal: true),
            inputFormatters: inputInFiat
                ? [CommaTextInputFormatter(), DecimalTextInputFormatter(decimalRange: 2, integerRange: 7)]
                : fiatAssets.contains(fromAsset)
                ? [CommaTextInputFormatter(), DecimalTextInputFormatter(decimalRange: 2, integerRange: 7)]
                : [
              CommaTextInputFormatter(),
              btcFormat == 'sats'
                  ? DecimalTextInputFormatter(decimalRange: 0)
                  : DecimalTextInputFormatter(decimalRange: 8, integerRange: 3),
            ],
            textAlign: TextAlign.right,
            style: TextStyle(
              color: Colors.white,
              fontSize: 32.sp,
            ),
            minFontSize: 18,
            maxLines: 1,
            decoration: InputDecoration(
              border: InputBorder.none,
              hintText: '0',
              hintStyle: TextStyle(color: Colors.grey, fontSize: 32.sp),
            ),
            onChanged: (value) async {
              if (inputInFiat) {
                if (value.isEmpty) {
                  ref.read(sendTxProvider.notifier).updateAmountFromInput('0', btcFormat);
                  ref.read(sendTxProvider.notifier).updateDrain(false);
                } else {
                  String send = btcFormat == 'sats'
                      ? calculateAmountToDisplayFromFiatInSats(
                      value, currency, ref.watch(currencyNotifierProvider))
                      : calculateAmountToDisplayFromFiat(
                      value, currency, ref.watch(currencyNotifierProvider));
                  ref.read(sendTxProvider.notifier).updateAmountFromInput(send, btcFormat);
                  ref.read(sendTxProvider.notifier).updateDrain(false);
                }
              } else {
                if (value.isEmpty) {
                  ref.read(sendTxProvider.notifier).updateAmountFromInput('0', btcFormat);
                  ref.read(sendTxProvider.notifier).updateDrain(false);
                } else {
                  ref.read(sendTxProvider.notifier).updateAmountFromInput(value, btcFormat);
                  ref.read(sendTxProvider.notifier).updateDrain(false);
                }
              }
            },
          ),
        ],
      );
    }
  }
  
  // Helper for buildSideswapInstantSwap to reduce complexity
  Widget _buildReceiveAmount(WidgetRef ref, dynamic quote) {
    final assetToSell = ref.watch(assetToSellProvider);
    final toAsset = ref.watch(toAssetProvider);
    final btcFormat = ref.read(settingsProvider).btcFormat;
    final currency = ref.read(settingsProvider).currency;
    final currencyRateFromBitcoin = ref.watch(selectedCurrencyProvider(currency));
  
    // FIX 1: Ensure all numbers from the quote are treated as doubles to prevent type errors.
    final amount = (assetToSell != quote.baseAsset ? quote.deliverAmount : quote.receiveAmount)?.toDouble() ?? 0.0;
    final quoteAmountForLowBalance = (assetToSell != quote.baseAsset ? quote.baseAmount : quote.quoteAmount)?.toDouble() ?? 0.0;
    final fixedFee = quote.fixedFee?.toDouble() ?? 0.0;
    final serverFee = quote.serverFee?.toDouble() ?? 0.0;
  
    // FIX 2: This logic now runs regardless of quote.status. This restores the ability
    // to show an estimated receive amount even if the input is zero.
    final quoteAmount = quote.status == 'LowBalance' ? quoteAmountForLowBalance : amount;
    double receiveAmount = quoteAmount - fixedFee - serverFee;
  
    // Prevent displaying a negative amount if fees are larger than the quote (e.g., for a 0 input).
    if (receiveAmount < 0) {
      receiveAmount = 0;
    }
  
    final formattedAmount = assetToSell != quote.baseAsset
        ? btcInDenominationFormatted(receiveAmount, btcFormat, !fiatAssets.contains(toAsset))
        : btcInDenominationFormatted(receiveAmount, btcFormat, false);
  
    final fiatValue = currencyFormat(
        (btcFormat == 'sats' ? (double.tryParse(formattedAmount.replaceAll(',', '')) ?? 0) / 100000000 : (double.tryParse(formattedAmount.replaceAll(',', '')) ?? 0)) * currencyRateFromBitcoin,
        currency
    );
  
    return Column(
      crossAxisAlignment: CrossAxisAlignment.end,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        AutoSizeText(
          formattedAmount,
          style: TextStyle(color: Colors.white, fontSize: 32.sp),
          maxLines: 1,
          minFontSize: 18,
        ),
        if (!fiatAssets.contains(toAsset)) ...[
          SizedBox(height: 4.h),
          Text(
            fiatValue,
            style: TextStyle(color: Colors.grey, fontSize: 16.sp),
          ),
        ],
        if (quote.status == 'LowBalance') ...[
          SizedBox(height: 4.h),
          Text(
            'Insufficient balance'.i18n,
            style: TextStyle(color: Colors.redAccent, fontSize: 14.sp),
          ),
        ]
      ],
    );
  }
  
  
  Widget buildLiquidPeg(WidgetRef ref, bool pegIn, TextEditingController controller) {
    final sideSwapStatus = ref.watch(sideswapStatusProvider);
    final valueToReceive = ref.watch(sendTxProvider).amount * (1 - sideSwapStatus.serverFeePercentPegOut / 100) - ref.watch(pegOutBitcoinCostProvider);
    final btcFormat = ref.watch(settingsProvider).btcFormat;
    final currency = ref.watch(settingsProvider).currency;
    final currencyRate = ref.read(selectedCurrencyProvider(currency));
    final formattedValueToReceive = btcInDenominationFormatted(valueToReceive, btcFormat);
    final sideSwapPeg = ref.watch(sideswapPegProvider);
    final formattedValueInBtc = btcInDenominationFormatted(valueToReceive, 'BTC');
    final valueInCurrency = currencyFormat(double.parse(formattedValueInBtc) * currencyRate, currency);
  
    return Column(
      crossAxisAlignment: CrossAxisAlignment.end,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        if (pegIn)
          if (double.parse(formattedValueToReceive) <= 0)
            AutoSizeText("0", style: TextStyle(fontSize: 32.sp, color: Colors.grey), maxLines: 1)
          else
            Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                AutoSizeText(formattedValueToReceive, style: TextStyle(fontSize: 32.sp, color: Colors.white), maxLines: 1, minFontSize: 18),
                SizedBox(height: 4.h),
                Text(valueInCurrency, style: TextStyle(fontSize: 16.sp, color: Colors.grey)),
              ],
            )
        else
          sideSwapPeg.when(
            data: (peg) {
              final options = [currency, btcFormat];
              final currentUnit = ref.watch(inputInFiatProvider) ? currency : btcFormat;
  
              return Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      DropdownButtonHideUnderline(
                        child: DropdownButton<String>(
                          value: currentUnit,
                          dropdownColor: const Color(0xFF212121),
                          borderRadius: const BorderRadius.all(Radius.circular(12.0)),
                          items: options.map((option) {
                            return DropdownMenuItem(
                              value: option,
                              child: Text(
                                option.toUpperCase(),
                                style: TextStyle(color: Colors.white, fontSize: 16.sp),
                              ),
                            );
                          }).toList(),
                          onChanged: (newUnit) {
                            if (newUnit != null && newUnit != currentUnit) {
                              final isSwitchingToFiat = newUnit == currency;
                              ref.read(inputInFiatProvider.notifier).state = isSwitchingToFiat;
                              if (isSwitchingToFiat) {
                                String fiatValue = calculateAmountInSelectedCurrency(
                                    ref.watch(sendTxProvider).amount, currency, ref.watch(currencyNotifierProvider));
                                controller.text = double.parse(fiatValue) < 0.01
                                    ? ''
                                    : double.parse(fiatValue).toStringAsFixed(2);
                              } else {
                                String btcValue = btcInDenominationFormatted(
                                    ref.watch(sendTxProvider).amount.toDouble(), btcFormat);
                                controller.text = btcValue;
                              }
                            }
                          },
                          icon: Padding(
                            padding: EdgeInsets.only(left: 8.0.w),
                            child: const Icon(Icons.keyboard_arrow_down_sharp, color: Colors.white),
                          ),
                          isDense: true,
                          style: TextStyle(color: Colors.white, fontSize: 16.sp),
                        ),
                      ),
                    ],
                  ),
                  AutoSizeTextField(
                    controller: controller,
                    keyboardType: const TextInputType.numberWithOptions(decimal: true),
                    inputFormatters: ref.watch(inputInFiatProvider)
                        ? [CommaTextInputFormatter(), DecimalTextInputFormatter(decimalRange: 2, integerRange: 7)]
                        : [
                      CommaTextInputFormatter(),
                      btcFormat == 'sats'
                          ? DecimalTextInputFormatter(decimalRange: 0)
                          : DecimalTextInputFormatter(decimalRange: 8, integerRange: 3),
                    ],
                    textAlign: TextAlign.right,
                    style: TextStyle(color: Colors.white, fontSize: 32.sp),
                    minFontSize: 18,
                    maxLines: 1,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: '0',
                      hintStyle: TextStyle(color: Colors.grey, fontSize: 32.sp),
                    ),
                    onChanged: (value) async {
                      if (ref.watch(inputInFiatProvider)) {
                        if (value.isEmpty) {
                          ref.read(sendTxProvider.notifier).updateAmountFromInput('0', btcFormat);
                          ref.read(sendTxProvider.notifier).updateAddress(peg.pegAddr ?? '');
                          ref.read(sendTxProvider.notifier).updateDrain(false);
                        } else {
                          String send = btcFormat == 'sats'
                              ? calculateAmountToDisplayFromFiatInSats(value, currency, ref.watch(currencyNotifierProvider))
                              : calculateAmountToDisplayFromFiat(value, currency, ref.watch(currencyNotifierProvider));
                          ref.read(sendTxProvider.notifier).updateAmountFromInput(send, btcFormat);
                          ref.read(sendTxProvider.notifier).updateAddress(peg.pegAddr ?? '');
                          ref.read(sendTxProvider.notifier).updateDrain(false);
                        }
                      } else {
                        if (value.isEmpty) {
                          ref.read(sendTxProvider.notifier).updateAmountFromInput('0', btcFormat);
                          ref.read(sendTxProvider.notifier).updateAddress(peg.pegAddr ?? '');
                          ref.read(sendTxProvider.notifier).updateDrain(false);
                        } else {
                          ref.read(sendTxProvider.notifier).updateAmountFromInput(value, btcFormat);
                          ref.read(sendTxProvider.notifier).updateAddress(peg.pegAddr ?? '');
                          ref.read(sendTxProvider.notifier).updateDrain(false);
                        }
                      }
                    },
                  ),
                ],
              );
            },
            loading: () => Center(child: _buildShimmer(height: 50.h, width: 120.w)),
            error: (error, stack) => Text(error.toString().i18n, style: TextStyle(color: Colors.white, fontSize: 20.sp)),
          ),
      ],
    );
  }
  
  Widget buildBitcoinPeg(WidgetRef ref, bool pegIn, TextEditingController controller) {
    final sideSwapStatus = ref.watch(sideswapStatusProvider);
    final btcFormat = ref.watch(settingsProvider).btcFormat;
    final currency = ref.watch(settingsProvider).currency;
    final currencyRate = ref.read(selectedCurrencyProvider(currency));
    final valueToReceive = ref.watch(sendTxProvider).amount * (1 - sideSwapStatus.serverFeePercentPegIn / 100) - ref.watch(pegOutBitcoinCostProvider);
    final formattedValueInBtc = btcInDenominationFormatted(valueToReceive, 'BTC');
    final valueInCurrency = currencyFormat(double.parse(formattedValueInBtc) * currencyRate, currency);
    final formattedValueToReceive = btcInDenominationFormatted(valueToReceive, btcFormat);
    final sideSwapPeg = ref.watch(sideswapPegProvider);
  
    return Column(
      crossAxisAlignment: CrossAxisAlignment.end,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        if (pegIn)
          if (double.parse(formattedValueToReceive) <= 0)
            AutoSizeText("0", style: TextStyle(fontSize: 32.sp, color: Colors.grey), maxLines: 1)
          else
            Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                AutoSizeText(formattedValueToReceive, style: TextStyle(fontSize: 32.sp, color: Colors.white), maxLines: 1, minFontSize: 18),
                SizedBox(height: 4.h),
                Text(valueInCurrency, style: TextStyle(fontSize: 16.sp, color: Colors.grey)),
              ],
            )
        else
          sideSwapPeg.when(
            data: (peg) {
              final options = [currency, btcFormat];
              final currentUnit = ref.watch(inputInFiatProvider) ? currency : btcFormat;
  
              return Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      DropdownButtonHideUnderline(
                        child: DropdownButton<String>(
                          value: currentUnit,
                          dropdownColor: const Color(0xFF212121),
                          borderRadius: const BorderRadius.all(Radius.circular(12.0)),
                          items: options.map((option) {
                            return DropdownMenuItem(
                              value: option,
                              child: Text(
                                option.toUpperCase(),
                                style: TextStyle(color: Colors.white, fontSize: 16.sp),
                              ),
                            );
                          }).toList(),
                          onChanged: (newUnit) {
                            if (newUnit != null && newUnit != currentUnit) {
                              final isSwitchingToFiat = newUnit == currency;
                              ref.read(inputInFiatProvider.notifier).state = isSwitchingToFiat;
                              if (isSwitchingToFiat) {
                                String fiatValue = calculateAmountInSelectedCurrency(
                                    ref.watch(sendTxProvider).amount, currency, ref.watch(currencyNotifierProvider));
                                controller.text = double.parse(fiatValue) < 0.01
                                    ? ''
                                    : double.parse(fiatValue).toStringAsFixed(2);
                              } else {
                                String btcValue = btcInDenominationFormatted(
                                    ref.watch(sendTxProvider).amount.toDouble(), btcFormat);
                                controller.text = btcValue;
                              }
                            }
                          },
                          icon: Padding(
                            padding: EdgeInsets.only(left: 8.0.w),
                            child: const Icon(Icons.keyboard_arrow_down_sharp, color: Colors.white),
                          ),
                          isDense: true,
                          style: TextStyle(color: Colors.white, fontSize: 16.sp),
                        ),
                      ),
                    ],
                  ),
                  AutoSizeTextField(
                    controller: controller,
                    keyboardType: const TextInputType.numberWithOptions(decimal: true),
                    inputFormatters: ref.watch(inputInFiatProvider)
                        ? [CommaTextInputFormatter(), DecimalTextInputFormatter(decimalRange: 2, integerRange: 7)]
                        : [
                      CommaTextInputFormatter(),
                      btcFormat == 'sats'
                          ? DecimalTextInputFormatter(decimalRange: 0)
                          : DecimalTextInputFormatter(decimalRange: 8, integerRange: 3),
                    ],
                    textAlign: TextAlign.right,
                    style: TextStyle(color: Colors.white, fontSize: 32.sp),
                    minFontSize: 18,
                    maxLines: 1,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: '0',
                      hintStyle: TextStyle(color: Colors.grey, fontSize: 32.sp),
                    ),
                    onChanged: (value) async {
                      if (ref.watch(inputInFiatProvider)) {
                        if (value.isEmpty) {
                          ref.read(sendTxProvider.notifier).updateAmountFromInput('0', btcFormat);
                          ref.read(sendTxProvider.notifier).updateAddress(peg.pegAddr ?? '');
                          ref.read(sendTxProvider.notifier).updateDrain(false);
                        } else {
                          String send = btcFormat == 'sats'
                              ? calculateAmountToDisplayFromFiatInSats(value, currency, ref.watch(currencyNotifierProvider))
                              : calculateAmountToDisplayFromFiat(value, currency, ref.watch(currencyNotifierProvider));
                          ref.read(sendTxProvider.notifier).updateAmountFromInput(send, btcFormat);
                          ref.read(sendTxProvider.notifier).updateAddress(peg.pegAddr ?? '');
                          ref.read(sendTxProvider.notifier).updateDrain(false);
                        }
                      } else {
                        if (value.isEmpty) {
                          ref.read(sendTxProvider.notifier).updateAmountFromInput('0', btcFormat);
                          ref.read(sendTxProvider.notifier).updateAddress(peg.pegAddr ?? '');
                          ref.read(sendTxProvider.notifier).updateDrain(false);
                        } else {
                          ref.read(sendTxProvider.notifier).updateAmountFromInput(value, btcFormat);
                          ref.read(sendTxProvider.notifier).updateAddress(peg.pegAddr ?? '');
                          ref.read(sendTxProvider.notifier).updateDrain(false);
                        }
                      }
                    },
                  ),
                ],
              );
            },
            loading: () => Center(child: _buildShimmer(height: 50.h, width: 120.w)),
            error: (error, stack) => Text(error.toString().i18n, style: TextStyle(color: Colors.white, fontSize: 20.sp)),
          ),
      ],
    );
  }
  
  
  List<Widget> _getFeeRows(WidgetRef ref) {
    final swapType = ref.watch(swapTypeProvider);
    final btcFormat = ref.read(settingsProvider).btcFormat;
  
    switch (swapType) {
      case SwapType.sideswapBtcToLbtc:
        final bitcoinFee = ref.watch(feeProvider);
        final sideswapStatus = ref.watch(sideswapStatusProvider);
        return bitcoinFee.when(
          data: (value) {
            return [
              _feeRow('Provider fee', '${sideswapStatus.serverFeePercentPegIn}%', ref),
              _feeRow('Network fee', '$value', ref),
              _feeRow(
                'Min amount',
                '${btcInDenominationFormatted(sideswapStatus.minPegInAmount, btcFormat)} $btcFormat',
                ref,
              ),
            ];
          },
          loading: () {
            return [
              _feeRow('Provider fee', '${sideswapStatus.serverFeePercentPegOut}%', ref),
              _feeRowShimmer('Network fee', ref),
              _feeRow(
                'Min amount',
                '${btcInDenominationFormatted(sideswapStatus.minPegInAmount, btcFormat)} $btcFormat',
                ref,
              ),
            ];
          },
          error: (error, stack) {
            return [
              _feeRow('Provider fee', '${sideswapStatus.serverFeePercentPegOut}%', ref),
              _feeRow('Network fee', '0', ref),
              _feeRow(
                'Min amount',
                '${btcInDenominationFormatted(sideswapStatus.minPegInAmount, btcFormat)} $btcFormat',
                ref,
              ),
            ];
          },
        );
  
      case SwapType.sideswapLbtcToBtc:
        final pegOutCost = ref.watch(pegOutBitcoinCostProvider);
        final sideswapStatus = ref.watch(sideswapStatusProvider);
        final liquidFee = ref.watch(liquidFeeProvider);
        return liquidFee.when(
          data: (value) {
            return [
              _feeRow('Provider fee', '${sideswapStatus.serverFeePercentPegOut}%', ref),
              _feeRow(
                'Peg out fee',
                '${btcInDenominationFormatted(pegOutCost, btcFormat)} $btcFormat',
                ref,
              ),
              _feeRow('Network fee', '$value', ref),
              _feeRow(
                'Min amount',
                '${btcInDenominationFormatted(sideswapStatus.minPegOutAmount, btcFormat)} $btcFormat',
                ref,
              ),
            ];
          },
          loading: () {
            return [
              _feeRow('Provider fee', '${sideswapStatus.serverFeePercentPegOut}%', ref),
              _feeRow(
                'Peg out fee',
                '${btcInDenominationFormatted(pegOutCost, btcFormat)} $btcFormat',
                ref,
              ),
              _feeRowShimmer('Network fee', ref),
              _feeRow(
                'Min amount',
                '${btcInDenominationFormatted(sideswapStatus.minPegOutAmount, btcFormat)} $btcFormat',
                ref,
              ),
            ];
          },
          error: (error, stack) {
            return [
              _feeRow('Provider fee', '${sideswapStatus.serverFeePercentPegOut}%', ref),
              _feeRow(
                'Peg out fee',
                '${btcInDenominationFormatted(pegOutCost, btcFormat)} $btcFormat',
                ref,
              ),
              _feeRow('Network fee', '0', ref),
              _feeRow(
                'Min amount',
                '${btcInDenominationFormatted(sideswapStatus.minPegOutAmount, btcFormat)} $btcFormat',
                ref,
              ),
            ];
          },
        );
  
      case SwapType.coinosLnToBTC:
        final pegOutCost = ref.watch(pegOutBitcoinCostProvider);
        return [
          _feeRow(
            'Network fee',
            '${btcInDenominationFormatted(pegOutCost, btcFormat)} $btcFormat',
            ref,
          ),
          _feeRow('Provider fee', '0.1%', ref),
        ];
  
      case SwapType.coinosLnToLBTC:
        return [
          _feeRow('Provider fee', '0.1%', ref),
        ];
  
      case SwapType.coinosBtcToLn:
        final bitcoinFee = ref.watch(feeProvider);
        return bitcoinFee.when(
          data: (value) {
            return [
              _feeRow('Network fee', '$value', ref),
            ];
          },
          loading: () {
            return [
              _feeRowShimmer('Network fee', ref),
            ];
          },
          error: (error, stack) {
            return [
              _feeRow('Network fee', '0', ref),
            ];
          },
        );
  
      case SwapType.coinosLbtcToLn:
        final liquidFee = ref.watch(liquidFeeProvider);
        return liquidFee.when(
          data: (value) {
            return [
              _feeRow('Network fee', '$value', ref),
            ];
          },
          loading: () {
            return [
              _feeRowShimmer('Network fee', ref),
            ];
          },
          error: (error, stack) {
            return [
              _feeRow('Network fee', '0', ref),
            ];
          },
        );
  
      case SwapType.sideswapDepixToUsdt:
      case SwapType.sideswapUsdtToEurox:
      case SwapType.sideswapUsdtToDepix:
      case SwapType.sideswapEuroxToUsdt:
        final quote = ref.watch(sideswapQuoteProvider);
        switch (quote.status) {
          case 'Success':
            final fixedFee = quote.fixedFee ?? 0;
            final serverFee = quote.serverFee ?? 0;
            final feeAsset = ref.read(toAssetProvider);
            final btcFormat = ref.read(settingsProvider).btcFormat;
            final fixedFeeStr = formatAssetAmount(feeAsset, fixedFee, btcFormat);
            final serverFeeStr = formatAssetAmount(feeAsset, serverFee, btcFormat);
            return [
              _feeRow('Fixed fee', fixedFeeStr, ref),
              _feeRow('Server fee', serverFeeStr, ref),
            ];
          case 'LowBalance':
            final fixedFee = quote.fixedFee ?? 0;
            final serverFee = quote.serverFee ?? 0;
            final feeAsset = ref.read(toAssetProvider);
            final btcFormat = ref.read(settingsProvider).btcFormat;
            final fixedFeeStr = formatAssetAmount(feeAsset, fixedFee, btcFormat);
            final serverFeeStr = formatAssetAmount(feeAsset, serverFee, btcFormat);
            return [
              _feeRow('Fixed fee', fixedFeeStr, ref),
              _feeRow('Server fee', serverFeeStr, ref),
              Text(
                'Insufficient balance'.i18n,
                style: TextStyle(color: Colors.grey, fontSize: 14.sp),
                textAlign: TextAlign.center,
              ),
            ];
          case 'Loading':
          case 'Initial':
            return [
              _feeRowShimmer('Fixed fee', ref),
              _feeRowShimmer('Server fee', ref),
            ];
          default:
            return [
              _feeRow('Fixed fee', formatAssetAmount(quote.feeAsset, 0, btcFormat), ref),
              _feeRow('Server fee', formatAssetAmount(quote.feeAsset, 0, btcFormat), ref),
            ];
        }
      case SwapType.sideswapLbtcToUsdt:
      case SwapType.sideswapLbtcToEurox:
      case SwapType.sideswapLbtcToDepix:
      case SwapType.sideswapUsdtToLbtc:
      case SwapType.sideswapEuroxToLbtc:
      case SwapType.sideswapDepixToLbtc:
        final quote = ref.watch(sideswapQuoteProvider);
        switch (quote.status) {
          case 'Success':
            final fixedFee = quote.fixedFee ?? 0;
            final serverFee = quote.serverFee ?? 0;
            final btcFormat = ref.read(settingsProvider).btcFormat;
            final fixedFeeStr = formatAssetAmount('Liquid Bitcoin', fixedFee, btcFormat);
            final serverFeeStr = formatAssetAmount('Liquid Bitcoin', serverFee, btcFormat);
            return [
              _feeRow('Fixed fee', fixedFeeStr, ref),
              _feeRow('Server fee', serverFeeStr, ref),
            ];
          case 'LowBalance':
            final fixedFee = quote.fixedFee ?? 0;
            final serverFee = quote.serverFee ?? 0;
            final btcFormat = ref.read(settingsProvider).btcFormat;
            final fixedFeeStr = formatAssetAmount('Liquid Bitcoin', fixedFee, btcFormat);
            final serverFeeStr = formatAssetAmount('Liquid Bitcoin', serverFee, btcFormat);
            return [
              _feeRow('Fixed fee', fixedFeeStr, ref),
              _feeRow('Server fee', serverFeeStr, ref),
              Text(
                'Insufficient balance'.i18n,
                style: TextStyle(color: Colors.grey, fontSize: 14.sp),
                textAlign: TextAlign.center,
              ),
            ];
          case 'Loading':
          case 'Initial':
            return [
              _feeRowShimmer('Fixed fee', ref),
              _feeRowShimmer('Server fee', ref),
            ];
          default:
            return [
              _feeRow('Fixed fee', formatAssetAmount('Liquid Bitcoin', 0, btcFormat), ref),
              _feeRow('Server fee', formatAssetAmount('Liquid Bitcoin', 0, btcFormat), ref),
            ];
        }
  
      default:
        return [
          _feeRow('Fee rate', '0%', ref),
        ];
    }
  }
  
  Widget _feeRow(String label, String value, WidgetRef ref) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 8.0.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label.i18n,
            style: TextStyle(
              color: Colors.white70,
              fontSize: 16.sp, // MODIFIED: Increased font size
            ),
          ),
          Text(
            value,
            style: TextStyle(
              color: Colors.grey,
              fontSize: 16.sp, // MODIFIED: Increased font size
              fontWeight: FontWeight.w600,
            ),
          ),
        ],
      ),
    );
  }
  
  Widget _feeRowShimmer(String label, WidgetRef ref) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 8.0.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label.i18n,
            style: TextStyle(
              color: Colors.white70,
              fontSize: 16.sp, // MODIFIED: Increased font size
            ),
          ),
          _buildShimmer(height: 16.sp, width: 80.w)
        ],
      ),
    );
  }
  
  Widget pickBitcoinFeeSuggestionsPegOut(WidgetRef ref) {
    // Watch the fee rate suggestions from the provider.
    final status = ref.watch(sideswapStatusProvider).bitcoinFeeRates ?? [];
    final selectedBlocks = ref.watch(pegOutBlocksProvider);
  
    // If fee rates are not yet available, show a shimmer effect.
    if (status.isEmpty) {
      return Center(
        child: _buildShimmer(height: 100.h),
      );
    }
  
    // The slider should go from slow to fast, so we reverse the list from the provider.
    final reversedStatus = status.reversed.toList();
  
    // Find the index of the currently selected block target for the slider's value.
    final currentIndex =
    reversedStatus.indexWhere((item) => item["blocks"] == selectedBlocks);
    final validInitialIndex = currentIndex >= 0 ? currentIndex : 0;
  
    // Get the data for the currently selected fee.
    final selectedFeeData = reversedStatus[validInitialIndex];
    final currentFee = selectedFeeData["value"].toDouble();
  
    // Helper to map block targets to human-readable time estimates.
    String getLabelForBlocks(int blocks) {
      if (blocks <= 1) return '~10 min'.i18n;
      if (blocks <= 3) return '~30 min'.i18n;
      if (blocks <= 6) return '~60 min'.i18n;
      if (blocks <= 144) return 'Days'.i18n;
      return 'Weeks'.i18n;
    }
  
    final currentLabel = getLabelForBlocks(selectedBlocks);
  
    return Column(
      children: [
        // Header row displaying the current fee and time estimate.
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Flexible(
              child: Text(
                '$currentLabel: $currentFee sat/vB',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.white.withOpacity(0.8),
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ],
        ),
        // The custom-styled slider.
        SliderTheme(
          data: SliderThemeData(
            trackHeight: 8.h,
            activeTrackColor: Colors.orangeAccent,
            inactiveTrackColor: Colors.white.withOpacity(0.2),
            thumbColor: Colors.white,
            overlayColor: Colors.orangeAccent.withOpacity(0.2),
            thumbShape: RoundSliderThumbShape(enabledThumbRadius: 10.r),
            overlayShape: RoundSliderOverlayShape(overlayRadius: 20.r),
            trackShape: const RoundedRectSliderTrackShape(),
          ),
          child: Slider(
            value: validInitialIndex.toDouble(),
            min: 0,
            max: (reversedStatus.length - 1).toDouble(),
            divisions: reversedStatus.length - 1,
            onChanged: (value) {
              final index = value.round();
              final newValue = reversedStatus[index];
              // Update the provider with the new block target.
              ref.read(pegOutBlocksProvider.notifier).state = newValue["blocks"];
              ref.read(bitcoinReceiveSpeedProvider.notifier).state =
              "${newValue["value"]} sats/vbyte";
            },
          ),
        ),
        // Labels for the slider ends.
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 8.w),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                'Slow'.i18n,
                style: TextStyle(color: Colors.white70, fontSize: 13.sp),
              ),
              Text(
                'Fast'.i18n,
                style: TextStyle(color: Colors.white70, fontSize: 13.sp),
              ),
            ],
          ),
        ),
      ],
    );
  }
  
  Widget feeSelection(WidgetRef ref) {
    final swapType = ref.watch(swapTypeProvider);
  
    switch (swapType) {
      case SwapType.sideswapBtcToLbtc:
        return bitcoinFeeSlider(ref);
      case SwapType.sideswapLbtcToBtc:
        return pickBitcoinFeeSuggestionsPegOut(ref);
      case SwapType.coinosLnToBTC:
      case SwapType.coinosLnToLBTC:
        return const SizedBox.shrink();
      case SwapType.coinosBtcToLn:
        return bitcoinFeeSlider(ref);
      case SwapType.coinosLbtcToLn:
        return const SizedBox.shrink();
      case SwapType.sideswapUsdtToLbtc:
      case SwapType.sideswapEuroxToLbtc:
      case SwapType.sideswapDepixToLbtc:
      case SwapType.sideswapLbtcToUsdt:
      case SwapType.sideswapLbtcToEurox:
      case SwapType.sideswapLbtcToDepix:
        return const SizedBox.shrink();
      default:
        return const SizedBox.shrink();
    }
  }
  
  Widget _liquidPegSlideToSend(WidgetRef ref, BuildContext context) {
    final status = ref.watch(sideswapStatusProvider);
    final pegStatus = ref.watch(sideswapPegStatusProvider);
  
    return pegStatus.when(
      data: (peg) {
        return Align(
          alignment: Alignment.bottomCenter,
          child: ActionSlider.standard(
            width: double.infinity,
            backgroundColor: Colors.black,
            toggleColor: const Color(0x00333333).withOpacity(0.4),
            icon: const Icon(
              Icons.keyboard_arrow_right_rounded,
              color: Colors.orange, // Orange arrow icon
            ),
            loadingIcon: const SizedBox(
              width: 24.0,
              height: 24.0,
              child: CircularProgressIndicator(
                strokeWidth: 2.0,
                color: Colors.orange, // Orange loading spinner
              ),
            ),
            successIcon: const Icon(
              Icons.check_rounded,
              color: Colors.orange, // Orange success icon
            ),
            failureIcon: const Icon(
              Icons.close_rounded,
              color: Colors.orange, // Orange failure icon
            ),
            action: (controller) async {
              ref.read(transactionInProgressProvider.notifier).state = true;
              controller.loading();
              try {
                if (ref.watch(sendTxProvider).amount < status.minPegOutAmount) {
                  ref.read(transactionInProgressProvider.notifier).state = false;
                  throw 'Amount is below minimum peg out amount'.i18n;
                }
                await ref.watch(sendLiquidTransactionProvider.future);
                await ref.read(sideswapHiveStorageProvider(peg.orderId!).future);
                showFullscreenExchangeModal(
                    amount: ref.read(sendTxProvider).amount,
                    context: context,
                    swapType: ref.read(swapTypeProvider)!,
                    orderId: peg.orderId ?? 'Unknown'
                );
                ref.read(sendTxProvider.notifier).updateAddress('');
                ref.read(sendTxProvider.notifier).updateAmount(0);
                ref.read(sendBlocksProvider.notifier).state = 1;
                Future.microtask(() {
                  ref.read(navigationProvider.notifier).state = 0;
                });
                controller.success();
                ref.read(transactionInProgressProvider.notifier).state = false;
                ref.read(sendTxProvider.notifier).resetToDefault();
              } catch (e) {
                controller.failure();
                ref.read(transactionInProgressProvider.notifier).state = false;
                showMessageSnackBar(
                  message: e.toString(),
                  error: true,
                  context: context,
                );
                controller.reset();
              }
            },
            child:  Text(
              'Slide to Swap'.i18n,
              style: TextStyle(
                color: Colors.grey,
                fontSize: 14.sp,
                fontWeight: FontWeight.bold,
              ),
              textAlign: TextAlign.center,
            ),
          ),
        );
      },
      loading: () => _buildShimmer(height: 50.h, borderRadius: 30.r),
      error: (error, stack) => Text(ref.watch(sendTxProvider).amount == 0 ? '' : error.toString().i18n, style: TextStyle(color: Colors.white, fontSize: 14.sp)),
    );
  }
  
  
  Widget _bitcoinPegSlideToSend(WidgetRef ref, BuildContext context) {
    final pegStatus = ref.watch(sideswapPegStatusProvider);
  
    return pegStatus.when(
      data: (peg) {
        return Align(
          alignment: Alignment.bottomCenter,
          child: ActionSlider.standard(
            width: double.infinity,
            backgroundColor: Colors.black,
            toggleColor: const Color(0x00333333).withOpacity(0.4),
            icon: const Icon(
              Icons.keyboard_arrow_right_rounded,
              color: Colors.orange, // Orange arrow icon
            ),
            loadingIcon: const SizedBox(
              width: 24.0,
              height: 24.0,
              child: CircularProgressIndicator(
                strokeWidth: 2.0,
                color: Colors.orange, // Orange loading spinner
              ),
            ),
            successIcon: const Icon(
              Icons.check_rounded,
              color: Colors.orange, // Orange success icon
            ),
            failureIcon: const Icon(
              Icons.close_rounded,
              color: Colors.orange, // Orange failure icon
            ),
            action: (controller) async {
              ref.read(transactionInProgressProvider.notifier).state = true;
              controller.loading();
              try {
                if (ref.watch(sendTxProvider).amount < ref.watch(sideswapStatusProvider).minPegInAmount) {
                  ref.read(transactionInProgressProvider.notifier).state = false;
                  throw 'Amount is below minimum peg in amount'.i18n;
                }
                await ref.watch(sendBitcoinTransactionProvider.future);
                await ref.read(sideswapHiveStorageProvider(peg.orderId!).future);
                showFullscreenExchangeModal(
                  amount: ref.read(sendTxProvider).amount,
                  context: context,
                  swapType: ref.read(swapTypeProvider)!,
                  orderId: peg.orderId ?? 'Unknown'
                );
                ref.read(sendTxProvider.notifier).updateAddress('');
                ref.read(sendTxProvider.notifier).updateAmount(0);
                ref.read(sendBlocksProvider.notifier).state = 1;
                Future.microtask(() {
                  ref.read(navigationProvider.notifier).state = 0;
                });
                controller.success();
                ref.read(transactionInProgressProvider.notifier).state = false;
                ref.read(sendTxProvider.notifier).resetToDefault();
              } catch (e) {
                ref.read(transactionInProgressProvider.notifier).state = false;
                controller.failure();
                showMessageSnackBar(
                  message: e.toString(),
                  error: true,
                  context: context,
                );
                controller.reset();
              }
            },
            child: Text(
              'Slide to Swap'.i18n,
              style: TextStyle(
                color: Colors.grey,
                fontSize: 14.sp,
                fontWeight: FontWeight.bold,
              ),
              textAlign: TextAlign.center,
            ),
          ),
        );
      },
      loading: () => Padding(
        padding: EdgeInsets.all(20.w),
        child: Center(child: _buildShimmer(height: 50.h, borderRadius: 30.r)),
      ),
      error: (error, stack) => Padding(
        padding: EdgeInsets.all(10.w),
        child: Text(error.toString().i18n, style: TextStyle(color: Colors.white, fontSize: 14.sp)),
      ),
    );
  }
  
  
  Widget _instantSwapSlideToSend(WidgetRef ref, BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(bottom: 20.w),
      child: Align(
        alignment: Alignment.bottomCenter,
        child: ActionSlider.standard(
          width: double.infinity,
          backgroundColor: Colors.black,
          toggleColor: const Color(0x00333333).withOpacity(0.4),
          icon: const Icon(
            Icons.keyboard_arrow_right_rounded,
            color: Colors.orange, // Orange arrow icon
          ),
          loadingIcon: const SizedBox(
            width: 24.0,
            height: 24.0,
            child: CircularProgressIndicator(
              strokeWidth: 2.0,
              color: Colors.orange, // Orange loading spinner
            ),
          ),
          successIcon: const Icon(
            Icons.check_rounded,
            color: Colors.orange, // Orange success icon
          ),
          failureIcon: const Icon(
            Icons.close_rounded,
            color: Colors.orange, // Orange failure icon
          ),
          action: (controller) async {
            ref.read(transactionInProgressProvider.notifier).state = true;
            controller.loading();
            try {
              final swap = await ref.read(sideswapUploadAndSignInputsProvider.future).then((value) => value);
              showFullscreenExchangeModal(
                amount: ref.read(sendTxProvider).amount,
                context: context,
                swapType: ref.read(swapTypeProvider)!,
                orderId: swap.txid
              );
              ref.read(sendTxProvider.notifier).updateAddress('');
              ref.read(sendTxProvider.notifier).updateAmount(0);
              ref.read(sendBlocksProvider.notifier).state = 1;
              Future.microtask(() {
                ref.read(navigationProvider.notifier).state = 0;
              });
              controller.success();
              ref.read(transactionInProgressProvider.notifier).state = false;
              ref.read(sendTxProvider.notifier).resetToDefault();
            } catch (e) {
              ref.read(transactionInProgressProvider.notifier).state = false;
              controller.failure();
              showMessageSnackBar(
                message: e.toString().i18n,
                error: true,
                context: context,
              );
              controller.reset();
            }
          },
          child: Text(
            'Slide to Swap'.i18n,
            style: TextStyle(
              color: Colors.grey,
              fontWeight: FontWeight.bold,
              fontSize: 14.sp,
            ),
            textAlign: TextAlign.center,
          ),
        ),
      ),
    );
  }
  
  
  
  Widget slideToSend(WidgetRef ref, BuildContext context) {
    final swapType = ref.watch(swapTypeProvider);
  
    switch (swapType) {
      case SwapType.sideswapBtcToLbtc:
        return _bitcoinPegSlideToSend(ref, context);
      case SwapType.sideswapLbtcToBtc:
        return _liquidPegSlideToSend(ref, context);
      case SwapType.sideswapUsdtToLbtc:
      case SwapType.sideswapEuroxToLbtc:
      case SwapType.sideswapDepixToLbtc:
      case SwapType.sideswapDepixToUsdt:
      case SwapType.sideswapUsdtToEurox:
      case SwapType.sideswapUsdtToDepix:
      case SwapType.sideswapEuroxToUsdt:
      case SwapType.sideswapLbtcToUsdt:
      case SwapType.sideswapLbtcToEurox:
      case SwapType.sideswapLbtcToDepix:
        final quote = ref.watch(sideswapQuoteProvider);
        if (quote.status == 'Success') {
          return _instantSwapSlideToSend(ref, context);
        } else {
          return SizedBox.shrink();
        }
      default:
        return SizedBox.shrink();
    }
  }