bep40 commited on
Commit
de64228
·
verified ·
1 Parent(s): af364ab

Restore app_v2.js WC 2026 section from 7a0c951: wc2026-live-section in loadHome, shorts fetch, switchWCTab call, render order

Browse files
Files changed (1) hide show
  1. static/app_v2.js +125 -305
static/app_v2.js CHANGED
@@ -1,5 +1,6 @@
1
  // === VNEWS Frontend v2 - Optimized for speed ===
2
 
 
3
  function _fetchWithTimeout(url, ms){
4
  return new Promise((resolve,reject)=>{
5
  const ctrl=new AbortController();
@@ -16,29 +17,32 @@ async function loadHome(){
16
  const homeEl = document.getElementById('view-home');
17
  if(!homeEl) return;
18
 
19
- // World Cup section sẽ được chèn vào đây (trước Livescore)
20
  homeEl.innerHTML =
21
  '<div id="home-featured-area"></div>'
22
- +'<div id="wc-home-section"></div>' // World Cup section - hiển thị đầu tiên
23
  +'<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>'
24
  +'<div id="hashtag-box"></div>'
25
  +'<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>'
26
- +'<div id="home-content"></div>';
 
27
 
28
- const afterEl = homeEl.querySelector('#home-content');
29
 
 
30
  loadLivescore('today');
31
  loadHotTopics();
32
 
33
- // Fetch all data with timeout - không để 1 API chậm treo cả trang
34
- const [featuredData, wallData, hlLeagues, aiData, wcData] = await Promise.allSettled([
35
  _fetchWithTimeout('/api/livescore/featured', 5000),
 
36
  _fetchWithTimeout('/api/wall', 5000),
37
- _fetchWithTimeout('/api/highlights/leagues', 15000),
38
  _fetchWithTimeout('/api/genk_ai', 8000),
39
- _fetchWithTimeout('/api/wc2026', 12000), // World Cup data
40
  ]).then(results => results.map(r => r.status === 'fulfilled' ? r.value : null));
41
 
 
42
  if(featuredData && featuredData.home){
43
  const sc=featuredData.status==='live'?'':'upcoming';
44
  const st=featuredData.status==='live'?`🔴 ${featuredData.minute||'LIVE'}`:`⏰ ${featuredData.time}`;
@@ -46,217 +50,22 @@ async function loadHome(){
46
  if(area) area.innerHTML=`<div class="featured-match" onclick="openMatch('${featuredData.event_id}')"><div class="fm-league">${featuredData.league}</div><div class="fm-teams"><div class="fm-team"><img src="${featuredData.home_logo}" onerror="this.style.display='none'"><span>${featuredData.home}</span></div><div class="fm-score">${featuredData.score||'VS'}</div><div class="fm-team"><img src="${featuredData.away_logo}" onerror="this.style.display='none'"><span>${featuredData.away}</span></div></div><div class="fm-status ${sc}">${st}</div></div>`;
47
  }
48
 
 
 
49
  _wallPosts = (wallData && wallData.posts) || [];
50
- _hlLeagueData = (hlLeagues && typeof hlLeagues === 'object') ? hlLeagues : {};
51
- _wcData = wcData || {}; // Store World Cup data globally
52
 
53
- // Render World Cup section NGAY SAU featured match (trước AI compose, hashtag, livescore)
54
- if(_wcData && Object.keys(_wcData).length > 0){
55
- _renderWorldCupSectionInHome();
56
- }
57
 
 
 
58
  _renderWallIn(afterEl);
59
  _renderHLIn(afterEl);
60
-
61
  if(aiData && aiData.length) _renderSlidesIn('ai-articles','Ứng dụng AI','🤖',aiData,afterEl);
62
  }
63
 
64
- // ===== WORLD CUP 2026 SECTION =====
65
- // Render World Cup trong trang chủ (sau featured match, trước AI compose)
66
- function _renderWorldCupSectionInHome(){
67
- const wcContainer = document.getElementById('wc-home-section');
68
- if(!wcContainer) return;
69
-
70
- const wc = _wcData;
71
- let h = '<div class="wc-section">';
72
- h += '<div class="wc-header"><span class="wc-title">🌍 World Cup 2026</span></div>';
73
- h += '<div class="wc-tabs"><span class="wc-tab active" onclick="switchWCTab(\'news\',this)">📰 Tin tức</span><span class="wc-tab" onclick="switchWCTab(\'fixtures\',this)">📅 Lịch thi đấu</span><span class="wc-tab" onclick="switchWCTab(\'standings\',this)">🏆 Bảng xếp hạng</span><span class="wc-tab" onclick="switchWCTab(\'stats\',this)">📊 Thống kê</span><span class="wc-tab" onclick="switchWCTab(\'highlights\',this)">🎬 Highlight</span></div>';
74
- h += '<div id="wc-tab-content" class="wc-tab-content"></div>';
75
- h += '</div>';
76
-
77
- wcContainer.innerHTML = h;
78
- _renderWCTabContent('news');
79
- }
80
-
81
- // Render World Cup trong view riêng (nếu cần)
82
- function _renderWorldCupSection(afterEl){
83
- const wc = _wcData;
84
- const wrap = document.createElement('div');
85
- wrap.className = 'wc-section';
86
- wrap.id = 'wc-section';
87
-
88
- let h = '<div class="wc-header"><span class="wc-title">🌍 World Cup 2026</span></div>';
89
- h += '<div class="wc-tabs"><span class="wc-tab active" onclick="switchWCTab(\'news\',this)">📰 Tin tức</span><span class="wc-tab" onclick="switchWCTab(\'fixtures\',this)">📅 Lịch thi đấu</span><span class="wc-tab" onclick="switchWCTab(\'standings\',this)">🏆 Bảng xếp hạng</span><span class="wc-tab" onclick="switchWCTab(\'stats\',this)">📊 Thống kê</span><span class="wc-tab" onclick="switchWCTab(\'highlights\',this)">🎬 Highlight</span></div>';
90
- h += '<div id="wc-tab-content" class="wc-tab-content"></div>';
91
-
92
- wrap.innerHTML = h;
93
- afterEl.parentNode.insertBefore(wrap, afterEl);
94
- _renderWCTabContent('news');
95
- }
96
-
97
- function switchWCTab(tab, el){
98
- document.querySelectorAll('.wc-tab').forEach(t => t.classList.remove('active'));
99
- if(el) el.classList.add('active');
100
- _renderWCTabContent(tab);
101
- }
102
-
103
- function _renderWCTabContent(tab){
104
- const contentEl = document.getElementById('wc-tab-content');
105
- if(!contentEl) return;
106
-
107
- if(tab === 'news'){
108
- _renderWCNews(contentEl);
109
- } else if(tab === 'fixtures'){
110
- _renderWCFixtures(contentEl);
111
- } else if(tab === 'standings'){
112
- _renderWCStandings(contentEl);
113
- } else if(tab === 'stats'){
114
- _renderWCStats(contentEl);
115
- } else if(tab === 'highlights'){
116
- _renderWCHighlights(contentEl);
117
- }
118
- }
119
-
120
- // Biến lưu trạng thái loading cho từng tab
121
- let _wcTabLoading = {};
122
- let _wcTabLoaded = {}; // Đánh dấu tab đã load xong (dù có data hay không)
123
-
124
- function _renderWCNews(el){
125
- // Nếu đang loading, hiển thị loading
126
- if(_wcTabLoading['news']){
127
- el.innerHTML = '<div class="loading">Đang tải tin tức...</div>';
128
- return;
129
- }
130
- // Nếu đã load xong nhưng không có data
131
- if(_wcTabLoaded['news'] && (!_wcData.news || !_wcData.news.length)){
132
- el.innerHTML = '<div class="loading">Chưa có dữ liệu tin tức World Cup.</div>';
133
- return;
134
- }
135
- // Nếu chưa load, trigger fetch
136
- if(!_wcTabLoaded['news']){
137
- el.innerHTML = '<div class="loading">Đang tải tin tức...</div>';
138
- _fetchWCTabData('news');
139
- return;
140
- }
141
- // Render data
142
- const news = _wcData.news || [];
143
- let h = '<div class="wc-news-list">';
144
- news.slice(0, 15).forEach(item => {
145
- h += `<div class="wc-news-item" onclick="readArticle('${esc(item.link)}')">`;
146
- if(item.img) h += `<div class="wc-news-img"><img src="${esc(item.img)}" loading="lazy" onerror="this.style.display='none'"></div>`;
147
- h += `<div class="wc-news-text"><div class="wc-news-title">${esc(item.title)}</div><div class="wc-news-source">${esc(item.source||'')}</div></div></div>`;
148
- });
149
- h += '</div>';
150
- el.innerHTML = h;
151
- }
152
-
153
- function _renderWCFixtures(el){
154
- if(_wcTabLoading['fixtures']){
155
- el.innerHTML = '<div class="loading">Đang tải lịch thi đấu...</div>';
156
- return;
157
- }
158
- if(_wcTabLoaded['fixtures'] && (!_wcData.fixtures || !_wcData.fixtures.matches || !_wcData.fixtures.matches.length)){
159
- el.innerHTML = '<div class="loading">Chưa có dữ liệu lịch thi đấu World Cup.</div>';
160
- return;
161
- }
162
- if(!_wcTabLoaded['fixtures']){
163
- el.innerHTML = '<div class="loading">Đang tải lịch thi đấu...</div>';
164
- _fetchWCTabData('fixtures');
165
- return;
166
- }
167
- const fixtures = _wcData.fixtures || {};
168
- const matches = fixtures.matches || [];
169
- let h = '<div class="wc-fixtures-list">';
170
- matches.slice(0, 20).forEach(m => {
171
- const statusClass = m.status === 'live' ? 'wc-live' : (m.status === 'finished' ? 'wc-finished' : 'wc-upcoming');
172
- const score = m.score || 'vs';
173
- h += `<div class="wc-match-item">`;
174
- h += `<div class="wc-match-date">${esc(m.date_vn||m.date_utc||'')}</div>`;
175
- h += `<div class="wc-match-teams"><span class="wc-team">${esc(m.home||'')}</span><span class="wc-score ${statusClass}">${esc(score)}</span><span class="wc-team">${esc(m.away||'')}</span></div>`;
176
- if(m.location) h += `<div class="wc-match-location">📍 ${esc(m.location)}</div>`;
177
- h += `</div>`;
178
- });
179
- h += '</div>';
180
- el.innerHTML = h;
181
- }
182
-
183
- function _renderWCStandings(el){
184
- if(_wcTabLoading['standings']){
185
- el.innerHTML = '<div class="loading">Đang tải bảng xếp hạng...</div>';
186
- return;
187
- }
188
- if(_wcTabLoaded['standings'] && (!_wcData.standings || !_wcData.standings.html)){
189
- el.innerHTML = '<div class="loading">Chưa có dữ liệu bảng xếp hạng World Cup.</div>';
190
- return;
191
- }
192
- if(!_wcTabLoaded['standings']){
193
- el.innerHTML = '<div class="loading">Đang tải bảng xếp hạng...</div>';
194
- _fetchWCTabData('standings');
195
- return;
196
- }
197
- const standings = _wcData.standings || {};
198
- el.innerHTML = '<div class="wc-standings-table">' + standings.html + '</div>';
199
- }
200
-
201
- function _renderWCStats(el){
202
- if(_wcTabLoading['stats']){
203
- el.innerHTML = '<div class="loading">Đang tải thống kê...</div>';
204
- return;
205
- }
206
- if(_wcTabLoaded['stats'] && (!_wcData.stats || !_wcData.stats.html)){
207
- el.innerHTML = '<div class="loading">Chưa có dữ liệu thống kê World Cup.</div>';
208
- return;
209
- }
210
- if(!_wcTabLoaded['stats']){
211
- el.innerHTML = '<div class="loading">Đang tải thống kê...</div>';
212
- _fetchWCTabData('stats');
213
- return;
214
- }
215
- const stats = _wcData.stats || {};
216
- el.innerHTML = '<div class="wc-stats-table">' + stats.html + '</div>';
217
- }
218
-
219
- function _renderWCHighlights(el){
220
- // Highlights lấy từ _hlLeagueData (đã fetch từ API highlights/leagues)
221
- if(!_hlLeagueData) _hlLeagueData = {};
222
- const highlights = _hlLeagueData['world-cup'] || [];
223
- if(!highlights.length){
224
- el.innerHTML = '<div class="loading">Chưa có highlight World Cup.</div>';
225
- return;
226
- }
227
- let h = '<div class="wc-highlights-grid">';
228
- highlights.slice(0, 12).forEach((item, i) => {
229
- // FIX: Đảm bảo luôn có title và placeholder cho img
230
- const title = item.title || 'World Cup Highlight';
231
- const imgHtml = item.img ?
232
- `<img src="${esc(item.img)}" loading="lazy" onerror="this.onerror=null;this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><rect fill=%22%23333%22 width=%22100%22 height=%22100%22/><text fill=%22%23999%22 x=%2250%22 y=%2255%22 text-anchor=%22middle%22 font-size=%2214%22>🌍</text></svg>'">` :
233
- `<div style="width:100%;height:100%;background:#222;display:flex;align-items:center;justify-content:center;font-size:24px;">🌍</div>`;
234
- h += `<div class="wc-hl-item" onclick="openHighlightFeed('world-cup',${i})">`;
235
- h += `<div class="wc-hl-thumb">${imgHtml}<div class="card-play">▶</div></div>`;
236
- h += `<div class="wc-hl-title">${esc(title)}</div></div>`;
237
- });
238
- h += '</div>';
239
- el.innerHTML = h;
240
- }
241
-
242
- async function _fetchWCTabData(tab){
243
- if(_wcTabLoading[tab]) return; // Đang loading rồi, không fetch lại
244
- _wcTabLoading[tab] = true;
245
- try{
246
- const data = await _fetchWithTimeout(`/api/wc2026/${tab}`, 8000);
247
- if(!_wcData) _wcData = {};
248
- _wcData[tab] = data;
249
- _wcTabLoading[tab] = false;
250
- _wcTabLoaded[tab] = true;
251
- _renderWCTabContent(tab); // Render lại tab hiện tại
252
- }catch(e){
253
- console.log(`WC ${tab} fetch failed:`, e.message);
254
- _wcTabLoading[tab] = false;
255
- _wcTabLoaded[tab] = true;
256
- _renderWCTabContent(tab); // Render lại để hiển thị thông báo lỗi
257
- }
258
- }
259
-
260
  function _renderSlidesIn(key, label, emoji, vids, afterEl){
261
  if(!vids||!vids.length||!afterEl) return;
262
  const wrap=document.createElement('div');
@@ -275,6 +84,21 @@ function _renderSlidesIn(key, label, emoji, vids, afterEl){
275
  afterEl.parentNode.insertBefore(wrap, afterEl);
276
  }
277
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
278
  function _renderWallIn(afterEl){
279
  if(!_wallPosts||!_wallPosts.length||!afterEl) return;
280
  const posts=_wallPosts;
@@ -296,30 +120,25 @@ function _renderWallIn(afterEl){
296
  }
297
 
298
  function _renderHLIn(afterEl){
299
- if(!_hlLeagueData || !afterEl) return;
300
- // Ưu tiên World Cup hiển thị đầu tiên
301
  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:"🤝"}};
302
-
303
- // Render World Cup trước nếu có
304
- const wcVids = _hlLeagueData['world-cup'];
305
- if(wcVids && wcVids.length > 0){
306
- _renderSlidesIn('world-cup', 'World Cup 2026', '🌍', wcVids, afterEl);
307
- }
308
-
309
- // Render các league khác
310
  for(const[key,cfg] of Object.entries(HL_CONFIG)){
311
- if(key === 'world-cup') continue; // Đã render ở trên
312
  const vids=_hlLeagueData[key];
313
  if(!vids||!vids.length) continue;
314
  _renderSlidesIn(key,cfg.name,cfg.emoji,vids,afterEl);
315
  }
316
  }
317
 
 
318
  function makeWallItem(p,i){
319
  const hasVideo = p.video && p.video.length > 0;
320
- const thumbContent = p.img ? `<img src="${esc(p.img)}" loading="lazy" onerror="this.style.display='none'">` : (hasVideo ? `<video src="${esc(p.video)}" muted></video>` : '');
 
 
321
  const videoBadge = hasVideo ? `<div class="wall-video-badge">🎬</div>` : '';
322
- const videoBtn = hasVideo ? `<button class="wall-btn-video" onclick="event.stopPropagation();openShortAIFeed(${i})">▶ Xem Short</button>` : `<button class="wall-btn-make" onclick="event.stopPropagation();makeShortVideo('${esc(p.id||i)}',this)">🎬 Tạo Video</button>`;
 
 
323
  return `<div class="wall-item" id="wall-item-${esc(p.id||i)}"><div class="wall-thumb">${thumbContent}${videoBadge}</div><div class="wall-title">${esc(p.title)}</div><div class="wall-text">${esc((p.text||'').slice(0,180))}</div><div class="wall-actions"><button class="primary" onclick="readWallPost(${i})">Xem</button>${videoBtn}</div></div>`;
324
  }
325
 
@@ -360,12 +179,17 @@ async function makeShortVideo(postId, btn, voice, speed){
360
  function refreshShortAISlider(){
361
  const aiShorts = _wallPosts.filter(p=>p.video);
362
  let shortAISection = document.getElementById('short-ai-section');
363
- if(aiShorts.length === 0){ if(shortAISection) shortAISection.remove(); return; }
 
 
 
364
  if(shortAISection){
365
  const track = shortAISection.querySelector('.slider-track');
366
  if(track){
367
  let h = '';
368
- 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="${esc(p.video)}" muted preload="metadata"></video><div class="card-play">▶</div></div><div class="slider-title">${esc(p.title)}</div></div>`;});
 
 
369
  track.innerHTML = h;
370
  }
371
  }
@@ -394,19 +218,26 @@ function prependWallPost(post){
394
  div.className='wall-item wall-item-new';
395
  div.id='wall-item-'+(post.id||'new-'+Date.now());
396
  const hasVideo = post.video && post.video.length > 0;
397
- const thumbContent = post.img ? `<img src="${esc(post.img)}" loading="lazy" onerror="this.style.display='none'">` : (hasVideo ? `<video src="${esc(p.video)}" muted></video>` : '');
 
 
398
  const videoBadge = hasVideo ? `<div class="wall-video-badge">🎬</div>` : '';
399
- const videoBtn = hasVideo ? `<button class="wall-btn-video" onclick="event.stopPropagation();openShortAIFeed(0)">▶ Xem Short</button>` : `<button class="wall-btn-make" onclick="event.stopPropagation();makeShortVideo('${esc(post.id)}',this)">🎬 Tạo Video</button>`;
 
 
400
  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>`;
401
  track.prepend(div);
402
  track.scrollTo({left:0,behavior:'smooth'});
403
  if(hasVideo) refreshShortAISlider();
404
  }
405
 
 
 
406
  let _wallPosts=[];
407
  let _currentView='home';
408
  let _currentEventId=null;
409
  let _currentMatchUrl=null;
 
410
  let _htPage=0,_htTopic='';
411
  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);}}
412
  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);}
@@ -422,7 +253,8 @@ function bindMatchClicks(el){
422
  const teamA=this.querySelector('.teams a[href*="/tran-dau/"]');
423
  const a = statusA || teamA;
424
  if(a){
425
- e.preventDefault();e.stopPropagation();
 
426
  const href=a.getAttribute('href')||'';
427
  const m=href.match(/\/tran-dau\/(\d+)\//);
428
  if(m){
@@ -432,7 +264,9 @@ function bindMatchClicks(el){
432
  }
433
  });
434
  });
435
- el.querySelectorAll('a').forEach(a=>{a.addEventListener('click',e=>{e.preventDefault();e.stopPropagation()});});
 
 
436
  }
437
  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')}
438
  function closeMatch(){document.getElementById('match-overlay').classList.remove('active');document.body.style.overflow=''}
@@ -449,74 +283,11 @@ async function loadCounters(videoIds){for(let i=0;i<videoIds.length;i++){const i
449
  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);}
450
  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;}
