<template>
    <div class="space-y-6">
        <Head title="Card Status" />

        <section class="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
            <StatCard
                title="Active Cards"
                :value="stats.active"
                hint="Cards ready for transactions."
            />
            <StatCard
                title="Printed Cards"
                :value="stats.printed"
                hint="Printed cards pending activation."
            />
            <StatCard
                title="Created Cards"
                :value="stats.created"
                hint="Personalized cards awaiting print."
            />
            <StatCard
                title="In Stock Cards"
                :value="stats.in_stock"
                hint="Pre-generated inventory in stock."
            />
        </section>

        <div class="rounded-2xl border border-slate-200 bg-white p-6">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-lg font-semibold">Card Status Management</h3>
                    <p class="mt-2 text-xs text-slate-500">
                        Activate issued cards and manage active-card lifecycle states.
                    </p>
                </div>
            </div>

            <!-- Filters -->
            <div class="mt-6 flex flex-wrap items-end gap-3 rounded-xl border border-slate-100 bg-slate-50/50 p-4">
                <div>
                    <label class="mb-1 block text-xs font-medium text-slate-600">Status</label>
                    <select
                        v-model="filterForm.status"
                        class="rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs focus:border-slate-400 focus:outline-none focus:ring-1 focus:ring-slate-400"
                    >
                        <option value="">All</option>
                        <option value="active">Active</option>
                        <option value="printed">Printed</option>
                        <option value="created">Created</option>
                        <option value="in_stock">In stock</option>
                        <option value="assigned">Assigned</option>
                        <option value="generated">Generated</option>
                        <option value="deactivated">Deactivated</option>
                        <option value="temporary_blocked">Temporary blocked</option>
                        <option value="permanent_blocked">Permanent blocked</option>
                        <option value="stolen">Stolen</option>
                        <option value="for_replacement">For replacement</option>
                    </select>
                </div>
                <div>
                    <label class="mb-1 block text-xs font-medium text-slate-600">Card type</label>
                    <select
                        v-model="filterForm.card_type"
                        class="rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs focus:border-slate-400 focus:outline-none focus:ring-1 focus:ring-slate-400"
                    >
                        <option value="">All</option>
                        <option value="PRE_GENERATED">Pre-generated</option>
                        <option value="PERSONALIZED">Personalized</option>
                    </select>
                </div>
                <div>
                    <label class="mb-1 block text-xs font-medium text-slate-600">Search</label>
                    <input
                        v-model="filterForm.search"
                        type="text"
                        placeholder="Card, client, account..."
                        class="rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs focus:border-slate-400 focus:outline-none focus:ring-1 focus:ring-slate-400"
                    />
                </div>
                <button
                    type="button"
                    class="rounded-lg bg-slate-700 px-4 py-2 text-xs font-medium text-white hover:bg-slate-600"
                    @click="applyFilters"
                >
                    Apply
                </button>
            </div>

            <div class="mt-4 overflow-hidden rounded-xl border border-slate-100">
                <table class="w-full text-left text-xs">
                    <thead class="bg-slate-50 text-slate-500">
                        <tr>
                            <th class="px-4 py-3">Card Number</th>
                            <th class="px-4 py-3">Client</th>
                            <th class="px-4 py-3">Account</th>
                            <th class="px-4 py-3">Status</th>
                            <th class="px-4 py-3">Created</th>
                            <th class="px-4 py-3 text-right">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr
                            v-for="card in cards"
                            :key="card.uuid"
                            class="border-t border-slate-100"
                        >
                            <td class="px-4 py-3 font-medium">
                                {{ card.card_number || '—' }}
                            </td>
                            <td class="px-4 py-3 text-slate-500">
                                {{ card.client_name || '—' }}
                            </td>
                            <td class="px-4 py-3 text-slate-500">
                                {{ card.account_number || '—' }}
                            </td>
                            <td class="px-4 py-3">
                                <span
                                    :class="statusBadge(card.status)"
                                    class="rounded-full px-2 py-1 text-[10px] font-semibold"
                                >
                                    {{ statusLabel(card.status) }}
                                </span>
                            </td>
                            <td class="px-4 py-3 text-slate-500">
                                {{ card.issued_at || '—' }}
                            </td>
                            <td class="px-4 py-3 text-right">
                                <div class="flex flex-col items-end gap-2">
                                    <div class="flex justify-end gap-2">
                                        <button
                                            type="button"
                                            class="rounded-lg border border-slate-200 px-3 py-1 text-[11px] font-semibold text-slate-700 hover:bg-slate-50"
                                            :disabled="!canManageCards || limitsModal.loading"
                                            @click="openLimitsModal(card)"
                                        >
                                            Manage Limits
                                        </button>
                                        <button
                                            type="button"
                                            class="rounded-lg border border-slate-200 px-3 py-1 text-[11px] font-semibold text-slate-700 hover:bg-slate-50"
                                            :disabled="
                                                !canManageCards ||
                                                !canActivate(card) ||
                                                activateForm.processing
                                            "
                                            @click="activate(card)"
                                        >
                                            Activate
                                        </button>
                                        <template v-if="canChangeActiveStatus(card)">
                                            <select
                                                v-model="statusSelections[card.uuid]"
                                                class="rounded-lg border border-slate-200 bg-white px-2 py-1 text-[11px] text-slate-700 focus:border-slate-400 focus:outline-none focus:ring-1 focus:ring-slate-400"
                                                :disabled="!canManageCards || statusForm.processing"
                                            >
                                                <option value="">Select status</option>
                                                <option
                                                    v-for="statusOption in statusTransitionOptions"
                                                    :key="statusOption.value"
                                                    :value="statusOption.value"
                                                >
                                                    {{ statusOption.label }}
                                                </option>
                                            </select>
                                            <button
                                                type="button"
                                                class="rounded-lg border border-slate-200 px-3 py-1 text-[11px] font-semibold text-slate-700 hover:bg-slate-50"
                                                :disabled="
                                                    !canManageCards ||
                                                    !statusSelections[card.uuid] ||
                                                    statusForm.processing
                                                "
                                                @click="updateStatus(card)"
                                            >
                                                Update
                                            </button>
                                        </template>
                                    </div>
                                    <p
                                        v-if="statusErrors[card.uuid]"
                                        class="text-[11px] text-red-600"
                                    >
                                        {{ statusErrors[card.uuid] }}
                                    </p>
                                </div>
                            </td>
                        </tr>
                        <tr v-if="cards.length === 0">
                            <td
                                class="px-4 py-6 text-center text-xs text-slate-400"
                                colspan="6"
                            >
                                No cards are available for status management.
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- Pagination -->
            <div
                v-if="pagination && pagination.last_page > 1"
                class="mt-4 flex flex-wrap items-center justify-between gap-3 border-t border-slate-100 pt-4"
            >
                <p class="text-xs text-slate-500">
                    Showing {{ pagination.from ?? 0 }}–{{ pagination.to ?? 0 }} of {{ pagination.total }}
                </p>
                <div class="flex items-center gap-1">
                    <a
                        v-if="pagination.prev_page_url"
                        :href="pagination.prev_page_url"
                        class="rounded-lg border border-slate-200 px-3 py-1.5 text-xs font-medium text-slate-700 hover:bg-slate-50"
                        @click.prevent="goToUrl(pagination.prev_page_url)"
                    >
                        Previous
                    </a>
                    <template v-for="(link, i) in pagination.links" :key="i">
                        <span
                            v-if="link.label === '...'"
                            class="px-2 py-1 text-xs text-slate-400"
                        >
                            {{ link.label }}
                        </span>
                        <a
                            v-else-if="link.url"
                            :href="link.url"
                            class="rounded-lg border px-3 py-1.5 text-xs font-medium"
                            :class="link.active ? 'border-slate-700 bg-slate-700 text-white' : 'border-slate-200 text-slate-700 hover:bg-slate-50'"
                            @click.prevent="goToUrl(link.url)"
                        >
                            {{ link.label || link.page }}
                        </a>
                    </template>
                    <a
                        v-if="pagination.next_page_url"
                        :href="pagination.next_page_url"
                        class="rounded-lg border border-slate-200 px-3 py-1.5 text-xs font-medium text-slate-700 hover:bg-slate-50"
                        @click.prevent="goToUrl(pagination.next_page_url)"
                    >
                        Next
                    </a>
                </div>
            </div>
        </div>

        <div class="rounded-2xl border border-slate-200 bg-white p-6">
            <h3 class="text-lg font-semibold">Lifecycle History</h3>
            <p class="mt-2 text-xs text-slate-500">
                Issuance, printing, activation, and assignment activity.
            </p>
            <div class="mt-4 overflow-hidden rounded-xl border border-slate-100">
                <table class="w-full text-left text-xs">
                    <thead class="bg-slate-50 text-slate-500">
                        <tr>
                            <th class="px-4 py-3">Time</th>
                            <th class="px-4 py-3">Action</th>
                            <th class="px-4 py-3">Entity</th>
                            <th class="px-4 py-3">Reference</th>
                            <th class="px-4 py-3">User</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr
                            v-for="row in history"
                            :key="row.id"
                            class="border-t border-slate-100"
                        >
                            <td class="px-4 py-3 text-slate-500">
                                {{ row.created_at || '—' }}
                            </td>
                            <td class="px-4 py-3 font-medium">
                                {{ row.action }}
                            </td>
                            <td class="px-4 py-3 text-slate-500">
                                {{ row.entity }}
                            </td>
                            <td class="px-4 py-3 text-slate-500">
                                {{ row.entity_id || '—' }}
                            </td>
                            <td class="px-4 py-3 text-slate-500">
                                {{ row.user }}
                            </td>
                        </tr>
                        <tr v-if="history.length === 0">
                            <td
                                class="px-4 py-6 text-center text-slate-400"
                                colspan="5"
                            >
                                No lifecycle history recorded yet.
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <div
            v-if="limitsModal.open"
            class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 p-4"
        >
            <div class="flex max-h-[90vh] w-full max-w-6xl flex-col rounded-2xl border border-slate-200 bg-white shadow-xl">
                <div class="flex items-start justify-between gap-3 border-b border-slate-100 px-5 py-4">
                    <div>
                        <h4 class="text-base font-semibold text-slate-800">Manage Card Limits</h4>
                        <p class="mt-1 text-xs text-slate-500">
                            Card {{ limitsModal.card?.card_number || '—' }}
                            <span v-if="limitsModal.card?.client_name">
                                • {{ limitsModal.card.client_name }}
                            </span>
                            • {{ statusLabel(limitsModal.card?.status) }}
                        </p>
                    </div>
                    <button
                        type="button"
                        class="rounded-lg px-2 py-1 text-xs text-slate-500 hover:bg-slate-100"
                        @click="closeLimitsModal"
                    >
                        Close
                    </button>
                </div>

                <div class="min-h-0 flex-1 overflow-auto p-5">
                    <div
                        v-if="limitsModal.error"
                        class="mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-xs text-red-700"
                    >
                        {{ limitsModal.error }}
                    </div>

                    <div class="mb-3 flex items-center justify-between gap-3">
                        <p class="text-xs text-slate-500">
                            Limits are saved per transaction type for this specific card.
                        </p>
                        <button
                            type="button"
                            class="rounded-lg border border-slate-200 px-3 py-1.5 text-xs font-medium text-slate-700 hover:bg-slate-50"
                            @click="addLimitRow"
                        >
                            Add Txn Type
                        </button>
                    </div>

                    <div class="overflow-x-auto rounded-xl border border-slate-100">
                        <table class="min-w-[1280px] text-left text-xs">
                            <thead class="bg-slate-50 text-slate-500">
                                <tr>
                                    <th class="px-3 py-3">Txn Type</th>
                                    <th class="px-3 py-3">Per Txn</th>
                                    <th class="px-3 py-3">Daily</th>
                                    <th class="px-3 py-3">Weekly</th>
                                    <th class="px-3 py-3">Monthly</th>
                                    <th class="px-3 py-3">Quarterly</th>
                                    <th class="px-3 py-3">Semi-Annual</th>
                                    <th class="px-3 py-3">Annual</th>
                                    <th class="px-3 py-3">Used Today</th>
                                    <th class="px-3 py-3">Used This Month</th>
                                    <th class="px-3 py-3 text-right">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr
                                    v-for="(row, index) in limitsModal.rows"
                                    :key="`${row.txn_type}-${index}`"
                                    class="border-t border-slate-100"
                                >
                                    <td class="px-3 py-2">
                                        <input
                                            v-model="row.txn_type"
                                            type="text"
                                            class="w-40 rounded-lg border border-slate-200 px-2 py-1.5 text-xs uppercase focus:border-slate-400 focus:outline-none focus:ring-1 focus:ring-slate-400"
                                            placeholder="PURCHASE"
                                        />
                                    </td>
                                    <td
                                        v-for="field in limitFields"
                                        :key="field.key"
                                        class="px-3 py-2"
                                    >
                                        <input
                                            v-model="row[field.key]"
                                            type="number"
                                            min="0"
                                            step="0.01"
                                            class="w-28 rounded-lg border border-slate-200 px-2 py-1.5 text-xs focus:border-slate-400 focus:outline-none focus:ring-1 focus:ring-slate-400"
                                        />
                                    </td>
                                    <td class="px-3 py-2 text-slate-600">
                                        {{ formatUsageAmount(row.usage?.daily?.amount_used) }}
                                        <span class="text-[11px] text-slate-400">
                                            ({{ row.usage?.daily?.txn_count || 0 }} txns)
                                        </span>
                                    </td>
                                    <td class="px-3 py-2 text-slate-600">
                                        {{ formatUsageAmount(row.usage?.monthly?.amount_used) }}
                                        <span class="text-[11px] text-slate-400">
                                            ({{ row.usage?.monthly?.txn_count || 0 }} txns)
                                        </span>
                                    </td>
                                    <td class="px-3 py-2 text-right">
                                        <button
                                            type="button"
                                            class="rounded-lg border border-red-200 px-2 py-1 text-[11px] font-medium text-red-600 hover:bg-red-50"
                                            @click="removeLimitRow(index)"
                                        >
                                            Remove
                                        </button>
                                    </td>
                                </tr>
                                <tr v-if="limitsModal.rows.length === 0">
                                    <td
                                        class="px-4 py-6 text-center text-xs text-slate-400"
                                        colspan="11"
                                    >
                                        No limit rows available.
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="flex items-center justify-end gap-2 border-t border-slate-100 px-5 py-4">
                    <button
                        type="button"
                        class="rounded-lg border border-slate-200 px-4 py-2 text-xs font-medium text-slate-700 hover:bg-slate-50"
                        @click="closeLimitsModal"
                    >
                        Cancel
                    </button>
                    <button
                        type="button"
                        class="rounded-lg bg-slate-700 px-4 py-2 text-xs font-medium text-white hover:bg-slate-600 disabled:cursor-not-allowed disabled:opacity-60"
                        :disabled="limitsModal.saving"
                        @click="saveLimits"
                    >
                        {{ limitsModal.saving ? 'Saving...' : 'Save Limits' }}
                    </button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { reactive, watch } from 'vue';
