import { create } from 'zustand';

interface AuthGateState {
  open: boolean;
  pendingCallback: (() => void) | null;
  triggerAuth: (callback?: () => void) => void;
  close: () => void;
  consumeCallback: () => void;
}

export const useAuthGateStore = create<AuthGateState>((set, get) => ({
  open: false,
  pendingCallback: null,
  triggerAuth: (callback) => set({ open: true, pendingCallback: callback ?? null }),
  close: () => set({ open: false, pendingCallback: null }),
  consumeCallback: () => {
    const cb = get().pendingCallback;
    if (cb) {
      // Close modal first, then fire the blocked action.
      // No-callback path (wishlist-merge sites): noop — modal stays open.
      set({ pendingCallback: null, open: false });
      cb();
    }
  },
}));
