Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 | 1x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 31x 1x 70x 14x 14x 14x 14x 14x 70x 1x 1x 70x 46x 70x 3x 2x 1x 1x 70x 8x 8x 8x 8x 8x 8x 6x 6x 6x 6x 6x 6x 6x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 70x 70x 70x 6x 6x 6x 1x 64x 5x 59x | /**
* RegistrationWizard Component (Story 4.1.5 - Tasks 4, 7, 8, 9)
*
* Main 2-step registration wizard container.
* Reusable component that works in both inline (HeroSection) and dedicated page contexts.
*
* Features:
* - 2-step accordion-style wizard (Personal Details → Confirm)
* - react-hook-form + zod validation
* - Progress indicator
* - Navigation with state preservation
* - API integration for registration submission
*/
import { useState, useRef, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useQueryClient } from '@tanstack/react-query';
import { Checkbox } from '@/components/public/ui/checkbox';
import { Label } from '@/components/public/ui/label';
import { PersonalDetailsStep, type PersonalDetailsStepRef } from './PersonalDetailsStep';
import { ConfirmRegistrationStep } from './ConfirmRegistrationStep';
import { RegistrationAccordion } from './RegistrationAccordion';
import { AttendeeQuickRegisterPanel } from './AttendeeQuickRegisterPanel';
import { Button } from '@/components/public/ui/button';
import { eventApiClient } from '@/services/eventApiClient';
import { useMyRegistration } from '@/hooks/useMyRegistration';
import { useAuth } from '@/hooks/useAuth/useAuth';
import { useUserProfile } from '@/hooks/useUserProfile/useUserProfile';
import type { CreateRegistrationRequest } from '@/types/event.types';
import { Loader2, CheckCircle2, Mail, ArrowLeft, AlertCircle, Building2 } from 'lucide-react';
import { DeregistrationByEmailModal } from '@/components/public/DeregistrationByEmailModal';
import { useTurnstile } from '@/hooks/useTurnstile';
export interface RegistrationWizardProps {
/** Event code for registration */
eventCode: string;
/** Optional cancel handler (for inline mode to collapse wizard) */
onCancel?: () => void;
/** Whether wizard is displayed inline (vs dedicated page) */
inline?: boolean;
/** AC8 (Story 10.11): Remaining spots. 0 = event full → waitlist flow. null/undefined = unlimited. */
spotsRemaining?: number | null;
}
/**
* RegistrationWizard - 2-Step Registration Flow
*
* Step 1: Personal Details (firstName, lastName, email, company, role)
* Step 2: Confirm Registration (review, preferences, special requests, terms)
*
* Works in both inline (hero section) and dedicated page contexts.
*/
export const RegistrationWizard = ({
eventCode,
onCancel,
inline = false,
spotsRemaining,
}: RegistrationWizardProps) => {
const navigate = useNavigate();
const { t, i18n } = useTranslation(['registration', 'common']);
const queryClient = useQueryClient();
const step1Ref = useRef<PersonalDetailsStepRef>(null);
// AC6: Check if authenticated user already has a registration (Story 10.10, T11)
const { data: myRegistration, isLoading: isRegistrationLoading } = useMyRegistration(eventCode);
// Pre-fill form from user profile when authenticated
const { isAuthenticated, user } = useAuth();
const { userProfile } = useUserProfile({ enabled: isAuthenticated });
// AC8 (Story 10.11): event is full when spotsRemaining is exactly 0 (not null/undefined)
const isEventFull = spotsRemaining === 0;
const {
getToken: getTurnstileToken,
resetWidget: resetTurnstileWidget,
widgetRef: turnstileWidgetRef,
} = useTurnstile();
// Wizard state
const [currentStep, setCurrentStep] = useState(1);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const [registrationSuccess, setRegistrationSuccess] = useState(false);
const [registeredEmail, setRegisteredEmail] = useState<string | null>(null);
// BATbern59 badge fix: backend refreshed the attendee's company on file (they
// entered a company differing from their stored profile). Drives a success notice.
const [companyUpdated, setCompanyUpdated] = useState(false);
const [waitlistAcknowledged, setWaitlistAcknowledged] = useState(false);
const [isWaitlistRegistration, setIsWaitlistRegistration] = useState(false);
const [deregisterModalOpen, setDeregisterModalOpen] = useState(false);
// Form data state
const [formData, setFormData] = useState<CreateRegistrationRequest>({
firstName: '',
lastName: '',
email: '',
company: '',
role: '',
termsAccepted: false,
communicationPreferences: {
newsletterSubscribed: false,
eventReminders: true,
},
specialRequests: '',
});
// Pre-fill form fields from user profile once resolved (only fills still-empty fields)
useEffect(() => {
if (!userProfile || !step1Ref.current) return;
step1Ref.current.prefill({
firstName: userProfile.firstName,
lastName: userProfile.lastName,
email: userProfile.email,
});
}, [userProfile]);
// Navigation handlers (Task 7)
const handleNext = async () => {
Eif (currentStep === 1) {
// Validate Step 1 before proceeding
const isValid = await step1Ref.current?.validateAndSync();
Iif (!isValid) {
setError(t('wizard.errors.fillRequired'));
return;
}
setError(null);
}
setCurrentStep((prev) => Math.min(prev + 1, 2));
};
const handleBack = () => {
setCurrentStep((prev) => Math.max(prev - 1, 1));
setError(null);
};
// Track wizard bottom when step changes (similar to HeroSection)
useEffect(() => {
Eif (currentStep !== 2 || !inline) return;
let animationFrame: number;
let startTime: number | null = null;
const animationDuration = 500; // Accordion animation duration
const trackWizardBottom = (timestamp: number) => {
if (!startTime) startTime = timestamp;
const elapsed = timestamp - startTime;
const wizardSection = document.getElementById('registration-wizard-section');
if (wizardSection && elapsed < animationDuration) {
const rect = wizardSection.getBoundingClientRect();
// Scroll so bottom of wizard aligns with bottom of viewport
const scrollTarget = window.pageYOffset + rect.bottom - window.innerHeight;
window.scrollTo({ top: scrollTarget, behavior: 'instant' });
animationFrame = requestAnimationFrame(trackWizardBottom);
}
};
animationFrame = requestAnimationFrame(trackWizardBottom);
return () => {
if (animationFrame) {
cancelAnimationFrame(animationFrame);
}
};
}, [currentStep, inline]);
const handleCancel = () => {
if (confirm(t('wizard.cancelConfirm'))) {
if (onCancel) {
// Inline mode: collapse wizard
onCancel();
} else {
// Dedicated page: navigate back to event
navigate(`/`);
}
}
};
// Form submission (Task 8)
const handleSubmit = async () => {
// Validate terms accepted
Iif (!formData.termsAccepted) {
setError(t('wizard.errors.acceptTerms'));
return;
}
setIsSubmitting(true);
setError(null);
try {
const turnstileToken = await getTurnstileToken();
const response = await eventApiClient.createRegistration(eventCode, formData, turnstileToken);
// Store registration in sessionStorage to show "already registered" on homepage
sessionStorage.setItem(
'pendingRegistration',
JSON.stringify({
email: response.email,
eventCode: eventCode,
timestamp: Date.now(),
expiresAt: Date.now() + 48 * 60 * 60 * 1000, // 48 hours (matches token validity)
})
);
// Success: Show success message inline (Story 4.1.5c)
setRegisteredEmail(response.email);
setCompanyUpdated(Boolean(response.companyUpdated));
setIsWaitlistRegistration(isEventFull);
setRegistrationSuccess(true);
setIsSubmitting(false);
// AC7: Invalidate my-registration cache so banner/guard reflect new status immediately
queryClient.invalidateQueries({ queryKey: ['my-registration', eventCode] });
} catch (err) {
// Handle Turnstile 403 errors (AC10, Story 10.31)
const isTurnstileError =
err instanceof Error &&
(err.message.includes('turnstile_required') || err.message.includes('turnstile_failed'));
if (isTurnstileError) {
resetTurnstileWidget();
setError(t('wizard.errors.failed'));
setIsSubmitting(false);
return;
}
// Handle duplicate registration (409 Conflict)
// Backend returns 409 only for confirmed/cancelled registrations
// For pending registrations, backend returns 200 OK (reuses existing)
Iif (err instanceof Error && err.message.includes('already registered')) {
// User is already confirmed - show error message
setError(
t('public.registration.errors.alreadyRegistered', {
defaultValue: 'You are already registered for this event.',
})
);
setIsSubmitting(false);
} else {
// Other errors: show error message
const errorMessage = err instanceof Error ? err.message : t('wizard.errors.failed');
setError(errorMessage);
setIsSubmitting(false);
}
}
};
// Step 1 summary for accordion
const step1Summary = formData.firstName && formData.lastName && (
<div className="flex items-center justify-between">
<span>
{formData.firstName} {formData.lastName} • {formData.email}
</span>
<Button
variant="ghost"
size="sm"
onClick={() => setCurrentStep(1)}
className="text-blue-400 hover:text-blue-300"
>
{t('wizard.buttons.edit')}
</Button>
</div>
);
// Quick registration for authenticated ATTENDEEs who are not yet registered:
// skip the 2-step form and show a one-click inline confirmation panel.
Iif (
isAuthenticated &&
user?.role === 'attendee' &&
!isRegistrationLoading &&
myRegistration == null
) {
return (
<AttendeeQuickRegisterPanel
eventCode={eventCode}
onCancel={onCancel ?? (() => {})}
inline={inline}
/>
);
}
// AC6: Registration Wizard guard (Story 10.10, T11)
// When the authenticated user already has a non-null registration:
// - REGISTERED / CONFIRMED / WAITLIST → show guard with "Go back" button
// - CANCELLED → show guard with "Register again" button (backend T4.6 allows re-registration)
if (!isRegistrationLoading && myRegistration != null) {
const isCancelled = myRegistration.status === 'CANCELLED';
const formattedDate = myRegistration.registrationDate
? new Date(myRegistration.registrationDate).toLocaleDateString(i18n.language, {
year: 'numeric',
month: 'long',
day: 'numeric',
})
: null;
return (
<div
className={`w-full ${inline ? 'max-w-4xl mx-auto' : ''}`}
data-testid="registration-status-guard"
>
<div className="text-center mb-6">
<AlertCircle className="h-12 w-12 text-amber-400 mx-auto mb-4" />
<h2 className="text-2xl font-light mb-2">
{isCancelled
? t('registrationStatusGuard.unregistered')
: t('registrationStatusGuard.alreadyRegistered')}
</h2>
{formattedDate && (
<p className="text-sm text-zinc-400">
{isCancelled
? formattedDate
: `${t(`registrationStatusBanner.${(myRegistration.status ?? '').toLowerCase()}`)} · ${formattedDate}`}
</p>
)}
</div>
<div className="flex justify-center gap-4 flex-wrap">
{isCancelled ? (
// CANCELLED: allow re-registration (backend deletes old record and creates new)
// Note: we can't reset myRegistration client-side, but the guard will dismiss
// once the query is invalidated after successful submission.
<Button
onClick={() => {
// Optimistically mark as not-registered so the wizard shows immediately.
// setQueryData (not removeQueries) avoids a re-fetch that would re-populate
// the guard before the user submits. The cache is properly invalidated on
// successful submission via queryClient.invalidateQueries in the success block.
queryClient.setQueryData(['my-registration', eventCode], null);
}}
data-testid="registration-guard-register-again-btn"
>
{t('registrationStatusGuard.registerAgain')}
</Button>
) : (
<>
<Button
variant="outline"
onClick={onCancel ?? (() => navigate('/'))}
data-testid="registration-guard-go-back-btn"
>
{t('registrationStatusGuard.goBack')}
</Button>
{/* Story 10.12 (AC9, T19): Cancel my registration — shown for active registrations */}
<Button
variant="ghost"
onClick={() => setDeregisterModalOpen(true)}
className="text-red-400 hover:text-red-300"
data-testid="registration-guard-cancel-btn"
>
{t('deregistration.wizard.cancelButton')}
</Button>
</>
)}
</div>
{/* Story 10.12 (AC9): Deregistration by email modal */}
<DeregistrationByEmailModal
open={deregisterModalOpen}
onClose={() => setDeregisterModalOpen(false)}
eventCode={eventCode}
/>
</div>
);
}
// Success view
if (registrationSuccess) {
return (
<div
data-testid="registration-success"
className={`w-full ${inline ? 'max-w-4xl mx-auto' : ''}`}
>
<div className="text-center">
<CheckCircle2 className="h-16 w-16 text-green-400 mx-auto mb-4" />
{isWaitlistRegistration ? (
<>
<h2 className="text-3xl font-light mb-2">{t('wizard.waitlistSuccessTitle')}</h2>
<p className="text-xl text-zinc-400 mb-8">{t('success.subtitle')}</p>
</>
) : (
<>
<h2 className="text-3xl font-light mb-2">{t('success.title')}</h2>
<p className="text-xl text-zinc-400 mb-8">{t('success.subtitle')}</p>
</>
)}
</div>
<div className="bg-zinc-900 border border-zinc-800 rounded-lg p-6 mb-6">
<div className="flex items-start gap-3">
<Mail className="h-6 w-6 text-blue-400 flex-shrink-0 mt-1" />
<div className="flex-1">
<h3 className="text-lg font-medium mb-2">{t('success.emailSent')}</h3>
{registeredEmail && (
<p className="text-zinc-300 mb-3">
{t('success.emailSentTo')}{' '}
<span
data-testid="registration-success-email"
className="font-mono text-blue-400"
>
{registeredEmail}
</span>
</p>
)}
<p className="text-sm text-zinc-400 mb-4">
{t('success.clickLink')}{' '}
<span className="text-zinc-300 font-medium">{t('success.validFor')}</span>
{t('success.valid')}
</p>
<div className="bg-zinc-800/50 border border-zinc-700 rounded p-3 mt-4">
<p className="text-sm font-medium text-zinc-300 mb-1">
{t('success.didntReceive')}
</p>
<ul className="text-sm text-zinc-400 space-y-1 ml-4">
<li>• {t('success.checkSpam')}</li>
<li>• {t('success.checkEmail')}</li>
<li>• {t('success.waitMinutes')}</li>
</ul>
</div>
</div>
</div>
</div>
{/* BATbern59 badge fix: tell the attendee we refreshed their company on file */}
{companyUpdated && formData.company && (
<div
data-testid="registration-company-updated"
className="bg-zinc-900 border border-zinc-800 rounded-lg p-4 mb-6"
>
<div className="flex items-start gap-3">
<Building2 className="h-5 w-5 text-amber-400 flex-shrink-0 mt-0.5" />
<p className="text-sm text-zinc-300">
{t('success.companyUpdated', { company: formData.company })}
</p>
</div>
</div>
)}
<div className="flex justify-center gap-4">
{onCancel && (
<Button variant="outline" onClick={onCancel}>
<ArrowLeft className="h-4 w-4 mr-2" />
{t('success.close')}
</Button>
)}
{!inline && (
<Button variant="outline" onClick={() => navigate('/')}>
<ArrowLeft className="h-4 w-4 mr-2" />
{t('navigation.home')}
</Button>
)}
</div>
</div>
);
}
return (
<div className={`w-full ${inline ? 'max-w-4xl mx-auto' : ''}`}>
{/* Progress Indicator (Task 9) */}
<div className="mb-8">
<div className="flex items-center justify-between mb-2">
<span
className={`text-sm ${
currentStep === 1 ? 'text-blue-400 font-medium' : 'text-zinc-500'
}`}
>
{t('wizard.steps.step1Progress')}
</span>
<span
className={`text-sm ${
currentStep === 2 ? 'text-blue-400 font-medium' : 'text-zinc-500'
}`}
>
{t('wizard.steps.step2Progress')}
</span>
</div>
<div className="h-2 bg-zinc-800 rounded-full overflow-hidden">
<div
className="h-full bg-blue-400 transition-all duration-300 ease-in-out"
style={{ width: `${(currentStep / 2) * 100}%` }}
/>
</div>
</div>
{/* Accordion Steps */}
<div className="space-y-4">
{/* Step 1: Personal Details */}
<RegistrationAccordion
isExpanded={currentStep === 1}
title={t('wizard.steps.step1Title')}
summary={step1Summary}
onToggle={() => {
if (currentStep !== 1) {
setCurrentStep(1);
setError(null);
}
}}
>
<PersonalDetailsStep ref={step1Ref} formData={formData} setFormData={setFormData} />
</RegistrationAccordion>
{/* Step 2: Confirm Registration */}
<RegistrationAccordion
isExpanded={currentStep === 2}
title={t('wizard.steps.step2Title')}
onToggle={() => {
// Step 2 can only be accessed by clicking Next from Step 1
// Clicking the header when collapsed should not expand it
if (currentStep === 2) {
// Do nothing - user must use Back button
}
}}
>
<ConfirmRegistrationStep
formData={formData}
setFormData={setFormData}
onEdit={() => setCurrentStep(1)}
/>
</RegistrationAccordion>
</div>
{/* AC8 (Story 10.11): Waitlist acknowledgment — shown in Step 2 when event is full */}
{isEventFull && currentStep === 2 && (
<div className="mt-4">
<div
role="alert"
className="mb-2 rounded-md border border-blue-400/30 bg-blue-400/15 px-4 py-2.5 text-sm text-blue-200"
>
{t('wizard.waitlistWarning')}
</div>
<div className="mt-1 flex items-center gap-2">
<Checkbox
id="waitlist-acknowledge"
checked={waitlistAcknowledged}
onCheckedChange={(checked) => setWaitlistAcknowledged(checked === true)}
data-testid="waitlist-acknowledge-checkbox"
/>
<Label htmlFor="waitlist-acknowledge" className="text-sm text-zinc-400">
{t('wizard.waitlistAcknowledgeLabel')}
</Label>
</div>
</div>
)}
{/* Error Message */}
{error && (
<div className="mt-4 p-4 bg-red-900/20 border border-red-800 rounded-lg">
<p className="text-sm text-red-400">{error}</p>
</div>
)}
{/* Invisible Turnstile widget container (Story 10.31, AC9) */}
<div ref={turnstileWidgetRef} />
{/* Navigation Buttons */}
<div className="mt-8 flex justify-between">
<Button
variant="outline"
onClick={handleCancel}
disabled={isSubmitting}
data-testid="registration-wizard-cancel-btn"
>
{t('wizard.buttons.cancel')}
</Button>
<div className="flex gap-4">
{currentStep > 1 && (
<Button
variant="outline"
onClick={handleBack}
disabled={isSubmitting}
data-testid="registration-wizard-back-btn"
>
{t('wizard.buttons.back')}
</Button>
)}
{currentStep < 2 ? (
<Button onClick={handleNext} data-testid="registration-wizard-next-btn">
{t('wizard.buttons.next')}
</Button>
) : (
<Button
onClick={handleSubmit}
disabled={
!formData.termsAccepted || isSubmitting || (isEventFull && !waitlistAcknowledged)
}
className="min-w-[200px]"
data-testid="registration-wizard-submit-btn"
>
{isSubmitting ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
{t('wizard.buttons.submitting')}
</>
) : (
t('wizard.buttons.complete')
)}
</Button>
)}
</div>
</div>
</div>
);
};
|