{% extends "base.jinja" %}
{% block main %}
    {% include "includes/hwi/hwi.jinja" %}
    {% include "includes/qr-scanner.html" %}
    <style>
        td {
            text-align: left;
        }

        @media screen and (max-width:720px) {
            #device_setup_wizard th, #device_setup_wizard td { 
                display: block;
                width: 100%;
            }
            #device_setup_wizard td:empty, #device_setup_wizard th:empty {
                display: none;
                margin: auto;
            }
            #device_setup_wizard th, #device_setup_wizard td, #device_setup_wizard td > input {
                text-align: center;
                width: 100%;
                margin: auto;
            }
            #device_setup_wizard .xpub {
                padding: 10px;
            }
            #device_setup_wizard #edit-xpubs-table-btn {
                margin: auto;
            }
        }
        .xpubs_edit {
            visibility: hidden;
        }
    </style>
    <div id="device_setup_wizard" style="width: 100%;" onsubmit="showPacman();">
        <h1 style="font-size: 2em;">Add {% if existing_device %}Keys{% else %}Device{% endif %}</h1><br>
        <form id="form" action="{{ url_for('devices_endpoint.new_device') }}" method="POST" class="card center" style="width: auto; margin: 40px;">
            {% 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 {% if not existing_device %}id="step1"{% else %}class="hidden"{% endif %}>
                <h1 style="font-size: 1.8em;">Select Your Device Type</h1>
                <input type="text" placeholder="Filter devices..." style="width: 60%; font-size: 1.4em; padding: 10px;" oninput="filterDeviceTypes(this.value)">
                <div id="devices_list" class="row overflow">
                    {% for cls in specter.device_manager.supported_devices %}
                        <label id="label_device_type_{{ cls.name }}">
                            <input onchange="setStepCompleted(1);nextStep();" type="radio" name="devices" value="{{ cls.device_type }}" data-qrcode="{{cls.qr_code_support}}" data-sdcard="{{cls.sd_card_support}}" data-hwi="{{cls.hwi_support}}" data-device-name="{{ cls.name }}" class="hidden device-type">
                            <div class="small-card radio" id="{{ cls.device_type }}_device_card" style="transform: scale(0.85); margin: 3px;">
                                <img src="{{ url_for('static', filename='img/devices/' ~ cls.icon) }}" width="18px">
                                {{ cls.name }}
                            </div>
                        </label>
                    {% endfor %}
                </div>
                <a class="note center" style="text-decoration: underline; cursor: pointer;" href="{{ url_for('devices_endpoint.new_device_manual') }}">Manual configuration</a>

            </div>
            <div {% if not existing_device %}id="step2-hot-wallet" class="hidden"{% elif existing_device.hot_wallet %}id="step1"{% else %}class="hidden"{% endif %}>
                <div id="hot-wallet" style="width: 80%; max-width: 700px; margin: auto;">
                    <br>
                    <p class="note" style="border-radius: 5px; padding: 20px; background: rgba(0,0,0,0.1); color: #ccc;">
                        <span style="display: inline-block;font-weight: bold; margin-bottom: 8px;">⚠️ A note on hot wallets:</span><br>
                        This will create a <a style="color: #ddd;" href="https://en.bitcoin.it/wiki/Hot_wallet" target="_blank">hot wallet</a> on your Bitcoin Core node.<br>
                        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 you mnemonic here or use the randomly generated one:</p>
                    <p><b>Make sure to backup these words!</b></p>
                    {% set wordslist = mnemonic.split(' ') %}
                    <nav class="row">
                        <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>
                    <input id="mnemonic_value" type="hidden" name="mnemonic" value="{{ mnemonic }}"/>
                    <textarea id="import_mnemonic" class="hidden" id="txt" placeholder="Enter your mnemonic here"></textarea>
                    <div id="generated_mnemonic">
                        <div id="generated_mnemonic_row" class="row center break-row-mobile" style="max-height: 30px;">
                            <fieldset style="border:none; display: inline;"> 
                                <select name="strength" id="strength">
                                    <option value="128">12 words</option>
                                    <option value="256">24 words</option>
                                </select>
                            </fieldset>
                            <button type="button" class="btn" style="max-width: 200px; margin-top: 9px;" onclick="generateMnemonic()">Generate New Mnemonic</button>
                        </div>
                        <br>
                        <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>
                    </div>
                </div>
            </div>
            <div {% if not existing_device or existing_device.hot_wallet %}id="step2" class="hidden"{% else %}id="step1"{% endif %}>
                <h1 style="font-size: 1.8em;">Upload Keys</h1>
                {% if not existing_device %}
                    <h2 style="max-width: 500px; margin: auto;">Name your Device: <input type="text" name="device_name" placeholder="My device" id="device_name" required/></h2>
                    <br>
                {% endif %}
                <div id="coldcard-instructions">
                    <p>
                    Connect your ColdCard to the computer via USB and unlock it or upload a wallet export file from micro SD card.<br>
                    </p>
                    <span class="note">
                    To export the wallet data file from the ColdCard, insert your micro SD card into the device, then:<br>
                    To get the single sig xpubs, go to: Advanced -> MicroSD Card -> Export Wallet -> Generic JSON. When asked for account, select acount number (default is 0) and confirm the export.<br>
                    To get the multisig xpubs, go to: Settings -> Multisig Wallets -> Export XPUB and confirm the export.
                    </span>
                </div>
                <div id="specter-instructions">
                    <p>
                    Connect your Specter-DIY to the computer via USB and unlock it or scan the wallet master public key.<br>
                    </p>
                    <span class="note">
                    To get the master public key QR code to scan, click on: Master public keys, then select each key type you'd like to import and scan the displayed QR code for each into Specter.
                    </span>
                </div>
                <div id="cobo-instructions">
                    <p>
                    Scan your Cobo Vault master public key or upload a wallet export file.<br>
                    </p>
                    <span class="note">
                    To get the master public keys QR codes to scan:<br>
                    For single sig, click on: Setting -> Watch-Only Wallet -> Generic Wallet, click next then select the wallet address type you would like to use for your wallet.
                    For multisig, click on: Multisig Wallet -> Show/Export XPUB, then select the wallet address type you would like to use for your wallet.
                    Cobo Vault will then display the QR code which you should scan into Specter.<br>
                    To import with SD card, click on "touch here to export the file with microSD" on the same screen as the QR code.
                    </span>
                </div>
                <div id="hwi-only-instructions">
                    <p>Connect your hardware device to the computer via USB.</p>
                </div>
                <br>
                <table>
                    <thead>
                    <tr>
                        <th></th><th>Purpose</th><th>Derivation</th><th>XPUB</th><th><button type="button" class="btn" style="width: 60px;" id="edit-xpubs-table-btn" onclick="editXpubsTable(this)">Edit</button></th>
                    </tr>
                    </thead>
                    <tbody id="xpubs_table">
                    </tbody>
                    <input id="xpubs-table-rows-count" name="xpubs_rows_count" type="hidden"/>
                </table>
                <br>
                <div class="row overflow">
                    <div id="connect-hwi" class="btn" style="max-width: 250px; width: 250px; margin: 10px;">
                        <img src="{{ url_for('static', filename='img/usb_tiny.svg') }}" style="width: 18px;">
                        Get via USB
                    </div>
                    <label id="connect-sdcard">
                        <input type="file" id="file" class="inputfile" multiple/>
                        <div class="btn" style="max-width: 250px; width: 250px; margin: 10px;">
                            <img src="{{ url_for('static', filename='img/sd_tiny.svg') }}" style="width: 18px;">
                            Upload from SD Card
                        </div>
                    </label>
                    <qr-scanner id="xpub-scan">
                        <a slot="button" href="#"  class="btn" style="max-width: 250px; width: 250px; margin: 10px;">
                            <img src="{{ url_for('static', filename='img/qr_tiny.svg') }}" style="width: 18px;">
                            Scan QR code
                        </a>
                    </qr-scanner>
                    <button type="button" onclick="showPageOverlay('paste-xpub-popup')" class="btn centered" id="xpub-paste" style="max-width: 250px; width: 250px; margin: 10px;">
                    <img src="{{ url_for('static', filename='img/paste_icon.svg') }}" style="width: 18px;">
                    Paste xpub
                    </button>
                    <div class="hidden" id="paste-xpub-popup">
                        <h1>Paste xpub</h1>
                        <input type="text" id="paste-xpub-text" placeholder="Paste your xpub here">
                        <br><br>
                        <button type="button" onclick="addXpubs(document.getElementById('paste-xpub-text').value);hidePageOverlay();document.getElementById('paste-xpub-text').value='';" class="btn centered">Add xpub</button>
                    </div>
                </div>
				<span id="toggle_advanced_xpubs" style="cursor: pointer;" onclick="toggleAdvancedXpubs()">Advanced &#9654;</span>
				<br>
                <div id="advanced_settings_xpubs" class="hidden">
                    <div id="advanced-hot-wallet" class="hidden" style="width: 400px; margin: auto;">
                        <label>Encrypt Wallet File: </label>
                        <input type="password" name="file_password" class="inline" placeholder="password">
                        <br>
                        <br>
                        <label>BIP39 passphrase (optional): </label>
                        <input type="password" name="passphrase" class="inline" placeholder="passphrase">
                        <br>
                        <p style="margin-bottom: 10px;">Addresses range to import: </p>
                        From: <input type="number" name="range_start" class="inline" placeholder="start" value=0 step=1 min=0 max=100000>
                        to: <input type="number" name="range_end" class="inline" placeholder="start" value=1000 step=1 min=0 max=100000>
                        <br>
                    </div>
				</div>
            </div>
            <br>
            <div class="row">
                <button type="button" class="btn hidden" style="width: 140px; max-width: 140px; margin: auto; margin-right: 40px;" id="wizard-previous" onclick="prevStep()">Previous</button>
                <button type="button" class="btn" style="width: 140px; max-width: 140px; margin: auto;" id="wizard-next" onclick="nextStep()" disabled>Next</button>
                <button type="submit" class="btn centered action hidden" style="width: 140px; max-width: 140px; margin: auto;" id="wizard-submit">Add {% if existing_device %}Keys{% else %}Device{% endif %}</button>
            </div>
        </form>
    </div>
{% endblock %}

{% block scripts %}
    <script>
        let xpubsTableRows = 0;

        function addXpub(purpose, derivation, xpub='-') {
			let xpubsTable = document.getElementById('xpubs_table');
            derivation = derivation.replaceAll("'", "h");
            for (let existingRow of xpubsTable.children) {
                let existingRowDerivation = document.getElementById(existingRow.id + '-derivation')
                if (existingRowDerivation && existingRowDerivation.innerHTML == derivation) {
                    document.getElementById(existingRow.id + '-xpub').innerHTML = xpub;
                    document.getElementById(existingRow.id + '-xpub-hidden').value = xpub;
                    if (purpose != 'Custom' && document.getElementById(existingRow.id + '-purpose').value == 'Custom') {
                        document.getElementById(existingRow.id + '-purpose').value = purpose;
                    }
                    return;
                }
            }
            xpubsTableRows++;
            let xpubsTableRowsInput = document.getElementById('xpubs-table-rows-count')
            xpubsTableRowsInput.value = xpubsTableRows;
            let xpubRowHTML = `
                <td></td>
                <td><input id="xpubs-table-row-${xpubsTableRows}-purpose" name="xpubs-table-row-${xpubsTableRows}-purpose" type="text" value="${purpose}" placeholder="XPUB purpose" style="width: 90%; min-width: 100px;"></td>
                <td id="xpubs-table-row-${xpubsTableRows}-derivation" style="min-width: 0px;">${derivation}</td>
                <input id="xpubs-table-row-${xpubsTableRows}-derivation-hidden" name="xpubs-table-row-${xpubsTableRows}-derivation-hidden" type="hidden" value="${derivation}">
                <td id="xpubs-table-row-${xpubsTableRows}-xpub" class="xpub scroll" style="overflow: auto;">${xpub}</td>
                <input id="xpubs-table-row-${xpubsTableRows}-xpub-hidden" name="xpubs-table-row-${xpubsTableRows}-xpub-hidden" type="hidden" value="${xpub}">
                <td><button type="button" class="btn xpubs_edit" style="width: 60px;" onclick="document.getElementById('xpubs-table-row-${xpubsTableRows}').remove()">Remove</button></td>
            `
            let xpubRow = document.createElement('tr');
            xpubRow.id = `xpubs-table-row-${xpubsTableRows}`;
			xpubRow.innerHTML = xpubRowHTML;
            xpubsTable.insertBefore(xpubRow, xpubsTable.children[xpubsTable.children.length - 3]);
        }

        function addXpubs(xpubs) {
            xpubs.split('\n').filter(xpub => xpub != '').forEach(xpub => {
                if (xpub.startsWith("[")) {
                    let [fingerprint, ...derivation] = xpub.split('[')[1].split(']')[0].split('/')
                    derivation = derivation.join('/').replace("'", 'h').toLowerCase();
                    addXpub('Custom', 'm/' + derivation, ['[' + fingerprint.toLowerCase(), '/' , derivation, ']', xpub.split(']')[1]].join(''))
                } else {
                    let xpubPurpose = 'Custom'
                    if (xpub.startsWith("ypub") || xpub.startsWith("upub")) {
                        xpubPurpose = '#0 Single Sig (Nested)';
                    } else if (xpub.startsWith("vpub") || xpub.startsWith("zpub")) {
                        xpubPurpose = '#0 Single Sig (Segwit)';
                    }
                    addXpub(xpubPurpose, 'm/', xpub)
                }
            })
            
            if (document.getElementById('edit-xpubs-table-btn').innerHTML != 'Edit') {
                for (let el of document.getElementsByClassName('xpubs_edit')) {
                    el.style.visibility = 'visible';
                }
            }
        }

        function setupXpubsTable(device='null') {
			let xpubsTable = document.getElementById('xpubs_table');
            xpubsTable.innerHTML = '';
            let xpubAddAccountRowHTML =  `
                <td></td>
                <td></td>
                <td><input id="account_number_xpubs" value="0" min="0" type="number" step="1" style="width: 150px;" placeholder="Account #"></td>
                <td><button type="button" class="btn" style="width: 150px;" onclick="addAccountXpubs()">Add account</button></td>
                <td></td>
            `
            let xpubAddAccountRow = document.createElement('tr');
            xpubAddAccountRow.id = `edit_add_account`;
            xpubAddAccountRow.style.display = 'none';
			xpubAddAccountRow.innerHTML = xpubAddAccountRowHTML;
            xpubsTable.appendChild(xpubAddAccountRow);

            let xpubAddCustomRowHTML =  `
                <td></td>
                <td><input id="new_xpub_purpose" type="text" placeholder="XPUB purpose"></td>
                <td><input id="new_xpub_derivation" type="text" placeholder="m/..."></td>
                <td></td>
                <td><button type="button" class="btn" style="width: 60px;" onclick="addCustomDerivation()">Add</button></td>
            `
            let xpubAddCustomRow = document.createElement('tr');
            xpubAddCustomRow.id = `edit_custom_der`;
            xpubAddCustomRow.style.display = 'none';
			xpubAddCustomRow.innerHTML = xpubAddCustomRowHTML;
            xpubsTable.appendChild(xpubAddCustomRow);

            let xpubAddRowHTML = `
                <td></td>
                <td></td>
                <td><button type="button" class="btn" style="width: 150px;" onclick="document.getElementById('edit_add_account').style.display='table-row';">Add account</button></td>
                <td><button type="button" class="btn" style="width: 150px;" onclick="document.getElementById('edit_custom_der').style.display='table-row';">Add custom derivation</button></td>
                <td></td>
            `
            let xpubAddRow = document.createElement('tr');
            xpubAddRow.id = `edit_select_add_method`;
            xpubAddRow.classList.add(`xpubs_edit`);
			xpubAddRow.innerHTML = xpubAddRowHTML;
            xpubsTable.appendChild(xpubAddRow);
            if (device && device != 'electrum') {
                addAccountXpubs();
            } else {
                addXpub('Custom', 'm/');
            }
            for (let el of document.getElementsByClassName('xpubs_edit')) {
                el.style.visibility = 'hidden';
            }
        }

        function addAccountXpubs() {
            let accountNumberField = document.getElementById('account_number_xpubs')
            let accountNumber = accountNumberField.value;
            addXpub('#' + accountNumber + ' Single Sig (Nested)', 'm/49h/{{ specter.is_testnet | int }}h/' + accountNumber + 'h');
            addXpub('#' + accountNumber + ' Single Sig (Segwit)', 'm/84h/{{ specter.is_testnet | int }}h/' + accountNumber + 'h');
            addXpub('#' + accountNumber + ' Multisig Sig (Nested)', 'm/48h/{{ specter.is_testnet | int }}h/' + accountNumber + 'h/1h');
            addXpub('#' + accountNumber + ' Multisig Sig (Segwit)', 'm/48h/{{ specter.is_testnet | int }}h/' + accountNumber + 'h/2h');
            document.getElementById('edit_add_account').style.display = 'none';
            accountNumberField.value = 0;
            for (let el of document.getElementsByClassName('xpubs_edit')) {
                el.style.visibility = 'visible';
            }
        }

        function addCustomDerivation() {
            let purposeTextField = document.getElementById('new_xpub_purpose')
            let derivationTextField = document.getElementById('new_xpub_derivation')
            addXpub(purposeTextField.value, derivationTextField.value);
            document.getElementById('edit_custom_der').style.display = 'none';
            purposeTextField.value = '';
            derivationTextField.value = '';
            for (let el of document.getElementsByClassName('xpubs_edit')) {
                el.style.visibility = 'visible';
            }
        }

        document.addEventListener("DOMContentLoaded", function(){
            setupXpubsTable();
        });

        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';
                generateMnemonicBtn.className = generateMnemonicBtn.className.replace(/checked/, '');
                importMnemonicBtn.className = importMnemonicBtn.className += ' checked';
                mnemonicValue.value = importMnemonic.value;
                importMnemonic.addEventListener("input", function() {
                    mnemonicValue.value = importMnemonic.value;
                });
            }
        }

        async function generateMnemonic() {
			let url = `{{ url_for('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);
			}
		}

        // Wizard JS

        let currentStep = 1;
        let totalSteps = parseInt('{{ 1 if existing_device and not existing_device.hot_wallet else 2 }}');
        let stepsCompleted = [];
        {% if existing_device %}
            {% if existing_device.hot_wallet %}
                setStepCompleted(1);
            {% else %}
                nextStep();
            {% endif %}
        {% endif %}

        function checkStepCompleted(step) {
        }

        function setStepCompleted(step) {
            document.getElementById('wizard-next').removeAttribute('disabled');
            stepsCompleted.push(step);
        }

        function setStepUncompleted(step) {
            document.getElementById('wizard-next').setAttribute('disabled', true);
            delete stepsCompleted[(stepsCompleted.indexOf(step))];
        }

        function nextStep() {
            if (currentStep == 1) {
                {% if existing_device %}
                    let device = {
                        value: "{{ existing_device.device_type }}",
                         'data-qrcode': "{{existing_device.qr_code_support}}",
                         'data-sdcard': "{{existing_device.sd_card_support}}",
                         'data-hwi': "{{existing_device.hwi_support}}",
                         'data-device-name': "{{ existing_device.name }}"
                    }
                {% else %}
                var devices = document.getElementsByName('devices');
                let device;
                for (var i = 0, length = devices.length; i < length; i++) {
                    if (devices[i].checked) {
                        device = devices[i];
                        break;
                    }
                }
                device = {
                    value: device.value,
                    'data-qrcode': device.getAttribute('data-qrcode'),
                    'data-sdcard': device.getAttribute('data-sdcard'),
                    'data-hwi': device.getAttribute('data-hwi'),
                    'data-device-name': device.getAttribute('data-device-name')
                }
                {% endif %}

                if (device.value == 'bitcoincore') {
                    if (document.getElementById('step2-hot-wallet')) {
                        document.getElementById('step2').id = 'step3';
                        document.getElementById('step2-hot-wallet').id = 'step2';
                    }
                    document.getElementById('toggle_advanced_xpubs').style.display = 'block';
                    totalSteps = parseInt('{{ 2 if existing_device else 3 }}');
                } else {
                    if (document.getElementById('step3')) {
                        document.getElementById('step3').id = 'step2';
                        document.getElementById('step2').id = 'step2-hot-wallet';
                    }
                    document.getElementById('toggle_advanced_xpubs').style.display = 'none';
                    totalSteps = parseInt('{{ 1 if existing_device else 2 }}');
                }

                

                // Update connect methods for step 2
                if (device['data-hwi'] == 'True') {
                    document.getElementById('connect-hwi').classList.remove('hidden');
                } else {
                    document.getElementById('connect-hwi').classList.add('hidden');
                }

                if (device['data-sdcard'] == 'True') {
                    document.getElementById('connect-sdcard').classList.remove('hidden');
                } else {
                    document.getElementById('connect-sdcard').classList.add('hidden');
                }

                if (device['data-qrcode'] == 'True') {
                    document.getElementById('xpub-scan').classList.remove('hidden');
                } else {
                    document.getElementById('xpub-scan').classList.add('hidden');
                }
                if (device.value == 'electrum' || device.value == 'other') {
                    document.getElementById('xpub-paste').classList.remove('hidden');
                } else {
                    document.getElementById('xpub-paste').classList.add('hidden');
                }
                document.getElementById('specter-instructions').classList.add('hidden');
                document.getElementById('coldcard-instructions').classList.add('hidden');
                document.getElementById('cobo-instructions').classList.add('hidden');
                document.getElementById('hot-wallet').classList.add('hidden');
                document.getElementById('advanced-hot-wallet').classList.add('hidden');
                document.getElementById('hwi-only-instructions').classList.add('hidden');
                switch(device.value) {
                    case 'specter':
                        document.getElementById('specter-instructions').classList.remove('hidden');
                        break;
                    case 'coldcard':
                        document.getElementById('coldcard-instructions').classList.remove('hidden');
                        break;
                    case 'cobo':
                        document.getElementById('cobo-instructions').classList.remove('hidden');
                        break;
                    case 'electrum':
                    case 'other':
                        break;
                    case 'bitcoincore':
                        document.getElementById('hot-wallet').classList.remove('hidden');
                        document.getElementById('advanced-hot-wallet').classList.remove('hidden');
                        break;
                    default:
                        document.getElementById('hwi-only-instructions').classList.remove('hidden');
                }
            }

            if (currentStep < totalSteps) {
                document.getElementById('wizard-previous').classList.remove('hidden');
                document.getElementById(`step${currentStep}`).classList.add('hidden');
                document.getElementById(`step${currentStep + 1}`).classList.remove('hidden');
                if (!document.getElementById('step3')) { // Only bitcoin core hot wallet
                    document.getElementById('wizard-next').setAttribute('disabled', 'true');
                }
                currentStep++;   
            }

            if (currentStep in stepsCompleted) {
                setStepCompleted(currentStep);
            }

            if (currentStep == totalSteps) {
                document.getElementById('wizard-next').classList.add('hidden');
                document.getElementById('wizard-submit').classList.remove('hidden');

                let deviceName;
                let deviceType;

                var devices = document.getElementsByName('devices');

                for (var i = 0, length = devices.length; i < length; i++) {
                    if (devices[i].checked) {
                        deviceName = devices[i]['data-device-name'];
                        deviceType = devices[i].value;
                        setupXpubsTable(deviceType);
                        break;
                    }
                }
                if (deviceType == 'other' || deviceType == 'electrum') {
                    xpubsEditable = true;
                } else {
                    xpubsEditable = false;
                }
            }
        }

        function prevStep() {
            document.getElementById(`step${currentStep}`).classList.add('hidden');
            document.getElementById(`step${currentStep - 1}`).classList.remove('hidden');
            currentStep--;
            if (currentStep == 1) {
                document.getElementById('wizard-previous').classList.add('hidden');
            }
            setStepCompleted(currentStep);

            
            document.getElementById('wizard-next').classList.remove('hidden');
            document.getElementById('wizard-submit').classList.add('hidden');
        }

        function filterDeviceTypes(text) {
            let devicesLabels = []
            {% for cls in specter.device_manager.supported_devices %}
                devicesLabels.push('label_device_type_{{ cls.name }}')
            {% endfor %}
            if (text) {
                for (let deviceLabel of devicesLabels) {
                    if (deviceLabel.split('label_device_type_')[1].toLowerCase().includes(text.toLowerCase())) {                                        
                        document.getElementById(deviceLabel).style.display = 'flex';
                    } else {
                        document.getElementById(deviceLabel).style.display = 'none';
                    }
                }
            } else {
                for (let deviceLabel of devicesLabels) {
                    document.getElementById(deviceLabel).style.display = 'flex';
                }
            }
        }

        function editXpubsTable(editBtn) {
            let visibility = '';
            if (editBtn.innerHTML == 'Edit') {
                editBtn.innerHTML = 'Done';
                visibility = 'visible';
            } else {
                editBtn.innerHTML = 'Edit';
                visibility = 'hidden';
            }
            document.getElementById('edit_select_add_method').style.display = 'table-row';
            document.getElementById('edit_add_account').style.display = 'none';
            document.getElementById('edit_custom_der').style.display = 'none';
            for (let el of document.getElementsByClassName('xpubs_edit')) {
                el.style.visibility = visibility;
            }
        }

        function toggleAdvancedXpubs() {
            let advancedButton = document.getElementById('toggle_advanced_xpubs');
            let advancedSettings = document.getElementById('advanced_settings_xpubs');
            if (advancedSettings.style.display === 'block') {
                advancedSettings.style.display = 'none';
                advancedButton.innerHTML = 'Advanced &#9654;';
            } else {
                advancedSettings.style.display = 'block';
                advancedButton.innerHTML = 'Advanced &#9660;';
                if (totalSteps == 3) {
                    document.getElementById('advanced-hot-wallet').display = 'block';
                } else {
                    document.getElementById('advanced-hot-wallet').display = 'none';
                }
            }
        }
    </script>

    <script type="text/javascript">
        document.getElementById('connect-hwi').addEventListener('click', async e => {
            var devicesRadios = document.getElementsByName('devices');
            let deviceType;
            for (var i = 0, length = devicesRadios.length; i < length; i++) {
                if (devicesRadios[i].checked) {
                    deviceType = devicesRadios[i].value;
                    break;
                }
            }
            // detect devices
            let devices = await enumerate(deviceType);
            if(devices == null){
                return
            }
            // this shouldn't happen actually
            if(devices.length == 0){
                showError("No devices found :(");
                return;
            }

            let device;
            if (devices.length == 1) {
                device = devices[0];
                let passphrase = await unlockDevice(device);
                if (passphrase != null){
                    device.passphrase = passphrase;
                }
            } else {
                // first only for now
                device = await selectDevice(devices);
            }

            // nothing to do if user cancelled
            if(device == null){
                return;
            }

            let xpubsTable = document.getElementById('xpubs_table');
            
            for (let xpubRow of [].slice.call(xpubsTable.children, 0, xpubsTable.children.length - 3)) {
                if (document.getElementById(xpubRow.id + '-xpub').innerHTML != '-') {
                    continue
                }

                let xpub = await getXpub(device,
                    document.getElementById(xpubRow.id + '-derivation').innerHTML,
                    "",
                    "{specter.chain}"
                );
                if(xpub == null){
                    showError('Failed to retrive device data. Please try again.');
                    return;
                }

                addXpub('Custom', document.getElementById(xpubRow.id + '-derivation').innerHTML, xpub)
            }
        });
    </script>

    <script type="text/javascript">
        document.addEventListener("DOMContentLoaded", function(){
            var el = document.getElementById("file");

            if (el != null) {
                el.addEventListener("change", (e) => {
                    files = e.currentTarget.files;
                    console.log(files);
                    for(let i=0; i<files.length; i++){
                        console.log(files[i].name);
                        let reader = new FileReader();
                        reader.onload = function(e) {
                            let str = reader.result
                            let data = "";
                            if (str.indexOf("{") >= 0) {
                                let json = JSON.parse(str);
                                console.log(str);
                                if ("keystore" in json) { // ColdCard electrum file
                                    let prefix = "";
                                    let fingerprint = "";
                                    if ("ckcc_xfp" in json.keystore){
                                        let num = json.keystore.ckcc_xfp;
                                        for (let i = 0; i < 4; i++) {
                                            fingerprint += ('0' + (num % 256).toString(16)).slice(-2);
                                            num = num >>> 8;
                                        }
                                    }
                                    if ("root_fingerprint" in json.keystore){
                                        fingerprint = json.keystore.root_fingerprint;
                                    }
                                    if ((fingerprint.length > 0) && ("derivation" in json.keystore)) {
                                        prefix = "[";
                                        prefix += fingerprint;
                                        prefix += json.keystore.derivation.substring(1).replace(/'/g,"h");
                                        prefix += "]";
                                    }
                                    let s = prefix + json.keystore.xpub + "\n";
                                    data += s;
                                } else if ("ExtPubKey" in json){
                                    // Probably Cobo single key txt file
                                    let der = '/' + json.AccountKeyPath.replace("m","").replace(/'/g,"h");
                                    data += `[${json.MasterFingerprint}${der}]${json.ExtPubKey}\n`;
                                } else if (("bip84" in json) && ("xfp" in json)){
                                // coldcard generic file
                                    let s = "";
                                    ["bip44","bip49","bip84"].forEach((bip)=>{
                                        if(bip in json){
                                            let der = json[bip].deriv.replace("m","").replace(/'/g,"h");
                                            let xpub = json[bip].xpub;
                                            if("_pub" in json[bip]){
                                                xpub = json[bip]["_pub"];
                                            }
                                            s += `[${json.xfp}${der}]${xpub}\n`;
                                        }
                                    });
                                    data += s;
                                } else if (("xpub" in json) && ("path" in json) && ("xfp" in json)) {
                                    // Probably Cobo single key file
                                    let der = json.path.replace("m","").replace(/'/g,"h");
                                    data += `[${json.xfp}${der}]${json.xpub}\n`;
                                } else if ("xfp" in json) {
                                // probably ColdCard multisig file
                                    let s = "";
                                    for (let k in json) {
                                        if (k+"_deriv" in json) {
                                            s += "["+json.xfp+json[k+"_deriv"].substring(1)+"]"+json[k]+"\n";
                                        }
                                    }
                                    data += s;
                                }
                            } else {
                                data += str+"\n";
                            }
                            addXpubs(data);
                        }
                        reader.readAsText(files[i]);
                    }
                    el.value = null;
                });
            }
        });
    </script>

    <script type="text/javascript">
        let scanner = document.getElementById('xpub-scan');
        if(scanner != null) {
            scanner.addEventListener('scan', e=>{
                let result = e.detail.result;
                if(result==null){
                    return;
                }
                // cobo uses json format
                if(result.includes("{")){
                    let obj = JSON.parse(result);
                    if( ("ExtPubKey" in obj) && 
                        ("AccountKeyPath" in obj) && 
                        ("MasterFingerprint" in obj)){
                        console.log(obj);
                        let path = obj.AccountKeyPath.replace(/'/g,'h');
                        let str = `[${obj.MasterFingerprint}/${path}]${obj.ExtPubKey}`;
                        addXpubs(str);
                    }else if( ("xfp" in obj) &&
                            ("xpub" in obj) &&
                            ("path" in obj)){
                        console.log(obj);
                        let path = obj.path.replace(/'/g,'h').replace("m/","");
                        let str = `[${obj.xfp}/${path}]${obj.xpub}`;
                        addXpubs(str);
                    }else{
                        showError("Unknown key format");
                    }
                }else{
                    addXpubs(result);
                }
            });
        }
    </script>
{% endblock %}
