Spaces:
Running
Running
Download youtube.html from Aichatbot12321/Transaltor: direct link, hf CLI and curl.
- Browser
- Download file 96 kB
-
https://huggingface.co/spaces/Aichatbot12321/Transaltor/resolve/main/youtube.html
- Command line
-
hf download hf://spaces/Aichatbot12321/Transaltor/youtube.html
-
curl -L -o youtube.html https://huggingface.co/spaces/Aichatbot12321/Transaltor/resolve/main/youtube.html
96 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
<title>YOUTUBE SEARCH - AI PRO SUITE</title>
<!-- Core Dependencies -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/localforage/1.10.0/localforage.min.js"></script>
<script src="https://www.youtube.com/iframe_api"></script>
<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Quicksand:wght@400;600;700&display=swap');
* {
box-sizing: border-box;
-webkit-touch-callout: none; /* KILLS THE IOS POPUP MENU */
}
body { font-family: 'Quicksand', sans-serif; margin: 0; padding: 0; background-color: #f0f8ff; color: #2c3e50; min-height: 100vh; overflow-x: hidden; }
/* SCALING TOP BAR */
.top-bar { position: sticky; top: 0; z-index: 100; background: #fff; padding: clamp(8px, 2vw, 15px) clamp(10px, 3vw, 20px); box-shadow: 0 2px 10px rgba(0,0,0,0.08); display: flex; gap: clamp(5px, 2vw, 10px); align-items: center; width: 100%; }
.hamburger { background: none; border: none; font-size: clamp(20px, 5vw, 26px); cursor: pointer; color: #0277bd; padding: 0 5px; flex-shrink: 0; transition: transform 0.2s; }
.hamburger:active { transform: scale(0.9); }
/* SEARCH & SUGGESTIONS */
.search-wrapper { flex-grow: 1; position: relative; display: flex; align-items: center; background: #fff; border: 2px solid #b3e5fc; border-radius: 20px; padding-right: 10px; min-width: 0; transition: border-color 0.3s; }
.search-wrapper:focus-within { border-color: #039be5; box-shadow: 0 0 8px rgba(3, 155, 229, 0.2); }
input[type="text"] { flex-grow: 1; padding: clamp(8px, 2vw, 12px) clamp(10px, 3vw, 15px); border: none; background: transparent; font-size: clamp(14px, 3.5vw, 16px); outline: none; font-family: 'Quicksand'; min-width: 0; width: 100%; user-select: text; -webkit-user-select: text; }
.mic-btn { background: none; border: none; cursor: pointer; font-size: clamp(16px, 4vw, 20px); color: #0277bd; display: flex; align-items: center; justify-content: center; padding: 5px; flex-shrink: 0; transition: transform 0.2s; }
.mic-btn:hover { color: #e53935; transform: scale(1.1); }
.search-dropdown { display: none; position: absolute; top: 100%; left: 0; right: 0; background: white; border-radius: 15px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); margin-top: 5px; max-height: 300px; overflow-y: auto; z-index: 101; border: 1px solid #e1f5fe; }
.suggestion-item { display: flex; justify-content: space-between; align-items: center; padding: 10px 15px; cursor: pointer; border-bottom: 1px solid #f0f8ff; transition: background 0.2s; font-size: clamp(13px, 3vw, 15px); }
.suggestion-item:hover { background: #e1f5fe; }
.suggestion-text { flex-grow: 1; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: flex; gap: 10px; align-items: center; }
.suggestion-del { color: #90a4ae; background: none; border: none; font-size: 16px; padding: 5px; cursor: pointer; }
.suggestion-del:hover { color: #e53935; }
/* BUTTONS */
.btn-action { padding: clamp(8px, 2vw, 12px) clamp(10px, 3vw, 20px); font-size: clamp(12px, 3vw, 15px); font-weight: 700; background: #039be5; color: white; border: none; border-radius: 20px; cursor: pointer; transition: all 0.2s ease; white-space: nowrap; text-align: center; flex-shrink: 0; box-shadow: 0 2px 5px rgba(3, 155, 229, 0.3); }
.btn-action:hover { background: #0277bd; transform: translateY(-2px); box-shadow: 0 4px 8px rgba(3, 155, 229, 0.4); }
.btn-action:active { transform: translateY(0) scale(0.95); }
/* FILTER CHIPS */
.filter-container { display: flex; gap: clamp(5px, 2vw, 10px); padding: 10px 15px; background: #e1f5fe; justify-content: center; flex-wrap: wrap; }
.filter-chip { background: white; border: 2px solid #81d4fa; color: #0277bd; padding: 6px clamp(10px, 3vw, 15px); border-radius: 20px; font-weight: 600; font-size: clamp(12px, 3vw, 14px); cursor: pointer; transition: 0.2s; font-family: 'Quicksand'; }
.filter-chip.active { background: #0277bd; color: white; border-color: #0277bd; box-shadow: 0 2px 8px rgba(2, 119, 189, 0.4); }
/* FLOATING DRAWER */
.drawer-overlay { display: none; position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background: rgba(0,0,0,0.5); z-index: 1000; backdrop-filter: blur(2px); animation: fadeIn 0.3s ease forwards; }
.drawer { position: fixed; top: 0; left: -100%; width: clamp(240px, 70vw, 300px); height: 100vh; background: #0277bd; color: white; padding: 20px 10px; box-shadow: 4px 0 15px rgba(0,0,0,0.2); transition: left 0.3s cubic-bezier(0.4, 0, 0.2, 1); z-index: 1001; overflow-y: auto; display: flex; flex-direction: column; gap: 8px; }
.drawer.active { left: 0; }
.drawer-header { display: flex; justify-content: space-between; align-items: center; padding: 0 10px 15px 10px; }
.drawer h3 { margin: 0; font-weight: 700; letter-spacing: 1px; font-size: clamp(16px, 4vw, 20px); }
.close-drawer { font-size: 24px; cursor: pointer; background: none; border: none; color: white; transition: transform 0.2s; }
.close-drawer:hover { transform: rotate(90deg); }
.menu-btn { width: 100%; text-align: left; padding: 12px 15px; background: rgba(255,255,255,0.15); border: none; border-radius: 10px; color: white; font-weight: 700; font-family: 'Quicksand'; cursor: pointer; transition: 0.2s; display: flex; align-items: center; gap: 10px; font-size: clamp(14px, 3.5vw, 16px); }
.menu-btn:hover { background: rgba(255,255,255,0.25); transform: translateX(5px); }
.menu-link { display: flex; align-items: center; gap: 10px; text-decoration: none; padding: 10px 15px; color: rgba(255,255,255,0.8); border-radius: 10px; transition: 0.2s; font-weight: 600; font-size: clamp(13px, 3vw, 15px); }
.menu-link:hover { background: rgba(255,255,255,0.1); color: white; padding-left: 20px; }
.menu-divider { border-top: 1px solid rgba(255,255,255,0.2); margin: 10px 5px; }
/* WORKSPACE & LIST ITEMS */
.workspace { padding: clamp(10px, 2vw, 20px); width: 100%; max-width: 1000px; margin: 0 auto; }
#selection-bar { display: none; background: #ab47bc; color: white; padding: 10px clamp(10px, 3vw, 20px); border-radius: 20px; margin-bottom: 15px; text-align: center; font-weight: bold; position: sticky; top: 65px; z-index: 99; box-shadow: 0 4px 10px rgba(0,0,0,0.2); flex-wrap: wrap; gap: 10px; justify-content: center; align-items: center; font-size: clamp(12px, 3vw, 15px); animation: slideDown 0.3s forwards; }
/* THUMBNAILS & PROGRESS BAR */
.result-item { position: relative; margin: clamp(10px, 2vw, 15px) 0; padding: clamp(10px, 2vw, 15px); border-radius: 12px; background: white; border-left: 6px solid #29b6f6; box-shadow: 0 4px 8px rgba(0,0,0,0.04); display: flex; align-items: center; gap: clamp(10px, 3vw, 15px); width: 100%; overflow: hidden; animation: slideUpFade 0.4s ease-out forwards; opacity: 0; transform: translateY(15px); transition: transform 0.2s; }
.result-item:hover { transform: translateY(-2px); box-shadow: 0 6px 12px rgba(0,0,0,0.08); }
.vid-checkbox { width: clamp(18px, 4vw, 22px); height: clamp(18px, 4vw, 22px); cursor: pointer; accent-color: #ab47bc; flex-shrink: 0; z-index: 5; }
.thumb-wrapper { position: relative; cursor: pointer; flex-shrink: 0; border-radius: 8px; overflow: hidden; background: #000; width: clamp(120px, 30vw, 160px); aspect-ratio: 16/9; }
.thumb { width: 100%; height: 100%; object-fit: cover; display: block; transition: filter 0.2s; }
.thumb-wrapper:hover .thumb { filter: brightness(0.85); }
.dur-badge { position: absolute; bottom: 5px; right: 5px; background: rgba(0,0,0,0.85); color: white; padding: 2px 6px; border-radius: 4px; font-size: clamp(10px, 2.5vw, 12px); font-weight: bold; z-index: 2; }
/* RED PROGRESS BAR */
.watch-progress-bg { position: absolute; bottom: 0; left: 0; width: 100%; height: 4px; background: rgba(255,255,255,0.3); z-index: 3; }
.watch-progress-fill { height: 100%; background: #e53935; width: 0%; transition: width 0.3s linear; }
.info-col { flex-grow: 1; min-width: 0; display: flex; flex-direction: column; justify-content: center; }
.title { font-size: clamp(14px, 3.5vw, 1.1em); font-weight: 700; cursor:pointer; color: #1a252f; margin-bottom: 5px; line-height: 1.4; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
.author { font-weight: 700; color: #0288d1; cursor: pointer; font-size: clamp(12px, 3vw, 14px); }
/* MODALS */
.modal-overlay { display: none; position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background: rgba(0,0,0,0.6); z-index: 500; backdrop-filter: blur(4px); animation: fadeIn 0.2s ease forwards; }
.modal-content { background: white; width: 96%; max-width: 800px; max-height: 90vh; margin: 5vh auto; border-radius: 20px; padding: clamp(15px, 4vw, 20px); overflow-y: auto; overflow-x: hidden; position: relative; box-shadow: 0 10px 30px rgba(0,0,0,0.3); animation: popIn 0.4s forwards; transform-origin: center; }
.close-modal { position: absolute; top: clamp(8px, 2vw, 10px); right: clamp(8px, 2vw, 10px); font-size: clamp(18px, 4vw, 22px); cursor: pointer; color: #fff; font-weight: bold; width: clamp(28px, 6vw, 32px); height: clamp(28px, 6vw, 32px); line-height: clamp(26px, 6vw, 30px); text-align: center; background: #e53935; border-radius: 50%; box-shadow: 0 2px 5px rgba(0,0,0,0.2); z-index: 10; border: 2px solid white; transition: 0.2s; }
.close-modal:hover { transform: scale(1.1) rotate(90deg); background: #d32f2f; }
.modal-header-actions { display: flex; flex-wrap: wrap; gap: clamp(5px, 2vw, 10px); margin-bottom: 15px; padding-right: clamp(30px, 8vw, 40px); align-items: center; }
.modal-header-actions .btn-action { flex: 1 1 auto; }
/* PLAYER OVERLAY & ROTATION FIX */
#player-overlay {
display: none;
position: fixed;
top: 0; left: 0; right: 0; bottom: 0;
background: #000;
z-index: 9999;
pointer-events: auto;
transition: transform 0.3s ease;
}
/* Clean Fullscreen Player Layout */
#player-menu-btn {
position: absolute;
top: clamp(10px, 3vw, 20px);
right: clamp(10px, 3vw, 20px);
color: white;
font-size: clamp(20px, 5vw, 28px);
cursor: pointer;
z-index: 10000;
background: rgba(0,0,0,0.6);
width: clamp(40px, 10vw, 48px);
height: clamp(40px, 10vw, 48px);
line-height: clamp(38px, 10vw, 46px);
text-align: center;
border-radius: 50%;
backdrop-filter: blur(5px);
border: 1px solid rgba(255,255,255,0.3);
transition: 0.2s;
user-select: none;
pointer-events: auto;
}
#player-menu-btn:hover { background: rgba(3, 155, 229, 0.8); transform: scale(1.1); }
.player-menu-dropdown {
position: absolute;
top: clamp(60px, 14vw, 75px);
right: clamp(10px, 3vw, 20px);
background: rgba(15, 23, 42, 0.95);
border: 1px solid #0288d1;
border-radius: 12px;
box-shadow: 0 10px 25px rgba(0,0,0,0.5);
z-index: 10001;
overflow: hidden;
min-width: 180px;
backdrop-filter: blur(8px);
animation: fadeIn 0.2s ease;
pointer-events: auto;
}
.player-menu-item {
padding: 12px 16px;
color: white;
font-size: 14px;
font-weight: 600;
cursor: pointer;
display: flex;
align-items: center;
gap: 10px;
transition: background 0.2s;
}
.player-menu-item:hover { background: #0277bd; }
.player-menu-item:not(:last-child) { border-bottom: 1px solid rgba(255,255,255,0.1); }
/* Force YouTube iframe to obey full dimensions and retain pointer/touch responsiveness */
#player-target, #player-overlay iframe {
position: absolute !important;
top: 0 !important;
left: 0 !important;
width: 100% !important;
height: 100% !important;
border: none !important;
margin: 0 !important;
padding: 0 !important;
max-width: none !important;
max-height: none !important;
object-fit: cover !important;
pointer-events: auto !important;
user-select: auto !important;
-webkit-user-select: auto !important;
touch-action: auto !important;
}
#custom-endscreen { display: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.9); z-index: 2050; padding: 40px 20px; overflow-y: auto; text-align: center; color: white; pointer-events: auto; }
#endscreen-grid { display: flex; flex-wrap: wrap; gap: 20px; justify-content: center; margin-top: 20px; }
.endscreen-card { width: clamp(200px, 40vw, 300px); background: #111; border-radius: 12px; overflow: hidden; cursor: pointer; transition: transform 0.2s; border: 2px solid transparent; }
.endscreen-card:hover { transform: scale(1.05); border-color: #29b6f6; }
.endscreen-card img { width: 100%; aspect-ratio: 16/9; object-fit: cover; }
.endscreen-card .title { color: white; font-size: 14px; padding: 10px; margin: 0; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
/* SETTING CARDS & SELECTS */
.setting-option-card {
display: flex;
align-items: center;
gap: 12px;
background: #f0f8ff;
border: 2px solid #b3e5fc;
padding: 12px 15px;
border-radius: 12px;
cursor: pointer;
transition: border-color 0.2s;
}
.setting-option-card:hover { border-color: #0277bd; }
.setting-option-card input[type="radio"] { width: 18px; height: 18px; accent-color: #0277bd; }
.setting-select {
width: 100%;
padding: 10px 12px;
border-radius: 10px;
border: 2px solid #b3e5fc;
outline: none;
font-family: 'Quicksand';
font-weight: 600;
color: #0277bd;
background: white;
cursor: pointer;
}
.setting-select:focus { border-color: #0288d1; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
@keyframes slideDown { from { transform: translateY(-20px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
@keyframes slideUpFade { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
@keyframes popIn { 0% { transform: scale(0.9); opacity: 0; } 100% { transform: scale(1); opacity: 1; } }
@media (max-width: 500px) {
.result-item { flex-direction: column; align-items: flex-start; padding: 12px; }
.thumb-wrapper { width: 100%; max-width: none; }
.vid-checkbox { position: absolute; top: 15px; left: 15px; z-index: 10; background: white; border-radius: 4px; box-shadow: 0 2px 5px rgba(0,0,0,0.3); transform: scale(1.2); }
}
</style>
</head>
<body>
<div class="top-bar">
<button class="hamburger" onclick="toggleDrawer()">☰</button>
<div class="search-wrapper">
<input type="text" id="searchInput" placeholder="Search or paste link..." autocomplete="off">
<button class="mic-btn" onclick="toggleVoiceSearch()" title="Voice Search">🎤</button>
<div class="search-dropdown" id="searchDropdown"></div>
</div>
<button class="btn-action" onclick="executeSearch(false)">Search</button>
<button class="btn-action" style="background:#5c6bc0; padding: clamp(8px, 2vw, 12px);" onclick="openHomepageSettings()" title="Settings">⚙</button>
</div>
<div class="filter-container">
<button class="filter-chip active" onclick="setSearchFilter('all', this)">All</button>
<button class="filter-chip" onclick="setSearchFilter('video', this)">Videos</button>
<button class="filter-chip" onclick="setSearchFilter('playlist', this)">Playlists</button>
</div>
<div id="drawer-overlay" class="drawer-overlay" onclick="toggleDrawer()"></div>
<div class="drawer" id="app-drawer" style="overflow-y:auto;">
<div class="drawer-header">
<h3>✦ STUDIO</h3>
<button class="close-drawer" onclick="toggleDrawer()">✖</button>
</div>
<button class="menu-btn" onclick="openModal('playlist-modal'); loadCustomPlaylists(); toggleDrawer();"><span>📁</span> My Playlists</button>
<button class="menu-btn" onclick="openModal('history-modal'); loadHistory(); toggleDrawer();" style="background: rgba(38, 166, 154, 0.4);"><span>🕒</span> Watch History</button>
<button class="menu-btn" onclick="openHomepageSettings(); toggleDrawer();" style="background: rgba(156, 39, 176, 0.4);"><span>⚙</span> Homepage</button>
<div class="menu-divider"></div>
<h4 style="margin: 5px 15px; color: #81d4fa;">Apps & Tools</h4>
<a href="index.html" class="menu-link">🏠 Dashboard</a>
<a href="lens.html" class="menu-link">✨ Lens Studio</a>
<a href="books.html" class="menu-link">📚 Book Deep Study</a>
<a href="maths.html" class="menu-link">🧮 Math Solver</a>
<a href="search.html" class="menu-link">🔎 Deep Search</a>
<a href="downloader.html" class="menu-link">📥 Video Downloader</a>
<a href="board.html" class="menu-link">📋 Whiteboard</a>
<a href="clone.html" class="menu-link">📑 Website Cloner</a>
<a href="runhtml.html" class="menu-link">🌐 Write HTML</a>
<a href="managequiz.html" class="menu-link">⚙️ Manage Quiz</a>
<a href="tutor.html" class="menu-link">👨🏫 AI Tutor</a>
<a href="quiz.html" class="menu-link">📝 Take a Quiz!</a>
<a href="book_quiz.html" class="menu-link">📝 Take a Book Quiz!</a>
<a href="tables.html" class="menu-link">🔢 Maths Table</a>
<a href="coding.html" class="menu-link">💻 AI Coding</a>
<a href="chess.html" class="menu-link">♟️ Chess AI</a>
<a href="translator.html" class="menu-link">🎙️ Text Translator</a>
<a href="image.html" class="menu-link">🖼️ Image Translator</a>
<a href="create.html" class="menu-link">🎨 Image Creator</a>
<a href="qa.html" class="menu-link">📚 Document Q&A</a>
<a href="history.html" class="menu-link">🕒 History & Downloads</a>
<a href="storage.html" class="menu-link">📂 Storage</a>
<a href="hub.html" class="menu-link">🛰️ HF Command Center</a>
<a href="live.html" class="menu-link">🗣️ Gemini Live</a>
</div>
<div class="workspace">
<div id="selection-bar">
<span id="sel-count">0</span> Items Marked
<button style="background:white; color:#ab47bc; border:none; padding:8px 16px; border-radius:20px; font-weight:bold; cursor:pointer;" onclick="initiateAddToPlaylist()">Transfer Selected</button>
</div>
<div id="results"></div>
<div id="load-more-container" style="text-align:center; padding: 20px; display:none;">
<button class="btn-action" style="background:#26a69a;" onclick="executeSearch(true)">Load Next Page</button>
</div>
</div>
<!-- MODALS -->
<div id="history-modal" class="modal-overlay">
<div class="modal-content">
<span class="close-modal" onclick="closeModal('history-modal')">✖</span>
<h3 style="color:#0277bd; margin: 0 0 15px 0;">Watch History</h3>
<div id="history-content"></div>
</div>
</div>
<div id="playlist-modal" class="modal-overlay">
<div class="modal-content">
<span class="close-modal" onclick="closeModal('playlist-modal')">✖</span>
<div class="modal-header-actions" style="margin-bottom: 20px;">
<button class="btn-action" style="background:#ab47bc;" onclick="openModal('create-playlist-modal')">+ Create New</button>
</div>
<h3 style="color:#ab47bc; margin: 0 0 15px 0;">Playlist Registry</h3>
<div id="playlist-list"></div>
<div id="playlist-view" style="display:none; border-top: 2px solid #eee; padding-top:15px;"></div>
</div>
</div>
<div id="create-playlist-modal" class="modal-overlay" style="z-index: 600;">
<div class="modal-content" style="max-width: 400px; text-align:center;">
<span class="close-modal" onclick="closeModal('create-playlist-modal')">✖</span>
<h3 style="margin-top:0;">Assign Name</h3>
<input type="text" id="newPlaylistName" style="width:100%; padding:12px; margin-bottom:15px; border-radius:10px; border:2px solid #ccc; outline:none;"><br>
<button class="btn-action" style="width:100%;" onclick="createNewPlaylist()">Done</button>
</div>
</div>
<div id="add-to-gui-modal" class="modal-overlay" style="z-index: 550;">
<div class="modal-content" style="text-align:center; max-width: 500px;">
<span class="close-modal" onclick="closeModal('add-to-gui-modal')">✖</span>
<div class="modal-header-actions" style="justify-content: center; padding: 0;">
<button class="btn-action" style="background:#ab47bc; width: 100%;" onclick="openModal('create-playlist-modal')">+ Create New Playlist</button>
</div>
<h3 style="margin:10px 0;">Destination Target</h3>
<div id="add-to-gui-content"></div>
</div>
</div>
<div id="history-action-modal" class="modal-overlay" style="z-index: 2500;">
<div class="modal-content" style="max-width: 400px; text-align: center;">
<span class="close-modal" onclick="closeModal('history-action-modal')">✖</span>
<h3 style="color:#ab47bc; margin-top:0;">History Options</h3>
<div id="history-action-details" style="margin-bottom: 20px;"></div>
<button class="btn-action" style="width:100%; background:#26a69a; margin-bottom:10px;" onclick="transferHistoryItem()">📁 Transfer to Playlist</button>
<button class="btn-action" style="width:100%; background:#e53935;" onclick="deleteHistoryItem()">🗑️ Delete from History</button>
</div>
</div>
<div id="yt-playlist-modal" class="modal-overlay">
<div class="modal-content">
<span class="close-modal" onclick="closeModal('yt-playlist-modal')">✖</span>
<div class="modal-header-actions">
<button class="btn-action" style="background:#26a69a;" onclick="playYTPlaylistMode(true)">Play All</button>
<button class="btn-action" style="background:#ffca28; color:#333;" onclick="toggleSelectAllYTPlaylist()">☑ Select All</button>
<button class="btn-action" style="background:#26a69a;" onclick="playYTPlaylistMode(false)">Play Selected</button>
<button class="btn-action" style="background:#ab47bc;" onclick="initiateAddToPlaylist()">Transfer Selected</button>
</div>
<h3 id="yt-playlist-title" style="color:#ab47bc; margin:0 0 15px 0;">YouTube Playlist</h3>
<div id="yt-playlist-content"></div>
</div>
</div>
<!-- HOMEPAGE & VIDEO SETTINGS MODAL -->
<div id="homepage-settings-modal" class="modal-overlay" style="z-index: 2600;">
<div class="modal-content" style="max-width: 480px;">
<span class="close-modal" onclick="closeModal('homepage-settings-modal')">✖</span>
<h3 style="color:#0277bd; margin-top:0;">⚙ Homepage & Video Settings</h3>
<h4 style="color:#0288d1; margin: 15px 0 10px 0; border-bottom: 1px solid #e1f5fe; padding-bottom: 5px;">🏠 Default Homepage View</h4>
<div style="display: flex; flex-direction: column; gap: 10px; margin-bottom: 20px;">
<label class="setting-option-card">
<input type="radio" name="hp_pref" value="recommended" id="hp_pref_rec">
<div>
<strong style="color:#0277bd;">✨ Recommended Videos</strong>
<div style="font-size:12px; color:#666;">Load personalized recommendations based on recent watch history</div>
</div>
</label>
<label class="setting-option-card">
<input type="radio" name="hp_pref" value="history" id="hp_pref_hist">
<div>
<strong style="color:#26a69a;">🕒 Watch History</strong>
<div style="font-size:12px; color:#666;">Display your recent watch history directly on homepage</div>
</div>
</label>
<label class="setting-option-card">
<input type="radio" name="hp_pref" value="playlist" id="hp_pref_pl">
<div>
<strong style="color:#ab47bc;">📁 My Playlists</strong>
<div style="font-size:12px; color:#666;">Display your custom playlist registry directly on homepage</div>
</div>
</label>
</div>
<h4 style="color:#0288d1; margin: 15px 0 10px 0; border-bottom: 1px solid #e1f5fe; padding-bottom: 5px;">🎬 Video Playback Settings</h4>
<div style="display: flex; flex-direction: column; gap: 12px; margin-bottom: 20px;">
<div>
<label style="font-weight: bold; font-size: 13px; color: #37474f; display: block; margin-bottom: 5px;">Default Video Orientation:</label>
<select id="setting_orientation" class="setting-select">
<option value="landscape">Landscape (Default)</option>
<option value="portrait">Portrait</option>
</select>
</div>
<div>
<label style="font-weight: bold; font-size: 13px; color: #37474f; display: block; margin-bottom: 5px;">Orientation Toggle Sequence Count (On Video Open):</label>
<select id="setting_rotation_count" class="setting-select">
<option value="1">1 Time (Default - Locks once)</option>
<option value="2">2 Times (Switches then switches back)</option>
<option value="3">3 Times</option>
</select>
</div>
<div>
<label style="font-weight: bold; font-size: 13px; color: #37474f; display: block; margin-bottom: 5px;">Player Button Mode (Top-Right):</label>
<select id="setting_button_mode" class="setting-select">
<option value="menu">Menu (Default - 3 dots menu)</option>
<option value="close">Close Player (Shows X to close directly)</option>
</select>
</div>
</div>
<button class="btn-action" style="width: 100%; margin-top: 10px;" onclick="saveHomepageSettings()">Save Settings</button>
</div>
</div>
<!-- PLAYER WITH CUSTOM ENDSCREEN & MENU -->
<div id="player-overlay" onclick="syncPlayerOrientation();">
<div id="player-menu-btn" onclick="togglePlayerMenu(event)" title="Player Options">⋮</div>
<div id="player-dropdown-menu" class="player-menu-dropdown" style="display:none;">
<div class="player-menu-item" onclick="closePlayer(); hidePlayerMenu();">
<span>✖</span> Close Player
</div>
<div class="player-menu-item" onclick="toggleOrientation(); hidePlayerMenu();">
<span>🔄</span> Change Orientation
</div>
</div>
<div id="player-target"></div>
<div id="custom-endscreen">
<h2 style="margin: 0; color: #29b6f6;">Up Next</h2>
<p>Keep the momentum going with these picks:</p>
<div id="endscreen-grid"></div>
<button class="btn-action" style="margin-top: 30px; background: #666;" onclick="closePlayer()">Close Player</button>
</div>
</div>
<script>
localforage.config({ driver: localforage.INDEXEDDB, name: 'CoolBreezeStorage', storeName: 'app_data_registry' });
// --- SUPABASE CONFIGURATION ---
const SUPABASE_URL = "https://twxdmzkwrntwipnambko.supabase.co";
const SUPABASE_ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InR3eGRtemt3cm50d2lwbmFtYmtvIiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODQ0MDU1MDQsImV4cCI6MjA5OTk4MTUwNH0.mBbsr6fstbffXL00x8z92qEMSm_rPF60tGEx97NNtnw";
let supabaseClient = null;
try { supabaseClient = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY); } catch(e) { console.error("Supabase Init Error:", e); }
let ytPlayer = null;
let saveInterval = null;
let currentVideoData = {};
let selectedVideos = [];
let currentSearchQuery = "";
let nextPageToken = "";
let currentFilter = 'all';
let cachedDurations = {};
// Format raw seconds to MM:SS or HH:MM:SS
function formatSecs(secs) {
if(!secs || isNaN(secs)) return "0:00";
const h = Math.floor(secs / 3600); const m = Math.floor((secs % 3600) / 60); const s = Math.floor(secs % 60);
if(h>0) return `${h}:${m.toString().padStart(2,'0')}:${s.toString().padStart(2,'0')}`;
return `${m}:${s.toString().padStart(2,'0')}`;
}
function toggleDrawer() { const d = document.getElementById('app-drawer'); const o = document.getElementById('drawer-overlay'); d.classList.toggle('active'); o.style.display = d.classList.contains('active') ? 'block' : 'none'; }
function openModal(id) { document.getElementById(id).style.display = 'block'; }
function closeModal(id) { document.getElementById(id).style.display = 'none'; }
window.onclick = function(event) { if (event.target.classList.contains('modal-overlay')) event.target.style.display = "none"; }
function setSearchFilter(type, btnElement) {
currentFilter = type; document.querySelectorAll('.filter-chip').forEach(b => b.classList.remove('active')); btnElement.classList.add('active');
document.querySelectorAll('#results .result-item').forEach(item => { item.style.display = (currentFilter === 'all' || currentFilter === item.getAttribute('data-type')) ? 'flex' : 'none'; });
}
// --- WATCH HISTORY MAP HELPER FOR PROGRESS DISPLAY ---
async function getHistoryMap() {
let histObj = {};
if (supabaseClient) {
try {
const { data, error } = await supabaseClient.from('watch_history').select('*');
if (!error && data) {
data.forEach(row => {
histObj[row.id] = {
id: row.id,
title: row.title,
thumb: row.thumb,
author: row.author,
timeWatched: row.time_watched,
total_secs: row.total_secs,
lastWatched: row.last_watched
};
});
}
} catch(e) {}
}
if (Object.keys(histObj).length === 0) {
histObj = await localforage.getItem('watch_history') || {};
}
return histObj;
}
// --- HOMEPAGE & VIDEO PLAYBACK SETTINGS ---
function getVideoSettings() {
try {
const saved = localStorage.getItem('yt_video_settings');
if (saved) return JSON.parse(saved);
} catch(e) {}
return {
orientation: 'landscape',
rotationCount: 1,
buttonMode: 'menu'
};
}
function saveVideoSettings(settings) {
localStorage.setItem('yt_video_settings', JSON.stringify(settings));
}
function openHomepageSettings() {
const pref = localStorage.getItem('yt_homepage_pref') || 'recommended';
if (pref === 'history') document.getElementById('hp_pref_hist').checked = true;
else if (pref === 'playlist') document.getElementById('hp_pref_pl').checked = true;
else document.getElementById('hp_pref_rec').checked = true;
const vSettings = getVideoSettings();
document.getElementById('setting_orientation').value = vSettings.orientation || 'landscape';
document.getElementById('setting_rotation_count').value = vSettings.rotationCount || 1;
document.getElementById('setting_button_mode').value = vSettings.buttonMode || 'menu';
openModal('homepage-settings-modal');
}
function saveHomepageSettings() {
const selectedHp = document.querySelector('input[name="hp_pref"]:checked')?.value || 'recommended';
localStorage.setItem('yt_homepage_pref', selectedHp);
const vSettings = {
orientation: document.getElementById('setting_orientation').value || 'landscape',
rotationCount: parseInt(document.getElementById('setting_rotation_count').value) || 1,
buttonMode: document.getElementById('setting_button_mode').value || 'menu'
};
saveVideoSettings(vSettings);
closeModal('homepage-settings-modal');
// FIX: Only reload homepage if user is not actively viewing a search result!
if (!currentSearchQuery) {
loadDefaultHomepageContent();
}
}
function loadDefaultHomepageContent() {
const pref = localStorage.getItem('yt_homepage_pref') || 'recommended';
if (pref === 'history') {
loadHistoryToMainWorkspace();
} else if (pref === 'playlist') {
loadCustomPlaylistsToMainWorkspace();
} else {
loadPersonalizedHomeFeed();
}
}
async function loadHistoryToMainWorkspace() {
const resultsDiv = document.getElementById('results');
resultsDiv.innerHTML = "<h3 style='text-align: center; color: #26a69a;'>Loading Watch History...</h3>";
let histObj = await getHistoryMap();
let keys = Object.keys(histObj);
resultsDiv.innerHTML = "<h3 style='color:#26a69a; margin-bottom: 15px;'>🕒 Your Watch History</h3>";
if(keys.length === 0) { resultsDiv.innerHTML += "<p style='color:#94a3b8;'>History is empty.</p>"; return; }
let animDelay = 0;
keys.sort((a,b) => new Date(histObj[b].lastWatched) - new Date(histObj[a].lastWatched)).forEach(key => {
let val = histObj[key]; const safeData = encodeURIComponent(JSON.stringify(val));
let pct = 0;
if(val.total_secs && val.total_secs > 0) { pct = Math.min(100, Math.max(0, (val.timeWatched / val.total_secs) * 100)); }
let progressHtml = `<div class="watch-progress-bg"><div class="watch-progress-fill" style="width: ${pct}%;"></div></div>`;
let timeFmt = val.total_secs ? formatSecs(val.total_secs) : val.duration || '';
resultsDiv.innerHTML += `
<div id="hist-item-${val.id}" class="result-item" style="padding:10px; animation-delay: ${animDelay}s; position: relative;"
onpointerdown="startHistoryPress(event, '${safeData}')"
onpointerup="cancelHistoryPress()"
onpointerleave="cancelHistoryPress()"
onpointercancel="cancelHistoryPress()">
<div class="thumb-wrapper" onclick="handleHistoryClick(event, '${safeData}')">
<img class="thumb" src="${val.thumb}">
${progressHtml}
<div class="dur-badge" style="z-index:4;">${timeFmt}</div>
</div>
<div class="info-col" onclick="handleHistoryClick(event, '${safeData}')" style="padding-right: 40px;">
<div class="title">${val.title}</div>
<div class="hist-time-text" style="font-size:0.8em; color:#e53935; font-weight:bold; margin-top:4px;">▶ Watched: ${formatSecs(val.timeWatched)} / ${formatSecs(val.total_secs || 0)}</div>
</div>
<button onclick="openHistoryOptions('${safeData}')" style="position: absolute; right: 5px; top: 50%; transform: translateY(-50%); background: transparent; border: none; font-size: 24px; color: #b0bec5; cursor: pointer; padding: 15px 10px; z-index: 10;">⋮</button>
</div>`;
animDelay += 0.05;
});
}
async function loadCustomPlaylistsToMainWorkspace() {
let p = await getPlaylists(); const resultsDiv = document.getElementById('results');
resultsDiv.innerHTML = "<h3 style='color:#ab47bc; margin-bottom: 15px;'>📁 Playlist Registry</h3>";
let keys = Object.keys(p); if(keys.length === 0) { resultsDiv.innerHTML += "<p style='color:#94a3b8;'>No playlists created yet.</p>"; return; }
keys.forEach(key => {
let coverImg = p[key].length > 0 ? p[key][0].thumb : 'data:image/svg+xml;charset=UTF-8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="160" height="90" viewBox="0 0 160 90"%3E%3Crect fill="%23e1f5fe" width="160" height="90"/%3E%3Ctext fill="%230277bd" font-family="sans-serif" font-size="14" dy="4.5" font-weight="bold" x="50%25" y="50%25" text-anchor="middle"%3EEmpty%3C/text%3E%3C/svg%3E';
resultsDiv.innerHTML += `
<div style="background:#f3e5f5; padding:15px; margin-bottom:10px; border-radius:10px; cursor:pointer; display:flex; align-items:center; animation: popIn 0.3s forwards;" onclick="openModal('playlist-modal'); viewPlaylistContents('${key.replace(/'/g, "\\'")}')">
<div class="thumb-wrapper" style="width: clamp(80px, 25vw, 120px); margin-right:15px;"><img class="thumb" src="${coverImg}"></div>
<div><div style="font-size:1.1em; font-weight:bold; color:#ab47bc; margin-bottom:5px;">${key}</div><div style="color:#666; font-size:0.9em;">${p[key].length} Items</div></div>
</div>`;
});
}
// --- AI AUTOCOMPLETE SUGGESTIONS (GROQ /api/groq-search ENDPOINT) ---
const searchInput = document.getElementById('searchInput');
const searchDropdown = document.getElementById('searchDropdown');
let suggestionTimeout;
async function fetchAiSuggestions(query) {
if (!query || query.length < 3) return []; // Save quota on short queries!
try {
const res = await fetch('/api/groq-search', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userPrompt: `Generate 5 to 8 short YouTube search autocomplete suggestions related to: '${query}'. Output ONLY a comma-separated list, nothing else.` })
});
const data = await res.json();
if(data && data.text) return data.text.split(',').map(s => s.trim()).filter(s => s);
} catch(e) { return []; }
return [];
}
function renderSuggestions(val, aiSugs = [], isLoading = false) {
if(!val) { searchDropdown.style.display = 'none'; return; }
let localHist = JSON.parse(localStorage.getItem('yt_search_history') || '[]').filter(q => q.toLowerCase().includes(val.toLowerCase()));
let combined = [...new Set([...localHist, ...aiSugs])].slice(0, 10);
searchDropdown.innerHTML = '';
if(combined.length === 0 && !isLoading) { searchDropdown.style.display = 'none'; return; }
combined.forEach(q => {
const isLocal = localHist.includes(q);
searchDropdown.innerHTML += `
<div class="suggestion-item">
<div class="suggestion-text" onclick="searchInput.value='${q.replace(/'/g,"\\")}'; searchDropdown.style.display='none'; executeSearch(false);">
${isLocal ? '🕒' : '✨'} ${q}
</div>
${isLocal ? `<button class="suggestion-del" onclick="deleteSearchItem('${q.replace(/'/g,"\\")}')">✖</button>` : ''}
</div>`;
});
if (isLoading) {
searchDropdown.innerHTML += `<div style="padding:10px 15px; text-align:center; color:#0277bd; font-weight:bold; font-size:13px;">⏳ Loading suggestions...</div>`;
}
searchDropdown.style.display = 'block';
}
function onSearchInput() {
const val = searchInput.value.trim();
if(!val) { searchDropdown.style.display = 'none'; return; }
// Instantly render local search history (0 quota used!)
renderSuggestions(val, [], false);
clearTimeout(suggestionTimeout);
// Don't call AI for less than 3 characters
if (val.length < 3) return;
// 800ms debounce: waits until you stop typing so it only sends 1 request to Groq!
suggestionTimeout = setTimeout(async () => {
renderSuggestions(val, [], true);
const aiSugs = await fetchAiSuggestions(val);
renderSuggestions(val, aiSugs, false);
}, 800);
}
searchInput.addEventListener('input', onSearchInput);
searchInput.addEventListener('focus', () => { if(searchInput.value.trim()) onSearchInput(); });
document.addEventListener('click', (e) => { if(!e.target.closest('.search-wrapper')) searchDropdown.style.display = 'none'; });
function saveSearchToHistory(query) {
let hist = JSON.parse(localStorage.getItem('yt_search_history') || '[]');
hist = hist.filter(q => q.toLowerCase() !== query.toLowerCase());
hist.unshift(query);
if(hist.length > 20) hist.pop();
localStorage.setItem('yt_search_history', JSON.stringify(hist));
}
function deleteSearchItem(query) {
let hist = JSON.parse(localStorage.getItem('yt_search_history') || '[]');
hist = hist.filter(q => q !== query);
localStorage.setItem('yt_search_history', JSON.stringify(hist));
onSearchInput();
}
async function executeSearch(isLoadMore = false) {
const query = searchInput.value.trim();
if(!query) return;
const ytRegex = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/i;
const match = query.match(ytRegex);
if (match && match && !isLoadMore) {
const videoId = match;
const mockData = encodeURIComponent(JSON.stringify({
id: videoId,
type: 'video',
title: 'Loading video...',
thumb: `https://i.ytimg.com/vi/${videoId}/hqdefault.jpg`,
author: 'YouTube',
duration: ''
}));
searchDropdown.style.display = 'none';
playVid(mockData);
fetch(`https://noembed.com/embed?url=https://www.youtube.com/watch?v=${videoId}`)
.then(res => res.json())
.then(meta => {
if (meta.title) {
currentVideoData.title = meta.title;
if (meta.author_name) currentVideoData.author = meta.author_name;
}
}).catch(e => {});
return;
}
searchDropdown.style.display = 'none';
if(!isLoadMore) { saveSearchToHistory(query); selectedVideos = []; updateSelectionBar(); currentSearchQuery = query; nextPageToken = ""; document.getElementById('results').innerHTML = "<h3>Querying Server...</h3>"; }
document.getElementById('load-more-container').style.display = 'none';
try {
const res = await fetch('/api/youtube-search', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ q: currentSearchQuery, token: nextPageToken }) });
const data = await res.json();
const resultsDiv = document.getElementById('results');
if(!isLoadMore) resultsDiv.innerHTML = "";
if (!data.items || data.items.length === 0) { if(!isLoadMore) resultsDiv.innerHTML = "<h3>No results found.</h3>"; return; }
let histMap = await getHistoryMap();
let animDelay = 0;
data.items.forEach(item => {
if(item.total_secs) cachedDurations[item.id] = item.total_secs;
const safeData = encodeURIComponent(JSON.stringify(item));
const isVid = item.type === 'video';
const clickAction = isVid ? `playVid('${safeData}')` : `openYoutubePlaylist('${item.id}', '${item.title.replace(/'/g, "\\'")}')`;
let hist = histMap[item.id];
let pct = 0;
let progressHtml = '';
let resumeText = '';
if (hist && hist.timeWatched && hist.timeWatched > 0) {
const totalSecs = hist.total_secs || item.total_secs || 1;
pct = Math.min(100, Math.max(0, (hist.timeWatched / totalSecs) * 100));
progressHtml = `<div class="watch-progress-bg"><div class="watch-progress-fill" style="width: ${pct}%;"></div></div>`;
resumeText = `<div class="hist-time-text" style="font-size:0.8em; color:#e53935; font-weight:bold; margin-top:4px;">▶ Watched: ${formatSecs(hist.timeWatched)} / ${formatSecs(totalSecs)}</div>`;
}
resultsDiv.innerHTML += `
<div class="result-item" data-type="${item.type}" style="border-left-color: ${isVid ? '#29b6f6' : '#ab47bc'}; animation-delay: ${animDelay}s;">
<input type="checkbox" class="vid-checkbox" onchange="toggleSelect(this, '${safeData}')">
<div class="thumb-wrapper" onclick="${clickAction}">
<img class="thumb" src="${item.thumb}">
${progressHtml}
${isVid ? `<div class="dur-badge">${item.duration}</div>` : `<div class="dur-badge">PLAYLIST</div>`}
</div>
<div class="info-col">
<div class="title" onclick="${clickAction}">${isVid ? '' : '🔀 '}${item.title}</div>
<div style="color: #546e7a; font-size: clamp(12px, 3vw, 0.9em); margin-top:5px;">By <span class="author">${item.author}</span></div>
${resumeText}
</div>
</div>`;
animDelay += 0.05;
});
document.querySelectorAll('#results .result-item').forEach(item => { item.style.display = (currentFilter === 'all' || currentFilter === item.getAttribute('data-type')) ? 'flex' : 'none'; });
nextPageToken = data.nextPageToken; document.getElementById('load-more-container').style.display = nextPageToken ? 'block' : 'none';
} catch(e) { document.getElementById('results').innerHTML = `<h3 style="color:red;">Error connecting to Server API.</h3>`; }
}
function toggleSelect(checkbox, safeData) { const data = JSON.parse(decodeURIComponent(safeData)); if(checkbox.checked) { selectedVideos.push(data); } else { selectedVideos = selectedVideos.filter(v => v.id !== data.id); } updateSelectionBar(); }
function updateSelectionBar() { const bar = document.getElementById('selection-bar'); if(selectedVideos.length > 0) { bar.style.display = 'flex'; document.getElementById('sel-count').innerText = selectedVideos.length; } else { bar.style.display = 'none'; } }
// --- YOUTUBE PLAYLIST LOGIC ---
let currentYTPlaylistVids = []; let ytSelectAllState = false;
async function openYoutubePlaylist(pid, title) {
if(!pid) return; openModal('yt-playlist-modal'); document.getElementById('yt-playlist-title').innerText = title;
const contentDiv = document.getElementById('yt-playlist-content'); contentDiv.innerHTML = "<p>Loading elements...</p>";
currentYTPlaylistVids = []; ytSelectAllState = false;
try {
const res = await fetch(`/api/youtube-playlist-items?id=${pid}`); const data = await res.json();
contentDiv.innerHTML = "";
if(!data.videos || data.videos.length === 0) { contentDiv.innerHTML = "<p>Private or Empty Array.</p>"; return; }
currentYTPlaylistVids = data.videos;
let histMap = await getHistoryMap();
let animDelay = 0;
data.videos.forEach((item, index) => {
let hist = histMap[item.id];
let pct = 0;
let progressHtml = '';
let resumeText = '';
if (hist && hist.timeWatched && hist.timeWatched > 0) {
item.timeWatched = hist.timeWatched;
item.total_secs = hist.total_secs || item.total_secs || 1;
pct = Math.min(100, Math.max(0, (hist.timeWatched / item.total_secs) * 100));
progressHtml = `<div class="watch-progress-bg"><div class="watch-progress-fill" style="width: ${pct}%;"></div></div>`;
resumeText = `<div class="hist-time-text" style="font-size:0.8em; color:#e53935; font-weight:bold; margin-top:4px;">▶ Watched: ${formatSecs(hist.timeWatched)} / ${formatSecs(item.total_secs)}</div>`;
}
const safeData = encodeURIComponent(JSON.stringify(item));
contentDiv.innerHTML += `
<div id="yt-pl-item-${item.id}" class="result-item" style="border-left-color: #29b6f6; animation-delay: ${animDelay}s;">
<input type="checkbox" class="vid-checkbox yt-pl-checkbox" data-index="${index}" onchange="toggleSelect(this, '${safeData}')">
<div class="thumb-wrapper" onclick="playVid('${safeData}')">
<img class="thumb" src="${item.thumb}">
${progressHtml}
</div>
<div class="info-col">
<div class="title" onclick="playVid('${safeData}')">${item.title}</div>
<div style="color: #546e7a; font-size: 0.9em;">By ${item.author}</div>
${resumeText}
</div>
</div>`;
animDelay += 0.05;
});
} catch(e) { contentDiv.innerHTML = "<p>Fetch Blocked.</p>"; }
}
function toggleSelectAllYTPlaylist() {
ytSelectAllState = !ytSelectAllState;
document.querySelectorAll('.yt-pl-checkbox').forEach(cb => { if(cb.checked !== ytSelectAllState) { cb.checked = ytSelectAllState; cb.dispatchEvent(new Event('change')); } });
}
function playYTPlaylistMode(playAll) {
if(currentYTPlaylistVids.length === 0) return; let targetArray = [];
if(playAll) { targetArray = currentYTPlaylistVids.map(v => v.id); }
else { document.querySelectorAll('.yt-pl-checkbox').forEach(cb => { if(cb.checked) targetArray.push(currentYTPlaylistVids[cb.getAttribute('data-index')].id); }); }
if(targetArray.length === 0) { alert("Selection Empty!"); return; }
startMultiplePlayback(targetArray);
}
// --- CUSTOM PLAYLISTS ---
async function getPlaylists() {
let p = await localforage.getItem('custom_playlists') || {};
if (supabaseClient) {
try {
const { data, error } = await supabaseClient.from('custom_playlists').select('*');
if (!error && data) {
let cloudPlaylists = {};
Object.keys(p).forEach(key => { if (p[key].length === 0) cloudPlaylists[key] = []; });
data.forEach(row => {
if (!cloudPlaylists[row.playlist_name]) cloudPlaylists[row.playlist_name] = [];
cloudPlaylists[row.playlist_name].push({
id: row.video_id,
title: row.title,
thumb: row.thumb,
duration: row.duration,
type: 'video'
});
});
p = cloudPlaylists;
await localforage.setItem('custom_playlists', p);
}
} catch(e) { console.error("Cloud playlist fetch failed", e); }
}
return p;
}
async function createNewPlaylist() {
const name = document.getElementById('newPlaylistName').value.trim(); if(!name) return;
let p = await getPlaylists();
if(!p[name]) {
p[name] = [];
await localforage.setItem('custom_playlists', p);
}
document.getElementById('newPlaylistName').value = ""; closeModal('create-playlist-modal');
if(document.getElementById('add-to-gui-modal').style.display === 'block') initiateAddToPlaylist(); else loadCustomPlaylists();
}
async function initiateAddToPlaylist() {
let p = await getPlaylists(); let keys = Object.keys(p);
const content = document.getElementById('add-to-gui-content'); openModal('add-to-gui-modal');
if(keys.length === 0) { content.innerHTML = "<p>No array structures. Create one above.</p>"; }
else {
let html = "<p style='margin-bottom:15px;'>Assign to array:</p>";
keys.forEach(k => { html += `<div style="background:#f3e5f5; padding:15px; margin-bottom:10px; border-radius:10px; cursor:pointer;" onclick="saveSelectedTo('${k.replace(/'/g, "\\'")}')">📁 <b>${k}</b></div>`; });
content.innerHTML = html;
}
}
async function saveSelectedTo(playlistName) {
let p = await getPlaylists();
let rowsToInsert = [];
selectedVideos.forEach(vid => {
if(!p[playlistName].find(v => v.id === vid.id)) {
p[playlistName].push(vid);
rowsToInsert.push({
playlist_name: playlistName,
video_id: vid.id,
title: vid.title,
thumb: vid.thumb,
duration: vid.duration || ''
});
}
});
await localforage.setItem('custom_playlists', p);
if (supabaseClient && rowsToInsert.length > 0) {
try { await supabaseClient.from('custom_playlists').insert(rowsToInsert); } catch(e){}
}
selectedVideos = []; document.querySelectorAll('.vid-checkbox').forEach(cb => cb.checked = false);
updateSelectionBar(); closeModal('add-to-gui-modal'); loadCustomPlaylists();
}
async function loadCustomPlaylists() {
let p = await getPlaylists(); const listDiv = document.getElementById('playlist-list');
document.getElementById('playlist-view').style.display = 'none'; listDiv.style.display = 'block'; listDiv.innerHTML = "";
let keys = Object.keys(p); if(keys.length === 0) { listDiv.innerHTML = "<p>Empty Sector.</p>"; return; }
keys.forEach(key => {
let coverImg = p[key].length > 0 ? p[key][0].thumb : 'data:image/svg+xml;charset=UTF-8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="160" height="90" viewBox="0 0 160 90"%3E%3Crect fill="%23e1f5fe" width="160" height="90"/%3E%3Ctext fill="%230277bd" font-family="sans-serif" font-size="14" dy="4.5" font-weight="bold" x="50%25" y="50%25" text-anchor="middle"%3EEmpty%3C/text%3E%3C/svg%3E';
listDiv.innerHTML += `
<div style="background:#f3e5f5; padding:15px; margin-bottom:10px; border-radius:10px; cursor:pointer; display:flex; align-items:center; animation: popIn 0.3s forwards;" onclick="viewPlaylistContents('${key.replace(/'/g, "\\'")}')">
<div class="thumb-wrapper" style="width: clamp(80px, 25vw, 120px); margin-right:15px;"><img class="thumb" src="${coverImg}"></div>
<div><div style="font-size:1.1em; font-weight:bold; color:#ab47bc; margin-bottom:5px;">${key}</div><div style="color:#666; font-size:0.9em;">${p[key].length} Items</div></div>
</div>`;
});
}
let customSelectAllState = false;
async function viewPlaylistContents(name) {
let p = await getPlaylists(); let vids = p[name];
document.getElementById('playlist-list').style.display = 'none';
const viewDiv = document.getElementById('playlist-view'); viewDiv.style.display = 'block'; customSelectAllState = false;
let html = `
<div style="margin-bottom: 20px;">
<div style="display:flex; align-items:center; gap: 10px; margin-bottom: 15px;">
<button class="btn-action" style="background:#78909c; padding: 8px 15px;" onclick="loadCustomPlaylists()">Back</button>
<h2 style="color:#ab47bc; margin:0;">${name}</h2>
</div>
<div class="modal-header-actions" style="padding-right:0;">
<button class="btn-action" style="background:#26a69a;" onclick="playMultipleFromPlaylist('${name.replace(/'/g, "\\'")}', true)">Play Sequential</button>
<button class="btn-action" style="background:#ffca28; color:#333;" onclick="toggleSelectAllCustomPlaylist()">☑ Select All</button>
<button class="btn-action" style="background:#26a69a;" onclick="playMultipleFromPlaylist('${name.replace(/'/g, "\\'")}', false)">Play Flagged Only</button>
<button class="btn-action" style="background:#e53935;" onclick="deleteEntirePlaylist('${name.replace(/'/g, "\\'")}')">Delete Stack</button>
</div>
</div>`;
if(vids.length === 0) { html += "<p>Array empty.</p>"; }
let histMap = await getHistoryMap();
let animDelay = 0;
vids.forEach((item, index) => {
let hist = histMap[item.id];
let pct = 0;
let progressHtml = '';
let resumeText = '';
if (hist && hist.timeWatched && hist.timeWatched > 0) {
item.timeWatched = hist.timeWatched;
item.total_secs = hist.total_secs || item.total_secs || 1;
pct = Math.min(100, Math.max(0, (hist.timeWatched / item.total_secs) * 100));
progressHtml = `<div class="watch-progress-bg"><div class="watch-progress-fill" style="width: ${pct}%;"></div></div>`;
resumeText = `<div class="hist-time-text" style="font-size:0.8em; color:#e53935; font-weight:bold; margin-top:4px;">▶ Watched: ${formatSecs(hist.timeWatched)} / ${formatSecs(item.total_secs)}</div>`;
}
const safeData = encodeURIComponent(JSON.stringify(item));
html += `
<div id="custom-pl-item-${item.id}" class="result-item" style="padding:10px; animation-delay: ${animDelay}s;">
<input type="checkbox" class="vid-checkbox custom-pl-checkbox" data-index="${index}">
<div class="thumb-wrapper" onclick="playVid('${safeData}')">
<img class="thumb" src="${item.thumb}">
${progressHtml}
<div class="dur-badge">${item.duration || ''}</div>
</div>
<div class="info-col">
<div class="title" onclick="playVid('${safeData}')">${item.title}</div>
${resumeText}
</div>
<button class="btn-action" style="background:#e53935; padding: 6px 12px; flex-shrink:0;" onclick="removeFromPlaylist('${name.replace(/'/g, "\\'")}', ${index})">Rem</button>
</div>`;
animDelay += 0.05;
});
viewDiv.innerHTML = html;
}
function toggleSelectAllCustomPlaylist() { customSelectAllState = !customSelectAllState; document.querySelectorAll('.custom-pl-checkbox').forEach(cb => cb.checked = customSelectAllState); }
async function deleteEntirePlaylist(name) {
let p = await getPlaylists(); delete p[name]; await localforage.setItem('custom_playlists', p);
if (supabaseClient) {
try { await supabaseClient.from('custom_playlists').delete().eq('playlist_name', name); } catch(e){}
}
loadCustomPlaylists();
}
async function removeFromPlaylist(playlistName, index) {
let p = await getPlaylists();
const vidToRemove = p[playlistName][index];
p[playlistName].splice(index, 1);
await localforage.setItem('custom_playlists', p);
if (supabaseClient && vidToRemove) {
try { await supabaseClient.from('custom_playlists').delete().match({ playlist_name: playlistName, video_id: vidToRemove.id }); } catch(e){}
}
viewPlaylistContents(playlistName);
}
async function playMultipleFromPlaylist(playlistName, playAll) {
let p = await getPlaylists(); let vids = p[playlistName]; if(vids.length === 0) return; let targetArray = [];
if(playAll) { targetArray = vids.map(v => v.id); } else { document.querySelectorAll('.custom-pl-checkbox').forEach(cb => { if(cb.checked) targetArray.push(vids[cb.getAttribute('data-index')].id); }); }
if(targetArray.length === 0) return;
startMultiplePlayback(targetArray);
}
// --- CORE PLAYER ENGINE & MENU / ORIENTATION SYSTEM ---
function applyPlayerButtonSettings() {
const videoSettings = getVideoSettings();
const btn = document.getElementById('player-menu-btn');
if (!btn) return;
if (videoSettings.buttonMode === 'close') {
btn.innerHTML = '✖';
btn.title = 'Close Player';
btn.onclick = function(e) {
if (e) e.stopPropagation();
closePlayer();
};
} else {
btn.innerHTML = '⋮';
btn.title = 'Player Options';
btn.onclick = function(e) {
togglePlayerMenu(e);
};
}
}
function togglePlayerMenu(e) {
if (e) e.stopPropagation();
const menu = document.getElementById('player-dropdown-menu');
if (menu) {
menu.style.display = (menu.style.display === 'none' || !menu.style.display) ? 'block' : 'none';
}
}
function hidePlayerMenu() {
const menu = document.getElementById('player-dropdown-menu');
if (menu) menu.style.display = 'none';
}
let currentOrientationIsLandscape = true;
async function syncPlayerOrientation() {
const overlay = document.getElementById('player-overlay');
if (!overlay || overlay.style.display !== 'block') return;
const target = currentOrientationIsLandscape ? 'landscape' : 'portrait';
// Re-request Fullscreen if not active so status bar / navigation bar stays hidden
if (!document.fullscreenElement) {
if (overlay.requestFullscreen) { overlay.requestFullscreen().catch(()=>{}); }
else if (overlay.webkitRequestFullscreen) { overlay.webkitRequestFullscreen(); }
}
if (screen.orientation && screen.orientation.lock) {
try {
await screen.orientation.lock(target).catch(()=>{});
} catch(e) {
console.log("Re-lock orientation note:", e);
}
}
}
async function toggleOrientation() {
currentOrientationIsLandscape = !currentOrientationIsLandscape;
await syncPlayerOrientation();
}
async function applyVideoOrientationSettings() {
const settings = getVideoSettings();
const targetOrientation = settings.orientation || 'landscape';
const sequenceCount = parseInt(settings.rotationCount) || 1;
currentOrientationIsLandscape = (targetOrientation === 'landscape');
const overlay = document.getElementById('player-overlay');
if (overlay.requestFullscreen) { overlay.requestFullscreen().catch(()=>{}); }
else if (overlay.webkitRequestFullscreen) { overlay.webkitRequestFullscreen(); }
if (!screen.orientation || !screen.orientation.lock) return;
try {
if (sequenceCount <= 1) {
await screen.orientation.lock(targetOrientation).catch(()=>{});
} else {
const oppositeOrientation = targetOrientation === 'landscape' ? 'portrait' : 'landscape';
await screen.orientation.lock(targetOrientation).catch(()=>{});
for (let i = 1; i < sequenceCount; i++) {
await new Promise(r => setTimeout(r, 400));
const nextOrient = (i % 2 === 1) ? oppositeOrientation : targetOrientation;
currentOrientationIsLandscape = (nextOrient === 'landscape');
await screen.orientation.lock(nextOrient).catch(()=>{});
}
}
} catch(e) {
console.log("Orientation sequence notice:", e);
}
}
function rebuildPlayerDOM() {
if (ytPlayer) { try { ytPlayer.destroy(); } catch(e){} ytPlayer = null; }
document.getElementById('custom-endscreen').style.display = 'none';
document.getElementById('player-target').style.opacity = '1';
hidePlayerMenu();
applyPlayerButtonSettings();
}
document.addEventListener('fullscreenchange', () => {
if (!document.fullscreenElement && screen.orientation && screen.orientation.unlock) {
screen.orientation.unlock();
} else if (document.fullscreenElement) {
syncPlayerOrientation();
}
});
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible' && document.getElementById('player-overlay').style.display === 'block') {
syncPlayerOrientation();
}
});
window.addEventListener('pageshow', () => {
syncPlayerOrientation();
});
window.addEventListener('focus', () => {
syncPlayerOrientation();
});
function startMultiplePlayback(idArray) {
const overlay = document.getElementById('player-overlay');
overlay.style.display = 'block';
rebuildPlayerDOM();
window.scrollTo(0, 0);
if (overlay.requestFullscreen) { overlay.requestFullscreen().catch(e=>{}); }
else if (overlay.webkitRequestFullscreen) { overlay.webkitRequestFullscreen(); }
applyVideoOrientationSettings();
function injectPlaylist() {
ytPlayer = new YT.Player('player-target', {
height: '100%',
width: '100%',
playerVars: { autoplay: 1, rel: 0, modestbranding: 1, playsinline: 1 },
events: {
'onReady': (e) => { e.target.loadPlaylist(idArray); },
'onStateChange': handleIframeStateChange,
'onError': (e) => {
if (e.data === 101 || e.data === 150 || e.data === 2) {
alert("Playback Error: This video cannot be embedded.");
closePlayer();
}
}
}
});
}
setTimeout(() => { injectPlaylist(); }, 1200);
}
function playVid(safeData) {
const data = JSON.parse(decodeURIComponent(safeData));
currentVideoData = data;
const overlay = document.getElementById('player-overlay');
overlay.style.display = 'block';
rebuildPlayerDOM();
window.scrollTo(0, 0);
if (overlay.requestFullscreen) { overlay.requestFullscreen().catch(e=>{}); }
else if (overlay.webkitRequestFullscreen) { overlay.webkitRequestFullscreen(); }
applyVideoOrientationSettings();
function injectVideo() {
const startSec = data.timeWatched ? Math.floor(data.timeWatched) : 0;
lastSavedTime = -1;
let playerOptions = {
height: '100%',
width: '100%',
playerVars: { start: startSec, autoplay: 1, rel: 0, modestbranding: 1, playsinline: 1 },
events: {
'onReady': (e) => { e.target.playVideo(); },
'onStateChange': handleIframeStateChange,
'onError': (e) => {
if (e.data === 101 || e.data === 150 || e.data === 2) {
alert("Playback Error: The video creator does not allow embedding this video.");
closePlayer();
}
}
}
};
if (data.type === 'playlist' && data.id) {
playerOptions.playerVars.listType = 'playlist';
playerOptions.playerVars.list = data.id;
} else {
playerOptions.videoId = data.id;
}
ytPlayer = new YT.Player('player-target', playerOptions);
startSavingHistory();
}
setTimeout(() => { injectVideo(); }, 1200);
}
async function handleIframeStateChange(event) {
if (event.data === YT.PlayerState.PLAYING && ytPlayer) {
const vidData = ytPlayer.getVideoData();
if (vidData && vidData.video_id) {
currentVideoData.id = vidData.video_id;
if (vidData.title && vidData.title !== 'Loading video...' && vidData.title !== 'Direct Link Play') {
currentVideoData.title = vidData.title;
}
if (vidData.author) currentVideoData.author = vidData.author;
if (!currentVideoData.thumb) currentVideoData.thumb = `https://i.ytimg.com/vi/${vidData.video_id}/hqdefault.jpg`;
}
}
if (event.data === YT.PlayerState.ENDED) {
document.getElementById('player-target').style.opacity = '0';
document.getElementById('custom-endscreen').style.display = 'block';
const grid = document.getElementById('endscreen-grid');
grid.innerHTML = '<p>Loading recommendations...</p>';
try {
const res = await fetch('/api/youtube-search', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ q: (currentVideoData.title || "recommended") + " related", token: "" })
});
const data = await res.json();
grid.innerHTML = '';
if(data.items && data.items.length > 0) {
const filteredItems = [];
const seenIds = new Set([currentVideoData.id]);
for (const item of data.items) {
if (item.id && !seenIds.has(item.id)) {
seenIds.add(item.id);
filteredItems.push(item);
}
if (filteredItems.length >= 2) break;
}
if (filteredItems.length > 0) {
filteredItems.forEach(item => {
const safeData = encodeURIComponent(JSON.stringify(item));
grid.innerHTML += `<div class="endscreen-card" onclick="document.getElementById('custom-endscreen').style.display='none'; document.getElementById('player-target').style.opacity='1'; playVid('${safeData}')"><img src="${item.thumb}"><p class="title">${item.title}</p></div>`;
});
} else {
grid.innerHTML = '<p>No other recommendations available.</p>';
}
} else {
grid.innerHTML = '<p>No suggestions available.</p>';
}
} catch(e) { grid.innerHTML = '<p>No suggestions available.</p>'; }
}
}
function closePlayer() {
const overlay = document.getElementById('player-overlay');
overlay.style.display = 'none';
hidePlayerMenu();
if(ytPlayer) { try { ytPlayer.stopVideo(); ytPlayer.destroy(); } catch(e){} ytPlayer = null; }
if (saveInterval) clearTimeout(saveInterval);
if(document.fullscreenElement) { document.exitFullscreen().catch(e=>{}); }
if (screen.orientation && screen.orientation.unlock) { screen.orientation.unlock(); }
}
let lastSavedTime = -1;
function startSavingHistory() {
if (saveInterval) clearTimeout(saveInterval);
async function saveTick() {
if(ytPlayer && typeof ytPlayer.getPlayerState === 'function' && ytPlayer.getPlayerState() === YT.PlayerState.PLAYING) {
const ct = ytPlayer.getCurrentTime();
if (ct && ct > 0 && Math.abs(ct - lastSavedTime) > 1) {
lastSavedTime = ct;
currentVideoData.timeWatched = ct;
const dur = ytPlayer.getDuration() || cachedDurations[currentVideoData.id] || 0;
currentVideoData.total_secs = dur;
let cloudSuccess = false;
if(supabaseClient) {
try {
const { error } = await supabaseClient.from('watch_history').upsert({ id: currentVideoData.id, title: currentVideoData.title, thumb: currentVideoData.thumb, author: currentVideoData.author, time_watched: ct, total_secs: dur, last_watched: new Date().toISOString() });
if(!error) cloudSuccess = true;
} catch(e) {}
}
if(!cloudSuccess) {
try {
let hist = await localforage.getItem('watch_history') || {};
hist[currentVideoData.id] = { ...currentVideoData, lastWatched: new Date().toISOString() };
await localforage.setItem('watch_history', hist);
} catch(e) {}
}
const targetIds = [
`hist-item-${currentVideoData.id}`,
`yt-pl-item-${currentVideoData.id}`,
`custom-pl-item-${currentVideoData.id}`
];
targetIds.forEach(id => {
const domItem = document.getElementById(id);
if (domItem) {
let pct = 0;
if(dur && dur > 0) { pct = Math.min(100, Math.max(0, (ct / dur) * 100)); }
let fill = domItem.querySelector('.watch-progress-fill');
let timeText = domItem.querySelector('.hist-time-text');
if (!fill) {
const thumbWrap = domItem.querySelector('.thumb-wrapper');
if(thumbWrap) thumbWrap.insertAdjacentHTML('beforeend', `<div class="watch-progress-bg"><div class="watch-progress-fill" style="width: ${pct}%;"></div></div>`);
const infoCol = domItem.querySelector('.info-col');
if(infoCol) infoCol.insertAdjacentHTML('beforeend', `<div class="hist-time-text" style="font-size:0.8em; color:#e53935; font-weight:bold; margin-top:4px;">▶ Watched: ${formatSecs(ct)} / ${formatSecs(dur)}</div>`);
} else {
fill.style.width = `${pct}%`;
if (timeText) timeText.innerText = `▶ Watched: ${formatSecs(ct)} / ${formatSecs(dur)}`;
}
} else if (id.startsWith('hist-item') && document.getElementById('history-modal').style.display === 'block') {
loadHistory();
}
});
}
}
saveInterval = setTimeout(saveTick, 5000);
}
saveInterval = setTimeout(saveTick, 5000);
}
// --- HISTORY LONG-PRESS & ACTION LOGIC ---
let pressTimer;
let isLongPressAction = false;
let activeHistoryVideo = null;
function startHistoryPress(event, safeData) {
isLongPressAction = false;
if (event.type === 'mousedown' && event.button !== 0) return;
pressTimer = setTimeout(() => { isLongPressAction = true; openHistoryOptions(safeData); }, 1200);
}
function cancelHistoryPress() { if (pressTimer) clearTimeout(pressTimer); }
function handleHistoryClick(event, safeData) {
if(isLongPressAction) { setTimeout(() => { isLongPressAction = false; }, 100); return; }
playVid(safeData);
}
function openHistoryOptions(safeData) {
activeHistoryVideo = JSON.parse(decodeURIComponent(safeData));
const detailsDiv = document.getElementById('history-action-details');
detailsDiv.innerHTML = `
<img src="${activeHistoryVideo.thumb}" style="width: 100%; border-radius: 10px; margin-bottom: 10px; aspect-ratio: 16/9; object-fit: cover; box-shadow: 0 4px 10px rgba(0,0,0,0.2);">
<div style="font-weight: 700; font-size: 15px; color: #2c3e50;">${activeHistoryVideo.title}</div>
`;
if (navigator.vibrate) { navigator.vibrate(50); }
openModal('history-action-modal');
}
async function deleteHistoryItem() {
if (!activeHistoryVideo) return;
const vidId = activeHistoryVideo.id;
if (supabaseClient) { try { await supabaseClient.from('watch_history').delete().eq('id', vidId); } catch(e) {} }
try {
let hist = await localforage.getItem('watch_history') || {};
if (hist[vidId]) { delete hist[vidId]; }
await localforage.setItem('watch_history', hist);
} catch(e) {}
closeModal('history-action-modal');
if (document.getElementById('history-modal').style.display === 'block') loadHistory();
else if (!currentSearchQuery) loadDefaultHomepageContent();
}
function transferHistoryItem() { closeModal('history-action-modal'); selectedVideos = [activeHistoryVideo]; initiateAddToPlaylist(); }
async function loadHistory() {
const content = document.getElementById('history-content'); content.innerHTML = "Loading database...";
let histObj = await getHistoryMap();
let keys = Object.keys(histObj);
if(keys.length === 0) { content.innerHTML = "<p style='text-align:center; color:#94a3b8;'>History is empty.</p>"; return; }
content.innerHTML = ""; let animDelay = 0;
keys.sort((a,b) => new Date(histObj[b].lastWatched) - new Date(histObj[a].lastWatched)).forEach(key => {
let val = histObj[key]; const safeData = encodeURIComponent(JSON.stringify(val));
let pct = 0;
if(val.total_secs && val.total_secs > 0) { pct = Math.min(100, Math.max(0, (val.timeWatched / val.total_secs) * 100)); }
let progressHtml = `<div class="watch-progress-bg"><div class="watch-progress-fill" style="width: ${pct}%;"></div></div>`;
let timeFmt = val.total_secs ? formatSecs(val.total_secs) : val.duration || '';
content.innerHTML += `
<div id="hist-item-${val.id}" class="result-item" style="padding:10px; animation-delay: ${animDelay}s; position: relative;"
onpointerdown="startHistoryPress(event, '${safeData}')"
onpointerup="cancelHistoryPress()"
onpointerleave="cancelHistoryPress()"
onpointercancel="cancelHistoryPress()">
<div class="thumb-wrapper" onclick="handleHistoryClick(event, '${safeData}')">
<img class="thumb" src="${val.thumb}">
${progressHtml}
<div class="dur-badge" style="z-index:4;">${timeFmt}</div>
</div>
<div class="info-col" onclick="handleHistoryClick(event, '${safeData}')" style="padding-right: 40px;">
<div class="title">${val.title}</div>
<div class="hist-time-text" style="font-size:0.8em; color:#e53935; font-weight:bold; margin-top:4px;">▶ Watched: ${formatSecs(val.timeWatched)} / ${formatSecs(val.total_secs || 0)}</div>
</div>
<button onclick="openHistoryOptions('${safeData}')" style="position: absolute; right: 5px; top: 50%; transform: translateY(-50%); background: transparent; border: none; font-size: 24px; color: #b0bec5; cursor: pointer; padding: 15px 10px; z-index: 10;">⋮</button>
</div>`;
animDelay += 0.05;
});
}
async function loadPersonalizedHomeFeed() {
const resultsDiv = document.getElementById('results');
resultsDiv.innerHTML = "<h3 style='text-align: center; color: #0277bd;'>Loading Your Videos...</h3>";
let searchQuery = "trending cool videos";
if (supabaseClient) {
try {
const { data, error } = await supabaseClient.from('watch_history').select('*').order('last_watched', { ascending: false }).limit(5);
if (!error && data && data.length > 0) {
let seedVideo = data[Math.floor(Math.random() * data.length)];
searchQuery = seedVideo.title + " related";
}
} catch (e) {}
}
try {
const res = await fetch('/api/youtube-search', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ q: searchQuery, token: "" })
});
const data = await res.json();
resultsDiv.innerHTML = "<h3 style='color:#ab47bc; margin-bottom: 15px;'>Recommended for You</h3>";
if (data.items && data.items.length > 0) {
let histMap = await getHistoryMap();
let animDelay = 0;
data.items.forEach(item => {
const safeData = encodeURIComponent(JSON.stringify(item));
const isVid = item.type === 'video';
const clickAction = isVid ? `playVid('${safeData}')` : `openYoutubePlaylist('${item.id}', '${item.title.replace(/'/g, "\\'")}')`;
let hist = histMap[item.id];
let pct = 0;
let progressHtml = '';
let resumeText = '';
if (hist && hist.timeWatched && hist.timeWatched > 0) {
const totalSecs = hist.total_secs || item.total_secs || 1;
pct = Math.min(100, Math.max(0, (hist.timeWatched / totalSecs) * 100));
progressHtml = `<div class="watch-progress-bg"><div class="watch-progress-fill" style="width: ${pct}%;"></div></div>`;
resumeText = `<div class="hist-time-text" style="font-size:0.8em; color:#e53935; font-weight:bold; margin-top:4px;">▶ Watched: ${formatSecs(hist.timeWatched)} / ${formatSecs(totalSecs)}</div>`;
}
resultsDiv.innerHTML += `
<div class="result-item" data-type="${item.type}" style="border-left-color: ${isVid ? '#29b6f6' : '#ab47bc'}; animation-delay: ${animDelay}s;">
<input type="checkbox" class="vid-checkbox" onchange="toggleSelect(this, '${safeData}')">
<div class="thumb-wrapper" onclick="${clickAction}">
<img class="thumb" src="${item.thumb}">
${progressHtml}
${isVid ? `<div class="dur-badge">${item.duration}</div>` : `<div class="dur-badge">PLAYLIST</div>`}
</div>
<div class="info-col">
<div class="title" onclick="${clickAction}">${isVid ? '' : '🔀 '}${item.title}</div>
<div style="color: #546e7a; font-size: clamp(12px, 3vw, 0.9em); margin-top:5px;">By <span class="author">${item.author}</span></div>
${resumeText}
</div>
</div>`;
animDelay += 0.05;
});
} else {
resultsDiv.innerHTML = "<h3>No recommendations found right now. Try searching!</h3>";
}
} catch(e) {
resultsDiv.innerHTML = `<h3 style="color:red;">Error loading feed.</h3>`;
}
}
// --- VOICE SEARCH MIC TOGGLE ---
let voiceRecognitionInstance = null;
let isVoiceListening = false;
function toggleVoiceSearch() {
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
if (!SpeechRecognition) {
alert("Bro, voice search isn't supported in this browser. Try Chrome!");
return;
}
const micBtn = document.querySelector('.mic-btn');
if (isVoiceListening && voiceRecognitionInstance) {
voiceRecognitionInstance.stop();
isVoiceListening = false;
micBtn.innerHTML = '🎤';
micBtn.style.transform = 'scale(1)';
return;
}
voiceRecognitionInstance = new SpeechRecognition();
voiceRecognitionInstance.lang = 'en-US';
voiceRecognitionInstance.interimResults = false;
voiceRecognitionInstance.onstart = function() {
isVoiceListening = true;
micBtn.innerHTML = '🔴';
micBtn.style.transform = 'scale(1.2)';
};
voiceRecognitionInstance.onresult = function(event) {
const transcript = event.results[0][0].transcript;
document.getElementById('searchInput').value = transcript;
executeSearch(false);
};
voiceRecognitionInstance.onerror = function(event) {
console.error("Speech recognition error:", event.error);
isVoiceListening = false;
micBtn.innerHTML = '🎤';
micBtn.style.transform = 'scale(1)';
};
voiceRecognitionInstance.onend = function() {
isVoiceListening = false;
micBtn.innerHTML = '🎤';
micBtn.style.transform = 'scale(1)';
};
voiceRecognitionInstance.start();
}
// --- DOM LOAD INITIALIZATION ---
window.addEventListener('DOMContentLoaded', () => {
loadDefaultHomepageContent();
});
// --- KEYBOARD SHORTCUTS ---
document.addEventListener('keydown', (e) => {
if (document.getElementById('player-overlay').style.display !== 'block') return;
if (document.activeElement.tagName === 'INPUT' || document.activeElement.tagName === 'TEXTAREA') return;
if (e.key === 'Escape') {
closePlayer();
return;
}
if (!ytPlayer || typeof ytPlayer.getPlayerState !== 'function') return;
switch(e.key.toLowerCase()) {
case ' ':
e.preventDefault();
if (ytPlayer.getPlayerState() === YT.PlayerState.PLAYING) {
ytPlayer.pauseVideo();
} else {
ytPlayer.playVideo();
}
break;
case 'f':
if (!document.fullscreenElement) {
document.documentElement.requestFullscreen().catch(()=>{});
} else {
document.exitFullscreen().catch(()=>{});
}
break;
case 'arrowleft':
ytPlayer.seekTo(ytPlayer.getCurrentTime() - 10, true);
break;
case 'arrowright':
ytPlayer.seekTo(ytPlayer.getCurrentTime() + 10, true);
break;
}
});
window.addEventListener('resize', () => {
const overlay = document.getElementById('player-overlay');
if (overlay.style.display === 'block') {
const iframe = overlay.querySelector('iframe');
if (iframe) {
iframe.style.width = '99.9%';
setTimeout(() => { iframe.style.width = '100%'; }, 150);
}
}
});
// NUKE NATIVE CONTEXT MENU EXCEPT IN INPUTS
window.addEventListener('contextmenu', function (e) {
if (e.target.tagName !== 'INPUT') {
e.preventDefault();
}
});
</script>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
<title>YOUTUBE SEARCH - AI PRO SUITE</title>
<!-- Core Dependencies -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/localforage/1.10.0/localforage.min.js"></script>
<script src="https://www.youtube.com/iframe_api"></script>
<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Quicksand:wght@400;600;700&display=swap');
* {
box-sizing: border-box;
-webkit-touch-callout: none; /* KILLS THE IOS POPUP MENU */
}
body { font-family: 'Quicksand', sans-serif; margin: 0; padding: 0; background-color: #f0f8ff; color: #2c3e50; min-height: 100vh; overflow-x: hidden; }
/* SCALING TOP BAR */
.top-bar { position: sticky; top: 0; z-index: 100; background: #fff; padding: clamp(8px, 2vw, 15px) clamp(10px, 3vw, 20px); box-shadow: 0 2px 10px rgba(0,0,0,0.08); display: flex; gap: clamp(5px, 2vw, 10px); align-items: center; width: 100%; }
.hamburger { background: none; border: none; font-size: clamp(20px, 5vw, 26px); cursor: pointer; color: #0277bd; padding: 0 5px; flex-shrink: 0; transition: transform 0.2s; }
.hamburger:active { transform: scale(0.9); }
/* SEARCH & SUGGESTIONS */
.search-wrapper { flex-grow: 1; position: relative; display: flex; align-items: center; background: #fff; border: 2px solid #b3e5fc; border-radius: 20px; padding-right: 10px; min-width: 0; transition: border-color 0.3s; }
.search-wrapper:focus-within { border-color: #039be5; box-shadow: 0 0 8px rgba(3, 155, 229, 0.2); }
input[type="text"] { flex-grow: 1; padding: clamp(8px, 2vw, 12px) clamp(10px, 3vw, 15px); border: none; background: transparent; font-size: clamp(14px, 3.5vw, 16px); outline: none; font-family: 'Quicksand'; min-width: 0; width: 100%; user-select: text; -webkit-user-select: text; }
.mic-btn { background: none; border: none; cursor: pointer; font-size: clamp(16px, 4vw, 20px); color: #0277bd; display: flex; align-items: center; justify-content: center; padding: 5px; flex-shrink: 0; transition: transform 0.2s; }
.mic-btn:hover { color: #e53935; transform: scale(1.1); }
.search-dropdown { display: none; position: absolute; top: 100%; left: 0; right: 0; background: white; border-radius: 15px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); margin-top: 5px; max-height: 300px; overflow-y: auto; z-index: 101; border: 1px solid #e1f5fe; }
.suggestion-item { display: flex; justify-content: space-between; align-items: center; padding: 10px 15px; cursor: pointer; border-bottom: 1px solid #f0f8ff; transition: background 0.2s; font-size: clamp(13px, 3vw, 15px); }
.suggestion-item:hover { background: #e1f5fe; }
.suggestion-text { flex-grow: 1; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: flex; gap: 10px; align-items: center; }
.suggestion-del { color: #90a4ae; background: none; border: none; font-size: 16px; padding: 5px; cursor: pointer; }
.suggestion-del:hover { color: #e53935; }
/* BUTTONS */
.btn-action { padding: clamp(8px, 2vw, 12px) clamp(10px, 3vw, 20px); font-size: clamp(12px, 3vw, 15px); font-weight: 700; background: #039be5; color: white; border: none; border-radius: 20px; cursor: pointer; transition: all 0.2s ease; white-space: nowrap; text-align: center; flex-shrink: 0; box-shadow: 0 2px 5px rgba(3, 155, 229, 0.3); }
.btn-action:hover { background: #0277bd; transform: translateY(-2px); box-shadow: 0 4px 8px rgba(3, 155, 229, 0.4); }
.btn-action:active { transform: translateY(0) scale(0.95); }
/* FILTER CHIPS */
.filter-container { display: flex; gap: clamp(5px, 2vw, 10px); padding: 10px 15px; background: #e1f5fe; justify-content: center; flex-wrap: wrap; }
.filter-chip { background: white; border: 2px solid #81d4fa; color: #0277bd; padding: 6px clamp(10px, 3vw, 15px); border-radius: 20px; font-weight: 600; font-size: clamp(12px, 3vw, 14px); cursor: pointer; transition: 0.2s; font-family: 'Quicksand'; }
.filter-chip.active { background: #0277bd; color: white; border-color: #0277bd; box-shadow: 0 2px 8px rgba(2, 119, 189, 0.4); }
/* FLOATING DRAWER */
.drawer-overlay { display: none; position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background: rgba(0,0,0,0.5); z-index: 1000; backdrop-filter: blur(2px); animation: fadeIn 0.3s ease forwards; }
.drawer { position: fixed; top: 0; left: -100%; width: clamp(240px, 70vw, 300px); height: 100vh; background: #0277bd; color: white; padding: 20px 10px; box-shadow: 4px 0 15px rgba(0,0,0,0.2); transition: left 0.3s cubic-bezier(0.4, 0, 0.2, 1); z-index: 1001; overflow-y: auto; display: flex; flex-direction: column; gap: 8px; }
.drawer.active { left: 0; }
.drawer-header { display: flex; justify-content: space-between; align-items: center; padding: 0 10px 15px 10px; }
.drawer h3 { margin: 0; font-weight: 700; letter-spacing: 1px; font-size: clamp(16px, 4vw, 20px); }
.close-drawer { font-size: 24px; cursor: pointer; background: none; border: none; color: white; transition: transform 0.2s; }
.close-drawer:hover { transform: rotate(90deg); }
.menu-btn { width: 100%; text-align: left; padding: 12px 15px; background: rgba(255,255,255,0.15); border: none; border-radius: 10px; color: white; font-weight: 700; font-family: 'Quicksand'; cursor: pointer; transition: 0.2s; display: flex; align-items: center; gap: 10px; font-size: clamp(14px, 3.5vw, 16px); }
.menu-btn:hover { background: rgba(255,255,255,0.25); transform: translateX(5px); }
.menu-link { display: flex; align-items: center; gap: 10px; text-decoration: none; padding: 10px 15px; color: rgba(255,255,255,0.8); border-radius: 10px; transition: 0.2s; font-weight: 600; font-size: clamp(13px, 3vw, 15px); }
.menu-link:hover { background: rgba(255,255,255,0.1); color: white; padding-left: 20px; }
.menu-divider { border-top: 1px solid rgba(255,255,255,0.2); margin: 10px 5px; }
/* WORKSPACE & LIST ITEMS */
.workspace { padding: clamp(10px, 2vw, 20px); width: 100%; max-width: 1000px; margin: 0 auto; }
#selection-bar { display: none; background: #ab47bc; color: white; padding: 10px clamp(10px, 3vw, 20px); border-radius: 20px; margin-bottom: 15px; text-align: center; font-weight: bold; position: sticky; top: 65px; z-index: 99; box-shadow: 0 4px 10px rgba(0,0,0,0.2); flex-wrap: wrap; gap: 10px; justify-content: center; align-items: center; font-size: clamp(12px, 3vw, 15px); animation: slideDown 0.3s forwards; }
/* THUMBNAILS & PROGRESS BAR */
.result-item { position: relative; margin: clamp(10px, 2vw, 15px) 0; padding: clamp(10px, 2vw, 15px); border-radius: 12px; background: white; border-left: 6px solid #29b6f6; box-shadow: 0 4px 8px rgba(0,0,0,0.04); display: flex; align-items: center; gap: clamp(10px, 3vw, 15px); width: 100%; overflow: hidden; animation: slideUpFade 0.4s ease-out forwards; opacity: 0; transform: translateY(15px); transition: transform 0.2s; }
.result-item:hover { transform: translateY(-2px); box-shadow: 0 6px 12px rgba(0,0,0,0.08); }
.vid-checkbox { width: clamp(18px, 4vw, 22px); height: clamp(18px, 4vw, 22px); cursor: pointer; accent-color: #ab47bc; flex-shrink: 0; z-index: 5; }
.thumb-wrapper { position: relative; cursor: pointer; flex-shrink: 0; border-radius: 8px; overflow: hidden; background: #000; width: clamp(120px, 30vw, 160px); aspect-ratio: 16/9; }
.thumb { width: 100%; height: 100%; object-fit: cover; display: block; transition: filter 0.2s; }
.thumb-wrapper:hover .thumb { filter: brightness(0.85); }
.dur-badge { position: absolute; bottom: 5px; right: 5px; background: rgba(0,0,0,0.85); color: white; padding: 2px 6px; border-radius: 4px; font-size: clamp(10px, 2.5vw, 12px); font-weight: bold; z-index: 2; }
/* RED PROGRESS BAR */
.watch-progress-bg { position: absolute; bottom: 0; left: 0; width: 100%; height: 4px; background: rgba(255,255,255,0.3); z-index: 3; }
.watch-progress-fill { height: 100%; background: #e53935; width: 0%; transition: width 0.3s linear; }
.info-col { flex-grow: 1; min-width: 0; display: flex; flex-direction: column; justify-content: center; }
.title { font-size: clamp(14px, 3.5vw, 1.1em); font-weight: 700; cursor:pointer; color: #1a252f; margin-bottom: 5px; line-height: 1.4; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
.author { font-weight: 700; color: #0288d1; cursor: pointer; font-size: clamp(12px, 3vw, 14px); }
/* MODALS */
.modal-overlay { display: none; position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background: rgba(0,0,0,0.6); z-index: 500; backdrop-filter: blur(4px); animation: fadeIn 0.2s ease forwards; }
.modal-content { background: white; width: 96%; max-width: 800px; max-height: 90vh; margin: 5vh auto; border-radius: 20px; padding: clamp(15px, 4vw, 20px); overflow-y: auto; overflow-x: hidden; position: relative; box-shadow: 0 10px 30px rgba(0,0,0,0.3); animation: popIn 0.4s forwards; transform-origin: center; }
.close-modal { position: absolute; top: clamp(8px, 2vw, 10px); right: clamp(8px, 2vw, 10px); font-size: clamp(18px, 4vw, 22px); cursor: pointer; color: #fff; font-weight: bold; width: clamp(28px, 6vw, 32px); height: clamp(28px, 6vw, 32px); line-height: clamp(26px, 6vw, 30px); text-align: center; background: #e53935; border-radius: 50%; box-shadow: 0 2px 5px rgba(0,0,0,0.2); z-index: 10; border: 2px solid white; transition: 0.2s; }
.close-modal:hover { transform: scale(1.1) rotate(90deg); background: #d32f2f; }
.modal-header-actions { display: flex; flex-wrap: wrap; gap: clamp(5px, 2vw, 10px); margin-bottom: 15px; padding-right: clamp(30px, 8vw, 40px); align-items: center; }
.modal-header-actions .btn-action { flex: 1 1 auto; }
/* PLAYER OVERLAY & ROTATION FIX */
#player-overlay {
display: none;
position: fixed;
top: 0; left: 0; right: 0; bottom: 0;
background: #000;
z-index: 9999;
pointer-events: auto;