<script setup>
import CoachLayout from '@/Layouts/CoachLayout.vue';
import { Head, Link, router } from '@inertiajs/vue3';
import { ref, computed } from 'vue';

const props = defineProps({
    plan: Object,
    purchases: Object,
});

// Selection state
const selectedPurchases = ref([]);
const selectAll = ref(false);

const toggleSelectAll = () => {
    if (selectAll.value) {
        selectedPurchases.value = props.purchases.data.map(p => p.id);
    } else {
        selectedPurchases.value = [];
    }
};

const isSelected = (purchaseId) => selectedPurchases.value.includes(purchaseId);

const toggleSelect = (purchaseId) => {
    const index = selectedPurchases.value.indexOf(purchaseId);
    if (index > -1) {
        selectedPurchases.value.splice(index, 1);
    } else {
        selectedPurchases.value.push(purchaseId);
    }
    selectAll.value = selectedPurchases.value.length === props.purchases.data.length;
};

const hasSelection = computed(() => selectedPurchases.value.length > 0);

// Bulk actions
const bulkConfirmPayments = () => {
    if (confirm(`¿Confirmar pago de ${selectedPurchases.value.length} compra(s)?`)) {
        router.post(route('coach.plans.purchases.bulk-confirm'), {
            purchase_ids: selectedPurchases.value,
        }, {
            onSuccess: () => {
                selectedPurchases.value = [];
                selectAll.value = false;
            }
        });
    }
};

const bulkCancel = () => {
    if (confirm(`¿Cancelar ${selectedPurchases.value.length} compra(s)? Esta acción no se puede deshacer.`)) {
        router.post(route('coach.plans.purchases.bulk-cancel'), {
            purchase_ids: selectedPurchases.value,
        }, {
            onSuccess: () => {
                selectedPurchases.value = [];
                selectAll.value = false;
            }
        });
    }
};

const bulkDelete = () => {
    if (confirm(`¿ELIMINAR ${selectedPurchases.value.length} compra(s)? Esta acción es PERMANENTE y no se puede deshacer.`)) {
        router.delete(route('coach.plans.purchases.bulk-delete'), {
            data: { purchase_ids: selectedPurchases.value },
            onSuccess: () => {
                selectedPurchases.value = [];
                selectAll.value = false;
            }
        });
    }
};

// Confirm payment modal
const showConfirmModal = ref(false);
const confirmingPurchase = ref(null);
const confirmPaymentRef = ref('');
const confirmingPayment = ref(false);

const openConfirmModal = (purchase) => {
    confirmingPurchase.value = purchase;
    confirmPaymentRef.value = '';
    showConfirmModal.value = true;
};

const closeConfirmModal = () => {
    showConfirmModal.value = false;
    confirmingPurchase.value = null;
    confirmPaymentRef.value = '';
    confirmingPayment.value = false;
};

const confirmPayment = () => {
    if (!confirmingPurchase.value) return;
    confirmingPayment.value = true;
    router.post(route('coach.plans.purchases.confirm', confirmingPurchase.value.id), {
        payment_reference: confirmPaymentRef.value,
    }, {
        preserveScroll: true,
        onSuccess: () => {
            closeConfirmModal();
        },
        onError: () => {
            confirmingPayment.value = false;
        },
    });
};

const cancelPurchase = (purchase) => {
    if (confirm('¿Cancelar esta solicitud de compra?')) {
        router.post(route('coach.plans.purchases.cancel', purchase.id));
    }
};

const suspendPurchase = (purchase) => {
    const reason = prompt('Motivo de la suspensión (opcional):');
    if (reason !== null) {
        router.post(route('coach.plans.purchases.suspend', purchase.id), {
            reason: reason,
        });
    }
};

const reactivatePurchase = (purchase) => {
    if (confirm('¿Reactivar el acceso de este cliente?')) {
        router.post(route('coach.plans.purchases.reactivate', purchase.id));
    }
};

const sendPaymentReminder = (purchase) => {
    if (confirm('¿Enviar recordatorio de pago al cliente?')) {
        router.post(route('coach.plans.purchases.send-reminder', purchase.id));
    }
};

