<?php
$actionButton = function (string $route, string $label, int $campaignId, string $returnTo = 'report', string $class = 'secondary'): string {
    ob_start();
    ?>
    <form method="post" action="index.php?route=<?= e($route) ?>" style="display:inline-block;margin:4px 6px 0 0;">
        <?= csrf_input() ?>
        <input type="hidden" name="campaign_id" value="<?= (int)$campaignId ?>">
        <input type="hidden" name="return_to" value="<?= e($returnTo) ?>">
        <button class="btn <?= e($class) ?> small" type="submit"><?= e($label) ?></button>
    </form>
    <?php
    return trim((string)ob_get_clean());
};
$deleteButton = function (int $campaignId, string $returnTo = 'reports', string $campaignName = 'this campaign'): string {
    ob_start();
    ?>
    <form method="post" action="index.php?route=messages/deleteCampaign" style="display:inline-block;margin:4px 6px 0 0;" onsubmit="return confirm('Delete <?= e(addslashes($campaignName)) ?>? This removes queued recipients, queued jobs, and unsent campaign history.');">
        <?= csrf_input() ?>
        <input type="hidden" name="campaign_id" value="<?= (int)$campaignId ?>">
        <input type="hidden" name="return_to" value="<?= e($returnTo) ?>">
        <button class="btn danger small" type="submit">Delete</button>
    </form>
    <?php
    return trim((string)ob_get_clean());
};
$operatorState = (string)($campaign['operator_state'] ?? 'running');
$displayStatus = (string)($campaign['display_status'] ?? ($campaign['status'] ?? 'draft'));
$hasQueued = (int)($campaign['queued_recipients'] ?? 0) > 0;
$hasFailed = (int)($campaign['failed_recipients'] ?? 0) > 0;
$isPending = ($campaign['approval_status'] ?? 'not_required') === 'pending';
$isActive = in_array((string)($campaign['status'] ?? ''), ['queued', 'processing'], true) && $operatorState === 'running';
$canDelete = !in_array((string)($campaign['status'] ?? ''), ['processing'], true)
    && (int)($campaign['sent_recipients'] ?? 0) <= 0
    && (int)($campaign['delivered_count'] ?? 0) <= 0;
