<section class="grid two">
    <div class="card">
        <h2>Send Single Message</h2>
        <div class="tabs-inline small muted">SMS/MMS and email are both available below.</div>
        <div class="grid two mt-12">
            <form method="post" action="index.php?route=messages/sendSms">
                <?= csrf_input() ?>
                <h3>SMS / MMS</h3>
                <select name="contact_id">
                    <option value="">Choose contact</option>
                    <?php foreach ($contacts as $contact): if (empty($contact['phone'])) continue; ?>
                        <option value="<?= (int)$contact['id'] ?>"><?= e(trim($contact['first_name'] . ' ' . $contact['last_name']) ?: $contact['phone']) ?> · <?= e($contact['phone']) ?></option>
                    <?php endforeach; ?>
                </select>
                <input name="to_address" placeholder="Or enter phone number">
                <select class="template-picker" data-target-body="sms-body" data-target-subject=""><option value="">Optional SMS template</option><?php foreach ($smsTemplates as $template): ?><option value="<?= (int)$template['id'] ?>" data-body="<?= e($template['body']) ?>"><?= e($template['name']) ?></option><?php endforeach; ?></select>
                <input name="media_url" placeholder="Optional media URL for MMS">
                <textarea id="sms-body" name="body" rows="6" placeholder="Message body"></textarea>
                <button class="btn primary">Send SMS/MMS</button>
            </form>
            <form method="post" action="index.php?route=messages/sendEmail" enctype="multipart/form-data">
                <?= csrf_input() ?>
                <h3>Email</h3>
                <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">
                <select class="template-picker" data-target-body="email-body" data-target-subject="email-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>
                <input id="email-subject" name="subject" placeholder="Subject line">
                <input type="file" name="attachment">
                <textarea id="email-body" name="body" rows="6" placeholder="HTML or plain text body"></textarea>
                <button class="btn primary">Send Email</button>
            </form>
        </div>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Commercial Campaign Studio</h2><span class="badge">V15</span></div>
        <p class="small muted">Built for commercial-grade campaigns with drag-and-drop email assembly, multi-variant testing, preflight checks, advanced analytics, and a deliverability-first release focus.</p>
        <form method="post" action="index.php?route=messages/createCampaign" id="campaign-form">
            <?= csrf_input() ?>
            <div class="form-grid three">
                <input name="name" placeholder="Campaign name" required>
                <select name="channel" id="campaign-channel"><option value="email">Email</option><option value="sms">SMS</option></select>
                <select name="template_id" id="campaign-template"><option value="">Choose template</option><?php foreach ($templates as $template): ?><option value="<?= (int)$template['id'] ?>" data-type="<?= e($template['type']) ?>"><?= e($template['name']) ?> (<?= e($template['type']) ?>)</option><?php endforeach; ?></select>
            </div>

            <div class="composer-shell mt-12">
                <div>
                    <div class="builder-palette">
                        <button type="button" class="btn secondary small builder-add" data-block="hero">+ Hero</button>
                        <button type="button" class="btn secondary small builder-add" data-block="heading">+ Heading</button>
                        <button type="button" class="btn secondary small builder-add" data-block="text">+ Text</button>
                        <button type="button" class="btn secondary small builder-add" data-block="image">+ Image</button>
                        <button type="button" class="btn secondary small builder-add" data-block="cta">+ CTA</button>
                        <button type="button" class="btn secondary small builder-add" data-block="divider">+ Divider</button>
                        <button type="button" class="btn secondary small builder-add" data-block="spacer">+ Spacer</button>
                    </div>
                    <input type="hidden" name="builder_json" id="campaign-builder-json">
                    <div id="builder-canvas" class="builder-canvas builder-dropzone"></div>
                    <div class="small muted">Drag blocks to reorder. The builder keeps the raw HTML editor below in sync.</div>

                    <div class="form-grid three mt-12">
                        <input name="segment_name" placeholder="Segment label">
                        <select name="segment_id"><option value="">Saved segment</option><?php foreach ($segments as $segment): ?><option value="<?= (int)$segment['id'] ?>"><?= e($segment['name']) ?></option><?php endforeach; ?></select>
                        <select name="contact_list_id" id="campaign-contact-list"><option value="">Saved contact list</option><?php foreach (($contactLists ?? []) as $list): ?><option value="<?= (int)$list['id'] ?>" data-channel="<?= e($list['channel']) ?>"><?= e($list['name']) ?> (<?= e(strtoupper($list['channel'])) ?>)</option><?php endforeach; ?></select>
                    </div>
                    <div class="form-grid two">
                        <input name="recipient_filter" placeholder="Contact tag filter">
                        <input name="scheduled_at" type="datetime-local">
                    </div>
                    <div class="form-grid two">
                        <label class="permission-pill"><input type="checkbox" name="send_time_optimization" value="1"> <span>Send-time optimization</span></label>
                        <div class="small muted">Use the deliverability center to decide whether to stage or launch immediately.</div>
                    </div>
                    <input name="subject_override" id="campaign-subject" placeholder="Subject override for email">
                    <textarea name="body_override" id="campaign-body" rows="8" placeholder="Fallback HTML / raw editor. Builder blocks keep this field updated."></textarea>

                    <details class="mt-12" open>
                        <summary><strong>Multi-variant testing</strong></summary>
                        <div class="form-grid two mt-12">
                            <label class="permission-pill"><input type="checkbox" name="ab_enabled" value="1"> <span>Enable control + A/B split</span></label>
                            <div class="small muted">Run a control version plus Variant A and Variant B content to compare opens, clicks, and bounce behavior.</div>
                            <input name="variant_a_subject" placeholder="Variant A subject (email)">
                            <input name="variant_b_subject" placeholder="Variant B subject (email)">
                            <textarea name="variant_a_body" rows="5" placeholder="Variant A body"></textarea>
                            <textarea name="variant_b_body" rows="5" placeholder="Variant B body"></textarea>
                        </div>
                    </details>

                    <details class="mt-12">
                        <summary><strong>Launch controls</strong></summary>
                        <div class="form-grid three mt-12">
                            <label class="permission-pill"><input type="checkbox" name="recurring_enabled" value="1"> <span>Recurring campaign</span></label>
                            <select name="recurring_rule"><option value="daily">Daily</option><option value="weekly">Weekly</option><option value="monthly">Monthly</option></select>
                            <select name="submit_mode">
                                <option value="queue">Queue / schedule immediately</option>
                                <option value="approval">Save for approval</option>
                                <option value="draft">Save as draft</option>
                            </select>
                        </div>
                    </details>
                </div>
                <div class="stacked-panel">
                    <div class="preview-box">
                        <div class="toolbar compact-toolbar"><strong>Live preview</strong><span class="badge">Drag-and-drop</span></div>
                        <div id="campaign-preview">Choose a template or add builder blocks to preview the campaign body here.</div>
                    </div>
                    <div class="preflight-card" id="campaign-preflight-panel">
                        <div class="toolbar compact-toolbar"><strong>Campaign preflight</strong><span class="badge">Commercial-grade</span></div>
                        <div id="campaign-preflight-summary" class="small muted">Checks update while you compose.</div>
                        <div id="campaign-preflight-list" class="preflight-list"></div>
                    </div>
                </div>
            </div>
            <button class="btn primary mt-12">Save Campaign</button>
        </form>
    </div>
