import {create} from 'zustand';
import {persist} from 'zustand/middleware';
import {isBrowser} from "motion/react";

interface AuthData {
  id: number;
  phone: string;
  access_token: string;
}

interface AuthState {
  isAuthenticated: boolean;
  user: AuthData | null;
  login: (data: AuthData) => void;
  logout: () => void;
}

export const useAuthStore = create<AuthState>()(
    persist(
        (set) => ({
          user: isBrowser && typeof window !== "undefined" ? JSON.parse(localStorage.getItem('auth-store') || 'null') : null,
          login: (data) => {
            set({user: data});
            if (isBrowser && typeof window !== "undefined") {
              localStorage.setItem('auth-store', JSON.stringify(data));
            }
          },
          logout: () => {
            set({user: null});
            if (isBrowser && typeof window !== "undefined") {
              localStorage.removeItem('auth-store');
            }
          },
          isAuthenticated: isBrowser && typeof window !== "undefined" && localStorage.getItem("auth-store") !== null,
        }),
        {
          name: 'auth-store',
        }
    )
);

