-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
1602 lines (1464 loc) · 87.1 KB
/
Copy pathApp.tsx
File metadata and controls
1602 lines (1464 loc) · 87.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
import React, { useState, useRef, useEffect } from 'react';
import { extractVideoId, blobToBase64, fetchVideoMetadata, searchYouTubeVideos, fetchChannelVideos, fetchChannelDetails, extractChannelId, fetchExploreFeed, extractTweetId } from './utils/youtube';
import { analyzeThumbnail, sendChatMessage, analyzeBotProbability, analyzeDirtyMind, analyzeXPost } from './services/geminiService';
import { AppState, AnalysisResult, ChatMessage, ChangelogEntry, BotAnalysisResult, SavedItem, RiceTubeCategory, SearchResult, ChannelDetails, VideoMetadata, DirtyAnalysisResult, XAnalysisResult } from './types';
import { ScoreCard } from './components/ScoreCard';
import {
Youtube, Search, CircleAlert, Loader2, Send, X,
TriangleAlert, Siren, Bot, FolderOpen, Trash2,
ShoppingBag, Check, Hammer, Settings, Key, MonitorPlay, Eye,
EyeOff, ArrowLeft, Link2, HelpCircle, Flame,
Home, Gamepad2, Music2, Cpu, Play, FileText, Download, MessageSquare, Megaphone,
RotateCw, RefreshCcw, Lock, Unlock, Brain, FlaskConical, Twitter,
ShieldCheck, ShieldAlert, Sofa, Ghost
} from 'lucide-react';
import clsx from 'clsx';
import { AnalysisChart } from './components/AnalysisChart';
const CHANGELOG_DATA: ChangelogEntry[] = [
{
version: "v2.54",
date: "2025-12-31",
title: "The De-Bar Update",
changes: [
"Removed unsightly black bars (footer border, custom scrollbar).",
"Cleaned up UI visual noise.",
"Updated browser theme color."
]
},
{
version: "v2.53",
date: "2025-12-31",
title: "The Anonymous Update",
changes: [
"Lazy Mode is now Anonymous Watch Mode.",
"Deprecated AI chat in Lazy Mode (it was hallucinating anyway).",
"Watch videos without being tracked by the algorithm."
]
},
{
version: "v2.52",
date: "2025-12-30",
title: "The Lazy Update",
changes: [
"Removed 'Ask Video' and replaced it by 'Stop being a lazy ass and go watch it yourself'.",
"Dirty Tester: Now smarter at distinguishing innocent vegetables from sus bait.",
"Improved research logic (less hallucination)."
]
},
{
version: "v2.51",
date: "2025-12-29",
title: "The Context Update",
changes: [
"Ask Video now researches web context instead of hallucinating.",
"Dirty Tester logic improved: now detects innocent vs bait.",
"UI tweaks for clarity."
]
},
{
version: "v2.50",
date: "2025-12-28",
title: "The Potato Update",
changes: [
"Rebranded to PotatoTool.",
"UI is now mobile responsive.",
"RiceTube became TaterTube.",
"New PotatoBot persona."
]
}
];
type ActiveTab = 'RATER' | 'BOT_HUNTER' | 'VIDEO_CHAT' | 'DIRTY_TESTER' | 'X_RATER';
type StoreView = 'SEARCH' | 'CHANNEL';
const SmashLogo = () => (
<div className="relative group w-10 h-10 flex items-center justify-center cursor-pointer">
<div className="absolute inset-0 bg-red-600 rounded-xl border-2 border-black shadow-[3px_3px_0px_0px_rgba(0,0,0,1)] group-hover:translate-y-1 group-hover:shadow-none transition-all duration-100 flex items-center justify-center overflow-hidden dark:shadow-[3px_3px_0px_0px_rgba(255,255,255,1)]">
<div className="w-0 h-0 border-t-[5px] border-t-transparent border-l-[10px] border-l-white border-b-[5px] border-b-transparent ml-1"></div>
<div className="absolute inset-0 bg-gradient-to-tr from-black/20 to-transparent pointer-events-none"></div>
</div>
<Hammer className="absolute -top-3 -right-3 w-8 h-8 text-black fill-zinc-300 drop-shadow-sm transition-transform duration-100 origin-bottom-left group-hover:rotate-[-45deg] z-10 dark:text-white dark:fill-zinc-600" />
<div className="absolute -bottom-6 left-1/2 -translate-x-1/2 text-[10px] font-bold uppercase text-black opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap bg-yellow-300 px-1 border border-black rotate-[-5deg] font-sans">
BONK!
</div>
</div>
);
const Tape = ({ className }: { className?: string }) => (
<div className={clsx("absolute w-24 h-8 bg-white/60 border border-black/10 rotate-[-3deg] backdrop-blur-sm shadow-sm z-20", className)}></div>
);
const BetaTape = () => (
<span className="absolute -top-3 -right-3 md:-right-4 bg-[#fde047] text-black text-[8px] md:text-[9px] font-black px-1.5 md:px-2 py-0.5 border border-black rotate-[-10deg] shadow-[1px_1px_0px_0px_rgba(0,0,0,1)] z-10 dark:border-white dark:shadow-[1px_1px_0px_0px_rgba(255,255,255,1)] pointer-events-none">
BETA
</span>
);
const PotatoBotAvatar = () => (
<div className="w-10 h-10 rounded-full border-[3px] border-black overflow-hidden bg-white shrink-0 hard-shadow-sm dark:border-white dark:shadow-[3px_3px_0px_0px_rgba(255,255,255,1)]">
<img src="https://i.imgur.com/gL1bk4m.png" alt="PotatoBot" className="w-full h-full object-cover" />
</div>
);
const generateCaptcha = () => Math.random().toString(36).substring(7);
const App: React.FC = () => {
const [activeTab, setActiveTab] = useState<ActiveTab>('RATER');
const [url, setUrl] = useState('');
const [appState, setAppState] = useState<AppState>(AppState.IDLE);
const [isDarkMode, setIsDarkMode] = useState(false);
const [thumbnailSrc, setThumbnailSrc] = useState<string | null>(null);
const [imageBase64, setImageBase64] = useState<string | null>(null);
const [videoTitle, setVideoTitle] = useState<string | null>(null);
const [videoDesc, setVideoDesc] = useState<string | null>(null);
const [videoKeywords, setVideoKeywords] = useState<string[]>([]);
const [isMetadataLoading, setIsMetadataLoading] = useState(false);
const [result, setResult] = useState<AnalysisResult | null>(null);
const [errorMsg, setErrorMsg] = useState<string | null>(null);
// RiceTube (Now TaterTube) State
const [showRiceTube, setShowRiceTube] = useState(false);
const [rtView, setRtView] = useState<StoreView>('SEARCH');
const [rtCategory, setRtCategory] = useState<RiceTubeCategory>('HOME');
const [rtQuery, setRtQuery] = useState('');
const [rtResults, setRtResults] = useState<SearchResult[]>([]);
const [rtIsLoading, setRtIsLoading] = useState(false);
const [rtSelectedChannel, setRtSelectedChannel] = useState<SearchResult | null>(null);
const [rtNextPageToken, setRtNextPageToken] = useState<string | undefined>(undefined);
const [isSusUnlocked, setIsSusUnlocked] = useState(false);
const [susCaptchaString, setSusCaptchaString] = useState(generateCaptcha());
const [susCaptchaInput, setSusCaptchaInput] = useState('');
const [copiedItemId, setCopiedItemId] = useState<string | null>(null);
const [revealedItems, setRevealedItems] = useState<Set<string>>(new Set());
const [botResult, setBotResult] = useState<BotAnalysisResult | null>(null);
const [analyzingChannel, setAnalyzingChannel] = useState<ChannelDetails | null>(null);
const [currentVideoMetadata, setCurrentVideoMetadata] = useState<VideoMetadata | null>(null);
const [activeVideoId, setActiveVideoId] = useState<string | null>(null);
const [dirtyResult, setDirtyResult] = useState<DirtyAnalysisResult | null>(null);
const [dirtyInput, setDirtyInput] = useState<string>('');
const [xResult, setXResult] = useState<XAnalysisResult | null>(null);
const [xUrl, setXUrl] = useState<string>('');
const [showImageWarning, setShowImageWarning] = useState(false);
const [showChangelog, setShowChangelog] = useState(false);
const [showHelp, setShowHelp] = useState(false);
const [showSusContent, setShowSusContent] = useState(false);
const [showSaveModal, setShowSaveModal] = useState(false);
const [showSavedList, setShowSavedList] = useState(false);
const [showSettings, setShowSettings] = useState(false);
const [showReporting, setShowReporting] = useState(false);
const [apiKeyInput, setApiKeyInput] = useState('');
const [savedItems, setSavedItems] = useState<SavedItem[]>([]);
const [chatHistory, setChatHistory] = useState<ChatMessage[]>([]);
const [chatInput, setChatInput] = useState('');
const [isChatLoading, setIsChatLoading] = useState(false);
const chatEndRef = useRef<HTMLDivElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const importInputRef = useRef<HTMLInputElement>(null);
const isCelebrationMode = result?.scores?.overall === 10;
useEffect(() => {
chatEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [chatHistory, isChatLoading]);
useEffect(() => {
try {
const storedItems = localStorage.getItem('thumb_rate_saved');
if (storedItems) setSavedItems(JSON.parse(storedItems));
const storedKey = localStorage.getItem('potatotool_api_key');
if (storedKey) setApiKeyInput(storedKey);
} catch (e) { console.error(e); }
}, []);
const handleSaveSettings = () => {
localStorage.setItem('potatotool_api_key', apiKeyInput);
setShowSettings(false);
alert("Settings saved.");
};
const toggleDarkMode = () => {
setIsDarkMode(!isDarkMode);
if (!isDarkMode) {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
};
// TaterTube Functions
const openRiceTube = () => {
setShowRiceTube(true);
if (rtResults.length === 0) loadRiceTubeCategory('HOME');
};
const refreshRiceTube = () => {
if (rtView === 'SEARCH') {
if (rtQuery) handleRiceTubeSearch();
else loadRiceTubeCategory(rtCategory);
} else if (rtView === 'CHANNEL' && rtSelectedChannel) {
handleRtItemClick(rtSelectedChannel);
}
};
const loadRiceTubeCategory = async (cat: RiceTubeCategory) => {
setRtCategory(cat);
setRtView('SEARCH');
setRtIsLoading(true);
setRtResults([]);
try {
const results = await fetchExploreFeed(cat);
setRtResults(results);
} catch (e) { console.error(e); }
finally { setRtIsLoading(false); }
};
const handleRiceTubeSearch = async () => {
if (!rtQuery.trim()) return;
setRtIsLoading(true);
setRtResults([]);
try {
const results = await searchYouTubeVideos(rtQuery);
setRtResults(results);
} catch (e) { console.error(e); }
finally { setRtIsLoading(false); }
};
const handleRtItemClick = async (item: SearchResult) => {
if (item.type === 'channel') {
setRtSelectedChannel(item);
setRtView('CHANNEL');
setRtIsLoading(true);
setRtResults([]);
try {
const vids = await fetchChannelVideos(item.id);
setRtResults(vids);
setRtNextPageToken("page:2");
} catch(e) { console.error(e); }
finally { setRtIsLoading(false); }
} else {
handleCopy(item.id, 'video');
}
};
const handleLoadMore = async () => {
if (rtView === 'CHANNEL' && rtSelectedChannel && rtNextPageToken) {
setRtIsLoading(true);
try {
const newVids = await fetchChannelVideos(rtSelectedChannel.id, rtNextPageToken);
setRtResults(prev => [...prev, ...newVids]);
if (newVids.length > 0) {
if (rtNextPageToken.startsWith('page:')) {
const curr = parseInt(rtNextPageToken.split(':')[1]);
setRtNextPageToken(`page:${curr + 1}`);
} else {
// Handle official API pagination if implemented
}
} else {
setRtNextPageToken(undefined);
}
} catch(e) { console.error(e); }
finally { setRtIsLoading(false); }
}
};
const handleCaptchaSubmit = () => {
if (susCaptchaInput === susCaptchaString) {
setIsSusUnlocked(true);
loadRiceTubeCategory('SUS');
} else {
alert("Wrong code. Are you a robot?");
setSusCaptchaString(generateCaptcha());
setSusCaptchaInput('');
}
};
const refreshCaptcha = () => {
setSusCaptchaString(generateCaptcha());
};
const handleUrlChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setUrl(e.target.value);
if (appState === AppState.ERROR) {
setAppState(AppState.IDLE);
setErrorMsg(null);
}
};
const resetAnalysis = () => {
setResult(null);
setBotResult(null);
setAnalyzingChannel(null);
setCurrentVideoMetadata(null);
setActiveVideoId(null);
setDirtyResult(null);
setXResult(null);
setXUrl('');
setDirtyInput('');
setVideoTitle(null);
setVideoDesc(null);
setVideoKeywords([]);
setAppState(AppState.IDLE);
setErrorMsg(null);
setChatHistory([]);
setChatInput('');
setShowSusContent(false);
setShowSaveModal(false);
setThumbnailSrc(null);
setImageBase64(null);
};
const fetchImageFromVideoId = async (videoId: string) => {
setAppState(AppState.LOADING_IMAGE);
setIsMetadataLoading(true);
fetchVideoMetadata(videoId).then(meta => {
setVideoTitle(meta.title || "Unknown Title");
setVideoDesc(meta.description || "No description found.");
setVideoKeywords(meta.keywords || []);
setIsMetadataLoading(false);
}).catch(e => {
console.error("Metadata fetch error:", e);
setIsMetadataLoading(false);
});
const tryFetch = async (resolution: 'maxresdefault' | 'hqdefault') => {
const imgUrl = `https://i.ytimg.com/vi/${videoId}/${resolution}.jpg`;
const proxyUrl = `https://api.codetabs.com/v1/proxy?quest=${encodeURIComponent(imgUrl)}`;
const response = await fetch(proxyUrl);
if (!response.ok) throw new Error(`Status ${response.status}`);
return response.blob();
};
try {
let blob: Blob;
try {
blob = await tryFetch('maxresdefault');
} catch (e) {
blob = await tryFetch('hqdefault');
}
const base64 = await blobToBase64(blob);
setImageBase64(base64);
const objectUrl = URL.createObjectURL(blob);
setThumbnailSrc(objectUrl);
setAppState(AppState.READY_TO_ANALYZE);
} catch (err) {
setErrorMsg("Could not fetch thumbnail. The video might be private or invalid.");
setAppState(AppState.ERROR);
}
};
const fetchImageFromChannel = async (channelId: string) => {
setAppState(AppState.LOADING_IMAGE);
try {
const details = await fetchChannelDetails(channelId);
if (!details || !details.thumbnailUrl) throw new Error("Channel not found");
setVideoTitle(details.title); // Use Channel Name as "Title"
setVideoDesc(details.description);
// Fetch PFP through proxy to get Base64
const proxyUrl = `https://api.codetabs.com/v1/proxy?quest=${encodeURIComponent(details.thumbnailUrl)}`;
const response = await fetch(proxyUrl);
const blob = await response.blob();
const base64 = await blobToBase64(blob);
setImageBase64(base64);
const objectUrl = URL.createObjectURL(blob);
setThumbnailSrc(objectUrl);
setAppState(AppState.READY_TO_ANALYZE);
} catch (e) {
setErrorMsg("Could not fetch channel details.");
setAppState(AppState.ERROR);
}
};
const runBotAnalysis = async (channelId: string) => {
setAppState(AppState.ANALYZING);
setBotResult(null);
try {
const channelData = await fetchChannelDetails(channelId);
if (!channelData) throw new Error("Could not find channel");
setAnalyzingChannel(channelData);
const videos = await fetchChannelVideos(channelId);
if (videos.length === 0) throw new Error("No videos found");
const result = await analyzeBotProbability(channelData, videos);
setBotResult(result);
setAppState(AppState.SUCCESS);
} catch (e) {
console.error(e);
setErrorMsg("Could not analyze channel. Check the link.");
setAppState(AppState.ERROR);
}
};
const runDirtyAnalysis = async (imageBase64: string, title: string) => {
setAppState(AppState.ANALYZING);
try {
const result = await analyzeDirtyMind(imageBase64, title);
setDirtyResult(result);
setAppState(AppState.SUCCESS);
} catch (e) {
console.error(e);
setErrorMsg("Analysis failed.");
setAppState(AppState.ERROR);
}
};
const runXAnalysis = async (link: string, imgBase64?: string | null) => {
setAppState(AppState.ANALYZING);
setXUrl(link);
try {
const result = await analyzeXPost(link, imgBase64);
setXResult(result);
setAppState(AppState.SUCCESS);
} catch (e) {
console.error(e);
setErrorMsg("Could not analyze tweet. Maybe upload a screenshot?");
setAppState(AppState.ERROR);
}
};
const handleInputSubmit = async () => {
const input = url.trim();
if (!input) return;
if (activeTab === 'RATER') {
const videoId = extractVideoId(input);
if (videoId) {
resetAnalysis();
fetchImageFromVideoId(videoId);
} else {
setErrorMsg("Invalid YouTube video URL.");
setAppState(AppState.ERROR);
}
} else if (activeTab === 'DIRTY_TESTER') {
resetAnalysis();
const videoId = extractVideoId(input);
const channelId = extractChannelId(input);
if (videoId) {
fetchImageFromVideoId(videoId);
} else if (channelId) {
fetchImageFromChannel(channelId);
} else {
// Attempt to resolve channel if it's a handle
if (input.includes('@') || input.includes('youtube.com/')) {
setErrorMsg("Invalid video or channel link.");
setAppState(AppState.ERROR);
} else {
setErrorMsg("Invalid link.");
setAppState(AppState.ERROR);
}
}
} else if (activeTab === 'VIDEO_CHAT') {
const videoId = extractVideoId(input);
if (videoId) {
resetAnalysis();
setActiveVideoId(videoId);
setAppState(AppState.SUCCESS);
} else {
setErrorMsg("Invalid YouTube video URL.");
setAppState(AppState.ERROR);
}
} else if (activeTab === 'X_RATER') {
resetAnalysis();
const tweetId = extractTweetId(input);
if (tweetId || input.includes('twitter.com') || input.includes('x.com')) {
runXAnalysis(input);
} else {
setErrorMsg("Invalid X/Twitter URL.");
setAppState(AppState.ERROR);
}
} else {
// BOT HUNTER
resetAnalysis();
let channelId = extractChannelId(input);
const videoId = extractVideoId(input);
if (videoId && !channelId) {
setAppState(AppState.LOADING_IMAGE);
const meta = await fetchVideoMetadata(videoId);
if (meta.channelId) {
channelId = meta.channelId;
}
}
if (channelId) {
runBotAnalysis(channelId);
} else {
setErrorMsg("Invalid channel or video link.");
setAppState(AppState.ERROR);
}
}
};
const handleCopy = (id: string, type: 'channel' | 'video', e?: React.MouseEvent) => {
e?.stopPropagation();
const link = type === 'channel'
? `https://www.youtube.com/channel/${id}`
: `https://www.youtube.com/watch?v=${id}`;
navigator.clipboard.writeText(link);
setCopiedItemId(id);
setTimeout(() => setCopiedItemId(null), 2000);
};
const toggleReveal = (id: string, e: React.MouseEvent) => {
e.stopPropagation();
const newRevealed = new Set(revealedItems);
if (newRevealed.has(id)) newRevealed.delete(id);
else newRevealed.add(id);
setRevealedItems(newRevealed);
};
const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
if (activeTab === 'BOT_HUNTER' || activeTab === 'VIDEO_CHAT') {
alert("This mode requires a YouTube link.");
return;
}
const file = e.target.files?.[0];
if (!file) return;
resetAnalysis();
try {
const base64 = await blobToBase64(file);
const objectUrl = URL.createObjectURL(file);
setThumbnailSrc(objectUrl);
setImageBase64(base64);
setVideoTitle("Uploaded Image");
if (activeTab === 'DIRTY_TESTER' || activeTab === 'X_RATER') {
setAppState(AppState.READY_TO_ANALYZE);
} else {
setShowImageWarning(true);
setAppState(AppState.READY_TO_ANALYZE);
}
} catch (err) {
setErrorMsg("Failed to process file.");
setAppState(AppState.ERROR);
}
};
const handleAnalyze = async () => {
if (!imageBase64 && activeTab !== 'X_RATER') return;
if (activeTab === 'DIRTY_TESTER') {
if (!imageBase64) return;
runDirtyAnalysis(imageBase64, videoTitle || "Unknown Title");
return;
}
if (activeTab === 'X_RATER') {
runXAnalysis(url || "Uploaded Image", imageBase64);
return;
}
setAppState(AppState.ANALYZING);
setShowSusContent(false);
try {
if (!imageBase64) throw new Error("No image");
const data = await analyzeThumbnail(imageBase64, 'image/jpeg', {
title: videoTitle,
description: videoDesc,
keywords: videoKeywords
});
setResult(data);
setAppState(AppState.SUCCESS);
} catch (err) {
setErrorMsg("Analysis failed. Please try again.");
setAppState(AppState.ERROR);
}
};
const handleSendMessage = async () => {
if (!chatInput.trim()) return;
if (activeTab === 'RATER' && (!imageBase64 || !result)) return;
if (activeTab === 'BOT_HUNTER' && (!botResult || !analyzingChannel)) return;
if (activeTab === 'VIDEO_CHAT') return; // Chat disabled in video chat
if (activeTab === 'DIRTY_TESTER' && !dirtyResult) return;
if (activeTab === 'X_RATER' && !xResult) return;
const userMsg = chatInput;
setChatInput('');
setChatHistory(prev => [...prev, { role: 'user', text: userMsg }]);
setIsChatLoading(true);
try {
const aiResponse = await sendChatMessage(chatHistory, userMsg, {
type: activeTab,
imageBase64: imageBase64,
raterResult: result,
botResult: botResult,
channelDetails: analyzingChannel,
videoResult: null,
videoMetadata: (activeTab === 'RATER' || activeTab === 'DIRTY_TESTER') ? { title: videoTitle, description: videoDesc, keywords: videoKeywords } : currentVideoMetadata,
dirtyResult: dirtyResult,
xResult: xResult,
xUrl: xUrl
});
setChatHistory(prev => [...prev, { role: 'model', text: aiResponse }]);
} catch (error) {
setChatHistory(prev => [...prev, { role: 'model', text: "Connection error." }]);
} finally {
setIsChatLoading(false);
}
};
const prepareSaveItem = (): SavedItem | null => {
if (activeTab === 'RATER' && result && imageBase64) return { id: crypto.randomUUID(), date: new Date().toISOString(), type: 'THUMB_RATER', thumbnailBase64: imageBase64, thumbnailResult: result, videoTitle, videoDesc, videoKeywords };
if (activeTab === 'BOT_HUNTER' && botResult && analyzingChannel) return { id: crypto.randomUUID(), date: new Date().toISOString(), type: 'BOT_HUNTER', botResult, channelDetails: analyzingChannel };
if (activeTab === 'DIRTY_TESTER' && dirtyResult && imageBase64) return { id: crypto.randomUUID(), date: new Date().toISOString(), type: 'DIRTY_TESTER', dirtyResult, thumbnailBase64: imageBase64, videoTitle };
if (activeTab === 'X_RATER' && xResult) return { id: crypto.randomUUID(), date: new Date().toISOString(), type: 'X_RATER', xResult, xUrl, thumbnailBase64: imageBase64 || undefined };
return null;
};
const handleSaveToApp = () => {
const item = prepareSaveItem();
if (!item) { alert("Saving not supported yet."); return; }
const newItems = [item, ...savedItems];
setSavedItems(newItems);
localStorage.setItem('thumb_rate_saved', JSON.stringify(newItems));
setShowSaveModal(false);
alert("Saved to Vault.");
};
const handleDownloadJSON = () => {
const item = prepareSaveItem();
if (!item) return;
const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(item));
const downloadAnchorNode = document.createElement('a');
downloadAnchorNode.setAttribute("href", dataStr);
downloadAnchorNode.setAttribute("download", `potatotool_${item.type}_${item.id.substring(0,8)}.json`);
document.body.appendChild(downloadAnchorNode);
downloadAnchorNode.click();
downloadAnchorNode.remove();
setShowSaveModal(false);
};
const deleteSavedItem = (id: string) => {
const newItems = savedItems.filter(item => item.id !== id);
setSavedItems(newItems);
localStorage.setItem('thumb_rate_saved', JSON.stringify(newItems));
};
const handleImportJSON = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (event) => {
try {
const item = JSON.parse(event.target?.result as string) as SavedItem;
loadSavedItem(item);
} catch (err) { alert("Invalid JSON file."); }
};
reader.readAsText(file);
if (importInputRef.current) importInputRef.current.value = '';
};
const loadSavedItem = (item: SavedItem) => {
resetAnalysis();
setShowSavedList(false);
if (item.type === 'THUMB_RATER') {
setActiveTab('RATER');
setImageBase64(item.thumbnailBase64!);
setThumbnailSrc(`data:image/jpeg;base64,${item.thumbnailBase64}`);
setResult(item.thumbnailResult!);
setVideoTitle(item.videoTitle || null);
setVideoDesc(item.videoDesc || null);
setVideoKeywords(item.videoKeywords || []);
setAppState(AppState.SUCCESS);
} else if (item.type === 'BOT_HUNTER') {
setActiveTab('BOT_HUNTER');
setAnalyzingChannel(item.channelDetails);
setBotResult(item.botResult!);
setAppState(AppState.SUCCESS);
} else if (item.type === 'DIRTY_TESTER') {
setActiveTab('DIRTY_TESTER');
setImageBase64(item.thumbnailBase64!);
setThumbnailSrc(`data:image/jpeg;base64,${item.thumbnailBase64}`);
setVideoTitle(item.videoTitle || "Unknown");
setDirtyResult(item.dirtyResult!);
setAppState(AppState.SUCCESS);
} else if (item.type === 'X_RATER') {
setActiveTab('X_RATER');
setXUrl(item.xUrl || "");
if (item.thumbnailBase64) {
setImageBase64(item.thumbnailBase64);
setThumbnailSrc(`data:image/jpeg;base64,${item.thumbnailBase64}`);
}
setXResult(item.xResult!);
setAppState(AppState.SUCCESS);
}
};
const handleReportChannel = () => {
setShowReporting(true);
setTimeout(() => {
setShowReporting(false);
alert("Channel reported to the internet police.");
}, 3000);
};
// Helper to get active tab color
const getActiveTabColor = () => {
switch(activeTab) {
case 'RATER': return 'bg-pink-400 text-black';
case 'BOT_HUNTER': return 'bg-blue-400 text-black';
case 'VIDEO_CHAT': return 'bg-zinc-400 text-black';
case 'DIRTY_TESTER': return 'bg-yellow-400 text-black';
case 'X_RATER': return 'bg-black text-white dark:bg-white dark:text-black';
default: return 'bg-black text-white';
}
};
return (
<div className="min-h-screen bg-bliss text-black font-sans pb-20 relative overflow-x-hidden dark:bg-zinc-900 w-full">
{/* ... [TaterTube Modal Component] ... */}
{showRiceTube && (
<div className="fixed inset-0 z-[200] bg-zinc-900 font-sans text-white flex flex-col w-full h-full">
<div className="h-16 bg-[#202020] flex items-center justify-between px-2 md:px-4 border-b border-zinc-700 shrink-0 gap-2">
<div className="flex items-center gap-2 md:gap-4">
<button onClick={() => setShowRiceTube(false)} className="p-2 hover:bg-zinc-700 rounded-full">
<ArrowLeft className="w-6 h-6" />
</button>
<div className="flex items-center gap-1">
<div className="w-8 h-8 bg-red-600 rounded-lg flex items-center justify-center">
<Play className="w-5 h-5 text-white fill-white" />
</div>
<span className="font-bold tracking-tighter text-xl hidden md:block">TaterTube™</span>
</div>
</div>
<div className="flex-1 max-w-xl mx-2">
<div className="relative flex items-center">
<input
type="text"
value={rtQuery}
onChange={(e) => setRtQuery(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && handleRiceTubeSearch()}
placeholder="Search TaterTube..."
className="w-full bg-[#121212] border border-zinc-700 rounded-full py-2 pl-4 pr-10 text-white focus:outline-none focus:border-blue-500 text-base"
/>
<button onClick={handleRiceTubeSearch} className="absolute right-0 top-0 h-full px-4 bg-zinc-800 rounded-r-full border-l border-zinc-700 hover:bg-zinc-700">
<Search className="w-5 h-5 text-zinc-400" />
</button>
</div>
</div>
<div className="w-10"></div>
</div>
<div className="flex-1 overflow-y-auto bg-[#0f0f0f]">
{rtView === 'SEARCH' ? (
<>
<div className="flex gap-2 p-3 overflow-x-auto no-scrollbar border-b border-zinc-800 sticky top-0 bg-[#0f0f0f]/95 backdrop-blur z-10">
{['HOME', 'TRENDING', 'GAMING', 'TECH', 'MUSIC', 'SUS'].map((cat) => (
<button
key={cat}
onClick={() => loadRiceTubeCategory(cat as RiceTubeCategory)}
className={clsx(
"px-3 py-1.5 rounded-lg text-sm font-medium whitespace-nowrap transition-colors",
rtCategory === cat ? "bg-white text-black" : "bg-zinc-800 text-zinc-300 hover:bg-zinc-700"
)}
>
{cat === 'SUS' ? (isSusUnlocked ? '💀 SUS (UNLOCKED)' : '🔒 SUS') : cat}
</button>
))}
</div>
{rtCategory === 'SUS' && !isSusUnlocked ? (
<div className="flex flex-col items-center justify-center h-full p-8 text-center space-y-4">
<Ghost className="w-16 h-16 text-zinc-500" />
<h2 className="text-2xl font-bold">The Dark Side of YouTube</h2>
<p className="text-zinc-400 max-w-md">Warning: This feed contains weird, obscure, and potentially unsettling content found in the depths of the algorithm.</p>
<div className="bg-zinc-800 p-6 rounded-xl border border-zinc-700 space-y-4 w-full max-w-sm">
<p className="text-sm text-zinc-400">Prove you are not a bot.</p>
<div className="bg-black p-4 rounded text-center font-mono text-2xl tracking-widest text-green-500 select-none relative overflow-hidden">
<div className="absolute inset-0 bg-green-500/10 animate-pulse"></div>
{susCaptchaString}
</div>
<div className="flex gap-2">
<input
type="text"
value={susCaptchaInput}
onChange={(e) => setSusCaptchaInput(e.target.value)}
placeholder="Enter code"
className="flex-1 bg-zinc-900 border border-zinc-700 rounded px-3 py-2 text-white text-center uppercase text-base"
/>
<button onClick={refreshCaptcha} className="p-2 bg-zinc-700 rounded hover:bg-zinc-600"><RotateCw className="w-5 h-5"/></button>
</div>
<button
onClick={handleCaptchaSubmit}
className="w-full bg-red-600 hover:bg-red-700 text-white font-bold py-3 rounded-lg transition-colors"
>
UNLOCK
</button>
</div>
</div>
) : (
<div className="p-4 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
{rtIsLoading ? (
Array(8).fill(0).map((_, i) => (
<div key={i} className="animate-pulse">
<div className="bg-zinc-800 aspect-video rounded-xl mb-3"></div>
<div className="flex gap-3">
<div className="w-9 h-9 bg-zinc-800 rounded-full"></div>
<div className="flex-1 space-y-2">
<div className="h-4 bg-zinc-800 rounded w-3/4"></div>
<div className="h-3 bg-zinc-800 rounded w-1/2"></div>
</div>
</div>
</div>
))
) : (
rtResults.map((item) => (
<div key={item.id} onClick={() => handleRtItemClick(item)} className="group cursor-pointer">
<div className="relative aspect-video rounded-xl overflow-hidden mb-2 bg-zinc-800 border border-zinc-800 group-hover:border-zinc-600 transition-colors">
<img src={item.thumbnail} alt={item.title} className="w-full h-full object-cover" />
{item.isSus && (
<div className="absolute top-1 right-1 bg-red-600 text-white text-[10px] font-bold px-1.5 py-0.5 rounded uppercase flex items-center gap-1">
<Siren className="w-3 h-3" /> SUS
</div>
)}
{item.type === 'channel' && (
<div className="absolute inset-0 bg-black/50 flex items-center justify-center">
<div className="bg-zinc-800 p-2 rounded-full border border-zinc-600">
<MonitorPlay className="w-6 h-6 text-white" />
</div>
</div>
)}
</div>
<div className="flex gap-3 px-1">
<div className="flex-1">
<h3 className="text-white font-medium text-sm line-clamp-2 leading-tight mb-1 group-hover:text-blue-400 transition-colors" dangerouslySetInnerHTML={{ __html: item.title }}></h3>
<div className="text-zinc-400 text-xs flex items-center gap-1">
<span>{item.channelTitle}</span>
<Check className="w-3 h-3 bg-zinc-700 rounded-full p-0.5" />
</div>
{item.publishedAt && <div className="text-zinc-500 text-xs mt-0.5">{new Date(item.publishedAt).toLocaleDateString()}</div>}
</div>
<button onClick={(e) => handleCopy(item.id, item.type, e)} className="text-zinc-500 hover:text-white self-start pt-1">
{copiedItemId === item.id ? <Check className="w-4 h-4 text-green-500" /> : <Link2 className="w-4 h-4" />}
</button>
</div>
</div>
))
)}
</div>
)}
</>
) : (
// Channel View
<div className="p-4 max-w-6xl mx-auto">
{rtSelectedChannel && (
<>
<div className="flex flex-col md:flex-row items-center md:items-start gap-6 mb-8 border-b border-zinc-800 pb-8">
<div className="w-32 h-32 rounded-full overflow-hidden border-4 border-zinc-800">
<img src={rtSelectedChannel.thumbnail} className="w-full h-full object-cover" />
</div>
<div className="text-center md:text-left flex-1">
<h1 className="text-3xl font-bold mb-2">{rtSelectedChannel.channelTitle}</h1>
<p className="text-zinc-400 text-sm max-w-2xl line-clamp-3 mb-4">{rtSelectedChannel.description || "No description provided."}</p>
<div className="flex items-center justify-center md:justify-start gap-4">
<button className="bg-white text-black px-6 py-2 rounded-full font-bold text-sm hover:bg-zinc-200">Subscribe</button>
<button onClick={() => {
setShowRiceTube(false);
setActiveTab('BOT_HUNTER');
setUrl(`https://youtube.com/channel/${rtSelectedChannel.id}`);
runBotAnalysis(rtSelectedChannel.id);
}} className="bg-zinc-800 text-white px-6 py-2 rounded-full font-bold text-sm border border-zinc-700 hover:bg-zinc-700 flex items-center gap-2">
<Bot className="w-4 h-4" /> Analyze
</button>
</div>
</div>
</div>
<h2 className="text-xl font-bold mb-4">Recent Videos</h2>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
{rtResults.map((item) => (
<div key={item.id} onClick={() => handleCopy(item.id, 'video')} className="group cursor-pointer">
<div className="relative aspect-video rounded-xl overflow-hidden mb-2 bg-zinc-800 border border-zinc-800 group-hover:border-zinc-600 transition-colors">
<img src={item.thumbnail} alt={item.title} className="w-full h-full object-cover" />
</div>
<h3 className="text-white font-medium text-sm line-clamp-2 leading-tight group-hover:text-blue-400 transition-colors" dangerouslySetInnerHTML={{ __html: item.title }}></h3>
<div className="text-zinc-500 text-xs mt-1">{new Date(item.publishedAt!).toLocaleDateString()}</div>
</div>
))}
</div>
{rtNextPageToken && (
<div className="mt-8 flex justify-center">
<button
onClick={handleLoadMore}
disabled={rtIsLoading}
className="px-6 py-3 bg-zinc-800 hover:bg-zinc-700 rounded-full font-medium text-sm disabled:opacity-50"
>
{rtIsLoading ? 'Loading...' : 'Load More Videos'}
</button>
</div>
)}
</>
)}
</div>
)}
</div>
</div>
)}
{/* Main Header */}
<header className="sticky top-0 z-50 bg-[#fbbf24] border-b-[3px] border-black px-4 py-3 flex items-center justify-between dark:bg-[#3f3f46] dark:border-white">
<div className="flex items-center gap-3">
<SmashLogo />
<h1 className="text-2xl md:text-3xl font-black italic tracking-tighter drop-shadow-sm text-black dark:text-white" style={{ fontFamily: '"Comic Neue", cursive' }}>
PotatoTool
</h1>
</div>
<div className="flex items-center gap-2 md:gap-4">
<button onClick={openRiceTube} className="hidden md:flex items-center gap-1 bg-white px-3 py-1.5 border-2 border-black rounded shadow-[2px_2px_0px_0px_rgba(0,0,0,1)] hover:translate-y-0.5 hover:shadow-none transition-all text-xs font-bold uppercase dark:bg-zinc-800 dark:text-white dark:border-zinc-400 dark:shadow-[2px_2px_0px_0px_rgba(255,255,255,1)]">
<Youtube className="w-4 h-4" /> TaterTube™
</button>
<button onClick={() => setShowSavedList(true)} className="bg-white p-2 border-2 border-black rounded shadow-[2px_2px_0px_0px_rgba(0,0,0,1)] hover:translate-y-0.5 hover:shadow-none transition-all flex items-center gap-1 dark:bg-zinc-800 dark:text-white dark:border-zinc-400 dark:shadow-[2px_2px_0px_0px_rgba(255,255,255,1)]">
<FolderOpen className="w-5 h-5" /> <span className="hidden md:inline font-bold text-xs uppercase">Vault</span>
</button>
<button onClick={() => setShowHelp(true)} className="p-2 bg-black text-white rounded hover:bg-zinc-800 transition-colors border-2 border-transparent hover:border-white dark:bg-white dark:text-black dark:hover:border-black">
<HelpCircle className="w-5 h-5" />
</button>
<button onClick={() => setShowSettings(true)} className="p-2 text-black hover:bg-black/10 rounded transition-colors dark:text-white">
<Settings className="w-5 h-5" />
</button>
</div>
</header>
{/* Tab Selector - FLEX WRAP for Clean Centered Layout */}
<div className="container mx-auto px-4 mt-6 mb-6">
<nav className="flex flex-wrap justify-center gap-2 md:gap-4 w-full">
{[
{ id: 'RATER', label: 'Thumb Rater', icon: <Search className="w-4 h-4"/>, color: 'bg-pink-400' },
{ id: 'BOT_HUNTER', label: 'Bot Hunter', icon: <Bot className="w-4 h-4"/>, color: 'bg-blue-400' },
{ id: 'VIDEO_CHAT', label: 'Anon Watch', icon: <EyeOff className="w-4 h-4"/>, color: 'bg-zinc-400' },
{ id: 'DIRTY_TESTER', label: 'Dirty Tester', icon: <Siren className="w-4 h-4"/>, color: 'bg-yellow-400', isBeta: true },
{ id: 'X_RATER', label: 'X Rater', icon: <Twitter className="w-4 h-4"/>, color: 'bg-black text-white', isBeta: true },
].map((tab) => (
<button
key={tab.id}
onClick={() => { setActiveTab(tab.id as ActiveTab); resetAnalysis(); }}
className={clsx(
"relative px-4 py-3 md:py-2 border-[3px] border-black font-black uppercase text-sm flex items-center justify-center gap-2 transition-all shadow-[4px_4px_0px_0px_rgba(0,0,0,1)] hover:-translate-y-1 hover:shadow-[6px_6px_0px_0px_rgba(0,0,0,1)] active:translate-y-0 active:shadow-none flex-grow md:flex-grow-0",
activeTab === tab.id ? `${tab.color} text-black` : "bg-white text-black hover:bg-gray-50",
tab.id === 'X_RATER' && activeTab === 'X_RATER' && "text-white"
)}
>
{tab.icon}
{tab.label}
{tab.isBeta && <BetaTape />}
</button>
))}
</nav>
</div>
<main className="container mx-auto px-4 max-w-4xl relative z-10">
{/* INPUT SECTION */}
<div className="bg-white border-[3px] border-black p-4 md:p-8 hard-shadow mb-8 relative dark:bg-zinc-800 dark:border-white dark:text-white">
<div className={clsx("absolute -top-3 left-6 px-2 py-0.5 font-bold text-xs uppercase -rotate-2 border border-black hard-shadow-sm", getActiveTabColor())}>
{activeTab === 'RATER' && "Input Zone"}
{activeTab === 'BOT_HUNTER' && "Target Acquisition"}
{activeTab === 'VIDEO_CHAT' && "Private Theater"}
{activeTab === 'DIRTY_TESTER' && "Mind Cleaner"}
{activeTab === 'X_RATER' && "Based Dept."}
</div>
<div className="flex flex-col gap-4">
{activeTab === 'RATER' && (
<>
<div className="flex flex-col md:flex-row gap-3">
<div className="flex-1 relative">
<input
type="text"
value={url}
onChange={handleUrlChange}