</section>

<section class="cards four">
    <div class="card stat"><h3>Delivery Rate</h3><p><?= number_format((float)($healthSummary['deliverability_rate'] ?? 0), 1) ?>%</p><span>30-day processed delivery success</span></div>
    <div class="card stat alt"><h3>Bounce Rate</h3><p><?= number_format((float)($healthSummary['bounce_rate'] ?? 0), 1) ?>%</p><span>Recent email bounce signal</span></div>
    <div class="card stat alt"><h3>Queue Backlog</h3><p><?= (int)($queueStats['queued_jobs'] ?? 0) ?></p><span><?= (int)($queueStats['failed_jobs'] ?? 0) ?> failed jobs · <?= number_format((float)($healthSummary['queue_pressure'] ?? 0), 1) ?>% pressure</span></div>
    <div class="card stat alt"><h3>Suppressed</h3><p><?= (int)($suppressionSummary['email_total'] ?? 0) ?></p><span><?= (int)($suppressionSummary['complaint_total'] ?? 0) ?> complaints · <?= (int)($suppressionSummary['bounce_total'] ?? 0) ?> bounce suppressions</span></div>
</section>

<section class="grid two">
    <div class="card">
        <div class="toolbar"><h2>System Health + Deliverability Center</h2><span class="badge">Release Anchor</span></div>
        <div class="health-grid">
            <div class="health-item"><div class="small muted">SMTP</div><strong><?= !empty($providerStatus['smtp']['configured']) ? 'Ready' : 'Missing' ?></strong><span><?= e($providerStatus['smtp']['from'] ?? '') ?></span></div>
            <div class="health-item"><div class="small muted">Twilio</div><strong><?= !empty($providerStatus['twilio']['configured']) ? 'Ready' : 'Missing' ?></strong><span><?= e($providerStatus['twilio']['from'] ?? '') ?></span></div>
            <div class="health-item"><div class="small muted">Unique Opens</div><strong><?= (int)($healthSummary['unique_open_count'] ?? 0) ?></strong><span>Last 30 days</span></div>
            <div class="health-item"><div class="small muted">Unique Clicks</div><strong><?= (int)($healthSummary['unique_click_count'] ?? 0) ?></strong><span>Last 30 days</span></div>
        </div>
        <div class="alert-list mt-12">
            <?php foreach ($deliverabilityAlerts as $alert): ?>
                <article class="alert-tile <?= e($alert['severity']) ?>">
                    <strong><?= e($alert['title']) ?></strong>
                    <div class="small muted"><?= e($alert['detail']) ?></div>
                </article>
            <?php endforeach; ?>
        </div>
        <div class="stacked-badges mt-12">
            <a class="btn secondary small" href="index.php?route=settings/diagnostics">Open Diagnostics</a>
            <a class="btn secondary small" href="index.php?route=settings/providerStatus">Provider Status</a>
        </div>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Deliverability Trend</h2><span class="badge">21 days</span></div>
        <div class="mini-chart" data-series='<?= e(json_encode($analytics)) ?>' data-keys="delivered_count,unique_open_count,unique_click_count,bounced_count" data-names="Delivered|Unique Opens|Unique Clicks|Bounced" data-label-key="day"></div>
    </div>