import { Head, router, useForm } from '@inertiajs/vue3';
import AuthenticatedLayout from '../../Layouts/AuthenticatedLayout.vue';
import StatCard from '../../Components/StatCard.vue';

defineOptions({
    layout: (h, page) =>
        h(AuthenticatedLayout, { title: 'Card Status' }, () => page),
});

const props = defineProps({
    cards: {
        type: Array,
        default: () => [],
    },
    stats: {
        type: Object,
        default: () => ({
            active: 0,
            printed: 0,
            created: 0,
            in_stock: 0,
        }),
    },
    history: {
        type: Array,
        default: () => [],
    },
    canManageCards: {
        type: Boolean,
        default: false,
    },
    filters: {
        type: Object,
        default: () => ({}),
    },
    pagination: {
        type: Object,
        default: () => null,
    },
});

const filterForm = reactive({
    status: props.filters?.status ?? '',
    card_type: props.filters?.card_type ?? '',
    search: props.filters?.search ?? '',
});

watch(
    () => props.filters,
    (f) => {
        if (f) {
            filterForm.status = f.status ?? '';
            filterForm.card_type = f.card_type ?? '';
            filterForm.search = f.search ?? '';
        }
    },
    { immediate: true }
);

function applyFilters() {
    router.get('/cards/status', {
        page: 1,
        status: filterForm.status || undefined,
        card_type: filterForm.card_type || undefined,
        search: filterForm.search?.trim() || undefined,
    });
}

