{{define "webmail_message.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>{{.parsed.Header.Subject}} - 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; }
        .msg-body-html { background-color: #fff; color: #000; border-radius: 6px; padding: 1rem; overflow-wrap: break-word; word-break: break-word; overflow-x: auto; max-width: 100%; }
        .msg-body-html img { max-width: 100%; height: auto; }
        .msg-body-html table { max-width: 100%; }
        .msg-body-text { white-space: pre-wrap; word-break: break-word; overflow-wrap: break-word; }
    </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/account" class="btn btn-outline-light btn-sm"><i class="bi bi-gear me-1"></i>Settings</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">
            <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 pb-5">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <a href="/webmail/mail/{{.active_folder}}" class="btn btn-outline-secondary btn-sm"><i class="bi bi-arrow-left me-1"></i>Back to {{.active_folder}}</a>
            <div class="btn-group btn-group-sm">
                <button type="button" id="replyBtn" onclick="openCompose('/webmail/mail/compose?reply={{.uid}}&folder={{.active_folder}}')" class="btn btn-outline-primary"><i class="bi bi-reply me-1"></i>Reply</button>
                <button type="button" id="replyAllBtn" onclick="openCompose('/webmail/mail/compose?replyall={{.uid}}&folder={{.active_folder}}')" class="btn btn-outline-primary"><i class="bi bi-reply-all me-1"></i>Reply All</button>
                <button type="button" id="forwardBtn" onclick="openCompose('/webmail/mail/compose?forward={{.uid}}&folder={{.active_folder}}')" class="btn btn-outline-primary"><i class="bi bi-arrow-right me-1"></i>Forward</button>
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-2">{{if .parsed.Header.Subject}}{{.parsed.Header.Subject}}{{else}}<span class="text-muted">(no subject)</span>{{end}}</h5>
                {{if or .smime.Signed .smime.Encrypted}}
                <div class="mb-2">
                    {{if .smime.Encrypted}}
                        {{if .smime.Decrypted}}<span class="badge bg-success"><i class="bi bi-unlock-fill me-1"></i>Encrypted &amp; decrypted</span>
                        {{else}}<span class="badge bg-danger" title="{{.smime.DecryptErr}}"><i class="bi bi-lock-fill me-1"></i>Encrypted — could not decrypt</span>{{end}}
                    {{end}}
                    {{if .smime.Signed}}
                        {{if .smime.SignatureOK}}<span class="badge bg-success" title="{{.smime.SignerEmail}}"><i class="bi bi-patch-check-fill me-1"></i>Signature verified{{if .smime.SignerEmail}} ({{.smime.SignerEmail}}){{end}}</span>
                        {{else}}<span class="badge bg-danger" title="{{.smime.SignatureErr}}"><i class="bi bi-exclamation-triangle-fill me-1"></i>Signature invalid</span>{{end}}
                    {{end}}
                </div>
                {{end}}
                {{if .pgp.Encrypted}}
                <div class="mb-2">
                    {{if .pgp.Decrypted}}<span class="badge bg-success"><i class="bi bi-unlock-fill me-1"></i>PGP encrypted &amp; decrypted</span>
                    {{else if .pgp.NeedsUnlock}}<span class="badge bg-warning text-dark"><i class="bi bi-lock-fill me-1"></i>PGP encrypted — enter your passphrase to decrypt</span>
                    {{else}}<span class="badge bg-danger" title="{{.pgp.DecryptErr}}"><i class="bi bi-lock-fill me-1"></i>PGP encrypted — could not decrypt</span>{{end}}
                </div>
                {{if .pgp.NeedsUnlock}}
                <form method="post" action="/webmail/pgp/unlock" class="row g-2 align-items-end">
                    <input type="hidden" name="next" value="{{.message_url}}">
                    <div class="col-auto">
                        <select class="form-select form-select-sm" name="identity_id">
                            {{range .pgp.Identities}}<option value="{{.ID}}">{{if .Label}}{{.Label}}{{else}}Key{{end}} ({{.Fingerprint}})</option>{{end}}
                        </select>
                    </div>
                    <div class="col-auto">
                        <input type="password" class="form-control form-control-sm" name="passphrase" placeholder="Passphrase" required>
                    </div>
                    <div class="col-auto">
                        <button type="submit" class="btn btn-warning btn-sm">Unlock &amp; Decrypt</button>
                    </div>
                </form>
                {{end}}
                {{end}}
                <div class="small text-muted">
                    <div><strong>From:</strong> {{.parsed.Header.From}}</div>
                    <div><strong>To:</strong> {{.parsed.Header.To}}</div>
                    {{if .parsed.Header.Cc}}<div><strong>Cc:</strong> {{.parsed.Header.Cc}}</div>{{end}}
                    <div><strong>Date:</strong> {{.parsed.Header.Date}}</div>
                </div>
            </div>
            <div class="card-body">
                {{if .images_blocked}}
                <div class="alert alert-secondary d-flex justify-content-between align-items-center py-2 mb-3">
                    <span><i class="bi bi-shield-lock me-1"></i>Remote images were blocked to protect your privacy.</span>
                    <span class="d-flex gap-2">
                        <a href="{{.message_url}}?show_images=1" class="btn btn-sm btn-outline-secondary">Show images</a>
                        {{if .sender_email}}
                        <form method="post" action="/webmail/mail/{{.active_folder}}/{{.uid}}/always-allow-images" class="d-inline">
                            <button type="submit" class="btn btn-sm btn-outline-secondary">Always show images from {{.sender_email}}</button>
                        </form>
                        {{end}}
                    </span>
                </div>
                {{end}}
                {{if .html_body}}
                <div class="msg-body-html">{{.html_body}}</div>
                {{else if .parsed.TextBody}}
                <div class="msg-body-text">{{.parsed.TextBody}}</div>
                {{else}}
                <p class="text-muted mb-0">(empty message body)</p>
                {{end}}

                {{if .parsed.Attachments}}
                <hr>
                <div class="d-flex justify-content-between align-items-center">
                    <h6><i class="bi bi-paperclip me-1"></i>Attachments</h6>
                    {{if gt (len .parsed.Attachments) 1}}
                    <a href="/webmail/mail/{{.active_folder}}/{{.uid}}/attachments.zip" class="btn btn-sm btn-outline-secondary"><i class="bi bi-file-earmark-zip me-1"></i>Download all</a>
                    {{end}}
                </div>
                <div class="list-group">
                    {{$folder := .active_folder}}
                    {{$uid := .uid}}
                    {{range $i, $att := .parsed.Attachments}}
                    <a href="/webmail/mail/{{$folder}}/{{$uid}}/attachment/{{$i}}" class="list-group-item list-group-item-action bg-transparent text-white d-flex justify-content-between align-items-center">
                        <span><i class="bi bi-file-earmark me-2"></i>{{$att.Filename}}</span>
                        <i class="bi bi-download"></i>
                    </a>
                    {{end}}
                </div>
                {{end}}
            </div>
        </div>

        <div class="card">
            <div class="card-body d-flex justify-content-between align-items-center flex-wrap gap-2">
                <form method="post" action="/webmail/mail/{{.active_folder}}/{{.uid}}/move" class="d-flex align-items-center gap-2">
                    <select name="target_folder" class="form-select form-select-sm" style="width: auto;">
                        <option value="">Move to&hellip;</option>
                        {{$folder := .active_folder}}
                        {{range .folders}}{{if ne . $folder}}<option value="{{.}}">{{.}}</option>{{end}}{{end}}
                    </select>
                    <button type="submit" class="btn btn-outline-secondary btn-sm">Move</button>
                </form>
                {{if .under_trash}}
                <form method="post" action="/webmail/mail/{{.active_folder}}/{{.uid}}/restore">
                    <button type="submit" class="btn btn-outline-secondary btn-sm"><i class="bi bi-arrow-counterclockwise me-1"></i>Restore</button>
                </form>
                {{end}}
                <form method="post" action="/webmail/mail/{{.active_folder}}/{{.uid}}/delete">
                    <button type="submit" class="btn btn-outline-danger btn-sm" data-confirm="{{if .under_trash}}Permanently delete this message? This cannot be undone.{{else}}Move this message to Trash?{{end}}"><i class="bi bi-trash me-1"></i>{{if .under_trash}}Delete Permanently{{else}}Move to Trash{{end}}</button>
                </form>
            </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();
                    }
                });
            });
        });
    </script>
</body>
</html>
{{end}}
