Hola por favor ayudame con lo siguiente necesito una pagina en react next js para que administrar stores y como cada store que hay en el serve tiene productos y servicios poder visualizarlos ahi, interesante en la pagina que es un solo archivo componente tenga lo siguiente : import React from 'react';
import styles from '../styles/Sidebar.module.css';

const Sidebar = ({ stores, selectedStore, onSelectStore }) => {
  console.log('Sidebar props:', { stores, selectedStore }); // Agregar log para depuración

  // Validación más detallada
  if (!stores) {
    console.log('No hay stores definido');
    return (
      <aside className={styles.sidebar}>
        <div className={styles.noStores}>
          Cargando tiendas...
        </div>
      </aside>
    );
  }

  if (!Array.isArray(stores)) {
    console.error('stores no es un array:', stores);
    return (
      <aside className={styles.sidebar}>
        <div className={styles.noStores}>
          Error al cargar tiendas
        </div>
      </aside>
    );
  }

  if (stores.length === 0) {
    console.log('Array de stores está vacío');
    return (
      <aside className={styles.sidebar}>
        <div className={styles.noStores}>
          No hay tiendas disponibles
        </div>
      </aside>
    );
  }

  return (
    <aside className={styles.sidebar}>
      <h2>Tiendas ({stores.length})</h2>
      <ul className={styles.storeList}>
        {stores.map(store => {
          console.log('Renderizando tienda:', store); // Log para cada tienda
          return (
            <li 
              key={store._id}
              className={`${styles.storeItem} ${selectedStore === store._id ? styles.selected : ''}`}
              onClick={() => onSelectStore(store._id)}
            >
              {store.name || 'Tienda sin nombre'}
            </li>
          );
        })}
      </ul>
    </aside>
  );
};

export default Sidebar;
y se contecte a nuestro contexto para consultar store y por cada store poder visualizar sus productos servicicios, crear un producto o servicio : // GlobalContext.js

import React, {
  createContext,
  useContext,
  useState,
  useEffect,
  useCallback,
  useMemo,
} from 'react';
import useSWR, { mutate } from 'swr';
import { useSocket } from './SocketContext';
import { useGeolocation } from '../hooks/useGeolocation';
import axios from 'axios';

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3003';
export { API_BASE_URL };
// Creación del contexto global con valores iniciales
const GlobalContext = createContext({
  worker: null,
  workerLoading: true,
  workerDocuments: {
    vehicle: [],
    license: [],
    insurance: [],
    certification: [],
  },
  loading: false,
  error: null,
  auth: {
    admin: { user: null, loading: false, error: null },
    seller: { user: null, loading: false, error: null },
    worker: { user: null, loading: false, error: null },
  },
  handleLogin: async (user, role) => {},
});

export const useGlobalContext = () => useContext(GlobalContext);

// Función para obtener el token de autenticación desde localStorage
const getToken = () => {
  const userTypes = ['admin', 'seller', 'worker'];
  for (const type of userTypes) {
    const storedUser = localStorage.getItem(`currentUser_${type}`);
    if (storedUser) {
      const { token } = JSON.parse(storedUser);
      if (token) {
        return token;
      }
    }
  }
  return null;
};

// Función fetcher personalizada para SWR
const fetcher = async (url, method = 'GET', body = null, params = {}) => {
  let modifiedUrl = url.startsWith('/api') ? url : `/api${url}`;

  const headers = {
    'Content-Type': 'application/json',
    Accept: 'application/json',
    ...(params.headers || {}),
  };

  const token = getToken();
  if (token) {
    headers.Authorization = `Bearer ${token}`;
  }

  // Añadir parámetros de consulta si existen
  if (params && Object.keys(params).length > 0) {
    const queryParams = { ...params };
    delete queryParams.headers;
    const queryString = new URLSearchParams(queryParams).toString();
    modifiedUrl += `?${queryString}`;
  }

  const response = await fetch(`${API_BASE_URL}${modifiedUrl}`, {
    method,
    headers,
    body: body ? JSON.stringify(body) : null,
  });

  if (!response.ok) {
    const errorData = await response.json();
    const error = new Error(errorData.message || 'Error en la solicitud');
    error.status = response.status;
    error.info = errorData;
    throw error;
  }

  return response.json();
};

