{% extends "base.jinja" %}
{% block main %}
    {% include "includes/hwi/hwi.jinja" %}
    {% include "includes/qr-scanner.html" %}

    <form class="flex flex-col" id="form" action="{{ url_for('devices_endpoint.new_device_mnemonic', device_type=device_type) }}" method="POST" onsubmit="if (checkAdvancedValidState()) { showPacman(); } else { event.preventDefault(); }">
        <div class="card center auto-width">
            <h1 data-style="font-size: 2em;">{{ _("Add") }} {% if existing_device %}{{ _("Keys") }}{% else %}{{ _("Device") }}{% endif %}</h1>

            {% if existing_device %}
                <input type="hidden" name="existing_device" value="{{ existing_device.alias }}">
            {% endif %}

            <input type="hidden" class="csrf-token" name="csrf_token" value="{{ csrf_token() }}"/>

            <div>
                <div id="hot-wallet">
                    <p class="note" data-style="border-radius: 5px; padding: 20px; background: rgba(0,0,0,0.1); color: #ccc;">
                        {{ _('This will create a ')}}<a data-style="color: #ddd;" href="https://en.bitcoin.it/wiki/Hot_wallet" target="_blank">{{ _('hot wallet')}}</a>{{ _(' on your Bitcoin Core node.')}}
                        {{ _("Hot wallets are considered less secure and are not recommended for use with significant amounts. Use with caution and beware the potential risks.") }}
                    </p>
                    <p>
                        {{ _("Enter your mnemonic here") }}{% if not existing_device %} {{ _("or use the randomly generated one") }}{% endif %}.
                        {% if not existing_device %}<b>{{ _("Make sure to backup these words!") }}</b>{% endif %}
                    </p>

                    {% set wordslist = mnemonic.split(' ') %}
                    {% if not existing_device %}
                        <nav class="mt-10">
                            <button type="button" id="generate_mnemonic_btn" class="btn radio left checked" onclick="setMnemonicView('generate')"> {{ _("Generate") }} </button>
                            <button type="button" id="import_mnemonic_btn" class="btn radio right" onclick="setMnemonicView('import')"> {{ _("Import") }} </button>
                        </nav>
                    {% endif %}

                    <input id="mnemonic_value" type="hidden" name="mnemonic" value="{{ mnemonic }}"/>

                    <textarea id="import_mnemonic" class="my-3 hidden" id="txt" placeholder='{{ _("Enter your mnemonic here (English, Spanish and Italian are supported)") }}'></textarea>

                    <div id="generated_mnemonic" {% if existing_device %}class="hidden"{% endif %}>
                        <div id="generated_mnemonic_row" class="my-3" data-style="max-height: 30px;">
                            <fieldset data-style="border:none; display: inline;"> 
                                <select name="strength" id="strength">
                                    <option value="128">12 words</option>
                                    <option value="256">24 words</option>
                                </select>
                            </fieldset>
                        </div>


                        <table id="mnemonic_table">
                            {% for i in range(wordslist|length // 4) %}
                                <tr>
                                    <td id="mnemonicwo">{{ 4 * i + 1 }}. {{ wordslist[4 * i] }}</td>
                                    <td>{{ 4 * i + 2 }}. {{ wordslist[4 * i + 1] }}</td>
                                    <td>{{ 4 * i + 3 }}. {{ wordslist[4 * i + 2] }}</td>
                                    <td>{{ 4 * i + 4 }}. {{ wordslist[4 * i + 3] }}</td>
                                </tr>
                            {% endfor %}
                        </table>

                        <button type="button" class="selection-button my-3" onclick="generateMnemonic()">{{ _("Generate New Mnemonic") }}</button>
                    </div>
                </div>
                <span id="toggle-advanced" data-style="cursor: pointer;" onclick="toggleAdvanced()">{{ _("Advanced") }} &#9654;</span>
                <div id="advanced-settings" class="hidden" data-style="width: 400px; margin: auto;">
                    <label>{{ _("Encrypt Wallet File:") }} </label>
                    <input type="password" name="file_password" id="file_password" class="inline" placeholder="password">
                    <br>
                    <br>
                    <label>{{ _("BIP39 passphrase (optional):") }} </label>
                    <input type="password" name="passphrase" id="passphrase" class="inline" placeholder="passphrase">
                    <br>
                    <p data-style="margin-bottom: 10px;">{{ _("Addresses range to import:") }} </p>
                    {{ _("From:") }} <input type="number" name="range_start" id="range_start" class="inline" placeholder="start" value=0 step=1 min=0 max=100000>
                    {{ _("to:") }} <input type="number" name="range_end" id="range_end" class="inline" placeholder="start" value=1000 step=1 min=0 max=100000>
                </div>
            </div>
        </div>

        <button type="submit" id="submit-mnemonic" class="self-end button mt-10 bg-accent text-white" data-style="width: 140px; max-width: 140px; margin: auto;">{{ _("Continue") }}</button>
    </form>
{% endblock %}

{% block scripts %}
    <script>
        let hiddenAdvancedConfirmed = false;
        document.addEventListener("DOMContentLoaded", function(){
            {% if existing_device %}
                setMnemonicView('import');
            {% endif %}
        });

        function checkAdvancedValidState() {
            let advancedSettings = document.getElementById('advanced-settings');
            if ((!hiddenAdvancedConfirmed && advancedSettings.style.display !== 'block') &&
                (
                    document.getElementById('file_password').value ||
                    document.getElementById('passphrase').value ||
                    document.getElementById('range_start').value != 0 ||
                    document.getElementById('range_end').value != 1000
                )
            ) {
                toggleAdvanced();
                showError(`{{ _("You have set values in the Advanced section but left it hidden. Please verify they are correct or delete them, then click again to submit.") }}`)
                hiddenAdvancedConfirmed = true;
                return false;   
            }
            return true;
        }

        function setMnemonicView(view) {
            var generatedMnemonic = document.getElementById("generated_mnemonic");
            var importMnemonic = document.getElementById("import_mnemonic");
            var generateMnemonicBtn = document.getElementById("generate_mnemonic_btn");
            var importMnemonicBtn = document.getElementById("import_mnemonic_btn");
            var mnemonicValue = document.getElementById("mnemonic_value");
            if (view == 'generate') {
                generatedMnemonic.style.display = 'block';
                importMnemonic.style.display = 'none';
                generateMnemonicBtn.className = generateMnemonicBtn.className += ' checked';
                importMnemonicBtn.className = importMnemonicBtn.className.replace(/checked/, '');
                mnemonicValue.value = '{{ mnemonic }}'
            } else {
                generatedMnemonic.style.display = 'none';
                importMnemonic.style.display = 'block';
                {% if not existing_device %}
                    generateMnemonicBtn.className = generateMnemonicBtn.className.replace(/checked/, '');
                    importMnemonicBtn.className = importMnemonicBtn.className += ' checked';
                {% endif %}
                mnemonicValue.value = importMnemonic.value;
                importMnemonic.addEventListener("input", function() {
                    mnemonicValue.value = importMnemonic.value;
                });
            }
        }

        async function generateMnemonic() {
			let url = `{{ url_for('wallets_endpoint_api.generatemnemonic') }}`;
            var formData = new FormData(document.getElementById('form'));
			try {
				const response = await fetch(
					url,
					{
						method: 'POST',
						body: formData
					}
				);
				if(response.status != 200){
					showError(await response.text());
					return;
				}
				const jsonResponse = await response.json();
                let mnemonic = jsonResponse.mnemonic;

                document.getElementById("mnemonic_value").value = mnemonic;
                let wordslist = mnemonic.split(' ');
                let mnemonicTable = document.getElementById("mnemonic_table");
                mnemonicTable.innerHTML = ``;
    
                for(let i=0; i < wordslist.length / 4; i++) {
                    mnemonicTable.innerHTML += `
                        <tr>
                            <td id="mnemonicwo">${ 4 * i + 1 }. ${ wordslist[4 * i] }</td>
                            <td>${ 4 * i + 2 }. ${ wordslist[4 * i + 1] }</td>
                            <td>${ 4 * i + 3 }. ${ wordslist[4 * i + 2] }</td>
                            <td>${ 4 * i + 4 }. ${ wordslist[4 * i + 3] }</td>
                        </tr>
                    `
                }
			} catch(e) {
				console.log("Caught error: ", e);
				showError(e);
			}
		}

        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;`;
            }
        }
    </script>
{% endblock %}
