<?php
/**
 * Tasks Kanban Board View
 *
 * @package Freelance_Studio
 */
 
if (!defined('ABSPATH')) {
    exit;
}

// Get user's role setting for "Me" label
$my_role = get_option('fs_my_role', 'freelancer');
$role_labels = array(
    'freelancer' => __('Freelancer', 'freelance-studio'),
    'designer' => __('Designer', 'freelance-studio'),
    'developer' => __('Developer', 'freelance-studio'),
    'project_manager' => __('Project Manager', 'freelance-studio'),
    'consultant' => __('Consultant', 'freelance-studio'),
    'agency' => __('Agency', 'freelance-studio'),
);
$my_role_label = isset($role_labels[$my_role]) ? $role_labels[$my_role] : __('Freelancer', 'freelance-studio');

// Get filter values
$filter_assignee = isset($_GET['assignee']) ? sanitize_text_field($_GET['assignee']) : '';
$filter_project = isset($_GET['project_id']) ? intval($_GET['project_id']) : 0;
$filter_priority = isset($_GET['priority']) ? sanitize_text_field($_GET['priority']) : '';

// Build query args - get all non-cancelled tasks, exclude archived projects
$args = array(
    'orderby' => 'position',
    'order' => 'ASC',
    'status' => array('pending', 'in_progress', 'needs_info', 'with_client', 'completed', 'requested'),
    'exclude_archived_projects' => true,
    'smart_recurring' => true,
);

if ($filter_project) {
    $args['project_id'] = $filter_project;
}

if ($filter_priority) {
    $args['priority'] = $filter_priority;
}

// Get all tasks including generic ones
$tasks = FS_Task::get_all($args);

// Filter by assignee (not built into model)
if ($filter_assignee) {
    $tasks = array_filter($tasks, function($task) use ($filter_assignee) {
        return ($task->assigned_to ?? 'freelancer') === $filter_assignee;
    });
}

// Group tasks by status
// Get customizable column labels from settings (with defaults)
$saved_column_labels = get_option('fs_kanban_column_labels', array());
$default_labels = array(
    'pending' => __('To Do', 'freelance-studio'),
    'in_progress' => __('In Progress', 'freelance-studio'),
    'needs_info' => __('Needs Information', 'freelance-studio'),
    'with_client' => __('With Client', 'freelance-studio'),
    'completed' => __('Done', 'freelance-studio'),
);

$columns = array(
    'pending' => array(
        'label' => isset($saved_column_labels['pending']) ? $saved_column_labels['pending'] : $default_labels['pending'],
        'tasks' => array(),
        'color' => '#6b7280',
    ),
    'in_progress' => array(
        'label' => isset($saved_column_labels['in_progress']) ? $saved_column_labels['in_progress'] : $default_labels['in_progress'],
        'tasks' => array(),
        'color' => '#3b82f6',
    ),
    'needs_info' => array(
        'label' => isset($saved_column_labels['needs_info']) ? $saved_column_labels['needs_info'] : $default_labels['needs_info'],
        'tasks' => array(),
        'color' => '#f59e0b',
    ),
    'with_client' => array(
        'label' => isset($saved_column_labels['with_client']) ? $saved_column_labels['with_client'] : $default_labels['with_client'],
        'tasks' => array(),
        'color' => '#8b5cf6',
    ),
    'completed' => array(
        'label' => isset($saved_column_labels['completed']) ? $saved_column_labels['completed'] : $default_labels['completed'],
        'tasks' => array(),
        'color' => '#22c55e',
    ),
);

foreach ($tasks as $task) {
    if ($task->status === 'requested') {
        // Requested tasks show in the Pending column
        $columns['pending']['tasks'][] = $task;
    } elseif (isset($columns[$task->status])) {
        $columns[$task->status]['tasks'][] = $task;
    }
}

// Get all projects for filter and task assignment
$projects = FS_Project::get_all(array('status' => array('active', 'pending')));

$priorities = FS_Task::get_priorities();
$priority_colors = array(
    'low' => '#6b7280',
    'medium' => '#f59e0b',
    'high' => '#f97316',
    'urgent' => '#ef4444',
);
?>

