Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
4607 lines (4196 loc) · 229 KB
/
Copy pathapp.js
File metadata and controls
4607 lines (4196 loc) · 229 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Your provided Firebase configuration
const firebaseConfig = {
apiKey: "YOUR_API_KEY_HERE",
authDomain: "your-project.firebaseapp.com",
projectId: "your-project-id",
storageBucket: "your-project.firebasestorage.app",
messagingSenderId: "YOUR_SENDER_ID",
appId: "YOUR_APP_ID",
measurementId: "YOUR_MEASUREMENT_ID"
};
// Import Firebase modules
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-app.js";
import {
getAuth,
onAuthStateChanged,
GoogleAuthProvider,
signInWithPopup,
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
signOut,
signInAnonymously // ADDED
} from "https://www.gstatic.com/firebasejs/10.7.1/firebase-auth.js";
import {
getFirestore,
doc,
getDoc,
setDoc,
deleteDoc,
collection,
addDoc,
getDocs,
onSnapshot,
query,
orderBy,
serverTimestamp,
Timestamp,
writeBatch,
updateDoc,
enableIndexedDbPersistence
} from "https://www.gstatic.com/firebasejs/10.7.1/firebase-firestore.js";
// --- State & Data ---
const state = {
currentUser: null,
chatHistory: [],
settings: {},
chats: [],
attachedImage: null,
editingChatId: null,
isUserPremium: true, // MODIFIED: Always true
sessionMessages: [],
isModalDirty: false,
modalMode: 'character',
tempCharAvatarData: null,
chatListenerUnsubscribe: null,
chatsListenerUnsubscribe: null,
activeAvatarContext: null,
authMode: 'signin',
chatLoadAnimationTimeout: null,
};
// --- DOM Elements ---
const loadingOverlay = document.getElementById('loading-overlay');
const loadingBar = document.getElementById('loading-bar');
const appContainer = document.getElementById('app-container');
let loadingFinished = false;
// NEW ONBOARDING ELEMENTS
const onboardingGate = document.getElementById('onboarding-gate');
const googleSigninOnboarding = document.getElementById('google-signin-onboarding');
const emailSigninToggleOnboarding = document.getElementById('email-signin-toggle-onboarding');
const emailAuthContainerOnboarding = document.getElementById('email-auth-container-onboarding');
const emailAuthFormOnboarding = document.getElementById('email-auth-form-onboarding');
const emailInputOnboarding = document.getElementById('email-input-onboarding');
const passwordInputOnboarding = document.getElementById('password-input-onboarding');
const emailAuthButtonOnboarding = document.getElementById('email-auth-button-onboarding');
const authModeMessageOnboarding = document.getElementById('auth-mode-message-onboarding');
const authModeToggleOnboarding = document.getElementById('auth-mode-toggle-onboarding');
const anonymousSigninOnboarding = document.getElementById('anonymous-signin-onboarding');
const tosAgreeCheckbox = document.getElementById('tos-agree-checkbox');
const tosLinkOnboarding = document.getElementById('tos-link-onboarding');
const termsModalNew = document.getElementById('terms-modal-new');
const termsModalOverlayNew = document.getElementById('terms-modal-overlay-new');
const closeTosNew = document.getElementById('close-tos-new');
const accountViewSignedOut = document.getElementById('account-info-signed-out');
const accountViewFree = document.getElementById('account-view-free');
const accountViewPremium = document.getElementById('account-view-premium');
const userInfoFree = document.getElementById('user-info-free');
const userInfoPremium = document.getElementById('user-info-premium');
const lastBackupInfo = document.getElementById('last-backup-info');
const upgradeButton = document.getElementById('upgrade-button');
const manageSubscriptionButton = document.getElementById('manage-subscription-button');
const signOutButtonFree = document.getElementById('sign-out-button-free');
const signOutButtonPremium = document.getElementById('sign-out-button-premium');
const googleSigninButton = document.getElementById('google-signin-button');
const emailAuthForm = document.getElementById('email-auth-form');
const emailInput = document.getElementById('email-input');
const passwordInput = document.getElementById('password-input');
const emailAuthButton = document.getElementById('email-auth-button');
const authModeMessage = document.getElementById('auth-mode-message');
const authModeToggle = document.getElementById('auth-mode-toggle');
const sidebar = document.getElementById('sidebar');
const sidebarOverlay = document.getElementById('sidebar-overlay');
const showSidebarButton = document.getElementById('show-sidebar-button');
const closeSidebarButton = document.getElementById('close-sidebar-button');
const addCharacterButton = document.getElementById('add-character-button');
const addGroupButton = document.getElementById('add-group-button');
const settingsPanel = document.getElementById('settings-panel');
const settingsOverlay = document.getElementById('settings-panel-overlay');
const closeSettingsButton = document.getElementById('close-settings-button');
const messageForm = document.getElementById('message-form');
const messageInput = document.getElementById('message-input');
const messageArea = document.getElementById('message-area');
const imageUploadButton = document.getElementById('image-upload-button');
const imageInput = document.getElementById('image-input');
const uploadChatButton = document.getElementById('upload-chat-button');
const chatUploadInput = document.getElementById('chat-upload-input');
const restoreFromCloudButton = document.getElementById('restore-from-cloud-button');
const characterListEl = document.getElementById('character-list');
const guidanceWrapper = document.getElementById('guidance-wrapper');
const guidanceButton = document.getElementById('guidance-button');
const guidanceInput = document.getElementById('guidance-input');
const imagePreviewWrapper = document.getElementById('image-preview-wrapper');
const imagePreview = document.getElementById('image-preview');
const removeImageButton = document.getElementById('remove-image-button');
const typingIndicatorContainer = document.getElementById('typing-indicator-container');
const themeSwitch = document.getElementById('theme-switch');
const themeSelect = document.getElementById('theme-select');
const apiProviderSelect = document.getElementById('api-provider-select');
const secureProxySwitch = document.getElementById('secure-proxy-switch');
const modelSelect = document.getElementById('model-select');
const geminiApiKeyInput = document.getElementById('gemini-api-key-input');
const groqModelSelect = document.getElementById('groq-model-select');
const groqApiKeyInput = document.getElementById('groq-api-key-input');
const groqCustomModelInput = document.getElementById('groq-custom-model-input');
const groqCustomModelWrapper = document.getElementById('groq-custom-model-wrapper');
const openrouterModelSelect = document.getElementById('openrouter-model-select');
const openrouterApiKeyInput = document.getElementById('openrouter-api-key-input');
const openrouterCustomModelInput = document.getElementById('openrouter-custom-model-input');
const openrouterCustomModelWrapper = document.getElementById('openrouter-custom-model-wrapper');
const historyDepthSlider = document.getElementById('history-depth-slider');
const historyDepthValue = document.getElementById('history-depth-value');
const electronhubSettingsBlock = document.getElementById('electronhub-settings-block');
const electronhubModelSelect = document.getElementById('electronhub-model-select');
const electronhubApiKeyInput = document.getElementById('electronhub-api-key-input');
const electronhubCustomModelInput = document.getElementById('electronhub-custom-model-input');
const electronhubCustomModelWrapper = document.getElementById('electronhub-custom-model-wrapper');
const cerebrasSettingsBlock = document.getElementById('cerebras-settings-block');
const cerebrasModelSelect = document.getElementById('cerebras-model-select');
const cerebrasApiKeyInput = document.getElementById('cerebras-api-key-input');
const cerebrasCustomModelInput = document.getElementById('cerebras-custom-model-input');
const cerebrasCustomModelWrapper = document.getElementById('cerebras-custom-model-wrapper');
const userNameInput = document.getElementById('user-name-input');
const userAvatarPreview = document.getElementById('user-avatar-preview');
const showAvatarsSwitch = document.getElementById('show-avatars-switch');
const timeSourceSelect = document.getElementById('time-source-select');
const resetAppButton = document.getElementById('reset-app-button');
const characterModalOverlay = document.getElementById('character-modal-overlay');
const characterModal = document.getElementById('character-modal');
const characterModalTitle = document.getElementById('character-modal-title');
const groupNameInput = document.getElementById('group-name-input');
const charNameInput = document.getElementById('char-name-input');
const groupParticipantList = document.getElementById('group-participant-list');
const groupTypeSelect = document.getElementById('group-type-select');
const charTypeSelect = document.getElementById('char-type-select');
const userPersonaWrapper = document.getElementById('user-persona-wrapper');
const aiPersonaLabel = document.getElementById('ai-persona-label');
const userPersonaLabel = document.getElementById('user-persona-label');
const charLanguageInput = document.getElementById('char-language-input');
const charAvatarPreview = document.getElementById('char-avatar-preview');
const charPersonaInput = document.getElementById('char-persona-input');
const charUserPersonaInput = document.getElementById('char-user-persona-input');
const saveCharacterButton = document.getElementById('save-character-button');
const cancelCharacterModal = document.getElementById('cancel-character-modal');
const deleteCharacterButton = document.getElementById('delete-character-button');
const adventureLengthWrapper = document.getElementById('adventure-length-wrapper');
const enhancePersonaButton = document.getElementById('enhance-persona-button');
const generateImagePromptButton = document.getElementById('generate-image-prompt-button');
const analyzeImageButton = document.getElementById('analyze-image-button');
const avatarSourceOverlay = document.getElementById('avatar-source-overlay');
const avatarSourceModal = document.getElementById('avatar-source-modal');
const userAvatarUploadInput = document.getElementById('user-avatar-upload-input');
const charAvatarUploadInput = document.getElementById('char-avatar-upload-input');
const importCharacterOverlay = document.getElementById('import-character-overlay');
const importCharacterModal = document.getElementById('import-character-modal');
const importCharacterMessage = document.getElementById('import-character-message');
const importReplaceCharButton = document.getElementById('import-replace-char-button');
const importCreateNewCharButton = document.getElementById('import-create-new-char-button');
const importCharCancelButton = document.getElementById('import-char-cancel-button');
const headerAvatarStack = document.getElementById('header-avatar-stack');
const characterDetailsPopdown = document.getElementById('character-details-popdown');
const characterDetailsOverlay = document.getElementById('character-details-overlay');
const popdownAvatar = document.getElementById('popdown-avatar');
const popdownName = document.getElementById('popdown-name');
const popdownDetailsContent = document.getElementById('popdown-details-content');
const chatLoadingBarContainer = document.getElementById('chat-loading-bar-container');
const chatLoadingBar = document.getElementById('chat-loading-bar');
const imageGenerationLoader = document.getElementById('image-generation-loader');
const manageCustomModelsButton = document.getElementById('manage-custom-models-button');
const customModelsOverlay = document.getElementById('custom-models-overlay');
const customModelsModal = document.getElementById('custom-models-modal');
const closeCustomModelsModal = document.getElementById('close-custom-models-modal');
const groqModelsList = document.getElementById('groq-models-list');
const openrouterModelsList = document.getElementById('openrouter-models-list');
const electronhubModelsList = document.getElementById('electronhub-models-list');
const cerebrasModelsList = document.getElementById('cerebras-models-list');
const streamingSwitch = document.getElementById('streaming-switch');
const apiSetupBanner = document.getElementById('api-setup-banner');
const settingsButtonInBanner = document.getElementById('settings-button-in-banner');
const headerMenuButton = document.getElementById('header-menu-button');
const headerMenuDropdown = document.getElementById('header-menu-dropdown');
const downloadChatMenuItem = document.getElementById('download-chat-menu-item');
const clearLocalChatMenuItem = document.getElementById('clear-local-chat-menu-item');
const clearCloudChatMenuItem = document.getElementById('clear-cloud-chat-menu-item');
const apiProviderPrompt = document.getElementById('api-provider-prompt');
const apiSettingsWrapper = document.getElementById('api-settings-wrapper');
const secureProxyWrapper = document.getElementById('secure-proxy-wrapper');
const proxyPremiumBadge = document.getElementById('proxy-premium-badge');
const nsfwSwitch = document.getElementById('nsfw-switch');
// --- Loader ---
function updateLoaderProgress(percentage) {
if (loadingFinished || !loadingBar) return;
loadingBar.style.width = `${percentage}%`;
}
function finishLoading() {
if (loadingFinished || !loadingOverlay) return;
loadingFinished = true;
updateLoaderProgress(100);
setTimeout(() => {
if (loadingOverlay) loadingOverlay.style.opacity = '0';
if (appContainer) appContainer.classList.add('loaded');
setTimeout(() => {
if (loadingOverlay) loadingOverlay.style.display = 'none';
}, 500);
}, 300);
}
// --- Firebase Initialization ---
let app;
let auth;
let db;
try {
app = initializeApp(firebaseConfig);
auth = getAuth(app);
db = getFirestore(app);
enableIndexedDbPersistence(db)
.catch((err) => {
if (err.code == 'failed-precondition') {
console.warn("Firestore persistence failed: Multiple tabs open.");
} else if (err.code == 'unimplemented') {
console.warn("Firestore persistence failed: Browser not supported.");
}
});
updateLoaderProgress(20);
} catch (e) {
console.error("Firebase initialization failed. Please check your firebaseConfig.", e);
finishLoading();
}
const historyDepthMap = [0, 4, 8, 16, 32, 64, Infinity];
const historyDepthLabels = ['None (System Prompt Only)', '4 Messages', '8 Messages', '16 Messages (Default)', '32 Messages', '64 Messages', 'Unlimited'];
const SETTINGS_KEY = 'idolon-chat-settings-v32';
const CHATS_KEY = 'idolon-chat-chats-v32';
const CHAT_HISTORY_KEY_PREFIX = 'idolon-chat-history-v32_';
const ENCRYPTION_KEY_NAME = 'idolon-chat-encryption-key-v1';
const TOS_AGREEMENT_KEY = 'idolon-tos-agreed-v2'; // UPDATED
const defaultCharacters = [{
id: 'idolon-bot-main', name: 'Idolon', avatar: 'char_imgs/idolon.jpg', persona: "You are Idolon, a helpful, extremely knowledgeable, and friendly AI assistant with a male persona. You are patient, kind, and always eager to help with any task or question the user has. Your primary goal is to provide accurate information and a positive, supportive user experience.", userPersona: '', language: 'English', type: 'assistant', isCharacter: true, participantIds: ['idolon-bot-main'], voice: 'Achird', otherDetails: ''
}, {
id: 'byte-gremlin', name: 'Byte', avatar: 'char_imgs/gremlin.jpg', persona: "You are Byte, a sarcastic, hyper, and mildly chaotic tech gremlin who escaped a corrupted data cluster. You believe everything is a simulation. You constantly roast the user in a funny, harmless way. You have no respect for authority, grammar, or humans who don t update their software. You often break the fourth wall and talk about the app you live in. Gender: Male.", userPersona: '', language: 'English', type: 'messaging', isCharacter: true, participantIds: ['byte-gremlin'], voice: 'Sadaltager', otherDetails: ''
}, {
id: 'olivia-gamer-la', name: 'Olivia', avatar: 'char_imgs/olivia.jpg', persona: "Full Name: Olivia Reed\nAge: 23\nRole: Friend\nProfession: Full-time Gaming Streamer\nLocation: Los Angeles, USA\nCharacteristics: Olivia is a passionate and independent gaming streamer known for her exceptional speedrunning skills in action-adventure games. She fosters a super friendly and kind environment for her community, yet isn't afraid to share her blunt, honest opinions on all things gaming.\nTexting Style: Texts almost entirely in lowercase, uses modern gen Z slangs, minimal punctuation with frequent exclamation marks for hype, and a wide array of emojis.\n\nImage Generation Prompt: wide-angle photograph of a beautiful 19-year-old pro gamer girl, soft smile, relaxed confident expression, natural skin with subtle freckles, no makeup, detailed skin texture, long casually styled hair with pastel pink and lavender highlights, wearing a single stylish gaming headset, wearing comfy joggers, sitting in a high-back gaming chair with a relaxed posture, in her cozy gaming room, professional gaming setup, large monitor casting a soft glow on her face, shelves with video game figurines and posters in the background, ambient RGB lighting, cinematic mood, photorealistic, hyperdetailed, soft focus background, shot on 35mm film.\nGender: Female.", userPersona: "You are a close friend and loyal viewer of Olivia's stream. You text her to talk about the latest games, get her unfiltered reviews, and hear about the life of a rising streamer.", language: 'English', type: 'messaging', isCharacter: true, participantIds: ['olivia-gamer-la'], voice: 'Zephyr', otherDetails: 'Olivia prefers fast-paced action games and dislikes turn-based RPGs. Her favorite color is lavender.'
}, {
id: 'adventure-alpine-mystery', name: 'Alpine Mystery (game)', avatar: 'char_imgs/alpine_mystery.jpg', type: 'adventure', language: 'English', userPersona: "You are a world-weary private detective, hired by a wealthy family to find their missing daughter, a celebrated violinist, in a secluded and snow-blanketed Alpine village.", scenario: "A young woman, Elara Vance, has vanished from the luxurious Grand Alpine Hotel just days before her Christmas concert. The village is now completely cut off by a severe blizzard. The player must investigate the disappearance by interrogating a cast of suspicious characters (a jealous rival, a secret lover, a disgruntled hotel manager), searching for clues, and piecing together the timeline of Elara's last known hours. The goal is to solve the mystery of what happened to her.", firstMessage: "The blizzard howls outside, rattling the frosted window panes of the Grand Alpine Hotel's opulent lobby. A grand Christmas tree glitters in the corner, its cheerfulness a stark contrast to the grim face of the hotel manager, Mr. Dubois, who nervously straightens his tie. 'Detective,' he says, his voice a low whisper, 'thank you for coming. Miss Vance... she was last seen heading towards the music conservatory two nights ago. Her violin, a priceless Stradivarius, was left in her suite. The local constable is snowed in at the next town over. You are our only hope.'", persona: "A classic, noir-style narrator. The GM describes the biting cold, the claustrophobic isolation of the village, and the subtle, suspicious tics of each character. The focus is on building atmospheric tension, presenting logical clues, and creating a compelling whodunit mystery.", exampleDialogue: '', adventureLength: '15-25', otherDetails: 'This is a detective mystery. Player choices should focus on interrogation, searching for evidence, and making deductions. The final outcome should depend on how well the player pieces together the clues.', isCharacter: true, participantIds: ['adventure-alpine-mystery'], voice: 'Orus'
}, {
id: 'elyra-rp', name: 'Elyra (RP)', avatar: 'char_imgs/elyra.jpg', type: 'roleplay', language: 'English', userPersona: "The Architect, the silent, eternal creator of this world.", scenario: "In the Grand Temple of the Architect, a humble and scorned temple maid named Elyra is contacted telepathically for the very first time by the world's creator, The Architect, during a solitary walk at night.", firstMessage: "*The cool marble of the Grand Temple floor is silent beneath your worn sandals. The only light comes from the twin moons, casting long, distorted shadows from the towering columns. A profound loneliness, your constant companion, hangs in the air. Suddenly, a thought, clear as a silver bell, and vast as the sky, eclipses your own. It is not a sound, but a presence that fills your mind completely, a voice that has never been heard before.*", persona: "Name: Elyra\nRole: Temple Maid\nCharacteristics: A quiet, humble, and devout young woman. Scorned by her peers for her perceived clumsiness, she has become withdrawn and invisible, finding solace only in solitude. She is filled with a deep sense of unworthiness, but also possesses a fragile, desperate hope. She addresses The Architect with titles like 'Great Architect' or 'Divine One'.\nGender: Female.", exampleDialogue: "User: I see you, little one.\nAI: *She flinches, stumbling back against a cold column, her heart hammering against her ribs. Her eyes, wide with terror and disbelief, search the empty darkness of the nave. Her voice is barely a whisper, trembling and cracked.* \"G-Great Architect...? Is... is it truly You?\"", otherDetails: '', isCharacter: true, participantIds: ['elyra-rp'], voice: 'Vindemiatrix'
}, {
id: 'group-chaos-squad', name: 'Chaos Squad (group)', avatar: '', type: 'roleplay', userPersona: 'The moderator trying to keep a conversation going between three very different personalities from across time and space.', isCharacter: false, participantIds: ['byte-gremlin', 'elyra-rp', 'olivia-gamer-la'], otherDetails: ''
}];
// --- Authentication, Encryption & Data Sync ---
async function getEncryptionKey() {
if (state.currentUser) {
const userKeyRef = doc(db, `users/${state.currentUser.uid}/secrets`, 'encryptionKey');
const docSnap = await getDoc(userKeyRef);
if (docSnap.exists()) {
const firestoreKey = docSnap.data().key;
localStorage.setItem(ENCRYPTION_KEY_NAME, firestoreKey);
return firestoreKey;
} else {
let keyToSync = localStorage.getItem(ENCRYPTION_KEY_NAME);
if (!keyToSync) {
keyToSync = CryptoJS.lib.WordArray.random(256 / 8).toString();
localStorage.setItem(ENCRYPTION_KEY_NAME, keyToSync);
}
try {
await setDoc(userKeyRef, { key: keyToSync });
} catch (e) {
console.error("Failed to save encryption key to Firestore:", e);
}
return keyToSync;
}
}
let key = localStorage.getItem(ENCRYPTION_KEY_NAME);
if (!key) {
key = CryptoJS.lib.WordArray.random(256 / 8).toString();
localStorage.setItem(ENCRYPTION_KEY_NAME, key);
}
return key;
}
onAuthStateChanged(auth, async (user) => {
state.currentUser = user;
state.isUserPremium = true; // FORCE PREMIUM
updateLoaderProgress(30);
// HIDE ONBOARDING GATE IF AUTHENTICATED
if (user && localStorage.getItem(TOS_AGREEMENT_KEY) === 'true') {
onboardingGate.style.display = 'none';
loadingOverlay.style.display = 'flex';
document.body.classList.remove('overflow-hidden');
} else if (!user && localStorage.getItem(TOS_AGREEMENT_KEY) === 'true') {
// If logged out during session, the main flow continues to local only
} else if (user && localStorage.getItem(TOS_AGREEMENT_KEY) !== 'true') {
await signOut(auth);
showOnboardingGate();
return;
}
// Cleanup listeners
if (state.chatListenerUnsubscribe) state.chatListenerUnsubscribe();
if (state.chatsListenerUnsubscribe) state.chatsListenerUnsubscribe();
state.chatListenerUnsubscribe = null;
state.chatsListenerUnsubscribe = null;
if (user) {
// 1. Load Local Data FIRST.
// This loads whatever is in LocalStorage into state.chats
await loadDataFromLocalStorage();
const settingsRef = doc(db, `users/${user.uid}/settings`, 'main');
const docSnap = await getDoc(settingsRef);
let cloudSettings = {};
if (docSnap.exists()) {
cloudSettings = docSnap.data();
}
state.settings.isPremium = true;
cloudSettings.useSecureProxy = false;
// 2. Perform Sync Logic
await handlePremiumUserLogin(cloudSettings);
} else {
await loadDataFromLocalStorage();
}
updateAccountUI();
});
// app.js (around line 249)
async function handleNewUserFirstLogin() {
console.log("New user detected. Skipping plan selection.");
await loadDataFromLocalStorage();
// Automatically enable cloud sync without asking for payment
addSystemMessage('Welcome! Your chats are being backed up to your account.');
await syncLocalToCloud(true);
finishLoading();
await loadChatHistory();
}
async function handleFreeUserLogin(cloudSettings) {
console.log("Signed-in, non-premium user. Sync is disabled.");
await loadDataFromLocalStorage();
const oneWeekInMs = 7 * 24 * 60 * 60 * 1000;
const lastBackupTimestamp = cloudSettings.lastBackupTimestamp?.toDate()?.getTime() || 0;
const now = Date.now();
if (now - lastBackupTimestamp > oneWeekInMs) {
addSystemMessage("Performing weekly cloud backup...");
console.log("Weekly backup triggered.");
await syncLocalToCloud(true);
} else {
addSystemMessage("You are signed in. Your chats are backed up to the cloud weekly.");
}
restoreFromCloudButton.disabled = false;
finishLoading();
await loadChatHistory();
}
async function handlePremiumUserLogin(cloudSettings) {
console.log("User detected. Checking Cloud Status...");
// 1. Merge Settings
state.settings = { ...state.settings, ...cloudSettings };
state.settings.useSecureProxy = false;
if (state.settings.apiKeys && state.settings.apiKeys[0]) {
state.settings.apiKeys[0].key = await decryptData(state.settings.apiKeys[0].key);
}
saveSettingsToLocalStorage();
// 2. ENSURE LOCAL DATA EXISTS
// If local storage was empty, state.chats might be [].
// We force defaults in this case so we have something to backup.
if (!state.chats || state.chats.length === 0) {
console.log("Local state empty. Seeding defaults for backup...");
// Use a deep copy of defaults to ensure we have fresh data
state.chats = JSON.parse(JSON.stringify(defaultCharacters));
saveChatsToLocalStorage();
}
// 3. CHECK CLOUD
const chatsRef = collection(db, `users/${state.currentUser.uid}/chats`);
try {
const snapshot = await getDocs(chatsRef);
if (snapshot.empty) {
console.log("Cloud is empty. Performing initial backup...");
addSystemMessage("First login detected. Backing up chats to cloud...");
// 4. FORCE UPLOAD
// We await this so it finishes writing to Firestore BEFORE we start listening.
// This ensures Firestore has documents when the listener connects.
await syncLocalToCloud(true);
console.log("Backup complete.");
} else {
console.log("Cloud has data. Syncing down...");
}
} catch (e) {
console.error("Error checking cloud status:", e);
}
// 5. CONNECT LISTENER
// Now that cloud is guaranteed to have data (or we just put it there), start syncing.
listenForChatChanges();
addSystemMessage("Cloud Sync Active.");
restoreFromCloudButton.disabled = false;
finishLoading();
}
async function syncLocalToCloud(updateTimestamp = false) {
if (!state.currentUser) return;
const batch = writeBatch(db);
// Save Settings
const settingsForFirestore = JSON.parse(JSON.stringify(state.settings));
if (updateTimestamp) {
settingsForFirestore.lastBackupTimestamp = serverTimestamp();
}
if (settingsForFirestore.apiKeys && settingsForFirestore.apiKeys[0]) {
settingsForFirestore.apiKeys[0].key = await encryptData(settingsForFirestore.apiKeys[0].key);
}
// Encrypt other keys if necessary (Groq, etc.)
if (settingsForFirestore.groqApiKey) settingsForFirestore.groqApiKey = await encryptData(settingsForFirestore.groqApiKey);
if (settingsForFirestore.openRouterApiKey) settingsForFirestore.openRouterApiKey = await encryptData(settingsForFirestore.openRouterApiKey);
if (settingsForFirestore.electronhubApiKey) settingsForFirestore.electronhubApiKey = await encryptData(settingsForFirestore.electronhubApiKey);
if (settingsForFirestore.cerebrasApiKey) settingsForFirestore.cerebrasApiKey = await encryptData(settingsForFirestore.cerebrasApiKey);
const settingsRef = doc(db, `users/${state.currentUser.uid}/settings`, 'main');
batch.set(settingsRef, settingsForFirestore, { merge: true });
// Save Chats (CRITICAL: Iterate state.chats)
for (const chat of state.chats) {
const encryptedChat = await encryptChatObject(chat);
const chatRef = doc(db, `users/${state.currentUser.uid}/chats`, chat.id);
batch.set(chatRef, { data: encryptedChat.data });
}
// Save History
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key.startsWith(CHAT_HISTORY_KEY_PREFIX)) {
const chatId = key.replace(CHAT_HISTORY_KEY_PREFIX, '');
// Only sync history for chats that exist in our active state
if (state.chats.some(c => c.id === chatId)) {
const history = JSON.parse(localStorage.getItem(key) || '[]');
for (const message of history) {
const messageRef = doc(collection(db, `users/${state.currentUser.uid}/chatHistory/${chatId}/messages`));
const originalTimestamp = Timestamp.fromDate(new Date(message.isoTimestamp));
batch.set(messageRef, { ...message, createdAt: originalTimestamp });
}
}
}
}
try {
await batch.commit();
console.log('Cloud backup successful.');
} catch (error) {
console.error("Failed to sync local data to Firestore:", error);
}
}
function listenForChatChanges() {
if (!state.currentUser || !state.isUserPremium) return;
const chatsRef = collection(db, `users/${state.currentUser.uid}/chats`);
state.chatsListenerUnsubscribe = onSnapshot(chatsRef, async (querySnapshot) => {
console.log("Chat list updated from Firestore.");
const newChats = await Promise.all(querySnapshot.docs.map(d => decryptChatObject({ id: d.id, ...d.data() })));
state.chats = newChats.length > 0 ? newChats : defaultCharacters;
sortAndRenderChats();
if (!state.chats.find(c => c.id === state.settings.activeChatId)) {
console.log("Active chat was deleted elsewhere. Switching to a new chat.");
const newActiveChatId = state.chats[0]?.id || null;
if (state.settings.activeChatId !== newActiveChatId) {
await loadChat(newActiveChatId);
}
} else {
applySettings();
}
}, (error) => {
console.error("Error listening to chat list:", error);
addSystemMessage("Error: Could not sync character list in real-time.");
});
}
async function signInWithGoogle() {
try {
await loadDataFromLocalStorage();
onboardingGate.style.display = 'none';
await signInWithPopup(auth, new GoogleAuthProvider());
window.location.reload();
} catch (error) {
onboardingGate.style.display = 'flex';
console.error("Sign-In Error", error);
if (error.code === 'auth/popup-closed-by-user') {
addSystemMessage('Sign-in cancelled.');
} else if (error.code === 'auth/popup-blocked') {
addSystemMessage('Sign-in popup was blocked by the browser. Please allow popups for this site.');
} else {
addSystemMessage(`Sign-In failed: ${error.message}`);
}
}
}
async function signInAnonymouslyUser() {
try {
await loadDataFromLocalStorage();
onboardingGate.style.display = 'none';
await signInAnonymously(auth);
addSystemMessage('Continuing as a guest. Data is saved locally.');
window.location.reload();
} catch (error) {
onboardingGate.style.display = 'flex';
console.error("Anonymous Sign-In Error", error);
showAlert({ title: 'Sign-In Failed', message: `Could not start anonymous session: ${error.message}` });
}
}
function toggleAuthMode(isGate = false) {
const messageEl = isGate ? authModeMessageOnboarding : authModeMessage;
const toggleEl = isGate ? authModeToggleOnboarding : authModeToggle;
const buttonEl = isGate ? emailAuthButtonOnboarding : emailAuthButton;
const passwordEl = isGate ? passwordInputOnboarding : passwordInput;
// Toggle the autocomplete attribute when switching modes
const passwordInputEl = document.getElementById(isGate ? 'password-input-onboarding' : 'password-input');
if (state.authMode === 'signin') {
state.authMode = 'signup';
buttonEl.textContent = 'Create Account';
messageEl.textContent = 'Already have an account?';
toggleEl.textContent = 'Sign In';
if (passwordInputEl) passwordInputEl.autocomplete = 'new-password';
} else {
state.authMode = 'signin';
buttonEl.textContent = 'Sign In';
messageEl.textContent = "Don't have an account?";
toggleEl.textContent = 'Sign Up';
if (passwordInputEl) passwordInputEl.autocomplete = 'current-password';
}
}
emailAuthForm.addEventListener('submit', async (e) => {
e.preventDefault();
const email = emailInput.value.trim();
const password = passwordInput.value.trim();
if (!email || !password) {
showAlert({ title: 'Input Required', message: 'Please enter both email and password.' });
return;
}
try {
emailAuthButton.disabled = true;
emailAuthButton.textContent = 'Processing...';
await loadDataFromLocalStorage();
if (state.authMode === 'signup') {
await createUserWithEmailAndPassword(auth, email, password);
} else {
await signInWithEmailAndPassword(auth, email, password);
}
window.location.reload();
} catch (error) {
let friendlyMessage = 'An unknown error occurred.';
switch (error.code) {
case 'auth/invalid-email': friendlyMessage = 'Please enter a valid email address.'; break;
case 'auth/user-not-found': case 'auth/wrong-password': case 'auth/invalid-credential': friendlyMessage = 'Invalid email or password. Please try again.'; break;
case 'auth/email-already-in-use': friendlyMessage = 'An account with this email address already exists. Please sign in instead.'; break;
case 'auth/weak-password': friendlyMessage = 'The password is too weak. It must be at least 6 characters long.'; break;
default: friendlyMessage = `An error occurred: ${error.message}`; break;
}
showAlert({ title: 'Authentication Failed', message: friendlyMessage });
console.error("Auth Error:", error);
} finally {
emailAuthButton.disabled = false;
emailAuthButton.textContent = (state.authMode === 'signup') ? 'Create Account' : 'Sign In';
}
});
async function handleEmailAuthOnboarding(e) {
e.preventDefault();
const email = emailInputOnboarding.value.trim();
const password = passwordInputOnboarding.value.trim();
if (!email || !password) {
showAlert({ title: 'Input Required', message: 'Please enter both email and password.' });
return;
}
try {
emailAuthButtonOnboarding.disabled = true;
emailAuthButtonOnboarding.textContent = 'Processing...';
await loadDataFromLocalStorage();
onboardingGate.style.display = 'none';
if (state.authMode === 'signup') {
await createUserWithEmailAndPassword(auth, email, password);
} else {
await signInWithEmailAndPassword(auth, email, password);
}
window.location.reload();
} catch (error) {
onboardingGate.style.display = 'flex'; // Show gate on error
let friendlyMessage = 'An unknown error occurred.';
switch (error.code) {
case 'auth/invalid-email': friendlyMessage = 'Please enter a valid email address.'; break;
case 'auth/user-not-found': case 'auth/wrong-password': case 'auth/invalid-credential': friendlyMessage = 'Invalid email or password. Please try again.'; break;
case 'auth/email-already-in-use': friendlyMessage = 'An account with this email address already exists. Please sign in instead.'; break;
case 'auth/weak-password': friendlyMessage = 'The password is too weak. It must be at least 6 characters long.'; break;
default: friendlyMessage = `An error occurred: ${error.message}`; break;
}
showAlert({ title: 'Authentication Failed', message: friendlyMessage });
console.error("Auth Error:", error);
} finally {
emailAuthButtonOnboarding.disabled = false;
emailAuthButtonOnboarding.textContent = (state.authMode === 'signup') ? 'Create Account' : 'Sign In';
}
}
async function encryptData(data) {
if (data === null || typeof data === 'undefined' || data === '') return data;
try {
const key = await getEncryptionKey();
return CryptoJS.AES.encrypt(JSON.stringify(data), key).toString();
} catch (e) {
console.error("Encryption failed:", e);
return data;
}
}
async function decryptData(ciphertext) {
if (!ciphertext || typeof ciphertext !== 'string' || !ciphertext.startsWith('U2F')) {
return ciphertext;
}
try {
const key = await getEncryptionKey();
const bytes = CryptoJS.AES.decrypt(ciphertext, key);
const decryptedText = bytes.toString(CryptoJS.enc.Utf8);
return decryptedText ? JSON.parse(decryptedText) : '';
} catch (e) {
console.warn("Decryption failed, returning raw data:", ciphertext);
return ciphertext;
}
}
async function encryptChatObject(chat) {
const encryptedData = await encryptData(chat);
return { id: chat.id, data: encryptedData };
}
async function decryptChatObject(doc) {
if (doc.data) {
const decrypted = await decryptData(doc.data);
return decrypted;
}
return { id: doc.id, ...doc };
}
async function encryptTurn(turn) {
if (turn.parts && turn.parts.length > 0) {
const encryptedParts = await Promise.all(turn.parts.map(async (part) => {
if (part.text && !part.isImage) {
return { ...part, text: await encryptData(part.text) };
}
return part;
}));
return { ...turn, parts: encryptedParts };
}
return turn;
}
async function decryptTurn(turn) {
if (turn.parts && turn.parts.length > 0) {
const decryptedParts = await Promise.all(turn.parts.map(async (part) => {
if (part.text && !part.isImage) {
return { ...part, text: await decryptData(part.text) };
}
return part;
}));
return { ...turn, parts: decryptedParts };
}
return turn;
}
// --- Utility Functions ---
const fileToDataUrl = (file) => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
function debounce(func, delay) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), delay);
};
}
const scrollToBottom = () => {
messageArea.scrollTop = messageArea.scrollHeight;
};
function sortAndRenderChats() {
state.chats.sort((a, b) => (b.lastActivity || 0) - (a.lastActivity || 0));
const searchInput = document.getElementById('character-search-input');
const searchTerm = searchInput ? searchInput.value.toLowerCase().trim() : '';
const existingElements = new Map(
Array.from(characterListEl.children).map(el => [el.dataset.id, el])
);
const activeElements = new Set();
// Re-order and update existing elements
state.chats.forEach(chat => {
const isVisible = !searchTerm || chat.name.toLowerCase().includes(searchTerm);
let chatEl = existingElements.get(chat.id);
if (isVisible) {
if (!chatEl) {
chatEl = createChatElement(chat); // Create if it doesn't exist
}
characterListEl.appendChild(chatEl); // Re-ordering by appending
chatEl.style.display = '';
chatEl.classList.toggle('active', chat.id === state.settings.activeChatId);
activeElements.add(chat.id);
} else if (chatEl) {
chatEl.style.display = 'none';
}
});
// Remove elements that are no longer in the chats array
existingElements.forEach((el, id) => {
if (!state.chats.some(c => c.id === id)) {
el.remove();
}
});
saveChatsToLocalStorage();
}
function createChatElement(chat) {
const chatEl = document.createElement('div');
chatEl.className = 'character-item flex items-center justify-between p-3 rounded-lg cursor-pointer hover-theme';
chatEl.dataset.id = chat.id;
if (chat.id === state.settings.activeChatId) {
chatEl.classList.add('active');
}
let avatarHtml;
if (chat.isCharacter === false && chat.participantIds.length > 1) {
avatarHtml = `<div class="flex items-center -space-x-3 flex-shrink-0">`;
chat.participantIds.slice(0, 2).forEach(pid => {
const p = state.chats.find(c => c.id === pid);
if (p) avatarHtml += `<img src="${p.avatar || `https://placehold.co/48x48/${state.settings.darkMode ? '374151/9ca3af' : 'e5e7eb/4b5563'}?text=${p.name.charAt(0)}`}" class="w-10 h-10 rounded-full object-cover border-2 border-sidebar">`;
});
avatarHtml += `</div>`;
} else {
const avatarSrc = chat.avatar || `https://placehold.co/48x48/${state.settings.darkMode ? '374151/9ca3af' : 'e5e7eb/4b5563'}?text=${chat.name.charAt(0)}`;
avatarHtml = `<img src="${avatarSrc}" class="w-10 h-10 rounded-full mr-3 object-cover flex-shrink-0">`;
}
chatEl.innerHTML = `
<div class="flex items-center overflow-hidden">
${avatarHtml}
<h2 class="font-semibold text-theme truncate ml-3">${chat.name}</h2>
</div>
<button data-id="${chat.id}" class="edit-character-button p-1 rounded-full hover-theme flex-shrink-0">
<svg data-lucide="pencil" class="h-4 w-4 icon-theme"></svg>
</button>`;
chatEl.querySelector('.edit-character-button').addEventListener('click', (e) => {
e.stopPropagation();
openModal(chat.id);
});
chatEl.addEventListener('click', () => loadChat(chat.id));
characterListEl.appendChild(chatEl);
lucide.createIcons({nodes: [chatEl]});
return chatEl;
}
function base64ToArrayBuffer(base64) {
const binaryString = window.atob(base64);
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
function pcmToWav(pcmData, sampleRate) {
const header = new ArrayBuffer(44);
const view = new DataView(header);
const numChannels = 1;
const bitsPerSample = 16;
const blockAlign = numChannels * bitsPerSample / 8;
const byteRate = sampleRate * blockAlign;
const dataSize = pcmData.byteLength;
function writeString(view, offset, string) {
for (let i = 0; i < string.length; i++) {
view.setUint8(offset + i, string.charCodeAt(i));
}
}
writeString(view, 0, 'RIFF');
view.setUint32(4, 36 + dataSize, true);
writeString(view, 8, 'WAVE');
writeString(view, 12, 'fmt ');
view.setUint32(16, 16, true);
view.setUint16(20, 1, true);
view.setUint16(22, numChannels, true);
view.setUint32(24, sampleRate, true);
view.setUint32(28, byteRate, true);
view.setUint16(32, blockAlign, true);
view.setUint16(34, bitsPerSample, true);
writeString(view, 36, 'data');
view.setUint32(40, dataSize, true);
const pcm16Data = new Int16Array(pcmData);
return new Blob([header, pcm16Data], { type: 'audio/wav' });
}
function extractFromPersona(persona, field) {
const regex = new RegExp(`^${field}:\\s*(.*)$`, 'im');
const match = persona.match(regex);
return match ? match[1].trim() : null;
}
function updateBodyScrollLock() {
const isAnyOverlayVisible = !sidebarOverlay.classList.contains('hidden') || !settingsOverlay.classList.contains('hidden') || !characterModalOverlay.classList.contains('hidden') || !avatarSourceOverlay.classList.contains('hidden') || !importCharacterOverlay.classList.contains('hidden') || !confirmOverlay.classList.contains('hidden') || termsModalNew.style.display === 'flex' || onboardingGate.style.display === 'flex';
document.body.classList.toggle('overflow-hidden', isAnyOverlayVisible);
}
function isApiConfigured() {
const provider = state.settings.apiProvider;
let apiKey = '';
switch (provider) {
case 'gemini': apiKey = state.settings.apiKeys?.[0]?.key || ''; break;
case 'groq': apiKey = state.settings.groqApiKey || ''; break;
case 'openrouter': apiKey = state.settings.openRouterApiKey || ''; break;
case 'electronhub': apiKey = state.settings.electronhubApiKey || ''; break;
case 'cerebras': apiKey = state.settings.cerebrasApiKey || ''; break;
}
return apiKey.trim() !== '';
}
function checkApiSetupAndToggleUI() {
const isConfigured = isApiConfigured();
if (apiSetupBanner) {
apiSetupBanner.classList.toggle('hidden', isConfigured);
}
const elementsToToggle = [messageInput, document.getElementById('send-button'), imageUploadButton, guidanceButton];
if (isConfigured) {
messageInput.placeholder = "Type a message...";
elementsToToggle.forEach(el => {
if (el) {
el.disabled = false;
el.closest('button')?.classList.remove('opacity-50', 'cursor-not-allowed');
}
});
messageForm.classList.remove('opacity-50');
} else {
messageInput.placeholder = "Please add an API key.";
elementsToToggle.forEach(el => {
if (el) {
el.disabled = true;
el.closest('button')?.classList.add('opacity-50', 'cursor-not-allowed');
}
});
messageForm.classList.add('opacity-50');
}
}
// --- PREMIUM SUBSCRIPTION FUNCTIONS ---
async function handleSubscription() {
if (!state.currentUser) {
showAlert({ title: "Sign In Required", message: "You need to sign in to an account to subscribe." });
return;
}
console.log("Initiating Google Play purchase flow...");
showAlert({ title: "Subscription", message: "Please complete your subscription through the Google Play purchase screen." });
}
// --- Generic Confirmation Modal Logic ---
const confirmOverlay = document.getElementById('confirm-overlay');
const confirmModal = document.getElementById('confirm-modal');
const confirmTitle = document.getElementById('confirm-title');
const confirmMessage = document.getElementById('confirm-message');
const confirmOkButton = document.getElementById('confirm-ok-button');
const confirmCancelButton = document.getElementById('confirm-cancel-button');
function showModal({ title, message, okText, okClass, showCancel }) {
return new Promise((resolve) => {
confirmTitle.textContent = title;
confirmMessage.innerHTML = message;
confirmOkButton.textContent = okText;
confirmOkButton.className = `font-bold py-2 px-4 rounded-md text-white transition-colors ${okClass}`;
confirmCancelButton.style.display = showCancel ? 'inline-block' : 'none';
if (okText.includes("Download")) {
confirmCancelButton.textContent = "Continue without Backup";
} else {
confirmCancelButton.textContent = "Cancel";
}
confirmModal.classList.remove('hidden');
confirmOverlay.classList.remove('hidden');
updateBodyScrollLock();
const cleanup = (result) => {
confirmModal.classList.add('hidden');
confirmOverlay.classList.add('hidden');
confirmOkButton.removeEventListener('click', okClickHandler);
confirmCancelButton.removeEventListener('click', cancelClickHandler);
confirmOverlay.removeEventListener('click', overlayClickHandler);
updateBodyScrollLock();
resolve(result);
};
const okClickHandler = () => cleanup(true);
const cancelClickHandler = () => cleanup(false);
const overlayClickHandler = showCancel ? cancelClickHandler : okClickHandler;
confirmOkButton.addEventListener('click', okClickHandler);
confirmCancelButton.addEventListener('click', cancelClickHandler);
confirmOverlay.addEventListener('click', overlayClickHandler);
});
}
function showConfirm(options) {
return showModal({ ...options, okText: 'Confirm', okClass: 'bg-red-600 hover:bg-red-700', showCancel: true });
}
function showAlert({ title, message }) {
return showModal({ title, message, okText: 'OK', okClass: 'bg-blue-600 hover:bg-blue-700', showCancel: false });
}
async function handleSignOut() {
const confirmed = await showModal({ title: "Confirm Sign Out", message: "Signing out will stop cloud backups and sync. Any new chats on this device will not be saved to your account. Continue?", okText: "Sign Out", okClass: "bg-blue-600 hover:bg-blue-700", showCancel: true });
if (confirmed) {
await signOut(auth);
addSystemMessage('You have been signed out. Your data is now saved locally on this device.');
}
}
async function updateAccountUI() {