-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2899 lines (2559 loc) · 160 KB
/
app.js
File metadata and controls
2899 lines (2559 loc) · 160 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
/**
* AuraStream Landing Page Script v10.0 (Advanced CSS Effects)
* - REMOVED Three.js module for a lightweight, performant CSS background.
* - ADDED Interactive cursor spotlight module.
* - ADDED Interactive phone demo player module.
* - ADDED Animated number counters for the analytics dashboard.
* - All other features, including Firebase auth, modals, and API fetching, are fully retained.
*/
// --- Main Application Object ---
const AuraStreamApp = {
// --- Configuration ---
config: {
// VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
// CRITICAL: REPLACE WITH YOUR VALID TMDB API KEY! GET ONE FROM themoviedb.org (Free)
// VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
TMDB_API_KEY: '431fb541e27bceeb9db2f4cab69b54e1', // <<<--- PUT YOUR REAL, ACTIVE KEY HERE
TMDB_BASE_URL: 'https://api.themoviedb.org/3',
IMAGE_BASE_URL: 'https://image.tmdb.org/t/p/',
POSTER_SIZE: 'w500',
PROFILE_SIZE: 'w185',
BACKDROP_SIZE: 'w1280',
HERO_BACKDROP_SIZE: 'original',
YOUTUBE_EMBED_URL: 'https://www.youtube.com/embed/',
CONTENT_SHELVES: [
{ id: 'trending-movie', title: 'Trending Movies', endpoint: '/trending/movie/week', containerSelector: '#trending-movies-scroll', type: 'movie' },
{ id: 'popular-tv', title: 'Popular TV Shows', endpoint: '/tv/popular', containerSelector: '#popular-tv-scroll', type: 'tv' },
{ id: 'toprated-movie', title: 'Top Rated Movies', endpoint: '/movie/top_rated', containerSelector: '#toprated-movies-scroll', type: 'movie' },
],
HERO_UPDATE_INTERVAL: 90000,
AOS_CONFIG: { duration: 700, once: true, offset: 80, easing: 'ease-out-cubic' },
SCROLL_DEBOUNCE: 150,
RESIZE_DEBOUNCE: 250,
LOADING_SCREEN_FADE_DURATION: 700,
GALLERY_AUTO_ROTATE_DELAY: 12000,
GALLERY_AUTO_ROTATE_INTERVAL: 6000,
AUTH_REDIRECT_URL: 'app.html',
DEBUG_MODE: true,
firebaseConfig: {
apiKey: "AIzaSyDp2V0ULE-32AcIJ92a_e3mhMe6f6yZ_H4",
authDomain: "sm4movies.firebaseapp.com",
projectId: "sm4movies",
storageBucket: "sm4movies.appspot.com",
messagingSenderId: "277353836953",
appId: "1:277353836953:web:85e02783526c7cb58de308"
}
},
// --- Application State ---
state: {
heroMovie: null,
featuredTrailerMovieId: null,
movieVideosCache: new Map(),
shelfScrollData: new Map(),
isMobileMenuOpen: false,
librariesLoaded: { bootstrap: false, aos: false },
galleryAutoRotateTimeout: null,
galleryAutoRotateInterval: null,
isGalleryDragging: false,
domReady: false,
initializationComplete: false,
apiKeyValid: false,
isLoggedIn: false,
currentUser: null,
firebaseApp: null,
firebaseAuth: null,
firebaseStorage: null,
firebaseFirestore: null,
authListenerUnsubscribe: null
},
// --- DOM Element Cache ---
elements: {},
// --- Utility Functions ---
utils: {
log: function(message, ...optionalParams) { if (AuraStreamApp.config.DEBUG_MODE) console.log(`[AuraStream] ${message}`, ...optionalParams); },
error: function(message, ...optionalParams) { console.error(`[AuraStream Error] ${message}`, ...optionalParams); },
warn: function(message, ...optionalParams) { console.warn(`[AuraStream Warn] ${message}`, ...optionalParams); },
escapeHtml: (unsafe) => { if (unsafe === null || typeof unsafe === 'undefined') return ''; return String(unsafe).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'"); },
debounce: (func, delay) => { let timeoutId; return (...args) => { clearTimeout(timeoutId); timeoutId = setTimeout(() => { func.apply(this, args); }, delay); }; },
fetchTMDB: async (endpoint, params = {}) => {
const config = AuraStreamApp.config; const utils = AuraStreamApp.utils;
if (!AuraStreamApp.state.apiKeyValid) { utils.error("API Key is invalid. Fetch aborted."); return null; }
const defaultParams = { api_key: config.TMDB_API_KEY, language: 'en-US' };
const urlParams = new URLSearchParams({ ...defaultParams, ...params });
const url = `${config.TMDB_BASE_URL}${endpoint}?${urlParams.toString()}`;
try {
const response = await fetch(url);
if (!response.ok) {
let errorData = { status_message: `HTTP error! Status: ${response.status}` }; try { errorData = await response.json(); } catch (e) {}
utils.error(`TMDB API Error ${response.status} for ${endpoint}:`, errorData); if (response.status === 401) { AuraStreamApp.state.apiKeyValid = false; AuraStreamApp.modules.loadingScreen.showError("Invalid API Key"); } return null;
}
return await response.json();
} catch (error) { utils.error(`TMDB Fetch Network Error (${endpoint}):`, error); AuraStreamApp.modules.loadingScreen.showError("Network Error"); return null; }
},
getLoadingTextHTML: (text = "Loading...") => `<div class="loading-shelf-text w-100 d-flex align-items-center justify-content-center py-4" role="status"><div class="loading-spinner me-2"></div> ${AuraStreamApp.utils.escapeHtml(text)}</div>`,
getErrorTextHTML: (text = "Could not load content.") => `<div class="error-shelf-text w-100 d-flex align-items-center justify-content-center py-4 text-danger" role="alert"><i class="bi bi-exclamation-triangle-fill me-2"></i> ${AuraStreamApp.utils.escapeHtml(text)}</div>`,
getSkeletonCardHTML: () => `<div class="movie-card skeleton-placeholder" aria-hidden="true"><div class="card-image-wrapper skeleton-item"></div><div class="card-content"><div class="skeleton-item title mb-2"></div><div class="skeleton-item meta"></div></div><style>.skeleton-item{background:linear-gradient(110deg,rgba(var(--border-color),.4) 8%,rgba(var(--border-color),.6) 18%,rgba(var(--border-color),.4) 33%);background-size:200% 100%;border-radius:var(--radius-sm);animation:1.8s pulse-skeleton linear infinite;}.skeleton-placeholder .title{height:1rem;width:85%;}.skeleton-placeholder .meta{height:.7rem;width:55%;}@keyframes pulse-skeleton{0%{background-position:100% 0}100%{background-position:-100% 0}}</style></div>`,
getSkeletonShelfHTML: (count = 6) => { let h = ''; for (let i = 0; i < count; i++) h += AuraStreamApp.utils.getSkeletonCardHTML(); return h; },
formatDate: (d) => { if (!d) return 'N/A'; try { return new Date(d).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }); } catch (e) { return 'Invalid Date'; } },
getYear: (d) => { if (!d) return ''; try { return new Date(d).getFullYear(); } catch (e) { return ''; } },
fetchMovieVideos: async function(movieId) { const utils=AuraStreamApp.utils;if(AuraStreamApp.state.movieVideosCache.has(movieId))return AuraStreamApp.state.movieVideosCache.get(movieId);if(!movieId)return[];const data=await utils.fetchTMDB(`/movie/${movieId}/videos`);if(!data){AuraStreamApp.state.movieVideosCache.set(movieId,[]);return[]}const videos=data?.results?.filter(v=>v.site==='YouTube')||[];AuraStreamApp.state.movieVideosCache.set(movieId,videos);return videos},
getBestTrailer: (vids) => { if(!vids||vids.length===0)return null;const t=vids.find(v=>v.type==='Trailer'&&v.official);if(t)return t;const ot=vids.find(v=>v.type==='Teaser'&&v.official);if(ot)return ot;const at=vids.find(v=>v.type==='Trailer');if(at)return at;const ayt=vids.find(v=>v.type==='Teaser');if(ayt)return ayt;return vids[0]||null },
setCopyrightYear: () => { try { const el = AuraStreamApp.elements.copyYear; if(el) el.textContent = new Date().getFullYear(); } catch(e) { AuraStreamApp.utils.error("Error setting copyright year:", e); } },
getInitials: (name = '', email = '') => { if (name && name.trim().length > 0) { const parts = name.trim().split(' '); if (parts.length > 1) { return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase(); } else if (parts[0].length > 0) { return parts[0].substring(0, 2).toUpperCase(); } } if (email && email.includes('@')) { return email[0].toUpperCase(); } return '??'; },
},
// --- API Key Validation ---
validateApiKey: function() {
const key = this.config.TMDB_API_KEY;
this.state.apiKeyValid = (key && key !== 'YOUR_TMDB_API_KEY_HERE' && key.length >= 32);
if (!this.state.apiKeyValid) {
this.utils.error(">>> ACTION REQUIRED: Set a valid TMDB API key in config. <<<");
} else {
this.utils.log("TMDB API Key structure appears OK.");
}
},
// --- Display Data Loading Errors ---
displayDataLoadingErrors: function(message = "Cannot load data: Check API Key or Network.") {
const utils = this.utils;
const errorHtml = utils.getErrorTextHTML(message);
this.modules.hero.handleInitialLoadFailure(message);
this.config.CONTENT_SHELVES.forEach(shelf => {
const container = document.querySelector(shelf.containerSelector);
if (container) container.innerHTML = errorHtml;
});
this.modules.trailerFeature.displayError(message);
this.modules.analyticsDashboard.displayError(message);
},
// --- Initialization ---
/*init: function() {
document.addEventListener('DOMContentLoaded', () => {
if (this.state.domReady) return;
this.utils.log("DOM Loaded. Starting App Initialization.");
this.state.domReady = true;
try {
if (!this.initDomElements()) throw new Error("Essential DOM elements missing.");
this.validateApiKey();
this.checkLibraries();
if (!this.initializeFirebase()) {
this.utils.error("Firebase initialization failed, but attempting public data load.");
}
this.initSyncModules();
this.initVisualLibraries();
// Async data loading is now triggered by the Firebase onAuthStateChanged listener.
this.utils.log(`AuraStream Initial Sync Setup Complete. API Key Valid: ${this.state.apiKeyValid}`);
} catch (error) {
this.utils.error("CRITICAL ERROR during Initialization:", error);
document.body.innerHTML = `<div style="padding: 20px; color: red;"><h1>Init Error</h1><p>Check console (F12).</p><pre>${error.message}</pre></div>`;
}
});
},*/
init: function() {
document.addEventListener('DOMContentLoaded', () => {
if (this.state.domReady) return;
this.utils.log("DOM Loaded. Starting App Initialization.");
try {
if (!this.initDomElements()) throw new Error("Essential DOM elements missing.");
this.validateApiKey();
this.checkLibraries();
if (!this.initializeFirebase()) {
this.utils.error("Firebase initialization failed, but attempting public data load.");
}
this.initSyncModules();
this.initVisualLibraries();
// Async data loading is now triggered by the Firebase onAuthStateChanged listener.
this.utils.log(`AuraStream Initial Sync Setup Complete. API Key Valid: ${this.state.apiKeyValid}`);
} catch (error) {
this.utils.error("CRITICAL ERROR during Initialization:", error);
document.body.innerHTML = `<div style="padding: 20px; color: red;"><h1>Init Error</h1><p>Check console (F12).</p><pre>${error.message}</pre></div>`;
}
});
},
initializeFirebase: function() {
const { firebaseConfig } = this.config;
const { state, utils, modules } = this;
if (!firebaseConfig?.apiKey || !firebaseConfig?.authDomain || !firebaseConfig?.projectId) {
utils.error("Firebase configuration missing or incomplete.");
return false;
}
if (typeof firebase === 'undefined' || !firebase.app || !firebase.auth) {
utils.error("Required Firebase SDKs not loaded.");
return false;
}
try {
if (!state.firebaseApp) {
state.firebaseApp = firebase.initializeApp(firebaseConfig);
state.firebaseAuth = firebase.auth();
state.firebaseStorage = firebase.storage ? firebase.storage() : null;
state.firebaseFirestore = firebase.firestore ? firebase.firestore() : null;
}
if (!state.authListenerUnsubscribe && state.firebaseAuth) {
state.authListenerUnsubscribe = state.firebaseAuth.onAuthStateChanged(user => {
const isInitialAuthCheck = !state.initializationComplete;
utils.log(`Firebase onAuthStateChanged: User is ${user ? 'LOGGED IN' : 'LOGGED OUT'}. Initial Check: ${isInitialAuthCheck}`);
state.isLoggedIn = !!user;
state.currentUser = user ? { uid: user.uid, email: user.email, displayName: user.displayName, photoURL: user.photoURL } : null;
modules.auth.updateAuthUI();
if (isInitialAuthCheck) {
modules.loadingScreen.hide(); // Hide loading screen once auth is resolved
if (state.apiKeyValid) {
this.runAsyncInits();
} else {
this.displayDataLoadingErrors();
}
state.initializationComplete = true;
}
});
}
return true;
} catch (error) {
utils.error("CRITICAL Firebase initialization failed:", error);
return false;
}
},
checkLibraries: function() {
this.state.librariesLoaded.bootstrap = typeof bootstrap !== 'undefined';
this.state.librariesLoaded.aos = typeof AOS !== 'undefined';
this.utils.log("Libraries Checked:", this.state.librariesLoaded);
},
initDomElements: function() {
this.utils.log("Caching DOM Elements...");
this.elements = {
loadingScreen: document.querySelector('.loading-screen'),
spotlight: document.querySelector('.spotlight'),
navbar: document.querySelector('.landing-navbar'),
backToTopBtn: document.getElementById('back-to-top'),
mobileMenuToggle: document.getElementById('mobile-menu-toggler'),
mobileMenuClose: document.getElementById('mobile-menu-close'),
mobileMenu: document.getElementById('mobile-menu'),
offcanvasOverlay: document.getElementById('offcanvas-overlay'),
heroSection: document.getElementById('hero'),
heroBgImage: document.getElementById('hero-bg-image'),
heroTitle: document.getElementById('hero-title'),
heroOverview: document.getElementById('hero-overview'),
heroInfoContainer: document.getElementById('hero-info-container'),
heroWatchTrailerBtn: document.getElementById('hero-watch-trailer-btn'),
heroMoreInfoBtn: document.getElementById('hero-more-info-btn'),
expandingGallery: document.getElementById('expanding-gallery'),
discoverTabs: document.querySelectorAll('.discover-tab'),
discoverContentPanels: document.querySelectorAll('.discover-content'),
panelTrending: document.getElementById('panel-trending'),
panelUpcoming: document.getElementById('panel-upcoming'),
gemFinderStrip: document.getElementById('gem-finder-strip'),
gemFinderButton: document.getElementById('gem-finder-button'),
gemFinderResult: document.getElementById('gem-finder-result'),
phoneDemoPlayer: document.getElementById('interactive-demo'),
youtubePlayer: document.getElementById('youtubePlayer'),
aiCanvas: document.getElementById('ai-canvas'),
aiHubContainer: document.getElementById('ai-hub-container'),
universeExplorerSection: document.getElementById('universe-explorer'),
universeBgImage: document.getElementById('universe-bg-image'),
universeTitle: document.getElementById('universe-title'),
universeOverview: document.getElementById('universe-overview'),
universeTimelineContainer: document.getElementById('universe-timeline-container'),
creatorsGrid: document.querySelector('.creators-grid'),
playButtonOverlay: document.getElementById('play-button-demo'),
trailerFeatureSection: document.getElementById('trailer-feature'),
trailerFeatureTitle: document.getElementById('trailer-feature-title'),
trailerFeatureDesc: document.getElementById('trailer-feature-desc'),
trailerFeatureThumbnail: document.getElementById('trailer-feature-thumbnail'),
trailerFeaturePlayBtn: document.getElementById('trailer-feature-play-btn'),
trailerFeatureMoreInfoBtn: document.getElementById('trailer-feature-more-info'),
galleryStage: document.getElementById('galleryStage'),
galleryCards: document.querySelectorAll('#gallery-section .gallery-card'),
galleryDotsContainer: document.getElementById('galleryDots'),
galleryDots: document.querySelectorAll('#gallery-section .dot'),
galleryPrevBtn: document.getElementById('prevBtn'),
galleryNextBtn: document.getElementById('nextBtn'),
galleryFullscreenModal: document.getElementById('fullscreenModal'),
galleryModalImageFs: document.getElementById('modalImageFs'),
galleryModalCaptionFs: document.getElementById('modalCaptionFs'),
galleryModalCloseFs: document.getElementById('modalClose'),
kpiCounters: document.querySelectorAll('.kpi-value[data-target]'),
gaugeFillElement: document.getElementById('gauge-fill-element'),
gaugeValueElement: document.getElementById('gauge-value-element'),
networkBarChart: document.getElementById('network-bar-chart'),
topActorsList: document.getElementById('top-actors-list'),
copyYear: document.getElementById('copy-year'),
launchAppModal: document.getElementById('launchAppModal'),
trailerModal: document.getElementById('trailer-modal'),
trailerIframe: document.getElementById('trailer-iframe'),
loginForm: document.getElementById('login-form'),
signupForm: document.getElementById('signup-form'),
googleLoginButton: document.getElementById('google-login-button'),
googleSignupButton: document.getElementById('google-signup-button'),
authErrorMessage: document.getElementById('auth-error-message'),
loginSignupButton: document.getElementById('login-signup-button'),
userInfoArea: document.getElementById('user-info-area'),
userAvatar: document.getElementById('user-avatar'),
userAvatarInitials: document.getElementById('user-avatar-initials'),
userAvatarImage: document.getElementById('user-avatar-image'),
userDisplayName: document.getElementById('user-display-name'),
logoutButton: document.getElementById('logout-button'),
signupNameInput: document.getElementById('signup-name'),
genreSpotlightSection: document.getElementById('genre-spotlight'),
genreFilterButtons: document.querySelectorAll('.genre-filters .btn'),
spotlightGridContainer: document.getElementById('spotlight-grid-container'),
signupAgeInput: document.getElementById('signup-age'),
signupAvatarInput: document.getElementById('signup-avatar'),
loginEmailInput: document.getElementById('login-email'),
loginPasswordInput: document.getElementById('login-password'),
signupEmailInput: document.getElementById('signup-email'),
signupPasswordInput: document.getElementById('signup-password'),
};
const essentialKeys = ['navbar', 'heroSection', 'launchAppModal', 'loginForm', 'signupForm'];
const missing = essentialKeys.filter(key => !this.elements[key]);
if (missing.length > 0) {
this.utils.error(`Critical DOM elements missing: ${missing.join(', ')}.`);
return false;
}
return true;
},
initSyncModules: function() {
Object.values(this.modules).forEach(module => {
if (module.init) {
try {
this.utils.log(`Initializing sync module: ${module.name || 'Anonymous Module'}`);
module.init();
} catch (e) {
this.utils.error(`Error initializing sync module ${module.name || ''}:`, e);
}
}
});
this.utils.setCopyrightYear();
},
initVisualLibraries: function() {
if (this.state.librariesLoaded.aos) {
try {
this.utils.log("Init AOS...");
AOS.init(this.config.AOS_CONFIG);
} catch (e) {
this.utils.error("AOS Init failed:", e);
}
}
},
runAsyncInits: async function() {
this.utils.log("Starting Async Initializations...");
const promises = [
this.modules.hero.loadBackgroundAndContent(true),
this.modules.shelves.loadAllShelves(),
this.modules.analyticsDashboard.loadAnalyticsData(),
this.modules.universeExplorer.loadContent(),
this.modules.creatorsCorner.loadContent() // ===== ADD THIS LINE =====
];
await Promise.allSettled(promises);
this.modules.hero.startBackgroundUpdates();
this.utils.log("Async Inits settled.");
},
// --- Modules ---
modules: {
loadingScreen: {
name: 'LoadingScreen',
hide: function() {
const el = AuraStreamApp.elements.loadingScreen;
if (el) {
el.classList.add('hidden');
}
},
showError: function(message) {
const el = AuraStreamApp.elements.loadingScreen;
if (el) {
el.innerHTML = `<div class="loading-text" style="color: var(--tertiary-accent);">${AuraStreamApp.utils.escapeHtml(message)}</div>`;
}
}
},
backToTop: {
name: 'BackToTop',
init: function() {
const btn = AuraStreamApp.elements.backToTopBtn;
if (!btn) return;
btn.addEventListener('click', (e) => {
e.preventDefault();
window.scrollTo({
top: 0,
behavior: 'smooth'
});
});
const scrollHandler = () => {
if (window.scrollY > 300) {
btn.classList.add('active');
} else {
btn.classList.remove('active');
}
};
window.addEventListener('scroll', AuraStreamApp.utils.debounce(scrollHandler, 100), { passive: true });
}
},
discoverPanel: {
name: 'DiscoverPanel',
state: {
isSpinning: false,
gemFinderMovies: []
},
init: function() {
const { discoverTabs } = AuraStreamApp.elements;
if (!discoverTabs || discoverTabs.length === 0) return;
discoverTabs.forEach(tab => {
tab.addEventListener('click', (e) => this.handleTabClick(e));
});
AuraStreamApp.elements.gemFinderButton?.addEventListener('click', () => this.spinGemFinder());
// Initial load for the active tab
this.loadTrending();
},
handleTabClick: function(e) {
const { discoverTabs, discoverContentPanels } = AuraStreamApp.elements;
const targetTab = e.currentTarget.dataset.tab;
discoverTabs.forEach(t => t.classList.remove('active'));
discoverContentPanels.forEach(p => p.classList.remove('active'));
e.currentTarget.classList.add('active');
const targetPanel = document.getElementById(`panel-${targetTab}`);
if (targetPanel) {
targetPanel.classList.add('active');
}
// Load content only if it hasn't been loaded yet
if (targetTab === 'upcoming' && !targetPanel.dataset.loaded) {
this.loadUpcoming();
} else if (targetTab === 'gem-finder' && !targetPanel.dataset.loaded) {
this.loadGemFinder();
}
},
loadTrending: async function() {
const { utils, elements } = AuraStreamApp;
const container = elements.panelTrending;
try {
const data = await utils.fetchTMDB('/trending/movie/week');
if (data?.results) {
container.innerHTML = this.renderTrendingList(data.results.slice(0, 10));
this.attachModalListeners(container);
container.dataset.loaded = 'true';
} else { throw new Error('No trending data'); }
} catch (error) {
container.innerHTML = utils.getErrorTextHTML('Could not load trending list.');
}
},
renderTrendingList: function(movies) {
const { utils } = AuraStreamApp;
return `<ul class="trending-list">${movies.map((movie, index) => `
<li class="trending-item detail-modal-trigger" data-item-id="${movie.id}" data-item-type="movie">
<span class="trending-rank">${index + 1}</span>
<img class="trending-poster" src="${AuraStreamApp.config.IMAGE_BASE_URL}w92${movie.poster_path}" alt="${utils.escapeHtml(movie.title)}">
<div class="trending-info">
<h5>${utils.escapeHtml(movie.title)}</h5>
<p>${utils.getYear(movie.release_date)}</p>
</div>
<div class="trending-rating">
<i class="bi bi-star-fill"></i> ${movie.vote_average.toFixed(1)}
</div>
</li>
`).join('')}</ul>`;
},
loadUpcoming: async function() {
const { utils, elements } = AuraStreamApp;
const container = elements.panelUpcoming;
try {
const data = await utils.fetchTMDB('/movie/upcoming');
if (data?.results) {
container.innerHTML = this.renderUpcomingGrid(data.results);
this.attachModalListeners(container);
container.dataset.loaded = 'true';
} else { throw new Error('No upcoming data'); }
} catch (error) {
container.innerHTML = utils.getErrorTextHTML('Could not load upcoming movies.');
}
},
renderUpcomingGrid: function(movies) {
const { utils } = AuraStreamApp;
return `<div class="upcoming-grid">${movies.map(movie => `
<div class="upcoming-item detail-modal-trigger" data-item-id="${movie.id}" data-item-type="movie">
<img src="${AuraStreamApp.config.IMAGE_BASE_URL}w342${movie.poster_path}" alt="${utils.escapeHtml(movie.title)}">
<div class="upcoming-overlay">
<h6>${utils.escapeHtml(movie.title)}</h6>
<span>${utils.formatDate(movie.release_date)}</span>
</div>
</div>
`).join('')}</div>`;
},
loadGemFinder: async function() {
const { utils, elements } = AuraStreamApp;
try {
// Fetch several pages of highly-rated but not blockbuster movies
const promises = [1, 2, 3].map(page =>
utils.fetchTMDB('/discover/movie', {
'vote_average.gte': 7.5,
'vote_count.gte': 500,
'vote_count.lte': 5000,
sort_by: 'popularity.desc',
page: page
})
);
const results = await Promise.all(promises);
this.state.gemFinderMovies = results.flatMap(res => res.results).filter(m => m.poster_path);
this.renderGemFinderStrip();
elements.panelGemFinder.dataset.loaded = 'true';
} catch (error) {
elements.gemFinderStrip.innerHTML = `<p class="text-danger">Could not load gems.</p>`;
}
},
renderGemFinderStrip: function() {
const { gemFinderStrip } = AuraStreamApp.elements;
if (this.state.gemFinderMovies.length < 20) return;
// Shuffle and create a long strip for spinning
const shuffled = [...this.state.gemFinderMovies].sort(() => 0.5 - Math.random());
this.state.gemFinderMovies = shuffled; // Keep the shuffled order
gemFinderStrip.innerHTML = shuffled.map(movie =>
`<img src="${AuraStreamApp.config.IMAGE_BASE_URL}w342${movie.poster_path}" alt="">`
).join('');
},
spinGemFinder: function() {
if (this.state.isSpinning) return;
this.state.isSpinning = true;
const { gemFinderStrip, gemFinderButton, gemFinderResult } = AuraStreamApp.elements;
gemFinderResult.classList.add('d-none'); // Hide previous result
gemFinderButton.disabled = true;
gemFinderButton.innerHTML = `<i class="bi bi-hourglass-split"></i> Spinning...`;
// Pick a random movie (not the first few)
const randomIndex = Math.floor(Math.random() * (this.state.gemFinderMovies.length - 10)) + 10;
const targetMovie = this.state.gemFinderMovies[randomIndex];
const targetPosition = randomIndex * 300; // 300px is the height of each poster
// Add extra spins for effect
const extraSpins = 300 * 20; // 20 full spins
gemFinderStrip.style.transition = 'transform 5s cubic-bezier(0.25, 1, 0.5, 1)';
gemFinderStrip.style.transform = `translateY(-${targetPosition + extraSpins}px)`;
setTimeout(() => {
this.state.isSpinning = false;
gemFinderButton.disabled = false;
gemFinderButton.innerHTML = `<i class="bi bi-shuffle"></i> Spin Again`;
this.showGemFinderResult(targetMovie);
}, 5000);
},
showGemFinderResult: function(movie) {
const { gemFinderResult } = AuraStreamApp.elements;
gemFinderResult.classList.remove('d-none');
gemFinderResult.innerHTML = `
<h5>${AuraStreamApp.utils.escapeHtml(movie.title)}</h5>
<p>A hidden gem for you to discover!</p>
<button class="btn btn-secondary-outline btn-sm detail-modal-trigger" data-item-id="${movie.id}" data-item-type="movie">
View Details
</button>
`;
this.attachModalListeners(gemFinderResult);
},
attachModalListeners: function(container) {
container.querySelectorAll('.detail-modal-trigger').forEach(trigger => {
trigger.addEventListener('click', e => {
const itemId = e.currentTarget.dataset.itemId;
const itemType = e.currentTarget.dataset.itemType;
AuraStreamApp.modules.modals.openDetailModal(itemId, itemType);
});
});
}
},
aiEngine: {
name: 'AIEngine',
state: {
// Store user choices
keywords: [],
// Canvas state
ctx: null,
particles: [],
mouse: { x: null, y: null, radius: 100 },
animationFrame: null,
},
init: function() {
const canvas = AuraStreamApp.elements.aiCanvas;
if (canvas) {
this.state.ctx = canvas.getContext('2d');
this._setupCanvas();
window.addEventListener('resize', AuraStreamApp.utils.debounce(() => this._setupCanvas(), 250));
} else {
AuraStreamApp.utils.warn("AI Canvas not found, background animation disabled.");
}
this._attachStepListeners();
},
// --- Canvas Neural Network Animation ---
_setupCanvas: function() {
const canvas = AuraStreamApp.elements.aiCanvas;
const dpr = window.devicePixelRatio || 1;
canvas.width = canvas.offsetWidth * dpr;
canvas.height = canvas.offsetHeight * dpr;
this.state.ctx.scale(dpr, dpr);
this.state.particles = [];
let numberOfParticles = (canvas.width * canvas.height) / 9000;
if (numberOfParticles > 150) numberOfParticles = 150; // Cap particles
for (let i = 0; i < numberOfParticles; i++) {
let size = Math.random() * 1.5 + 0.5;
let x = Math.random() * (canvas.offsetWidth - size * 2) + size;
let y = Math.random() * (canvas.offsetHeight - size * 2) + size;
let directionX = (Math.random() * .4) - .2;
let directionY = (Math.random() * .4) - .2;
this.state.particles.push({ x, y, directionX, directionY, size });
}
if (this.state.animationFrame) cancelAnimationFrame(this.state.animationFrame);
this._animateCanvas();
canvas.addEventListener('mousemove', (e) => {
const rect = canvas.getBoundingClientRect();
this.state.mouse.x = e.clientX - rect.left;
this.state.mouse.y = e.clientY - rect.top;
});
canvas.addEventListener('mouseleave', () => {
this.state.mouse.x = null;
this.state.mouse.y = null;
});
},
_animateCanvas: function() {
const { ctx, particles, mouse } = this.state;
const canvas = AuraStreamApp.elements.aiCanvas;
ctx.clearRect(0, 0, canvas.offsetWidth, canvas.offsetHeight);
particles.forEach(p => {
// Movement
if (p.x + p.size > canvas.offsetWidth || p.x - p.size < 0) p.directionX = -p.directionX;
if (p.y + p.size > canvas.offsetHeight || p.y - p.size < 0) p.directionY = -p.directionY;
p.x += p.directionX;
p.y += p.directionY;
// Draw particle
ctx.beginPath();
ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2, false);
ctx.fillStyle = 'rgba(168, 85, 247, 0.5)';
ctx.fill();
});
// Draw connections
for (let a = 0; a < particles.length; a++) {
for (let b = a; b < particles.length; b++) {
let distance = Math.sqrt(Math.pow(particles[a].x - particles[b].x, 2) + Math.pow(particles[a].y - particles[b].y, 2));
if (distance < 100) {
ctx.strokeStyle = `rgba(168, 85, 247, ${1 - (distance / 100)})`;
ctx.lineWidth = 0.5;
ctx.beginPath();
ctx.moveTo(particles[a].x, particles[b].x);
ctx.lineTo(particles[b].x, particles[b].y);
ctx.stroke();
}
}
}
this.state.animationFrame = requestAnimationFrame(() => this._animateCanvas());
},
// --- Interactive Step Logic ---
_attachStepListeners: function() {
const { aiHubContainer } = AuraStreamApp.elements;
if (!aiHubContainer) return;
aiHubContainer.addEventListener('click', (e) => {
const optionCard = e.target.closest('.ai-option-card');
if (optionCard) {
const nextStep = optionCard.dataset.nextStep;
const keyword = optionCard.dataset.keyword;
this.state.keywords.push(keyword);
this.goToStep(nextStep);
}
});
},
goToStep: function(stepNumber) {
const { aiHubContainer } = AuraStreamApp.elements;
aiHubContainer.querySelectorAll('.ai-step').forEach(step => step.classList.remove('active'));
const nextStepEl = aiHubContainer.querySelector(`.ai-step[data-step="${stepNumber}"]`);
if(nextStepEl) nextStepEl.classList.add('active');
if (stepNumber === "3") { // Analysis step
this._runAnalysis();
}
},
_runAnalysis: async function() {
const { utils } = AuraStreamApp;
// Display selected keywords
const keyword1El = document.getElementById('keyword1');
const keyword2El = document.getElementById('keyword2');
if(keyword1El) keyword1El.textContent = this.state.keywords[0] || '';
if(keyword2El) keyword2El.textContent = this.state.keywords[1] || '';
// Map user keywords to TMDb genre IDs
const genreMap = {
adventure: '12', comedy: '35', thriller: '53', drama: '18',
space: '878', magic: '14', crime: '80', future: '878' // Using Sci-Fi for space and future
};
const genreIds = this.state.keywords.map(kw => genreMap[kw]).join(',');
// Wait for the analysis animation (2s) then fetch movie
setTimeout(async () => {
try {
const data = await utils.fetchTMDB('/discover/movie', {
with_genres: genreIds,
sort_by: 'popularity.desc',
'vote_count.gte': 500,
page: 1
});
if (data?.results?.length > 0) {
const movie = data.results[Math.floor(Math.random() * Math.min(data.results.length, 10))];
this._renderRecommendation(movie);
this.goToStep("4");
} else {
throw new Error("No movies found for these criteria.");
}
} catch(err) {
this._renderError();
this.goToStep("4");
}
}, 2200);
},
_renderRecommendation: function(movie) {
const { utils, config, modules } = AuraStreamApp;
const container = document.querySelector('.ai-recommendation-wrapper');
if (!container) return;
const title = utils.escapeHtml(movie.title);
const overview = utils.escapeHtml(movie.overview.substring(0, 150) + '...');
const posterUrl = `${config.IMAGE_BASE_URL}${config.POSTER_SIZE}${movie.poster_path}`;
container.innerHTML = `
<div class="rec-card">
<img src="${posterUrl}" alt="${title} Poster">
<div class="rec-card-overlay"></div>
</div>
<div class="rec-info">
<h3>${title}</h3>
<p>${overview}</p>
<button class="btn btn-primary-gradient btn-lg detail-modal-trigger" data-item-id="${movie.id}" data-item-type="movie">
<i class="bi bi-info-circle"></i> View Details
</button>
</div>
`;
// Re-attach listener for the new button
container.querySelector('.detail-modal-trigger').addEventListener('click', (e) => {
modules.modals.openDetailModal(e.currentTarget.dataset.itemId, e.currentTarget.dataset.itemType);
});
},
_renderError: function() {
const container = document.querySelector('.ai-recommendation-wrapper');
if (!container) return;
container.innerHTML = `<div class="rec-info"><h3 class="text-danger">Analysis Failed</h3><p>AuraLens couldn't find a perfect match. Please try a different combination.</p></div>`;
}
},
// Inside AuraStreamApp.modules = { ... }
genreSpotlight: {
name: 'GenreSpotlight',
init: function() {
const { genreFilterButtons } = AuraStreamApp.elements;
if (!genreFilterButtons || genreFilterButtons.length === 0) {
AuraStreamApp.utils.warn("Genre filter buttons not found. Spotlight disabled.");
return;
}
genreFilterButtons.forEach(btn => {
btn.addEventListener('click', (e) => {
const genreId = e.currentTarget.dataset.genreId;
this.loadGenre(genreId, e.currentTarget);
});
});
// Load the initial active genre on page load
const initialActiveButton = document.querySelector('.genre-filters .btn.active');
if (initialActiveButton) {
this.loadGenre(initialActiveButton.dataset.genreId, initialActiveButton);
}
},
loadGenre: async function(genreId, activeBtnEl) {
const { utils, elements } = AuraStreamApp;
if (!genreId) return;
utils.log(`Loading genre spotlight for ID: ${genreId}`);
// Update active button state
elements.genreFilterButtons.forEach(btn => btn.classList.remove('active', 'btn-primary-gradient'));
activeBtnEl.classList.add('active', 'btn-primary-gradient');
const grid = elements.spotlightGridContainer;
grid.classList.add('loading');
grid.innerHTML = `<div class="loading-placeholder"><div class="loading-spinner"></div><span>Loading ${utils.escapeHtml(activeBtnEl.textContent)}...</span></div>`;
try {
const data = await utils.fetchTMDB('/discover/movie', {
with_genres: genreId,
sort_by: 'popularity.desc',
'vote_count.gte': 200, // Ensure movies are somewhat known
page: 1
});
if (data?.results) {
this.renderGrid(data.results.slice(0, 14)); // Show a good number of movies
} else {
throw new Error("No results found.");
}
} catch (error) {
utils.error("Failed to load genre spotlight:", error);
grid.innerHTML = utils.getErrorTextHTML("Could not load movies for this genre.");
} finally {
grid.classList.remove('loading');
}
},
renderGrid: function(movies) {
const { utils, config, elements, modules } = AuraStreamApp;
const grid = elements.spotlightGridContainer;
grid.innerHTML = ''; // Clear previous content
const fragment = document.createDocumentFragment();
movies.forEach((movie, index) => {
if (!movie.poster_path) return; // Skip movies without a poster
const title = utils.escapeHtml(movie.title || 'Untitled');
const year = utils.getYear(movie.release_date);
const posterUrl = `${config.IMAGE_BASE_URL}${config.POSTER_SIZE}${movie.poster_path}`;
const item = document.createElement('a');
item.href = '#';
item.className = 'spotlight-item detail-modal-trigger';
item.dataset.itemId = movie.id;
item.dataset.itemType = 'movie';
item.style.animationDelay = `${index * 50}ms`; // Staggered animation
item.innerHTML = `
<img src="${posterUrl}" alt="${title} Poster" loading="lazy">
<div class="spotlight-overlay">
<h4 class="spotlight-title">${title}</h4>
<p class="spotlight-year">${year || ''}</p>
</div>
`;
item.addEventListener('click', (e) => {
e.preventDefault();
// Re-use the existing modal functionality
modules.modals.openDetailModal(movie.id, 'movie');
});
fragment.appendChild(item);
});
grid.appendChild(fragment);
// Call the tilt effect function on the newly created items
this._attachTiltEffect(grid.querySelectorAll('.spotlight-item'));
},
// ===== NEW: ADD THIS ENTIRE FUNCTION TO THE MODULE =====
_attachTiltEffect: function(items) {
items.forEach(item => {
item.addEventListener('mousemove', (e) => {
const rect = item.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
const centerX = rect.width / 2;
const centerY = rect.height / 2;
const rotateX = (y - centerY) / centerY * -8; // Max rotation 8 degrees
const rotateY = (x - centerX) / centerX * 8; // Max rotation 8 degrees
// Tilt the entire item
item.style.transform = `perspective(1000px) scale(1.05) rotateX(${rotateX}deg) rotateY(${rotateY}deg)`;
// Set CSS Custom Properties for the glare effect
item.style.setProperty('--glare-x', `${x}px`);
item.style.setProperty('--glare-y', `${y}px`);
item.classList.add('is-hovered');
});
item.addEventListener('mouseleave', () => {
// Reset transformations smoothly
item.style.transform = 'perspective(1000px) scale(1) rotateX(0deg) rotateY(0deg)';
item.classList.remove('is-hovered');
});
});
}
},
cursorSpotlight: {
name: 'CursorSpotlight',
init: function() {
const spotlightEl = AuraStreamApp.elements.spotlight;
if (!spotlightEl) return;
const mouse = { x: window.innerWidth / 2, y: window.innerHeight / 2 };
const rendered = { x: mouse.x, y: mouse.y };
window.addEventListener('mousemove', e => {
mouse.x = e.clientX;
mouse.y = e.clientY;
}, { passive: true });
const updateSpotlight = () => {
rendered.x += (mouse.x - rendered.x) * 0.08;
rendered.y += (mouse.y - rendered.y) * 0.08;
spotlightEl.style.transform = `translate(calc(${rendered.x}px - 50%), calc(${rendered.y}px - 50%))`;
requestAnimationFrame(updateSpotlight);
};
updateSpotlight();
}
},
phoneDemo: {
name: 'PhoneDemo',
init: function() {
const { youtubePlayer, playButtonOverlay } = AuraStreamApp.elements;
if (playButtonOverlay && youtubePlayer) {
playButtonOverlay.addEventListener('click', () => {
if (!youtubePlayer.src.includes('autoplay')) {
youtubePlayer.src += "?autoplay=1&mute=1&rel=0";
}
playButtonOverlay.classList.add('hidden');
});
}
}
},
navbar: {
name: 'Navbar',
init: function() {
const { navbar, mobileMenuToggle, mobileMenuClose, mobileMenu, offcanvasOverlay } = AuraStreamApp.elements;
if (!navbar) return;
window.addEventListener('scroll', AuraStreamApp.utils.debounce(() => this.handleScroll(), 50), { passive: true });
this.handleScroll();
mobileMenuToggle?.addEventListener('click', () => this.openMobileMenu());
mobileMenuClose?.addEventListener('click', () => this.closeMobileMenu());
offcanvasOverlay?.addEventListener('click', () => this.closeMobileMenu());
mobileMenu?.querySelectorAll('.nav-link').forEach(link => link.addEventListener('click', () => this.closeMobileMenu()));
},
handleScroll: function() {
const navbar = AuraStreamApp.elements.navbar;
if (navbar) window.scrollY > 50 ? navbar.classList.add('scrolled') : navbar.classList.remove('scrolled');
},
openMobileMenu: function() { AuraStreamApp.elements.mobileMenu?.classList.add('active'); AuraStreamApp.elements.offcanvasOverlay?.classList.add('active'); document.body.classList.add('offcanvas-open'); },
closeMobileMenu: function() { AuraStreamApp.elements.mobileMenu?.classList.remove('active'); AuraStreamApp.elements.offcanvasOverlay?.classList.remove('active'); document.body.classList.remove('offcanvas-open'); }
},
hero: {
name: 'Hero',
updateIntervalId: null,
init: function() { this.setupButtonListeners(); },
loadBackgroundAndContent: async function(isInitial = false) {
const { utils, state, modules } = AuraStreamApp;