import { create } from 'zustand';
import { AuthAPI, AuthUser } from '../api';

interface AuthState {
  user: AuthUser | null;
  loading: boolean;
  /** 启动时调用：从后端拉当前登录态 */
  bootstrap: () => Promise<void>;
  login: (email: string, password: string) => Promise<void>;
  register: (p: { email: string; password: string; name: string; inviteCode?: string }) => Promise<void>;
  logout: () => Promise<void>;
}

const loadSavedUser = (): AuthUser | null => {
  try {
    const raw = localStorage.getItem('mock-user');
    if (!raw) return null;
    return JSON.parse(raw) as AuthUser;
  } catch {
    return null;
  }
};

export const useAuth = create<AuthState>((set) => ({
  user: typeof localStorage === 'undefined' ? null : loadSavedUser(),
  loading: false,
  bootstrap: async () => {
    set({ loading: false });
  },
  login: async (email, password) => {
    const ok = await AuthAPI.verify(email, password);
    if (!ok) throw new Error('身份验证失败');
    const u: AuthUser = {
      id: 'mock',
      email,
      name: email.split('@')[0] || 'User',
      role: 'user'
    };
    try {
      localStorage.setItem('mock-auth', '1');
      localStorage.setItem('mock-user', JSON.stringify(u));
    } catch {
    }
    set({ user: u });
  },
  register: async (p) => {
    const u = await AuthAPI.register(p);
    set({ user: u });
  },
  logout: async () => {
    try {
      await AuthAPI.logout();
    } catch {
    }
    try {
      localStorage.removeItem('mock-auth');
      localStorage.removeItem('mock-user');
    } catch {
    }
    set({ user: null });
  }
}));
