<section class="workspace-hero">
    <div>
        <h2>Mail Center</h2>
        <p>Gmail-style internal email workspace with Inbox, Outbox, Sent, Junk, Trash, custom folders, threaded email review, and conversation moves between folders.</p>
    </div>
    <div class="workspace-actions">
        <a class="btn secondary small" href="index.php?route=messages/inboxEmail">Classic Email View</a>
        <a class="btn secondary small" href="index.php?route=settings/providerStatus">Provider Status</a>
    </div>
</section>

<section class="mail-center-layout">
    <div class="card spaced-card folder-rail-card">
        <div class="toolbar"><h2>Folders</h2><span class="badge">Email</span></div>
        <div class="folder-list">
            <?php foreach (($mailFolders ?? []) as $folder): ?>
                <a class="folder-item <?= ($currentMailbox ?? 'inbox') === ($folder['key'] ?? '') ? 'active' : '' ?>" href="index.php?route=messages/mailCenter&mailbox=<?= urlencode((string)($folder['key'] ?? 'inbox')) ?>&q=<?= urlencode((string)($mailboxFilters['q'] ?? '')) ?>">
                    <span class="folder-item-copy">
                        <strong><?= e($folder['name'] ?? 'Folder') ?></strong>
                        <span class="small muted"><?= !empty($folder['system']) ? 'System folder' : 'Custom folder' ?></span>
                    </span>
                    <span class="badge"><?= (int)($mailFolderCounts[$folder['key']] ?? 0) ?></span>
                </a>
            <?php endforeach; ?>
        </div>

        <div class="mail-folder-create">
            <div class="toolbar compact-toolbar"><strong>Create Folder</strong><span class="badge">Custom</span></div>
            <form method="post" action="index.php?route=messages/saveMailFolder">
                <?= csrf_input() ?>
                <input type="hidden" name="return_mailbox" value="<?= e($currentMailbox ?? 'inbox') ?>">
                <input name="folder_name" placeholder="Folder name" required>
                <button class="btn primary mt-12">Create Folder</button>
            </form>
        </div>

        <div class="alert-list">
            <article class="alert-tile ok"><strong>Folders persist inside the app</strong><div class="small muted">Move conversations into system folders or custom folders without a database migration.</div></article>
            <article class="alert-tile warn"><strong>Outbox and Sent are live views</strong><div class="small muted">Queued outbound emails appear in Outbox. Sent outbound emails appear in Sent unless you manually move the conversation.</div></article>
        </div>
    </div>

    <div class="card spaced-card">
        <div class="toolbar">
            <h2><?= e($currentFolder['name'] ?? 'Inbox') ?></h2>
            <span class="badge"><?= (int)(($mailboxMeta['total'] ?? 0)) ?> conversations</span>
        </div>

        <form method="get" class="inline-form toolbar-right stacked-on-mobile">
            <input type="hidden" name="route" value="messages/mailCenter">
            <input type="hidden" name="mailbox" value="<?= e($currentMailbox ?? 'inbox') ?>">
            <input name="q" placeholder="Search subject, body, address" value="<?= e($mailboxFilters['q'] ?? '') ?>">
            <button class="btn secondary small">Search</button>
        </form>

        <div class="conversation-list mail-conversation-list">
            <?php foreach (($mailboxConversations ?? []) as $conversation): ?>
                <a class="conversation-item <?= ($selectedConversation ?? '') === ($conversation['conversation_key'] ?? '') ? 'active' : '' ?>" href="index.php?route=messages/mailCenter&mailbox=<?= urlencode((string)($currentMailbox ?? 'inbox')) ?>&q=<?= urlencode((string)($mailboxFilters['q'] ?? '')) ?>&conversation=<?= urlencode((string)($conversation['conversation_key'] ?? '')) ?>">
                    <div class="conversation-head">
                        <strong><?= e(($conversation['contact_name'] ?? '') ?: ($conversation['address'] ?? 'Email conversation')) ?></strong>
                        <span class="badge"><?= e(strtoupper((string)($conversation['folder_key'] ?? 'inbox'))) ?></span>
                    </div>
                    <div class="small muted"><?= e($conversation['address'] ?? '') ?></div>
                    <?php if (!empty($conversation['subject'])): ?><div class="preview-subject"><?= e($conversation['subject']) ?></div><?php endif; ?>
                    <div class="conversation-preview"><?= e(mb_strimwidth((string)($conversation['last_preview'] ?? ''), 0, 110, '...')) ?></div>
                    <div class="conversation-meta small muted">
                        <span><?= e($conversation['last_message_at'] ?? '') ?></span>
                        <span><?= (int)($conversation['message_count'] ?? 0) ?> msgs</span>
                        <?php if (!empty($conversation['unread_like_count'])): ?><span><?= (int)$conversation['unread_like_count'] ?> new</span><?php endif; ?>
                        <?php if (!empty($conversation['has_attachment'])): ?><span>attachment</span><?php endif; ?>
                    </div>
                </a>
            <?php endforeach; ?>
            <?php if (empty($mailboxConversations)): ?>
                <div class="empty-state-cell muted">No email conversations are currently in <?= e(strtolower((string)($currentFolder['name'] ?? 'this folder'))) ?>.</div>
            <?php endif; ?>
        </div>

        <?php if (!empty($mailboxMeta) && (int)($mailboxMeta['pages'] ?? 1) > 1): ?>
            <div class="pagination">
                <?php for ($page = 1; $page <= (int)$mailboxMeta['pages']; $page++): ?>
                    <a class="page-link <?= $page === (int)($mailboxMeta['page'] ?? 1) ? 'active' : '' ?>" href="index.php?route=messages/mailCenter&mailbox=<?= urlencode((string)($currentMailbox ?? 'inbox')) ?>&q=<?= urlencode((string)($mailboxFilters['q'] ?? '')) ?>&page=<?= $page ?><?= !empty($selectedConversation) ? '&conversation=' . urlencode((string)$selectedConversation) : '' ?>"><?= $page ?></a>
                <?php endfor; ?>
            </div>
        <?php endif; ?>
    </div>

    <div class="mail-center-detail">
        <div class="card spaced-card">
            <div class="toolbar">
                <h2><?= !empty($selectedMailboxSummary['subject']) ? e($selectedMailboxSummary['subject']) : 'Threaded View' ?></h2>
                <span class="badge"><?= e(strtoupper((string)($selectedMailboxSummary['folder_key'] ?? ($currentMailbox ?? 'inbox')))) ?></span>
            </div>

            <?php if (empty($thread)): ?>
                <p class="muted">Select a conversation from the current folder to read and reply.</p>
            <?php else: ?>
                <div class="mailbox-move-bar">
                    <form method="post" action="index.php?route=messages/moveEmailConversation" class="inline-form stacked-on-mobile">
                        <?= csrf_input() ?>
                        <input type="hidden" name="conversation_key" value="<?= e($selectedConversation ?? '') ?>">
                        <input type="hidden" name="mailbox" value="<?= e($currentMailbox ?? 'inbox') ?>">
                        <select name="target_folder">
                            <?php foreach (($mailFolders ?? []) as $folder): ?>
                                <option value="<?= e($folder['key'] ?? 'inbox') ?>" <?= ($selectedMailboxSummary['folder_key'] ?? ($currentMailbox ?? 'inbox')) === ($folder['key'] ?? '') ? 'selected' : '' ?>>Move to <?= e($folder['name'] ?? 'Folder') ?></option>
                            <?php endforeach; ?>
                        </select>
                        <button class="btn secondary small" type="submit">Move Conversation</button>
                    </form>
                </div>

                <div class="thread mail-thread">
                    <?php foreach ($thread as $message): ?>
                        <article class="bubble <?= e($message['direction']) ?>">
                            <div class="bubble-meta small muted">
                                <span><?= e(($message['direction'] ?? '') === 'inbound' ? 'From: ' . ($message['from_address'] ?? '') : 'To: ' . ($message['to_address'] ?? '')) ?></span>
                                <span><?= e($message['created_at'] ?? '') ?></span>
                                <span><?= e($message['status'] ?? '') ?></span>
                            </div>
                            <?php if (!empty($message['subject'])): ?><h3><?= e($message['subject']) ?></h3><?php endif; ?>
                            <div><?= nl2br(e(strip_tags((string)($message['body'] ?? '')))) ?></div>
                            <?php if (!empty($message['attachment_path'])): ?><div class="small muted" style="margin-top:8px;">Attachment saved: <?= e($message['attachment_path']) ?></div><?php endif; ?>
                        </article>
                    <?php endforeach; ?>
                </div>

                <hr>
                <form method="post" action="index.php?route=messages/reply">
                    <?= csrf_input() ?>
                    <input type="hidden" name="conversation_key" value="<?= e($selectedConversation ?? '') ?>">
                    <input type="hidden" name="channel" value="email">
                    <input type="hidden" name="return_route" value="messages/mailCenter">
                    <input type="hidden" name="mailbox" value="<?= e($currentMailbox ?? 'inbox') ?>">
                    <div class="form-grid">
                        <input name="subject" value="<?= e('Re: ' . ((string)($selectedMailboxSummary['subject'] ?? 'Conversation'))) ?>" placeholder="Reply subject">
                        <select class="template-picker" data-target-body="mail-center-reply-body" data-target-subject="mail-center-reply-subject">
                            <option value="">Optional canned 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>
                    <textarea id="mail-center-reply-body" name="body" rows="7" placeholder="Reply body"></textarea>
                    <button class="btn primary mt-12">Send Reply</button>
                </form>
            <?php endif; ?>
        </div>

        <div class="card spaced-card">
            <div class="toolbar"><h2>Compose Email</h2><span class="badge">Mail Center</span></div>
            <form method="post" action="index.php?route=messages/sendEmail" enctype="multipart/form-data">
                <?= csrf_input() ?>
                <input type="hidden" name="return_route" value="messages/mailCenter">
                <input type="hidden" name="mailbox" value="sent">
                <div class="form-grid">
                    <select name="contact_id">
                        <option value="">Choose contact</option>
                        <?php foreach (($contacts ?? []) as $contact): if (empty($contact['email'])) continue; ?>
                            <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="mail-center-compose-body" data-target-subject="mail-center-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="mail-center-compose-subject" name="subject" placeholder="Subject line">
                    <input type="file" name="attachment">
                </div>
                <textarea id="mail-center-compose-body" name="body" rows="9" placeholder="HTML or plain text body"></textarea>
                <button class="btn primary mt-12">Send Email</button>
            </form>

            <div class="toolbar" style="margin-top:8px;"><h3>Canned Replies</h3><span class="badge"><?= count($cannedReplies ?? []) ?></span></div>
            <div class="thread" style="max-height:240px;">
                <?php foreach (($cannedReplies ?? []) as $reply): ?>
                    <article class="bubble inbound">
                        <div class="bubble-meta small muted"><?= e($reply['title'] ?? 'Reply') ?></div>
                        <?php if (!empty($reply['subject'])): ?><strong><?= e($reply['subject']) ?></strong><?php endif; ?>
                        <div><?= nl2br(e((string)($reply['body'] ?? ''))) ?></div>
                    </article>
                <?php endforeach; ?>
                <?php if (empty($cannedReplies)): ?>
                    <p class="muted">No canned replies are saved for email yet.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</section>