<script>document.body.classList.add('fs-kanban-page');</script>
<div class="wrap fs-wrap fs-kanban-wrap">
    <div class="fs-page-header">
        <h1 class="fs-page-title"><?php esc_html_e('Tasks', 'freelance-studio'); ?></h1>
        <div class="fs-view-toggle">
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-tasks&view=list') ); ?>" class="fs-btn fs-btn-secondary" title="<?php esc_attr_e('List View', 'freelance-studio'); ?>">
                <span class="dashicons dashicons-list-view"></span>
            </a>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-tasks&view=kanban') ); ?>" class="fs-btn fs-btn-primary" title="<?php esc_attr_e('Kanban Board', 'freelance-studio'); ?>">
                <span class="dashicons dashicons-screenoptions"></span>
            </a>
        </div>
        <div style="flex:1;"></div>
        <button type="button" class="fs-btn fs-btn-primary" id="add-kanban-task-btn">
            <?php esc_html_e('New task', 'freelance-studio'); ?>
        </button>
    </div>
    
    <!-- Filters -->
    <div class="fs-kanban-filters">
        <form method="get" class="fs-filters-form">
            <input type="hidden" name="page" value="fs-tasks">
            <input type="hidden" name="view" value="kanban">
            
            <select name="project_id" class="fs-filter-select">
                <option value=""><?php esc_html_e('All Projects', 'freelance-studio'); ?></option>
                <option value="0" <?php selected($filter_project === 0 && isset($_GET['project_id'])); ?>><?php esc_html_e('No Project (Internal)', 'freelance-studio'); ?></option>
                <?php foreach ($projects as $project): ?>
                    <option value="<?php echo esc_attr($project->id); ?>" <?php selected($filter_project, $project->id); ?>>
                        <?php echo esc_html($project->name); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            
            <select name="assignee" class="fs-filter-select">
                <option value=""><?php esc_html_e('All Assignees', 'freelance-studio'); ?></option>
                <option value="freelancer" <?php selected($filter_assignee, 'freelancer'); ?>><?php esc_html_e('My Tasks', 'freelance-studio'); ?></option>
                <option value="client" <?php selected($filter_assignee, 'client'); ?>><?php esc_html_e('Client Tasks', 'freelance-studio'); ?></option>
            </select>
            
            <select name="priority" class="fs-filter-select">
                <option value=""><?php esc_html_e('All Priorities', 'freelance-studio'); ?></option>
                <?php foreach ($priorities as $key => $label): ?>
                    <option value="<?php echo esc_attr($key); ?>" <?php selected($filter_priority, $key); ?>>
                        <?php echo esc_html($label); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            
            <button type="submit" class="button"><?php esc_html_e('Filter', 'freelance-studio'); ?></button>
            
            <?php if ($filter_assignee || $filter_project || $filter_priority): ?>
                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-tasks&view=kanban') ); ?>" class="button"><?php esc_html_e('Clear', 'freelance-studio'); ?></a>
            <?php endif; ?>
        </form>
    </div>
    
    <!-- Kanban Board -->
    <div class="fs-kanban-board">
        <?php foreach ($columns as $status => $column): ?>
            <div class="fs-kanban-column" data-status="<?php echo esc_attr($status); ?>">
                <div class="fs-kanban-column-header">
                    <div class="fs-kanban-column-title">
                        <span class="fs-kanban-column-dot" style="background-color: <?php echo esc_attr($column['color']); ?>;"></span>
                        <span class="fs-kanban-column-name" data-status="<?php echo esc_attr($status); ?>"><?php echo esc_html($column['label']); ?></span>
                        <button type="button" class="fs-column-edit-btn" data-status="<?php echo esc_attr($status); ?>" title="<?php esc_attr_e('Edit column name', 'freelance-studio'); ?>">
                            <span class="dashicons dashicons-edit"></span>
                        </button>
                        <span class="fs-kanban-column-count"><?php echo count($column['tasks']); ?></span>
                    </div>
                    <button type="button" class="fs-kanban-add-task" data-status="<?php echo esc_attr($status); ?>" title="<?php esc_attr_e('Add task to this column', 'freelance-studio'); ?>">
                        <span class="dashicons dashicons-plus"></span>
                    </button>
                    <?php if ($status === 'completed' && !empty($column['tasks'])): ?>
                    <button type="button" class="fs-kanban-archive-all" title="<?php esc_attr_e('Archive all completed tasks', 'freelance-studio'); ?>">
                        <span class="dashicons dashicons-archive"></span>
                    </button>
                    <?php endif; ?>
                </div>
                <div class="fs-kanban-column-body" data-status="<?php echo esc_attr($status); ?>">
                    <?php if (empty($column['tasks'])): ?>
                        <div class="fs-kanban-empty">
                            <span class="dashicons dashicons-grid-view"></span>
                            <p><?php esc_html_e('No tasks', 'freelance-studio'); ?></p>
                        </div>
                    <?php else: ?>
                        <?php foreach ($column['tasks'] as $task): 
                            $is_overdue = $task->due_date && strtotime($task->due_date) < time() && $task->status !== 'completed';
                            $is_completed = $task->status === 'completed';
                            $assigned_to = $task->assigned_to ?? 'freelancer';
                            $is_client_task = $assigned_to === 'client';
                            $is_my_task = $assigned_to === 'freelancer'; // "Me" tasks
                            $is_team_task = in_array($assigned_to, array('team_designer', 'developer', 'contractor', 'copywriter'));
                            $priority_color = $priority_colors[$task->priority] ?? '#6b7280';
                            
                            // Determine assignee display info
                            $assignee_labels = array(
                                /* translators: 1. me value */
                                'freelancer' => sprintf(__('Me (%s)', 'freelance-studio'), $my_role_label),
                                'client' => __('Client', 'freelance-studio'),
                                'team_designer' => __('Designer', 'freelance-studio'),
                                'developer' => __('Developer', 'freelance-studio'),
                                'contractor' => __('Contractor', 'freelance-studio'),
                                'copywriter' => __('Copywriter', 'freelance-studio'),
                            );
                            $assignee_label = isset($assignee_labels[$assigned_to]) ? $assignee_labels[$assigned_to] : $my_role_label;
                            
                            // Determine assignee class for styling
                            if ($is_my_task) {
                                $assignee_class = 'designer';
                            } elseif ($is_client_task) {
                                $assignee_class = 'client';
                            } else {
                                $assignee_class = 'team';
                            }
                        ?>
                            <div class="fs-kanban-card <?php echo $is_client_task ? 'client-task' : ''; ?> <?php echo $is_completed ? 'completed' : ''; ?>" 
                                 data-id="<?php echo esc_attr($task->id); ?>"
                                 data-status="<?php echo esc_attr($task->status); ?>"
                                 data-position="<?php echo esc_attr($task->position); ?>"
                                 data-priority="<?php echo esc_attr($task->priority); ?>"
                                 draggable="true">
                                
                                <div class="fs-kanban-card-priority" style="background-color: <?php echo esc_attr($priority_color); ?>;"></div>
                                
                                <div class="fs-kanban-card-header">
                                    <div class="fs-kanban-card-badges">
                                        <?php if (!empty($task->is_recurring)): ?>
                                            <span class="fs-kanban-badge recurring" title="<?php esc_attr_e('Recurring task', 'freelance-studio'); ?>">
                                                ↻
                                            </span>
                                        <?php endif; ?>
                                        <?php if ($task->status === 'requested'): ?>
                                            <span class="fs-kanban-badge requested" title="<?php esc_attr_e('Client Request', 'freelance-studio'); ?>">
                                                <span class="dashicons dashicons-star-filled"></span>
                                                <?php esc_html_e('Request', 'freelance-studio'); ?>
                                            </span>
                                        <?php endif; ?>
                                        <?php if ($is_overdue): ?>
                                            <span class="fs-kanban-badge overdue" title="<?php esc_attr_e('Overdue', 'freelance-studio'); ?>">
                                                <span class="dashicons dashicons-flag"></span>
                                            </span>
                                        <?php endif; ?>
                                        <?php if ($task->project_id && $task->project_name): ?>
                                            <span class="fs-kanban-badge project">
                                                <span class="dashicons dashicons-portfolio"></span>
                                                <?php echo esc_html(wp_trim_words($task->project_name, 3, '...')); ?>
                                            </span>
                                        <?php elseif (!empty($task->client_id) && !empty($task->client_is_internal)): ?>
                                            <span class="fs-kanban-badge internal">
                                                <span class="dashicons dashicons-building"></span>
                                                <?php esc_html_e('Internal', 'freelance-studio'); ?>
                                            </span>
                                        <?php elseif (!empty($task->client_id)): ?>
                                            <span class="fs-kanban-badge client">
                                                <span class="dashicons dashicons-businessman"></span>
                                                <?php echo esc_html(wp_trim_words($task->client_company_name ?: $task->client_name, 3, '...')); ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="fs-kanban-badge internal">
                                                <span class="dashicons dashicons-tag"></span>
                                                <?php esc_html_e('Internal', 'freelance-studio'); ?>
                                            </span>
                                        <?php endif; ?>
                                    </div>
                                    <div class="fs-kanban-card-actions">
                                        <?php if ($task->status === 'requested'): ?>
                                        <button type="button" class="fs-kanban-card-btn accept-task-request" data-id="<?php echo esc_attr($task->id); ?>" title="<?php esc_attr_e('Accept Request', 'freelance-studio'); ?>">
                                            <span class="dashicons dashicons-yes-alt"></span>
                                        </button>
                                        <?php endif; ?>
                                        <?php if ($task->status !== 'completed'): ?>
                                        <?php if ( ! function_exists( 'fs_studio_is_free_plan' ) || ! fs_studio_is_free_plan() ): ?>
                                        <button type="button" class="fs-task-start-timer fs-kanban-card-btn"
                                                data-task-id="<?php echo esc_attr($task->id); ?>"
                                                data-project-id="<?php echo esc_attr($task->project_id); ?>"
                                                data-task-name="<?php echo esc_attr($task->title); ?>"
                                                title="<?php esc_attr_e('Start Timer', 'freelance-studio'); ?>">
                                            <span class="dashicons dashicons-clock"></span>
                                        </button>
                                        <?php endif; ?>
                                        <?php endif; ?>
                                        <button type="button" class="fs-kanban-card-btn edit-kanban-task" data-id="<?php echo esc_attr($task->id); ?>" title="<?php esc_attr_e('Edit', 'freelance-studio'); ?>">
                                            <span class="dashicons dashicons-edit"></span>
                                        </button>
                                        <button type="button" class="fs-kanban-card-btn archive-kanban-task" data-id="<?php echo esc_attr($task->id); ?>" title="<?php esc_attr_e('Archive', 'freelance-studio'); ?>">
                                            <span class="dashicons dashicons-archive"></span>
                                        </button>
                                        <button type="button" class="fs-kanban-card-btn delete-kanban-task" data-id="<?php echo esc_attr($task->id); ?>" title="<?php esc_attr_e('Delete', 'freelance-studio'); ?>">
                                            <span class="dashicons dashicons-trash"></span>
                                        </button>
                                    </div>
                                </div>
                                
                                <?php if ($is_completed): ?>
                                    <div class="fs-kanban-card-completed-badge">
                                        <span class="dashicons dashicons-yes-alt"></span>
                                    </div>
                                <?php endif; ?>
                                
                                <div class="fs-kanban-card-body">
                                    <h4 class="fs-kanban-card-title"><?php echo esc_html($task->title); ?></h4>
                                    <?php if ($task->description): ?>
                                        <p class="fs-kanban-card-description"><?php echo esc_html(wp_trim_words($task->description, 12)); ?></p>
                                    <?php endif; ?>
                                </div>
                                
                                <div class="fs-kanban-card-footer">
                                    <div class="fs-kanban-card-meta">
                                        <?php if ($task->due_date): ?>
                                            <span class="fs-kanban-meta-item <?php echo $is_overdue ? 'overdue' : ''; ?>">
                                                <span class="dashicons dashicons-calendar-alt"></span>
                                                <?php echo  esc_html( gmdate('M j', strtotime($task->due_date)) ); ?>
                                            </span>
                                        <?php endif; ?>
                                        
                                        <?php if ($task->estimated_hours): ?>
                                            <span class="fs-kanban-meta-item">
                                                <span class="dashicons dashicons-clock"></span>
                                                <?php echo  esc_html( $task->estimated_hours ); ?>h
                                            </span>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <div class="fs-kanban-card-assignee <?php echo  esc_attr( $assignee_class ); ?>" title="<?php echo esc_attr($assignee_label); ?>">
                                        <span class="dashicons <?php echo $is_client_task ? 'dashicons-businessperson' : ($is_team_task ? 'dashicons-groups' : 'dashicons-admin-users'); ?>"></span>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
    
    <!-- Scroll hint indicators -->
    <div class="fs-kanban-scroll-hint fs-kanban-scroll-left fs-hidden" id="fs-kanban-scroll-left" title="<?php esc_attr_e('Scroll back', 'freelance-studio'); ?>">
        <span class="dashicons dashicons-arrow-left-alt2"></span>
    </div>
    <div class="fs-kanban-scroll-hint" id="fs-kanban-scroll-hint" title="<?php esc_attr_e('Scroll to see more columns', 'freelance-studio'); ?>">
        <span class="dashicons dashicons-arrow-right-alt2"></span>
    </div>
