<script setup>
/**
 * Coach Create Meal Plan - Multiple Diet Plans Support
 * Tab 1: Plan De Dieta (Plan settings, days, macros, calories)
 * Tab 2: Comidas (Meal blocks with foods)
 * 
 * Supports creating multiple diet plans per meal plan
 */
import CoachLayout from '@/Layouts/CoachLayout.vue';
import { Head, Link, useForm } from '@inertiajs/vue3';
import { ref, computed, watch } from 'vue';

const props = defineProps({
    client: Object,
    foods: Array,
    mealTypes: Object,
});

const form = useForm({
    name: '',
    description: '',
    notes: '',
    is_active: true,
    diet_plans: [],
});

// Multi-plan support
const dietPlans = ref([]);
const activePlanIndex = ref(0);

// Calculate initial macros from client data
const calculateInitialMacros = () => {
    const macros = props.client?.macros;
    const tdee = props.client?.tdee || props.client?.calculated_tdee || 2000;
    const calorieAdj = props.client?.calorie_adjustment || 0;
    const adjustedCals = Math.round(tdee * (1 + calorieAdj / 100));
    
    if (macros) {
        // Calculate percentages from grams
        const proteinPercent = Math.round((macros.protein * 4 / adjustedCals) * 100);
        const fatPercent = Math.round((macros.fats * 9 / adjustedCals) * 100);
        const carbPercent = Math.round((macros.carbs * 4 / adjustedCals) * 100);
        
        return {
            protein_percent: proteinPercent || 30,
            fat_percent: fatPercent || 25,
            carb_percent: carbPercent || 45,
        };
    }
    
    // Default percentages if no client macros available
    return {
        protein_percent: 30,
        fat_percent: 25,
        carb_percent: 45,
    };
};

// Initialize with one empty diet plan
const initDietPlan = () => {
    const initialMacros = calculateInitialMacros();
    return {
        name: '',
        description: '',
        days: [],
        use_percentages: true,
        protein_percent: initialMacros.protein_percent,
        fat_percent: initialMacros.fat_percent,
        carb_percent: initialMacros.carb_percent,
        calorie_adjustment: props.client?.calorie_adjustment || 0,
        mealBlocks: [],
    };
};

// Initialize first plan
if (dietPlans.value.length === 0) {
    dietPlans.value.push(initDietPlan());
}

// Tabs
const activeTab = ref('plan'); // 'plan' or 'comidas'

// Sincronizar form.name con el nombre del primer plan
watch(() => dietPlans.value[0]?.name, (newName) => {
    if (newName) {
        form.name = newName;
    }
}, { immediate: true });

// Inicializar bloque predeterminado cuando se cambia a pestaña Comidas
watch(activeTab, (newTab) => {
    if (newTab === 'comidas') {
        const plan = dietPlans.value[activePlanIndex.value];
        // Solo crear bloque predeterminado si:
        // 1. No hay bloques existentes
        // 2. No hay bloque activo
        if (plan.mealBlocks.length === 0 && activeBlockIndex.value === null) {
            // Crear bloque "Comida 1" predeterminado - listo para seleccionar tipo
            currentBlock.value = { mealType: '', items: [] };
            configStep.value = 1;
        }
    }
});

// Days
const weekDays = [
    { key: 'DOM', label: 'Domingo' },
    { key: 'LUN', label: 'Lunes' },
    { key: 'MAR', label: 'Martes' },
    { key: 'MIE', label: 'Miércoles' },
    { key: 'JUE', label: 'Jueves' },
    { key: 'VIE', label: 'Viernes' },
    { key: 'SAB', label: 'Sábado' },
];

const currentPlan = computed(() => dietPlans.value[activePlanIndex.value] || initDietPlan());

const toggleDay = (day) => {
    const plan = dietPlans.value[activePlanIndex.value];
    const idx = plan.days.indexOf(day);
    if (idx > -1) {
        plan.days.splice(idx, 1);
    } else {
        plan.days.push(day);
    }
};

// TDEE & Calorie calculations
const clientTdee = computed(() => {
    const tdee = props.client?.tdee || props.client?.calculated_tdee || 2000;
    return Math.round(Number(tdee));
});

const calorieAdjustment = computed(() => {
    const adjustment = clientTdee.value * (currentPlan.value.calorie_adjustment / 100);
    return Math.round(Number(adjustment));
});

const adjustedCalories = computed(() => {
    const result = clientTdee.value + calorieAdjustment.value;
    return Math.round(Number(result));
});

// Calorie adjustment label
const calorieAdjustmentLabel = computed(() => {
    if (currentPlan.value.calorie_adjustment > 0) return 'Superávit Calórico';
    if (currentPlan.value.calorie_adjustment < 0) return 'Déficit Calórico';
    return 'Mantenimiento';
});

// Slider gradient position
const sliderGradient = computed(() => {
    const percent = (currentPlan.value.calorie_adjustment + 100) / 2;
    return `linear-gradient(to right, #10b981 0%, #10b981 ${percent}%, #e5e7eb ${percent}%, #e5e7eb 100%)`;
});

// Macro calculations from percentages
const targetProtein = computed(() => {
    if (currentPlan.value.use_percentages) {
        const calories = adjustedCalories.value || 2000;
        const percent = Number(currentPlan.value.protein_percent) || 0;
        return Math.round((calories * (percent / 100)) / 4);
    } else {
        return Math.round(Number(currentPlan.value.protein_percent) || 0);
    }
});

