/**
 * Unified Task Modal Handler
 * 
 * Shared JS for task create/edit modal across Kanban, Project, and Client views.
 * Requires: jQuery, ajaxurl, fsTaskModal global config object.
 *
 * Expected global: window.fsTaskModal = { nonce: '...', context: 'kanban|project|client' }
 */
(function($) {
    'use strict';
    
    if (typeof window.fsTaskModal === 'undefined') return;
    
    var config = window.fsTaskModal;
    var $modal = $('#fs-task-modal');
    if (!$modal.length) return;
    
    var ajaxNonce = config.nonce;
    var context = config.context;
    
    // Localized strings (set defaults, overridden by config)
    var strings = $.extend({
        addTask: 'Add Task',
        editTask: 'Edit Task',
        createTask: 'Add Task',
        updateTask: 'Update Task',
        errorLoading: 'Error loading task',
        errorSaving: 'Error saving task',
        saving: 'Saving...'
    }, config.strings || {});
    
    /**
     * Open the task modal
     * @param {Object|null} task - Task data for editing, null for new task
     * @param {string|null} status - Default status for new tasks (kanban column)
     */
    function openTaskModal(task, status) {
        var isEdit = !!task;
        
        // Reset form
        $('#fs-task-form')[0].reset();
        $('#fs-task-id').val('');
        $('#fs-task-status').val(status || 'pending');
        $('#fs-task-status-select').val(status || 'pending');
        $('#fs-task-priority').val('medium');
        $('#fs-task-recurring-options').hide();
        $('#fs-task-recurring-days-row').hide();
        $('input[name="recurring_days[]"]').prop('checked', false);
        $('#fs-task-non-billable').prop('checked', false);
        
        // Show/hide status dropdown (only visible when editing)
        if (isEdit) {
            $('#fs-task-status-row').show();
        } else {
            $('#fs-task-status-row').hide();
        }
        
        // Set defaults for project context
        if ($('#fs-task-client-visible').length) {
            $('#fs-task-client-visible').prop('checked', true);
        }
        
        // Update title and button text
        $modal.find('.fs-modal-title').text(isEdit ? strings.editTask : strings.addTask);
        $modal.find('.fs-task-save-btn').text(isEdit ? strings.updateTask : strings.createTask);
        
        if (isEdit) {
            $('#fs-task-id').val(task.id);
            $('#fs-task-title').val(task.title || '');
            $('#fs-task-description').val(task.description || '');
            $('#fs-task-project').val(task.project_id || '');
            $('#fs-task-priority').val(task.priority || 'medium');
            $('#fs-task-due').val(task.due_date || '');
            $('#fs-task-hours').val(task.estimated_hours || '');
            $('#fs-task-assigned').val(task.assigned_to || 'freelancer');
            $('#fs-task-status').val(task.status || 'pending');
            $('#fs-task-status-select').val(task.status || 'pending');
            
            // Milestone (project context)
            if ($('#fs-task-milestone').length) {
                $('#fs-task-milestone').val(task.milestone_id || '');
            }
            
            // Client visible (project context)
            if ($('#fs-task-client-visible').length) {
                $('#fs-task-client-visible').prop('checked', task.is_client_visible == 1);
            }
            
            // Non-billable
            $('#fs-task-non-billable').prop('checked', task.is_non_billable == 1);
            
            // Recurring fields
            if (task.is_recurring == 1) {
                $('#fs-task-recurring').prop('checked', true);
                $('#fs-task-recurring-options').show();
                $('#fs-task-frequency').val(task.recurring_frequency || 'weekly');
                $('#fs-task-recur-end').val(task.recurring_end_date || '');
                
                // Hide until due date
                $('#fs-task-hide-until-due').prop('checked', task.hide_until_due == 1);
                
                // Recurring days
                var freq = task.recurring_frequency || 'weekly';
                toggleDayPicker(freq);
                if (task.recurring_days) {
                    var days;
                    if (Array.isArray(task.recurring_days)) {
                        days = task.recurring_days;
                    } else if (typeof task.recurring_days === 'string') {
                        // Stored as comma-separated string e.g. "tue" or "mon,wed,fri"
                        // May also be JSON array string e.g. '["tue"]' — handle both
                        var trimmed = task.recurring_days.trim();
                        if (trimmed.charAt(0) === '[') {
                            try { days = JSON.parse(trimmed); } catch(e) { days = []; }
                        } else {
                            days = trimmed.split(',').map(function(d) { return d.trim(); }).filter(Boolean);
                        }
                    } else {
                        days = [];
                    }
                    if (Array.isArray(days)) {
                        days.forEach(function(d) {
                            $('input[name="recurring_days[]"][value="' + d + '"]').prop('checked', true);
                        });
                    }
                }
            }
        }
        
        // Show modal
        $modal.addClass('active').fadeIn(200);
        $('#fs-task-title').focus();
    }
    
    function closeTaskModal() {
        $modal.removeClass('active').fadeOut(200);
    }
    
    // Expose openTaskModal globally so views can call it
    window.openTaskModal = openTaskModal;
    window.closeTaskModal = closeTaskModal;
    
    // ========== Accept Task Request ==========
    
    $(document).on('click', '.accept-task-request', function(e) {
        e.preventDefault();
        e.stopPropagation();
        var $btn = $(this);
        var taskId = $btn.data('id');
        
        $btn.prop('disabled', true);
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_accept_task_request',
                nonce: ajaxNonce,
                id: taskId
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert(response.data || strings.error || 'Error');
                    $btn.prop('disabled', false);
                }
            },
            error: function() {
                alert(strings.error || 'Error');
                $btn.prop('disabled', false);
            }
        });
    });
    
    // ========== Popup Timer ==========
    
    // Timer handler moved to standalone block at end of file
    
    // ========== Event Handlers ==========
    
    // Close modal
    $modal.find('.fs-modal-close, .fs-modal-cancel').on('click', closeTaskModal);
    $modal.on('click', function(e) {
        if (e.target === this) closeTaskModal();
    });
    $(document).on('keydown', function(e) {
        if (e.key === 'Escape' && $modal.is(':visible')) closeTaskModal();
    });
    
    // Recurring toggle
    $('#fs-task-recurring').on('change', function() {
        if ($(this).is(':checked')) {
            $('#fs-task-recurring-options').slideDown(200);
            toggleDayPicker($('#fs-task-frequency').val());
        } else {
            $('#fs-task-recurring-options').slideUp(200);
        }
    });
    
    // Status select → sync with hidden input
    $('#fs-task-status-select').on('change', function() {
        $('#fs-task-status').val($(this).val());
    });
    
    // Show/hide day picker based on frequency
    function toggleDayPicker(freq) {
        if (freq === 'weekly' || freq === 'biweekly') {
            $('#fs-task-recurring-days-row').show();
        } else {
            $('#fs-task-recurring-days-row').hide();
            $('input[name="recurring_days[]"]').prop('checked', false);
        }
    }
    
    $('#fs-task-frequency').on('change', function() {
        toggleDayPicker($(this).val());
    });
    
    // Click task title to edit (works across all views)
    $(document).on('click', '.fs-task-title-link', function(e) {
        e.preventDefault();
        e.stopPropagation();
        var taskId = $(this).data('id');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: { action: 'fs_get_task', nonce: ajaxNonce, id: taskId },
            success: function(response) {
                if (response.success) {
                    openTaskModal(response.data);
                } else {
                    alert(response.data || strings.errorLoading);
                }
            },
            error: function() { alert(strings.errorLoading); }
        });
    });
    
    // Edit task button (kanban cards, project task rows)
    $(document).on('click', '.edit-task-btn, .edit-kanban-task', function(e) {
        e.preventDefault();
        e.stopPropagation();
        var taskId = $(this).data('id');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: { action: 'fs_get_task', nonce: ajaxNonce, id: taskId },
            success: function(response) {
                if (response.success) {
                    openTaskModal(response.data);
                } else {
                    alert(response.data || strings.errorLoading);
                }
            },
            error: function() { alert(strings.errorLoading); }
        });
    });
    
    // Save task (unified handler for all contexts)
    $('#fs-task-form').on('submit', function(e) {
        e.preventDefault();
        
        var $btn = $modal.find('.fs-task-save-btn');
        var originalText = $btn.text();
        $btn.prop('disabled', true).text(strings.saving);
        
        var formData = {
            action: 'fs_save_task',
            nonce: ajaxNonce,
            id: $('#fs-task-id').val(),
            title: $('#fs-task-title').val(),
            description: $('#fs-task-description').val(),
            project_id: $('#fs-task-project').val() || '',
            priority: $('#fs-task-priority').val(),
            due_date: $('#fs-task-due').val(),
            estimated_hours: $('#fs-task-hours').val(),
            assigned_to: $('#fs-task-assigned').val() || 'freelancer',
            status: $('#fs-task-status').val(),
            is_recurring: $('#fs-task-recurring').is(':checked') ? 1 : 0,
            recurring_frequency: $('#fs-task-recurring').is(':checked') ? $('#fs-task-frequency').val() : '',
            recurring_end_date: $('#fs-task-recurring').is(':checked') ? $('#fs-task-recur-end').val() : '',
            recurring_days: $('#fs-task-recurring').is(':checked') ? $('input[name="recurring_days[]"]:checked').map(function() { return this.value; }).get().join(',') : '',
            hide_until_due: $('#fs-task-recurring').is(':checked') && $('#fs-task-hide-until-due').is(':checked') ? 1 : 0,
            is_non_billable: $('#fs-task-non-billable').is(':checked') ? 1 : 0
        };
        
        // Context-specific fields
        if ($('#fs-task-client').length) {
            formData.client_id = $('#fs-task-client').val();
        }
        if ($('#fs-task-milestone').length) {
            formData.milestone_id = $('#fs-task-milestone').val();
        }
        if ($('#fs-task-client-visible').length) {
            formData.is_client_visible = $('#fs-task-client-visible').is(':checked') ? 1 : 0;
        }
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: formData,
            success: function(response) {
                if (response.success) {
                    closeTaskModal();
                    location.reload();
                } else {
                    alert(response.data || strings.errorSaving);
                    $btn.prop('disabled', false).text(originalText);
                }
            },
            error: function() {
                alert(strings.errorSaving);
                $btn.prop('disabled', false).text(originalText);
            }
        });
    });
    
    // Task toggle (mark complete/incomplete) - works across all views
    $(document).on('change', '.fs-task-toggle', function() {
        var $checkbox = $(this);
        var taskId = $checkbox.data('id');
        var newStatus = $checkbox.prop('checked') ? 'completed' : 'pending';
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_update_task_status',
                nonce: ajaxNonce,
                task_id: taskId,
                status: newStatus
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    $checkbox.prop('checked', !$checkbox.prop('checked'));
                    alert(response.data || strings.errorSaving);
                }
            },
            error: function() {
                $checkbox.prop('checked', !$checkbox.prop('checked'));
                alert(strings.errorSaving);
            }
        });
    });
    
})(jQuery);

/**
 * Quick Timer Launcher (standalone)
 * Works on any page with .fs-task-start-timer buttons,
 * including the dashboard where fsTaskModal may not be defined.
 */
(function($) {
    'use strict';
    
    $(document).on('click', '.fs-task-start-timer', function(e) {
        e.preventDefault();
        e.stopPropagation();
        var taskId = $(this).data('task-id');
        var projectId = $(this).data('project-id') || '';
        var taskName = $(this).data('task-name') || '';
        
        var url = (typeof ajaxurl !== 'undefined' ? ajaxurl : '').replace('admin-ajax.php', 'admin.php') + 
            '?page=fs-time-tracking&action=popup_timer' +
            '&task_id=' + taskId +
            '&project_id=' + projectId +
            '&task_name=' + encodeURIComponent(taskName);
        
        var w = 340, h = 440;
        var left = (screen.width - w) / 2;
        var top = (screen.height - h) / 2;
        
        window.open(url, 'fs_popup_timer_' + taskId, 
            'width=' + w + ',height=' + h + ',left=' + left + ',top=' + top + 
            ',menubar=no,toolbar=no,location=no,status=no,resizable=yes');
    });
    
})(jQuery);