// Copy link with toast
const linkCopied = ref(false);
const copyLink = () => {
    const url = route('public.coach-plan', props.plan.slug);
    navigator.clipboard.writeText(url);
    linkCopied.value = true;
    setTimeout(() => { linkCopied.value = false; }, 2500);
};

// Edit purchase modal
const showEditModal = ref(false);
const editingPurchase = ref(null);
const editForm = ref({
    buyer_name: '',
    buyer_email: '',
    buyer_phone: '',
    amount: 0,
    status: '',
    notes: '',
    payment_reference: '',
});
const savingEdit = ref(false);

const openEditModal = (purchase) => {
    editingPurchase.value = purchase;
    editForm.value = {
        buyer_name: purchase.buyer_name || purchase.client?.name || '',
        buyer_email: purchase.buyer_email || purchase.client?.email || '',
        buyer_phone: purchase.buyer_phone || '',
        amount: purchase.amount,
        status: purchase.status,
        notes: purchase.notes || '',
        payment_reference: purchase.payment_reference || '',
    };
    showEditModal.value = true;
};

const closeEditModal = () => {
    showEditModal.value = false;
    editingPurchase.value = null;
};

const saveEdit = () => {
    if (!editingPurchase.value) return;
    savingEdit.value = true;
    router.put(route('coach.plans.purchases.update', editingPurchase.value.id), editForm.value, {
        preserveScroll: true,
        onSuccess: () => {
            closeEditModal();
            savingEdit.value = false;
        },
        onError: () => {
            savingEdit.value = false;
        },
    });
};

// Refund
const refundPurchase = (purchase) => {
    if (confirm('¿Marcar esta compra como reembolsada? Se revocará el acceso del cliente.')) {
        router.post(route('coach.plans.purchases.refund', purchase.id));
    }
};

// Individual delete
const deletePurchase = (purchase) => {
    if (confirm('¿ELIMINAR esta compra? Esta acción es PERMANENTE y no se puede deshacer.')) {
        router.delete(route('coach.plans.purchases.delete', purchase.id));
    }
};

// Receipt viewer modal
const showReceiptModal = ref(false);
const currentReceipt = ref(null);

const viewReceipt = (receipt) => {
    currentReceipt.value = receipt;
    showReceiptModal.value = true;
};

const closeReceiptModal = () => {
    showReceiptModal.value = false;
    currentReceipt.value = null;
};

const statusColors = {
    pending: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400',
    paid: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
    cancelled: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-400',
    refunded: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
    expired: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
    suspended: 'bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-400',
};

const statusLabels = {
    pending: 'Pendiente',
    paid: 'Pagado',
    cancelled: 'Cancelado',
    refunded: 'Reembolsado',
    expired: 'Expirado',
    suspended: 'Suspendido',
};

const editableStatuses = [
    { value: 'pending', label: 'Pendiente' },
    { value: 'paid', label: 'Pagado' },
    { value: 'suspended', label: 'Suspendido' },
    { value: 'cancelled', label: 'Cancelado' },
    { value: 'refunded', label: 'Reembolsado' },
];

const isManualPayment = (purchase) => {
    return ['bank_dominican', 'bank_international', 'western_union'].includes(purchase.payment_method);
};
</script>

