import { Play, CheckCircle2 } from 'lucide-react'; import { useState, useEffect } from 'react'; export default function EpisodeList({ episodes, currentTap, movieSlug }) { const [serverIndex, setServerIndex] = useState(0); const [selectedChunkIndex, setSelectedChunkIndex] = useState(0); const [watched, setWatched] = useState([]); // Tự động đồng bộ server và tab (chunk) chứa tập đang phát (currentTap) useEffect(() => { if (currentTap && episodes?.length) { const foundServerIdx = episodes.findIndex(server => server.server_data?.some(ep => ep.name === currentTap) ); if (foundServerIdx !== -1) { setServerIndex(foundServerIdx); const targetServer = episodes[foundServerIdx]; const targetEpisodes = targetServer?.server_data || []; const epIdx = targetEpisodes.findIndex(ep => ep.name === currentTap); if (epIdx !== -1) { const targetChunkIdx = Math.floor(epIdx / 25); setSelectedChunkIndex(targetChunkIdx); } } } }, [currentTap, episodes]); // Tải lịch sử xem phim useEffect(() => { try { const history = JSON.parse(localStorage.getItem('txa_watch_history') || '{}'); if (history[movieSlug]?.watched) { setWatched(history[movieSlug].watched); } } catch (e) { console.error('Failed to load watch history'); } }, [movieSlug]); if (!episodes?.length) return null; const currentServer = episodes[serverIndex] || episodes[0]; const allEpisodes = currentServer?.server_data || []; // Chia danh sách tập phim thành các nhóm tối đa 25 tập const chunkSize = 25; const chunks = []; for (let i = 0; i < allEpisodes.length; i += chunkSize) { chunks.push(allEpisodes.slice(i, i + chunkSize)); } // Đảm bảo selectedChunkIndex không vượt quá phạm vi mới sau khi đổi server const activeChunkIndex = selectedChunkIndex < chunks.length ? selectedChunkIndex : 0; const visibleEpisodes = chunks[activeChunkIndex] || []; return (
{/* Tiêu đề & Chọn Server / Chọn Tab 25 tập */}

Danh sách tập

{/* Các Server phát */} {episodes.length > 1 && (
{episodes.map((server, idx) => ( ))}
)}
{/* Các Tab phân trang 25 tập (chỉ hiện khi có trên 25 tập) */} {chunks.length > 1 && (
{chunks.map((chunk, idx) => { const startIdx = idx * chunkSize + 1; const endIdx = Math.min((idx + 1) * chunkSize, allEpisodes.length); // Tạo nhãn tab trực quan theo tên tập hoặc index số const getLabel = () => { const sName = chunk[0]?.name; const eName = chunk[chunk.length - 1]?.name; const sNum = parseInt(sName); const eNum = parseInt(eName); if (!isNaN(sNum) && !isNaN(eNum)) { return `Tập ${sNum} - ${eNum}`; } return `${sName} - ${eName}`; }; const isActive = activeChunkIndex === idx; return ( ); })}
)}
{/* Grid danh sách tập */}
{visibleEpisodes.map((ep) => { const isWatched = watched.includes(ep.name); const isActive = ep.name === currentTap; return ( {ep.name.toLowerCase().includes('tập') ? ep.name : `Tập ${ep.name}`} {isWatched && !isActive && (
)} {isActive && (
)}
); })}
); }