import { Link } from '@remix-run/react'; import { useAuth } from '~/lib/hooks/useAuth'; import { useState, useEffect } from 'react'; /** * Authentication controls component for the header * Separated into a client component to prevent module loading issues */ export default function HeaderAuthControls() { // Error state for component-level error handling const [renderError, setRenderError] = useState(null); // Call useAuth at the top level of the component as required by React hooks rules let authState; try { // Properly use the hook at component top level authState = useAuth(); } catch (error) { console.error('Error initializing auth hook:', error); // Return fallback UI immediately if hook initialization fails return (
); } // Safely extract values from auth state const { isAuthenticated, isLoading, user, login, logout } = authState || {}; // Reset render error when dependencies change useEffect(() => { if (renderError) { setRenderError(null); } }, [isAuthenticated, isLoading, user]); // Safely handle login with fallback const handleLogin = () => { try { if (typeof login === 'function') { login(); } else { // Fallback if login function is unavailable window.location.href = '/auth/login'; } } catch (error) { console.error('Error during login:', error); // Fallback to direct navigation on error window.location.href = '/auth/login'; } }; // Safely handle logout with fallback const handleLogout = () => { try { if (typeof logout === 'function') { logout(); } else { // Fallback if logout function is unavailable window.location.href = '/auth/logout'; } } catch (error) { console.error('Error during logout:', error); // Fallback to direct navigation on error window.location.href = '/auth/logout'; } }; // Handle loading state if (isLoading) { return (
); } // Handle render errors if (renderError) { return (
); } try { // Handle authenticated state if (isAuthenticated && user) { return (
Signed in as {user.username || 'User'}
Your profile
); } // Handle unauthenticated state (default) return ( ); } catch (error) { // Catch any rendering errors console.error('Error rendering auth controls:', error); setRenderError(error instanceof Error ? error : new Error(String(error))); // Return fallback UI return ( ); } }