-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
574 lines (504 loc) · 22.5 KB
/
script.js
File metadata and controls
574 lines (504 loc) · 22.5 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
/* ============================================
CineLog — Main Script
============================================ */
// ============ CONFIGURATION ============
// Get your FREE API key from: https://www.omdbapi.com/apikey.aspx
// Replace the key below with your own key
const OMDB_API_KEY = 'd91eb2b5'; // <-- REPLACE THIS
const OMDB_BASE = `https://www.omdbapi.com/?apikey=${OMDB_API_KEY}`;
// ============ MEMORY PHOTOS ============
// Add your personal movie-watching memory photos here
// These appear in the filmstrip on the hero section
// Replace these placeholder URLs with your own photo links
// Focus can be 'top', 'center', 'bottom', 'left', 'right' or any combination (e.g. 'top left')
const memoryPhotos = [
{
url: 'images/1.jpg',
caption: 'Movie night vibes',focus:'top'
},
{
url: 'images/2.jpg',
caption: 'Movie night vibes',focus:'center'
},
{
url: 'images/3.jpg',
caption: 'Movie night vibes',focus:'center'
},
{
url: 'images/4.jpg',
caption: 'Movie night vibes',focus:'center'
},
{
url: 'images/5.jpg',
caption: 'Movie night vibes',focus:'center'
},
{
url: 'images/6.jpg',
caption: 'Movie night vibes',focus:'center'
},
{
url: 'images/7.jpg',
caption: 'Movie night vibes',focus:'center'
},
{
url: 'images/8.jpg',
caption: 'Movie night vibes',focus:'center'
}
];
// ============ STATE ============
let allMovies = []; // Combined: personal JSON + OMDb data
let filteredMovies = []; // After search/filter/sort
// ============ INIT ============
document.addEventListener('DOMContentLoaded', init);
async function init() {
try {
// 1. Load personal movie data from JSON
const response = await fetch('movies.json');
const personalData = await response.json();
// 2. Fetch OMDb data for each movie
allMovies = await Promise.all(personalData.map(fetchMovieData));
// 3. Populate filters
populateFilters();
// 4. Render everything
filteredMovies = [...allMovies];
sortMovies('recent');
renderSlider();
renderFilmstrip();
renderMovies();
updateStats();
updateCounter();
updateHoursCounter();
// 5. Setup event listeners
setupEventListeners();
// 6. Hide loading
setTimeout(() => {
document.getElementById('loadingOverlay').classList.add('hidden');
}, 600);
} catch (error) {
console.error('Failed to initialize:', error);
document.getElementById('loadingOverlay').innerHTML = `
<div class="loading-spinner">
<p style="color: #e06848;">Error loading movies. Check console for details.</p>
<p style="color: #565b73; margin-top: 8px; font-size: 0.8rem;">${error.message}</p>
</div>
`;
}
}
// ============ FETCH OMDb DATA ============
async function fetchMovieData(movie) {
const merged = { ...movie };
// Auto-generate imdb_link if missing
if (!merged.imdb_link && merged.imdb_id) {
merged.imdb_link = `https://www.imdb.com/title/${merged.imdb_id}/`;
}
// Default missing fields
if (merged.personal_rating === undefined) merged.personal_rating = 0;
if (!merged.mood_labels) merged.mood_labels = [];
if (!merged.comments) merged.comments = "";
if (merged.rewatch_count === undefined) merged.rewatch_count = 0;
if (!merged.watch_date) merged.watch_date = "";
if (!merged.watched_with) merged.watched_with = [];
if (merged.watch_location === undefined) merged.watch_location = 0;
// If no API key is set, use placeholder data
if (OMDB_API_KEY === 'YOUR_API_KEY_HERE') {
// Sample runtimes for demo hours counter
const sampleRuntimes = {
'tt0111161': '142 min', 'tt0068646': '175 min', 'tt0468569': '152 min',
'tt0109830': '142 min', 'tt0137523': '139 min', 'tt0120737': '178 min',
'tt0816692': '169 min', 'tt0110912': '154 min', 'tt0167260': '201 min',
'tt1375666': '148 min'
};
const defaultName = movie.name || 'Unknown Movie';
return {
...merged,
name: defaultName,
poster: 'https://via.placeholder.com/300x450/131620/565b73?text=' + encodeURIComponent(defaultName),
genre: 'Drama, Thriller',
language: 'English',
country: 'United States',
year: '2024',
runtime: sampleRuntimes[movie.imdb_id] || '120 min',
director: 'N/A',
actors: 'N/A',
imdb_rating: '8.5',
plot: 'Add your OMDb API key to auto-fetch movie data.'
};
}
try {
const res = await fetch(`${OMDB_BASE}&i=${movie.imdb_id}&plot=short`);
const data = await res.json();
if (data.Response === 'True') {
// If name is missing in json, use OMDb Title
if (!merged.name) {
merged.name = data.Title || 'Unknown Movie';
}
merged.poster = data.Poster !== 'N/A' ? data.Poster : null;
merged.genre = data.Genre || 'N/A';
merged.language = data.Language || 'N/A';
merged.country = data.Country || 'N/A';
merged.year = data.Year || 'N/A';
merged.runtime = data.Runtime || 'N/A';
merged.director = data.Director || 'N/A';
merged.actors = data.Actors || 'N/A';
merged.imdb_rating = data.imdbRating || 'N/A';
merged.plot = data.Plot || '';
} else {
if (!merged.name) merged.name = 'Unknown Movie';
merged.poster = null;
merged.imdb_rating = 'N/A';
merged.genre = merged.language = merged.country = merged.year = merged.runtime = 'N/A';
}
} catch (err) {
console.warn(`OMDb fetch failed for ${movie.imdb_id}:`, err);
if (!merged.name) merged.name = 'Unknown Movie';
merged.poster = null;
merged.imdb_rating = 'N/A';
merged.genre = merged.language = merged.country = merged.year = merged.runtime = 'N/A';
}
return merged;
}
// ============ POPULATE FILTERS ============
function populateFilters() {
const genres = new Set();
const countries = new Set();
const years = new Set();
allMovies.forEach(m => {
if (m.genre && m.genre !== 'N/A') {
m.genre.split(',').forEach(g => genres.add(g.trim()));
}
if (m.country && m.country !== 'N/A') {
m.country.split(',').forEach(c => countries.add(c.trim()));
}
if (m.year && m.year !== 'N/A') {
years.add(m.year);
}
});
fillSelect('genreFilter', [...genres].sort());
fillSelect('countryFilter', [...countries].sort());
fillSelect('yearFilter', [...years].sort((a, b) => b - a));
}
function fillSelect(id, items) {
const sel = document.getElementById(id);
items.forEach(item => {
const opt = document.createElement('option');
opt.value = item;
opt.textContent = item;
sel.appendChild(opt);
});
}
// ============ RENDER SLIDER ============
function renderSlider() {
const track = document.getElementById('sliderTrack');
const recent = [...allMovies]
.sort((a, b) => {
const dateA = new Date(a.watch_date);
const dateB = new Date(b.watch_date);
const timeA = isNaN(dateA) ? 0 : dateA.getTime();
const timeB = isNaN(dateB) ? 0 : dateB.getTime();
return timeB - timeA;
})
.slice(0, 10);
const cardHTML = m => `
<a class="ticker-card" href="${m.imdb_link}" target="_blank" title="${m.name}">
<img src="${m.poster || `https://via.placeholder.com/200x280/131620/565b73?text=${encodeURIComponent(m.name)}`}"
alt="${m.name}" loading="lazy"
onerror="this.src='https://via.placeholder.com/200x280/131620/565b73?text=${encodeURIComponent(m.name)}'">
<div class="ticker-card-overlay">
<div class="ticker-card-title">${m.name}</div>
<div class="ticker-card-meta">★ ${m.imdb_rating} · ${m.year || ''}</div>
</div>
</a>`;
// Duplicate the set for seamless infinite loop
track.innerHTML = recent.map(cardHTML).join('') + recent.map(cardHTML).join('');
// Set animation speed based on card count
const speed = recent.length * 3;
track.style.setProperty('--ticker-speed', `${speed}s`);
}
// ============ RENDER MOVIES ============
function renderMovies() {
const container = document.getElementById('movieContainer');
const noResults = document.getElementById('noResults');
if (filteredMovies.length === 0) {
container.innerHTML = '';
noResults.style.display = 'block';
return;
}
noResults.style.display = 'none';
// Group by release year
const groups = {};
filteredMovies.forEach(m => {
const releaseYear = m.year && m.year !== 'N/A' ? m.year : 'Unknown';
if (!groups[releaseYear]) groups[releaseYear] = [];
groups[releaseYear].push(m);
});
// Sort year groups descending
const sortedYears = Object.keys(groups).sort((a, b) => b - a);
container.innerHTML = sortedYears.map(year => {
const films = groups[year];
const limit = 4;
const hasMore = films.length > limit;
const visible = films.slice(0, limit);
const hidden = films.slice(limit);
return `
<div class="year-group">
<div class="year-header">
<span class="year-label">${year}</span>
<div class="year-line"></div>
<span class="year-count">${films.length} film${films.length > 1 ? 's' : ''}</span>
</div>
<div class="movie-grid">
${visible.map((m, idx) => renderMovieCard(m, idx)).join('')}
${hidden.map((m, idx) => renderMovieCard(m, idx + limit, true)).join('')}
</div>
${hasMore ? `
<button class="show-more-btn" onclick="toggleYearGroup(this)" data-count="${hidden.length}">
<svg class="show-more-chevron" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="6 9 12 15 18 9"/></svg>
<span class="show-more-label">Show ${hidden.length} more film${hidden.length > 1 ? 's' : ''}</span>
</button>` : ''}
</div>
`;
}).join('');
}
function toggleYearGroup(btn) {
const grid = btn.closest('.year-group').querySelector('.movie-grid');
const hiddenCards = grid.querySelectorAll('.hidden-card');
const isExpanded = btn.classList.contains('expanded');
const count = parseInt(btn.dataset.count);
if (!isExpanded) {
hiddenCards.forEach((card, i) => {
card.style.display = 'grid';
card.style.animationDelay = `${i * 0.06}s`;
card.classList.add('reveal');
});
btn.classList.add('expanded');
btn.querySelector('.show-more-label').textContent = 'Show less';
} else {
hiddenCards.forEach(card => {
card.style.display = 'none';
card.classList.remove('reveal');
card.style.animationDelay = '';
});
btn.classList.remove('expanded');
btn.querySelector('.show-more-label').textContent =
`Show ${count} more film${count > 1 ? 's' : ''}`;
}
}
function renderMovieCard(m, idx, isHidden = false) {
const posterUrl = m.poster || `https://via.placeholder.com/110x165/0f1222/4e5570?text=No+Poster`;
const watchDate = m.watch_date ? formatDate(m.watch_date) : '';
const genres = m.genre && m.genre !== 'N/A'
? m.genre.split(',').slice(0, 3).map(g => `<span class="meta-chip genre-chip">${g.trim()}</span>`).join('')
: '';
const country = m.country && m.country !== 'N/A'
? `<span class="meta-chip country-chip">${m.country.split(',')[0].trim()}</span>` : '';
const language = m.language && m.language !== 'N/A'
? `<span class="meta-chip lang-chip">${m.language.split(',')[0].trim()}</span>` : '';
const runtimeChip = m.runtime && m.runtime !== 'N/A'
? `<span class="meta-chip runtime-chip">${m.runtime}</span>` : '';
const moodTags = (m.mood_labels || [])
.map(mood => `<span class="mood-tag-sm" data-mood="${mood}">${mood}</span>`)
.join('');
let watchedWith = '';
if (m.watched_with && m.watched_with.length > 0) {
if (m.watched_with.length === 1 && (m.watched_with[0] === 0 || m.watched_with[0] === '0')) {
watchedWith = 'Alone';
} else {
watchedWith = m.watched_with.join(', ');
}
}
const SVG = (path) => `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${path}</svg>`;
const iconCalendar = SVG(`<rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/>`);
const iconRewatch = SVG(`<path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/>`);
const iconUser = SVG(`<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>`);
const iconUsers = SVG(`<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>`);
const iconHome = SVG(`<path d="m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/>`);
const iconCinema = SVG(`<path d="M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z"/><path d="M13 5v2"/><path d="M13 17v2"/><path d="M13 11v2"/>`);
const locationIcon = m.watch_location === 1 ? iconCinema : iconHome;
const locationText = m.watch_location === 1 ? 'Cinema' : 'Home';
return `
<a class="movie-card${isHidden ? ' hidden-card' : ''}" href="${m.imdb_link || '#'}" target="_blank" rel="noopener"
style="${isHidden ? 'display:none;' : `animation-delay: ${idx * 0.05}s`}">
<div class="movie-card-poster">
<img src="${posterUrl}" alt="${m.name}" loading="lazy"
onerror="this.src='https://via.placeholder.com/110x165/0f1222/4e5570?text=N/A'">
</div>
<div class="movie-card-body">
<div class="movie-card-top">
<h3 class="movie-card-title">${m.name}</h3>
<div class="movie-card-ratings">
<span class="card-rating imdb">★ ${m.imdb_rating}</span>
<span class="card-rating mine">Me ${m.personal_rating}</span>
</div>
</div>
${genres || country || language || runtimeChip ? `
<div class="movie-card-chips">
${genres}${country}${language}${runtimeChip}
</div>` : ''}
${moodTags ? `<div class="movie-card-moods">${moodTags}</div>` : ''}
${watchDate || watchedWith || m.rewatch_count ? `
<div class="movie-card-meta">
${watchDate ? `<span class="movie-card-meta-item">${iconCalendar} ${watchDate}</span>` : ''}
${m.rewatch_count ? `<span class="movie-card-meta-item">${iconRewatch} ${m.rewatch_count}x</span>` : ''}
${watchedWith ? `<span class="movie-card-meta-item">${watchedWith === 'Alone' ? iconUser : iconUsers} ${watchedWith}</span>` : ''}
<span class="movie-card-meta-item">${locationIcon} ${locationText}</span>
</div>` : ''}
${m.comments ? `
<div class="movie-card-comment">"${m.comments}"</div>` : ''}
</div>
</a>
`;
}
// ============ SORTING ============
function sortMovies(criteria) {
switch (criteria) {
case 'recent':
filteredMovies.sort((a, b) => {
const dateA = new Date(a.watch_date);
const dateB = new Date(b.watch_date);
const timeA = isNaN(dateA) ? 0 : dateA.getTime();
const timeB = isNaN(dateB) ? 0 : dateB.getTime();
return timeB - timeA;
});
break;
case 'imdb_desc':
filteredMovies.sort((a, b) => parseFloat(b.imdb_rating || 0) - parseFloat(a.imdb_rating || 0));
break;
case 'imdb_asc':
filteredMovies.sort((a, b) => parseFloat(a.imdb_rating || 0) - parseFloat(b.imdb_rating || 0));
break;
case 'personal_desc':
filteredMovies.sort((a, b) => (b.personal_rating || 0) - (a.personal_rating || 0));
break;
case 'personal_asc':
filteredMovies.sort((a, b) => (a.personal_rating || 0) - (b.personal_rating || 0));
break;
case 'year_desc':
filteredMovies.sort((a, b) => parseInt(b.year || 0) - parseInt(a.year || 0));
break;
case 'year_asc':
filteredMovies.sort((a, b) => parseInt(a.year || 0) - parseInt(b.year || 0));
break;
case 'name_asc':
filteredMovies.sort((a, b) => a.name.localeCompare(b.name));
break;
}
}
// ============ FILTERING ============
function applyFilters() {
const search = document.getElementById('searchInput').value.toLowerCase().trim();
const genre = document.getElementById('genreFilter').value;
const country = document.getElementById('countryFilter').value;
const year = document.getElementById('yearFilter').value;
const sort = document.getElementById('sortSelect').value;
filteredMovies = allMovies.filter(m => {
// Search
if (search) {
const haystack = `${m.name} ${m.genre} ${m.director} ${m.actors} ${m.comments} ${m.mood_labels?.join(' ')} ${m.watched_with?.join(' ')}`.toLowerCase();
if (!haystack.includes(search)) return false;
}
// Genre
if (genre !== 'all') {
if (!m.genre || !m.genre.includes(genre)) return false;
}
// Country
if (country !== 'all') {
if (!m.country || !m.country.includes(country)) return false;
}
// Year (release year)
if (year !== 'all') {
if (m.year !== year) return false;
}
return true;
});
sortMovies(sort);
renderMovies();
}
// ============ EVENT LISTENERS ============
function setupEventListeners() {
// Search with debounce
let searchTimeout;
document.getElementById('searchInput').addEventListener('input', () => {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(applyFilters, 250);
});
// Sort & Filters
document.getElementById('sortSelect').addEventListener('change', applyFilters);
document.getElementById('genreFilter').addEventListener('change', applyFilters);
document.getElementById('countryFilter').addEventListener('change', applyFilters);
document.getElementById('yearFilter').addEventListener('change', applyFilters);
}
// ============ STATS ============
function updateStats() {
const total = allMovies.length;
const imdbRatings = allMovies.filter(m => m.imdb_rating && m.imdb_rating !== 'N/A').map(m => parseFloat(m.imdb_rating));
const personalRatings = allMovies.filter(m => m.personal_rating).map(m => m.personal_rating);
const totalRewatches = allMovies.reduce((sum, m) => sum + (m.rewatch_count || 0), 0);
const genres = new Set();
allMovies.forEach(m => {
if (m.genre && m.genre !== 'N/A') {
m.genre.split(',').forEach(g => genres.add(g.trim()));
}
});
document.getElementById('statTotal').textContent = total;
document.getElementById('statAvgImdb').textContent = imdbRatings.length > 0
? (imdbRatings.reduce((a, b) => a + b, 0) / imdbRatings.length).toFixed(1)
: '—';
document.getElementById('statAvgPersonal').textContent = personalRatings.length > 0
? (personalRatings.reduce((a, b) => a + b, 0) / personalRatings.length).toFixed(1)
: '—';
document.getElementById('statRewatches').textContent = totalRewatches;
document.getElementById('statGenres').textContent = genres.size;
}
function updateCounter() {
document.getElementById('totalMovies').textContent = allMovies.length;
}
// ============ FILM STRIP MEMORIES ============
function renderFilmstrip() {
const track = document.getElementById('filmstripTrack');
if (!track || memoryPhotos.length === 0) return;
// Double the photos for seamless infinite scroll
const allPhotos = [...memoryPhotos, ...memoryPhotos];
const framesHTML = allPhotos.map(photo => `
<div class="filmstrip-frame">
<img src="${photo.url}" alt="${photo.caption}" loading="lazy" style="object-position: ${photo.focus || 'center'}"
onerror="this.parentElement.style.display='none'">
<div class="filmstrip-frame-overlay">
<div class="filmstrip-frame-caption">${photo.caption}</div>
</div>
</div>
`).join('');
track.innerHTML = `<div class="filmstrip-scroll">${framesHTML}</div>`;
// Adjust animation duration based on number of photos
const scrollEl = track.querySelector('.filmstrip-scroll');
if (scrollEl) {
const duration = memoryPhotos.length * 3; // 3 seconds per photo
scrollEl.style.animationDuration = `${duration}s`;
}
}
// ============ HOURS COUNTER ============
function updateHoursCounter() {
let totalMinutes = 0;
allMovies.forEach(m => {
if (m.runtime && m.runtime !== 'N/A') {
// runtime is like "142 min"
const mins = parseInt(m.runtime);
if (!isNaN(mins)) {
// Multiply by (rewatch_count + 1) to account for rewatches
const watches = (m.rewatch_count || 0) + 1;
totalMinutes += mins * watches;
}
}
});
const hours = Math.floor(totalMinutes / 60);
const mins = totalMinutes % 60;
document.getElementById('totalHours').textContent = hours;
document.getElementById('totalMins').textContent = mins;
}
// ============ HELPERS ============
function formatDate(dateStr) {
if (dateStr.toLowerCase() === "can't remember") return "Can't remember";
const d = new Date(dateStr);
if (isNaN(d.getTime())) return dateStr;
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return `${months[d.getMonth()]} ${d.getDate()}, ${d.getFullYear()}`;
}