let currentTask = null;
let taskStartTime = 0;
let timerInterval = null;

function applyFilters() {
    const type = document.getElementById('filterType').value;
    const difficulty = document.getElementById('filterDiff').value;
    const search = document.getElementById('searchInput').value;
    
    const params = new URLSearchParams();
    if (type !== 'all') params.append('type', type);
    if (difficulty !== 'all') params.append('difficulty', difficulty);
    if (search) params.append('search', search);
    
    window.location.href = 'tasks.php' + (params.toString() ? '?' + params.toString() : '');
}

async function openTaskModal(task) {
    console.log('Opening task:', task);
    currentTask = task;
    taskStartTime = Math.floor(Date.now() / 1000);
    
    const modal = document.getElementById('taskModal');
    const modalTitle = document.getElementById('modalTaskTitle');
    const modalContent = document.getElementById('modalTaskContent');
    
    if (!modal || !modalTitle || !modalContent) {
        console.error('Modal elements not found!');
        alert('Modal error! Check console.');
        return;
    }
    
    modalTitle.textContent = task.title || 'Task Details';
    
    let content = `
        <div style="background: var(--darker-bg); padding: 16px; border-radius: 12px; margin-bottom: 20px; border: 2px solid var(--border-color);">
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 16px;">
                <div>
                    <div style="color: var(--text-secondary); margin-bottom: 6px; font-size: 11px; font-weight: 700; text-transform: uppercase;">Type</div>
                    <div style="font-weight: 800; color: var(--text-primary); font-size: 14px;">${(task.task_type || 'task').toUpperCase()}</div>
                </div>
                <div>
                    <div style="color: var(--text-secondary); margin-bottom: 6px; font-size: 11px; font-weight: 700; text-transform: uppercase;">Difficulty</div>
                    <div style="font-weight: 800; color: var(--text-primary); font-size: 14px;">${(task.difficulty || 'medium').toUpperCase()}</div>
                </div>
                <div>
                    <div style="color: var(--text-secondary); margin-bottom: 6px; font-size: 11px; font-weight: 700; text-transform: uppercase;">Reward</div>
                    <div style="font-weight: 900; background: var(--gradient-success); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-size: 18px;">Ksh ${parseFloat(task.reward || 0).toFixed(2)}</div>
                </div>
                <div>
                    <div style="color: var(--text-secondary); margin-bottom: 6px; font-size: 11px; font-weight: 700; text-transform: uppercase;">Times/Day</div>
                    <div style="font-weight: 800; color: var(--text-primary); font-size: 14px;">${task.daily_limit_per_user || 1}x</div>
                </div>
            </div>
        </div>
        
        <div class="instructions-box">
            <div class="instructions-title"><i class="fas fa-list-check"></i> Instructions</div>
            <div style="color: var(--text-secondary); margin-bottom: 16px; line-height: 1.6; font-size: 14px;">${task.description || 'Complete this task.'}</div>
        </div>
    `;
    
    if (task.task_url) {
        content += `
            <div style="background: var(--gradient-info); padding: 16px; border-radius: 12px; margin-bottom: 20px; text-align: center;">
                <div style="color: white; margin-bottom: 12px; font-weight: 700; font-size: 14px;">
                    <i class="fas fa-external-link-alt"></i> External Task Link
                </div>
                <a href="${task.task_url}" target="_blank" style="display: inline-block; background: white; color: #3b82f6; padding: 10px 24px; border-radius: 10px; font-weight: 800; text-decoration: none;">
                    Open Task Link <i class="fas fa-arrow-right"></i>
                </a>
            </div>
        `;
    }
    
    if ((task.min_duration_seconds || 0) > 0) {
        content += `
            <div class="timer-box">
                <div style="font-size: 12px; margin-bottom: 10px;"><i class="fas fa-stopwatch"></i> Timer</div>
                <div class="timer-value" id="taskTimer">00:00</div>
                <div style="margin-top: 10px; font-size: 12px;">Min ${task.min_duration_seconds}s required</div>
            </div>
        `;
        setTimeout(() => startTimer(task.min_duration_seconds), 100);
    }
    
    if (task.content_type === 'internal') {
        content += '<div class="content-loading"><i class="fas fa-spinner fa-spin"></i><div style="margin-top: 16px;">Loading...</div></div>';
        
        modalContent.innerHTML = content;
        modal.classList.add('active');
        document.body.style.overflow = 'hidden';
        
        try {
            console.log('Fetching AJAX...');
            const response = await fetch(`tasks.php?ajax=get_task_content&task_id=${task.id}`);
            const data = await response.json();
            console.log('Response:', data);
            
            if (data.success && data.content) {
                const taskContent = renderTaskContent(data.content, task);
                content = content.replace(/<div class="content-loading">.*?<\/div>/s, taskContent);
                modalContent.innerHTML = content;
            } else {
                content += `<div style="padding: 20px; text-align: center; color: #ef4444;">Error: ${data.error || 'Failed to load'}</div>`;
                modalContent.innerHTML = content;
            }
        } catch (error) {
            console.error('Error:', error);
            content += '<div style="padding: 20px; text-align: center; color: #ef4444;">Error loading content.</div>';
            modalContent.innerHTML = content;
        }
    } else {
        content += renderExternalTaskForm(task);
        modalContent.innerHTML = content;
        modal.classList.add('active');
        document.body.style.overflow = 'hidden';
    }
}