const targetFat = computed(() => {
    if (currentPlan.value.use_percentages) {
        const calories = adjustedCalories.value || 2000;
        const percent = Number(currentPlan.value.fat_percent) || 0;
        return Math.round((calories * (percent / 100)) / 9);
    } else {
        return Math.round(Number(currentPlan.value.fat_percent) || 0);
    }
});

const targetCarbs = computed(() => {
    if (currentPlan.value.use_percentages) {
        const calories = adjustedCalories.value || 2000;
        const percent = Number(currentPlan.value.carb_percent) || 0;
        return Math.round((calories * (percent / 100)) / 4);
    } else {
        return Math.round(Number(currentPlan.value.carb_percent) || 0);
    }
});

// Calculate percentages from grams (when use_percentages is false)
const proteinPercentFromGrams = computed(() => {
    if (!currentPlan.value.use_percentages) {
        const grams = Number(currentPlan.value.protein_percent) || 0;
        if (grams > 0) {
            const calories = grams * 4;
            const totalCals = adjustedCalories.value || 2000;
            return Math.round((calories / totalCals) * 100);
        }
    }
    return 0;
});

const fatPercentFromGrams = computed(() => {
    if (!currentPlan.value.use_percentages) {
        const grams = Number(currentPlan.value.fat_percent) || 0;
        if (grams > 0) {
            const calories = grams * 9;
            const totalCals = adjustedCalories.value || 2000;
            return Math.round((calories / totalCals) * 100);
        }
    }
    return 0;
});

const carbsPercentFromGrams = computed(() => {
    if (!currentPlan.value.use_percentages) {
        const grams = Number(currentPlan.value.carb_percent) || 0;
        if (grams > 0) {
            const calories = grams * 4;
            const totalCals = adjustedCalories.value || 2000;
            return Math.round((calories / totalCals) * 100);
        }
    }
    return 0;
});

// Auto-recalculate macros based on toggle
const recalculateMacros = (macroType) => {
    // Force Vue to recalculate computed properties
    // The computed properties will automatically update based on use_percentages
    if (currentPlan.value.use_percentages) {
        // When in percentage mode, ensure valid percentages
        if (macroType === 'protein' && !currentPlan.value.protein_percent) {
            currentPlan.value.protein_percent = 30;
        }
        if (macroType === 'fat' && !currentPlan.value.fat_percent) {
            currentPlan.value.fat_percent = 25;
        }
        if (macroType === 'carbs' && !currentPlan.value.carb_percent) {
            currentPlan.value.carb_percent = 45;
        }
    } else {
        // When in grams mode, calculate from percentages if not set
        if (macroType === 'protein' && !currentPlan.value.protein_percent) {
            currentPlan.value.protein_percent = targetProtein.value;
        }
        if (macroType === 'fat' && !currentPlan.value.fat_percent) {
            currentPlan.value.fat_percent = targetFat.value;
        }
        if (macroType === 'carbs' && !currentPlan.value.carb_percent) {
            currentPlan.value.carb_percent = targetCarbs.value;
        }
    }
};

// Meal blocks for Comidas tab
const activeBlockIndex = ref(null);
const configStep = ref(1);

const currentBlock = ref({
    mealType: 'desayuno',
    items: [],
});

const foodSearch = ref('');
const showFoodList = ref(false);

const filteredFoods = computed(() => {
    if (!props.foods) return [];
    return props.foods.filter(f => {
        return !foodSearch.value || f.name.toLowerCase().includes(foodSearch.value.toLowerCase());
    });
});

// Format number without unnecessary decimals
const formatNumber = (num) => {
    const rounded = Math.round(num * 100) / 100;
    return rounded % 1 === 0 ? Math.round(rounded) : rounded;
};

const getBlockMacros = (block) => {
    return block.items.reduce((acc, item) => {
        const mult = (item.quantity || 100) / 100;
        acc.calories += (item.calories || 0) * mult;
        acc.proteins += (item.proteins || 0) * mult;
        acc.carbs += (item.carbs || 0) * mult;
        acc.fats += (item.fats || 0) * mult;
        return acc;
    }, { calories: 0, proteins: 0, carbs: 0, fats: 0 });
};

const currentBlockMacros = computed(() => getBlockMacros(currentBlock.value));

const totalMacros = computed(() => {
    const plan = dietPlans.value[activePlanIndex.value];
    if (!plan || !plan.mealBlocks) return { calories: 0, proteins: 0, carbs: 0, fats: 0 };
    
    // Sumar macros de bloques guardados
    const savedBlocksMacros = plan.mealBlocks.reduce((acc, block) => {
        // Solo sumar si no es el bloque que estamos editando actualmente
        if (activeBlockIndex.value !== null && plan.mealBlocks.indexOf(block) === activeBlockIndex.value) {
            return acc; // Skip el bloque en edición para evitar duplicados
        }
        const m = getBlockMacros(block);
        acc.calories += m.calories;
        acc.proteins += m.proteins;
        acc.carbs += m.carbs;
        acc.fats += m.fats;
        return acc;
    }, { calories: 0, proteins: 0, carbs: 0, fats: 0 });
    
    // Agregar macros del bloque actual (en edición)
    if (currentBlock.value && currentBlock.value.items && currentBlock.value.items.length > 0) {
        const currentMacros = getBlockMacros(currentBlock.value);
        savedBlocksMacros.calories += currentMacros.calories;
        savedBlocksMacros.proteins += currentMacros.proteins;
        savedBlocksMacros.carbs += currentMacros.carbs;
        savedBlocksMacros.fats += currentMacros.fats;
    }
    
    return savedBlocksMacros;
});

