<!DOCTYPE html>
<html lang="de">
<head>
    <%- include('partials/head') %>
</head>
<body class="min-h-screen flex flex-col transition-colors duration-300 bg-gray-50 dark:bg-gray-900 text-gray-900 dark:text-gray-100" id="body">
    <%- include('partials/header', { hideSettings: true }) %>

    <main class="flex-1 container mx-auto px-4 py-8 max-w-4xl">
        <!-- Back link -->
        <a href="/" class="inline-flex items-center gap-2 text-sm text-blue-600 dark:text-blue-400 hover:underline mb-6">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
            </svg>
            Zurück zur Übersicht
        </a>

        <div class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 mb-8">
            <div class="flex flex-wrap items-center justify-between gap-3 mb-4">
                <div>
                    <h2 class="text-lg font-semibold text-gray-800 dark:text-white">Postfach — unverknüpfte E-Mails</h2>
                    <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">
                        E-Mails aus dem Postfach, die keiner Bewerbung zugeordnet sind. Hier per Hand einer Bewerbung zuweisen.
                    </p>
                </div>
                <% if (mailConfigured) { %>
                <form action="/email/fetch" method="POST" class="shrink-0">
                    <input type="hidden" name="back" value="/postfach">
                    <button type="submit" class="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded-md text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path></svg>
                        Postfach abrufen
                    </button>
                </form>
                <% } %>
            </div>

            <% if (!mailConfigured) { %>
                <div class="flex items-center gap-3 rounded-lg bg-yellow-50 dark:bg-yellow-900/30 border border-yellow-200 dark:border-yellow-800 px-4 py-3">
                    <svg class="w-5 h-5 text-yellow-600 dark:text-yellow-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path></svg>
                    <span class="text-sm text-yellow-800 dark:text-yellow-200">E-Mail ist nicht konfiguriert. Bitte <code>MAIL_HOST</code>, <code>MAIL_USER</code> und <code>MAIL_PASSWORD</code> in der <code>.env</code> setzen.</span>
                </div>
            <% } else { %>

                <% if (mailError) { %>
                    <div class="rounded-lg bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 px-4 py-3 mb-4 text-sm text-red-800 dark:text-red-200"><%= mailError %></div>
                <% } %>
                <% if (mailOk) { %>
                    <div class="rounded-lg bg-green-50 dark:bg-green-900/30 border border-green-200 dark:border-green-800 px-4 py-3 mb-4 text-sm text-green-800 dark:text-green-200"><%= mailOk %></div>
                <% } %>

                <% if (emails && emails.length) { %>
                    <ul class="space-y-4">
                        <% emails.forEach(function(e){ %>
                            <li class="rounded-lg border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-700/40 px-4 py-4">
                                <div class="flex flex-wrap items-center justify-between gap-2 mb-1">
                                    <div class="flex items-center gap-2 min-w-0">
                                        <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-600 text-white">Empfangen</span>
                                        <span class="text-sm text-gray-700 dark:text-gray-200 truncate">Von: <%= e.from_addr || '(unbekannt)' %></span>
                                    </div>
                                    <span class="text-xs text-gray-500 dark:text-gray-400 shrink-0"><%= e.email_date ? new Date(e.email_date).toLocaleString('de-DE', { timeZone: 'Europe/Berlin' }) : '' %></span>
                                </div>
                                <p class="text-sm font-medium text-gray-800 dark:text-gray-100 mb-1"><%= e.subject || '(kein Betreff)' %></p>
                                <% if (e.display_srcdoc) { %>
                                    <iframe class="email-html-frame w-full border border-gray-200 dark:border-gray-600 rounded bg-white" style="height:6rem"
                                        sandbox="allow-same-origin" referrerpolicy="no-referrer"
                                        srcdoc="<%= e.display_srcdoc %>"></iframe>
                                <% } else { %>
                                    <p class="email-body whitespace-pre-wrap break-words text-sm leading-relaxed text-gray-700 dark:text-gray-300 max-h-40 overflow-hidden"><%= e.body_text || '' %></p>
                                    <% if (e.body_text && e.body_text.length > 600) { %>
                                    <button type="button" class="email-toggle text-xs text-blue-600 hover:text-blue-800 dark:text-blue-400 hover:underline mt-1"
                                        data-expanded="false">Vollständig anzeigen</button>
                                    <% } %>
                                <% } %>

                                <% if (e.anhaenge && e.anhaenge.length) { %>
                                    <div class="mt-2 flex flex-wrap gap-2">
                                        <% e.anhaenge.forEach(function(a){ %>
                                            <a href="/email-anhaenge/<%= a.id %>/download" class="inline-flex items-center gap-1 text-xs px-2 py-1 rounded border border-gray-300 dark:border-gray-600 text-blue-600 dark:text-blue-400 hover:underline">
                                                <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"></path></svg>
                                                <%= a.name || 'Anhang' %>
                                            </a>
                                        <% }); %>
                                    </div>
                                <% } %>

                                <!-- Assign to an existing application (searchable) + delete -->
                                <div class="mt-3 border-t border-gray-200 dark:border-gray-600 pt-3 flex flex-wrap items-end gap-2">
                                    <form action="/postfach/<%= e.id %>/zuweisen" method="POST" class="flex-1 min-w-52 flex flex-wrap items-end gap-2" data-assign-form>
                                        <div class="flex-1 min-w-52 relative" data-combo>
                                            <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Bewerbung zuweisen</label>
                                            <input type="text" class="combo-input w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-800 dark:text-white text-sm"
                                                placeholder="Firma, Stelle oder Ort suchen…" autocomplete="off"
                                                role="combobox" aria-expanded="false" aria-autocomplete="list">
                                            <input type="hidden" name="bewerbung_id" class="combo-value">
                                            <ul class="combo-list hidden absolute z-20 left-0 right-0 mt-1 max-h-56 overflow-auto rounded-md border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-700 shadow-lg text-sm"></ul>
                                        </div>
                                        <button type="submit"
                                            class="inline-flex items-center gap-1.5 px-4 py-2 text-sm bg-blue-600 hover:bg-blue-700 text-white rounded-md transition-colors">
                                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>
                                            Zuweisen
                                        </button>
                                    </form>
                                    <form action="/postfach/<%= e.id %>/delete" method="POST"
                                          onsubmit="return confirm('Diese E-Mail endgültig aus dem Postfach löschen?');">
                                        <button type="submit"
                                            class="inline-flex items-center gap-1.5 px-4 py-2 text-sm border border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-md transition-colors">
                                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                                            Löschen
                                        </button>
                                    </form>
                                </div>
                            </li>
                        <% }); %>
                    </ul>
                <% } else { %>
                    <div class="text-center py-10">
                        <svg class="w-12 h-12 mx-auto text-gray-300 dark:text-gray-600 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path></svg>
                        <p class="text-sm text-gray-500 dark:text-gray-400">Keine unverknüpften E-Mails. Alle Nachrichten im Postfach sind bereits einer Bewerbung zugeordnet.</p>
                    </div>
                <% } %>

            <% } %>
        </div>
    </main>

    <%- include('partials/footer') %>

    <script>
        window.__bewerbungen = <%- JSON.stringify((bewerbungen || []).map(function (b) { return { id: b.id, firma: b.firma, stelle: b.stelle, ort: b.ort, datum: b.datum }; })).replace(/</g, '\\u003c') %>;
    </script>
    <script>
        (function () {
            const cy = document.getElementById('currentYear');
            if (cy) cy.textContent = new Date().getFullYear();

            // Size each sandboxed e-mail iframe to its rendered content. The
            // sandbox omits allow-scripts, so mail scripts never run; allow-same-
            // origin lets us measure the document height.
            function fitFrame(f) {
                try {
                    var doc = f.contentDocument || (f.contentWindow && f.contentWindow.document);
                    if (!doc || !doc.body) return;
                    var h = Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight);
                    if (h > 0) f.style.height = (h + 6) + 'px';
                } catch (e) { /* leave default height */ }
            }
            document.querySelectorAll('.email-html-frame').forEach(function (f) {
                f.addEventListener('load', function () { fitFrame(f); });
                fitFrame(f);
                setTimeout(function () { fitFrame(f); }, 400);
                setTimeout(function () { fitFrame(f); }, 1500);
            });

            // Expand/collapse the full e-mail body for each card.
            document.querySelectorAll('.email-toggle').forEach(function (btn) {
                btn.addEventListener('click', function () {
                    var body = btn.previousElementSibling;
                    if (!body || !body.classList.contains('email-body')) return;
                    var expanded = btn.dataset.expanded === 'true';
                    body.classList.toggle('max-h-40', expanded);
                    body.classList.toggle('overflow-hidden', expanded);
                    btn.dataset.expanded = expanded ? 'false' : 'true';
                    btn.textContent = expanded ? 'Vollständig anzeigen' : 'Weniger anzeigen';
                });
            });

            // --- Searchable application picker (combobox) for assigning e-mails ---
            var apps = Array.isArray(window.__bewerbungen) ? window.__bewerbungen : [];
            function unesc(s) {
                return String(s == null ? '' : s)
                    .replace(/&lt;/g, '<').replace(/&gt;/g, '>')
                    .replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, '&');
            }
            function fmtDate(d) { if (!d) return ''; try { return new Date(d).toLocaleDateString('de-DE'); } catch (e) { return ''; } }
            apps.forEach(function (b) {
                b._label = unesc(b.firma) + (b.stelle ? ' · ' + unesc(b.stelle) : '');
                b._sub = [unesc(b.ort || ''), fmtDate(b.datum)].filter(Boolean).join(' · ');
                b._search = (b._label + ' ' + unesc(b.ort || '') + ' ' + fmtDate(b.datum)).toLowerCase();
            });

            document.querySelectorAll('[data-combo]').forEach(function (combo) {
                var input = combo.querySelector('.combo-input');
                var hidden = combo.querySelector('.combo-value');
                var list = combo.querySelector('.combo-list');
                var items = [], active = -1;

                function open() { list.classList.remove('hidden'); input.setAttribute('aria-expanded', 'true'); }
                function close() { list.classList.add('hidden'); input.setAttribute('aria-expanded', 'false'); active = -1; }
                function choose(b) { hidden.value = b.id; input.value = b._label; close(); }
                function highlight() {
                    Array.prototype.forEach.call(list.children, function (li, i) {
                        li.classList.toggle('bg-blue-100', i === active);
                        li.classList.toggle('dark:bg-gray-600', i === active);
                        if (i === active && li.scrollIntoView) li.scrollIntoView({ block: 'nearest' });
                    });
                }
                function render(q) {
                    var tokens = q.toLowerCase().split(/\s+/).filter(Boolean);
                    items = apps.filter(function (b) {
                        return tokens.every(function (t) { return b._search.indexOf(t) > -1; });
                    }).slice(0, 50);
                    list.innerHTML = '';
                    if (!items.length) {
                        var empty = document.createElement('li');
                        empty.className = 'px-3 py-2 text-gray-400';
                        empty.textContent = apps.length ? 'Keine Treffer' : 'Noch keine Bewerbungen vorhanden';
                        list.appendChild(empty);
                        open(); return;
                    }
                    items.forEach(function (b) {
                        var li = document.createElement('li');
                        li.className = 'combo-item cursor-pointer px-3 py-2 hover:bg-blue-50 dark:hover:bg-gray-600';
                        var top = document.createElement('div');
                        top.className = 'font-medium text-gray-800 dark:text-gray-100';
                        top.textContent = b._label;
                        var sub = document.createElement('div');
                        sub.className = 'text-xs text-gray-500 dark:text-gray-400';
                        sub.textContent = b._sub;
                        li.appendChild(top); li.appendChild(sub);
                        li.addEventListener('mousedown', function (ev) { ev.preventDefault(); choose(b); });
                        list.appendChild(li);
                    });
                    active = -1; open();
                }

                input.addEventListener('input', function () { hidden.value = ''; render(input.value); });
                input.addEventListener('focus', function () { render(input.value); });
                input.addEventListener('keydown', function (ev) {
                    if (list.classList.contains('hidden')) return;
                    if (ev.key === 'ArrowDown') { ev.preventDefault(); active = Math.min(active + 1, items.length - 1); highlight(); }
                    else if (ev.key === 'ArrowUp') { ev.preventDefault(); active = Math.max(active - 1, 0); highlight(); }
                    else if (ev.key === 'Enter') { if (active > -1 && items[active]) { ev.preventDefault(); choose(items[active]); } }
                    else if (ev.key === 'Escape') { close(); }
                });
                document.addEventListener('click', function (ev) { if (!combo.contains(ev.target)) close(); });
            });

            // Block assignment submits until an application has actually been picked.
            document.querySelectorAll('[data-assign-form]').forEach(function (f) {
                f.addEventListener('submit', function (ev) {
                    var hidden = f.querySelector('.combo-value');
                    if (!hidden || !hidden.value) {
                        ev.preventDefault();
                        var inp = f.querySelector('.combo-input');
                        if (inp) inp.focus();
                        alert('Bitte zuerst eine Bewerbung aus der Liste auswählen.');
                    }
                });
            });
        })();
    </script>
</body>
</html>