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

const props = defineProps({
    plan: Object,
    currentPlan: Object,
    paymentMethods: Array,
    banks: Array,
    settings: Object,
    walletBalance: {
        type: Number,
        default: 0,
    },
});

const form = useForm({
    payment_method: props.paymentMethods?.[0]?.id || 'bank_transfer',
    selected_bank_id: null,
    receipt_file: null,
});

const processing = ref(false);
const calculationError = ref(null);
const receiptPreview = ref(null);
const fileInput = ref(null);

// Handle receipt file selection
const onReceiptSelected = (event) => {
    const file = event.target.files[0];
    if (file) {
        if (file.size > 5 * 1024 * 1024) {
            alert('El archivo no debe superar 5MB');
            event.target.value = '';
            return;
        }
        form.receipt_file = file;
        const reader = new FileReader();
        reader.onload = (e) => {
            receiptPreview.value = e.target.result;
        };
        reader.readAsDataURL(file);
    }
};

const removeReceipt = () => {
    form.receipt_file = null;
    receiptPreview.value = null;
    if (fileInput.value) fileInput.value.value = '';
};

// Check if wallet payment is available (sufficient balance)
const canPayWithWallet = computed(() => {
    return props.settings?.wallet_payment_enabled &&
           props.walletBalance >= planPrice.value;
});

// Insufficient wallet balance
const insufficientWalletBalance = computed(() => {
    return props.settings?.wallet_payment_enabled &&
           props.walletBalance > 0 &&
           props.walletBalance < planPrice.value;
});

const selectedMethod = computed(() => {
    if (form.payment_method === 'wallet') {
        return { id: 'wallet', name: 'Saldo de Billetera' };
    }
    return props.paymentMethods?.find(m => m.id === form.payment_method);
});

const submit = () => {
    if (isNaN(total.value) || total.value <= 0) {
        calculationError.value = 'Error en el cálculo del total. Por favor recarga la página.';
        return;
    }

    // Validate bank selection for bank_transfer
    if (form.payment_method === 'bank_transfer' && props.banks?.length > 0 && !form.selected_bank_id) {
        alert('Por favor selecciona el banco donde realizarás el pago.');
        return;
    }

    processing.value = true;
    form.post(route('coach.subscription.process', props.plan.slug), {
        forceFormData: true,
        onFinish: () => {
            processing.value = false;
        },
        onError: (errors) => {
            processing.value = false;
            if (errors.payment_method) {
                alert('Error: ' + errors.payment_method);
            }
        },
    });
};

// Parse price to number safely
const parsePrice = (value) => {
    if (typeof value === 'number') return value;
    if (typeof value === 'string') {
        const parsed = parseFloat(value.replace(',', '.'));
        return isNaN(parsed) ? 0 : parsed;
    }
    return 0;
};

const formatPrice = (price) => {
    const numPrice = parsePrice(price);
    const currency = props.settings?.currency || 'USD';
    return new Intl.NumberFormat('es-ES', { style: 'currency', currency }).format(numPrice);
};

const formatLimit = (value) => {
    return value === -1 ? 'Ilimitado' : value;
};

// Safe price calculation
const planPrice = computed(() => parsePrice(props.plan?.price));

// Fee calculation based on payment method
const feeInfo = computed(() => {
    const method = form.payment_method;
    if (method === 'stripe' && props.settings?.stripe_fee_enabled) {
        // Stripe: 2.9% + $0.30
        const percentFee = 0.029;
        const fixedFee = 0.30;
        const subtotal = planPrice.value;
        const totalWithFee = (subtotal + fixedFee) / (1 - percentFee);
        const fee = totalWithFee - subtotal;
        return { enabled: true, fee: Math.round(fee * 100) / 100, label: 'Tarifa Stripe', tooltip: '2.9% + $0.30 por transacción' };
    }
    if (method === 'paypal' && props.settings?.paypal_fee_enabled) {
        // PayPal: 3.49% + $0.49
        const percentFee = 0.0349;
        const fixedFee = 0.49;
        const subtotal = planPrice.value;
        const totalWithFee = (subtotal + fixedFee) / (1 - percentFee);
        const fee = totalWithFee - subtotal;
        return { enabled: true, fee: Math.round(fee * 100) / 100, label: 'Tarifa PayPal', tooltip: '3.49% + $0.49 por transacción' };
    }
    return { enabled: false, fee: 0, label: '', tooltip: '' };
});

