<?php
$isTrash = $mode === 'trash';
$basePath = $isTrash ? '/animals/trash' : '/animals/archived';
$removedLabel = $isTrash ? t('inactive.deleted_on') : t('inactive.archived_on');
$profileMark = static function (string $value, string $label): string {
    [$symbol,$class,$state] = match($value) {
        'yes' => ['✓','text-green',t('common.yes')],'no' => ['✕','text-red',t('common.no')],default => ['—','text-secondary',t('common.unknown')]
    };
    return '<span class="' . $class . '" title="' . h($label . ' : ' . $state) . '">' . $symbol . '</span>';
};
$testBadge = static function (string $value, string $label): string {
    [$symbol,$class,$title] = match($value) {
        'neg' => ['−','bg-green-lt',t('animals.test_negative')],'pos' => ['+','bg-red-lt',t('animals.test_positive')],'doubtful' => ['?','bg-yellow-lt',t('animals.test_doubtful')],default => ['?','bg-secondary-lt',t('animals.test_unknown')]
    };
    return '<span class="badge ' . $class . '" title="' . h($label . ' : ' . $title) . '">' . h($label . ' ' . $symbol) . '</span>';
};
?>
<style>
    .inactive-age {
        width: 5.75rem;
        min-width: 5.75rem;
        white-space: nowrap
    }

    .inactive-profile {
        width: 5.75rem;
        min-width: 5.75rem;
        text-align: center
    }

    .inactive-profile-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: .15rem;
        align-items: center
    }

    .inactive-profile-grid>* {
        display: inline-flex;
        justify-content: center;
        font-weight: 700
    }

    .inactive-photo {
        width: 44px;
        height: 44px;
        object-fit: cover;
        border-radius: 10px
    }

    .inactive-weight {
        min-width: 7.5rem;
        white-space: nowrap
    }

