// 發起回報頁面 JavaScript 功能

// 頁面狀態
let uploadedPhotos = [];
let isSubmitting = false;
const MAX_PHOTOS = 5;
const MAX_PHOTO_SIZE = 5 * 1024 * 1024; // 5MB

// DOM 元素
let reportTitle, reportLocation, reportDate, reportTime, reportContent;
let photoInput, photoUploadArea, uploadPlaceholder, photoPreviewContainer;
let submitBtn, confirmModal;
let titleCharCount, locationCharCount, contentCharCount;

// 頁面初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeElements();
    initializeTimeOptions();
    initializeCharCounters();
    initializePhotoUpload();
    initializeForm();
    
    // 設定預設日期為今天
    setDefaultDate();
    
    console.log('發起回報頁面初始化完成');
});

// 初始化 DOM 元素
function initializeElements() {
    reportTitle = document.getElementById('reportTitle');
    reportLocation = document.getElementById('reportLocation');
    reportDate = document.getElementById('reportDate');
    reportTime = document.getElementById('reportTime');
    reportContent = document.getElementById('reportContent');
    
    photoInput = document.getElementById('reportPhotos');
    photoUploadArea = document.getElementById('photoUploadArea');
    uploadPlaceholder = document.getElementById('uploadPlaceholder');
    photoPreviewContainer = document.getElementById('photoPreviewContainer');
    
    submitBtn = document.getElementById('submitBtn');
    confirmModal = document.getElementById('confirmModal');
    
    titleCharCount = document.getElementById('titleCharCount');
    locationCharCount = document.getElementById('locationCharCount');
    contentCharCount = document.getElementById('contentCharCount');
}

// 初始化時間選項（30分鐘間隔）
function initializeTimeOptions() {
    if (!reportTime) return;
    
    for (let hour = 0; hour < 24; hour++) {
        for (let minute = 0; minute < 60; minute += 30) {
            const timeString = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
            const option = document.createElement('option');
            option.value = timeString;
            option.textContent = timeString;
            reportTime.appendChild(option);
        }
    }
}

// 初始化字數統計
function initializeCharCounters() {
    if (reportTitle && titleCharCount) {
        reportTitle.addEventListener('input', () => updateCharCount(reportTitle, titleCharCount, 120));
    }
    
    if (reportLocation && locationCharCount) {
        reportLocation.addEventListener('input', () => updateCharCount(reportLocation, locationCharCount, 120));
    }
    
    if (reportContent && contentCharCount) {
        reportContent.addEventListener('input', () => updateCharCount(reportContent, contentCharCount, 1000));
    }
}

// 更新字數統計
function updateCharCount(input, counter, maxLength) {
    const currentLength = input.value.length;
    counter.textContent = currentLength;
    
    const parent = counter.parentElement;
    parent.classList.remove('warning', 'error');
    
    if (currentLength > maxLength * 0.9) {
        parent.classList.add('warning');
    }
    
    if (currentLength >= maxLength) {
        parent.classList.add('error');
    }
    
    // 檢查表單有效性
    validateForm();
}

// 初始化照片上傳
function initializePhotoUpload() {
    if (!photoUploadArea || !photoInput) return;
    
    // 點擊上傳區域
    uploadPlaceholder.addEventListener('click', () => {
        photoInput.click();
    });
    
    // 拖拽上傳
    photoUploadArea.addEventListener('dragover', handleDragOver);
    photoUploadArea.addEventListener('dragleave', handleDragLeave);
    photoUploadArea.addEventListener('drop', handleDrop);
    
    // 文件選擇
    photoInput.addEventListener('change', handleFileSelect);
}

// 處理拖拽懸停
function handleDragOver(e) {
    e.preventDefault();
    photoUploadArea.classList.add('dragover');
}

// 處理拖拽離開
function handleDragLeave(e) {
    e.preventDefault();
    photoUploadArea.classList.remove('dragover');
}

// 處理拖拽放下
function handleDrop(e) {
    e.preventDefault();
    photoUploadArea.classList.remove('dragover');
    
    const files = Array.from(e.dataTransfer.files);
    const imageFiles = files.filter(file => file.type.startsWith('image/'));
    
    if (imageFiles.length > 0) {
        addPhotos(imageFiles);
    }
}

// 處理文件選擇
function handleFileSelect(e) {
    const files = Array.from(e.target.files);
    if (files.length > 0) {
        addPhotos(files);
    }
    // 清空 input 以允許重複選擇相同文件
    e.target.value = '';
}

