{% extends "wallet/components/wallet_tab.jinja" %}
{% set tab = 'send' %}

{% block content %}
	{% include "includes/qr-scanner.html" %}
	{% include "includes/recipient-box.html" %}

	{% from 'wallet/send/components/send_nav.jinja' import send_nav %}
	{{ send_nav('send_new', wallet_alias) }}

	<message-box type="error" id="amount_errors_container" style="position: absolute; top: 0; display: none;">
		Error!
		</ul>
	</message-box>

	<form action="{{ url_for('wallets_endpoint.send_new',wallet_alias=wallet_alias) }}" id="send-form" method="POST" data-style="width: 100%;">
		<input type="hidden" class="csrf-token" name="csrf_token" value="{{ csrf_token() }}"/>
		<input type="hidden" name="rbf_tx_id" value="{{ rbf_tx_id }}"/>
		<input type="hidden" name="recipient_dicts"  id="recipient_dicts" value=""/>  

		<h3>{{ _("Create Transaction") }}</h3>

		<div class="flex">
			<p>
				{{ _("Available funds:") }} {{wallet.amount_available | btcunitamount}}
				{% if specter.unit == 'sat' %}sats{% else %}{% if specter.is_testnet %}t{%endif%}{% if specter.is_liquid %}L{%endif%}BTC{% endif %}

				{% if specter.price_check %}
					<span>{{ wallet.amount_available | altunit }}</span>
				{% endif %}

				{% if specter.is_liquid and wallet.balance.get("assets", {}) %}
					<span>
						{{ _("Assets:") }}
						{% for asset in wallet.balance.get("assets",{}).keys() | sort %}
							{% set balance = wallet.balance.get("assets",{}).get(asset, {}) %}
							<span data-style="margin: 0 10px;">
								{{ (balance.get("trusted", 0) + balance.get("untrusted_pending", 0) + balance.get("immature", 0)) | btcamount }}
								<asset-label data-asset="{{asset}}" data-label="{{asset | assetlabel}}"></asset-label>
							</span>
						{% endfor %}
					</span>
				{% endif %}
			</p>

			{% if wallet.amount_locked_unsigned  > 0 or wallet.amount_frozen > 0 %}
				<div>
					<tool-tip width="150px">
							<h4 slot="title">{{ _("Why is this less than my total balance?") }}</h4>
							<span slot="paragraph">
							{{ _(' Frozen outputs and outputs locked in unsigned transactions are not available here.  
							To make more funds available, click on the "Unsigned" tab and delete not required transactions or unfreeze UTXO under "Transactions".') }}
							</span>
					</tool-tip>
				</div>
			{% endif %}
		</div>

		<div class="flex flex-col">			
			<div id="recipients" class="mt-3 rounded-t-xl overflow-hidden {% if ui_option != 'ui' %}hidden{% else %} recipient_wrapper" {% endif %}></div>
			<div class="px-4 py-3 cursor-pointer hover:bg-dark-700 rounded-b-xl bg-dark-600 text-white mb-2" id="add-recipient" title="Add a recipient" class="recipient_button recipient_add" onclick="addRecipient('', '', 'btc', '')">+ Add Recipient</div>

			<div id="recipients-txt-container" {% if ui_option == 'ui' %}class="hidden"{% endif %}>
				<div class="flex justify-between my-2">
					<span class="text-base">Unit Selection</span>
					<div class="space-x-4 flex items-center">
						<label class="checkbox-wrapper-inline">
							<input type="radio" name="amount_unit_text" value="sat" onchange="toggleTextUnit(this)" {% if specter.unit == 'sat' %}checked{% endif %} data-cy="csv-editor-sats-checkbox">
							<span>sat</span>
						</label>
						<label class="checkbox-wrapper-inline">
							<input type="radio" name="amount_unit_text" value="btc" onchange="toggleTextUnit(this)" {% if specter.unit != 'sat' %}checked{% endif %} data-cy="csv-editor-btc-checkbox">
							<span>BTC</span>
						</label>
					</div>
				</div>

				<textarea id="recipients-txt" name="recipients" placeholder="{{ _('Enter recipient address, amount') }}" onblur="validateForm()" data-cy="csv-editor-textarea">{{ recipients_txt }}</textarea>
				<p class="note" data-style="line-height: 2; background-color: #16202d; padding: 10px; border-radius: 7px;">
					{{ _("Enter each recipient address, amount as a new line:") }}<br>
					&lt;{{ _("ADDRESS") }}1&gt;, &lt;{{ _("AMOUNT") }}1&gt;<br>
					&lt;{{ _("ADDRESS") }}2&gt;, &lt;{{ _("AMOUNT") }}2&gt;<br>
					&lt;{{ _("ADDRESS") }}3&gt;, &lt;{{ _("AMOUNT") }}3&gt;<br>
				</p>
			</div>

			<div class="my-3 flex">
				<button type="button" class="btn cursor-pointer" id="calculated_tx_fee_label" onclick="showEstimatedFee()" data-cy="show-estimated-fee-btn">{{ _("Show Estimated Fee") }}</button>
				<div class="text-white bg-dark-800 rounded-full py-1 px-2 hidden" id="estimated-fee-box" data-cy="estimated-fee-box"></div>
				<button type="button" class="btn cursor-pointer hidden" id="close-estimated-fee-box-btn" onclick="closeFeeBox()" data-cy="close-fee-box-btn">&times;</div>
			</div>

			<span class="cursor-pointer mt-3" id="toggle_advanced">{{ _("Advanced") }} {% if show_advanced_settings %}&#9660;{% else %}&#9654;{% endif %}</span>

			<div id="advanced_settings" class="{% if not show_advanced_settings %}hidden{% endif %}">
				<h3 class="mt-5">{{ _("Transaction editor") }}</h3>
				<p class="mb-3">Select CSV to batch import several outputs for your transaction.</p>
				<div class="grid grid-cols-2 gap-3">
					<label class="checkbox-wrapper">
						<input type="radio" class="checkbox-input peer" name="ui_option" value="ui" onclick="toggleSendUIType(this)" {% if ui_option == 'ui' %}checked{% endif %} id="ui-radio-btn">
						<span class="checkbox-label">Interface</span>
					</label>
					<label class="checkbox-wrapper">
						<input type="radio" class="peer checkbox-input" name="ui_option" value="text" onclick="toggleSendUIType(this);" {% if ui_option != 'ui' %}checked{% endif %} data-cy="csv-editor-checkbox">
						<span>CSV</span>
					</label>
				</div>

				<h3 class="mt-5">{{ _("Fee Selection") }}</h3>
				{% include "includes/fee-selection.html" %}
				<fee-selection id="fee-selection-component"></fee-selection>

				<div class="row break-row-mobile" id="vertical-space-for-subtract-fees-from-amount-checkbox" data-style="margin-top: 0px;"></div>
			</div>

			{% include "includes/tx-row.html" %}
			{% include "includes/tx-data.html" %}
			{% include "includes/explorer-link.html" %}
			{% include "includes/tx-table.html" %}
			{% include "includes/coin_selection.html" %}

			<div class="mt-3">
				<coin-selection  
					id="coinselection-webcomponent"
					wallet-alias="{{wallet.alias}}"
					spendable-amount='{{ wallet.full_available_balance | btcamount }}'
					is-liquid="{{specter.is_liquid}}"
					selected-coins="{{ selected_coins }}">
				</coin-selection>
			</div>

			<div class="flex justify-end mt-8">
				<button onclick="validateForm(true)" type="button" name="action" value="createpsbt" id="create_psbt_btn" class="button bg-accent text-white">{{ _('Create ')}}<span class="optional">&nbsp;{{ _('Unsigned')}}&nbsp;</span>{{ _('Transaction') }}</button>
			</div>
		</div>
	</form>
{% endblock %}

{% block scripts %}
	<script>
		{% if specter.is_liquid %}
			const MIN_FEE_RATE = 0.1;
			const NETWORK = "Liquid"
		{% else %}
			const MIN_FEE_RATE = 1;
			const NETWORK = "Bitcoin"
		{% endif %}

		function getRecipientIds() {
			var ids = [];
			var children = document.getElementById(`recipients`).children;
			for (var i = 0; i < children.length; i++) {
				ids.push(children[i].recipientId)
			}
			return ids
		}

		// combines all html recipients to a list
		function getRecipients() {
			var data = [];

			var recipientIds = getRecipientIds();
			for  (var i in recipientIds)   {
				var recipientId = recipientIds[i];
				let recipient = document.getElementById(`recipient_${recipientId}`);
				data.push(recipient);
			}

			return data;
		}


		// combines all recipient.value's to a list
		function getRecipientDicts() {
			var data = [];

			var recipients = getRecipients();
			for  (var i in recipients)   {
				data.push(recipients[i].value);
			}

			return data;
		}

		function setVisibilityRemoveRecipientButton(){
			var recipientList = getRecipients();
			var hidden = recipientList.length == 1
			for (var i in recipientList) {
				recipientList[i].hiddenRemoveButton = hidden;
			}	

		}

		// Amounts and units
		var textUnit = '{{ specter.unit }}';
		// TODO: use total balance including unconfirmed
		var assetBalances = {
			"btc": {
				"balance": {{ wallet.full_available_balance }},
				"label": "{% if specter.is_testnet %}t{%endif%}{% if specter.is_liquid %}L{%endif%}BTC",
			},
			"sat": {
				"balance": Math.round({{ wallet.full_available_balance*1e8 }}),
				"label": "sat",
			},
		{% for asset in wallet.balance.get("assets",{}).keys() | sort %}
			"{{asset}}": {
				"balance": {{wallet.balance.get("assets",{}).get(asset, {}).get("trusted", 0)}},
				"label": "{{ asset | assetlabel }}",
			},
		{% endfor %}
		};
		var spendableAmount = {{ wallet.full_available_balance }}

		// Set up web components
		var coinselectionWebcomponent = document.getElementById('coinselection-webcomponent');
		coinselectionWebcomponent.assetBalances = assetBalances
		coinselectionWebcomponent.addEventListener("change", (event) => {
			validateForm()
		})
		var FeeSelectionComponent = document.getElementById('fee-selection-component')
		FeeSelectionComponent = document.getElementById('fee-selection-component')

		// Switch off RBF and subtract fee for Liquid
		function adjustForLiquid() {
			if (NETWORK == "Liquid") {
			console.log("On Liquid, removing RBF and subtract from features ... ")
			FeeSelectionComponent.deactivateRbf()
			FeeSelectionComponent.deactivateSubtract() // Subtract from is still set to true for send max under the hood
			// Remove some line breaks
			advancedSettingsDiv = document.getElementById("advanced_settings")
			lineBreaks = Array.from(advancedSettingsDiv.querySelectorAll('br'))
			lineBreaks.pop() // We still need the last line break
			for (var br of lineBreaks) {
				if (br.parentNode == advancedSettingsDiv) {
					advancedSettingsDiv.removeChild(br)
				}
			}
			}	
		}
		
		// Main part of displaying subtractFrom, the rest is with addRecipient, deleteRecipient and toggleSendUIType
		FeeSelectionComponent.addEventListener("subtractClick", (event) => {
			if ((getRecipientIds().length > 1 || !document.getElementById('ui-radio-btn').checked) && document.getElementById('subtract').checked) {
				FeeSelectionComponent.showSubtractFrom(true)
				if (!document.getElementById('ui-radio-btn').checked) {
					FeeSelectionComponent.addLineBreaks(2)
				}
			} 
			else {
				FeeSelectionComponent.showSubtractFrom(false)
				if (!document.getElementById('ui-radio-btn').checked) {
					FeeSelectionComponent.removeLineBreaks()
				}
			}
		})


		function addRecipient(address, amount, amount_unit, label) {
			let recipientIds = getRecipientIds();
			recipientId = 0;
			if (recipientIds.length > 0) {
				recipientId = Math.max(...recipientIds)+1
			}; 

			// This adds the recipient
			let recipients = document.getElementById('recipients');			
			let newRecipient = new RecipientBox();
			newRecipient.id = `recipient_${recipientId}`;
			newRecipient.recipientId = recipientId;
			newRecipient.title = `Recipient ${recipientId+1}`;
			newRecipient.address = address;
			newRecipient.amount = amount;
			newRecipient.unit = amount_unit;
			newRecipient.label = label;
			newRecipient.classList = "group"
			newRecipient.addEventListener('remove', (event) => {
				removeRecipient(newRecipient.recipientId);
			})
			newRecipient.addEventListener('address-input', (event) => {
				validateForm();
			})
			newRecipient.addEventListener('unit-change', (event) => {
				validateForm();
			})
			newRecipient.addEventListener('send-max', (event) => {
				setMaxAmount(newRecipient.recipientId);
			})

			recipients.appendChild(newRecipient);

			// This adds the id's to the subtract_from_recipient_id_select
			var feeSelectionComponent = document.getElementById('fee-selection-component');
			var subtractFromRecipientIdSelect = feeSelectionComponent.subtractFrom.children.subtract_from_recipient_id_select;
			var opt = document.createElement('option');
			opt.value = recipientId;
			opt.innerHTML = newRecipient.title;
			subtractFromRecipientIdSelect.appendChild(opt);		

			// Make the remove button visible again for all recipient components
			setVisibilityRemoveRecipientButton();

			// control visibility  and vertical spaces
			if (getRecipientIds().length == 1) {
				FeeSelectionComponent.showSubtractFrom(false);
				document.getElementById('vertical-space-for-subtract-fees-from-amount-checkbox').style['margin-top'] = '0px';
			} else {
				document.getElementById('vertical-space-for-subtract-fees-from-amount-checkbox').style['margin-top'] = '60px';
				if (document.getElementById('subtract').checked) {
					FeeSelectionComponent.showSubtractFrom(true)
				}
			}

		} 

		function removeRecipient(recipientId=-1) {	
			if (recipientId==-1) {
				recipientId = getRecipientIds().length - 1
			};
			let recipients = document.getElementById('recipients');

			// This removes the recipient div 
			for (var i = recipients.children.length -1; i >= 0; i--) {
				let	child =  recipients.children[i];
				if (child.recipientId == recipientId) {
					recipients.removeChild(child)
				}
			}

			// This removes the recipientId from the subtract_from_recipient_id_select
			var subtractFromRecipientIdSelect = FeeSelectionComponent.subtractFrom.children.subtract_from_recipient_id_select;
			for (var i = subtractFromRecipientIdSelect.children.length -1; i >= 0; i--) {
				let	child =  subtractFromRecipientIdSelect.children[i];
				if (child.value == recipientId) {
					subtractFromRecipientIdSelect.removeChild(child)
				}
			}

			// Not strictly necessary but better to have it to avoid any divergence
			FeeSelectionComponent.subtractUpdated();

			// Hide the remove button if we only have one recipient
			setVisibilityRemoveRecipientButton();

			// control visibility  and vertical spaces
			if (getRecipientIds().length == 1) {
				FeeSelectionComponent.showSubtractFrom(false);
				document.getElementById('vertical-space-for-subtract-fees-from-amount-checkbox').style['margin-top'] = '0px';
			} else {
				document.getElementById('vertical-space-for-subtract-fees-from-amount-checkbox').style['margin-top'] = '60px';
			}
		}

		function toggleTextUnit(unitSelected) {
			textUnit = unitSelected.value
		}

		function isAboveWalletBalance(unit, amount) {
			// TODO: Currently check is disabled for RBF for simplicity, should add it back for RBF
			if ("{{rbf_tx_id}}") {
				return false;
			}
			if(unit in assetBalances){
				return amount > assetBalances[unit].balance;
			}else{
				return amount > 0;
			}
		}

		function isInvalidValue(unit, amount){
			if (!amount) {
				return false;
			}
			return (unit == 'sat' ? amount / 1e8 : amount) < 1e-8;
		}

		async function setMaxAmount(recipientId) {
			const recipients = getRecipients();
			const recipient = document.getElementById(`recipient_${recipientId}`);
			FeeSelectionComponent.showSubtractFrom(true)
			FeeSelectionComponent.setSubtractFrom(recipientId)
			if (!validAddress(recipientId)) {
				return;
			}
			FeeSelectionComponent.setSubtract(recipient.unit == 'sat' || recipient.unit == 'btc' || recipient.unit == 'lbtc');

			let othersAmount = 0;
			for(let j in recipients) {		
				other_recipient = recipients[j]		;
				if (other_recipient.recipientId != recipientId) {
					let unit = other_recipient.unit;
					let amount = other_recipient.amount;
					// assets
					if(other_recipient.unit != 'sat' || other_recipient.unit != 'btc'){
						if(unit == recipient.unit){
							othersAmount += amount;
						}
					// btc
					}else{
						if(unit == 'sat' || unit == 'btc'){
							othersAmount += (unit == 'sat' ? amount / 1e8 : amount);
						}
					}
				}
			}

			let maxAmount = (coinselectionWebcomponent.getSpendableAmount(recipient.unit) - (recipient.unit == 'sat' ? othersAmount * 1e8 : othersAmount));
			if (recipient.unit == 'sat') {
				maxAmount = Math.round(maxAmount);
			} else {
				maxAmount = parseFloat(maxAmount.toFixed(8));
			}
			if (maxAmount < 0) {
				maxAmount = 0;
			}
			document.getElementById(`recipient_${recipientId}`).amount = maxAmount;
		}

		// Form validation
		function validateAmount(unit, amount, recipientId, allowZero=false) {
			if (isNaN(amount)) {
				showError(`{{ _("Amount entered is invalid.") }}`, 5000);
				return false;
			}
			if (recipientId) {				
				if (coinselectionWebcomponent != null) {
					document.getElementById(`recipient_${recipientId}`).max = coinselectionWebcomponent.getSpendableAmount(unit);
				} else {
					document.getElementById(`recipient_${recipientId}`).max = spendableAmount
				}
			}
			if (!amount && !allowZero) {
				showError(`{{ _("Amount is zero.") }}`, 5000);
				return false;
			}
			if (isAboveWalletBalance(unit, amount)) {
				showError(`{{ _("You cannot send more than") }} ${assetBalances[unit].balance} ${assetBalances[unit].label}!`, 5000);
				return false;
			} 
			// Directly checks coin selection in here
			else if (coinselectionWebcomponent.shouldSelectMoreCoins(unit, amount)) {
				showError(`{{ _("You need to select more coins!") }}`, 5000);
				return false;
			} 
			else if (isInvalidValue(unit, amount)) {
				showError(`{{ _("Invalid amount! Wrong unit?") }}`, 5000);
				return false;
			} 
			else {
				return true;
			}
		}

		// Returns true if the address is valid 
		function validAddress(recipientId) {
			let reWhite = /\s/;
			let address = document.getElementById(`recipient_${recipientId}`).address;
			if (!address) {
				showError(`{{ _("You provided no address.") }}`, 5000);
				return false
			}
			// Segwit addresses are always between 14 and 74 characters long.
			else if (address.length < 14) {
				showError(`{{ _("Please provide a valid address!") }}`, 5000);
				return false
			}
			else if (reWhite.test(address)) {
				showError(`{{ _("Looks like there are whitespaces in the address field.") }}`, 5000);
				return false
			}
			else {
				return true;
			}
		}

		// Returns true if the fee is valid
		function validFee() {
			let feeRate = FeeSelectionComponent.selectedFee()
			if (feeRate == '') {
				showError(`{{ _("You didn't input a number for the fee or left it empty.") }}`, 5000)
				return false	
			}
			else if (feeRate < MIN_FEE_RATE) {
				showError(`{{ _("Your fee is too low. The minimum fee for ${NETWORK} is ${MIN_FEE_RATE} satoshi.") }}`, 5000)
				return false	
			}
			else {
				return true
			}
		}

		function validateForm(submitted=false) {
			const recipients = getRecipients();
			// this assures that the 'recipient_dicts' input has the newest recipientDicts
			document.getElementById('recipient_dicts').value  = JSON.stringify(getRecipientDicts());  
			console.log("validateForm is called")
			let createPSBTButton = document.getElementById('create_psbt_btn');
			// Disables submit but button still clickable before every validation
			createPSBTButton.setAttribute('type', 'button');
			let totalAmount = 0.0;
			let assetAmounts = {};
			if (document.getElementById('ui-radio-btn').checked) {
				for(let i in recipients) {
					let recipient = recipients[i];
					if(recipient.unit == 'btc' || recipient.unit == 'sat'){
						totalAmount += (recipient.unit == 'sat' ? recipient.amount / 1e8 : recipient.amount);
					}else{
						if(recipient.unit in assetAmounts){
							assetAmounts[recipient.unit] += recipient.amount;
						}else{
							assetAmounts[recipient.unit] = recipient.amount;
						}
					}


					if (submitted) {
						// Check address
						if (!validAddress(recipient.recipientId)) {
							return;
						}
						// Check amount
						if (!validateAmount(recipient.unit, recipient.amount, recipient.recipientId)) {
							return;
						}
					}
				}
				// Check fee selection
				if (submitted) {
					if (!validFee()) {
					return
					}	
				}
	
			} else {
				let outputs = document.getElementById('recipients-txt').value.split('\n');
				for (let output of outputs) {
					if (textUnit == 'sat') {
						totalAmount += parseInt(output.split(',')[1].trim()) / 1e8;
					} else {
						totalAmount += parseFloat(output.split(',')[1].trim());
					}
				}
			}

			// Check Liquid assets
			for(asset in assetAmounts){
				if(!validateAmount(asset, assetAmounts[asset])){
					return;
				}
			}
			// Necessary since recipients can be removed which leades to
			// mismatches between the index in the get_recipient_list and the selected recipientId
			indexSubtractFromRecipient = getRecipientIds().indexOf(parseInt(FeeSelectionComponent.subtractFromRecipientIdSelect.value, 10));
			FeeSelectionComponent.setSubtractFrom(indexSubtractFromRecipient)
			createPSBTButton.setAttribute('type', 'submit');
			return true;
		}

		// Utils
		function setVisibility(id, visibility) {
			document.getElementById(id).style.display = visibility;
		}

		function toggleAdvanced() {
			let advancedButton = document.getElementById('toggle_advanced');
			let advancedSettings = document.getElementById('advanced_settings');
			if (advancedSettings.style.display === 'block') {
				advancedSettings.style.display = 'none';
				advancedButton.innerHTML = `{{ _("Advanced") }} &#9654;`;
			} else {
				advancedSettings.style.display = 'block';
				advancedButton.innerHTML = `{{ _("Advanced") }} &#9660;`;
			}
		}

		function toggleSendUIType(radioBtn) {
			if (radioBtn.value == 'ui') {
				FeeSelectionComponent.removeLineBreaks()
				setVisibility('recipients', 'block');
				setVisibility('add-recipient', 'flex');
				setVisibility('recipients-txt-container', 'none');
				setVisibility('subtract', 'block');
				if (getRecipientIds().length <= 1) {
					FeeSelectionComponent.showSubtractFrom(false)
				}
			} else {
				setVisibility('recipients', 'none');
				setVisibility('add-recipient', 'none');
				setVisibility('recipients-txt-container', 'block');
				// Assumes that text is always used for multiple recipients
				if (document.getElementById('subtract').checked) {
					FeeSelectionComponent.showSubtractFrom(true)
					// Adds two line breaks after the RBF checkbox, since it gets crowded
					FeeSelectionComponent.addLineBreaks(2)
				}
			}
		}

		const feeBox = document.getElementById('estimated-fee-box')
		const closeFeeBoxBtn = document.getElementById('close-estimated-fee-box-btn')

		async function showEstimatedFee() {	
			if (!validateForm(true)) {
				return;
			}
			const url = `{{ url_for("wallets_endpoint_api.estimate_fee", wallet_alias=wallet.alias) }}`	
			const formData = new FormData(document.getElementById('send-form'));
			formData.append("estimate_fee", true)
			const response = await send_request(url, 'POST', "{{ csrf_token() }}", formData);
			const fee = response.fee
			if (fee) {
				feeBox.classList.remove('hidden')
				closeFeeBoxBtn.classList.remove('hidden')
				let feeInSats = parseInt(response.fee * 1e8)
				if ('{{ specter.price_check }}' == 'True') {
					let altRate = parseFloat('{{ specter.alt_rate }}');
					let altSymbol = '{{ specter.alt_symbol }}';
					let altAmount = parseFloat((altRate * fee).toFixed(2))
					if (!isNaN(altAmount) && (altSymbol && altRate)) {
						feeBox.innerText = `${feeInSats} sats (${altAmount}${altSymbol})`;
					}
				}
				else {
					feeBox.innerText = `${feeInSats} sats`
				}
			}
			else {
				feeBox.innerText = "Fee estimate didn't work"
			}
		}

		function closeFeeBox() {
			feeBox.classList.add('hidden')
			closeFeeBoxBtn.classList.add('hidden')
		}

		document.addEventListener("DOMContentLoaded", function() {
			{% if fillform %}
				{% for addr, amount, amount_unit, label in recipients %}
				addRecipient("{{ addr }}", {{ amount }}, "{{ amount_unit }}", "{{ label }}");
				{% endfor %}
			{% else %}
				addRecipient("", "", "btc", "");
			{% endif %}
				adjustForLiquid()
				document.getElementById('toggle_advanced').addEventListener('click', (event) => {
					toggleAdvanced();
				});
			// Hide the remove button if the page is loaded with only once recipient 
			setVisibilityRemoveRecipientButton();
		});
	</script>
{% endblock %}