function goToUrl(url) {
    if (!url) return;
    router.visit(url);
}

const limitFields = [
    { key: 'per_transaction_limit' },
    { key: 'daily_limit' },
    { key: 'weekly_limit' },
    { key: 'monthly_limit' },
    { key: 'quarterly_limit' },
    { key: 'semi_annual_limit' },
    { key: 'annual_limit' },
];

const limitsModal = reactive({
    open: false,
    loading: false,
    saving: false,
    error: '',
    card: null,
    rows: [],
});

function normalizeLimitRow(row = {}) {
    return {
        txn_type: (row.txn_type ?? '').toString().toUpperCase(),
        per_transaction_limit: row.per_transaction_limit ?? '0',
        daily_limit: row.daily_limit ?? '0',
        weekly_limit: row.weekly_limit ?? '0',
        monthly_limit: row.monthly_limit ?? '0',
        quarterly_limit: row.quarterly_limit ?? '0',
        semi_annual_limit: row.semi_annual_limit ?? '0',
        annual_limit: row.annual_limit ?? '0',
        usage: row.usage ?? {},
    };
}

function formatUsageAmount(amount) {
    if (amount === null || amount === undefined || amount === '') {
        return '0.00';
    }
    const parsed = Number(amount);
    return Number.isFinite(parsed) ? parsed.toFixed(2) : '0.00';
}