// 添加照片
function addPhotos(files) {
    const remainingSlots = MAX_PHOTOS - uploadedPhotos.length;
    const filesToAdd = files.slice(0, remainingSlots);
    
    if (files.length > remainingSlots) {
        showToast(`最多只能上傳${MAX_PHOTOS}張照片`, 'error');
    }
    
    filesToAdd.forEach(file => {
        // 檢查文件大小
        if (file.size > MAX_PHOTO_SIZE) {
            showToast(`照片 ${file.name} 超過5MB，請選擇較小的文件`, 'error');
            return;
        }
        
        // 檢查文件類型
        if (!file.type.startsWith('image/')) {
            showToast(`文件 ${file.name} 不是有效的圖片格式`, 'error');
            return;
        }
        
        const photoId = Date.now() + Math.random();
        const photoData = {
            id: photoId,
            file: file,
            url: URL.createObjectURL(file)
        };
        
        uploadedPhotos.push(photoData);
        createPhotoPreview(photoData);
    });
    
    updateUploadArea();
}

// 創建照片預覽
function createPhotoPreview(photoData) {
    const previewItem = document.createElement('div');
    previewItem.className = 'photo-preview-item';
    previewItem.dataset.photoId = photoData.id;
    
    previewItem.innerHTML = `
        <img src="${photoData.url}" alt="預覽照片" class="photo-preview-image">
        <button type="button" class="photo-remove-btn" onclick="removePhoto('${photoData.id}')">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M19 6.41L17.59 5L12 10.59L6.41 5L5 6.41L10.59 12L5 17.59L6.41 19L12 13.41L17.59 19L19 17.59L13.41 12L19 6.41Z" fill="currentColor"/>
            </svg>
        </button>
    `;
    
    photoPreviewContainer.appendChild(previewItem);
}

// 移除照片
function removePhoto(photoId) {
    // 從陣列中移除
    const index = uploadedPhotos.findIndex(photo => photo.id == photoId);
    if (index !== -1) {
        // 釋放 URL 物件
        URL.revokeObjectURL(uploadedPhotos[index].url);
        uploadedPhotos.splice(index, 1);
    }
    
    // 從 DOM 中移除
    const previewItem = document.querySelector(`[data-photo-id="${photoId}"]`);
    if (previewItem) {
        previewItem.remove();
    }
    
    updateUploadArea();
}

// 更新上傳區域顯示
function updateUploadArea() {
    const hasPhotos = uploadedPhotos.length > 0;
    const canAddMore = uploadedPhotos.length < MAX_PHOTOS;
    
    if (hasPhotos) {
        uploadPlaceholder.style.display = canAddMore ? 'block' : 'none';
        if (!canAddMore) {
            uploadPlaceholder.style.display = 'none';
        } else {
            uploadPlaceholder.querySelector('.upload-text').textContent = `再上傳照片 (${uploadedPhotos.length}/${MAX_PHOTOS})`;
        }
    } else {
        uploadPlaceholder.style.display = 'block';
        uploadPlaceholder.querySelector('.upload-text').textContent = '點擊上傳照片';
    }
}

// 初始化表單驗證
function initializeForm() {
    const formInputs = [reportTitle, reportLocation, reportDate, reportContent];
    
    formInputs.forEach(input => {
        if (input) {
            input.addEventListener('input', validateForm);
            input.addEventListener('blur', validateField);
        }
    });
    
    // 初始驗證
    validateForm();
}

// 驗證單個字段
function validateField(e) {
    const field = e.target;
    const value = field.value.trim();
    
    // 移除之前的錯誤樣式
    field.classList.remove('error');
    removeFieldError(field);
    
    // 驗證必填字段
    if (field.hasAttribute('required') && !value) {
        showFieldError(field, '此欄位為必填');
        return false;
    }
    
    // 特定字段驗證
    switch (field.id) {
        case 'reportTitle':
            if (value && value.length < 5) {
                showFieldError(field, '標題至少需要5個字');
                return false;
            }
            break;
        case 'reportContent':
            if (value && value.length < 20) {
                showFieldError(field, '內容至少需要20個字');
                return false;
            }
            break;
        case 'reportDate':
            if (value) {
                const selectedDate = new Date(value);
                const today = new Date();
                today.setHours(0, 0, 0, 0);
                
                if (selectedDate > today) {
                    showFieldError(field, '日期不能選擇未來');
                    return false;
                }
            }
            break;
    }
    
    return true;
}

// 顯示字段錯誤
function showFieldError(field, message) {
    field.classList.add('error');
    
    // 移除舊的錯誤消息
    removeFieldError(field);
    
    // 添加新的錯誤消息
    const errorDiv = document.createElement('div');
    errorDiv.className = 'error-message';
    errorDiv.innerHTML = `
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M12 2C6.48 2 2 6.48 2 12S6.48 22 12 22S22 17.52 22 12S17.52 2 12 2ZM13 17H11V11H13V17ZM13 9H11V7H13V9Z" fill="currentColor"/>
        </svg>
        ${message}
    `;
    
    field.parentElement.appendChild(errorDiv);
}

