{% from 'includes/sidebar/components/sidebar_btn.jinja' import sidebar_btn %}
{% from "components/bitcoin_svg.jinja" import bitcoin_svg %}
{% include "includes/sidebar/components/node_select_popup.jinja" %}
<style>
    #wallets_overview_link {
        text-transform: none;
        text-decoration: none;
        float: right;
        margin-right: 10px;
    }

    #wallets_overview_link:hover {
        text-decoration: underline;
        color: #fff;
    }

    #node-switch-icon {
        padding: 5px;
        
        float: right;
        width: 30px;
        position: absolute;
        {% if session["is_language_rtl"] %}
        right: 210px;
        {% else %}
        left: 210px;
        {% endif %}
        top: 5px;
        border-radius: 10px;
    }

    #node-switch-icon:hover {
        background-color: #737f98;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% {  transform: rotate(359deg); }
    }
    .spinning {
        animation: spin 2s linear infinite;
    }

</style>
<div id="side-content">
    <nav class="side">
        {% if specter.info["initialblockdownload"] %}
            <p class="warning" style="margin-top: 30px;"><img src="{{ url_for('static', filename='img/info_sign.svg') }}" style="width: 20px;"/><br>{{ _("Bitcoin Core is still syncing...")}}<br>{{ _('(data might be outdated)')}}</p>
        {% endif %}
        {% if specter.network_info.version < 200000 %}
            <p class="warning" style="margin-top: 30px;"><img src="{{ url_for('static', filename='img/warning_sign.svg') }}" style="width: 20px;"/><br>{{ _("Bitcoin Core version is outdated.")}}<br>{{ _('Some features might not work...')}}<br>{{ _("(minimum required: v20.0.0).") }}</p>
        {% endif %}
            <div 
                id="active-node" onclick="showPageOverlay('bitcoin_core_info');document.getElementById('side-content').classList.remove('active');" 
                class="item core" style="cursor: pointer;">

            {% if specter.is_liquid %}
                {% from "components/liquid_svg.jinja" import liquid_svg %}
                {{ liquid_svg(specter.info.chain, 40) }}
            {% else %}
                {% from "components/bitcoin_svg.jinja" import bitcoin_svg %}
                {{ bitcoin_svg(specter.info.chain, 40) }}
            {% endif %}
            {% include "includes/sidebar/components/bitcoin_core_info.jinja" %}
            <div>
                <span style="max-width: 140px;">{{ specter.node.name }}</span>
                <img id="node-switch-icon" src="{{ url_for('static', filename='img/flip-horizontal.svg')}}" class="svg-white" onclick="showNodeSelectPopup()"/>
                <br>
                <small>
                    {% if specter.chain %}
                        {% if specter.bitcoin_core_version != '' %}
                            v{{ specter.bitcoin_core_version }}
                        {% endif %}
                        ({{specter.chain}}):
                        {% if specter.info["blocks"] %}
                            {{ specter.info.blocks }} blocks
                        {% else %}
                            {{ specter.info.chain }}
                        {% endif %}
                    {% else %}
                        {{ _("Unavailable. Click to configure.") }}
                    {% endif %}
                </small>
            </div>

        </div>
        {% if specter.info["utxorescan"] %}
        <div class="rescan_progress {{ specter.info.chain }}">
            <div id="utxo_rescan_progress" style='width: {{ specter.info["utxorescan"] }}%'></div>
        </div>
        <script>
            let utxoRescanProgress = '{{ specter.info["utxorescan"] }}';
            let utxoRescanActive = true;
            async function fetchUTXORescanProgress() {
                try {
                    const response = await fetch(
                        "{{ url_for('wallets_endpoint_api.get_scantxoutset_status') }}",
                        {
                            method: 'GET'
                        }
                    );
                    let result = await response.json();
                    utxoRescanActive = result.active;
                    utxoRescanProgress = result.progress;
                    let walletRescanData = document.getElementById('wallet_rescan_data');
                    let walletRescanPercentsSettings = document.getElementById('wallet_rescan_percents');
                    let walletRescanPercents = document.getElementById('{{ specter.utxorescanwallet }}_balances_wallet_rescan_percents');
                    if (utxoRescanActive) {
                        document.getElementById('utxo_rescan_progress').style.width = utxoRescanProgress + '%';
                        if (walletRescanPercents) {
                            walletRescanPercents.innerHTML = (Math.round(parseFloat(utxoRescanProgress) * 100) / 100).toFixed(2);
                        } else if (walletRescanPercentsSettings) {
                            walletRescanPercentsSettings.innerHTML = (Math.round(parseFloat(utxoRescanProgress) * 100) / 100).toFixed(2);
                        }
                        setTimeout(fetchUTXORescanProgress, 1000);
                    } else {
                        document.getElementById('utxo_rescan_progress').style.display = 'none';
                        if (walletRescanData) {
                            walletRescanData.style.display = 'none';
                        }
                        if (walletRescanData || walletRescanPercentsSettings) {
                            window.location = window.location.href;
                        }
                    }
                } catch(e) {
                    console.log('Caught error:', e);
                    return { success: false, error: e };
                }
            }
            setTimeout(fetchUTXORescanProgress, 1000);
        </script>
        {% endif %}
        {% if specter.setup_status.stage != "start" and specter.rpc is none %}
            {{ sidebar_btn(url_for('setup_endpoint.' + specter.setup_status.stage), _('See setup progress'), class='btn action', icon=false) }}
        {% endif %}
        <div class="separator">
            <span id="toggle_wallets_list" style="cursor: pointer;">{{ _("Wallets") }} &nbsp; &#9660;</span>
            {% if (specter.wallet_manager.wallets | length) > 1 %}
                <a class="note" id="wallets_overview_link" href="{{ url_for('wallets_endpoint.wallets_overview') }}" style="cursor: pointer;">
                    {{ _("Wallets overview") }}
                </a>
            {% endif %}
        </div>
        <div id="wallets_list">
            <span id="wallets-loading-indicator" class="note {% if not specter.wallet_manager.is_loading or not specter.chain %}hidden{% endif %}" style="text-align: left; margin-left: 20px; margin-top: 5px;">
                <img height="16px" class="spinning" id="wallet-manager-loader" style="vertical-align: sub;" src="{{ url_for('static', filename='img/refresh.svg') }}" />
                {{ _("Updating wallets data...") }}
            </span>
            <span id="wallets-loading-done" class="note hidden" style="text-align: left; margin: 5px 5px 5px 20px;">
                {{ _("Finished updating your wallets") }}
                <br>
                <span id="wallets-loading-done-refresh" class="explorer-link" onclick="location.reload()" style="text-decoration: underline; margin-left: 20px;">
                    {{ _("Click here to refresh") }}
                </span>
            </span>
            {% set loading_wallets = [] %}
            {% for wallet in specter.wallet_manager.wallets_update_list if wallet not in specter.wallet_manager.wallets_names %}
                {% set loading_wallets = loading_wallets.append(specter.wallet_manager.wallets_update_list[wallet]) %}
            {% endfor %}
            {% if (specter.device_manager.devices | length) != 0 and specter.chain %}
                {% from 'includes/sidebar/components/sidebar_wallet_list_item.jinja' import sidebar_wallet_list_item %}
                {% for wallet in ((specter.wallet_manager.wallets.values()|list) + loading_wallets) | sort(attribute='name') %}
                    {{ sidebar_wallet_list_item(wallet, wallet_alias, specter.info.chain, loading=(wallet in loading_wallets)) }}
                {% endfor %}
            {% endif %}
            {% if specter.chain %}
                {{ sidebar_btn(url_for('wallets_endpoint.new_wallet_type'), _('Add new wallet'), 'btn_new_wallet') }}
                {% if specter.wallet_manager.failed_load_wallets %}
                    <form action="{{ url_for('wallets_endpoint.failed_wallets') }}" method="POST">
                        <input type="hidden" class="csrf-token" name="csrf_token" value="{{ csrf_token() }}"/>
                        <p class="warning center">
                            <img src="{{ url_for('static', filename='img/warning_sign.svg') }}" style="width: 20px;"/><br>{{ _("Failed to load some wallets") }}<br>
                            <button class="btn" name="action" value="retry_loading_wallets" style="margin: auto;">{{ _("Retry loading wallets") }}</button>
                            <button type="button" class="btn" onclick="showPageOverlay('failed_wallets_popup')" style="margin: auto; margin-top: 5px;">{{ _("Show Details") }}</button>
                        </p>
                    </form>
                    <div class="hidden" id="failed_wallets_popup">
                        {% for wallet in specter.wallet_manager.failed_load_wallets %}
                            <div class="card">
                                <h1>{{ _("Wallet Name") }}: {{wallet.name}}</h1>
                                <h2>{{ _("Error Details") }}:</h2>
                                <p style="color: red">{{wallet.loading_error}}</p>
                                <br><br>
                                <form action="{{ url_for('wallets_endpoint.failed_wallets') }}" method="POST" class="row center">
                                    <input type="hidden" class="csrf-token" name="csrf_token" value="{{ csrf_token() }}"/>
                                    <input type="hidden" name="wallet_data" value='{{ wallet|tojson }}' />
                                    <a class="btn" id="download_failed_wallet_{{wallet.alias}}" download="{{ wallet.name }}.json" style="width: 180px; height: 35px; margin-top: 1.5px;">{{ _("Download wallet file") }}</a>&nbsp;&nbsp;
                                    <button class="btn" type="submit" name="action" value="importwallet" formaction="{{ url_for('wallets_endpoint.new_wallet', wallet_type='import_wallet') }}">{{ _("Recreate the wallet") }}</button>&nbsp;&nbsp;
                                    <button class="btn" name="action" value="delete_failed_wallet">{{ _("Delete wallet") }}</button>
                                </form>
                            </div>
                            <script>
                                document.addEventListener("DOMContentLoaded", function(){
                                    document.getElementById('download_failed_wallet_{{wallet.alias}}').href = 'data:text/json,' + encodeURIComponent(`{{ wallet|tojson }}`);
                                });
                            </script>
                        {% endfor %}
                    </div>
                {% endif %}
            {% elif not specter.setup_status.stage == "bitcoind_datadir" %}
                <p class="warning" style="border: 1px solid #fff;">
                <img src="{{ url_for('static', filename='img/info_sign.svg') }}" style="width: 20px;"/>
                <br>{{ _("Wallets are unavailable if Specter is not connected to Bitcoin Core!") }}<br>
                {% if current_user.is_admin %}
                <a style="margin: 5px; transform: scale(0.9); font-size: 1em;" class="btn" href="{{ url_for('nodes_endpoint.node_settings', node_alias=specter.node.alias) }}">
                    <img src="{{ url_for('static', filename='img/gear.svg') }}" style="width: 24px; margin: 0px;" class="svg-white">{{ _('Configure Node') }}
                </a>
                {% endif %}
                </p>
            {% endif %}

        </div>

        <div class="separator">
            <span id="toggle_devices_list" style="cursor: pointer;">{{ _("Devices") }} &nbsp; &#9660;</span>
        </div>
        {% from 'includes/sidebar/components/sidebar_device_list_item.jinja' import sidebar_device_list_item %}
        <div id="devices_list">
            {% for device_name in specter.device_manager.devices_names %}
                    {{ sidebar_device_list_item(specter.device_manager.devices[device_name], device_alias) }}
            {% endfor %}
            {{ sidebar_btn(url_for('devices_endpoint.new_device_type'), _('Add new device'),'btn_new_device') }}
        </div>
        {% include "services/sidebar_services_list.jinja" %}
        {{ sidebar_btn(url_for('services_endpoint.choose'), 'Choose plugins', 'btn_plugins') }}
        <br>
        <div class="footer">
	        <span>{{ _("Specter Version:") }} <strong>{{ specter.version.current }}</strong></span>
            <a style="color: #fff; font-size: 1.1em; margin: 10px; text-align: center;" href="{{ url_for('welcome_endpoint.about') }}">
            {{ _("About Specter") }}<br>
            <img src="{{ url_for('static', filename='img/ghost_3d.png') }}" style="width: 35px;"/>
            </a>
        </div>
    </nav>