async function openLimitsModal(card) {
    if (!props.canManageCards || !card?.uuid) {
        return;
    }

    limitsModal.open = true;
    limitsModal.loading = true;
    limitsModal.saving = false;
    limitsModal.error = '';
    limitsModal.card = {
        uuid: card.uuid,
        card_number: card.card_number,
        client_name: card.client_name,
        status: card.status,
    };
    limitsModal.rows = [];

    try {
        const response = await window.axios.get(`/cards/${card.uuid}/limits`);
        const rows = Array.isArray(response.data?.limits)
            ? response.data.limits
            : [];
        limitsModal.rows = rows.map(normalizeLimitRow);
    } catch (error) {
        limitsModal.error =
            error?.response?.data?.message || 'Unable to load card limits.';
    } finally {
        limitsModal.loading = false;
    }
}

function closeLimitsModal() {
    limitsModal.open = false;
    limitsModal.loading = false;
    limitsModal.saving = false;
    limitsModal.error = '';
    limitsModal.card = null;
    limitsModal.rows = [];
}

function addLimitRow() {
    limitsModal.rows.push(normalizeLimitRow({ txn_type: '' }));
}

function removeLimitRow(index) {
    limitsModal.rows.splice(index, 1);
}

async function saveLimits() {
    if (!limitsModal.card?.uuid) return;

    const sanitizedRows = limitsModal.rows
        .map((row) => ({
            txn_type: row.txn_type?.toString().trim().toUpperCase(),
            per_transaction_limit: row.per_transaction_limit || 0,
            daily_limit: row.daily_limit || 0,
            weekly_limit: row.weekly_limit || 0,
            monthly_limit: row.monthly_limit || 0,
            quarterly_limit: row.quarterly_limit || 0,
            semi_annual_limit: row.semi_annual_limit || 0,
            annual_limit: row.annual_limit || 0,
        }))
        .filter((row) => row.txn_type);

    if (sanitizedRows.length === 0) {
        limitsModal.error = 'Add at least one transaction type limit row.';
        return;
    }

    limitsModal.error = '';
    limitsModal.saving = true;

    try {
        await window.axios.put(`/cards/${limitsModal.card.uuid}/limits`, {
            limits: sanitizedRows,
        });
        closeLimitsModal();
    } catch (error) {
        const responseErrors = error?.response?.data?.errors;
        if (responseErrors) {
            limitsModal.error = Object.values(responseErrors)
                .flat()
                .join(' ');
        } else {
            limitsModal.error =
                error?.response?.data?.message || 'Failed to save card limits.';
        }
    } finally {
        limitsModal.saving = false;
    }
}

