import React, { createContext, useContext, useState, useEffect } from 'react';

const AuthContext = createContext(null);

export function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // Check for stored session on mount
    const stored = localStorage.getItem('aethex_user');
    if (stored) {
      try {
        setUser(JSON.parse(stored));
      } catch (e) {
        localStorage.removeItem('aethex_user');
      }
    }
    setLoading(false);
  }, []);

  const login = (userData) => {
    const userWithDefaults = {
      id: Date.now(),
      email: userData.email,
      username: userData.username || userData.email.split('@')[0],
      displayName: userData.displayName || userData.email.split('@')[0],
      avatar: null,
      createdAt: new Date().toISOString(),
      ...userData,
    };
    setUser(userWithDefaults);
    localStorage.setItem('aethex_user', JSON.stringify(userWithDefaults));
  };

  const register = (userData) => {
    const newUser = {
      id: Date.now(),
      email: userData.email,
      username: userData.username,
      displayName: userData.displayName || userData.username,
      avatar: null,
      createdAt: new Date().toISOString(),
      ...userData,
    };
    setUser(newUser);
    localStorage.setItem('aethex_user', JSON.stringify(newUser));
  };

  const logout = () => {
    setUser(null);
    localStorage.removeItem('aethex_user');
  };

  const updateUser = (updates) => {
    const updated = { ...user, ...updates };
    setUser(updated);
    localStorage.setItem('aethex_user', JSON.stringify(updated));
  };

  return (
    <AuthContext.Provider value={{ 
      user, 
      loading, 
      isAuthenticated: !!user,
      login, 
      register, 
      logout,
      updateUser,
    }}>
      {children}
    </AuthContext.Provider>
  );
}

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

export default AuthContext;
