{{define "webmail_folder.html"}}
<!DOCTYPE html>
<html lang="en" data-bs-theme="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{if .search_query}}Search: {{.search_query}}{{else}}{{.active_folder}}{{end}} - Webmail</title>
    <link href="/webmail/static/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="/webmail/static/vendor/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        body { background-color: #1a1a1a; color: #e0e0e0; }
        .card { background-color: #2d2d2d; border: 1px solid #404040; }
        .table-dark { --bs-table-bg: #2d2d2d; --bs-table-border-color: #404040; }
        .folder-link.active { background-color: #0d6efd; color: #fff !important; }
        .msg-unread { font-weight: 600; }
        .msg-row { cursor: grab; }
        .msg-row.dragging { opacity: 0.4; }
        .folder-link.drop-hover { background-color: #0d6efd; color: #fff !important; outline: 2px dashed #6ea8fe; outline-offset: -2px; }
        .folder-unread-badge { font-size: .7rem; }
        .msg-row-older { display: none; }
        .msg-group-toggle { cursor: pointer; }
    </style>
</head>
<body>
    {{template "csrf_script" .}}
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark mb-4">
        <div class="container-fluid">
            <span class="navbar-brand mb-0 h1"><i class="bi bi-inbox-fill me-2"></i>Webmail <small class="text-muted">{{.mailbox.Email}}</small></span>
            <div class="navbar-nav flex-row gap-2 ms-auto">
                <a href="/webmail/mail/INBOX" class="btn btn-outline-light btn-sm"><i class="bi bi-envelope me-1"></i>Mail</a>
                <button type="button" onclick="openCompose('/webmail/mail/compose')" class="btn btn-outline-light btn-sm"><i class="bi bi-pencil-square me-1"></i>Compose</button>
                <a href="/webmail/rules" class="btn btn-outline-light btn-sm"><i class="bi bi-funnel me-1"></i>Rules</a>
                <a href="/webmail/certs" class="btn btn-outline-light btn-sm"><i class="bi bi-shield-lock me-1"></i>Certs</a>
                <a href="/webmail/account" class="btn btn-outline-light btn-sm"><i class="bi bi-gear me-1"></i>Account</a>
                <form method="post" action="/webmail/logout" class="d-inline">
                    <button type="submit" class="btn btn-outline-light btn-sm"><i class="bi bi-box-arrow-right me-1"></i>Sign out</button>
                </form>
            </div>
        </div>
    </nav>

    <div class="toast-container position-fixed top-0 end-0 p-3" style="z-index: 1090;">
        {{range .flashes}}
        <div class="toast align-items-center text-bg-{{if eq .Category "error"}}danger{{else}}{{.Category}}{{end}} border-0" role="alert" aria-live="assertive" aria-atomic="true" data-bs-autohide="false">
            <div class="d-flex">
                <div class="toast-body">
                    <i class="bi bi-{{if eq .Category "error"}}exclamation-triangle{{else if eq .Category "success"}}check-circle{{else}}info-circle{{end}} me-2"></i>
                    {{.Message}}
                </div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
        </div>
        {{end}}
    </div>

    <div class="container-fluid pb-5">
        <div class="row">
            <div class="col-lg-2 mb-4">
                <div class="card">
                    <div class="card-body p-2">
                        <form method="get" action="/webmail/mail/search" class="mb-2">
                            <div class="input-group input-group-sm">
                                <input type="search" name="q" id="mailSearchInput" class="form-control" placeholder="Search all mail" value="{{.search_query}}">
                                <button type="submit" class="btn btn-outline-light"><i class="bi bi-search"></i></button>
                            </div>
                        </form>
                        <div class="list-group list-group-flush">
                            {{$active := .active_folder}}
                            {{$unread := .unread_counts}}
                            {{range .folders}}
                            <div class="d-flex align-items-center folder-row">
                                <a href="/webmail/mail/{{.}}" data-folder="{{.}}" class="list-group-item list-group-item-action bg-transparent text-white folder-link flex-grow-1 d-flex justify-content-between align-items-center {{if eq . $active}}active{{end}}">
                                    <span><i class="bi bi-folder2 me-1"></i>{{.}}</span>
                                    {{$n := index $unread .}}
                                    {{if $n}}<span class="badge bg-primary rounded-pill folder-unread-badge">{{$n}}</span>{{end}}
                                </a>
                                {{if not (isStandardFolder .)}}
                                <form method="post" action="/webmail/mail/folders/{{.}}/remove" class="d-inline">
                                    <button type="submit" class="btn btn-sm btn-outline-danger border-0" title="Remove folder" data-confirm="Remove folder &quot;{{.}}&quot;? Any mail in it moves to INBOX."><i class="bi bi-x-lg"></i></button>
                                </form>
                                {{end}}
                            </div>
                            {{end}}
                        </div>
                        <hr class="my-2">
                        <form method="post" action="/webmail/mail/folders/add" class="d-flex gap-1">
                            <input type="text" class="form-control form-control-sm" name="name" placeholder="New folder" maxlength="60" required>
                            <button type="submit" class="btn btn-sm btn-outline-primary" title="Create folder"><i class="bi bi-plus-lg"></i></button>
                        </form>
                    </div>
                </div>
            </div>

            <div class="col-lg-10 mb-4">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">
                            {{if .search_query}}<i class="bi bi-search me-2"></i>Search results for &ldquo;{{.search_query}}&rdquo;
                            {{else}}<i class="bi bi-folder2-open me-2"></i>{{.active_folder}}{{end}}
                        </h5>
                        <small class="text-muted">{{.total}} message{{if ne .total 1}}s{{end}}</small>
                    </div>
                    <div class="card-body p-0">
                        {{if .messages}}
                        <div class="table-responsive">
                            <table class="table table-dark table-hover mb-0">
                                <thead>
                                    <tr>
                                        {{if not .search_query}}<th>{{if eq .active_folder "Sent"}}To{{else}}From{{end}}</th>{{else}}<th>From / To</th>{{end}}
                                        <th>Subject</th>
                                        {{if .search_query}}<th>Folder</th>{{end}}
                                        <th>Date</th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {{$folders := .folders}}
                                    {{$showFolderCol := .search_query}}
                                    {{range .messages}}
                                    {{$rowHref := printf "/webmail/mail/%s/%d" .Folder .ID}}
                                    {{if eq .Folder "Drafts"}}{{$rowHref = printf "/webmail/mail/compose?draft=%d&folder=Drafts" .ID}}{{end}}
                                    <tr class="{{if .Unread}}msg-unread{{end}} msg-row{{if .Collapsed}} msg-row-older{{end}}" draggable="true" data-uid="{{.ID}}" data-folder="{{.Folder}}">
                                        <td><a class="text-reset text-decoration-none" href="{{$rowHref}}">{{if eq .Folder "Sent"}}{{if .CachedTo}}{{.CachedTo}}{{else}}(no recipient){{end}}{{else}}{{.CachedFrom}}{{end}}</a></td>
                                        <td>
                                            <a class="text-reset text-decoration-none" href="{{$rowHref}}">{{if .CachedSubject}}{{.CachedSubject}}{{else}}<span class="text-muted">(no subject)</span>{{end}}</a>
                                            {{if gt .GroupExtra 0}}<span class="badge bg-secondary msg-group-toggle" data-group-toggle="{{.ID}}">+{{.GroupExtra}} more</span>{{end}}
                                        </td>
                                        {{if $showFolderCol}}<td><small class="text-muted">{{.Folder}}</small></td>{{end}}
                                        <td><small class="text-muted">{{strftime "%Y-%m-%d %H:%M" .InternalDate}}</small></td>
                                        <td class="text-end">
                                            <div class="btn-group btn-group-sm" role="group">
                                                <form method="post" action="/webmail/mail/{{.Folder}}/{{.ID}}/move" class="d-inline-flex">
                                                    <select name="target_folder" class="form-select form-select-sm" style="width: auto;" onchange="this.form.submit()">
                                                        <option value="">Move to&hellip;</option>
                                                        {{$rowFolder := .Folder}}
                                                        {{range $folders}}{{if ne . $rowFolder}}<option value="{{.}}">{{.}}</option>{{end}}{{end}}
                                                    </select>
                                                </form>
                                                <form method="post" action="/webmail/mail/{{.Folder}}/{{.ID}}/delete" class="d-inline">
                                                    <button type="submit" class="btn btn-outline-danger btn-sm" title="{{if eq .Folder "Trash"}}Delete permanently{{else}}Move to Trash{{end}}" data-confirm="{{if eq .Folder "Trash"}}Permanently delete this message? This cannot be undone.{{else}}Move this message to Trash?{{end}}"><i class="bi bi-trash"></i></button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                    {{end}}
                                </tbody>
                            </table>
                        </div>
                        {{if or .has_prev .has_next}}
                        <div class="d-flex justify-content-between p-3">
                            {{if .has_prev}}<a href="?page={{sub .page 1}}" class="btn btn-outline-secondary btn-sm">&laquo; Newer</a>{{else}}<span></span>{{end}}
                            {{if .has_next}}<a href="?page={{add .page 1}}" class="btn btn-outline-secondary btn-sm">Older &raquo;</a>{{end}}
                        </div>
                        {{end}}
                        {{else}}
                        <div class="text-center py-5">
                            <i class="bi bi-inbox text-muted" style="font-size: 3rem;"></i>
                            <h5 class="text-muted mt-3">No messages in {{.active_folder}}</h5>
                        </div>
                        {{end}}
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="confirmationModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-question-circle me-2"></i>Confirm Action</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="confirmationModalBody">Are you sure you want to proceed?</div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-danger" id="confirmationModalConfirm">Confirm</button>
                </div>
            </div>
        </div>
    </div>

    {{template "compose_widget" .}}
    {{template "webmail_shortcuts" .}}

    <script src="/webmail/static/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('.toast').forEach(function(el) { new bootstrap.Toast(el, {delay: 5000}).show(); });
        });
        function showConfirmation(message) {
            return new Promise((resolve) => {
                const modal = document.getElementById('confirmationModal');
                document.getElementById('confirmationModalBody').textContent = message;
                const confirmButton = document.getElementById('confirmationModalConfirm');
                const handleConfirm = () => { resolve(true); bootstrap.Modal.getInstance(modal).hide(); cleanup(); };
                const handleCancel = () => { resolve(false); cleanup(); };
                const cleanup = () => {
                    confirmButton.removeEventListener('click', handleConfirm);
                    modal.removeEventListener('hidden.bs.modal', handleCancel);
                };
                confirmButton.addEventListener('click', handleConfirm);
                modal.addEventListener('hidden.bs.modal', handleCancel, { once: true });
                new bootstrap.Modal(modal).show();
            });
        }
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('[data-confirm]').forEach(function(button) {
                button.addEventListener('click', async function(e) {
                    e.preventDefault();
                    if (await showConfirmation(this.getAttribute('data-confirm'))) {
                        const form = this.closest('form');
                        if (form) form.submit();
                    }
                });
            });
        });

        // Drag a message row onto a folder in the sidebar to move it there — a
        // shortcut for the same "Move to..." dropdown every row already has. Each
        // row carries its OWN folder (data-folder) rather than assuming the page's
        // active folder, since a search result can span multiple folders.
        (function() {
            let draggedUID = null;
            let draggedFolder = null;

            document.querySelectorAll('.msg-row').forEach(function(row) {
                row.addEventListener('dragstart', function() {
                    draggedUID = row.dataset.uid;
                    draggedFolder = row.dataset.folder;
                    row.classList.add('dragging');
                });
                row.addEventListener('dragend', function() {
                    row.classList.remove('dragging');
                });
            });

            document.querySelectorAll('.folder-link').forEach(function(link) {
                link.addEventListener('dragover', function(e) {
                    if (!draggedUID || link.dataset.folder === draggedFolder) return;
                    e.preventDefault();
                    link.classList.add('drop-hover');
                });
                link.addEventListener('dragleave', function() {
                    link.classList.remove('drop-hover');
                });
                link.addEventListener('drop', async function(e) {
                    e.preventDefault();
                    link.classList.remove('drop-hover');
                    const targetFolder = link.dataset.folder;
                    if (!draggedUID || !targetFolder || targetFolder === draggedFolder) return;
                    const body = new URLSearchParams();
                    body.set('target_folder', targetFolder);
                    await fetch(`/webmail/mail/${draggedFolder}/${draggedUID}/move`, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        body: body.toString(),
                    });
                    window.location.reload();
                });
            });
        })();

        // "+N more" toggle for a collapsed same-subject run — reveals every
        // immediately-following row marked as part of that group, self-terminating
        // at the first row that isn't (no need to track the count client-side).
        document.querySelectorAll('[data-group-toggle]').forEach(function(badge) {
            badge.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                let sib = badge.closest('tr').nextElementSibling;
                while (sib && sib.classList.contains('msg-row-older')) {
                    sib.style.display = '';
                    sib = sib.nextElementSibling;
                }
                badge.style.display = 'none';
            });
        });
    </script>
</body>
</html>
{{end}}
