import { create } from 'zustand';

export interface User {
  id: string;
  username: string;
  email: string;
  role: 'user' | 'moderator' | 'admin' | 'owner';
  tier: 'normal' | 'premium' | 'vip';
  mmr: number;
  wins: number;
  losses: number;
  matches_played: number;
  current_streak: number;
  placement_done: boolean;
  steam_id: string | null;
  steam_persona_name: string | null;
  steam_avatar_url: string | null;
  steam_linked_at: string | null;
  profile_banner: string | null;
  created_at: string;
  last_match_at: string | null;
}

interface AuthState {
  token: string | null;
  refreshToken: string | null;
  user: User | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  setToken: (token: string) => void;
  setRefreshToken: (refreshToken: string) => void;
  setUser: (user: User) => void;
  login: (token: string, refreshToken: string | null, user: User) => void;
  logout: () => void;
  updateUser: (partial: Partial<User>) => void;
  setLoading: (loading: boolean) => void;
}

const savedToken = localStorage.getItem('token');
const savedRefreshToken = localStorage.getItem('refresh_token');

export const useAuthStore = create<AuthState>((set) => ({
  token: savedToken,
  refreshToken: savedRefreshToken,
  user: null,
  isAuthenticated: !!savedToken,
  isLoading: !!savedToken,

  setToken: (token) => {
    localStorage.setItem('token', token);
    set({ token, isAuthenticated: true });
  },

  setRefreshToken: (refreshToken) => {
    localStorage.setItem('refresh_token', refreshToken);
    set({ refreshToken });
  },

  setUser: (user) => set({ user }),

  login: (token, refreshToken, user) => {
    localStorage.setItem('token', token);
    if (refreshToken) {
      localStorage.setItem('refresh_token', refreshToken);
    }
    set({ token, refreshToken: refreshToken ?? null, user, isAuthenticated: true, isLoading: false });
  },

  logout: () => {
    localStorage.removeItem('token');
    localStorage.removeItem('refresh_token');
    set({ token: null, refreshToken: null, user: null, isAuthenticated: false, isLoading: false });
  },

  updateUser: (partial) =>
    set((state) => ({
      user: state.user ? { ...state.user, ...partial } : null,
    })),

  setLoading: (isLoading) => set({ isLoading }),
}));
