{% extends "secrets/secret_addedit.html" %}
{% load django_bootstrap5 %}
{% load i18n %}
{% block form_attributes %}enctype="multipart/form-data"{% endblock %}
{% block content_type_fields %}
    <div class="row mb-3 required">
        <label class="col-xl-2 col-form-label form-label securely-saved" for="{{ form.file.id_for_label }}">
            {{ form.file.label }}
        </label>
        <div class="col-xl-8">
            <div class="input-group {% if form.file.errors %}is-invalid{% endif %}">
                <input type="text" class="form-control {% if form.file.errors %}is-invalid{% endif %}" readonly
                       autocomplete="off" id="file-text"
                       placeholder="{% if secret %}{% translate "(unchanged)" %}{% else %}{% translate "No file selected" %}{% endif %}">
                <div class="btn-group">
                    <input id="id_file" name="file" type="file" class="d-none"
                           {% if not secret %}required="required"{% endif %}>
                    <label class="btn btn-outline-accent btn-file" for="id_file">
                        {% translate "Browse..." %}
                    </label>
                </div>
            </div>
            {% for error in form.file.errors %}
                <div class="invalid-feedback">{{ error }}</div>
            {% endfor %}
        </div>
    </div>
{% endblock %}

{% block additionalJS %}
    {{ block.super }}
    <script>
        window.addEventListener('DOMContentLoaded', () => {
            const fileInput = document.getElementById('id_file')
            const fileNameInput = document.getElementById('file-text')
            fileInput.addEventListener('change', () => {
                fileNameInput.value = fileInput.files[0].name
            })
            window.addEventListener('load', () => {
                /* Set file name even after going back in browser history */
                if (fileInput.files.length === 1) {
                    fileNameInput.value = fileInput.files[0].name
                }
            })
        })
    </script>
{% endblock %}