</style>
<div class="card">
    <div class="card-header d-flex flex-wrap align-items-center gap-3">
        <div class="me-auto">
            <h3 class="card-title mb-1"><?= $isTrash ? t('inactive.trash') : t('inactive.archives') ?></h3>
            <div class="text-muted small"><?= $isTrash ? t('inactive.trash_help') : t('inactive.archive_help') ?></div>
        </div><a class="btn btn-outline-primary" href="/animals"><?= h(t('inactive.back')) ?></a>
    </div>
    <div class="card-body border-bottom">
        <form class="row g-2 align-items-center" method="get" action="<?= h($basePath) ?>">
            <div class="col"><input class="form-control" name="q" value="<?= h($q) ?>"
                    placeholder="<?= h(t('inactive.search')) ?>"></div>
            <div class="col-12 col-md-3"><select class="form-select"
                    name="status"><?php foreach ($statuses as $key => $label): ?><option value="<?= h($key) ?>"
                        <?= $status === $key ? 'selected' : '' ?>><?= h($label) ?></option><?php endforeach; ?></select>
            </div>
            <div class="col-auto"><button class="btn btn-primary" type="submit"><?= h(t('common.search')) ?></button>
            </div><?php if ($q !== '' || $status !== ''): ?><div class="col-auto"><a class="btn btn-outline-secondary"
                    href="<?= h($basePath) ?>"><?= h(t('common.clear')) ?></a></div><?php endif; ?>
        </form>
    </div>
    <div class="table-responsive">
        <table class="table table-vcenter card-table">
            <thead>
                <tr>
                    <th><?= h(t('animals.photo')) ?></th>
                    <th><?= sort_th(t('animals.name'), 'name', $sort, $dir, $basePath) ?> <span
                            class="text-muted mx-1">·</span>
                        <?= sort_th(t('animals.sex'), 'sex', $sort, $dir, $basePath) ?></th>
                    <th class="inactive-age"><?= sort_th(t('animals.age'), 'age', $sort, $dir, $basePath) ?></th>
                    <th><?= sort_th(t('animals.status'), 'status', $sort, $dir, $basePath) ?></th>
                    <th class="inactive-profile">
                        <div class="inactive-profile-grid"><?php foreach (['compatibility_dogs' => ['🐶',t('animals.dogs')],'compatibility_cats' => ['🐱',t('animals.cats')],'house_trained' => ['🧼',t('animals.cleanliness')]] as $key => [$icon,$label]):$qs = $_GET;
                            $qs['sort'] = $key;
                            $qs['dir'] = $sort === $key && $dir === 'ASC' ? 'desc' : 'asc'; ?><a class="text-reset text-decoration-none"
                                href="<?= h($basePath . '?' . http_build_query($qs)) ?>"
                                title="<?= h(t('animals.sort_by', ['label' => $label])) ?>"><?= $icon ?><?= $sort === $key ? ($dir === 'ASC' ? '↑' : '↓') : '' ?></a><?php endforeach; ?>
                        </div>
                    </th>
                    <th class="text-nowrap">FIV/FeLV</th>
                    <th class="inactive-weight"><?= sort_th(t('common.weight'), 'weight', $sort, $dir, $basePath) ?>
                    </th>
                    <th><?= sort_th(t('animals.location'), 'rescue_location_name', $sort, $dir, $basePath) ?></th>
                    <th class="text-nowrap"><?= sort_th($removedLabel, 'removed_at', $sort, $dir, $basePath) ?></th>
                    <?php if ($isTrash): ?><th><?= h(t('inactive.reason')) ?></th><?php endif; ?><th></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($animals as $animal):
                    $src = !empty($animal['primary_photo']) ? '/media/animals/' . (int)$animal['id'] . '/' . rawurlencode($animal['primary_photo']) : '/assets/cat_placeholder.svg';
                    $ageLabel = '—';
                    if (!empty($animal['birth_date'])) {
                        try {
                            $age = (new DateTimeImmutable((string)$animal['birth_date']))->diff(new DateTimeImmutable('today'));
                            $ageLabel = $age->y > 0 ? $age->y . ' a' . ($age->m ? ' · ' . $age->m . ' m' : '') : $age->m . ' m';
                            if (!empty($animal['birth_is_estimated'])) {
                                $ageLabel = '~ ' . $ageLabel;
                            }
                        } catch (Throwable) {
                        }
                    }
                    $sex = match((string)($animal['sex'] ?? 'U')) {
                        'M' => ['♂','bg-blue-lt text-blue',t('sex.male')],'F' => ['♀','bg-purple-lt text-purple',t('sex.female')],default => ['?','bg-secondary-lt text-secondary',t('sex.unknown')]
                    };
                    $removed = $animal[$isTrash ? 'deleted_at' : 'archived_at'] ?? null;
                    $removedDate = $removed ? (new DateTimeImmutable((string)$removed))->format('d/m/Y H:i') : '—';
                    ?>
                <tr>
                    <td><img class="inactive-photo" src="<?= h($src) ?>" alt=""></td>
                    <td>
                        <div class="d-flex align-items-center gap-2"><span class="coat-swatch"
                                style="<?= h(coat_swatch_style($animal['color'] ?? '')) ?>"></span><?php if (!$isTrash): ?><a
                                class="fw-bold"
                                href="/animal?id=<?= (int)$animal['id'] ?>"><?= h($animal['name']) ?></a><?php else: ?><strong><?= h($animal['name']) ?></strong><?php endif; ?><span
                                class="badge bg-secondary-lt"><?= h(species_label($animal['species'] ?? '')) ?></span><span
                                class="badge <?= h($sex[1]) ?>" title="<?= h($sex[2]) ?>"><?= h($sex[0]) ?></span></div>
                    </td>
                    <td class="inactive-age"><?= h($ageLabel) ?></td>
                    <td><?php [$statusClass,$statusLabel] = status_badge((string)$animal['status']); ?><span
                            class="badge <?= h($statusClass) ?>"><?= h($statusLabel) ?></span></td>
                    <td class="inactive-profile">
                        <div class="inactive-profile-grid">
                            <?= $profileMark((string)($animal['compatibility_dogs'] ?? 'unknown'), t('animals.dogs')) ?><?= $profileMark((string)($animal['compatibility_cats'] ?? 'unknown'), t('animals.cats')) ?><?= $profileMark((string)($animal['house_trained'] ?? 'unknown'), t('animals.cleanliness')) ?>
                        </div>
                    </td>
                    <td><?php if (SpeciesService::isCat((string)($animal['species'] ?? ''))): ?><div
                            class="d-flex flex-nowrap gap-1">
                            <?= $testBadge((string)($animal['fiv_status'] ?? 'unknown'), 'FIV') ?><?= $testBadge((string)($animal['felv_status'] ?? 'unknown'), 'FeLV') ?>
                        </div><?php else: ?><span class="text-muted">—</span><?php endif; ?></td>
                    <td class="inactive-weight"><?php if ($animal['last_weight'] === null): ?>—<?php else:$arrow = '→';
                        if ($animal['prev_weight'] !== null) {
                            $arrow = (float)$animal['last_weight'] > (float)$animal['prev_weight'] ? '↑' : ((float)$animal['last_weight'] < (float)$animal['prev_weight'] ? '↓' : '→');
                        } ?><?= h(number_format((float)$animal['last_weight'], 2, ',', ' ')) ?> kg <span
                            class="text-muted"><?= $arrow ?></span><?php endif; ?></td>
                    <td><?= h(($animal['rescue_location_name'] ?? '') ?: ($animal['rescue_address'] ?? '')) ?></td>
                    <td class="text-nowrap"><?= h($removedDate) ?></td><?php if ($isTrash): ?><td>
                        <?= h($animal['deletion_reason'] ?: '—') ?></td><?php endif; ?>
                    <td class="text-end">
                        <form method="post" action="/animal/restore"
                            onsubmit="return confirm(<?= h(json_encode(t('inactive.restore_confirm'), JSON_HEX_APOS | JSON_HEX_QUOT)) ?>);">
                            <input type="hidden" name="csrf" value="<?= h(Auth::csrf()) ?>"><input type="hidden"
                                name="id" value="<?= (int)$animal['id'] ?>"><button class="btn btn-success btn-sm"
                                type="submit"><?= h(t('inactive.restore')) ?></button></form>
                    </td>
                </tr>
                <?php endforeach; ?><?php if (!$animals): ?><tr>
                    <td colspan="<?= $isTrash ? 11 : 10 ?>" class="text-center text-muted py-4">
                        <?= $isTrash ? t('inactive.no_trash') : t('inactive.no_archive') ?></td>
                </tr><?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