function renderTaskContent(content, task) {
    switch (content.type) {
        case 'quiz':
            return renderQuizContent(content.questions, task);
        case 'survey':
            return renderSurveyContent(content.questions, task);
        case 'blog':
            return renderBlogContent(content.requirements, task);
        default:
            return renderExternalTaskForm(task);
    }
}

function renderQuizContent(questions, task) {
    if (!questions || questions.length === 0) {
        return '<div style="padding: 20px; text-align: center;">No questions available.</div>';
    }
    
    let html = `
        <form method="POST" enctype="multipart/form-data" onsubmit="return validateSubmission()">
            <input type="hidden" name="action" value="complete_task">
            <input type="hidden" name="task_id" value="${task.id}">
            <input type="hidden" name="start_time" value="${taskStartTime}">
            
            <h3 style="font-size: 18px; font-weight: 900; margin-bottom: 20px;">
                <i class="fas fa-question-circle"></i> Answer All Questions (70%+ to Pass)
            </h3>
    `;
    
    questions.forEach((q, i) => {
        html += `
            <div class="quiz-question">
                <span class="question-number">Question ${i + 1} of ${questions.length}</span>
                <div class="question-text">${q.question}</div>
                <div class="quiz-options">
        `;
        
        ['A', 'B', 'C', 'D'].forEach(opt => {
            const key = `option_${opt.toLowerCase()}`;
            const text = q[key];
            if (text) {
                html += `
                    <div class="quiz-option">
                        <input type="radio" name="quiz_answers[${q.id}]" value="${opt}" id="q${q.id}_${opt}" required>
                        <label for="q${q.id}_${opt}"><strong>${opt}.</strong> ${text}</label>
                    </div>
                `;
            }
        });
        
        html += '</div></div>';
    });
    
    html += '<button type="submit" class="btn-start-task" style="margin-top: 20px;"><i class="fas fa-paper-plane"></i> Submit Quiz</button></form>';
    
    return html;
}

function renderSurveyContent(questions, task) {
    if (!questions || questions.length === 0) {
        return '<div style="padding: 20px; text-align: center;">No questions available.</div>';
    }
    
    let html = `
        <form method="POST" enctype="multipart/form-data" onsubmit="return validateSubmission()">
            <input type="hidden" name="action" value="complete_task">
            <input type="hidden" name="task_id" value="${task.id}">
            <input type="hidden" name="start_time" value="${taskStartTime}">
            
            <h3 style="font-size: 18px; font-weight: 900; margin-bottom: 20px;">
                <i class="fas fa-clipboard-list"></i> Complete This Survey
            </h3>
    `;
    
    questions.forEach((q, i) => {
        html += `<div class="survey-question"><label class="survey-label">${i + 1}. ${q.question} ${q.required == 1 ? '<span style="color: #ef4444;">*</span>' : ''}</label>`;
        
        switch (q.question_type) {
            case 'text':
                html += `<input type="text" name="survey_answers[${q.id}]" class="survey-input" placeholder="Your answer..." ${q.required == 1 ? 'required' : ''}>`;
                break;
            case 'textarea':
                html += `<textarea name="survey_answers[${q.id}]" class="survey-input" placeholder="Your answer..." ${q.required == 1 ? 'required' : ''}></textarea>`;
                break;
            case 'multiple_choice':
                if (q.options) {
                    q.options.split('|').forEach((opt, j) => {
                        html += `<div class="survey-option"><input type="radio" name="survey_answers[${q.id}]" value="${opt}" id="s${q.id}_${j}" ${q.required == 1 ? 'required' : ''}><label for="s${q.id}_${j}">${opt}</label></div>`;
                    });
                }
                break;
        }
        
        html += '</div>';
    });
    
    html += '<button type="submit" class="btn-start-task" style="margin-top: 20px;"><i class="fas fa-paper-plane"></i> Submit Survey</button></form>';
    
    return html;
}