</section>

<section class="grid two">
    <div class="card">
        <div class="toolbar"><h2>Channel Volume + Failures</h2><span class="badge">Advanced analytics</span></div>
        <div class="mini-chart" data-series='<?= e(json_encode($analytics)) ?>' data-keys="email_count,sms_count,failed_count" data-names="Email Volume|SMS Volume|Failures" data-label-key="day"></div>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Recovery Queue</h2><span class="badge">Jobs</span></div>
        <table>
            <thead><tr><th>ID</th><th>Type</th><th>Error</th></tr></thead>
            <tbody>
            <?php foreach ($failedQueueJobs as $job): ?>
                <tr>
                    <td>#<?= (int)$job['id'] ?></td>
                    <td><?= e($job['job_type']) ?></td>
                    <td><?= e(mb_strimwidth((string)$job['last_error'], 0, 90, '...')) ?></td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$failedQueueJobs): ?><tr><td colspan="3" class="muted">No failed queue jobs.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
</section>

<section class="grid conversation-grid">
    <div class="card">
        <div class="toolbar"><h2>Conversations</h2><a class="btn secondary small" href="index.php?route=messages/exportCsv&<?= e(qs_without(['route'])) ?>">Export CSV</a></div>
        <form method="get" class="inline-form toolbar-right stacked-on-mobile">
            <input type="hidden" name="route" value="messages/index">
            <input name="q" placeholder="Search address, subject, body" value="<?= e($filters['q'] ?? '') ?>">
            <select name="channel"><option value="all">All channels</option><option value="sms" <?= ($filters['channel'] ?? '') === 'sms' ? 'selected' : '' ?>>SMS</option><option value="email" <?= ($filters['channel'] ?? '') === 'email' ? 'selected' : '' ?>>Email</option></select>
            <select name="direction"><option value="all">Any direction</option><option value="inbound" <?= ($filters['direction'] ?? '') === 'inbound' ? 'selected' : '' ?>>Inbound</option><option value="outbound" <?= ($filters['direction'] ?? '') === 'outbound' ? 'selected' : '' ?>>Outbound</option></select>
            <select name="status"><option value="all">Any status</option><?php foreach (['queued','sent','delivered','received','failed','undelivered','bounced'] as $status): ?><option value="<?= $status ?>" <?= ($filters['status'] ?? '') === $status ? 'selected' : '' ?>><?= ucfirst($status) ?></option><?php endforeach; ?></select>
            <button class="btn secondary small">Filter</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/index&<?= e(qs_without(['conversation', 'route'])) ?>&conversation=<?= urlencode($conversation['conversation_key']) ?>">
                    <div class="conversation-head"><strong><?= e($conversation['contact_name'] ?: $conversation['address']) ?></strong><span class="badge"><?= e(strtoupper($conversation['channel'])) ?></span></div>
                    <div class="small muted"><?= e($conversation['address']) ?></div>
                    <div class="conversation-preview"><?= e(mb_strimwidth($conversation['last_preview'], 0, 90, '...')) ?></div>
                    <div class="conversation-meta small muted"><?= e($conversation['last_message_at']) ?> · <?= (int)$conversation['message_count'] ?> msgs<?php if ($conversation['unread_like_count']): ?> · <?= (int)$conversation['unread_like_count'] ?> new<?php endif; ?></div>
                </a>
            <?php endforeach; ?>
        </div>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Threaded View</h2><?php if ($lastMessage): ?><span class="badge"><?= e(strtoupper($lastMessage['channel'])) ?></span><?php endif; ?></div>
        <?php if (!$thread): ?>
            <p class="muted">Select a conversation to view its full history and reply inline.</p>
        <?php else: ?>
            <div class="thread">
                <?php foreach ($thread as $message): ?>
                    <article class="bubble <?= e($message['direction']) ?>">
                        <div class="bubble-meta small muted"><?= e(strtoupper($message['channel'])) ?> · <?= e($message['created_at']) ?> · <?= e($message['status']) ?></div>
                        <?php if (!empty($message['contact_id'])): ?><div class="small"><a href="index.php?route=contacts/show&id=<?= (int)$message['contact_id'] ?>">Open contact timeline</a></div><?php endif; ?>
                        <?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">
                <?= csrf_input() ?>
                <input type="hidden" name="conversation_key" value="<?= e($selectedConversation) ?>">
                <input type="hidden" name="channel" value="<?= e($lastMessage['channel']) ?>">
                <?php if (($lastMessage['channel'] ?? '') === 'email'): ?>
                    <input name="subject" value="<?= e((stripos((string)($lastMessage['subject'] ?? ''), 'Re:') === 0 ? $lastMessage['subject'] : 'Re: ' . ($lastMessage['subject'] ?? 'Conversation'))) ?>">
                <?php endif; ?>
                <textarea name="body" rows="6" placeholder="Reply in this thread"></textarea>
                <button class="btn primary">Send Reply</button>
            </form>
        <?php endif; ?>
    </div>