<template>
    <Head :title="plan.name" />

    <CoachLayout>
        <template #header>
            <div class="flex items-center gap-4">
                <Link
                    :href="route('coach.plans.index')"
                    class="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
                >
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
                    </svg>
                </Link>
                <div class="flex-1">
                    <h2 class="text-xl font-semibold leading-tight text-gray-800 dark:text-white">
                        {{ plan.name }}
                    </h2>
                    <p class="text-sm text-gray-500 dark:text-gray-400">
                        Detalles y compras del plan
                    </p>
                </div>
                <div class="flex gap-2">
                    <div class="relative">
                        <button
                            @click="copyLink"
                            class="inline-flex items-center px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 transition"
                        >
                            <svg v-if="!linkCopied" class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
                            </svg>
                            <svg v-else class="w-4 h-4 mr-2 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                            </svg>
                            {{ linkCopied ? '¡Copiado!' : 'Copiar enlace' }}
                        </button>
                        <transition
                            enter-active-class="transition ease-out duration-200"
                            enter-from-class="opacity-0 translate-y-1"
                            enter-to-class="opacity-100 translate-y-0"
                            leave-active-class="transition ease-in duration-150"
                            leave-from-class="opacity-100 translate-y-0"
                            leave-to-class="opacity-0 translate-y-1"
                        >
                            <div v-if="linkCopied" class="absolute top-full left-1/2 -translate-x-1/2 mt-2 px-3 py-1.5 bg-gray-900 dark:bg-gray-600 text-white text-xs rounded-lg shadow-lg whitespace-nowrap z-10">
                                Enlace copiado al portapapeles
                            </div>
                        </transition>
                    </div>
                    <Link
                        :href="route('coach.plans.edit', plan.id)"
                        class="inline-flex items-center px-3 py-2 bg-indigo-600 hover:bg-indigo-700 text-white font-medium rounded-md transition"
                    >
                        <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                        </svg>
                        Editar
                    </Link>
                </div>
            </div>
        </template>

        <div class="py-6">
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <!-- Plan Details -->
                <div class="lg:col-span-1">
                    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
                        <div class="h-40 bg-gradient-to-r from-indigo-500 to-purple-600 flex items-center justify-center">
                            <img
                                v-if="plan.image"
                                :src="`/storage/${plan.image}`"
                                class="w-full h-full object-cover"
                                :alt="plan.name"
                            >
                            <span v-else class="text-6xl">💪</span>
                        </div>
                        <div class="p-5">
                            <div class="flex items-center justify-between mb-4">
                                <span
                                    :class="[
                                        'px-3 py-1 text-sm font-medium rounded-full',
                                        plan.is_active
                                            ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
                                            : 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-400'
                                    ]"
                                >
                                    {{ plan.is_active ? '✓ Activo' : '✗ Inactivo' }}
                                </span>
                                <span
                                    :class="[
                                        'px-3 py-1 text-sm font-medium rounded-full',
                                        plan.is_public
                                            ? 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400'
                                            : 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-400'
                                    ]"
                                >
                                    {{ plan.is_public ? '🌐 Público' : '🔒 Privado' }}
                                </span>
                            </div>

                            <p class="text-gray-600 dark:text-gray-400 mb-4">
                                {{ plan.description || 'Sin descripción' }}
                            </p>

                            <div class="space-y-3 text-sm">
                                <div class="flex justify-between">
                                    <span class="text-gray-500 dark:text-gray-400">Precio:</span>
                                    <span class="font-semibold text-gray-900 dark:text-white">${{ Number(plan.price).toFixed(2) }}</span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-500 dark:text-gray-400">Duración:</span>
                                    <span class="font-semibold text-gray-900 dark:text-white">{{ plan.duration_days }} días</span>
                                </div>
                                <div class="flex justify-between" v-if="plan.max_clients">
                                    <span class="text-gray-500 dark:text-gray-400">Límite:</span>
                                    <span class="font-semibold text-gray-900 dark:text-white">{{ plan.current_clients }}/{{ plan.max_clients }}</span>
                                </div>
                            </div>

                            <div v-if="plan.features?.length" class="mt-4 pt-4 border-t border-gray-200 dark:border-gray-700">
                                <h4 class="text-sm font-medium text-gray-900 dark:text-white mb-2">Características:</h4>
                                <ul class="space-y-1">
                                    <li v-for="feature in plan.features" :key="feature" class="flex items-center text-sm text-gray-600 dark:text-gray-400">
                                        <svg class="w-4 h-4 text-green-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                                        </svg>
                                        {{ feature }}
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Purchases List -->
                <div class="lg:col-span-2">
                    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
                        <div class="px-5 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
                            <h3 class="text-lg font-medium text-gray-900 dark:text-white">
                                Compras ({{ purchases.total }})
                            </h3>
                            <!-- Bulk Actions Bar -->
                            <div v-if="hasSelection" class="flex items-center gap-2">
                                <span class="text-sm text-gray-500 dark:text-gray-400">
                                    {{ selectedPurchases.length }} seleccionados
                                </span>
                                <button
                                    @click="bulkConfirmPayments"
                                    class="px-3 py-1.5 text-xs font-medium rounded-md bg-green-100 text-green-700 hover:bg-green-200 dark:bg-green-900/30 dark:text-green-400 dark:hover:bg-green-900/50"
                                    title="Confirmar pagos seleccionados"
                                >
                                    Confirmar
                                </button>
                                <button
                                    @click="bulkCancel"
                                    class="px-3 py-1.5 text-xs font-medium rounded-md bg-orange-100 text-orange-700 hover:bg-orange-200 dark:bg-orange-900/30 dark:text-orange-400 dark:hover:bg-orange-900/50"
                                    title="Cancelar seleccionados"
                                >
                                    Cancelar
                                </button>
                                <button
                                    @click="bulkDelete"
                                    class="px-3 py-1.5 text-xs font-medium rounded-md bg-red-100 text-red-700 hover:bg-red-200 dark:bg-red-900/30 dark:text-red-400 dark:hover:bg-red-900/50"
                                    title="Eliminar seleccionados"
                                >
                                    Eliminar
                                </button>
                            </div>
                        </div>

                        <div v-if="purchases.data.length">
                            <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                                <thead class="bg-gray-50 dark:bg-gray-700/50">
                                    <tr>
                                        <th class="px-3 py-3 w-10">
                                            <input
                                                type="checkbox"
                                                v-model="selectAll"
                                                @change="toggleSelectAll"
                                                class="w-4 h-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500 dark:border-gray-600 dark:bg-gray-700"
                                            />
                                        </th>
                                        <th class="px-5 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                                            Cliente
                                        </th>
                                        <th class="px-5 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                                            Estado
                                        </th>
                                        <th class="px-5 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                                            Monto
                                        </th>
                                        <th class="px-5 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                                            Fecha
                                        </th>
                                        <th class="px-5 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                                            Comprobante
                                        </th>
                                        <th class="px-5 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                                            Acciones
                                        </th>
                                    </tr>
                                </thead>
                                <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                                    <tr v-for="purchase in purchases.data" :key="purchase.id" :class="{ 'bg-indigo-50 dark:bg-indigo-900/20': isSelected(purchase.id) }">
                                        <td class="px-3 py-4 w-10">
                                            <input
                                                type="checkbox"
                                                :checked="isSelected(purchase.id)"
                                                @change="toggleSelect(purchase.id)"
                                                class="w-4 h-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500 dark:border-gray-600 dark:bg-gray-700"
                                            />
                                        </td>
                                        <td class="px-5 py-4 whitespace-nowrap">
                                            <div class="text-sm font-medium text-gray-900 dark:text-white">
                                                {{ purchase.client?.name || purchase.buyer_name || 'Sin nombre' }}
                                            </div>
                                            <div class="text-sm text-gray-500 dark:text-gray-400">
                                                {{ purchase.client?.email || purchase.buyer_email || '' }}
                                            </div>
                                        </td>
                                        <td class="px-5 py-4 whitespace-nowrap">
                                            <span :class="['px-2 py-1 text-xs font-medium rounded-full', statusColors[purchase.status]]">
                                                {{ statusLabels[purchase.status] }}
                                            </span>
                                        </td>
                                        <td class="px-5 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-white">
                                            ${{ Number(purchase.amount).toFixed(2) }}
                                        </td>
                                        <td class="px-5 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
                                            {{ new Date(purchase.created_at).toLocaleDateString() }}
                                        </td>
                                        <td class="px-5 py-4 whitespace-nowrap text-sm">
                                            <button
                                                v-if="purchase.receipts && purchase.receipts.length > 0"
                                                @click="viewReceipt(purchase.receipts[0])"
                                                class="inline-flex items-center gap-1.5 px-2.5 py-1.5 bg-blue-50 hover:bg-blue-100 dark:bg-blue-900/30 dark:hover:bg-blue-900/50 text-blue-600 dark:text-blue-400 rounded-lg transition text-xs font-medium"
                                                title="Ver comprobante"
                                            >
                                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                                </svg>
                                                Ver
                                            </button>
                                            <span v-else class="text-gray-400 dark:text-gray-500 text-xs">
                                                Sin comprobante
                                            </span>
                                        </td>
                                        <td class="px-5 py-4 whitespace-nowrap text-right text-sm font-medium">
                                            <div class="flex justify-end gap-1">
                                                <!-- Edit button (always shown) -->
                                                <button
                                                    @click="openEditModal(purchase)"
                                                    class="p-1.5 text-indigo-600 hover:bg-indigo-50 dark:text-indigo-400 dark:hover:bg-indigo-900/30 rounded-lg transition"
                                                    title="Editar compra"
                                                >
                                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                                    </svg>
                                                </button>

                                                <!-- Pending actions -->
                                                <template v-if="purchase.status === 'pending'">
                                                    <button
                                                        @click="openConfirmModal(purchase)"
                                                        class="p-1.5 text-green-600 hover:bg-green-50 dark:text-green-400 dark:hover:bg-green-900/30 rounded-lg transition"
                                                        title="Confirmar pago"
                                                    >
                                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                                                        </svg>
                                                    </button>
                                                    <button
                                                        @click="sendPaymentReminder(purchase)"
                                                        class="p-1.5 text-blue-600 hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-blue-900/30 rounded-lg transition"
                                                        title="Enviar recordatorio"
                                                    >
                                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                                                        </svg>
                                                    </button>
                                                    <button
                                                        @click="cancelPurchase(purchase)"
                                                        class="p-1.5 text-red-600 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-900/30 rounded-lg transition"
                                                        title="Cancelar"
                                                    >
                                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                                                        </svg>
                                                    </button>
                                                </template>

                                                <!-- Paid actions -->
                                                <template v-else-if="purchase.status === 'paid'">
                                                    <button
                                                        @click="suspendPurchase(purchase)"
                                                        class="p-1.5 text-orange-600 hover:bg-orange-50 dark:text-orange-400 dark:hover:bg-orange-900/30 rounded-lg transition"
                                                        title="Suspender acceso"
                                                    >
                                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 9v6m4-6v6m7-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                                                        </svg>
                                                    </button>
                                                    <button
                                                        @click="refundPurchase(purchase)"
                                                        class="p-1.5 text-red-600 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-900/30 rounded-lg transition"
                                                        title="Reembolsar"
                                                    >
                                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6" />
                                                        </svg>
                                                    </button>
                                                </template>

                                                <!-- Suspended actions -->
                                                <template v-else-if="purchase.status === 'suspended'">
                                                    <button
                                                        @click="reactivatePurchase(purchase)"
                                                        class="p-1.5 text-green-600 hover:bg-green-50 dark:text-green-400 dark:hover:bg-green-900/30 rounded-lg transition"
                                                        title="Reactivar acceso"
                                                    >
                                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
                                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                                        </svg>
                                                    </button>
                                                </template>

                                                <!-- Delete button (always shown) -->
                                                <button
                                                    @click="deletePurchase(purchase)"
                                                    class="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 dark:hover:text-red-400 dark:hover:bg-red-900/30 rounded-lg transition"
                                                    title="Eliminar compra"
                                                >
                                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                                    </svg>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>

                            <!-- Pagination -->
                            <div v-if="purchases.last_page > 1" class="px-5 py-4 border-t border-gray-200 dark:border-gray-700 flex justify-center">
                                <nav class="flex gap-1">
                                    <Link
                                        v-for="link in purchases.links"
                                        :key="link.label"
                                        :href="link.url"
                                        :class="[
                                            'px-3 py-1 rounded text-sm',
                                            link.active
                                                ? 'bg-indigo-600 text-white'
                                                : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600',
                                            !link.url && 'opacity-50 cursor-not-allowed'
                                        ]"
                                        v-html="link.label"
                                    />
                                </nav>
                            </div>
                        </div>

                        <div v-else class="p-8 text-center">
                            <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z" />
                            </svg>
                            <h3 class="mt-4 text-sm font-medium text-gray-900 dark:text-white">Sin compras aún</h3>
                            <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
                                Comparte el enlace del plan con tus clientes para empezar a recibir compras.
                            </p>
                            <button
                                @click="copyLink"
                                class="mt-4 inline-flex items-center px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white font-medium rounded-md transition"
                            >
                                <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
                                </svg>
                                Copiar enlace público
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Confirm Payment Modal -->
        <transition
            enter-active-class="transition ease-out duration-200"
            enter-from-class="opacity-0"
            enter-to-class="opacity-100"
            leave-active-class="transition ease-in duration-150"
            leave-from-class="opacity-100"
            leave-to-class="opacity-0"
        >
            <div v-if="showConfirmModal" class="fixed inset-0 z-50 overflow-y-auto">
                <div class="flex items-center justify-center min-h-screen px-4">
                    <div class="fixed inset-0 bg-black/50" @click="closeConfirmModal"></div>
                    <div class="relative bg-white dark:bg-gray-800 rounded-2xl shadow-xl max-w-md w-full p-6 z-10">
                        <div class="text-center mb-5">
                            <div class="w-14 h-14 mx-auto rounded-full bg-green-100 dark:bg-green-900/30 flex items-center justify-center mb-4">
                                <svg class="w-7 h-7 text-green-600 dark:text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                                </svg>
                            </div>
                            <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Confirmar pago</h3>
                            <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">
                                ¿Confirmar pago de <strong>{{ confirmingPurchase?.client?.name || confirmingPurchase?.buyer_name || 'Cliente' }}</strong> por <strong>${{ Number(confirmingPurchase?.amount || 0).toFixed(2) }}</strong>?
                            </p>
                        </div>

                        <div class="mb-5">
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Referencia de pago (opcional)</label>
                            <input v-model="confirmPaymentRef" type="text"
                                   class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white text-sm"
                                   placeholder="ID de transacción, número de confirmación...">
                        </div>

                        <div class="flex gap-3">
                            <button @click="closeConfirmModal"
                                    class="flex-1 px-4 py-2.5 text-sm text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition">
                                Cancelar
                            </button>
                            <button @click="confirmPayment" :disabled="confirmingPayment"
                                    class="flex-1 px-4 py-2.5 text-sm bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 transition flex items-center justify-center gap-2">
                                <svg v-if="confirmingPayment" class="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
                                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
                                </svg>
                                {{ confirmingPayment ? 'Confirmando...' : 'Confirmar pago' }}
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </transition>

        <!-- Edit Purchase Modal -->
        <transition
            enter-active-class="transition ease-out duration-200"
            enter-from-class="opacity-0"
            enter-to-class="opacity-100"
            leave-active-class="transition ease-in duration-150"
            leave-from-class="opacity-100"
            leave-to-class="opacity-0"
        >
            <div v-if="showEditModal" class="fixed inset-0 z-50 overflow-y-auto">
                <div class="flex items-center justify-center min-h-screen px-4">
                    <div class="fixed inset-0 bg-black/50" @click="closeEditModal"></div>
                    <div class="relative bg-white dark:bg-gray-800 rounded-2xl shadow-xl max-w-lg w-full p-6 z-10">
                        <div class="flex items-center justify-between mb-5">
                            <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Editar Compra</h3>
                            <button @click="closeEditModal" class="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded-lg">
                                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>
                        </div>

                        <div class="space-y-4">
                            <!-- Status -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Estado</label>
                                <select v-model="editForm.status" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white text-sm">
                                    <option v-for="s in editableStatuses" :key="s.value" :value="s.value">{{ s.label }}</option>
                                </select>
                            </div>

                            <!-- Buyer Name -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Nombre del comprador</label>
                                <input v-model="editForm.buyer_name" type="text" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white text-sm">
                            </div>

                            <!-- Buyer Email -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Email</label>
                                <input v-model="editForm.buyer_email" type="email" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white text-sm">
                            </div>

                            <!-- Buyer Phone -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Teléfono</label>
                                <input v-model="editForm.buyer_phone" type="text" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white text-sm">
                            </div>

                            <!-- Amount -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Monto</label>
                                <input v-model="editForm.amount" type="number" step="0.01" min="0" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white text-sm">
                            </div>

                            <!-- Payment Reference -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Referencia de pago</label>
                                <input v-model="editForm.payment_reference" type="text" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white text-sm" placeholder="ID de transacción, número de confirmación...">
                            </div>

                            <!-- Notes -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Notas</label>
                                <textarea v-model="editForm.notes" rows="2" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white text-sm" placeholder="Notas internas sobre esta compra..."></textarea>
                            </div>
                        </div>

                        <div class="flex justify-end gap-3 mt-6 pt-4 border-t border-gray-200 dark:border-gray-700">
                            <button @click="closeEditModal" class="px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition">
                                Cancelar
                            </button>
                            <button @click="saveEdit" :disabled="savingEdit" class="px-4 py-2 text-sm bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50 transition">
                                {{ savingEdit ? 'Guardando...' : 'Guardar cambios' }}
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </transition>

        <!-- Receipt Viewer Modal -->
        <transition
            enter-active-class="transition ease-out duration-200"
            enter-from-class="opacity-0"
            enter-to-class="opacity-100"
            leave-active-class="transition ease-in duration-150"
            leave-from-class="opacity-100"
            leave-to-class="opacity-0"
        >
            <div v-if="showReceiptModal" class="fixed inset-0 z-50 overflow-y-auto">
                <div class="flex items-center justify-center min-h-screen px-4 py-8">
                    <div class="fixed inset-0 bg-black/75" @click="closeReceiptModal"></div>
                    <div class="relative bg-white dark:bg-gray-800 rounded-2xl shadow-xl max-w-3xl w-full z-10 overflow-hidden">
                        <!-- Header -->
                        <div class="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                            <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Comprobante de Pago</h3>
                            <button @click="closeReceiptModal" class="p-1.5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition">
                                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>
                        </div>

                        <!-- Receipt Image -->
                        <div class="p-6">
                            <div v-if="currentReceipt" class="space-y-4">
                                <!-- Image Container -->
                                <div class="bg-gray-50 dark:bg-gray-900 rounded-xl overflow-hidden">
                                    <img :src="'/storage/' + currentReceipt.receipt_image"
                                         :alt="'Comprobante #' + currentReceipt.id"
                                         class="w-full h-auto max-h-[500px] object-contain mx-auto">
                                </div>

                                <!-- Receipt Details -->
                                <div class="grid grid-cols-2 gap-4 pt-4 border-t border-gray-200 dark:border-gray-700">
                                    <div v-if="currentReceipt.transfer_reference">
                                        <p class="text-xs text-gray-500 dark:text-gray-400 mb-1">Referencia</p>
                                        <p class="text-sm font-medium text-gray-900 dark:text-white">{{ currentReceipt.transfer_reference }}</p>
                                    </div>
                                    <div v-if="currentReceipt.type">
                                        <p class="text-xs text-gray-500 dark:text-gray-400 mb-1">Tipo</p>
                                        <p class="text-sm font-medium text-gray-900 dark:text-white capitalize">{{ currentReceipt.type }}</p>
                                    </div>
                                    <div v-if="currentReceipt.status">
                                        <p class="text-xs text-gray-500 dark:text-gray-400 mb-1">Estado</p>
                                        <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium"
                                              :class="{
                                                  'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400': currentReceipt.status === 'verified',
                                                  'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400': currentReceipt.status === 'pending',
                                                  'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400': currentReceipt.status === 'rejected'
                                              }">
                                            {{ currentReceipt.status === 'verified' ? 'Verificado' : currentReceipt.status === 'pending' ? 'Pendiente' : 'Rechazado' }}
                                        </span>
                                    </div>
                                    <div v-if="currentReceipt.created_at">
                                        <p class="text-xs text-gray-500 dark:text-gray-400 mb-1">Fecha de subida</p>
                                        <p class="text-sm font-medium text-gray-900 dark:text-white">{{ new Date(currentReceipt.created_at).toLocaleDateString('es-DO', { year: 'numeric', month: 'short', day: 'numeric' }) }}</p>
                                    </div>
                                </div>

                                <!-- Download Link -->
                                <div class="pt-4">
                                    <a :href="'/storage/' + currentReceipt.receipt_image"
                                       target="_blank"
                                       download
                                       class="inline-flex items-center gap-2 px-4 py-2 text-sm bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                                        </svg>
                                        Descargar comprobante
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </transition>
    </CoachLayout>
</template>
