<script setup>
import { computed, onMounted, ref, watch } from 'vue';
import { Head, Link, useForm, usePage } from '@inertiajs/vue3';
import AppCard from '@/Components/ui/AppCard.vue';
import FundingAccountsList from '@/Components/app/FundingAccountsList.vue';
import TransactionReceiptModal from '@/Components/app/TransactionReceiptModal.vue';
import MobileAppLayout from '@/Layouts/MobileAppLayout.vue';
import StatusBadge from '@/Components/ui/StatusBadge.vue';

const props = defineProps({
    wallet: Object,
    ledger: Object,
    referralBonus: {
        type: Object,
        default: () => ({ count: 0, total: '0.00', recent: [] }),
    },
    cashbackBonus: {
        type: Object,
        default: () => ({ count: 0, total: '0.00', recent: [] }),
    },
    cashbackWallet: {
        type: Object,
        default: () => ({ balance: '0.00' }),
    },
    cashbackLedger: {
        type: Array,
        default: () => [],
    },
    cashbackPolicy: {
        type: Object,
        default: () => ({ enabled: false, expiry_days: 90, expires_at: null, days_remaining: null }),
    },
    walletTransferSettings: {
        type: Object,
        default: () => ({ enabled: false, min_amount: 100, max_amount: 1000000 }),
    },
    walletTransferUsage: {
        type: Object,
        default: () => ({
            sent_count: 0,
            sent_amount: 0,
            daily_count_limit: 20,
            daily_total_limit: 3000000,
            remaining_count: 20,
            remaining_amount: 3000000,
        }),
    },
    reservedAccounts: Array,
    fundingMethods: {
        type: Object,
        default: () => ({}),
    },
    fundingLimits: {
        type: Object,
        default: () => ({ min_amount: 100, max_amount: 5000000 }),
    },
    fundingAttempts: {
        type: Array,
        default: () => [],
    },
});

const page = usePage();
const appName = computed(() => String(page.props?.branding?.app_name || 'VTU App').trim());
const hasTransactionPin = computed(() => !!page.props.auth?.user?.has_transaction_pin);
const verifiedRecipientInput = ref('');
const beneficiaryLookupState = ref({
    status: 'idle',
    message: '',
    beneficiary: null,
});

const transferForm = useForm({
    recipient: '',
    amount: '',
    narration: '',
    transaction_pin: '',
});
const fundingForm = useForm({
    amount: '',
});
const fundingProviderInProgress = ref('');

const fundingMethodByKey = computed(() => {
    return {
        monnifyReserved: props.fundingMethods?.monnify_reserved ?? {},
        paymentpointReserved: props.fundingMethods?.paymentpoint_reserved ?? {},
        monnifyInstant: props.fundingMethods?.monnify_instant ?? {},
        paystack: props.fundingMethods?.paystack ?? {},
    };
});
const fundingAttempts = computed(() => props.fundingAttempts ?? []);

const walletTabs = [
    { key: 'funding', label: 'Funding' },
    { key: 'transfer', label: 'Transfer' },
    { key: 'rewards', label: 'Rewards' },
    { key: 'ledger', label: 'Ledger' },
];

const activeTab = ref('funding');
const TAB_STORAGE_KEY = 'vtuapp.wallet.active_tab';
const showLedgerReceiptModal = ref(false);
const selectedLedgerReceipt = ref(null);

const isValidTab = (tab) => {
    return walletTabs.some((item) => item.key === tab);
};

const getTabFromUrl = () => {
    if (typeof window === 'undefined') {
        return null;
    }

    const tab = String(new URLSearchParams(window.location.search).get('tab') || '').trim().toLowerCase();

    return isValidTab(tab) ? tab : null;
};

const getTabFromStorage = () => {
    if (typeof window === 'undefined') {
        return null;
    }

    const tab = String(window.localStorage.getItem(TAB_STORAGE_KEY) || '').trim().toLowerCase();

    return isValidTab(tab) ? tab : null;
};

