<script setup>
/**
 * Coach Edit Meal Plan - Multiple Diet Plans Support
 * Tab 1: Plan De Dieta (Plan settings, days, macros, calories)
 * Tab 2: Comidas (Meal blocks with foods)
 * 
 * Updated to match Create.vue design and functionality
 */
import CoachLayout from '@/Layouts/CoachLayout.vue';
import { Head, Link, useForm } from '@inertiajs/vue3';
import { ref, computed, onMounted, watch } from 'vue';

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

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

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

// Initialize empty diet plan
const initDietPlan = () => ({
    id: null,
    name: '',
    description: '',
    days: [],
    use_percentages: true,
    protein_percent: 30,
    fat_percent: 25,
    carb_percent: 45,
    calorie_adjustment: props.client?.calorie_adjustment || 0,
    mealBlocks: [],
});

// 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 && plan.mealBlocks.length === 0 && activeBlockIndex.value === null) {
            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' },
];

// Initialize from existing data
onMounted(() => {
    if (props.mealPlan.diet_plans && props.mealPlan.diet_plans.length > 0) {
        dietPlans.value = props.mealPlan.diet_plans.map(dp => {
            // Group items by meal type into blocks
            const groupedItems = {};
            (dp.items || []).forEach(item => {
                const type = item.meal_type || 'other';
                if (!groupedItems[type]) {
                    groupedItems[type] = [];
                }
                groupedItems[type].push({
                    food_id: item.food_id,
                    food_name: item.food?.name || 'Alimento',
                    serving_size: item.food?.serving_size || null,
                    serving_weight: item.food?.serving_weight || null,
                    quantity: parseFloat(item.quantity),
                    unit: item.unit || '',
                    calories: parseFloat(item.food?.calories || item.calories || 0),
                    proteins: parseFloat(item.food?.proteins || item.proteins || 0),
                    carbs: parseFloat(item.food?.carbs || item.carbs || 0),
                    fats: parseFloat(item.food?.fats || item.fats || 0),
                });
            });
            
            const mealBlocks = [];
            Object.keys(groupedItems).forEach(type => {
                mealBlocks.push({
                    mealType: type,
                    items: groupedItems[type],
                });
            });

            return {
                id: dp.id,
                name: dp.name || '',
                description: dp.description || '',
                days: dp.days || [],
                use_percentages: dp.use_percentages ?? true,
                protein_percent: dp.protein_percent || 30,
                fat_percent: dp.fat_percent || 25,
                carb_percent: dp.carb_percent || 45,
                calorie_adjustment: dp.calorie_adjustment || 0,
                mealBlocks,
            };
        });
        
        // Check if there's a specific plan index in the URL query params
        const urlParams = new URLSearchParams(window.location.search);
        const planParam = urlParams.get('plan');
        if (planParam !== null) {
            const planIndex = parseInt(planParam, 10);
            if (!isNaN(planIndex) && planIndex >= 0 && planIndex < dietPlans.value.length) {
                activePlanIndex.value = planIndex;
            }
        }
    } else {
        // Fallback if no diet_plans (for backwards compatibility)
        dietPlans.value.push(initDietPlan());
    }
});

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

const toggleDay = (day) => {
    const plan = dietPlans.value[activePlanIndex.value];
    if (!plan) return;
    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 || 0) / 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) > 0) return 'Superávit Calórico';
    if ((currentPlan.value?.calorie_adjustment || 0) < 0) return 'Déficit Calórico';
    return 'Mantenimiento';
});

// 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);
    }
});