</div>
<script>

    async function updateWalletsLoadingData() {
        try {
            let url="{{ url_for('wallets_endpoint_api.wallets_loading') }}"
            const response = await fetch(
                url,
                {
                    method: 'GET'
                }
            );
            let result = await response.json();
            if (result.is_loading) {
                setTimeout(updateWalletsLoadingData, 1000);
            } else {
                document.getElementById("wallets-loading-indicator").classList.add("hidden");
                {% if not specter.wallet_manager.failed_load_wallets %}
                if ('{{wallet_alias}}' && window.location.href.endsWith('history/')) {
                    document.getElementById("wallets-loading-done").classList.remove("hidden");
                }
                {% endif %}
            }
            for (wallet of result.loaded_wallets) {
                document.getElementById(`${wallet}-sidebar-loading-placeholder`).style.display = 'none';
                document.getElementById(`${wallet}-sidebar-list-item`).style.display = 'flex';
            }
            for (wallet of result.failed_load_wallets) {
                document.getElementById(`${wallet}-sidebar-loading-placeholder`).style.display = 'none';
                document.getElementById(`${wallet}-sidebar-list-item`).style.display = 'none';
            }
        } catch(e) {
            console.log('Caught error:', e);
            return { success: false, error: e };
        }
    }

    function toggleList(type, display_text) {
        let titleButton = document.getElementById('toggle_' + type + '_list');
        let list = document.getElementById(type + '_list');
        if (list.style.display === 'none') {
            list.style.display = 'block';
            titleButton.innerHTML = capitalize(display_text) + ' &nbsp; &#9660;';
        } else {
            list.style.display = 'none';
            titleButton.innerHTML = capitalize(display_text) + ' &nbsp; &#9654;';
        }
    }

    document.addEventListener("DOMContentLoaded", function(){
        if ('{{ specter.device_manager.devices_names | length }}' == '0') {
            document.getElementById('toggle_devices_list').innerHTML = `{{ _("Devices") }}`;
        } else {
            document.getElementById('toggle_devices_list').addEventListener('click', (event) => {
                toggleList('devices', '{{ _("Devices") }}');
            });
        }
        {% if specter.device_manager.devices_names|length > 0 %}
            // Make the default state hidden
            toggleList('devices', '{{ _("Devices") }}');
        {% endif %}

        if ('{{ specter.wallet_manager.wallets_names | length }}' == '0') {
            document.getElementById('toggle_wallets_list').innerHTML = `{{ _("Wallets") }}`;
        } else {
            document.getElementById('toggle_wallets_list').addEventListener('click', (event) => {
                toggleList('wallets', '{{ _("Wallets") }}');
            });
        }

        if ('{{ specter.service_manager.service_names | length }}' == '0') {
            document.getElementById('toggle_services_list').innerHTML = 'Plugins';
        } else {
            document.getElementById('toggle_services_list').addEventListener('click', (event) => {
                toggleList('services');
            });
        }
        {% if specter.wallet_manager.is_loading %}
            updateWalletsLoadingData();
        {% endif %}
    });
</script>
