@onairosofficial/onairos-capacitor 0.1.0 → 0.1.2

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.
Files changed (202) hide show
  1. package/CAPACITOR_QUICK_START.md +379 -0
  2. package/CONNECTORS.md +122 -0
  3. package/LICENSE +194 -10
  4. package/OnairosofficialOnairosCapacitor.podspec +13 -0
  5. package/Package.swift +26 -0
  6. package/README.md +176 -25
  7. package/dist/onairos.capacitor.esm.js +1 -0
  8. package/dist/onairos.capacitor.esm.turbopack.js +1 -0
  9. package/docs/CAPACITOR_INTEGRATION_GUIDE.md +159 -0
  10. package/docs/CAPACITOR_MOCK_APP_TESTING.md +213 -0
  11. package/docs/CAPACITOR_SDK_FIXES_SUMMARY.md +65 -0
  12. package/docs/CROSS_SDK_PARITY.md +239 -0
  13. package/docs/DATA_FREQUENCY.md +57 -0
  14. package/docs/DEVELOPER_SDK_CHANGES.md +532 -0
  15. package/docs/INCIDENT_ENABLETRAINING_PIN_WEB_8.1.9.md +82 -0
  16. package/docs/ONAIROS_BUTTON_PROPS.md +152 -0
  17. package/docs/PLATFORM_APIS.md +559 -0
  18. package/docs/RAW_MEMORIES_API.md +305 -0
  19. package/docs/RAW_MEMORIES_SDK_UPDATE.md +54 -0
  20. package/docs/SDK_PARITY_ROLLUP_2026_04_24_to_05_02.md +96 -0
  21. package/docs/oldFixes.md +216 -0
  22. package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosChatGPTNativePlugin.swift +993 -0
  23. package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosNetflixNativePlugin.swift +33 -0
  24. package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosSpotifyNativePlugin.swift +1082 -0
  25. package/onairos.d.ts +656 -0
  26. package/package.json +188 -37
  27. package/src/OnairosReconnectButton.jsx +272 -0
  28. package/src/RSA.jsx +57 -0
  29. package/src/assets/NewLogo.png +0 -0
  30. package/src/assets/OnairosNewLogo.png +0 -0
  31. package/src/assets/chatgpt-icon.png +0 -0
  32. package/src/assets/fire-horse.png +0 -0
  33. package/src/assets/fire-horse.transparent.png +0 -0
  34. package/src/assets/latest-firehorse.png +0 -0
  35. package/src/assets/perplexity.png +0 -0
  36. package/src/assets/persona.png +0 -0
  37. package/src/assets/persona1.png +0 -0
  38. package/src/assets/persona2.png +0 -0
  39. package/src/assets/persona3.png +0 -0
  40. package/src/assets/persona4.png +0 -0
  41. package/src/assets/persona5.png +0 -0
  42. package/src/capacitorConnectorCatalog.js +38 -0
  43. package/src/capacitorOAuthConfig.js +52 -0
  44. package/src/chatgptHostedImport/index.js +303 -0
  45. package/src/components/AuthButtons.jsx +48 -0
  46. package/src/components/ConnectChatGPTModal.jsx +666 -0
  47. package/src/components/ConnectClaudeModal.jsx +610 -0
  48. package/src/components/ConnectGeminiModal.jsx +639 -0
  49. package/src/components/ConnectGrokModal.jsx +701 -0
  50. package/src/components/ConnectPerplexityModal.jsx +726 -0
  51. package/src/components/DataExplainerScreen.jsx +349 -0
  52. package/src/components/DataRequest.js +885 -0
  53. package/src/components/DataRequest.jsx +1055 -0
  54. package/src/components/EmailAuth.js +1871 -0
  55. package/src/components/EmailAuth.jsx +2062 -0
  56. package/src/components/ExtensionInstallPrompt.jsx +142 -0
  57. package/src/components/GoogleButton.js +133 -0
  58. package/src/components/LLMConnectorManager.jsx +201 -0
  59. package/src/components/LoadingPage.jsx +19 -0
  60. package/src/components/LoadingScreen.jsx +81 -0
  61. package/src/components/LunarBirthdate.jsx +96 -0
  62. package/src/components/LunarLoadingPage.jsx +251 -0
  63. package/src/components/Notification.jsx +21 -0
  64. package/src/components/OnairosAppButton.jsx +85 -0
  65. package/src/components/OnairosSSO.jsx +645 -0
  66. package/src/components/OnairosTrigger.jsx +61 -0
  67. package/src/components/PerplexityLogo.jsx +43 -0
  68. package/src/components/PinSetup.js +200 -0
  69. package/src/components/PinSetup.jsx +228 -0
  70. package/src/components/SDK_PIN_INTEGRATION_REQUIRED_CHANGES.md +526 -0
  71. package/src/components/SdkErrorBoundary.jsx +36 -0
  72. package/src/components/SecuritySetup.js +81 -0
  73. package/src/components/SessionUserBar.jsx +83 -0
  74. package/src/components/SignUp.js +123 -0
  75. package/src/components/TestTelegramButton.js +53 -0
  76. package/src/components/TrainingComponent.jsx +200 -0
  77. package/src/components/TrainingScreen.jsx +897 -0
  78. package/src/components/UniversalOnboarding.js +306 -0
  79. package/src/components/UniversalOnboarding.jsx +4837 -0
  80. package/src/components/ValentineLoadingPage.jsx +502 -0
  81. package/src/components/ValentineModeSelector.jsx +162 -0
  82. package/src/components/WelcomeScreen.jsx +435 -0
  83. package/src/components/WrappedLoadingPage.jsx +205 -0
  84. package/src/components/connectors/ChatGPTConnector.js +348 -0
  85. package/src/components/connectors/ChatGPTConnector.jsx +348 -0
  86. package/src/components/connectors/ClaudeConnector.js +44 -0
  87. package/src/components/connectors/ClaudeConnector.jsx +44 -0
  88. package/src/components/connectors/GeminiConnector.js +170 -0
  89. package/src/components/connectors/GeminiConnector.jsx +170 -0
  90. package/src/components/connectors/GmailConnector.js +148 -0
  91. package/src/components/connectors/GmailConnector.jsx +148 -0
  92. package/src/components/connectors/GrokConnector.js +16 -0
  93. package/src/components/connectors/GrokConnector.jsx +16 -0
  94. package/src/components/connectors/HingeConnector.js +419 -0
  95. package/src/components/connectors/HingeConnector.jsx +419 -0
  96. package/src/components/connectors/InstagramDataConnector.js +726 -0
  97. package/src/components/connectors/InstagramDataConnector.jsx +726 -0
  98. package/src/components/connectors/LinkedInConnector.js +4 -0
  99. package/src/components/connectors/LinkedInConnector.jsx +296 -0
  100. package/src/components/connectors/PerplexityConnector.jsx +16 -0
  101. package/src/components/connectors/PinterestConnector.js +208 -0
  102. package/src/components/connectors/PinterestConnector.jsx +208 -0
  103. package/src/components/connectors/README.md +292 -0
  104. package/src/components/connectors/RedditConnector.js +229 -0
  105. package/src/components/connectors/RedditConnector.jsx +229 -0
  106. package/src/components/connectors/SephoraConnector.js +482 -0
  107. package/src/components/connectors/SephoraConnector.jsx +482 -0
  108. package/src/components/connectors/TikTokConnector.jsx +430 -0
  109. package/src/components/connectors/YoutubeConnector.js +361 -0
  110. package/src/components/connectors/YoutubeConnector.jsx +361 -0
  111. package/src/components/connectors/index.js +50 -0
  112. package/src/components/icons.jsx +46 -0
  113. package/src/components/icons.tsx +21 -0
  114. package/src/components/ui/PageLayout.jsx +1255 -0
  115. package/src/components/ui/PrimaryButton.jsx +162 -0
  116. package/src/components/ui/button.jsx +49 -0
  117. package/src/components/ui/card.jsx +61 -0
  118. package/src/components/ui/checkbox.jsx +33 -0
  119. package/src/components/ui/label.jsx +29 -0
  120. package/src/components/utils/UpdateConnections.js +45 -0
  121. package/src/components/utils/oauthHelper.js +97 -0
  122. package/src/config/api-config.js +138 -0
  123. package/src/deepLink.jsx +38 -0
  124. package/src/getPin.js +26 -0
  125. package/src/icons/Avatar.png +0 -0
  126. package/src/icons/Sentiment.png +0 -0
  127. package/src/icons/Trait.png +0 -0
  128. package/src/iframe/DataRequestPage.jsx +285 -0
  129. package/src/iframe/OnairosButtonIntegration.md +148 -0
  130. package/src/iframe/components/Box.jsx +56 -0
  131. package/src/iframe/components/IndividualConnection.jsx +88 -0
  132. package/src/iframe/dataRequestHandler.js +714 -0
  133. package/src/iframe/data_request_iframe.html +27 -0
  134. package/src/iframe/data_request_page.js +47 -0
  135. package/src/iframe/icons/Avatar.png +1 -0
  136. package/src/iframe/icons/Avatar2.png +1 -0
  137. package/src/iframe/icons/Sentiment.png +1 -0
  138. package/src/iframe/icons/Trait.png +1 -0
  139. package/src/iframe/icons/onairos_logo.png +0 -0
  140. package/src/iframe/utils/api.js +57 -0
  141. package/src/index.js +274 -0
  142. package/src/laravel/OnairosVue.vue +410 -0
  143. package/src/laravel/blade-helpers.js +320 -0
  144. package/src/laravel/vite-plugin.js +179 -0
  145. package/src/mobile/MobileDataRequestPage.jsx +233 -0
  146. package/src/mobile/components/MobileBox.jsx +71 -0
  147. package/src/mobile/components/MobileIndividualConnection.jsx +51 -0
  148. package/src/mobile/shims/browser-apis.js +78 -0
  149. package/src/mobile/shims/lucide-shim.js +85 -0
  150. package/src/nativeConnectors.js +5 -0
  151. package/src/newUI/EMAIL_VERIFICATION_API_SCHEMA.md +268 -0
  152. package/src/newUI/PlatformConnectorsStep.tsx +435 -0
  153. package/src/newUI/PrimaryButton.tsx +213 -0
  154. package/src/newUI/SignInStep.tsx +194 -0
  155. package/src/newUI/VerificationStep.tsx +133 -0
  156. package/src/newUI/WelcomeScreen.tsx +311 -0
  157. package/src/newUI/services/connectedAccountsService.js +129 -0
  158. package/src/onairos.capacitor.jsx +15 -0
  159. package/src/onairos.core.jsx +133 -0
  160. package/src/onairos.jsx +14 -0
  161. package/src/onairos.native.jsx +15 -0
  162. package/src/onairosButton.jsx +9000 -0
  163. package/src/overlay/CheckBox.jsx +114 -0
  164. package/src/overlay/IndividualConnection copy.js +86 -0
  165. package/src/overlay/IndividualConnection.js +191 -0
  166. package/src/overlay/IndividualConnectionNew.jsx +157 -0
  167. package/src/overlay/box.js +84 -0
  168. package/src/overlay/overlay.js +437 -0
  169. package/src/styles/onairos-scoped-preflight.css +97 -0
  170. package/src/styles/sdkCssRegistry.js +20 -0
  171. package/src/styles/styleLoaderInsertShadow.js +69 -0
  172. package/src/styles/tailwind.capacitor.css +395 -0
  173. package/src/styles/tailwind.css +395 -0
  174. package/src/theme/colors.js +40 -0
  175. package/src/utils/apiKeyValidation.js +341 -0
  176. package/src/utils/apiResponseLogger.js +316 -0
  177. package/src/utils/authHeaders.js +275 -0
  178. package/src/utils/biometrics.js +26 -0
  179. package/src/utils/bookmarkletUtils.js +28 -0
  180. package/src/utils/capacitorDetection.js +278 -0
  181. package/src/utils/capacitorLLMHelper.js +352 -0
  182. package/src/utils/capacitorPlugins.js +366 -0
  183. package/src/utils/crossDomainSSO.js +587 -0
  184. package/src/utils/deepLinking.js +27 -0
  185. package/src/utils/devLogger.js +46 -0
  186. package/src/utils/extensionDetection.js +418 -0
  187. package/src/utils/extractMemory.js +277 -0
  188. package/src/utils/framerBrandingOverrides.js +40 -0
  189. package/src/utils/googleWebClientId.js +55 -0
  190. package/src/utils/overlayHandler.js +224 -0
  191. package/src/utils/platformDisconnect.js +309 -0
  192. package/src/utils/pollTrainingStatus.js +200 -0
  193. package/src/utils/rawMemoriesAccess.js +211 -0
  194. package/src/utils/resolveBackendAppId.js +47 -0
  195. package/src/utils/responseFormatter.js +140 -0
  196. package/src/utils/sdkDebugStorage.js +113 -0
  197. package/src/utils/sdkInitialization.js +645 -0
  198. package/src/utils/sessionManager.js +1258 -0
  199. package/src/utils/startBackgroundTraining.js +100 -0
  200. package/src/utils/userDataFormatter.js +222 -0
  201. package/index.d.ts +0 -1
  202. package/index.js +0 -1
