@onairosofficial/onairos-capacitor 0.1.0 → 0.1.1

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