<?php
$folderMeta = $mailboxFolderMeta ?? ['name' => 'Inbox', 'token' => 'inbox'];
$baseQuery = qs_without(['route', 'folder', 'conversation', 'page', 'compose']);
$replySubject = '';
$replyAddress = '';
$referencesHeader = '';
$composeMode = !empty($_GET['compose']) || empty($selectedConversation);
if (!empty($lastMessage)) {
    $replySubject = stripos((string)($lastMessage['subject'] ?? ''), 'Re:') === 0
        ? (string)$lastMessage['subject']
        : 'Re: ' . (string)($lastMessage['subject'] ?? 'Conversation');
    $replyAddress = normalize_address(($lastMessage['direction'] ?? 'inbound') === 'inbound' ? ($lastMessage['from_address'] ?? '') : ($lastMessage['to_address'] ?? ''));
    $referencesHeader = trim(((string)($lastMessage['references_header'] ?? '')) . ' ' . ((string)($lastMessage['external_id'] ?? '')));
}
$selectedTitle = !empty($thread)
    ? (trim((string)(($thread[count($thread) - 1]['first_name'] ?? '') . ' ' . ($thread[count($thread) - 1]['last_name'] ?? ''))) ?: ($thread[count($thread) - 1]['direction'] === 'inbound' ? ($thread[count($thread) - 1]['from_address'] ?? '') : ($thread[count($thread) - 1]['to_address'] ?? '')))
    : 'Mailbox';
?>
<section class="workspace-hero">
    <div>
        <h2>Mailbox</h2>
        <p>Gmail-style email workspace with Inbox, Outbox, Sent, Junk, Trash, threaded conversations, and custom folders for organizing messages.</p>
    </div>
    <div class="workspace-actions">
        <a class="btn secondary small" href="index.php?route=messages/inboxEmail">Classic Email Inbox</a>
        <a class="btn secondary small" href="index.php?route=messages/mailbox&folder=<?= urlencode($mailboxFolder ?? 'inbox') ?>&compose=1">Compose Email</a>
        <a class="btn secondary small" href="index.php?route=settings/providerStatus">Provider Status</a>
    </div>
</section>