const caloriePercentage = computed(() => Math.min(100, Math.round((totalMacros.value.calories / adjustedCalories.value) * 100)));

const addBlock = () => {
    activeBlockIndex.value = null;
    currentBlock.value = { mealType: '', items: [] };
    configStep.value = 1;
};

const editBlock = (index) => {
    activeBlockIndex.value = index;
    currentBlock.value = JSON.parse(JSON.stringify(currentPlan.value.mealBlocks[index]));
    configStep.value = 2;
};

const deleteBlock = (index) => {
    currentPlan.value.mealBlocks.splice(index, 1);
    if (activeBlockIndex.value === index) {
        activeBlockIndex.value = null;
        currentBlock.value = { mealType: 'desayuno', items: [] };
        configStep.value = 1;
    }
};

const addFoodToBlock = (food) => {
    const exists = currentBlock.value.items.find(i => i.food_id === food.id);
    if (!exists) {
        currentBlock.value.items.push({
            food_id: food.id,
            food_name: food.name,
            serving_size: food.serving_size,
            serving_weight: food.serving_weight,
            quantity: food.serving_weight || 100,
            unit: food.serving_unit || 'g',
            calories: food.calories,
            proteins: food.proteins,
            carbs: food.carbs,
            fats: food.fats,
        });
    }
    // Cerrar dropdown automáticamente después de seleccionar
    showFoodList.value = false;
    foodSearch.value = '';
};

const removeFoodFromBlock = (index) => {
    currentBlock.value.items.splice(index, 1);
};

// Handle unit change - adjust quantity based on unit type
const onUnitChange = (item) => {
    // When changing to non-gram units, default to 1 if currently in grams
    const nonGramUnits = ['unidad', 'unidades', 'taza', '1/2 taza', '1/4 taza', 'cucharada', 'cucharadita', 'scoop', 'batida', 'slice', 'mediana', 'pequeña', 'grande', 'porcion', 'vaso', 'vasos'];
    
    if (nonGramUnits.includes(item.unit)) {
        // If switching from grams to a unit-based measurement, default to 1
        if (item.quantity > 10) {
            item.quantity = 1;
        }
    } else if (item.unit === 'g') {
        // If switching back to grams, use serving_weight or default 100
        item.quantity = item.serving_weight || 100;
    } else if (item.unit === 'oz') {
        item.quantity = item.serving_weight ? Math.round(item.serving_weight / 28.35) : 3.5;
    } else if (item.unit === 'ml') {
        item.quantity = item.serving_weight || 100;
    }
};

const clearCurrentBlockFoods = () => {
    currentBlock.value.items = [];
};

const saveBlock = () => {
    if (currentBlock.value.items.length === 0) return;
    const blockData = JSON.parse(JSON.stringify(currentBlock.value));
    const plan = dietPlans.value[activePlanIndex.value];
    if (activeBlockIndex.value !== null) {
        plan.mealBlocks[activeBlockIndex.value] = blockData;
    } else {
        plan.mealBlocks.push(blockData);
    }
    activeBlockIndex.value = null;
    currentBlock.value = { mealType: 'desayuno', items: [] };
    configStep.value = 1;
};

const proceedToFoods = () => {
    configStep.value = 2;
};

// Auto-avanzar al paso 2 cuando se selecciona el tipo de comida
watch(() => currentBlock.value.mealType, (newType) => {
    if (newType && configStep.value === 1) {
        configStep.value = 2;
    }
});

// Auto-guardar cuando hay alimentos en el bloque actual
watch(() => currentBlock.value.items.length, (newLength) => {
    if (newLength > 0 && activeBlockIndex.value === null) {
        // Auto-guardar nuevo bloque cuando se agregan alimentos
        const blockData = JSON.parse(JSON.stringify(currentBlock.value));
        const plan = dietPlans.value[activePlanIndex.value];
        plan.mealBlocks.push(blockData);
        activeBlockIndex.value = plan.mealBlocks.length - 1;
    } else if (newLength > 0 && activeBlockIndex.value !== null) {
        // Actualizar bloque existente
        const blockData = JSON.parse(JSON.stringify(currentBlock.value));
        const plan = dietPlans.value[activePlanIndex.value];
        plan.mealBlocks[activeBlockIndex.value] = blockData;
    }
});

const getMealTypeLabel = (type) => props.mealTypes?.[type] || type;

// Multi-plan functions
const addDietPlan = () => {
    dietPlans.value.push(initDietPlan());
    activePlanIndex.value = dietPlans.value.length - 1;
    activeTab.value = 'plan';
};

const deleteDietPlan = (index) => {
    if (dietPlans.value.length <= 1) return;
    dietPlans.value.splice(index, 1);
    if (activePlanIndex.value >= dietPlans.value.length) {
        activePlanIndex.value = dietPlans.value.length - 1;
    }
};

const selectPlan = (index) => {
    activePlanIndex.value = index;
    activeBlockIndex.value = null;
    currentBlock.value = { mealType: 'desayuno', items: [] };
    configStep.value = 1;
};

