import { createStore, StoreApi, useStore } from "zustand";
import React from "react";
import { ActivityIndicator } from "react-native";
import { User } from "@/types/user.types";
import { useAuthStore } from "@/stores/auth";

const UserStoreContext = React.createContext<StoreApi<User> | null>(null);

export const UserStoreProvider = ({ children }: { children: React.ReactNode }) => {
  const { user, loading } = useAuthStore();

  if (loading) {
    return <ActivityIndicator />;
  }

  if (!user) {
    return null;
  }

  const store = createStore<User>()(() => user);

  return (
    <UserStoreContext.Provider value={store as StoreApi<User>}>
      {children}
    </UserStoreContext.Provider>
  );
};

export const useUser = () => {
  const store = React.useContext(UserStoreContext);
  if (!store) {
    throw new Error("Missing UserStoreProvider");
  }
  return useStore(store);
};