const statusErrors = reactive({});
const activateForm = useForm({});
const statusForm = useForm({ status: '' });
const statusSelections = reactive({});
const statusTransitionOptions = [
    { value: 'deactivated', label: 'Deactivated' },
    { value: 'temporary_blocked', label: 'Temporary blocked' },
    { value: 'permanent_blocked', label: 'Permanent blocked' },
    { value: 'stolen', label: 'Stolen' },
    { value: 'for_replacement', label: 'For replacement' },
];

const canActivate = (card) =>
    (card.card_type === 'PERSONALIZED' && card.status === 'printed') ||
    (card.card_type === 'PRE_GENERATED' && card.status === 'assigned');

const activate = (card) => {
    statusErrors[card.uuid] = '';

    if (!props.canManageCards) {
        statusErrors[card.uuid] = 'You do not have permission to manage cards.';
        return;
    }

    if (!canActivate(card)) {
        statusErrors[card.uuid] =
            'Only printed personalized cards or assigned stock cards can be activated.';
        return;
    }

    activateForm.put(`/cards/${card.uuid}/activate`, {
        preserveScroll: true,
        onError: (errors) => {
            if (errors.card_uuid) {
                statusErrors[card.uuid] = errors.card_uuid;
            }
        },
    });
};

const canChangeActiveStatus = (card) => card.status === 'active';

