<?php $pendingApproval = count(array_filter($campaigns ?? [], fn($row) => ($row['approval_status'] ?? 'not_required') === 'pending')); ?>
<section class="workspace-hero">
    <div>
        <h2>Campaign Dashboard</h2>
        <p>Monitor delivery rate, bounce rate, queue backlog, suppressed addresses, system health, deliverability trends, campaign comparisons, and performance by template and segment.</p>
    </div>
    <div class="workspace-actions">
        <a class="btn secondary small" href="index.php?route=messages/commercialCampaign">Commercial Campaign</a>
        <a class="btn secondary small" href="index.php?route=messages/campaignStudio">Campaign Studio</a>
        <a class="btn secondary small" href="index.php?route=messages/campaignReports">Campaign Reports</a>
    </div>
</section>

<section class="cards four compact-stats">
    <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">Mail</div><strong><?= !empty($providerStatus['smtp']['configured']) ? 'Ready' : 'Missing' ?></strong><span><?= e(($providerStatus['smtp']['label'] ?? 'Mail') . ' · ' . ($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>
            <a class="btn secondary small" href="index.php?route=messages/campaignReports">Recovery Queue</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>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; ?>
            <?php if (empty($campaignComparison)): ?><tr><td colspan="5" class="muted">No recent campaign analytics yet.</td></tr><?php endif; ?>
            </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; ?>
            <?php if (empty($templatePerformance)): ?><tr><td colspan="4" class="muted">No template performance data yet.</td></tr><?php endif; ?>
            </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; ?>
            <?php if (empty($segmentPerformance)): ?><tr><td colspan="4" class="muted">No segment performance data yet.</td></tr><?php endif; ?>
            </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 (empty($suppressionRecent)): ?><tr><td colspan="4" class="muted">No recent suppressions.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
    <div class="card spaced-card">
        <div class="toolbar"><h2>Campaign Operations Snapshot</h2><span class="badge">Live summary</span></div>
        <div class="metric-strip">
            <div class="metric-chip"><strong><?= count($campaigns ?? []) ?></strong><span class="small muted">campaigns on record</span></div>
            <div class="metric-chip"><strong><?= (int)$pendingApproval ?></strong><span class="small muted">pending approvals</span></div>
            <div class="metric-chip"><strong><?= (int)($queueStats['failed_jobs'] ?? 0) ?></strong><span class="small muted">failed queue jobs</span></div>
        </div>
        <ul class="feature-list small">
            <li>Use Campaign Studio to design launches with drag-and-drop blocks and preflight checks.</li>
            <li>Use Campaign Reports to monitor the recovery queue and open detailed campaign reports.</li>
            <li>The Deliverability Center is the primary control point for reliability, visibility, and trust.</li>
        </ul>
    </div>
</section>
