<script setup>
/**
 * Client Dashboard - Mobile-First Design
 * Complete overview of workouts, meals, progress, and coach communication
 */
import ClientLayout from '@/Layouts/ClientLayout.vue';
import FeaturedProductsWidget from '@/Components/FeaturedProductsWidget.vue';
import { Head, Link, useForm, router, usePage } from '@inertiajs/vue3';
import { ref, computed, onMounted } from 'vue';
import PullToRefresh from '@/Components/Mobile/PullToRefresh.vue';

const page = usePage();
const features = computed(() => page.props.features || {});

const props = defineProps({
    client: Object,
    coach: Object,
    stats: Object,
    compliance_logs: Array,
    progress_photos: Array,
    weight_history: Array,
    weekly_compliance: Array,
    notifications: Array,
    no_profile: Boolean,
});

// Safe getters
const clientName = computed(() => props.client?.name || 'Cliente');
const clientWeight = computed(() => props.client?.weight || 70);
const statsData = computed(() => props.stats || {
    workouts: 0, meal_plans: 0, bmi: null, tdee: null, streak: 0,
    total_workouts_completed: 0, total_meals_completed: 0, unread_messages: 0
});

// Forms
const weightForm = useForm({
    weight: clientWeight.value,
});

const complianceForm = useForm({
    resource_type: '',
    resource_id: '',
});

const photoForm = useForm({
    image: null,
    type: 'front',
    weight: clientWeight.value,
    date: new Date().toISOString().split('T')[0],
});

// State
const showPhotoModal = ref(false);
const dashboardPhotoSlides = ref({}); // Track slider state for dashboard photos

const activeTab = ref('overview');
const selectedWorkout = ref(null);
const selectedMealPlan = ref(null);
const isRefreshing = ref(false);

const handleRefresh = () => {
    isRefreshing.value = true;
    router.reload({ onFinish: () => { isRefreshing.value = false; } });
};

// Methods
const updateWeight = () => {
    weightForm.post(route('client.metrics.update'), {
        preserveScroll: true,
    });
};

const markDone = (type, id) => {
    complianceForm.resource_type = type;
    complianceForm.resource_id = id;
    complianceForm.post(route('client.compliance.log'), {
        preserveScroll: true,
    });
};

const uploadPhoto = () => {
    photoForm.post(route('client.photos.upload'), {
        onSuccess: () => {
            showPhotoModal.value = false;
            photoForm.reset('image');
        },
    });
};

const formatQuantity = (item) => {
    const qty = item.quantity || 100;
    const unit = item.unit || 'g';
    const formattedQty = qty % 1 === 0 ? Math.round(qty) : parseFloat(qty.toFixed(2).replace(/\.?0+$/, ''));
    return `${formattedQty} ${unit}`;
};

const isCompletedToday = (type, id) => {
    if (!props.compliance_logs?.length) return false;
    const today = new Date().toISOString().split('T')[0];
    return props.compliance_logs.some(log =>
        log.resource_type === type &&
        log.resource_id === id &&
        log.completed_at?.split('T')[0] === today
    );
};



const getBmiCategory = computed(() => {
    if (!statsData.value?.bmi) return null;
    const bmi = parseFloat(statsData.value.bmi);
    if (bmi < 18.5) return { label: 'Bajo peso', color: 'text-blue-600 bg-blue-100', icon: '💙' };
    if (bmi < 25) return { label: 'Normal', color: 'text-green-600 bg-green-100', icon: '💚' };
    if (bmi < 30) return { label: 'Sobrepeso', color: 'text-yellow-600 bg-yellow-100', icon: '💛' };
    return { label: 'Obesidad', color: 'text-red-600 bg-red-100', icon: '❤️' };
});

const todayDayName = computed(() => {
    const days = ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'];
    return days[new Date().getDay()];
});

const greeting = computed(() => {
    const hour = new Date().getHours();
    if (hour < 12) return '¡Buenos días';
    if (hour < 19) return '¡Buenas tardes';
    return '¡Buenas noches';
});

const unreadNotifications = computed(() =>
    props.notifications?.filter(n => !n.read_at) || []
);
</script>

