
// ── Data Store — conectado a API real ─────────────────────────────────────────
const { createContext, useContext, useReducer, useEffect, useState } = React;

const SaludContext = createContext(null);

const INITIAL_STATE = {
  foods:    [],
  meals:    [],
  weights:  [],
  workouts: [],
  photos:   [],
  menus:    [],
  goals:    { kcal: 2200, prot: 160, carbs: 230, fat: 65 },
  loading:  true,
  error:    null,
};

function saludReducer(state, action) {
  switch (action.type) {
    case 'SET_FOODS':    return { ...state, foods:    action.data };
    case 'SET_MEALS':    return { ...state, meals:    action.data };
    case 'SET_WEIGHTS':  return { ...state, weights:  action.data };
    case 'SET_WORKOUTS': return { ...state, workouts: action.data };
    case 'SET_PHOTOS':   return { ...state, photos:   action.data };
    case 'SET_MENUS':    return { ...state, menus:    action.data };
    case 'SET_GOALS':    return { ...state, goals:    action.data };
    case 'SET_LOADING':  return { ...state, loading:  action.value };
    case 'SET_ERROR':    return { ...state, error:    action.value };

    case 'ADD_FOOD':     return { ...state, foods:    [...state.foods,    action.item] };
    case 'UPDATE_FOOD':  return { ...state, foods:    state.foods.map(f => f.id === action.item.id ? action.item : f) };
    case 'DELETE_FOOD':  return { ...state, foods:    state.foods.filter(f => f.id !== action.id) };

    case 'ADD_MEAL':     return { ...state, meals:    [...state.meals,    action.item] };
    case 'UPDATE_MEAL':  return { ...state, meals:    state.meals.map(m => m.id === action.item.id ? action.item : m) };
    case 'DELETE_MEAL':  return { ...state, meals:    state.meals.filter(m => m.id !== action.id) };

    case 'ADD_WEIGHT':   return { ...state, weights:  [...state.weights,  action.item].sort((a,b) => a.date.localeCompare(b.date)) };
    case 'DELETE_WEIGHT':return { ...state, weights:  state.weights.filter(w => w.id !== action.id) };

    case 'ADD_WORKOUT':  return { ...state, workouts: [...state.workouts, action.item] };
    case 'DELETE_WORKOUT':return{ ...state, workouts: state.workouts.filter(w => w.id !== action.id) };

    case 'ADD_PHOTO':    return { ...state, photos:   [...state.photos,   action.item] };
    case 'DELETE_PHOTO': return { ...state, photos:   state.photos.filter(p => p.id !== action.id) };

    case 'ADD_MENU':     return { ...state, menus:    [...state.menus,    action.item] };
    case 'DELETE_MENU':  return { ...state, menus:    state.menus.filter(m => m.id !== action.id) };

    default: return state;
  }
}