onMounted(() => {
    const tabFromUrl = getTabFromUrl();
    if (tabFromUrl) {
        activeTab.value = tabFromUrl;
        return;
    }

    const tabFromStorage = getTabFromStorage();
    if (tabFromStorage) {
        activeTab.value = tabFromStorage;
    }
});

watch(activeTab, (tab) => {
    if (typeof window === 'undefined' || !isValidTab(tab)) {
        return;
    }

    window.localStorage.setItem(TAB_STORAGE_KEY, tab);
});

watch(
    () => transferForm.recipient,
    (value) => {
        const normalized = String(value || '').trim();
        if (normalized !== verifiedRecipientInput.value) {
            beneficiaryLookupState.value = {
                status: 'idle',
                message: '',
                beneficiary: null,
            };
        }
    }
);

const lookupBeneficiary = async () => {
    const recipient = String(transferForm.recipient || '').trim();
    transferForm.clearErrors('recipient');

    if (recipient === '') {
        transferForm.setError('recipient', 'Enter beneficiary email, referral code, or user ID.');
        return;
    }

    beneficiaryLookupState.value = {
        status: 'loading',
        message: '',
        beneficiary: null,
    };

    try {
        const response = await fetch(route('app.wallet.beneficiary.lookup', { recipient }), {
            headers: {
                Accept: 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
            },
        });
        const payload = await response.json();

        if (!response.ok || !payload?.found) {
            const message = payload?.message || 'Beneficiary not found. Enter a valid registered email, referral code, or user ID.';
            beneficiaryLookupState.value = {
                status: 'error',
                message,
                beneficiary: null,
            };
            transferForm.setError('recipient', message);
            verifiedRecipientInput.value = '';
            return;
        }

        beneficiaryLookupState.value = {
            status: 'verified',
            message: payload.message || 'Beneficiary verified.',
            beneficiary: payload.beneficiary || null,
        };
        verifiedRecipientInput.value = recipient;
    } catch (error) {
        const message = 'Unable to verify beneficiary right now. Please try again.';
        beneficiaryLookupState.value = {
            status: 'error',
            message,
            beneficiary: null,
        };
        transferForm.setError('recipient', message);
        verifiedRecipientInput.value = '';
    }
};

const submitTransfer = () => {
    const recipient = String(transferForm.recipient || '').trim();
    if (recipient === '' || verifiedRecipientInput.value !== recipient) {
        transferForm.setError('recipient', 'Verify beneficiary before completing transfer.');
        return;
    }

    transferForm.post(route('app.wallet.transfer'), {
        preserveScroll: true,
        onSuccess: () => {
            transferForm.reset('recipient', 'amount', 'narration', 'transaction_pin');
            transferForm.clearErrors('recipient');
            verifiedRecipientInput.value = '';
            beneficiaryLookupState.value = {
                status: 'idle',
                message: '',
                beneficiary: null,
            };
        },
    });
};

const hasAnyFundingMethod = computed(() => {
    return [
        fundingMethodByKey.value.monnifyInstant,
        fundingMethodByKey.value.paystack,
    ].some((method) => method?.available);
});

const startFunding = (provider) => {
    if (provider === 'paystack' && !fundingMethodByKey.value.paystack?.available) return;
    if (provider !== 'paystack' && !fundingMethodByKey.value.monnifyInstant?.available) return;

    const routeName = provider === 'paystack'
        ? 'app.wallet.funding.paystack'
        : 'app.wallet.funding.monnify-instant';

    fundingProviderInProgress.value = provider;

    fundingForm.post(route(routeName), {
        preserveScroll: true,
        onSuccess: () => {
            fundingForm.reset('amount');
        },
        onFinish: () => {
            fundingProviderInProgress.value = '';
        },
    });
};