// Check if all plans have required data
const canSubmit = computed(() => {
    // Validar que el plan principal tenga nombre
    const planName = dietPlans.value[0]?.name;
    if (!planName) return false;
    
    // Si estamos en la pestaña 'plan', solo validar el nombre
    if (activeTab.value === 'plan') {
        return true;
    }
    
    // Si estamos en la pestaña 'comidas', validar que tenga al menos un bloque con alimentos
    return dietPlans.value.every(plan => {
        if (!plan.name) return false;
        // Verificar que tenga al menos un bloque con alimentos
        const hasItems = plan.mealBlocks.some(block => block.items && block.items.length > 0);
        return hasItems;
    });
});

const submit = () => {
    // Asegurar que el nombre del formulario esté sincronizado
    form.name = dietPlans.value[0]?.name || '';
    
    // Transform dietPlans to the format expected by the backend
    form.diet_plans = dietPlans.value.map(plan => {
        // Filtrar bloques vacíos y asegurar que meal_type tenga valor
        const validBlocks = plan.mealBlocks.filter(block => 
            block.items && block.items.length > 0 && block.mealType
        );
        
        return {
            name: plan.name,
            description: plan.description,
            days: plan.days,
            use_percentages: plan.use_percentages,
            protein_percent: plan.protein_percent,
            fat_percent: plan.fat_percent,
            carb_percent: plan.carb_percent,
            calorie_adjustment: plan.calorie_adjustment,
            meal_items: validBlocks.flatMap(block => 
                block.items.map(item => ({
                    food_id: item.food_id,
                    meal_type: block.mealType,
                    quantity: item.quantity,
                    unit: item.unit || 'g',
                }))
            ),
        };
    });
    
    form.post(route('coach.clients.meal-plans.store', props.client.id));
};
</script>