451
  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);}
452
- 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){try{fr.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}','*');}catch(e){}}}});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)}
453
  async function openHighlightFeed(league,idx,forceUrl){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();}
454
- async function openYTShortsFeed(startIdx){
455
- showView('view-tiktok');
456
- const el=document.getElementById('view-tiktok');
457
- el.innerHTML='<div class="loading">Đang tải shorts...</div>';
458
- let arts = _shortsData.length ? _shortsData : [];
459
- if(!arts.length){try{arts=await fetch('/api/shorts').then(r=>r.json()).catch(()=>[]);}catch(e){arts=[];}}
460
- if(!arts.length){el.innerHTML='<div class="loading">Không có shorts</div>';return;}
461
- const ordered=startIdx>0?[...arts.slice(startIdx),...arts.slice(0,startIdx)]:arts;
462
- let h=`<button class="back-btn" onclick="switchCat('home')">← Shorts</button><div class="tiktok-container"><div class="tiktok-feed" id="tiktok-feed">`;
463
- ordered.forEach((v,i)=>{
464
- const id=v.id||'';
465
- const src=`https://www.youtube.com/embed/${id}?autoplay=0&rel=0&playsinline=1&mute=1&loop=1&playlist=${id}&enablejsapi=1`;
466
- const vtag=`<iframe data-yt-src="${src}" allowfullscreen allow="accelerometer;autoplay;clipboard-write;encrypted-media;gyroscope;picture-in-picture"></iframe>`;
467
- let badge,badgeClass;
468
- if(v.channel==='baosuckhoedoisongboyte'){badge='SKĐS';badgeClass='badge-fpt';}
469
- else if(v.channel==='vtvnambo'){badge='VTV Nam Bộ';badgeClass='badge-dantri';}
470
- else{badge='Dân trí';badgeClass='badge-vne';}
471
- const videoId='yt-'+id;
472
- h+=buildTikTokSlide({vtag,title:v.title,badge,badgeClass,videoId,idx:i,total:ordered.length,shareUrl:'https://youtube.com/shorts/'+id});
473
- });
474
- h+='</div></div>';
475
- el.innerHTML=h;
476
- initTikTokFeed();
477
- }
478
  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();}