// 移除字段錯誤
function removeFieldError(field) {
    const errorDiv = field.parentElement.querySelector('.error-message');
    if (errorDiv) {
        errorDiv.remove();
    }
}

// 驗證表單
function validateForm() {
    const title = reportTitle?.value.trim() || '';
    const location = reportLocation?.value.trim() || '';
    const date = reportDate?.value || '';
    const content = reportContent?.value.trim() || '';
    
    const isValid = title.length >= 5 && 
                   location.length > 0 && 
                   date && 
                   content.length >= 20;
    
    if (submitBtn) {
        submitBtn.disabled = !isValid;
        submitBtn.classList.toggle('disabled', !isValid);
    }
    
    return isValid;
}

// 設定預設日期
function setDefaultDate() {
    if (reportDate) {
        const today = new Date();
        const dateString = today.toISOString().split('T')[0];
        reportDate.value = dateString;
    }
}

// 提交回報
function submitReport() {
    if (!validateForm()) {
        showToast('請檢查並完成所有必填欄位', 'error');
        return;
    }
    
    if (isSubmitting) return;
    
    // 顯示確認對話框
    showConfirmModal();
}

// 顯示確認對話框
function showConfirmModal() {
    if (confirmModal) {
        confirmModal.style.display = 'flex';
        setTimeout(() => {
            confirmModal.classList.add('show');
        }, 10);
    }
}

// 關閉確認對話框
function closeConfirmModal() {
    if (confirmModal) {
        confirmModal.classList.remove('show');
        setTimeout(() => {
            confirmModal.style.display = 'none';
        }, 300);
    }
}

// 確認提交
function confirmSubmit() {
    closeConfirmModal();
    
    if (isSubmitting) return;
    isSubmitting = true;
    
    // 更新提交按鈕狀態
    if (submitBtn) {
        submitBtn.disabled = true;
        submitBtn.classList.add('loading');
        submitBtn.innerHTML = '<div class="loading-spinner"></div>';
    }
    
    // 收集表單資料
    const formData = collectFormData();
    
    // 模擬 API 調用
    setTimeout(() => {
        // 模擬成功提交
        showToast('回報提交成功！將在3個工作天內回覆處理情況', 'success');
        
        // 3秒後導航回 GO想 頁面
        setTimeout(() => {
            window.location.href = 'goxiang.html';
        }, 3000);
    }, 2000);
}

// 收集表單資料
function collectFormData() {
    const formData = {
        title: reportTitle?.value.trim() || '',
        location: reportLocation?.value.trim() || '',
        date: reportDate?.value || '',
        timeSlot: reportTime?.value || null,
        content: reportContent?.value.trim() || '',
        photos: uploadedPhotos.map(photo => photo.file),
        submittedAt: new Date().toISOString()
    };
    
    console.log('收集的表單資料:', formData);
    return formData;
}

// 返回上一頁
function goBack() {
    // 檢查是否有未保存的內容
    const hasContent = (reportTitle?.value.trim() || '') ||
                      (reportLocation?.value.trim() || '') ||
                      (reportContent?.value.trim() || '') ||
                      uploadedPhotos.length > 0;
    
    if (hasContent) {
        const confirmLeave = confirm('您有未保存的內容，確定要離開嗎？');
        if (!confirmLeave) return;
    }
    
    // 清理上傳的照片 URL
    uploadedPhotos.forEach(photo => {
        URL.revokeObjectURL(photo.url);
    });
    
    window.location.href = 'goxiang.html';
}

// 顯示 Toast 通知
function showToast(message, type = 'success') {
    const toast = document.getElementById('toast');
    const toastMessage = toast?.querySelector('.toast-message');
    const toastIcon = toast?.querySelector('.toast-icon');
    
    if (toast && toastMessage) {
        toastMessage.textContent = message;
        
        // 重置類別
        toast.classList.remove('error', 'info', 'success');
        
        // 設定圖示和樣式
        switch (type) {
            case 'success':
                toastIcon.textContent = '✓';
                toast.classList.add('success');
                break;
            case 'error':
                toastIcon.textContent = '✕';
                toast.classList.add('error');
                break;
            case 'info':
                toastIcon.textContent = 'i';
                toast.classList.add('info');
                break;
        }
        
        toast.classList.add('show');
        
        setTimeout(() => {
            toast.classList.remove('show');
        }, 4000);
    }
}

// 頁面卸載時清理資源
window.addEventListener('beforeunload', function() {
    uploadedPhotos.forEach(photo => {
        URL.revokeObjectURL(photo.url);
    });
});

// 防止表單意外提交
document.addEventListener('keydown', function(e) {
    if (e.key === 'Enter' && e.target.tagName !== 'TEXTAREA') {
        e.preventDefault();
    }
});

// 導出主要功能（供測試使用）
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        validateForm,
        addPhotos,
        removePhoto,
        showToast
    };
}
