@proveanything/smartlinks-auth-ui 0.1.4 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -68,7 +68,7 @@ const AuthContainer = ({ children, theme = 'light', className = '', config, mini
68
68
  // - null or empty string: hide logo completely
69
69
  // - string URL: use custom logo
70
70
  const logoUrl = config?.branding?.logoUrl === undefined
71
- ? '/smartlinks-logo.png' // Default
71
+ ? 'https://smartlinks.app/smartlinks/landscape-medium.png' // Default Smartlinks logo
72
72
  : config?.branding?.logoUrl || null; // Custom or explicitly hidden
73
73
  const containerClass = minimal
74
74
  ? `auth-minimal auth-theme-${theme} ${className}`
@@ -11432,1092 +11432,1092 @@ const useAuth = () => {
11432
11432
  return context;
11433
11433
  };
11434
11434
 
11435
- const AccountManagement = ({ apiEndpoint, clientId, onProfileUpdated, onEmailChangeRequested, onPasswordChanged, onAccountDeleted, onError, theme = 'light', className = '', customization = {}, minimal = false, }) => {
11436
- const auth = useAuth();
11435
+ // Default Smartlinks Google OAuth Client ID (public - safe to expose)
11436
+ const DEFAULT_GOOGLE_CLIENT_ID = '696509063554-jdlbjl8vsjt7cr0vgkjkjf3ffnvi3a70.apps.googleusercontent.com';
11437
+ const SmartlinksAuthUI = ({ apiEndpoint, clientId, clientName, accountData, onAuthSuccess, onAuthError, enabledProviders = ['email', 'google', 'phone'], initialMode = 'login', redirectUrl, theme = 'light', className, customization, skipConfigFetch = false, minimal = false, }) => {
11438
+ const [mode, setMode] = React.useState(initialMode);
11437
11439
  const [loading, setLoading] = React.useState(false);
11438
- const [profile, setProfile] = React.useState(null);
11439
11440
  const [error, setError] = React.useState();
11440
- const [success, setSuccess] = React.useState();
11441
- // Track which section is being edited
11442
- const [editingSection, setEditingSection] = React.useState(null);
11443
- // Profile form state
11444
- const [displayName, setDisplayName] = React.useState('');
11445
- // Email change state
11446
- const [newEmail, setNewEmail] = React.useState('');
11447
- const [emailPassword, setEmailPassword] = React.useState('');
11448
- // Password change state
11449
- const [currentPassword, setCurrentPassword] = React.useState('');
11450
- const [newPassword, setNewPassword] = React.useState('');
11451
- const [confirmPassword, setConfirmPassword] = React.useState('');
11452
- // Phone change state (reuses existing sendPhoneCode flow)
11453
- const [newPhone, setNewPhone] = React.useState('');
11454
- const [phoneCode, setPhoneCode] = React.useState('');
11455
- const [phoneCodeSent, setPhoneCodeSent] = React.useState(false);
11456
- // Account deletion state
11457
- const [deletePassword, setDeletePassword] = React.useState('');
11458
- const [deleteConfirmText, setDeleteConfirmText] = React.useState('');
11459
- const [showDeleteConfirm, setShowDeleteConfirm] = React.useState(false);
11460
- const { showProfileSection = true, showEmailSection = true, showPasswordSection = true, showPhoneSection = true, showDeleteAccount = false, } = customization;
11461
- // Reinitialize Smartlinks SDK when apiEndpoint changes
11441
+ const [resetSuccess, setResetSuccess] = React.useState(false);
11442
+ const [authSuccess, setAuthSuccess] = React.useState(false);
11443
+ const [successMessage, setSuccessMessage] = React.useState();
11444
+ const [showResendVerification, setShowResendVerification] = React.useState(false);
11445
+ const [resendEmail, setResendEmail] = React.useState();
11446
+ const [showRequestNewReset, setShowRequestNewReset] = React.useState(false);
11447
+ const [resetRequestEmail, setResetRequestEmail] = React.useState();
11448
+ const [resetToken, setResetToken] = React.useState(); // Store the reset token from URL
11449
+ const [config, setConfig] = React.useState(null);
11450
+ const [configLoading, setConfigLoading] = React.useState(!skipConfigFetch);
11451
+ const [showEmailForm, setShowEmailForm] = React.useState(false); // Track if email form should be shown when emailDisplayMode is 'button'
11452
+ const api = new AuthAPI(apiEndpoint, clientId, clientName);
11453
+ const auth = useAuth();
11454
+ // Reinitialize Smartlinks SDK when apiEndpoint changes (for test/dev scenarios)
11455
+ // IMPORTANT: Preserve bearer token during reinitialization
11462
11456
  React.useEffect(() => {
11463
- if (apiEndpoint) {
11464
- smartlinks__namespace.initializeApi({
11465
- baseURL: apiEndpoint,
11466
- proxyMode: false,
11467
- ngrokSkipBrowserWarning: true,
11468
- });
11469
- }
11470
- }, [apiEndpoint]);
11471
- // Load user profile on mount
11457
+ const reinitializeWithToken = async () => {
11458
+ if (apiEndpoint) {
11459
+ // Get current token before reinitializing
11460
+ const currentToken = await auth.getToken();
11461
+ smartlinks__namespace.initializeApi({
11462
+ baseURL: apiEndpoint,
11463
+ proxyMode: false, // Direct API calls when custom endpoint is provided
11464
+ ngrokSkipBrowserWarning: true,
11465
+ });
11466
+ // Restore bearer token after reinitialization using auth.verifyToken
11467
+ if (currentToken) {
11468
+ smartlinks__namespace.auth.verifyToken(currentToken).catch(err => {
11469
+ console.warn('Failed to restore bearer token after reinit:', err);
11470
+ });
11471
+ }
11472
+ }
11473
+ };
11474
+ reinitializeWithToken();
11475
+ }, [apiEndpoint, auth]);
11476
+ // Get the effective redirect URL (use prop or default to current page)
11477
+ const getRedirectUrl = () => {
11478
+ if (redirectUrl)
11479
+ return redirectUrl;
11480
+ // Get the full current URL including hash routes
11481
+ // Remove any existing query parameters to avoid duplication
11482
+ const currentUrl = window.location.href.split('?')[0];
11483
+ return currentUrl;
11484
+ };
11485
+ // Fetch UI configuration
11472
11486
  React.useEffect(() => {
11473
- loadProfile();
11474
- }, [clientId]);
11475
- const loadProfile = async () => {
11476
- if (!auth.isAuthenticated) {
11477
- setError('You must be logged in to manage your account');
11487
+ if (skipConfigFetch) {
11488
+ setConfig(customization || {});
11478
11489
  return;
11479
11490
  }
11480
- setLoading(true);
11481
- setError(undefined);
11482
- try {
11483
- // TODO: Backend implementation required
11484
- // Endpoint: GET /api/v1/authkit/:clientId/account/profile
11485
- // SDK method: smartlinks.authKit.getProfile(clientId)
11486
- // Temporary mock data for UI testing
11487
- const profileData = {
11488
- uid: auth.user?.uid || '',
11489
- email: auth.user?.email,
11490
- displayName: auth.user?.displayName,
11491
- phoneNumber: auth.user?.phoneNumber,
11492
- photoURL: auth.user?.photoURL,
11493
- emailVerified: true,
11494
- accountData: auth.accountData || {},
11495
- };
11496
- setProfile(profileData);
11497
- setDisplayName(profileData.displayName || '');
11498
- }
11499
- catch (err) {
11500
- const errorMessage = err instanceof Error ? err.message : 'Failed to load profile';
11501
- setError(errorMessage);
11502
- onError?.(err instanceof Error ? err : new Error(errorMessage));
11503
- }
11504
- finally {
11505
- setLoading(false);
11506
- }
11507
- };
11508
- const handleUpdateProfile = async (e) => {
11509
- e.preventDefault();
11510
- setLoading(true);
11511
- setError(undefined);
11512
- setSuccess(undefined);
11513
- try {
11514
- // TODO: Backend implementation required
11515
- // Endpoint: POST /api/v1/authkit/:clientId/account/update-profile
11516
- // SDK method: smartlinks.authKit.updateProfile(clientId, updateData)
11517
- setError('Backend API not yet implemented. See console for required endpoint.');
11518
- console.log('Required API endpoint: POST /api/v1/authkit/:clientId/account/update-profile');
11519
- console.log('Update data:', { displayName });
11520
- // Uncomment when backend is ready:
11521
- // const updateData: ProfileUpdateData = {
11522
- // displayName: displayName || undefined,
11523
- // photoURL: photoURL || undefined,
11524
- // };
11525
- // const updatedProfile = await smartlinks.authKit.updateProfile(clientId, updateData);
11526
- // setProfile(updatedProfile);
11527
- // setSuccess('Profile updated successfully!');
11528
- // setEditingSection(null);
11529
- // onProfileUpdated?.(updatedProfile);
11530
- }
11531
- catch (err) {
11532
- const errorMessage = err instanceof Error ? err.message : 'Failed to update profile';
11533
- setError(errorMessage);
11534
- onError?.(err instanceof Error ? err : new Error(errorMessage));
11491
+ const fetchConfig = async () => {
11492
+ try {
11493
+ // Check localStorage cache first
11494
+ const cacheKey = `auth_ui_config_${clientId || 'default'}`;
11495
+ const cached = localStorage.getItem(cacheKey);
11496
+ if (cached) {
11497
+ const { config: cachedConfig, timestamp } = JSON.parse(cached);
11498
+ const age = Date.now() - timestamp;
11499
+ // Use cache if less than 1 hour old
11500
+ if (age < 3600000) {
11501
+ setConfig({ ...cachedConfig, ...customization });
11502
+ setConfigLoading(false);
11503
+ // Fetch in background to update cache
11504
+ api.fetchConfig().then(freshConfig => {
11505
+ localStorage.setItem(cacheKey, JSON.stringify({
11506
+ config: freshConfig,
11507
+ timestamp: Date.now()
11508
+ }));
11509
+ });
11510
+ return;
11511
+ }
11512
+ }
11513
+ // Fetch from API
11514
+ const fetchedConfig = await api.fetchConfig();
11515
+ // Merge with customization props (props take precedence)
11516
+ const mergedConfig = { ...fetchedConfig, ...customization };
11517
+ setConfig(mergedConfig);
11518
+ // Cache the fetched config
11519
+ localStorage.setItem(cacheKey, JSON.stringify({
11520
+ config: fetchedConfig,
11521
+ timestamp: Date.now()
11522
+ }));
11523
+ }
11524
+ catch (err) {
11525
+ console.error('Failed to fetch config:', err);
11526
+ setConfig(customization || {});
11527
+ }
11528
+ finally {
11529
+ setConfigLoading(false);
11530
+ }
11531
+ };
11532
+ fetchConfig();
11533
+ }, [apiEndpoint, clientId, customization, skipConfigFetch]);
11534
+ // Reset showEmailForm when mode changes away from login/register
11535
+ React.useEffect(() => {
11536
+ if (mode !== 'login' && mode !== 'register') {
11537
+ setShowEmailForm(false);
11535
11538
  }
11536
- finally {
11537
- setLoading(false);
11539
+ }, [mode]);
11540
+ // Handle URL-based auth flows (email verification, password reset)
11541
+ React.useEffect(() => {
11542
+ // Helper to get URL parameters from either hash or search
11543
+ const getUrlParams = () => {
11544
+ // First check if there are params in the hash (for hash routing)
11545
+ const hash = window.location.hash;
11546
+ const hashQueryIndex = hash.indexOf('?');
11547
+ if (hashQueryIndex !== -1) {
11548
+ // Extract query string from hash (e.g., #/test?mode=verifyEmail&token=abc)
11549
+ const hashQuery = hash.substring(hashQueryIndex + 1);
11550
+ return new URLSearchParams(hashQuery);
11551
+ }
11552
+ // Fall back to regular search params (for non-hash routing)
11553
+ return new URLSearchParams(window.location.search);
11554
+ };
11555
+ const params = getUrlParams();
11556
+ const urlMode = params.get('mode');
11557
+ const token = params.get('token');
11558
+ console.log('URL params detected:', { urlMode, token, hash: window.location.hash, search: window.location.search });
11559
+ if (urlMode && token) {
11560
+ handleURLBasedAuth(urlMode, token);
11538
11561
  }
11539
- };
11540
- const cancelEdit = () => {
11541
- setEditingSection(null);
11542
- setDisplayName(profile?.displayName || '');
11543
- setNewEmail('');
11544
- setEmailPassword('');
11545
- setCurrentPassword('');
11546
- setNewPassword('');
11547
- setConfirmPassword('');
11548
- setNewPhone('');
11549
- setPhoneCode('');
11550
- setPhoneCodeSent(false);
11551
- setError(undefined);
11552
- setSuccess(undefined);
11553
- };
11554
- const handleChangeEmail = async (e) => {
11555
- e.preventDefault();
11562
+ }, []);
11563
+ const handleURLBasedAuth = async (urlMode, token) => {
11556
11564
  setLoading(true);
11557
11565
  setError(undefined);
11558
- setSuccess(undefined);
11559
11566
  try {
11560
- // TODO: Backend implementation required
11561
- // Endpoint: POST /api/v1/authkit/:clientId/account/change-email
11562
- // SDK method: smartlinks.authKit.changeEmail(clientId, newEmail, password)
11563
- // Note: No verification flow for now - direct email update
11564
- setError('Backend API not yet implemented. See console for required endpoint.');
11565
- console.log('Required API endpoint: POST /api/v1/authkit/:clientId/account/change-email');
11566
- console.log('Data:', { newEmail });
11567
- // Uncomment when backend is ready:
11568
- // await smartlinks.authKit.changeEmail(clientId, newEmail, emailPassword);
11569
- // setSuccess('Email changed successfully!');
11570
- // setEditingSection(null);
11571
- // setNewEmail('');
11572
- // setEmailPassword('');
11573
- // onEmailChangeRequested?.();
11574
- // await loadProfile(); // Reload to show new email
11575
- }
11576
- catch (err) {
11577
- const errorMessage = err instanceof Error ? err.message : 'Failed to change email';
11578
- setError(errorMessage);
11579
- onError?.(err instanceof Error ? err : new Error(errorMessage));
11580
- }
11581
- finally {
11582
- setLoading(false);
11567
+ if (urlMode === 'verifyEmail') {
11568
+ console.log('Verifying email with token:', token);
11569
+ const response = await api.verifyEmailWithToken(token);
11570
+ // Get email verification mode from response or config
11571
+ const verificationMode = response.emailVerificationMode || config?.emailVerification?.mode || 'verify-then-auto-login';
11572
+ if ((verificationMode === 'verify-then-auto-login' || verificationMode === 'immediate') && response.token) {
11573
+ // Auto-login modes: Log the user in immediately if token is provided
11574
+ auth.login(response.token, response.user, response.accountData);
11575
+ setAuthSuccess(true);
11576
+ setSuccessMessage('Email verified successfully! You are now logged in.');
11577
+ onAuthSuccess(response.token, response.user, response.accountData);
11578
+ // Clear the URL parameters
11579
+ const cleanUrl = window.location.href.split('?')[0];
11580
+ window.history.replaceState({}, document.title, cleanUrl);
11581
+ // Redirect after a brief delay to show success message
11582
+ if (redirectUrl) {
11583
+ setTimeout(() => {
11584
+ window.location.href = redirectUrl;
11585
+ }, 2000);
11586
+ }
11587
+ }
11588
+ else {
11589
+ // verify-then-manual-login mode or no token: Show success but require manual login
11590
+ setAuthSuccess(true);
11591
+ setSuccessMessage('Email verified successfully! Please log in with your credentials.');
11592
+ // Clear the URL parameters
11593
+ const cleanUrl = window.location.href.split('?')[0];
11594
+ window.history.replaceState({}, document.title, cleanUrl);
11595
+ // Switch back to login mode after a delay
11596
+ setTimeout(() => {
11597
+ setAuthSuccess(false);
11598
+ setMode('login');
11599
+ }, 3000);
11600
+ }
11601
+ }
11602
+ else if (urlMode === 'resetPassword') {
11603
+ console.log('Verifying reset token:', token);
11604
+ // Verify token is valid, then show password reset form
11605
+ await api.verifyResetToken(token);
11606
+ setResetToken(token); // Store token for use in password reset
11607
+ setMode('reset-password');
11608
+ // Clear the URL parameters
11609
+ const cleanUrl = window.location.href.split('?')[0];
11610
+ window.history.replaceState({}, document.title, cleanUrl);
11611
+ }
11612
+ else if (urlMode === 'magicLink') {
11613
+ console.log('Verifying magic link token:', token);
11614
+ const response = await api.verifyMagicLink(token);
11615
+ // Auto-login with magic link if token is provided
11616
+ if (response.token) {
11617
+ auth.login(response.token, response.user, response.accountData);
11618
+ setAuthSuccess(true);
11619
+ setSuccessMessage('Magic link verified! You are now logged in.');
11620
+ onAuthSuccess(response.token, response.user, response.accountData);
11621
+ // Clear the URL parameters
11622
+ const cleanUrl = window.location.href.split('?')[0];
11623
+ window.history.replaceState({}, document.title, cleanUrl);
11624
+ // Redirect after a brief delay to show success message
11625
+ if (redirectUrl) {
11626
+ setTimeout(() => {
11627
+ window.location.href = redirectUrl;
11628
+ }, 2000);
11629
+ }
11630
+ }
11631
+ else {
11632
+ throw new Error('Authentication failed - no token received');
11633
+ }
11634
+ }
11583
11635
  }
11584
- };
11585
- const handleChangePassword = async (e) => {
11586
- e.preventDefault();
11587
- if (newPassword !== confirmPassword) {
11588
- setError('New passwords do not match');
11589
- return;
11636
+ catch (err) {
11637
+ console.error('URL-based auth error:', err);
11638
+ const errorMessage = err instanceof Error ? err.message : 'An error occurred';
11639
+ // If it's an email verification error (expired/invalid token), show resend option
11640
+ if (urlMode === 'verifyEmail') {
11641
+ setError(`${errorMessage} - Please enter your email below to receive a new verification link.`);
11642
+ setShowResendVerification(true);
11643
+ setMode('login'); // Show the login form UI
11644
+ // Clear the URL parameters
11645
+ const cleanUrl = window.location.href.split('?')[0];
11646
+ window.history.replaceState({}, document.title, cleanUrl);
11647
+ }
11648
+ else if (urlMode === 'resetPassword') {
11649
+ // If password reset token is invalid/expired, show request new reset link option
11650
+ setError(`${errorMessage} - Please enter your email below to receive a new password reset link.`);
11651
+ setShowRequestNewReset(true);
11652
+ setMode('login');
11653
+ // Clear the URL parameters
11654
+ const cleanUrl = window.location.href.split('?')[0];
11655
+ window.history.replaceState({}, document.title, cleanUrl);
11656
+ }
11657
+ else if (urlMode === 'magicLink') {
11658
+ // If magic link is invalid/expired
11659
+ setError(`${errorMessage} - Please request a new magic link below.`);
11660
+ setMode('magic-link');
11661
+ // Clear the URL parameters
11662
+ const cleanUrl = window.location.href.split('?')[0];
11663
+ window.history.replaceState({}, document.title, cleanUrl);
11664
+ }
11665
+ else {
11666
+ setError(errorMessage);
11667
+ }
11668
+ onAuthError?.(err instanceof Error ? err : new Error('An error occurred'));
11590
11669
  }
11591
- if (newPassword.length < 6) {
11592
- setError('Password must be at least 6 characters');
11593
- return;
11670
+ finally {
11671
+ setLoading(false);
11594
11672
  }
11673
+ };
11674
+ const handleEmailAuth = async (data) => {
11595
11675
  setLoading(true);
11596
11676
  setError(undefined);
11597
- setSuccess(undefined);
11677
+ setAuthSuccess(false);
11598
11678
  try {
11599
- // TODO: Backend implementation required
11600
- // Endpoint: POST /api/v1/authkit/:clientId/account/change-password
11601
- // SDK method: smartlinks.authKit.changePassword(clientId, currentPassword, newPassword)
11602
- setError('Backend API not yet implemented. See console for required endpoint.');
11603
- console.log('Required API endpoint: POST /api/v1/authkit/:clientId/account/change-password');
11604
- console.log('Data: currentPassword and newPassword provided');
11605
- // Uncomment when backend is ready:
11606
- // await smartlinks.authKit.changePassword(clientId, currentPassword, newPassword);
11607
- // setSuccess('Password changed successfully!');
11608
- // setEditingSection(null);
11609
- // setCurrentPassword('');
11610
- // setNewPassword('');
11611
- // setConfirmPassword('');
11612
- // onPasswordChanged?.();
11679
+ const response = mode === 'login'
11680
+ ? await api.login(data.email, data.password)
11681
+ : await api.register({
11682
+ ...data,
11683
+ accountData: mode === 'register' ? accountData : undefined,
11684
+ redirectUrl: getRedirectUrl(), // Include redirect URL for email verification
11685
+ });
11686
+ // Get email verification mode from response or config (default: verify-then-auto-login)
11687
+ const verificationMode = response.emailVerificationMode || config?.emailVerification?.mode || 'verify-then-auto-login';
11688
+ const gracePeriodHours = config?.emailVerification?.gracePeriodHours || 24;
11689
+ if (mode === 'register') {
11690
+ // Handle different verification modes
11691
+ if (verificationMode === 'immediate' && response.token) {
11692
+ // Immediate mode: Log in right away if token is provided
11693
+ auth.login(response.token, response.user, response.accountData);
11694
+ setAuthSuccess(true);
11695
+ const deadline = response.emailVerificationDeadline
11696
+ ? new Date(response.emailVerificationDeadline).toLocaleString()
11697
+ : `${gracePeriodHours} hours`;
11698
+ setSuccessMessage(`Account created! You're logged in now. Please verify your email by ${deadline} to keep your account active.`);
11699
+ if (response.token) {
11700
+ onAuthSuccess(response.token, response.user, response.accountData);
11701
+ }
11702
+ if (redirectUrl) {
11703
+ setTimeout(() => {
11704
+ window.location.href = redirectUrl;
11705
+ }, 2000);
11706
+ }
11707
+ }
11708
+ else if (verificationMode === 'verify-then-auto-login') {
11709
+ // Verify-then-auto-login mode: Don't log in yet, but will auto-login after email verification
11710
+ setAuthSuccess(true);
11711
+ setSuccessMessage('Account created! Please check your email and click the verification link to complete your registration.');
11712
+ }
11713
+ else {
11714
+ // verify-then-manual-login mode: Traditional flow
11715
+ setAuthSuccess(true);
11716
+ setSuccessMessage('Account created successfully! Please check your email to verify your account, then log in.');
11717
+ }
11718
+ }
11719
+ else {
11720
+ // Login mode - always log in if token is provided
11721
+ if (response.token) {
11722
+ // Check for account lock or verification requirements
11723
+ if (response.accountLocked) {
11724
+ throw new Error('Your account has been locked due to unverified email. Please check your email or request a new verification link.');
11725
+ }
11726
+ if (response.requiresEmailVerification) {
11727
+ throw new Error('Please verify your email before logging in. Check your inbox for the verification link.');
11728
+ }
11729
+ auth.login(response.token, response.user, response.accountData);
11730
+ setAuthSuccess(true);
11731
+ setSuccessMessage('Login successful!');
11732
+ onAuthSuccess(response.token, response.user, response.accountData);
11733
+ if (redirectUrl) {
11734
+ setTimeout(() => {
11735
+ window.location.href = redirectUrl;
11736
+ }, 2000);
11737
+ }
11738
+ }
11739
+ else {
11740
+ throw new Error('Authentication failed - please verify your email before logging in.');
11741
+ }
11742
+ }
11613
11743
  }
11614
11744
  catch (err) {
11615
- const errorMessage = err instanceof Error ? err.message : 'Failed to change password';
11616
- setError(errorMessage);
11617
- onError?.(err instanceof Error ? err : new Error(errorMessage));
11745
+ const errorMessage = err instanceof Error ? err.message : 'Authentication failed';
11746
+ // Check if error is about email already registered
11747
+ if (mode === 'register' && errorMessage.toLowerCase().includes('already') && errorMessage.toLowerCase().includes('email')) {
11748
+ setShowResendVerification(true);
11749
+ setResendEmail(data.email);
11750
+ setError('This email is already registered. If you didn\'t receive the verification email, you can resend it below.');
11751
+ }
11752
+ else {
11753
+ setError(errorMessage);
11754
+ }
11755
+ onAuthError?.(err instanceof Error ? err : new Error(errorMessage));
11618
11756
  }
11619
11757
  finally {
11620
11758
  setLoading(false);
11621
11759
  }
11622
11760
  };
11623
- const handleSendPhoneCode = async () => {
11761
+ const handleResendVerification = async () => {
11762
+ if (!resendEmail)
11763
+ return;
11624
11764
  setLoading(true);
11625
11765
  setError(undefined);
11626
11766
  try {
11627
- await smartlinks__namespace.authKit.sendPhoneCode(clientId, newPhone);
11628
- setPhoneCodeSent(true);
11629
- setSuccess('Verification code sent to your phone');
11767
+ // For resend, we need the userId. If we don't have it, we need to handle this differently
11768
+ // The backend should ideally handle this case
11769
+ await api.resendVerification('unknown', resendEmail, getRedirectUrl());
11770
+ setAuthSuccess(true);
11771
+ setSuccessMessage('Verification email sent! Please check your inbox.');
11772
+ setShowResendVerification(false);
11630
11773
  }
11631
11774
  catch (err) {
11632
- const errorMessage = err instanceof Error ? err.message : 'Failed to send verification code';
11775
+ const errorMessage = err instanceof Error ? err.message : 'Failed to resend verification email';
11633
11776
  setError(errorMessage);
11634
- onError?.(err instanceof Error ? err : new Error(errorMessage));
11777
+ onAuthError?.(err instanceof Error ? err : new Error(errorMessage));
11635
11778
  }
11636
11779
  finally {
11637
11780
  setLoading(false);
11638
11781
  }
11639
11782
  };
11640
- const handleUpdatePhone = async (e) => {
11641
- e.preventDefault();
11783
+ const handleRequestNewReset = async () => {
11784
+ if (!resetRequestEmail)
11785
+ return;
11642
11786
  setLoading(true);
11643
11787
  setError(undefined);
11644
- setSuccess(undefined);
11645
11788
  try {
11646
- // TODO: Backend implementation required
11647
- // Endpoint: POST /api/v1/authkit/:clientId/account/update-phone
11648
- // SDK method: smartlinks.authKit.updatePhone(clientId, phoneNumber, verificationCode)
11649
- setError('Backend API not yet implemented. See console for required endpoint.');
11650
- console.log('Required API endpoint: POST /api/v1/authkit/:clientId/account/update-phone');
11651
- console.log('Data:', { phoneNumber: newPhone, code: phoneCode });
11652
- // Uncomment when backend is ready:
11653
- // await smartlinks.authKit.updatePhone(clientId, newPhone, phoneCode);
11654
- // setSuccess('Phone number updated successfully!');
11655
- // setEditingSection(null);
11656
- // setNewPhone('');
11657
- // setPhoneCode('');
11658
- // setPhoneCodeSent(false);
11659
- // await loadProfile();
11789
+ await api.requestPasswordReset(resetRequestEmail, getRedirectUrl());
11790
+ setAuthSuccess(true);
11791
+ setSuccessMessage('Password reset email sent! Please check your inbox.');
11792
+ setShowRequestNewReset(false);
11793
+ setResetRequestEmail('');
11660
11794
  }
11661
11795
  catch (err) {
11662
- const errorMessage = err instanceof Error ? err.message : 'Failed to update phone number';
11796
+ const errorMessage = err instanceof Error ? err.message : 'Failed to send password reset email';
11663
11797
  setError(errorMessage);
11664
- onError?.(err instanceof Error ? err : new Error(errorMessage));
11798
+ onAuthError?.(err instanceof Error ? err : new Error(errorMessage));
11665
11799
  }
11666
11800
  finally {
11667
11801
  setLoading(false);
11668
11802
  }
11669
11803
  };
11670
- const handleDeleteAccount = async () => {
11671
- if (deleteConfirmText !== 'DELETE') {
11672
- setError('Please type DELETE to confirm account deletion');
11673
- return;
11804
+ const handleGoogleLogin = async () => {
11805
+ // Use custom client ID from config, or fall back to default Smartlinks client ID
11806
+ const googleClientId = config?.googleClientId || DEFAULT_GOOGLE_CLIENT_ID;
11807
+ // Determine OAuth flow: default to 'oneTap' for better UX, but allow 'popup' for iframe compatibility
11808
+ const oauthFlow = config?.googleOAuthFlow || 'oneTap';
11809
+ setLoading(true);
11810
+ setError(undefined);
11811
+ try {
11812
+ const google = window.google;
11813
+ if (!google) {
11814
+ throw new Error('Google Identity Services not loaded. Please check your internet connection.');
11815
+ }
11816
+ if (oauthFlow === 'popup') {
11817
+ // Use OAuth2 popup flow (works in iframes but requires popup permission)
11818
+ if (!google.accounts.oauth2) {
11819
+ throw new Error('Google OAuth2 not available');
11820
+ }
11821
+ const client = google.accounts.oauth2.initTokenClient({
11822
+ client_id: googleClientId,
11823
+ scope: 'openid email profile',
11824
+ callback: async (response) => {
11825
+ try {
11826
+ if (response.error) {
11827
+ throw new Error(response.error_description || response.error);
11828
+ }
11829
+ const accessToken = response.access_token;
11830
+ // Send access token to backend
11831
+ const authResponse = await api.loginWithGoogle(accessToken);
11832
+ if (authResponse.token) {
11833
+ auth.login(authResponse.token, authResponse.user, authResponse.accountData);
11834
+ setAuthSuccess(true);
11835
+ setSuccessMessage('Google login successful!');
11836
+ onAuthSuccess(authResponse.token, authResponse.user, authResponse.accountData);
11837
+ }
11838
+ else {
11839
+ throw new Error('Authentication failed - no token received');
11840
+ }
11841
+ if (redirectUrl) {
11842
+ setTimeout(() => {
11843
+ window.location.href = redirectUrl;
11844
+ }, 2000);
11845
+ }
11846
+ setLoading(false);
11847
+ }
11848
+ catch (err) {
11849
+ const errorMessage = err instanceof Error ? err.message : 'Google login failed';
11850
+ setError(errorMessage);
11851
+ onAuthError?.(err instanceof Error ? err : new Error(errorMessage));
11852
+ setLoading(false);
11853
+ }
11854
+ },
11855
+ });
11856
+ client.requestAccessToken();
11857
+ }
11858
+ else {
11859
+ // Use One Tap / Sign-In button flow (smoother UX but doesn't work in iframes)
11860
+ google.accounts.id.initialize({
11861
+ client_id: googleClientId,
11862
+ callback: async (response) => {
11863
+ try {
11864
+ const idToken = response.credential;
11865
+ const authResponse = await api.loginWithGoogle(idToken);
11866
+ if (authResponse.token) {
11867
+ auth.login(authResponse.token, authResponse.user, authResponse.accountData);
11868
+ setAuthSuccess(true);
11869
+ setSuccessMessage('Google login successful!');
11870
+ onAuthSuccess(authResponse.token, authResponse.user, authResponse.accountData);
11871
+ }
11872
+ else {
11873
+ throw new Error('Authentication failed - no token received');
11874
+ }
11875
+ if (redirectUrl) {
11876
+ setTimeout(() => {
11877
+ window.location.href = redirectUrl;
11878
+ }, 2000);
11879
+ }
11880
+ setLoading(false);
11881
+ }
11882
+ catch (err) {
11883
+ const errorMessage = err instanceof Error ? err.message : 'Google login failed';
11884
+ setError(errorMessage);
11885
+ onAuthError?.(err instanceof Error ? err : new Error(errorMessage));
11886
+ setLoading(false);
11887
+ }
11888
+ },
11889
+ auto_select: false,
11890
+ cancel_on_tap_outside: true,
11891
+ });
11892
+ google.accounts.id.prompt((notification) => {
11893
+ if (notification.isNotDisplayed() || notification.isSkippedMoment()) {
11894
+ setLoading(false);
11895
+ }
11896
+ });
11897
+ }
11674
11898
  }
11675
- if (!deletePassword) {
11676
- setError('Password is required');
11677
- return;
11899
+ catch (err) {
11900
+ const errorMessage = err instanceof Error ? err.message : 'Google login failed';
11901
+ setError(errorMessage);
11902
+ onAuthError?.(err instanceof Error ? err : new Error(errorMessage));
11903
+ setLoading(false);
11678
11904
  }
11905
+ };
11906
+ const handlePhoneAuth = async (phoneNumber, verificationCode) => {
11679
11907
  setLoading(true);
11680
11908
  setError(undefined);
11681
11909
  try {
11682
- // TODO: Backend implementation required
11683
- // Endpoint: DELETE /api/v1/authkit/:clientId/account/delete
11684
- // SDK method: smartlinks.authKit.deleteAccount(clientId, password, confirmText)
11685
- // Note: This performs a SOFT DELETE (marks as deleted, obfuscates email)
11686
- setError('Backend API not yet implemented. See console for required endpoint.');
11687
- console.log('Required API endpoint: DELETE /api/v1/authkit/:clientId/account/delete');
11688
- console.log('Data: password and confirmText="DELETE" provided');
11689
- console.log('Note: Backend should soft delete (mark deleted, obfuscate email, disable account)');
11690
- // Uncomment when backend is ready:
11691
- // await smartlinks.authKit.deleteAccount(clientId, deletePassword, deleteConfirmText);
11692
- // setSuccess('Account deleted successfully');
11693
- // onAccountDeleted?.();
11694
- // await auth.logout();
11910
+ if (!verificationCode) {
11911
+ // Send verification code via Twilio Verify Service
11912
+ await api.sendPhoneCode(phoneNumber);
11913
+ // Twilio Verify Service tracks the verification by phone number
11914
+ // No need to store verificationId
11915
+ }
11916
+ else {
11917
+ // Verify code - Twilio identifies the verification by phone number
11918
+ const response = await api.verifyPhoneCode(phoneNumber, verificationCode);
11919
+ // Update auth context with account data if token is provided
11920
+ if (response.token) {
11921
+ auth.login(response.token, response.user, response.accountData);
11922
+ onAuthSuccess(response.token, response.user, response.accountData);
11923
+ if (redirectUrl) {
11924
+ window.location.href = redirectUrl;
11925
+ }
11926
+ }
11927
+ else {
11928
+ throw new Error('Authentication failed - no token received');
11929
+ }
11930
+ }
11695
11931
  }
11696
11932
  catch (err) {
11697
- const errorMessage = err instanceof Error ? err.message : 'Failed to delete account';
11933
+ const errorMessage = err instanceof Error ? err.message : 'Phone authentication failed';
11698
11934
  setError(errorMessage);
11699
- onError?.(err instanceof Error ? err : new Error(errorMessage));
11935
+ onAuthError?.(err instanceof Error ? err : new Error(errorMessage));
11700
11936
  }
11701
11937
  finally {
11702
11938
  setLoading(false);
11703
11939
  }
11704
11940
  };
11705
- if (!auth.isAuthenticated) {
11706
- return (jsxRuntime.jsx("div", { className: `account-management ${className}`, children: jsxRuntime.jsx("p", { className: "text-muted-foreground", children: "Please log in to manage your account" }) }));
11707
- }
11708
- if (loading && !profile) {
11709
- return (jsxRuntime.jsx("div", { className: `account-management ${className}`, children: jsxRuntime.jsx("p", { className: "text-muted-foreground", children: "Loading..." }) }));
11710
- }
11711
- return (jsxRuntime.jsxs("div", { className: `account-management ${className}`, style: { maxWidth: '600px' }, children: [error && (jsxRuntime.jsx("div", { className: "auth-error", role: "alert", children: error })), success && (jsxRuntime.jsx("div", { className: "auth-success", role: "alert", children: success })), showProfileSection && (jsxRuntime.jsxs("section", { className: "account-section", children: [jsxRuntime.jsxs("div", { className: "account-field", children: [jsxRuntime.jsxs("div", { className: "field-info", children: [jsxRuntime.jsx("label", { className: "field-label", children: "Display Name" }), jsxRuntime.jsx("div", { className: "field-value", children: profile?.displayName || 'Not set' })] }), editingSection !== 'profile' && (jsxRuntime.jsx("button", { type: "button", onClick: () => setEditingSection('profile'), className: "auth-button button-secondary", children: "Change" }))] }), editingSection === 'profile' && (jsxRuntime.jsxs("form", { onSubmit: handleUpdateProfile, className: "edit-form", children: [jsxRuntime.jsx("div", { className: "form-group", children: jsxRuntime.jsx("input", { id: "displayName", type: "text", value: displayName, onChange: (e) => setDisplayName(e.target.value), placeholder: "Your display name", className: "auth-input" }) }), jsxRuntime.jsxs("div", { className: "button-group", children: [jsxRuntime.jsx("button", { type: "submit", className: "auth-button", disabled: loading, children: loading ? 'Saving...' : 'Save' }), jsxRuntime.jsx("button", { type: "button", onClick: cancelEdit, className: "auth-button button-secondary", children: "Cancel" })] })] }))] })), showEmailSection && (jsxRuntime.jsxs("section", { className: "account-section", children: [jsxRuntime.jsxs("div", { className: "account-field", children: [jsxRuntime.jsxs("div", { className: "field-info", children: [jsxRuntime.jsx("label", { className: "field-label", children: "Email Address" }), jsxRuntime.jsxs("div", { className: "field-value", children: [profile?.email || 'Not set', profile?.emailVerified && (jsxRuntime.jsx("span", { className: "verification-badge verified", children: "Verified" })), profile?.email && !profile?.emailVerified && (jsxRuntime.jsx("span", { className: "verification-badge unverified", children: "Unverified" }))] })] }), editingSection !== 'email' && (jsxRuntime.jsx("button", { type: "button", onClick: () => setEditingSection('email'), className: "auth-button button-secondary", children: "Change Email" }))] }), editingSection === 'email' && (jsxRuntime.jsxs("form", { onSubmit: handleChangeEmail, className: "edit-form", children: [jsxRuntime.jsxs("div", { className: "form-group", children: [jsxRuntime.jsx("label", { htmlFor: "newEmail", children: "New Email" }), jsxRuntime.jsx("input", { id: "newEmail", type: "email", value: newEmail, onChange: (e) => setNewEmail(e.target.value), placeholder: "new.email@example.com", className: "auth-input", required: true })] }), jsxRuntime.jsxs("div", { className: "form-group", children: [jsxRuntime.jsx("label", { htmlFor: "emailPassword", children: "Confirm Password" }), jsxRuntime.jsx("input", { id: "emailPassword", type: "password", value: emailPassword, onChange: (e) => setEmailPassword(e.target.value), placeholder: "Enter your password", className: "auth-input", required: true })] }), jsxRuntime.jsxs("div", { className: "button-group", children: [jsxRuntime.jsx("button", { type: "submit", className: "auth-button", disabled: loading, children: loading ? 'Changing...' : 'Change Email' }), jsxRuntime.jsx("button", { type: "button", onClick: cancelEdit, className: "auth-button button-secondary", children: "Cancel" })] })] }))] })), showPasswordSection && (jsxRuntime.jsxs("section", { className: "account-section", children: [jsxRuntime.jsxs("div", { className: "account-field", children: [jsxRuntime.jsxs("div", { className: "field-info", children: [jsxRuntime.jsx("label", { className: "field-label", children: "Password" }), jsxRuntime.jsx("div", { className: "field-value", children: "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022" })] }), editingSection !== 'password' && (jsxRuntime.jsx("button", { type: "button", onClick: () => setEditingSection('password'), className: "auth-button button-secondary", children: "Change Password" }))] }), editingSection === 'password' && (jsxRuntime.jsxs("form", { onSubmit: handleChangePassword, className: "edit-form", children: [jsxRuntime.jsxs("div", { className: "form-group", children: [jsxRuntime.jsx("label", { htmlFor: "currentPassword", children: "Current Password" }), jsxRuntime.jsx("input", { id: "currentPassword", type: "password", value: currentPassword, onChange: (e) => setCurrentPassword(e.target.value), placeholder: "Enter current password", className: "auth-input", required: true })] }), jsxRuntime.jsxs("div", { className: "form-group", children: [jsxRuntime.jsx("label", { htmlFor: "newPassword", children: "New Password" }), jsxRuntime.jsx("input", { id: "newPassword", type: "password", value: newPassword, onChange: (e) => setNewPassword(e.target.value), placeholder: "Enter new password", className: "auth-input", required: true, minLength: 6 })] }), jsxRuntime.jsxs("div", { className: "form-group", children: [jsxRuntime.jsx("label", { htmlFor: "confirmPassword", children: "Confirm New Password" }), jsxRuntime.jsx("input", { id: "confirmPassword", type: "password", value: confirmPassword, onChange: (e) => setConfirmPassword(e.target.value), placeholder: "Confirm new password", className: "auth-input", required: true, minLength: 6 })] }), jsxRuntime.jsxs("div", { className: "button-group", children: [jsxRuntime.jsx("button", { type: "submit", className: "auth-button", disabled: loading, children: loading ? 'Changing...' : 'Change Password' }), jsxRuntime.jsx("button", { type: "button", onClick: cancelEdit, className: "auth-button button-secondary", children: "Cancel" })] })] }))] })), showPhoneSection && (jsxRuntime.jsxs("section", { className: "account-section", children: [jsxRuntime.jsxs("div", { className: "account-field", children: [jsxRuntime.jsxs("div", { className: "field-info", children: [jsxRuntime.jsx("label", { className: "field-label", children: "Phone Number" }), jsxRuntime.jsx("div", { className: "field-value", children: profile?.phoneNumber || 'Not set' })] }), editingSection !== 'phone' && (jsxRuntime.jsx("button", { type: "button", onClick: () => setEditingSection('phone'), className: "auth-button button-secondary", children: "Change Phone" }))] }), editingSection === 'phone' && (jsxRuntime.jsxs("form", { onSubmit: handleUpdatePhone, className: "edit-form", children: [jsxRuntime.jsxs("div", { className: "form-group", children: [jsxRuntime.jsx("label", { htmlFor: "newPhone", children: "New Phone Number" }), jsxRuntime.jsx("input", { id: "newPhone", type: "tel", value: newPhone, onChange: (e) => setNewPhone(e.target.value), placeholder: "+1234567890", className: "auth-input", required: true })] }), !phoneCodeSent ? (jsxRuntime.jsxs("div", { className: "button-group", children: [jsxRuntime.jsx("button", { type: "button", onClick: handleSendPhoneCode, className: "auth-button", disabled: loading || !newPhone, children: loading ? 'Sending...' : 'Send Code' }), jsxRuntime.jsx("button", { type: "button", onClick: cancelEdit, className: "auth-button button-secondary", children: "Cancel" })] })) : (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsxs("div", { className: "form-group", children: [jsxRuntime.jsx("label", { htmlFor: "phoneCode", children: "Verification Code" }), jsxRuntime.jsx("input", { id: "phoneCode", type: "text", value: phoneCode, onChange: (e) => setPhoneCode(e.target.value), placeholder: "Enter 6-digit code", className: "auth-input", required: true, maxLength: 6 })] }), jsxRuntime.jsxs("div", { className: "button-group", children: [jsxRuntime.jsx("button", { type: "submit", className: "auth-button", disabled: loading, children: loading ? 'Verifying...' : 'Verify & Save' }), jsxRuntime.jsx("button", { type: "button", onClick: cancelEdit, className: "auth-button button-secondary", children: "Cancel" })] })] }))] }))] })), showDeleteAccount && (jsxRuntime.jsxs("section", { className: "account-section danger-zone", children: [jsxRuntime.jsx("h3", { className: "section-title text-danger", children: "Danger Zone" }), !showDeleteConfirm ? (jsxRuntime.jsx("button", { type: "button", onClick: () => setShowDeleteConfirm(true), className: "auth-button button-danger", children: "Delete Account" })) : (jsxRuntime.jsxs("div", { className: "delete-confirm", children: [jsxRuntime.jsx("p", { className: "warning-text", children: "\u26A0\uFE0F This action cannot be undone. This will permanently delete your account and all associated data." }), jsxRuntime.jsxs("div", { className: "form-group", children: [jsxRuntime.jsx("label", { htmlFor: "deletePassword", children: "Confirm Password" }), jsxRuntime.jsx("input", { id: "deletePassword", type: "password", value: deletePassword, onChange: (e) => setDeletePassword(e.target.value), placeholder: "Enter your password", className: "auth-input" })] }), jsxRuntime.jsxs("div", { className: "form-group", children: [jsxRuntime.jsx("label", { htmlFor: "deleteConfirm", children: "Type DELETE to confirm" }), jsxRuntime.jsx("input", { id: "deleteConfirm", type: "text", value: deleteConfirmText, onChange: (e) => setDeleteConfirmText(e.target.value), placeholder: "DELETE", className: "auth-input" })] }), jsxRuntime.jsxs("div", { className: "button-group", children: [jsxRuntime.jsx("button", { type: "button", onClick: handleDeleteAccount, className: "auth-button button-danger", disabled: loading, children: loading ? 'Deleting...' : 'Permanently Delete Account' }), jsxRuntime.jsx("button", { type: "button", onClick: () => {
11712
- setShowDeleteConfirm(false);
11713
- setDeletePassword('');
11714
- setDeleteConfirmText('');
11715
- }, className: "auth-button button-secondary", children: "Cancel" })] })] }))] }))] }));
11716
- };
11717
-
11718
- const SmartlinksClaimUI = ({ apiEndpoint, clientId, clientName, collectionId, productId, proofId, onClaimSuccess, onClaimError, additionalFields = [], theme = 'light', className = '', minimal = false, customization = {}, }) => {
11719
- const auth = useAuth();
11720
- const [claimStep, setClaimStep] = React.useState(auth.isAuthenticated ? 'questions' : 'auth');
11721
- const [claimData, setClaimData] = React.useState({});
11722
- const [error, setError] = React.useState();
11723
- const [loading, setLoading] = React.useState(false);
11724
- const handleAuthSuccess = (token, user, accountData) => {
11725
- // Authentication successful
11726
- auth.login(token, user, accountData);
11727
- // If no additional questions, proceed directly to claim
11728
- if (additionalFields.length === 0) {
11729
- executeClaim(user);
11730
- }
11731
- else {
11732
- setClaimStep('questions');
11941
+ const handlePasswordReset = async (emailOrPassword, confirmPassword) => {
11942
+ setLoading(true);
11943
+ setError(undefined);
11944
+ try {
11945
+ if (resetToken && confirmPassword) {
11946
+ // Complete password reset with token
11947
+ await api.completePasswordReset(resetToken, emailOrPassword);
11948
+ setResetSuccess(true);
11949
+ setResetToken(undefined); // Clear token after successful reset
11950
+ }
11951
+ else {
11952
+ // Request password reset email
11953
+ await api.requestPasswordReset(emailOrPassword, getRedirectUrl());
11954
+ setResetSuccess(true);
11955
+ }
11733
11956
  }
11734
- };
11735
- const handleQuestionSubmit = async (e) => {
11736
- e.preventDefault();
11737
- // Validate required fields
11738
- const missingFields = additionalFields
11739
- .filter(field => field.required && !claimData[field.name])
11740
- .map(field => field.label);
11741
- if (missingFields.length > 0) {
11742
- setError(`Please fill in: ${missingFields.join(', ')}`);
11743
- return;
11957
+ catch (err) {
11958
+ const errorMessage = err instanceof Error ? err.message : 'Password reset failed';
11959
+ setError(errorMessage);
11960
+ onAuthError?.(err instanceof Error ? err : new Error(errorMessage));
11744
11961
  }
11745
- // Execute claim with collected data
11746
- if (auth.user) {
11747
- executeClaim(auth.user);
11962
+ finally {
11963
+ setLoading(false);
11748
11964
  }
11749
11965
  };
11750
- const executeClaim = async (user) => {
11751
- setClaimStep('claiming');
11966
+ const handleMagicLink = async (email) => {
11752
11967
  setLoading(true);
11753
11968
  setError(undefined);
11754
11969
  try {
11755
- // Create attestation to claim the proof
11756
- const response = await smartlinks__namespace.attestation.create(collectionId, productId, proofId, {
11757
- public: {
11758
- claimed: true,
11759
- claimedAt: new Date().toISOString(),
11760
- claimedBy: user.uid,
11761
- ...claimData,
11762
- },
11763
- private: {},
11764
- proof: {},
11765
- });
11766
- setClaimStep('success');
11767
- // Call success callback
11768
- onClaimSuccess({
11769
- proofId,
11770
- user,
11771
- claimData,
11772
- attestationId: response.id,
11773
- });
11970
+ await api.sendMagicLink(email, getRedirectUrl());
11971
+ setAuthSuccess(true);
11972
+ setSuccessMessage('Magic link sent! Check your email to log in.');
11774
11973
  }
11775
11974
  catch (err) {
11776
- console.error('Claim error:', err);
11777
- const errorMessage = err instanceof Error ? err.message : 'Failed to claim proof';
11975
+ const errorMessage = err instanceof Error ? err.message : 'Failed to send magic link';
11778
11976
  setError(errorMessage);
11779
- onClaimError?.(err instanceof Error ? err : new Error(errorMessage));
11780
- setClaimStep(additionalFields.length > 0 ? 'questions' : 'auth');
11977
+ onAuthError?.(err instanceof Error ? err : new Error(errorMessage));
11781
11978
  }
11782
11979
  finally {
11783
11980
  setLoading(false);
11784
11981
  }
11785
11982
  };
11786
- const handleFieldChange = (fieldName, value) => {
11787
- setClaimData(prev => ({
11788
- ...prev,
11789
- [fieldName]: value,
11790
- }));
11791
- };
11792
- // Render authentication step
11793
- if (claimStep === 'auth') {
11794
- return (jsxRuntime.jsx("div", { className: className, children: jsxRuntime.jsx(SmartlinksAuthUI, { apiEndpoint: apiEndpoint, clientId: clientId, clientName: clientName, onAuthSuccess: handleAuthSuccess, onAuthError: onClaimError, theme: theme, minimal: minimal, customization: customization.authConfig }) }));
11795
- }
11796
- // Render additional questions step
11797
- if (claimStep === 'questions') {
11798
- return (jsxRuntime.jsxs("div", { className: `claim-questions ${className}`, children: [jsxRuntime.jsxs("div", { className: "claim-header mb-6", children: [jsxRuntime.jsx("h2", { className: "text-2xl font-bold mb-2", children: customization.claimTitle || 'Complete Your Claim' }), customization.claimDescription && (jsxRuntime.jsx("p", { className: "text-muted-foreground", children: customization.claimDescription }))] }), error && (jsxRuntime.jsx("div", { className: "claim-error bg-destructive/10 text-destructive px-4 py-3 rounded-md mb-4", children: error })), jsxRuntime.jsxs("form", { onSubmit: handleQuestionSubmit, className: "claim-form space-y-4", children: [additionalFields.map((field) => (jsxRuntime.jsxs("div", { className: "claim-field", children: [jsxRuntime.jsxs("label", { htmlFor: field.name, className: "block text-sm font-medium mb-2", children: [field.label, field.required && jsxRuntime.jsx("span", { className: "text-destructive ml-1", children: "*" })] }), field.type === 'textarea' ? (jsxRuntime.jsx("textarea", { id: field.name, name: field.name, placeholder: field.placeholder, value: claimData[field.name] || '', onChange: (e) => handleFieldChange(field.name, e.target.value), required: field.required, className: "w-full px-3 py-2 border border-input rounded-md bg-background", rows: 4 })) : field.type === 'select' ? (jsxRuntime.jsxs("select", { id: field.name, name: field.name, value: claimData[field.name] || '', onChange: (e) => handleFieldChange(field.name, e.target.value), required: field.required, className: "w-full px-3 py-2 border border-input rounded-md bg-background", children: [jsxRuntime.jsx("option", { value: "", children: "Select..." }), field.options?.map((option) => (jsxRuntime.jsx("option", { value: option, children: option }, option)))] })) : (jsxRuntime.jsx("input", { id: field.name, name: field.name, type: field.type, placeholder: field.placeholder, value: claimData[field.name] || '', onChange: (e) => handleFieldChange(field.name, e.target.value), required: field.required, className: "w-full px-3 py-2 border border-input rounded-md bg-background" }))] }, field.name))), jsxRuntime.jsx("button", { type: "submit", disabled: loading, className: "claim-submit-button w-full bg-primary text-primary-foreground px-4 py-2 rounded-md font-medium hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed", children: loading ? 'Claiming...' : 'Submit Claim' })] })] }));
11983
+ if (configLoading) {
11984
+ return (jsxRuntime.jsx(AuthContainer, { theme: theme, className: className, minimal: minimal || config?.branding?.minimal || false, children: jsxRuntime.jsx("div", { style: { textAlign: 'center', padding: '2rem' }, children: jsxRuntime.jsx("div", { className: "auth-spinner" }) }) }));
11799
11985
  }
11800
- // Render claiming step (loading state)
11801
- if (claimStep === 'claiming') {
11802
- return (jsxRuntime.jsxs("div", { className: `claim-loading ${className} flex flex-col items-center justify-center py-12`, children: [jsxRuntime.jsx("div", { className: "claim-spinner w-12 h-12 border-4 border-primary border-t-transparent rounded-full animate-spin mb-4" }), jsxRuntime.jsx("p", { className: "text-muted-foreground", children: "Claiming your product..." })] }));
11803
- }
11804
- // Render success step
11805
- if (claimStep === 'success') {
11806
- return (jsxRuntime.jsxs("div", { className: `claim-success ${className} text-center py-12`, children: [jsxRuntime.jsx("div", { className: "claim-success-icon w-16 h-16 bg-green-500 text-white rounded-full flex items-center justify-center text-3xl font-bold mx-auto mb-4", children: "\u2713" }), jsxRuntime.jsx("h2", { className: "text-2xl font-bold mb-2", children: "Claim Successful!" }), jsxRuntime.jsx("p", { className: "text-muted-foreground", children: customization.successMessage || 'Your product has been successfully claimed and registered to your account.' })] }));
11807
- }
11808
- return null;
11809
- };
11810
-
11811
- const ProtectedRoute = ({ children, fallback, redirectTo, }) => {
11812
- const { isAuthenticated, isLoading } = useAuth();
11813
- // Show loading state
11814
- if (isLoading) {
11815
- return jsxRuntime.jsx("div", { children: "Loading..." });
11816
- }
11817
- // If not authenticated, redirect or show fallback
11818
- if (!isAuthenticated) {
11819
- if (redirectTo) {
11820
- window.location.href = redirectTo;
11821
- return null;
11822
- }
11823
- return fallback ? jsxRuntime.jsx(jsxRuntime.Fragment, { children: fallback }) : jsxRuntime.jsx("div", { children: "Access denied. Please log in." });
11824
- }
11825
- // Render protected content
11826
- return jsxRuntime.jsx(jsxRuntime.Fragment, { children: children });
11827
- };
11828
-
11829
- const AuthUIPreview = ({ customization, enabledProviders = ['email', 'google', 'phone'], providerOrder, emailDisplayMode = 'form', theme = 'light', className, minimal = false, }) => {
11830
- const showEmail = enabledProviders.includes('email');
11831
- const showGoogle = enabledProviders.includes('google');
11832
- const showPhone = enabledProviders.includes('phone');
11833
- const showMagicLink = enabledProviders.includes('magic-link');
11834
- // Determine ordered providers (excluding email if in button mode)
11835
- const orderedProviders = providerOrder && providerOrder.length > 0
11836
- ? providerOrder.filter(p => enabledProviders.includes(p) && p !== 'email')
11837
- : enabledProviders.filter(p => p !== 'email');
11838
- const hasOtherProviders = showGoogle || showPhone || showMagicLink;
11839
- // Render provider button helper
11840
- const renderProviderButton = (provider) => {
11841
- if (provider === 'google' && showGoogle) {
11842
- return (jsxRuntime.jsxs("button", { className: "auth-provider-button", disabled: true, children: [jsxRuntime.jsxs("svg", { width: "18", height: "18", viewBox: "0 0 18 18", fill: "none", children: [jsxRuntime.jsx("path", { d: "M17.64 9.2c0-.637-.057-1.251-.164-1.84H9v3.481h4.844c-.209 1.125-.843 2.078-1.796 2.717v2.258h2.908c1.702-1.567 2.684-3.874 2.684-6.615z", fill: "#4285F4" }), jsxRuntime.jsx("path", { d: "M9 18c2.43 0 4.467-.806 5.956-2.183l-2.908-2.259c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332C2.438 15.983 5.482 18 9 18z", fill: "#34A853" }), jsxRuntime.jsx("path", { d: "M3.964 10.707c-.18-.54-.282-1.117-.282-1.707 0-.593.102-1.167.282-1.707V4.961H.957C.347 6.175 0 7.548 0 9s.348 2.825.957 4.039l3.007-2.332z", fill: "#FBBC05" }), jsxRuntime.jsx("path", { d: "M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0 5.482 0 2.438 2.017.957 4.958L3.964 7.29C4.672 5.163 6.656 3.58 9 3.58z", fill: "#EA4335" })] }), jsxRuntime.jsx("span", { children: "Continue with Google" })] }, "google"));
11843
- }
11844
- if (provider === 'phone' && showPhone) {
11845
- return (jsxRuntime.jsxs("button", { className: "auth-provider-button", disabled: true, children: [jsxRuntime.jsx("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", children: jsxRuntime.jsx("path", { d: "M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z" }) }), jsxRuntime.jsx("span", { children: "Continue with Phone" })] }, "phone"));
11846
- }
11847
- if (provider === 'magic-link' && showMagicLink) {
11848
- return (jsxRuntime.jsxs("button", { className: "auth-provider-button", disabled: true, children: [jsxRuntime.jsx("svg", { width: "18", height: "18", viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", children: jsxRuntime.jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" }) }), jsxRuntime.jsx("span", { children: "Continue with Magic Link" })] }, "magic-link"));
11849
- }
11850
- if (provider === 'email' && showEmail && emailDisplayMode === 'button') {
11851
- return (jsxRuntime.jsxs("button", { className: "auth-provider-button", disabled: true, children: [jsxRuntime.jsx("svg", { width: "18", height: "18", viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", children: jsxRuntime.jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" }) }), jsxRuntime.jsx("span", { children: "Continue with Email" })] }, "email"));
11852
- }
11853
- return null;
11854
- };
11855
- return (jsxRuntime.jsx(AuthContainer, { theme: theme, className: className, config: customization, minimal: minimal, children: emailDisplayMode === 'button' ? (jsxRuntime.jsx("div", { className: "auth-provider-buttons", children: orderedProviders.concat(showEmail ? ['email'] : []).map(provider => renderProviderButton(provider)) })) : (
11856
- /* Form mode: show email form first, then other providers */
11857
- jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [showEmail && (jsxRuntime.jsxs("div", { className: "auth-form", children: [jsxRuntime.jsxs("div", { className: "auth-form-group", children: [jsxRuntime.jsx("label", { className: "auth-label", children: "Email" }), jsxRuntime.jsx("input", { type: "email", className: "auth-input", placeholder: "Enter your email", disabled: true })] }), jsxRuntime.jsxs("div", { className: "auth-form-group", children: [jsxRuntime.jsx("label", { className: "auth-label", children: "Password" }), jsxRuntime.jsx("input", { type: "password", className: "auth-input", placeholder: "Enter your password", disabled: true })] }), jsxRuntime.jsx("button", { className: "auth-button auth-button-primary", disabled: true, children: "Sign In" }), jsxRuntime.jsx("div", { style: { textAlign: 'center', marginTop: '1rem' }, children: jsxRuntime.jsx("button", { className: "auth-link", disabled: true, children: "Forgot password?" }) }), jsxRuntime.jsxs("div", { style: { textAlign: 'center', marginTop: '0.5rem', fontSize: '0.875rem', color: 'var(--auth-text-muted, #6B7280)' }, children: ["Don't have an account?", ' ', jsxRuntime.jsx("button", { className: "auth-link", disabled: true, children: "Sign up" })] })] })), hasOtherProviders && (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [showEmail && (jsxRuntime.jsx("div", { className: "auth-or-divider", children: jsxRuntime.jsx("span", { children: "or continue with" }) })), jsxRuntime.jsx("div", { className: "auth-provider-buttons", children: orderedProviders.map(provider => renderProviderButton(provider)) })] }))] })) }));
11986
+ return (jsxRuntime.jsx(AuthContainer, { theme: theme, className: className, config: config, minimal: minimal || config?.branding?.minimal || false, children: authSuccess ? (jsxRuntime.jsxs("div", { style: { textAlign: 'center', padding: '2rem' }, children: [jsxRuntime.jsx("div", { style: {
11987
+ color: 'var(--auth-primary-color, #4F46E5)',
11988
+ fontSize: '3rem',
11989
+ marginBottom: '1rem'
11990
+ }, children: "\u2713" }), jsxRuntime.jsx("h2", { style: {
11991
+ marginBottom: '0.5rem',
11992
+ fontSize: '1.5rem',
11993
+ fontWeight: 600
11994
+ }, children: successMessage?.includes('verified') ? 'Email Verified!' :
11995
+ successMessage?.includes('Magic link') ? 'Check Your Email!' :
11996
+ mode === 'register' ? 'Account Created!' : 'Login Successful!' }), jsxRuntime.jsx("p", { style: {
11997
+ color: '#6B7280',
11998
+ fontSize: '0.875rem'
11999
+ }, children: successMessage })] })) : mode === 'magic-link' ? (jsxRuntime.jsx(MagicLinkForm, { onSubmit: handleMagicLink, onCancel: () => setMode('login'), loading: loading, error: error })) : mode === 'phone' ? (jsxRuntime.jsx(PhoneAuthForm, { onSubmit: handlePhoneAuth, onBack: () => setMode('login'), loading: loading, error: error })) : mode === 'reset-password' ? (jsxRuntime.jsx(PasswordResetForm, { onSubmit: handlePasswordReset, onBack: () => {
12000
+ setMode('login');
12001
+ setResetSuccess(false);
12002
+ setResetToken(undefined); // Clear token when going back
12003
+ }, loading: loading, error: error, success: resetSuccess, token: resetToken })) : (mode === 'login' || mode === 'register') ? (jsxRuntime.jsx(jsxRuntime.Fragment, { children: showResendVerification ? (jsxRuntime.jsxs("div", { style: { marginTop: '1rem', padding: '1.5rem', backgroundColor: 'rgba(79, 70, 229, 0.05)', borderRadius: '0.5rem' }, children: [jsxRuntime.jsx("h3", { style: { marginBottom: '0.75rem', fontSize: '1rem', fontWeight: 600, color: 'var(--auth-text-color, #374151)' }, children: "Verification Link Expired" }), jsxRuntime.jsx("p", { style: { marginBottom: '1rem', fontSize: '0.875rem', color: 'var(--auth-text-color, #6B7280)', lineHeight: '1.5' }, children: "Your verification link has expired or is no longer valid. Please enter your email address below and we'll send you a new verification link." }), jsxRuntime.jsx("input", { type: "email", value: resendEmail || '', onChange: (e) => setResendEmail(e.target.value), placeholder: "your@email.com", style: {
12004
+ width: '100%',
12005
+ padding: '0.625rem',
12006
+ marginBottom: '1rem',
12007
+ border: '1px solid var(--auth-border-color, #D1D5DB)',
12008
+ borderRadius: '0.375rem',
12009
+ fontSize: '0.875rem',
12010
+ boxSizing: 'border-box'
12011
+ } }), jsxRuntime.jsxs("div", { style: { display: 'flex', gap: '0.75rem' }, children: [jsxRuntime.jsx("button", { onClick: handleResendVerification, disabled: loading || !resendEmail, style: {
12012
+ flex: 1,
12013
+ padding: '0.625rem 1rem',
12014
+ backgroundColor: 'var(--auth-primary-color, #4F46E5)',
12015
+ color: 'white',
12016
+ border: 'none',
12017
+ borderRadius: '0.375rem',
12018
+ cursor: (loading || !resendEmail) ? 'not-allowed' : 'pointer',
12019
+ fontSize: '0.875rem',
12020
+ fontWeight: 500,
12021
+ opacity: (loading || !resendEmail) ? 0.6 : 1
12022
+ }, children: loading ? 'Sending...' : 'Send New Verification Link' }), jsxRuntime.jsx("button", { onClick: () => {
12023
+ setShowResendVerification(false);
12024
+ setResendEmail('');
12025
+ setError(undefined);
12026
+ }, disabled: loading, style: {
12027
+ padding: '0.625rem 1rem',
12028
+ backgroundColor: 'transparent',
12029
+ color: 'var(--auth-text-color, #6B7280)',
12030
+ border: '1px solid var(--auth-border-color, #D1D5DB)',
12031
+ borderRadius: '0.375rem',
12032
+ cursor: loading ? 'not-allowed' : 'pointer',
12033
+ fontSize: '0.875rem',
12034
+ fontWeight: 500,
12035
+ opacity: loading ? 0.6 : 1
12036
+ }, children: "Cancel" })] })] })) : showRequestNewReset ? (jsxRuntime.jsxs("div", { style: { marginTop: '1rem', padding: '1.5rem', backgroundColor: 'rgba(239, 68, 68, 0.05)', borderRadius: '0.5rem' }, children: [jsxRuntime.jsx("h3", { style: { marginBottom: '0.75rem', fontSize: '1rem', fontWeight: 600, color: 'var(--auth-text-color, #374151)' }, children: "Password Reset Link Expired" }), jsxRuntime.jsx("p", { style: { marginBottom: '1rem', fontSize: '0.875rem', color: 'var(--auth-text-color, #6B7280)', lineHeight: '1.5' }, children: "Your password reset link has expired or is no longer valid. Please enter your email address below and we'll send you a new password reset link." }), jsxRuntime.jsx("input", { type: "email", value: resetRequestEmail || '', onChange: (e) => setResetRequestEmail(e.target.value), placeholder: "your@email.com", style: {
12037
+ width: '100%',
12038
+ padding: '0.625rem',
12039
+ marginBottom: '1rem',
12040
+ border: '1px solid var(--auth-border-color, #D1D5DB)',
12041
+ borderRadius: '0.375rem',
12042
+ fontSize: '0.875rem',
12043
+ boxSizing: 'border-box'
12044
+ } }), jsxRuntime.jsxs("div", { style: { display: 'flex', gap: '0.75rem' }, children: [jsxRuntime.jsx("button", { onClick: handleRequestNewReset, disabled: loading || !resetRequestEmail, style: {
12045
+ flex: 1,
12046
+ padding: '0.625rem 1rem',
12047
+ backgroundColor: '#EF4444',
12048
+ color: 'white',
12049
+ border: 'none',
12050
+ borderRadius: '0.375rem',
12051
+ cursor: (loading || !resetRequestEmail) ? 'not-allowed' : 'pointer',
12052
+ fontSize: '0.875rem',
12053
+ fontWeight: 500,
12054
+ opacity: (loading || !resetRequestEmail) ? 0.6 : 1
12055
+ }, children: loading ? 'Sending...' : 'Send New Reset Link' }), jsxRuntime.jsx("button", { onClick: () => {
12056
+ setShowRequestNewReset(false);
12057
+ setResetRequestEmail('');
12058
+ setError(undefined);
12059
+ }, disabled: loading, style: {
12060
+ padding: '0.625rem 1rem',
12061
+ backgroundColor: 'transparent',
12062
+ color: 'var(--auth-text-color, #6B7280)',
12063
+ border: '1px solid var(--auth-border-color, #D1D5DB)',
12064
+ borderRadius: '0.375rem',
12065
+ cursor: loading ? 'not-allowed' : 'pointer',
12066
+ fontSize: '0.875rem',
12067
+ fontWeight: 500,
12068
+ opacity: loading ? 0.6 : 1
12069
+ }, children: "Cancel" })] })] })) : (jsxRuntime.jsx(jsxRuntime.Fragment, { children: (() => {
12070
+ const emailDisplayMode = config?.emailDisplayMode || 'form';
12071
+ const providerOrder = config?.providerOrder || (config?.enabledProviders || enabledProviders);
12072
+ const actualProviders = config?.enabledProviders || enabledProviders;
12073
+ // Button mode: show provider selection first, then email form if email is selected
12074
+ if (emailDisplayMode === 'button' && !showEmailForm) {
12075
+ return (jsxRuntime.jsx(ProviderButtons, { enabledProviders: actualProviders, providerOrder: providerOrder, onEmailLogin: () => setShowEmailForm(true), onGoogleLogin: handleGoogleLogin, onPhoneLogin: () => setMode('phone'), onMagicLinkLogin: () => setMode('magic-link'), loading: loading }));
12076
+ }
12077
+ // Form mode or email button was clicked: show email form with other providers
12078
+ return (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [emailDisplayMode === 'button' && showEmailForm && (jsxRuntime.jsx("button", { onClick: () => setShowEmailForm(false), style: {
12079
+ marginBottom: '1rem',
12080
+ padding: '0.5rem',
12081
+ background: 'none',
12082
+ border: 'none',
12083
+ color: 'var(--auth-text-color, #6B7280)',
12084
+ cursor: 'pointer',
12085
+ fontSize: '0.875rem',
12086
+ display: 'flex',
12087
+ alignItems: 'center',
12088
+ gap: '0.25rem'
12089
+ }, children: "\u2190 Back to options" })), jsxRuntime.jsx(EmailAuthForm, { mode: mode, onSubmit: handleEmailAuth, onModeSwitch: () => {
12090
+ setMode(mode === 'login' ? 'register' : 'login');
12091
+ setShowResendVerification(false);
12092
+ setShowRequestNewReset(false);
12093
+ setError(undefined);
12094
+ }, onForgotPassword: () => setMode('reset-password'), loading: loading, error: error, additionalFields: config?.signupAdditionalFields }), emailDisplayMode === 'form' && actualProviders.length > 1 && (jsxRuntime.jsx(ProviderButtons, { enabledProviders: actualProviders.filter((p) => p !== 'email'), providerOrder: providerOrder, onGoogleLogin: handleGoogleLogin, onPhoneLogin: () => setMode('phone'), onMagicLinkLogin: () => setMode('magic-link'), loading: loading }))] }));
12095
+ })() })) })) : null }));
11858
12096
  };
11859
12097
 
11860
- // Default Smartlinks Google OAuth Client ID (public - safe to expose)
11861
- const DEFAULT_GOOGLE_CLIENT_ID = '696509063554-jdlbjl8vsjt7cr0vgkjkjf3ffnvi3a70.apps.googleusercontent.com';
11862
- const SmartlinksAuthUI = ({ apiEndpoint, clientId, clientName, accountData, onAuthSuccess, onAuthError, enabledProviders = ['email', 'google', 'phone'], initialMode = 'login', redirectUrl, theme = 'light', className, customization, skipConfigFetch = false, minimal = false, }) => {
11863
- const [mode, setMode] = React.useState(initialMode);
12098
+ const AccountManagement = ({ apiEndpoint, clientId, onError, className = '', customization = {}, }) => {
12099
+ const auth = useAuth();
11864
12100
  const [loading, setLoading] = React.useState(false);
12101
+ const [profile, setProfile] = React.useState(null);
11865
12102
  const [error, setError] = React.useState();
11866
- const [resetSuccess, setResetSuccess] = React.useState(false);
11867
- const [authSuccess, setAuthSuccess] = React.useState(false);
11868
- const [successMessage, setSuccessMessage] = React.useState();
11869
- const [showResendVerification, setShowResendVerification] = React.useState(false);
11870
- const [resendEmail, setResendEmail] = React.useState();
11871
- const [showRequestNewReset, setShowRequestNewReset] = React.useState(false);
11872
- const [resetRequestEmail, setResetRequestEmail] = React.useState();
11873
- const [resetToken, setResetToken] = React.useState(); // Store the reset token from URL
11874
- const [config, setConfig] = React.useState(null);
11875
- const [configLoading, setConfigLoading] = React.useState(!skipConfigFetch);
11876
- const [showEmailForm, setShowEmailForm] = React.useState(false); // Track if email form should be shown when emailDisplayMode is 'button'
11877
- const api = new AuthAPI(apiEndpoint, clientId, clientName);
11878
- const auth = useAuth();
11879
- // Reinitialize Smartlinks SDK when apiEndpoint changes (for test/dev scenarios)
11880
- // IMPORTANT: Preserve bearer token during reinitialization
11881
- React.useEffect(() => {
11882
- const reinitializeWithToken = async () => {
11883
- if (apiEndpoint) {
11884
- // Get current token before reinitializing
11885
- const currentToken = await auth.getToken();
11886
- smartlinks__namespace.initializeApi({
11887
- baseURL: apiEndpoint,
11888
- proxyMode: false, // Direct API calls when custom endpoint is provided
11889
- ngrokSkipBrowserWarning: true,
11890
- });
11891
- // Restore bearer token after reinitialization using auth.verifyToken
11892
- if (currentToken) {
11893
- smartlinks__namespace.auth.verifyToken(currentToken).catch(err => {
11894
- console.warn('Failed to restore bearer token after reinit:', err);
11895
- });
11896
- }
11897
- }
11898
- };
11899
- reinitializeWithToken();
11900
- }, [apiEndpoint, auth]);
11901
- // Get the effective redirect URL (use prop or default to current page)
11902
- const getRedirectUrl = () => {
11903
- if (redirectUrl)
11904
- return redirectUrl;
11905
- // Get the full current URL including hash routes
11906
- // Remove any existing query parameters to avoid duplication
11907
- const currentUrl = window.location.href.split('?')[0];
11908
- return currentUrl;
11909
- };
11910
- // Fetch UI configuration
11911
- React.useEffect(() => {
11912
- if (skipConfigFetch) {
11913
- setConfig(customization || {});
11914
- return;
11915
- }
11916
- const fetchConfig = async () => {
11917
- try {
11918
- // Check localStorage cache first
11919
- const cacheKey = `auth_ui_config_${clientId || 'default'}`;
11920
- const cached = localStorage.getItem(cacheKey);
11921
- if (cached) {
11922
- const { config: cachedConfig, timestamp } = JSON.parse(cached);
11923
- const age = Date.now() - timestamp;
11924
- // Use cache if less than 1 hour old
11925
- if (age < 3600000) {
11926
- setConfig({ ...cachedConfig, ...customization });
11927
- setConfigLoading(false);
11928
- // Fetch in background to update cache
11929
- api.fetchConfig().then(freshConfig => {
11930
- localStorage.setItem(cacheKey, JSON.stringify({
11931
- config: freshConfig,
11932
- timestamp: Date.now()
11933
- }));
11934
- });
11935
- return;
11936
- }
11937
- }
11938
- // Fetch from API
11939
- const fetchedConfig = await api.fetchConfig();
11940
- // Merge with customization props (props take precedence)
11941
- const mergedConfig = { ...fetchedConfig, ...customization };
11942
- setConfig(mergedConfig);
11943
- // Cache the fetched config
11944
- localStorage.setItem(cacheKey, JSON.stringify({
11945
- config: fetchedConfig,
11946
- timestamp: Date.now()
11947
- }));
11948
- }
11949
- catch (err) {
11950
- console.error('Failed to fetch config:', err);
11951
- setConfig(customization || {});
11952
- }
11953
- finally {
11954
- setConfigLoading(false);
11955
- }
11956
- };
11957
- fetchConfig();
11958
- }, [apiEndpoint, clientId, customization, skipConfigFetch]);
11959
- // Reset showEmailForm when mode changes away from login/register
12103
+ const [success, setSuccess] = React.useState();
12104
+ // Track which section is being edited
12105
+ const [editingSection, setEditingSection] = React.useState(null);
12106
+ // Profile form state
12107
+ const [displayName, setDisplayName] = React.useState('');
12108
+ // Email change state
12109
+ const [newEmail, setNewEmail] = React.useState('');
12110
+ const [emailPassword, setEmailPassword] = React.useState('');
12111
+ // Password change state
12112
+ const [currentPassword, setCurrentPassword] = React.useState('');
12113
+ const [newPassword, setNewPassword] = React.useState('');
12114
+ const [confirmPassword, setConfirmPassword] = React.useState('');
12115
+ // Phone change state (reuses existing sendPhoneCode flow)
12116
+ const [newPhone, setNewPhone] = React.useState('');
12117
+ const [phoneCode, setPhoneCode] = React.useState('');
12118
+ const [phoneCodeSent, setPhoneCodeSent] = React.useState(false);
12119
+ // Account deletion state
12120
+ const [deletePassword, setDeletePassword] = React.useState('');
12121
+ const [deleteConfirmText, setDeleteConfirmText] = React.useState('');
12122
+ const [showDeleteConfirm, setShowDeleteConfirm] = React.useState(false);
12123
+ const { showProfileSection = true, showEmailSection = true, showPasswordSection = true, showPhoneSection = true, showDeleteAccount = false, } = customization;
12124
+ // Reinitialize Smartlinks SDK when apiEndpoint changes
11960
12125
  React.useEffect(() => {
11961
- if (mode !== 'login' && mode !== 'register') {
11962
- setShowEmailForm(false);
12126
+ if (apiEndpoint) {
12127
+ smartlinks__namespace.initializeApi({
12128
+ baseURL: apiEndpoint,
12129
+ proxyMode: false,
12130
+ ngrokSkipBrowserWarning: true,
12131
+ });
11963
12132
  }
11964
- }, [mode]);
11965
- // Handle URL-based auth flows (email verification, password reset)
12133
+ }, [apiEndpoint]);
12134
+ // Load user profile on mount
11966
12135
  React.useEffect(() => {
11967
- // Helper to get URL parameters from either hash or search
11968
- const getUrlParams = () => {
11969
- // First check if there are params in the hash (for hash routing)
11970
- const hash = window.location.hash;
11971
- const hashQueryIndex = hash.indexOf('?');
11972
- if (hashQueryIndex !== -1) {
11973
- // Extract query string from hash (e.g., #/test?mode=verifyEmail&token=abc)
11974
- const hashQuery = hash.substring(hashQueryIndex + 1);
11975
- return new URLSearchParams(hashQuery);
11976
- }
11977
- // Fall back to regular search params (for non-hash routing)
11978
- return new URLSearchParams(window.location.search);
11979
- };
11980
- const params = getUrlParams();
11981
- const urlMode = params.get('mode');
11982
- const token = params.get('token');
11983
- console.log('URL params detected:', { urlMode, token, hash: window.location.hash, search: window.location.search });
11984
- if (urlMode && token) {
11985
- handleURLBasedAuth(urlMode, token);
12136
+ loadProfile();
12137
+ }, [clientId]);
12138
+ const loadProfile = async () => {
12139
+ if (!auth.isAuthenticated) {
12140
+ setError('You must be logged in to manage your account');
12141
+ return;
11986
12142
  }
11987
- }, []);
11988
- const handleURLBasedAuth = async (urlMode, token) => {
11989
12143
  setLoading(true);
11990
12144
  setError(undefined);
11991
12145
  try {
11992
- if (urlMode === 'verifyEmail') {
11993
- console.log('Verifying email with token:', token);
11994
- const response = await api.verifyEmailWithToken(token);
11995
- // Get email verification mode from response or config
11996
- const verificationMode = response.emailVerificationMode || config?.emailVerification?.mode || 'verify-then-auto-login';
11997
- if ((verificationMode === 'verify-then-auto-login' || verificationMode === 'immediate') && response.token) {
11998
- // Auto-login modes: Log the user in immediately if token is provided
11999
- auth.login(response.token, response.user, response.accountData);
12000
- setAuthSuccess(true);
12001
- setSuccessMessage('Email verified successfully! You are now logged in.');
12002
- onAuthSuccess(response.token, response.user, response.accountData);
12003
- // Clear the URL parameters
12004
- const cleanUrl = window.location.href.split('?')[0];
12005
- window.history.replaceState({}, document.title, cleanUrl);
12006
- // Redirect after a brief delay to show success message
12007
- if (redirectUrl) {
12008
- setTimeout(() => {
12009
- window.location.href = redirectUrl;
12010
- }, 2000);
12011
- }
12012
- }
12013
- else {
12014
- // verify-then-manual-login mode or no token: Show success but require manual login
12015
- setAuthSuccess(true);
12016
- setSuccessMessage('Email verified successfully! Please log in with your credentials.');
12017
- // Clear the URL parameters
12018
- const cleanUrl = window.location.href.split('?')[0];
12019
- window.history.replaceState({}, document.title, cleanUrl);
12020
- // Switch back to login mode after a delay
12021
- setTimeout(() => {
12022
- setAuthSuccess(false);
12023
- setMode('login');
12024
- }, 3000);
12025
- }
12026
- }
12027
- else if (urlMode === 'resetPassword') {
12028
- console.log('Verifying reset token:', token);
12029
- // Verify token is valid, then show password reset form
12030
- await api.verifyResetToken(token);
12031
- setResetToken(token); // Store token for use in password reset
12032
- setMode('reset-password');
12033
- // Clear the URL parameters
12034
- const cleanUrl = window.location.href.split('?')[0];
12035
- window.history.replaceState({}, document.title, cleanUrl);
12036
- }
12037
- else if (urlMode === 'magicLink') {
12038
- console.log('Verifying magic link token:', token);
12039
- const response = await api.verifyMagicLink(token);
12040
- // Auto-login with magic link if token is provided
12041
- if (response.token) {
12042
- auth.login(response.token, response.user, response.accountData);
12043
- setAuthSuccess(true);
12044
- setSuccessMessage('Magic link verified! You are now logged in.');
12045
- onAuthSuccess(response.token, response.user, response.accountData);
12046
- // Clear the URL parameters
12047
- const cleanUrl = window.location.href.split('?')[0];
12048
- window.history.replaceState({}, document.title, cleanUrl);
12049
- // Redirect after a brief delay to show success message
12050
- if (redirectUrl) {
12051
- setTimeout(() => {
12052
- window.location.href = redirectUrl;
12053
- }, 2000);
12054
- }
12055
- }
12056
- else {
12057
- throw new Error('Authentication failed - no token received');
12058
- }
12059
- }
12146
+ // TODO: Backend implementation required
12147
+ // Endpoint: GET /api/v1/authkit/:clientId/account/profile
12148
+ // SDK method: smartlinks.authKit.getProfile(clientId)
12149
+ // Temporary mock data for UI testing
12150
+ const profileData = {
12151
+ uid: auth.user?.uid || '',
12152
+ email: auth.user?.email,
12153
+ displayName: auth.user?.displayName,
12154
+ phoneNumber: auth.user?.phoneNumber,
12155
+ photoURL: auth.user?.photoURL,
12156
+ emailVerified: true,
12157
+ accountData: auth.accountData || {},
12158
+ };
12159
+ setProfile(profileData);
12160
+ setDisplayName(profileData.displayName || '');
12060
12161
  }
12061
12162
  catch (err) {
12062
- console.error('URL-based auth error:', err);
12063
- const errorMessage = err instanceof Error ? err.message : 'An error occurred';
12064
- // If it's an email verification error (expired/invalid token), show resend option
12065
- if (urlMode === 'verifyEmail') {
12066
- setError(`${errorMessage} - Please enter your email below to receive a new verification link.`);
12067
- setShowResendVerification(true);
12068
- setMode('login'); // Show the login form UI
12069
- // Clear the URL parameters
12070
- const cleanUrl = window.location.href.split('?')[0];
12071
- window.history.replaceState({}, document.title, cleanUrl);
12072
- }
12073
- else if (urlMode === 'resetPassword') {
12074
- // If password reset token is invalid/expired, show request new reset link option
12075
- setError(`${errorMessage} - Please enter your email below to receive a new password reset link.`);
12076
- setShowRequestNewReset(true);
12077
- setMode('login');
12078
- // Clear the URL parameters
12079
- const cleanUrl = window.location.href.split('?')[0];
12080
- window.history.replaceState({}, document.title, cleanUrl);
12081
- }
12082
- else if (urlMode === 'magicLink') {
12083
- // If magic link is invalid/expired
12084
- setError(`${errorMessage} - Please request a new magic link below.`);
12085
- setMode('magic-link');
12086
- // Clear the URL parameters
12087
- const cleanUrl = window.location.href.split('?')[0];
12088
- window.history.replaceState({}, document.title, cleanUrl);
12089
- }
12090
- else {
12091
- setError(errorMessage);
12092
- }
12093
- onAuthError?.(err instanceof Error ? err : new Error('An error occurred'));
12163
+ const errorMessage = err instanceof Error ? err.message : 'Failed to load profile';
12164
+ setError(errorMessage);
12165
+ onError?.(err instanceof Error ? err : new Error(errorMessage));
12094
12166
  }
12095
12167
  finally {
12096
12168
  setLoading(false);
12097
12169
  }
12098
12170
  };
12099
- const handleEmailAuth = async (data) => {
12171
+ const handleUpdateProfile = async (e) => {
12172
+ e.preventDefault();
12100
12173
  setLoading(true);
12101
12174
  setError(undefined);
12102
- setAuthSuccess(false);
12175
+ setSuccess(undefined);
12103
12176
  try {
12104
- const response = mode === 'login'
12105
- ? await api.login(data.email, data.password)
12106
- : await api.register({
12107
- ...data,
12108
- accountData: mode === 'register' ? accountData : undefined,
12109
- redirectUrl: getRedirectUrl(), // Include redirect URL for email verification
12110
- });
12111
- // Get email verification mode from response or config (default: verify-then-auto-login)
12112
- const verificationMode = response.emailVerificationMode || config?.emailVerification?.mode || 'verify-then-auto-login';
12113
- const gracePeriodHours = config?.emailVerification?.gracePeriodHours || 24;
12114
- if (mode === 'register') {
12115
- // Handle different verification modes
12116
- if (verificationMode === 'immediate' && response.token) {
12117
- // Immediate mode: Log in right away if token is provided
12118
- auth.login(response.token, response.user, response.accountData);
12119
- setAuthSuccess(true);
12120
- const deadline = response.emailVerificationDeadline
12121
- ? new Date(response.emailVerificationDeadline).toLocaleString()
12122
- : `${gracePeriodHours} hours`;
12123
- setSuccessMessage(`Account created! You're logged in now. Please verify your email by ${deadline} to keep your account active.`);
12124
- if (response.token) {
12125
- onAuthSuccess(response.token, response.user, response.accountData);
12126
- }
12127
- if (redirectUrl) {
12128
- setTimeout(() => {
12129
- window.location.href = redirectUrl;
12130
- }, 2000);
12131
- }
12132
- }
12133
- else if (verificationMode === 'verify-then-auto-login') {
12134
- // Verify-then-auto-login mode: Don't log in yet, but will auto-login after email verification
12135
- setAuthSuccess(true);
12136
- setSuccessMessage('Account created! Please check your email and click the verification link to complete your registration.');
12137
- }
12138
- else {
12139
- // verify-then-manual-login mode: Traditional flow
12140
- setAuthSuccess(true);
12141
- setSuccessMessage('Account created successfully! Please check your email to verify your account, then log in.');
12142
- }
12143
- }
12144
- else {
12145
- // Login mode - always log in if token is provided
12146
- if (response.token) {
12147
- // Check for account lock or verification requirements
12148
- if (response.accountLocked) {
12149
- throw new Error('Your account has been locked due to unverified email. Please check your email or request a new verification link.');
12150
- }
12151
- if (response.requiresEmailVerification) {
12152
- throw new Error('Please verify your email before logging in. Check your inbox for the verification link.');
12153
- }
12154
- auth.login(response.token, response.user, response.accountData);
12155
- setAuthSuccess(true);
12156
- setSuccessMessage('Login successful!');
12157
- onAuthSuccess(response.token, response.user, response.accountData);
12158
- if (redirectUrl) {
12159
- setTimeout(() => {
12160
- window.location.href = redirectUrl;
12161
- }, 2000);
12162
- }
12163
- }
12164
- else {
12165
- throw new Error('Authentication failed - please verify your email before logging in.');
12166
- }
12167
- }
12177
+ // TODO: Backend implementation required
12178
+ // Endpoint: POST /api/v1/authkit/:clientId/account/update-profile
12179
+ // SDK method: smartlinks.authKit.updateProfile(clientId, updateData)
12180
+ setError('Backend API not yet implemented. See console for required endpoint.');
12181
+ console.log('Required API endpoint: POST /api/v1/authkit/:clientId/account/update-profile');
12182
+ console.log('Update data:', { displayName });
12183
+ // Uncomment when backend is ready:
12184
+ // const updateData: ProfileUpdateData = {
12185
+ // displayName: displayName || undefined,
12186
+ // photoURL: photoURL || undefined,
12187
+ // };
12188
+ // const updatedProfile = await smartlinks.authKit.updateProfile(clientId, updateData);
12189
+ // setProfile(updatedProfile);
12190
+ // setSuccess('Profile updated successfully!');
12191
+ // setEditingSection(null);
12192
+ // onProfileUpdated?.(updatedProfile);
12168
12193
  }
12169
12194
  catch (err) {
12170
- const errorMessage = err instanceof Error ? err.message : 'Authentication failed';
12171
- // Check if error is about email already registered
12172
- if (mode === 'register' && errorMessage.toLowerCase().includes('already') && errorMessage.toLowerCase().includes('email')) {
12173
- setShowResendVerification(true);
12174
- setResendEmail(data.email);
12175
- setError('This email is already registered. If you didn\'t receive the verification email, you can resend it below.');
12176
- }
12177
- else {
12178
- setError(errorMessage);
12179
- }
12180
- onAuthError?.(err instanceof Error ? err : new Error(errorMessage));
12195
+ const errorMessage = err instanceof Error ? err.message : 'Failed to update profile';
12196
+ setError(errorMessage);
12197
+ onError?.(err instanceof Error ? err : new Error(errorMessage));
12198
+ }
12199
+ finally {
12200
+ setLoading(false);
12201
+ }
12202
+ };
12203
+ const cancelEdit = () => {
12204
+ setEditingSection(null);
12205
+ setDisplayName(profile?.displayName || '');
12206
+ setNewEmail('');
12207
+ setEmailPassword('');
12208
+ setCurrentPassword('');
12209
+ setNewPassword('');
12210
+ setConfirmPassword('');
12211
+ setNewPhone('');
12212
+ setPhoneCode('');
12213
+ setPhoneCodeSent(false);
12214
+ setError(undefined);
12215
+ setSuccess(undefined);
12216
+ };
12217
+ const handleChangeEmail = async (e) => {
12218
+ e.preventDefault();
12219
+ setLoading(true);
12220
+ setError(undefined);
12221
+ setSuccess(undefined);
12222
+ try {
12223
+ // TODO: Backend implementation required
12224
+ // Endpoint: POST /api/v1/authkit/:clientId/account/change-email
12225
+ // SDK method: smartlinks.authKit.changeEmail(clientId, newEmail, password)
12226
+ // Note: No verification flow for now - direct email update
12227
+ setError('Backend API not yet implemented. See console for required endpoint.');
12228
+ console.log('Required API endpoint: POST /api/v1/authkit/:clientId/account/change-email');
12229
+ console.log('Data:', { newEmail });
12230
+ // Uncomment when backend is ready:
12231
+ // await smartlinks.authKit.changeEmail(clientId, newEmail, emailPassword);
12232
+ // setSuccess('Email changed successfully!');
12233
+ // setEditingSection(null);
12234
+ // setNewEmail('');
12235
+ // setEmailPassword('');
12236
+ // onEmailChangeRequested?.();
12237
+ // await loadProfile(); // Reload to show new email
12238
+ }
12239
+ catch (err) {
12240
+ const errorMessage = err instanceof Error ? err.message : 'Failed to change email';
12241
+ setError(errorMessage);
12242
+ onError?.(err instanceof Error ? err : new Error(errorMessage));
12181
12243
  }
12182
12244
  finally {
12183
12245
  setLoading(false);
12184
12246
  }
12185
12247
  };
12186
- const handleResendVerification = async () => {
12187
- if (!resendEmail)
12248
+ const handleChangePassword = async (e) => {
12249
+ e.preventDefault();
12250
+ if (newPassword !== confirmPassword) {
12251
+ setError('New passwords do not match');
12252
+ return;
12253
+ }
12254
+ if (newPassword.length < 6) {
12255
+ setError('Password must be at least 6 characters');
12188
12256
  return;
12257
+ }
12189
12258
  setLoading(true);
12190
12259
  setError(undefined);
12260
+ setSuccess(undefined);
12191
12261
  try {
12192
- // For resend, we need the userId. If we don't have it, we need to handle this differently
12193
- // The backend should ideally handle this case
12194
- await api.resendVerification('unknown', resendEmail, getRedirectUrl());
12195
- setAuthSuccess(true);
12196
- setSuccessMessage('Verification email sent! Please check your inbox.');
12197
- setShowResendVerification(false);
12262
+ // TODO: Backend implementation required
12263
+ // Endpoint: POST /api/v1/authkit/:clientId/account/change-password
12264
+ // SDK method: smartlinks.authKit.changePassword(clientId, currentPassword, newPassword)
12265
+ setError('Backend API not yet implemented. See console for required endpoint.');
12266
+ console.log('Required API endpoint: POST /api/v1/authkit/:clientId/account/change-password');
12267
+ console.log('Data: currentPassword and newPassword provided');
12268
+ // Uncomment when backend is ready:
12269
+ // await smartlinks.authKit.changePassword(clientId, currentPassword, newPassword);
12270
+ // setSuccess('Password changed successfully!');
12271
+ // setEditingSection(null);
12272
+ // setCurrentPassword('');
12273
+ // setNewPassword('');
12274
+ // setConfirmPassword('');
12275
+ // onPasswordChanged?.();
12198
12276
  }
12199
12277
  catch (err) {
12200
- const errorMessage = err instanceof Error ? err.message : 'Failed to resend verification email';
12278
+ const errorMessage = err instanceof Error ? err.message : 'Failed to change password';
12201
12279
  setError(errorMessage);
12202
- onAuthError?.(err instanceof Error ? err : new Error(errorMessage));
12280
+ onError?.(err instanceof Error ? err : new Error(errorMessage));
12203
12281
  }
12204
12282
  finally {
12205
12283
  setLoading(false);
12206
12284
  }
12207
12285
  };
12208
- const handleRequestNewReset = async () => {
12209
- if (!resetRequestEmail)
12210
- return;
12286
+ const handleSendPhoneCode = async () => {
12211
12287
  setLoading(true);
12212
12288
  setError(undefined);
12213
12289
  try {
12214
- await api.requestPasswordReset(resetRequestEmail, getRedirectUrl());
12215
- setAuthSuccess(true);
12216
- setSuccessMessage('Password reset email sent! Please check your inbox.');
12217
- setShowRequestNewReset(false);
12218
- setResetRequestEmail('');
12290
+ await smartlinks__namespace.authKit.sendPhoneCode(clientId, newPhone);
12291
+ setPhoneCodeSent(true);
12292
+ setSuccess('Verification code sent to your phone');
12219
12293
  }
12220
12294
  catch (err) {
12221
- const errorMessage = err instanceof Error ? err.message : 'Failed to send password reset email';
12295
+ const errorMessage = err instanceof Error ? err.message : 'Failed to send verification code';
12222
12296
  setError(errorMessage);
12223
- onAuthError?.(err instanceof Error ? err : new Error(errorMessage));
12297
+ onError?.(err instanceof Error ? err : new Error(errorMessage));
12224
12298
  }
12225
12299
  finally {
12226
12300
  setLoading(false);
12227
12301
  }
12228
12302
  };
12229
- const handleGoogleLogin = async () => {
12230
- // Use custom client ID from config, or fall back to default Smartlinks client ID
12231
- const googleClientId = config?.googleClientId || DEFAULT_GOOGLE_CLIENT_ID;
12232
- // Determine OAuth flow: default to 'oneTap' for better UX, but allow 'popup' for iframe compatibility
12233
- const oauthFlow = config?.googleOAuthFlow || 'oneTap';
12303
+ const handleUpdatePhone = async (e) => {
12304
+ e.preventDefault();
12234
12305
  setLoading(true);
12235
12306
  setError(undefined);
12307
+ setSuccess(undefined);
12236
12308
  try {
12237
- const google = window.google;
12238
- if (!google) {
12239
- throw new Error('Google Identity Services not loaded. Please check your internet connection.');
12240
- }
12241
- if (oauthFlow === 'popup') {
12242
- // Use OAuth2 popup flow (works in iframes but requires popup permission)
12243
- if (!google.accounts.oauth2) {
12244
- throw new Error('Google OAuth2 not available');
12245
- }
12246
- const client = google.accounts.oauth2.initTokenClient({
12247
- client_id: googleClientId,
12248
- scope: 'openid email profile',
12249
- callback: async (response) => {
12250
- try {
12251
- if (response.error) {
12252
- throw new Error(response.error_description || response.error);
12253
- }
12254
- const accessToken = response.access_token;
12255
- // Send access token to backend
12256
- const authResponse = await api.loginWithGoogle(accessToken);
12257
- if (authResponse.token) {
12258
- auth.login(authResponse.token, authResponse.user, authResponse.accountData);
12259
- setAuthSuccess(true);
12260
- setSuccessMessage('Google login successful!');
12261
- onAuthSuccess(authResponse.token, authResponse.user, authResponse.accountData);
12262
- }
12263
- else {
12264
- throw new Error('Authentication failed - no token received');
12265
- }
12266
- if (redirectUrl) {
12267
- setTimeout(() => {
12268
- window.location.href = redirectUrl;
12269
- }, 2000);
12270
- }
12271
- setLoading(false);
12272
- }
12273
- catch (err) {
12274
- const errorMessage = err instanceof Error ? err.message : 'Google login failed';
12275
- setError(errorMessage);
12276
- onAuthError?.(err instanceof Error ? err : new Error(errorMessage));
12277
- setLoading(false);
12278
- }
12279
- },
12280
- });
12281
- client.requestAccessToken();
12282
- }
12283
- else {
12284
- // Use One Tap / Sign-In button flow (smoother UX but doesn't work in iframes)
12285
- google.accounts.id.initialize({
12286
- client_id: googleClientId,
12287
- callback: async (response) => {
12288
- try {
12289
- const idToken = response.credential;
12290
- const authResponse = await api.loginWithGoogle(idToken);
12291
- if (authResponse.token) {
12292
- auth.login(authResponse.token, authResponse.user, authResponse.accountData);
12293
- setAuthSuccess(true);
12294
- setSuccessMessage('Google login successful!');
12295
- onAuthSuccess(authResponse.token, authResponse.user, authResponse.accountData);
12296
- }
12297
- else {
12298
- throw new Error('Authentication failed - no token received');
12299
- }
12300
- if (redirectUrl) {
12301
- setTimeout(() => {
12302
- window.location.href = redirectUrl;
12303
- }, 2000);
12304
- }
12305
- setLoading(false);
12306
- }
12307
- catch (err) {
12308
- const errorMessage = err instanceof Error ? err.message : 'Google login failed';
12309
- setError(errorMessage);
12310
- onAuthError?.(err instanceof Error ? err : new Error(errorMessage));
12311
- setLoading(false);
12312
- }
12313
- },
12314
- auto_select: false,
12315
- cancel_on_tap_outside: true,
12316
- });
12317
- google.accounts.id.prompt((notification) => {
12318
- if (notification.isNotDisplayed() || notification.isSkippedMoment()) {
12319
- setLoading(false);
12320
- }
12321
- });
12322
- }
12309
+ // TODO: Backend implementation required
12310
+ // Endpoint: POST /api/v1/authkit/:clientId/account/update-phone
12311
+ // SDK method: smartlinks.authKit.updatePhone(clientId, phoneNumber, verificationCode)
12312
+ setError('Backend API not yet implemented. See console for required endpoint.');
12313
+ console.log('Required API endpoint: POST /api/v1/authkit/:clientId/account/update-phone');
12314
+ console.log('Data:', { phoneNumber: newPhone, code: phoneCode });
12315
+ // Uncomment when backend is ready:
12316
+ // await smartlinks.authKit.updatePhone(clientId, newPhone, phoneCode);
12317
+ // setSuccess('Phone number updated successfully!');
12318
+ // setEditingSection(null);
12319
+ // setNewPhone('');
12320
+ // setPhoneCode('');
12321
+ // setPhoneCodeSent(false);
12322
+ // await loadProfile();
12323
12323
  }
12324
12324
  catch (err) {
12325
- const errorMessage = err instanceof Error ? err.message : 'Google login failed';
12325
+ const errorMessage = err instanceof Error ? err.message : 'Failed to update phone number';
12326
12326
  setError(errorMessage);
12327
- onAuthError?.(err instanceof Error ? err : new Error(errorMessage));
12327
+ onError?.(err instanceof Error ? err : new Error(errorMessage));
12328
+ }
12329
+ finally {
12328
12330
  setLoading(false);
12329
12331
  }
12330
12332
  };
12331
- const handlePhoneAuth = async (phoneNumber, verificationCode) => {
12333
+ const handleDeleteAccount = async () => {
12334
+ if (deleteConfirmText !== 'DELETE') {
12335
+ setError('Please type DELETE to confirm account deletion');
12336
+ return;
12337
+ }
12338
+ if (!deletePassword) {
12339
+ setError('Password is required');
12340
+ return;
12341
+ }
12332
12342
  setLoading(true);
12333
12343
  setError(undefined);
12334
12344
  try {
12335
- if (!verificationCode) {
12336
- // Send verification code via Twilio Verify Service
12337
- await api.sendPhoneCode(phoneNumber);
12338
- // Twilio Verify Service tracks the verification by phone number
12339
- // No need to store verificationId
12340
- }
12341
- else {
12342
- // Verify code - Twilio identifies the verification by phone number
12343
- const response = await api.verifyPhoneCode(phoneNumber, verificationCode);
12344
- // Update auth context with account data if token is provided
12345
- if (response.token) {
12346
- auth.login(response.token, response.user, response.accountData);
12347
- onAuthSuccess(response.token, response.user, response.accountData);
12348
- if (redirectUrl) {
12349
- window.location.href = redirectUrl;
12350
- }
12351
- }
12352
- else {
12353
- throw new Error('Authentication failed - no token received');
12354
- }
12355
- }
12345
+ // TODO: Backend implementation required
12346
+ // Endpoint: DELETE /api/v1/authkit/:clientId/account/delete
12347
+ // SDK method: smartlinks.authKit.deleteAccount(clientId, password, confirmText)
12348
+ // Note: This performs a SOFT DELETE (marks as deleted, obfuscates email)
12349
+ setError('Backend API not yet implemented. See console for required endpoint.');
12350
+ console.log('Required API endpoint: DELETE /api/v1/authkit/:clientId/account/delete');
12351
+ console.log('Data: password and confirmText="DELETE" provided');
12352
+ console.log('Note: Backend should soft delete (mark deleted, obfuscate email, disable account)');
12353
+ // Uncomment when backend is ready:
12354
+ // await smartlinks.authKit.deleteAccount(clientId, deletePassword, deleteConfirmText);
12355
+ // setSuccess('Account deleted successfully');
12356
+ // onAccountDeleted?.();
12357
+ // await auth.logout();
12358
+ }
12359
+ catch (err) {
12360
+ const errorMessage = err instanceof Error ? err.message : 'Failed to delete account';
12361
+ setError(errorMessage);
12362
+ onError?.(err instanceof Error ? err : new Error(errorMessage));
12363
+ }
12364
+ finally {
12365
+ setLoading(false);
12366
+ }
12367
+ };
12368
+ if (!auth.isAuthenticated) {
12369
+ return (jsxRuntime.jsx("div", { className: `account-management ${className}`, children: jsxRuntime.jsx("p", { className: "text-muted-foreground", children: "Please log in to manage your account" }) }));
12370
+ }
12371
+ if (loading && !profile) {
12372
+ return (jsxRuntime.jsx("div", { className: `account-management ${className}`, children: jsxRuntime.jsx("p", { className: "text-muted-foreground", children: "Loading..." }) }));
12373
+ }
12374
+ return (jsxRuntime.jsxs("div", { className: `account-management ${className}`, style: { maxWidth: '600px' }, children: [error && (jsxRuntime.jsx("div", { className: "auth-error", role: "alert", children: error })), success && (jsxRuntime.jsx("div", { className: "auth-success", role: "alert", children: success })), showProfileSection && (jsxRuntime.jsxs("section", { className: "account-section", children: [jsxRuntime.jsxs("div", { className: "account-field", children: [jsxRuntime.jsxs("div", { className: "field-info", children: [jsxRuntime.jsx("label", { className: "field-label", children: "Display Name" }), jsxRuntime.jsx("div", { className: "field-value", children: profile?.displayName || 'Not set' })] }), editingSection !== 'profile' && (jsxRuntime.jsx("button", { type: "button", onClick: () => setEditingSection('profile'), className: "auth-button button-secondary", children: "Change" }))] }), editingSection === 'profile' && (jsxRuntime.jsxs("form", { onSubmit: handleUpdateProfile, className: "edit-form", children: [jsxRuntime.jsx("div", { className: "form-group", children: jsxRuntime.jsx("input", { id: "displayName", type: "text", value: displayName, onChange: (e) => setDisplayName(e.target.value), placeholder: "Your display name", className: "auth-input" }) }), jsxRuntime.jsxs("div", { className: "button-group", children: [jsxRuntime.jsx("button", { type: "submit", className: "auth-button", disabled: loading, children: loading ? 'Saving...' : 'Save' }), jsxRuntime.jsx("button", { type: "button", onClick: cancelEdit, className: "auth-button button-secondary", children: "Cancel" })] })] }))] })), showEmailSection && (jsxRuntime.jsxs("section", { className: "account-section", children: [jsxRuntime.jsxs("div", { className: "account-field", children: [jsxRuntime.jsxs("div", { className: "field-info", children: [jsxRuntime.jsx("label", { className: "field-label", children: "Email Address" }), jsxRuntime.jsxs("div", { className: "field-value", children: [profile?.email || 'Not set', profile?.emailVerified && (jsxRuntime.jsx("span", { className: "verification-badge verified", children: "Verified" })), profile?.email && !profile?.emailVerified && (jsxRuntime.jsx("span", { className: "verification-badge unverified", children: "Unverified" }))] })] }), editingSection !== 'email' && (jsxRuntime.jsx("button", { type: "button", onClick: () => setEditingSection('email'), className: "auth-button button-secondary", children: "Change Email" }))] }), editingSection === 'email' && (jsxRuntime.jsxs("form", { onSubmit: handleChangeEmail, className: "edit-form", children: [jsxRuntime.jsxs("div", { className: "form-group", children: [jsxRuntime.jsx("label", { htmlFor: "newEmail", children: "New Email" }), jsxRuntime.jsx("input", { id: "newEmail", type: "email", value: newEmail, onChange: (e) => setNewEmail(e.target.value), placeholder: "new.email@example.com", className: "auth-input", required: true })] }), jsxRuntime.jsxs("div", { className: "form-group", children: [jsxRuntime.jsx("label", { htmlFor: "emailPassword", children: "Confirm Password" }), jsxRuntime.jsx("input", { id: "emailPassword", type: "password", value: emailPassword, onChange: (e) => setEmailPassword(e.target.value), placeholder: "Enter your password", className: "auth-input", required: true })] }), jsxRuntime.jsxs("div", { className: "button-group", children: [jsxRuntime.jsx("button", { type: "submit", className: "auth-button", disabled: loading, children: loading ? 'Changing...' : 'Change Email' }), jsxRuntime.jsx("button", { type: "button", onClick: cancelEdit, className: "auth-button button-secondary", children: "Cancel" })] })] }))] })), showPasswordSection && (jsxRuntime.jsxs("section", { className: "account-section", children: [jsxRuntime.jsxs("div", { className: "account-field", children: [jsxRuntime.jsxs("div", { className: "field-info", children: [jsxRuntime.jsx("label", { className: "field-label", children: "Password" }), jsxRuntime.jsx("div", { className: "field-value", children: "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022" })] }), editingSection !== 'password' && (jsxRuntime.jsx("button", { type: "button", onClick: () => setEditingSection('password'), className: "auth-button button-secondary", children: "Change Password" }))] }), editingSection === 'password' && (jsxRuntime.jsxs("form", { onSubmit: handleChangePassword, className: "edit-form", children: [jsxRuntime.jsxs("div", { className: "form-group", children: [jsxRuntime.jsx("label", { htmlFor: "currentPassword", children: "Current Password" }), jsxRuntime.jsx("input", { id: "currentPassword", type: "password", value: currentPassword, onChange: (e) => setCurrentPassword(e.target.value), placeholder: "Enter current password", className: "auth-input", required: true })] }), jsxRuntime.jsxs("div", { className: "form-group", children: [jsxRuntime.jsx("label", { htmlFor: "newPassword", children: "New Password" }), jsxRuntime.jsx("input", { id: "newPassword", type: "password", value: newPassword, onChange: (e) => setNewPassword(e.target.value), placeholder: "Enter new password", className: "auth-input", required: true, minLength: 6 })] }), jsxRuntime.jsxs("div", { className: "form-group", children: [jsxRuntime.jsx("label", { htmlFor: "confirmPassword", children: "Confirm New Password" }), jsxRuntime.jsx("input", { id: "confirmPassword", type: "password", value: confirmPassword, onChange: (e) => setConfirmPassword(e.target.value), placeholder: "Confirm new password", className: "auth-input", required: true, minLength: 6 })] }), jsxRuntime.jsxs("div", { className: "button-group", children: [jsxRuntime.jsx("button", { type: "submit", className: "auth-button", disabled: loading, children: loading ? 'Changing...' : 'Change Password' }), jsxRuntime.jsx("button", { type: "button", onClick: cancelEdit, className: "auth-button button-secondary", children: "Cancel" })] })] }))] })), showPhoneSection && (jsxRuntime.jsxs("section", { className: "account-section", children: [jsxRuntime.jsxs("div", { className: "account-field", children: [jsxRuntime.jsxs("div", { className: "field-info", children: [jsxRuntime.jsx("label", { className: "field-label", children: "Phone Number" }), jsxRuntime.jsx("div", { className: "field-value", children: profile?.phoneNumber || 'Not set' })] }), editingSection !== 'phone' && (jsxRuntime.jsx("button", { type: "button", onClick: () => setEditingSection('phone'), className: "auth-button button-secondary", children: "Change Phone" }))] }), editingSection === 'phone' && (jsxRuntime.jsxs("form", { onSubmit: handleUpdatePhone, className: "edit-form", children: [jsxRuntime.jsxs("div", { className: "form-group", children: [jsxRuntime.jsx("label", { htmlFor: "newPhone", children: "New Phone Number" }), jsxRuntime.jsx("input", { id: "newPhone", type: "tel", value: newPhone, onChange: (e) => setNewPhone(e.target.value), placeholder: "+1234567890", className: "auth-input", required: true })] }), !phoneCodeSent ? (jsxRuntime.jsxs("div", { className: "button-group", children: [jsxRuntime.jsx("button", { type: "button", onClick: handleSendPhoneCode, className: "auth-button", disabled: loading || !newPhone, children: loading ? 'Sending...' : 'Send Code' }), jsxRuntime.jsx("button", { type: "button", onClick: cancelEdit, className: "auth-button button-secondary", children: "Cancel" })] })) : (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsxs("div", { className: "form-group", children: [jsxRuntime.jsx("label", { htmlFor: "phoneCode", children: "Verification Code" }), jsxRuntime.jsx("input", { id: "phoneCode", type: "text", value: phoneCode, onChange: (e) => setPhoneCode(e.target.value), placeholder: "Enter 6-digit code", className: "auth-input", required: true, maxLength: 6 })] }), jsxRuntime.jsxs("div", { className: "button-group", children: [jsxRuntime.jsx("button", { type: "submit", className: "auth-button", disabled: loading, children: loading ? 'Verifying...' : 'Verify & Save' }), jsxRuntime.jsx("button", { type: "button", onClick: cancelEdit, className: "auth-button button-secondary", children: "Cancel" })] })] }))] }))] })), showDeleteAccount && (jsxRuntime.jsxs("section", { className: "account-section danger-zone", children: [jsxRuntime.jsx("h3", { className: "section-title text-danger", children: "Danger Zone" }), !showDeleteConfirm ? (jsxRuntime.jsx("button", { type: "button", onClick: () => setShowDeleteConfirm(true), className: "auth-button button-danger", children: "Delete Account" })) : (jsxRuntime.jsxs("div", { className: "delete-confirm", children: [jsxRuntime.jsx("p", { className: "warning-text", children: "\u26A0\uFE0F This action cannot be undone. This will permanently delete your account and all associated data." }), jsxRuntime.jsxs("div", { className: "form-group", children: [jsxRuntime.jsx("label", { htmlFor: "deletePassword", children: "Confirm Password" }), jsxRuntime.jsx("input", { id: "deletePassword", type: "password", value: deletePassword, onChange: (e) => setDeletePassword(e.target.value), placeholder: "Enter your password", className: "auth-input" })] }), jsxRuntime.jsxs("div", { className: "form-group", children: [jsxRuntime.jsx("label", { htmlFor: "deleteConfirm", children: "Type DELETE to confirm" }), jsxRuntime.jsx("input", { id: "deleteConfirm", type: "text", value: deleteConfirmText, onChange: (e) => setDeleteConfirmText(e.target.value), placeholder: "DELETE", className: "auth-input" })] }), jsxRuntime.jsxs("div", { className: "button-group", children: [jsxRuntime.jsx("button", { type: "button", onClick: handleDeleteAccount, className: "auth-button button-danger", disabled: loading, children: loading ? 'Deleting...' : 'Permanently Delete Account' }), jsxRuntime.jsx("button", { type: "button", onClick: () => {
12375
+ setShowDeleteConfirm(false);
12376
+ setDeletePassword('');
12377
+ setDeleteConfirmText('');
12378
+ }, className: "auth-button button-secondary", children: "Cancel" })] })] }))] }))] }));
12379
+ };
12380
+
12381
+ const SmartlinksClaimUI = ({ apiEndpoint, clientId, clientName, collectionId, productId, proofId, onClaimSuccess, onClaimError, additionalFields = [], theme = 'light', className = '', minimal = false, customization = {}, }) => {
12382
+ const auth = useAuth();
12383
+ const [claimStep, setClaimStep] = React.useState(auth.isAuthenticated ? 'questions' : 'auth');
12384
+ const [claimData, setClaimData] = React.useState({});
12385
+ const [error, setError] = React.useState();
12386
+ const [loading, setLoading] = React.useState(false);
12387
+ const handleAuthSuccess = (token, user, accountData) => {
12388
+ // Authentication successful
12389
+ auth.login(token, user, accountData);
12390
+ // If no additional questions, proceed directly to claim
12391
+ if (additionalFields.length === 0) {
12392
+ executeClaim(user);
12356
12393
  }
12357
- catch (err) {
12358
- const errorMessage = err instanceof Error ? err.message : 'Phone authentication failed';
12359
- setError(errorMessage);
12360
- onAuthError?.(err instanceof Error ? err : new Error(errorMessage));
12394
+ else {
12395
+ setClaimStep('questions');
12361
12396
  }
12362
- finally {
12363
- setLoading(false);
12397
+ };
12398
+ const handleQuestionSubmit = async (e) => {
12399
+ e.preventDefault();
12400
+ // Validate required fields
12401
+ const missingFields = additionalFields
12402
+ .filter(field => field.required && !claimData[field.name])
12403
+ .map(field => field.label);
12404
+ if (missingFields.length > 0) {
12405
+ setError(`Please fill in: ${missingFields.join(', ')}`);
12406
+ return;
12407
+ }
12408
+ // Execute claim with collected data
12409
+ if (auth.user) {
12410
+ executeClaim(auth.user);
12364
12411
  }
12365
12412
  };
12366
- const handlePasswordReset = async (emailOrPassword, confirmPassword) => {
12413
+ const executeClaim = async (user) => {
12414
+ setClaimStep('claiming');
12367
12415
  setLoading(true);
12368
12416
  setError(undefined);
12369
12417
  try {
12370
- if (resetToken && confirmPassword) {
12371
- // Complete password reset with token
12372
- await api.completePasswordReset(resetToken, emailOrPassword);
12373
- setResetSuccess(true);
12374
- setResetToken(undefined); // Clear token after successful reset
12375
- }
12376
- else {
12377
- // Request password reset email
12378
- await api.requestPasswordReset(emailOrPassword, getRedirectUrl());
12379
- setResetSuccess(true);
12380
- }
12418
+ // Create attestation to claim the proof
12419
+ const response = await smartlinks__namespace.attestation.create(collectionId, productId, proofId, {
12420
+ public: {
12421
+ claimed: true,
12422
+ claimedAt: new Date().toISOString(),
12423
+ claimedBy: user.uid,
12424
+ ...claimData,
12425
+ },
12426
+ private: {},
12427
+ proof: {},
12428
+ });
12429
+ setClaimStep('success');
12430
+ // Call success callback
12431
+ onClaimSuccess({
12432
+ proofId,
12433
+ user,
12434
+ claimData,
12435
+ attestationId: response.id,
12436
+ });
12381
12437
  }
12382
12438
  catch (err) {
12383
- const errorMessage = err instanceof Error ? err.message : 'Password reset failed';
12439
+ console.error('Claim error:', err);
12440
+ const errorMessage = err instanceof Error ? err.message : 'Failed to claim proof';
12384
12441
  setError(errorMessage);
12385
- onAuthError?.(err instanceof Error ? err : new Error(errorMessage));
12442
+ onClaimError?.(err instanceof Error ? err : new Error(errorMessage));
12443
+ setClaimStep(additionalFields.length > 0 ? 'questions' : 'auth');
12386
12444
  }
12387
12445
  finally {
12388
12446
  setLoading(false);
12389
12447
  }
12390
12448
  };
12391
- const handleMagicLink = async (email) => {
12392
- setLoading(true);
12393
- setError(undefined);
12394
- try {
12395
- await api.sendMagicLink(email, getRedirectUrl());
12396
- setAuthSuccess(true);
12397
- setSuccessMessage('Magic link sent! Check your email to log in.');
12449
+ const handleFieldChange = (fieldName, value) => {
12450
+ setClaimData(prev => ({
12451
+ ...prev,
12452
+ [fieldName]: value,
12453
+ }));
12454
+ };
12455
+ // Render authentication step
12456
+ if (claimStep === 'auth') {
12457
+ return (jsxRuntime.jsx("div", { className: className, children: jsxRuntime.jsx(SmartlinksAuthUI, { apiEndpoint: apiEndpoint, clientId: clientId, clientName: clientName, onAuthSuccess: handleAuthSuccess, onAuthError: onClaimError, theme: theme, minimal: minimal, customization: customization.authConfig }) }));
12458
+ }
12459
+ // Render additional questions step
12460
+ if (claimStep === 'questions') {
12461
+ return (jsxRuntime.jsxs("div", { className: `claim-questions ${className}`, children: [jsxRuntime.jsxs("div", { className: "claim-header mb-6", children: [jsxRuntime.jsx("h2", { className: "text-2xl font-bold mb-2", children: customization.claimTitle || 'Complete Your Claim' }), customization.claimDescription && (jsxRuntime.jsx("p", { className: "text-muted-foreground", children: customization.claimDescription }))] }), error && (jsxRuntime.jsx("div", { className: "claim-error bg-destructive/10 text-destructive px-4 py-3 rounded-md mb-4", children: error })), jsxRuntime.jsxs("form", { onSubmit: handleQuestionSubmit, className: "claim-form space-y-4", children: [additionalFields.map((field) => (jsxRuntime.jsxs("div", { className: "claim-field", children: [jsxRuntime.jsxs("label", { htmlFor: field.name, className: "block text-sm font-medium mb-2", children: [field.label, field.required && jsxRuntime.jsx("span", { className: "text-destructive ml-1", children: "*" })] }), field.type === 'textarea' ? (jsxRuntime.jsx("textarea", { id: field.name, name: field.name, placeholder: field.placeholder, value: claimData[field.name] || '', onChange: (e) => handleFieldChange(field.name, e.target.value), required: field.required, className: "w-full px-3 py-2 border border-input rounded-md bg-background", rows: 4 })) : field.type === 'select' ? (jsxRuntime.jsxs("select", { id: field.name, name: field.name, value: claimData[field.name] || '', onChange: (e) => handleFieldChange(field.name, e.target.value), required: field.required, className: "w-full px-3 py-2 border border-input rounded-md bg-background", children: [jsxRuntime.jsx("option", { value: "", children: "Select..." }), field.options?.map((option) => (jsxRuntime.jsx("option", { value: option, children: option }, option)))] })) : (jsxRuntime.jsx("input", { id: field.name, name: field.name, type: field.type, placeholder: field.placeholder, value: claimData[field.name] || '', onChange: (e) => handleFieldChange(field.name, e.target.value), required: field.required, className: "w-full px-3 py-2 border border-input rounded-md bg-background" }))] }, field.name))), jsxRuntime.jsx("button", { type: "submit", disabled: loading, className: "claim-submit-button w-full bg-primary text-primary-foreground px-4 py-2 rounded-md font-medium hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed", children: loading ? 'Claiming...' : 'Submit Claim' })] })] }));
12462
+ }
12463
+ // Render claiming step (loading state)
12464
+ if (claimStep === 'claiming') {
12465
+ return (jsxRuntime.jsxs("div", { className: `claim-loading ${className} flex flex-col items-center justify-center py-12`, children: [jsxRuntime.jsx("div", { className: "claim-spinner w-12 h-12 border-4 border-primary border-t-transparent rounded-full animate-spin mb-4" }), jsxRuntime.jsx("p", { className: "text-muted-foreground", children: "Claiming your product..." })] }));
12466
+ }
12467
+ // Render success step
12468
+ if (claimStep === 'success') {
12469
+ return (jsxRuntime.jsxs("div", { className: `claim-success ${className} text-center py-12`, children: [jsxRuntime.jsx("div", { className: "claim-success-icon w-16 h-16 bg-green-500 text-white rounded-full flex items-center justify-center text-3xl font-bold mx-auto mb-4", children: "\u2713" }), jsxRuntime.jsx("h2", { className: "text-2xl font-bold mb-2", children: "Claim Successful!" }), jsxRuntime.jsx("p", { className: "text-muted-foreground", children: customization.successMessage || 'Your product has been successfully claimed and registered to your account.' })] }));
12470
+ }
12471
+ return null;
12472
+ };
12473
+
12474
+ const ProtectedRoute = ({ children, fallback, redirectTo, }) => {
12475
+ const { isAuthenticated, isLoading } = useAuth();
12476
+ // Show loading state
12477
+ if (isLoading) {
12478
+ return jsxRuntime.jsx("div", { children: "Loading..." });
12479
+ }
12480
+ // If not authenticated, redirect or show fallback
12481
+ if (!isAuthenticated) {
12482
+ if (redirectTo) {
12483
+ window.location.href = redirectTo;
12484
+ return null;
12398
12485
  }
12399
- catch (err) {
12400
- const errorMessage = err instanceof Error ? err.message : 'Failed to send magic link';
12401
- setError(errorMessage);
12402
- onAuthError?.(err instanceof Error ? err : new Error(errorMessage));
12486
+ return fallback ? jsxRuntime.jsx(jsxRuntime.Fragment, { children: fallback }) : jsxRuntime.jsx("div", { children: "Access denied. Please log in." });
12487
+ }
12488
+ // Render protected content
12489
+ return jsxRuntime.jsx(jsxRuntime.Fragment, { children: children });
12490
+ };
12491
+
12492
+ const AuthUIPreview = ({ customization, enabledProviders = ['email', 'google', 'phone'], providerOrder, emailDisplayMode = 'form', theme = 'light', className, minimal = false, }) => {
12493
+ const showEmail = enabledProviders.includes('email');
12494
+ const showGoogle = enabledProviders.includes('google');
12495
+ const showPhone = enabledProviders.includes('phone');
12496
+ const showMagicLink = enabledProviders.includes('magic-link');
12497
+ // Determine ordered providers (excluding email if in button mode)
12498
+ const orderedProviders = providerOrder && providerOrder.length > 0
12499
+ ? providerOrder.filter(p => enabledProviders.includes(p) && p !== 'email')
12500
+ : enabledProviders.filter(p => p !== 'email');
12501
+ const hasOtherProviders = showGoogle || showPhone || showMagicLink;
12502
+ // Render provider button helper
12503
+ const renderProviderButton = (provider) => {
12504
+ if (provider === 'google' && showGoogle) {
12505
+ return (jsxRuntime.jsxs("button", { className: "auth-provider-button", disabled: true, children: [jsxRuntime.jsxs("svg", { width: "18", height: "18", viewBox: "0 0 18 18", fill: "none", children: [jsxRuntime.jsx("path", { d: "M17.64 9.2c0-.637-.057-1.251-.164-1.84H9v3.481h4.844c-.209 1.125-.843 2.078-1.796 2.717v2.258h2.908c1.702-1.567 2.684-3.874 2.684-6.615z", fill: "#4285F4" }), jsxRuntime.jsx("path", { d: "M9 18c2.43 0 4.467-.806 5.956-2.183l-2.908-2.259c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332C2.438 15.983 5.482 18 9 18z", fill: "#34A853" }), jsxRuntime.jsx("path", { d: "M3.964 10.707c-.18-.54-.282-1.117-.282-1.707 0-.593.102-1.167.282-1.707V4.961H.957C.347 6.175 0 7.548 0 9s.348 2.825.957 4.039l3.007-2.332z", fill: "#FBBC05" }), jsxRuntime.jsx("path", { d: "M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0 5.482 0 2.438 2.017.957 4.958L3.964 7.29C4.672 5.163 6.656 3.58 9 3.58z", fill: "#EA4335" })] }), jsxRuntime.jsx("span", { children: "Continue with Google" })] }, "google"));
12403
12506
  }
12404
- finally {
12405
- setLoading(false);
12507
+ if (provider === 'phone' && showPhone) {
12508
+ return (jsxRuntime.jsxs("button", { className: "auth-provider-button", disabled: true, children: [jsxRuntime.jsx("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", children: jsxRuntime.jsx("path", { d: "M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z" }) }), jsxRuntime.jsx("span", { children: "Continue with Phone" })] }, "phone"));
12509
+ }
12510
+ if (provider === 'magic-link' && showMagicLink) {
12511
+ return (jsxRuntime.jsxs("button", { className: "auth-provider-button", disabled: true, children: [jsxRuntime.jsx("svg", { width: "18", height: "18", viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", children: jsxRuntime.jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" }) }), jsxRuntime.jsx("span", { children: "Continue with Magic Link" })] }, "magic-link"));
12406
12512
  }
12513
+ if (provider === 'email' && showEmail && emailDisplayMode === 'button') {
12514
+ return (jsxRuntime.jsxs("button", { className: "auth-provider-button", disabled: true, children: [jsxRuntime.jsx("svg", { width: "18", height: "18", viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", children: jsxRuntime.jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" }) }), jsxRuntime.jsx("span", { children: "Continue with Email" })] }, "email"));
12515
+ }
12516
+ return null;
12407
12517
  };
12408
- if (configLoading) {
12409
- return (jsxRuntime.jsx(AuthContainer, { theme: theme, className: className, minimal: minimal || config?.branding?.minimal || false, children: jsxRuntime.jsx("div", { style: { textAlign: 'center', padding: '2rem' }, children: jsxRuntime.jsx("div", { className: "auth-spinner" }) }) }));
12410
- }
12411
- return (jsxRuntime.jsx(AuthContainer, { theme: theme, className: className, config: config, minimal: minimal || config?.branding?.minimal || false, children: authSuccess ? (jsxRuntime.jsxs("div", { style: { textAlign: 'center', padding: '2rem' }, children: [jsxRuntime.jsx("div", { style: {
12412
- color: 'var(--auth-primary-color, #4F46E5)',
12413
- fontSize: '3rem',
12414
- marginBottom: '1rem'
12415
- }, children: "\u2713" }), jsxRuntime.jsx("h2", { style: {
12416
- marginBottom: '0.5rem',
12417
- fontSize: '1.5rem',
12418
- fontWeight: 600
12419
- }, children: successMessage?.includes('verified') ? 'Email Verified!' :
12420
- successMessage?.includes('Magic link') ? 'Check Your Email!' :
12421
- mode === 'register' ? 'Account Created!' : 'Login Successful!' }), jsxRuntime.jsx("p", { style: {
12422
- color: '#6B7280',
12423
- fontSize: '0.875rem'
12424
- }, children: successMessage })] })) : mode === 'magic-link' ? (jsxRuntime.jsx(MagicLinkForm, { onSubmit: handleMagicLink, onCancel: () => setMode('login'), loading: loading, error: error })) : mode === 'phone' ? (jsxRuntime.jsx(PhoneAuthForm, { onSubmit: handlePhoneAuth, onBack: () => setMode('login'), loading: loading, error: error })) : mode === 'reset-password' ? (jsxRuntime.jsx(PasswordResetForm, { onSubmit: handlePasswordReset, onBack: () => {
12425
- setMode('login');
12426
- setResetSuccess(false);
12427
- setResetToken(undefined); // Clear token when going back
12428
- }, loading: loading, error: error, success: resetSuccess, token: resetToken })) : (mode === 'login' || mode === 'register') ? (jsxRuntime.jsx(jsxRuntime.Fragment, { children: showResendVerification ? (jsxRuntime.jsxs("div", { style: { marginTop: '1rem', padding: '1.5rem', backgroundColor: 'rgba(79, 70, 229, 0.05)', borderRadius: '0.5rem' }, children: [jsxRuntime.jsx("h3", { style: { marginBottom: '0.75rem', fontSize: '1rem', fontWeight: 600, color: 'var(--auth-text-color, #374151)' }, children: "Verification Link Expired" }), jsxRuntime.jsx("p", { style: { marginBottom: '1rem', fontSize: '0.875rem', color: 'var(--auth-text-color, #6B7280)', lineHeight: '1.5' }, children: "Your verification link has expired or is no longer valid. Please enter your email address below and we'll send you a new verification link." }), jsxRuntime.jsx("input", { type: "email", value: resendEmail || '', onChange: (e) => setResendEmail(e.target.value), placeholder: "your@email.com", style: {
12429
- width: '100%',
12430
- padding: '0.625rem',
12431
- marginBottom: '1rem',
12432
- border: '1px solid var(--auth-border-color, #D1D5DB)',
12433
- borderRadius: '0.375rem',
12434
- fontSize: '0.875rem',
12435
- boxSizing: 'border-box'
12436
- } }), jsxRuntime.jsxs("div", { style: { display: 'flex', gap: '0.75rem' }, children: [jsxRuntime.jsx("button", { onClick: handleResendVerification, disabled: loading || !resendEmail, style: {
12437
- flex: 1,
12438
- padding: '0.625rem 1rem',
12439
- backgroundColor: 'var(--auth-primary-color, #4F46E5)',
12440
- color: 'white',
12441
- border: 'none',
12442
- borderRadius: '0.375rem',
12443
- cursor: (loading || !resendEmail) ? 'not-allowed' : 'pointer',
12444
- fontSize: '0.875rem',
12445
- fontWeight: 500,
12446
- opacity: (loading || !resendEmail) ? 0.6 : 1
12447
- }, children: loading ? 'Sending...' : 'Send New Verification Link' }), jsxRuntime.jsx("button", { onClick: () => {
12448
- setShowResendVerification(false);
12449
- setResendEmail('');
12450
- setError(undefined);
12451
- }, disabled: loading, style: {
12452
- padding: '0.625rem 1rem',
12453
- backgroundColor: 'transparent',
12454
- color: 'var(--auth-text-color, #6B7280)',
12455
- border: '1px solid var(--auth-border-color, #D1D5DB)',
12456
- borderRadius: '0.375rem',
12457
- cursor: loading ? 'not-allowed' : 'pointer',
12458
- fontSize: '0.875rem',
12459
- fontWeight: 500,
12460
- opacity: loading ? 0.6 : 1
12461
- }, children: "Cancel" })] })] })) : showRequestNewReset ? (jsxRuntime.jsxs("div", { style: { marginTop: '1rem', padding: '1.5rem', backgroundColor: 'rgba(239, 68, 68, 0.05)', borderRadius: '0.5rem' }, children: [jsxRuntime.jsx("h3", { style: { marginBottom: '0.75rem', fontSize: '1rem', fontWeight: 600, color: 'var(--auth-text-color, #374151)' }, children: "Password Reset Link Expired" }), jsxRuntime.jsx("p", { style: { marginBottom: '1rem', fontSize: '0.875rem', color: 'var(--auth-text-color, #6B7280)', lineHeight: '1.5' }, children: "Your password reset link has expired or is no longer valid. Please enter your email address below and we'll send you a new password reset link." }), jsxRuntime.jsx("input", { type: "email", value: resetRequestEmail || '', onChange: (e) => setResetRequestEmail(e.target.value), placeholder: "your@email.com", style: {
12462
- width: '100%',
12463
- padding: '0.625rem',
12464
- marginBottom: '1rem',
12465
- border: '1px solid var(--auth-border-color, #D1D5DB)',
12466
- borderRadius: '0.375rem',
12467
- fontSize: '0.875rem',
12468
- boxSizing: 'border-box'
12469
- } }), jsxRuntime.jsxs("div", { style: { display: 'flex', gap: '0.75rem' }, children: [jsxRuntime.jsx("button", { onClick: handleRequestNewReset, disabled: loading || !resetRequestEmail, style: {
12470
- flex: 1,
12471
- padding: '0.625rem 1rem',
12472
- backgroundColor: '#EF4444',
12473
- color: 'white',
12474
- border: 'none',
12475
- borderRadius: '0.375rem',
12476
- cursor: (loading || !resetRequestEmail) ? 'not-allowed' : 'pointer',
12477
- fontSize: '0.875rem',
12478
- fontWeight: 500,
12479
- opacity: (loading || !resetRequestEmail) ? 0.6 : 1
12480
- }, children: loading ? 'Sending...' : 'Send New Reset Link' }), jsxRuntime.jsx("button", { onClick: () => {
12481
- setShowRequestNewReset(false);
12482
- setResetRequestEmail('');
12483
- setError(undefined);
12484
- }, disabled: loading, style: {
12485
- padding: '0.625rem 1rem',
12486
- backgroundColor: 'transparent',
12487
- color: 'var(--auth-text-color, #6B7280)',
12488
- border: '1px solid var(--auth-border-color, #D1D5DB)',
12489
- borderRadius: '0.375rem',
12490
- cursor: loading ? 'not-allowed' : 'pointer',
12491
- fontSize: '0.875rem',
12492
- fontWeight: 500,
12493
- opacity: loading ? 0.6 : 1
12494
- }, children: "Cancel" })] })] })) : (jsxRuntime.jsx(jsxRuntime.Fragment, { children: (() => {
12495
- const emailDisplayMode = config?.emailDisplayMode || 'form';
12496
- const providerOrder = config?.providerOrder || (config?.enabledProviders || enabledProviders);
12497
- const actualProviders = config?.enabledProviders || enabledProviders;
12498
- // Button mode: show provider selection first, then email form if email is selected
12499
- if (emailDisplayMode === 'button' && !showEmailForm) {
12500
- return (jsxRuntime.jsx(ProviderButtons, { enabledProviders: actualProviders, providerOrder: providerOrder, onEmailLogin: () => setShowEmailForm(true), onGoogleLogin: handleGoogleLogin, onPhoneLogin: () => setMode('phone'), onMagicLinkLogin: () => setMode('magic-link'), loading: loading }));
12501
- }
12502
- // Form mode or email button was clicked: show email form with other providers
12503
- return (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [emailDisplayMode === 'button' && showEmailForm && (jsxRuntime.jsx("button", { onClick: () => setShowEmailForm(false), style: {
12504
- marginBottom: '1rem',
12505
- padding: '0.5rem',
12506
- background: 'none',
12507
- border: 'none',
12508
- color: 'var(--auth-text-color, #6B7280)',
12509
- cursor: 'pointer',
12510
- fontSize: '0.875rem',
12511
- display: 'flex',
12512
- alignItems: 'center',
12513
- gap: '0.25rem'
12514
- }, children: "\u2190 Back to options" })), jsxRuntime.jsx(EmailAuthForm, { mode: mode, onSubmit: handleEmailAuth, onModeSwitch: () => {
12515
- setMode(mode === 'login' ? 'register' : 'login');
12516
- setShowResendVerification(false);
12517
- setShowRequestNewReset(false);
12518
- setError(undefined);
12519
- }, onForgotPassword: () => setMode('reset-password'), loading: loading, error: error, additionalFields: config?.signupAdditionalFields }), emailDisplayMode === 'form' && actualProviders.length > 1 && (jsxRuntime.jsx(ProviderButtons, { enabledProviders: actualProviders.filter((p) => p !== 'email'), providerOrder: providerOrder, onGoogleLogin: handleGoogleLogin, onPhoneLogin: () => setMode('phone'), onMagicLinkLogin: () => setMode('magic-link'), loading: loading }))] }));
12520
- })() })) })) : null }));
12518
+ return (jsxRuntime.jsx(AuthContainer, { theme: theme, className: className, config: customization, minimal: minimal, children: emailDisplayMode === 'button' ? (jsxRuntime.jsx("div", { className: "auth-provider-buttons", children: orderedProviders.concat(showEmail ? ['email'] : []).map(provider => renderProviderButton(provider)) })) : (
12519
+ /* Form mode: show email form first, then other providers */
12520
+ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [showEmail && (jsxRuntime.jsxs("div", { className: "auth-form", children: [jsxRuntime.jsxs("div", { className: "auth-form-group", children: [jsxRuntime.jsx("label", { className: "auth-label", children: "Email" }), jsxRuntime.jsx("input", { type: "email", className: "auth-input", placeholder: "Enter your email", disabled: true })] }), jsxRuntime.jsxs("div", { className: "auth-form-group", children: [jsxRuntime.jsx("label", { className: "auth-label", children: "Password" }), jsxRuntime.jsx("input", { type: "password", className: "auth-input", placeholder: "Enter your password", disabled: true })] }), jsxRuntime.jsx("button", { className: "auth-button auth-button-primary", disabled: true, children: "Sign In" }), jsxRuntime.jsx("div", { style: { textAlign: 'center', marginTop: '1rem' }, children: jsxRuntime.jsx("button", { className: "auth-link", disabled: true, children: "Forgot password?" }) }), jsxRuntime.jsxs("div", { style: { textAlign: 'center', marginTop: '0.5rem', fontSize: '0.875rem', color: 'var(--auth-text-muted, #6B7280)' }, children: ["Don't have an account?", ' ', jsxRuntime.jsx("button", { className: "auth-link", disabled: true, children: "Sign up" })] })] })), hasOtherProviders && (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [showEmail && (jsxRuntime.jsx("div", { className: "auth-or-divider", children: jsxRuntime.jsx("span", { children: "or continue with" }) })), jsxRuntime.jsx("div", { className: "auth-provider-buttons", children: orderedProviders.map(provider => renderProviderButton(provider)) })] }))] })) }));
12521
12521
  };
12522
12522
 
12523
12523
  exports.AccountManagement = AccountManagement;