// Meal blocks
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) => {
    if (!block || !block.items) return { calories: 0, proteins: 0, carbs: 0, fats: 0 };
    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, idx) => {
        // Solo sumar si no es el bloque que estamos editando actualmente
        if (activeBlockIndex.value !== null && idx === 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 || null,
            serving_weight: food.serving_weight || null,
            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, oldLength) => {
    if (newLength > 0 && oldLength === 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 form can submit based on active tab
const canSubmit = computed(() => {
    if (activeTab.value === 'plan') {
        // En tab Plan De Dieta, solo validar nombre del plan
        return dietPlans.value[0]?.name?.length > 0;
    } else {
        // En tab Comidas, validar que tenga al menos una comida con alimentos
        const plan = dietPlans.value[activePlanIndex.value];
        const hasValidBlocks = plan?.mealBlocks?.some(block => block.items?.length > 0);
        return form.name && hasValidBlocks;
    }
});

const submit = () => {
    // Filtrar bloques vacíos antes de enviar
    const validDietPlans = dietPlans.value.map(plan => ({
        id: plan.id,
        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: plan.mealBlocks
            .filter(block => block.items && block.items.length > 0)
            .flatMap(block => 
                block.items.map(item => ({
                    food_id: item.food_id,
                    meal_type: block.mealType,
                    quantity: item.quantity,
                    unit: item.unit || 'g',
                }))
            ),
    })).filter(plan => plan.name && plan.meal_items.length > 0);
    
    form.diet_plans = validDietPlans;
    form.put(route('coach.clients.meal-plans.update', [props.client.id, props.mealPlan.id]));
};
</script>

<template>
    <Head :title="`Editar ${mealPlan.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">✏️ Editar Dieta</h2>
                        <p class="text-sm text-gray-500">{{ client.name }} - {{ mealPlan.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 && 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 Percentages -->
                    <div v-if="currentPlan.use_percentages" 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">
                                Proteínas (%) 🔄
                            </label>
                            <input 
                                v-model.number="currentPlan.protein_percent" 
                                type="number" 
                                min="0" 
                                max="100"
                                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 mt-1">{{ targetProtein }} g</p>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                Grasas (%) 🔄
                            </label>
                            <input 
                                v-model.number="currentPlan.fat_percent" 
                                type="number" 
                                min="0" 
                                max="100"
                                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 mt-1">{{ targetFat }} g</p>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                Carbohidratos (%) 🔄
                            </label>
                            <input 
                                v-model.number="currentPlan.carb_percent" 
                                type="number" 
                                min="0" 
                                max="100"
                                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 mt-1">{{ targetCarbs }} g</p>
                        </div>
                    </div>

                    <!-- Calorie Adjustment Slider -->
                    <div class="mb-6">
                        <div class="flex justify-between items-center mb-2">
                            <label class="text-sm font-medium text-gray-700 dark:text-gray-300 flex items-center gap-1">
                                Ajuste de calorías
                                <span class="text-gray-400 cursor-help" title="Ajusta las calorías según el objetivo">ⓘ</span>
                            </label>
                            <span class="text-lg font-bold text-green-600">{{ (currentPlan.calorie_adjustment || 0) >= 0 ? '+' : '' }}{{ currentPlan.calorie_adjustment || 0 }}%</span>
                        </div>
                        <div class="relative pt-1">
                            <input 
                                type="range" 
                                v-model.number="currentPlan.calorie_adjustment"
                                min="-100" 
                                max="100" 
                                step="5"
                                class="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-green-600"
                            />
                            <div class="flex justify-between text-xs text-gray-500 mt-1">
                                <span>-100%</span>
                                <span>0%</span>
                                <span>+100%</span>
                            </div>
                        </div>
                    </div>

                    <!-- TDEE Summary -->
                    <div class="bg-gray-50 dark:bg-gray-700/50 rounded-xl p-4 space-y-3">
                        <div class="flex justify-between">
                            <span class="text-gray-600 dark:text-gray-400">TDEE (Gasto Energético Total Diario):</span>
                            <span class="font-bold text-gray-900 dark:text-white">{{ clientTdee }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-600 dark:text-gray-400">Ajuste:</span>
                            <span class="font-bold" :class="calorieAdjustment >= 0 ? 'text-green-600' : 'text-red-600'">
                                {{ calorieAdjustment >= 0 ? '+' : '' }}{{ calorieAdjustment }}
                            </span>
                        </div>
                        <div class="flex justify-between border-t border-gray-200 dark:border-gray-600 pt-3">
                            <span class="text-gray-600 dark:text-gray-400">Calorías ajustadas:</span>
                            <span class="font-bold text-xl text-green-600">{{ adjustedCalories }}</span>
                        </div>
                    </div>

                    <!-- Continue Button -->
                    <div class="mt-6 flex justify-end">
                        <button 
                            @click="activeTab = 'comidas'"
                            :disabled="!currentPlan.name"
                            class="px-6 py-3 bg-green-600 hover:bg-green-700 text-white font-semibold rounded-lg disabled:opacity-50"
                        >
                            Continuar a Comidas →
                        </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">
                                    <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">{{ getMealTypeLabel(block.mealType) }}</h4>
                                                <p class="text-sm text-gray-500">{{ block.items.length }} alimentos • {{ Math.round(getBlockMacros(block).calories) }} kcal</p>
                                                <!-- Food items with portions -->
                                                <div v-if="block.items.length" class="mt-2 space-y-1">
                                                    <div v-for="item in block.items.slice(0, 3)" :key="item.food_id" class="text-xs text-gray-600 dark:text-gray-400">
                                                        • {{ item.food_name }} 
                                                        <span class="text-green-600 font-semibold">({{ formatNumber(item.quantity) }} {{ item.unit || 'g' }})</span>
                                                        <span v-if="item.serving_size" class="text-gray-400 ml-1 text-[10px]">📦 {{ item.serving_size }}</span>
                                                    </div>
                                                    <p v-if="block.items.length > 3" class="text-xs text-gray-400 italic">
                                                        +{{ block.items.length - 3 }} más...
                                                    </p>
                                                </div>
                                                <div 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>
                                            </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>
                                    <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
                                    </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 v-for="(label, key) in mealTypes" :key="key" :value="key">{{ label }}</option>
                                            </select>
                                        </div>
                                        <button @click="proceedToFoods" class="w-full py-3 bg-green-600 hover:bg-green-700 text-white font-medium rounded-lg">Continuar a Alimentos →</button>
                                    </div>

                                    <div v-else class="space-y-5">
                                        <div class="flex items-center justify-between pb-4 border-b border-gray-100">
                                            <span class="font-medium text-gray-900">🍽️ {{ getMealTypeLabel(currentBlock.mealType) }}</span>
                                            <button @click="configStep = 1" class="text-sm text-green-600">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>

                                        <button @click="saveBlock" :disabled="currentBlock.items.length === 0" class="w-full py-3 bg-gradient-to-r from-green-500 to-emerald-600 text-white font-semibold rounded-lg disabled:opacity-50 flex items-center justify-center gap-2">
                                            <span class="w-2 h-2 bg-white/80 rounded-full"></span>
                                            Comida Configurada
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Notes Widget -->
                <div v-if="activeTab === 'comidas'" class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 p-6 mt-6">
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center gap-2">
                        📝 Notas para el Cliente
                    </h3>
                    <p class="text-sm text-gray-500 dark:text-gray-400 mb-3">
                        Estas notas serán visibles para el cliente en su panel y en el PDF de la dieta.
                    </p>
                    <textarea 
                        v-model="form.notes" 
                        rows="4" 
                        placeholder="Ej: Recuerda beber 2 litros de agua al día. Evita comer tarde en la noche..."
                        class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white resize-none"
                    ></textarea>
                </div>

                <!-- Action Buttons -->
                <div class="mt-6 flex justify-end items-center gap-3">
                    <Link 
                        :href="route('coach.clients.meal-plans.show', [client.id, mealPlan.id])"
                        class="px-6 py-3 bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300 font-semibold rounded-xl transition-colors"
                    >
                        Cancelar
                    </Link>
                    <button 
                        @click="submit"
                        :disabled="form.processing || !canSubmit"
                        class="px-8 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-xl shadow-lg disabled:opacity-50 disabled:cursor-not-allowed transition-all"
                    >
                        Guardar
                    </button>
                </div>
            </div>
        </div>
    </CoachLayout>
</template>
