<?php
$filters = $mailboxFilters ?? [];
$currentMailbox = (string)($currentMailbox ?? 'inbox');
$selectedConversation = (string)($selectedConversation ?? '');
$baseParams = [
    'route' => 'messages/mailCenter',
    'mailbox' => $currentMailbox,
    'q' => (string)($filters['q'] ?? ''),
    'bucket' => (string)($filters['bucket'] ?? 'all'),
    'label' => (string)($filters['label_key'] ?? 'all'),
    'starred' => !empty($filters['starred']) ? '1' : null,
    'shared_mailbox_id' => !empty($filters['shared_mailbox_id']) ? (int)$filters['shared_mailbox_id'] : null,
    'conversation' => $selectedConversation !== '' ? $selectedConversation : null,
];
$mailCenterUrl = static function (array $overrides = []) use ($baseParams): string {
    $params = array_merge($baseParams, $overrides);
    foreach ($params as $key => $value) {
        if ($value === null || $value === '') {
            unset($params[$key]);
        }
    }
    return 'index.php?' . http_build_query($params);
};
$currentLabel = (string)($filters['label_key'] ?? 'all');
$currentBucket = (string)($filters['bucket'] ?? 'all');
$currentSharedMailbox = (int)($filters['shared_mailbox_id'] ?? 0);
$selectedContact = $selectedContact ?? null;
$selectedSummary = $selectedMailboxSummary ?? null;
$replyDraft = $replyDraft ?? null;
$composeDraft = $composeDraft ?? null;
$systemFolders = array_values(array_filter((array)($mailFolders ?? []), static fn(array $folder): bool => !empty($folder['system'])));
$customFolders = array_values(array_filter((array)($mailFolders ?? []), static fn(array $folder): bool => empty($folder['system'])));
$refreshUrl = $mailCenterUrl(['page' => null]);
?>
<div class="mail-outlook-shell" id="mail-outlook-shell" data-mail-layout="right" data-mail-density="roomy">
<section class="card spaced-card mail-outlook-header">
    <div class="mail-outlook-brand">
        <button class="btn primary" type="button" data-compose-toggle="true">New mail</button>
        <div>
            <h2>Mail Center</h2>
            <p class="muted">Cleaned up into an Outlook-style workspace with a lighter command bar, cleaner folders, a denser conversation list, and a more focused reading pane.</p>
        </div>
    </div>
    <div class="mail-outlook-controls">
        <a class="btn secondary small" href="<?= e($refreshUrl) ?>">Refresh</a>
        <a class="btn secondary small" href="index.php?route=messages/inboxEmail">Classic view</a>
        <a class="btn secondary small" href="index.php?route=settings/providerStatus">Provider status</a>
        <div class="mail-view-toggle" aria-label="Message list density">
            <span class="small muted">Density</span>
            <button type="button" class="mail-view-button" data-mail-density="roomy">Roomy</button>
            <button type="button" class="mail-view-button" data-mail-density="cozy">Cozy</button>
            <button type="button" class="mail-view-button" data-mail-density="compact">Compact</button>
        </div>
        <div class="mail-view-toggle" aria-label="Reading pane layout">
            <span class="small muted">Reading pane</span>
            <button type="button" class="mail-view-button" data-mail-layout="right">Right</button>
            <button type="button" class="mail-view-button" data-mail-layout="bottom">Bottom</button>
            <button type="button" class="mail-view-button" data-mail-layout="focus">Focus</button>
        </div>
    </div>
</section>

<section class="card spaced-card mail-outlook-search">
    <form method="get" class="mail-search-form">
        <input type="hidden" name="route" value="messages/mailCenter">
        <input type="hidden" name="mailbox" value="<?= e($currentMailbox) ?>">
        <label class="mail-search-field">
            <span class="small muted">Search</span>
            <input name="q" placeholder="Search from:, subject, body, company, tags" value="<?= e($filters['q'] ?? '') ?>">
        </label>
        <label>
            <span class="small muted">Bucket</span>
            <select name="bucket">
                <option value="all" <?= $currentBucket === 'all' ? 'selected' : '' ?>>All mail</option>
                <option value="focused" <?= $currentBucket === 'focused' ? 'selected' : '' ?>>Focused</option>
                <option value="other" <?= $currentBucket === 'other' ? 'selected' : '' ?>>Other</option>
            </select>
        </label>
        <label>
            <span class="small muted">Label</span>
            <select name="label">
                <option value="all">All labels</option>
                <?php foreach (($mailLabels ?? []) as $label): ?>
                    <option value="<?= e($label['label_key']) ?>" <?= $currentLabel === ($label['label_key'] ?? '') ? 'selected' : '' ?>><?= e($label['name']) ?></option>
                <?php endforeach; ?>
            </select>
        </label>
        <label>
            <span class="small muted">Shared mailbox</span>
            <select name="shared_mailbox_id">
                <option value="">All shared mailboxes</option>
                <?php foreach (($sharedMailboxes ?? []) as $mailbox): ?>
                    <option value="<?= (int)$mailbox['id'] ?>" <?= $currentSharedMailbox === (int)$mailbox['id'] ? 'selected' : '' ?>><?= e($mailbox['name']) ?></option>
                <?php endforeach; ?>
            </select>
        </label>
        <label class="mail-inline-check mail-star-filter"><input type="checkbox" name="starred" value="1" <?= !empty($filters['starred']) ? 'checked' : '' ?>> Starred only</label>
        <button class="btn secondary small">Apply</button>
    </form>