function SaludProvider({ children }) {
  const [state, dispatch] = useReducer(saludReducer, INITIAL_STATE);

  // ── Cargar datos iniciales ──────────────────────────────────────────────────
  useEffect(() => {
    async function loadAll() {
      dispatch({ type: 'SET_LOADING', value: true });
      try {
        const [foods, weights, workouts, photos, menus, goals] = await Promise.all([
          api.getFoods(),
          api.getWeights(),
          api.getWorkouts(),
          api.getPhotos(),
          api.getMenus(),
          api.getGoals(),
        ]);
        dispatch({ type: 'SET_FOODS',    data: foods });
        dispatch({ type: 'SET_WEIGHTS',  data: weights });
        dispatch({ type: 'SET_WORKOUTS', data: workouts });
        dispatch({ type: 'SET_PHOTOS',   data: photos });
        dispatch({ type: 'SET_MENUS',    data: menus });
        dispatch({ type: 'SET_GOALS',    data: goals });
      } catch (e) {
        dispatch({ type: 'SET_ERROR', value: e.message });
      } finally {
        dispatch({ type: 'SET_LOADING', value: false });
      }
    }
    loadAll();
  }, []);

  // ── Helpers de nutrición ────────────────────────────────────────────────────
  const getMealsForDate = (date) => state.meals.filter(m => m.date === date);
  const getWeightForDate = (date) => state.weights.find(w => w.date === date);
  const getWorkoutsForDate = (date) => state.workouts.filter(w => w.date === date);

  const calcMealNutrition = (meal) => {
    const items = meal.items || [];
    return items.reduce((acc, item) => {
      // La API devuelve los macros directamente en el item (JOIN con foods)
      const cal   = item.cal   || (state.foods.find(f => f.id === (item.foodId || item.food_id))?.cal   || 0);
      const prot  = item.prot  || (state.foods.find(f => f.id === (item.foodId || item.food_id))?.prot  || 0);
      const carbs = item.carbs || (state.foods.find(f => f.id === (item.foodId || item.food_id))?.carbs || 0);
      const fat   = item.fat   || (state.foods.find(f => f.id === (item.foodId || item.food_id))?.fat   || 0);
      const f = item.grams / 100;
      return { kcal: acc.kcal + cal*f, prot: acc.prot + prot*f, carbs: acc.carbs + carbs*f, fat: acc.fat + fat*f };
    }, { kcal: 0, prot: 0, carbs: 0, fat: 0 });
  };

  const calcDayNutrition = (date) => {
    return getMealsForDate(date).reduce((acc, meal) => {
      const n = calcMealNutrition(meal);
      return { kcal: acc.kcal + n.kcal, prot: acc.prot + n.prot, carbs: acc.carbs + n.carbs, fat: acc.fat + n.fat };
    }, { kcal: 0, prot: 0, carbs: 0, fat: 0 });
  };

  // ── API actions ─────────────────────────────────────────────────────────────
  const actions = {
    // Foods
    addFood: async (food) => {
      const item = await api.addFood(food);
      dispatch({ type: 'ADD_FOOD', item });
      return item;
    },
    updateFood: async (food) => {
      await api.updateFood(food.id, food);
      dispatch({ type: 'UPDATE_FOOD', item: food });
    },
    deleteFood: async (id) => {
      await api.deleteFood(id);
      dispatch({ type: 'DELETE_FOOD', id });
    },

    // Meals
    loadMealsForDate: async (date) => {
      const meals = await api.getMeals(date);
      // Merge: reemplaza los del día, mantiene los demás
      dispatch({ type: 'SET_MEALS', data: [
        ...state.meals.filter(m => m.date !== date),
        ...meals,
      ]});
      return meals;
    },
    addMeal: async (meal) => {
      const item = await api.addMeal({
        date: meal.date,
        type: meal.type,
        items: (meal.items || []).map(i => ({ foodId: i.foodId || i.food_id, grams: i.grams })),
      });
      // Recargar el día para tener los nombres de alimentos
      const updated = await api.getMeals(meal.date);
      dispatch({ type: 'SET_MEALS', data: [
        ...state.meals.filter(m => m.date !== meal.date),
        ...updated,
      ]});
      return item;
    },
    updateMeal: async (meal) => {
      await api.updateMeal(meal.id, {
        date: meal.date,
        type: meal.type,
        items: (meal.items || []).map(i => ({ foodId: i.foodId || i.food_id, grams: i.grams })),
      });
      const updated = await api.getMeals(meal.date);
      dispatch({ type: 'SET_MEALS', data: [
        ...state.meals.filter(m => m.date !== meal.date),
        ...updated,
      ]});
    },
    deleteMeal: async (id, date) => {
      await api.deleteMeal(id);
      dispatch({ type: 'DELETE_MEAL', id });
    },

    // Weights
    addWeight: async (date, kg) => {
      const item = await api.addWeight(date, kg);
      // Quitar el del mismo día si existía y añadir el nuevo
      dispatch({ type: 'SET_WEIGHTS', data: [
        ...state.weights.filter(w => w.date !== date),
        item,
      ].sort((a,b) => a.date.localeCompare(b.date))});
      return item;
    },
    deleteWeight: async (id) => {
      await api.deleteWeight(id);
      dispatch({ type: 'DELETE_WEIGHT', id });
    },

    // Workouts
    addWorkout: async (workout) => {
      const item = await api.addWorkout(workout);
      dispatch({ type: 'ADD_WORKOUT', item });
      return item;
    },
    deleteWorkout: async (id) => {
      await api.deleteWorkout(id);
      dispatch({ type: 'DELETE_WORKOUT', id });
    },

    // Photos
    uploadPhoto: async (file, date, note) => {
      const item = await api.uploadPhoto(file, date, note);
      dispatch({ type: 'ADD_PHOTO', item: { ...item, url: api.getPhotoUrl(item.filename) } });
      return item;
    },
    deletePhoto: async (id) => {
      await api.deletePhoto(id);
      dispatch({ type: 'DELETE_PHOTO', id });
    },

    // Menus
    addMenu: async (menu) => {
      const item = await api.addMenu(menu);
      dispatch({ type: 'ADD_MENU', item });
      return item;
    },
    deleteMenu: async (id) => {
      await api.deleteMenu(id);
      dispatch({ type: 'DELETE_MENU', id });
    },

    // Goals
    updateGoals: async (goals) => {
      await api.updateGoals(goals);
      dispatch({ type: 'SET_GOALS', data: goals });
    },
  };

  const value = {
    state, dispatch,
    getMealsForDate, getWeightForDate, getWorkoutsForDate,
    calcMealNutrition, calcDayNutrition,
    ...actions,
  };

  return React.createElement(SaludContext.Provider, { value }, children);
}

function useSalud() { return useContext(SaludContext); }

Object.assign(window, { SaludContext, SaludProvider, useSalud });