$reportPerPageOptions = $reportPerPageOptions ?? [15, 25, 50];
$reportWindowUrl = function (array $changes = [], ?string $hash = null) use ($campaign): string {
    $query = $_GET;
    $query['route'] = 'messages/report';
    $query['id'] = (int)($campaign['id'] ?? 0);
    foreach ($changes as $key => $value) {
        if ($value === null) {
            unset($query[$key]);
            continue;
        }
        $query[$key] = $value;
    }
    return 'index.php?' . http_build_query($query) . ($hash ? '#' . $hash : '');
};
$renderReportPager = function (array $pager, string $pageKey, string $perPageKey, string $windowId, string $label = 'records') use ($reportPerPageOptions, $reportWindowUrl): string {
    $start = $pager['total'] > 0 ? ($pager['offset'] + 1) : 0;
    $end = min($pager['offset'] + $pager['per_page'], $pager['total']);
    $from = max(1, $pager['page'] - 2);
    $to = min($pager['pages'], $pager['page'] + 2);
    $currentQuery = $_GET;
    ob_start();
    ?>
    <div class="report-window-footer">
        <div class="small muted">Showing <?= (int)$start ?>-<?= (int)$end ?> of <?= (int)$pager['total'] ?> <?= e($label) ?></div>
        <div class="report-window-footer-actions">
            <form method="get" action="<?= e($reportWindowUrl([], $windowId)) ?>" class="report-window-page-size">
                <?php foreach ($currentQuery as $queryKey => $queryValue): ?>
                    <?php if (in_array($queryKey, [$pageKey, $perPageKey], true)) { continue; } ?>
                    <input type="hidden" name="<?= e((string)$queryKey) ?>" value="<?= e((string)$queryValue) ?>">
                <?php endforeach; ?>
                <input type="hidden" name="<?= e($pageKey) ?>" value="1">
                <label>
                    <span>View</span>
                    <select name="<?= e($perPageKey) ?>" onchange="this.form.submit()">
                        <?php foreach ($reportPerPageOptions as $option): ?>
                            <option value="<?= (int)$option ?>" <?= (int)$pager['per_page'] === (int)$option ? 'selected' : '' ?>><?= (int)$option ?></option>
                        <?php endforeach; ?>
                    </select>
                </label>
            </form>
            <?php if (($pager['pages'] ?? 1) > 1): ?>
                <nav class="report-window-pager" aria-label="<?= e(ucfirst(str_replace('_', ' ', $pageKey))) ?> pages">
                    <a class="<?= $pager['page'] <= 1 ? 'is-disabled' : '' ?>" href="<?= $pager['page'] <= 1 ? '#' : e($reportWindowUrl([$pageKey => $pager['page'] - 1], $windowId)) ?>">Previous</a>
                    <?php for ($pageNumber = $from; $pageNumber <= $to; $pageNumber++): ?>
                        <a class="<?= $pageNumber === (int)$pager['page'] ? 'is-active' : '' ?>" href="<?= e($reportWindowUrl([$pageKey => $pageNumber], $windowId)) ?>"><?= (int)$pageNumber ?></a>
                    <?php endfor; ?>
                    <a class="<?= $pager['page'] >= $pager['pages'] ? 'is-disabled' : '' ?>" href="<?= $pager['page'] >= $pager['pages'] ? '#' : e($reportWindowUrl([$pageKey => $pager['page'] + 1], $windowId)) ?>">Next</a>
                </nav>
            <?php endif; ?>
        </div>
    </div>
    <?php
    return trim((string)ob_get_clean());
};
?>
<section class="cards four">
    <div class="card stat"><h3>Recipients</h3><p><?= (int)($campaign['total_recipients'] ?? 0) ?></p><span><?= e($campaign['name']) ?></span></div>
    <div class="card stat alt"><h3>Queued</h3><p><?= (int)($campaign['queued_recipients'] ?? 0) ?></p><span><?= e(ucfirst($operatorState)) ?> run control</span></div>
    <div class="card stat alt"><h3>Delivery Rate</h3><p><?= number_format((float)($campaignHealth['delivery_rate'] ?? 0), 1) ?>%</p><span><?= e(strtoupper($campaign['channel'] ?? '')) ?> launch health</span></div>
    <div class="card stat alt"><h3>Click Rate</h3><p><?= number_format((float)($campaignHealth['click_rate'] ?? 0), 1) ?>%</p><span>Unique clicks vs recipients</span></div>
</section>

