import { createContext, useContext, useState, useEffect, type ReactNode } from "react";
import { CURRENT_USER } from "@/data/mockData";
import type { MockUser } from "@/data/mockData";

interface AuthContextType {
  user: MockUser | null;
  isLoggedIn: boolean;
  isLoading: boolean;
  login: (email: string, password: string) => boolean;
  logout: () => void;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<MockUser | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const stored = localStorage.getItem("gemtrack_logged_in");
    if (stored === "true") {
      setUser(CURRENT_USER);
    }
    setIsLoading(false);
  }, []);

  const login = (email: string, password: string): boolean => {
    if (email && password) {
      setUser(CURRENT_USER);
      localStorage.setItem("gemtrack_logged_in", "true");
      return true;
    }
    return false;
  };

  const logout = () => {
    setUser(null);
    localStorage.removeItem("gemtrack_logged_in");
  };

  return (
    <AuthContext.Provider value={{ user, isLoggedIn: !!user, isLoading, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  const context = useContext(AuthContext);
  if (!context) throw new Error("useAuth must be used within AuthProvider");
  return context;
}