</section>

<section class="grid two">
    <div class="card">
        <h2>Conversation Workflow</h2>
        <?php if ($selectedConversation): ?>
        <form method="post" action="index.php?route=messages/saveConversationState">
            <?= csrf_input() ?>
            <input type="hidden" name="conversation_key" value="<?= e($selectedConversation) ?>">
            <div class="form-grid">
                <select name="status">
                    <?php foreach (['open','pending','closed'] as $statusOpt): ?>
                        <option value="<?= $statusOpt ?>" <?= (($conversationState['status'] ?? 'open') === $statusOpt) ? 'selected' : '' ?>><?= ucfirst($statusOpt) ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="assigned_user_id">
                    <option value="">Unassigned</option>
                    <?php foreach ($users as $user): ?>
                        <option value="<?= (int)$user['id'] ?>" <?= (int)($conversationState['assigned_user_id'] ?? 0) === (int)$user['id'] ? 'selected' : '' ?>><?= e($user['name']) ?></option>
                    <?php endforeach; ?>
                </select>
                <input name="internal_note" value="<?= e($conversationState['internal_note'] ?? '') ?>" placeholder="Internal note">
            </div>
            <button class="btn secondary">Save Workflow State</button>
        </form>
        <?php else: ?><p class="muted">Select a conversation to manage assignment and status.</p><?php endif; ?>
    </div>
    <div class="card">
        <h2>Canned Replies</h2>
        <div class="small muted">Copy/paste these into replies for faster handling.</div>
        <?php foreach ($cannedReplies as $reply): ?>
            <article class="bubble inbound" style="margin-top:12px;">
                <div class="bubble-meta small muted"><?= e($reply['title']) ?> · <?= e(strtoupper($reply['channel'])) ?></div>
                <?php if (!empty($reply['subject'])): ?><strong><?= e($reply['subject']) ?></strong><?php endif; ?>
                <div><?= nl2br(e($reply['body'])) ?></div>
            </article>
        <?php endforeach; ?>
    </div>
</section>

