-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
1650 lines (1436 loc) · 66.7 KB
/
Copy pathmain.js
File metadata and controls
1650 lines (1436 loc) · 66.7 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
// ============================================================
// main.js — MoodSpace student app (ES Module)
// Connected to: Supabase Auth + DB, ModelsLab LLM AI
// Security: client-side rate limiting, input sanitization,
// auth guard, submission debounce, length caps
// ============================================================
// === IMPORTS ===
// Supabase via ESM CDN — no bundler needed
import { createClient } from 'https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2/+esm'
// Keys come from config-loader.js which reads either:
// • config.js (local dev, gitignored)
// • /api/config serverless function (Vercel — reads env vars automatically)
// window._configReady is a Promise set by config-loader.js
const _cfg = await window._configReady.catch(err => {
document.body.innerHTML =
`<p style="padding:2rem;font-family:sans-serif;color:#B33A3A">
⚠️ Could not load app config: ${err.message}
</p>`
throw err
})
const {
supabaseUrl, supabaseAnonKey,
stripePublishableKey: STRIPE_PUBLISHABLE_KEY,
stripePriceId: STRIPE_PRICE_ID,
} = _cfg
// ── Pro feature gates ────────────────────────────────────────
// Free: 3 AI/day, 7-day history, 2 themes
// Pro: Unlimited AI, 90-day history, all themes, export, badge
const PRO_PRICE = '$8.99 / month'
const FREE_AI_LIMIT = 3 // per day (Supabase-backed)
const FREE_THEMES = ['default', 'ocean'] // all others are pro-only
const AI_PERSONALITIES = {
friend: { label: '👫 Supportive Friend', desc: 'Warm, casual, like texting your best friend', tone: 'like a warm, caring best friend — casual, emoji-friendly, never preachy' },
mentor: { label: '🎓 Wise Mentor', desc: 'Thoughtful, grounded advice from someone who cares', tone: 'like a wise older mentor — thoughtful, honest, and encouraging without being preachy' },
coach: { label: '💪 Hype Coach', desc: 'Energetic, motivational, gets you moving', tone: 'like an energetic life coach — motivational, positive, action-focused and uplifting' },
therapist: { label: '🧘 Calm Guide', desc: 'Gentle, mindful, focuses on self-compassion', tone: 'like a calm mindfulness guide — gentle, non-judgmental, focused on self-compassion and breathing' },
journal: { label: '📓 Journaling Partner', desc: 'Asks deep questions to help you reflect', tone: 'like a journaling partner — ask one meaningful reflective question after validating their feelings, to deepen self-awareness' },
}
function isPro() { return !!currentProfile?.is_pro }
// Checks + increments today's AI usage.
// Uses Supabase (entries with ai_response today) as the source of truth —
// incognito / localStorage clearing can't bypass this.
async function checkDailyAiLimit() {
if (isPro()) return true // unlimited for pro
const start = new Date()
start.setHours(0, 0, 0, 0)
const { count, error } = await supabase
.from('entries')
.select('id', { count: 'exact', head: true })
.eq('user_id', currentUser.id)
.not('ai_response', 'is', null)
.gte('created_at', start.toISOString())
if (error) {
console.warn('[Limit] Could not check AI count, allowing:', error.message)
return true // fail open — don't block user if DB is slow
}
return (count || 0) < FREE_AI_LIMIT
}
// Redirect user to Stripe Checkout session URL
async function startStripeCheckout() {
const { data: { session } } = await supabase.auth.getSession()
if (!session?.access_token) throw new Error('No auth session')
const res = await fetch('/api/stripe-checkout', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${session.access_token}`,
},
})
const json = await res.json()
if (!res.ok) throw new Error(json.error || 'Could not start checkout')
return json.url
}
const supabase = createClient(supabaseUrl, supabaseAnonKey)
// ============================================================
// SECURITY — Rate limiting & guards
// ============================================================
// Tracks timestamps of recent actions in memory (cleared on page reload)
const rateLimiter = {
aiCalls: [], // timestamps of Gemini requests
saves: [], // timestamps of entry saves
// Returns true if the action is allowed, false if rate-limited
check(key, maxCount, windowMs) {
const now = Date.now()
this[key] = this[key].filter(t => now - t < windowMs)
if (this[key].length >= maxCount) return false
this[key].push(now)
return true
}
}
// Sanitizes user-supplied text before inserting into innerHTML
// Prevents XSS if any content ever reaches the DOM as HTML
function sanitize(str) {
const el = document.createElement('div')
el.textContent = str
return el.innerHTML
}
// Enforces max character length and strips dangerous patterns
function sanitizeInput(text, maxLen = 2000) {
if (typeof text !== 'string') return ''
return text.trim().substring(0, maxLen)
}
// Simple debounce — prevents double-submission on rapid clicks
function debounce(fn, delay = 600) {
let timer
return (...args) => {
clearTimeout(timer)
timer = setTimeout(() => fn(...args), delay)
}
}
// ============================================================
// STATE
// ============================================================
const state = {
currentTab: 'checkin', // 'checkin' | 'insights' | 'resources' | 'settings'
currentView: 'checkin', // 'checkin' | 'journal'
selectedMood: null,
selectedTopic: null,
isGeneratingAI: false,
aiResponse: null,
isSaving: false,
history: [], // populated from Supabase
theme: localStorage.getItem('ms-theme') || 'default',
chartType: localStorage.getItem('ms-chart') || 'bar', // 'bar' | 'line' | 'dots'
aiPersonality: localStorage.getItem('ms-ai-personality') || 'friend', // pro feature
affirmation: localStorage.getItem('ms-affirmation') || '', // pro feature
}
// Auth state
let currentUser = null
let currentProfile = null
// ============================================================
// STATIC DATA
// ============================================================
const moods = [
{ id: 'great', emoji: '😄', label: 'Great', color: 'var(--color-mood-great)', score: 5 },
{ id: 'good', emoji: '🙂', label: 'Good', color: 'var(--color-mood-good)', score: 4 },
{ id: 'okay', emoji: '😐', label: 'Okay', color: 'var(--color-mood-okay)', score: 3 },
{ id: 'low', emoji: '😔', label: 'Low', color: 'var(--color-mood-low)', score: 2 },
{ id: 'rough', emoji: '😢', label: 'Rough', color: 'var(--color-mood-rough)', score: 1 },
{ id: 'special', emoji: '💬', label: 'Something else', color: 'var(--color-mood-special)', score: 0, isSpecial: true }
]
const topics = [
{ id: 'heartbreak', label: '💔 Heartbreak' },
{ id: 'friend_drama', label: '👥 Friend drama' },
{ id: 'family', label: '🏠 Family' },
{ id: 'burnout', label: '📚 Burnout' },
{ id: 'loneliness', label: '😶 Loneliness' },
{ id: 'anger', label: '😤 Anger' },
{ id: 'not_sure', label: '🤷 Not sure' }
]
// Tips shown per topic in journal mode
const tips = {
heartbreak: [
{ icon: '💙', text: "Give yourself permission to grieve — it's a real loss." },
{ icon: '🔇', text: "Unfollow or mute if you need to. Protecting your peace isn't petty." }
],
friend_drama: [
{ icon: '🚪', text: "You don't owe anyone access to you when you're hurting." },
{ icon: '⏳', text: "Most fallouts look different after 48 hours. Give it time." }
],
family: [
{ icon: '🎧', text: "Find one small space that feels like yours — even just headphones in." },
{ icon: '💙', text: "You can love people and still need distance from them." }
],
burnout: [
{ icon: '✅', text: "Done is better than perfect right now. Finish, then improve." },
{ icon: '🧠', text: "Break it into 20-minute chunks. Your brain can do anything for 20 min." }
],
loneliness: [
{ icon: '💬', text: "Loneliness lies — it tells you no one cares but that's not true." },
{ icon: '📍', text: "Try showing up somewhere consistently. Belonging takes repetition." }
],
anger: [
{ icon: '❓', text: "Ask: what's underneath the anger — hurt? fear? disrespect?" },
{ icon: '🏃', text: "Move your body before you respond. Walk, run, punch a pillow." }
],
not_sure: [
{ icon: '🪑', text: "Not knowing what you feel is still a feeling. Sit in it." },
{ icon: '✏️', text: 'Try finishing: "I just wish someone knew that…"' }
],
default: [
{ icon: '🫁', text: "Take a deep breath in for 4 seconds, hold for 4, out for 6." },
{ icon: '🛋️', text: "Find a comfortable spot and drop your shoulders away from your ears." }
]
}
// ============================================================
// DOM REFS (set once after DOMContentLoaded)
// ============================================================
let mainContent, appHeader, mainTitle, mainSubtitle, tabButtons
// ============================================================
// INIT
// ============================================================
// top-level await above means DOMContentLoaded has already fired by the time
// this module resumes — run init directly instead of adding a listener
;(async () => {
mainContent = document.getElementById('main-content')
appHeader = document.getElementById('app-header')
mainTitle = document.getElementById('main-title')
mainSubtitle = document.getElementById('main-subtitle')
tabButtons = document.querySelectorAll('.tab-btn')
await verifyAuth()
// verifyAuth() may redirect unauthenticated users — stop here if so
if (!currentUser) return
// Restore saved theme before first render
applyTheme(state.theme)
setupTabBar()
await loadHistory()
render()
await handleStripeReturn()
})()
// ============================================================
// AUTH
// ============================================================
// Guards the page — redirects to auth.html if no session
async function verifyAuth() {
const { data: { session } } = await supabase.auth.getSession()
if (!session) {
window.location.href = 'auth.html'
return
}
currentUser = session.user
const { data: profile, error } = await supabase
.from('profiles')
.select('*')
.eq('id', currentUser.id)
.single()
if (error && error.code !== 'PGRST116') {
console.error('[Auth] Profile error:', error.message)
}
if (!profile) {
// First Google OAuth login — auto-create profile
const name = currentUser.user_metadata?.full_name
|| currentUser.user_metadata?.display_name
|| currentUser.email?.split('@')[0]
|| 'Friend'
await supabase.from('profiles').insert([{
id: currentUser.id,
email: currentUser.email,
display_name: name,
role: 'student',
streak_count: 0
}])
const { data: fresh } = await supabase
.from('profiles').select('*').eq('id', currentUser.id).single()
currentProfile = fresh
} else {
currentProfile = profile
}
// Counselors land on dashboard, not here
if (currentProfile?.role === 'counselor') {
window.location.href = 'dashboard.html'
return
}
console.log('[Auth] Signed in as:', currentProfile?.display_name)
}
// Signs out and returns to auth page
async function logout() {
await supabase.auth.signOut()
window.location.href = 'auth.html'
}
// ============================================================
// DATABASE — load history
// ============================================================
// Fetches the 7 most recent entries from Supabase for the insights tab
async function loadHistory() {
try {
let query = supabase
.from('entries')
.select('id, mood, mood_score, note, topic, created_at, is_journal')
.eq('user_id', currentUser.id)
.order('created_at', { ascending: false })
if (isPro()) {
// Pro: last 90 days
const cutoff = new Date()
cutoff.setDate(cutoff.getDate() - 90)
query = query.gte('created_at', cutoff.toISOString())
} else {
// Free: last 7 entries only
query = query.limit(7)
}
const { data, error } = await query
if (error) throw error
state.history = data || []
console.log('[DB] History loaded:', state.history.length, 'entries', isPro() ? '(Pro 90d)' : '(Free 7)')
} catch (err) {
console.error('[DB] History load error:', err.message)
state.history = []
}
}
// ============================================================
// RENDER LOOP
// ============================================================
function render() {
// Journal mode: hide the default app header
if (state.currentView === 'journal') {
appHeader.classList.add('hidden')
document.body.classList.add('journal-mode')
} else {
appHeader.classList.remove('hidden')
document.body.classList.remove('journal-mode')
}
// Update header text + user info
if (state.currentView !== 'journal') {
const name = currentProfile?.display_name || 'Friend'
const streak = currentProfile?.streak_count || 0
if (state.currentTab === 'checkin') {
mainTitle.textContent = `Hey ${name} 👋`
mainSubtitle.innerHTML = `
<span style="display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap">
<span style="color:var(--color-text-muted)">How are you feeling right now?</span>
<span style="display:flex;align-items:center;gap:10px">
<span style="color:var(--color-accent-secondary);font-weight:600;font-size:0.9rem">🔥 ${streak}d streak</span>
<button id="logout-btn"
style="font-size:0.78rem;color:var(--color-text-muted);padding:4px 10px;
border:1.5px solid #EAEBE9;border-radius:999px;background:none;cursor:pointer;
font-family:inherit;transition:0.15s ease"
onmouseover="this.style.color='var(--color-text-main)'"
onmouseout="this.style.color='var(--color-text-muted)'">
Log out
</button>
</span>
</span>`
document.getElementById('logout-btn')?.addEventListener('click', logout)
} else if (state.currentTab === 'insights') {
mainTitle.textContent = 'Insights'
mainSubtitle.textContent = 'Looking back at your week'
} else if (state.currentTab === 'resources') {
mainTitle.textContent = 'Resources'
mainSubtitle.textContent = 'Tools to help you anchor'
}
}
// Render active tab content
if (state.currentTab === 'checkin') {
mainContent.innerHTML = renderCheckin()
} else if (state.currentTab === 'insights') {
mainContent.innerHTML = renderInsights()
} else if (state.currentTab === 'resources') {
mainContent.innerHTML = renderResources()
} else if (state.currentTab === 'settings') {
mainContent.innerHTML = renderSettings()
}
attachEventListeners()
}
// ============================================================
// CHECKIN VIEW
// ============================================================
function renderCheckin() {
if (state.selectedMood === 'special' && state.currentView === 'journal') {
return renderJournalMode()
}
const moodButtonsHTML = moods.map(m => `
<button class="mood-btn ${m.id === state.selectedMood ? 'selected' : ''} ${m.isSpecial ? 'mood-special' : ''}"
data-mood="${m.id}">
<span class="mood-emoji">${m.emoji}</span>
<span class="mood-label">${m.label}</span>
</button>
`).join('')
// Always show the note area and save button once a mood is picked
const showActions = !!state.selectedMood
let aiBlockHTML = ''
if (state.isGeneratingAI) {
aiBlockHTML = `
<div class="ai-card animate-fade-in">
<div class="ai-card-title">Thinking of something for you…</div>
<div class="dot-typing"></div>
</div>`
} else if (state.aiResponse) {
aiBlockHTML = `
<div class="ai-card animate-fade-in">
<div class="ai-card-title">✨ Here for you</div>
<div class="ai-card-content">${sanitize(state.aiResponse)}</div>
</div>`
}
// Pro affirmation banner
const affirmationHTML = isPro() && state.affirmation
? `<div class="affirmation-banner animate-fade-in">💙 ${sanitize(state.affirmation)}</div>`
: ''
return `
<div class="view-container active">
${affirmationHTML}
<div class="mood-grid animate-fade-in">${moodButtonsHTML}</div>
<div class="input-wrapper animate-fade-in" style="${showActions ? '' : 'display:none'}">
<textarea id="checkin-note" class="short-note"
maxlength="500"
placeholder="What's making you feel this way? (Optional — you can save without writing)">${state._lastNote && !state.aiResponse ? state._lastNote : ''}</textarea>
</div>
${aiBlockHTML}
<div class="actions animate-fade-in" style="${showActions ? '' : 'display:none'}">
<button id="btn-ai-support" class="btn btn-primary ${state.isGeneratingAI ? 'loading' : ''}">
✨ Get AI Support
</button>
<button id="btn-save" class="btn btn-secondary" ${state.isSaving ? 'disabled' : ''}>
${state.isSaving ? 'Saving…' : 'Save check-in'}
</button>
</div>
</div>
`
}
function renderJournalMode() {
const topicsHTML = topics.map(t => `
<button class="topic-pill ${t.id === state.selectedTopic ? 'selected' : ''}"
data-topic="${t.id}">${t.label}</button>
`).join('')
let tipsHTML = ''
if (state.selectedTopic) {
const topicTips = tips[state.selectedTopic] || tips.default
tipsHTML = `<div class="animate-fade-in">` + topicTips.map(t => `
<div class="tip-card">
<div class="tip-icon">${t.icon}</div>
<div class="tip-text">${t.text}</div>
</div>
`).join('') + `</div>`
}
let aiBlockHTML = ''
if (state.isGeneratingAI) {
aiBlockHTML = `
<div class="ai-card journal-version animate-fade-in">
<div class="ai-card-title">Reading your thoughts…</div>
<div class="dot-typing" style="margin-left:15px;margin-top:10px"></div>
</div>`
} else if (state.aiResponse) {
aiBlockHTML = `
<div class="ai-card journal-version animate-fade-in" style="margin-bottom:24px">
<div class="ai-card-title">🌿 Gentle thought</div>
<div class="ai-card-content">${sanitize(state.aiResponse)}</div>
</div>`
}
return `
<div class="view-container active">
<button id="btn-back-checkin" class="btn-back">← Back to check-in</button>
<h2 class="title" style="font-size:1.6rem">This space is just for you.</h2>
<p class="subtitle" style="margin-bottom:16px">
You don't have to label it. Just write what's going on.
</p>
<div class="topic-scroll-row">${topicsHTML}</div>
${tipsHTML}
<div class="input-wrapper">
<textarea id="journal-note" class="journal-note"
maxlength="3000"
placeholder="Take a deep breath and start typing whenever you're ready…"></textarea>
</div>
${aiBlockHTML}
<div class="actions" style="${state.aiResponse ? 'display:none' : ''}">
<button id="btn-ai-support-journal" class="btn btn-primary ${state.isGeneratingAI ? 'loading' : ''}">
✨ Get AI Support
</button>
<button id="btn-save-journal" class="btn btn-secondary" ${state.isSaving ? 'disabled' : ''}>
${state.isSaving ? 'Saving…' : 'Save entry'}
</button>
</div>
${state.aiResponse ? `
<div class="actions animate-fade-in">
<button id="btn-save-after-ai" class="btn btn-primary" ${state.isSaving ? 'disabled' : ''}>
${state.isSaving ? 'Saving…' : '💾 Save entry'}
</button>
</div>` : ''}
</div>
`
}
// ============================================================
// INSIGHTS VIEW
// ============================================================
function renderInsights() {
// Build day map — keyed YYYY-MM-DD, one entry per day
const entryByDate = {}
state.history.forEach(entry => {
const d = new Date(entry.created_at)
const key = `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`
if (!entryByDate[key]) entryByDate[key] = entry
})
// Last 7 calendar days
const last7 = []
for (let i = 6; i >= 0; i--) {
const d = new Date()
d.setDate(d.getDate() - i)
const key = `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`
last7.push({ key, dayLabel: d.toLocaleDateString('en-US', { weekday: 'short' })[0] })
}
const hasAny = last7.some(({ key }) => entryByDate[key])
const W = 300, H = 100 // SVG viewport for line chart
// ── Bar chart ────────────────────────────────────────────────
function buildBar() {
return last7.map(({ key, dayLabel }) => {
const entry = entryByDate[key]
if (entry) {
const m = moods.find(x => x.id === entry.mood) || moods[2]
const score = entry.mood_score ?? 3
const height = Math.max(20, Math.round((score / 5) * 90))
return `<div class="chart-bar-group">
<div class="chart-bar" style="height:${height}px;background:${m.color}" title="${m.label}"></div>
<span class="chart-day">${dayLabel}</span></div>`
}
return `<div class="chart-bar-group">
<div class="chart-bar" style="height:20px;background:var(--color-bg-surface)"></div>
<span class="chart-day" style="opacity:0.35">${dayLabel}</span></div>`
}).join('')
}
// ── Line chart (inline SVG) ──────────────────────────────────
function buildLine() {
const pts = last7.map(({ key }, i) => {
const entry = entryByDate[key]
const score = entry ? (entry.mood_score ?? 3) : null
const x = Math.round((i / 6) * (W - 20) + 10)
const y = score !== null ? Math.round(H - (score / 5) * (H - 16) - 8) : null
return { x, y, score, entry, key }
})
// Polyline only through filled points
const filled = pts.filter(p => p.y !== null)
const polyline = filled.length > 1
? `<polyline fill="none" stroke="var(--color-primary)" stroke-width="2.5"
stroke-linecap="round" stroke-linejoin="round"
points="${filled.map(p => `${p.x},${p.y}`).join(' ')}" />`
: ''
// Gradient fill under the line
const fillPath = filled.length > 1
? `<path fill="url(#lineGrad)" opacity="0.18"
d="M${filled[0].x},${H} ${filled.map(p => `L${p.x},${p.y}`).join(' ')} L${filled[filled.length-1].x},${H} Z" />`
: ''
const dots = pts.map(p => {
if (p.y === null) return `<circle cx="${p.x}" cy="${H/2}" r="3" fill="var(--color-bg-surface)" />`
const m = p.entry ? moods.find(x => x.id === p.entry.mood) || moods[2] : moods[2]
return `<circle cx="${p.x}" cy="${p.y}" r="5" fill="${m.color}" stroke="#fff" stroke-width="2"
title="${m.label}" />`
}).join('')
const labels = pts.map(p =>
`<text x="${p.x}" y="${H + 14}" text-anchor="middle"
font-size="9" fill="${p.y !== null ? 'var(--color-text-muted)' : 'rgba(0,0,0,0.2)'}"
font-family="inherit" font-weight="600">${p.key.slice(-2) === new Date().toISOString().split('T')[0].slice(-2) && p === pts[6] ? 'T' : p.entry ? last7[pts.indexOf(p)].dayLabel : last7[pts.indexOf(p)].dayLabel}</text>`
).join('')
return `<svg viewBox="0 0 ${W} ${H+18}" width="100%" style="overflow:visible;display:block">
<defs>
<linearGradient id="lineGrad" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="var(--color-primary)" />
<stop offset="100%" stop-color="var(--color-primary)" stop-opacity="0" />
</linearGradient>
</defs>
${fillPath}${polyline}${dots}${labels}
</svg>`
}
// ── Dots / Scatter chart ─────────────────────────────────────
function buildDots() {
return `<div class="dots-chart">` +
last7.map(({ key, dayLabel }) => {
const entry = entryByDate[key]
const m = entry ? moods.find(x => x.id === entry.mood) || moods[2] : null
const score = entry?.mood_score ?? 0
const size = entry ? Math.max(28, Math.round((score / 5) * 52)) : 16
return `<div class="dots-col">
<div class="dots-bubble" style="${entry
? `width:${size}px;height:${size}px;background:${m.color};opacity:1`
: 'width:14px;height:14px;background:var(--color-bg-surface);opacity:0.5'
}" title="${entry ? m.label : 'No entry'}">
${entry ? `<span style="font-size:${Math.max(10, size*0.45)}px">${m.emoji}</span>` : ''}
</div>
<span class="chart-day" style="${!entry ? 'opacity:0.35' : ''}">${dayLabel}</span>
</div>`
}).join('') + `</div>`
}
// Pick active chart
const chartInner = {
bar: buildBar(),
line: buildLine(),
dots: buildDots(),
}[state.chartType] || buildBar()
const isLineOrDots = state.chartType !== 'bar'
// Chart type switcher
const chartSwitcher = `
<div class="chart-switcher">
${[['bar','bar_chart','Bar'],['line','show_chart','Line'],['dots','scatter_plot','Dots']].map(([type, icon, label]) => `
<button class="chart-type-btn ${state.chartType === type ? 'active' : ''}" data-chart="${type}">
<span class="material-symbols-outlined">${icon}</span>
${label}
</button>`).join('')}
</div>`
// Entry list
const entriesHTML = state.history.length > 0
? state.history.map(entry => {
const m = moods.find(x => x.id === entry.mood) || { emoji: '📝', label: 'Entry' }
const topic = topics.find(t => t.id === entry.topic)
const tagHtml = topic
? `<span style="font-size:0.72rem;background:rgba(0,0,0,0.05);padding:2px 8px;border-radius:12px;margin-left:6px">${topic.label}</span>`
: ''
const date = new Date(entry.created_at)
.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
const snippet = entry.note
? sanitize(entry.note.substring(0, 60)) + (entry.note.length > 60 ? '…' : '')
: m.label
return `<div class="entry-card">
<div class="entry-emoji">${m.emoji}</div>
<div class="entry-details">
<div class="entry-date">${date}${tagHtml}</div>
<div class="entry-snippet">${snippet}</div>
</div></div>`
}).join('')
: `<p style="color:var(--color-text-muted);font-size:0.9rem;text-align:center;padding:24px 0">
Check in every day to build your history 🌱</p>`
const streak = currentProfile?.streak_count || 0
const emptyMsg = !hasAny
? `<p style="position:absolute;inset:0;display:flex;align-items:center;justify-content:center;
color:var(--color-text-muted);font-size:0.9rem;text-align:center;padding:0 20px">
No check-ins yet — your chart will appear here 🌱</p>`
: ''
return `
<div class="view-container active">
<div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:24px">
<div style="background:var(--color-bg-card);border-radius:var(--radius-md);padding:20px;
text-align:center;box-shadow:var(--shadow-sm)">
<div id="ins-streak" style="font-size:2rem;font-weight:700;color:var(--color-accent-secondary)">${streak}</div>
<div style="font-size:0.82rem;color:var(--color-text-muted);margin-top:4px">🔥 Current streak</div>
</div>
<div style="background:var(--color-bg-card);border-radius:var(--radius-md);padding:20px;
text-align:center;box-shadow:var(--shadow-sm)">
<div id="ins-longest" style="font-size:2rem;font-weight:700;color:var(--color-accent-primary)">—</div>
<div style="font-size:0.82rem;color:var(--color-text-muted);margin-top:4px">🏆 Longest streak</div>
</div>
</div>
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:12px">
<h2 class="section-title" style="margin-bottom:0">Your week</h2>
${chartSwitcher}
</div>
<div class="chart-container ${isLineOrDots ? 'chart-alt' : ''}" style="position:relative">
${chartInner}${emptyMsg}
</div>
<h2 class="section-title">Recent entries</h2>
<div class="entries-list">${entriesHTML}</div>
</div>
`
}
// ============================================================
// RESOURCES VIEW
// ============================================================
function renderResources() {
return `
<div class="view-container active">
<h2 class="section-title">When you need it</h2>
<!-- Crisis — always first, tappable on mobile -->
<div class="resource-card crisis-card" style="cursor:default">
<div class="resource-info" style="width:100%">
<h3>Crisis Support</h3>
<p style="margin-bottom:12px;font-size:0.9rem;color:#8a3a3a">
You're not alone. Reach out — it's free, 24/7 and confidential.
</p>
<div style="display:flex;gap:10px;flex-wrap:wrap">
<a href="sms:741741?body=HOME" class="crisis-action-btn crisis-text">
<span class="material-symbols-outlined">sms</span>
Text HOME to 741741
</a>
<a href="tel:988" class="crisis-action-btn crisis-call">
<span class="material-symbols-outlined">call</span>
Call / Text 988
</a>
</div>
</div>
</div>
<div class="resource-card" id="card-breath" onclick="toggleResource('breath-detail','breath-arrow')">
<div class="resource-info">
<h3>Box breathing</h3>
<p>A 2-minute reset for your nervous system.</p>
</div>
<div class="resource-action" id="breath-arrow">🫁</div>
</div>
<div id="breath-detail"
style="display:none;background:var(--color-bg-card);border-radius:var(--radius-md);
padding:20px;margin-top:-8px;margin-bottom:12px;box-shadow:var(--shadow-sm)">
<p style="font-size:0.9rem;color:var(--color-text-muted);margin-bottom:16px">
Repeat 4 times. Works great before a test or a hard conversation.
</p>
<div style="display:flex;gap:8px">
${['Inhale<br>4 sec','Hold<br>4 sec','Exhale<br>4 sec','Hold<br>4 sec'].map(s => `
<div style="flex:1;background:rgba(139,184,136,0.12);border-radius:12px;padding:12px 6px;
text-align:center;font-size:0.8rem;font-weight:600;
color:var(--color-accent-primary);line-height:1.5">${s}</div>
`).join('')}
</div>
</div>
<div class="resource-card" onclick="toggleResource('ground-detail','ground-arrow')">
<div class="resource-info">
<h3>5-4-3-2-1 Grounding</h3>
<p>Bring your focus back to the present moment.</p>
</div>
<div class="resource-action" id="ground-arrow">🌿</div>
</div>
<div id="ground-detail"
style="display:none;background:var(--color-bg-card);border-radius:var(--radius-md);
padding:20px;margin-top:-8px;margin-bottom:12px;box-shadow:var(--shadow-sm)">
${[['5','things you can see'],['4','things you can touch'],
['3','things you can hear'],['2','things you can smell'],
['1','thing you can taste']].map(([n, s]) => `
<div style="display:flex;align-items:center;gap:12px;margin-bottom:12px">
<div style="width:30px;height:30px;border-radius:50%;background:var(--color-accent-primary);
color:white;display:flex;align-items:center;justify-content:center;
font-weight:700;font-size:0.85rem;flex-shrink:0">${n}</div>
<span style="font-size:0.92rem">${s}</span>
</div>`).join('')}
</div>
<div class="resource-card" onclick="toggleResource('move-detail','move-arrow')">
<div class="resource-info">
<h3>Move your body</h3>
<p>One of the fastest ways to shift your mood.</p>
</div>
<div class="resource-action" id="move-arrow">🚶</div>
</div>
<div id="move-detail"
style="display:none;background:var(--color-bg-card);border-radius:var(--radius-md);
padding:20px;margin-top:-8px;margin-bottom:12px;box-shadow:var(--shadow-sm)">
<ul style="padding-left:20px;line-height:2;font-size:0.92rem">
<li>10-minute walk outside (no phone)</li>
<li>20 jumping jacks or push-ups</li>
<li>Dance to one song, full out</li>
<li>5 minutes of stretching</li>
<li>Ride a bike, shoot hoops, kick a ball</li>
</ul>
</div>
</div>
`
}
// ============================================================
// SETTINGS VIEW
// ============================================================
const THEMES = {
// ── Free themes ─────────────────────────────────────────────
default: { label: '🌿 Terracotta', primary: '#9b452e', primaryContainer: '#ffad97', bg: '#fff8f1', surface: '#fceae0', surfaceLow: '#fff1e6', secondary: '#ffe0bd' },
ocean: { label: '🌊 Ocean', primary: '#1d6fa4', primaryContainer: '#b3daff', bg: '#f0f8ff', surface: '#daeeff', surfaceLow: '#edf6ff', secondary: '#d0ecff' },
// ── Pro-only themes ──────────────────────────────────────────
gold: { label: '✨ Gold', primary: '#a07000', primaryContainer: '#ffe082', bg: '#fffdf0', surface: '#fff8d6', surfaceLow: '#fffbe8', secondary: '#fff0b3' },
silver: { label: '🪙 Silver', primary: '#546e7a', primaryContainer: '#cfd8dc', bg: '#f8fafb', surface: '#e8eef1', surfaceLow: '#f1f5f7', secondary: '#dde6ea' },
rose: { label: '🌹 Rose Gold', primary: '#b5546a', primaryContainer: '#fcd0da', bg: '#fff5f7', surface: '#fde5ea', surfaceLow: '#fff0f3', secondary: '#fad7df' },
cherry: { label: '🌸 Cherry', primary: '#ad1457', primaryContainer: '#f8bbd0', bg: '#fff5f8', surface: '#fde0eb', surfaceLow: '#ffeef4', secondary: '#f9c8da' },
sunset: { label: '🌅 Sunset', primary: '#c0392b', primaryContainer: '#ffd5cc', bg: '#fff8f7', surface: '#ffe8e4', surfaceLow: '#fff3f1', secondary: '#ffd0c8' },
amethyst: { label: '💎 Amethyst', primary: '#6a1b9a', primaryContainer: '#e1bee7', bg: '#fdf5ff', surface: '#f3e5f5', surfaceLow: '#f8f0fc', secondary: '#e8d5f0' },
arctic: { label: '🧊 Arctic', primary: '#006494', primaryContainer: '#b2ebf2', bg: '#f0fdff', surface: '#d8f5f8', surfaceLow: '#eafbfc', secondary: '#c4eef3' },
sage: { label: '🍃 Sage', primary: '#4a6741', primaryContainer: '#c8e6c9', bg: '#f5faf5', surface: '#dff0df', surfaceLow: '#ecf6ec', secondary: '#d4ebd4' },
lavender: { label: '💜 Lavender', primary: '#6d3fa0', primaryContainer: '#ddd6fe', bg: '#faf5ff', surface: '#ede9fe', surfaceLow: '#f5f0ff', secondary: '#e9e0fd' },
forest: { label: '🌲 Forest', primary: '#2a6741', primaryContainer: '#b2f0cc', bg: '#f0fdf4', surface: '#dcf7e8', surfaceLow: '#edfaf3', secondary: '#c6f0d8' },
midnight: { label: '🌙 Midnight', primary: '#4f7cd4', primaryContainer: '#bfcfff', bg: '#f5f7ff', surface: '#e8edff', surfaceLow: '#f0f3ff', secondary: '#d8e0ff' },
}
function applyTheme(name) {
const t = THEMES[name] || THEMES.default
const r = document.documentElement
r.style.setProperty('--color-primary', t.primary)
r.style.setProperty('--color-accent-primary', t.primary)
r.style.setProperty('--color-accent-primary-hover', shadeColor(t.primary, -15))
r.style.setProperty('--color-primary-container', t.primaryContainer)
r.style.setProperty('--color-accent-special', t.primaryContainer)
r.style.setProperty('--color-bg-main', t.bg)
r.style.setProperty('--color-bg-journal', t.surfaceLow)
r.style.setProperty('--color-bg-surface', t.surface)
r.style.setProperty('--color-bg-surface-low', t.surfaceLow)
r.style.setProperty('--color-secondary-container', t.secondary)
state.theme = name
localStorage.setItem('ms-theme', name)
}
// Darken/lighten a hex color by amt (-255 to 255)
function shadeColor(hex, amt) {
const n = parseInt(hex.replace('#',''), 16)
const r = Math.min(255, Math.max(0, (n >> 16) + amt))
const g = Math.min(255, Math.max(0, ((n >> 8) & 0xff) + amt))
const b = Math.min(255, Math.max(0, (n & 0xff) + amt))
return '#' + [r,g,b].map(x => x.toString(16).padStart(2,'0')).join('')
}
function renderSettings() {
const name = sanitize(currentProfile?.display_name || 'Friend')
const email = sanitize(currentUser?.email || '')
const initials = (currentProfile?.display_name || 'F').charAt(0).toUpperCase()
const pro = isPro()
// Theme swatches — pro-only themes show a lock for free users
const themeButtons = Object.entries(THEMES).map(([key, t]) => {
const isFreeTheme = FREE_THEMES.includes(key)
const locked = !pro && !isFreeTheme
const active = state.theme === key
return `
<button class="theme-swatch ${active ? 'active' : ''} ${locked ? 'locked' : ''}"
data-theme="${key}" ${locked ? 'data-locked="1"' : ''}
style="background:${t.primary}" title="${t.label}${locked ? ' — Pro' : ''}">
${active ? '<span class="material-symbols-outlined" style="font-size:0.95rem;color:#fff">check</span>' : ''}
${locked ? '<span class="material-symbols-outlined" style="font-size:0.8rem;color:#fff;opacity:0.85">lock</span>' : ''}
</button>`
}).join('')
// AI personality buttons (pro only)
const personalityButtons = Object.entries(AI_PERSONALITIES).map(([key, p]) => `
<button class="personality-btn ${state.aiPersonality === key ? 'active' : ''}"
data-personality="${key}" ${!pro ? 'data-locked="1"' : ''}>
<span class="personality-icon">${p.label.split(' ')[0]}</span>
<span class="personality-name">${p.label.split(' ').slice(1).join(' ')}</span>
<span class="personality-desc">${p.desc}</span>
</button>`
).join('')
// AI usage display (Supabase count is async so we show status message)
const aiDisplay = pro
? `<span style="color:var(--color-primary);font-weight:700">Unlimited ✨</span>`
: `<span style="color:var(--color-text-muted)">${FREE_AI_LIMIT}/day — <a href="#" id="link-upgrade" style="color:var(--color-primary);font-weight:600">Upgrade for unlimited</a></span>`
// Pro badge or upgrade card
const proSection = pro ? `
<div class="settings-section pro-active-card">
<div style="display:flex;align-items:center;gap:10px;margin-bottom:8px">
<span class="pro-badge">PRO</span>
<span style="font-weight:700">MoodSpace Pro — Active</span>
</div>
<div style="font-size:0.85rem;color:var(--color-text-muted)">
Unlimited AI · Full history · All themes · ${PRO_PRICE}
</div>
<button id="btn-cancel-sub" class="btn-danger-pill" style="margin-top:14px;font-size:0.8rem">
Cancel subscription
</button>
</div>
` : `
<div class="settings-section upgrade-card">
<div class="upgrade-header">
<span class="pro-badge">PRO</span>
<span style="font-weight:800;font-size:1.1rem">Upgrade to Pro</span>
<span class="upgrade-price">${PRO_PRICE}</span>
</div>
<ul class="upgrade-features">
<li><span class="material-symbols-outlined">auto_awesome</span> Unlimited AI support every day</li>
<li><span class="material-symbols-outlined">history</span> 90-day mood history</li>
<li><span class="material-symbols-outlined">palette</span> All 5 color themes</li>
<li><span class="material-symbols-outlined">workspace_premium</span> Pro badge on your profile</li>
</ul>
<div id="stripe-checkout-area" style="margin-top:16px">
<a href="./checkout.html" style="text-decoration:none;display:block">
<button id="btn-stripe-checkout" class="btn btn-primary" style="width:100%;padding:14px;font-size:1rem;font-weight:700;border-radius:var(--radius-pill);background:var(--color-accent-primary);color:#fff;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M20 12V7a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v5"/><path d="M2 17h20"/><path d="M6 21h12"/></svg>
Upgrade to Pro — ${PRO_PRICE}
</button>
</a>
<p style="text-align:center;font-size:0.78rem;color:var(--color-text-muted);margin-top:8px">Secure payment via Stripe · Cancel anytime</p>
</div>
</div>
`
return `
<div class="view-container active">
<!-- Profile card -->
<div class="settings-profile-card">
<div class="settings-avatar-big">${initials}</div>
<div style="flex:1">
<div style="display:flex;align-items:center;gap:8px">
<span style="font-weight:700;font-size:1.05rem">${name}</span>
${pro ? '<span class="pro-badge">PRO</span>' : ''}
</div>
<div style="font-size:0.85rem;color:var(--color-text-muted)">${email}</div>
</div>
</div>
<!-- Pro status / upgrade -->
${proSection}
<!-- Profile section -->
<div class="settings-section">
<h2 class="settings-section-title">
<span class="material-symbols-outlined">person</span> Profile
</h2>
<div class="settings-group">
<label class="settings-label">Display name</label>
<input id="settings-name" class="settings-input" type="text"
value="${name}" maxlength="50" placeholder="Your name" />
</div>
<button id="btn-save-profile" class="btn btn-primary" style="margin-top:12px">
Save changes
</button>
</div>
<!-- AI usage -->
<div class="settings-section">
<h2 class="settings-section-title">
<span class="material-symbols-outlined">auto_awesome</span> AI Usage
</h2>
<div class="settings-row-info">
<div style="font-size:0.92rem">Daily AI requests</div>
<div style="font-size:0.92rem">${aiDisplay}</div>
</div>
</div>
<!-- Check-in reset -->
<div class="settings-section">
<h2 class="settings-section-title">
<span class="material-symbols-outlined">today</span> Today's Check-in
</h2>
<div class="settings-row-info">
<div>
<div style="font-weight:600;font-size:0.95rem">Reset today's entry</div>
<div style="font-size:0.82rem;color:var(--color-text-muted);margin-top:2px">
Delete today's check-in and start over
</div>
</div>
<button id="btn-reset-checkin" class="btn-danger-pill">Reset</button>