<section class="card mailbox-card">
    <div class="mailbox-shell">
        <aside class="mailbox-sidebar">
            <div>
                <div class="toolbar compact-toolbar"><strong>System folders</strong><span class="badge">Mail</span></div>
                <div class="mail-folder-list">
                    <?php foreach (($systemFolders ?? []) as $folder): ?>
                        <a class="mail-folder-link <?= ($mailboxFolder ?? 'inbox') === ($folder['token'] ?? '') ? 'active' : '' ?>" href="index.php?route=messages/mailbox&folder=<?= urlencode($folder['token']) ?><?= $baseQuery ? '&' . e($baseQuery) : '' ?>">
                            <span><?= e($folder['name']) ?></span>
                            <strong class="mailbox-count"><?= (int)($folder['count'] ?? 0) ?></strong>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>

            <div>
                <div class="toolbar compact-toolbar"><strong>Custom folders</strong><span class="badge"><?= (int)count($customFolders ?? []) ?></span></div>
                <div class="mail-folder-list">
                    <?php foreach (($customFolders ?? []) as $folder): ?>
                        <div class="mail-folder-row">
                            <a class="mail-folder-link <?= ($mailboxFolder ?? 'inbox') === ($folder['token'] ?? '') ? 'active' : '' ?>" href="index.php?route=messages/mailbox&folder=<?= urlencode($folder['token']) ?><?= $baseQuery ? '&' . e($baseQuery) : '' ?>">
                                <span><?= e($folder['name']) ?></span>
                                <strong class="mailbox-count"><?= (int)($folder['count'] ?? 0) ?></strong>
                            </a>
                            <form method="post" action="index.php?route=messages/deleteMailboxFolder" onsubmit="return confirm('Delete this folder? Messages will be returned to Inbox.')">
                                <?= csrf_input() ?>
                                <input type="hidden" name="slug" value="<?= e($folder['slug']) ?>">
                                <button class="btn danger small" type="submit">Delete</button>
                            </form>
                        </div>
                    <?php endforeach; ?>
                    <?php if (empty($customFolders)): ?>
                        <div class="small muted">No custom folders yet.</div>
                    <?php endif; ?>
                </div>
            </div>

            <form method="post" action="index.php?route=messages/createMailboxFolder" class="mailbox-folder-form">
                <?= csrf_input() ?>
                <input type="hidden" name="return_folder" value="<?= e($mailboxFolder ?? 'inbox') ?>">
                <label for="mail-folder-name">Create folder</label>
                <input id="mail-folder-name" name="name" placeholder="Projects, VIP, Renewals" required>
                <button class="btn secondary" type="submit">Add Folder</button>
            </form>

            <div class="preview-box small">
                <strong>Mailbox behavior</strong>
                <div class="muted" style="margin-top:6px;line-height:1.6;">Outbox and Sent update automatically from email status. Use Junk, Trash, or custom folders to organize threads manually.</div>
            </div>
        </aside>

        <div class="mailbox-list-panel">
            <div class="toolbar"><h2><?= e($folderMeta['name'] ?? 'Inbox') ?></h2><span class="badge"><?= (int)($conversationMeta['total'] ?? 0) ?> threads</span></div>
            <form method="get" class="inline-form toolbar-right stacked-on-mobile">
                <input type="hidden" name="route" value="messages/mailbox">
                <input type="hidden" name="folder" value="<?= e($mailboxFolder ?? 'inbox') ?>">
                <input name="q" placeholder="Search subject, body, address" value="<?= e($filters['q'] ?? '') ?>">
                <button class="btn secondary small">Search</button>
            </form>
            <div class="conversation-list">
                <?php foreach (($conversations ?? []) as $conversation): ?>
                    <a class="conversation-item <?= ($selectedConversation ?? '') === $conversation['conversation_key'] ? 'active' : '' ?>" href="index.php?route=messages/mailbox&folder=<?= urlencode($mailboxFolder ?? 'inbox') ?><?= $baseQuery ? '&' . e($baseQuery) : '' ?>&conversation=<?= urlencode($conversation['conversation_key']) ?>">
                        <div class="conversation-head">
                            <strong><?= e($conversation['contact_name'] ?: $conversation['address']) ?></strong>
                            <span class="badge"><?= (int)($conversation['message_count'] ?? 0) ?> msgs</span>
                        </div>
                        <div class="mail-address"><?= e($conversation['address']) ?></div>
                        <div class="conversation-preview"><?= e(mb_strimwidth((string)($conversation['last_preview'] ?? ''), 0, 110, '...')) ?></div>
                        <div class="conversation-meta small muted">
                            <?= e($conversation['last_message_at'] ?? '') ?>
                            <?php if (!empty($conversation['unread_like_count'])): ?> · <?= (int)$conversation['unread_like_count'] ?> new<?php endif; ?>
                        </div>
                    </a>
                <?php endforeach; ?>
                <?php if (empty($conversations)): ?>
                    <div class="mailbox-empty muted">No email threads match this folder yet.</div>
                <?php endif; ?>
            </div>
        </div>

        <div class="mailbox-preview-panel">
            <div class="card spaced-card" style="margin:0;">
                <div class="toolbar"><h2><?= e($selectedTitle) ?></h2><span class="badge"><?= !empty($thread) ? count($thread) . ' messages' : 'Preview' ?></span></div>
                <?php if (empty($thread)): ?>
                    <div class="mailbox-empty muted">Select a thread to read, move, reply, or create a new email from this mailbox workspace.</div>
                <?php else: ?>
                    <div class="mailbox-thread-actions">
                        <form method="post" action="index.php?route=messages/moveConversation">
                            <?= csrf_input() ?>
                            <input type="hidden" name="conversation_key" value="<?= e($selectedConversation ?? '') ?>">
                            <input type="hidden" name="current_folder" value="<?= e($mailboxFolder ?? 'inbox') ?>">
                            <select name="destination_folder">
                                <?php foreach (($moveFolders ?? []) as $folder): ?>
                                    <option value="<?= e($folder['token']) ?>" <?= ($mailboxFolder ?? 'inbox') === ($folder['token'] ?? '') ? 'selected' : '' ?>>Move to <?= e($folder['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                            <button class="btn secondary small" type="submit">Move</button>
                        </form>
                        <?php if (($mailboxFolder ?? 'inbox') !== 'junk'): ?>
                            <form method="post" action="index.php?route=messages/moveConversation">
                                <?= csrf_input() ?>
                                <input type="hidden" name="conversation_key" value="<?= e($selectedConversation ?? '') ?>">
                                <input type="hidden" name="current_folder" value="<?= e($mailboxFolder ?? 'inbox') ?>">
                                <input type="hidden" name="destination_folder" value="junk">
                                <button class="btn secondary small" type="submit">Mark Junk</button>
                            </form>
                        <?php endif; ?>
                        <?php if (($mailboxFolder ?? 'inbox') !== 'trash'): ?>
                            <form method="post" action="index.php?route=messages/moveConversation">
                                <?= csrf_input() ?>
                                <input type="hidden" name="conversation_key" value="<?= e($selectedConversation ?? '') ?>">
                                <input type="hidden" name="current_folder" value="<?= e($mailboxFolder ?? 'inbox') ?>">
                                <input type="hidden" name="destination_folder" value="trash">
                                <button class="btn danger small" type="submit">Trash</button>
                            </form>
                        <?php endif; ?>
                        <?php if (($mailboxFolder ?? 'inbox') !== 'inbox'): ?>
                            <form method="post" action="index.php?route=messages/moveConversation">
                                <?= csrf_input() ?>
                                <input type="hidden" name="conversation_key" value="<?= e($selectedConversation ?? '') ?>">
                                <input type="hidden" name="current_folder" value="<?= e($mailboxFolder ?? 'inbox') ?>">
                                <input type="hidden" name="destination_folder" value="inbox">
                                <button class="btn secondary small" type="submit">Restore to Inbox</button>
                            </form>
                        <?php endif; ?>
                    </div>
                    <div class="thread">
                        <?php foreach ($thread as $message): ?>
                            <article class="bubble <?= e($message['direction']) ?>">
                                <div class="bubble-meta small muted">
                                    <?= e(strtoupper($message['direction'])) ?> · <?= e($message['created_at']) ?> · <?= e($message['status']) ?>
                                </div>
                                <div class="small muted">
                                    <?= e($message['direction'] === 'inbound' ? ($message['from_address'] ?? '') : ($message['to_address'] ?? '')) ?>
                                </div>
                                <?php if (!empty($message['subject'])): ?><h3><?= e($message['subject']) ?></h3><?php endif; ?>
                                <div><?= nl2br(e(strip_tags((string)($message['body'] ?? '')))) ?></div>
                            </article>
                        <?php endforeach; ?>
                    </div>

                    <hr>
                    <form method="post" action="index.php?route=messages/reply" class="mailbox-reply">
                        <?= csrf_input() ?>
                        <input type="hidden" name="conversation_key" value="<?= e($selectedConversation ?? '') ?>">
                        <input type="hidden" name="channel" value="email">
                        <input type="hidden" name="return_to" value="mailbox">
                        <input type="hidden" name="folder" value="<?= e($mailboxFolder ?? 'inbox') ?>">
                        <div class="toolbar compact-toolbar"><strong>Reply in thread</strong><span class="badge"><?= e($replyAddress) ?></span></div>
                        <select class="template-picker" data-target-body="mailbox-reply-body" data-target-subject="mailbox-reply-subject">
                            <option value="">Optional canned reply</option>
                            <?php foreach (($cannedReplies ?? []) as $reply): ?>
                                <option value="<?= (int)$reply['id'] ?>" data-subject="<?= e($reply['subject'] ?? $replySubject) ?>" data-body="<?= e($reply['body']) ?>"><?= e($reply['title']) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <input id="mailbox-reply-subject" name="subject" value="<?= e($replySubject) ?>">
                        <textarea id="mailbox-reply-body" name="body" rows="6" placeholder="Reply in this email thread"></textarea>
                        <button class="btn primary" type="submit">Send Reply</button>
                    </form>
                <?php endif; ?>
            </div>

            <div class="card spaced-card" style="margin:0;">
                <div class="toolbar"><h2>Compose New Email</h2><span class="badge"><?= $composeMode ? 'Open' : 'Quick compose' ?></span></div>
                <form method="post" action="index.php?route=messages/sendEmail" enctype="multipart/form-data" class="mailbox-compose">
                    <?= csrf_input() ?>
                    <input type="hidden" name="return_to" value="mailbox">
                    <input type="hidden" name="folder" value="sent">
                    <div class="form-grid">
                        <select name="contact_id">
                            <option value="">Choose contact</option>
                            <?php foreach (($contacts ?? []) as $contact): ?>
                                <option value="<?= (int)$contact['id'] ?>"><?= e(trim(($contact['first_name'] ?? '') . ' ' . ($contact['last_name'] ?? '')) ?: ($contact['email'] ?? '')) ?> · <?= e($contact['email']) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <input name="to_address" placeholder="Or enter email address">
                    </div>
                    <select class="template-picker" data-target-body="mailbox-compose-body" data-target-subject="mailbox-compose-subject">
                        <option value="">Optional email template</option>
                        <?php foreach (($emailTemplates ?? []) as $template): ?>
                            <option value="<?= (int)$template['id'] ?>" data-subject="<?= e($template['subject']) ?>" data-body="<?= e($template['body']) ?>"><?= e($template['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <div class="form-grid">
                        <input id="mailbox-compose-subject" name="subject" placeholder="Subject line">
                        <input type="file" name="attachment">
                    </div>
                    <textarea id="mailbox-compose-body" name="body" rows="8" placeholder="Write your email"></textarea>
                    <button class="btn primary" type="submit">Send Email</button>
                </form>
            </div>
        </div>
    </div>
</section>