// Tooltip state
const showFeeTooltip = ref(false);

const total = computed(() => planPrice.value + feeInfo.value.fee);

onMounted(() => {
    // Component mounted
});

const getMethodIcon = (method) => {
    const icons = {
        wallet: `<svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" />
        </svg>`,
        stripe: `<svg class="w-8 h-8" viewBox="0 0 24 24" fill="currentColor">
            <path d="M13.976 9.15c-2.172-.806-3.356-1.426-3.356-2.409 0-.831.683-1.305 1.901-1.305 2.227 0 4.515.858 6.09 1.631l.89-5.494C18.252.975 15.697 0 12.165 0 9.667 0 7.589.654 6.104 1.872 4.56 3.147 3.757 4.992 3.757 7.218c0 4.039 2.467 5.76 6.476 7.219 2.585.92 3.445 1.574 3.445 2.583 0 .98-.84 1.545-2.354 1.545-1.875 0-4.965-.921-6.99-2.109l-.9 5.555C5.175 22.99 8.385 24 11.714 24c2.641 0 4.843-.624 6.328-1.813 1.664-1.305 2.525-3.236 2.525-5.732 0-4.128-2.524-5.851-6.591-7.305z"/>
        </svg>`,
        paypal: `<svg class="w-8 h-8" viewBox="0 0 24 24" fill="currentColor">
            <path d="M7.076 21.337H2.47a.641.641 0 0 1-.633-.74L4.944.901C5.026.382 5.474 0 5.998 0h7.46c2.57 0 4.578.543 5.69 1.81 1.01 1.15 1.304 2.42 1.012 4.287-.023.143-.047.288-.077.437-.983 5.05-4.349 6.797-8.647 6.797h-2.19c-.524 0-.968.382-1.05.9l-1.12 7.106zm14.146-14.42a3.35 3.35 0 0 0-.607-.541c-.013.076-.026.175-.041.254-.59 3.025-2.566 6.082-8.558 6.082h-2.19a1.88 1.88 0 0 0-1.854 1.588l-1.094 6.938-.263 1.664c-.078.49.3.943.796.943h4.605c.524 0 .968-.382 1.05-.9l.962-6.1c.082-.518.526-.9 1.05-.9h.66c4.298 0 7.664-1.747 8.647-6.797.376-1.93.14-3.423-.876-4.44-.163-.164-.34-.319-.536-.46l.249-.33z"/>
        </svg>`,
        bank_transfer: `<svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
        </svg>`,
    };
    return icons[method] || icons.bank_transfer;
};

const getMethodColor = (method, selected) => {
    if (!selected) return 'border-gray-200 dark:border-gray-700';
    const colors = {
        wallet: 'border-emerald-500 bg-emerald-50 dark:bg-emerald-900/20',
        stripe: 'border-indigo-500 bg-indigo-50 dark:bg-indigo-900/20',
        paypal: 'border-blue-500 bg-blue-50 dark:bg-blue-900/20',
        bank_transfer: 'border-green-500 bg-green-50 dark:bg-green-900/20',
    };
    return colors[method] || 'border-blue-500 bg-blue-50';
};
</script>