479
- async function readArticle(url){
480
- showView('view-article');
481
- const el=document.getElementById('view-article');
482
- el.innerHTML='<div class="loading">Đang tải...</div>';
483
- try{const cached=localStorage.getItem('article_'+url);if(cached){const parsed=JSON.parse(cached);if(parsed&&parsed.body&&parsed.body.length){_currentArticle={url,data:parsed};_renderArticle(el,parsed,url);return}}}catch(e){}
484
- try{
485
- const ctrl=new AbortController();
486
- const tid=setTimeout(()=>ctrl.abort(),15000);
487
- const r=await fetch('/api/article?url='+encodeURIComponent(url),{signal:ctrl.signal});
488
- clearTimeout(tid);
489
- const data=await r.json();
490
- if(data&&!data.error&&data.body&&data.body.length){
491
- _currentArticle={url,data};
492
- try{localStorage.setItem('article_'+url,JSON.stringify(data))}catch(e){}
493
- _renderArticle(el,data,url);
494
- return;
495
- }
496
- }catch(e){}
497
- el.innerHTML=`<button class="back-btn" onclick="switchCat('home')">← Quay lại</button><div class="loading"><p>Không đọc được.</p><button class="primary" onclick="window.open('${esc(url)}','_blank')" style="margin-top:8px">📖 Mở bài gốc</button></div>`;
498
- }
499
- function _renderArticle(el,data,url){
500
- 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>`;
501
- if(data.summary)h+=`<div class="article-summary">${esc(data.summary)}</div>`;
502
- const seen={};
503
- data.body.forEach(b=>{
504
- if(b.type==='p')h+=`<p class="article-p">${b.text}</p>`;
505
- 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'">`}
506
- else if(b.type==='heading')h+=`<h2 class="article-h2">${esc(b.text)}</h2>`;
507
- });
508
- if(data.fallback){
509
- h+=`<div style="background:#fff3cd;border:1px solid #ffc107;border-radius:8px;padding:12px;margin:12px 0;font-size:13px;color:#856404">📰 <strong>Nội dung tóm tắt</strong> — Trang nguồn giới hạn truy cập. <a href="${esc(url)}" target="_blank" style="color:#856404;text-decoration:underline">Đọc bài đầy đủ →</a></div>`;
510
- }
511
- h+=`<div class="article-actions">`;
512
- h+=`<button class="primary" onclick="window.open('${esc(url)}','_blank')">📖 Đọc bài gốc</button>`;
513
- h+=`<button onclick="rewriteArticle()">🤖 Rewrite AI</button>`;
514
- h+=`<button onclick="doShare('${esc(data.title)}','${esc(url)}','${esc(data.og_image||'')}')">📤</button>`;
515
- h+=`</div>`;
516
- h+=`<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>`;
517
- el.innerHTML=h;
518
- window.scrollTo(0,0);
519
- }
520
  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)}}