const fundingProviderLabel = (provider) => {
    const key = String(provider || '').toLowerCase();
    if (key === 'paystack') return 'Paystack';
    if (key === 'monnify_instant') return 'Monnify Instant';

    return key || 'Unknown';
};

const fundingAttemptDate = (attempt) => {
    return attempt?.paid_at || attempt?.created_at || '';
};

const openLedgerReceipt = (entry) => {
    const receipt = entry?.transaction_receipt || null;
    if (!receipt) return;

    selectedLedgerReceipt.value = receipt;
    showLedgerReceiptModal.value = true;
};

const closeLedgerReceiptModal = () => {
    showLedgerReceiptModal.value = false;
};

const cashbackExpirySummary = computed(() => {
    if (!props.cashbackPolicy?.enabled) {
        return 'Cashback expiry is currently off.';
    }

    const days = Number(props.cashbackPolicy?.expiry_days || 0);
    const expiresAt = String(props.cashbackPolicy?.expires_at || '').trim();
    if (expiresAt) {
        return `Cashback expires after ${days} day(s) of inactivity. Next expiry: ${expiresAt}.`;
    }

    return `Cashback expires after ${days} day(s) of inactivity.`;
});
</script>

<template>
    <Head title="Wallet" />

    <MobileAppLayout title="Wallet">
        <div class="space-y-4">
            <section class="user-balance-card user-balance-card--wallet rounded-3xl p-4 shadow-lg">
                <div class="text-xs uppercase tracking-[0.16em] user-balance-card__kicker">Service Credit</div>
                <div class="mt-2 text-2xl font-semibold">NGN {{ wallet?.balance || '0.00' }}</div>
                <div class="mt-1 text-xs user-balance-card__muted">
                    {{ appName }} service credit for purchases (ledger-backed).
                </div>
            </section>

            <section class="rounded-2xl border border-slate-200 bg-white p-1.5 shadow-sm">
                <div class="grid grid-cols-4 gap-1">
                    <button
                        v-for="tab in walletTabs"
                        :key="tab.key"
                        type="button"
                        class="rounded-xl px-2 py-2 text-[11px] font-semibold transition"
                        :class="activeTab === tab.key ? 'bg-slate-900 text-white shadow-sm' : 'text-slate-600 hover:bg-slate-100'"
                        @click="activeTab = tab.key"
                    >
                        {{ tab.label }}
                    </button>
                </div>
            </section>

            <div v-if="activeTab === 'funding'" class="space-y-4">
                <AppCard
                    v-if="fundingMethodByKey.monnifyReserved?.available || fundingMethodByKey.paymentpointReserved?.available"
                    title="Reserved Accounts"
                    subtitle="Use these funding accounts to fund your wallet."
                >
                    <FundingAccountsList :reserved-accounts="reservedAccounts" />
                </AppCard>

                <AppCard
                    title="Instant Funding Checkout"
                    subtitle="Choose a payment method and complete payment securely."
                >
                    <div class="space-y-3">
                        <div v-if="!hasAnyFundingMethod" class="rounded-2xl border border-rose-200 bg-rose-50 p-3 text-xs text-rose-900">
                            No instant funding method is available right now.
                        </div>

                        <div v-if="hasAnyFundingMethod" class="rounded-2xl border border-slate-200 bg-slate-50 p-3 text-xs text-slate-700">
                            Enter amount between NGN {{ fundingLimits?.min_amount ?? 0 }} and NGN {{ fundingLimits?.max_amount ?? 0 }}.
                        </div>

                        <div>
                            <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-700">Funding Amount (NGN)</label>
                            <input
                                v-model="fundingForm.amount"
                                type="number"
                                :min="fundingLimits?.min_amount ?? 1"
                                :max="fundingLimits?.max_amount ?? undefined"
                                step="0.01"
                                placeholder="1000"
                                class="w-full rounded-xl border-slate-300 text-sm shadow-sm focus:border-slate-500 focus:ring-slate-400"
                                :disabled="fundingForm.processing || !hasAnyFundingMethod"
                            />
                            <p v-if="fundingForm.errors.amount" class="mt-1 text-xs text-rose-600">{{ fundingForm.errors.amount }}</p>
                        </div>

                        <div class="grid grid-cols-1 gap-2 sm:grid-cols-2">
                            <button
                                type="button"
                                class="inline-flex w-full items-center justify-center rounded-xl border px-4 py-3 text-sm font-semibold transition disabled:cursor-not-allowed disabled:opacity-50"
                                :class="fundingMethodByKey.paystack?.available ? 'border-slate-900 bg-slate-900 text-white hover:bg-slate-800' : 'border-slate-300 bg-slate-100 text-slate-500'"
                                :disabled="fundingForm.processing || !fundingMethodByKey.paystack?.available"
                                @click="startFunding('paystack')"
                            >
                                {{ fundingProviderInProgress === 'paystack' ? 'Opening Paystack...' : 'Fund with Paystack' }}
                            </button>

                            <button
                                type="button"
                                class="inline-flex w-full items-center justify-center rounded-xl border px-4 py-3 text-sm font-semibold transition disabled:cursor-not-allowed disabled:opacity-50"
                                :class="fundingMethodByKey.monnifyInstant?.available ? 'border-slate-900 bg-slate-900 text-white hover:bg-slate-800' : 'border-slate-300 bg-slate-100 text-slate-500'"
                                :disabled="fundingForm.processing || !fundingMethodByKey.monnifyInstant?.available"
                                @click="startFunding('monnify')"
                            >
                                {{ fundingProviderInProgress === 'monnify' ? 'Opening Monnify...' : 'Fund with Monnify' }}
                            </button>
                        </div>

                        <div class="space-y-1 text-[11px] text-slate-500">
                            <div v-if="fundingMethodByKey.paystack?.reason">Paystack: {{ fundingMethodByKey.paystack.reason }}</div>
                            <div v-if="fundingMethodByKey.monnifyInstant?.reason">Monnify Instant: {{ fundingMethodByKey.monnifyInstant.reason }}</div>
                            <div v-if="fundingMethodByKey.monnifyReserved?.reason">
                                Monnify Reserved Account: {{ fundingMethodByKey.monnifyReserved.reason }}
                            </div>
                            <div v-if="fundingMethodByKey.paymentpointReserved?.reason">
                                PaymentPoint Reserved Account: {{ fundingMethodByKey.paymentpointReserved.reason }}
                            </div>
                        </div>
                    </div>
                </AppCard>

                <AppCard
                    title="Funding Attempts"
                    subtitle="Your latest checkout attempts and statuses."
                >
                    <div class="space-y-2">
                        <div
                            v-for="attempt in fundingAttempts"
                            :key="attempt.id"
                            class="rounded-2xl border border-slate-200 bg-white p-3"
                        >
                            <div class="flex items-start justify-between gap-3">
                                <div class="min-w-0">
                                    <div class="truncate text-sm font-semibold text-slate-900">
                                        {{ fundingProviderLabel(attempt.provider) }}
                                    </div>
                                    <div class="truncate text-[11px] text-slate-500">{{ attempt.reference }}</div>
                                </div>
                                <StatusBadge :status="attempt.status" />
                            </div>
                            <div class="mt-2 grid grid-cols-2 gap-2 text-xs">
                                <div class="rounded-xl bg-slate-50 px-2 py-1.5">
                                    <div class="text-slate-500">Amount</div>
                                    <div class="font-semibold text-slate-900">
                                        {{ attempt.currency || 'NGN' }} {{ attempt.amount }}
                                    </div>
                                </div>
                                <div class="rounded-xl bg-slate-50 px-2 py-1.5">
                                    <div class="text-slate-500">Time</div>
                                    <div class="truncate font-medium text-slate-700">{{ fundingAttemptDate(attempt) }}</div>
                                </div>
                            </div>
                        </div>
                        <div
                            v-if="!fundingAttempts.length"
                            class="rounded-2xl border border-dashed border-slate-300 p-3 text-xs text-slate-500"
                        >
                            No funding attempts yet.
                        </div>
                    </div>
                </AppCard>
            </div>

            <AppCard
                v-if="activeTab === 'transfer'"
                title="Wallet Transfer"
                subtitle="Send wallet balance to another registered user (email, referral code, or user ID)."
            >
                <div class="space-y-3">
                    <div class="rounded-2xl border p-3 text-xs"
                         :class="walletTransferSettings?.enabled ? 'border-emerald-200 bg-emerald-50 text-emerald-900' : 'border-rose-200 bg-rose-50 text-rose-900'">
                        <div class="font-semibold">
                            Wallet transfer is {{ walletTransferSettings?.enabled ? 'On' : 'Off' }}
                        </div>
                        <div class="mt-1">
                            Limit: NGN {{ walletTransferSettings?.min_amount ?? 0 }} - NGN {{ walletTransferSettings?.max_amount ?? 0 }}
                        </div>
                        <div class="mt-1">
                            Daily: {{ walletTransferUsage?.remaining_count ?? 0 }}/{{ walletTransferUsage?.daily_count_limit ?? 0 }} transfers left • NGN {{ walletTransferUsage?.remaining_amount ?? 0 }} remaining
                        </div>
                    </div>

                    <div v-if="!hasTransactionPin" class="rounded-2xl border border-amber-200 bg-amber-50 p-3 text-xs text-amber-900">
                        Set your transaction PIN first before transferring.
                        <div class="mt-2">
                            <Link :href="route('profile.edit')" class="inline-flex rounded-md border border-amber-300 bg-white px-3 py-1.5 text-xs font-medium text-amber-800">
                                Go to Profile
                            </Link>
                        </div>
                    </div>

                    <form v-else class="space-y-3" @submit.prevent="submitTransfer">
                        <div>
                            <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-700">Recipient</label>
                            <div class="flex items-center gap-2">
                                <input
                                    v-model="transferForm.recipient"
                                    type="text"
                                    placeholder="Email, referral code, or user ID"
                                    class="wallet-transfer-input w-full rounded-xl border-slate-300 text-sm shadow-sm focus:border-slate-500 focus:ring-slate-400"
                                    :disabled="!walletTransferSettings?.enabled || transferForm.processing || beneficiaryLookupState.status === 'loading'"
                                />
                                <button
                                    type="button"
                                    class="inline-flex shrink-0 items-center justify-center rounded-xl border border-slate-300 bg-white px-3 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-50"
                                    :disabled="!walletTransferSettings?.enabled || transferForm.processing || beneficiaryLookupState.status === 'loading'"
                                    @click="lookupBeneficiary"
                                >
                                    {{ beneficiaryLookupState.status === 'loading' ? 'Checking...' : 'Verify' }}
                                </button>
                            </div>
                            <p v-if="transferForm.errors.recipient" class="mt-1 text-xs text-rose-600">{{ transferForm.errors.recipient }}</p>

                            <div
                                v-if="beneficiaryLookupState.status === 'verified' && beneficiaryLookupState.beneficiary"
                                class="mt-2 rounded-xl border border-emerald-200 bg-emerald-50 p-2 text-xs text-emerald-900"
                            >
                                <div class="font-semibold">Beneficiary Verified</div>
                                <div class="mt-1">Name: {{ beneficiaryLookupState.beneficiary.name }}</div>
                                <div class="mt-0.5">Email: {{ beneficiaryLookupState.beneficiary.email }}</div>
                            </div>

                            <div
                                v-if="beneficiaryLookupState.status === 'error' && beneficiaryLookupState.message"
                                class="mt-2 rounded-xl border border-rose-200 bg-rose-50 p-2 text-xs text-rose-900"
                            >
                                {{ beneficiaryLookupState.message }}
                            </div>
                        </div>

                        <div>
                            <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-700">Amount (NGN)</label>
                            <input
                                v-model="transferForm.amount"
                                type="number"
                                :min="walletTransferSettings?.min_amount ?? 1"
                                :max="walletTransferSettings?.max_amount ?? undefined"
                                step="0.01"
                                placeholder="1000"
                                class="wallet-transfer-input w-full rounded-xl border-slate-300 text-sm shadow-sm focus:border-slate-500 focus:ring-slate-400"
                                :disabled="!walletTransferSettings?.enabled || transferForm.processing"
                            />
                            <p v-if="transferForm.errors.amount" class="mt-1 text-xs text-rose-600">{{ transferForm.errors.amount }}</p>
                        </div>

                        <div>
                            <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-700">Narration (Optional)</label>
                            <input
                                v-model="transferForm.narration"
                                type="text"
                                maxlength="255"
                                placeholder="Narration"
                                class="wallet-transfer-input w-full rounded-xl border-slate-300 text-sm shadow-sm focus:border-slate-500 focus:ring-slate-400"
                                :disabled="!walletTransferSettings?.enabled || transferForm.processing"
                            />
                            <p v-if="transferForm.errors.narration" class="mt-1 text-xs text-rose-600">{{ transferForm.errors.narration }}</p>
                        </div>

                        <div>
                            <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-700">Transaction PIN</label>
                            <input
                                v-model="transferForm.transaction_pin"
                                type="password"
                                inputmode="numeric"
                                maxlength="4"
                                placeholder="4-digit PIN"
                                class="wallet-transfer-input w-full rounded-xl border-slate-300 text-sm shadow-sm focus:border-slate-500 focus:ring-slate-400"
                                :disabled="!walletTransferSettings?.enabled || transferForm.processing"
                            />
                            <p v-if="transferForm.errors.transaction_pin" class="mt-1 text-xs text-rose-600">{{ transferForm.errors.transaction_pin }}</p>
                        </div>

                        <button
                            type="submit"
                            class="inline-flex w-full items-center justify-center rounded-xl bg-slate-900 px-4 py-3 text-sm font-semibold text-white transition hover:bg-slate-800 disabled:cursor-not-allowed disabled:opacity-50"
                            :disabled="!walletTransferSettings?.enabled || transferForm.processing"
                        >
                            {{ transferForm.processing ? 'Transferring...' : 'Transfer Wallet Balance' }}
                        </button>

                        <p class="text-[11px] text-slate-500">
                            Transfer only proceeds after beneficiary verification.
                        </p>
                    </form>
                </div>
            </AppCard>

            <AppCard
                v-if="activeTab === 'rewards'"
                title="Referral Bonus"
                subtitle="Referral rewards are credited to your wallet and recorded in ledger history."
            >
                <div class="space-y-3">
                    <div class="grid grid-cols-2 gap-2">
                        <div class="rounded-2xl border border-slate-200 bg-slate-50 p-3">
                            <div class="text-[11px] uppercase tracking-wide text-slate-600">Total Bonus</div>
                            <div class="mt-1 text-sm font-semibold text-slate-900">NGN {{ referralBonus?.total || '0.00' }}</div>
                        </div>
                        <div class="rounded-2xl border border-slate-200 bg-slate-50 p-3">
                            <div class="text-[11px] uppercase tracking-wide text-slate-600">Rewarded Referrals</div>
                            <div class="mt-1 text-sm font-semibold text-slate-900">{{ referralBonus?.count || 0 }}</div>
                        </div>
                    </div>

                    <div class="space-y-2">
                        <div
                            v-for="bonus in (referralBonus?.recent || [])"
                            :key="bonus.id"
                            class="rounded-2xl border border-slate-200 bg-white p-3"
                        >
                            <div class="flex items-start justify-between gap-3">
                                <div class="min-w-0">
                                    <div class="truncate text-sm font-semibold text-slate-900">{{ bonus.narration }}</div>
                                    <div class="truncate text-[11px] text-slate-500">{{ bonus.reference }}</div>
                                </div>
                                <div class="text-sm font-semibold text-slate-900">+NGN {{ bonus.amount }}</div>
                            </div>
                            <div class="mt-2 text-xs text-slate-500">{{ bonus.created_at }}</div>
                        </div>
                        <div v-if="!(referralBonus?.recent || []).length" class="rounded-2xl border border-dashed border-slate-300 p-3 text-xs text-slate-500">
                            No referral bonus credit yet.
                        </div>
                    </div>
                </div>
            </AppCard>

            <AppCard
                v-if="activeTab === 'rewards'"
                title="Cashback Rewards"
                subtitle="Successful purchases can earn instant cashback when cashback is enabled by admin."
            >
                <div class="space-y-3">
                    <div class="cashback-expiry-banner rounded-2xl border border-indigo-200 bg-indigo-50 p-3 text-xs text-indigo-900">
                        {{ cashbackExpirySummary }}
                    </div>
                    <div class="rounded-2xl border border-slate-200 bg-slate-50 p-3">
                        <div class="text-[11px] uppercase tracking-wide text-slate-600">Cashback Balance</div>
                        <div class="mt-1 text-sm font-semibold text-slate-900">NGN {{ cashbackWallet?.balance || '0.00' }}</div>
                    </div>

                    <div class="grid grid-cols-2 gap-2">
                        <div class="rounded-2xl border border-slate-200 bg-slate-50 p-3">
                            <div class="text-[11px] uppercase tracking-wide text-slate-600">Total Cashback</div>
                            <div class="mt-1 text-sm font-semibold text-slate-900">NGN {{ cashbackBonus?.total || '0.00' }}</div>
                        </div>
                        <div class="rounded-2xl border border-slate-200 bg-slate-50 p-3">
                            <div class="text-[11px] uppercase tracking-wide text-slate-600">Cashback Credits</div>
                            <div class="mt-1 text-sm font-semibold text-slate-900">{{ cashbackBonus?.count || 0 }}</div>
                        </div>
                    </div>

                    <div class="space-y-2">
                        <div
                            v-for="entry in cashbackLedger"
                            :key="`cashback-ledger-${entry.id}`"
                            class="rounded-2xl border border-slate-200 bg-white p-3"
                        >
                            <div class="flex items-start justify-between gap-3">
                                <div class="min-w-0">
                                    <div class="truncate text-sm font-semibold text-slate-900">{{ entry.narration }}</div>
                                    <div class="truncate text-[11px] text-slate-500">{{ entry.reference }}</div>
                                </div>
                                <StatusBadge :status="entry.entry_type" />
                            </div>
                            <div class="mt-2 grid grid-cols-2 gap-2 text-xs">
                                <div class="rounded-xl bg-slate-50 px-2 py-1.5">
                                    <div class="text-slate-500">Amount</div>
                                    <div class="font-semibold text-slate-900">NGN {{ entry.amount }}</div>
                                </div>
                                <div class="rounded-xl bg-slate-50 px-2 py-1.5">
                                    <div class="text-slate-500">Balance After</div>
                                    <div class="font-semibold text-slate-900">{{ entry.balance_after }}</div>
                                </div>
                            </div>
                            <div class="mt-2 text-xs text-slate-500">{{ entry.created_at }}</div>
                        </div>

                        <div
                            v-for="reward in (cashbackBonus?.recent || [])"
                            :key="reward.id"
                            class="rounded-2xl border border-slate-200 bg-white p-3"
                        >
                            <div class="flex items-start justify-between gap-3">
                                <div class="min-w-0">
                                    <div class="truncate text-sm font-semibold text-slate-900">{{ reward.narration }}</div>
                                    <div class="truncate text-[11px] text-slate-500">{{ reward.reference }}</div>
                                </div>
                                <div class="text-sm font-semibold text-slate-900">+NGN {{ reward.amount }}</div>
                            </div>
                            <div class="mt-2 text-xs text-slate-500">{{ reward.created_at }}</div>
                        </div>
                        <div v-if="!cashbackLedger.length && !(cashbackBonus?.recent || []).length" class="rounded-2xl border border-dashed border-slate-300 p-3 text-xs text-slate-500">
                            No cashback activity yet.
                        </div>
                    </div>
                </div>
            </AppCard>

            <AppCard v-if="activeTab === 'ledger'" title="Ledger History">
                <div class="space-y-2">
                    <component
                        v-for="entry in ledger.data"
                        :is="entry.transaction_receipt ? 'button' : 'div'"
                        :key="entry.id"
                        class="w-full rounded-2xl border bg-white p-3 text-left"
                        :class="[
                            entry.source === 'cashback'
                                ? 'border-sky-200'
                                : (entry.meta_json?.kind === 'referral_reward' ? 'border-emerald-200' : 'border-slate-200'),
                            entry.transaction_receipt ? 'cursor-pointer transition hover:border-slate-300' : '',
                        ]"
                        v-bind="entry.transaction_receipt ? { type: 'button' } : {}"
                        @click="entry.transaction_receipt ? openLedgerReceipt(entry) : null"
                    >
                        <div class="flex items-start justify-between gap-3">
                            <div class="min-w-0">
                                <div class="truncate text-sm font-semibold text-slate-900">{{ entry.narration }}</div>
                                <div class="truncate text-[11px] text-slate-500">
                                    {{ entry.reference }}
                                    <span
                                        v-if="entry.meta_json?.kind === 'referral_reward'"
                                        class="ml-2 rounded-full border border-emerald-300 bg-emerald-50 px-1.5 py-0.5 text-[10px] font-semibold text-emerald-700"
                                    >
                                        Referral Bonus
                                    </span>
                                    <span
                                        v-if="entry.source === 'cashback'"
                                        class="ml-2 rounded-full border border-sky-300 bg-sky-50 px-1.5 py-0.5 text-[10px] font-semibold text-sky-700"
                                    >
                                        Cashback
                                    </span>
                                </div>
                            </div>
                            <StatusBadge :status="entry.entry_type" />
                        </div>
                        <div class="mt-2 grid grid-cols-2 gap-2 text-xs">
                            <div class="rounded-xl bg-slate-50 px-2 py-1.5">
                                <div class="text-slate-500">Source</div>
                                <div class="font-medium text-slate-700 capitalize">{{ entry.source }}</div>
                            </div>
                            <div class="rounded-xl bg-slate-50 px-2 py-1.5">
                                <div class="text-slate-500">Amount</div>
                                <div class="font-semibold text-slate-900">NGN {{ entry.amount }}</div>
                            </div>
                            <div class="rounded-xl bg-slate-50 px-2 py-1.5">
                                <div class="text-slate-500">Balance After</div>
                                <div class="font-medium text-slate-700">{{ entry.balance_after }}</div>
                            </div>
                            <div class="rounded-xl bg-slate-50 px-2 py-1.5">
                                <div class="text-slate-500">Date</div>
                                <div class="truncate font-medium text-slate-700">{{ entry.created_at }}</div>
                            </div>
                        </div>
                        <div v-if="entry.transaction_receipt" class="mt-2 text-[11px] font-semibold text-sky-600">
                            Tap to view receipt
                        </div>
                    </component>
                    <div v-if="ledger.data.length === 0" class="rounded-2xl border border-dashed border-slate-300 p-4 text-sm text-slate-500">
                        No ledger entries yet.
                    </div>
                </div>
            </AppCard>
        </div>

        <TransactionReceiptModal
            :show="showLedgerReceiptModal"
            :receipt="selectedLedgerReceipt"
            @close="closeLedgerReceiptModal"
        />
    </MobileAppLayout>
</template>