<template>
    <Head :title="`Checkout - ${plan.name}`" />

    <CoachLayout>
        <div class="py-8">
            <div class="mx-auto max-w-4xl px-4 sm:px-6 lg:px-8">
                <!-- Header -->
                <div class="mb-8">
                    <Link :href="route('coach.subscription.index')" class="inline-flex items-center text-sm text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300 mb-4">
                        <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
                        </svg>
                        Volver a planes
                    </Link>
                    <h1 class="text-2xl font-bold text-gray-900 dark:text-white">Checkout</h1>
                    <p class="text-gray-500 dark:text-gray-400">Completa tu compra para activar el plan</p>
                </div>

                <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">
                    <!-- Payment Methods (Left Column - 3 cols) -->
                    <div class="lg:col-span-3 space-y-6">
                        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-6">
                            <h2 class="text-lg font-semibold text-gray-900 dark:text-white mb-6">Método de Pago</h2>

                            <form @submit.prevent="submit" class="space-y-4">
                                <!-- Wallet Payment Option (if available) -->
                                <div v-if="settings?.wallet_payment_enabled && walletBalance > 0" class="mb-6">
                                    <label
                                        :class="[
                                            'flex items-center p-4 border-2 rounded-xl transition-all',
                                            canPayWithWallet ? 'cursor-pointer' : 'cursor-not-allowed opacity-60',
                                            getMethodColor('wallet', form.payment_method === 'wallet')
                                        ]"
                                    >
                                        <input
                                            type="radio"
                                            v-model="form.payment_method"
                                            value="wallet"
                                            :disabled="!canPayWithWallet"
                                            class="sr-only"
                                        />
                                        <div class="flex-shrink-0 mr-4" :class="form.payment_method === 'wallet' ? 'text-emerald-600' : 'text-gray-400'" v-html="getMethodIcon('wallet')"></div>
                                        <div class="flex-1">
                                            <div class="flex items-center gap-2">
                                                <span class="font-medium text-gray-900 dark:text-white">Pagar con Saldo de Billetera</span>
                                                <span class="px-2 py-0.5 text-xs font-semibold bg-emerald-100 text-emerald-800 dark:bg-emerald-900/30 dark:text-emerald-400 rounded-full">
                                                    Instantáneo
                                                </span>
                                            </div>
                                            <p class="text-sm text-gray-500 dark:text-gray-400">
                                                Saldo disponible:
                                                <span class="font-semibold" :class="canPayWithWallet ? 'text-emerald-600' : 'text-red-500'">
                                                    {{ formatPrice(walletBalance) }}
                                                </span>
                                            </p>
                                            <p v-if="insufficientWalletBalance" class="text-xs text-amber-600 dark:text-amber-400 mt-1">
                                                ⚠️ Saldo insuficiente. Necesitas {{ formatPrice(planPrice - walletBalance) }} más.
                                                <Link :href="route('coach.wallet.index')" class="underline hover:text-amber-700">Recargar billetera</Link>
                                            </p>
                                        </div>
                                        <div class="flex-shrink-0 ml-4">
                                            <div :class="[
                                                'w-5 h-5 rounded-full border-2 flex items-center justify-center',
                                                form.payment_method === 'wallet' ? 'border-emerald-600 bg-emerald-600' : 'border-gray-300'
                                            ]">
                                                <svg v-if="form.payment_method === 'wallet'" class="w-3 h-3 text-white" fill="currentColor" viewBox="0 0 20 20">
                                                    <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                                                </svg>
                                            </div>
                                        </div>
                                    </label>

                                    <!-- Divider -->
                                    <div class="relative my-4">
                                        <div class="absolute inset-0 flex items-center">
                                            <div class="w-full border-t border-gray-200 dark:border-gray-700"></div>
                                        </div>
                                        <div class="relative flex justify-center text-sm">
                                            <span class="px-3 bg-white dark:bg-gray-800 text-gray-500 dark:text-gray-400">o paga con</span>
                                        </div>
                                    </div>
                                </div>

                                <!-- Payment Method Options -->
                                <div class="space-y-3">
                                    <!-- No payment methods available message -->
                                    <div v-if="!paymentMethods || paymentMethods.length === 0" class="p-6 bg-amber-50 dark:bg-amber-900/20 rounded-xl border border-amber-200 dark:border-amber-800 text-center">
                                        <svg class="w-12 h-12 mx-auto text-amber-500 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                                        </svg>
                                        <h3 class="text-lg font-semibold text-amber-800 dark:text-amber-200 mb-2">No hay métodos de pago disponibles</h3>
                                        <p class="text-sm text-amber-600 dark:text-amber-400">
                                            Los métodos de pago no están configurados correctamente. Por favor, contacta con soporte técnico o intenta más tarde.
                                        </p>
                                    </div>

                                    <label
                                        v-for="method in paymentMethods"
                                        :key="method.id"
                                        :class="[
                                            'flex items-center p-4 border-2 rounded-xl cursor-pointer transition-all',
                                            getMethodColor(method.id, form.payment_method === method.id)
                                        ]"
                                    >
                                        <input
                                            type="radio"
                                            v-model="form.payment_method"
                                            :value="method.id"
                                            class="sr-only"
                                        />
                                        <div class="flex-shrink-0 mr-4" :class="form.payment_method === method.id ? 'text-blue-600' : 'text-gray-400'" v-html="getMethodIcon(method.id)"></div>
                                        <div class="flex-1">
                                            <span class="font-medium text-gray-900 dark:text-white">{{ method.name }}</span>
                                            <p class="text-sm text-gray-500 dark:text-gray-400">{{ method.description }}</p>
                                            <!-- Show test mode badges -->
                                            <span
                                                v-if="method.id === 'stripe' && settings?.stripe_test_mode"
                                                class="inline-block mt-1 px-2 py-0.5 text-xs font-medium bg-yellow-100 text-yellow-800 rounded"
                                            >
                                                Modo Prueba
                                            </span>
                                            <span
                                                v-if="method.id === 'paypal' && settings?.paypal_sandbox"
                                                class="inline-block mt-1 px-2 py-0.5 text-xs font-medium bg-yellow-100 text-yellow-800 rounded"
                                            >
                                                Sandbox
                                            </span>
                                        </div>
                                        <div class="flex-shrink-0 ml-4">
                                            <div :class="[
                                                'w-5 h-5 rounded-full border-2 flex items-center justify-center',
                                                form.payment_method === method.id ? 'border-blue-600 bg-blue-600' : 'border-gray-300'
                                            ]">
                                                <svg v-if="form.payment_method === method.id" class="w-3 h-3 text-white" fill="currentColor" viewBox="0 0 20 20">
                                                    <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                                                </svg>
                                            </div>
                                        </div>
                                    </label>
                                </div>

                                <!-- Bank Details (shown when bank_transfer selected) -->
                                <div v-if="form.payment_method === 'bank_transfer' && banks?.length > 0" class="mt-6 space-y-6">
                                    <!-- Bank Selection -->
                                    <div class="p-4 bg-blue-50 dark:bg-blue-900/20 rounded-xl border border-blue-200 dark:border-blue-800">
                                        <h3 class="font-medium text-blue-900 dark:text-blue-100 mb-4">Selecciona el banco donde realizarás el pago:</h3>
                                        <div class="space-y-3">
                                            <label v-for="bank in banks" :key="bank.id"
                                                   :class="[
                                                       'flex items-start p-3 bg-white dark:bg-gray-800 rounded-lg shadow-sm cursor-pointer border-2 transition-all',
                                                       form.selected_bank_id === bank.id
                                                           ? 'border-green-500 ring-1 ring-green-500/30'
                                                           : 'border-transparent hover:border-gray-300 dark:hover:border-gray-600'
                                                   ]">
                                                <input type="radio" v-model="form.selected_bank_id" :value="bank.id" class="sr-only" />
                                                <div class="flex items-center mr-3 mt-0.5">
                                                    <div :class="[
                                                        'w-5 h-5 rounded-full border-2 flex items-center justify-center',
                                                        form.selected_bank_id === bank.id ? 'border-green-600 bg-green-600' : 'border-gray-300 dark:border-gray-500'
                                                    ]">
                                                        <svg v-if="form.selected_bank_id === bank.id" class="w-3 h-3 text-white" fill="currentColor" viewBox="0 0 20 20">
                                                            <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                                                        </svg>
                                                    </div>
                                                </div>
                                                <div v-if="bank.logo_url" class="w-12 h-12 rounded-lg overflow-hidden mr-3 flex-shrink-0 bg-white border">
                                                    <img :src="bank.logo_url" :alt="bank.bank_name" class="w-full h-full object-contain" />
                                                </div>
                                                <div v-else-if="bank.bank_type === 'western_union'" class="w-12 h-12 rounded-lg bg-[#FFDD00] flex items-center justify-center mr-3 flex-shrink-0">
                                                    <span class="text-black font-extrabold text-sm tracking-tight">WU</span>
                                                </div>
                                                <div v-else class="w-12 h-12 rounded-lg bg-gray-100 dark:bg-gray-700 flex items-center justify-center mr-3 flex-shrink-0">
                                                    <span class="text-xl">🏦</span>
                                                </div>
                                                <div class="flex-1 text-sm">
                                                    <p class="font-semibold text-gray-900 dark:text-white">{{ bank.bank_name }}</p>

                                                    <!-- Western Union specific fields -->
                                                    <template v-if="bank.bank_type === 'western_union'">
                                                        <p class="text-gray-600 dark:text-gray-400">
                                                            <span class="font-medium">Beneficiario:</span> {{ bank.account_holder }}
                                                        </p>
                                                        <p v-if="bank.phone_number" class="text-gray-600 dark:text-gray-400">
                                                            <span class="font-medium">Teléfono:</span> {{ bank.phone_number }}
                                                        </p>
                                                    </template>

                                                    <!-- Traditional bank fields -->
                                                    <template v-else>
                                                        <p v-if="bank.account_number" class="text-gray-600 dark:text-gray-400">
                                                            {{ bank.account_type === 'savings' ? 'Ahorro' : 'Corriente' }}:
                                                            <span class="font-mono">{{ bank.account_number }}</span>
                                                        </p>
                                                        <p class="text-gray-600 dark:text-gray-400">Titular: {{ bank.account_holder }}</p>
                                                        <p v-if="bank.rnc" class="text-gray-500 dark:text-gray-500 text-xs">RNC: {{ bank.rnc }}</p>
                                                    </template>

                                                    <p v-if="bank.instructions" class="text-gray-500 dark:text-gray-400 text-xs mt-1 italic">{{ bank.instructions }}</p>
                                                </div>
                                            </label>
                                        </div>
                                        <p v-if="form.errors.selected_bank_id" class="mt-2 text-sm text-red-600">{{ form.errors.selected_bank_id }}</p>
                                    </div>

                                    <!-- Receipt Upload -->
                                    <div class="p-4 bg-green-50 dark:bg-green-900/20 rounded-xl border border-green-200 dark:border-green-800">
                                        <h3 class="font-medium text-green-900 dark:text-green-100 mb-2">Subir comprobante de pago</h3>
                                        <p class="text-sm text-green-700 dark:text-green-300 mb-4">Adjunta una foto o captura de pantalla del comprobante de tu transferencia para agilizar la verificación.</p>

                                        <div v-if="!receiptPreview" class="relative">
                                            <input
                                                ref="fileInput"
                                                type="file"
                                                accept="image/jpeg,image/png,image/webp,application/pdf"
                                                @change="onReceiptSelected"
                                                class="absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10"
                                            />
                                            <div class="flex flex-col items-center justify-center p-6 border-2 border-dashed border-green-300 dark:border-green-600 rounded-lg hover:border-green-400 dark:hover:border-green-500 transition-colors bg-white/50 dark:bg-gray-800/50">
                                                <svg class="w-10 h-10 text-green-400 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                                                </svg>
                                                <span class="text-sm font-medium text-green-700 dark:text-green-300">Haz clic o arrastra tu comprobante aquí</span>
                                                <span class="text-xs text-green-600 dark:text-green-400 mt-1">JPG, PNG, WebP o PDF (máx. 5MB)</span>
                                            </div>
                                        </div>

                                        <!-- Preview -->
                                        <div v-else class="relative">
                                            <div class="bg-white dark:bg-gray-800 rounded-lg border border-green-200 dark:border-green-700 overflow-hidden">
                                                <img v-if="!form.receipt_file?.name?.endsWith('.pdf')" :src="receiptPreview" alt="Comprobante" class="w-full h-48 object-contain bg-gray-50 dark:bg-gray-900" />
                                                <div v-else class="flex items-center justify-center h-32 bg-gray-50 dark:bg-gray-900">
                                                    <svg class="w-12 h-12 text-red-500" fill="currentColor" viewBox="0 0 24 24">
                                                        <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8l-6-6zM14 9V3.5L18.5 8H15a1 1 0 01-1-1v2z"/>
                                                    </svg>
                                                    <span class="ml-2 text-sm text-gray-600 dark:text-gray-400">{{ form.receipt_file?.name }}</span>
                                                </div>
                                                <div class="p-3 flex items-center justify-between">
                                                    <span class="text-sm text-green-700 dark:text-green-300 flex items-center gap-1">
                                                        <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" /></svg>
                                                        Comprobante adjuntado
                                                    </span>
                                                    <button type="button" @click="removeReceipt" class="text-sm text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 font-medium">
                                                        Eliminar
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                        <p v-if="form.errors.receipt_file" class="mt-2 text-sm text-red-600">{{ form.errors.receipt_file }}</p>
                                    </div>

                                    <p class="text-sm text-blue-700 dark:text-blue-300">
                                        <strong>Nota:</strong> Incluye el número de factura en el concepto de la transferencia o envío.
                                    </p>
                                </div>

                                <!-- Submit Button -->
                                <button
                                    type="submit"
                                    :disabled="form.processing || processing || (!paymentMethods?.length && !canPayWithWallet)"
                                    :class="[
                                        'w-full mt-6 py-4 px-6 text-white rounded-xl font-semibold disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-sm hover:shadow-md',
                                        form.payment_method === 'wallet'
                                            ? 'bg-emerald-600 hover:bg-emerald-700'
                                            : 'bg-blue-600 hover:bg-blue-700'
                                    ]"
                                >
                                    <span v-if="form.processing || processing" class="flex items-center justify-center">
                                        <svg class="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" 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 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                        </svg>
                                        Procesando...
                                    </span>
                                    <span v-else>
                                        {{ form.payment_method === 'bank_transfer'
                                            ? 'Generar Orden'
                                            : form.payment_method === 'wallet'
                                                ? `Pagar con Billetera ${formatPrice(total)}`
                                                : `Pagar ${formatPrice(total)}`
                                        }}
                                    </span>
                                </button>

                                <p class="text-xs text-center text-gray-500 dark:text-gray-400 mt-4">
                                    Al continuar, aceptas nuestros
                                    <a href="/page/terms" class="text-blue-600 hover:underline">términos de servicio</a>
                                    y
                                    <a href="/page/privacy" class="text-blue-600 hover:underline">política de privacidad</a>.
                                </p>
                            </form>
                        </div>
                    </div>

                    <!-- Order Summary (Right Column - 2 cols) -->
                    <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 sticky top-4">
                            <!-- Plan Header -->
                            <div class="p-6 text-white bg-blue-600">
                                <p class="text-sm opacity-80">Plan seleccionado</p>
                                <h3 class="text-2xl font-bold">{{ plan.name }}</h3>
                                <p class="text-sm opacity-80 mt-1">{{ plan.duration_days }} días de acceso</p>
                            </div>

                            <!-- Plan Features -->
                            <div class="p-6 border-b dark:border-gray-700">
                                <h4 class="font-medium text-gray-900 dark:text-white mb-3">Incluye:</h4>
                                <ul class="space-y-2 text-sm">
                                    <li class="flex items-center text-gray-600 dark:text-gray-400">
                                        <svg class="w-4 h-4 text-green-500 mr-2" fill="currentColor" viewBox="0 0 20 20">
                                            <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                                        </svg>
                                        {{ formatLimit(plan.features?.max_clients) }} clientes
                                    </li>
                                    <li class="flex items-center text-gray-600 dark:text-gray-400">
                                        <svg class="w-4 h-4 text-green-500 mr-2" fill="currentColor" viewBox="0 0 20 20">
                                            <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                                        </svg>
                                        {{ formatLimit(plan.features?.max_diets) }} dietas
                                    </li>
                                    <li class="flex items-center text-gray-600 dark:text-gray-400">
                                        <svg class="w-4 h-4 text-green-500 mr-2" fill="currentColor" viewBox="0 0 20 20">
                                            <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                                        </svg>
                                        {{ formatLimit(plan.features?.max_routines) }} rutinas
                                    </li>
                                    <li v-if="plan.features?.custom_foods" class="flex items-center text-gray-600 dark:text-gray-400">
                                        <svg class="w-4 h-4 text-green-500 mr-2" fill="currentColor" viewBox="0 0 20 20">
                                            <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                                        </svg>
                                        Alimentos personalizados
                                    </li>
                                    <li v-if="plan.features?.pdf_export" class="flex items-center text-gray-600 dark:text-gray-400">
                                        <svg class="w-4 h-4 text-green-500 mr-2" fill="currentColor" viewBox="0 0 20 20">
                                            <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                                        </svg>
                                        Exportar a PDF
                                    </li>
                                </ul>
                            </div>

                            <!-- Price Breakdown -->
                            <div class="p-6 bg-gray-50 dark:bg-gray-900/50">
                                <!-- Calculation Error Alert -->
                                <div v-if="calculationError" class="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
                                    {{ calculationError }}
                                </div>

                                <div class="space-y-2 text-sm">
                                    <div class="flex justify-between">
                                        <span class="text-gray-600 dark:text-gray-400">Subtotal</span>
                                        <span class="text-gray-900 dark:text-white">{{ formatPrice(planPrice) }}</span>
                                    </div>
                                    <!-- Payment Fee -->
                                    <div v-if="feeInfo.enabled" class="flex justify-between text-amber-600 dark:text-amber-400">
                                        <span class="flex items-center relative">
                                            <button
                                                type="button"
                                                @mouseenter="showFeeTooltip = true"
                                                @mouseleave="showFeeTooltip = false"
                                                @click="showFeeTooltip = !showFeeTooltip"
                                                class="mr-1 hover:text-amber-700 dark:hover:text-amber-300 focus:outline-none"
                                            >
                                                <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="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                                </svg>
                                            </button>
                                            <!-- Tooltip -->
                                            <div
                                                v-show="showFeeTooltip"
                                                class="absolute bottom-full left-0 mb-2 px-3 py-2 bg-gray-900 dark:bg-gray-700 text-white text-xs rounded-lg shadow-lg whitespace-nowrap z-10"
                                            >
                                                {{ feeInfo.tooltip }}
                                                <div class="absolute top-full left-4 w-0 h-0 border-l-4 border-r-4 border-t-4 border-transparent border-t-gray-900 dark:border-t-gray-700"></div>
                                            </div>
                                            {{ feeInfo.label }}
                                        </span>
                                        <span>+{{ formatPrice(feeInfo.fee) }}</span>
                                    </div>
                                    <div class="pt-3 mt-3 border-t dark:border-gray-700 flex justify-between">
                                        <span class="font-semibold text-gray-900 dark:text-white">Total</span>
                                        <span class="text-xl font-bold text-blue-600">{{ formatPrice(total) }}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </CoachLayout>
</template>
