document.addEventListener('DOMContentLoaded', function () {
    const btnGenerate = document.getElementById('btnGenerate');
    const btnExport = document.getElementById('btnExport');
    const fileInput = document.getElementById('videoFiles');
    const logElement = document.getElementById('log');
    const thumbnailPreview = document.getElementById('thumbnailPreview');
    const resultsContainer = document.getElementById('resultsContainer');
    const fileListContainer = document.getElementById('fileListContainer');
    const progressCounter = document.getElementById('progressCounter');
    const successCountEl = document.getElementById('successCount');
    const failedCountEl = document.getElementById('failedCount');
    let processedResults = [];

    // ---- Drag & Drop batch upload ----
    const dropZone = document.getElementById('dropZone');
    let files = [];
    dropZone.addEventListener('dragover', function (e) {
        e.preventDefault(); dropZone.classList.add('dragover');
    });
    dropZone.addEventListener('dragleave', function () {
        dropZone.classList.remove('dragover');
    });
    dropZone.addEventListener('drop', function (e) {
        e.preventDefault(); dropZone.classList.remove('dragover');
        files = Array.from(e.dataTransfer.files);
        renderFileList();
    });
    fileInput.addEventListener('change', function () {
        files = Array.from(fileInput.files);
        renderFileList();
    });
    function renderFileList() {
        fileListContainer.innerHTML = '';
        files.forEach((file, idx) => {
            const li = document.createElement('li');
            li.className = 'list-group-item d-flex justify-content-between align-items-center';
            li.innerHTML = `<span>${file.name} (${(file.size / 1024 / 1024).toFixed(2)}MB)</span>
                <span class="badge bg-secondary" id="status-${idx}">Chờ xử lý</span>`;
            fileListContainer.appendChild(li);
        });
    }

    // ---- Logging ----
    function appendLog(message, color = 'black') {
        logElement.innerHTML += `<span style="color:${color}">${message}</span><br>`;
        logElement.scrollTop = logElement.scrollHeight;
    }

    // ---- Show/result cards ----
    function displayResult(data, thumbnailPath) {
        const resultCard = document.createElement('div'); 
        resultCard.className = 'result-card card mb-3';
        resultCard.innerHTML = `
        <div class="row g-0">
            <div class="col-md-3">
                <img src="${thumbnailPath}" class="img-fluid rounded-start thumbnail" alt="Thumbnail for ${data.Filename}">
            </div>
            <div class="col-md-9">
                <div class="card-body">
                    <div class="filename">${data.Filename}</div>
                    <div class="title">${data.Title}</div>
                    <div class="description mb-2"><strong>Description:</strong> <span>${data.Description}</span></div>
                    <div class="keywords-container">${(data.Keywords || '').split(',').map(kw =>
                        `<span class="keyword-tag">${kw.trim()}</span>`).join('')}</div>
                    <div class="mt-1"><strong>Category:</strong> <span>${data.Category}</span></div>
                    <div><strong>Status:</strong> <span class="badge bg-success">${data.Status}</span></div>
                </div>
            </div>
        </div>
        `;
		// Sau khi nhận response thành công và có thumbnailPath từ server 
		if (thumbnailPath) {
			thumbnailPreview.src = thumbnailPath;
			thumbnailPreview.style.display = 'block';
		}

	
        resultsContainer.appendChild(resultCard);
    }

    // ---- Long polling status ----
    function pollStatus() {
        fetch('status.php')
            .then(response => response.json())
            .then(data => {
                if (data.success && data.data) {
                    const status = data.data;
                    progressCounter.textContent = `${status.processed}/${status.total}`;
                    successCountEl.textContent = status.processed - status.failed;
                    failedCountEl.textContent = status.failed;
                    document.getElementById('statusMessage').textContent = status.message;
                    if (status.total > 0) {
                        const percent = Math.round(100 * status.processed / status.total);
                        document.getElementById('progressBar').style.width = percent + '%';
                    }
                }
            })
            .finally(() => {
                setTimeout(pollStatus, 5000);
            });
    }
    pollStatus();

 

    // ---- Batch process ----
    btnGenerate.addEventListener('click', async function () {
        if (!files.length) {
            alert('Vui lòng chọn hoặc kéo thả ít nhất một file.');
            return;
        }
        const buttonIcon = btnGenerate.querySelector('i');
        const spinner = btnGenerate.querySelector('.spinner-border');
        buttonIcon.classList.add('d-none');
        spinner.classList.remove('d-none');
        btnGenerate.disabled = true;

        let successCount = 0, failedCount = 0;
        successCountEl.textContent = '0';
        failedCountEl.textContent = '0';
        progressCounter.style.display = 'block';
        btnExport.disabled = true;
        processedResults = [];
        resultsContainer.innerHTML = '';
        logElement.innerHTML = '';
        thumbnailPreview.style.display = 'none';

        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            const formData = new FormData();
            formData.append('videoFile', file);
            formData.append('apiKey', document.getElementById('apiKey').value);
            formData.append('aiEngine', document.getElementById('aiEngine').value);
            formData.append('customPrompt', document.getElementById('customPrompt').value);
            formData.append('geminiModel', document.getElementById('geminiModel').value);

            if (document.getElementById(`status-${i}`)) {
                document.getElementById(`status-${i}`).textContent = 'Đang xử lý...';
                document.getElementById(`status-${i}`).className = 'badge bg-warning';
            }
            appendLog(`Processing ${file.name}`, 'orange');
            try {
                const response = await fetch('process_files.php', { method: 'POST', body: formData });
                const result = await response.json();
                if (result.success) {
                    appendLog(`Success ${file.name}`, 'green');
                    processedResults.push(result);
                    displayResult(result.data, result.thumbnailpath);
                    successCount++;
                    if (document.getElementById(`status-${i}`)) {
                        document.getElementById(`status-${i}`).textContent = 'Thành công';
                        document.getElementById(`status-${i}`).className = 'badge bg-success';
                    }
                } else {
                    appendLog(`Error ${result.message}`, 'red');
                    failedCount++;
                    if (document.getElementById(`status-${i}`)) {
                        document.getElementById(`status-${i}`).textContent = 'Lỗi';
                        document.getElementById(`status-${i}`).className = 'badge bg-danger';
                    }
                }
            } catch (error) {
                appendLog(`Critical Error processing ${file.name}: ${error}`, 'red');
                failedCount++;
                if (document.getElementById(`status-${i}`)) {
                    document.getElementById(`status-${i}`).textContent = 'Lỗi lớn';
                    document.getElementById(`status-${i}`).className = 'badge bg-danger';
                }
            } finally {
                successCountEl.textContent = successCount;
                failedCountEl.textContent = failedCount;
            }
        }
        appendLog("All files processed!");
        buttonIcon.classList.remove('d-none');
        spinner.classList.add('d-none');
        btnGenerate.disabled = false;

        // Hiện thumbnail cuối cùng
        if (processedResults.length) {
            btnExport.disabled = false;
			autoSaveCSVToTemp();
            const lastResult = processedResults[processedResults.length - 1];
			document.getElementById('thumbnailPreview').src = lastResult.thumbnailpath;
			document.getElementById('thumbnailPreview').style.display = 'block';

 
            alert('Tất cả file đã xử lý xong! Bạn có thể xuất CSV.');
        }
    });

			// ---- Export CSV đa format ----
 btnExport.addEventListener('click', function (event) {
    event.preventDefault();
    const processedMetadata = processedResults.map(r => r.data);
    if (!processedMetadata.length) {
        alert("Không có metadata export.");
        return;
    }
    const format = document.getElementById('exportFormat').value;
    let headers, dataRows;

    if (format === 'adobe') {
        headers = ['Filename', 'Title', 'Description', 'Keywords', 'Category'];
        dataRows = processedMetadata.map(item => [
            item.Filename, item.Title, item.Description, item.Keywords, item.Category
        ]);
    } else if (format === 'shutterstock') {
        headers = ['Filename', 'Title', 'Keywords', 'Category 1', 'Category 2'];
        dataRows = processedMetadata.map(item => [
            item.Filename, item.Title, item.Keywords, item.Category, ''
        ]);
    } else { // freepik
        headers = ['Filename', 'Title', 'Keywords', 'Description'];
        dataRows = processedMetadata.map(item => [
            item.Filename, item.Title, item.Keywords, item.Description
        ]);
    }

    let csvContent = headers.join(",") + "\n";
    dataRows.forEach(rowArray => {
        const row = rowArray.map(value => {
            let val = value ? value.toString().replace(/"/g, '""') : "";
            if (val.includes(",") || val.includes("\n")) val = '"' + val + '"';
            return val;
        });
        csvContent += row.join(",") + "\n";
    });

    // Đặt tên file dạng ddmmyyyy
const now = new Date();
const dd = String(now.getDate()).padStart(2, '0');
const mm = String(now.getMonth() + 1).padStart(2, '0');
const yyyy = now.getFullYear();
const hh = String(now.getHours()).padStart(2, '0');
const min = String(now.getMinutes()).padStart(2, '0');
const ss = String(now.getSeconds()).padStart(2, '0');

const dateStr = dd + mm + yyyy + '_' + hh + min + ss;
const filename = `metadata_export_${format}_${dateStr}.csv`;


    // Nếu trình duyệt hỗ trợ showSaveFilePicker, lưu local
    if (window.showSaveFilePicker) {
        (async () => {
            try {
                const handle = await window.showSaveFilePicker({
                    suggestedName: filename,
                    types: [{ description: 'CSV File', accept: { 'text/csv': ['.csv'] } }]
                });
                const writable = await handle.createWritable();
                await writable.write(csvContent);
                await writable.close();
            } catch (e) {
                alert("Lưu file bị hủy hoặc xảy ra lỗi!");
            }
        })();
    } else {
        // Nếu không hỗ trợ, tạo link download truyền thống
        const blob = new Blob([csvContent], { type: "text/csv" });
        const link = document.createElement("a");
        const url = URL.createObjectURL(blob);
        link.setAttribute("href", url);
        link.setAttribute("download", filename);
        link.style.visibility = "hidden";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
    }

    // Lưu vào TEMP server
    autoSaveCSVToTemp(csvContent, format);
});


	
				document.getElementById('btnCheckApi').addEventListener('click', function(){
				const apiKey = document.getElementById('apiKey').value.trim();
				if (!apiKey) {
					alert('Vui lòng nhập API Key bên trên!'); return;
				}
				fetch('check_quota.php', {
					method: 'POST',
					body: new URLSearchParams({ apiKey: apiKey })
				})
				.then(resp => resp.json())
				.then(data => {
					let info = '';
					if (data.success) {
						info = `<div class="alert alert-success">Gemini API vẫn khả dụng cho project này.<br>${data.quota}</div>`;
					} else {
						info = `<div class="alert alert-danger">${data.message}</div>`;
					}
					document.getElementById('quotaInfo').innerHTML = info;
					if (window.bootstrap) {
						new bootstrap.Modal(document.getElementById('quotaModal')).show();
					} else {
						$('#quotaModal').modal('show'); // Nếu dùng Bootstrap 4 hoặc 5 với jQuery
					}
				})
				.catch(e => {
					document.getElementById('quotaInfo').innerHTML = `<div class="alert alert-danger">Không kiểm tra được: ${e}</div>`;
					if (window.bootstrap) {
						new bootstrap.Modal(document.getElementById('quotaModal')).show();
					} else {
						$('#quotaModal').modal('show');
					}
				});
			});
			
			
			function autoSaveCSVToTemp(csvContent, format) {
const now = new Date();
const dd = String(now.getDate()).padStart(2, '0');
const mm = String(now.getMonth() + 1).padStart(2, '0');
const yyyy = now.getFullYear();
const hh = String(now.getHours()).padStart(2, '0');
const min = String(now.getMinutes()).padStart(2, '0');
const ss = String(now.getSeconds()).padStart(2, '0');

const dateStr = dd + mm + yyyy + '_' + hh + min + ss;
const filename = `metadata_export_${format}_${dateStr}.csv`;


				fetch('save_temp_csv.php', {
					method: 'POST',
					headers: { 'Content-Type': 'application/json' },
					body: JSON.stringify({
						csv: csvContent,
						filename: filename
					})
				})
				.then(res => res.json())
				.then(data => {
					if (data.success) {
						console.log('File đã tự động lưu vào TEMP:', data.temp_path);
					} else {
						console.warn('Lưu TEMP thất bại:', data.message);
					}
				})
				.catch(err => {
					console.error('Lỗi gửi TEMP:', err);
				});
			}


});