<section class="grid two">
    <div class="card">
        <div class="toolbar"><h2>Campaign Report</h2><span class="badge">V16.9.2</span></div>
        <table>
            <tbody>
                <tr><th>Name</th><td><?= e($campaign['name']) ?></td></tr>
                <tr><th>Channel</th><td><?= e(strtoupper($campaign['channel'])) ?></td></tr>
                <tr><th>Template</th><td><?= e($campaign['template_name'] ?? 'None') ?></td></tr>
                <tr><th>Status</th><td><?= e($displayStatus) ?></td></tr>
                <tr><th>Run Control</th><td><?= e(ucfirst($operatorState)) ?></td></tr>
                <tr><th>Approval</th><td><?= e($campaign['approval_status'] ?? 'not_required') ?></td></tr>
                <tr><th>Scheduled</th><td><?= e($campaign['scheduled_at'] ?? 'Immediate') ?></td></tr>
                <tr><th>Audience</th><td><?= e($preflight['summary']['audience_source'] ?? ($campaign['segment_name'] ?: 'All reachable contacts')) ?></td></tr>
                <tr><th>Saved List</th><td><?= e($campaign['contact_list_name'] ?? 'None') ?></td></tr>
                <tr><th>Variants</th><td><?= (int)($preflight['summary']['variant_count'] ?? 1) ?> versions</td></tr>
                <tr><th>Builder Blocks</th><td><?= (int)($preflight['summary']['block_count'] ?? 0) ?></td></tr>
            </tbody>
        </table>
        <div class="stacked-badges mt-12">
            <a class="btn secondary small" href="index.php?route=messages/campaignReports">Back to Campaign Reports</a>
            <a class="btn secondary small" href="index.php?route=settings/providerStatus">Provider Status</a>
            <?php if ($isPending): ?>
                <a class="btn primary small" href="index.php?route=messages/approveCampaign&id=<?= (int)$campaign['id'] ?>">Approve Campaign</a>
            <?php endif; ?>
        </div>
        <div class="mt-12">
            <div class="small muted" style="margin-bottom:10px;">Open report windows for <?= e($campaign['name']) ?></div>
            <div class="stacked-badges">
                <button type="button" class="btn secondary small" data-report-window-launch="report-window-recipients">Recipient Breakdown</button>
                <button type="button" class="btn secondary small" data-report-window-launch="report-window-opened">People Who Opened</button>
                <button type="button" class="btn secondary small" data-report-window-launch="report-window-clicked">People Who Clicked</button>
            </div>
            <div class="small muted" style="margin-top:8px;">These windows stay closed until you open them for this campaign.</div>
        </div>
        <div class="mt-12">
            <?php if (!$isPending): ?>
                <?php if ($hasQueued): ?>
                    <?= $actionButton('messages/startCampaign', 'Start', (int)$campaign['id']) ?>
                <?php endif; ?>
                <?php if ($isActive): ?>
                    <?= $actionButton('messages/pauseCampaign', 'Pause', (int)$campaign['id']) ?>
                    <?= $actionButton('messages/stopCampaign', 'Stop', (int)$campaign['id']) ?>
                <?php endif; ?>
                <?php if ($hasFailed || $operatorState === 'stopped'): ?>
                    <?= $actionButton('messages/restartCampaign', 'Restart', (int)$campaign['id']) ?>
                <?php endif; ?>
                <?php if ($hasQueued || $hasFailed): ?>
                    <?= $actionButton('messages/forceQueueCampaign', 'Force Queue', (int)$campaign['id'], 'report', 'primary') ?>
                <?php endif; ?>
            <?php endif; ?>
            <?php if ($canDelete): ?>
                <?= $deleteButton((int)$campaign['id'], 'reports', (string)($campaign['name'] ?? 'this campaign')) ?>
            <?php else: ?>
                <span class="small muted">Delete is available before a campaign sends or enters active processing.</span>
            <?php endif; ?>
        </div>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Run Controls</h2><span class="badge">Queue recovery</span></div>
        <div class="health-grid">
            <div class="health-item"><div class="small muted">Queued Recipients</div><strong><?= (int)($campaign['queued_recipients'] ?? 0) ?></strong><span>ready to resume or force</span></div>
            <div class="health-item"><div class="small muted">Failed Recipients</div><strong><?= (int)($campaign['failed_recipients'] ?? 0) ?></strong><span>restart to recover</span></div>
            <div class="health-item"><div class="small muted">Queue Jobs</div><strong><?= (int)($queueStats['queued_jobs'] ?? 0) ?> queued</strong><span><?= (int)($queueStats['failed_jobs'] ?? 0) ?> failed jobs</span></div>
            <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>
        <ul class="feature-list small" style="margin-top:16px;">
            <li><strong>Start</strong> resumes queued recipients while respecting the scheduled send time unless you use Force Queue.</li>
            <li><strong>Pause</strong> halts active processing and leaves unsent recipients in the queue.</li>
            <li><strong>Stop</strong> halts the run until an operator explicitly restarts or force-queues it.</li>
            <li><strong>Restart</strong> returns failed recipients to the queue and launches a fresh processing pass.</li>
            <li><strong>Force Queue</strong> pulls the campaign back into the queue immediately after provider or SMTP changes.</li>
            <li><strong>Delete</strong> removes campaigns created by mistake before they send, including queued recipients and pending queue jobs.</li>
        </ul>
    </div>
</section>

