-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
661 lines (589 loc) · 23.1 KB
/
script.js
File metadata and controls
661 lines (589 loc) · 23.1 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
const firebaseConfig = {
apiKey: "AIzaSyCxAhTuPuNelY0IiWYvguR7sFxJ2dXAphQ",
authDomain: "future-self-mirror-server.firebaseapp.com",
projectId: "future-self-mirror-server"
};
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
function createParticles() {
const container = document.getElementById('particles');
for (let i = 0; i < 50; i++) {
const particle = document.createElement('div');
particle.className = 'particle';
particle.style.left = Math.random() * 100 + '%';
particle.style.animationDelay = Math.random() * 15 + 's';
particle.style.animationDuration = (Math.random() * 10 + 15) + 's';
container.appendChild(particle);
}
}
createParticles();
function typeText(el, text, speed = 22) {
return new Promise(resolve => {
el.textContent = "";
el.classList.add("typing");
let i = 0;
const timer = setInterval(() => {
el.textContent += text[i++];
if (i >= text.length) {
clearInterval(timer);
el.classList.remove("typing");
resolve();
}
}, speed);
});
}
function analyzeHabit(text) {
const patterns = {
mental: {
keywords: ["overthink", "stress", "anxiety", "negative", "worry", "ruminate", "panic", "fear", "doubt"],
subTypes: {
cognitive: ["overthink", "ruminate", "analyze"],
emotional: ["anxiety", "worry", "panic", "fear"],
selfTalk: ["negative", "doubt", "critic"]
}
},
behavioral: {
keywords: ["phone", "scroll", "instagram", "youtube", "gaming", "netflix", "social media", "tiktok", "shopping", "gambling"],
subTypes: {
digital: ["phone", "scroll", "instagram", "youtube", "tiktok", "gaming"],
consumption: ["netflix", "binge", "watch"],
compulsive: ["shopping", "gambling", "betting"]
}
},
productivity: {
keywords: ["procrastinate", "delay", "lazy", "avoid", "distract", "waste time", "unproductive"],
subTypes: {
avoidance: ["procrastinate", "delay", "avoid"],
distraction: ["distract", "wander", "unfocused"],
inertia: ["lazy", "unmotivated", "stuck"]
}
},
physical: {
keywords: ["junk", "unhealthy", "no exercise", "sedentary", "smoking", "drinking", "eating", "sugar", "caffeine"],
subTypes: {
nutrition: ["junk", "sugar", "eating", "food"],
substance: ["smoking", "drinking", "alcohol", "caffeine"],
movement: ["sedentary", "no exercise", "inactive"]
}
},
social: {
keywords: ["isolate", "avoid people", "lonely", "withdraw", "anti-social"],
subTypes: {
withdrawal: ["isolate", "withdraw", "hide"],
avoidance: ["avoid people", "anti-social"]
}
},
sleep: {
keywords: ["late", "insomnia", "sleep", "night", "tired"],
subTypes: {
timing: ["late", "night owl"],
quality: ["insomnia", "restless"]
}
}
};
let primaryType = "general";
let subType = null;
let maxScore = 0;
for (let type in patterns) {
const score = patterns[type].keywords.filter(w => text.includes(w)).length;
if (score > maxScore) {
maxScore = score;
primaryType = type;
for (let sub in patterns[type].subTypes) {
if (patterns[type].subTypes[sub].some(w => text.includes(w))) {
subType = sub;
break;
}
}
}
}
return { primaryType, subType };
}
function analyzeGoal(text) {
const patterns = {
relief: {
keywords: ["calm", "meditate", "peace", "relax", "breathe", "mindful", "zen"],
intensity: ["deep peace", "total calm"]
},
discipline: {
keywords: ["routine", "consistent", "discipline", "structure", "schedule", "habit", "regular"],
intensity: ["strict", "rigorous", "unwavering"]
},
growth: {
keywords: ["learn", "study", "skill", "career", "improve", "master", "develop", "grow"],
intensity: ["excel", "master", "expert"]
},
fitness: {
keywords: ["exercise", "gym", "workout", "run", "fit", "healthy", "strong", "athletic"],
intensity: ["transform", "athlete", "peak"]
},
creative: {
keywords: ["create", "write", "paint", "music", "art", "express"],
intensity: ["daily practice", "prolific"]
},
social: {
keywords: ["connect", "friends", "relationship", "communicate", "people"],
intensity: ["thriving", "deep connections"]
},
financial: {
keywords: ["save", "money", "budget", "invest", "financial"],
intensity: ["wealth", "financial freedom"]
}
};
let goalType = "general";
let ambitionLevel = "moderate";
let maxScore = 0;
for (let type in patterns) {
const score = patterns[type].keywords.filter(w => text.includes(w)).length;
if (score > maxScore) {
maxScore = score;
goalType = type;
if (patterns[type].intensity.some(w => text.includes(w))) {
ambitionLevel = "high";
}
}
}
return { goalType, ambitionLevel };
}
function analyzeSeverity(habitText, goalText) {
let score = 0;
if (["always", "every day", "daily", "constantly"].some(w => habitText.includes(w))) score += 3;
if (["can't stop", "addicted", "compulsive", "uncontrollable"].some(w => habitText.includes(w))) score += 4;
if (["hours", "all day", "entire day"].some(w => habitText.includes(w))) score += 2;
if (["multiple times", "repeatedly"].some(w => habitText.includes(w))) score += 2;
if (["sometimes", "occasionally", "rarely"].some(w => habitText.includes(w))) score -= 2;
if (["want to", "ready to"].some(w => goalText.includes(w))) score -= 1;
if (["trying", "attempting"].some(w => goalText.includes(w))) score += 1;
if (score >= 5) return { level: "severe", attempts: 0 };
if (score >= 3) return { level: "moderate", attempts: habitText.includes("tried") ? 1 : 0 };
return { level: "mild", attempts: habitText.includes("started") ? 1 : 0 };
}
function analyzeContext(habitText, goalText) {
const context = {
emotional: false,
environmental: false,
social: false,
timeConstrained: false,
identityDriven: false
};
if (["feel", "emotion", "stress", "anxiety", "sad", "angry"].some(w => habitText.includes(w))) {
context.emotional = true;
}
if (["home", "work", "room", "desk", "bed"].some(w => habitText.includes(w))) {
context.environmental = true;
}
if (["friends", "people", "social", "alone", "others"].some(w => habitText.includes(w) || goalText.includes(w))) {
context.social = true;
}
if (["morning", "evening", "night", "weekend", "schedule"].some(w => goalText.includes(w))) {
context.timeConstrained = true;
}
if (["become", "be someone", "type of person", "who I am"].some(w => goalText.includes(w))) {
context.identityDriven = true;
}
return context;
}
function buildSmartPrediction({ name, habitAnalysis, goalAnalysis, severityData, context }) {
const { primaryType: habitType, subType } = habitAnalysis;
const { goalType, ambitionLevel } = goalAnalysis;
const { level: severity, attempts } = severityData;
const frictionPatterns = {
severe: {
mental: "intense cognitive loops and emotional resistance",
behavioral: "powerful dopamine-driven urges and withdrawal symptoms",
productivity: "deep-rooted avoidance patterns and fear of failure",
physical: "strong physiological cravings and body-mind disconnection",
social: "profound isolation patterns and social anxiety",
sleep: "circadian disruption and hyperarousal states",
general: "deeply entrenched automatic behaviors"
},
moderate: {
mental: "recurring thought patterns and emotional discomfort",
behavioral: "habitual impulses and mild withdrawal effects",
productivity: "moderate resistance and distraction tendencies",
physical: "regular cravings and comfort-seeking behaviors",
social: "selective avoidance and social hesitation",
sleep: "irregular sleep-wake patterns",
general: "familiar comfort zones and routine resistance"
},
mild: {
mental: "occasional mental drift and minor stress responses",
behavioral: "situational temptations and brief impulses",
productivity: "intermittent procrastination and low motivation",
physical: "mild cravings triggered by specific contexts",
social: "sporadic withdrawal and minor social discomfort",
sleep: "occasional late nights",
general: "minor habit inertia"
}
};
const adaptationStrategies = {
mental: {
cognitive: "metacognitive awareness and thought defusion techniques",
emotional: "emotional regulation and distress tolerance skills",
selfTalk: "cognitive reframing and self-compassion practices"
},
behavioral: {
digital: "environmental design, friction tools, and replacement routines",
consumption: "scheduled exposure limits and alternative rewards",
compulsive: "urge surfing and delay strategies"
},
productivity: {
avoidance: "exposure therapy to difficult tasks and micro-commitment strategies",
distraction: "attention training and single-tasking protocols",
inertia: "activation energy reduction and momentum-building rituals"
},
physical: {
nutrition: "meal planning, environment control, and nutritional awareness",
substance: "gradual reduction protocols and substitute behaviors",
movement: "identity-based exercise and incremental activity increase"
},
social: {
withdrawal: "graduated exposure to social situations and connection rituals",
avoidance: "social skills practice and relationship investment"
},
sleep: {
timing: "chronotherapy and consistent wake times",
quality: "sleep hygiene optimization and stress management"
},
general: "pattern interruption and environmental restructuring"
};
const outcomeProjections = {
relief: {
high: "profound inner peace and emotional mastery",
moderate: "consistent calm and stress resilience",
low: "baseline relaxation and reduced anxiety"
},
discipline: {
high: "effortless consistency and systems-driven living",
moderate: "reliable routines and structured days",
low: "improved follow-through on commitments"
},
growth: {
high: "accelerated skill mastery and career transformation",
moderate: "steady competence building and expanded capabilities",
low: "noticeable improvement in targeted areas"
},
fitness: {
high: "physical transformation and athletic identity",
moderate: "consistent fitness and improved health markers",
low: "regular movement and energy increase"
},
creative: {
high: "prolific output and artistic identity",
moderate: "regular creative practice and skill development",
low: "occasional creative expression"
},
social: {
high: "thriving social life and deep connections",
moderate: "quality relationships and social confidence",
low: "reduced isolation and improved connections"
},
financial: {
high: "financial freedom and wealth accumulation",
moderate: "financial stability and growing savings",
low: "better money management and reduced stress"
},
general: {
high: "personal transformation and life optimization",
moderate: "sustainable life improvements and balance",
low: "positive changes and increased wellbeing"
}
};
const predictions = [];
let phase1 = `${name} begins confronting ${frictionPatterns[severity][habitType]}`;
if (context.emotional) {
phase1 += ", particularly when emotional triggers arise";
}
if (context.environmental) {
phase1 += ". Environmental cues initially provoke strong habit impulses";
}
if (attempts > 0) {
phase1 += `. Unlike previous attempts, awareness of failure patterns creates strategic advantage`;
}
phase1 += ".";
predictions.push(phase1);
const strategy = subType
? adaptationStrategies[habitType][subType]
: adaptationStrategies[habitType];
let phase2 = `Over weeks 3-8, ${strategy} becomes the primary change mechanism`;
if (context.timeConstrained) {
phase2 += ", integrated into specific daily time blocks";
}
if (context.social) {
phase2 += ", supported by social accountability structures";
}
phase2 += ". Willpower gradually becomes unnecessary.";
predictions.push(phase2);
let phase3;
if (severity === "severe") {
phase3 = `Months 3-4 mark the identity inflection point. ${name} no longer identifies with the old habit. Behavioral choices align with the emerging self-concept rather than requiring active resistance.`;
} else if (severity === "moderate") {
phase3 = `By month 3, the habit loses its grip on daily decisions. ${name} experiences increasing moments where the new behavior feels natural, not forced.`;
} else {
phase3 = `Within 8-10 weeks, the old habit becomes an occasional temptation rather than a default response. Decision-making shifts from effortful to intuitive.`;
}
predictions.push(phase3);
const outcome = outcomeProjections[goalType]
? outcomeProjections[goalType][ambitionLevel]
: outcomeProjections.general[ambitionLevel];
let phase4 = `By month 6, ${outcome} becomes the lived reality`;
if (context.identityDriven) {
phase4 += `. The transformation reflects ${name}'s core identity rather than external achievements`;
}
phase4 += `. What once required discipline now operates automatically—a new baseline has been established.`;
predictions.push(phase4);
return predictions;
}
function buildSmartTimeline({ habitAnalysis, goalAnalysis, severityData, context }) {
const { primaryType: habitType } = habitAnalysis;
const { level: severity } = severityData;
const timelineTemplates = {
severe: {
mental: [
"Intense awareness of thought patterns emerges",
"Emotional regulation skills develop under pressure",
"Thought-behavior gap widens noticeably",
"New neural pathways strengthen through repetition",
"Old patterns lose their automatic quality",
"Mental clarity becomes the new baseline"
],
behavioral: [
"Withdrawal symptoms peak and begin declining",
"Environmental controls prevent automatic triggers",
"Urge intensity decreases by 40-50%",
"Alternative rewards become genuinely satisfying",
"Identity shifts from 'recovering' to 'changed'",
"Old behavior feels foreign and unappealing"
],
productivity: [
"Task avoidance confronted with micro-commitments",
"Small wins accumulate, reducing fear response",
"Momentum builds through consistent small actions",
"Procrastination loses its emotional charge",
"Proactive behavior becomes more frequent than reactive",
"High-value work becomes energizing rather than draining"
],
physical: [
"Physical cravings intensify before declining",
"Body resets to natural hunger/energy rhythms",
"Health improvements become noticeable feedback",
"Physical sensations guide decisions automatically",
"Energy and vitality replace previous numbness",
"Physical identity transforms completely"
],
default: [
"Strong resistance and discomfort surface",
"Coping mechanisms develop and strengthen",
"Behavioral control increases significantly",
"New patterns feel increasingly natural",
"Old habit loses its psychological grip",
"Transformation solidifies as permanent identity"
]
},
moderate: {
mental: [
"Mental patterns become visible through observation",
"Moments of choice expand between trigger and response",
"Stress response system begins recalibrating",
"Cognitive flexibility increases noticeably",
"Emotional reactivity decreases substantially",
"Mental peace becomes accessible on-demand"
],
behavioral: [
"Temptations arise but feel manageable",
"Replacement behaviors begin satisfying similar needs",
"Slip-ups become learning opportunities, not failures",
"Consistency builds through small daily decisions",
"Behavior aligns with values more often than not",
"New identity as disciplined person fully integrates"
],
productivity: [
"Resistance noticed and worked with rather than against",
"Task initiation becomes easier through reduced friction",
"Productive periods lengthen incrementally each week",
"Focus capacity strengthens through deliberate practice",
"Procrastination becomes the exception, not the rule",
"Work satisfaction and output quality both increase"
],
physical: [
"Body awareness increases, cravings become readable",
"Healthier choices feel more rewarding than expected",
"Physical feedback loop reinforces positive behaviors",
"Energy levels stabilize and improve",
"Body confidence grows with visible changes",
"Physical wellbeing becomes a core life priority"
],
default: [
"Initial resistance gives way to curiosity",
"Behavioral adjustments tested and refined",
"Consistency patterns emerge and stabilize",
"Confidence in change process deepens",
"Old habit feels less compelling",
"New identity locks in permanently"
]
},
mild: {
mental: [
"Awareness of patterns develops gradually",
"Small mindset shifts accumulate",
"Mental flexibility improves through practice",
"Emotional responses become more regulated",
"Clarity increases in daily decision-making",
"Mental wellbeing feels substantially improved"
],
behavioral: [
"Behavioral experiments begin with low stakes",
"Positive feedback reinforces new choices",
"Habit cues lose their automatic quality",
"New routines establish and feel comfortable",
"Behavioral identity shifts incrementally",
"Desired behavior operates on autopilot"
],
productivity: [
"Small productivity wins build early momentum",
"Task approach anxiety diminishes",
"Work sessions become more focused",
"Completion rate increases across projects",
"Productive identity strengthens",
"High performance feels natural and sustainable"
],
physical: [
"Initial changes feel manageable and positive",
"Body responds positively to new patterns",
"Physical routines establish without strain",
"Health markers improve steadily",
"Physical capacity expands noticeably",
"Healthy lifestyle becomes effortless default"
],
default: [
"Awareness and intention set the foundation",
"Behavioral experiments yield positive results",
"Consistency builds through gentle persistence",
"Confidence in process grows steadily",
"Old habit fades into background",
"New lifestyle fully integrated"
]
}
};
const template = timelineTemplates[severity][habitType] || timelineTemplates[severity].default;
return template.map((item, index) => {
let enhanced = item;
if (index === 1 && context.environmental) {
enhanced += " with strategic environment redesign";
}
if (index === 2 && context.social) {
enhanced += " through social support and accountability";
}
if (index === 4 && context.identityDriven) {
enhanced += " as core identity transformation deepens";
}
return enhanced;
});
}
function smoothScrollToBottom() {
setTimeout(() => {
window.scrollTo({
top: document.body.scrollHeight,
behavior: "smooth"
});
}, 100);
}
async function generateFuture() {
const name = document.getElementById("name").value.trim();
const bad = document.getElementById("currentHabit").value.toLowerCase();
const good = document.getElementById("newHabit").value.toLowerCase();
if (!name || !bad || !good) {
alert("Please fill in all fields to reveal your future.");
return;
}
const generateBtn = document.getElementById("generateBtn");
generateBtn.disabled = true;
generateBtn.innerHTML = '<span>✨ Generating...</span>';
const habitAnalysis = analyzeHabit(bad);
const goalAnalysis = analyzeGoal(good);
const severityData = analyzeSeverity(bad, good);
const context = analyzeContext(bad, good);
const result = document.getElementById("result");
result.classList.remove("hidden");
smoothScrollToBottom();
const predictions = buildSmartPrediction({
name,
habitAnalysis,
goalAnalysis,
severityData,
context
});
const list = document.getElementById("futureList");
list.innerHTML = "";
const progressBar = document.getElementById("progressBar");
let progress = 0;
for (let i = 0; i < predictions.length; i++) {
const li = document.createElement("li");
list.appendChild(li);
smoothScrollToBottom();
await typeText(li, predictions[i]);
progress = ((i + 1) / (predictions.length + 6)) * 100;
progressBar.style.width = progress + "%";
await new Promise(r => setTimeout(r, 300));
smoothScrollToBottom();
}
const timelineData = buildSmartTimeline({
habitAnalysis,
goalAnalysis,
severityData,
context
});
const timeline = document.getElementById("timeline");
timeline.innerHTML = "";
for (let i = 0; i < 6; i++) {
const div = document.createElement("div");
div.className = "month";
const h4 = document.createElement("h4");
const p = document.createElement("p");
div.append(h4, p);
timeline.appendChild(div);
smoothScrollToBottom();
await typeText(h4, `Month ${i + 1}`, 30);
await typeText(p, timelineData[i], 18);
progress = ((predictions.length + i + 1) / (predictions.length + 6)) * 100;
progressBar.style.width = progress + "%";
await new Promise(r => setTimeout(r, 200));
smoothScrollToBottom();
}
document.getElementById("newBtn").classList.remove("hidden");
generateBtn.disabled = false;
generateBtn.innerHTML = '<span>✨ Reveal My Future</span>';
try {
await db.collection("futureSelf").add({
name,
currentHabit: bad,
newHabit: good,
habitType: habitAnalysis.primaryType,
habitSubType: habitAnalysis.subType,
goalType: goalAnalysis.goalType,
ambitionLevel: goalAnalysis.ambitionLevel,
severity: severityData.level,
previousAttempts: severityData.attempts,
context: context,
predictions: predictions,
timeline: timelineData,
createdAt: firebase.firestore.FieldValue.serverTimestamp()
});
} catch (error) {
console.error("Firebase save error:", error);
}
}
function resetPrediction() {
document.getElementById("name").value = "";
document.getElementById("currentHabit").value = "";
document.getElementById("newHabit").value = "";
document.getElementById("result").classList.add("hidden");
document.getElementById("newBtn").classList.add("hidden");
document.getElementById("futureList").innerHTML = "";
document.getElementById("timeline").innerHTML = "";
document.getElementById("progressBar").style.width = "0%";
window.scrollTo({
top: 0,
behavior: "smooth"
});
}