521
  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)}}
522
  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}}
@@ -526,20 +297,29 @@ async function readWallPost(i){const p=_wallPosts[i];if(!p)return;showView('view
526
  if(images.length > 0){
527
  imgGallery = '<div class="article-image-gallery">';
528
  images.forEach((imgUrl, imgIdx) => {
529
- if(imgIdx === 0){imgGallery += `<img class="article-img article-hero-img" src="${esc(imgUrl)}" onerror="this.style.display='none" loading="eager">`;}
530
- else{if(imgIdx === 1) imgGallery += '<div class="gallery-thumbs">';imgGallery += `<div class="gallery-thumb"><img src="${esc(imgUrl)}" onerror="this.parentElement.style.display='none'" loading="lazy"></div>`;}
 
 
 
 
531
  });
532
  if(images.length > 1) imgGallery += '</div>';
533
  imgGallery += '</div>';
534
  }
535
  const hasVideo = p.video && p.video.length > 0;
536
- const voiceOptions = [{id:'hoaimy',label:'🎙️ Nữ — Hoài My'},{id:'namminh',label:'🎙️ Nam — Nam Minh'}];
 
 
 
537
  let voiceSelector = '';
538
  if(!hasVideo){
539
  voiceSelector = `<div class="tts-selector"><div class="tts-selector-label">🎙️ Chọn giọng đọc:</div><div class="tts-voice-btns">`;
540
- voiceOptions.forEach(v=>{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>`;});
541
- voiceSelector+=`</div><div class="tts-speed-row"><span>Tốc độ:</span><select id="selected-speed"><option value="1.0">1.0x</option><option value="1.2" selected>1.2x</option><option value="1.5">1.5x</option><option value="0.8">0.8x</option></select></div>`;
542
- voiceSelector+=`<input type="hidden" id="selected-voice" value="hoaimy"></div>`;
 
 
543
  }
544
  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>`;
545
  const firstVoiceBtn = document.querySelector('.tts-voice-btn');
@@ -548,6 +328,46 @@ async function readWallPost(i){const p=_wallPosts[i];if(!p)return;showView('view
548
  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}" loading="lazy">`:''}</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>'}}
549
  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}" loading="lazy">`:''}</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}
550
  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(()=>{});
551
- (function(){try{var hash=window.location.hash;if(hash&&hash.length>1){var articleUrl=decodeURIComponent(hash.substring(1));if(articleUrl.startsWith('http')){history.replaceState(null,'',window.location.pathname);if(typeof readArticle==='function')readArticle(articleUrl);}}}catch(e){}})();
552
- (function(){try{const pa=localStorage.getItem('pending_article');const pv=localStorage.getItem('pending_video');if(pa){localStorage.removeItem('pending_article');if(typeof readArticle==='function')readArticle(pa);}if(pv){localStorage.removeItem('pending_video');try{const v=JSON.parse(pv);if(v&&v.url)window.open(v.url,'_blank');}catch(e){}}}catch(e){}})();
553
- if(document.readyState==='loading'){document.addEventListener('DOMContentLoaded',function(){if(typeof loadHome==='function')loadHome();});}else{if(typeof loadHome==='function')loadHome();}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  // === VNEWS Frontend v2 - Optimized for speed ===
2
 
3
+ // === LOAD HOME - Fast: immediate shell + parallel fetch ===
4
  function _fetchWithTimeout(url, ms){
5
  return new Promise((resolve,reject)=>{
6
  const ctrl=new AbortController();
 
17
  const homeEl = document.getElementById('view-home');
18
  if(!homeEl) return;
19
 
20
+ // Build shell IMMEDIATELY no skeleton, no delay
21
  homeEl.innerHTML =
22
  '<div id="home-featured-area"></div>'
 
23
  +'<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>'
24
  +'<div id="hashtag-box"></div>'
25
  +'<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>'
26
+ +'<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>'
27
+ +'<div id="home-after-wc"></div>';
28
 
29
+ const afterEl = homeEl.querySelector('#home-after-wc');
30
 
31
+ // Start critical loads immediately
32
  loadLivescore('today');
33
  loadHotTopics();
34
 
35
+ // Fetch all data in parallel with shorter timeouts
36
+ const [featuredData, shortsData, wallData, hlLeagues, aiData, wcData] = await Promise.allSettled([
37
  _fetchWithTimeout('/api/livescore/featured', 5000),
38
+ _fetchWithTimeout('/api/shorts', 8000),
39
  _fetchWithTimeout('/api/wall', 5000),
40
+ _fetchWithTimeout('/api/highlights/leagues', 10000),
41
  _fetchWithTimeout('/api/genk_ai', 8000),
42
+ _fetchWithTimeout('/api/wc2026', 8000),
43
  ]).then(results => results.map(r => r.status === 'fulfilled' ? r.value : null));
44
 
45
+ // Render featured match
46
  if(featuredData && featuredData.home){
47
  const sc=featuredData.status==='live'?'':'upcoming';
48
  const st=featuredData.status==='live'?`🔴 ${featuredData.minute||'LIVE'}`:`⏰ ${featuredData.time}`;
 
50
  if(area) area.innerHTML=`<div class="featured-match" onclick="openMatch('${featuredData.event_id}')"><div class="fm-league">${featuredData.league}</div><div class="fm-teams"><div class="fm-team"><img src="${featuredData.home_logo}" onerror="this.style.display='none'"><span>${featuredData.home}</span></div><div class="fm-score">${featuredData.score||'VS'}</div><div class="fm-team"><img src="${featuredData.away_logo}" onerror="this.style.display='none'"><span>${featuredData.away}</span></div></div><div class="fm-status ${sc}">${st}</div></div>`;
51
  }
52
 
53
+ // Store globally
54
+ _shortsData = shortsData || [];
55
  _wallPosts = (wallData && wallData.posts) || [];
56
+ _hlLeagueData = hlLeagues || {};
57
+ _wc2026Data = wcData;
58
 
59
+ // Render WC if data arrived
60
+ if(wcData) switchWCTab('news');
 
 
61
 
62
+ // Render sections into the after-wc area
63
+ _renderShortsIn(afterEl);
64
  _renderWallIn(afterEl);
65
  _renderHLIn(afterEl);
 
66
  if(aiData && aiData.length) _renderSlidesIn('ai-articles','Ứng dụng AI','🤖',aiData,afterEl);
67
  }
68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  function _renderSlidesIn(key, label, emoji, vids, afterEl){
70
  if(!vids||!vids.length||!afterEl) return;
71
  const wrap=document.createElement('div');
 
84
  afterEl.parentNode.insertBefore(wrap, afterEl);
85
  }
86
 
87
+ function _renderShortsIn(afterEl){
88
+ if(!_shortsData||!_shortsData.length||!afterEl) return;
89
+ const mixed=interleaveShorts(_shortsData);
90
+ if(!mixed.length) return;
91
+ const wrap=document.createElement('div');
92
+ wrap.className='slider-wrap';
93
+ let h=`<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">`;
94
+ mixed.slice(0,30).forEach((a,i)=>{
95
+ const badge=a.channel==='baosuckhoedoisongboyte'?'SKĐS':'Dân trí';
96
+ h+=`<div class="slider-item shorts-item" onclick="openYTShortsFeed(${i})"><div class="slider-thumb shorts-thumb">${a.img?`<img src="${a.img}" loading="lazy">`:''}<div class="card-play">▶</div></div><div class="slider-title"><span style="color:#f0c040;font-size:8px">${badge}</span> ${esc(a.title)}</div></div>`;
97
+ });
98
+ h+='</div>';wrap.innerHTML=h;
99
+ afterEl.parentNode.insertBefore(wrap,afterEl);
100
+ }
101
+
102
  function _renderWallIn(afterEl){
103
  if(!_wallPosts||!_wallPosts.length||!afterEl) return;
104
  const posts=_wallPosts;
 
120
  }
121
 
122
  function _renderHLIn(afterEl){
123
+ if(!_hlLeagueData||Object.keys(_hlLeagueData).length===0||!afterEl) return;
 
124
  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:"🤝"}};
 
 
 
 
 
 
 
 
125
  for(const[key,cfg] of Object.entries(HL_CONFIG)){
 
126
  const vids=_hlLeagueData[key];
127
  if(!vids||!vids.length) continue;
128
  _renderSlidesIn(key,cfg.name,cfg.emoji,vids,afterEl);
129
  }
130
  }
131
 
132
+ // === WALL POST HELPERS ===
133
  function makeWallItem(p,i){
134
  const hasVideo = p.video && p.video.length > 0;
135
+ const thumbContent = p.img
136
+ ? `<img src="${esc(p.img)}" loading="lazy" onerror="this.style.display='none'">`
137
+ : (hasVideo ? `<video src="${esc(p.video)}" muted></video>` : '');
138
  const videoBadge = hasVideo ? `<div class="wall-video-badge">🎬</div>` : '';
139
+ const videoBtn = hasVideo
140
+ ? `<button class="wall-btn-video" onclick="event.stopPropagation();openShortAIFeed(${i})">▶ Xem Short</button>`
141
+ : `<button class="wall-btn-make" onclick="event.stopPropagation();makeShortVideo('${esc(p.id||i)}',this)">🎬 Tạo Video</button>`;
142
  return `<div class="wall-item" id="wall-item-${esc(p.id||i)}"><div class="wall-thumb">${thumbContent}${videoBadge}</div><div class="wall-title">${esc(p.title)}</div><div class="wall-text">${esc((p.text||'').slice(0,180))}</div><div class="wall-actions"><button class="primary" onclick="readWallPost(${i})">Xem</button>${videoBtn}</div></div>`;
143
  }
144
 
 
179
  function refreshShortAISlider(){
180
  const aiShorts = _wallPosts.filter(p=>p.video);
181
  let shortAISection = document.getElementById('short-ai-section');
182
+ if(aiShorts.length === 0){
183
+ if(shortAISection) shortAISection.remove();
184
+ return;
185
+ }
186
  if(shortAISection){
187
  const track = shortAISection.querySelector('.slider-track');
188
  if(track){
189
  let h = '';
190
+ aiShorts.slice(0,20).forEach((p,i)=>{
191
+ 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>`;
192
+ });
193
  track.innerHTML = h;
194
  }
195
  }
 
218
  div.className='wall-item wall-item-new';
219
  div.id='wall-item-'+(post.id||'new-'+Date.now());
220
  const hasVideo = post.video && post.video.length > 0;
221
+ const thumbContent = post.img
222
+ ? `<img src="${esc(post.img)}" loading="lazy" onerror="this.style.display='none'">`
223
+ : (hasVideo ? `<video src="${esc(post.video)}" muted></video>` : '');
224
  const videoBadge = hasVideo ? `<div class="wall-video-badge">🎬</div>` : '';
225
+ const videoBtn = hasVideo
226
+ ? `<button class="wall-btn-video" onclick="event.stopPropagation();openShortAIFeed(0)">▶ Xem Short</button>`
227
+ : `<button class="wall-btn-make" onclick="event.stopPropagation();makeShortVideo('${esc(post.id)}',this)">🎬 Tạo Video</button>`;
228
  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>`;
229
  track.prepend(div);
230
  track.scrollTo({left:0,behavior:'smooth'});
231
  if(hasVideo) refreshShortAISlider();
232
  }
233
 
234
+ // === REST OF FUNCTIONS ===
235
+ let _shortsData=[];
236
  let _wallPosts=[];
237
  let _currentView='home';
238
  let _currentEventId=null;
239
  let _currentMatchUrl=null;
240
+ 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;}
241
  let _htPage=0,_htTopic='';
242
  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);}}
243
  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);}
 
253
  const teamA=this.querySelector('.teams a[href*="/tran-dau/"]');
254
  const a = statusA || teamA;
255
  if(a){
256
+ e.preventDefault();
257
+ e.stopPropagation();
258
  const href=a.getAttribute('href')||'';
259
  const m=href.match(/\/tran-dau\/(\d+)\//);
260
  if(m){
 
264
  }
265
  });
266
  });
267
+ el.querySelectorAll('a').forEach(a=>{
268
+ a.addEventListener('click',e=>{e.preventDefault();e.stopPropagation()});
269
+ });
270
  }