<section class="grid two">
    <div class="card">
        <div class="toolbar"><h2>Campaign Queue + Reports</h2><span class="badge">Commercial campaigns</span></div>
        <table>
            <thead><tr><th>Name</th><th>Channel</th><th>Total</th><th>Sent</th><th>Approval</th><th></th></tr></thead>
            <tbody>
            <?php foreach ($campaigns as $campaign): ?>
                <tr>
                    <td><?= e($campaign['name']) ?><br><span class="small muted"><?= e($campaign['status']) ?></span></td>
                    <td><?= e(strtoupper($campaign['channel'])) ?></td>
                    <td><?= (int)($campaign['total_recipients'] ?? 0) ?></td>
                    <td><?= (int)($campaign['sent_recipients'] ?? 0) ?></td>
                    <td><?= e($campaign['approval_status'] ?? 'not_required') ?></td>
                    <td class="actions-cell">
                        <a class="btn secondary small" href="index.php?route=messages/report&id=<?= (int)$campaign['id'] ?>">Report</a>
                        <?php if (($campaign['approval_status'] ?? 'not_required') === 'pending'): ?>
                            <a class="btn primary small" href="index.php?route=messages/approveCampaign&id=<?= (int)$campaign['id'] ?>">Approve</a>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Campaign Comparison</h2><span class="badge">Analytics</span></div>
        <table>
            <thead><tr><th>Campaign</th><th>Sent</th><th>Opens</th><th>Clicks</th><th>Bounces</th></tr></thead>
            <tbody>
            <?php foreach ($campaignComparison as $row): ?>
                <tr>
                    <td><a href="index.php?route=messages/report&id=<?= (int)$row['id'] ?>"><?= e($row['name']) ?></a></td>
                    <td><?= (int)($row['sent_recipients'] ?? 0) ?></td>
                    <td><?= (int)($row['unique_open_count'] ?? 0) ?></td>
                    <td><?= (int)($row['unique_click_count'] ?? 0) ?></td>
                    <td><?= (int)($row['bounced_count'] ?? 0) ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</section>

<section class="grid two">
    <div class="card">
        <div class="toolbar"><h2>Template Performance</h2><span class="badge">Top templates</span></div>
        <table>
            <thead><tr><th>Name</th><th>Messages</th><th>Opens</th><th>Bounces</th></tr></thead>
            <tbody><?php foreach ($templatePerformance as $row): ?><tr><td><?= e($row['name']) ?></td><td><?= (int)($row['message_count'] ?? 0) ?></td><td><?= (int)($row['unique_open_count'] ?? 0) ?></td><td><?= (int)($row['bounced_count'] ?? 0) ?></td></tr><?php endforeach; ?></tbody>
        </table>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Segment Performance</h2><span class="badge">Top segments</span></div>
        <table>
            <thead><tr><th>Segment</th><th>Messages</th><th>Clicks</th><th>Bounces</th></tr></thead>
            <tbody><?php foreach ($segmentPerformance as $row): ?><tr><td><?= e($row['segment_name']) ?></td><td><?= (int)($row['message_count'] ?? 0) ?></td><td><?= (int)($row['unique_click_count'] ?? 0) ?></td><td><?= (int)($row['bounced_count'] ?? 0) ?></td></tr><?php endforeach; ?></tbody>
        </table>
    </div>
</section>

<section class="grid two">
    <div class="card">
        <div class="toolbar"><h2>Recent Suppression Watchlist</h2><span class="badge">Deliverability</span></div>
        <table>
            <thead><tr><th>Address</th><th>Channel</th><th>Reason</th><th>Updated</th></tr></thead>
            <tbody>
            <?php foreach ($suppressionRecent as $row): ?>
                <tr>
                    <td><?= e($row['address']) ?></td>
                    <td><?= e(strtoupper($row['channel'])) ?></td>
                    <td><?= e($row['reason']) ?></td>
                    <td><?= e($row['updated_at'] ?? $row['created_at']) ?></td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$suppressionRecent): ?><tr><td colspan="4" class="muted">No recent suppressions.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
    <div class="card">
        <div class="toolbar"><h2>V15 Focus</h2><span class="badge">Commercial-grade</span></div>
        <ul class="clean-list small">
            <li>Drag-and-drop email builder with reusable content blocks and live preview.</li>
            <li>Advanced analytics charts for deliverability, volume, and campaign comparison.</li>
            <li>System Health + Deliverability Center for queue, provider, and suppression visibility.</li>
            <li>Multi-variant testing using a control version plus Variant A and Variant B.</li>
            <li>Campaign preflight checks that catch missing subjects, content, providers, and audience issues before launch.</li>
        </ul>
    </div>
</section>

<script>
window.__TEMPLATES__ = <?= $templateJson ?>;
window.__CAMPAIGN_CONTEXT__ = <?= $campaignContextJson ?>;
</script>