<section class="grid two">
    <div class="card">
        <div class="toolbar"><h2>Preflight Checklist</h2><span class="badge">Launch guardrails</span></div>
        <div class="preflight-list">
            <?php foreach (($preflight['checks'] ?? []) as $check): ?>
                <div class="preflight-row status-<?= e($check['status']) ?>">
                    <strong><?= e($check['label']) ?></strong>
                    <span><?= e($check['detail']) ?></span>
                </div>
            <?php endforeach; ?>
        </div>
        <?php if (!empty($preflight['warnings'])): ?>
            <div class="alert-list mt-12">
                <?php foreach ($preflight['warnings'] as $warning): ?>
                    <article class="alert-tile warn"><strong>Warning</strong><div class="small muted"><?= e($warning) ?></div></article>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
        <?php if (!empty($preflight['errors'])): ?>
            <div class="alert-list mt-12">
                <?php foreach ($preflight['errors'] as $error): ?>
                    <article class="alert-tile error"><strong>Blocking issue</strong><div class="small muted"><?= e($error) ?></div></article>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Send Test</h2><span class="badge">Preview lane</span></div>
        <form method="post" action="index.php?route=messages/sendCampaignTest">
            <?= csrf_input() ?>
            <input type="hidden" name="campaign_id" value="<?= (int)$campaign['id'] ?>">
            <div class="form-grid">
                <input name="to_address" placeholder="<?= ($campaign['channel'] ?? 'email') === 'sms' ? 'Phone number' : 'Email address' ?>" required>
                <select name="variant">
                    <option value="default">Control content</option>
                    <?php if (!empty($campaign['variant_a_body']) || !empty($campaign['variant_a_subject'])): ?><option value="a">Variant A</option><?php endif; ?>
                    <?php if (!empty($campaign['variant_b_body']) || !empty($campaign['variant_b_subject'])): ?><option value="b">Variant B</option><?php endif; ?>
                </select>
            </div>
            <button class="btn primary">Send Test</button>
        </form>
        <div class="mini-chart mt-12" data-series='<?= e(json_encode($trend)) ?>' 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>Variant Performance</h2><span class="badge">Control + A/B</span></div>
        <div class="mini-chart" data-series='<?= e(json_encode($variantPerformance)) ?>' data-keys="message_count,unique_open_count,unique_click_count,bounced_count" data-names="Messages|Unique Opens|Unique Clicks|Bounced" data-label-key="label"></div>
        <table style="margin-top:16px;">
            <thead><tr><th>Variant</th><th>Messages</th><th>Open Rate</th><th>Click Rate</th><th>Bounce Rate</th></tr></thead>
            <tbody>
            <?php foreach ($variantPerformance as $row): ?>
                <tr>
                    <td><?= e($row['label']) ?></td>
                    <td><?= (int)($row['message_count'] ?? 0) ?></td>
                    <td><?= number_format((float)($row['open_rate'] ?? 0), 1) ?>%</td>
                    <td><?= number_format((float)($row['click_rate'] ?? 0), 1) ?>%</td>
                    <td><?= number_format((float)($row['bounce_rate'] ?? 0), 1) ?>%</td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$variantPerformance): ?><tr><td colspan="5" class="muted">No variant data yet.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Comparison Snapshot</h2><span class="badge">Recent campaigns</span></div>
        <table>
            <thead><tr><th>Campaign</th><th>Sent</th><th>Opens</th><th>Clicks</th></tr></thead>
            <tbody>
            <?php foreach ($comparison 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>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</section>


<section class="grid two">
    <div class="card">
        <div class="toolbar"><h2>Report Explorer</h2><span class="badge">Open on demand</span></div>
        <div class="metric-strip">
            <div class="metric-chip"><strong><?= (int)($recipientPager['total'] ?? 0) ?></strong><span class="small muted">Recipient breakdown rows ready to inspect.</span></div>
            <div class="metric-chip"><strong><?= (int)($openPager['total'] ?? 0) ?></strong><span class="small muted">Tracked open rows for this campaign.</span></div>
            <div class="metric-chip"><strong><?= (int)($clickPager['total'] ?? 0) ?></strong><span class="small muted">Tracked click rows for this campaign.</span></div>
        </div>
        <p class="small muted" style="margin-top:16px;">Use the campaign-level buttons above to open only the report window you need. Each window can still be dragged, minimized, restored, or closed once opened.</p>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Template + Segment Performance</h2><span class="badge">Benchmarks</span></div>
        <div class="grid two" style="margin-bottom:0;">
            <div>
                <h3>Templates</h3>
                <table>
                    <thead><tr><th>Name</th><th>Messages</th><th>Opens</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></tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <div>
                <h3>Segments</h3>
                <table>
                    <thead><tr><th>Segment</th><th>Messages</th><th>Clicks</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></tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</section>

<div class="theme-pro-window report-drilldown-window report-drilldown-window--wide" id="report-window-recipients" hidden data-report-window="report-window-recipients" data-default-left="36" data-default-top="160">
    <div class="theme-pro-window-head" data-report-window-handle>
        <div class="theme-pro-window-meta">
            <strong>Recipient Breakdown</strong>
            <small>Campaign execution log with paged results and fast navigation.</small>
        </div>
        <div class="theme-pro-window-actions">
            <span class="theme-pro-window-badge"><?= (int)($recipientPager['total'] ?? 0) ?> recipients</span>
            <button type="button" class="btn secondary small" data-report-window-minimize="report-window-recipients">Minimize</button>
            <button type="button" class="btn secondary small" data-report-window-close="report-window-recipients">Close</button>
        </div>
    </div>
    <div class="theme-pro-window-body">
        <div class="report-window-table-wrap">
            <table>
                <thead><tr><th>Recipient</th><th>Status</th><th>Message</th><th>Processed</th></tr></thead>
                <tbody>
                <?php foreach ($recipients as $row): ?>
                    <tr>
                        <td><?= e(trim(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? '')) ?: ($row['address'] ?? '')) ?><br><span class="small muted"><?= e($row['address']) ?></span></td>
                        <td><?= e($row['status']) ?><?php if (!empty($row['error_message'])): ?><br><span class="small muted"><?= e($row['error_message']) ?></span><?php endif; ?></td>
                        <td><?= e($row['message_status'] ?? '-') ?></td>
                        <td><?= e($row['processed_at'] ?? '-') ?></td>
                    </tr>
                <?php endforeach; ?>
                <?php if (!$recipients): ?><tr><td colspan="4" class="muted">No recipient activity captured yet.</td></tr><?php endif; ?>
                </tbody>
            </table>
        </div>
        <?= $renderReportPager($recipientPager, 'rb_page', 'rb_per_page', 'report-window-recipients', 'recipients') ?>
    </div>