function renderBlogContent(req, task) {
    const min = req?.min_words || 300;
    const max = req?.max_words || 1500;
    
    return `
        <form method="POST" enctype="multipart/form-data" onsubmit="return validateSubmission()">
            <input type="hidden" name="action" value="complete_task">
            <input type="hidden" name="task_id" value="${task.id}">
            <input type="hidden" name="start_time" value="${taskStartTime}">
            
            <div class="blog-requirements">
                <h4><i class="fas fa-info-circle"></i> Requirements</h4>
                <p>Word Count: ${min} - ${max} words</p>
            </div>
            
            <input type="text" name="blog_title" class="blog-input-title" placeholder="Blog title..." required>
            <textarea name="blog_content" id="blogContent" class="blog-textarea" placeholder="Write your blog here..." required oninput="updateWordCount()"></textarea>
            <div class="word-counter">Words: <span id="wordCount">0</span> / ${min}-${max}</div>
            
            <button type="submit" class="btn-start-task" style="margin-top: 20px;"><i class="fas fa-paper-plane"></i> Submit Blog</button>
        </form>
    `;
}

function renderExternalTaskForm(task) {
    return `
        <form method="POST" enctype="multipart/form-data" onsubmit="return validateSubmission()">
            <input type="hidden" name="action" value="complete_task">
            <input type="hidden" name="task_id" value="${task.id}">
            <input type="hidden" name="start_time" value="${taskStartTime}">
            
            <div class="form-group">
                <label class="form-label"><i class="fas fa-camera"></i> Upload Screenshot ${task.requires_proof ? '(Required)' : '(Optional)'}</label>
                <div class="file-upload-area" onclick="document.getElementById('proofScreenshot').click()">
                    <i class="fas fa-cloud-upload-alt"></i>
                    <div><div style="font-weight: 700; margin-bottom: 4px;">Click to upload</div><div style="font-size: 12px;">JPG, PNG, GIF (Max 5MB)</div></div>
                </div>
                <input type="file" name="proof_screenshot" id="proofScreenshot" class="file-upload-input" accept="image/*" ${task.requires_proof ? 'required' : ''} onchange="previewFile(this)">
                <div class="file-preview" id="filePreview">
                    <div id="fileName"></div>
                    <div id="fileSize"></div>
                    <img id="fileImage" alt="Preview" style="max-width: 100%; margin-top: 12px;">
                </div>
            </div>
            
            <div class="form-group">
                <label class="form-label"><i class="fas fa-comment"></i> Additional Info (Optional)</label>
                <textarea name="proof_text" class="form-control" placeholder="Username, code, notes..."></textarea>
            </div>
            
            <button type="submit" class="btn-start-task" style="margin-top: 20px;"><i class="fas fa-check"></i> Submit Task</button>
        </form>
    `;
}

function updateWordCount() {
    const textarea = document.getElementById('blogContent');
    const counter = document.getElementById('wordCount');
    if (textarea && counter) {
        const words = textarea.value.trim() ? textarea.value.trim().split(/\s+/).length : 0;
        counter.textContent = words;
    }
}

function previewFile(input) {
    const file = input.files[0];
    if (file) {
        document.getElementById('fileName').textContent = file.name;
        document.getElementById('fileSize').textContent = formatFileSize(file.size);
        
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('fileImage').src = e.target.result;
            document.getElementById('filePreview').classList.add('active');
        };
        reader.readAsDataURL(file);
    }
}

function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
}

function closeTaskModal() {
    document.getElementById('taskModal').classList.remove('active');
    document.body.style.overflow = '';
    if (timerInterval) {
        clearInterval(timerInterval);
        timerInterval = null;
    }
}

function startTimer(minSeconds) {
    let elapsed = 0;
    const timer = document.getElementById('taskTimer');
    if (!timer) return;
    
    timerInterval = setInterval(() => {
        elapsed++;
        const min = Math.floor(elapsed / 60);
        const sec = elapsed % 60;
        timer.textContent = String(min).padStart(2, '0') + ':' + String(sec).padStart(2, '0');
        
        if (elapsed >= minSeconds) {
            timer.style.color = '#10b981';
        }
    }, 1000);
}

function validateSubmission() {
    if (!currentTask) return false;
    
    const elapsed = Math.floor(Date.now() / 1000) - taskStartTime;
    const minDuration = currentTask.min_duration_seconds || 0;
    
    if (minDuration > 0 && elapsed < minDuration) {
        alert(`Please spend at least ${minDuration} seconds on this task.`);
        return false;
    }
    
    if (currentTask.content_type === 'internal' && (currentTask.task_type === 'quiz' || currentTask.task_type === 'trivia')) {
        const groups = document.querySelectorAll('.quiz-question');
        for (let group of groups) {
            const radios = group.querySelectorAll('input[type="radio"]');
            const checked = Array.from(radios).some(r => r.checked);
            if (!checked) {
                alert('Please answer all questions!');
                return false;
            }
        }
    }
    
    return confirm('Submit this task?');
}

window.addEventListener('DOMContentLoaded', function() {
    const modal = document.getElementById('taskModal');
    if (modal) {
        modal.addEventListener('click', function(e) {
            if (e.target === this) closeTaskModal();
        });
    }
});

document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        const modal = document.getElementById('taskModal');
        if (modal && modal.classList.contains('active')) closeTaskModal();
    }
});