<template>
    <Head title="Mi Panel" />

    <ClientLayout>
        <template #header>
            <div class="flex justify-between items-center">
                <div class="min-w-0">
                    <h2 class="text-lg sm:text-xl md:text-2xl font-bold text-gray-900 dark:text-white truncate">
                        {{ greeting }}, {{ clientName }}! 👋
                    </h2>
                    <p class="text-xs sm:text-sm text-gray-500 dark:text-gray-400 mt-0.5">
                        {{ todayDayName }}, {{ new Date().toLocaleDateString('es-ES', { day: 'numeric', month: 'long' }) }}
                    </p>
                </div>
            </div>
        </template>



        <PullToRefresh :loading="isRefreshing" @refresh="handleRefresh">
        <div class="py-3 sm:py-4 md:py-8">
            <div class="mx-auto max-w-7xl px-3 sm:px-6 lg:px-8 space-y-4 sm:space-y-6">

                <!-- No Profile Warning -->
                <div v-if="no_profile" class="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-xl p-4 sm:p-6 text-center">
                    <div class="text-4xl sm:text-5xl mb-3 sm:mb-4">⚠️</div>
                    <h3 class="text-lg sm:text-xl font-bold text-yellow-800 dark:text-yellow-300 mb-2">Perfil No Configurado</h3>
                    <p class="text-sm text-yellow-700 dark:text-yellow-400 mb-4">
                        Tu entrenador aún no ha configurado tu perfil de cliente.
                        Contacta con tu coach para activar tu cuenta completamente.
                    </p>
                </div>

                <template v-if="!no_profile">
                    <!-- Quick Stats Grid -->
                    <div class="grid grid-cols-2 lg:grid-cols-4 gap-2.5 sm:gap-3 md:gap-4">
                        <!-- Streak -->
                        <div class="bg-gradient-to-br from-orange-500 to-amber-500 rounded-xl p-3 sm:p-4 text-white shadow-lg">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-[10px] sm:text-xs md:text-sm opacity-90 font-medium">Racha actual</p>
                                    <p class="text-xl sm:text-2xl md:text-3xl font-bold">{{ statsData.streak }} <span class="text-xs sm:text-sm font-normal">días</span></p>
                                </div>
                                <span class="text-2xl sm:text-3xl md:text-4xl">🔥</span>
                            </div>
                        </div>

                        <!-- BMI -->
                        <div class="bg-white dark:bg-gray-800 rounded-xl p-3 sm:p-4 shadow-sm border border-gray-100 dark:border-gray-700">
                            <div class="flex items-center gap-2 sm:gap-3">
                                <span class="text-xl sm:text-2xl md:text-3xl">{{ getBmiCategory?.icon || '📊' }}</span>
                                <div class="min-w-0">
                                    <p class="text-[10px] sm:text-xs md:text-sm text-gray-500 dark:text-gray-400">IMC</p>
                                    <p class="text-base sm:text-lg md:text-xl font-bold text-gray-900 dark:text-white">{{ statsData.bmi || '-' }}</p>
                                    <span v-if="getBmiCategory" :class="['text-xs px-2 py-0.5 rounded-full', getBmiCategory.color]">
                                        {{ getBmiCategory.label }}
                                    </span>
                                </div>
                            </div>
                        </div>

                        <!-- TDEE -->
                        <div class="bg-white dark:bg-gray-800 rounded-xl p-3 sm:p-4 shadow-sm border border-gray-100 dark:border-gray-700">
                            <div class="flex items-center gap-2 sm:gap-3">
                                <span class="text-xl sm:text-2xl md:text-3xl">⚡</span>
                                <div class="min-w-0">
                                    <p class="text-[10px] sm:text-xs md:text-sm text-gray-500 dark:text-gray-400">Calorías</p>
                                    <p class="text-base sm:text-lg md:text-xl font-bold text-gray-900 dark:text-white">
                                        {{ statsData.tdee ? Math.round(statsData.tdee) : '-' }} <span class="text-[10px] sm:text-xs font-normal">kcal</span>
                                    </p>
                                </div>
                            </div>
                        </div>

                        <!-- Weight -->
                        <div class="bg-white dark:bg-gray-800 rounded-xl p-3 sm:p-4 shadow-sm border border-gray-100 dark:border-gray-700">
                            <div class="flex items-center gap-2 sm:gap-3">
                                <span class="text-xl sm:text-2xl md:text-3xl">⚖️</span>
                                <div class="min-w-0">
                                    <p class="text-[10px] sm:text-xs md:text-sm text-gray-500 dark:text-gray-400">Peso</p>
                                    <p class="text-base sm:text-lg md:text-xl font-bold text-gray-900 dark:text-white">{{ statsData.current_weight || '-' }} <span class="text-[10px] sm:text-xs font-normal">kg</span></p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Coach Info Card -->
                    <div v-if="coach" class="bg-gradient-to-r from-emerald-600 to-green-500 rounded-xl p-4 md:p-6 text-white shadow-lg">
                        <div class="flex items-center justify-between">
                            <div class="flex items-center gap-4">
                                <img v-if="coach.avatar" :src="coach.avatar" :alt="coach.name" class="w-12 h-12 md:w-14 md:h-14 rounded-full object-cover border-2 border-white/30" />
                                <div v-else class="w-12 h-12 md:w-14 md:h-14 bg-white/20 rounded-full flex items-center justify-center text-xl md:text-2xl font-bold">
                                    {{ coach.name?.charAt(0).toUpperCase() }}
                                </div>
                                <div>
                                    <p class="text-xs md:text-sm opacity-90">Tu entrenador</p>
                                    <h3 class="text-lg md:text-xl font-bold">{{ coach.name }}</h3>
                                </div>
                            </div>
                            <Link
                                :href="route('client.chat.index')"
                                class="bg-white/20 hover:bg-white/30 px-4 py-2 rounded-lg text-sm font-medium transition-colors flex items-center gap-2"
                            >
                                <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="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                                </svg>
                                <span class="hidden md:inline">Enviar mensaje</span>
                            </Link>
                        </div>
                    </div>

                    <!-- Métricas Metabólicas y Datos Físicos -->
                    <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
                        <!-- Métricas Metabólicas -->
                        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 overflow-hidden">
                            <div class="px-4 md:px-6 py-4 bg-gradient-to-r from-blue-500 to-indigo-500">
                                <h3 class="text-lg font-bold text-white flex items-center gap-2">
                                    <span>⚡</span> Métricas Metabólicas
                                </h3>
                            </div>
                            <div class="p-4 md:p-6">
                                <div class="space-y-3">
                                    <!-- BMR -->
                                    <div class="flex items-center justify-between p-3 bg-orange-50 dark:bg-orange-900/20 rounded-xl">
                                        <div class="flex items-center gap-3">
                                            <div class="w-10 h-10 bg-orange-100 dark:bg-orange-900/50 rounded-lg flex items-center justify-center">
                                                <span class="text-xl">🔥</span>
                                            </div>
                                            <div>
                                                <p class="text-xs text-gray-600 dark:text-gray-400">TMB (Metabolismo Basal)</p>
                                                <p class="text-sm text-gray-500 dark:text-gray-500">Calorías en reposo</p>
                                            </div>
                                        </div>
                                        <div class="text-right">
                                            <p class="text-2xl font-bold text-orange-600 dark:text-orange-400">{{ statsData.bmr ? Math.round(statsData.bmr) : '-' }}</p>
                                            <p class="text-xs text-gray-500 dark:text-gray-400">kcal/día</p>
                                        </div>
                                    </div>

                                    <!-- TDEE -->
                                    <div class="flex items-center justify-between p-3 bg-green-50 dark:bg-green-900/20 rounded-xl">
                                        <div class="flex items-center gap-3">
                                            <div class="w-10 h-10 bg-green-100 dark:bg-green-900/50 rounded-lg flex items-center justify-center">
                                                <span class="text-xl">⚡</span>
                                            </div>
                                            <div>
                                                <p class="text-xs text-gray-600 dark:text-gray-400">TDEE (Gasto Energético)</p>
                                                <p class="text-sm text-gray-500 dark:text-gray-500">Calorías totales diarias</p>
                                            </div>
                                        </div>
                                        <div class="text-right">
                                            <p class="text-2xl font-bold text-green-600 dark:text-green-400">{{ statsData.tdee ? Math.round(statsData.tdee) : '-' }}</p>
                                            <p class="text-xs text-gray-500 dark:text-gray-400">kcal/día</p>
                                        </div>
                                    </div>

                                    <!-- Macros Recomendados -->
                                    <div v-if="statsData.macros" class="p-3 bg-purple-50 dark:bg-purple-900/20 rounded-xl border-2 border-purple-200 dark:border-purple-800">
                                        <div class="flex items-center justify-between mb-3">
                                            <p class="text-sm font-semibold text-gray-700 dark:text-gray-300">🎯 Tus Macros</p>
                                            <p class="text-lg font-bold text-purple-600 dark:text-purple-400">{{ statsData.macros.calories }} kcal</p>
                                        </div>
                                        <div class="grid grid-cols-3 gap-2">
                                            <div class="text-center p-2 bg-red-100 dark:bg-red-900/30 rounded-lg">
                                                <p class="text-xs text-gray-600 dark:text-gray-400">Proteínas</p>
                                                <p class="text-lg font-bold text-red-600 dark:text-red-400">{{ statsData.macros.protein }}g</p>
                                            </div>
                                            <div class="text-center p-2 bg-amber-100 dark:bg-amber-900/30 rounded-lg">
                                                <p class="text-xs text-gray-600 dark:text-gray-400">Carbos</p>
                                                <p class="text-lg font-bold text-amber-600 dark:text-amber-400">{{ statsData.macros.carbs }}g</p>
                                            </div>
                                            <div class="text-center p-2 bg-blue-100 dark:bg-blue-900/30 rounded-lg">
                                                <p class="text-xs text-gray-600 dark:text-gray-400">Grasas</p>
                                                <p class="text-lg font-bold text-blue-600 dark:text-blue-400">{{ statsData.macros.fats }}g</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <Link
                                    :href="route('client.profile.index') + '?tab=biometrics'"
                                    class="mt-4 w-full inline-block text-center px-4 py-2 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-colors text-sm font-medium"
                                >
                                    Ver detalles completos →
                                </Link>
                            </div>
                        </div>

                        <!-- Datos Físicos -->
                        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 overflow-hidden">
                            <div class="px-4 md:px-6 py-4 bg-gradient-to-r from-emerald-500 to-teal-500">
                                <h3 class="text-lg font-bold text-white flex items-center gap-2">
                                    <span>💪</span> Datos Físicos
                                </h3>
                            </div>
                            <div class="p-4 md:p-6">
                                <div class="grid grid-cols-2 gap-3">
                                    <!-- Peso -->
                                    <div class="p-3 bg-gray-50 dark:bg-gray-700/50 rounded-xl text-center">
                                        <p class="text-xs text-gray-500 dark:text-gray-400 mb-1">Peso actual</p>
                                        <p class="text-2xl font-bold text-gray-900 dark:text-white">{{ statsData.current_weight || '-' }} <span class="text-sm">kg</span></p>
                                    </div>

                                    <!-- Altura -->
                                    <div class="p-3 bg-gray-50 dark:bg-gray-700/50 rounded-xl text-center">
                                        <p class="text-xs text-gray-500 dark:text-gray-400 mb-1">Altura</p>
                                        <p class="text-2xl font-bold text-gray-900 dark:text-white">{{ client?.height || '-' }} <span class="text-sm">cm</span></p>
                                    </div>

                                    <!-- Edad -->
                                    <div class="p-3 bg-gray-50 dark:bg-gray-700/50 rounded-xl text-center">
                                        <p class="text-xs text-gray-500 dark:text-gray-400 mb-1">Edad</p>
                                        <p class="text-2xl font-bold text-gray-900 dark:text-white">{{ client?.age || '-' }} <span class="text-sm">años</span></p>
                                    </div>

                                    <!-- Género -->
                                    <div class="p-3 bg-gray-50 dark:bg-gray-700/50 rounded-xl text-center">
                                        <p class="text-xs text-gray-500 dark:text-gray-400 mb-1">Género</p>
                                        <p class="text-lg font-bold text-gray-900 dark:text-white">
                                            {{ client?.gender === 'male' ? '♂️ M' : client?.gender === 'female' ? '♀️ F' : '-' }}
                                        </p>
                                    </div>
                                </div>

                                <!-- Objetivo -->
                                <div v-if="client?.objective" class="mt-3 p-3 bg-gradient-to-r from-purple-50 to-pink-50 dark:from-purple-900/20 dark:to-pink-900/20 rounded-xl border-2 border-purple-200 dark:border-purple-800">
                                    <p class="text-xs text-gray-600 dark:text-gray-400 mb-1">Tu Objetivo</p>
                                    <p class="text-lg font-bold" :class="client.objective === 'lose' ? 'text-red-600 dark:text-red-400' : client.objective === 'gain' ? 'text-blue-600 dark:text-blue-400' : 'text-green-600 dark:text-green-400'">
                                        {{ client.objective === 'lose' ? '📉 Perder peso' : client.objective === 'gain' ? '📈 Ganar masa' : '⚖️ Mantener' }}
                                    </p>
                                </div>

                                <!-- Nivel de actividad -->
                                <div v-if="client?.activity_level" class="mt-3 p-3 bg-gray-50 dark:bg-gray-700/50 rounded-xl">
                                    <p class="text-xs text-gray-600 dark:text-gray-400 mb-1">Nivel de Actividad</p>
                                    <p class="text-sm font-semibold text-gray-900 dark:text-white">
                                        {{ {
                                            'sedentary': '🪑 Sedentario',
                                            'light': '🚶 Ligero',
                                            'moderate': '🏃 Moderado',
                                            'active': '💪 Muy activo',
                                            'very_active': '🏋️ Extra activo'
                                        }[client.activity_level] || '-' }}
                                    </p>
                                </div>

                                <Link
                                    :href="route('client.profile.index')"
                                    class="mt-4 w-full inline-block text-center px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg transition-colors text-sm font-semibold"
                                >
                                    Actualizar datos →
                                </Link>
                            </div>
                        </div>
                    </div>

                    <!-- Weekly Progress Chart -->
                    <div v-if="weekly_compliance?.length" class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 p-4 md:p-6">
                        <h3 class="text-lg font-bold text-gray-900 dark:text-white mb-4 flex items-center gap-2">
                            <span>📈</span> Tu semana
                        </h3>
                        <div class="flex items-end justify-between gap-2 h-32">
                            <div
                                v-for="day in weekly_compliance"
                                :key="day.date"
                                class="flex-1 flex flex-col items-center gap-1"
                            >
                                <div class="w-full flex flex-col gap-1 h-24 justify-end">
                                    <!-- Workout bar -->
                                    <div
                                        :style="{ height: day.workouts ? `${Math.min(day.workouts * 30, 100)}%` : '4px' }"
                                        :class="['w-full rounded-t transition-all', day.workouts ? 'bg-emerald-500' : 'bg-gray-200 dark:bg-gray-700']"
                                    ></div>
                                    <!-- Meal bar -->
                                    <div
                                        :style="{ height: day.meals ? `${Math.min(day.meals * 30, 100)}%` : '4px' }"
                                        :class="['w-full rounded-t transition-all', day.meals ? 'bg-blue-500' : 'bg-gray-200 dark:bg-gray-700']"
                                    ></div>
                                </div>
                                <span class="text-[10px] md:text-xs text-gray-500 dark:text-gray-400 font-medium">{{ day.day }}</span>
                            </div>
                        </div>
                        <div class="flex items-center justify-center gap-6 mt-4 text-xs text-gray-500 dark:text-gray-400">
                            <span class="flex items-center gap-1"><span class="w-3 h-3 bg-emerald-500 rounded"></span> Entrenos</span>
                            <span class="flex items-center gap-1"><span class="w-3 h-3 bg-blue-500 rounded"></span> Comidas</span>
                        </div>
                    </div>

                    <!-- Main Content Grid -->
                    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                        <!-- Left Column: Today's Plans -->
                        <div class="lg:col-span-2 space-y-6">
                            <!-- Active Workouts -->
                            <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 overflow-hidden">
                                <div class="p-4 md:p-6 border-b border-gray-100 dark:border-gray-700 flex items-center justify-between">
                                    <h3 class="text-lg font-bold text-gray-900 dark:text-white flex items-center gap-2">
                                        <span>💪</span> Mis Rutinas
                                    </h3>
                                    <Link
                                        :href="route('client.workout.index')"
                                        class="text-sm text-emerald-600 dark:text-emerald-400 hover:underline font-medium"
                                    >
                                        Ver todas →
                                    </Link>
                                </div>
                                <div class="p-4 md:p-6">
                                    <div v-if="client?.workouts?.length" class="space-y-4">
                                        <div
                                            v-for="workout in client.workouts"
                                            :key="workout.id"
                                            class="border dark:border-gray-700 rounded-xl overflow-hidden hover:border-emerald-300 dark:hover:border-emerald-600 transition-colors"
                                        >
                                            <div class="p-4">
                                                <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
                                                    <div class="flex-1">
                                                        <div class="flex items-center gap-2">
                                                            <h4 class="font-bold text-gray-900 dark:text-white">{{ workout.name }}</h4>
                                                            <span
                                                                v-if="isCompletedToday('workout', workout.id)"
                                                                class="bg-green-100 dark:bg-green-900/50 text-green-700 dark:text-green-300 text-xs px-2 py-0.5 rounded-full font-semibold"
                                                            >
                                                                ✓ Hecho
                                                            </span>
                                                        </div>
                                                        <p v-if="workout.description" class="text-sm text-gray-500 dark:text-gray-400 mt-1 line-clamp-1">{{ workout.description }}</p>
                                                        <div class="mt-2 flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
                                                            <span class="bg-gray-100 dark:bg-gray-700 px-2 py-1 rounded">
                                                                {{ workout.exercises?.length || 0 }} ejercicios
                                                            </span>
                                                        </div>
                                                    </div>
                                                    <div class="flex items-center gap-2">
                                                        <button
                                                            @click="selectedWorkout = selectedWorkout === workout.id ? null : workout.id"
                                                            class="px-3 py-2 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white border border-gray-200 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
                                                        >
                                                            {{ selectedWorkout === workout.id ? 'Ocultar' : 'Ver ejercicios' }}
                                                        </button>
                                                        <button
                                                            @click="markDone('workout', workout.id)"
                                                            :disabled="isCompletedToday('workout', workout.id)"
                                                            :class="[
                                                                'px-4 py-2 text-sm font-semibold rounded-lg transition-all',
                                                                isCompletedToday('workout', workout.id)
                                                                    ? 'bg-green-500 text-white cursor-default'
                                                                    : 'bg-emerald-600 hover:bg-emerald-700 text-white shadow-lg hover:shadow-emerald-500/25'
                                                            ]"
                                                        >
                                                            {{ isCompletedToday('workout', workout.id) ? '✓' : '¡Hecho!' }}
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>

                                            <!-- Expanded Exercise List -->
                                            <div v-if="selectedWorkout === workout.id" class="border-t border-gray-100 dark:border-gray-700 bg-gray-50 dark:bg-gray-700/30 p-4">
                                                <div class="space-y-3">
                                                    <div
                                                        v-for="(exercise, idx) in workout.exercises"
                                                        :key="exercise.id"
                                                        class="flex items-center gap-3 p-3 bg-white dark:bg-gray-800 rounded-lg"
                                                    >
                                                        <!-- GIF or Number -->
                                                        <div v-if="exercise.gif_url" class="w-14 h-14 rounded-lg overflow-hidden bg-gray-100 dark:bg-gray-700 flex-shrink-0">
                                                            <img :src="exercise.gif_url" :alt="exercise.name" class="w-full h-full object-cover" />
                                                        </div>
                                                        <div v-else class="w-10 h-10 bg-emerald-100 dark:bg-emerald-900/50 text-emerald-700 dark:text-emerald-400 rounded-lg flex items-center justify-center font-bold flex-shrink-0">
                                                            {{ idx + 1 }}
                                                        </div>

                                                        <div class="flex-1 min-w-0">
                                                            <h5 class="font-medium text-gray-900 dark:text-white text-sm truncate">{{ exercise.name }}</h5>
                                                            <p v-if="exercise.muscle_group" class="text-xs text-gray-500 dark:text-gray-400">{{ exercise.muscle_group }}</p>
                                                        </div>

                                                        <div class="flex items-center gap-4 text-center">
                                                            <div>
                                                                <p class="text-lg font-bold text-gray-900 dark:text-white">{{ exercise.pivot?.sets || exercise.sets || 3 }}</p>
                                                                <p class="text-[10px] text-gray-500 uppercase">Series</p>
                                                            </div>
                                                            <div>
                                                                <p class="text-lg font-bold text-gray-900 dark:text-white">{{ exercise.pivot?.reps || exercise.reps || '12' }}</p>
                                                                <p class="text-[10px] text-gray-500 uppercase">Reps</p>
                                                            </div>
                                                            <div>
                                                                <p class="text-lg font-bold text-gray-900 dark:text-white">{{ exercise.pivot?.rest_seconds || exercise.rest_seconds || 60 }}s</p>
                                                                <p class="text-[10px] text-gray-500 uppercase">Descanso</p>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                <a
                                                    :href="route('client.workout.pdf', workout.id)"
                                                    target="_blank"
                                                    class="mt-4 block text-center py-2 text-sm text-emerald-600 dark:text-emerald-400 hover:underline"
                                                >
                                                    📄 Descargar PDF
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                    <div v-else class="text-center py-12 bg-gray-50 dark:bg-gray-700/30 rounded-xl">
                                        <span class="text-4xl mb-3 block">💪</span>
                                        <p class="text-gray-500 dark:text-gray-400">No tienes rutinas asignadas aún</p>
                                        <p class="text-sm text-gray-400 dark:text-gray-500 mt-1">Tu coach te asignará una pronto</p>
                                    </div>
                                </div>
                            </div>

                            <!-- Active Meal Plans -->
                            <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 overflow-hidden">
                                <div class="px-4 py-3 sm:p-4 md:px-6 md:py-4 border-b border-gray-100 dark:border-gray-700 flex items-center justify-between">
                                    <h3 class="text-base sm:text-lg font-bold text-gray-900 dark:text-white flex items-center gap-2">
                                        <span>🥗</span> Mi Plan Nutricional
                                    </h3>
                                    <Link
                                        :href="route('client.meal-plan.index')"
                                        class="text-xs sm:text-sm text-emerald-600 dark:text-emerald-400 hover:underline font-medium whitespace-nowrap"
                                    >
                                        Ver todos →
                                    </Link>
                                </div>
                                <div class="p-3 sm:p-4 md:p-6">
                                    <div v-if="client?.mealPlans?.length || client?.meal_plans?.length" class="space-y-3 sm:space-y-4">
                                        <div
                                            v-for="plan in (client.mealPlans || client.meal_plans)"
                                            :key="plan.id"
                                            class="border dark:border-gray-700 rounded-xl overflow-hidden hover:border-blue-300 dark:hover:border-blue-600 transition-colors"
                                        >
                                            <div class="p-3 sm:p-4">
                                                <!-- Plan name + completed badge -->
                                                <div class="flex items-start justify-between gap-2 mb-2">
                                                    <h4 class="font-bold text-gray-900 dark:text-white text-sm sm:text-base leading-tight">{{ plan.name }}</h4>
                                                    <span
                                                        v-if="isCompletedToday('meal', plan.id)"
                                                        class="bg-green-100 dark:bg-green-900/50 text-green-700 dark:text-green-300 text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 rounded-full font-semibold whitespace-nowrap flex-shrink-0"
                                                    >
                                                        ✓ Hecho
                                                    </span>
                                                </div>

                                                <!-- Calories + Macros row -->
                                                <div class="flex items-center gap-2 sm:gap-3 mb-2">
                                                    <span class="text-sm sm:text-base font-bold text-blue-600 dark:text-blue-400">
                                                        {{ Math.round(plan.total_calories || 0) }} kcal
                                                    </span>
                                                </div>
                                                <div class="grid grid-cols-3 gap-1 sm:gap-2 text-[11px] sm:text-xs mb-3">
                                                    <span class="text-center px-1.5 py-1 bg-teal-50 dark:bg-teal-900/30 text-teal-600 dark:text-teal-400 rounded font-semibold">P: {{ Math.round(plan.total_protein || 0) }}g</span>
                                                    <span class="text-center px-1.5 py-1 bg-orange-50 dark:bg-orange-900/30 text-orange-600 dark:text-orange-400 rounded font-semibold">C: {{ Math.round(plan.total_carbs || 0) }}g</span>
                                                    <span class="text-center px-1.5 py-1 bg-purple-50 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400 rounded font-semibold">G: {{ Math.round(plan.total_fat || 0) }}g</span>
                                                </div>

                                                <!-- Diet Plans Preview -->
                                                <div v-if="plan.diet_plans?.length || plan.dietPlans?.length" class="flex flex-wrap gap-1.5 sm:gap-2 mb-3">
                                                    <span
                                                        v-for="dietPlan in (plan.diet_plans || plan.dietPlans || []).slice(0, 3)"
                                                        :key="dietPlan.id"
                                                        class="px-2 py-0.5 sm:py-1 bg-emerald-50 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300 rounded text-[10px] sm:text-xs font-medium"
                                                    >
                                                        📅 {{ dietPlan.name || 'Plan' }}
                                                    </span>
                                                </div>

                                                <!-- Action buttons - full width stack on mobile -->
                                                <div class="grid grid-cols-2 gap-2">
                                                    <button
                                                        @click="selectedMealPlan = selectedMealPlan === plan.id ? null : plan.id"
                                                        class="px-2 sm:px-3 py-2 text-xs sm:text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white border border-gray-200 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors text-center"
                                                    >
                                                        {{ selectedMealPlan === plan.id ? 'Ocultar' : 'Ver comidas' }}
                                                    </button>
                                                    <button
                                                        @click="markDone('meal', plan.id)"
                                                        :disabled="isCompletedToday('meal', plan.id)"
                                                        :class="[
                                                            'px-2 sm:px-4 py-2 text-xs sm:text-sm font-semibold rounded-lg transition-all text-center',
                                                            isCompletedToday('meal', plan.id)
                                                                ? 'bg-green-500 text-white cursor-default'
                                                                : 'bg-blue-600 hover:bg-blue-700 text-white shadow-lg hover:shadow-blue-500/25'
                                                        ]"
                                                    >
                                                        {{ isCompletedToday('meal', plan.id) ? '✓ Hecho' : '¡Hecho!' }}
                                                    </button>
                                                </div>
                                            </div>

                                            <!-- Expanded Diet Plans List -->
                                            <div v-if="selectedMealPlan === plan.id" class="border-t border-gray-100 dark:border-gray-700 bg-gray-50 dark:bg-gray-700/30 p-3 sm:p-4">
                                                <div v-if="plan.diet_plans?.length || plan.dietPlans?.length" class="space-y-3 sm:space-y-4">
                                                    <div
                                                        v-for="dietPlan in (plan.diet_plans || plan.dietPlans || [])"
                                                        :key="dietPlan.id"
                                                        class="bg-white dark:bg-gray-800 rounded-lg p-3 sm:p-4"
                                                    >
                                                        <h5 class="font-bold text-gray-900 dark:text-white mb-2 sm:mb-3 border-b-2 border-emerald-500 pb-2 text-sm sm:text-base">
                                                            📅 {{ dietPlan.name || 'Plan de Dieta' }}
                                                        </h5>
                                                        <div class="space-y-1.5 sm:space-y-2">
                                                            <div
                                                                v-for="item in (dietPlan.items || []).slice(0, 5)"
                                                                :key="item.id"
                                                                class="flex items-center justify-between p-2 bg-gray-50 dark:bg-gray-700/50 rounded gap-2"
                                                            >
                                                                <div class="flex items-center gap-2 min-w-0 flex-1">
                                                                    <span class="text-base sm:text-lg flex-shrink-0">🍽️</span>
                                                                    <div class="min-w-0">
                                                                        <p class="font-medium text-gray-900 dark:text-white text-xs sm:text-sm truncate">{{ item.food?.name || 'Alimento' }}</p>
                                                                        <p class="text-[10px] sm:text-xs text-gray-500 dark:text-gray-400">{{ formatQuantity(item) }}</p>
                                                                    </div>
                                                                </div>
                                                                <span class="text-xs sm:text-sm font-medium text-gray-600 dark:text-gray-400 whitespace-nowrap flex-shrink-0">{{ Math.round(item.calories != null ? parseFloat(item.calories) : ((item.food?.calories || 0) * ((item.quantity || 100) / 100))) }} kcal</span>
                                                            </div>
                                                            <p v-if="(dietPlan.items || []).length > 5" class="text-[10px] sm:text-xs text-gray-400 text-center">
                                                                +{{ (dietPlan.items || []).length - 5 }} más...
                                                            </p>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div v-else class="text-center py-4 text-gray-400 text-sm">
                                                    Sin planes de dieta configurados
                                                </div>
                                                <a
                                                    :href="route('client.meal-plan.pdf', plan.id)"
                                                    target="_blank"
                                                    class="mt-3 sm:mt-4 block text-center py-2 text-xs sm:text-sm text-blue-600 dark:text-blue-400 hover:underline"
                                                >
                                                    📄 Descargar PDF
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                    <div v-else class="text-center py-8 sm:py-12 bg-gray-50 dark:bg-gray-700/30 rounded-xl">
                                        <span class="text-3xl sm:text-4xl mb-3 block">🥗</span>
                                        <p class="text-sm text-gray-500 dark:text-gray-400">No tienes planes nutricionales asignados</p>
                                        <p class="text-xs text-gray-400 dark:text-gray-500 mt-1">Tu coach te asignará uno pronto</p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Right Column: Quick Actions & Progress -->
                        <div class="space-y-6">
                            <!-- Quick Weight Update -->
                            <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 p-4 md:p-6">
                                <h3 class="text-lg font-bold text-gray-900 dark:text-white mb-4 flex items-center gap-2">
                                    <span>⚖️</span> Actualizar Peso
                                </h3>
                                <form @submit.prevent="updateWeight" class="space-y-4">
                                    <div class="relative">
                                        <input
                                            type="number"
                                            step="0.1"
                                            v-model="weightForm.weight"
                                            class="w-full rounded-xl border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white text-center text-2xl font-bold py-4 focus:ring-emerald-500 focus:border-emerald-500"
                                            placeholder="70.0"
                                            required
                                        />
                                        <span class="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400 text-lg">kg</span>
                                    </div>
                                    <button
                                        type="submit"
                                        :disabled="weightForm.processing"
                                        class="w-full bg-emerald-600 hover:bg-emerald-700 text-white font-semibold py-3 rounded-xl transition-colors disabled:opacity-50"
                                    >
                                        {{ weightForm.processing ? 'Guardando...' : 'Guardar' }}
                                    </button>
                                </form>
                            </div>

                            <!-- Progress Photos -->
                            <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 p-4 md:p-6">
                                <div class="flex items-center justify-between mb-4">
                                    <h3 class="text-lg font-bold text-gray-900 dark:text-white flex items-center gap-2">
                                        <span>📸</span> Fotos de Progreso
                                    </h3>
                                    <button
                                        @click="showPhotoModal = true"
                                        class="text-sm text-emerald-600 dark:text-emerald-400 hover:underline font-medium"
                                    >
                                        + Nueva
                                    </button>
                                </div>
                                <div v-if="progress_photos?.length" class="grid grid-cols-3 gap-2">
                                    <div
                                        v-for="photo in progress_photos.slice(0, 6)"
                                        :key="photo.id"
                                        class="aspect-square rounded-lg overflow-hidden bg-gray-100 dark:bg-gray-700 relative group"
                                    >
                                        <!-- Si tiene ANTES y DESPUÉS, mostrar mini slider -->
                                        <div v-if="photo.after_image_path" class="relative w-full h-full">
                                            <!-- Imagen ANTES -->
                                            <div
                                                :class="['absolute inset-0 transition-opacity duration-300', dashboardPhotoSlides[photo.id] === 1 ? 'opacity-0' : 'opacity-100']"
                                            >
                                                <img :src="photo.image_path" alt="ANTES" class="w-full h-full object-cover" />
                                                <!-- Mini badge ANTES -->
                                                <div class="absolute top-1 left-1 bg-red-500 text-white px-2 py-0.5 rounded-full text-[10px] font-bold">
                                                    ANTES
                                                </div>
                                            </div>

                                            <!-- Imagen DESPUÉS -->
                                            <div
                                                :class="['absolute inset-0 transition-opacity duration-300', dashboardPhotoSlides[photo.id] === 1 ? 'opacity-100' : 'opacity-0']"
                                            >
                                                <img :src="photo.after_image_path" alt="DESPUÉS" class="w-full h-full object-cover" />
                                                <!-- Mini badge DESPUÉS -->
                                                <div class="absolute top-1 left-1 bg-emerald-500 text-white px-2 py-0.5 rounded-full text-[10px] font-bold">
                                                    DESPUÉS
                                                </div>
                                            </div>

                                            <!-- Mini indicadores -->
                                            <div class="absolute bottom-1 left-1/2 transform -translate-x-1/2 flex gap-1">
                                                <div
                                                    v-for="i in 2"
                                                    :key="i"
                                                    @click="dashboardPhotoSlides[photo.id] = i - 1"
                                                    :class="[
                                                        'w-4 h-0.5 rounded-full transition-all cursor-pointer',
                                                        (dashboardPhotoSlides[photo.id] === (i - 1) || (!dashboardPhotoSlides[photo.id] && i === 1)) ? 'bg-white' : 'bg-white/50'
                                                    ]"
                                                ></div>
                                            </div>

                                            <!-- Hover effect para cambiar automáticamente -->
                                            <div
                                                @mouseenter="dashboardPhotoSlides[photo.id] = 1"
                                                @mouseleave="dashboardPhotoSlides[photo.id] = 0"
                                                class="absolute inset-0"
                                            ></div>
                                        </div>

                                        <!-- Si solo tiene ANTES -->
                                        <img v-else :src="photo.image_path" alt="Progreso" class="w-full h-full object-cover" />
                                    </div>
                                </div>
                                <div v-else class="text-center py-8 bg-gray-50 dark:bg-gray-700/30 rounded-xl">
                                    <span class="text-3xl mb-2 block">📷</span>
                                    <p class="text-sm text-gray-500 dark:text-gray-400">Sube tu primera foto</p>
                                </div>
                                <Link
                                    :href="route('client.photos.index')"
                                    class="mt-4 block text-center py-2 text-sm text-emerald-600 dark:text-emerald-400 hover:underline"
                                >
                                    Ver todas las fotos →
                                </Link>
                            </div>

                            <!-- Stats Summary -->
                            <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 p-4 md:p-6">
                                <h3 class="text-lg font-bold text-gray-900 dark:text-white mb-4 flex items-center gap-2">
                                    <span>🏆</span> Tu Progreso Total
                                </h3>
                                <div class="space-y-4">
                                    <div class="flex items-center justify-between">
                                        <span class="text-sm text-gray-500 dark:text-gray-400">Entrenos completados</span>
                                        <span class="text-lg font-bold text-emerald-600 dark:text-emerald-400">{{ statsData.total_workouts_completed }}</span>
                                    </div>
                                    <div class="flex items-center justify-between">
                                        <span class="text-sm text-gray-500 dark:text-gray-400">Comidas completadas</span>
                                        <span class="text-lg font-bold text-blue-600 dark:text-blue-400">{{ statsData.total_meals_completed }}</span>
                                    </div>
                                    <div class="flex items-center justify-between">
                                        <span class="text-sm text-gray-500 dark:text-gray-400">TMB (Metabolismo basal)</span>
                                        <span class="text-lg font-bold text-gray-900 dark:text-white">{{ statsData.bmr ? Math.round(statsData.bmr) : '-' }} kcal</span>
                                    </div>
                                </div>
                                <Link
                                    :href="route('client.progress.index')"
                                    class="mt-4 block text-center py-3 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-xl text-sm font-medium text-gray-700 dark:text-gray-300 transition-colors"
                                >
                                    Ver historial completo →
                                </Link>
                            </div>

                            <!-- Quick Links -->
                            <div class="grid grid-cols-2 gap-3">
                                <Link
                                    :href="route('client.profile.index')"
                                    class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 p-4 text-center hover:border-emerald-300 dark:hover:border-emerald-600 transition-colors"
                                >
                                    <span class="text-2xl mb-2 block">👤</span>
                                    <span class="text-sm font-medium text-gray-700 dark:text-gray-300">Mi Perfil</span>
                                </Link>
                                <Link
                                    :href="route('client.chat.index')"
                                    class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 p-4 text-center hover:border-emerald-300 dark:hover:border-emerald-600 transition-colors relative"
                                >
                                    <span class="text-2xl mb-2 block">💬</span>
                                    <span class="text-sm font-medium text-gray-700 dark:text-gray-300">Chat</span>
                                    <span
                                        v-if="statsData.unread_messages"
                                        class="absolute top-2 right-2 w-5 h-5 bg-red-500 text-white text-xs rounded-full flex items-center justify-center"
                                    >
                                        {{ statsData.unread_messages }}
                                    </span>
                                </Link>
                            </div>
                        </div>
                    </div>

                    <!-- Featured Products Widget -->
                    <FeaturedProductsWidget routePrefix="client" />
                </template>
            </div>
        </div>

        <!-- Photo Upload Modal -->
        <Teleport to="body">
            <div
                v-if="showPhotoModal"
                class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
                @click.self="showPhotoModal = false"
            >
                <div class="bg-white dark:bg-gray-800 rounded-2xl shadow-xl w-full max-w-md overflow-hidden">
                    <div class="p-6 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
                        <h3 class="text-lg font-bold text-gray-900 dark:text-white">📸 Subir foto de progreso</h3>
                        <button @click="showPhotoModal = false" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
                            <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="M6 18L18 6M6 6l12 12" />
                            </svg>
                        </button>
                    </div>
                    <form @submit.prevent="uploadPhoto" class="p-6 space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Foto</label>
                            <input
                                type="file"
                                accept="image/*"
                                @change="photoForm.image = $event.target.files[0]"
                                class="w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-emerald-50 file:text-emerald-700 hover:file:bg-emerald-100"
                                required
                            />
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Tipo</label>
                            <select
                                v-model="photoForm.type"
                                class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                            >
                                <option value="front">Frontal</option>
                                <option value="side">Lateral</option>
                                <option value="back">Espalda</option>
                            </select>
                        </div>
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Peso (kg)</label>
                                <input
                                    type="number"
                                    step="0.1"
                                    v-model="photoForm.weight"
                                    class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                                />
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Fecha</label>
                                <input
                                    type="date"
                                    v-model="photoForm.date"
                                    class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                                    required
                                />
                            </div>
                        </div>
                        <button
                            type="submit"
                            :disabled="photoForm.processing"
                            class="w-full bg-emerald-600 hover:bg-emerald-700 text-white font-semibold py-3 rounded-xl transition-colors disabled:opacity-50"
                        >
                            {{ photoForm.processing ? 'Subiendo...' : 'Subir foto' }}
                        </button>
                    </form>
                </div>
            </div>
        </Teleport>
        </PullToRefresh>
    </ClientLayout>
</template>
