"use client";

import { useState, useEffect, ReactNode } from "react";
import { AuthContext, getStoredToken, getStoredUser, setStoredToken, setStoredUser } from "@/lib/auth";
import { User } from "@/lib/api";

export default function AuthProvider({ children }: { children: ReactNode }) {
  const [token, setToken] = useState<string | null>(null);
  const [user, setUser] = useState<User | null>(null);
  const [loaded, setLoaded] = useState(false);

  useEffect(() => {
    setToken(getStoredToken());
    setUser(getStoredUser());
    setLoaded(true);
  }, []);

  function setAuth(newToken: string | null, newUser: User | null) {
    setToken(newToken);
    setUser(newUser);
    setStoredToken(newToken);
    setStoredUser(newUser);
  }

  function logout() {
    setAuth(null, null);
  }

  if (!loaded) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
      </div>
    );
  }

  return (
    <AuthContext.Provider value={{ token, user, setAuth, logout }}>
      {children}
    </AuthContext.Provider>
  );
}
