
// ── API Client ────────────────────────────────────────────────────────────────
// Centraliza todas las llamadas a https://salud.rubenfer.es/api

const API_BASE = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'
  ? 'http://localhost:3004/api'
  : '/api';

const TOKEN_KEY = 'salud_jwt';

function getToken() { return localStorage.getItem(TOKEN_KEY); }
function setToken(t) { localStorage.setItem(TOKEN_KEY, t); }
function clearToken() { localStorage.removeItem(TOKEN_KEY); }

async function apiFetch(path, options = {}) {
  const token = getToken();
  const res = await fetch(`${API_BASE}${path}`, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
      ...(options.headers || {}),
    },
    body: options.body ? (typeof options.body === 'string' ? options.body : JSON.stringify(options.body)) : undefined,
  });
  if (res.status === 401) {
    clearToken();
    window.dispatchEvent(new Event('salud:logout'));
    throw new Error('Sesión expirada');
  }
  const data = await res.json();
  if (!res.ok) throw new Error(data.error || 'Error de servidor');
  return data;
}

const api = {
  // Auth
  login: (username, password) =>
    apiFetch('/auth/login', { method: 'POST', body: { username, password } }),
  changePassword: (oldPassword, newPassword) =>
    apiFetch('/auth/change-password', { method: 'POST', body: { oldPassword, newPassword } }),
  me: () => apiFetch('/auth/me'),

  // Foods
  getFoods:   (params = {}) => apiFetch('/foods?' + new URLSearchParams(params)),
  addFood:    (food)        => apiFetch('/foods', { method: 'POST', body: food }),
  updateFood: (id, food)    => apiFetch(`/foods/${id}`, { method: 'PUT', body: food }),
  deleteFood: (id)          => apiFetch(`/foods/${id}`, { method: 'DELETE' }),
  getFoodUsage: (id)        => apiFetch(`/foods/${id}/usage`),

  // Meals
  getMeals:      (date)        => apiFetch(`/meals${date ? '?date=' + date : ''}`),
  addMeal:       (meal)        => apiFetch('/meals', { method: 'POST', body: meal }),
  updateMeal:    (id, meal)    => apiFetch(`/meals/${id}`, { method: 'PUT', body: meal }),
  deleteMeal:    (id)          => apiFetch(`/meals/${id}`, { method: 'DELETE' }),
  getDaySummary: (date)        => apiFetch(`/meals/summary/${date}`),

  // Weights
  getWeights: ()           => apiFetch('/weights'),
  addWeight:  (date, kg)   => apiFetch('/weights', { method: 'POST', body: { date, kg } }),
  deleteWeight: (id)       => apiFetch(`/weights/${id}`, { method: 'DELETE' }),
  getWeightStats: ()       => apiFetch('/weights/stats'),

  // Workouts
  getWorkouts:  (date)       => apiFetch(`/workouts${date ? '?date=' + date : ''}`),
  addWorkout:   (workout)    => apiFetch('/workouts', { method: 'POST', body: workout }),
  updateWorkout:(id, workout)=> apiFetch(`/workouts/${id}`, { method: 'PUT', body: workout }),
  deleteWorkout:(id)         => apiFetch(`/workouts/${id}`, { method: 'DELETE' }),
  getWeeklyWorkouts: ()      => apiFetch('/workouts/weekly'),

  // Menus
  getMenus:   ()          => apiFetch('/menus'),
  getMenu:    (id)        => apiFetch(`/menus/${id}`),
  addMenu:    (menu)      => apiFetch('/menus', { method: 'POST', body: menu }),
  deleteMenu: (id)        => apiFetch(`/menus/${id}`, { method: 'DELETE' }),

  // Goals
  getGoals:   ()          => apiFetch('/goals'),
  updateGoals:(goals)     => apiFetch('/goals', { method: 'PUT', body: goals }),

  // Photos
  getPhotos:  ()          => apiFetch('/photos'),
  deletePhoto:(id)        => apiFetch(`/photos/${id}`, { method: 'DELETE' }),
  getPhotoUrl:(filename)  => `${API_BASE}/photos/file/${filename}`,
  uploadPhoto: async (file, date, note) => {
    const token = getToken();
    const form = new FormData();
    form.append('photo', file);
    form.append('date', date);
    if (note) form.append('note', note);
    const res = await fetch(`${API_BASE}/photos`, {
      method: 'POST',
      headers: { Authorization: `Bearer ${token}` },
      body: form,
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.error || 'Error subiendo foto');
    return data;
  },

  // Nutrition AI
  estimateNutrition: (name, grams) =>
    apiFetch('/nutrition/estimate', { method: 'POST', body: { name, grams } }),

  // Utils
  getToken, setToken, clearToken,
};

Object.assign(window, { api });
