{% extends "base.html" %}
{% block title %}{{ 'Konto bearbeiten' if edit_mode else 'Neues Konto' }} - MailsAuswerten{% endblock %}
{% block content %}
<p style="margin-bottom: 1rem;"><a href="/accounts" class="link">&larr; Zurueck zur Liste</a></p>

<h1>{{ 'Konto bearbeiten' if edit_mode else 'Neues Konto anlegen' }}</h1>

<div class="card">
    <form method="post" id="accountForm">
        <h2 style="margin-bottom: 1rem;">Kontodaten</h2>

        <label for="name">Kontoname</label>
        <input type="text" id="name" name="name" value="{{ account.name }}"
               {{ 'readonly style="background:#eee;"' if edit_mode }} required>

        <h2 style="margin: 1.5rem 0 1rem;">IMAP-Server</h2>
        <div class="form-row">
            <div>
                <label for="server">Server</label>
                <input type="text" id="server" name="server" value="{{ account.server }}" required>
            </div>
            <div>
                <label for="port">Port</label>
                <input type="number" id="port" name="port" value="{{ account.port or 993 }}">
            </div>
        </div>
        <div class="form-row">
            <div>
                <label for="username">Benutzername</label>
                <input type="text" id="username" name="username" value="{{ account.username }}" required>
            </div>
            <div>
                <label for="password">Passwort</label>
                <input type="password" id="password" name="password" value="{{ account.password }}" required>
            </div>
        </div>
        <div class="form-row">
            <div>
                <label for="use_ssl">SSL verwenden</label>
                <select id="use_ssl" name="use_ssl">
                    <option value="true" {{ 'selected' if account.use_ssl in (true, 'true', True) }}>Ja</option>
                    <option value="false" {{ 'selected' if account.use_ssl in (false, 'false', False) }}>Nein</option>
                </select>
            </div>
            <div></div>
        </div>

        <h2 style="margin: 1.5rem 0 1rem;">Postfach</h2>
        <div class="form-row">
            <div>
                <label for="folder">Ordner</label>
                <div style="display: flex; gap: 0.5rem;">
                    <select id="folderSelect" style="flex: 1; display: none;" onchange="document.getElementById('folder').value = this.value;">
                    </select>
                    <input type="text" id="folder" name="folder" value="{{ account.folder or 'INBOX' }}" style="flex: 1;">
                    <button type="button" class="btn btn-primary btn-sm" id="loadFoldersBtn"
                            onclick="loadFolders()" style="white-space: nowrap;">
                        Ordner laden
                    </button>
                </div>
            </div>
            <div>
                <label for="search_criteria">Suchkriterium</label>
                <select id="search_criteria" name="search_criteria">
                    <option value="UNSEEN" {{ 'selected' if account.search_criteria == 'UNSEEN' }}>Nur ungelesene (UNSEEN)</option>
                    <option value="ALL" {{ 'selected' if account.search_criteria == 'ALL' }}>Alle (ALL)</option>
                </select>
            </div>
        </div>

        <div style="margin-top: 0.5rem;">
            <label style="display: inline-flex; align-items: center; gap: 0.5rem; font-weight: normal; cursor: pointer;">
                <input type="checkbox" name="include_subfolders" value="true"
                       {{ 'checked' if account.get('include_subfolders', false) in (true, 'true', True) }}
                       id="includeSubfolders">
                <span>Unterordner einbeziehen</span>
            </label>
            <small style="display: block; color: #888; margin-top: 0.2rem;">
                Wenn aktiviert, werden auch alle Unterordner des gewaehlten Ordners durchsucht.
            </small>
        </div>

        <div id="subfolderPreview" style="margin-top: 0.5rem; display: none;">
            <small style="color: #555;"><strong>Unterordner:</strong> <span id="subfolderList"></span></small>
        </div>

        <h2 style="margin: 1.5rem 0 1rem;">Abruf-Limit</h2>
        <div class="form-row">
            <div>
                <label for="max_emails">Max. E-Mails pro Abruf (0 = unbegrenzt)</label>
                <input type="number" id="max_emails" name="max_emails" value="{{ account.max_emails or 0 }}" min="0">
            </div>
            <div></div>
        </div>

        <div style="display: flex; gap: 1rem; margin-top: 1.5rem;">
            <button type="submit" class="btn btn-success">Speichern</button>
        </div>
    </form>
</div>

{% if edit_mode %}
<div class="card">
    <h2 style="margin-bottom: 1rem;">Verbindungstest</h2>
    <p style="margin-bottom: 1rem; color: #666;">Prueft ob die IMAP-Zugangsdaten gueltig sind.</p>
    <form method="post" action="/accounts/{{ account.name }}/test">
        <button type="submit" class="btn btn-primary"
                onclick="this.disabled=true; this.textContent='Teste...'; this.form.submit();">
            Verbindung testen
        </button>
    </form>
</div>
{% endif %}

<script>
let allFolders = [];

function loadFolders() {
    const btn = document.getElementById('loadFoldersBtn');
    const originalText = btn.textContent;
    btn.disabled = true;
    btn.textContent = 'Lade...';

    const data = {
        server: document.getElementById('server').value,
        port: parseInt(document.getElementById('port').value) || 993,
        username: document.getElementById('username').value,
        password: document.getElementById('password').value,
        use_ssl: document.getElementById('use_ssl').value === 'true',
    };

    {% if edit_mode %}
    data.account_name = '{{ account.name }}';
    {% endif %}

    fetch('/api/folders', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data),
    })
    .then(r => r.json())
    .then(result => {
        btn.disabled = false;
        btn.textContent = originalText;

        if (result.error) {
            alert('Fehler: ' + result.error);
            return;
        }

        allFolders = result.folders;
        const select = document.getElementById('folderSelect');
        const input = document.getElementById('folder');
        const currentValue = input.value;

        select.innerHTML = '';
        result.folders.forEach(f => {
            const opt = document.createElement('option');
            opt.value = f;
            opt.textContent = f;
            if (f === currentValue) opt.selected = true;
            select.appendChild(opt);
        });

        select.style.display = 'block';
        input.style.display = 'none';

        select.onchange = function() {
            input.value = this.value;
            showSubfolders();
        };

        showSubfolders();
    })
    .catch(err => {
        btn.disabled = false;
        btn.textContent = originalText;
        alert('Verbindungsfehler: ' + err.message);
    });
}

function showSubfolders() {
    const folder = document.getElementById('folder').value;
    const preview = document.getElementById('subfolderPreview');
    const listEl = document.getElementById('subfolderList');

    if (allFolders.length === 0) {
        preview.style.display = 'none';
        return;
    }

    const subs = allFolders.filter(f =>
        f !== folder && (f.startsWith(folder + '.') || f.startsWith(folder + '/'))
    );

    if (subs.length > 0) {
        listEl.textContent = subs.join(', ');
        preview.style.display = 'block';
    } else {
        listEl.textContent = '(keine)';
        preview.style.display = 'block';
    }
}
</script>
{% endblock %}
