@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,1055 @@
1
+ import React, { useState, useEffect, useCallback, useMemo } from "react";
2
+ import { API_CONFIG } from '../config/api-config';
3
+ import SessionUserBar from './SessionUserBar.jsx';
4
+ import { PERPLEXITY_LOGO_DATA_URI } from './PerplexityLogo.jsx';
5
+ import OnairosLogo from '../assets/NewLogo.png';
6
+ // import personaImg from "../assets/persona.png";
7
+ // Use remote URL to avoid 403 Forbidden on local asset during dev/prod mismatch
8
+ const personaImg = "https://anushkasirv.sirv.com/persona.jpg";
9
+
10
+ /* -------------------------
11
+ ICON COMPONENTS
12
+ -------------------------- */
13
+ const Icon = ({ type, isGlass }) => {
14
+ const base = `w-4 h-4 ${isGlass ? 'text-white/70' : 'text-gray-700'}`;
15
+
16
+ switch (type) {
17
+ case "User":
18
+ return (
19
+ <svg className={base} viewBox="0 0 24 24" fill="currentColor">
20
+ <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
21
+ </svg>
22
+ );
23
+ case "Memory":
24
+ return (
25
+ <svg className={base} viewBox="0 0 24 24" fill="currentColor">
26
+ <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/>
27
+ </svg>
28
+ );
29
+ case "Grid3X3":
30
+ return (
31
+ <svg className={base} viewBox="0 0 24 24" fill="currentColor">
32
+ <path d="M3 13h8V3H3v10zm0 8h8v-6H3v6zm10 0h8V11h-8v10zm0-18v6h8V3h-8z"/>
33
+ </svg>
34
+ );
35
+ case "Brain":
36
+ return (
37
+ <svg className={base} viewBox="0 0 24 24" fill="currentColor">
38
+ <path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm3.5-9c.83 0 1.5-.67 1.5-1.5S16.33 8 15.5 8 14 8.67 14 9.5s.67 1.5 1.5 1.5zm-7 0c.83 0 1.5-.67 1.5-1.5S9.33 8 8.5 8 7 8.67 7 9.5 7.67 11 8.5 11zm3.5 6.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z"/>
39
+ </svg>
40
+ );
41
+ default:
42
+ return null;
43
+ }
44
+ };
45
+
46
+ /* -------------------------
47
+ TOGGLE (soft apple style)
48
+ -------------------------- */
49
+ const DataTypeToggle = React.memo(({ dataType, enabled, onToggle, isNative, isGlass }) => {
50
+ const isDisabled = dataType.required || dataType.disabled;
51
+
52
+ const handle = useCallback(() => {
53
+ if (isDisabled) return;
54
+ onToggle(dataType.id, !enabled);
55
+ }, [dataType.id, enabled, isDisabled, onToggle]);
56
+
57
+ const title = useMemo(() => {
58
+ if (dataType.required) return 'Required - cannot be disabled';
59
+ if (dataType.disabled && dataType.disabledReason) return dataType.disabledReason;
60
+ return '';
61
+ }, [dataType.disabled, dataType.disabledReason, dataType.required]);
62
+
63
+ const checkboxVisualStyle = useMemo(() => ({
64
+ width: 20,
65
+ height: 20,
66
+ borderRadius: 6,
67
+ borderWidth: 2,
68
+ borderStyle: 'solid',
69
+ borderColor: dataType.disabled
70
+ ? (isGlass ? 'rgba(255,255,255,0.28)' : '#D1D5DB')
71
+ : enabled
72
+ ? (isGlass ? 'rgba(255,255,255,0.55)' : '#111827')
73
+ : (isGlass ? 'rgba(255,255,255,0.75)' : '#4B5563'),
74
+ backgroundColor: dataType.disabled
75
+ ? (isGlass ? 'rgba(255,255,255,0.06)' : '#F3F4F6')
76
+ : enabled
77
+ ? (isGlass ? 'rgba(255,255,255,0.22)' : '#111827')
78
+ : '#FFFFFF',
79
+ boxShadow: enabled || dataType.disabled
80
+ ? '0 1px 2px rgba(17,24,39,0.12)'
81
+ : `0 0 0 1px ${isGlass ? 'rgba(255,255,255,0.28)' : 'rgba(17,24,39,0.16)'}, inset 0 0 0 1px rgba(255,255,255,0.85)`,
82
+ outline: 'none',
83
+ opacity: 1,
84
+ WebkitAppearance: 'none',
85
+ appearance: 'none',
86
+ WebkitTextFillColor: 'currentColor',
87
+ }), [dataType.disabled, enabled, isGlass]);
88
+
89
+ return (
90
+ <button
91
+ onClick={handle}
92
+ className={`
93
+ w-full flex items-center justify-between
94
+ py-2.5 px-3
95
+ ${isGlass ? 'bg-white/10' : 'bg-white/40 backdrop-blur-sm'}
96
+ ${isDisabled ? 'cursor-not-allowed opacity-50' : isGlass ? 'hover:bg-white/20 cursor-pointer' : 'hover:bg-white/70 cursor-pointer'}
97
+ transition rounded-xl shadow-sm
98
+ `}
99
+ style={{ maxWidth: '100%', minWidth: 0, boxSizing: 'border-box' }}
100
+ title={title}
101
+ disabled={dataType.disabled}
102
+ >
103
+ <div className="flex items-center gap-2.5 flex-1 min-w-0">
104
+ <div className={`w-7 h-7 flex items-center justify-center rounded-full flex-shrink-0 ${dataType.disabled ? (isGlass ? 'bg-white/5' : 'bg-gray-200') : (isGlass ? 'bg-white/10' : 'bg-gray-100')}`}>
105
+ <Icon type={dataType.icon} isGlass={isGlass} />
106
+ </div>
107
+ <div className="flex flex-col items-start min-w-0">
108
+ <span className={`${isNative ? 'text-[14px]' : 'text-[13px]'} font-medium ${dataType.disabled ? (isGlass ? 'text-white/40' : 'text-gray-400') : (isGlass ? 'text-white' : 'text-gray-900')}`} style={{ fontFamily: 'Inter, system-ui, sans-serif' }}>
109
+ {dataType.name}
110
+ {dataType.required && <span className={`ml-1.5 text-[11px] ${isGlass ? 'text-white/50' : 'text-gray-500'}`}>(Required)</span>}
111
+ </span>
112
+ {dataType.description && (
113
+ <span className={`text-[11px] leading-tight ${dataType.disabled ? (isGlass ? 'text-white/30' : 'text-gray-400') : (isGlass ? 'text-white/50' : 'text-gray-500')}`} style={{ fontFamily: 'Inter, system-ui, sans-serif' }}>
114
+ {dataType.description}
115
+ </span>
116
+ )}
117
+ </div>
118
+ </div>
119
+
120
+ <div
121
+ className={`w-5 h-5 rounded-md border-2 flex items-center justify-center shadow-sm flex-shrink-0 ml-2
122
+ transition
123
+ ${dataType.disabled
124
+ ? isGlass ? "bg-white/5 border-white/20" : "bg-gray-100 border-gray-300"
125
+ : enabled
126
+ ? isGlass ? "bg-white/20 border-white/30" : "bg-gray-900 border-gray-900"
127
+ : isGlass ? "bg-transparent border-white/60" : "bg-white border-gray-500"
128
+ }`}
129
+ style={checkboxVisualStyle}
130
+ >
131
+ {enabled && !dataType.disabled && (
132
+ <svg className="w-3 h-3 text-white" style={{ color: '#FFFFFF', WebkitTextFillColor: '#FFFFFF' }} viewBox="0 0 20 20" fill="currentColor">
133
+ <path d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"/>
134
+ </svg>
135
+ )}
136
+ </div>
137
+ </button>
138
+ );
139
+ });
140
+
141
+ DataTypeToggle.displayName = 'DataTypeToggle';
142
+
143
+ /* -------------------------
144
+ MAIN COMPONENT
145
+ -------------------------- */
146
+
147
+ /** Sources that can back “Raw Memories” (LLMs + retail/media raw pipelines). */
148
+ const RAW_MEMORY_SOURCE_KEYS = new Set([
149
+ 'chatgpt',
150
+ 'claude',
151
+ 'gemini',
152
+ 'grok',
153
+ 'perplexity',
154
+ 'netflix',
155
+ 'spotify',
156
+ 'sephora',
157
+ ]);
158
+
159
+ const LLM_RAW_MEMORY_SOURCE_KEYS = new Set([
160
+ 'chatgpt',
161
+ 'claude',
162
+ 'gemini',
163
+ 'grok',
164
+ 'perplexity',
165
+ ]);
166
+
167
+ const X_LOGO_SVG =
168
+ 'data:image/svg+xml,%3Csvg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"%3E%3Cpath fill="%23000000" d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/%3E%3C/svg%3E';
169
+
170
+ /** Logos for “connected / add connection” row on the data request sheet */
171
+ const DATA_REQUEST_PLATFORM_LOGOS = {
172
+ Instagram: 'https://upload.wikimedia.org/wikipedia/commons/a/a5/Instagram_icon.png',
173
+ YouTube: 'https://upload.wikimedia.org/wikipedia/commons/0/09/YouTube_full-color_icon_%282017%29.svg',
174
+ LinkedIn: 'https://upload.wikimedia.org/wikipedia/commons/c/ca/LinkedIn_logo_initials.png',
175
+ Reddit: 'https://upload.wikimedia.org/wikipedia/en/b/bd/Reddit_Logo_Icon.svg',
176
+ Pinterest: 'https://upload.wikimedia.org/wikipedia/commons/0/08/Pinterest-logo.png',
177
+ Sephora: 'https://www.sephora.com/favicon.ico',
178
+ GitHub: 'https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png',
179
+ Facebook: 'https://upload.wikimedia.org/wikipedia/commons/5/51/Facebook_f_logo_%282019%29.svg',
180
+ Gmail: 'https://upload.wikimedia.org/wikipedia/commons/7/7e/Gmail_icon_%282020%29.svg',
181
+ X: X_LOGO_SVG,
182
+ Twitter: X_LOGO_SVG,
183
+ ChatGPT: 'https://anushkasirv.sirv.com/openai.png',
184
+ Claude: 'https://anushkasirv.sirv.com/claude-color.png',
185
+ Gemini: 'https://anushkasirv.sirv.com/gemini-color.png',
186
+ Grok: 'https://anushkasirv.sirv.com/grok.png',
187
+ Perplexity: PERPLEXITY_LOGO_DATA_URI,
188
+ TikTok:
189
+ 'data:image/svg+xml,%3Csvg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"%3E%3Cpath fill="%23010101" d="M14.5 3.5v10.34a3.84 3.84 0 1 1-3.84-3.84c.29 0 .57.03.84.09v2.18a1.7 1.7 0 1 0 .8 1.44V3.5h2.2a3.86 3.86 0 0 0 3.12 3.78v2.13a6.12 6.12 0 0 1-3.12-1.02V3.5z"/%3E%3Cpath fill="%2325F4EE" d="M13.8 2.9v10.34a3.84 3.84 0 1 1-3.84-3.84c.29 0 .57.03.84.09v1.4a2.35 2.35 0 1 0 1.74 2.27V2.9h1.26z" opacity="0.95"/%3E%3C/svg%3E',
190
+ Netflix: 'https://upload.wikimedia.org/wikipedia/commons/0/08/Netflix_2015_logo.svg',
191
+ Spotify: 'https://upload.wikimedia.org/wikipedia/commons/8/84/Spotify_icon.svg',
192
+ };
193
+
194
+ /**
195
+ * Consent options. Each option maps to one or more backend `approved` scopes via `scopes`.
196
+ * UI is intentionally minimal (one toggle; two when Raw Memories is available), but the
197
+ * scopes emitted downstream are unchanged so personalization quality isn't reduced.
198
+ */
199
+ const getOptions = (appName, hasRawMemorySources) => [
200
+ // Basic profile is always included — rendered as an "included" line, not a checkbox.
201
+ { id: "basic", name: "Basic Profile", icon: "User", required: true, scopes: ["basic"], description: "Your name and account basics — the minimum needed to set up your profile" },
202
+ // Combines the former "Preferences" + "Interests" toggles into a single consent.
203
+ {
204
+ id: "personalization",
205
+ name: "Personalization",
206
+ icon: "Brain",
207
+ scopes: ["preferences", "personality"],
208
+ description: `Lets ${appName} tailor your experience to your taste`,
209
+ },
210
+ {
211
+ id: "rawMemories",
212
+ name: "Raw Memories",
213
+ icon: "Memory",
214
+ scopes: ["rawMemories"],
215
+ description: hasRawMemorySources
216
+ ? "Share secure raw data from your connected sources"
217
+ : "Connect a supported source (LLM, Netflix, Spotify, Sephora, …) to enable",
218
+ disabled: !hasRawMemorySources,
219
+ disabledReason: !hasRawMemorySources ? "Connect a raw data source first" : null,
220
+ },
221
+ ];
222
+
223
+ const DataRequest = ({ appName = "My App", onComplete, onConnectMoreApps, connectedPlatforms = [], showTime = false, userEmail = null, onLogout = null, appIcon = null, customTitle = null, theme = 'default', rawMemoriesOnly = false, rawMemoriesConfig = null, requestData = null, allowedPlatforms = null, rawMemoriesOffered = null, privacyPolicyUrl = 'https://privacy.onairos.io', allowContinueWithoutConnections = false, demoMode = false }) => {
224
+ const isGlass = theme === 'glass';
225
+ // One-checkbox model: basic is required, personalization is the single opt-out choice
226
+ // (pre-selected for lower friction), raw memories is an opt-in second choice when available.
227
+ const [selected, setSelected] = useState({
228
+ basic: true,
229
+ personalization: true,
230
+ rawMemories: false,
231
+ });
232
+
233
+ const normalizedRequestData = useMemo(
234
+ () => (Array.isArray(requestData) ? requestData.map((s) => String(s).toLowerCase()) : null),
235
+ [requestData]
236
+ );
237
+
238
+ const [freq, setFreq] = useState("weekly");
239
+ const [platformIconFailed, setPlatformIconFailed] = useState({});
240
+ const [platforms, setPlatforms] = useState(() => getConnected());
241
+ const [isSubmitting, setIsSubmitting] = useState(false);
242
+
243
+ const isWrappedApp = typeof appName === 'string' && appName.toLowerCase().includes('wrapped');
244
+
245
+ // Debug: Log props on mount
246
+ useEffect(() => {
247
+ console.log('🔍 [DATAREQUEST-MOUNT] Props received:', {
248
+ userEmail,
249
+ connectedPlatforms,
250
+ appName,
251
+ hasUserEmail: !!userEmail,
252
+ connectedPlatformsType: typeof connectedPlatforms,
253
+ connectedPlatformsIsArray: Array.isArray(connectedPlatforms),
254
+ connectedPlatformsLength: Array.isArray(connectedPlatforms) ? connectedPlatforms.length : 'N/A'
255
+ });
256
+
257
+ // Also check localStorage
258
+ try {
259
+ const u = JSON.parse(localStorage.getItem("onairosUser") || "{}");
260
+ console.log('🔍 [DATAREQUEST-MOUNT] localStorage onairosUser:', {
261
+ email: u.email,
262
+ connectedAccounts: u.connectedAccounts,
263
+ hasConnectedAccounts: !!u.connectedAccounts,
264
+ connectedAccountsLength: Array.isArray(u.connectedAccounts) ? u.connectedAccounts.length : 'N/A'
265
+ });
266
+ } catch (e) {
267
+ console.error('❌ Failed to read localStorage:', e);
268
+ }
269
+ }, []); // Run only once on mount
270
+
271
+ // Normalize platform ids/names coming from different sources (SDK, backend, localStorage)
272
+ // so logos always render (e.g. "linkedin" -> "LinkedIn").
273
+ function normalizePlatformName(p) {
274
+ const key = String(p || '').trim();
275
+ // Reject pure-numeric strings (leaked array indices)
276
+ if (/^\d+$/.test(key)) return '';
277
+ const lower = key.toLowerCase();
278
+ const map = {
279
+ instagram: 'Instagram',
280
+ youtube: 'YouTube',
281
+ linkedin: 'LinkedIn',
282
+ reddit: 'Reddit',
283
+ pinterest: 'Pinterest',
284
+ sephora: 'Sephora',
285
+ github: 'GitHub',
286
+ facebook: 'Facebook',
287
+ gmail: 'Gmail',
288
+ twitter: 'X',
289
+ x: 'X',
290
+ chatgpt: 'ChatGPT',
291
+ claude: 'Claude',
292
+ gemini: 'Gemini',
293
+ grok: 'Grok',
294
+ perplexity: 'Perplexity',
295
+ tiktok: 'TikTok',
296
+ netflix: 'Netflix',
297
+ spotify: 'Spotify',
298
+ };
299
+ return map[lower] || (key ? key.charAt(0).toUpperCase() + key.slice(1) : '');
300
+ }
301
+
302
+ function platformKeyForFilter(displayName) {
303
+ return String(normalizePlatformName(displayName) || '').trim().toLowerCase();
304
+ }
305
+
306
+ /** When `allowedPlatforms` is set, at least one must be a raw-memory pipeline (LLM / Netflix / Spotify / Sephora). */
307
+ function allowlistIncludesAnyRawSource(allowedSet) {
308
+ if (!allowedSet || allowedSet.size === 0) return true;
309
+ for (const k of allowedSet) {
310
+ if (RAW_MEMORY_SOURCE_KEYS.has(k)) return true;
311
+ }
312
+ return false;
313
+ }
314
+
315
+ /** User has a connected raw-capable account; if allowlist is set, that connection must be on it. */
316
+ function userHasConnectedRawSourceInAllowlist(connectedList, allowedSet) {
317
+ const list = Array.isArray(connectedList) ? connectedList : [];
318
+ if (!allowedSet || allowedSet.size === 0) {
319
+ return list.some((p) => RAW_MEMORY_SOURCE_KEYS.has(platformKeyForFilter(p)));
320
+ }
321
+ return list.some((p) => {
322
+ const k = platformKeyForFilter(p);
323
+ return RAW_MEMORY_SOURCE_KEYS.has(k) && allowedSet.has(k);
324
+ });
325
+ }
326
+
327
+ function userHasConnectedLlmRawSourceInAllowlist(connectedList, allowedSet) {
328
+ const list = Array.isArray(connectedList) ? connectedList : [];
329
+ if (!allowedSet || allowedSet.size === 0) {
330
+ return list.some((p) => LLM_RAW_MEMORY_SOURCE_KEYS.has(platformKeyForFilter(p)));
331
+ }
332
+ return list.some((p) => {
333
+ const k = platformKeyForFilter(p);
334
+ return LLM_RAW_MEMORY_SOURCE_KEYS.has(k) && allowedSet.has(k);
335
+ });
336
+ }
337
+
338
+ /** Raw row only if export is offered for this app and developer opted in explicitly. */
339
+ function developerExplicitlyWantsRawMemoriesInUI() {
340
+ if (rawMemoriesOffered === false) return false;
341
+ if (rawMemoriesOnly || rawMemoriesConfig != null) return true;
342
+ if (requestData == null) return false;
343
+ if (!Array.isArray(requestData) || requestData.length === 0) return false;
344
+ return !!(normalizedRequestData && normalizedRequestData.includes('rawmemories'));
345
+ }
346
+
347
+ function normalizePlatformList(items) {
348
+ const normalized = (Array.isArray(items) ? items : [])
349
+ .map(normalizePlatformName)
350
+ .filter(Boolean);
351
+ return [...new Set(normalized)];
352
+ }
353
+
354
+ function extractPlatformCandidates(source) {
355
+ if (!source || typeof source !== 'object') return [];
356
+ return [
357
+ source.connectedAccounts,
358
+ source.connectedPlatforms,
359
+ source.connected_platforms,
360
+ source.accounts,
361
+ source.accountStatus?.connectedPlatforms,
362
+ source.accountStatus?.connected_platforms,
363
+ source.accountStatus?.accounts,
364
+ source.accountStatus?.llmPlatforms,
365
+ source.AccountStatus?.connectedPlatforms,
366
+ source.AccountStatus?.connected_platforms,
367
+ source.AccountStatus?.accounts,
368
+ source.AccountStatus?.llmPlatforms,
369
+ source.accountInfo?.connectedPlatforms,
370
+ source.accountInfo?.connected_platforms,
371
+ source.accountInfo?.accounts,
372
+ source.accountInfo?.llmPlatforms,
373
+ source.AccountInfo?.connectedPlatforms,
374
+ source.AccountInfo?.connected_platforms,
375
+ source.AccountInfo?.accounts,
376
+ source.AccountInfo?.llmPlatforms,
377
+ source.body?.connectedPlatforms,
378
+ source.body?.connected_platforms,
379
+ source.body?.accounts,
380
+ source.body?.llmPlatforms,
381
+ source.body?.accountStatus?.connectedPlatforms,
382
+ source.body?.accountStatus?.connected_platforms,
383
+ source.body?.accountStatus?.accounts,
384
+ source.body?.accountStatus?.llmPlatforms,
385
+ source.body?.AccountStatus?.connectedPlatforms,
386
+ source.body?.AccountStatus?.connected_platforms,
387
+ source.body?.AccountStatus?.accounts,
388
+ source.body?.AccountStatus?.llmPlatforms,
389
+ source.body?.AccountInfo?.connectedPlatforms,
390
+ source.body?.AccountInfo?.connected_platforms,
391
+ source.body?.AccountInfo?.accounts,
392
+ source.body?.AccountInfo?.llmPlatforms,
393
+ source.accountDetails?.existingUserData?.connections,
394
+ source.accountInfo?.existingUserData?.connections,
395
+ source.AccountInfo?.existingUserData?.connections,
396
+ source.body?.accountDetails?.existingUserData?.connections,
397
+ source.body?.accountInfo?.existingUserData?.connections,
398
+ source.body?.AccountInfo?.existingUserData?.connections,
399
+ ];
400
+ }
401
+
402
+ function normalizePlatformCandidate(candidate) {
403
+ if (Array.isArray(candidate)) {
404
+ const objectConnections = candidate
405
+ .map((item) => {
406
+ if (!item || typeof item !== 'object') return item;
407
+ if (!isMeaningfullyConnectedPlatformValue(item)) return '';
408
+ return item.platform || item.displayName || item.name || item.connector || item.id || '';
409
+ })
410
+ .filter(Boolean);
411
+ return normalizePlatformList(objectConnections);
412
+ }
413
+
414
+ if (candidate && typeof candidate === 'object') {
415
+ const mappedRaw = Object.entries(candidate)
416
+ .filter(([_, v]) => isMeaningfullyConnectedPlatformValue(v))
417
+ .map(([k]) => k);
418
+ return normalizePlatformList(mappedRaw);
419
+ }
420
+
421
+ return [];
422
+ }
423
+
424
+ function isMeaningfullyConnectedPlatformValue(value) {
425
+ if (value === true) return true;
426
+ if (value === false || value == null || value === '') return false;
427
+ if (typeof value !== 'object') return Boolean(value);
428
+ if (Array.isArray(value)) return value.length > 0;
429
+ if (Object.keys(value).length === 0) return false;
430
+
431
+ const status = String(value.status || '').toLowerCase();
432
+ if (
433
+ value.connected === false ||
434
+ value.enabled === false ||
435
+ status === 'disconnected' ||
436
+ status === 'revoked' ||
437
+ status === 'disabled'
438
+ ) {
439
+ return false;
440
+ }
441
+
442
+ return !!(
443
+ value.connected === true ||
444
+ value.enabled === true ||
445
+ status === 'connected' ||
446
+ value.accessToken ||
447
+ value.refreshToken ||
448
+ value.token ||
449
+ value.tokenExpiry ||
450
+ value.oauthToken ||
451
+ value.oauth_token ||
452
+ value.username ||
453
+ value.userName ||
454
+ value.email ||
455
+ value.id ||
456
+ value.userId ||
457
+ value.publicIdentifier ||
458
+ value.firstName ||
459
+ value.connectedAt ||
460
+ value.lastSyncedAt ||
461
+ value.channelId ||
462
+ value.channelName ||
463
+ value.onairosId ||
464
+ value.profileUrl ||
465
+ value.profileLastUpdated ||
466
+ value.lastUsed ||
467
+ value.hasData ||
468
+ value.hasEncryptedData ||
469
+ value.totalInteractions
470
+ );
471
+ }
472
+
473
+ function readLocalConnectedSnapshot() {
474
+ try {
475
+ const u = JSON.parse(localStorage.getItem("onairosUser") || "{}");
476
+ if (!u || typeof u !== 'object') {
477
+ return { hasField: false, platforms: [] };
478
+ }
479
+
480
+ let sawField = false;
481
+ for (const candidate of extractPlatformCandidates(u)) {
482
+ if (candidate !== undefined && candidate !== null) sawField = true;
483
+ const platforms = normalizePlatformCandidate(candidate);
484
+ if (platforms.length > 0) {
485
+ return { hasField: true, platforms };
486
+ }
487
+ }
488
+
489
+ return { hasField: sawField, platforms: [] };
490
+ } catch (e) {
491
+ console.error('❌ Failed to read localStorage:', e);
492
+ return { hasField: false, platforms: [] };
493
+ }
494
+ }
495
+
496
+ const selectedCount = useMemo(() => Object.values(selected).filter(Boolean).length, [selected]);
497
+
498
+ // Ensure we actually show connected platforms even if prop isn't passed
499
+ function getConnected() {
500
+ console.log('📊 DataRequest getConnected:', {
501
+ connectedPlatforms,
502
+ isArray: Array.isArray(connectedPlatforms),
503
+ type: typeof connectedPlatforms
504
+ });
505
+
506
+ // Prefer non-empty localStorage snapshots: UniversalOnboarding updates them on OAuth return.
507
+ // If localStorage only has an empty/stale field, keep falling through to props/backend.
508
+ const localSnapshot = readLocalConnectedSnapshot();
509
+ if (localSnapshot.platforms.length > 0) {
510
+ console.log('✅ Using localStorage connectedAccounts:', localSnapshot.platforms);
511
+ return localSnapshot.platforms;
512
+ }
513
+
514
+ // Fall back to prop if localStorage isn't available / doesn't have the field.
515
+ // If array provided, use it
516
+ if (Array.isArray(connectedPlatforms) && connectedPlatforms.length > 0) {
517
+ const unique = normalizePlatformList(connectedPlatforms);
518
+ console.log('✅ Using connectedPlatforms prop (array):', connectedPlatforms, '→', unique);
519
+ return unique;
520
+ }
521
+
522
+ // If object provided, map truthy keys
523
+ if (connectedPlatforms && typeof connectedPlatforms === "object" && !Array.isArray(connectedPlatforms)) {
524
+ for (const candidate of [connectedPlatforms, ...extractPlatformCandidates(connectedPlatforms)]) {
525
+ const unique = normalizePlatformCandidate(candidate);
526
+ if (unique.length > 0) {
527
+ console.log('✅ Using connectedPlatforms prop (object):', candidate, '→', unique);
528
+ return unique;
529
+ }
530
+ }
531
+ }
532
+
533
+ console.log('⚠️ No connected platforms found');
534
+ return [];
535
+ }
536
+
537
+ // Refresh platforms list on mount and when connectedPlatforms changes
538
+ useEffect(() => {
539
+ const refreshPlatforms = () => {
540
+ const newPlatforms = getConnected();
541
+ console.log('🔄 DataRequest refreshing platforms:', newPlatforms);
542
+ setPlatforms(newPlatforms);
543
+ };
544
+
545
+ // Initial load
546
+ refreshPlatforms();
547
+
548
+ // If no platforms found and user is authenticated, fetch from backend
549
+ // This helps existing users who don't have connectedAccounts in localStorage yet
550
+ let cancelled = false;
551
+ let refreshTimer = null;
552
+ let refreshTimerType = null;
553
+ const scheduleRefresh = (callback, delay = 0) => {
554
+ const run = () => {
555
+ if (!cancelled) callback();
556
+ };
557
+ if (delay > 0) {
558
+ refreshTimer = window.setTimeout(run, delay);
559
+ refreshTimerType = 'timeout';
560
+ return;
561
+ }
562
+ if (typeof window.requestIdleCallback === 'function') {
563
+ refreshTimer = window.requestIdleCallback(run, { timeout: 1500 });
564
+ refreshTimerType = 'idle';
565
+ return;
566
+ }
567
+ refreshTimer = window.setTimeout(run, 0);
568
+ refreshTimerType = 'timeout';
569
+ };
570
+
571
+ const fetchFromBackendIfNeeded = async () => {
572
+ const currentPlatforms = getConnected();
573
+ console.log('🔍 [FETCH-CHECK] currentPlatforms:', currentPlatforms);
574
+ console.log('🔍 [FETCH-CHECK] userEmail:', userEmail);
575
+ console.log('🔍 [FETCH-CHECK] Should fetch?', !!userEmail);
576
+
577
+ if (userEmail) {
578
+ console.log('🔄 Refreshing connected platforms from backend to avoid stale localStorage...');
579
+ try {
580
+ const baseUrl = API_CONFIG.getBaseUrl();
581
+
582
+ console.log('📡 Fetching from:', `${baseUrl}/getAccountInfo/email`);
583
+ console.log('📡 Request body:', { Info: { identifier: userEmail } });
584
+
585
+ const resp = await fetch(`${baseUrl}/getAccountInfo/email`, {
586
+ method: 'POST',
587
+ headers: { 'Content-Type': 'application/json' },
588
+ body: JSON.stringify({ Info: { identifier: userEmail } })
589
+ });
590
+
591
+ console.log('📡 Response status:', resp.status);
592
+ console.log('📡 Response ok:', resp.ok);
593
+
594
+ if (resp.ok) {
595
+ const data = await resp.json();
596
+ console.log('📡 Full response data:', data);
597
+ console.log('📡 accountStatus:', data?.accountStatus);
598
+ console.log('📡 accountStatus.connectedPlatforms:', data?.accountStatus?.connectedPlatforms);
599
+
600
+ const connectedRaw = extractPlatformCandidates(data).find((candidate) => {
601
+ return normalizePlatformCandidate(candidate).length > 0;
602
+ }) || [];
603
+
604
+ console.log('📡 connectedRaw:', connectedRaw);
605
+
606
+ {
607
+ const unique = normalizePlatformCandidate(connectedRaw);
608
+ if (unique.length === 0) {
609
+ console.log('⚠️ No connected platforms found in backend response');
610
+ return;
611
+ }
612
+ console.log('✅ Fetched connected platforms from backend:', unique);
613
+
614
+ // Save to localStorage so it persists
615
+ try {
616
+ const u = JSON.parse(localStorage.getItem("onairosUser") || "{}");
617
+ u.connectedAccounts = unique;
618
+ localStorage.setItem("onairosUser", JSON.stringify(u));
619
+ console.log('💾 Saved connectedAccounts to localStorage');
620
+ } catch (e) {
621
+ console.error('❌ Failed to save to localStorage:', e);
622
+ }
623
+
624
+ // Update platforms display. Backend truth wins over stale localStorage.
625
+ if (cancelled) return;
626
+ setPlatforms((prev) => {
627
+ const prevKey = normalizePlatformList(prev).join('|');
628
+ const nextKey = unique.join('|');
629
+ return prevKey === nextKey ? prev : unique;
630
+ });
631
+ // Dispatch event so other components know about the update
632
+ try { window.dispatchEvent(new Event('onairos-connected-accounts-update')); } catch {}
633
+ try {
634
+ window.dispatchEvent(new CustomEvent('onairos-data-connection-end', {
635
+ detail: { status: 'connected', connectedPlatforms: unique }
636
+ }));
637
+ } catch {}
638
+ }
639
+ } else {
640
+ const errorText = await resp.text();
641
+ console.error('❌ Backend request failed:', resp.status, errorText);
642
+ }
643
+ } catch (error) {
644
+ console.error('❌ Failed to fetch connected platforms from backend:', error);
645
+ }
646
+ }
647
+ };
648
+
649
+ const initialPlatforms = getConnected();
650
+ // If we already have platforms from storage/props, keep the first interaction responsive
651
+ // and refresh backend truth after the consent sheet has settled.
652
+ scheduleRefresh(fetchFromBackendIfNeeded, initialPlatforms.length > 0 ? 750 : 0);
653
+
654
+ // Listen for custom event from UniversalOnboarding
655
+ const handleConnectedAccountsUpdate = () => {
656
+ console.log('📡 DataRequest received connectedAccountsUpdate event');
657
+ refreshPlatforms();
658
+ };
659
+
660
+ // Listen for storage events (cross-tab/window updates)
661
+ const handleStorageChange = (e) => {
662
+ if (e.key === 'onairosUser') {
663
+ console.log('💾 DataRequest detected storage change');
664
+ refreshPlatforms();
665
+ }
666
+ };
667
+
668
+ window.addEventListener('onairos-connected-accounts-update', handleConnectedAccountsUpdate);
669
+ window.addEventListener('storage', handleStorageChange);
670
+
671
+ return () => {
672
+ cancelled = true;
673
+ if (refreshTimer != null) {
674
+ try {
675
+ if (refreshTimerType === 'idle' && typeof window.cancelIdleCallback === 'function') {
676
+ window.cancelIdleCallback(refreshTimer);
677
+ } else {
678
+ window.clearTimeout(refreshTimer);
679
+ }
680
+ } catch {}
681
+ }
682
+ window.removeEventListener('onairos-connected-accounts-update', handleConnectedAccountsUpdate);
683
+ window.removeEventListener('storage', handleStorageChange);
684
+ };
685
+ }, [connectedPlatforms, userEmail]); // Re-run if connectedPlatforms prop or userEmail changes
686
+
687
+ useEffect(() => {
688
+ console.log('🎯 Final platforms to display:', platforms);
689
+ }, [platforms]);
690
+
691
+ // SDK parity: Capacitor should look like mobile web.
692
+ // Avoid “native-only” sizing differences here.
693
+
694
+ const allowedNormalizedSet = useMemo(() => {
695
+ if (!Array.isArray(allowedPlatforms) || allowedPlatforms.length === 0) return null;
696
+ return new Set(allowedPlatforms.map((p) => platformKeyForFilter(p)).filter(Boolean));
697
+ }, [allowedPlatforms]);
698
+
699
+ const visibleConnectedPlatforms = useMemo(() => {
700
+ if (!allowedNormalizedSet) return platforms;
701
+ return platforms.filter((p) => allowedNormalizedSet.has(platformKeyForFilter(p)));
702
+ }, [platforms, allowedNormalizedSet]);
703
+ const hasVisibleConnectedPlatforms = visibleConnectedPlatforms.length > 0;
704
+
705
+ const hasRawMemorySources = userHasConnectedRawSourceInAllowlist(platforms, allowedNormalizedSet);
706
+ const hasLlmRawMemorySources = userHasConnectedLlmRawSourceInAllowlist(platforms, allowedNormalizedSet);
707
+ const showRawMemoriesOption =
708
+ rawMemoriesOffered !== false &&
709
+ (developerExplicitlyWantsRawMemoriesInUI() || hasLlmRawMemorySources) &&
710
+ hasRawMemorySources &&
711
+ allowlistIncludesAnyRawSource(allowedNormalizedSet);
712
+
713
+ // Options follow requestData; rawMemories only when developer wants it AND user has a raw-capable source.
714
+ // A combined option (e.g. personalization → preferences + personality) shows if ANY of its scopes
715
+ // are requested, so collapsing toggles never hides a scope the developer asked for.
716
+ const availableOptions = useMemo(() => getOptions(appName, hasRawMemorySources).filter((opt) => {
717
+ if (opt.required) return true;
718
+ if (opt.id === 'rawMemories') return showRawMemoriesOption;
719
+ if (!normalizedRequestData || normalizedRequestData.length === 0) return true;
720
+ const optScopes = (opt.scopes && opt.scopes.length ? opt.scopes : [opt.id]).map((s) => s.toLowerCase());
721
+ return optScopes.some((s) => normalizedRequestData.includes(s));
722
+ }), [appName, hasRawMemorySources, normalizedRequestData, showRawMemoriesOption]);
723
+
724
+ // Split required (shown as an "included" line) from the user's actual checkboxes.
725
+ const requiredOptions = useMemo(() => availableOptions.filter((opt) => opt.required), [availableOptions]);
726
+ const choiceOptions = useMemo(() => availableOptions.filter((opt) => !opt.required), [availableOptions]);
727
+
728
+ const toggle = useCallback((id, val) => {
729
+ // Ensure "basic" is always true (required) and disabled options can't be toggled
730
+ const option = availableOptions.find(opt => opt.id === id);
731
+ if (option?.required || option?.disabled) {
732
+ return; // Don't allow toggling required or disabled options
733
+ }
734
+ setSelected((p) => (p[id] === val ? p : { ...p, [id]: val }));
735
+ }, [availableOptions]);
736
+
737
+ const freqToPercent = (f) => (f === "once" ? 0 : f === "weekly" ? 50 : 100);
738
+
739
+ const showConnectPlatformsCard = visibleConnectedPlatforms.length > 0;
740
+
741
+ const renderConnectPlatformChip = (platform, index) => {
742
+ const src = DATA_REQUEST_PLATFORM_LOGOS[platform] || '';
743
+ const key = `conn-${platform}-${index}`;
744
+ const failed = !!platformIconFailed[key];
745
+ const fallbackText = (() => {
746
+ if (platform === 'LinkedIn') return 'in';
747
+ if (platform === 'YouTube') return 'YT';
748
+ if (platform === 'ChatGPT') return 'AI';
749
+ return String(platform || '?').slice(0, 2).toUpperCase();
750
+ })();
751
+ const face = failed || !src ? (
752
+ <div
753
+ title={platform}
754
+ className="w-6 h-6 rounded-md shadow-sm flex-shrink-0 bg-gray-100 text-gray-700 flex items-center justify-center text-[10px] font-semibold"
755
+ >
756
+ {fallbackText}
757
+ </div>
758
+ ) : (
759
+ <img
760
+ src={src}
761
+ alt={platform}
762
+ title={platform}
763
+ className="w-6 h-6 rounded-md shadow-sm flex-shrink-0"
764
+ onError={() => setPlatformIconFailed((p) => ({ ...p, [key]: true }))}
765
+ />
766
+ );
767
+ return (
768
+ <span key={key} className="inline-flex flex-shrink-0">
769
+ {face}
770
+ </span>
771
+ );
772
+ };
773
+
774
+ const handleRailClick = (e) => {
775
+ const rect = e.currentTarget.getBoundingClientRect();
776
+ const x = Math.max(0, Math.min(rect.width, e.clientX - rect.left));
777
+ const ratio = x / rect.width;
778
+ if (ratio < 1 / 3) setFreq("once");
779
+ else if (ratio < 2 / 3) setFreq("weekly");
780
+ else setFreq("daily");
781
+ };
782
+
783
+ // Expand each enabled option into its backend scopes. Combined toggles (personalization)
784
+ // emit multiple scopes so downstream `approved.includes('preferences'|'personality')` still works.
785
+ const buildApprovedScopes = useCallback(() => {
786
+ const scopes = [];
787
+ availableOptions.forEach((opt) => {
788
+ if (!selected[opt.id]) return;
789
+ const optScopes = opt.scopes && opt.scopes.length ? opt.scopes : [opt.id];
790
+ optScopes.forEach((s) => scopes.push(s));
791
+ });
792
+ return [...new Set(scopes)];
793
+ }, [availableOptions, selected]);
794
+
795
+ const canSubmit = selectedCount > 0 && !isSubmitting && (hasVisibleConnectedPlatforms || allowContinueWithoutConnections);
796
+
797
+ const handleAcceptContinue = async () => {
798
+ if (!canSubmit) return;
799
+ setIsSubmitting(true);
800
+ try {
801
+ await new Promise((resolve) => requestAnimationFrame(resolve));
802
+ await onComplete?.({
803
+ approved: buildApprovedScopes(),
804
+ freq,
805
+ demoMode: !!demoMode,
806
+ });
807
+ } finally {
808
+ setIsSubmitting(false);
809
+ }
810
+ };
811
+
812
+ return (
813
+ <div className={`flex flex-col h-full max-h-full md:max-h-[90vh] rounded-3xl overflow-hidden ${isGlass ? 'bg-transparent' : 'bg-white/70 backdrop-blur-2xl'}`}>
814
+
815
+ {userEmail && (
816
+ <SessionUserBar userEmail={userEmail} onLogout={onLogout} theme={theme} />
817
+ )}
818
+
819
+ {/* CONTENT */}
820
+ <div className={`flex-1 overflow-y-auto px-6 pb-2 ${demoMode ? 'pt-3 md:pt-4' : 'pt-3 md:pt-6'}`}>
821
+
822
+ {/* ICONS */}
823
+ <div className="flex justify-center items-center gap-3 mb-3 md:mb-4">
824
+ {/* Wrapped: Onairos -> Persona. Non-wrapped: Onairos -> app placeholder */}
825
+ <div className={`w-10 h-10 rounded-2xl shadow flex items-center justify-center overflow-hidden ${isGlass ? 'bg-white/10' : 'bg-white'}`}>
826
+ <img
827
+ src={OnairosLogo}
828
+ alt="Onairos"
829
+ className="w-full h-full object-contain p-1"
830
+ />
831
+ </div>
832
+ <svg className={`w-5 h-5 ${isGlass ? 'text-white/40' : 'text-gray-400'}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
833
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14 5l7 7m0 0l-7 7m7-7H3" />
834
+ </svg>
835
+ <div className={`w-10 h-10 rounded-2xl shadow flex items-center justify-center overflow-hidden ${isGlass ? 'bg-white/10' : 'bg-white'}`}>
836
+ {appIcon ? (
837
+ <img
838
+ src={appIcon}
839
+ alt={appName}
840
+ className="w-full h-full object-cover"
841
+ onError={(e) => {
842
+ e.currentTarget.style.display = 'none';
843
+ e.currentTarget.parentElement.innerHTML = `<span class="text-lg font-serif font-bold" style="font-family: IBM Plex Sans, system-ui, sans-serif">${(appName || 'A').charAt(0).toUpperCase()}</span>`;
844
+ }}
845
+ />
846
+ ) : isWrappedApp ? (
847
+ <img
848
+ src={personaImg}
849
+ alt="Persona"
850
+ className="w-6 h-6 object-contain rounded-xl"
851
+ onError={(e) => {
852
+ e.currentTarget.style.display = 'none';
853
+ e.currentTarget.parentElement.innerHTML = '<span class="text-xl">🎁</span>';
854
+ }}
855
+ />
856
+ ) : (
857
+ <span className="text-lg font-serif font-bold" style={{ fontFamily: 'IBM Plex Sans, system-ui, sans-serif' }}>{(appName || 'A').charAt(0).toUpperCase()}</span>
858
+ )}
859
+ </div>
860
+ </div>
861
+
862
+ {/* TITLE */}
863
+ <div className={`text-center ${demoMode ? 'mb-3 md:mb-3' : 'mb-4 md:mb-5'}`}>
864
+ <h1 className={`text-[20px] md:text-[22px] font-semibold leading-tight tracking-tight ${isGlass ? 'text-white' : 'text-gray-900'}`} style={{ fontFamily: 'IBM Plex Sans, system-ui, sans-serif' }}>
865
+ {customTitle || `${appName} wants to personalize your experience`}
866
+ </h1>
867
+ <div className="mt-1 flex items-center justify-center gap-2">
868
+ <p className={`text-[12px] ${isGlass ? 'text-white/50' : 'text-gray-500'}`} style={{ fontFamily: 'Inter, system-ui, sans-serif' }}>
869
+ choose what to share
870
+ </p>
871
+ {privacyPolicyUrl && (
872
+ <a
873
+ href={privacyPolicyUrl}
874
+ target="_blank"
875
+ rel="noopener noreferrer"
876
+ aria-label="How your data is used"
877
+ title="How your data is used"
878
+ className={`inline-flex items-center justify-center w-5 h-5 rounded-full border transition flex-shrink-0 ${isGlass ? 'border-white/40 text-white/80 hover:text-white hover:border-white/70' : 'border-gray-400 text-gray-500 hover:text-gray-800 hover:border-gray-600'}`}
879
+ >
880
+ <span className="text-[12px] font-semibold leading-none" style={{ fontFamily: 'Georgia, serif' }}>i</span>
881
+ </a>
882
+ )}
883
+ </div>
884
+ {demoMode && (
885
+ <p className={`mx-auto mt-1.5 max-w-[300px] text-[11px] leading-snug ${isGlass ? 'text-white/55' : 'text-gray-500'}`} style={{ fontFamily: 'Inter, system-ui, sans-serif' }}>
886
+ Demo mode — consent flow only. No account data is fetched or processed.
887
+ </p>
888
+ )}
889
+ </div>
890
+
891
+ {/* CONSENT - one checkbox (two when Raw Memories is available) */}
892
+ <div className={`flex flex-col gap-2 ${demoMode ? 'mb-3 md:mb-4' : 'mb-4 md:mb-6'}`}>
893
+ {choiceOptions.map((opt) => (
894
+ <DataTypeToggle
895
+ key={opt.id}
896
+ dataType={opt}
897
+ enabled={selected[opt.id]}
898
+ onToggle={toggle}
899
+ isNative={false}
900
+ isGlass={isGlass}
901
+ />
902
+ ))}
903
+
904
+ {/* Always-included items shown as a quiet line rather than a checkbox.
905
+ Left structure mirrors DataTypeToggle (px-3 + w-7 icon slot + gap-2.5) so text aligns. */}
906
+ {requiredOptions.map((opt) => (
907
+ <div key={opt.id} className={`flex items-start gap-2.5 px-3 pt-0.5 ${isGlass ? 'text-white/55' : 'text-gray-500'}`} style={{ fontFamily: 'Inter, system-ui, sans-serif' }}>
908
+ <div className="w-7 flex-shrink-0 flex items-center justify-center mt-0.5">
909
+ <svg className={`w-3.5 h-3.5 ${isGlass ? 'text-white/55' : 'text-gray-400'}`} viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
910
+ <path d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" />
911
+ </svg>
912
+ </div>
913
+ <span className="text-[11px] leading-snug min-w-0">
914
+ <span className="font-medium">{opt.name}</span>
915
+ <span className={isGlass ? 'text-white/40' : 'text-gray-400'}> · always included</span>
916
+ {opt.description && (
917
+ <span className={`block ${isGlass ? 'text-white/40' : 'text-gray-400'}`}>{opt.description}</span>
918
+ )}
919
+ </span>
920
+ </div>
921
+ ))}
922
+ </div>
923
+
924
+ {/* FREQUENCY PANEL - Only shown if showTime is true */}
925
+ {showTime && (
926
+ <div className="p-5 rounded-3xl bg-white/50 backdrop-blur-md border border-black/5 shadow-sm">
927
+ <div className="flex justify-between items-center mb-3">
928
+ <span className="text-sm font-medium text-gray-900" style={{ fontFamily: 'Inter, system-ui, sans-serif' }}>
929
+ How often can {appName} receive updates?
930
+ </span>
931
+ <span className="text-[11px] text-gray-500" style={{ fontFamily: 'Inter, system-ui, sans-serif' }}>
932
+ {freq === "once"
933
+ ? "one-time only"
934
+ : freq === "weekly"
935
+ ? "once per week"
936
+ : "once per day"}
937
+ </span>
938
+ </div>
939
+
940
+ {/* SLIDER: subtle rail, monochrome progress, click-to-set */}
941
+ <div
942
+ className="relative h-2.5 rounded-full bg-gray-200/90 overflow-hidden mb-4 border border-black/5 shadow-inner cursor-pointer"
943
+ onClick={handleRailClick}
944
+ >
945
+ <div
946
+ className="absolute h-full transition-all rounded-full"
947
+ style={{
948
+ width: `${freqToPercent(freq)}%`,
949
+ background: "linear-gradient(90deg, rgba(31,41,55,0.95) 0%, rgba(107,114,128,0.9) 60%, rgba(209,213,219,0.85) 100%)",
950
+ }}
951
+ />
952
+ {/* Tick marks for 3 stops */}
953
+ <span className="absolute left-0 top-1/2 -translate-y-1/2 w-[2px] h-3 bg-black/10" />
954
+ <span className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 w-[2px] h-3 bg-black/10" />
955
+ <span className="absolute right-0 top-1/2 -translate-y-1/2 w-[2px] h-3 bg-black/10" />
956
+ {/* Thumb indicator (sleek) */}
957
+ <span
958
+ className="absolute top-1/2 -translate-y-1/2 -translate-x-1/2 w-4.5 h-4.5 rounded-full bg-white border border-black/20 shadow-md"
959
+ style={{
960
+ left: `${freqToPercent(freq)}%`,
961
+ }}
962
+ />
963
+ </div>
964
+
965
+ <div className="grid grid-cols-3 text-center text-[12px] font-medium" style={{ fontFamily: 'Inter, system-ui, sans-serif' }}>
966
+ <button onClick={() => setFreq("once")} className="text-gray-700">1× only</button>
967
+ <button onClick={() => setFreq("weekly")} className="text-gray-900 font-semibold">1× weekly</button>
968
+ <button onClick={() => setFreq("daily")} className="text-gray-700">1× daily</button>
969
+ </div>
970
+
971
+ <p className="text-[11px] text-gray-500 mt-3 leading-snug" style={{ fontFamily: 'Inter, system-ui, sans-serif' }}>
972
+ This only controls update frequency; It does not grant more access.
973
+ </p>
974
+ </div>
975
+ )}
976
+
977
+ </div>
978
+
979
+ {/* FOOTER */}
980
+ <div
981
+ className={`px-6 pt-3 md:pt-4 border-t flex-shrink-0 ${isGlass ? 'bg-transparent border-white/10' : 'bg-white/80 backdrop-blur border-black/5'}`}
982
+ style={{ paddingBottom: 'calc(12px + env(safe-area-inset-bottom))' }}
983
+ >
984
+ {/* Connected sources only. */}
985
+ {showConnectPlatformsCard && (
986
+ <div className={`mb-3 rounded-2xl backdrop-blur border px-3 py-2.5 ${isGlass ? 'bg-white/5 border-white/10' : 'bg-white/60 border-black/5'}`}>
987
+ <div className="text-center mb-1">
988
+ <div className={`text-[13px] font-semibold ${isGlass ? 'text-white' : 'text-gray-900'}`} style={{ fontFamily: 'IBM Plex Sans, system-ui, sans-serif' }}>Connect Platforms</div>
989
+ <div className={`text-[11px] ${isGlass ? 'text-white/50' : 'text-gray-500'}`} style={{ fontFamily: 'Inter, system-ui, sans-serif' }}>more connections, smarter personalization</div>
990
+ </div>
991
+ <div className="flex items-center justify-center gap-2 overflow-x-auto whitespace-nowrap pb-1" style={{ WebkitOverflowScrolling: 'touch' }}>
992
+ {visibleConnectedPlatforms.map((platform, index) => renderConnectPlatformChip(platform, index))}
993
+ </div>
994
+ {typeof onConnectMoreApps === 'function' && (
995
+ <div className="mt-1 flex justify-center">
996
+ <button
997
+ type="button"
998
+ onClick={onConnectMoreApps}
999
+ className={`text-[11px] font-medium inline-flex items-center gap-1.5 ${isGlass ? 'text-white/60 hover:text-white/90' : 'text-gray-700 hover:text-gray-900'}`}
1000
+ style={{ WebkitTextFillColor: isGlass ? undefined : '#111827', fontFamily: 'Inter, system-ui, sans-serif' }}
1001
+ >
1002
+ <span style={{ fontFamily: 'Inter, system-ui, sans-serif' }}>Connect more</span>
1003
+ <span
1004
+ aria-hidden="true"
1005
+ className={`inline-flex items-center justify-center w-4 h-4 rounded-full border leading-none ${isGlass ? 'border-white/30 text-white/60' : 'border-gray-400 text-gray-800'}`}
1006
+ style={{ WebkitTextFillColor: isGlass ? undefined : '#111827' }}
1007
+ >
1008
+ +
1009
+ </span>
1010
+ </button>
1011
+ </div>
1012
+ )}
1013
+ </div>
1014
+ )}
1015
+
1016
+ {/* If no platforms are connected yet, explain the preloaded/background flow or allow connecting apps. */}
1017
+ {(!platforms || platforms.length === 0) &&
1018
+ visibleConnectedPlatforms.length === 0 &&
1019
+ typeof onConnectMoreApps === 'function' && (
1020
+ <div className={`mb-3 rounded-2xl backdrop-blur border px-3 py-2 text-center ${isGlass ? 'bg-white/5 border-white/10' : 'bg-white/60 border-black/5'}`}>
1021
+ <div className={`text-[11px] mb-1 ${isGlass ? 'text-white/50' : 'text-gray-500'}`} style={{ fontFamily: 'Inter, system-ui, sans-serif' }}>
1022
+ {allowContinueWithoutConnections ? 'Personalization is preparing in the background' : 'No apps connected yet'}
1023
+ </div>
1024
+ {!allowContinueWithoutConnections && (
1025
+ <button
1026
+ type="button"
1027
+ onClick={onConnectMoreApps}
1028
+ className="text-[12px] font-medium underline underline-offset-2 text-gray-700 hover:text-gray-900"
1029
+ style={{ WebkitTextFillColor: '#111827', fontFamily: 'Inter, system-ui, sans-serif' }}
1030
+ >
1031
+ Connect apps?
1032
+ </button>
1033
+ )}
1034
+ </div>
1035
+ )}
1036
+ <button
1037
+ className={`w-full rounded-full py-3 text-sm font-medium shadow-sm flex items-center justify-center gap-2 transition ${!canSubmit ? 'cursor-not-allowed opacity-70' : 'cursor-pointer'} ${isGlass ? 'bg-white/15 border border-white/20' : 'bg-gray-900'}`}
1038
+ style={{ color: '#ffffff', fontFamily: 'Inter, system-ui, sans-serif' }}
1039
+ disabled={!canSubmit}
1040
+ onClick={handleAcceptContinue}
1041
+ >
1042
+ {isSubmitting ? (
1043
+ <svg className="w-4 h-4 animate-spin" viewBox="0 0 24 24" fill="none" aria-hidden="true">
1044
+ <circle className="opacity-25" cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="3" />
1045
+ <path className="opacity-90" d="M21 12a9 9 0 0 0-9-9" stroke="currentColor" strokeWidth="3" strokeLinecap="round" />
1046
+ </svg>
1047
+ ) : null}
1048
+ {hasVisibleConnectedPlatforms || allowContinueWithoutConnections ? 'Accept & Continue' : 'Connect apps to continue'}
1049
+ </button>
1050
+ </div>
1051
+ </div>
1052
+ );
1053
+ };
1054
+
1055
+ export default DataRequest;