<?php
declare(strict_types=1);

/**
 * @var \App\View\AppView $this
 * @var \Cake\Collection\CollectionInterface<\App\Model\Entity\ContactMessage> $messages
 * @var array<string, string> $statusOptions
 * @var array<string, string> $interestOptions
 * @var array<string, int> $metrics
 * @var int $filteredCount
 * @var string $status
 * @var string $interest
 * @var string $search
 */

// $messages is paginated. Iterate directly; toList() works on ResultSet too.
$messageList = is_object($messages) && method_exists($messages, 'toList')
    ? $messages->toList()
    : iterator_to_array($messages);
$totalUnread = (int)($metrics['new'] ?? 0);
$totalInProgress = (int)($metrics['in_progress'] ?? 0);
$totalResolved = (int)($metrics['resolved'] ?? 0);
$totalSpam = (int)($metrics['spam'] ?? 0);
$totalAll = (int)($metrics['total'] ?? 0);

$chipDefs = [
    ''            => ['All',         $totalAll],
    'new'         => ['New',         $totalUnread],
    'in_progress' => ['In progress', $totalInProgress],
    'resolved'    => ['Resolved',    $totalResolved],
    'spam'        => ['Spam',        $totalSpam],
];

function interest_display(?string $value, array $map): string
{
    if ($value === null || $value === '') {
        return '—';
    }
    return $map[$value] ?? ucfirst(str_replace('_', ' ', $value));
}
?>
<?php $this->assign('title', 'Inbox · CandleCraft Admin'); ?>

<section class="cc-admin-page">
    <div class="cc-admin-page__head">
        <div>
            <div class="cc-eyebrow" style="margin-bottom: 12px;">Inbox</div>
            <h1>Today's enquiries · <span style="color: var(--cc-clay);"><?= $totalUnread ?> unread</span></h1>
        </div>
        <div class="cc-admin-page__stats">
            <?php foreach ([[$totalUnread, 'New'], [$totalInProgress, 'In progress'], [$totalResolved, 'Resolved'], [$totalSpam, 'Spam']] as [$n, $l]): ?>
                <div class="cc-admin-stat">
                    <strong><?= $n ?></strong>
                    <span><?= h($l) ?></span>
                </div>
            <?php endforeach; ?>
        </div>
    </div>

    <?= $this->Form->create(null, ['type' => 'get', 'class' => 'cc-inbox-controls']) ?>
        <div class="cc-inbox-search">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
                <circle cx="7" cy="7" r="5" /><path d="M11 11 L14 14" />
            </svg>
            <?= $this->Form->control('q', [
                'label' => false,
                'class' => 'cc-input',
                'value' => $search,
                'placeholder' => 'Search by name, email, subject…',
                'id' => 'q',
            ]) ?>
        </div>
        <div class="cc-inbox-chips">
            <?php foreach ($chipDefs as $value => [$label, $count]):
                $isOn = $status === $value;
                $href = $this->Url->build([
                    '_name' => 'admin_messages',
                    '?' => array_filter([
                        'status' => $value ?: null,
                        'q' => $search ?: null,
                        'interest' => $interest ?: null,
                    ]),
                ]);
            ?>
                <a class="cc-inbox-chip<?= $isOn ? ' is-on' : '' ?>" href="<?= h($href) ?>">
                    <?= h($label) ?>
                    <span class="cc-inbox-chip__count"><?= (int)$count ?></span>
                </a>
            <?php endforeach; ?>
        </div>
        <?php if ($search !== ''): ?>
            <input type="hidden" name="status" value="<?= h($status) ?>">
        <?php endif; ?>
    <?= $this->Form->end() ?>

    <table class="cc-inbox-table">
        <thead>
            <tr class="cc-inbox-row cc-inbox-row--head">
                <th scope="col" style="width: 24px;"></th>
                <th scope="col">Sender</th>
                <th scope="col" data-priority="2">Interest</th>
                <th scope="col" data-priority="3">Subject</th>
                <th scope="col" data-priority="2">Submitted</th>
                <th scope="col" data-priority="1">Status</th>
                <th scope="col" style="text-align:right;">Action</th>
            </tr>
        </thead>
        <tbody>
        <?php if (empty($messageList)): ?>
            <tr>
                <td colspan="7">
                    <div class="cc-inbox-empty">
                        <h3>No enquiries yet.</h3>
                        <p>The quiet is a feature.</p>
                    </div>
                </td>
            </tr>
        <?php else: ?>
            <?php foreach ($messageList as $m):
                $isNew = $m->status === 'new';
                $interestLabel = interest_display((string)$m->interest_area, $interestOptions);
                $viewUrl = $this->Url->build(['_name' => 'admin_message_view', 'id' => $m->id]);
                $submitted = $m->created?->format('d M · H:i') ?? '';
            ?>
                <tr class="cc-inbox-row cc-inbox-row--data<?= $isNew ? ' cc-inbox-row--new' : '' ?>" onclick="window.location='<?= h($viewUrl) ?>'">
                    <td>
                        <?php if ($isNew): ?><span class="cc-inbox-row__newdot" aria-label="New"></span><?php endif; ?>
                    </td>
                    <td>
                        <div class="cc-inbox-sender-name"><?= h($m->full_name) ?></div>
                        <div class="cc-inbox-sender-email"><?= h($m->email) ?></div>
                    </td>
                    <td data-priority="2"><?= h($interestLabel) ?></td>
                    <td data-priority="3" class="cc-inbox-subject"><?= h((string)($m->subject ?: 'General question')) ?></td>
                    <td data-priority="2" class="cc-inbox-submitted"><?= h($submitted) ?></td>
                    <td data-priority="1"><span class="cc-badge cc-badge--<?= h((string)$m->status) ?>"><?= h(ucwords(str_replace('_', ' ', (string)$m->status))) ?></span></td>
                    <td style="text-align:right;">
                        <a class="cc-btn cc-btn--ghost cc-btn--sm" href="<?= h($viewUrl) ?>" onclick="event.stopPropagation();">Open →</a>
                    </td>
                </tr>
            <?php endforeach; ?>
        <?php endif; ?>
        </tbody>
    </table>

    <?php $pagingParams = $this->Paginator->params(); ?>
    <nav class="cc-paginator" aria-label="Pagination">
        <div class="cc-paginator__info">
            Showing <?= count($messageList) ?> of <?= (int)($pagingParams['count'] ?? $totalAll) ?> · page <?= (int)($pagingParams['page'] ?? 1) ?> of <?= max(1, (int)($pagingParams['pageCount'] ?? 1)) ?>
        </div>
        <ul class="cc-paginator__pages">
            <?= $this->Paginator->prev('‹ Prev', ['class' => 'cc-paginator__btn']) ?>
            <?= $this->Paginator->numbers(['class' => 'cc-paginator__num', 'modulus' => 4, 'first' => 1, 'last' => 1, 'separator' => '']) ?>
            <?= $this->Paginator->next('Next ›', ['class' => 'cc-paginator__btn']) ?>
        </ul>
    </nav>
</section>