</section>

<section class="mail-v16-layout mail-outlook-layout">
    <aside class="card spaced-card mail-v16-left mail-outlook-left">
        <div class="mail-rail-header">
            <div>
                <div class="small muted">Folders</div>
                <h3>Browse mailbox</h3>
            </div>
            <span class="badge"><?= count($mailFolders ?? []) ?></span>
        </div>

        <div class="mail-rail-section">
            <div class="mail-rail-title">System folders</div>
            <div class="folder-list folder-list-compact">
                <?php foreach ($systemFolders as $folder): ?>
                    <a class="folder-item <?= $currentMailbox === ($folder['key'] ?? '') ? 'active' : '' ?>" href="<?= e($mailCenterUrl(['mailbox' => (string)($folder['key'] ?? 'inbox'), 'conversation' => null, 'page' => null])) ?>">
                        <span class="folder-item-copy">
                            <strong><?= e($folder['display_name'] ?? $folder['name'] ?? 'Folder') ?></strong>
                            <span class="small muted"><?= e($folder['description'] ?? 'System folder') ?></span>
                        </span>
                        <span class="badge"><?= (int)($mailFolderCounts[$folder['key']] ?? 0) ?></span>
                    </a>
                <?php endforeach; ?>
            </div>
        </div>

        <?php if (!empty($customFolders)): ?>
            <div class="mail-rail-section">
                <div class="mail-rail-title">Custom folders</div>
                <div class="folder-list folder-list-compact">
                    <?php foreach ($customFolders as $folder): ?>
                        <a class="folder-item <?= $currentMailbox === ($folder['key'] ?? '') ? 'active' : '' ?>" href="<?= e($mailCenterUrl(['mailbox' => (string)($folder['key'] ?? 'inbox'), 'conversation' => null, 'page' => null])) ?>">
                            <span class="folder-item-copy">
                                <strong><?= e($folder['display_name'] ?? $folder['name'] ?? 'Folder') ?></strong>
                                <span class="small muted"><?= !empty($folder['parent_key']) ? 'Subfolder' : 'Custom folder' ?></span>
                            </span>
                            <span class="badge"><?= (int)($mailFolderCounts[$folder['key']] ?? 0) ?></span>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>

        <details class="mail-rail-manage" open>
            <summary>Labels & views</summary>
            <div class="mail-chip-list">
                <?php foreach (($mailLabels ?? []) as $label): ?>
                    <a class="mail-chip color-<?= e($label['color_token'] ?? 'blue') ?>" href="<?= e($mailCenterUrl(['label' => (string)$label['label_key'], 'page' => null])) ?>"><?= e($label['name']) ?></a>
                <?php endforeach; ?>
                <?php if (empty($mailLabels)): ?><span class="muted small">No labels yet.</span><?php endif; ?>
            </div>
            <div class="mail-rail-helper muted small">Use labels for flexible views, while folders keep the mailbox structured.</div>
        </details>

        <details class="mail-rail-manage">
            <summary>Organize mailbox</summary>
            <form method="post" action="index.php?route=messages/saveMailFolder" class="stacked-panel">
                <?= csrf_input() ?>
                <input type="hidden" name="return_mailbox" value="<?= e($currentMailbox) ?>">
                <div class="mail-mini-section-title">Create folder</div>
                <input name="folder_name" placeholder="Folder name" required>
                <select name="parent_key">
                    <option value="">Top-level folder</option>
                    <?php foreach ($customFolders as $folder): ?>
                        <option value="<?= e($folder['key']) ?>"><?= e($folder['display_name'] ?? $folder['name']) ?></option>
                    <?php endforeach; ?>
                </select>
                <button class="btn secondary small">Save folder</button>
            </form>

            <form method="post" action="index.php?route=messages/saveMailLabel" class="stacked-panel">
                <?= csrf_input() ?>
                <input type="hidden" name="return_mailbox" value="<?= e($currentMailbox) ?>">
                <div class="mail-mini-section-title">Create label</div>
                <input name="label_name" placeholder="Label name" required>
                <select name="color_token">
                    <?php foreach (['blue','green','amber','red','violet','slate'] as $color): ?>
                        <option value="<?= e($color) ?>"><?= e(ucfirst($color)) ?></option>
                    <?php endforeach; ?>
                </select>
                <button class="btn secondary small">Create label</button>
            </form>
        </details>

        <details class="mail-rail-manage">
            <summary>Rules & shared mailboxes</summary>
            <form method="post" action="index.php?route=messages/saveMailRule" class="stacked-panel">
                <?= csrf_input() ?>
                <input type="hidden" name="return_mailbox" value="<?= e($currentMailbox) ?>">
                <div class="mail-mini-section-title">Move rule</div>
                <input name="name" placeholder="Rule name" required>
                <div class="form-grid">
                    <select name="match_field">
                        <option value="from_address">From contains</option>
                        <option value="subject">Subject contains</option>
                        <option value="body">Body contains</option>
                    </select>
                    <select name="match_operator">
                        <option value="contains">contains</option>
                        <option value="equals">equals</option>
                    </select>
                </div>
                <input name="match_value" placeholder="Match value" required>
                <div class="form-grid">
                    <select name="target_folder_key">
                        <option value="">Keep current folder</option>
                        <?php foreach (($mailFolders ?? []) as $folder): ?>
                            <option value="<?= e($folder['key']) ?>"><?= e($folder['display_name'] ?? $folder['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <select name="target_bucket">
                        <option value="">Keep current bucket</option>
                        <option value="focused">Focused</option>
                        <option value="other">Other</option>
                    </select>
                </div>
                <select name="target_label_key">
                    <option value="">No label</option>
                    <?php foreach (($mailLabels ?? []) as $label): ?>
                        <option value="<?= e($label['label_key']) ?>"><?= e($label['name']) ?></option>
                    <?php endforeach; ?>
                </select>
                <label class="mail-inline-check"><input type="checkbox" name="is_active" value="1" checked> Active</label>
                <button class="btn secondary small">Create rule</button>
            </form>
            <div class="mail-rule-list mail-rule-list-compact">
                <?php foreach (($mailRules ?? []) as $rule): ?>
                    <div class="mail-rule-item">
                        <strong><?= e($rule['name']) ?></strong>
                        <div class="small muted"><?= e($rule['match_field']) ?> <?= e($rule['match_operator']) ?> “<?= e($rule['match_value']) ?>”</div>
                    </div>
                <?php endforeach; ?>
                <?php if (empty($mailRules)): ?><span class="muted small">No rules yet.</span><?php endif; ?>
            </div>
            <div class="mail-chip-list">
                <?php foreach (($sharedMailboxes ?? []) as $mailbox): ?>
                    <a class="mail-chip color-slate" href="<?= e($mailCenterUrl(['shared_mailbox_id' => (int)$mailbox['id'], 'page' => null])) ?>"><?= e($mailbox['name']) ?></a>
                <?php endforeach; ?>
                <?php if (empty($sharedMailboxes)): ?><span class="muted small">No shared mailboxes yet.</span><?php endif; ?>
            </div>
            <form method="post" action="index.php?route=messages/createSharedMailbox" class="stacked-panel">
                <?= csrf_input() ?>
                <input type="hidden" name="return_mailbox" value="<?= e($currentMailbox) ?>">
                <div class="mail-mini-section-title">Create shared mailbox</div>
                <input name="name" placeholder="Mailbox name" required>
                <input name="email_address" placeholder="Mailbox email" required>
                <input name="description" placeholder="Description">
                <button class="btn secondary small">Create shared mailbox</button>
            </form>
        </details>
    </aside>

    <section class="card spaced-card mail-v16-center mail-outlook-center">
        <div class="mail-list-header">
            <div>
                <div class="small muted">Mailbox</div>
                <h2><?= e($currentFolder['name'] ?? 'Inbox') ?></h2>
            </div>
            <div class="mail-list-header-meta">
                <span class="badge"><?= (int)($mailboxMeta['total'] ?? 0) ?> conversations</span>
                <?php if (!empty($filters['starred'])): ?><span class="badge">Starred</span><?php endif; ?>
            </div>
        </div>
        <div class="mail-bucket-tabs mail-bucket-tabs-outlook">
            <a class="mail-tab <?= $currentBucket === 'focused' ? 'active' : '' ?>" href="<?= e($mailCenterUrl(['bucket' => 'focused', 'page' => null])) ?>">Focused</a>
            <a class="mail-tab <?= $currentBucket === 'other' ? 'active' : '' ?>" href="<?= e($mailCenterUrl(['bucket' => 'other', 'page' => null])) ?>">Other</a>
            <a class="mail-tab <?= $currentBucket === 'all' ? 'active' : '' ?>" href="<?= e($mailCenterUrl(['bucket' => 'all', 'page' => null])) ?>">All</a>
        </div>
        <div class="mail-list-headline small muted">
            <span>From</span>
            <span>Subject & preview</span>
            <span>Received</span>
        </div>
        <div class="conversation-list mail-v16-conversation-list">
            <?php foreach (($mailboxConversations ?? []) as $conversation): ?>
                <?php $rowSender = ($conversation['contact_name'] ?? '') ?: ($conversation['address'] ?? 'Email conversation'); ?>
                <a class="conversation-item mail-v16-row <?= $selectedConversation === ($conversation['conversation_key'] ?? '') ? 'active' : '' ?>" href="<?= e($mailCenterUrl(['conversation' => (string)($conversation['conversation_key'] ?? ''), 'mailbox' => $currentMailbox])) ?>">
                    <div class="mail-row-left">
                        <div class="mail-row-sender-line">
                            <strong class="mail-row-sender"><?= e($rowSender) ?></strong>
                            <?php if (!empty($conversation['unread_like_count'])): ?><span class="mail-row-unread-dot"></span><?php endif; ?>
                        </div>
                        <div class="small muted"><?= e($conversation['address'] ?? '') ?></div>
                    </div>
                    <div class="mail-row-main">
                        <div class="mail-row-subject-line">
                            <span class="mail-row-subject"><?= e(($conversation['subject'] ?? '') ?: 'No subject') ?></span>
                            <span class="mail-row-preview"><?= e(mb_strimwidth((string)($conversation['last_preview'] ?? ''), 0, 145, '...')) ?></span>
                        </div>
                        <div class="mail-row-tags">
                            <span class="mail-row-star <?= !empty($conversation['is_starred']) ? 'is-on' : '' ?>"><?= !empty($conversation['is_starred']) ? '★' : '☆' ?></span>
                            <span class="mail-row-bucket"><?= e(ucfirst((string)($conversation['focus_bucket'] ?? 'focused'))) ?></span>
                            <?php foreach (($conversation['labels'] ?? []) as $label): ?>
                                <span class="mail-chip color-<?= e($label['color_token'] ?? 'blue') ?>"><?= e($label['name'] ?? '') ?></span>
                            <?php endforeach; ?>
                            <?php if (!empty($conversation['has_attachment'])): ?><span class="mail-row-bucket">Attachment</span><?php endif; ?>
                        </div>
                    </div>
                    <div class="mail-row-right small muted">
                        <span><?= e($conversation['last_message_at'] ?? '') ?></span>
                        <span><?= (int)($conversation['message_count'] ?? 0) ?> msgs</span>
                    </div>
                </a>
            <?php endforeach; ?>
            <?php if (empty($mailboxConversations)): ?>
                <div class="empty-state-cell muted">No email conversations matched this folder and filter set.</div>
            <?php endif; ?>
        </div>

        <?php if (!empty($mailboxMeta) && (int)($mailboxMeta['pages'] ?? 1) > 1): ?>
            <div class="page-slider mail-page-slider">
                <?php $page = (int)($mailboxMeta['page'] ?? 1); $pages = (int)($mailboxMeta['pages'] ?? 1); ?>
                <a class="btn secondary small <?= $page <= 1 ? 'is-disabled' : '' ?>" href="<?= $page > 1 ? e($mailCenterUrl(['page' => $page - 1])) : '#' ?>">Previous</a>
                <div class="page-slider-control">
                    <input class="js-page-slider" type="range" min="1" max="<?= $pages ?>" value="<?= $page ?>" data-page-template="<?= e($mailCenterUrl(['page' => '__PAGE__'])) ?>">
                    <div class="small muted">Page <span data-slider-value><?= $page ?></span> of <?= $pages ?></div>
                </div>
                <a class="btn secondary small <?= $page >= $pages ? 'is-disabled' : '' ?>" href="<?= $page < $pages ? e($mailCenterUrl(['page' => $page + 1])) : '#' ?>">Next</a>
            </div>
        <?php endif; ?>
    </section>

    <section class="mail-v16-detail mail-outlook-detail">
        <div class="card spaced-card mail-reading-pane">
            <?php if (empty($thread) || !$selectedSummary): ?>
                <div class="mail-empty-detail">
                    <h3>Select a conversation</h3>
                    <p class="muted">Open any thread from the conversation list to review it, label it, snooze it, route it to a team mailbox, or add internal notes.</p>
                </div>
            <?php else: ?>
                <div class="toolbar mail-thread-toolbar">
                    <div>
                        <h2><?= e(($selectedSummary['subject'] ?? '') ?: 'Conversation thread') ?></h2>
                        <div class="small muted"><?= e(($selectedSummary['contact_name'] ?? '') ?: ($selectedSummary['address'] ?? '')) ?> • <?= e($selectedSummary['address'] ?? '') ?></div>
                    </div>
                    <div class="mail-thread-actions">
                        <form method="post" action="index.php?route=messages/toggleMailStar">
                            <?= csrf_input() ?>
                            <input type="hidden" name="conversation_key" value="<?= e($selectedConversation) ?>">
                            <input type="hidden" name="mailbox" value="<?= e($currentMailbox) ?>">
                            <button class="btn secondary small"><?= !empty($selectedSummary['is_starred']) ? 'Unstar' : 'Star' ?></button>
                        </form>
                        <form method="post" action="index.php?route=messages/archiveMailConversation">
                            <?= csrf_input() ?>
                            <input type="hidden" name="conversation_key" value="<?= e($selectedConversation) ?>">
                            <input type="hidden" name="mailbox" value="<?= e($currentMailbox) ?>">
                            <input type="hidden" name="mode" value="<?= $currentMailbox === 'archive' ? 'unarchive' : 'archive' ?>">
                            <button class="btn secondary small"><?= $currentMailbox === 'archive' ? 'Unarchive' : 'Archive' ?></button>
                        </form>
                        <form method="post" action="index.php?route=messages/snoozeMailConversation" class="inline-form">
                            <?= csrf_input() ?>
                            <input type="hidden" name="conversation_key" value="<?= e($selectedConversation) ?>">
                            <input type="hidden" name="mailbox" value="<?= e($currentMailbox) ?>">
                            <select name="snooze_preset">
                                <option value="tomorrow">Snooze to tomorrow</option>
                                <option value="two_days">Snooze 2 days</option>
                                <option value="next_week">Snooze next week</option>
                                <option value="clear">Clear snooze</option>
                            </select>
                            <button class="btn secondary small">Snooze</button>
                        </form>
                    </div>
                </div>

                <div class="mail-thread-meta-bar">
                    <form method="post" action="index.php?route=messages/moveEmailConversation" class="inline-form">
                        <?= csrf_input() ?>
                        <input type="hidden" name="conversation_key" value="<?= e($selectedConversation) ?>">
                        <input type="hidden" name="mailbox" value="<?= e($currentMailbox) ?>">
                        <select name="target_folder">
                            <?php foreach (($mailFolders ?? []) as $folder): ?>
                                <option value="<?= e($folder['key']) ?>" <?= ($selectedSummary['folder_key'] ?? $currentMailbox) === ($folder['key'] ?? '') ? 'selected' : '' ?>><?= e($folder['display_name'] ?? $folder['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <button class="btn secondary small">Move</button>
                    </form>
                    <form method="post" action="index.php?route=messages/applyConversationLabels" class="inline-form">
                        <?= csrf_input() ?>
                        <input type="hidden" name="conversation_key" value="<?= e($selectedConversation) ?>">
                        <input type="hidden" name="mailbox" value="<?= e($currentMailbox) ?>">
                        <select name="label_keys[]" multiple size="3">
                            <?php $selectedLabels = array_map(static fn($row) => (string)($row['label_key'] ?? ''), $selectedSummary['labels'] ?? []); ?>
                            <?php foreach (($mailLabels ?? []) as $label): ?>
                                <option value="<?= e($label['label_key']) ?>" <?= in_array((string)$label['label_key'], $selectedLabels, true) ? 'selected' : '' ?>><?= e($label['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <button class="btn secondary small">Apply labels</button>
                    </form>
                </div>

                <div class="mail-thread-stack">
                    <?php foreach ($thread as $message): ?>
                        <?php
                        $name = trim(($message['first_name'] ?? '') . ' ' . ($message['last_name'] ?? '')) ?: (($message['direction'] ?? '') === 'inbound' ? ($message['from_address'] ?? 'Sender') : 'You');
                        $initials = strtoupper(substr($name, 0, 1));
                        $attachment = (string)($message['attachment_path'] ?? '');
                        $ext = strtolower(pathinfo($attachment, PATHINFO_EXTENSION));
                        $isPreviewImage = in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp'], true);
                        ?>
                        <article class="mail-thread-card <?= e($message['direction']) ?>">
                            <div class="mail-avatar"><?= e($initials) ?></div>
                            <div class="mail-thread-body">
                                <div class="mail-thread-card-head">
                                    <strong><?= e($name) ?></strong>
                                    <span class="small muted"><?= e($message['created_at'] ?? '') ?> • <?= e($message['status'] ?? '') ?></span>
                                </div>
                                <div class="small muted"><?= e(($message['direction'] ?? '') === 'inbound' ? 'From: ' . ($message['from_address'] ?? '') : 'To: ' . ($message['to_address'] ?? '')) ?></div>
                                <?php if (!empty($message['subject'])): ?><h3><?= e($message['subject']) ?></h3><?php endif; ?>
                                <div class="mail-thread-content"><?= nl2br(e(strip_tags((string)($message['body'] ?? '')))) ?></div>
                                <?php if ($attachment !== ''): ?>
                                    <div class="mail-attachment-card">
                                        <strong>Attachment</strong>
                                        <?php if ($isPreviewImage): ?>
                                            <a href="uploads/<?= e($attachment) ?>" target="_blank" rel="noopener"><img src="uploads/<?= e($attachment) ?>" alt="Attachment preview"></a>
                                        <?php else: ?>
                                            <a href="uploads/<?= e($attachment) ?>" target="_blank" rel="noopener"><?= e($attachment) ?></a>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </article>
                    <?php endforeach; ?>
                </div>

                <div class="mail-reply-wrap">
                    <div class="toolbar compact-toolbar"><h3>Inline reply</h3><span class="badge">Autosave</span></div>
                    <div class="mail-chip-list compact" style="margin-bottom:10px;">
                        <?php foreach (($cannedReplies ?? []) as $reply): ?>
                            <button type="button" class="mail-chip color-slate js-apply-reply" data-target="mail-reply-body" data-subject-target="mail-reply-subject" data-body="<?= e((string)($reply['body'] ?? '')) ?>" data-subject="<?= e((string)($reply['subject'] ?? '')) ?>"><?= e($reply['title'] ?? 'Reply') ?></button>
                        <?php endforeach; ?>
                    </div>
                    <form method="post" action="index.php?route=messages/reply" class="mail-autosave-form" data-autosave-url="index.php?route=messages/saveMailDraft">
                        <?= csrf_input() ?>
                        <input type="hidden" name="draft_type" value="reply">
                        <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) ?>">
                        <?php if (!empty($replyDraft['id'])): ?><input type="hidden" name="draft_id" value="<?= (int)$replyDraft['id'] ?>"><?php endif; ?>
                        <div class="form-grid">
                            <input id="mail-reply-subject" name="subject" value="<?= e((string)($replyDraft['subject'] ?? ('Re: ' . ((string)($selectedSummary['subject'] ?? 'Conversation'))))) ?>" placeholder="Reply subject">
                            <select class="template-picker" data-target-body="mail-reply-body" data-target-subject="mail-reply-subject">
                                <option value="">Optional 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-reply-body" name="body" rows="8" placeholder="Reply body"><?= e((string)($replyDraft['body'] ?? '')) ?></textarea>
                        <div class="mail-draft-status small muted">Drafts autosave while you type.</div>
                        <button class="btn primary mt-12">Send reply</button>
                    </form>
                </div>
            <?php endif; ?>
        </div>

        <aside class="mail-v16-side mail-outlook-insights">
            <div class="card spaced-card mail-insights-card">
                <div class="mail-insights-nav" role="tablist" aria-label="Conversation insights">
                    <button type="button" class="mail-insight-tab is-active" data-mail-insight-tab="workflow">Workflow</button>
                    <button type="button" class="mail-insight-tab" data-mail-insight-tab="crm">CRM</button>
                    <button type="button" class="mail-insight-tab" data-mail-insight-tab="campaigns">Campaigns</button>
                    <button type="button" class="mail-insight-tab" data-mail-insight-tab="notes">Notes</button>
                </div>

                <section class="mail-insight-panel is-active" data-mail-insight-panel="workflow">
                    <div class="toolbar compact-toolbar"><h3>Conversation workflow</h3><span class="badge">Phase 4</span></div>
                    <?php if (!$selectedSummary): ?>
                        <p class="muted">Open a conversation to assign it to a teammate, route it to a shared mailbox, set SLA status, or run an approval step.</p>
                    <?php else: ?>
                        <form method="post" action="index.php?route=messages/updateMailConversation" class="stacked-panel">
                            <?= csrf_input() ?>
                            <input type="hidden" name="conversation_key" value="<?= e($selectedConversation) ?>">
                            <input type="hidden" name="mailbox" value="<?= e($currentMailbox) ?>">
                            <div class="form-grid">
                                <select name="focus_bucket">
                                    <option value="focused" <?= ($selectedSummary['focus_bucket'] ?? 'focused') === 'focused' ? 'selected' : '' ?>>Focused</option>
                                    <option value="other" <?= ($selectedSummary['focus_bucket'] ?? '') === 'other' ? 'selected' : '' ?>>Other</option>
                                </select>
                                <select name="assigned_user_id">
                                    <option value="">Unassigned</option>
                                    <?php foreach (($users ?? []) as $user): ?>
                                        <option value="<?= (int)$user['id'] ?>" <?= (int)($selectedSummary['assigned_user_id'] ?? 0) === (int)$user['id'] ? 'selected' : '' ?>><?= e($user['name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="form-grid">
                                <select name="shared_mailbox_id">
                                    <option value="">No shared mailbox</option>
                                    <?php foreach (($sharedMailboxes ?? []) as $mailbox): ?>
                                        <option value="<?= (int)$mailbox['id'] ?>" <?= (int)($selectedSummary['shared_mailbox_id'] ?? 0) === (int)$mailbox['id'] ? 'selected' : '' ?>><?= e($mailbox['name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <select name="sla_status">
                                    <?php foreach (['normal' => 'Normal', 'watch' => 'Watch', 'due_soon' => 'Due Soon', 'breached' => 'Breached', 'resolved' => 'Resolved'] as $value => $label): ?>
                                        <option value="<?= e($value) ?>" <?= ($selectedSummary['sla_status'] ?? 'normal') === $value ? 'selected' : '' ?>><?= e($label) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="form-grid">
                                <select name="approval_status">
                                    <?php foreach (['not_required' => 'No approval', 'pending' => 'Pending approval', 'approved' => 'Approved', 'rejected' => 'Rejected'] as $value => $label): ?>
                                        <option value="<?= e($value) ?>" <?= ($selectedSummary['approval_status'] ?? 'not_required') === $value ? 'selected' : '' ?>><?= e($label) ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <select name="approval_requested_user_id">
                                    <option value="">Approval owner</option>
                                    <?php foreach (($users ?? []) as $user): ?>
                                        <option value="<?= (int)$user['id'] ?>" <?= (int)($selectedSummary['approval_requested_user_id'] ?? 0) === (int)$user['id'] ? 'selected' : '' ?>><?= e($user['name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <button class="btn secondary small">Save workflow</button>
                        </form>
                    <?php endif; ?>
                </section>

                <section class="mail-insight-panel" data-mail-insight-panel="crm">
                    <div class="toolbar compact-toolbar"><h3>CRM sidebar</h3><span class="badge">Contact</span></div>
                    <?php if (!$selectedContact): ?>
                        <p class="muted">No linked contact for this conversation yet.</p>
                    <?php else: ?>
                        <div class="mail-crm-grid">
                            <div><span class="muted small">Client</span><strong><?= e(trim(($selectedContact['first_name'] ?? '') . ' ' . ($selectedContact['last_name'] ?? ''))) ?></strong></div>
                            <div><span class="muted small">Company</span><strong><?= e($selectedContact['company'] ?? '—') ?></strong></div>
                            <div><span class="muted small">Lifecycle</span><strong><?= e($selectedContact['lifecycle_stage'] ?? 'lead') ?></strong></div>
                            <div><span class="muted small">Score</span><strong><?= (int)($selectedContact['score'] ?? 0) ?></strong></div>
                            <div><span class="muted small">Email</span><strong><?= e($selectedContact['email'] ?? '—') ?></strong></div>
                            <div><span class="muted small">Phone</span><strong><?= e($selectedContact['phone'] ?? '—') ?></strong></div>
                        </div>
                        <?php if (!empty($selectedContact['tags'])): ?><div class="mail-chip-list"><?php foreach (explode(',', (string)$selectedContact['tags']) as $tag): $tag = trim($tag); if ($tag === '') continue; ?><span class="mail-chip color-slate"><?= e($tag) ?></span><?php endforeach; ?></div><?php endif; ?>
                        <p><a class="btn secondary small" href="index.php?route=contacts/show&id=<?= (int)$selectedContact['id'] ?>">Open contact record</a></p>
                    <?php endif; ?>
                </section>

                <section class="mail-insight-panel" data-mail-insight-panel="campaigns">
                    <div class="toolbar compact-toolbar"><h3>Campaign linkage</h3><span class="badge">Context</span></div>
                    <div class="mail-campaign-stack">
                        <?php foreach (($threadCampaigns ?? []) as $campaign): ?>
                            <a class="mail-campaign-card" href="index.php?route=messages/report&id=<?= (int)$campaign['id'] ?>">
                                <strong><?= e($campaign['name']) ?></strong>
                                <span class="small muted"><?= e(strtoupper((string)($campaign['channel'] ?? 'email'))) ?> • <?= e($campaign['status'] ?? '') ?></span>
                            </a>
                        <?php endforeach; ?>
                        <?php if (empty($threadCampaigns) && !empty($contactCampaigns)): foreach ($contactCampaigns as $campaign): ?>
                            <a class="mail-campaign-card" href="index.php?route=messages/report&id=<?= (int)$campaign['id'] ?>">
                                <strong><?= e($campaign['name']) ?></strong>
                                <span class="small muted"><?= e(strtoupper((string)($campaign['channel'] ?? 'email'))) ?> • <?= e($campaign['status'] ?? '') ?></span>
                            </a>
                        <?php endforeach; endif; ?>
                        <?php if (empty($threadCampaigns) && empty($contactCampaigns)): ?><p class="muted">No linked campaigns were found for this conversation yet.</p><?php endif; ?>
                    </div>
                </section>

                <section class="mail-insight-panel" data-mail-insight-panel="notes">
                    <div class="toolbar compact-toolbar"><h3>Internal notes</h3><span class="badge"><?= count($mailInternalNotes ?? []) ?></span></div>
                    <?php if ($selectedSummary): ?>
                        <form method="post" action="index.php?route=messages/addMailInternalNote" class="stacked-panel">
                            <?= csrf_input() ?>
                            <input type="hidden" name="conversation_key" value="<?= e($selectedConversation) ?>">
                            <input type="hidden" name="mailbox" value="<?= e($currentMailbox) ?>">
                            <textarea name="note_body" rows="4" placeholder="Add an internal note"></textarea>
                            <button class="btn secondary small">Save note</button>
                        </form>
                    <?php endif; ?>
                    <div class="mail-note-stack">
                        <?php foreach (($mailInternalNotes ?? []) as $note): ?>
                            <article class="mail-note-card">
                                <strong><?= e($note['created_by_name'] ?? 'Team') ?></strong>
                                <div class="small muted"><?= e($note['created_at'] ?? '') ?></div>
                                <p><?= nl2br(e((string)($note['note_body'] ?? ''))) ?></p>
                            </article>
                        <?php endforeach; ?>
                        <?php if (empty($mailInternalNotes)): ?><p class="muted">No internal notes yet.</p><?php endif; ?>
                    </div>
                </section>
            </div>
        </aside>        </aside>
    </section>
</section>
</div>

<div class="mail-compose-drawer" id="mail-compose-drawer" aria-hidden="true">
    <div class="mail-compose-panel card spaced-card">
        <div class="toolbar">
            <h2>Compose</h2>
            <button type="button" class="btn secondary small" data-compose-close="true">Close</button>
        </div>
        <div class="small muted" style="margin-bottom:10px;">Pop-out compose with server-side draft autosave.</div>
        <div class="mail-chip-list compact" style="margin-bottom:10px;">
            <?php foreach (($cannedReplies ?? []) as $reply): ?>
                <button type="button" class="mail-chip color-slate js-apply-reply" data-target="mail-compose-body" data-subject-target="mail-compose-subject" data-body="<?= e((string)($reply['body'] ?? '')) ?>" data-subject="<?= e((string)($reply['subject'] ?? '')) ?>"><?= e($reply['title'] ?? 'Reply') ?></button>
            <?php endforeach; ?>
        </div>
        <form method="post" action="index.php?route=messages/sendEmail" enctype="multipart/form-data" class="mail-autosave-form" data-autosave-url="index.php?route=messages/saveMailDraft">
            <?= csrf_input() ?>
            <input type="hidden" name="draft_type" value="compose">
            <?php if (!empty($composeDraft['id'])): ?><input type="hidden" name="draft_id" value="<?= (int)$composeDraft['id'] ?>"><?php endif; ?>
            <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'] ?>" <?= (int)($composeDraft['contact_id'] ?? 0) === (int)$contact['id'] ? 'selected' : '' ?>><?= e(trim(($contact['first_name'] ?? '') . ' ' . ($contact['last_name'] ?? '')) ?: ($contact['email'] ?? '')) ?> · <?= e($contact['email']) ?></option>
                    <?php endforeach; ?>
                </select>
                <input name="to_address" value="<?= e((string)($composeDraft['to_address'] ?? '')) ?>" placeholder="Or enter email address">
            </div>
            <select class="template-picker" data-target-body="mail-compose-body" data-target-subject="mail-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-compose-subject" name="subject" value="<?= e((string)($composeDraft['subject'] ?? '')) ?>" placeholder="Subject line">
                <input type="file" name="attachment">
            </div>
            <textarea id="mail-compose-body" name="body" rows="12" placeholder="HTML or plain text body"><?= e((string)($composeDraft['body'] ?? '')) ?></textarea>
            <div class="mail-draft-status small muted">This compose drawer autosaves to your account.</div>
            <button class="btn primary mt-12">Send Email</button>
        </form>
    </div>
</div>
