'use client';

import { createOrderStore } from './store';
import { createContext, type PropsWithChildren, useRef } from 'react';

export type OrderStoreApi = ReturnType<typeof createOrderStore>;

export const OrderStoreContext = createContext<OrderStoreApi | undefined>(undefined);

export function OrderStoreProvider({ children }: Readonly<PropsWithChildren>) {
  const storeRef = useRef<null | OrderStoreApi>(null);
  if (storeRef.current === null) {
    storeRef.current = createOrderStore();
  }

  return <OrderStoreContext value={storeRef.current}>{children}</OrderStoreContext>;
}