const updateStatus = (card) => {
    statusErrors[card.uuid] = '';

    if (!props.canManageCards) {
        statusErrors[card.uuid] = 'You do not have permission to manage cards.';
        return;
    }

    if (!canChangeActiveStatus(card)) {
        statusErrors[card.uuid] = 'Only active cards can be updated to another lifecycle status.';
        return;
    }

    const selectedStatus = statusSelections[card.uuid];
    if (!selectedStatus) {
        statusErrors[card.uuid] = 'Please choose a status before updating.';
        return;
    }

    statusForm.status = selectedStatus;
    statusForm.put(`/cards/${card.uuid}/status`, {
        preserveScroll: true,
        onSuccess: () => {
            statusSelections[card.uuid] = '';
        },
        onError: (errors) => {
            if (errors.card_uuid) {
                statusErrors[card.uuid] = errors.card_uuid;
                return;
            }
            if (errors.status) {
                statusErrors[card.uuid] = errors.status;
            }
        },
    });
};

const statusBadge = (status) => {
    if (status === 'active') {
        return 'bg-emerald-100 text-emerald-700';
    }
    if (status === 'printed') {
        return 'bg-slate-100 text-slate-700';
    }
    if (status === 'created') {
        return 'bg-amber-100 text-amber-700';
    }
    if (status === 'in_stock') {
        return 'bg-sky-100 text-sky-700';
    }
    if (status === 'assigned') {
        return 'bg-indigo-100 text-indigo-700';
    }
    if (status === 'deactivated') {
        return 'bg-slate-200 text-slate-700';
    }
    if (status === 'temporary_blocked') {
        return 'bg-orange-100 text-orange-700';
    }
    if (status === 'permanent_blocked') {
        return 'bg-red-100 text-red-700';
    }
    if (status === 'stolen') {
        return 'bg-rose-100 text-rose-700';
    }
    if (status === 'for_replacement') {
        return 'bg-violet-100 text-violet-700';
    }
    return 'bg-slate-100 text-slate-600';
};

const statusLabel = (status) => {
    const labels = {
        active: 'Active',
        printed: 'Printed',
        created: 'Created',
        in_stock: 'In stock',
        assigned: 'Assigned',
        generated: 'Generated',
        deactivated: 'Deactivated',
        temporary_blocked: 'Temporary blocked',
        permanent_blocked: 'Permanent blocked',
        stolen: 'Stolen',
        for_replacement: 'For replacement',
    };

    return labels[status] ?? status;
};
</script>
