import React, { useState, useEffect } from 'react'; import { useNavigate, useLocation } from 'react-router-dom'; import { useAuth } from '../contexts/AuthContext'; import { useUserOrganizations } from '../contexts/UserOrganizationsContext'; import { Card, Button } from '../components/UiKit'; const OrgSelection: React.FC = () => { const navigate = useNavigate(); const location = useLocation(); const { user } = useAuth(); const { organizations, loading, selectOrganization, createOrganization, joinOrganization } = useUserOrganizations(); const [showCreateOrg, setShowCreateOrg] = useState(false); const [newOrgName, setNewOrgName] = useState(''); const [inviteCode, setInviteCode] = useState(''); const [isCreating, setIsCreating] = useState(false); const [isJoining, setIsJoining] = useState(false); useEffect(() => { // Check for invite code in URL const hashSearch = location.hash.includes('?') ? location.hash.split('?')[1] : ''; const searchParams = new URLSearchParams(hashSearch); const queryInvite = searchParams.get('invite'); if (queryInvite) { setInviteCode(queryInvite); } }, [location]); // Auto-join organization when invite code is present useEffect(() => { if (inviteCode && !isJoining && !loading) { handleJoinWithInvite(); } }, [inviteCode, isJoining, loading]); const handleSelectOrg = (orgId: string) => { selectOrganization(orgId); // Check if the organization needs onboarding completion const selectedOrg = organizations.find(org => org.orgId === orgId); if (selectedOrg && !selectedOrg.onboardingCompleted && selectedOrg.role === 'owner') { navigate('/onboarding', { replace: true }); } else { navigate('/reports', { replace: true }); } }; const handleCreateOrg = async () => { if (!newOrgName.trim() || isCreating) return; setIsCreating(true); try { const result = await createOrganization(newOrgName); selectOrganization(result.orgId); // Check if subscription setup is required if (result.requiresSubscription) { navigate(`/subscription-setup?orgId=${result.orgId}`, { replace: true }); } else { navigate('/onboarding', { replace: true }); } } catch (error) { console.error('Failed to create organization:', error); alert('Failed to create organization. Please try again.'); } finally { setIsCreating(false); } }; const handleJoinWithInvite = async () => { if (!inviteCode.trim() || isJoining) return; setIsJoining(true); try { const orgId = await joinOrganization(inviteCode); selectOrganization(orgId); navigate('/employee-questionnaire', { replace: true }); } catch (error) { console.error('Failed to join organization:', error); alert('Failed to join organization. Please check your invite code.'); } finally { setIsJoining(false); } }; if (loading) { return
Select an organization to continue
You've been invited to join an organization with code: {inviteCode}