</div>

<!-- Task Modal (shared partial) -->
<?php
$task_modal_context = 'kanban';
$task_modal_projects = $projects;
include JEEB_FS_PLUGIN_DIR . 'includes/views/partials/task-modal.php';
?>


<script>
window.fsTaskModal = {
    nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
    context: 'kanban',
    strings: {
        addTask: '<?php echo esc_js(__('Add Task', 'freelance-studio')); ?>',
        editTask: '<?php echo esc_js(__('Edit Task', 'freelance-studio')); ?>',
        createTask: '<?php echo esc_js(__('Add Task', 'freelance-studio')); ?>',
        updateTask: '<?php echo esc_js(__('Update Task', 'freelance-studio')); ?>',
        errorLoading: '<?php echo esc_js(__('Error loading task', 'freelance-studio')); ?>',
        errorSaving: '<?php echo esc_js(__('Error saving task', 'freelance-studio')); ?>',
        saving: '<?php echo esc_js(__('Saving...', 'freelance-studio')); ?>'
    }
};
</script>
<script>
jQuery(document).ready(function($) {
    var ajaxNonce = '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>';
    var draggedCard = null;
    var dragOverColumn = null;
    
    // Drag and drop functionality
    function initDragAndDrop() {
        var cards = document.querySelectorAll('.fs-kanban-card');
        var columns = document.querySelectorAll('.fs-kanban-column-body');
        
        cards.forEach(function(card) {
            card.addEventListener('dragstart', handleDragStart);
            card.addEventListener('dragend', handleDragEnd);
        });
        
        columns.forEach(function(column) {
            column.addEventListener('dragover', handleDragOver);
            column.addEventListener('dragenter', handleDragEnter);
            column.addEventListener('dragleave', handleDragLeave);
            column.addEventListener('drop', handleDrop);
        });
    }
    
    function handleDragStart(e) {
        draggedCard = this;
        this.classList.add('dragging');
        e.dataTransfer.effectAllowed = 'move';
        e.dataTransfer.setData('text/html', this.innerHTML);
    }
    
    function handleDragEnd(e) {
        this.classList.remove('dragging');
        document.querySelectorAll('.fs-kanban-column-body').forEach(function(col) {
            col.classList.remove('drag-over');
        });
        draggedCard = null;
    }
    
    function handleDragOver(e) {
        if (e.preventDefault) {
            e.preventDefault();
        }
        e.dataTransfer.dropEffect = 'move';
        
        // Determine drop position within column
        var afterElement = getDragAfterElement(this, e.clientY);
        var draggingElement = document.querySelector('.dragging');
        
        if (afterElement == null) {
            this.appendChild(draggingElement);
        } else {
            this.insertBefore(draggingElement, afterElement);
        }
        
        return false;
    }
    
    function getDragAfterElement(container, y) {
        var draggableElements = [...container.querySelectorAll('.fs-kanban-card:not(.dragging)')];
        
        return draggableElements.reduce(function(closest, child) {
            var box = child.getBoundingClientRect();
            var offset = y - box.top - box.height / 2;
            
            if (offset < 0 && offset > closest.offset) {
                return { offset: offset, element: child };
            } else {
                return closest;
            }
        }, { offset: Number.NEGATIVE_INFINITY }).element;
    }
    
    function handleDragEnter(e) {
        this.classList.add('drag-over');
    }
    
    function handleDragLeave(e) {
        this.classList.remove('drag-over');
    }
    
    function handleDrop(e) {
        if (e.stopPropagation) {
            e.stopPropagation();
        }
        
        this.classList.remove('drag-over');
        
        if (draggedCard) {
            var newStatus = this.getAttribute('data-status');
            var taskId = draggedCard.getAttribute('data-id');
            var oldStatus = draggedCard.getAttribute('data-status');
            
            // Update card data attribute
            draggedCard.setAttribute('data-status', newStatus);
            
            // Toggle completed styling
            if (newStatus === 'completed') {
                draggedCard.classList.add('completed');
                // Add completed badge if not present
                if (!draggedCard.querySelector('.fs-kanban-card-completed-badge')) {
                    var badge = document.createElement('div');
                    badge.className = 'fs-kanban-card-completed-badge';
                    badge.innerHTML = '<span class="dashicons dashicons-yes-alt"></span>';
                    draggedCard.querySelector('.fs-kanban-card-header').after(badge);
                }
            } else if (oldStatus === 'completed') {
                draggedCard.classList.remove('completed');
                // Remove completed badge
                var badge = draggedCard.querySelector('.fs-kanban-card-completed-badge');
                if (badge) badge.remove();
            }
            
            // Get new position (order in column)
            var cards = this.querySelectorAll('.fs-kanban-card');
            var positions = [];
            cards.forEach(function(card, index) {
                positions.push({
                    id: card.getAttribute('data-id'),
                    position: index
                });
            });
            
            // Send update to server
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'fs_update_task_status',
                    nonce: ajaxNonce,
                    task_id: taskId,
                    status: newStatus,
                    positions: positions
                },
                success: function(response) {
                    if (response.success) {
                        updateColumnCounts();
                        // Remove empty state if needed
                        var emptyState = document.querySelector('.fs-kanban-column-body[data-status="' + newStatus + '"] .fs-kanban-empty');
                        if (emptyState) {
                            emptyState.remove();
                        }
                    } else {
                        alert(response.data || '<?php esc_html_e('Error updating task', 'freelance-studio'); ?>');
                        location.reload();
                    }
                },
                error: function() {
                    alert('<?php esc_html_e('Error updating task', 'freelance-studio'); ?>');
                    location.reload();
                }
            });
        }
        
        return false;
    }
    
    function updateColumnCounts() {
        document.querySelectorAll('.fs-kanban-column').forEach(function(column) {
            var status = column.getAttribute('data-status');
            var count = column.querySelectorAll('.fs-kanban-card').length;
            column.querySelector('.fs-kanban-column-count').textContent = count;
        });
    }
    
    // Initialize drag and drop
    initDragAndDrop();
    
    // Scroll hint indicators
    (function() {
        var $board = $('.fs-kanban-board');
        var $hintRight = $('#fs-kanban-scroll-hint');
        var $hintLeft = $('#fs-kanban-scroll-left');
        
        function updateScrollHints() {
            var el = $board[0];
            if (!el) return;
            // Hide right arrow when scrolled to near the end (within 20px)
            var atEnd = el.scrollLeft + el.clientWidth >= el.scrollWidth - 20;
            $hintRight.toggleClass('fs-hidden', atEnd);
            // Hide left arrow when scrolled to the start (within 20px)
            var atStart = el.scrollLeft <= 20;
            $hintLeft.toggleClass('fs-hidden', atStart);
        }
        
        $board.on('scroll', updateScrollHints);
        $(window).on('resize', updateScrollHints);
        updateScrollHints();
        
        $hintRight.on('click', function() {
            var el = $board[0];
            var remaining = el.scrollWidth - el.scrollLeft - el.clientWidth;
            var scrollAmount = Math.min(380, remaining);
            $board.animate({ scrollLeft: $board.scrollLeft() + scrollAmount }, 300);
        });
        
        $hintLeft.on('click', function() {
            var scrollAmount = Math.min(380, $board.scrollLeft());
            $board.animate({ scrollLeft: $board.scrollLeft() - scrollAmount }, 300);
        });
    })();
    
    
    // Wire up add task buttons to shared modal
    $('#add-kanban-task-btn').on('click', function() {
        openTaskModal(null, 'pending');
    });
    
    // Add task to specific column
    $('.fs-kanban-add-task').on('click', function() {
        var status = $(this).data('status');
        openTaskModal(null, status);
    });
    
    // Delete task
    $(document).on('click', '.delete-kanban-task', function(e) {
        e.stopPropagation();
        if (!confirm('<?php echo esc_js(__('Are you sure you want to delete this task?', 'freelance-studio')); ?>')) return;
        
        var taskId = $(this).data('id');
        var $card = $(this).closest('.fs-kanban-card');
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: { action: 'fs_delete_task', nonce: ajaxNonce, id: taskId },
            success: function(response) {
                if (response.success) {
                    $card.slideUp(200, function() {
                        $(this).remove();
                        updateColumnCounts();
                    });
                } else {
                    alert(response.data || '<?php echo esc_js(__('Error deleting task', 'freelance-studio')); ?>');
                }
            }
        });
    });
    
    // Archive single task
    $(document).on('click', '.archive-kanban-task', function(e) {
        e.stopPropagation();
        var taskId = $(this).data('id');
        var $card = $(this).closest('.fs-kanban-card');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: { action: 'fs_archive_task', nonce: ajaxNonce, id: taskId },
            success: function(response) {
                if (response.success) {
                    $card.slideUp(200, function() {
                        $(this).remove();
                        updateColumnCounts();
                    });
                } else {
                    alert(response.data || '<?php echo esc_js(__('Error archiving task', 'freelance-studio')); ?>');
                }
            }
        });
    });
    
    // Archive all completed tasks
    $(document).on('click', '.fs-kanban-archive-all', function(e) {
        e.stopPropagation();
        var completedCount = $('.fs-kanban-column[data-status="completed"] .fs-kanban-card').length;
        if (!completedCount) return;
        
        if (!confirm('<?php echo esc_js(__('Archive all completed tasks? They can be restored from the task list\'s Archived tab.', 'freelance-studio')); ?>')) return;
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: { action: 'fs_archive_completed_tasks', nonce: ajaxNonce },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert(response.data || '<?php echo esc_js(__('Error archiving tasks', 'freelance-studio')); ?>');
                }
            }
        });
    });
    
    // Column name editing
    var editingColumnStatus = null;
    
    $('.fs-column-edit-btn').on('click', function(e) {
        e.stopPropagation();
        var status = $(this).data('status');
        var $nameSpan = $('.fs-kanban-column-name[data-status="' + status + '"]');
        var currentName = $nameSpan.text().trim();
        
        // Create inline input
        var $input = $('<input type="text" class="fs-column-name-input" value="' + currentName + '" data-status="' + status + '" data-original="' + currentName + '">');
        $nameSpan.replaceWith($input);
        $input.focus().select();
        
        // Hide edit button while editing
        $(this).hide();
        
        editingColumnStatus = status;
    });
    
    // Save column name on blur or Enter
    $(document).on('blur keydown', '.fs-column-name-input', function(e) {
        if (e.type === 'keydown' && e.key !== 'Enter' && e.key !== 'Escape') {
            return;
        }
        
        var $input = $(this);
        var status = $input.data('status');
        var originalName = $input.data('original');
        var newName = $input.val().trim();
        
        // If Escape, revert to original
        if (e.type === 'keydown' && e.key === 'Escape') {
            newName = originalName;
        }
        
        // Ensure we have a name
        if (!newName) {
            newName = originalName;
        }
        
        // Create span back
        var $nameSpan = $('<span class="fs-kanban-column-name" data-status="' + status + '">' + newName + '</span>');
        $input.replaceWith($nameSpan);
        
        // Show edit button again
        $('.fs-column-edit-btn[data-status="' + status + '"]').show();
        
        editingColumnStatus = null;
        
        // Save if changed
        if (newName !== originalName) {
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'fs_save_kanban_column_label',
                    nonce: ajaxNonce,
                    status: status,
                    label: newName
                },
                success: function(response) {
                    if (!response.success) {
                        // Revert on error
                        $nameSpan.text(originalName);
                    }
                },
                error: function() {
                    // Revert on error
                    $nameSpan.text(originalName);
                }
            });
        }
    });
});
</script>