271
  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')}
272
  function closeMatch(){document.getElementById('match-overlay').classList.remove('active');document.body.style.overflow=''}
 
283
  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);}
284
  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;}
285
  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);}
286
+ 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)}
287
  async function openHighlightFeed(league,idx,forceUrl){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();}
288
+ 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();}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289
  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();}
290
+ 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>`;}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
291
  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)}}
292
  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)}}
293
  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}}
 
297
  if(images.length > 0){
298
  imgGallery = '<div class="article-image-gallery">';
299
  images.forEach((imgUrl, imgIdx) => {
300
+ if(imgIdx === 0){
301
+ imgGallery += `<img class="article-img article-hero-img" src="${esc(imgUrl)}" onerror="this.style.display='none" loading="eager">`;
302
+ } else {
303
+ if(imgIdx === 1) imgGallery += '<div class="gallery-thumbs">';
304
+ imgGallery += `<div class="gallery-thumb"><img src="${esc(imgUrl)}" onerror="this.parentElement.style.display='none'" loading="lazy"></div>`;
305
+ }
306
  });
307
  if(images.length > 1) imgGallery += '</div>';
308
  imgGallery += '</div>';
309
  }
310
  const hasVideo = p.video && p.video.length > 0;
311
+ const voiceOptions = [
312
+ {id:'hoaimy', label:'🎙️ Nữ — Hoài My'},
313
+ {id:'namminh', label:'🎙️ Nam — Nam Minh'},
314
+ ];
315
  let voiceSelector = '';
316
  if(!hasVideo){
317
  voiceSelector = `<div class="tts-selector"><div class="tts-selector-label">🎙️ Chọn giọng đọc:</div><div class="tts-voice-btns">`;
318
+ voiceOptions.forEach(v=>{
319
+ 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>`;
320
+ });
321
+ 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>`;
322
+ voiceSelector += `<input type="hidden" id="selected-voice" value="hoaimy"></div>`;
323
  }
324
  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>`;