@@ -0,0 +1,1871 @@
1
+ import React, { useState, useEffect, useRef, memo } from 'react';
2
+ import { Mail, ArrowRight, Check } from 'lucide-react';
3
+ import PrimaryButton from './ui/PrimaryButton.jsx';
4
+ import { COLORS } from '../theme/colors.js';
5
+ import { isMobileApp, isMobileBrowser } from '../utils/capacitorDetection';
6
+ import { GoogleLogin } from '@react-oauth/google';
7
+ import { getApiKey, setUserToken } from '../utils/authHeaders';
8
+ import { API_CONFIG } from '../config/api-config';
9
+ import { shouldHideOnairosLogoOnWelcomeAndEmail, getAiPlusPartnerWelcomeCopy } from '../utils/framerBrandingOverrides.js';
10
+ import {
11
+ isCapacitorNativePlatform,
12
+ isNativeGoogleAuthAvailable,
13
+ performNativeGoogleSignIn,
14
+ getCapacitorBrowser,
15
+ } from '../utils/capacitorPlugins.js';
16
+
17
+ // CRITICAL: Wrap in React.memo to prevent re-renders (and potential remounts) when parent re-renders
18
+ // This preserves internal state (like the current step: 'email' -> 'code' -> 'success')
19
+ function EmailAuthComponent({ onSuccess, testMode = false, preVerifiedEmail = null, theme = 'default' }) {
20
+ const isGlass = theme === 'glass';
21
+ const hideOnairosLogo = shouldHideOnairosLogoOnWelcomeAndEmail();
22
+ const partnerWelcomeCopy = getAiPlusPartnerWelcomeCopy();
23
+ const usePartnerCopy = !!partnerWelcomeCopy;
24
+ // Helper to mask email (e.g., "john@example.com" -> "j*****@example.com")
25
+ // Shows first character, stars, and full domain for user recognition
26
+ const maskEmail = (emailStr) => {
27
+ if (!emailStr || typeof emailStr !== 'string') return '';
28
+ const [local, domain] = emailStr.split('@');
29
+ if (!local || !domain) return emailStr;
30
+ if (local.length <= 2) return `${local[0]}*****@${domain}`;
31
+ return `${local[0]}${'*'.repeat(5)}@${domain}`;
32
+ };
33
+
34
+ // Check if preVerifiedEmail is valid
35
+ const isValidPreVerifiedEmail = (email) => {
36
+ return !!(email && typeof email === 'string' && email.includes('@') && email.includes('.'));
37
+ };
38
+
39
+ // Initial state based on preVerifiedEmail prop
40
+ const hasPreVerifiedEmail = isValidPreVerifiedEmail(preVerifiedEmail);
41
+
42
+ const [email, setEmail] = useState(hasPreVerifiedEmail ? preVerifiedEmail.trim().toLowerCase() : '');
43
+ // Store verification code as per-digit state
44
+ const [codeDigits, setCodeDigits] = useState(() => Array(6).fill(''));
45
+ const [step, setStep] = useState(hasPreVerifiedEmail ? 'preVerified' : 'email'); // 'preVerified' | 'email' | 'code' | 'success'
46
+
47
+ // Track if we've already handled the preVerifiedEmail to avoid re-triggering
48
+ const preVerifiedEmailHandledRef = useRef(hasPreVerifiedEmail ? preVerifiedEmail : null);
49
+
50
+ // REACTIVE: Handle preVerifiedEmail prop changes (e.g., null → valid email)
51
+ // This allows developers to pass email that loads asynchronously
52
+ useEffect(() => {
53
+ const normalizedNew = preVerifiedEmail ? preVerifiedEmail.trim().toLowerCase() : null;
54
+ const alreadyHandled = preVerifiedEmailHandledRef.current;
55
+
56
+ // Only react if:
57
+ // 1. preVerifiedEmail is now valid AND
58
+ // 2. We haven't already handled this specific email AND
59
+ // 3. User is still on the 'email' step (hasn't started entering their own email)
60
+ if (
61
+ isValidPreVerifiedEmail(normalizedNew) &&
62
+ normalizedNew !== alreadyHandled &&
63
+ step === 'email'
64
+ ) {
65
+ console.log('📧 [EmailAuth] preVerifiedEmail prop updated, switching to pre-verified flow:', maskEmail(normalizedNew));
66
+ preVerifiedEmailHandledRef.current = normalizedNew;
67
+ setEmail(normalizedNew);
68
+ setStep('preVerified');
69
+ }
70
+ }, [preVerifiedEmail, step]);
71
+ const [isLoading, setIsLoading] = useState(false);
72
+ const [error, setError] = useState('');
73
+ // Google-in-WebView failures are expected on iOS (WKWebView restrictions). Keep messaging non-blocking/non-red.
74
+ const [googleHint, setGoogleHint] = useState('');
75
+ const [emailSent, setEmailSent] = useState(true);
76
+ const [emailServiceMessage, setEmailServiceMessage] = useState('');
77
+
78
+ const isCodeComplete = codeDigits.every((d) => typeof d === 'string' && d.length === 1);
79
+ const resetCodeDigits = () => setCodeDigits(Array(6).fill(''));
80
+ // Capacitor native should use the SAME UI layout as mobile web for SDK parity.
81
+ const isMobileWeb = isMobileBrowser() || isMobileApp();
82
+ // On iOS WKWebView (Capacitor), Google's embedded button can render and then disappear
83
+ // (iframe removed) depending on WebView/cookie state. Never leave a blank space:
84
+ // we always render a fallback button and only hide it while the widget is actually present.
85
+ // Start optimistically as 'true' to avoid flashing the error button on first render.
86
+ // The detection logic will switch to false after 300ms if the iframe doesn't appear.
87
+ const [googleWidgetPresent, setGoogleWidgetPresent] = useState(true);
88
+ const googleContainerRef = useRef(null);
89
+ const googleAbsentTimerRef = useRef(null);
90
+ const mountedRef = useRef(true);
91
+ const instanceIdRef = useRef(Math.random().toString(36).substring(7));
92
+
93
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
94
+
95
+ // DEBUG: Track component mount/unmount to identify remount issues
96
+ useEffect(() => {
97
+ const id = instanceIdRef.current;
98
+ console.log(`🔄 [EmailAuth:${id}] Component MOUNTED - initial step: ${step}`);
99
+ mountedRef.current = true;
100
+ return () => {
101
+ console.log(`🔄 [EmailAuth:${id}] Component UNMOUNTING - final step: ${step}`);
102
+ mountedRef.current = false;
103
+ };
104
+ }, []);
105
+
106
+ // DEBUG: Track step changes
107
+ useEffect(() => {
108
+ const id = instanceIdRef.current;
109
+ console.log(`📍 [EmailAuth:${id}] Step changed to: "${step}"`);
110
+ }, [step]);
111
+
112
+ useEffect(() => {
113
+ // Always run Google widget detection on the email step, regardless of device type
114
+ // The widget should work everywhere, and we need to detect when it's blocked
115
+ if (step !== 'email') return;
116
+
117
+ const el = googleContainerRef.current;
118
+ if (!el) return;
119
+
120
+ const isPresentNow = () => {
121
+ try {
122
+ // GoogleLogin typically injects an iframe. In some cases it injects a div with role=button.
123
+ const hasIframe = !!el.querySelector('iframe');
124
+ const hasRoleButton = !!el.querySelector('[role="button"]');
125
+ return hasIframe || hasRoleButton;
126
+ } catch {
127
+ return false;
128
+ }
129
+ };
130
+
131
+ const setPresent = (present) => {
132
+ if (!mountedRef.current) return;
133
+ setGoogleWidgetPresent(present);
134
+ };
135
+
136
+ const reconcile = () => {
137
+ const present = isPresentNow();
138
+
139
+ // If widget is present, show it and cancel any pending "absent" transition.
140
+ if (present) {
141
+ if (googleAbsentTimerRef.current) {
142
+ clearTimeout(googleAbsentTimerRef.current);
143
+ googleAbsentTimerRef.current = null;
144
+ }
145
+ setPresent(true);
146
+ return;
147
+ }
148
+
149
+ // If widget is absent, debounce the transition to avoid flicker while the iframe is mounting.
150
+ if (!googleAbsentTimerRef.current) {
151
+ googleAbsentTimerRef.current = setTimeout(() => {
152
+ googleAbsentTimerRef.current = null;
153
+ setPresent(false);
154
+ }, 300);
155
+ }
156
+ };
157
+
158
+ // Initial reconcile + observe changes
159
+ reconcile();
160
+ const obs = new MutationObserver(reconcile);
161
+ try {
162
+ obs.observe(el, { childList: true, subtree: true, attributes: true });
163
+ } catch {}
164
+
165
+ // Also periodically reconcile because some WebViews mutate the iframe contents without DOM childList changes.
166
+ const intervalId = setInterval(reconcile, 750);
167
+
168
+ return () => {
169
+ try { obs.disconnect(); } catch {}
170
+ clearInterval(intervalId);
171
+ if (googleAbsentTimerRef.current) {
172
+ clearTimeout(googleAbsentTimerRef.current);
173
+ googleAbsentTimerRef.current = null;
174
+ }
175
+ };
176
+ }, [step]);
177
+
178
+ const postJson = async (url, apiKey, body) => {
179
+ const response = await fetch(url, {
180
+ method: 'POST',
181
+ headers: {
182
+ 'Content-Type': 'application/json',
183
+ 'x-api-key': apiKey,
184
+ 'Authorization': `Bearer ${apiKey}`,
185
+ },
186
+ body: JSON.stringify(body),
187
+ });
188
+ return response;
189
+ };
190
+
191
+ const requestEmailVerification = async ({ baseUrl, apiKey, email: rawEmail }) => {
192
+ const normalizedEmail = (rawEmail || '').trim().toLowerCase();
193
+ console.log('📧 [EmailAuth] requestEmailVerification called for:', normalizedEmail);
194
+
195
+ // New endpoint
196
+ try {
197
+ console.log('📧 [EmailAuth] Trying new endpoint: /email/verification');
198
+ const res = await postJson(`${baseUrl}/email/verification`, apiKey, {
199
+ email: normalizedEmail,
200
+ action: 'request',
201
+ });
202
+ console.log('📧 [EmailAuth] New endpoint response status:', res.status, res.ok);
203
+ if (res.ok) {
204
+ const data = await res.json();
205
+ console.log('✅ [EmailAuth] New endpoint success:', data);
206
+ return data;
207
+ }
208
+ // Log non-ok response for debugging
209
+ console.log('⚠️ [EmailAuth] New endpoint returned non-OK status:', res.status);
210
+ try {
211
+ const errorBody = await res.json();
212
+ console.log('⚠️ [EmailAuth] New endpoint error body:', errorBody);
213
+ } catch {}
214
+ } catch (err) {
215
+ // Log the actual error instead of silently ignoring
216
+ console.warn('⚠️ [EmailAuth] New endpoint failed, falling back to legacy:', err?.message || err);
217
+ }
218
+
219
+ // Legacy endpoint
220
+ console.log('📧 [EmailAuth] Trying legacy endpoint: /email/verify');
221
+ const legacyRes = await postJson(`${baseUrl}/email/verify`, apiKey, { email: normalizedEmail });
222
+ console.log('📧 [EmailAuth] Legacy endpoint response status:', legacyRes.status, legacyRes.ok);
223
+
224
+ if (!legacyRes.ok) {
225
+ let msg = 'Failed to send verification code';
226
+ try {
227
+ const err = await legacyRes.json();
228
+ console.error('❌ [EmailAuth] Legacy endpoint error:', err);
229
+ if (err?.error) msg = err.error;
230
+ if (err?.message) msg = err.message;
231
+ } catch (parseErr) {
232
+ console.error('❌ [EmailAuth] Could not parse legacy error response:', parseErr);
233
+ }
234
+ throw new Error(msg);
235
+ }
236
+
237
+ const data = await legacyRes.json();
238
+ console.log('✅ [EmailAuth] Legacy endpoint success:', data);
239
+ return data;
240
+ };
241
+
242
+ const verifyEmailCode = async ({ baseUrl, apiKey, email: rawEmail, code: rawCode }) => {
243
+ const normalizedEmail = (rawEmail || '').trim().toLowerCase();
244
+ const normalizedCode = String(rawCode || '').trim();
245
+
246
+ // New endpoint
247
+ try {
248
+ const res = await postJson(`${baseUrl}/email/verification`, apiKey, {
249
+ email: normalizedEmail,
250
+ action: 'verify',
251
+ code: normalizedCode,
252
+ });
253
+ if (res.ok) return await res.json();
254
+ try {
255
+ const err = await res.json();
256
+ throw new Error(err?.error || err?.message || 'Verification failed');
257
+ } catch (e) {
258
+ if (e instanceof Error) throw e;
259
+ }
260
+ } catch (e) {
261
+ const msg = e?.message || '';
262
+ if (msg && !msg.toLowerCase().includes('not found') && !msg.toLowerCase().includes('cannot')) {
263
+ // Keep going to legacy
264
+ }
265
+ }
266
+
267
+ // Legacy endpoint with retry
268
+ const maxAttempts = 5;
269
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
270
+ const res = await postJson(`${baseUrl}/email/verify/confirm`, apiKey, {
271
+ email: normalizedEmail,
272
+ code: normalizedCode,
273
+ });
274
+
275
+ if (res.ok) return await res.json();
276
+
277
+ let errMsg = 'Invalid verification code';
278
+ try {
279
+ const err = await res.json();
280
+ if (err?.error) errMsg = err.error;
281
+ if (typeof err?.attemptsRemaining === 'number') {
282
+ errMsg = `${errMsg} (attempts remaining: ${err.attemptsRemaining})`;
283
+ }
284
+ } catch {}
285
+
286
+ if (errMsg.toLowerCase().includes('no verification code found') && attempt < maxAttempts) {
287
+ await sleep(150 * attempt);
288
+ continue;
289
+ }
290
+
291
+ throw new Error(errMsg);
292
+ }
293
+
294
+ throw new Error('Verification failed');
295
+ };
296
+
297
+ const handleOAuthSuccess = async (gmailEmail, credential) => {
298
+ try {
299
+ setIsLoading(true);
300
+ console.log('✅ Google OAuth completed successfully, email:', gmailEmail);
301
+
302
+ const normalizedEmail = (gmailEmail || '').trim().toLowerCase();
303
+ setEmail(normalizedEmail);
304
+
305
+ const baseUrl = (typeof window !== 'undefined' && window.onairosBaseUrl) || API_CONFIG.getBaseUrl();
306
+ const apiKey = getApiKey();
307
+
308
+ // STEP 1: Call backend to create/login account
309
+ const isCapacitorNative = isCapacitorNativePlatform();
310
+ const authPath = isCapacitorNative ? '/register/google' : '/google/google';
311
+ console.log(`🔐 Authenticating with backend via ${authPath}...`);
312
+ console.log('🔑 Sending ID token (JWT format) to backend for verification');
313
+
314
+ try {
315
+ const authResponse = await fetch(`${baseUrl}${authPath}`, {
316
+ method: 'POST',
317
+ headers: {
318
+ 'Content-Type': 'application/json',
319
+ 'x-api-key': apiKey,
320
+ },
321
+ body: JSON.stringify({
322
+ credential: credential // Google ID token (JWT) - NOT access token!
323
+ })
324
+ });
325
+
326
+ if (!authResponse.ok) {
327
+ let msg = `Failed to authenticate with backend (${authResponse.status})`;
328
+ try {
329
+ const errorData = await authResponse.json();
330
+ msg =
331
+ errorData?.body?.message ||
332
+ errorData?.error ||
333
+ errorData?.message ||
334
+ msg;
335
+ } catch (_) {
336
+ try {
337
+ const t = await authResponse.text();
338
+ if (t) msg = t;
339
+ } catch {}
340
+ }
341
+ throw new Error(msg);
342
+ }
343
+
344
+ const authData = await authResponse.json();
345
+ const isLegacyShape = !!authData?.body;
346
+ const jwtToken = isLegacyShape ? authData.body?.token : authData?.token;
347
+ const username =
348
+ (isLegacyShape ? authData.body?.username : authData?.user?.username) || normalizedEmail;
349
+ const backendIsNewUser = isLegacyShape ? authData.body?.isNewUser : authData?.isNewUser;
350
+ // Treat "missing flag" as NOT-new (safer). New users should be explicitly flagged by backend.
351
+ const isNewUser = backendIsNewUser === true;
352
+
353
+ console.log('✅ Backend authentication successful:', { username, isNewUser });
354
+
355
+ // Store the JWT token for future requests
356
+ if (jwtToken) {
357
+ setUserToken(jwtToken);
358
+ }
359
+
360
+ // STEP 2: Check account status for additional info (using JWT from login)
361
+ let accountInfo = null;
362
+ let accountStatus = null;
363
+
364
+ try {
365
+ console.log('🔍 Fetching account status...');
366
+ const accountCheckResponse = await fetch(`${baseUrl}/getAccountInfo/email`, {
367
+ method: 'POST',
368
+ headers: {
369
+ 'Content-Type': 'application/json',
370
+ 'x-api-key': apiKey,
371
+ 'Authorization': `Bearer ${jwtToken}`, // Use JWT from login
372
+ },
373
+ body: JSON.stringify({
374
+ Info: {
375
+ identifier: normalizedEmail
376
+ }
377
+ })
378
+ });
379
+
380
+ if (accountCheckResponse.ok) {
381
+ const accountData = await accountCheckResponse.json();
382
+ // Backend responses are not always consistent in key naming/shape.
383
+ // On some paths (notably native /register/google), we may get accountStatus without AccountInfo.
384
+ accountInfo =
385
+ accountData?.AccountInfo ||
386
+ accountData?.accountInfo ||
387
+ accountData?.body?.AccountInfo ||
388
+ accountData?.body?.accountInfo ||
389
+ accountInfo;
390
+
391
+ accountStatus =
392
+ accountData?.accountStatus ||
393
+ accountData?.AccountStatus ||
394
+ accountData?.body?.accountStatus ||
395
+ accountData?.body?.AccountStatus ||
396
+ accountStatus;
397
+
398
+ // Normalize connectedPlatforms across backend shapes
399
+ try {
400
+ const connectedPlatformsRaw =
401
+ accountStatus?.connectedPlatforms ||
402
+ accountStatus?.connected_platforms ||
403
+ accountInfo?.connectedPlatforms ||
404
+ accountInfo?.connected_platforms ||
405
+ accountData?.connectedPlatforms ||
406
+ accountData?.connected_platforms ||
407
+ accountData?.body?.connectedPlatforms ||
408
+ accountData?.body?.connected_platforms ||
409
+ null;
410
+ if (Array.isArray(connectedPlatformsRaw)) {
411
+ accountStatus = {
412
+ ...(accountStatus || {}),
413
+ connectedPlatforms: connectedPlatformsRaw,
414
+ };
415
+ }
416
+ const existsRaw =
417
+ (typeof accountStatus?.exists === 'boolean' && accountStatus.exists) ||
418
+ (typeof accountStatus?.exists === 'boolean' ? accountStatus.exists : undefined) ||
419
+ (typeof accountInfo?.exists === 'boolean' ? accountInfo.exists : undefined) ||
420
+ (typeof accountData?.exists === 'boolean' ? accountData.exists : undefined) ||
421
+ (typeof accountData?.body?.exists === 'boolean' ? accountData.body.exists : undefined);
422
+ if (typeof existsRaw === 'boolean') {
423
+ accountStatus = { ...(accountStatus || {}), exists: existsRaw };
424
+ }
425
+ } catch (_) {}
426
+ console.log('✅ Account status retrieved:', {
427
+ hasAccountInfo: !!accountInfo,
428
+ exists: accountStatus?.exists,
429
+ connectedPlatforms: accountStatus?.connectedPlatforms
430
+ });
431
+ }
432
+ } catch (accountCheckError) {
433
+ console.warn('⚠️ Could not fetch account status (non-critical):', accountCheckError);
434
+ }
435
+
436
+ setStep('success');
437
+ setIsLoading(false);
438
+
439
+ // STEP 3: Return success with token and user data
440
+ setTimeout(() => {
441
+ onSuccess({
442
+ email: normalizedEmail,
443
+ verified: true,
444
+ token: jwtToken, // ✅ NOW we have a JWT token from backend!
445
+ jwtToken: jwtToken,
446
+ userName: username,
447
+ username: username,
448
+ existingUser: !isNewUser,
449
+ accountInfo: accountInfo,
450
+ accountStatus: accountStatus,
451
+ isNewUser: isNewUser,
452
+ flowType: isNewUser ? 'onboarding' : 'dataRequest',
453
+ adminMode: false,
454
+ userCreated: isNewUser,
455
+ provider: 'google',
456
+ accountDetails: accountInfo || {
457
+ email: normalizedEmail,
458
+ createdAt: new Date().toISOString(),
459
+ ssoProvider: 'google'
460
+ }
461
+ });
462
+ }, 400);
463
+
464
+ } catch (authError) {
465
+ console.error('❌ Backend authentication failed:', authError);
466
+ setError(authError.message || 'Failed to authenticate with backend. Please try again.');
467
+ setIsLoading(false);
468
+ return;
469
+ }
470
+
471
+ } catch (error) {
472
+ console.error('❌ Error handling OAuth success:', error);
473
+ setError('Failed to continue with Google authentication. Please try again.');
474
+ setIsLoading(false);
475
+ }
476
+ };
477
+
478
+ const handleGoogleFallbackClick = async () => {
479
+ // Clear any previous messaging (and avoid showing a big red inline error for this expected case).
480
+ setError('');
481
+ setGoogleHint('');
482
+
483
+ // If we're in a native Capacitor app, prefer native Google sign-in (no embedded WKWebView).
484
+ if (isCapacitorNativePlatform()) {
485
+ const googleAuth = getCapacitorGoogleAuth();
486
+ if (!googleAuth) {
487
+ setGoogleHint('Google sign-in requires a native Google auth plugin in this app. Use email login.');
488
+ return;
489
+ }
490
+
491
+ let handedOffToBackend = false;
492
+ try {
493
+ setIsLoading(true);
494
+
495
+ // Support multiple native plugin APIs.
496
+ // - @capgo/capacitor-social-login: initialize() + login({ provider:'google', options:{...} })
497
+ // - other plugins: signIn()
498
+ let result = null;
499
+ if (typeof googleAuth.initialize === 'function' && typeof googleAuth.login === 'function') {
500
+ const webClientId =
501
+ (typeof window !== 'undefined' && window.onairosGoogleClientId) || '';
502
+ const iosClientId =
503
+ (typeof window !== 'undefined' && window.onairosGoogleIosClientId) || '';
504
+
505
+ if (!webClientId || !iosClientId) {
506
+ setGoogleHint('To enable Google sign-in in this iOS app, set updateGoogleClientIds({ webClientId, iosClientId }) in the host app. Otherwise use email login.');
507
+ setIsLoading(false);
508
+ return;
509
+ }
510
+
511
+ try {
512
+ await googleAuth.initialize({
513
+ google: {
514
+ webClientId,
515
+ iOSClientId: iosClientId,
516
+ // If your backend verifies tokens / you need server-side validation, set this to the web client id.
517
+ // (Safe default here.)
518
+ iOSServerClientId: webClientId,
519
+ mode: 'online',
520
+ },
521
+ });
522
+ } catch (e) {
523
+ console.warn('Google plugin initialize failed:', e);
524
+ setGoogleHint('Google sign-in is not configured correctly in this app. Please use email login.');
525
+ setIsLoading(false);
526
+ return;
527
+ }
528
+
529
+ const r = await googleAuth.login({
530
+ provider: 'google',
531
+ options: { scopes: ['profile', 'email'] },
532
+ });
533
+ result = r?.result || r;
534
+ } else if (typeof googleAuth.signIn === 'function') {
535
+ result = await googleAuth.signIn();
536
+ } else {
537
+ setGoogleHint('Google sign-in requires a compatible native Google auth plugin in this app. Use email login.');
538
+ setIsLoading(false);
539
+ return;
540
+ }
541
+
542
+ // Best-effort extraction across common Capacitor Google Auth plugins.
543
+ const idToken =
544
+ result?.authentication?.idToken ||
545
+ result?.idToken ||
546
+ result?.result?.idToken ||
547
+ result?.credential ||
548
+ result?.tokens?.idToken ||
549
+ result?.response?.idToken ||
550
+ '';
551
+
552
+ // Prefer explicit email if provided; otherwise decode from the JWT (same as web flow).
553
+ let userEmail =
554
+ result?.email ||
555
+ result?.user?.email ||
556
+ result?.profile?.email ||
557
+ result?.result?.profile?.email ||
558
+ '';
559
+
560
+ if (!idToken) {
561
+ setGoogleHint('Google sign-in did not return an ID token. Use email login.');
562
+ setIsLoading(false);
563
+ return;
564
+ }
565
+
566
+ if (!userEmail) {
567
+ try {
568
+ const base64Url = String(idToken).split('.')[1];
569
+ const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
570
+ const jsonPayload = decodeURIComponent(
571
+ atob(base64)
572
+ .split('')
573
+ .map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
574
+ .join('')
575
+ );
576
+ const payload = JSON.parse(jsonPayload);
577
+ userEmail = String(payload?.email || '').trim().toLowerCase();
578
+ } catch (_) {}
579
+ }
580
+
581
+ if (!userEmail) {
582
+ setGoogleHint('Could not determine your email from Google sign-in. Use email login.');
583
+ setIsLoading(false);
584
+ return;
585
+ }
586
+
587
+ // Reuse the existing backend login flow which expects an ID token (JWT).
588
+ handedOffToBackend = true;
589
+ await handleOAuthSuccess(userEmail, idToken);
590
+ } catch (e) {
591
+ console.error('Native Google sign-in failed:', e);
592
+ setGoogleHint('Google sign-in failed in this app. Please use email login.');
593
+ if (!handedOffToBackend) setIsLoading(false);
594
+ }
595
+
596
+ return;
597
+ }
598
+
599
+ // Non-native environment: if the embedded widget is missing, we can only suggest email.
600
+ setGoogleHint('Google sign-in is unavailable here. Please use email login.');
601
+ };
602
+
603
+ // Note: No OAuth callback checking needed - frontend SDK handles everything automatically
604
+
605
+ // Google Sign-In success handler
606
+ // Receives ID token (JWT) from Google - this is the CORRECT token type for authentication
607
+ const handleGoogleSuccess = async (credentialResponse) => {
608
+ try {
609
+ setIsLoading(true);
610
+ setError('');
611
+ setGoogleHint('');
612
+ console.log('✅ Google OAuth successful - ID token received');
613
+
614
+ // credentialResponse.credential is the ID token (JWT format: eyJhbGciOiJ...)
615
+ const idToken = credentialResponse.credential;
616
+
617
+ if (!idToken) {
618
+ throw new Error('No ID token received from Google');
619
+ }
620
+
621
+ console.log('🔑 ID token format:', idToken.substring(0, 20) + '...');
622
+
623
+ // Decode the JWT to get user email (without verifying - backend will verify)
624
+ try {
625
+ const base64Url = idToken.split('.')[1];
626
+ const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
627
+ const jsonPayload = decodeURIComponent(atob(base64).split('').map(c => {
628
+ return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
629
+ }).join(''));
630
+
631
+ const payload = JSON.parse(jsonPayload);
632
+ const userEmail = payload.email;
633
+
634
+ console.log('✅ Decoded email from ID token:', userEmail);
635
+
636
+ // Handle OAuth success with email and ID token (not access token!)
637
+ await handleOAuthSuccess(userEmail, idToken);
638
+
639
+ } catch (decodeError) {
640
+ console.error('❌ Failed to decode ID token:', decodeError);
641
+ setError('Failed to process Google authentication. Please try again.');
642
+ setIsLoading(false);
643
+ }
644
+
645
+ } catch (error) {
646
+ console.error('❌ Error handling Google success:', error);
647
+ setError('Failed to sign in with Google. Please try again.');
648
+ setIsLoading(false);
649
+ }
650
+ };
651
+
652
+ const handleGoogleError = (error) => {
653
+ console.error('❌ Google Sign In failed:', error);
654
+ setError('Failed to sign in with Google. Please try again.');
655
+ setIsLoading(false);
656
+ };
657
+
658
+ // Web-only fallback when the Google widget is blocked/unavailable.
659
+ // This handler is referenced by the UI. If it’s missing, EmailAuth crashes.
660
+ const handleGoogleUnavailable = async () => {
661
+ try {
662
+ await handleCapacitorBrowserGoogleSignIn();
663
+ } catch (e) {
664
+ console.error('❌ Google fallback failed:', e);
665
+ setError('Failed to open Google sign-in. Please try email login.');
666
+ setIsLoading(false);
667
+ }
668
+ };
669
+
670
+ /**
671
+ * Native Google Sign-In for Capacitor apps.
672
+ * Uses @codetrix-studio/capacitor-google-auth or similar native plugin.
673
+ *
674
+ * Only used if developer has installed native plugin AND provided their googleClientIds.
675
+ */
676
+ const handleNativeGoogleSignIn = async () => {
677
+ try {
678
+ setIsLoading(true);
679
+ setError('');
680
+ console.log('📱 Attempting native Google Sign-In...');
681
+
682
+ const result = await performNativeGoogleSignIn();
683
+
684
+ if (!result.success) {
685
+ console.error('❌ Native Google Sign-In failed:', result.error);
686
+ setError(result.error || 'Native Google Sign-In failed. Please try email login.');
687
+ setIsLoading(false);
688
+ return;
689
+ }
690
+
691
+ console.log('✅ Native Google Sign-In successful:', result.user?.email);
692
+
693
+ // Use the ID token from native sign-in (same flow as web GoogleLogin)
694
+ if (result.idToken) {
695
+ await handleOAuthSuccess(result.user?.email, result.idToken);
696
+ } else {
697
+ // Some plugins don't return idToken but return serverAuthCode
698
+ console.error('❌ No ID token from native sign-in. Ensure plugin is configured with serverClientId.');
699
+ setError('Authentication configuration error. Please contact support.');
700
+ setIsLoading(false);
701
+ }
702
+ } catch (error) {
703
+ console.error('❌ Native Google Sign-In error:', error);
704
+ setError('Failed to sign in with Google. Please try email login.');
705
+ setIsLoading(false);
706
+ }
707
+ };
708
+
709
+ /**
710
+ * System Browser Google Sign-In for Capacitor apps (DEFAULT).
711
+ * Uses Onairos's web client ID via system browser (SFSafariViewController/Chrome Custom Tabs).
712
+ * Works out of the box without developer configuration.
713
+ */
714
+ const handleCapacitorBrowserGoogleSignIn = async () => {
715
+ try {
716
+ setIsLoading(true);
717
+ setError('');
718
+ console.log('📱 Capacitor: Opening Google Sign-In in system browser...');
719
+
720
+ const baseUrl = (typeof window !== 'undefined' && window.onairosBaseUrl) || API_CONFIG.getBaseUrl();
721
+ const apiKey = getApiKey();
722
+
723
+ // Prefer a host-app override for OAuth return origin (deep link scheme), otherwise return to current URL.
724
+ // This is critical for Capacitor apps where `window.location.href` is often `capacitor://localhost/...`,
725
+ // which many backends reject or cannot redirect back to safely.
726
+ let returnUrl = window.location.href;
727
+ try {
728
+ const forced =
729
+ typeof window !== 'undefined' && window.onairosOAuthReturnOrigin
730
+ ? String(window.onairosOAuthReturnOrigin)
731
+ : '';
732
+ if (forced) {
733
+ const u = new URL(forced);
734
+ const pathname = u.pathname && u.pathname.length ? u.pathname : '/';
735
+ returnUrl = `${u.protocol}//${u.host}${pathname}${u.search || ''}${u.hash || ''}`;
736
+ }
737
+ } catch (_) {}
738
+
739
+ // Get OAuth URL from backend (uses Onairos's default web client ID)
740
+ const response = await fetch(`${baseUrl}/google/authorize`, {
741
+ method: 'POST',
742
+ headers: {
743
+ 'Content-Type': 'application/json',
744
+ 'x-api-key': apiKey,
745
+ 'Authorization': `Bearer ${apiKey}`,
746
+ },
747
+ body: JSON.stringify({
748
+ returnUrl, // Return to app (deep link origin override if provided)
749
+ }),
750
+ });
751
+
752
+ if (!response.ok) {
753
+ let msg = `Google authorize failed (${response.status})`;
754
+ try {
755
+ const err = await response.json();
756
+ msg = err?.message || err?.error || err?.body?.message || msg;
757
+ } catch (_) {
758
+ try {
759
+ const text = await response.text();
760
+ if (text) msg = text;
761
+ } catch {}
762
+ }
763
+ throw new Error(msg);
764
+ }
765
+
766
+ const result = await response.json();
767
+ const googleURL = result?.googleURL || result?.authUrl || result?.url;
768
+
769
+ if (!googleURL) {
770
+ throw new Error(result?.message || result?.error || 'No Google authorization URL received');
771
+ }
772
+
773
+ // Open in system browser (SFSafariViewController on iOS, Chrome Custom Tabs on Android)
774
+ const BrowserPlugin = getCapacitorBrowser();
775
+ if (BrowserPlugin?.open) {
776
+ await BrowserPlugin.open({
777
+ url: googleURL,
778
+ windowName: '_blank',
779
+ presentationStyle: 'fullscreen',
780
+ });
781
+ // User will be redirected back after OAuth completes
782
+ // The OAuth callback handling is done in the parent component
783
+ } else {
784
+ // Fallback: redirect in WebView (may have issues but better than nothing)
785
+ console.warn('⚠️ Capacitor Browser plugin not available, falling back to redirect');
786
+ window.location.href = googleURL;
787
+ }
788
+
789
+ setIsLoading(false);
790
+ } catch (error) {
791
+ console.error('❌ Capacitor browser Google Sign-In error:', error);
792
+ setError('Failed to open Google Sign-In. Please try email login.');
793
+ setIsLoading(false);
794
+ }
795
+ };
796
+
797
+ // Determine which Google Sign-In method to use on Capacitor
798
+ // Prefer native Google Sign-In on Capacitor whenever a native plugin is present.
799
+ // The system-browser fallback previously relied on a backend `/google/authorize` endpoint, which may not exist.
800
+ const shouldUseNativeGoogleAuth = isCapacitorNativePlatform() && isNativeGoogleAuthAvailable();
801
+ const shouldUseCapacitorBrowser = isCapacitorNativePlatform() && !shouldUseNativeGoogleAuth;
802
+
803
+ const applyVerificationDigits = (startIndex, rawText) => {
804
+ const digits = String(rawText || '').replace(/\D/g, '');
805
+ if (!digits) return;
806
+
807
+ setCodeDigits((prev) => {
808
+ const next = [...prev];
809
+ for (let i = 0; i < digits.length && startIndex + i < 6; i++) {
810
+ next[startIndex + i] = digits[i];
811
+ }
812
+ return next;
813
+ });
814
+
815
+ const raf =
816
+ typeof requestAnimationFrame === 'function'
817
+ ? requestAnimationFrame
818
+ : (cb) => setTimeout(cb, 0);
819
+
820
+ raf(() => {
821
+ const inputs = document.querySelectorAll('input.onairos-verification-digit');
822
+ if (!inputs || !inputs.length) return;
823
+ const lastFilled = Math.min(startIndex + digits.length - 1, 5);
824
+ const focusIndex = Math.min(startIndex + digits.length, 5);
825
+ const el = inputs[focusIndex] || inputs[lastFilled];
826
+ if (el && typeof el.focus === 'function') el.focus();
827
+ });
828
+ };
829
+
830
+ // Auto-focus code input
831
+ useEffect(() => {
832
+ if (step === 'code') {
833
+ setTimeout(() => {
834
+ const firstInput = document.querySelector('input.onairos-verification-digit');
835
+ if (firstInput) firstInput.focus();
836
+ }, 100);
837
+ }
838
+ }, [step]);
839
+
840
+ const validateEmail = (email) => {
841
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
842
+ return emailRegex.test(email);
843
+ };
844
+
845
+ const handleEmailSubmit = async (e) => {
846
+ e.preventDefault();
847
+ setError('');
848
+ setEmailSent(true);
849
+ setEmailServiceMessage('');
850
+ resetCodeDigits();
851
+
852
+ console.log('📧 [EmailAuth] handleEmailSubmit started for:', email);
853
+
854
+ if (!validateEmail(email)) {
855
+ console.log('❌ [EmailAuth] Invalid email format');
856
+ setError('Please enter a valid email address');
857
+ return;
858
+ }
859
+
860
+ setIsLoading(true);
861
+ console.log('📧 [EmailAuth] Starting verification request...');
862
+
863
+ try {
864
+ if (testMode) {
865
+ console.log('🧪 [EmailAuth] Test mode - simulating delay');
866
+ setTimeout(() => {
867
+ setStep('code');
868
+ setIsLoading(false);
869
+ }, 800);
870
+ } else {
871
+ const baseUrl = (typeof window !== 'undefined' && window.onairosBaseUrl) || API_CONFIG.getBaseUrl();
872
+ const apiKey = getApiKey();
873
+ console.log('📧 [EmailAuth] API baseUrl:', baseUrl);
874
+
875
+ // Email providers can be slow on mobile networks; don't block the UI forever.
876
+ // We proceed to the code entry screen quickly and continue the send in the background.
877
+ const sendPromise = requestEmailVerification({ baseUrl, apiKey, email });
878
+ const timeoutMs = 3500;
879
+
880
+ const raced = await Promise.race([
881
+ sendPromise,
882
+ sleep(timeoutMs).then(() => ({ __timeout: true })),
883
+ ]);
884
+
885
+ console.log('📧 [EmailAuth] Race result:', raced?.__timeout ? 'TIMEOUT' : 'API_RESPONSE', raced);
886
+
887
+ if (raced && raced.__timeout) {
888
+ // Show code entry immediately.
889
+ console.log('⏱️ [EmailAuth] Timeout won - proceeding to code step while waiting for API');
890
+ setEmailSent(true);
891
+ setEmailServiceMessage("Sending your code… (check spam/promotions if it doesn't arrive)");
892
+ setStep('code');
893
+ setIsLoading(false);
894
+
895
+ // Update status when the backend responds (if still mounted).
896
+ sendPromise
897
+ .then((data) => {
898
+ console.log('✅ [EmailAuth] Background API response:', data);
899
+ if (!mountedRef.current) {
900
+ console.log('⚠️ [EmailAuth] Component unmounted, ignoring response');
901
+ return;
902
+ }
903
+ setEmailSent(data?.emailSent !== false);
904
+ setEmailServiceMessage(data?.message || 'Code sent. Check your inbox (and spam/promotions).');
905
+ })
906
+ .catch((err) => {
907
+ console.error('❌ [EmailAuth] Background API error:', err);
908
+ if (!mountedRef.current) {
909
+ console.log('⚠️ [EmailAuth] Component unmounted, ignoring error');
910
+ return;
911
+ }
912
+ setError(err?.message || 'Failed to send verification code');
913
+ });
914
+ } else {
915
+ const data = raced;
916
+ console.log('✅ [EmailAuth] API responded before timeout:', data);
917
+
918
+ // Guard against malformed data
919
+ if (!data || typeof data !== 'object') {
920
+ console.error('❌ [EmailAuth] Invalid API response format:', data);
921
+ throw new Error('Invalid response from server. Please try again.');
922
+ }
923
+
924
+ setEmailSent(data.emailSent !== false);
925
+ setEmailServiceMessage(data.message || '');
926
+ setStep('code');
927
+ setIsLoading(false);
928
+ console.log('📧 [EmailAuth] Transitioning to code step');
929
+ }
930
+ }
931
+ } catch (error) {
932
+ console.error('❌ [EmailAuth] Email request error:', error);
933
+ console.error('❌ [EmailAuth] Error details:', {
934
+ name: error?.name,
935
+ message: error?.message,
936
+ stack: error?.stack?.substring(0, 500)
937
+ });
938
+ // Ensure we always show a user-friendly error message
939
+ const errorMessage = error?.message || 'Something went wrong. Please try again.';
940
+ setError(errorMessage);
941
+ setIsLoading(false);
942
+ }
943
+ };
944
+
945
+ const handleCodeSubmit = async (e) => {
946
+ e.preventDefault();
947
+ setError('');
948
+ setIsLoading(true);
949
+
950
+ try {
951
+ if (testMode) {
952
+ const code = codeDigits.join('');
953
+ if (code === '123456' || isCodeComplete) {
954
+ setStep('success');
955
+ setTimeout(() => {
956
+ onSuccess({
957
+ email,
958
+ verified: true,
959
+ token: 'test-token',
960
+ userName: email.split('@')[0],
961
+ existingUser: false,
962
+ isNewUser: true,
963
+ flowType: 'onboarding',
964
+ accountDetails: {
965
+ email: email,
966
+ createdAt: new Date().toISOString(),
967
+ testAccount: true
968
+ }
969
+ });
970
+ }, 600);
971
+ } else {
972
+ setError('Invalid code.');
973
+ setIsLoading(false);
974
+ }
975
+ } else {
976
+ const baseUrl = (typeof window !== 'undefined' && window.onairosBaseUrl) || API_CONFIG.getBaseUrl();
977
+ const apiKey = getApiKey();
978
+ const codeToSubmit = codeDigits.join('');
979
+
980
+ if (!isCodeComplete) {
981
+ throw new Error('Please enter the full 6-digit code.');
982
+ }
983
+
984
+ const data = await verifyEmailCode({ baseUrl, apiKey, email, code: codeToSubmit.trim() });
985
+
986
+ if (!data.success) {
987
+ throw new Error(data.error || 'Verification failed');
988
+ }
989
+
990
+ // Store the JWT token for future requests
991
+ const jwtToken = data.token || data.jwtToken;
992
+ if (jwtToken) {
993
+ setUserToken(jwtToken);
994
+ }
995
+
996
+ // Show success screen IMMEDIATELY after verification (don't wait for account check)
997
+ setStep('success');
998
+
999
+ // Email-code verification responses are not always consistent about returning accountStatus,
1000
+ // especially for existing users. To keep DataRequest connected apps accurate, we perform the
1001
+ // same accountStatus lookup that Google OAuth uses.
1002
+ let accountInfo = data.user || data.accountInfo || null;
1003
+ let accountStatus = data.accountStatus || null;
1004
+ let existingUser = false;
1005
+ let isNewUser = data.isNewUser !== undefined ? data.isNewUser : true;
1006
+
1007
+ // Run account check AND minimum display timer in PARALLEL
1008
+ const accountCheckPromise = (async () => {
1009
+ try {
1010
+ const normalizedEmail = String(email || '').trim().toLowerCase();
1011
+ if (normalizedEmail && jwtToken) {
1012
+ console.log('🔍 (Email) Checking account status via /getAccountInfo/email for:', normalizedEmail);
1013
+ const accountCheckResponse = await fetch(`${baseUrl}/getAccountInfo/email`, {
1014
+ method: 'POST',
1015
+ headers: {
1016
+ 'Content-Type': 'application/json',
1017
+ 'Authorization': `Bearer ${jwtToken}`, // Use JWT from verification
1018
+ },
1019
+ body: JSON.stringify({
1020
+ Info: {
1021
+ identifier: normalizedEmail,
1022
+ },
1023
+ }),
1024
+ });
1025
+
1026
+ if (accountCheckResponse.ok) {
1027
+ const accountData = await accountCheckResponse.json();
1028
+ // Explicit "no account" response -> force onboarding for truly new users
1029
+ const noAccount =
1030
+ !accountData?.AccountInfo ||
1031
+ accountData?.AccountInfo === 'No Account Found' ||
1032
+ (typeof accountData?.accountStatus?.exists === 'boolean' && accountData.accountStatus.exists === false);
1033
+
1034
+ if (noAccount) {
1035
+ accountInfo = null;
1036
+ accountStatus = accountData?.accountStatus || { exists: false, connectedPlatforms: [] };
1037
+ existingUser = false;
1038
+ isNewUser = true;
1039
+ } else if (accountData?.AccountInfo) {
1040
+ accountInfo = accountData.AccountInfo || accountInfo;
1041
+ }
1042
+ if (accountData?.accountStatus) {
1043
+ accountStatus = accountData.accountStatus;
1044
+ }
1045
+ if (typeof accountStatus?.exists === 'boolean') {
1046
+ existingUser = accountStatus.exists;
1047
+ isNewUser = !accountStatus.exists;
1048
+ }
1049
+ } else {
1050
+ console.log('ℹ️ (Email) /getAccountInfo/email returned non-OK; continuing with verification response');
1051
+ }
1052
+ }
1053
+ } catch (accountCheckError) {
1054
+ console.warn('⚠️ (Email) Could not check account status; continuing with verification response:', accountCheckError);
1055
+ }
1056
+ })();
1057
+
1058
+ // Minimum 400ms to show success animation (same as Google OAuth)
1059
+ const minDisplayTimer = sleep(400);
1060
+
1061
+ // Wait for BOTH account check AND minimum display time
1062
+ await Promise.all([accountCheckPromise, minDisplayTimer]);
1063
+
1064
+ // Fall back if accountStatus didn't provide an exists boolean
1065
+ if (typeof accountStatus?.exists !== 'boolean') {
1066
+ existingUser = !isNewUser;
1067
+ }
1068
+
1069
+ onSuccess({
1070
+ email,
1071
+ verified: true,
1072
+ token: data.token || data.jwtToken,
1073
+ userName: data.userName || accountInfo?.userName,
1074
+ existingUser: existingUser,
1075
+ isNewUser: isNewUser,
1076
+ flowType: isNewUser ? 'onboarding' : 'dataRequest',
1077
+ accountInfo: accountInfo,
1078
+ accountStatus: accountStatus,
1079
+ accountDetails: accountInfo || {
1080
+ email: email,
1081
+ createdAt: data.createdAt || new Date().toISOString(),
1082
+ provider: 'email'
1083
+ }
1084
+ });
1085
+ }
1086
+ } catch (error) {
1087
+ console.error('Email verification error:', error);
1088
+ setError(error.message || 'Invalid code. Please try again.');
1089
+ setIsLoading(false);
1090
+ }
1091
+ };
1092
+
1093
+ /**
1094
+ * Handle pre-verified email flow
1095
+ * The developer's app already verified this email, so we skip the code step
1096
+ * and directly authenticate with the backend.
1097
+ */
1098
+ const handlePreVerifiedContinue = async () => {
1099
+ setError('');
1100
+ setIsLoading(true);
1101
+
1102
+ try {
1103
+ const normalizedEmail = email.trim().toLowerCase();
1104
+ const baseUrl = (typeof window !== 'undefined' && window.onairosBaseUrl) || API_CONFIG.getBaseUrl();
1105
+ const apiKey = getApiKey();
1106
+
1107
+ console.log('🔐 [EmailAuth] Pre-verified email flow for:', normalizedEmail);
1108
+
1109
+ // Call backend to authenticate/register with pre-verified email (NO OTP).
1110
+ // Preferred route: POST /email/pre-verified
1111
+ // Back-compat fallback: POST /email/verification { action: "preVerified" }
1112
+ let response = await fetch(`${baseUrl}/email/pre-verified`, {
1113
+ method: 'POST',
1114
+ headers: {
1115
+ 'Content-Type': 'application/json',
1116
+ 'x-api-key': apiKey,
1117
+ 'Authorization': `Bearer ${apiKey}`,
1118
+ },
1119
+ body: JSON.stringify({
1120
+ email: normalizedEmail,
1121
+ preVerified: true,
1122
+ source: 'sdk_passthrough',
1123
+ }),
1124
+ });
1125
+
1126
+ if (response.status === 404) {
1127
+ response = await fetch(`${baseUrl}/email/verification`, {
1128
+ method: 'POST',
1129
+ headers: {
1130
+ 'Content-Type': 'application/json',
1131
+ 'x-api-key': apiKey,
1132
+ 'Authorization': `Bearer ${apiKey}`,
1133
+ },
1134
+ body: JSON.stringify({
1135
+ email: normalizedEmail,
1136
+ action: 'preVerified',
1137
+ preVerified: true,
1138
+ source: 'sdk_passthrough',
1139
+ }),
1140
+ });
1141
+ }
1142
+
1143
+ // If the pre-verified endpoint doesn't exist or fails (e.g. 404),
1144
+ // do NOT fall back to OTP — the host app already verified the email.
1145
+ // If this fails, it indicates the backend doesn't support pre-verified auth
1146
+ // (or credentials are invalid). We keep the user on this screen and show
1147
+ // the backend error so integrators can fix the environment.
1148
+ if (response.status === 404 || !response.ok) {
1149
+ console.log('⚠️ [EmailAuth] Pre-verified endpoint failed or not found.', {
1150
+ status: response.status,
1151
+ ok: response.ok,
1152
+ });
1153
+
1154
+ let backendMsg = `Pre-verified sign-in failed (${response.status}).`;
1155
+ try {
1156
+ const ct = response.headers?.get?.('content-type') || '';
1157
+ if (ct.includes('application/json')) {
1158
+ const err = await response.json();
1159
+ backendMsg =
1160
+ err?.message ||
1161
+ err?.error ||
1162
+ err?.body?.message ||
1163
+ err?.body?.error ||
1164
+ backendMsg;
1165
+ } else {
1166
+ const text = await response.text();
1167
+ if (text) backendMsg = text;
1168
+ }
1169
+ } catch (_) {}
1170
+
1171
+ setIsLoading(false);
1172
+ setError(
1173
+ backendMsg ||
1174
+ 'Pre-verified sign-in failed. Please try again, or use a different email.'
1175
+ );
1176
+ // Stay on preVerified step; do not redirect to OTP/code entry.
1177
+ return;
1178
+ }
1179
+
1180
+ const data = await response.json();
1181
+ console.log('✅ [EmailAuth] Pre-verified authentication successful:', data);
1182
+
1183
+ const jwtToken = data.token || data.jwtToken;
1184
+ if (jwtToken) {
1185
+ setUserToken(jwtToken);
1186
+ }
1187
+
1188
+ // Show success step
1189
+ setStep('success');
1190
+
1191
+ // Check account status (same as regular flow)
1192
+ let accountInfo = data.user || data.accountInfo || null;
1193
+ let accountStatus = data.accountStatus || null;
1194
+ let existingUser = false;
1195
+ // Prefer backend explicit flags, but fall back to existingUser boolean if provided.
1196
+ let isNewUser =
1197
+ data.isNewUser !== undefined
1198
+ ? data.isNewUser
1199
+ : (typeof data.existingUser === 'boolean' ? !data.existingUser : true);
1200
+
1201
+ // Run account check AND minimum display timer in PARALLEL
1202
+ const accountCheckPromise = (async () => {
1203
+ try {
1204
+ if (normalizedEmail && jwtToken) {
1205
+ console.log('🔍 (Pre-verified) Checking account status...');
1206
+ const accountCheckResponse = await fetch(`${baseUrl}/getAccountInfo/email`, {
1207
+ method: 'POST',
1208
+ headers: {
1209
+ 'Content-Type': 'application/json',
1210
+ // Some deployments require the API key for this endpoint even with a valid JWT.
1211
+ ...(apiKey ? { 'x-api-key': apiKey } : {}),
1212
+ 'Authorization': `Bearer ${jwtToken}`,
1213
+ },
1214
+ body: JSON.stringify({
1215
+ Info: { identifier: normalizedEmail },
1216
+ }),
1217
+ });
1218
+
1219
+ if (accountCheckResponse.ok) {
1220
+ const accountData = await accountCheckResponse.json();
1221
+ const noAccount =
1222
+ !accountData?.AccountInfo ||
1223
+ accountData?.AccountInfo === 'No Account Found' ||
1224
+ (typeof accountData?.accountStatus?.exists === 'boolean' && accountData.accountStatus.exists === false);
1225
+
1226
+ if (noAccount) {
1227
+ accountInfo = null;
1228
+ accountStatus = accountData?.accountStatus || { exists: false, connectedPlatforms: [] };
1229
+ existingUser = false;
1230
+ isNewUser = true;
1231
+ } else if (accountData?.AccountInfo) {
1232
+ accountInfo = accountData.AccountInfo || accountInfo;
1233
+ }
1234
+ if (accountData?.accountStatus) {
1235
+ accountStatus = accountData.accountStatus;
1236
+ }
1237
+ if (typeof accountStatus?.exists === 'boolean') {
1238
+ existingUser = accountStatus.exists;
1239
+ isNewUser = !accountStatus.exists;
1240
+ }
1241
+ }
1242
+ }
1243
+ } catch (accountCheckError) {
1244
+ console.warn('⚠️ (Pre-verified) Could not check account status:', accountCheckError);
1245
+ }
1246
+ })();
1247
+
1248
+ const minDisplayTimer = sleep(400);
1249
+ await Promise.all([accountCheckPromise, minDisplayTimer]);
1250
+
1251
+ if (typeof accountStatus?.exists !== 'boolean') {
1252
+ existingUser = !isNewUser;
1253
+ }
1254
+
1255
+ onSuccess({
1256
+ email: normalizedEmail,
1257
+ verified: true,
1258
+ token: jwtToken,
1259
+ userName: data.userName || accountInfo?.userName,
1260
+ existingUser: existingUser,
1261
+ isNewUser: isNewUser,
1262
+ flowType: isNewUser ? 'onboarding' : 'dataRequest',
1263
+ accountInfo: accountInfo,
1264
+ accountStatus: accountStatus,
1265
+ preVerified: true, // Flag indicating this was pre-verified flow
1266
+ accountDetails: accountInfo || {
1267
+ email: normalizedEmail,
1268
+ createdAt: data.createdAt || new Date().toISOString(),
1269
+ provider: 'email',
1270
+ preVerified: true
1271
+ }
1272
+ });
1273
+
1274
+ } catch (error) {
1275
+ console.error('❌ Pre-verified authentication error:', error);
1276
+ setError(error.message || 'Authentication failed. Please try again.');
1277
+ setIsLoading(false);
1278
+ }
1279
+ };
1280
+
1281
+ // --- RENDER HELPERS ---
1282
+
1283
+ const renderEmailStep = () => {
1284
+ // Mobile Web Layout (OnairosEvents Style)
1285
+ if (isMobileWeb) {
1286
+ return (
1287
+ <div className="w-full flex flex-col h-full px-6 pt-8">
1288
+ <div className="flex-1 flex flex-col">
1289
+ {/* Onairos Logo with raised border */}
1290
+ {!hideOnairosLogo && (
1291
+ <div className="mb-4 w-full flex justify-center">
1292
+ <div
1293
+ className="w-16 h-16 flex items-center justify-center"
1294
+ style={{
1295
+ borderRadius: '12px',
1296
+ boxShadow: '0 2px 8px -2px rgba(0, 0, 0, 0.12), 0 1px 3px -1px rgba(0, 0, 0, 0.08)',
1297
+ }}
1298
+ >
1299
+ <img
1300
+ className="w-full h-full object-cover"
1301
+ src="https://blasianhokage.sirv.com/Images/Logo%20V1.png"
1302
+ alt="Onairos"
1303
+ style={{ borderRadius: '12px' }}
1304
+ />
1305
+ </div>
1306
+ </div>
1307
+ )}
1308
+ <div className="mb-8 w-full text-left">
1309
+ <h1 className="text-2xl font-bold mb-2 leading-tight" style={{ fontFamily: 'IBM Plex Sans, system-ui, sans-serif', color: isGlass ? '#FFFFFF' : '#000000' }}>
1310
+ {usePartnerCopy ? partnerWelcomeCopy : 'Build your Onairos persona to own your digital identity'}
1311
+ </h1>
1312
+ {!usePartnerCopy && (
1313
+ <p className="text-base" style={{ fontFamily: 'Inter, system-ui, sans-serif', color: isGlass ? 'rgba(255, 255, 255, 0.7)' : '#62646C' }}>
1314
+ Sign in or create an account
1315
+ </p>
1316
+ )}
1317
+ </div>
1318
+
1319
+ {/* Email Input */}
1320
+ <div className="mb-4 w-full">
1321
+ <input
1322
+ type="email"
1323
+ value={email}
1324
+ onChange={(e) => setEmail(e.target.value)}
1325
+ placeholder="Enter your email"
1326
+ className="w-full outline-none transition-all placeholder-gray-500 bg-[#F5F5F5] rounded-lg border border-[#E5E5E5] text-[#1F242F]"
1327
+ style={{
1328
+ height: '56px',
1329
+ paddingLeft: 16,
1330
+ paddingRight: 16,
1331
+ fontSize: 16,
1332
+ fontFamily: 'Inter, system-ui, sans-serif',
1333
+ color: '#000000',
1334
+ WebkitTextFillColor: '#000000'
1335
+ }}
1336
+ onKeyDown={(e) => { if (e.key === 'Enter') handleEmailSubmit(e); }}
1337
+ disabled={isLoading}
1338
+ autoFocus={!isMobileWeb}
1339
+ />
1340
+ </div>
1341
+
1342
+ {/* Continue Button (Below Email Input) */}
1343
+ <div className="mb-6 w-full">
1344
+ <PrimaryButton
1345
+ label={isLoading ? 'Loading...' : 'Continue'}
1346
+ onClick={handleEmailSubmit}
1347
+ disabled={isLoading || !email.trim()}
1348
+ loading={isLoading}
1349
+ className="!text-white w-full h-14 rounded-full"
1350
+ textStyle={{ color: '#FFFFFF' }}
1351
+ />
1352
+ </div>
1353
+
1354
+ {/* Divider */}
1355
+ <div className="flex items-center gap-4 mb-6">
1356
+ <div className="h-[1px] bg-[#E5E5E5] flex-1" />
1357
+ <span className="text-sm text-[#86888E]" style={{ fontFamily: 'Inter, system-ui, sans-serif' }}>Or</span>
1358
+ <div className="h-[1px] bg-[#E5E5E5] flex-1" />
1359
+ </div>
1360
+
1361
+ {/* Google Button */}
1362
+ <div className="mb-8 w-full google-button-container" ref={googleContainerRef}>
1363
+ {/*
1364
+ Google Sign-In logic:
1365
+ 1. Capacitor + custom googleClientIds + native plugin → Native SDK
1366
+ 2. Capacitor (default) → System browser with Onairos's web client ID
1367
+ 3. Web → @react-oauth/google widget
1368
+ */}
1369
+ {shouldUseNativeGoogleAuth ? (
1370
+ /* Native Google Sign-In (developer provided their own client IDs) */
1371
+ <button
1372
+ type="button"
1373
+ onClick={handleNativeGoogleSignIn}
1374
+ disabled={isLoading}
1375
+ className="w-full h-14 rounded-full border border-[#DADCE0] bg-white shadow-sm flex items-center justify-center gap-3"
1376
+ style={{
1377
+ fontFamily: 'Inter, system-ui, sans-serif',
1378
+ opacity: isLoading ? 0.6 : 1,
1379
+ }}
1380
+ >
1381
+ <svg width="20" height="20" viewBox="0 0 24 24" aria-hidden="true">
1382
+ <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
1383
+ <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
1384
+ <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/>
1385
+ <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/>
1386
+ </svg>
1387
+ <span className="text-[15px] font-medium text-[#3C4043]">
1388
+ {isLoading ? 'Signing in...' : 'Continue with Google'}
1389
+ </span>
1390
+ </button>
1391
+ ) : shouldUseCapacitorBrowser ? (
1392
+ /* Capacitor default: System browser OAuth with Onairos's web client ID */
1393
+ <button
1394
+ type="button"
1395
+ onClick={handleCapacitorBrowserGoogleSignIn}
1396
+ disabled={isLoading}
1397
+ className="w-full h-14 rounded-full border border-[#DADCE0] bg-white shadow-sm flex items-center justify-center gap-3"
1398
+ style={{
1399
+ fontFamily: 'Inter, system-ui, sans-serif',
1400
+ opacity: isLoading ? 0.6 : 1,
1401
+ }}
1402
+ >
1403
+ <svg width="20" height="20" viewBox="0 0 24 24" aria-hidden="true">
1404
+ <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
1405
+ <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
1406
+ <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/>
1407
+ <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/>
1408
+ </svg>
1409
+ <span className="text-[15px] font-medium text-[#3C4043]">
1410
+ {isLoading ? 'Signing in...' : 'Continue with Google'}
1411
+ </span>
1412
+ </button>
1413
+ ) : (
1414
+ /* Web: @react-oauth/google widget */
1415
+ <>
1416
+ <div style={{ display: googleWidgetPresent ? 'block' : 'none', width: '100%' }}>
1417
+ <GoogleLogin
1418
+ onSuccess={handleGoogleSuccess}
1419
+ onError={handleGoogleError}
1420
+ text="continue_with"
1421
+ theme="outline"
1422
+ shape="pill"
1423
+ size="large"
1424
+ width="100%"
1425
+ disabled={isLoading}
1426
+ />
1427
+ </div>
1428
+
1429
+ <div style={{ display: googleWidgetPresent ? 'none' : 'block', width: '100%' }}>
1430
+ <button
1431
+ type="button"
1432
+ onClick={handleGoogleUnavailable}
1433
+ disabled={isLoading}
1434
+ className="w-full h-14 rounded-full border border-[#DADCE0] bg-white shadow-sm flex items-center justify-center gap-3"
1435
+ style={{
1436
+ fontFamily: 'Inter, system-ui, sans-serif',
1437
+ opacity: isLoading ? 0.6 : 1,
1438
+ }}
1439
+ >
1440
+ <svg width="20" height="20" viewBox="0 0 24 24" aria-hidden="true">
1441
+ <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
1442
+ <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
1443
+ <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/>
1444
+ <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/>
1445
+ </svg>
1446
+ <span className="text-[15px] font-medium text-[#3C4043]">Continue with Google</span>
1447
+ </button>
1448
+ </div>
1449
+ </>
1450
+ )}
1451
+ <style>{`
1452
+ .google-button-container {
1453
+ width: 100% !important;
1454
+ min-width: 100% !important;
1455
+ max-width: 100% !important;
1456
+ }
1457
+ .google-button-container > div {
1458
+ width: 100% !important;
1459
+ min-width: 100% !important;
1460
+ max-width: 100% !important;
1461
+ }
1462
+ .google-button-container iframe {
1463
+ width: 100% !important;
1464
+ min-width: 100% !important;
1465
+ max-width: 100% !important;
1466
+ }
1467
+ `}</style>
1468
+ </div>
1469
+
1470
+ {/* Keep Google-in-WebView messaging non-red; WKWebView blocking is expected on iOS. */}
1471
+ {!!googleHint && (
1472
+ <div className="mb-4">
1473
+ <p className="text-xs text-center text-gray-500" style={{ fontFamily: 'Inter, system-ui, sans-serif' }}>
1474
+ {googleHint}
1475
+ </p>
1476
+ </div>
1477
+ )}
1478
+
1479
+ {/* Keep real errors (email/code/backend) as errors */}
1480
+ {error && (
1481
+ <div className="mb-6">
1482
+ <p className="text-sm text-center" style={{ color: COLORS.error }}>{error}</p>
1483
+ </div>
1484
+ )}
1485
+ </div>
1486
+ </div>
1487
+ );
1488
+ }
1489
+
1490
+ // Desktop Layout (Centered Card)
1491
+ return (
1492
+ <div className="flex flex-col h-full items-center justify-center p-6 text-center max-w-sm mx-auto">
1493
+ {/* Onairos Logo with raised border */}
1494
+ {!hideOnairosLogo && (
1495
+ <div className="mb-6">
1496
+ <div
1497
+ className="w-20 h-20 flex items-center justify-center"
1498
+ style={{
1499
+ borderRadius: '16px',
1500
+ boxShadow: '0 2px 8px -2px rgba(0, 0, 0, 0.12), 0 1px 3px -1px rgba(0, 0, 0, 0.08)',
1501
+ }}
1502
+ >
1503
+ <img
1504
+ className="w-full h-full object-cover"
1505
+ src="https://blasianhokage.sirv.com/Images/Logo%20V1.png"
1506
+ alt="Onairos"
1507
+ style={{ borderRadius: '16px' }}
1508
+ />
1509
+ </div>
1510
+ </div>
1511
+ )}
1512
+ <h1 className={`text-2xl font-bold mb-2 ${isGlass ? 'text-white' : 'text-gray-900'}`} style={{ fontFamily: 'IBM Plex Sans, system-ui, sans-serif' }}>
1513
+ {usePartnerCopy ? partnerWelcomeCopy : 'Sign in with Onairos'}
1514
+ </h1>
1515
+ {!usePartnerCopy && (
1516
+ <p className={`mb-8 ${isGlass ? 'text-white/70' : 'text-gray-600'}`} style={{ fontFamily: 'Inter, system-ui, sans-serif' }}>
1517
+ {"You're about to share your Onairos profile with this app."}
1518
+ </p>
1519
+ )}
1520
+
1521
+ <div className="w-full space-y-4">
1522
+ <input
1523
+ type="email"
1524
+ value={email}
1525
+ onChange={(e) => setEmail(e.target.value)}
1526
+ placeholder="name@example.com"
1527
+ className={`w-full px-4 py-2 border rounded focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none ${isGlass ? 'border-white/30 placeholder-white/50' : 'border-gray-300'}`}
1528
+ style={{ color: isGlass ? '#FFFFFF' : '#000000', WebkitTextFillColor: isGlass ? '#FFFFFF' : '#000000', backgroundColor: isGlass ? 'rgba(255,255,255,0.1)' : undefined, fontFamily: 'Inter, system-ui, sans-serif' }}
1529
+ onKeyDown={(e) => { if (e.key === 'Enter') handleEmailSubmit(e); }}
1530
+ disabled={isLoading}
1531
+ autoFocus={!isMobileWeb}
1532
+ />
1533
+ <button
1534
+ onClick={handleEmailSubmit}
1535
+ disabled={isLoading || !email.trim()}
1536
+ className={`w-full font-medium rounded transition-colors disabled:opacity-50 ${isGlass ? 'bg-white/15 border border-white/20 text-white hover:bg-white/25' : 'bg-black text-white hover:bg-gray-800'}`}
1537
+ style={{ fontFamily: 'Inter, system-ui, sans-serif', height: '44px', minHeight: '44px' }}
1538
+ >
1539
+ {isLoading ? 'Sending...' : 'Continue with Email'}
1540
+ </button>
1541
+
1542
+ <div className="relative flex py-2 items-center">
1543
+ <div className={`flex-grow border-t ${isGlass ? 'border-white/20' : 'border-gray-300'}`}></div>
1544
+ <span className={`flex-shrink-0 mx-4 text-sm ${isGlass ? 'text-white/50' : 'text-gray-400'}`} style={{ fontFamily: 'Inter, system-ui, sans-serif' }}>Or</span>
1545
+ <div className={`flex-grow border-t ${isGlass ? 'border-white/20' : 'border-gray-300'}`}></div>
1546
+ </div>
1547
+
1548
+ <div className="google-button-container-desktop">
1549
+ {/*
1550
+ Google Sign-In logic (desktop layout):
1551
+ 1. Capacitor + custom googleClientIds + native plugin → Native SDK
1552
+ 2. Capacitor (default) → System browser with Onairos's web client ID
1553
+ 3. Web → @react-oauth/google widget
1554
+ */}
1555
+ {shouldUseNativeGoogleAuth ? (
1556
+ <button
1557
+ type="button"
1558
+ onClick={handleNativeGoogleSignIn}
1559
+ disabled={isLoading}
1560
+ className="w-full h-11 rounded border border-gray-300 bg-white shadow-sm flex items-center justify-center gap-3 hover:bg-gray-50 transition-colors"
1561
+ style={{
1562
+ fontFamily: 'Inter, system-ui, sans-serif',
1563
+ opacity: isLoading ? 0.6 : 1,
1564
+ }}
1565
+ >
1566
+ <svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true">
1567
+ <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
1568
+ <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
1569
+ <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/>
1570
+ <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/>
1571
+ </svg>
1572
+ <span className="text-sm font-medium text-gray-700">
1573
+ {isLoading ? 'Signing in...' : 'Continue with Google'}
1574
+ </span>
1575
+ </button>
1576
+ ) : shouldUseCapacitorBrowser ? (
1577
+ <button
1578
+ type="button"
1579
+ onClick={handleCapacitorBrowserGoogleSignIn}
1580
+ disabled={isLoading}
1581
+ className="w-full h-11 rounded border border-gray-300 bg-white shadow-sm flex items-center justify-center gap-3 hover:bg-gray-50 transition-colors"
1582
+ style={{
1583
+ fontFamily: 'Inter, system-ui, sans-serif',
1584
+ opacity: isLoading ? 0.6 : 1,
1585
+ }}
1586
+ >
1587
+ <svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true">
1588
+ <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
1589
+ <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
1590
+ <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/>
1591
+ <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/>
1592
+ </svg>
1593
+ <span className="text-sm font-medium text-gray-700">
1594
+ {isLoading ? 'Signing in...' : 'Continue with Google'}
1595
+ </span>
1596
+ </button>
1597
+ ) : (
1598
+ <GoogleLogin
1599
+ onSuccess={handleGoogleSuccess}
1600
+ onError={handleGoogleError}
1601
+ text="continue_with"
1602
+ size="large"
1603
+ width="100%"
1604
+ disabled={isLoading}
1605
+ />
1606
+ )}
1607
+ <style>{`
1608
+ .google-button-container-desktop {
1609
+ width: 100% !important;
1610
+ min-width: 100% !important;
1611
+ max-width: 100% !important;
1612
+ }
1613
+ .google-button-container-desktop > div {
1614
+ width: 100% !important;
1615
+ min-width: 100% !important;
1616
+ max-width: 100% !important;
1617
+ }
1618
+ .google-button-container-desktop iframe {
1619
+ width: 100% !important;
1620
+ min-width: 100% !important;
1621
+ max-width: 100% !important;
1622
+ }
1623
+ `}</style>
1624
+ </div>
1625
+
1626
+ {error && <p className="mt-2 text-sm text-red-500" style={{ fontFamily: 'Inter, system-ui, sans-serif' }}>{error}</p>}
1627
+ </div>
1628
+ </div>
1629
+ );
1630
+ };
1631
+
1632
+ const renderCodeStep = () => (
1633
+ <div className="w-full flex flex-col h-full px-6 pt-16 text-center">
1634
+ <h1 className="text-2xl font-bold mb-2" style={{ fontFamily: 'IBM Plex Sans, system-ui, sans-serif', color: isGlass ? '#FFFFFF' : COLORS.textPrimary }}>
1635
+ Enter verification code
1636
+ </h1>
1637
+ <p className="mb-6" style={{ fontFamily: 'Inter, system-ui, sans-serif', color: isGlass ? 'rgba(255,255,255,0.7)' : COLORS.textSecondary }}>
1638
+ {emailSent ? `We've sent a 6-digit code to ${email}` : `Code generated for ${email}`}
1639
+ </p>
1640
+
1641
+ <div className="flex justify-center space-x-3 mb-8">
1642
+ {Array.from({ length: 6 }, (_, index) => (
1643
+ <input
1644
+ key={index}
1645
+ type="text"
1646
+ inputMode="numeric"
1647
+ maxLength={index === 0 ? 6 : 1}
1648
+ autoComplete={index === 0 ? 'one-time-code' : 'off'}
1649
+ name={index === 0 ? 'onairos-email-otp' : undefined}
1650
+ value={codeDigits[index] || ''}
1651
+ onChange={(e) => {
1652
+ const raw = e.target.value || '';
1653
+ const val = String(raw).replace(/\D/g, '');
1654
+
1655
+ if (val.length > 1) {
1656
+ applyVerificationDigits(index, val);
1657
+ return;
1658
+ }
1659
+
1660
+ const next = [...codeDigits];
1661
+ next[index] = val;
1662
+ setCodeDigits(next);
1663
+ if (val && index < 5) e.target.parentElement.children[index + 1].focus();
1664
+ }}
1665
+ onPaste={(e) => {
1666
+ const text = e.clipboardData?.getData('text') || '';
1667
+ const digits = String(text).replace(/\D/g, '');
1668
+ if (!digits) return;
1669
+ e.preventDefault();
1670
+ applyVerificationDigits(index, digits);
1671
+ }}
1672
+ onKeyDown={(e) => {
1673
+ if (e.key === 'Backspace' && !codeDigits[index] && index > 0) {
1674
+ e.target.parentElement.children[index - 1].focus();
1675
+ }
1676
+ }}
1677
+ className={`onairos-verification-digit w-12 h-12 border rounded-lg text-center text-lg font-medium focus:ring-2 focus:ring-blue-500 outline-none ${isGlass ? 'border-white/30' : ''}`}
1678
+ style={{ borderColor: isGlass ? 'rgba(255,255,255,0.3)' : COLORS.border, backgroundColor: isGlass ? 'rgba(255,255,255,0.1)' : '#F5F5F5', color: isGlass ? '#FFFFFF' : '#000000', WebkitTextFillColor: isGlass ? '#FFFFFF' : '#000000', caretColor: isGlass ? '#FFFFFF' : '#000000' }}
1679
+ />
1680
+ ))}
1681
+ </div>
1682
+
1683
+ {error && <p className="mb-6 text-sm text-red-500" style={{ fontFamily: 'Inter, system-ui, sans-serif' }}>{error}</p>}
1684
+
1685
+ <div className="max-w-sm mx-auto w-full">
1686
+ <PrimaryButton
1687
+ label="Continue"
1688
+ onClick={handleCodeSubmit}
1689
+ loading={isLoading}
1690
+ disabled={isLoading || !isCodeComplete}
1691
+ className="!text-white"
1692
+ textStyle={{ color: '#FFFFFF' }}
1693
+ />
1694
+ </div>
1695
+
1696
+ <button
1697
+ onClick={() => { resetCodeDigits(); setStep('email'); }}
1698
+ className={`mt-6 text-sm font-medium ${isGlass ? 'text-white/60' : 'text-gray-500'}`}
1699
+ style={{ fontFamily: 'Inter, system-ui, sans-serif' }}
1700
+ >
1701
+ Use a different email
1702
+ </button>
1703
+ </div>
1704
+ );
1705
+
1706
+ /**
1707
+ * Render the pre-verified email step
1708
+ * Shows masked email with a checkmark, allowing user to continue without code entry
1709
+ */
1710
+ const renderPreVerifiedStep = () => {
1711
+ const maskedEmail = maskEmail(email);
1712
+
1713
+ return (
1714
+ <div className="w-full flex flex-col h-full px-6 pt-14 text-center">
1715
+ {/* Onairos Logo */}
1716
+ {!hideOnairosLogo && (
1717
+ <div className="mb-6 w-full flex justify-center">
1718
+ <div
1719
+ className="w-16 h-16 flex items-center justify-center"
1720
+ style={{
1721
+ borderRadius: '16px',
1722
+ boxShadow: '0 2px 10px rgba(17,24,39,0.10)',
1723
+ }}
1724
+ >
1725
+ <img
1726
+ className="w-full h-full object-cover"
1727
+ src="https://blasianhokage.sirv.com/Images/Logo%20V1.png"
1728
+ alt="Onairos"
1729
+ style={{ borderRadius: '16px' }}
1730
+ />
1731
+ </div>
1732
+ </div>
1733
+ )}
1734
+
1735
+ <h1
1736
+ className="text-3xl font-bold mb-2"
1737
+ style={{
1738
+ fontFamily: 'IBM Plex Sans, system-ui, sans-serif',
1739
+ color: COLORS.textPrimary,
1740
+ letterSpacing: '-0.02em',
1741
+ }}
1742
+ >
1743
+ Welcome
1744
+ </h1>
1745
+ <p
1746
+ className="mb-8"
1747
+ style={{
1748
+ fontFamily: 'Inter, system-ui, sans-serif',
1749
+ color: COLORS.textSecondary,
1750
+ fontSize: 15,
1751
+ }}
1752
+ >
1753
+ Your email is verified by the app you’re using.
1754
+ </p>
1755
+
1756
+ <div className="mb-8 w-full flex justify-center">
1757
+ <div
1758
+ className="relative flex items-center gap-3 px-5 py-4 rounded-3xl w-full max-w-sm"
1759
+ style={{
1760
+ background: 'linear-gradient(180deg, #FFFFFF 0%, #F9FAFB 100%)',
1761
+ border: '1px solid rgba(17,24,39,0.10)',
1762
+ boxShadow: '0 14px 34px rgba(17,24,39,0.10)',
1763
+ }}
1764
+ >
1765
+ <div
1766
+ aria-hidden="true"
1767
+ className="absolute inset-y-0 left-0 w-1.5 rounded-l-3xl"
1768
+ style={{
1769
+ background: 'linear-gradient(180deg, rgba(59,130,246,0.95) 0%, rgba(17,24,39,0.95) 100%)',
1770
+ }}
1771
+ />
1772
+ <div
1773
+ className="flex-shrink-0 w-10 h-10 rounded-xl flex items-center justify-center"
1774
+ style={{
1775
+ backgroundColor: '#FFFFFF',
1776
+ border: '1px solid rgba(17,24,39,0.08)',
1777
+ }}
1778
+ >
1779
+ <Mail className="w-5 h-5" style={{ color: '#0B1220' }} />
1780
+ </div>
1781
+ <div className="flex-1 text-left">
1782
+ <p className="text-sm font-semibold truncate" style={{ fontFamily: 'Inter, system-ui, sans-serif', color: '#111827' }}>
1783
+ {maskedEmail}
1784
+ </p>
1785
+ <div className="mt-1">
1786
+ <span
1787
+ className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold"
1788
+ style={{
1789
+ fontFamily: 'Inter, system-ui, sans-serif',
1790
+ backgroundColor: 'rgba(17,24,39,0.92)',
1791
+ color: '#FFFFFF',
1792
+ border: '1px solid rgba(255,255,255,0.10)',
1793
+ }}
1794
+ >
1795
+ <span
1796
+ aria-hidden="true"
1797
+ className="inline-block w-1.5 h-1.5 rounded-full"
1798
+ style={{ backgroundColor: COLORS.info }}
1799
+ />
1800
+ Verified by app
1801
+ </span>
1802
+ </div>
1803
+ </div>
1804
+ </div>
1805
+ </div>
1806
+
1807
+ <div className="max-w-sm mx-auto w-full mb-6">
1808
+ <PrimaryButton
1809
+ label={isLoading ? 'Connecting...' : 'Continue'}
1810
+ onClick={handlePreVerifiedContinue}
1811
+ disabled={isLoading}
1812
+ loading={isLoading}
1813
+ className="!text-white w-full"
1814
+ textStyle={{ color: '#FFFFFF' }}
1815
+ />
1816
+ </div>
1817
+
1818
+ <button
1819
+ onClick={() => {
1820
+ setEmail('');
1821
+ setStep('email');
1822
+ }}
1823
+ className="text-sm text-gray-500 font-medium hover:text-gray-700 transition-colors"
1824
+ style={{ fontFamily: 'Inter, system-ui, sans-serif' }}
1825
+ disabled={isLoading}
1826
+ >
1827
+ Use a different email
1828
+ </button>
1829
+
1830
+ {/* Error message */}
1831
+ {error && (
1832
+ <div className="mt-4">
1833
+ <p className="text-sm text-center" style={{ color: COLORS.error }}>{error}</p>
1834
+ </div>
1835
+ )}
1836
+ </div>
1837
+ );
1838
+ };
1839
+
1840
+ const renderSuccessStep = () => (
1841
+ <div className="w-full flex flex-col items-center pt-16 px-12 space-y-6">
1842
+ <div className="flex items-center justify-center w-16 h-16 rounded-full bg-green-100">
1843
+ <Check className="w-8 h-8 text-green-600" />
1844
+ </div>
1845
+ <div className="text-center">
1846
+ <h2 className="text-xl font-semibold text-gray-900" style={{ fontFamily: 'IBM Plex Sans, system-ui, sans-serif' }}>Email verified!</h2>
1847
+ <p className="text-gray-500" style={{ fontFamily: 'Inter, system-ui, sans-serif' }}>Setting up your account...</p>
1848
+ </div>
1849
+ <div className="animate-spin h-8 w-8 border-2 border-blue-600 rounded-full border-t-transparent"></div>
1850
+ </div>
1851
+ );
1852
+
1853
+ return (
1854
+ <div className="w-full h-full">
1855
+ <div key={step} className="onairos-screen-transition w-full h-full">
1856
+ {step === 'preVerified' && renderPreVerifiedStep()}
1857
+ {step === 'email' && renderEmailStep()}
1858
+ {step === 'code' && renderCodeStep()}
1859
+ {step === 'success' && renderSuccessStep()}
1860
+ </div>
1861
+ </div>
1862
+ );
1863
+ }
1864
+
1865
+ // Memoize to prevent remounting when parent re-renders
1866
+ // This is CRITICAL - without it, parent state changes cause EmailAuth to remount,
1867
+ // which resets the internal 'step' state from 'code' back to 'email'
1868
+ const EmailAuth = memo(EmailAuthComponent);
1869
+ EmailAuth.displayName = 'EmailAuth';
1870
+
1871
+ export default EmailAuth;