<template>
    <Head :title="`Crear Dieta - ${client.name}`" />

    <CoachLayout>
        <template #header>
            <div class="flex items-center justify-between">
                <div class="flex items-center gap-4">
                    <Link :href="route('coach.clients.meal-plans.index', client.id)"
                        class="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
                        </svg>
                    </Link>
                    <div>
                        <h2 class="text-xl font-bold text-gray-900 dark:text-white">🥗 Nueva Dieta</h2>
                        <p class="text-sm text-gray-500">{{ client.name }}</p>
                    </div>
                </div>
            </div>
        </template>

        <div class="py-6">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                
                <!-- Tabs -->
                <div class="flex justify-center mb-6">
                    <div class="inline-flex bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-1">
                        <button 
                            @click="activeTab = 'plan'"
                            :class="['px-8 py-3 rounded-lg font-medium transition-all', activeTab === 'plan' ? 'bg-green-500 text-white shadow' : 'text-gray-600 hover:text-gray-900']"
                        >
                            Plan De Dieta
                        </button>
                        <button 
                            @click="activeTab = 'comidas'"
                            :class="['px-8 py-3 rounded-lg font-medium transition-all', activeTab === 'comidas' ? 'bg-green-500 text-white shadow' : 'text-gray-600 hover:text-gray-900']"
                        >
                            Comidas
                        </button>
                    </div>
                </div>

                <!-- Tab 1: Plan De Dieta -->
                <div v-if="activeTab === 'plan'" class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 p-6">
                    
                    <!-- Plan Name -->
                    <div class="mb-6">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Nombre del Plan *</label>
                        <input 
                            v-model="currentPlan.name" 
                            type="text" 
                            placeholder="Ej: Día de entrenamiento, Día de descanso, etc."
                            class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                        />
                    </div>

                    <!-- Days Selector -->
                    <div class="mb-6">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Repetir los días</label>
                        <div class="flex flex-wrap gap-2">
                            <button 
                                v-for="day in weekDays" 
                                :key="day.key"
                                @click="toggleDay(day.key)"
                                :class="[
                                    'px-4 py-2 rounded-lg font-medium text-sm transition-all',
                                    currentPlan.days.includes(day.key) 
                                        ? 'bg-gray-800 text-white' 
                                        : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                                ]"
                            >
                                {{ day.key }}
                            </button>
                        </div>
                    </div>

                    <!-- Percentage Toggle -->
                    <div class="mb-6 flex items-center gap-4">
                        <label class="relative inline-flex items-center cursor-pointer">
                            <input type="checkbox" v-model="currentPlan.use_percentages" class="sr-only peer">
                            <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-green-600"></div>
                        </label>
                        <div>
                            <span class="font-medium text-gray-900 dark:text-white">Cálculo por porcentajes</span>
                            <p class="text-sm text-gray-500">Desactiva para calcular por gramos directamente</p>
                        </div>
                    </div>

                    <!-- Macro Inputs (always visible, label changes based on toggle) -->
                    <div class="grid grid-cols-3 gap-4 mb-6">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2 flex items-center gap-1">
                                Proteínas {{ currentPlan.use_percentages ? '(%)' : '(g)' }}
                                <button type="button" @click="recalculateMacros('protein')" class="text-blue-500 hover:text-blue-600 text-lg" title="Actualizar">
                                    🔄
                                </button>
                            </label>
                            <input 
                                v-model.number="currentPlan.protein_percent" 
                                type="number" 
                                :min="0"
                                :max="currentPlan.use_percentages ? 100 : 1000"
                                :step="currentPlan.use_percentages ? 1 : 1"
                                class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white text-lg"
                            />
                            <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">
                                {{ currentPlan.use_percentages ? `${targetProtein} g` : `${proteinPercentFromGrams}%` }}
                            </p>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2 flex items-center gap-1">
                                Grasas {{ currentPlan.use_percentages ? '(%)' : '(g)' }}
                                <button type="button" @click="recalculateMacros('fat')" class="text-blue-500 hover:text-blue-600 text-lg" title="Actualizar">
                                    🔄
                                </button>
                            </label>
                            <input 
                                v-model.number="currentPlan.fat_percent" 
                                type="number" 
                                :min="0"
                                :max="currentPlan.use_percentages ? 100 : 1000"
                                :step="currentPlan.use_percentages ? 1 : 1"
                                class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white text-lg"
                            />
                            <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">
                                {{ currentPlan.use_percentages ? `${targetFat} g` : `${fatPercentFromGrams}%` }}
                            </p>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2 flex items-center gap-1">
                                Carbohidratos {{ currentPlan.use_percentages ? '(%)' : '(g)' }}
                                <button type="button" @click="recalculateMacros('carbs')" class="text-blue-500 hover:text-blue-600 text-lg" title="Actualizar">
                                    🔄
                                </button>
                            </label>
                            <input 
                                v-model.number="currentPlan.carb_percent" 
                                type="number" 
                                :min="0"
                                :max="currentPlan.use_percentages ? 100 : 1000"
                                :step="currentPlan.use_percentages ? 1 : 1"
                                class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white text-lg"
                            />
                            <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">
                                {{ currentPlan.use_percentages ? `${targetCarbs} g` : `${carbsPercentFromGrams}%` }}
                            </p>
                        </div>
                    </div>

                    <!-- Calorie Adjustment Slider (Widget completo como en /coach/clients/create) -->
                    <div class="bg-gradient-to-br from-green-50 to-emerald-50 dark:from-green-900/20 dark:to-emerald-900/20 rounded-xl p-5 border border-green-200 dark:border-green-700">
                        <div class="flex items-center justify-between mb-3">
                            <label class="text-sm font-medium text-gray-700 dark:text-gray-300 flex items-center gap-2">
                                Ajuste de calorías
                                <span class="inline-flex items-center justify-center w-4 h-4 text-xs text-gray-400 border border-gray-300 rounded-full cursor-help" title="Ajusta las calorías según las necesidades específicas del cliente">ⓘ</span>
                            </label>
                            <div class="flex items-center gap-2">
                                <span v-if="currentPlan.calorie_adjustment !== 0" :class="[
                                    'text-xs font-medium px-2 py-1 rounded-full flex items-center gap-1',
                                    currentPlan.calorie_adjustment > 0 ? 'bg-green-100 text-green-700 dark:bg-green-800 dark:text-green-300' : 'bg-red-100 text-red-700 dark:bg-red-800 dark:text-red-300'
                                ]">
                                    <span>→</span>
                                    {{ calorieAdjustmentLabel }}
                                </span>
                                <span class="text-lg font-bold" :class="[
                                    currentPlan.calorie_adjustment > 0 ? 'text-green-600' : currentPlan.calorie_adjustment < 0 ? 'text-red-600' : 'text-gray-700'
                                ]">{{ currentPlan.calorie_adjustment > 0 ? '+' : '' }}{{ currentPlan.calorie_adjustment }}%</span>
                            </div>
                        </div>
                        
                        <!-- Slider -->
                        <div class="relative mt-2 mb-3">
                            <input 
                                type="range" 
                                v-model.number="currentPlan.calorie_adjustment"
                                min="-100" 
                                max="100" 
                                step="1"
                                class="w-full h-3 rounded-lg appearance-none cursor-pointer slider-green"
                                :style="{ background: sliderGradient }"
                            />
                            <div class="flex justify-between text-xs text-gray-500 dark:text-gray-400 mt-2">
                                <span class="text-red-500">-100%</span>
                                <span class="text-gray-400">0%</span>
                                <span class="text-green-500">+100%</span>
                            </div>
                        </div>
                        
                        <!-- TDEE Info Table -->
                        <div class="mt-4 bg-white dark:bg-gray-800 rounded-lg p-4 shadow-sm">
                            <div class="space-y-3">
                                <div class="flex justify-between items-center py-2 border-b border-gray-100 dark:border-gray-700">
                                    <span class="text-sm text-gray-600 dark:text-gray-400">TDEE:</span>
                                    <span class="font-semibold text-gray-900 dark:text-white">{{ clientTdee }} kcal</span>
                                </div>
                                <div class="flex justify-between items-center py-2 border-b border-gray-100 dark:border-gray-700">
                                    <span class="text-sm text-gray-600 dark:text-gray-400">Ajuste:</span>
                                    <span :class="[
                                        'font-semibold',
                                        calorieAdjustment > 0 ? 'text-green-600' : calorieAdjustment < 0 ? 'text-red-600' : 'text-gray-600'
                                    ]">
                                        {{ calorieAdjustment > 0 ? '+' : '' }}{{ calorieAdjustment }} kcal
                                    </span>
                                </div>
                                <div class="flex justify-between items-center pt-2">
                                    <span class="font-medium text-gray-700 dark:text-gray-300">Calorías:</span>
                                    <span class="font-bold text-xl text-green-600 dark:text-green-400">{{ adjustedCalories }} kcal</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Action Buttons for Plan De Dieta Tab -->
                    <div class="mt-8 flex justify-between items-center">
                        <Link 
                            :href="`/coach/clients/${client.id}`"
                            class="px-6 py-3 bg-gray-100 hover:bg-gray-200 text-gray-700 font-semibold rounded-lg"
                        >
                            Cancelar
                        </Link>
                        <button 
                            @click="activeTab = 'comidas'"
                            :disabled="!currentPlan.name"
                            class="px-6 py-3 bg-gradient-to-r from-green-500 to-emerald-600 hover:from-green-600 hover:to-emerald-700 text-white font-semibold rounded-lg disabled:opacity-50 shadow-lg"
                        >
                            Crear Plan de Dieta →
                        </button>
                    </div>
                </div>

                <!-- Tab 2: Comidas -->
                <div v-if="activeTab === 'comidas'">
                    <!-- Two Panel Layout -->
                    <div class="grid grid-cols-1 lg:grid-cols-12 gap-6">
                        <!-- Left Panel -->
                        <div class="lg:col-span-5 space-y-4">
                            <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-5 py-4 border-b border-gray-100 dark:border-gray-700">
                                    <h3 class="font-semibold text-gray-900 dark:text-white">Bloques de comida</h3>
                                    <p class="text-xs text-gray-500">{{ currentPlan.name || 'Plan actual' }}</p>
                                </div>
                                <div class="p-4 space-y-3">
                                    <!-- Bloques guardados -->
                                    <div 
                                        v-for="(block, index) in currentPlan.mealBlocks" 
                                        :key="index"
                                        :class="['relative p-4 rounded-xl border-2 cursor-pointer group', activeBlockIndex === index ? 'border-green-500 bg-green-50 dark:bg-green-900/20' : 'border-gray-200 dark:border-gray-700 hover:border-green-300']"
                                        @click="editBlock(index)"
                                    >
                                        <div class="flex items-start gap-3">
                                            <div class="w-8 h-8 rounded-full bg-gradient-to-br from-green-500 to-emerald-600 flex items-center justify-center text-white font-bold text-sm">{{ index + 1 }}</div>
                                            <div class="flex-1">
                                                <h4 class="font-semibold text-gray-900 dark:text-white">{{ block.mealType ? getMealTypeLabel(block.mealType) : `Comida ${index + 1}` }}</h4>
                                                <p class="text-sm text-gray-500">{{ block.items.length }} alimentos{{ block.items.length > 0 ? ` • ${Math.round(getBlockMacros(block).calories)} kcal` : '' }}</p>
                                                <div v-if="block.items.length > 0" class="flex gap-2 mt-2">
                                                    <span class="px-2 py-0.5 bg-red-100 text-red-700 text-xs rounded">P: {{ Math.round(getBlockMacros(block).proteins) }}g</span>
                                                    <span class="px-2 py-0.5 bg-amber-100 text-amber-700 text-xs rounded">C: {{ Math.round(getBlockMacros(block).carbs) }}g</span>
                                                    <span class="px-2 py-0.5 bg-blue-100 text-blue-700 text-xs rounded">G: {{ Math.round(getBlockMacros(block).fats) }}g</span>
                                                </div>
                                                <p v-if="activeBlockIndex === index" class="text-xs text-green-600 mt-1">✏️ Editando...</p>
                                            </div>
                                            <button @click.stop="deleteBlock(index)" class="p-1.5 text-red-500 hover:bg-red-50 rounded-lg opacity-0 group-hover:opacity-100">
                                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                                </svg>
                                            </button>
                                        </div>
                                    </div>
                                    
                                    <!-- Nuevo bloque en edición (solo si no hay bloques o estamos creando uno nuevo) -->
                                    <div 
                                        v-if="activeBlockIndex === null && currentPlan.mealBlocks.length === 0"
                                        :class="['relative p-4 rounded-xl border-2', 'border-green-500 bg-green-50 dark:bg-green-900/20']"
                                    >
                                        <div class="flex items-start gap-3">
                                            <div class="w-8 h-8 rounded-full bg-gradient-to-br from-green-500 to-emerald-600 flex items-center justify-center text-white font-bold text-sm">1</div>
                                            <div class="flex-1">
                                                <h4 class="font-semibold text-gray-900 dark:text-white">{{ currentBlock.mealType ? getMealTypeLabel(currentBlock.mealType) : 'Comida 1' }}</h4>
                                                <p class="text-sm text-gray-500">{{ currentBlock.items.length }} alimentos{{ currentBlock.items.length > 0 ? ` • ${Math.round(currentBlockMacros.calories)} kcal` : '' }}</p>
                                                <p class="text-xs text-green-600 mt-1">✏️ Selecciona un tipo de comida para comenzar...</p>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <button @click="addBlock" class="w-full py-3 border-2 border-dashed border-gray-300 rounded-xl text-gray-500 hover:border-green-400 hover:text-green-600 flex items-center justify-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="M12 4v16m8-8H4" /></svg>
                                        Agregar bloque de comida
                                    </button>
                                </div>
                            </div>

                            <!-- Summary -->
                            <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 p-5">
                                <h3 class="font-semibold text-gray-900 dark:text-white mb-4">Resumen Nutricional</h3>
                                <div class="mb-4">
                                    <div class="flex justify-between text-sm mb-1.5">
                                        <span class="text-gray-600">Calorías</span>
                                        <span class="font-medium">{{ caloriePercentage }}%</span>
                                    </div>
                                    <div class="h-3 bg-gray-200 rounded-full overflow-hidden">
                                        <div class="h-full bg-gradient-to-r from-green-500 to-emerald-500 rounded-full" :style="{ width: caloriePercentage + '%' }"></div>
                                    </div>
                                    <p class="text-right text-sm text-gray-500 mt-1">{{ Math.round(totalMacros.calories) }} de {{ adjustedCalories }} kcal</p>
                                </div>
                                <div class="space-y-3">
                                    <div class="flex justify-between">
                                        <span class="text-sm text-gray-600">Proteínas</span>
                                        <span class="font-semibold text-red-600">{{ Math.round(totalMacros.proteins) }}g / {{ targetProtein }}g</span>
                                    </div>
                                    <div class="flex justify-between">
                                        <span class="text-sm text-gray-600">Grasas</span>
                                        <span class="font-semibold text-blue-600">{{ Math.round(totalMacros.fats) }}g / {{ targetFat }}g</span>
                                    </div>
                                    <div class="flex justify-between">
                                        <span class="text-sm text-gray-600">Carbohidratos</span>
                                        <span class="font-semibold text-amber-600">{{ Math.round(totalMacros.carbs) }}g / {{ targetCarbs }}g</span>
                                    </div>
                                </div>
                            </div>

                        </div>

                        <!-- Right Panel -->
                        <div class="lg:col-span-7">
                            <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 overflow-hidden sticky top-6">
                                <div class="px-5 py-4 border-b border-gray-100 dark:border-gray-700 flex items-center justify-between">
                                    <div class="flex items-center gap-4">
                                        <h3 class="font-semibold text-gray-900 dark:text-white">Configurar Comida</h3>
                                        <div class="flex items-center gap-2 text-sm">
                                            <span :class="['px-2.5 py-1 rounded-full font-medium', configStep >= 1 ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500']">1 Tipo</span>
                                            <span class="text-gray-300">—</span>
                                            <span :class="['px-2.5 py-1 rounded-full font-medium', configStep >= 2 ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500']">2 Alimentos</span>
                                        </div>
                                    </div>
                                    <div class="flex gap-2 text-xs">
                                        <span class="px-2 py-1 bg-red-50 text-red-600 rounded">P: {{ Math.round(currentBlockMacros.proteins) }}g</span>
                                        <span class="px-2 py-1 bg-amber-50 text-amber-600 rounded">C: {{ Math.round(currentBlockMacros.carbs) }}g</span>
                                        <span class="px-2 py-1 bg-blue-50 text-blue-600 rounded">G: {{ Math.round(currentBlockMacros.fats) }}g</span>
                                    </div>
                                </div>

                                <div class="p-5">
                                    <div v-if="configStep === 1" class="space-y-4">
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700 mb-2">Tipo de Comida</label>
                                            <select v-model="currentBlock.mealType" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white py-3">
                                                <option value="" disabled>Seleccionar tipo de comida...</option>
                                                <option v-for="(label, key) in mealTypes" :key="key" :value="key">{{ label }}</option>
                                            </select>
                                        </div>
                                    </div>

                                    <div v-else class="space-y-5">
                                        <div class="flex items-center justify-between pb-4 border-b border-gray-100">
                                            <div>
                                                <span class="text-xs text-gray-500">Tipo de Comida</span>
                                                <p class="font-medium text-gray-900">🍽️ {{ getMealTypeLabel(currentBlock.mealType) }}</p>
                                            </div>
                                            <button @click="configStep = 1" class="text-sm text-green-600 hover:text-green-700">Cambiar</button>
                                        </div>

                                        <div>
                                            <div class="flex items-center justify-between mb-2">
                                                <label class="text-sm font-medium text-gray-700">Seleccionar Alimentos</label>
                                                <button v-if="currentBlock.items.length" @click="clearCurrentBlockFoods" class="text-xs text-green-600">Limpiar</button>
                                            </div>
                                            <div v-if="currentBlock.items.length" class="flex flex-wrap gap-2 mb-3">
                                                <span v-for="(item, idx) in currentBlock.items" :key="idx" class="inline-flex items-center gap-1 px-3 py-1.5 bg-green-100 text-green-700 rounded-full text-sm">
                                                    {{ item.food_name }}
                                                    <button @click="removeFoodFromBlock(idx)" class="ml-1">×</button>
                                                </span>
                                            </div>
                                            <div class="relative">
                                                <input v-model="foodSearch" @focus="showFoodList = true" @blur="setTimeout(() => showFoodList = false, 200)" type="text" placeholder="Clic aquí para ver todos los alimentos..." class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white pl-10" />
                                                <svg class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" /></svg>
                                            </div>
                                            <p class="text-xs text-gray-500 mt-2">{{ currentBlock.items.length }} alimentos seleccionados</p>
                                        </div>

                                        <div v-if="showFoodList" class="max-h-60 overflow-y-auto border border-gray-200 rounded-lg divide-y">
                                            <div v-for="food in filteredFoods.slice(0, 50)" :key="food.id" @click="addFoodToBlock(food)" class="p-3 hover:bg-gray-50 cursor-pointer">
                                                <div class="flex items-center justify-between">
                                                    <p class="font-medium text-gray-900 text-sm">{{ food.name }}</p>
                                                    <span v-if="food.serving_size" class="text-xs bg-green-100 text-green-700 px-2 py-0.5 rounded-full">
                                                        {{ food.serving_size }}
                                                    </span>
                                                </div>
                                                <div class="flex items-center justify-between mt-1">
                                                    <p class="text-xs text-gray-500">{{ food.calories }} kcal • P:{{ food.proteins }}g C:{{ food.carbs }}g G:{{ food.fats }}g</p>
                                                    <span v-if="food.serving_weight" class="text-xs text-gray-400">{{ food.serving_weight }}g/porción</span>
                                                </div>
                                            </div>
                                        </div>

                                        <div v-if="currentBlock.items.length">
                                            <h4 class="text-sm font-medium text-gray-700 mb-3">Alimentos seleccionados ({{ currentBlock.items.length }})</h4>
                                            <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                                                <div v-for="(item, idx) in currentBlock.items" :key="idx" class="bg-gray-50 rounded-lg p-4">
                                                    <div class="flex justify-between items-start mb-2">
                                                        <div>
                                                            <h5 class="font-medium text-gray-900 text-sm">{{ item.food_name }}</h5>
                                                            <p v-if="item.serving_size" class="text-xs text-green-600 font-medium mt-0.5">
                                                                📦 {{ item.serving_size }}
                                                                <span v-if="item.serving_weight" class="text-gray-400">({{ item.serving_weight }}g)</span>
                                                            </p>
                                                            <p class="text-xs text-gray-500">{{ Math.round(item.calories * item.quantity / 100) }} kcal</p>
                                                        </div>
                                                        <button @click="removeFoodFromBlock(idx)" class="text-red-400 text-lg">×</button>
                                                    </div>
                                                    <div class="flex items-center gap-2 flex-wrap">
                                                        <input 
                                                            v-model.number="item.quantity" 
                                                            type="number" 
                                                            min="0.1" 
                                                            :step="item.unit === 'g' || item.unit === 'ml' || item.unit === 'oz' ? '1' : '0.5'"
                                                            class="w-20 text-center rounded-lg border-gray-300 text-sm py-1.5" 
                                                        />
                                                        <select 
                                                            v-model="item.unit" 
                                                            class="rounded-lg border-gray-300 text-sm py-1.5 pr-8"
                                                            @change="onUnitChange(item)"
                                                        >
                                                            <option value="g">gramos (g)</option>
                                                            <option value="unidad">unidad</option>
                                                            <option value="unidades">unidades</option>
                                                            <option value="taza">taza</option>
                                                            <option value="1/2 taza">1/2 taza</option>
                                                            <option value="1/4 taza">1/4 taza</option>
                                                            <option value="cucharada">cucharada</option>
                                                            <option value="cucharadita">cucharadita</option>
                                                            <option value="scoop">scoop</option>
                                                            <option value="batida">batida</option>
                                                            <option value="slice">slice/rebanada</option>
                                                            <option value="mediana">mediana</option>
                                                            <option value="pequeña">pequeña</option>
                                                            <option value="grande">grande</option>
                                                            <option value="porcion">porción</option>
                                                            <option value="vaso">vaso</option>
                                                            <option value="vasos">vasos</option>
                                                            <option value="oz">onza (oz)</option>
                                                            <option value="ml">mililitros (ml)</option>
                                                        </select>
                                                        <button 
                                                            v-if="item.serving_weight && item.quantity !== item.serving_weight && item.unit === 'g'"
                                                            @click="item.quantity = item.serving_weight"
                                                            class="text-xs text-green-600 hover:text-green-700"
                                                        >
                                                            Usar porción
                                                        </button>
                                                    </div>
                                                    <div class="flex gap-2 mt-2 text-xs">
                                                        <span class="text-red-500">P: {{ Math.round(item.proteins * item.quantity / 100) }}g</span>
                                                        <span class="text-amber-500">C: {{ Math.round(item.carbs * item.quantity / 100) }}g</span>
                                                        <span class="text-blue-500">G: {{ Math.round(item.fats * item.quantity / 100) }}g</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div v-if="currentBlock.items.length > 0" class="bg-green-50 border border-green-200 rounded-lg p-3 text-sm text-green-700">
                                            <p class="font-medium flex items-center gap-2">
                                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                                                </svg>
                                                Comida guardada automáticamente
                                            </p>
                                            <p class="text-xs mt-1">{{ currentBlock.items.length }} ítem(s) • {{ Math.round(currentBlockMacros.calories) }} kcal</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Action Buttons for Comidas Tab -->
                    <div class="mt-6 flex justify-between items-center bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 p-4">
                        <button 
                            @click="activeTab = 'plan'"
                            class="px-6 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-700 font-semibold rounded-lg"
                        >
                            ← Volver a Plan
                        </button>
                        <div class="flex gap-3">
                            <Link 
                                :href="`/coach/clients/${client.id}`"
                                class="px-6 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-700 font-semibold rounded-lg"
                            >
                                Cancelar
                            </Link>
                            <button 
                                @click="submit"
                                :disabled="form.processing || !canSubmit"
                                class="px-6 py-2.5 bg-gradient-to-r from-green-500 to-emerald-600 hover:from-green-600 hover:to-emerald-700 text-white font-semibold rounded-lg shadow-lg disabled:opacity-50 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="M5 13l4 4L19 7" />
                                </svg>
                                Crear Dieta
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </CoachLayout>
</template>