</div>

<div class="theme-pro-window report-drilldown-window" id="report-window-opened" hidden data-report-window="report-window-opened" data-default-left="120" data-default-top="212">
    <div class="theme-pro-window-head" data-report-window-handle>
        <div class="theme-pro-window-meta">
            <strong>People Who Opened</strong>
            <small>Track which contacts opened the campaign and when they first and last opened.</small>
        </div>
        <div class="theme-pro-window-actions">
            <span class="theme-pro-window-badge"><?= (int)($openPager['total'] ?? 0) ?> opens</span>
            <button type="button" class="btn secondary small" data-report-window-minimize="report-window-opened">Minimize</button>
            <button type="button" class="btn secondary small" data-report-window-close="report-window-opened">Close</button>
        </div>
    </div>
    <div class="theme-pro-window-body">
        <div class="report-window-table-wrap">
            <table>
                <thead><tr><th>Contact</th><th>Opens</th><th>First Open</th><th>Last Open</th></tr></thead>
                <tbody>
                <?php foreach ($openRecipients as $row): ?>
                    <tr>
                        <td>
                            <?php if (!empty($row['contact_id'])): ?>
                                <a href="index.php?route=contacts/show&id=<?= (int)$row['contact_id'] ?>&comm=email"><?= e(trim(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? '')) ?: ($row['email'] ?? $row['to_address'] ?? 'Contact')) ?></a>
                            <?php else: ?>
                                <?= e(trim(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? '')) ?: ($row['email'] ?? $row['to_address'] ?? 'Contact')) ?>
                            <?php endif; ?>
                            <br><span class="small muted"><?= e($row['email'] ?? $row['to_address'] ?? '') ?></span>
                        </td>
                        <td><?= (int)($row['open_count'] ?? 0) ?></td>
                        <td><?= e($row['first_open_at'] ?? '-') ?></td>
                        <td><?= e($row['last_open_at'] ?? '-') ?></td>
                    </tr>
                <?php endforeach; ?>
                <?php if (!$openRecipients): ?><tr><td colspan="4" class="muted">No open activity captured yet.</td></tr><?php endif; ?>
                </tbody>
            </table>
        </div>
        <?= $renderReportPager($openPager, 'open_page', 'open_per_page', 'report-window-opened', 'open records') ?>
    </div>
</div>

