import { create } from 'zustand';
import { User } from '../types/auth';
import axios from 'axios';

interface AuthState {
  user: User | null;
  loading: boolean;
  setUser: (user: User | null) => void;
  setLoading: (loading: boolean) => void;
  login: (email: string, password: string, tempUser?: User) => Promise<void>;
  logout: () => void;
}

export const useAuthStore = create<AuthState>((set) => ({
  user: null,
  loading: false,
  setUser: (user) => set({ user }),
  setLoading: (loading) => set({ loading }),
  login: async (email: string, password: string, tempUser?: User) => {
    try {
      set({ loading: true });
      
      if (tempUser) {
        // Use temporary user for development
        set({ user: tempUser });
        localStorage.setItem('tempUser', JSON.stringify(tempUser));
        return;
      }

      const response = await axios.post('/api/auth/login', {
        email,
        password
      });
      const { user, token } = response.data;
      localStorage.setItem('token', token);
      set({ user });
    } finally {
      set({ loading: false });
    }
  },
  logout: () => {
    localStorage.removeItem('token');
    localStorage.removeItem('tempUser');
    set({ user: null });
  }
}));