bep40 commited on
Commit
8151f94
·
verified ·
1 Parent(s): 437fe01

Upload static/app_v2.js with huggingface_hub

Browse files
Files changed (1) hide show
  1. static/app_v2.js +490 -0
static/app_v2.js ADDED
@@ -0,0 +1,490 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // === VNEWS Frontend v2 - Full Functions + VTV Player ===
2
+ // Updated: VTV multi-source player, team stats, fast API
3
+
4
+ // ===== VTV CHANNELS =====
5
+ const VTV_CHANNELS = [
6
+ {id:'vtv1', name:'VTV1', badge:'Tin tức'},
7
+ {id:'vtv2', name:'VTV2', badge:'Khoa học'},
8
+ {id:'vtv3', name:'VTV3', badge:'Giải trí'},
9
+ {id:'vtv4', name:'VTV4', badge:'Quốc tế'},
10
+ {id:'vtv5', name:'VTV5', badge:'Miền Nam'},
11
+ {id:'vtv6', name:'VTV6', badge:'Thanh niên'},
12
+ {id:'vtv7', name:'VTV7', badge:'Giáo dục'},
13
+ {id:'vtv8', name:'VTV8', badge:'Miền Trung'},
14
+ {id:'vtv9', name:'VTV9', badge:'Miền Bắc'},
15
+ {id:'vtv10', name:'VTV10', badge:'VTV10'},
16
+ {id:'vtvprime', name:'VTVPrime', badge:'Prime'},
17
+ ];
18
+
19
+ const VTV_EPG = {
20
+ vtv1:[{t:'06:00',n:'Nhật ký ngày mai'},{t:'07:00',n:'Thời sự sáng'},{t:'09:00',n:'Thời sự'},{t:'12:00',n:'Thời sự trưa'},{t:'19:00',n:'Thời sự tối'},{t:'21:00',n:'Thời sự đêm'}],
21
+ vtv2:[{t:'06:00',n:'Khoa học & CN'},{t:'08:00',n:'Thế giới tự nhiên'},{t:'10:00',n:'Khoa học 360'},{t:'14:00',n:'Sức khỏe'},{t:'20:00',n:'Khoa học & Tương lai'}],
22
+ vtv3:[{t:'06:00',n:'Sáng vui'},{t:'08:00',n:'Phim truyện'},{t:'12:00',n:'Âm nhạc'},{t:'16:00',n:'Giải trí chiều'},{t:'20:00',n:'Phim đặc biệt'}],
23
+ vtv4:[{t:'06:00',n:'News'},{t:'08:00',n:'World News'},{t:'12:00',n:'Midday News'},{t:'18:00',n:'Evening News'},{t:'20:00',n:'World Today'}],
24
+ vtv5:[{t:'06:00',n:'Thời sự miền Nam'},{t:'10:00',n:'Phim truyện'},{t:'14:00',n:'Giải trí'},{t:'18:00',n:'Thời sự chiều'},{t:'22:00',n:'Thời sự tối'}],
25
+ vtv6:[{t:'06:00',n:'Khởi động ngày mới'},{t:'08:00',n:'Thanh niên & Sáng tạo'},{t:'12:00',n:'Nhịp sống trẻ'},{t:'18:00',n:'Thời sự trẻ'},{t:'20:00',n:'Đêm nhạc'}],
26
+ vtv7:[{t:'06:00',n:'Giáo dục sáng'},{t:'08:00',n:'Học mọi lúc'},{t:'12:00',n:'Giáo dục trưa'},{t:'16:00',n:'Thiếu nhi'},{t:'20:00',n:'Tài liệu GD'}],
27
+ vtv8:[{t:'06:00',n:'Thời sự miền Trung'},{t:'10:00',n:'Phim truyện'},{t:'14:00',n:'Giải trí'},{t:'18:00',n:'Thời sự chiều'},{t:'22:00',n:'Thời sự tối'}],
28
+ vtv9:[{t:'06:00',n:'Thời sự miền Bắc'},{t:'10:00',n:'Phim truyện'},{t:'14:00',n:'Giải trí'},{t:'18:00',n:'Thời sự chiều'},{t:'22:00',n:'Thời sự tối'}],
29
+ vtv10:[{t:'06:00',n:'Thời sự Tây Nam Bộ'},{t:'10:00',n:'Phim truyện'},{t:'14:00',n:'Giải trí'},{t:'18:00',n:'Thời sự chiều'},{t:'22:00',n:'Thời sự tối'}],
30
+ vtvprime:[{t:'06:00',n:'Prime Morning'},{t:'10:00',n:'Prime Sports'},{t:'14:00',n:'Prime Drama'},{t:'18:00',n:'Prime Evening'},{t:'20:00',n:'Prime Night'}],
31
+ };
32
+
33
+ // Fallback static sources (when API is down)
34
+ const VTV_STATIC_SOURCES = {
35
+ vtv1:["https://live-a.fptplay53.net/live/media/vtv1/live247-hls-avc/index.m3u8","https://vtvgolive-failover.vtvdigital.vn/vtvgo/vtv1-manifest.m3u8","https://live.fptplay53.net/fnxch2/vtv1hd_abr.smil/chunklist.m3u8"],
36
+ vtv2:["https://live-a.fptplay53.net/live/media/vtv2/live247-hls-avc/index.m3u8","https://vtvgolive-failover.vtvdigital.vn/vtvgo/vtv2-manifest.m3u8","https://live.fptplay53.net/fnxch2/vtv2hd_abr.smil/chunklist.m3u8"],
37
+ vtv3:["https://live-a.fptplay53.net/live/media/vtv3/live247-hls-avc/index.m3u8","https://vtvgolive-failover.vtvdigital.vn/vtvgo/vtv3-manifest.m3u8","https://live.fptplay53.net/fnxch2/vtv3hd_abr.smil/chunklist.m3u8"],
38
+ vtv4:["https://live-a.fptplay53.net/live/media/vtv4/live247-hls-avc/index.m3u8","https://vtvgolive-failover.vtvdigital.vn/vtvgo/vtv4-manifest.m3u8"],
39
+ vtv5:["https://live-a.fptplay53.net/live/media/vtv5/live247-hls-avc/index.m3u8","https://vtvgolive-failover.vtvdigital.vn/vtvgo/vtv5-manifest.m3u8","https://live-a.fptplay53.net/live/media/VTV5HD/live_hls_avc/index.m3u8"],
40
+ vtv6:["https://live-a.fptplay53.net/live/media/vtv6/live247-hls-avc/vtv6-avc1_5600000=10000-mp4a_131600=20000.m3u8","https://live-a.fptplay53.net/live/media/vtv6/live247-hls-avc/index.m3u8"],
41
+ vtv7:["https://live-a.fptplay53.net/live/media/vtv7/live247-hls-avc/index.m3u8","https://vtvgolive-failover.vtvdigital.vn/vtvgo/vtv7-manifest.m3u8","https://live.fptplay53.net/fnxhd1/vtv7hd_vhls.smil/chunklist_b5000000.m3u8"],
42
+ vtv8:["https://live.fptplay53.net/epzhd1/vtv8hd_vhls.smil/chunklist.m3u8","https://vtvgolive-failover.vtvdigital.vn/vtvgo/vtv8-manifest.m3u8"],
43
+ vtv9:["https://live.fptplay53.net/fnxhd1/vtv9hd_vhls.smil/chunklist.m3u8","https://vtvgolive-failover.vtvdigital.vn/vtvgo/vtv9-manifest.m3u8"],
44
+ vtv10:["https://live-a.fptplay53.net/live/media/vtv10/live247-hls-avc/vtv10-avc1_5600000=10000-mp4a_131600=20000.m3u8","https://live-a.fptplay53.net/live/media/vtv10/live247-hls-avc/index.m3u8"],
45
+ vtvprime:["https://live.fptplay53.net/fnxch2/vtvprime_abr.smil/chunklist.m3u8"],
46
+ };
47
+
48
+ let _vtvStreams = {};
49
+ let _vtvCurrentCh = null;
50
+ let _vtvHls = null;
51
+
52
+ function buildVTVEPG(chId){
53
+ const epg = VTV_EPG[chId] || [];
54
+ if(!epg.length) return '';
55
+ const curH = new Date().getHours();
56
+ let items = '';
57
+ epg.forEach(item => {
58
+ const itemH = parseInt(item.t.split(':')[0], 10);
59
+ const isNow = itemH <= curH && (itemH + 2) > curH;
60
+ items += `<div class="vtv-epg-item${isNow?' now':''}"><span class="epg-t">${item.t}</span><span class="epg-n">${item.n}</span></div>`;
61
+ });
62
+ return `<div class="vtv-epg"><div class="vtv-epg-title">📋 Lịch phát sóng</div><div class="vtv-epg-list">${items}</div></div>`;
63
+ }
64
+
65
+ function buildVTVBlockHTML(){
66
+ let tabs = '';
67
+ VTV_CHANNELS.forEach(ch => {
68
+ tabs += `<button class="vtv-tab off" id="vtvt-${ch.id}" onclick="_vtvPlay('${ch.id}')">${ch.name}</button>`;
69
+ });
70
+ return `<div class="vtv-wrap" id="vtv-block">
71
+ <div class="vtv-head"><span class="vtv-title">📺 VTV Trực Tuyến</span><span class="vtv-badge">● LIVE</span></div>
72
+ <div class="vtv-tabs">${tabs}</div>
73
+ <div class="vtv-player-area">
74
+ <div class="vtv-load" id="vtv-load"><div class="vtv-spinner"></div>Đang tải danh sách kênh...</div>
75
+ <video id="vtv-player" playsinline muted controls preload="auto" style="display:none"></video>
76
+ <div class="vtv-err" id="vtv-err" style="display:none"><span id="vtv-err-msg">Không thể tải kênh</span><button onclick="_vtvRetry()">Thử lại</button></div>
77
+ </div>
78
+ <div id="vtv-epg-wrap"></div>
79
+ </div>`;
80
+ }
81
+
82
+ async function loadVTVStreams(){
83
+ let apiOk = false;
84
+ try {
85
+ const r = await fetch('/api/vtv/streams', {signal: AbortSignal.timeout(8000)});
86
+ if(r.ok){
87
+ const data = await r.json();
88
+ VTV_CHANNELS.forEach(ch => {
89
+ const info = data[ch.id];
90
+ const sources = (info && info.all_sources && info.all_sources.length > 0) ? info.all_sources : (info && info.stream_url ? [info.stream_url] : []);
91
+ if(sources.length > 0){
92
+ _vtvStreams[ch.id] = sources.map(u => '/api/proxy/m3u8/vtv?url=' + encodeURIComponent(u));
93
+ apiOk = true;
94
+ }
95
+ });
96
+ }
97
+ } catch(e) {
98
+ console.warn('VTV API error:', e);
99
+ }
100
+ if(!apiOk){
101
+ VTV_CHANNELS.forEach(ch => {
102
+ if(!_vtvStreams[ch.id] || _vtvStreams[ch.id].length === 0){
103
+ const fallback = VTV_STATIC_SOURCES[ch.id] || [];
104
+ _vtvStreams[ch.id] = fallback.map(u => '/api/proxy/m3u8/vtv?url=' + encodeURIComponent(u));
105
+ }
106
+ });
107
+ }
108
+ VTV_CHANNELS.forEach(ch => {
109
+ const tab = document.getElementById('vtvt-'+ch.id);
110
+ if(tab){
111
+ if(_vtvStreams[ch.id] && _vtvStreams[ch.id].length > 0){
112
+ tab.classList.remove('off');
113
+ tab.textContent = ch.name;
114
+ } else {
115
+ tab.style.opacity = '0.35';
116
+ tab.textContent = ch.name + ' ✕';
117
+ }
118
+ }
119
+ });
120
+ }
121
+
122
+ function _vtvRetry(){
123
+ if(_vtvCurrentCh) _vtvPlay(_vtvCurrentCh);
124
+ }
125
+
126
+ function _vtvPlay(chId){
127
+ const ch = VTV_CHANNELS.find(c => c.id === chId);
128
+ if(!ch) return;
129
+ _vtvCurrentCh = chId;
130
+ document.querySelectorAll('.vtv-tab').forEach(t => t.classList.remove('on'));
131
+ const tab = document.getElementById('vtvt-'+chId);
132
+ if(tab) tab.classList.add('on');
133
+ const video = document.getElementById('vtv-player');
134
+ const errEl = document.getElementById('vtv-err');
135
+ const loadEl = document.getElementById('vtv-load');
136
+ const errMsg = document.getElementById('vtv-err-msg');
137
+ video.style.display = 'none';
138
+ errEl.style.display = 'none';
139
+ loadEl.style.display = 'flex';
140
+ loadEl.innerHTML = '<div class="vtv-spinner"></div>Đang kết nối ' + ch.name + '...';
141
+ if(_vtvHls){ _vtvHls.destroy(); _vtvHls = null; }
142
+ const urls = _vtvStreams[chId] || [];
143
+ if(urls.length === 0){
144
+ loadEl.style.display = 'none';
145
+ errEl.style.display = 'flex';
146
+ errMsg.textContent = chId === 'vtvprime' ? 'VTVPrime: Kênh trả phí.' : ch.name + ': Không tìm thấy luồng.';
147
+ return;
148
+ }
149
+ const epgWrap = document.getElementById('vtv-epg-wrap');
150
+ if(epgWrap) epgWrap.innerHTML = buildVTVEPG(chId);
151
+ _vtvTryPlay(video, urls, 0, ch.name, loadEl, errEl, errMsg);
152
+ }
153
+
154
+ function _vtvTryPlay(video, urls, idx, name, loadEl, errEl, errMsg){
155
+ if(idx >= urls.length){
156
+ loadEl.style.display = 'none';
157
+ errEl.style.display = 'flex';
158
+ errMsg.textContent = name + ': Tất cả nguồn đều lỗi. Thử lại sau.';
159
+ return;
160
+ }
161
+ const src = urls[idx];
162
+ loadEl.innerHTML = '<div class="vtv-spinner"></div>Đang kết nối ' + name + ' (' + (idx+1) + '/' + urls.length + ')...';
163
+ if(typeof Hls !== 'undefined' && Hls.isSupported()){
164
+ const hls = new Hls({enableWorker:true,lowLatencyMode:true,startLevel:-1,capLevelToPlayerSize:true,maxBufferLength:15,maxMaxBufferLength:30});
165
+ _vtvHls = hls;
166
+ hls.loadSource(src);
167
+ hls.attachMedia(video);
168
+ hls.on(Hls.Events.MANIFEST_PARSED, () => { video.play().catch(()=>{}); loadEl.style.display='none'; video.style.display='block'; });
169
+ let recAttempts = 0;
170
+ hls.on(Hls.Events.ERROR, (ev, data) => {
171
+ if(data.fatal){
172
+ if(data.type === Hls.ErrorTypes.NETWORK_ERROR){
173
+ recAttempts++;
174
+ if(recAttempts <= 2){ setTimeout(() => hls.startLoad(), 1500); }
175
+ else { hls.destroy(); _vtvHls = null; _vtvTryPlay(video, urls, idx+1, name, loadEl, errEl, errMsg); }
176
+ } else if(data.type === Hls.ErrorTypes.MEDIA_ERROR){
177
+ try { hls.recoverMediaError(); } catch(e) {}
178
+ } else { hls.destroy(); _vtvHls = null; _vtvTryPlay(video, urls, idx+1, name, loadEl, errEl, errMsg); }
179
+ }
180
+ });
181
+ } else if(video.canPlayType('application/vnd.apple.mpegurl')){
182
+ video.src = src;
183
+ video.addEventListener('loadedmetadata', () => { video.play().catch(()=>{}); loadEl.style.display='none'; video.style.display='block'; }, {once:true});
184
+ video.addEventListener('error', () => { _vtvTryPlay(video, urls, idx+1, name, loadEl, errEl, errMsg); }, {once:true});
185
+ } else {
186
+ loadEl.style.display = 'none'; errEl.style.display = 'flex'; errMsg.textContent = 'Trình duyệt không hỗ trợ HLS';
187
+ }
188
+ }
189
+
190
+ // === LOAD HOME ===
191
+ async function loadHome(){
192
+ // Load VTV streams in parallel (non-blocking)
193
+ loadVTVStreams();
194
+
195
+ const[featured,sh,wall,hlLeagues,ai,wcData]=await Promise.all([
196
+ fetch('/api/livescore/featured').then(r=>r.json()).catch(()=>null),
197
+ fetch('/api/shorts').then(r=>r.json()).catch(()=>[]),
198
+ fetch('/api/wall').then(r=>r.json()).catch(()=>({posts:[]})),
199
+ fetch('/api/highlights/leagues').then(r=>r.json()).catch(()=>({})),
200
+ fetch('/api/genk_ai').then(r=>r.json()).catch(()=>[]),
201
+ fetch('/api/wc2026').then(r=>r.json()).catch(()=>null)
202
+ ]);
203
+ _hlLeagueData=hlLeagues;
204
+ _wc2026Data=wcData;
205
+ _shortsData=interleaveShorts(sh||[]);
206
+ _wallPosts=(wall&&wall.posts)||[];
207
+ let h='';
208
+
209
+ // VTV BLOCK — first thing on homepage
210
+ h += buildVTVBlockHTML();
211
+
212
+ if(featured&&featured.home&&featured.event_id){
213
+ const sc=featured.status==='live'?'':'upcoming';
214
+ const st=featured.status==='live'?`🔴 ${featured.minute||'LIVE'}`:`⏰ ${featured.time}`;
215
+ const eid=String(featured.event_id||'').replace(/[<>&"']/g,'');
216
+ const mUrl=String(featured.url||'').replace(/[<>&"']/g,'');
217
+ const fH=String(featured.home||'').replace(/[<>&"']/g,'');
218
+ const fA=String(featured.away||'').replace(/[<>&"']/g,'');
219
+ const fL=String(featured.league||'').replace(/[<>&"']/g,'');
220
+ const fS=String(featured.score||'VS').replace(/[<>&"']/g,'');
221
+ const fHL=String(featured.home_logo||'').replace(/[<>&"']/g,'');
222
+ const fAL=String(featured.away_logo||'').replace(/[<>&"']/g,'');
223
+ h+=`<div class="featured-match" data-event-id="${eid}" data-url="${mUrl}" onclick="openMatch('${eid}','${mUrl}')" title="${fH} vs ${fA} — ${fL}">`+
224
+ `<div class="fm-league">${fL}</div>`+
225
+ `<div class="fm-teams">`+
226
+ `<div class="fm-team"><img src="${fHL}" onerror="this.style.display='none'"><span>${fH}</span></div>`+
227
+ `<div class="fm-score">${fS}</div>`+
228
+ `<div class="fm-team"><img src="${fAL}" onerror="this.style.display='none'"><span>${fA}</span></div>`+
229
+ `</div>`+
230
+ `<div class="fm-status ${sc}">${st}</div>`+
231
+ `</div>`;
232
+ }
233
+ h+=`<div class="ai-compose"><div class="ai-compose-title">🤖 AI viết bài</div><div class="ai-compose-row"><input id="topic-input" placeholder="Nhập chủ đề..."><button onclick="searchTopic()">Tìm nguồn</button></div><div class="ai-compose-row"><input id="url-input" placeholder="Dán URL bài viết..."><button class="secondary" onclick="rewriteUrl()">Rewrite</button></div><div id="hot-topics" class="hot-topic-row"></div></div>`;
234
+ h+='<div id="hashtag-box"></div>';
235
+ h+=`<div class="ls-section"><div class="ls-header"><h3>⚽ Livescore</h3></div><div class="ls-tabs"><span class="ls-tab active" data-tab="today" onclick="loadLivescore('today')">📅 Hôm nay</span><span class="ls-tab" data-tab="live" onclick="loadLivescore('live')">🔴 Live</span><span class="ls-tab" data-tab="incoming" onclick="loadLivescore('incoming')">⏰ Sắp tới</span><span class="ls-tab" data-tab="results" onclick="loadLivescore('results')">✅ Kết quả</span><span class="ls-tab" data-tab="bxh_nha" onclick="loadLivescore('bxh_nha')">🏆 NHA</span><span class="ls-tab" data-tab="bxh_laliga" onclick="loadLivescore('bxh_laliga')">🏆 La Liga</span></div><div class="ls-content" id="ls-content"><div class="loading">Đang tải...</div></div></div>`;
236
+ h+=`<div id="wc2026-live-section" class="wc2026-section"><div class="wc-header"><h2>🏆 World Cup 2026</h2><span class="wc-live-badge">● LIVE</span></div><div class="wc-tabs"><span class="wc-tab active" onclick="switchWCTab('news')">📰 Tin tức</span><span class="wc-tab" onclick="switchWCTab('fixtures')">📅 Lịch thi đấu</span><span class="wc-tab" onclick="switchWCTab('standings')">🏆 BXH</span><span class="wc-tab" onclick="switchWCTab('highlights')">🎬 Highlight</span><span class="wc-tab" onclick="switchWCTab('stats')">📊 Thống kê</span></div><div class="wc-content" id="wc-content"><div class="loading">Đang tải World Cup 2026...</div></div></div>`;
237
+ const wallPosts=_wallPosts;
238
+ const aiShorts=wallPosts.filter(p=>p.video);
239
+ if(aiShorts.length){h+='<div class="slider-wrap"><div class="slider-header"><span class="slider-label">🎬 Short AI</span></div><div class="slider-track">';aiShorts.slice(0,20).forEach((p,i)=>{h+=`<div class="slider-item shorts-item" onclick="openShortAIFeed(${i})"><div class="slider-thumb shorts-thumb"><video src="${p.video}" muted preload="metadata"></video><div class="card-play">▶</div></div><div class="slider-title">${esc(p.title)}</div></div>`});h+='</div></div>';}
240
+ if(_shortsData.length){h+='<div class="slider-wrap"><div class="slider-header"><span class="slider-label">📱 Shorts Dân trí & SKĐS</span><span class="slider-note">Mới nhất · xen kẽ</span></div><div class="slider-track">';_shortsData.slice(0,30).forEach((a,i)=>{const badge=a.channel==='baosuckhoedoisongboyte'?'SKĐS':'Dân trí';h+=`<div class="slider-item shorts-item" onclick="openYTShortsFeed(${i})"><div class="slider-thumb shorts-thumb">${a.img?`<img src="${a.img}">`:''}<div class="card-play">▶</div></div><div class="slider-title"><span style="color:#f0c040;font-size:8px">${badge}</span> ${esc(a.title)}</div></div>`});h+='</div></div>';}
241
+ if(wallPosts.length){h+=`<div class="slider-wrap" id="ai-wall-wrap"><div class="slider-header"><span class="slider-label">🧱 Tường AI</span></div><div class="slider-track" id="ai-wall-track">`;wallPosts.slice(0,20).forEach((p,i)=>{h+=makeWallItem(p,i)});h+='</div></div>';}
242
+ const HL_CONFIG={"world-cup":{name:"World Cup 2026",emoji:"🌍"},"premier-league":{name:"Premier League",emoji:"🏴"},"champions-league":{name:"Champions League",emoji:"⭐"},"la-liga":{name:"La Liga",emoji:"🇪🇸"},"serie-a":{name:"Serie A",emoji:"🇮🇹"},"bundesliga":{name:"Bundesliga",emoji:"🇩🇪"},"friendly":{name:"Giao hữu",emoji:"🤝"}};
243
+ for(const[key,cfg] of Object.entries(HL_CONFIG)){const vids=hlLeagues[key];if(!vids||!vids.length)continue;h+=`<div class="slider-wrap"><div class="slider-header"><span class="slider-label">${cfg.emoji} ${cfg.name}</span></div><div class="slider-track">`;vids.slice(0,8).forEach((a,i)=>{h+=`<div class="slider-item" onclick="openHighlightFeed('${key}',${i})"><div class="slider-thumb">${a.img?`<img src="${a.img}">`:''}<div class="card-play">▶</div></div><div class="slider-title">${esc(a.title)}</div></div>`});h+='</div></div>';}
244
+ if(ai&&ai.length){h+='<div class="slider-wrap"><div class="slider-header"><span class="slider-label">🤖 Ứng dụng AI</span></div><div class="slider-track">';ai.slice(0,12).forEach(a=>{h+=`<div class="slider-item" onclick="readArticle('${esc(a.link)}')"><div class="slider-thumb">${a.img?`<img src="${a.img}">`:''}</div><div class="slider-title">${esc(a.title)}</div></div>`});h+='</div></div>';}
245
+ document.getElementById('view-home').innerHTML=h;
246
+ loadLivescore('today');loadHotTopics();
247
+ if(_wc2026Data)switchWCTab('news');
248
+ }
249
+
250
+ // === WALL POST HELPERS ===
251
+ function makeWallItem(p,i){
252
+ const hasVideo = p.video && p.video.length > 0;
253
+ const thumbContent = p.img
254
+ ? `<img src="${esc(p.img)}" onerror="this.style.display='none'">`
255
+ : (hasVideo ? `<video src="${esc(p.video)}" muted></video>` : '');
256
+ const videoBadge = hasVideo
257
+ ? `<div class="wall-video-badge">🎬</div>`
258
+ : '';
259
+ const videoBtn = hasVideo
260
+ ? `<button class="wall-btn-video" onclick="event.stopPropagation();openShortAIFeed(${i})">▶ Xem Short</button>`
261
+ : `<button class="wall-btn-make" onclick="event.stopPropagation();makeShortVideo('${esc(p.id||i)}',this)">🎬 Tạo Video</button>`;
262
+
263
+ return `<div class="wall-item" id="wall-item-${esc(p.id||i)}">
264
+ <div class="wall-thumb">
265
+ ${thumbContent}
266
+ ${videoBadge}
267
+ </div>
268
+ <div class="wall-title">${esc(p.title)}</div>
269
+ <div class="wall-text">${esc((p.text||'').slice(0,180))}</div>
270
+ <div class="wall-actions">
271
+ <button class="primary" onclick="readWallPost(${i})">Xem</button>
272
+ ${videoBtn}
273
+ </div>
274
+ </div>`;
275
+ }
276
+
277
+ // === GENERATE SHORT VIDEO FOR A WALL POST ===
278
+ async function makeShortVideo(postId, btn, voice, speed){
279
+ if(!postId)return;
280
+ const origText = btn ? btn.textContent : '🎬 Tạo Video';
281
+ if(btn){btn.disabled=true;btn.textContent='⏳ Đang tạo...';}
282
+ toast('⏳ Đang tạo video shorts...');
283
+ try{
284
+ let url = '/api/ai/short/'+encodeURIComponent(postId);
285
+ const params = [];
286
+ if(voice) params.push('voice='+encodeURIComponent(voice));
287
+ if(speed) params.push('speed='+encodeURIComponent(speed));
288
+ if(params.length) url += '?' + params.join('&');
289
+ const r = await fetch(url, {method:'POST'});
290
+ const j = await r.json();
291
+ if(!r.ok || j.error) throw new Error(j.error||'Lỗi tạo video');
292
+ toast('✅ Đã tạo video shorts!');
293
+ const p = _wallPosts.find(x => String(x.id) === String(postId));
294
+ if(p){
295
+ p.video = j.video;
296
+ const itemId = 'wall-item-'+postId;
297
+ const el = document.getElementById(itemId);
298
+ if(el){
299
+ const idx = _wallPosts.indexOf(p);
300
+ el.outerHTML = makeWallItem(p, idx);
301
+ const newEl = document.getElementById(itemId);
302
+ if(newEl) newEl.className = 'wall-item wall-item-new';
303
+ }
304
+ }
305
+ refreshShortAISlider();
306
+ }catch(e){
307
+ toast('❌ '+e.message);
308
+ if(btn){btn.disabled=false;btn.textContent=origText;}
309
+ }
310
+ }
311
+
312
+ // Refresh Short AI slider after video generation
313
+ function refreshShortAISlider(){
314
+ const aiShorts = _wallPosts.filter(p=>p.video);
315
+ let shortAISection = document.getElementById('short-ai-section');
316
+ if(aiShorts.length === 0){
317
+ if(shortAISection) shortAISection.remove();
318
+ return;
319
+ }
320
+ if(shortAISection){
321
+ const track = shortAISection.querySelector('.slider-track');
322
+ if(track){
323
+ let h = '';
324
+ aiShorts.slice(0,20).forEach((p,i)=>{
325
+ h+=`<div class="slider-item shorts-item" onclick="openShortAIFeed(${i})"><div class="slider-thumb shorts-thumb"><video src="${esc(p.video)}" muted preload="metadata"></video><div class="card-play">▶</div></div><div class="slider-title">${esc(p.title)}</div></div>`;
326
+ });
327
+ track.innerHTML = h;
328
+ }
329
+ }
330
+ }
331
+
332
+ function prependWallPost(post){
333
+ _wallPosts.unshift(post);
334
+ const track=document.getElementById('ai-wall-track');
335
+ const wrap=document.getElementById('ai-wall-wrap');
336
+ const homeEl=document.getElementById('view-home');
337
+ if(!track||!wrap){
338
+ if(homeEl){
339
+ let insertBefore=homeEl.querySelector('.slider-wrap');
340
+ const newWrap=document.createElement('div');
341
+ newWrap.className='slider-wrap';
342
+ newWrap.id='ai-wall-wrap';
343
+ newWrap.innerHTML=`<div class="slider-header"><span class="slider-label">🧱 Tường AI</span></div><div class="slider-track" id="ai-wall-track">${makeWallItem(post,0)}</div>`;
344
+ if(insertBefore){
345
+ homeEl.insertBefore(newWrap,insertBefore);
346
+ }else{
347
+ homeEl.appendChild(newWrap);
348
+ }
349
+ const firstItem=newWrap.querySelector('.wall-item');
350
+ if(firstItem)firstItem.className='wall-item wall-item-new';
351
+ }
352
+ return;
353
+ }
354
+ const div=document.createElement('div');
355
+ div.className='wall-item wall-item-new';
356
+ div.id='wall-item-'+(post.id||'new-'+Date.now());
357
+ const hasVideo = post.video && post.video.length > 0;
358
+ const thumbContent = post.img
359
+ ? `<img src="${esc(post.img)}" onerror="this.style.display='none'">`
360
+ : (hasVideo ? `<video src="${esc(post.video)}" muted></video>` : '');
361
+ const videoBadge = hasVideo ? `<div class="wall-video-badge">🎬</div>` : '';
362
+ const videoBtn = hasVideo
363
+ ? `<button class="wall-btn-video" onclick="event.stopPropagation();openShortAIFeed(0)">▶ Xem Short</button>`
364
+ : `<button class="wall-btn-make" onclick="event.stopPropagation();makeShortVideo('${esc(post.id)}',this)">🎬 Tạo Video</button>`;
365
+ div.innerHTML=`<div class="wall-thumb">${thumbContent}${videoBadge}</div><div class="wall-title">${esc(post.title)}</div><div class="wall-text">${esc((post.text||'').slice(0,180))}</div><div class="wall-actions"><button class="primary" onclick="readWallPost(0)">Xem</button>${videoBtn}</div>`;
366
+ track.prepend(div);
367
+ track.scrollTo({left:0,behavior:'smooth'});
368
+ if(hasVideo) refreshShortAISlider();
369
+ }
370
+
371
+ // === REST OF FUNCTIONS ===
372
+ let _shortsData=[];
373
+ let _wallPosts=[];
374
+ let _currentView='home';
375
+ let _currentEventId=null;
376
+ let _currentMatchUrl=null;
377
+ function interleaveShorts(shorts){const dt=shorts.filter(s=>s.channel==='baodantri7941');const sk=shorts.filter(s=>s.channel==='baosuckhoedoisongboyte');const result=[];let i=0,j=0;while(i<dt.length||j<sk.length){if(i<dt.length)result.push(dt[i++]);if(j<sk.length)result.push(sk[j++]);}return result;}
378
+ let _htPage=0,_htTopic='';
379
+ async function loadHotTopics(){const j=await fetch('/api/hot_topics').then(r=>r.json()).catch(()=>({topics:[]}));const el=document.getElementById('hot-topics');if(!el)return;el.innerHTML=(j.topics||[]).slice(0,18).map(t=>{const topicText=t.topic||t.label.replace(/^#/,'');return`<button class="hot-chip" onclick="searchTopic('${topicText.replace(/'/g,"\\'")}')">${esc(t.label)}</button>`;}).join('');if(j.topics&&j.topics[0]){const firstTopic=j.topics[0].topic||j.topics[0].label.replace(/^#/,'');setTimeout(()=>searchTopic(firstTopic),800);}}
380
+ function searchTopic(topic){if(!topic){topic=document.getElementById('topic-input')?.value.trim();if(!topic){alert('Nhập chủ đề');return;}}document.getElementById('topic-input').value='';_htTopic=topic;_htPage=0;showHashtagSources(topic,0);}
381
+ async function showHashtagSources(topic,page){const box=document.getElementById('hashtag-box');if(!box)return;if(page===0)box.innerHTML=`<div class="hashtag-sources"><h3>🔍 ${esc(topic)}</h3><div class="hashtag-loading"><div class="hashtag-spinner"></div>Đang tìm...</div></div>`;try{const r=await fetch(`/api/hashtag/sources?topic=${encodeURIComponent(topic)}&page=${page}`);const j=await r.json();const sources=j.sources||[];if(!sources.length&&page===0){box.innerHTML=`<div class="hashtag-sources"><h3>🔍 ${esc(topic)}</h3><div style="color:#888;padding:8px">Không tìm được bài viết liên quan</div></div>`;return;}let h='';if(page===0)h=`<div class="hashtag-sources"><h3>🔍 ${esc(topic)} <span style="font-size:10px;color:#888">(${j.total} bài từ 8 nguồn)</span></h3><div id="ht-list">`;sources.forEach((s,i)=>{const idx=page*8+i;h+=`<div class="hashtag-src-item" onclick="readArticle('${esc(s.url)}')"><div class="hashtag-src-img" id="ht-img-${idx}"></div><div class="hashtag-src-text"><div class="hashtag-src-title">${esc(s.title)}</div><div class="hashtag-src-via">${esc(s.via||'')}</div></div></div>`;});if(page===0){h+=`</div><button class="hashtag-rewrite-btn" onclick="rewriteHashtag('${esc(topic).replace(/'/g,"\\'")}')">🤖 Rewrite AI tổng hợp & đăng tường</button>`;if(j.has_more)h+=`<button class="hashtag-load-more" id="ht-more" onclick="loadMoreHashtag()">Tải thêm ▼</button>`;h+=`</div>`;box.innerHTML=h;}else{document.getElementById('ht-list')?.insertAdjacentHTML('beforeend',h);const btn=document.getElementById('ht-more');if(btn){if(!j.has_more)btn.remove();else{btn.disabled=false;btn.textContent='Tải thêm ▼';}}}sources.forEach((s,i)=>{const idx=page*8+i;if(!s.url)return;fetch('/api/article?url='+encodeURIComponent(s.url)).then(r=>r.json()).then(d=>{if(d&&(d.og_image||d.img)){const el=document.getElementById('ht-img-'+idx);if(el)el.innerHTML=`<img src="${esc(d.og_image||d.img)}" onerror="this.style.display='none'">`;}}).catch(()=>{});});}catch(e){box.innerHTML=`<div class="hashtag-sources"><h3>🔍 ${esc(topic)}</h3><div style="color:#e74c3c;padding:8px">Lỗi: ${esc(e.message)}</div></div>`;}}
382
+ function loadMoreHashtag(){_htPage++;const btn=document.getElementById('ht-more');if(btn){btn.disabled=true;btn.textContent='Đang tải...';}showHashtagSources(_htTopic,_htPage);}
383
+ async function rewriteHashtag(topic){const btn=event?.target;if(btn){btn.disabled=true;btn.textContent='Đang tổng hợp...';}try{const r=await fetch('/api/topic_post',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({topic})});const j=await r.json();if(!r.ok||j.error)throw new Error(j.error||'Lỗi');toast('✅ Đã đăng Tường AI!');if(btn)btn.textContent='✅ Đăng thành công!';if(j.post)prependWallPost(j.post);}catch(e){toast('❌ '+e.message);if(btn){btn.disabled=false;btn.textContent='🤖 Rewrite AI';}}}
384
+ async function loadLivescore(tab){document.querySelectorAll('.ls-tab').forEach(t=>t.classList.remove('active'));document.querySelector(`.ls-tab[data-tab="${tab}"]`)?.classList.add('active');const el=document.getElementById('ls-content');if(!el)return;el.innerHTML='<div class="loading">Đang tải...</div>';let ep='/api/livescore/'+tab;if(tab.startsWith('bxh_'))ep='/api/livescore/standings/'+tab.replace('bxh_','');try{const r=await fetch(ep);const d=await r.json();el.innerHTML=d.html&&d.html.length>50?d.html:'<div class="loading">Không có dữ liệu</div>';bindMatchClicks(el);}catch(e){el.innerHTML='<div class="loading">Lỗi</div>';}}
385
+ function bindMatchClicks(el){
386
+ if(!el) return;
387
+ el.querySelectorAll('.match-detail').forEach(md=>{
388
+ if(md._bound) return;
389
+ md._bound = true;
390
+ md.style.cursor='pointer';
391
+ md.addEventListener('click',function(e){
392
+ // Skip if clicking directly on a link
393
+ if(e.target.closest('a')) return;
394
+ const statusA=this.querySelector('.status a');
395
+ const teamA=this.querySelector('.teams a[href*="/tran-dau/"]');
396
+ const a = statusA || teamA;
397
+ if(a){
398
+ e.preventDefault();
399
+ e.stopPropagation();
400
+ const href=a.getAttribute('href')||'';
401
+ const m=href.match(/\/tran-dau\/(\d+)\//);
402
+ if(m){
403
+ const fullUrl=href.startsWith('http')?href:'https://bongda.com.vn'+href;
404
+ openMatch(m[1],fullUrl);
405
+ }
406
+ }
407
+ });
408
+ });
409
+ }
410
+ function openMatch(id,url){if(!id)return;_currentEventId=id;if(url)_currentMatchUrl=url;document.getElementById('match-overlay').classList.add('active');document.body.style.overflow='hidden';loadMatchTab('detail')}
411
+ function closeMatch(){document.getElementById('match-overlay').classList.remove('active');document.body.style.overflow=''}
412
+ async function loadMatchTab(tab){document.querySelectorAll('.mo-tab').forEach(t=>t.classList.remove('active'));document.querySelectorAll('.mo-tab').forEach(t=>{if((tab==='comm'&&t.textContent==='Diễn biến')||(tab==='stats'&&t.textContent==='Thống kê')||(tab==='detail'&&t.textContent.includes('Chi tiết')))t.classList.add('active')});const el=document.getElementById('mo-body');if(!el)return;el.innerHTML='<div class="loading">Đang tải...</div>';try{let apiUrl;if(tab==='stats')apiUrl=`/api/match/${_currentEventId}/stats`;else if(tab==='comm')apiUrl=`/api/match/${_currentEventId}/commentaries`;else{apiUrl=`/api/match/${_currentEventId}/detail`;if(_currentMatchUrl)apiUrl+='?url='+encodeURIComponent(_currentMatchUrl)}const r=await fetch(apiUrl);if(!r.ok){el.innerHTML='<div class="loading">Lỗi máy chủ ('+r.status+')</div>';return}const d=await r.json();if(d.error){el.innerHTML='<div class="loading">'+esc(d.error)+'</div>';return}if(tab==='detail'&&typeof renderMatchDetail==='function'){renderMatchDetail(el,d);return}el.innerHTML=d.html||'<div class="loading">Không có dữ liệu</div>'}catch(e){el.innerHTML='<div class="loading">Lỗi</div>'}}
413
+ async function doInteract(videoId,type){try{const r=await fetch('/api/v2/interact',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id:videoId,type})});return await r.json();}catch(e){return null;}}
414
+ async function getInteractions(videoId){try{return await fetch('/api/v2/interactions?id='+encodeURIComponent(videoId)).then(r=>r.json());}catch(e){return{views:0,likes:0,comments:0};}}
415
+ async function getComments(videoId){try{const j=await fetch('/api/v2/comments?id='+encodeURIComponent(videoId)).then(r=>r.json());return j.comments||[];}catch(e){return[];}}
416
+ async function postComment(videoId,text){try{const j=await fetch('/api/v2/comment',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id:videoId,text})}).then(r=>r.json());return j.comments||[];}catch(e){return[];}}
417
+ function buildTikTokSlide(opts){return`<div class="tiktok-slide" data-vid="${esc(opts.videoId)}">${opts.vtag}<div class="tiktok-bottom"><span class="badge ${opts.badgeClass||'badge-fpt'}">${opts.badge||''}</span><p class="tiktok-title">${esc(opts.title)}</p></div><div class="tiktok-right"><button class="tiktok-right-btn" onclick="event.stopPropagation();doView('${esc(opts.videoId)}',this)"><div class="icon">👁</div><div class="count" id="vc-${opts.idx}">0</div></button><button class="tiktok-right-btn" onclick="event.stopPropagation();doLike('${esc(opts.videoId)}',this)"><div class="icon">❤️</div><div class="count" id="lc-${opts.idx}">0</div></button><button class="tiktok-right-btn" onclick="event.stopPropagation();toggleComments('${esc(opts.videoId)}',${opts.idx})"><div class="icon">💬</div><div class="count" id="cc-${opts.idx}">0</div></button><button class="tiktok-right-btn" onclick="event.stopPropagation();doShare('${esc(opts.title)}','${esc(opts.shareUrl||'')}','')"><div class="icon">📤</div></button>${opts.extraBtn||''}</div><span class="tiktok-counter">${opts.idx+1}/${opts.total}</span><div class="inline-comments" id="cmt-inline-${opts.idx}" style="display:none"></div></div>`;}
418
+ async function doView(videoId,btn){const j=await doInteract(videoId,'view');if(j){const c=btn.querySelector('.count');if(c)c.textContent=fmtNum(j.views);}}
419
+ async function doLike(videoId,btn){const j=await doInteract(videoId,'like');if(j){const c=btn.querySelector('.count');if(c)c.textContent=fmtNum(j.likes);}}
420
+ function fmtNum(n){if(!n)return'0';if(n>=1000000)return(n/1000000).toFixed(1)+'M';if(n>=1000)return(n/1000).toFixed(1)+'K';return String(n);}
421
+ async function loadCounters(videoIds){for(let i=0;i<videoIds.length;i++){const id=videoIds[i];if(!id)continue;const j=await getInteractions(id);const vc=document.getElementById('vc-'+i);if(vc)vc.textContent=fmtNum(j.views);const lc=document.getElementById('lc-'+i);if(lc)lc.textContent=fmtNum(j.likes);const cc=document.getElementById('cc-'+i);if(cc)cc.textContent=fmtNum(j.comments);}}
422
+ async function toggleComments(videoId,idx){const panel=document.getElementById('cmt-inline-'+idx);if(!panel)return;if(panel.style.display!=='none'){panel.style.display='none';return;}panel.style.display='block';panel.innerHTML='<div style="padding:8px;color:#888;font-size:11px">Đang tải...</div>';const cmts=await getComments(videoId);renderInlineComments(panel,videoId,idx,cmts);}
423
+ function renderInlineComments(panel,videoId,idx,cmts){let h='<div class="inline-cmt-header"><span>💬 Bình luận</span><button onclick="document.getElementById(\'cmt-inline-'+idx+'\').style.display=\'none\'">✕</button></div><div class="inline-cmt-list">';if(cmts.length){cmts.slice(-30).forEach(c=>{h+=`<div class="inline-cmt-item"><span class="inline-cmt-time">${c.time||''}</span>${esc(c.text)}</div>`;});}else{h+='<div style="color:#777;font-size:11px;padding:4px">Chưa có bình luận</div>';}h+=`</div><div class="inline-cmt-input"><input id="cmt-input-${idx}" placeholder="Viết bình luận..." onkeydown="if(event.key==='Enter')submitInlineCmt('${esc(videoId)}',${idx})"><button onclick="submitInlineCmt('${esc(videoId)}',${idx})">Gửi</button></div>`;panel.innerHTML=h;const list=panel.querySelector('.inline-cmt-list');if(list)list.scrollTop=list.scrollHeight;}
424
+ async function submitInlineCmt(videoId,idx){const inp=document.getElementById('cmt-input-'+idx);if(!inp)return;const text=inp.value.trim();if(!text)return;inp.value='';inp.disabled=true;const cmts=await postComment(videoId,text);inp.disabled=false;const panel=document.getElementById('cmt-inline-'+idx);if(panel)renderInlineComments(panel,videoId,idx,cmts);const cc=document.getElementById('cc-'+idx);if(cc)cc.textContent=fmtNum(cmts.length);}
425
+ function initTikTokFeed(){const feed=document.getElementById('tiktok-feed');if(!feed)return;const slides=feed.querySelectorAll('.tiktok-slide');let cur=-1;function act(i){if(i===cur)return;slides.forEach((sl,idx)=>{const v=sl.querySelector('video');const fr=sl.querySelector('iframe');if(idx===i){if(v&&v.dataset.hls&&!v._hls&&typeof Hls!=='undefined'&&Hls.isSupported()){const hls=new Hls();hls.loadSource(v.dataset.hls);hls.attachMedia(v);hls.on(Hls.Events.MANIFEST_PARSED,()=>v.play().catch(()=>{}));v._hls=hls}else if(v)v.play().catch(()=>{});if(fr&&!fr.src&&fr.dataset.ytSrc)fr.src=fr.dataset.ytSrc;const vid=sl.dataset.vid;if(vid&&!sl._viewed){sl._viewed=true;doInteract(vid,'view').then(j=>{if(j){const vc=document.getElementById('vc-'+idx);if(vc)vc.textContent=fmtNum(j.views);}});}}else{if(v){v.pause();if(v._hls){v._hls.destroy();v._hls=null}}if(fr&&fr.src)fr.src=''}});cur=i}let sT;feed.addEventListener('scroll',()=>{clearTimeout(sT);sT=setTimeout(()=>{const rect=feed.getBoundingClientRect(),ctr=rect.top+rect.height/2;let best=-1,bestD=1e9;slides.forEach((sl,i)=>{const d=Math.abs(sl.getBoundingClientRect().top+sl.getBoundingClientRect().height/2-ctr);if(d<bestD){bestD=d;best=i}});if(best>=0)act(best)},150)});setTimeout(()=>act(0),400);slides.forEach(sl=>{const v=sl.querySelector('video');if(v)v.addEventListener('click',e=>{e.preventDefault();v.paused?v.play().catch(()=>{}):v.pause()})});const ids=[...slides].map(sl=>sl.dataset.vid||'');loadCounters(ids)}
426
+ async function openHighlightFeed(league,idx){showView('view-tiktok');const el=document.getElementById('view-tiktok');el.innerHTML='<div class="loading">Đang tải...</div>';let articles=(_hlLeagueData||{})[league]||[];if(!articles.length){try{articles=await fetch('/api/highlights/'+league).then(r=>r.json())}catch(e){articles=[]}}if(!articles.length){el.innerHTML='<div class="loading">Không có video</div>';return}const vids=[];const results=await Promise.all(articles.map(async(a,i)=>{try{const r=await fetch('/api/video_url?url='+encodeURIComponent(a.link));const v=await r.json();if(v&&v.src)return{...a,...v,_idx:i}}catch(e){}return null}));results.forEach(r=>{if(r)vids.push(r)});vids.sort((a,b)=>a._idx-b._idx);if(!vids.length){el.innerHTML='<div class="loading">Không tìm thấy video</div>';return}let ti=vids.findIndex(v=>v._idx===idx);if(ti<0)ti=0;const ordered=ti>0?[...vids.slice(ti),...vids.slice(0,ti)]:vids;let h=`<button class="back-btn" onclick="switchCat('home')">← Highlight</button><div class="tiktok-container"><div class="tiktok-feed" id="tiktok-feed">`;ordered.forEach((v,i)=>{const isYT=v.type==='youtube',isHLS=!isYT&&v.src?.includes('.m3u8'),poster=v.poster?` poster="${v.poster}"`:'';const vtag=isYT?`<iframe data-yt-src="${v.src}" allowfullscreen allow="accelerometer;autoplay;clipboard-write;encrypted-media;gyroscope;picture-in-picture"></iframe>`:isHLS?`<video playsinline preload="none"${poster} data-hls="${v.src}" loop controls></video>`:`<video playsinline preload="none"${poster} loop controls><source src="${v.src}" type="video/mp4"></video>`;const videoId='hl-'+league+'-'+(v.id||v._idx);h+=buildTikTokSlide({vtag,title:v.title,badge:'HL',badgeClass:'badge-fpt',videoId,idx:i,total:ordered.length,shareUrl:v.link||'',extraBtn:`<button class="tiktok-right-btn" onclick="event.stopPropagation();this.closest('.tiktok-slide').classList.toggle('ratio-wide')"><div class="icon">⬜</div><div class="count">16:9</div></button>`});});h+='</div></div>';el.innerHTML=h;initTikTokFeed();}
427
+ async function openYTShortsFeed(startIdx){showView('view-tiktok');const el=document.getElementById('view-tiktok');el.innerHTML='<div class="loading">Đang tải...</div>';const arts=_shortsData.length?_shortsData:await fetch('/api/shorts').then(r=>r.json()).catch(()=>[]);if(!arts.length){el.innerHTML='<div class="loading">Không có shorts</div>';return}const ordered=startIdx>0?[...arts.slice(startIdx),...arts.slice(0,startIdx)]:arts;let h=`<button class="back-btn" onclick="switchCat('home')">← Shorts</button><div class="tiktok-container"><div class="tiktok-feed" id="tiktok-feed">`;ordered.forEach((v,i)=>{const id=v.id||'';const src=`https://www.youtube.com/embed/${id}?autoplay=1&rel=0&playsinline=1`;const vtag=`<iframe data-yt-src="${src}" allowfullscreen allow="accelerometer;autoplay;clipboard-write;encrypted-media;gyroscope;picture-in-picture"></iframe>`;const badge=v.channel==='baosuckhoedoisongboyte'?'SKĐS':'Dân trí';const videoId='yt-'+id;h+=buildTikTokSlide({vtag,title:v.title,badge,badgeClass:'badge-fpt',videoId,idx:i,total:ordered.length,shareUrl:'https://youtube.com/watch?v='+id});});h+='</div></div>';el.innerHTML=h;initTikTokFeed();}
428
+ async function openShortAIFeed(startIdx){showView('view-tiktok');const el=document.getElementById('view-tiktok');el.innerHTML='<div class="loading">Đang tải...</div>';const wall=(await fetch('/api/wall').then(r=>r.json()).catch(()=>({posts:[]}))).posts||[];const vids=wall.filter(p=>p.video);if(!vids.length){el.innerHTML='<div class="loading">Chưa có Short AI</div>';return}const ordered=startIdx>0?[...vids.slice(startIdx),...vids.slice(0,startIdx)]:vids;let h=`<button class="back-btn" onclick="switchCat('home')">← Short AI</button><div class="tiktok-container"><div class="tiktok-feed" id="tiktok-feed">`;ordered.forEach((p,i)=>{const vtag=`<video src="${p.video}" playsinline loop controls></video>`;const videoId='ai-'+(p.id||i);h+=buildTikTokSlide({vtag,title:p.title,badge:'AI',badgeClass:'badge-ai',videoId,idx:i,total:ordered.length,shareUrl:SPACE});});h+='</div></div>';el.innerHTML=h;initTikTokFeed();}
429
+ async function readArticle(url){showView('view-article');const el=document.getElementById('view-article');el.innerHTML='<div class="loading">Đang tải...</div>';try{const r=await fetch('/api/article?url='+encodeURIComponent(url));const data=await r.json();if(data&&!data.error&&data.body&&data.body.length){_currentArticle={url,data};let h=`<button class="back-btn" onclick="switchCat('home')">← Quay lại</button><div class="article-view"><h1 class="article-title">${esc(data.title)}</h1>`;if(data.summary)h+=`<div class="article-summary">${esc(data.summary)}</div>`;const seen={};data.body.forEach(b=>{if(b.type==='p')h+=`<p class="article-p">${b.text}</p>`;else if(b.type==='img'&&b.src&&!seen[b.src]){seen[b.src]=1;h+=`<img class="article-img" src="${esc(b.src)}" onerror="this.style.display='none'">`}else if(b.type==='heading')h+=`<h2 class="article-h2">${esc(b.text)}</h2>`});h+=`<div class="article-actions"><button class="primary" onclick="rewriteArticle()">🤖 Rewrite AI đăng tường</button><button onclick="doShare('${esc(data.title)}','${esc(url)}','${esc(data.og_image||'')}')">📤</button><button onclick="window.open('${esc(url)}','_blank')">🔗 Gốc</button></div><div class="article-ai-ask"><h3 style="font-size:14px;color:#5cb87a">🤖 Hỏi AI</h3><textarea id="ask-q" placeholder="Hỏi về bài viết..."></textarea><button onclick="askAI()">Hỏi</button><div id="ask-a" class="article-ai-answer"></div></div></div>`;el.innerHTML=h;window.scrollTo(0,0);return;}}catch(e){}el.innerHTML=`<button class="back-btn" onclick="switchCat('home')">← Quay lại</button><div class="loading"><p>Không đọc được.</p><a href="${esc(url)}" target="_blank" style="color:#5cb87a">Mở gốc →</a></div>`;}
430
+ async function rewriteArticle(){const url=_currentArticle?.url;if(!url)return;toast('⏳ Đang rewrite...');try{const r=await fetch('/api/rewrite_share',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url,context:document.querySelector('.article-view')?.innerText?.slice(0,14000)||''})});const j=await r.json();if(!r.ok||j.error)throw new Error(j.error);toast('✅ Đã đăng Tường AI!');if(j.post)prependWallPost(j.post);}catch(e){toast('❌ '+e.message)}}
431
+ async function rewriteUrl(){const url=document.getElementById('url-input')?.value.trim();if(!url)return alert('Dán URL');toast('⏳ Đang rewrite...');try{const r=await fetch('/api/url_wall',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url})});const j=await r.json();if(!r.ok||j.error)throw new Error(j.error);toast('✅ Đã đăng!');document.getElementById('url-input').value='';if(j.post)prependWallPost(j.post);}catch(e){toast('❌ '+e.message)}}
432
+ async function askAI(){const q=document.getElementById('ask-q')?.value.trim();if(!q)return alert('Nhập câu hỏi');const a=document.getElementById('ask-a');a.textContent='Đang hỏi...';try{const r=await fetch('/api/article/ask',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url:_currentArticle?.url||'',question:q,context:document.querySelector('.article-view')?.innerText?.slice(0,12000)||''})});const j=await r.json();a.textContent=j.answer||'Không trả lời được';}catch(e){a.textContent='Lỗi: '+e.message}}
433
+ async function readWallPost(i){const p=_wallPosts[i];if(!p)return;showView('view-article');
434
+ const images = p.images || [];
435
+ let imgGallery = '';
436
+ if(images.length > 0){
437
+ imgGallery = '<div class="article-image-gallery">';
438
+ images.forEach((imgUrl, idx) => {
439
+ if(idx === 0){
440
+ imgGallery += `<img class="article-img article-hero-img" src="${esc(imgUrl)}" onerror="this.style.display='none" loading="eager">`;
441
+ } else {
442
+ if(idx === 1) imgGallery += '<div class="gallery-thumbs">';
443
+ imgGallery += `<div class="gallery-thumb"><img src="${esc(imgUrl)}" onerror="this.parentElement.style.display='none'" loading="lazy"></div>`;
444
+ }
445
+ });
446
+ if(images.length > 1) imgGallery += '</div>';
447
+ imgGallery += '</div>';
448
+ }
449
+ const hasVideo = p.video && p.video.length > 0;
450
+ const voiceOptions = [
451
+ {id:'hoaimy', label:'🎙️ Nữ — Hoài My'},
452
+ {id:'namminh', label:'🎙️ Nam — Nam Minh'},
453
+ ];
454
+ let voiceSelector = '';
455
+ if(!hasVideo){
456
+ voiceSelector = `<div class="tts-selector"><div class="tts-selector-label">🎙️ Chọn giọng đọc:</div><div class="tts-voice-btns">`;
457
+ voiceOptions.forEach(v=>{
458
+ voiceSelector += `<button class="tts-voice-btn" onclick="document.querySelectorAll('.tts-voice-btn').forEach(b=>b.classList.remove('active'));this.classList.add('active');document.getElementById('selected-voice').value='${v.id}'">${v.label}</button>`;
459
+ });
460
+ voiceSelector += `</div><div class="tts-speed-row"><span>Tốc độ:</span><select id="selected-speed"><option value="1.0">1.0x — Bình thường</option><option value="1.2" selected>1.2x — Nhanh</option><option value="1.5">1.5x — Rất nhanh</option><option value="0.8">0.8x — Chậm</option></select></div>`;
461
+ voiceSelector += `<input type="hidden" id="selected-voice" value="hoaimy"></div>`;
462
+ }
463
+ document.getElementById('view-article').innerHTML=`<button class="back-btn" onclick="switchCat('home')">← Quay lại</button><div class="article-view"><span class="badge badge-ai">AI</span><h1 class="article-title">${esc(p.title)}</h1>${imgGallery}<p class="article-p" style="white-space:pre-wrap">${esc(p.text)}</p>${hasVideo?`<video class="article-img" src="${esc(p.video)}" controls playsinline style="max-height:400px"></video>`:''}<div class="article-actions">${hasVideo?`<button onclick="openShortAIFeed(${i})">🎬 Xem Short</button>${voiceSelector}<button class="primary" onclick="makeShortVideo('${esc(p.id)}',this,document.getElementById('selected-voice')?.value,parseFloat(document.getElementById('selected-speed')?.value)||1.2)">🔄 Tạo lại Short</button>`:`${voiceSelector}<button class="primary" onclick="makeShortVideo('${esc(p.id)}',this,document.getElementById('selected-voice')?.value,parseFloat(document.getElementById('selected-speed')?.value)||1.2)">🎬 Tạo Video Shorts</button>`}<button onclick="doShare('${esc(p.title)}','${SPACE}','${esc(p.img||'')}')">📤</button></div></div>`;
464
+ const firstVoiceBtn = document.querySelector('.tts-voice-btn');
465
+ if(firstVoiceBtn) firstVoiceBtn.classList.add('active');
466
+ window.scrollTo(0,0)}
467
+ async function loadNewsTab(){const el=document.getElementById('view-cat');el.innerHTML='<div class="loading">Đang tải...</div>';try{const r=await fetch('/api/homepage');const news=await r.json();if(!news.length){el.innerHTML='<div class="loading">Không có tin</div>';return}const groups={};news.forEach(a=>{if(!groups[a.group])groups[a.group]=[];groups[a.group].push(a)});let h='';for(const[g,arts] of Object.entries(groups)){h+=`<div class="section-title">${g}</div><div class="grid">`;arts.slice(0,6).forEach(a=>{h+=`<div class="card" onclick="readArticle('${esc(a.link)}')"><div class="card-img">${a.img?`<img src="${a.img}">`:''}</div><div class="card-body"><span class="badge badge-vne">${esc(a.source||'VnE')}</span><div class="card-title">${esc(a.title)}</div></div></div>`});h+='</div>'}el.innerHTML=h}catch(e){el.innerHTML='<div class="loading">Lỗi</div>'}}
468
+ async function loadCat(id){const el=document.getElementById('view-cat');el.innerHTML='<div class="loading">Đang tải...</div>';const arts=await fetch('/api/category/'+id).then(r=>r.json()).catch(()=>[]);if(!arts.length){el.innerHTML='<div class="loading">Không có tin</div>';return}let h='<div class="grid">';arts.forEach(a=>{h+=`<div class="card" onclick="readArticle('${esc(a.link)}')"><div class="card-img">${a.img?`<img src="${a.img}">`:''}</div><div class="card-body"><span class="badge badge-vne">${esc(a.source||'')}</span><div class="card-title">${esc(a.title)}</div></div></div>`});h+='</div>';el.innerHTML=h}
469
+ fetch('/api/storage_status').then(r=>r.json()).then(j=>{if(!j.persistent){const home=document.getElementById('view-home');if(home){const w=document.createElement('div');w.className='storage-warn';w.innerHTML='⚠️ Persistent Storage chưa bật.';home.prepend(w)}}}).catch(()=>{});
470
+
471
+ // === AUTO-OPEN SHARE LINKS (/s?url=... sets pending_article) ===
472
+ (function(){
473
+ try{
474
+ const pa=localStorage.getItem('pending_article');
475
+ const pv=localStorage.getItem('pending_video');
476
+ if(pa){
477
+ localStorage.removeItem('pending_article');
478
+ setTimeout(()=>{
479
+ if(typeof readArticle==='function') readArticle(pa);
480
+ },1500);
481
+ }
482
+ if(pv){
483
+ localStorage.removeItem('pending_video');
484
+ try{
485
+ const v=JSON.parse(pv);
486
+ if(v&&v.url) setTimeout(()=>{window.open(v.url,'_blank')},1500);
487
+ }catch(e){}
488
+ }
489
+ }catch(e){}
490
+ })();