<div class="theme-pro-window report-drilldown-window" id="report-window-clicked" hidden data-report-window="report-window-clicked" data-default-left="204" data-default-top="264">
    <div class="theme-pro-window-head" data-report-window-handle>
        <div class="theme-pro-window-meta">
            <strong>People Who Clicked</strong>
            <small>Track clicked links, counts, and the most recent click timestamp.</small>
        </div>
        <div class="theme-pro-window-actions">
            <span class="theme-pro-window-badge"><?= (int)($clickPager['total'] ?? 0) ?> click records</span>
            <button type="button" class="btn secondary small" data-report-window-minimize="report-window-clicked">Minimize</button>
            <button type="button" class="btn secondary small" data-report-window-close="report-window-clicked">Close</button>
        </div>
    </div>
    <div class="theme-pro-window-body">
        <div class="report-window-table-wrap">
            <table>
                <thead><tr><th>Contact</th><th>Clicked Link</th><th>Clicks</th><th>Last Click</th></tr></thead>
                <tbody>
                <?php foreach ($clickRecipients as $row): ?>
                    <tr>
                        <td>
                            <?php if (!empty($row['contact_id'])): ?>
                                <a href="index.php?route=contacts/show&id=<?= (int)$row['contact_id'] ?>&comm=email"><?= e(trim(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? '')) ?: ($row['email'] ?? $row['to_address'] ?? 'Contact')) ?></a>
                            <?php else: ?>
                                <?= e(trim(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? '')) ?: ($row['email'] ?? $row['to_address'] ?? 'Contact')) ?>
                            <?php endif; ?>
                            <br><span class="small muted"><?= e($row['email'] ?? $row['to_address'] ?? '') ?></span>
                        </td>
                        <td><div style="max-width:320px;word-break:break-word;"><?= e($row['clicked_url'] ?? '(tracked link)') ?></div></td>
                        <td><?= (int)($row['click_count'] ?? 0) ?></td>
                        <td><?= e($row['last_click_at'] ?? '-') ?></td>
                    </tr>
                <?php endforeach; ?>
                <?php if (!$clickRecipients): ?><tr><td colspan="4" class="muted">No click activity captured yet.</td></tr><?php endif; ?>
                </tbody>
            </table>
        </div>
        <?= $renderReportPager($clickPager, 'click_page', 'click_per_page', 'report-window-clicked', 'click records') ?>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const windows = Array.from(document.querySelectorAll('[data-report-window]'));
    if (!windows.length) return;
    const launchButtons = Array.from(document.querySelectorAll('[data-report-window-launch]'));
    const campaignId = <?= (int)($campaign['id'] ?? 0) ?>;
    const storageKey = 'aio-report-drilldowns-' + campaignId;
    let zIndex = 120;
    let state = {};
    try {
        state = JSON.parse(localStorage.getItem(storageKey) || '{}') || {};
    } catch (error) {
        state = {};
    }
    const saveState = () => {
        const next = {};
        windows.forEach((windowEl) => {
            next[windowEl.id] = {
                left: windowEl.style.left || null,
                top: windowEl.style.top || null,
                zIndex: windowEl.style.zIndex || null,
            };
        });
        localStorage.setItem(storageKey, JSON.stringify(next));
    };
    const updateLaunchState = () => {
        launchButtons.forEach((button) => {
            const targetId = button.getAttribute('data-report-window-launch');
            const target = document.getElementById(targetId || '');
            if (!target) return;
            button.classList.toggle('is-muted', !!target.hidden);
            if (target.hidden) {
                button.dataset.windowState = 'closed';
            } else if (target.classList.contains('is-minimized')) {
                button.dataset.windowState = 'minimized';
            } else {
                button.dataset.windowState = 'open';
            }
        });
    };
    const clampWindow = (windowEl) => {
        const width = windowEl.offsetWidth || 860;
        const height = windowEl.offsetHeight || 420;
        const left = Math.min(Math.max(parseFloat(windowEl.style.left || '0'), 12), Math.max(12, window.innerWidth - width - 12));
        const top = Math.min(Math.max(parseFloat(windowEl.style.top || '0'), 72), Math.max(72, window.innerHeight - Math.max(height, 110) - 12));
        windowEl.style.left = left + 'px';
        windowEl.style.top = top + 'px';
    };
    const bringToFront = (windowEl) => {
        zIndex += 1;
        windowEl.style.zIndex = String(zIndex);
    };
    const restoreWindow = (windowEl) => {
        if (!windowEl) return;
        windowEl.hidden = false;
        windowEl.classList.remove('is-minimized');
        const minimizeButton = windowEl.querySelector('[data-report-window-minimize]');
        if (minimizeButton) minimizeButton.textContent = 'Minimize';
        bringToFront(windowEl);
        clampWindow(windowEl);
        saveState();
        updateLaunchState();
    };
    const toggleMinimize = (windowEl) => {
        if (!windowEl) return;
        if (windowEl.hidden) {
            restoreWindow(windowEl);
            return;
        }
        if (windowEl.classList.contains('is-minimized')) {
            windowEl.classList.remove('is-minimized');
            const minimizeButton = windowEl.querySelector('[data-report-window-minimize]');
            if (minimizeButton) minimizeButton.textContent = 'Minimize';
            clampWindow(windowEl);
        } else {
            windowEl.classList.add('is-minimized');
            const minimizeButton = windowEl.querySelector('[data-report-window-minimize]');
            if (minimizeButton) minimizeButton.textContent = 'Restore';
        }
        bringToFront(windowEl);
        saveState();
        updateLaunchState();
    };
    windows.forEach((windowEl) => {
        const saved = state[windowEl.id] || {};
        if (saved.left) windowEl.style.left = saved.left;
        if (saved.top) windowEl.style.top = saved.top;
        if (saved.zIndex) windowEl.style.zIndex = saved.zIndex;
        if (!saved.left) windowEl.style.left = (parseFloat(windowEl.dataset.defaultLeft || '36')) + 'px';
        if (!saved.top) windowEl.style.top = (parseFloat(windowEl.dataset.defaultTop || '160')) + 'px';
        windowEl.hidden = true;
        windowEl.classList.remove('is-minimized');
        const minimizeButton = windowEl.querySelector('[data-report-window-minimize]');
        if (minimizeButton) minimizeButton.textContent = 'Minimize';
        bringToFront(windowEl);
        clampWindow(windowEl);
        const handle = windowEl.querySelector('[data-report-window-handle]');
        const closeButton = windowEl.querySelector('[data-report-window-close]');
        if (closeButton) {
            closeButton.addEventListener('click', function () {
                windowEl.hidden = true;
                windowEl.classList.remove('is-minimized');
                const button = windowEl.querySelector('[data-report-window-minimize]');
                if (button) button.textContent = 'Minimize';
                updateLaunchState();
            });
        }
        if (minimizeButton) {
            minimizeButton.addEventListener('click', function () {
                toggleMinimize(windowEl);
            });
        }
        if (handle) {
            let drag = null;
            handle.addEventListener('pointerdown', function (event) {
                if (event.target.closest('button, a, input, select, textarea, label')) return;
                drag = {
                    pointerId: event.pointerId,
                    startX: event.clientX,
                    startY: event.clientY,
                    left: windowEl.offsetLeft,
                    top: windowEl.offsetTop,
                };
                bringToFront(windowEl);
                windowEl.classList.add('is-dragging');
                handle.setPointerCapture(event.pointerId);
                event.preventDefault();
            });
            handle.addEventListener('pointermove', function (event) {
                if (!drag || drag.pointerId !== event.pointerId) return;
                const nextLeft = drag.left + (event.clientX - drag.startX);
                const nextTop = drag.top + (event.clientY - drag.startY);
                windowEl.style.left = nextLeft + 'px';
                windowEl.style.top = nextTop + 'px';
                clampWindow(windowEl);
            });
            const endDrag = function (event) {
                if (!drag || drag.pointerId !== event.pointerId) return;
                windowEl.classList.remove('is-dragging');
                drag = null;
                saveState();
            };
            handle.addEventListener('pointerup', endDrag);
            handle.addEventListener('pointercancel', endDrag);
            handle.addEventListener('dblclick', function (event) {
                if (event.target.closest('button, a, input, select, textarea, label')) return;
                toggleMinimize(windowEl);
            });
        }
        windowEl.addEventListener('mousedown', function () {
            bringToFront(windowEl);
            saveState();
        });
    });
    launchButtons.forEach((button) => {
        button.addEventListener('click', function () {
            const target = document.getElementById(button.getAttribute('data-report-window-launch') || '');
            if (!target) return;
            restoreWindow(target);
        });
    });
    if (window.location.hash) {
        const hashTarget = document.querySelector(window.location.hash);
        if (hashTarget && hashTarget.matches('[data-report-window]')) {
            restoreWindow(hashTarget);
        }
    }
    window.addEventListener('resize', function () {
        windows.forEach(clampWindow);
        saveState();
    });
    updateLaunchState();
    saveState();
});
</script>
