/**
 * Aysa Task Management JavaScript
 * Handles task detail modals, progress tracking, and task interactions
 */

jQuery(document).ready(function($) {
    
    initializeTaskManagement();
    
    function initializeTaskManagement() {
        $('.aysa-task-checkbox').on('change', function() {
            const taskItem = $(this).closest('.aysa-task-item');
            const isChecked = $(this).is(':checked');
            
            if (isChecked) {
                taskItem.attr('data-status', 'completed');
                updateTaskProgress(taskItem, 100);
            } else {
                taskItem.attr('data-status', 'pending');
                updateTaskProgress(taskItem, 0);
            }
        });
        
        $(document).on('click', '.aysa-task-detail-close', function() {
            $('.aysa-task-detail-modal').hide();
        });
        
        $(document).on('click', '.aysa-task-detail-modal', function(e) {
            if (e.target === this) {
                $(this).hide();
            }
        });
        
        $(document).on('keydown', function(e) {
            if (e.key === 'Escape') {
                $('.aysa-task-detail-modal').hide();
            }
        });
    }
    
    function updateTaskProgress(taskItem, percentage) {
        const progressBar = taskItem.find('.progress-bar');
        const progressText = taskItem.find('.progress-text');
        
        progressBar.css('--percentage', percentage + '%');
        progressText.text(percentage + '% Complete');
        
        if (percentage === 100) {
            progressBar.css('--progress-color', '#34a853');
        } else if (percentage > 0) {
            progressBar.css('--progress-color', '#2271b1');
        } else {
            progressBar.css('--progress-color', '#e0e0e0');
        }
    }
    
    window.openTaskDetail = function(taskId) {
        if ($('#aysa-task-detail-modal').length === 0) {
            createTaskDetailModal();
        }
        
        loadTaskDetails(taskId);
        
        $('#aysa-task-detail-modal').show();
    };
    
    function createTaskDetailModal() {
        const modalHtml = `
            <div id="aysa-task-detail-modal" class="aysa-task-detail-modal">
                <div class="aysa-task-detail-content">
                    <div class="aysa-task-detail-header">
                        <h3 id="task-detail-title">Task Details</h3>
                        <button class="aysa-task-detail-close">&times;</button>
                    </div>
                    <div class="aysa-task-detail-body">
                        <div id="task-detail-content">
                            <div class="aysa-loading">Loading task details...</div>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        $('body').append(modalHtml);
    }
    
    function loadTaskDetails(taskId) {
        const dummyData = getDummyTaskData(taskId);
        renderTaskDetails(dummyData);
        
    }
    
    function getDummyTaskData(taskId) {
        const dummyTasks = {
            'auto-1': {
                title: 'Set up automated link building campaigns',
                status: 'in-progress',
                progress: 65,
                type: 'automated',
                estimatedTime: '2 hours remaining',
                completedSteps: 3,
                totalSteps: 5,
                steps: [
                    { text: 'Analyze target keywords', status: 'completed' },
                    { text: 'Identify potential link sources', status: 'completed' },
                    { text: 'Configure automation rules', status: 'completed' },
                    { text: 'Set up monitoring dashboard', status: 'current' },
                    { text: 'Launch campaign', status: 'pending' }
                ],
                metrics: {
                    successRate: '87%',
                    linksFound: '142',
                    avgConfidence: '92%',
                    timeSpent: '3.2h'
                },
                dependencies: ['Keyword research completed', 'Target audience defined'],
                troubleshooting: 'If automation fails, check API credentials and rate limits.'
            },
            'auto-2': {
                title: 'Analyze competitor backlink profiles',
                status: 'completed',
                progress: 100,
                type: 'automated',
                estimatedTime: 'Completed',
                completedSteps: 4,
                totalSteps: 4,
                steps: [
                    { text: 'Identify top competitors', status: 'completed' },
                    { text: 'Extract backlink data', status: 'completed' },
                    { text: 'Analyze link quality', status: 'completed' },
                    { text: 'Generate insights report', status: 'completed' }
                ],
                metrics: {
                    successRate: '95%',
                    linksAnalyzed: '2,847',
                    avgConfidence: '94%',
                    timeSpent: '1.8h'
                },
                dependencies: ['Competitor list finalized'],
                troubleshooting: 'Analysis completed successfully with no issues.'
            },
            'auto-3': {
                title: 'Monitor and track link building progress',
                status: 'pending',
                progress: 0,
                type: 'automated',
                estimatedTime: '4 hours estimated',
                completedSteps: 0,
                totalSteps: 6,
                steps: [
                    { text: 'Set up monitoring infrastructure', status: 'pending' },
                    { text: 'Configure tracking parameters', status: 'pending' },
                    { text: 'Implement alert system', status: 'pending' },
                    { text: 'Create progress dashboard', status: 'pending' },
                    { text: 'Schedule automated reports', status: 'pending' },
                    { text: 'Test monitoring system', status: 'pending' }
                ],
                metrics: {
                    successRate: '--',
                    linksTracked: '0',
                    avgConfidence: '--',
                    timeSpent: '0h'
                },
                dependencies: ['Link building campaigns active', 'Monitoring tools configured'],
                troubleshooting: 'Ensure all prerequisite tasks are completed before starting.'
            },
            'manual-1': {
                title: 'Get 20 links with at least 25 authority',
                status: 'in-progress',
                progress: 40,
                type: 'manual',
                estimatedTime: '3 hours remaining',
                completedSteps: 2,
                totalSteps: 5,
                steps: [
                    { text: 'Research high authority websites', status: 'completed' },
                    { text: 'Create outreach contact list', status: 'completed' },
                    { text: 'Draft personalized outreach emails', status: 'current' },
                    { text: 'Send outreach campaigns', status: 'pending' },
                    { text: 'Follow up and secure links', status: 'pending' }
                ],
                metrics: {
                    linksSecured: '8',
                    responseRate: '12%',
                    avgAuthority: '28',
                    timeSpent: '2.1h'
                },
                dependencies: ['Target audience research', 'Content assets ready'],
                troubleshooting: 'Focus on personalization to improve response rates.'
            },
            'manual-2': {
                title: 'Ask the website development company to improve your website speed',
                status: 'pending',
                progress: 15,
                type: 'manual',
                estimatedTime: '6 hours estimated',
                completedSteps: 1,
                totalSteps: 7,
                steps: [
                    { text: 'Audit current website speed', status: 'completed' },
                    { text: 'Identify speed bottlenecks', status: 'pending' },
                    { text: 'Create improvement requirements', status: 'pending' },
                    { text: 'Contact development company', status: 'pending' },
                    { text: 'Review proposed solutions', status: 'pending' },
                    { text: 'Implement speed improvements', status: 'pending' },
                    { text: 'Test and validate improvements', status: 'pending' }
                ],
                metrics: {
                    currentSpeed: '3.2s',
                    targetSpeed: '1.5s',
                    improvementNeeded: '53%',
                    timeSpent: '0.8h'
                },
                dependencies: ['Speed audit completed', 'Development budget approved'],
                troubleshooting: 'Ensure clear requirements and timeline expectations with development team.'
            },
            'manual-3': {
                title: 'Publish at least 4 articles monthly',
                status: 'completed',
                progress: 100,
                type: 'manual',
                estimatedTime: 'Completed',
                completedSteps: 4,
                totalSteps: 4,
                steps: [
                    { text: 'Plan content calendar', status: 'completed' },
                    { text: 'Research article topics', status: 'completed' },
                    { text: 'Write and edit articles', status: 'completed' },
                    { text: 'Publish and promote articles', status: 'completed' }
                ],
                metrics: {
                    articlesPublished: '4',
                    avgWordCount: '1,250',
                    totalViews: '2,847',
                    timeSpent: '12.5h'
                },
                dependencies: ['Content strategy defined', 'Editorial calendar set'],
                troubleshooting: 'Content publishing completed successfully for this month.'
            },
            'manual-4': {
                title: 'Interact on social media with links to the website',
                status: 'pending',
                progress: 5,
                type: 'manual',
                estimatedTime: '8 hours estimated',
                completedSteps: 0,
                totalSteps: 6,
                steps: [
                    { text: 'Identify relevant social platforms', status: 'pending' },
                    { text: 'Create social media content plan', status: 'pending' },
                    { text: 'Schedule regular posts with links', status: 'pending' },
                    { text: 'Engage with community discussions', status: 'pending' },
                    { text: 'Monitor engagement metrics', status: 'pending' },
                    { text: 'Optimize posting strategy', status: 'pending' }
                ],
                metrics: {
                    postsScheduled: '0',
                    engagementRate: '--',
                    clickThrough: '--',
                    timeSpent: '0.3h'
                },
                dependencies: ['Social media accounts active', 'Content assets ready'],
                troubleshooting: 'Start with platform research and content planning before posting.'
            }
        };
        
        return dummyTasks[taskId] || {
            title: 'Unknown Task',
            status: 'pending',
            progress: 0,
            type: 'manual',
            estimatedTime: 'Unknown',
            completedSteps: 0,
            totalSteps: 1,
            steps: [{ text: 'Task details not available', status: 'pending' }],
            metrics: {},
            dependencies: [],
            troubleshooting: 'No troubleshooting information available.'
        };
    }
    
    function renderTaskDetails(taskData) {
        $('#task-detail-title').text(taskData.title);
        
        const statusClass = `aysa-task-status-${taskData.status}`;
        const statusText = taskData.status.replace('-', ' ').toUpperCase();
        
        let stepsHtml = '';
        taskData.steps.forEach(function(step, index) {
            const stepClass = `aysa-task-step-${step.status}`;
            const stepIcon = step.status === 'completed' ? '✓' : 
                           step.status === 'current' ? '●' : (index + 1);
            
            stepsHtml += `
                <li class="aysa-task-step">
                    <div class="aysa-task-step-icon ${stepClass}">${stepIcon}</div>
                    <div class="aysa-task-step-text">${step.text}</div>
                </li>
            `;
        });
        
        let metricsHtml = '';
        Object.keys(taskData.metrics).forEach(function(key) {
            const label = key.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase());
            metricsHtml += `
                <div class="aysa-task-metric">
                    <div class="aysa-task-metric-value">${taskData.metrics[key]}</div>
                    <div class="aysa-task-metric-label">${label}</div>
                </div>
            `;
        });
        
        const dependenciesHtml = taskData.dependencies.map(dep => `<li>${dep}</li>`).join('');
        
        const contentHtml = `
            <div class="aysa-task-status-badge ${statusClass}">${statusText}</div>
            
            <div class="aysa-task-detail-section">
                <h4>Progress Overview</h4>
                <div class="aysa-task-progress">
                    <div class="progress-container">
                        <div class="progress-bar" style="--percentage: ${taskData.progress}%; --progress-color: ${taskData.progress === 100 ? '#34a853' : '#2271b1'}"></div>
                    </div>
                    <span class="progress-text">${taskData.progress}% Complete</span>
                </div>
                <p><strong>Estimated Time:</strong> ${taskData.estimatedTime}</p>
                <p><strong>Steps Completed:</strong> ${taskData.completedSteps} of ${taskData.totalSteps}</p>
            </div>
            
            <div class="aysa-task-detail-section">
                <h4>Completion Steps</h4>
                <ul class="aysa-task-steps">
                    ${stepsHtml}
                </ul>
            </div>
            
            <div class="aysa-task-detail-section">
                <h4>Performance Metrics</h4>
                <div class="aysa-task-metrics">
                    ${metricsHtml}
                </div>
            </div>
            
            <div class="aysa-task-detail-section">
                <h4>Dependencies</h4>
                <ul>
                    ${dependenciesHtml}
                </ul>
            </div>
            
            <div class="aysa-task-detail-section">
                <h4>Troubleshooting</h4>
                <p>${taskData.troubleshooting}</p>
            </div>
        `;
        
        $('#task-detail-content').html(contentHtml);
    }
    
    function renderTaskError(message) {
        $('#task-detail-content').html(`<div class="aysa-error">${message}</div>`);
    }
});