// Provider global que utiliza SWR para la gestión de datos
export const GlobalProvider = ({ children }) => {
  const [auth, setAuth] = useState({
    admin: { user: null, loading: false, error: null },
    seller: { user: null, loading: false, error: null },
    worker: { user: null, loading: false, error: null },
  });

  const [error, setError] = useState(null);
  const [validationErrors, setValidationErrors] = useState({});
  const [notifications, setNotifications] = useState({
    proposals: 0,
    lastChecked: null,
  });

  const [currentStoreId, setCurrentStoreId] = useState(null);
  const [currentStore, setCurrentStore] = useState(null);
  const [storeSettings, setStoreSettings] = useState(null);

  const [worker, setWorker] = useState(null);
  const [workerLoading, setWorkerLoading] = useState(true);
  const [workerError, setWorkerError] = useState(null);
  const [workerStatus, setWorkerStatus] = useState({
    isAvailable: false,
    currentStatus: 'offline',
    lastUpdate: null,
  });
  const [workerProfile, setWorkerProfile] = useState(null);

  const [socketError, setSocketError] = useState(null);

  const { socket, isConnected, connectSocket, disconnectSocket } = useSocket();
  const { location } = useGeolocation();

  const [availableUsers, setAvailableUsers] = useState([]);
  const [loginError, setLoginError] = useState(null);

  // Agregar el estado showLoginModal
  const [showLoginModal, setShowLoginModal] = useState(false);

  // Función para manejar errores generales
  const handleError = useCallback((error, customMessage) => {
    const errorMessage =
      error.info?.message || error.message || customMessage;
    console.error(customMessage, error);
    setError(errorMessage);
    return {
      success: false,
      message: errorMessage,
    };
  }, []);

  // ===========================
  // Hooks SWR Personalizados
  // ===========================

  // Hook para obtener estadísticas
  const useStats = () => {
    const { data, error } = useSWR('/api/stats', fetcher);

    return {
      stats: data?.data || {
        sales: 0,
        orders: 0,
        products: 0,
        stores: 0,
        users: 0,
        currentActiveUsers: 0,
        conversionRate: 0,
        averageOrderValue: 0,
        timeInApps: '0 min',
        clientMobileAppActiveUsers: 0,
        businessMobileAppActiveUsers: 0,
        hubAppActiveUsers: 0
      },
      isLoading: !error && !data,
      isError: error
    };
  };

  // Hook para obtener alertas
  const useAlerts = () => {
    const { data, error } = useSWR('/api/alerts', fetcher);

    return {
      alerts: data,
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener tiendas
  const useStores = () => {
    const { data, error } = useSWR('/api/stores', fetcher);

    return {
      stores: data,
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener cooperativas
  const useCooperatives = () => {
    const { data, error } = useSWR('/api/cooperatives', fetcher);

    return {
      cooperatives: data,
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener productos y servicios de una tienda
  const useProductsAndServices = (storeId) => {
    const { data, error } = useSWR(
      storeId ? `/api/products/${storeId}` : null,
      fetcher
    );

    return {
      products: data?.data?.products || [],
      services: data?.data?.services || [],
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener usuarios con paginación y filtros
  const useUsers = (page = 1, limit = 10, filters = {}) => {
    const queryParams = new URLSearchParams({
      page,
      limit,
      ...filters,
      sortBy: filters.sortBy || 'createdAt',
      sortOrder: filters.sortOrder || -1,
    }).toString();

    const { data, error } = useSWR(`/api/users?${queryParams}`, fetcher);

    return {
      users: data?.users || [],
      totalUsers: data?.totalUsers || 0,
      totalPages: data?.totalPages || 1,
      currentPage: data?.currentPage || 1,
      hasMore: data?.hasMore || false,
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener órdenes
  const useOrders = () => {
    const { data, error } = useSWR('/api/orders', fetcher);

    return {
      orders: data || [],
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener servicios
  const useServices = () => {
    const { data, error } = useSWR('/api/services', fetcher);

    return {
      services: data || [],
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener entregas activas
  const useActiveDeliveries = (workerId) => {
    const { data, error } = useSWR(
      workerId ? `/api/workers/${workerId}/active-deliveries` : null,
      fetcher
    );

    return {
      activeDeliveries: data || [],
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener la entrega actual
  const useCurrentDelivery = (workerId) => {
    const { data, error } = useSWR(
      workerId ? `/api/workers/${workerId}/current-delivery` : null,
      fetcher
    );

    return {
      currentDelivery: data || null,
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener el dashboard del trabajador
  const useDashboardStats = (workerId) => {
    const { data, error } = useSWR(
      workerId ? `/api/workers/${workerId}/dashboard-stats` : null,
      fetcher
    );

    return {
      dashboardStats: data || null,
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener las ganancias del trabajador
  const useWorkerEarnings = () => {
    const { data, error } = useSWR('/api/earnings', fetcher);

    return {
      workerEarnings: data?.data || { today: 0, week: 0, month: 0 },
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener el historial de entregas
  const useDeliveryHistory = () => {
    const { data, error } = useSWR('/api/deliveries/history', fetcher);

    return {
      deliveryHistory: data?.data || [],
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener documentos del trabajador
  const useWorkerDocuments = () => {
    const { data, error } = useSWR('/api/worker/documents', fetcher);

    return {
      workerDocuments: data?.data || {
        vehicle: [],
        license: [],
        insurance: [],
        certification: [],
      },
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener chats activos
  const useActiveChats = () => {
    const { data, error } = useSWR('/api/chat/active', fetcher);

    return {
      activeChats: data?.data || [],
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener métricas de entregas
  const useDeliveryMetrics = () => {
    const { data, error } = useSWR('/api/deliveries/metrics', fetcher);

    return {
      deliveryMetrics: data?.data || null,
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener datos del dashboard del trabajador
  const useWorkerDashboard = (workerId) => {
    const { data, error } = useSWR(
      workerId ? `/api/worker/dashboard` : null,
      fetcher
    );

    return {
      workerDashboard: data || {
        dailyStats: { orders: 0, earnings: 0, distance: 0 },
        weeklyStats: { orders: 0, earnings: 0, distance: 0 },
        performanceMetrics: {
          rating: 0,
          completionRate: 0,
          avgDeliveryTime: 0,
          customerSatisfaction: 0,
        },
        availableOrders: [],
      },
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener rutas inteligentes
  const useSmartRoutes = () => {
    const { data, error } = useSWR('/api/routes', fetcher);

    return {
      smartRoutes: data || {
        activeOrders: [],
        optimizedRoute: null,
        trafficData: null,
        hotZones: [],
        timeSlots: [],
      },
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener las entregas de una tienda
  const useStoreDeliveries = (storeId) => {
    const { data, error } = useSWR(
      storeId ? `/api/stores/${storeId}/deliveries` : null,
      fetcher
    );

    return {
      storeDeliveries: data?.data || [],
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener detalles de una tienda
  const useStoreDetails = (storeId) => {
    const { data, error } = useSWR(
      storeId ? `/api/stores/details/${storeId}` : null,
      fetcher
    );

    return {
      storeDetails: data?.data || null,
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener propuestas de venta al por mayor
  const useWholesaleProposals = (userId) => {
    const { data, error } = useSWR(
      userId ? `/api/proposals?userId=${userId}` : null,
      fetcher
    );

    return {
      wholesaleProposals: data || [],
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener productos de todas las tiendas
  const useAllProducts = (params) => {
    const queryParams = new URLSearchParams({
      page: params.page,
      limit: params.limit,
      search: params.search,
      store: params.filters.store,
      type: params.filters.type,
      status: params.filters.status,
      sortBy: params.sort?.key,
      sortDirection: params.sort?.direction,
    }).toString();

    const { data, error } = useSWR(`/api/products/list?${queryParams}`, fetcher);

    return {
      allProducts: data?.products || [],
      total: data?.total || 0,
      page: data?.page || 1,
      totalPages: data?.totalPages || 1,
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener productos de una tienda
  const useStoreProducts = (storeId) => {
    const { data, error } = useSWR(
      storeId ? `/api/products/${storeId}` : null,
      fetcher
    );

    return {
      storeProducts: data?.data?.products || [],
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener ventas de una tienda
  const useStoreSales = (storeId) => {
    const { data, error } = useSWR(
      storeId ? `/api/stores/${storeId}/sales` : null,
      fetcher
    );

    return {
      storeSales: data?.data?.sales || [],
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener el conteo de productos de una tienda
  const useStoreProductCount = (storeId) => {
    const { data, error } = useSWR(
      storeId ? `/api/stores/${storeId}/products/count` : null,
      fetcher
    );

    return {
      productCount: data?.count || 0,
      isLoading: !error && !data,
      isError: error,
    };
  };

  // Hook para obtener el conteo de órdenes de una tienda
  const useStoreOrderCount = (storeId) => {
    const { data, error } = useSWR(
      storeId ? `/api/stores/${storeId}/orders/count` : null,
      fetcher
    );

    return {
      orderCount: data?.count || 0,
      isLoading: !error && !data,
      isError: error,
    };
  };

  // ===========================
  // Funciones de Mutación y Acciones
  // ===========================

  // Función para agregar una tienda
  const addStore = useCallback(async (storeData) => {
    try {
      const newStore = await fetcher('/api/stores', 'POST', storeData);
      mutate('/api/stores', (stores) => [...stores, newStore], false);
      return newStore;
    } catch (error) {
      return handleError(error, 'Error al crear la tienda');
    }
  }, [handleError]);

  // Función para actualizar una tienda
  const updateStore = useCallback(async (storeId, storeData) => {
    try {
      const updatedStore = await fetcher(
        `/api/stores/${storeId}`,
        'PUT',
        storeData
      );
      mutate('/api/stores', (stores) =>
        stores.map((store) => (store._id === storeId ? updatedStore : store))
      );
      return updatedStore;
    } catch (error) {
      return handleError(error, 'Error al actualizar la tienda');
    }
  }, [handleError]);

  // Función para eliminar una tienda
  const deleteStore = useCallback(async (storeId) => {
    try {
      await fetcher(`/api/stores/${storeId}`, 'DELETE');
      mutate('/api/stores', (stores) =>
        stores.filter((store) => store._id !== storeId)
      );
      return { success: true };
    } catch (error) {
      return handleError(error, 'Error al eliminar la tienda');
    }
  }, [handleError]);

  // Función para agregar una cooperativa
  const addCooperative = useCallback(async (cooperativeData) => {
    try {
      const newCoop = await fetcher(
        '/api/cooperatives',
        'POST',
        cooperativeData
      );
      mutate('/api/cooperatives', (cooperatives) => [...cooperatives, newCoop]);
      return newCoop;
    } catch (error) {
      return handleError(error, 'Error al crear la cooperativa');
    }
  }, [handleError]);

  // Función para actualizar una cooperativa
  const updateCooperative = useCallback(async (cooperativeId, cooperativeData) => {
    try {
      const updatedCoop = await fetcher(
        `/api/cooperatives/${cooperativeId}`,
        'PUT',
        cooperativeData
      );
      mutate('/api/cooperatives', (cooperatives) =>
        cooperatives.map((coop) =>
          coop._id === cooperativeId ? updatedCoop : coop
        )
      );
      return updatedCoop;
    } catch (error) {
      return handleError(error, 'Error al actualizar la cooperativa');
    }
  }, [handleError]);

  // Función para eliminar una cooperativa
  const deleteCooperative = useCallback(async (cooperativeId) => {
    try {
      await fetcher(`/api/cooperatives/${cooperativeId}`, 'DELETE');
      mutate('/api/cooperatives', (cooperatives) =>
        cooperatives.filter((coop) => coop._id !== cooperativeId)
      );
      return { success: true };
    } catch (error) {
      return handleError(error, 'Error al eliminar la cooperativa');
    }
  }, [handleError]);

  // Función para agregar un producto
  const addProduct = useCallback(async (productData) => {
    try {
      const newProduct = await fetcher('/api/products', 'POST', productData);
      mutate('/api/products/list', (data) => ({
        ...data,
        products: [...data.products, newProduct],
      }));
      return newProduct;
    } catch (error) {
      if (error.info?.errors) {
        setValidationErrors(error.info.errors);
      }
      return handleError(error, 'Error al crear el producto');
    }
  }, [handleError]);

  // Función para actualizar un producto
  const updateProduct = useCallback(async (productId, productData) => {
    try {
      const updatedProduct = await fetcher(
        `/api/products/${productId}`,
        'PUT',
        productData
      );
      mutate('/api/products/list', (data) => ({
        ...data,
        products: data.products.map((product) =>
          product._id === productId ? updatedProduct : product
        ),
      }));
      return updatedProduct;
    } catch (error) {
      return handleError(error, 'Error al actualizar el producto');
    }
  }, [handleError]);

  // Función para eliminar un producto
  const deleteProduct = useCallback(async (productId) => {
    try {
      await fetcher(`/api/products/${productId}`, 'DELETE');
      mutate('/api/products/list', (data) => ({
        ...data,
        products: data.products.filter((product) => product._id !== productId),
      }));
      return { success: true };
    } catch (error) {
      return handleError(error, 'Error al eliminar el producto');
    }
  }, [handleError]);

  // Función para agregar un servicio
  const addService = useCallback(async (serviceData) => {
    try {
      const newService = await fetcher('/api/services', 'POST', serviceData);
      mutate('/api/services', (services) => [...services, newService]);
      return newService;
    } catch (error) {
      return handleError(error, 'Error al crear el servicio');
    }
  }, [handleError]);

  // Función para actualizar un servicio
  const updateService = useCallback(async (serviceId, serviceData) => {
    try {
      const updatedService = await fetcher(
        `/api/services/${serviceId}`,
        'PUT',
        serviceData
      );
      mutate('/api/services', (services) =>
        services.map((service) =>
          service._id === serviceId ? updatedService : service
        )
      );
      return updatedService;
    } catch (error) {
      return handleError(error, 'Error al actualizar el servicio');
    }
  }, [handleError]);

  // Función para eliminar un servicio
  const deleteService = useCallback(async (serviceId) => {
    try {
      await fetcher(`/api/services/${serviceId}`, 'DELETE');
      mutate('/api/services', (services) =>
        services.filter((service) => service._id !== serviceId)
      );
      return { success: true };
    } catch (error) {
      return handleError(error, 'Error al eliminar el servicio');
    }
  }, [handleError]);

  // Función para agregar un usuario
  const addUser = useCallback(async (userData) => {
    try {
      const newUser = await fetcher('/api/users', 'POST', userData);
      mutate('/api/users', (users) => [...users, newUser]);
      return newUser;
    } catch (error) {
      return handleError(error, 'Error al agregar usuario');
    }
  }, [handleError]);

  // Función para actualizar un usuario
  const updateUser = useCallback(async (userId, userData) => {
    try {
      const updatedUser = await fetcher(
        `/api/users/${userId}`,
        'PATCH',
        userData
      );
      mutate('/api/users', (users) =>
        users.map((user) => (user._id === userId ? updatedUser : user))
      );
      return updatedUser;
    } catch (error) {
      return handleError(error, 'Error al actualizar el usuario');
    }
  }, [handleError]);

  // Función para eliminar un usuario
  const deleteUser = useCallback(async (userId) => {
    try {
      await fetcher(`/api/users/${userId}`, 'DELETE');
      mutate('/api/users', (users) =>
        users.filter((user) => user._id !== userId)
      );
      return { success: true };
    } catch (error) {
      return handleError(error, 'Error al eliminar el usuario');
    }
  }, [handleError]);

  // Función para actualizar el estado de una orden
  const updateOrderStatus = useCallback(
    async (orderId, newStatus, storeId = null) => {
      try {
        const updatedOrder = await fetcher(
          `/api/orders/${orderId}/status`,
          'PATCH',
          { status: newStatus, storeId }
        );
        mutate('/api/orders', (orders) =>
          orders.map((order) =>
            order._id === orderId ? { ...order, status: newStatus } : order
          )
        );
        return { success: true, data: updatedOrder };
      } catch (error) {
        return handleError(error, 'Error al actualizar el estado de la orden');
      }
    },
    [handleError]
  );

  // Función para actualizar el estado del trabajador
  const updateWorkerStatus = useCallback(
    async (newStatus) => {
      try {
        if (!worker) throw new Error('No autenticado');

        const workerId = worker._id;
        const locationData = location
          ? {
              type: 'Point',
              coordinates: [location.longitude, location.latitude],
            }
          : null;

        const updatedWorker = await fetcher(
          `/api/workers/${workerId}/status`,
          'PUT',
          {
            status: newStatus,
            location: locationData,
          }
        );

        mutate(`/api/workers/${workerId}`, updatedWorker, false);

        setWorker((prev) => ({
          ...prev,
          status: newStatus,
          lastUpdate: new Date(),
          currentLocation: locationData,
        }));

        if (socket) {
          socket.emit('worker_status_update', {
            workerId,
            status: newStatus,
            location: locationData,
          });
        }

        return updatedWorker;
      } catch (error) {
        return handleError(error, 'Error al actualizar estado del worker');
      }
    },
    [worker, location, socket, handleError]
  );

  // Función para aceptar una entrega
  const acceptDelivery = useCallback(
    async (deliveryId, locationData) => {
      try {
        if (!worker) throw new Error('No autenticado');

        const workerId = worker._id;

        const updatedDelivery = await fetcher(
          `/api/workers/${workerId}/deliveries/${deliveryId}/accept`,
          'POST',
          {
            location: {
              type: 'Point',
              coordinates: [locationData.longitude, locationData.latitude],
            },
          }
        );

        mutate(
          `/api/workers/${workerId}/active-deliveries`,
          (deliveries) => [updatedDelivery, ...deliveries],
          false
        );

        mutate(
          `/api/workers/${workerId}/current-delivery`,
          updatedDelivery,
          false
        );

        if (socket) {
          socket.emit('delivery_accepted', {
            deliveryId,
            workerId,
            location: locationData,
            status: 'accepted',
          });
        }

        return { success: true, data: updatedDelivery };
      } catch (error) {
        return handleError(error, 'Error al aceptar la entrega');
      }
    },
    [worker, socket, handleError]
  );

  // Función para actualizar el estado de una entrega
  const updateDeliveryStatus = useCallback(
    async (deliveryId, newStatus, locationData) => {
      try {
        if (!worker) throw new Error('No autenticado');

        const workerId = worker._id;

        const updatedDelivery = await fetcher(
          `/api/workers/${workerId}/deliveries/${deliveryId}/status`,
          'PUT',
          {
            status: newStatus,
            location: {
              type: 'Point',
              coordinates: [locationData.longitude, locationData.latitude],
            },
          }
        );

        mutate(
          `/api/workers/${workerId}/active-deliveries`,
          (deliveries) =>
            deliveries.map((delivery) =>
              delivery._id === deliveryId ? updatedDelivery : delivery
            ),
          false
        );

        if (newStatus === 'delivered') {
          mutate(`/api/workers/${workerId}/current-delivery`, null, false);
          await mutate(`/api/workers/${workerId}/dashboard-stats`);
        } else {
          mutate(
            `/api/workers/${workerId}/current-delivery`,
            updatedDelivery,
            false
          );
        }

        if (socket) {
          socket.emit('delivery_status_update', {
            deliveryId,
            workerId,
            status: newStatus,
            location: locationData,
          });
        }

        return { success: true, data: updatedDelivery };
      } catch (error) {
        return handleError(error, 'Error al actualizar estado de la entrega');
      }
    },
    [worker, socket, handleError]
  );

  // Función para reportar un problema en una entrega
  const reportDeliveryIssue = useCallback(
    async (deliveryId, issue) => {
      try {
        if (!worker) throw new Error('No autenticado');

        const updatedDelivery = await fetcher(
          `/api/deliveries/${deliveryId}/issues`,
          'POST',
          issue
        );

        if (issue.requiresCancellation) {
          mutate(
            `/api/workers/${worker._id}/active-deliveries`,
            (deliveries) =>
              deliveries.filter((delivery) => delivery._id !== deliveryId),
            false
          );
          mutate(`/api/workers/${worker._id}/current-delivery`, null, false);
        }

        return { success: true, data: updatedDelivery };
      } catch (error) {
        return handleError(error, 'Error al reportar problema');
      }
    },
    [worker, handleError]
  );

  // Función para optimizar rutas
  const optimizeRoute = useCallback(
    async (orders, currentLocation) => {
      try {
        const data = await fetcher('/api/routes/optimize', 'POST', {
          orders,
          currentLocation,
        });

        if (data.success) {
          mutate('/api/routes', { ...data }, false);
          return { success: true, data: data.data };
        }
        return { success: false, error: data.message };
      } catch (error) {
        return handleError(error, 'Error al optimizar ruta');
      }
    },
    [handleError]
  );

  // Función para manejar el inicio de sesión
  const handleLogin = useCallback(async (user, role) => {
    try {
      const normalizedRole = role === 'vendor/seller' ? 'seller' : role;

      const response = await fetcher('/users/login', 'POST', {
        username: user.username,
        password: user.password,
        role
      });

      if (response.token) {
        localStorage.setItem(`currentUser_${normalizedRole}`, JSON.stringify({ token: response.token, ...response.user }));
        
        setAuth(prev => ({
          ...prev,
          [normalizedRole]: { user: response.user, loading: false, error: null },
        }));

        // Asegurarse de que el token se incluya en las solicitudes futuras
        // Si fetcher usa una configuración global, asegúrate de que incluya el token
        // Por ejemplo:
        axios.defaults.headers.common['Authorization'] = `Bearer ${response.token}`;

        return { success: true };
      } else {
        return { success: false, message: response.message || 'Error al iniciar sesión' };
      }
    } catch (error) {
      console.error('Error en handleLogin:', error);
      return { success: false, message: 'Error al iniciar sesión' };
    }
  }, [fetcher]);

  // Función para manejar el cierre de sesión
  const handleLogout = useCallback(async (userType) => {
    try {
      localStorage.removeItem(`currentUser_${userType}`);

      setAuth((prev) => ({
        ...prev,
        [userType]: { user: null, loading: false, error: null },
      }));

      if (userType === 'worker') {
        setWorker(null);
        disconnectSocket();
      }

      return { success: true };
    } catch (error) {
      return handleError(error, 'Error en logout');
    }
  }, [disconnectSocket, handleError]);

  // Función para verificar la autenticación
  const checkAuth = useCallback(async (userType) => {
    try {
      const storedUser = localStorage.getItem(`currentUser_${userType}`);
      if (!storedUser) return null;

      const userData = JSON.parse(storedUser);
      const endpoint = `/api/users/${userType}/verify`;

      const data = await fetcher(endpoint, 'GET', null, {
        headers: { Authorization: `Bearer ${userData.token}` },
      });

      if (!data.success) {
        localStorage.removeItem(`currentUser_${userType}`);
        setAuth((prev) => ({
          ...prev,
          [userType]: { user: null, loading: false, error: null },
        }));
        return null;
      }

      setAuth((prev) => ({
        ...prev,
        [userType]: { user: userData, loading: false, error: null },
      }));

      if (userType === 'worker') {
        setWorker(userData);
        connectSocket(userData.token);
      }

      return userData;
    } catch (error) {
      console.error(`Error verificando autenticación para ${userType}:`, error);
      localStorage.removeItem(`currentUser_${userType}`);
      setAuth((prev) => ({
        ...prev,
        [userType]: { user: null, loading: false, error: error.message },
      }));
      return null;
    }
  }, [connectSocket]);

  // Función para actualizar la disponibilidad del trabajador
  const updateWorkerAvailability = useCallback(
    async (newStatus) => {
      try {
        if (!location) {
          throw new Error(
            'Se requiere acceso a la ubicación para cambiar el estado'
          );
        }

        const response = await updateWorkerStatus(newStatus);

        setWorkerStatus((prev) => ({
          ...prev,
          isAvailable: newStatus === 'active',
          currentStatus: newStatus,
          lastUpdate: new Date(),
        }));

        if (socket) {
          socket.emit('worker_status_update', {
            workerId: worker._id,
            status: newStatus,
            location: {
              type: 'Point',
              coordinates: [location.longitude, location.latitude],
            },
          });
        }

        return { success: true, data: response.data };
      } catch (error) {
        return handleError(
          error,
          'Error al actualizar disponibilidad del worker'
        );
      }
    },
    [location, updateWorkerStatus, socket, worker, handleError]
  );

  // Función para manejar nuevas órdenes de entrega
  const handleNewDeliveryOrder = useCallback((order) => {
    // Lógica para manejar nuevas órdenes
  }, []);

  // Función para actualizar el perfil del trabajador
  const updateWorkerProfile = useCallback(
    async (profileData) => {
      try {
        const data = await fetcher(
          `/api/workers/${worker?._id}`,
          'PUT',
          profileData
        );
        if (data.success) {
          setWorkerProfile(data.data);
          setWorker((prev) => ({ ...prev, ...data.data }));
          return { success: true, data: data.data };
        }
        return { success: false, error: data.message };
      } catch (error) {
        return handleError(error, 'Error al actualizar el perfil');
      }
    },
    [worker, handleError]
  );

  // ===========================
  // Efectos Iniciales
  // ===========================

  // Efecto para inicializar la autenticación al montar el componente
  useEffect(() => {
    const initializeAuth = async () => {
      await Promise.all([
        checkAuth('admin'),
        checkAuth('seller'),
        checkAuth('worker'),
      ]);
    };

    initializeAuth();
  }, [checkAuth]);

  // Efecto para actualizar la ubicación del trabajador en tiempo real
  useEffect(() => {
    if (
      socket &&
      isConnected &&
      worker?._id &&
      location &&
      worker.status === 'active'
    ) {
      const locationData = {
        type: 'Point',
        coordinates: [location.longitude, location.latitude],
      };

      socket.emit('worker_location_update', {
        workerId: worker._id,
        location: locationData,
      });
    }
  }, [socket, isConnected, worker, location]);

  // Modificar el useEffect para cargar usuarios
  useEffect(() => {
    const loadUsers = async () => {
      try {
        const response = await fetch(`${API_BASE_URL}/api/users/available`);
        const users = await response.json();

        if (users.success) {
          setAvailableUsers(users.data);
        } else {
          setLoginError(users.message || 'Error al cargar usuarios disponibles');
        }
      } catch (error) {
        setLoginError('Error al cargar usuarios disponibles');
      }
    };

    if (showLoginModal) {
      loadUsers();
    }
  }, [showLoginModal]);

  // Efecto para mostrar el modal de login cuando no hay usuario autenticado
  useEffect(() => {
    if (!auth.admin.user && !auth.seller.user && !auth.worker.user) {
      setShowLoginModal(true);
    } else {
      setShowLoginModal(false);
    }
  }, [auth.admin.user, auth.seller.user, auth.worker.user]);

  // ===========================
  // Valor del Contexto
  // ===========================

  const { stats, isLoading: statsLoading, isError: statsError } = useStats();
  const { alerts, isLoading: alertsLoading, isError: alertsError } = useAlerts();
  const { stores, isLoading: storesLoading, isError: storesError } = useStores();
  const { cooperatives, isLoading: cooperativesLoading, isError: cooperativesError } = useCooperatives();
  const { products, services: storeServices, isLoading: productsServicesLoading, isError: productsServicesError } = useProductsAndServices(currentStoreId);
  const { users, totalUsers, totalPages, currentPage, hasMore, isLoading: usersLoading, isError: usersError } = useUsers();
  const { orders, isLoading: ordersLoading, isError: ordersError } = useOrders();
  const { services, isLoading: servicesLoading, isError: servicesError } = useServices();
  const { activeDeliveries, isLoading: activeDeliveriesLoading, isError: activeDeliveriesError } = useActiveDeliveries(worker?._id);
  const { currentDelivery, isLoading: currentDeliveryLoading, isError: currentDeliveryError } = useCurrentDelivery(worker?._id);
  const { dashboardStats, isLoading: dashboardStatsLoading, isError: dashboardStatsError } = useDashboardStats(worker?._id);
  const { workerEarnings, isLoading: workerEarningsLoading, isError: workerEarningsError } = useWorkerEarnings();
  const { deliveryHistory, isLoading: deliveryHistoryLoading, isError: deliveryHistoryError } = useDeliveryHistory();
  const { workerDocuments, isLoading: workerDocumentsLoading, isError: workerDocumentsError } = useWorkerDocuments();
  const { activeChats, isLoading: activeChatsLoading, isError: activeChatsError } = useActiveChats();
  const { deliveryMetrics, isLoading: deliveryMetricsLoading, isError: deliveryMetricsError } = useDeliveryMetrics();
  const { workerDashboard, isLoading: workerDashboardLoading, isError: workerDashboardError } = useWorkerDashboard(worker?._id);
  const { smartRoutes, isLoading: smartRoutesLoading, isError: smartRoutesError } = useSmartRoutes();
  const { storeDeliveries, isLoading: storeDeliveriesLoading, isError: storeDeliveriesError } = useStoreDeliveries(currentStoreId);
  const { storeDetails, isLoading: storeDetailsLoading, isError: storeDetailsError } = useStoreDetails(currentStoreId);
  const { wholesaleProposals, isLoading: wholesaleProposalsLoading, isError: wholesaleProposalsError } = useWholesaleProposals(worker?._id);

  const value = useMemo(() => {
    return {
      // Datos obtenidos por SWR
      stats,
      statsLoading,
      statsError,
      alerts,
      alertsLoading,
      alertsError,
      stores,
      storesLoading,
      storesError,
      cooperatives,
      cooperativesLoading,
      cooperativesError,
      products,
      services: storeServices,
      productsServicesLoading,
      productsServicesError,
      users,
      totalUsers,
      totalPages,
      currentPage,
      hasMore,
      usersLoading,
      usersError,
      orders,
      ordersLoading,
      ordersError,
      services,
      servicesLoading,
      servicesError,

      activeDeliveries,
      activeDeliveriesLoading,
      activeDeliveriesError,
      currentDelivery,
      currentDeliveryLoading,
      currentDeliveryError,
      dashboardStats,
      dashboardStatsLoading,
      dashboardStatsError,

      workerEarnings,
      workerEarningsLoading,
      workerEarningsError,
      deliveryHistory,
      deliveryHistoryLoading,
      deliveryHistoryError,
      workerDocuments,
      workerDocumentsLoading,
      workerDocumentsError,
      activeChats,
      activeChatsLoading,
      activeChatsError,
      deliveryMetrics,
      deliveryMetricsLoading,
      deliveryMetricsError,
      workerDashboard,
      workerDashboardLoading,
      workerDashboardError,
      smartRoutes,
      smartRoutesLoading,
      smartRoutesError,
      storeDeliveries,
      storeDeliveriesLoading,
      storeDeliveriesError,
      storeDetails,
      storeDetailsLoading,
      storeDetailsError,
      wholesaleProposals,
      wholesaleProposalsLoading,
      wholesaleProposalsError,

      // Estados globales
      worker,
      workerLoading,
      workerError,
      error,
      validationErrors,
      notifications,
      socketError,
      currentStoreId,
      setCurrentStoreId,
      currentStore,
      setCurrentStore,
      storeSettings,
      setStoreSettings,
      workerStatus,
      workerProfile,
      auth,

      // Funciones de mutación y acciones
      addStore,
      updateStore,
      deleteStore,
      addCooperative,
      updateCooperative,
      deleteCooperative,
      addProduct,
      updateProduct,
      deleteProduct,
      addService,
      updateService,
      deleteService,
      addUser,
      updateUser,
      deleteUser,
      updateOrderStatus,
      updateWorkerStatus,
      acceptDelivery,
      updateDeliveryStatus,
      reportDeliveryIssue,
      optimizeRoute,
      handleLogin,
      handleLogout,
      checkAuth,
      updateWorkerAvailability,
      handleNewDeliveryOrder,
      updateWorkerProfile,
      availableUsers,
      setAvailableUsers,
      loginError,
      setLoginError,
      showLoginModal,
      setShowLoginModal,
    };
  }, [
    // Dependencias de los valores obtenidos fuera de useMemo
    stats,
    statsLoading,
    statsError,
    alerts,
    alertsLoading,
    alertsError,
    stores,
    storesLoading,
    storesError,
    cooperatives,
    cooperativesLoading,
    cooperativesError,
    products,
    storeServices,
    productsServicesLoading,
    productsServicesError,
    users,
    totalUsers,
    totalPages,
    currentPage,
    hasMore,
    usersLoading,
    usersError,
    orders,
    ordersLoading,
    ordersError,
    services,
    servicesLoading,
    servicesError,

    activeDeliveries,
    activeDeliveriesLoading,
    activeDeliveriesError,
    currentDelivery,
    currentDeliveryLoading,
    currentDeliveryError,
    dashboardStats,
    dashboardStatsLoading,
    dashboardStatsError,

    workerEarnings,
    workerEarningsLoading,
    workerEarningsError,
    deliveryHistory,
    deliveryHistoryLoading,
    deliveryHistoryError,
    workerDocuments,
    workerDocumentsLoading,
    workerDocumentsError,
    activeChats,
    activeChatsLoading,
    activeChatsError,
    deliveryMetrics,
    deliveryMetricsLoading,
    deliveryMetricsError,
    workerDashboard,
    workerDashboardLoading,
    workerDashboardError,
    smartRoutes,
    smartRoutesLoading,
    smartRoutesError,
    storeDeliveries,
    storeDeliveriesLoading,
    storeDeliveriesError,
    storeDetails,
    storeDetailsLoading,
    storeDetailsError,
    wholesaleProposals,
    wholesaleProposalsLoading,
    wholesaleProposalsError,

    // Dependencias de los estados y funciones
    worker,
    workerLoading,
    workerError,
    error,
    validationErrors,
    notifications,
    socketError,
    currentStoreId,
    currentStore,
    storeSettings,
    workerStatus,
    workerProfile,
    auth,

    // Funciones
    addStore,
    updateStore,
    deleteStore,
    addCooperative,
    updateCooperative,
    deleteCooperative,
    addProduct,
    updateProduct,
    deleteProduct,
    addService,
    updateService,
    deleteService,
    addUser,
    updateUser,
    deleteUser,
    updateOrderStatus,
    updateWorkerStatus,
    acceptDelivery,
    updateDeliveryStatus,
    reportDeliveryIssue,
    optimizeRoute,
    handleLogin,
    handleLogout,
    checkAuth,
    updateWorkerAvailability,
    handleNewDeliveryOrder,
    updateWorkerProfile,
    availableUsers,
    loginError,
    showLoginModal,
  ]);

  return (
    <GlobalContext.Provider value={value}>{children}</GlobalContext.Provider>
  );
};

// Función auxiliar para obtener la clase CSS según el estado de la orden
const getOrderStatusClass = (status) => {
  switch (status.toLowerCase()) {
    case 'pending':
      return 'status-pending';
    case 'completed':
      return 'status-completed';
    case 'cancelled':
      return 'status-cancelled';
    default:
      return 'status-unknown';
  }
};

// Función auxiliar para formatear cantidades monetarias
const formatCurrency = (amount, currency = 'USD') => {
  return new Intl.NumberFormat('es-ES', {
    style: 'currency',
    currency,
  }).format(amount);
};

export default GlobalContext;

 y los modelos 1.const mongoose = require('mongoose');
const mongooseDelete = require('mongoose-delete');

const variationSchema = new mongoose.Schema({
  title: { type: String, required: true },
  price: { type: Number, required: true },
}, { _id: false });

const categorySchema = new mongoose.Schema({
  name: { type: String, required: true },
  subcategories: [{ type: String }],
}, { _id: false });

const priceTierSchema = new mongoose.Schema({
  minQuantity: { type: Number, required: true },
  maxQuantity: { type: Number },
  price: { type: Number, required: true },
  discount: { type: Number },
}, { _id: false });

const lotSchema = new mongoose.Schema({
  lotNumber: { type: String, required: true },
  entryDate: { type: Date, default: Date.now },
  expirationDate: { type: Date },
  harvestDate: { type: Date },
  quantity: { type: Number, required: true, min: 0 },
  sourceModel: {
    type: String,
    required: true,
    enum: ['Seller', 'Store', 'Cooperative', 'Other'],
  },
  source: {
    type: mongoose.Schema.Types.ObjectId,
    required: true,
    refPath: 'lots.sourceModel',
  },
  qualityGrade: { type: String, enum: ['A', 'B', 'C'] },
  notes: String,
}, { _id: false });

const storageConditionsSchema = new mongoose.Schema({
  temperature: {
    min: Number,
    max: Number,
    unit: { type: String, enum: ['C', 'F'], default: 'C' }
  },
  humidity: {
    min: Number,
    max: Number
  },
  specialInstructions: String
}, { _id: false });

const productSchema = new mongoose.Schema({
  name: { type: String, required: true, trim: true },
  presentations: [{
    type: {
      type: String,
      required: true,
      enum: {
        values: ['BOLSA', 'CAJA', 'TULA', 'BOTELLA', 'FRASCO', 'LATA', 'PAQUETE', 'SACO', 'OTRO'],
        message: 'Tipo de presentación no válido'
      }
    },
    customType: {
      type: String,
      required: function() {
        return this.type === 'OTRO';
      },
      validate: {
        validator: function(v) {
          return this.type !== 'OTRO' || (v && v.length >= 2);
        },
        message: 'Debe especificar un tipo de presentación personalizado de al menos 2 caracteres'
      }
    },
    description: { type: String },
    isDefault: { type: Boolean, default: false }
  }],
  category: {
    type: categorySchema,
    required: true,
  },
  type: {
    type: String,
    required: true,
    enum: ['nuevo', 'usado', 'reacondicionado', 'servicio', 'subasta', 'perecedero', 'no perecedero'],
  },
  description: { type: String, trim: true },
  quantity: { type: Number, required: true, min: 0 },
  purchasePrice: { type: Number, min: 0 }, // Eliminado required
  salePrice: { type: Number, min: 0 },     // Eliminado required
  marketPrice: { type: Number, min: 0 },
  wholesalePrice: { type: Number, min: 0 },
  minOrderQuantity: { type: Number, default: 1, min: 1 },
  images: [{ type: String }],
  unit: {
    type: String,
    required: true,
    enum: ['KILO', 'GRAMO', 'LITRO', 'MILILITRO', 'UNIDAD', 'DOCENA', 'CAJA', 'PAQUETE'],
    default: 'UNIDAD'
  },
  alternativeUnits: [{
    unit: {
      type: String,
      enum: ['KILO', 'GRAMO', 'LITRO', 'MILILITRO', 'UNIDAD', 'DOCENA', 'CAJA', 'PAQUETE']
    },
    conversionFactor: Number
  }],
  pricePerUnit: { type: Number, required: true, min: 0 },
  variations: [variationSchema],
  discount: { type: Boolean, default: false },
  discountedPrice: {
    type: Number,
    min: 0,
    validate: {
      validator: function(v) {
        // Validar solo si discount es true y salePrice está definido
        return !this.discount || (this.salePrice != null && v < this.salePrice);
      },
      message: 'El precio con descuento debe ser menor al precio de venta'
    }
  },
  expirationDate: {
    type: Date,
    required: function() { return this.type === 'perecedero'; },
    validate: {
      validator: function(v) {
        return this.type !== 'perecedero' || v > new Date();
      },
      message: 'La fecha de expiración debe ser futura'
    }
  },
  storageConditions: {
    type: storageConditionsSchema,
    required: function() {
      return this.type === 'perecedero';
    }
  },
  isWholesale: { type: Boolean, default: false },
  isDirectSale: { type: Boolean, default: true },
  visible: { type: Boolean, default: true },
  status: {
    type: String,
    enum: ['active', 'outOfStock', 'discontinued', 'comingSoon'],
    default: 'active'
  },
  priceTiers: [priceTierSchema],
  lots: [lotSchema],
  seller: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Seller',
    required: false  // Cambiado a false
  },
  store: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Store',
    required: true
  },
  cooperative: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Cooperative',
  },
  tags: [String],
  ratings: {
    average: { type: Number, default: 0 },
    count: { type: Number, default: 0 }
  },
  storeId: { type: mongoose.Schema.Types.ObjectId, ref: 'Store', required: true },
}, {
  timestamps: true,
  toJSON: { virtuals: true },
  toObject: { virtuals: true }
});

// Plugins y middlewares
productSchema.plugin(mongooseDelete, { overrideMethods: 'all', deletedAt: true });

// Índices para mejorar el rendimiento de búsquedas
productSchema.index({ name: 'text', description: 'text', tags: 'text' });
productSchema.index({ 'category.name': 1 });
productSchema.index({ type: 1 });
productSchema.index({ visible: 1 });

productSchema.pre('save', function(next) {
  // Validar que los lotes tengan los campos necesarios
  if (this.lots && this.lots.length > 0) {
    for (const lot of this.lots) {
      if (!lot.source || !lot.sourceModel) {
        return next(new Error('Cada lote debe tener un origen y un modelo de origen.'));
      }
    }

    // Actualizar cantidad total basada en lotes
    this.quantity = this.lots.reduce((sum, lot) => sum + lot.quantity, 0);
  }

  // Validar precios solo si existen
  if (this.discountedPrice != null) {
    if (this.salePrice == null) {
      return next(new Error('Debe proporcionar el precio de venta si se aplica un descuento.'));
    }
    if (this.discountedPrice >= this.salePrice) {
      return next(new Error('El precio con descuento debe ser menor al precio de venta'));
    }
  }

  // Validar que exista al menos una presentación por defecto
  if (this.presentations && this.presentations.length > 0) {
    const defaultPresentation = this.presentations.find(p => p.isDefault);
    if (!defaultPresentation) {
      return next(new Error('Debe existir al menos una presentación marcada como predeterminada'));
    }
  } else {
    return next(new Error('Debe especificar al menos una presentación para el producto'));
  }

  next();
});

productSchema.post('save', function(doc, next) {
  console.log(`Producto '${doc.name}' guardado exitosamente.`);
  next();
});

productSchema.post('remove', function(doc, next) {
  console.log(`Producto '${doc.name}' eliminado exitosamente.`);
  next();
});

module.exports = mongoose.model('Product', productSchema);
2. const mongoose = require('mongoose');

const serviceSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true
  },
  description: {
    type: String,
    required: true,
    trim: true
  },
  category: {
    type: String,
    required: true,
    enum: ['Delivery', 'Transport', 'Maintenance', 'Professional', 'Other']
  },
  price: {
    type: Number,
    required: true,
    min: 0
  },
  priceType: {
    type: String,
    enum: ['fixed', 'hourly', 'variable'],
    default: 'fixed'
  },
  duration: {
    type: Number, // duración en minutos
    required: true
  },
  availability: [{
    day: {
      type: String,
      enum: ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
    },
    slots: [{
      startTime: String,
      endTime: String
    }]
  }],
  provider: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  store: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Store'
  },
  cooperative: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Cooperative'
  },
  status: {
    type: String,
    enum: ['active', 'inactive', 'pending'],
    default: 'active'
  },
  ratings: [{
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
    },
    rating: {
      type: Number,
      min: 1,
      max: 5
    },
    comment: String,
    date: {
      type: Date,
      default: Date.now
    }
  }],
  averageRating: {
    type: Number,
    default: 0
  }
}, {
  timestamps: true
});

// Middleware para calcular el rating promedio
serviceSchema.pre('save', function(next) {
  if (this.ratings.length > 0) {
    this.averageRating = this.ratings.reduce((acc, curr) => acc + curr.rating, 0) / this.ratings.length;
  }
  next();
});

module.exports = mongoose.model('Service', serviceSchema);
3.const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const storeSchema = new Schema({
  name: {
    type: String,
    required: true,
    trim: true
  },
  description: {
    type: String,
    trim: true
  },
  owner: {
    type: Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  products: [{
    type: Schema.Types.ObjectId,
    ref: 'Product'
  }],
  services: [{
    type: Schema.Types.ObjectId,
    ref: 'Service'
  }],
  parentStore: {
    type: Schema.Types.ObjectId,
    ref: 'Store'
  },
  childStores: [{
    type: Schema.Types.ObjectId,
    ref: 'Store'
  }],
  category: {
    type: String,
    required: true,
    enum: ['retail', 'wholesale', 'service', 'manufacturing', 'other']
  },
  categories: [{
    name: {
      type: String,
      required: true
    },
    description: String,
    parent: {
      type: Schema.Types.ObjectId,
      ref: 'Store.categories'
    }
  }],
  status: {
    type: String,
    enum: ['active', 'inactive', 'pending', 'suspended'],
    default: 'pending'
  },
  location: {
    address: String,
    city: String,
    state: String,
    country: String,
    coordinates: {
      type: {
        type: String,
        enum: ['Point'],
        default: 'Point'
      },
      coordinates: {
        type: [Number],
        default: [0, 0]
      }
    }
  },
  employees: [{
    type: Schema.Types.ObjectId,
    ref: 'User'
  }],
  ratings: [{
    user: {
      type: Schema.Types.ObjectId,
      ref: 'User'
    },
    rating: {
      type: Number,
      min: 1,
      max: 5
    },
    comment: String,
    date: {
      type: Date,
      default: Date.now
    }
  }],
  schedule: {
    monday: { open: String, close: String },
    tuesday: { open: String, close: String },
    wednesday: { open: String, close: String },
    thursday: { open: String, close: String },
    friday: { open: String, close: String },
    saturday: { open: String, close: String },
    sunday: { open: String, close: String }
  }
}, {
  timestamps: true,
  toJSON: { virtuals: true },
  toObject: { virtuals: true }
});

// Índices
storeSchema.index({ 'location.coordinates': '2dsphere' });
storeSchema.index({ name: 'text', description: 'text' });

module.exports = mongoose.model('Store', storeSchema);