Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
1886 lines (1715 loc) · 71.1 KB
/
Copy pathscript.js
File metadata and controls
1886 lines (1715 loc) · 71.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
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
let movies=[];
let movieSources=[];
let watchedIndices=[];
let currentMovie=null;
let activeMovieIndex=-1;
let activeMovieSlug='';
let movieDisplayRequest=0;
let nextMovieRequest=0;
let historyNavigationRequest=0;
const movieLoadTimeout=15000;
let isSpeaking=false;
let speechTimeout=null;
let pullStartY=0;
let pullTracking=false;
let isPullRefreshing=false;
const pullRefreshThreshold=90;
const fallbackPoster='data:image/svg+xml;charset=UTF-8,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 400 600%22%3E%3Crect width=%22400%22 height=%22600%22 fill=%22%231b1b1b%22/%3E%3Crect x=%22120%22 y=%22170%22 width=%22160%22 height=%22190%22 rx=%2210%22 fill=%22none%22 stroke=%22%23777777%22 stroke-width=%228%22/%3E%3Cpath d=%22M150 315l40-45 35 35 25-25 25 35%22 fill=%22none%22 stroke=%22%23777777%22 stroke-width=%228%22/%3E%3Ctext x=%22200%22 y=%22415%22 text-anchor=%22middle%22 fill=%22%23aaaaaa%22 font-size=%2224%22 font-family=%22Arial,sans-serif%22%3ENO POSTER%3C/text%3E%3C/svg%3E';
const wikidataCache=new Map();
const wikipediaCache=new Map();
const wikidataEntityCache=new Map();
const movieDetailsCache=new Map();
const plotSummaryCache=new Map();
let prefetchedNextIndex=null;
let prefetchCandidateIndex=null;
let prefetchInProgress=null;
function updateDocumentTitle(showMovieTitle=false){
const overlay=document.getElementById('curtainOverlay');
if(!showMovieTitle||!overlay?.classList.contains('open')||overlay.classList.contains('loading-movie')||!currentMovie){
document.title='Picks';
return;
}
const title=currentMovie.title?.trim();
const year=currentMovie.year?.trim();
document.title=title?`Picks - ${title}${year?' '+year:''}`:'Picks';
}
async function loadMoviesDatabase(){
try{
setupMoviePosterSearch();
const listFiles=['movies-new.txt','movies-own.txt','movies-fav.txt'];
const listResults=await Promise.all(listFiles.map(async file=>{
const response=await fetch(file,{cache:'no-store'});
if(!response.ok)throw new Error(`Could not load ${file}: HTTP ${response.status}`);
return {file,text:await response.text()};
}));
const movieEntryMap=new Map();
listResults.forEach(({file,text})=>{
text.split(/\r?\n/).forEach(rawLine=>{
const line=rawLine.trim();
if(!line||line.startsWith('#'))return;
const movie=parseMovieLine(line);
if(!movie.year)return;
const key=normaliseTitle(`${movie.title} ${movie.year}`);
const existing=movieEntryMap.get(key);
if(existing){
if(!existing.sources.includes(file))existing.sources.push(file);
return;
}
movieEntryMap.set(key,{line,sources:[file]});
});
});
const movieEntries=Array.from(movieEntryMap.values());
movies=movieEntries.map(entry=>entry.line);
movieSources=movieEntries.map(entry=>entry.sources);
if(!movies.length){
await showNoMoviesToWatch();
return;
}
document.querySelector('#spotlightContent .spotlight-text').innerHTML='That’s a wrap!<br>Every movie has been featured.';
const isHomeScreenApp=window.navigator.standalone===true;
if(isHomeScreenApp&&location.hash){
history.replaceState(null,'',location.pathname+location.search);
}
const linkedIndex=isHomeScreenApp?-1:findMovieIndexFromHash();
applyMovieSectionStates();
if(linkedIndex>=0)normaliseMovieUrl(linkedIndex);
const navigationEntry=performance.getEntriesByType('navigation')[0];
const isPageRefresh=navigationEntry?.type==='reload';
window.addEventListener('popstate',handleMovieUrlChange);
window.addEventListener('hashchange',handleMovieUrlChange);
if(linkedIndex>=0&&isPageRefresh){
watchedIndices.push(linkedIndex);
await fetchNextMovie(false);
}else if(linkedIndex>=0){
watchedIndices.push(linkedIndex);
await displayMovieAtIndex(linkedIndex);
}else{
await fetchNextMovie(true);
}
setupPullToRefresh();
}catch(error){
console.error('Error loading movie lists:',error);
document.getElementById('movieTitle').innerText='Error Loading Movie Lists';
document.getElementById('movieSynopsis').innerText=error.message||'One or more movie list files could not be loaded.';
const overlay=document.getElementById('curtainOverlay');
stopSpeech();
overlay.classList.remove('open','no-light','loading-movie');
updateDocumentTitle(false);
document.querySelector('#spotlightContent .spotlight-text').textContent='Error loading movie lists. Check that movies-new.txt, movies-own.txt, and movies-fav.txt are available.';
document.getElementById('reloadBtn').style.display='none';
await new Promise(resolve=>setTimeout(resolve,600));
overlay.classList.add('show-spotlight');
}
}
function setupPullToRefresh(){
const indicator=document.createElement('div');
indicator.id='pullRefreshIndicator';
indicator.textContent='↓ Pull to refresh movie';
document.body.append(indicator);
let pullDistance=0;
let pullStartX=0;
window.addEventListener('touchstart',event=>{
if(event.touches.length!==1||window.scrollY>0||isPullRefreshing)return;
if(event.target.closest('.synopsis-scroll-area'))return;
pullStartY=event.touches[0].clientY;
pullStartX=event.touches[0].clientX;
pullDistance=0;
pullTracking=true;
},{passive:true});
window.addEventListener('touchmove',event=>{
if(!pullTracking||event.touches.length!==1)return;
const deltaX=event.touches[0].clientX-pullStartX;
pullDistance=event.touches[0].clientY-pullStartY;
if(Math.abs(deltaX)>Math.abs(pullDistance)&&Math.abs(deltaX)>12){
pullTracking=false;
indicator.classList.remove('visible','ready');
indicator.style.transform='';
return;
}
if(pullDistance<=0){
indicator.classList.remove('visible','ready');
return;
}
if(window.scrollY>0){
pullTracking=false;
indicator.classList.remove('visible','ready');
return;
}
event.preventDefault();
if(pullDistance>8){
indicator.classList.add('visible');
indicator.classList.toggle('ready',pullDistance>=pullRefreshThreshold);
indicator.textContent=pullDistance>=pullRefreshThreshold?'↑ Release to refresh movie':'↓ Pull to refresh movie';
indicator.style.transform=`translate(-50%, ${Math.min(pullDistance*0.55,70)-70}px)`;
}
},{passive:false});
const finishPull=()=>{
if(!pullTracking)return;
pullTracking=false;
const shouldRefresh=pullDistance>=pullRefreshThreshold;
indicator.classList.remove('visible','ready');
indicator.style.transform='';
if(shouldRefresh&&!isPullRefreshing){
isPullRefreshing=true;
refreshMovieWithCurtains();
}
pullDistance=0;
};
window.addEventListener('touchend',finishPull,{passive:true});
window.addEventListener('touchcancel',()=>{
pullTracking=false;
pullDistance=0;
indicator.classList.remove('visible','ready');
indicator.style.transform='';
},{passive:true});
setupEdgeSwipes();
}
async function refreshMovieWithCurtains(){
const overlay=document.getElementById('curtainOverlay');
stopSpeech();
updateDocumentTitle(false);
await scrollToTopAndWait();
resetPosterFlipCard();
overlay.classList.remove('no-light');
overlay.classList.add('loading-movie');
await new Promise(resolve=>setTimeout(resolve,300));
overlay.classList.remove('open');
await new Promise(resolve=>setTimeout(resolve,1000));
await new Promise(resolve=>setTimeout(resolve,300));
const refreshUrl=location.pathname+'?__picks_refresh='+Date.now()+location.hash;
location.replace(refreshUrl);
}
function setupEdgeSwipes(){
const poster=document.getElementById('posterLink');
if(!poster)return;
let startX=0;
let startY=0;
let tracking=false;
let horizontalSwipe=false;
let navigating=false;
const swipeThreshold=80;
poster.addEventListener('touchstart',event=>{
if(event.touches.length!==1||navigating)return;
startX=event.touches[0].clientX;
startY=event.touches[0].clientY;
tracking=true;
horizontalSwipe=false;
},{passive:true});
poster.addEventListener('touchmove',event=>{
if(!tracking||event.touches.length!==1)return;
const deltaX=event.touches[0].clientX-startX;
const deltaY=event.touches[0].clientY-startY;
if(Math.abs(deltaX)>12&&Math.abs(deltaX)>Math.abs(deltaY)){
horizontalSwipe=true;
event.preventDefault();
}
},{passive:false});
poster.addEventListener('touchend',event=>{
if(!tracking||event.changedTouches.length!==1)return;
tracking=false;
const endX=event.changedTouches[0].clientX;
const endY=event.changedTouches[0].clientY;
const deltaX=endX-startX;
const deltaY=endY-startY;
if(Math.abs(deltaX)<swipeThreshold||Math.abs(deltaY)>=Math.abs(deltaX)*0.8)return;
if(deltaX<0){
navigating=true;
fetchNextMovie().finally(()=>{navigating=false;});
}else if(history.state?.movie&&history.length>1){
navigating=true;
history.back();
setTimeout(()=>{navigating=false;},1200);
}
},{passive:true});
poster.addEventListener('touchcancel',()=>{tracking=false;horizontalSwipe=false;},{passive:true});
poster.addEventListener('click',event=>{
if(!horizontalSwipe)return;
event.preventDefault();
event.stopImmediatePropagation();
horizontalSwipe=false;
},true);
}
function setupMoviePosterSearch(){
const posterLink=document.getElementById('posterLink');
const card=document.getElementById('posterFlipCard');
const menu=document.getElementById('movieSearchMenu');
if(!posterLink||!card||!menu)return;
const closeButton=menu.querySelector('.movie-search-close');
const customSearchUrl=document.getElementById('customSearchUrl');
const watchNowButton=document.getElementById('watchNowBtn');
const customSearchStorageKey='picksCustomSearchUrl';
const parseCustomSearchConfig=value=>{
const parts=String(value||'').split(';');
const firstPart=parts.shift()||'';
const urlStart=firstPart.search(/https?:\/\//i);
if(urlStart<0)return {separator:'',urls:[]};
const rawPrefix=firstPart.slice(0,urlStart);
const separator=rawPrefix.trim()?rawPrefix.trim():(rawPrefix?' ':'');
const firstUrl=firstPart.slice(urlStart).trim().replace(/\\:/g,':');
const secondUrl=parts.join(';').trim().replace(/^\+/,'').replace(/\\:/g,':');
return {separator,urls:[firstUrl,...(secondUrl?[secondUrl]:[])]};
};
const isValidCustomSearchUrl=value=>{
const urls=parseCustomSearchConfig(value).urls;
return urls.length>0&&urls.every(url=>{try{const parsed=new URL(url);return (parsed.protocol==='http:'||parsed.protocol==='https:')&&Boolean(parsed.hostname);}catch(error){return false;}});
};
const getCurrentMovieIsOwn=()=>activeMovieIndex>=0&&(movieSources[activeMovieIndex]||[]).includes('movies-own.txt');
const updateCustomSearchState=()=>{const config=parseCustomSearchConfig(customSearchUrl.value);const valid=isValidCustomSearchUrl(customSearchUrl.value);menu.classList.toggle('has-custom-search-url',valid);watchNowButton.hidden=!valid;watchNowButton.textContent=valid&&config.urls.length>1&&getCurrentMovieIsOwn()?'Watch Now':'Watch';};
document.addEventListener('picks:movie-changed',updateCustomSearchState);
try{customSearchUrl.value=localStorage.getItem(customSearchStorageKey)||'';}catch(error){}
updateCustomSearchState();
customSearchUrl.addEventListener('input',()=>{try{localStorage.setItem(customSearchStorageKey,customSearchUrl.value);}catch(error){}updateCustomSearchState();});
const tmdbApiKeyInput=document.getElementById('tmdbApiKey');
const tmdbApiKeyStorageKey='picksTmdbApiKey';
try{if(tmdbApiKeyInput)tmdbApiKeyInput.value=localStorage.getItem(tmdbApiKeyStorageKey)||'';}catch(error){}
if(tmdbApiKeyInput){
tmdbApiKeyInput.addEventListener('input',()=>{try{localStorage.setItem(tmdbApiKeyStorageKey,tmdbApiKeyInput.value.trim());}catch(error){}});
tmdbApiKeyInput.addEventListener('change',()=>{
try{localStorage.setItem(tmdbApiKeyStorageKey,tmdbApiKeyInput.value.trim());}catch(error){}
movieDetailsCache.clear();
if(activeMovieIndex>=0)displayMovieAtIndex(activeMovieIndex);
});
}
watchNowButton.addEventListener('click',()=>{
const config=parseCustomSearchConfig(customSearchUrl.value);
if(!isValidCustomSearchUrl(customSearchUrl.value))return;
const rawTitle=document.getElementById('movieTitle').textContent.trim();
const title=Array.from(rawTitle).filter(char=>/[\p{L}\p{N}\s]/u.test(char)).join('').replace(/\s+/g,' ').trim();
const rawYear=document.getElementById('movieYear').textContent.trim();
const movieYear=rawYear&&rawYear!=='N/A'?Array.from(rawYear).filter(char=>/[0-9]/.test(char)).join(''):'';
const formattedName=config.separator?title.replace(/\s+/g,()=>config.separator):title;
const titleWithoutThe=title.replace(/^the\s+/i,'');
const formattedTitleWithoutThe=config.separator?titleWithoutThe.replace(/\s+/g,()=>config.separator):titleWithoutThe;
const lowerName=formattedName.toLocaleLowerCase(),upperName=formattedName.toLocaleUpperCase();
const lowerTitleWithoutThe=formattedTitleWithoutThe.toLocaleLowerCase(),upperTitleWithoutThe=formattedTitleWithoutThe.toLocaleUpperCase();
const yearSeparator=config.separator||(movieYear?' ':'');
const formatUrl=url=>url.replace(/%tname%%year%/gi,formattedTitleWithoutThe+yearSeparator+movieYear).replace(/%tlname%%year%/gi,lowerTitleWithoutThe+yearSeparator+movieYear).replace(/%tuname%%year%/gi,upperTitleWithoutThe+yearSeparator+movieYear).replace(/%tname%/gi,formattedTitleWithoutThe).replace(/%tlname%/gi,lowerTitleWithoutThe).replace(/%tuname%/gi,upperTitleWithoutThe).replace(/%name%%year%/gi,formattedName+yearSeparator+movieYear).replace(/%tlname%/gi,lowerTitleWithoutThe).replace(/%lname%/gi,lowerName).replace(/%tuname%/gi,upperTitleWithoutThe).replace(/%uname%/gi,upperName).replace(/%name%/gi,formattedName).replace(/%year%/gi,movieYear);
const isOwnMovie=getCurrentMovieIsOwn();
const selectedUrl=config.urls.length>1&&isOwnMovie?config.urls[1]:config.urls[0];
window.open(formatUrl(selectedUrl),'_blank','noopener,noreferrer');
});
const setFlipped=flipped=>{const wasFlipped=card.classList.contains('is-flipped');if(wasFlipped!==flipped)scrollToTopAndWait();card.classList.toggle('is-flipped',flipped);posterLink.setAttribute('aria-expanded',String(flipped));menu.setAttribute('aria-hidden',String(!flipped));menu.inert=!flipped;posterLink.setAttribute('aria-label',flipped?'Movie searches revealed':'Tap to reveal movie searches');};
const openMenu=()=>setFlipped(true);
const closeMenu=returnFocus=>{setFlipped(false);if(returnFocus)posterLink.focus({preventScroll:true});};
posterLink.addEventListener('click',event=>{event.preventDefault();openMenu();});
posterLink.addEventListener('keydown',event=>{if(event.key==='Enter'||event.key===' '){event.preventDefault();openMenu();}});
closeButton.addEventListener('click',()=>closeMenu(true));
menu.addEventListener('click',event=>{if(event.target.closest('.poster-back-controls'))return;const button=event.target.closest('button[data-search-type]');if(!button){closeMenu(true);return;}if(button.classList.contains('movie-search-close'))return;const movieTitle=document.getElementById('movieTitle').textContent.trim();const movieYear=document.getElementById('movieYear').textContent.trim();const searchType=button.dataset.searchType;const movieLabel=movieTitle+(movieYear?' '+movieYear:'');if(searchType==='wikipedia'){const wikiQuery=movieYear&&movieYear!=='N/A'?'\"'+movieTitle+'\" '+movieYear+' film':'\"'+movieTitle+'\" film';window.open('https://en.wikipedia.org/w/index.php?search='+encodeURIComponent(wikiQuery),'_blank','noopener,noreferrer');return;}if(searchType==='imdb'){window.open('https://www.imdb.com/find/?q='+encodeURIComponent(movieLabel),'_blank','noopener,noreferrer');return;}if(searchType==='parents-guide'){const imdbId=currentMovie?.imdbId||currentMovie?.imdb_id||currentMovie?.externalIds?.imdb_id;const googleSearch='https://www.google.com/search?q='+encodeURIComponent(movieLabel+' Parents Guide');const target=imdbId&&/^tt\d+$/.test(imdbId)?'https://www.imdb.com/title/'+imdbId+'/parentalguide/':googleSearch;window.open(target,'_blank','noopener,noreferrer');return;}const searchTerms={trailer:'original theatrical trailer','bts-making-of':'behind the scenes BTS making of documentary featurette production footage cast interviews',history:'film history retrospective documentary'};window.open('https://www.youtube.com/results?search_query='+encodeURIComponent(movieLabel+' '+(searchTerms[searchType]||searchType)),'_blank','noopener,noreferrer');});
document.addEventListener('keydown',event=>{if(event.key==='Escape'&&card.classList.contains('is-flipped'))closeMenu(true);});
}
function parseMovieLine(line){
const cleaned=String(line||'').trim().replace(/^[-*+]\s+/,'').trim();
const match=cleaned.match(/^(.+?)\s+\(?([0-9]{4})\)?\s*$/);
return match?{title:match[1].trim(),year:match[2]}:{title:cleaned,year:''};
}
function movieSlug(title,year){
return normaliseTitle([title,year].filter(Boolean).join(' '));
}
function normaliseMovieUrl(index){
const movie=parseMovieLine(movies[index]);
const slug=movieSlug(movie.title,movie.year);
const movieUrl=`#${slug.replace(/\s+/g,'_')}`;
if(location.hash!==movieUrl)history.replaceState({movie:slug},'',movieUrl);
return slug;
}
const defaultMovieSectionStates={
movieSynopsisSection:true,
movieBlurbSection:true,
moviePlotSummarySection:false,
movieDetailsSection:true
};
function applyMovieSectionStates(){
Object.keys(defaultMovieSectionStates).forEach(id=>{
const section=document.getElementById(id);
if(section)section.open=defaultMovieSectionStates[id];
});
}
function findMovieIndexFromHash(){
let slug=location.hash.slice(1);
try{slug=decodeURIComponent(slug);}catch(error){}
slug=normaliseTitle(slug.replace(/_/g,' '));
if(!slug)return -1;
const exactIndex=movies.findIndex(line=>{
const movie=parseMovieLine(line);
return movieSlug(movie.title,movie.year)===slug;
});
if(exactIndex>=0)return exactIndex;
const requested=slug.match(/^(.*?)\s+((?:19|20)\d{2})$/);
const requestedTitle=requested?requested[1]:slug;
const requestedYear=requested?requested[2]:'';
const candidates=movies.map((line,index)=>{
const movie=parseMovieLine(line);
return {index,title:movie.title,year:movie.year,similarity:titleSimilarity(requestedTitle,movie.title)};
}).filter(movie=>requestedYear?movie.year===requestedYear&&movie.similarity>=0.8:movie.similarity>=0.8);
if(!candidates.length)return -1;
candidates.sort((a,b)=>b.similarity-a.similarity||Number(b.year||0)-Number(a.year||0)||a.index-b.index);
if(candidates.length>1&&candidates[0].similarity===candidates[1].similarity&&normaliseTitle(candidates[0].title)!==normaliseTitle(candidates[1].title))return -1;
if(requestedYear)return candidates[0].index;
const bestSimilarity=candidates[0].similarity;
const bestTitle=normaliseTitle(candidates[0].title);
const sameTitleCandidates=candidates.filter(movie=>movie.similarity===bestSimilarity&&normaliseTitle(movie.title)===bestTitle);
if(sameTitleCandidates.length<2)return candidates[0].index;
const storageKey='picksTitleMatch:'+slug;
let previousIndex=-1;
try{previousIndex=Number(sessionStorage.getItem(storageKey));}catch(error){}
const previousPosition=sameTitleCandidates.findIndex(movie=>movie.index===previousIndex);
const selected=sameTitleCandidates[(previousPosition+1)%sameTitleCandidates.length];
try{sessionStorage.setItem(storageKey,String(selected.index));}catch(error){}
return selected.index;
}
function resetPosterFlipCard(){
const card=document.getElementById('posterFlipCard');
const posterLink=document.getElementById('posterLink');
const menu=document.getElementById('movieSearchMenu');
if(card)card.classList.remove('is-flipped');
if(posterLink)posterLink.setAttribute('aria-expanded','false');
if(menu){
menu.setAttribute('aria-hidden','true');
menu.inert=true;
}
}
function scrollToTopAndWait(){
const synopsisArea=document.querySelector('.synopsis-scroll-area');
window.scrollTo({top:0,behavior:'smooth'});
if(synopsisArea)synopsisArea.scrollTo({top:0,behavior:'smooth'});
return new Promise(resolve=>{
let stableFrames=0;
const checkScroll=()=>{
const pageAtTop=window.scrollY<=1;
const synopsisAtTop=!synopsisArea||synopsisArea.scrollTop<=1;
if(pageAtTop&&synopsisAtTop){
stableFrames++;
if(stableFrames>=3){
resolve();
return;
}
}else{
stableFrames=0;
}
requestAnimationFrame(checkScroll);
};
requestAnimationFrame(checkScroll);
});
}
async function handleMovieUrlChange(){
const index=findMovieIndexFromHash();
if(index<0)return;
const slug=normaliseMovieUrl(index);
if(activeMovieSlug===slug)return;
activeMovieSlug=slug;
const navigationRequest=++historyNavigationRequest;
if(!watchedIndices.includes(index))watchedIndices.push(index);
updateDocumentTitle(false);
const overlay=document.getElementById('curtainOverlay');
stopSpeech();
await scrollToTopAndWait();
resetPosterFlipCard();
overlay.classList.remove('no-light');
overlay.classList.add('loading-movie');
await new Promise(resolve=>setTimeout(resolve,300));
overlay.classList.remove('open');
await new Promise(resolve=>setTimeout(resolve,1000));
await new Promise(resolve=>setTimeout(resolve,300));
if(navigationRequest!==historyNavigationRequest)return;
await displayMovieAtIndex(index);
}
async function showNoMoviesToWatch(){
const overlay=document.getElementById('curtainOverlay');
const message=document.querySelector('#spotlightContent .spotlight-text');
stopSpeech();
await scrollToTopAndWait();
resetPosterFlipCard();
overlay.classList.remove('open','no-light','loading-movie');
updateDocumentTitle(false);
message.innerHTML='<span class="empty-library-title">No Movies to Watch</span><span class="empty-library-instructions">Add movies with a title and year to<br><code>movies-new.txt</code>, <code>movies-own.txt</code>, or <code>movies-fav.txt</code>.</span>';
document.getElementById('reloadBtn').style.display='none';
await new Promise(resolve=>setTimeout(resolve,600));
overlay.classList.add('show-spotlight');
}
async function showNoMoreMovies(){
const overlay=document.getElementById('curtainOverlay');
stopSpeech();
await scrollToTopAndWait();
resetPosterFlipCard();
overlay.classList.remove('open','no-light','loading-movie');
updateDocumentTitle(false);
await new Promise(resolve=>setTimeout(resolve,600));
overlay.classList.add('show-spotlight');
document.getElementById('reloadBtn').style.display='none';
}
async function fetchNextMovie(isInitial=false){
const requestId=++nextMovieRequest;
if(watchedIndices.length>=movies.length){
await showNoMoreMovies();
return;
}
if(!isInitial){
updateDocumentTitle(false);
const overlay=document.getElementById('curtainOverlay');
stopSpeech();
resetPosterFlipCard();
await scrollToTopAndWait();
overlay.classList.remove('no-light');
overlay.classList.add('loading-movie');
await new Promise(resolve=>setTimeout(resolve,300));
overlay.classList.remove('open');
await new Promise(resolve=>setTimeout(resolve,1000));
await new Promise(resolve=>setTimeout(resolve,300));
}
if(requestId!==nextMovieRequest)return;
const chooseRandomMovie=()=>{
const candidates=movies.map((_,index)=>index).filter(index=>
!watchedIndices.includes(index)&&
index!==activeMovieIndex&&
index!==prefetchCandidateIndex
);
if(!candidates.length){
const remaining=movies.map((_,index)=>index).filter(index=>!watchedIndices.includes(index));
return remaining.length?remaining[Math.floor(Math.random()*remaining.length)]:-1;
}
return candidates[Math.floor(Math.random()*candidates.length)];
};
let nextIndex=prefetchedNextIndex!==null&&!watchedIndices.includes(prefetchedNextIndex)
?prefetchedNextIndex
:chooseRandomMovie();
if(nextIndex===-1&&prefetchCandidateIndex!==null&&!watchedIndices.includes(prefetchCandidateIndex)){
nextIndex=prefetchCandidateIndex;
}
if(nextIndex===prefetchedNextIndex)prefetchedNextIndex=null;
while(nextIndex>=0&&requestId===nextMovieRequest){
const index=nextIndex;
const parsed=parseMovieLine(movies[index]);
const slug=movieSlug(parsed.title,parsed.year);
const movieUrl=`#${slug.replace(/\s+/g,'_').replace(/%20/gi,'_')}`;
const displayAttempt=(async()=>{
await displayMovieAtIndex(index);
if(!document.getElementById('curtainOverlay').classList.contains('open')||activeMovieSlug!==slug)return false;
if(isInitial){
history.replaceState({movie:slug},'',movieUrl);
}else{
history.pushState({movie:slug},'',movieUrl);
}
if(!watchedIndices.includes(index))watchedIndices.push(index);
return true;
})();
const result=await Promise.race([
displayAttempt.catch(error=>{
console.error('Movie failed to load:',movies[index],error);
return false;
}),
new Promise(resolve=>setTimeout(()=>resolve(false),movieLoadTimeout))
]);
if(requestId!==nextMovieRequest)return;
if(result)return;
movieDisplayRequest++;
if(!watchedIndices.includes(index))watchedIndices.push(index);
if(prefetchedNextIndex===index)prefetchedNextIndex=null;
const overlay=document.getElementById('curtainOverlay');
overlay.classList.remove('open','no-light','loading-movie');
updateDocumentTitle(false);
if(watchedIndices.length>=movies.length){
await showNoMoreMovies();
return;
}
nextIndex=chooseRandomMovie();
}
if(requestId===nextMovieRequest&&watchedIndices.length>=movies.length){
await showNoMoreMovies();
}
}
async function copyMovieUrl(){
const url=`${location.origin}${location.pathname}${location.search}${location.hash.replace(/%20/gi,'_').replace(/ /g,'_')}`;
const button=document.getElementById('shareMovieBtn');
try{
if(navigator.clipboard&&window.isSecureContext){
await navigator.clipboard.writeText(url);
}else{
throw new Error('Clipboard API unavailable');
}
}catch(error){
const textarea=document.createElement('textarea');
textarea.value=url;
textarea.style.position='fixed';
textarea.style.opacity='0';
document.body.appendChild(textarea);
textarea.select();
let copied=false;
try{copied=document.execCommand('copy');}catch(copyError){}
textarea.remove();
if(!copied){
console.error('Could not copy movie URL:',error);
return;
}
}
const originalText='Share Movie';
button.textContent='Copied!';
setTimeout(()=>{if(button.textContent==='Copied!')button.textContent=originalText;},1500);
}
async function displayMovieAtIndex(randomIndex){
const requestId=++movieDisplayRequest;
const overlay=document.getElementById('curtainOverlay');
overlay.classList.add('loading-movie');
const parsed=parseMovieLine(movies[randomIndex]);
activeMovieIndex=randomIndex;
activeMovieSlug=movieSlug(parsed.title,parsed.year);
const title=parsed.title;
const year=parsed.year;
let movie=movieDetailsCache.get(randomIndex);
if(!movie){
movie=await fetchMovieDetails(title,year);
movieDetailsCache.set(randomIndex,movie);
}
if(requestId!==movieDisplayRequest)return;
currentMovie=movie;
const sourceBadge=document.getElementById('movieSourceBadge');
if(sourceBadge){
const sources=movieSources[randomIndex]||['movies-new.txt'];
const labels={'movies-new.txt':['U','New'],'movies-fav.txt':['F','Favourite'],'movies-own.txt':['O','Owned']};
const sourceCodes=['movies-new.txt','movies-fav.txt','movies-own.txt'].filter(file=>sources.includes(file));
const activeLetters={
U:sources.includes('movies-new.txt'),
F:sources.includes('movies-fav.txt'),
O:sources.includes('movies-own.txt')
};
sourceBadge.innerHTML=['U','F','O'].map(letter=>'<span class="source-letter'+(activeLetters[letter]?'':' inactive')+'">'+letter+'</span>').join('');
sourceBadge.setAttribute('aria-label',['U','F','O'].map(letter=>activeLetters[letter]?({U:'New',F:'Favourite',O:'Owned'})[letter]:null).filter(Boolean).join(' and ')+' movie list'+(sourceCodes.length>1?'s':''));
}
document.getElementById('movieTitle').innerText=currentMovie.title;
document.getElementById('movieYear').innerText=currentMovie.year;
document.dispatchEvent(new Event('picks:movie-changed'));
document.getElementById('movieSynopsis').innerText=currentMovie.synopsis;
document.getElementById('movieBlurb').innerText=currentMovie.blurb;
document.getElementById('movieBlurbSection').style.display=currentMovie.blurb?'':'none';
document.getElementById('moviePlotSummary').innerText=currentMovie.plotSummary||'';
document.getElementById('moviePlotSummarySection').hidden=!currentMovie.plotSummary;
document.getElementById('movieDetails').innerHTML=renderMovieDetails(currentMovie);
requestAnimationFrame(()=>requestAnimationFrame(updateSynopsisScrollHints));
await loadPoster(currentMovie);
if(requestId!==movieDisplayRequest)return;
const posterElement=document.getElementById('moviePoster');
const posterCard=document.getElementById('posterFlipCard');
const searchMenu=document.getElementById('movieSearchMenu');
posterCard?.classList.remove('is-flipped');
posterLink.setAttribute('aria-expanded','false');
searchMenu?.setAttribute('aria-hidden','true');
if(searchMenu)searchMenu.inert=true;
posterLink.setAttribute('aria-label',`Tap to search YouTube for ${title}${year?' '+year:''}`);
posterLink.title=`Tap to reveal YouTube searches for ${title}${year?' '+year:''}`;
const updatePosterLayout=()=>{
fitCardToPoster();
posterCard?.classList.toggle('has-wide-poster',Boolean(posterElement.naturalWidth&&posterElement.naturalHeight&&posterElement.naturalWidth/posterElement.naturalHeight>1.15));
};
posterElement.onload=updatePosterLayout;
posterElement.src=currentMovie.poster;
const searchPosterBackdrop=document.getElementById('searchPosterBackdrop');
if(searchPosterBackdrop)searchPosterBackdrop.src=currentMovie.poster;
if(posterElement.complete)updatePosterLayout();
document.getElementById('bgBackdrop').style.backgroundImage=`url('${currentMovie.poster}')`;
await new Promise(resolve=>setTimeout(resolve,150));
overlay.classList.remove('loading-movie');
overlay.classList.add('open');
updateDocumentTitle(true);
setTimeout(()=>overlay.classList.add('no-light'),1050);
prefetchNextMovie();
}
async function prefetchNextMovie(){
if(prefetchInProgress||prefetchedNextIndex!==null||!movies.length||watchedIndices.length>=movies.length)return;
const attempted=new Set();
const timeoutResult=Symbol('prefetch-timeout');
const maxPrefetchAttempts=Math.min(3,movies.length);
const task=(async()=>{
try{
while(attempted.size<maxPrefetchAttempts){
const candidates=movies.map((_,index)=>index).filter(index=>
!watchedIndices.includes(index)&&
index!==activeMovieIndex&&
!attempted.has(index)
);
if(!candidates.length)return;
const index=candidates[Math.floor(Math.random()*candidates.length)];
attempted.add(index);
prefetchCandidateIndex=index;
const attempt=(async()=>{
let movie=movieDetailsCache.get(index);
if(!movie){
const parsed=parseMovieLine(movies[index]);
movie=await fetchMovieDetails(parsed.title,parsed.year);
movieDetailsCache.set(index,movie);
}
if(movie.synopsis==='Synopsis currently unavailable.'&&movie.poster===fallbackPoster){
throw new Error('Movie details could not be found');
}
await loadPoster(movie);
return movie;
})();
try{
const movie=await Promise.race([
attempt,
new Promise(resolve=>setTimeout(()=>resolve(timeoutResult),movieLoadTimeout))
]);
if(movie===timeoutResult){
console.warn('Movie preloading timed out; trying another movie:',movies[index]);
if(prefetchCandidateIndex===index)prefetchCandidateIndex=null;
continue;
}
if(watchedIndices.includes(index)||index===activeMovieIndex){
if(prefetchCandidateIndex===index)prefetchCandidateIndex=null;
continue;
}
prefetchedNextIndex=index;
return;
}catch(error){
console.error('Movie preloading failed; trying another movie:',movies[index],error);
if(prefetchCandidateIndex===index)prefetchCandidateIndex=null;
}
}
}finally{
if(prefetchInProgress===task)prefetchInProgress=null;
if(prefetchCandidateIndex!==null&&prefetchedNextIndex!==prefetchCandidateIndex)prefetchCandidateIndex=null;
}
})();
prefetchInProgress=task;
await task;
}
function normaliseTitle(title){
const transliterations={
'æ':'ae',
'ǽ':'ae',
'œ':'oe',
'ß':'ss',
'ø':'o',
'ł':'l',
'đ':'d',
'ð':'d',
'þ':'th',
'ħ':'h',
'ı':'i'
};
return String(title||'')
.toLowerCase()
.replace(/[æǽœßøłđðþħı]/g,character=>transliterations[character]||character)
.normalize('NFD')
.replace(/[\u0300-\u036f]/g,'')
.replace(/&/g,'and')
.replace(/['’]/g,'')
.replace(/[^\p{L}\p{N}]+/gu,' ')
.replace(/\s+/g,' ')
.trim();
}
function titleWords(title){
return normaliseTitle(title).split(' ').filter(Boolean);
}
function titleSimilarity(a,b){
const x=normaliseTitle(a);
const y=normaliseTitle(b);
if(!x||!y)return 0;
if(x===y)return 1;
const ax=new Set(titleWords(a));
const bx=new Set(titleWords(b));
let common=0;
ax.forEach(word=>{
if(bx.has(word))common++;
});
return common/Math.max(ax.size,bx.size);
}
function getYearFromClaims(claims){
const claim=claims?.P577?.[0]?.mainsnak?.datavalue?.value?.time;
if(!claim)return '';
const match=claim.match(/\+(\d{4})-/);
return match?match[1]:'';
}
function isFilmEntity(entity){
const description=(entity.description?.value||'').toLowerCase();
if(description.includes('film')||
description.includes('movie')||
description.includes('motion picture')||
description.includes('feature-length')){
return true;
}
const filmTypes=[
'Q11424',
'Q24869',
'Q29168811',
'Q202866',
'Q506240',
'Q18011172',
'Q93204',
'Q130232',
'Q229390'
];
const p31=entity.claims?.P31||[];
return p31.some(claim=>{
const id=claim.mainsnak?.datavalue?.value?.id;
return filmTypes.includes(id);
});
}
function getAliases(entity){
const aliases=[];
if(entity.aliases){
Object.values(entity.aliases).forEach(list=>{
list.forEach(item=>{
if(item.value)aliases.push(item.value);
});
});
}
return aliases;
}
function scoreWikidataEntity(entity,title,year){
if(!isFilmEntity(entity))return -100000;
const label=entity.labels?.en?.value||'';
const aliases=getAliases(entity);
const requested=normaliseTitle(title);
let score=0;
if(normaliseTitle(label)===requested)score+=1000;
aliases.forEach(alias=>{
if(normaliseTitle(alias)===requested)score+=950;
});
const bestLabelSimilarity=titleSimilarity(title,label);
if(bestLabelSimilarity===1)score+=500;
else score+=bestLabelSimilarity*300;
aliases.forEach(alias=>{
score=Math.max(score,titleSimilarity(title,alias)*280);
});
const entityYear=getYearFromClaims(entity.claims);
if(year){
if(entityYear===year)score+=800;
else if(entityYear)score-=700;
}
if(entity.sitelinks?.enwiki)score+=150;
if(entity.description?.value){
const description=entity.description.value.toLowerCase();
if(description.includes('film'))score+=100;
if(description.includes('american film'))score+=20;
if(description.includes('british film'))score+=20;
if(description.includes('french film'))score+=20;
if(description.includes('italian film'))score+=20;
if(description.includes('german film'))score+=20;
if(description.includes('czech film'))score+=20;
}
return score;
}
async function searchWikidata(title,year){
const cacheKey=`${title}|${year}`;
if(wikidataCache.has(cacheKey)){
return wikidataCache.get(cacheKey);
}
const languages=['en','fr','it','de','es','cs','ru'];
const searches=languages.map(language=>()=>fetch(
`https://www.wikidata.org/w/api.php?action=wbsearchentities&search=${encodeURIComponent(title)}&language=${language}&uselang=en&type=item&limit=20&format=json&origin=*`
).then(response=>response.ok?response.json():null).catch(()=>null));
const responses=[];
for(let i=0;i<searches.length;i+=3){
responses.push(...await Promise.all(searches.slice(i,i+3).map(search=>search())));
}
const ids=new Set();
responses.forEach(data=>{
(data?.search||[]).forEach(result=>{
if(result.id)ids.add(result.id);
});
});
if(!ids.size){
wikidataCache.set(cacheKey,null);
return null;
}
const entityResponse=await fetch(
`https://www.wikidata.org/w/api.php?action=wbgetentities&ids=${[...ids].join('|')}&props=labels|aliases|claims|sitelinks&languages=en&sitefilter=enwiki&format=json&origin=*`
);
if(!entityResponse.ok){
wikidataCache.set(cacheKey,null);
return null;
}
const entityData=await entityResponse.json();
const entities=Object.values(entityData.entities||{});
entities.sort((a,b)=>scoreWikidataEntity(b,title,year)-scoreWikidataEntity(a,title,year));
const buildResult=(entity,entityYear)=>{
const wikipediaTitle=entity.sitelinks?.enwiki?.title;
if(!wikipediaTitle)return null;
return {
id:entity.id,
title:entity.labels?.en?.value||title,
year:entityYear||year||'',
wikipediaTitle,
claims:entity.claims||{}
};
};
const requestedTitle=normaliseTitle(title);
const isExactTitleMatch=entity=>{
const label=normaliseTitle(entity.labels?.en?.value||'');
return label===requestedTitle||getAliases(entity).some(alias=>normaliseTitle(alias)===requestedTitle);
};
const exactTitleEntities=entities.filter(entity=>
scoreWikidataEntity(entity,title,year)>=500&&
isExactTitleMatch(entity)&&
entity.sitelinks?.enwiki
);
// First pass: prefer a known release year that exactly matches the requested year.
for(const entity of exactTitleEntities){
const entityYear=getYearFromClaims(entity.claims);
if(year&&entityYear!==year)continue;
const result=buildResult(entity,entityYear);
if(!result)continue;
wikidataCache.set(cacheKey,result);
return result;
}
// Second pass: when no exact-year match exists, choose the closest known release year.
// This avoids picking an arbitrary film when a title has several versions, such as Hercules.
if(year){
const nearestYearEntities=exactTitleEntities
.map(entity=>({entity,entityYear:getYearFromClaims(entity.claims)}))
.filter(item=>item.entityYear)
.sort((a,b)=>Math.abs(Number(a.entityYear)-Number(year))-Math.abs(Number(b.entityYear)-Number(year))||
scoreWikidataEntity(b.entity,title,year)-scoreWikidataEntity(a.entity,title,year));
for(const item of nearestYearEntities){
const result=buildResult(item.entity,item.entityYear);
if(!result)continue;
wikidataCache.set(cacheKey,result);
return result;
}
}
// Last fallback: exact title/alias with no known year, or a title mismatch only if there is no exact-title entity.
for(const entity of exactTitleEntities){
const entityYear=getYearFromClaims(entity.claims);
if(entityYear)continue;
const result=buildResult(entity,entityYear);
if(!result)continue;
wikidataCache.set(cacheKey,result);
return result;
}
wikidataCache.set(cacheKey,null);
return null;
}
async function getWikipediaSummary(pageTitle){
if(wikipediaCache.has(pageTitle)){
return wikipediaCache.get(pageTitle);
}
try{
const response=await fetch(
`https://en.wikipedia.org/api/rest_v1/page/summary/${encodeURIComponent(pageTitle)}`
);
if(!response.ok){
wikipediaCache.set(pageTitle,null);
return null;
}
const data=await response.json();
if(data.type==='disambiguation'||!data.extract){
wikipediaCache.set(pageTitle,null);
return null;
}
wikipediaCache.set(pageTitle,data);
return data;
}catch(error){
console.error('Wikipedia summary error:',error);
wikipediaCache.set(pageTitle,null);
return null;
}