import React, { useState, useEffect } from 'react'; import { useLocation, useNavigate, useParams } from 'react-router-dom'; import { useAuth } from '../contexts/AuthContext'; import { useOrg } from '../contexts/OrgContext'; import { Card, Button } from '../components/UiKit'; const Login: React.FC = () => { const navigate = useNavigate(); const location = useLocation(); const { inviteCode: routeInviteCode } = useParams<{ inviteCode: string }>(); const [email, setEmail] = useState('demo@auditly.com'); const [password, setPassword] = useState('demo123'); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(''); const [inviteCode, setInviteCode] = useState(null); const { signInWithGoogle, signInWithEmail, signUpWithEmail, user, loading } = useAuth(); const { consumeInvite, org } = useOrg(); useEffect(() => { // Check for invite code in route params first, then fallback to query params if (routeInviteCode) { console.log('Invite code from route params:', routeInviteCode); setInviteCode(routeInviteCode); // Clear demo credentials for invite flow setEmail(''); setPassword(''); } else { // Extract query params from hash-based URL const hashSearch = location.hash.includes('?') ? location.hash.split('?')[1] : ''; const searchParams = new URLSearchParams(hashSearch); const queryInvite = searchParams.get('invite'); if (queryInvite) { console.log('Invite code from query params:', queryInvite); setInviteCode(queryInvite); // Clear demo credentials for invite flow setEmail(''); setPassword(''); } } }, [routeInviteCode, location]); const handleSuccessfulLogin = async () => { if (inviteCode) { // Invite flow - redirect to org selection with invite code navigate(`/org-selection?invite=${inviteCode}`, { replace: true }); } else { // Regular login - redirect to org selection to choose/create org navigate('/org-selection', { replace: true }); } }; useEffect(() => { if (user && !loading) { handleSuccessfulLogin(); } }, [user, loading]); const handleEmailLogin = async (e: React.FormEvent) => { e.preventDefault(); setIsLoading(true); setError(''); try { if (inviteCode) { // For invites, try to create account first since they're new users console.log('Invite flow: attempting to create account for', email); await signUpWithEmail(email, password, email.split('@')[0]); } else { // Regular login await signInWithEmail(email, password); } // Success will be handled by the useEffect hook } catch (error) { console.error('Auth failed:', error); const errorMessage = error instanceof Error ? error.message : 'Unknown error'; if (inviteCode) { // For invite flow, if account creation failed, try login instead if (errorMessage.includes('User already exists') || errorMessage.includes('already-exists')) { try { console.log('Account exists, trying login instead...'); await signInWithEmail(email, password); } catch (loginError) { console.error('Login also failed:', loginError); setError(`Account exists but password is incorrect. Please check your password or contact your administrator.`); setIsLoading(false); } } else { setError(`Failed to create account: ${errorMessage}. Please try a different email or contact your administrator.`); setIsLoading(false); } } else { // Regular login flow - try signup if user not found if (errorMessage.includes('User not found')) { try { console.log('User not found, attempting sign-up...'); await signUpWithEmail(email, password, email.split('@')[0]); // Success will be handled by the useEffect hook } catch (signUpError) { console.error('Sign-up also failed:', signUpError); setError(`Failed to create account: ${signUpError instanceof Error ? signUpError.message : 'Unknown error'}`); setIsLoading(false); } } else { setError(`Login failed: ${errorMessage}`); setIsLoading(false); } } } }; const handleGoogleLogin = async () => { setIsLoading(true); setError(''); try { await signInWithGoogle(); // Success will be handled by the useEffect hook } catch (error) { console.error('Google login failed:', error); setError(`Google login failed: ${error instanceof Error ? error.message : 'Unknown error'}`); setIsLoading(false); } }; return (
A

Welcome to Auditly

{inviteCode ? 'Complete your profile to join the team survey' : 'Sign in to your account'}

{inviteCode && (

Employee Survey Invitation
No account needed! Just create a password to secure your responses and start the questionnaire.

)} {error && (

{error}

)}
setEmail(e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-lg bg-white text-gray-900 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-800 dark:text-white dark:border-gray-600 dark:placeholder-gray-400" required />
setPassword(e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-lg bg-white text-gray-900 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-800 dark:text-white dark:border-gray-600 dark:placeholder-gray-400" required /> {inviteCode && (

Choose a secure password for your new account

)}

Or continue with

{/* Manual invite code entry - only show if no invite code in URL */} {!inviteCode && (

Employee? Use Your Invite Code

Skip account creation - employees can go directly to their questionnaire

{ if (e.key === 'Enter') { const code = (e.target as HTMLInputElement).value.trim(); if (code) { window.location.href = `#/invite/${code}`; } else { alert('Please enter an invite code'); } } }} />

No account needed - just answer questions and submit

)}

{inviteCode ? 'Demo mode: Enter any email and password to create your account.' : 'Demo mode: No Firebase configuration detected.\nUse any email/password to continue.' }

); }; export default Login;