* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    min-height: 100vh;
    padding: 20px;
}

.container {
    max-width: 1400px;
    margin: 0 auto;
    background: white;
    border-radius: 15px;
    box-shadow: 0 20px 40px rgba(0,0,0,0.1);
    overflow: hidden;
}

h1 {
    background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
    color: white;
    text-align: center;
    padding: 30px;
    font-size: 2.5em;
    margin: 0;
}

h2 {
    color: #333;
    margin-bottom: 20px;
    padding: 20px 30px 0;
    border-bottom: 2px solid #f0f0f0;
}

h3 {
    color: #555;
    margin-bottom: 15px;
}

.search-section, .results-section {
    padding: 30px;
}

.search-input-group {
    display: flex;
    gap: 15px;
    margin-bottom: 30px;
}

.search-input {
    flex: 1;
    padding: 15px 20px;
    border: 2px solid #e0e0e0;
    border-radius: 10px;
    font-size: 16px;
    transition: border-color 0.3s;
}

.search-input:focus {
    outline: none;
    border-color: #4ecdc4;
}

.search-btn {
    padding: 15px 30px;
    background: linear-gradient(45deg, #4ecdc4, #44a08d);
    color: white;
    border: none;
    border-radius: 10px;
    font-size: 16px;
    font-weight: bold;
    cursor: pointer;
    transition: transform 0.2s;
}

.search-btn:hover {
    transform: translateY(-2px);
}

.filters-section {
    background: #f8f9fa;
    padding: 25px;
    border-radius: 10px;
    margin-bottom: 20px;
}

.filter-group {
    display: inline-block;
    margin: 10px 20px 10px 0;
    vertical-align: top;
}

.filter-group label {
    display: block;
    margin-bottom: 5px;
    font-weight: bold;
    color: #555;
}

.filter-group select {
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 5px;
    background: white;
    min-width: 150px;
}

.results-controls {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 10px;
}

.button-group {
    display: flex;
    gap: 10px;
}

.quantity-input {
    display: flex;
    align-items: center;
    gap: 10px;
}

.quantity-input label {
    font-weight: bold;
    color: #555;
}

.count-input {
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 5px;
    width: 80px;
}

.download-btn {
    padding: 12px 25px;
    background: linear-gradient(45deg, #ff6b6b, #ee5a24);
    color: white;
    border: none;
    border-radius: 8px;
    font-weight: bold;
    cursor: pointer;
    transition: transform 0.2s;
}

.copy-column8-btn {
    padding: 12px 25px;
    background: linear-gradient(45deg, #4ecdc4, #44a08d);
    color: white;
    border: none;
    border-radius: 8px;
    font-weight: bold;
    cursor: pointer;
    transition: transform 0.2s;
}

.download-btn:hover:not(:disabled),
.copy-column8-btn:hover:not(:disabled) {
    transform: translateY(-2px);
}

.download-btn:disabled,
.copy-column8-btn:disabled {
    background: #ccc;
    cursor: not-allowed;
}

.loading {
    text-align: center;
    padding: 40px;
}

.spinner {
    border: 4px solid #f3f3f3;
    border-top: 4px solid #4ecdc4;
    border-radius: 50%;
    width: 50px;
    height: 50px;
    animation: spin 1s linear infinite;
    margin: 0 auto 20px;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.results-table {
    overflow-x: auto;
    margin-top: 20px;
}

table {
    width: 100%;
    border-collapse: collapse;
    background: white;
    border-radius: 10px;
    overflow: hidden;
    box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}

th, td {
    padding: 12px 8px;
    text-align: left;
    border-bottom: 1px solid #eee;
    font-size: 12px;
}

th {
    background: linear-gradient(45deg, #667eea, #764ba2);
    color: white;
    font-weight: bold;
    position: sticky;
    top: 0;
}

tr:hover {
    background-color: #f8f9fa;
}

td:nth-child(1) { width: 8%; }
td:nth-child(2) { width: 25%; }
td:nth-child(3) { width: 10%; }
td:nth-child(4) { width: 15%; }
td:nth-child(5) { width: 12%; }
td:nth-child(6) { width: 15%; }
td:nth-child(7) { width: 8%; }
td:nth-child(8) { width: 25%; }

.copy-btn {
    background: #4ecdc4;
    color: white;
    border: none;
    padding: 4px 8px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 10px;
    margin-left: 5px;
}

.copy-btn:hover {
    background: #44a08d;
}

.error {
    background: #ffebee;
    color: #c62828;
    padding: 20px;
    border-radius: 10px;
    text-align: center;
    border: 1px solid #ffcdd2;
}

.hidden {
    display: none;
}

@media (max-width: 768px) {
    .container {
        margin: 10px;
        border-radius: 10px;
    }
    
    h1 {
        font-size: 1.8em;
        padding: 20px;
    }
    
    .search-section, .results-section {
        padding: 20px;
    }
    
    .search-input-group {
        flex-direction: column;
    }
    
    .results-controls {
        flex-direction: column;
        gap: 15px;
        align-items: stretch;
    }
    
    .filter-group {
        display: block;
        margin: 10px 0;
    }
    
    table {
        font-size: 10px;
    }
    
    th, td {
        padding: 8px 4px;
    }
}
```

```javascript:script.js
class YouTubeSearchTool {
    constructor() {
        this.apiKey = 'AIzaSyBjOpGZloLYRODbhLHmwBHAiDGW5gyL-kA';
        this.baseUrl = 'https://www.googleapis.com/youtube/v3';
        this.searchResults = [];
        
        this.initializeEventListeners();
    }
    
    initializeEventListeners() {
        document.getElementById('searchBtn').addEventListener('click', () => this.searchVideos());
        document.getElementById('downloadBtn').addEventListener('click', () => this.downloadResults());
        document.getElementById('copyColumn8Btn').addEventListener('click', () => this.copyColumn8());
        
        // Enter key để tìm kiếm
        document.getElementById('searchKeyword').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.searchVideos();
            }
        });
    }
    
    async searchVideos() {
        const keyword = document.getElementById('searchKeyword').value.trim();
        const videoCount = parseInt(document.getElementById('videoCount').value);
        
        if (!keyword) {
            alert('Vui lòng nhập từ khóa tìm kiếm!');
            return;
        }
        
        this.showLoading();
        this.hideError();
        
        try {
            const filters = this.getSearchFilters();
            const searchParams = {
                part: 'snippet',
                q: keyword,
                type: 'video',
                maxResults: Math.min(videoCount, 50),
                key: this.apiKey,
                ...filters
            };
            
            const response = await fetch(`${this.baseUrl}/search?${new URLSearchParams(searchParams)}`);
            const data = await response.json();
            
            if (data.error) {
                throw new Error(data.error.message);
            }
            
            if (data.items && data.items.length > 0) {
                await this.getVideoDetails(data.items, keyword);
            } else {
                this.showError('Không tìm thấy video nào với từ khóa này.');
            }
            
        } catch (error) {
            console.error('Search error:', error);
            this.showError('Có lỗi xảy ra khi tìm kiếm: ' + error.message);
        }
        
        this.hideLoading();
    }
    
    getSearchFilters() {
        const filters = {};
        
        const uploadDate = document.getElementById('uploadDate').value;
        if (uploadDate) {
            const dateMap = {
                'hour': '2024-01-01T00:00:00Z',
                'today': '2024-01-01T00:00:00Z',
                'week': '2024-01-01T00:00:00Z',
                'month': '2024-01-01T00:00:00Z',
                'year': '2024-01-01T00:00:00Z'
            };
            filters.publishedAfter = dateMap[uploadDate];
        }
        
        const sortBy = document.getElementById('sortBy').value;
        if (sortBy) {
            const sortMap = {
                'relevance': 'relevance',
                'date': 'date',
                'viewCount': 'viewCount',
                'rating': 'rating'
            };
            filters.order = sortMap[sortBy];
        }
        
        return filters;
    }
    
    async getVideoDetails(videoItems, keyword) {
        try {
            const videoIds = videoItems.map(item => item.id.videoId).join(',');
            const response = await fetch(`${this.baseUrl}/videos?part=snippet,contentDetails&id=${videoIds}&key=${this.apiKey}`);
            const data = await response.json();
            
            if (data.error) {
                throw new Error(data.error.message);
            }
            
            this.searchResults = data.items.map((video, index) => {
                const searchItem = videoItems[index];
                return {
                    keyword: keyword,
                    title: video.snippet.title,
                    videoId: video.id,
                    videoUrl: `https://www.youtube.com/watch?v=${video.id}`,
                    channelName: video.snippet.channelTitle,
                    channelUrl: `https://www.youtube.com/@${video.snippet.channelId}`,
                    duration: this.formatDuration(video.contentDetails.duration),
                    summary: this.createSummary(video.snippet.channelTitle, video.snippet.channelId, video.snippet.title, video.id)
                };
            });
            
            this.displayResults();
            document.getElementById('downloadBtn').disabled = false;
            document.getElementById('copyColumn8Btn').disabled = false;
            
        } catch (error) {
            console.error('Video details error:', error);
            this.showError('Có lỗi xảy ra khi lấy thông tin video: ' + error.message);
        }
    }
    
    formatDuration(duration) {
        const match = duration.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);
        if (!match) return '00:00';
        
        const hours = parseInt(match[1] || 0);
        const minutes = parseInt(match[2] || 0);
        const seconds = parseInt(match[3] || 0);
        
        if (hours > 0) {
            return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        } else {
            return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        }
    }
    
    createSummary(channelName, channelId, title, videoId) {
        return `${channelName}--https://www.youtube.com/@${channelId}--${title}--https://www.youtube.com/watch?v=${videoId}&ab_channel=${channelId}--${this.formatDuration}`;
    }
    
    displayResults() {
        const tbody = document.getElementById('resultsBody');
        tbody.innerHTML = '';
        
        this.searchResults.forEach((result, index) => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${result.keyword}</td>
                <td>${result.title}</td>
                <td>${result.videoId}</td>
                <td><a href="${result.videoUrl}" target="_blank">${result.videoUrl}</a></td>
                <td>${result.channelName}</td>
                <td><a href="${result.channelUrl}" target="_blank">${result.channelUrl}</a></td>
                <td>${result.duration}</td>
                <td>
                    <span class="summary-text">${result.summary}</span>
                    <button class="copy-btn" onclick="copyToClipboard('${result.summary.replace(/'/g, "\\'")}')">Copy</button>
                </td>
            `;
            tbody.appendChild(row);
        });
        
        document.getElementById('results').classList.remove('hidden');
    }
    
    downloadResults() {
        if (this.searchResults.length === 0) {
            alert('Không có dữ liệu để tải về!');
            return;
        }
        
        const csvContent = this.generateCSV();
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        
        if (link.download !== undefined) {
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', `youtube_search_results_${new Date().toISOString().split('T')[0]}.csv`);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    }
    
    generateCSV() {
        const headers = ['Từ khóa', 'Tiêu đề video', 'Link video (ID)', 'Link video (Full)', 'Tên kênh', 'Link kênh', 'Thời lượng', 'Tổng hợp'];
        const rows = this.searchResults.map(result => [
            result.keyword,
            `"${result.title}"`,
            result.videoId,
            result.videoUrl,
            result.channelName,
            result.channelUrl,
            result.duration,
            `"${result.summary}"`
        ]);
        
        return [headers, ...rows].map(row => row.join(',')).join('\n');
    }

    copyColumn8() {
        if (this.searchResults.length === 0) {
            alert('Không có dữ liệu để copy!');
            return;
        }
        
        // Lấy tất cả dữ liệu cột 8 (summary)
        const column8Data = this.searchResults.map(result => result.summary);
        
        // Chuyển đổi thành text với xuống dòng ngăn cách
        const textToCopy = column8Data.join('\n');
        
        // Copy vào clipboard
        navigator.clipboard.writeText(textToCopy).then(() => {
            // Tạo thông báo tạm thời
            const notification = document.createElement('div');
            notification.textContent = 'Đã copy cột 8!';
            notification.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: #4ecdc4;
                color: white;
                padding: 10px 20px;
                border-radius: 5px;
                z-index: 1000;
                font-weight: bold;
            `;
            document.body.appendChild(notification);
            
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 2000);
        }).catch(err => {
            console.error('Copy failed:', err);
            alert('Không thể copy. Vui lòng copy thủ công.');
        });
    }
    
    showLoading() {
        document.getElementById('loading').classList.remove('hidden');
        document.getElementById('results').classList.add('hidden');
    }
    
    hideLoading() {
        document.getElementById('loading').classList.add('hidden');
    }
    
    showError(message) {
        const errorDiv = document.getElementById('error');
        errorDiv.querySelector('p').textContent = message;
        errorDiv.classList.remove('hidden');
    }
    
    hideError() {
        document.getElementById('error').classList.add('hidden');
    }
}

// Hàm copy to clipboard
function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        // Tạo thông báo tạm thời
        const notification = document.createElement('div');
        notification.textContent = 'Đã copy!';
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: #4ecdc4;
            color: white;
            padding: 10px 20px;
            border-radius: 5px;
            z-index: 1000;
            font-weight: bold;
        `;
        document.body.appendChild(notification);
        
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 2000);
    }).catch(err => {
        console.error('Copy failed:', err);
        alert('Không thể copy. Vui lòng copy thủ công.');
    });
}

// Khởi tạo ứng dụng khi trang được tải
document.addEventListener('DOMContentLoaded', () => {
    new YouTubeSearchTool();
});

