// store/orderStore.ts
import { CartItem } from '@/features/cart/lib/api';
import { create } from 'zustand';

type State = {
  order: CartItem | null;
};

type Actions = {
  setOrder: (order: CartItem) => void;
};

const getInitialOrder = (): CartItem | null => {
  if (typeof window === 'undefined') return null; // SSR check
  const stored = localStorage.getItem('order');
  if (!stored) return null;
  try {
    return JSON.parse(stored);
  } catch (err) {
    console.error('Failed to parse order from localStorage', err);
    return null;
  }
};

const useOrderStore = create<State & Actions>((set) => ({
  order: getInitialOrder(),
  setOrder: (order: CartItem) => {
    if (typeof window !== 'undefined') {
      localStorage.setItem('order', JSON.stringify(order));
    }
    set({ order });
  },
}));

export default useOrderStore;