325
  const firstVoiceBtn = document.querySelector('.tts-voice-btn');
 
328
  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}" loading="lazy">`:''}</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>'}}
329
  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}" loading="lazy">`:''}</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}
330
  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(()=>{});
331
+
332
+ (function(){
333
+ try{
334
+ var hash = window.location.hash;
335
+ if(hash && hash.length > 1){
336
+ var articleUrl = decodeURIComponent(hash.substring(1));
337
+ if(articleUrl.startsWith('http')){
338
+ history.replaceState(null, '', window.location.pathname);
339
+ setTimeout(function(){
340
+ if(typeof readArticle==='function') readArticle(articleUrl);
341
+ }, 1500);
342
+ }
343
+ }
344
+ }catch(e){}
345
+ })();
346
+
347
+ (function(){
348
+ try{
349
+ const pa=localStorage.getItem('pending_article');
350
+ const pv=localStorage.getItem('pending_video');
351
+ if(pa){
352
+ localStorage.removeItem('pending_article');
353
+ setTimeout(()=>{
354
+ if(typeof readArticle==='function') readArticle(pa);
355
+ },1500);
356
+ }
357
+ if(pv){
358
+ localStorage.removeItem('pending_video');
359
+ try{
360
+ const v=JSON.parse(pv);
361
+ if(v&&v.url) setTimeout(()=>{window.open(v.url,'_blank')},1500);
362
+ }catch(e){}
363
+ }
364
+ }catch(e){}
365
+ })();
366
+
367
+ if (document.readyState === 'loading') {
368
+ document.addEventListener('DOMContentLoaded', function() {
369
+ if (typeof loadHome === 'function') loadHome();
370
+ });
371
+ } else {
372
+ if (typeof loadHome === 'function') loadHome();
373
+ }