<?php
/**
 * Project Template Form View - Nested Layout
 *
 * @package Freelance_Studio
 */

if (!defined('ABSPATH')) {
    exit;
}

$is_edit = !empty($template);
$page_title = $is_edit ? __('Edit Project Template', 'freelance-studio') : __('New Project Template', 'freelance-studio');
$milestones = $is_edit ? $template->default_milestones : array();
$tasks = $is_edit ? $template->default_tasks : array();

// Group tasks by milestone_index
$tasks_by_milestone = array();
$unassigned_tasks = array();
foreach ($tasks as $task) {
    if (isset($task['milestone_index']) && $task['milestone_index'] !== '' && $task['milestone_index'] !== null) {
        $tasks_by_milestone[$task['milestone_index']][] = $task;
    } else {
        $unassigned_tasks[] = $task;
    }
}

// Ensure billing_types is set
if (!isset($billing_types) || empty($billing_types)) {
    $billing_types = array(
        'hourly' => __('Hourly', 'freelance-studio'),
        'fixed' => __('Fixed Price', 'freelance-studio'),
        'retainer' => __('Retainer', 'freelance-studio'),
    );
}

// Ensure priorities is set
if (!isset($priorities) || empty($priorities)) {
    $priorities = array(
        'low' => __('Low', 'freelance-studio'),
        'medium' => __('Medium', 'freelance-studio'),
        'high' => __('High', 'freelance-studio'),
        'urgent' => __('Urgent', 'freelance-studio'),
    );
}
?>

<div class="wrap fs-wrap">
    <div class="fs-breadcrumb">
        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-settings&tab=templates') ); ?>"><?php esc_html_e('Project Templates', 'freelance-studio'); ?></a>
        <span>/</span>
        <span><?php echo  esc_html( $is_edit ? esc_html($template->name) : __('New', 'freelance-studio') ); ?></span>
    </div>

    <h1><?php echo  esc_html( $page_title ); ?></h1>

    <form method="post" action="" class="fs-form" id="template-form">
        <?php wp_nonce_field('fs_save_project_template', 'fs_template_nonce'); ?>
        <input type="hidden" name="template_id" value="<?php echo  esc_attr( $is_edit ? $template->id : 0 ); ?>">

        <div class="fs-form-container">
            <div class="fs-form-main">
                <!-- Basic Info -->
                <div class="fs-form-section">
                    <h2><?php esc_html_e('Template Details', 'freelance-studio'); ?></h2>
                    
                    <div class="fs-form-row">
                        <div class="fs-form-field fs-col-6">
                            <label for="name"><?php esc_html_e('Template Name', 'freelance-studio'); ?> <span class="required">*</span></label>
                            <input type="text" name="name" id="name" value="<?php echo $is_edit ? esc_attr($template->name) : ''; ?>" required placeholder="<?php esc_attr_e('e.g., Website Redesign', 'freelance-studio'); ?>">
                        </div>
                        
                        <div class="fs-form-field fs-col-3">
                            <label for="default_billing_type"><?php esc_html_e('Default Billing Type', 'freelance-studio'); ?></label>
                            <select name="default_billing_type" id="default_billing_type">
                                <?php foreach ($billing_types as $value => $label): ?>
                                    <option value="<?php echo esc_attr($value); ?>" <?php selected($is_edit ? $template->default_billing_type : 'hourly', $value); ?>>
                                        <?php echo esc_html($label); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="fs-form-field fs-col-3">
                            <label for="default_hourly_rate"><?php esc_html_e('Default Hourly Rate', 'freelance-studio'); ?></label>
                            <input type="number" name="default_hourly_rate" id="default_hourly_rate" step="0.01" value="<?php echo $is_edit && $template->default_hourly_rate ? esc_attr($template->default_hourly_rate) : ''; ?>" placeholder="0.00">
                        </div>
                    </div>
                    
                    <div class="fs-form-row">
                        <div class="fs-form-field fs-col-12">
                            <label for="description"><?php esc_html_e('Description', 'freelance-studio'); ?></label>
                            <textarea name="description" id="description" rows="3" placeholder="<?php esc_attr_e('Describe what this template is used for...', 'freelance-studio'); ?>"><?php echo $is_edit ? esc_textarea($template->description) : ''; ?></textarea>
                        </div>
                    </div>
                    
                    <div class="fs-form-row">
                        <div class="fs-form-field fs-col-4">
                            <label for="estimated_hours"><?php esc_html_e('Estimated Hours', 'freelance-studio'); ?></label>
                            <input type="number" name="estimated_hours" id="estimated_hours" step="0.5" value="<?php echo $is_edit && $template->estimated_hours ? esc_attr($template->estimated_hours) : ''; ?>" placeholder="0">
                        </div>
                        
                        <div class="fs-form-field fs-col-4">
                            <label for="typical_price_min"><?php esc_html_e('Typical Price (Min)', 'freelance-studio'); ?></label>
                            <input type="number" name="typical_price_min" id="typical_price_min" step="0.01" value="<?php echo $is_edit && $template->typical_price_min ? esc_attr($template->typical_price_min) : ''; ?>" placeholder="0.00">
                        </div>
                        
                        <div class="fs-form-field fs-col-4">
                            <label for="typical_price_max"><?php esc_html_e('Typical Price (Max)', 'freelance-studio'); ?></label>
                            <input type="number" name="typical_price_max" id="typical_price_max" step="0.01" value="<?php echo $is_edit && $template->typical_price_max ? esc_attr($template->typical_price_max) : ''; ?>" placeholder="0.00">
                        </div>
                    </div>
                </div>

                <!-- Milestones & Tasks (Nested) -->
                <div class="fs-form-section">
                    <h2><?php esc_html_e('Milestones & Tasks', 'freelance-studio'); ?></h2>
                    <p class="description"><?php esc_html_e('Define milestones and their associated tasks. Tasks will be created under each milestone when the template is applied.', 'freelance-studio'); ?></p>
                    
                    <div id="milestones-tasks-container">
                        <?php if (!empty($milestones)): ?>
                            <?php foreach ($milestones as $m_index => $milestone): ?>
                                <div class="fs-milestone-block" data-milestone-index="<?php echo  esc_attr( $m_index ); ?>">
                                    <!-- Milestone Header -->
                                    <div class="fs-template-item milestone-item">
                                        <div class="fs-template-item-header">
                                            <div class="fs-reorder-buttons">
                                                <button type="button" class="fs-move-up" title="<?php esc_attr_e('Move Up', 'freelance-studio'); ?>"><span class="dashicons dashicons-arrow-up-alt2"></span></button>
                                                <button type="button" class="fs-move-down" title="<?php esc_attr_e('Move Down', 'freelance-studio'); ?>"><span class="dashicons dashicons-arrow-down-alt2"></span></button>
                                            </div>
                                            <strong><?php esc_html_e('Milestone', 'freelance-studio'); ?> <span class="milestone-number"><?php echo  esc_html( $m_index + 1 ); ?></span></strong>
                                            <button type="button" class="button-link remove-milestone"><?php esc_html_e('Remove', 'freelance-studio'); ?></button>
                                        </div>
                                        <div class="fs-template-item-body">
                                            <div class="fs-form-row">
                                                <div class="fs-form-field fs-col-35">
                                                    <label><?php esc_html_e('Milestone Name', 'freelance-studio'); ?></label>
                                                    <input type="text" name="milestone_name[]" value="<?php echo esc_attr($milestone['name']); ?>">
                                                </div>
                                                <div class="fs-form-field fs-col-2">
                                                    <label><?php esc_html_e('Days from Start', 'freelance-studio'); ?></label>
                                                    <input type="number" name="milestone_days_offset[]" value="<?php echo esc_attr($milestone['days_offset'] ?? 0); ?>" min="0">
                                                </div>
                                                <div class="fs-form-field fs-col-2">
                                                    <label><?php esc_html_e('Invoice %', 'freelance-studio'); ?></label>
                                                    <input type="number" name="milestone_percentage[]" step="0.01" value="<?php echo esc_attr($milestone['invoice_percentage'] ?? ''); ?>">
                                                </div>
                                                <div class="fs-form-field fs-col-3 fs-checkbox-field">
                                                    <label class="fs-checkbox-label">
                                                        <input type="checkbox" name="milestone_invoice[<?php echo  esc_attr( $m_index ); ?>]" value="1" <?php checked(!empty($milestone['invoice_on_completion'])); ?>>
                                                        <?php esc_html_e('Invoice on completion', 'freelance-studio'); ?>
                                                    </label>
                                                </div>
                                            </div>
                                            <div class="fs-form-row">
                                                <div class="fs-form-field fs-col-12">
                                                    <label><?php esc_html_e('Description', 'freelance-studio'); ?></label>
                                                    <input type="text" name="milestone_description[]" value="<?php echo esc_attr($milestone['description'] ?? ''); ?>">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Tasks for this Milestone -->
                                    <div class="fs-milestone-tasks">
                                        <?php 
                                        $milestone_tasks = isset($tasks_by_milestone[$m_index]) ? $tasks_by_milestone[$m_index] : array();
                                        foreach ($milestone_tasks as $t_index => $task): 
                                        ?>
                                            <div class="fs-template-item task-item nested-task">
                                                <div class="fs-template-item-header">
                                                    <div class="fs-reorder-buttons">
                                                        <button type="button" class="fs-move-up" title="<?php esc_attr_e('Move Up', 'freelance-studio'); ?>"><span class="dashicons dashicons-arrow-up-alt2"></span></button>
                                                        <button type="button" class="fs-move-down" title="<?php esc_attr_e('Move Down', 'freelance-studio'); ?>"><span class="dashicons dashicons-arrow-down-alt2"></span></button>
                                                    </div>
                                                    <strong><?php esc_html_e('Task', 'freelance-studio'); ?> <span class="task-number"><?php echo  esc_html( $t_index + 1 ); ?></span></strong>
                                                    <button type="button" class="button-link remove-task"><?php esc_html_e('Remove', 'freelance-studio'); ?></button>
                                                </div>
                                                <div class="fs-template-item-body">
                                                    <input type="hidden" name="task_milestone_index[]" class="task-milestone-index" value="<?php echo  esc_attr( $m_index ); ?>">
                                                    <div class="fs-form-row">
                                                        <div class="fs-form-field fs-col-5">
                                                            <label><?php esc_html_e('Task Title', 'freelance-studio'); ?></label>
                                                            <input type="text" name="task_title[]" value="<?php echo esc_attr($task['title']); ?>">
                                                        </div>
                                                        <div class="fs-form-field fs-col-2">
                                                            <label><?php esc_html_e('Priority', 'freelance-studio'); ?></label>
                                                            <select name="task_priority[]">
                                                                <?php foreach ($priorities as $value => $label): ?>
                                                                    <option value="<?php echo esc_attr($value); ?>" <?php selected($task['priority'] ?? 'medium', $value); ?>><?php echo esc_html($label); ?></option>
                                                                <?php endforeach; ?>
                                                            </select>
                                                        </div>
                                                        <div class="fs-form-field fs-col-2">
                                                            <label><?php esc_html_e('Days from Start', 'freelance-studio'); ?></label>
                                                            <input type="number" name="task_days_offset[]" value="<?php echo esc_attr($task['days_offset'] ?? 0); ?>" min="0">
                                                        </div>
                                                        <div class="fs-form-field fs-col-3">
                                                            <label><?php esc_html_e('Est. Hours', 'freelance-studio'); ?></label>
                                                            <input type="number" name="task_hours[]" step="0.5" value="<?php echo esc_attr($task['estimated_hours'] ?? ''); ?>">
                                                        </div>
                                                    </div>
                                                    <div class="fs-form-row">
                                                        <div class="fs-form-field fs-col-12">
                                                            <label><?php esc_html_e('Description', 'freelance-studio'); ?></label>
                                                            <input type="text" name="task_description[]" value="<?php echo esc_attr($task['description'] ?? ''); ?>">
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                        
                                        <button type="button" class="fs-add-task-to-milestone">
                                            <span class="dashicons dashicons-plus-alt2"></span> <?php esc_html_e('Add Task', 'freelance-studio'); ?>
                                        </button>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                    
                    <button type="button" class="button" id="add-milestone">
                        <span class="dashicons dashicons-plus-alt2"></span> <?php esc_html_e('Add Milestone', 'freelance-studio'); ?>
                    </button>
                </div>

                <!-- Unassigned Tasks -->
                <div class="fs-form-section">
                    <h2><?php esc_html_e('Tasks Without Milestone', 'freelance-studio'); ?></h2>
                    <p class="description"><?php esc_html_e('These tasks are not linked to any milestone and will be created as standalone tasks.', 'freelance-studio'); ?></p>
                    
                    <div id="unassigned-tasks-container">
                        <?php foreach ($unassigned_tasks as $t_index => $task): ?>
                            <div class="fs-template-item task-item">
                                <div class="fs-template-item-header">
                                    <div class="fs-reorder-buttons">
                                        <button type="button" class="fs-move-up" title="<?php esc_attr_e('Move Up', 'freelance-studio'); ?>"><span class="dashicons dashicons-arrow-up-alt2"></span></button>
                                        <button type="button" class="fs-move-down" title="<?php esc_attr_e('Move Down', 'freelance-studio'); ?>"><span class="dashicons dashicons-arrow-down-alt2"></span></button>
                                    </div>
                                    <strong><?php esc_html_e('Task', 'freelance-studio'); ?> <span class="task-number"><?php echo  esc_html( $t_index + 1 ); ?></span></strong>
                                    <button type="button" class="button-link remove-task"><?php esc_html_e('Remove', 'freelance-studio'); ?></button>
                                </div>
                                <div class="fs-template-item-body">
                                    <input type="hidden" name="task_milestone_index[]" class="task-milestone-index" value="">
                                    <div class="fs-form-row">
                                        <div class="fs-form-field fs-col-5">
                                            <label><?php esc_html_e('Task Title', 'freelance-studio'); ?></label>
                                            <input type="text" name="task_title[]" value="<?php echo esc_attr($task['title']); ?>">
                                        </div>
                                        <div class="fs-form-field fs-col-2">
                                            <label><?php esc_html_e('Priority', 'freelance-studio'); ?></label>
                                            <select name="task_priority[]">
                                                <?php foreach ($priorities as $value => $label): ?>
                                                    <option value="<?php echo esc_attr($value); ?>" <?php selected($task['priority'] ?? 'medium', $value); ?>><?php echo esc_html($label); ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="fs-form-field fs-col-2">
                                            <label><?php esc_html_e('Days from Start', 'freelance-studio'); ?></label>
                                            <input type="number" name="task_days_offset[]" value="<?php echo esc_attr($task['days_offset'] ?? 0); ?>" min="0">
                                        </div>
                                        <div class="fs-form-field fs-col-3">
                                            <label><?php esc_html_e('Est. Hours', 'freelance-studio'); ?></label>
                                            <input type="number" name="task_hours[]" step="0.5" value="<?php echo esc_attr($task['estimated_hours'] ?? ''); ?>">
                                        </div>
                                    </div>
                                    <div class="fs-form-row">
                                        <div class="fs-form-field fs-col-12">
                                            <label><?php esc_html_e('Description', 'freelance-studio'); ?></label>
                                            <input type="text" name="task_description[]" value="<?php echo esc_attr($task['description'] ?? ''); ?>">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <button type="button" class="button" id="add-unassigned-task">
                        <span class="dashicons dashicons-plus-alt2"></span> <?php esc_html_e('Add Task', 'freelance-studio'); ?>
                    </button>
                </div>
            </div>

            <div class="fs-form-sidebar">
                <div class="fs-sidebar-section">
                    <h3><?php esc_html_e('Summary', 'freelance-studio'); ?></h3>
                    
                    <div class="fs-summary-item">
                        <span class="label"><?php esc_html_e('Milestones', 'freelance-studio'); ?></span>
                        <span class="value" id="summary-milestones"><?php echo count($milestones); ?></span>
                    </div>
                    
                    <div class="fs-summary-item">
                        <span class="label"><?php esc_html_e('Tasks', 'freelance-studio'); ?></span>
                        <span class="value" id="summary-tasks"><?php echo count($tasks); ?></span>
                    </div>
                </div>
                
                <div class="fs-sidebar-actions">
                    <button type="submit" class="fs-btn fs-btn-primary">
                        <?php echo  esc_html( $is_edit ? __('Update Template', 'freelance-studio') : __('Create Template', 'freelance-studio') ); ?>
                    </button>
                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-settings&tab=templates') ); ?>" class="fs-btn fs-btn-secondary">
                        <?php esc_html_e('Cancel', 'freelance-studio'); ?>
                    </a>
                </div>
            </div>
        </div>
    </form>
</div>

<script>
jQuery(document).ready(function($) {
    // Update summary counts
    function updateSummary() {
        var milestoneCount = $('.fs-milestone-block').length;
        var taskCount = $('.task-item').length;
        $('#summary-milestones').text(milestoneCount);
        $('#summary-tasks').text(taskCount);
    }
    
    // Renumber all items
    function renumberItems() {
        // Renumber milestones
        $('.fs-milestone-block').each(function(index) {
            $(this).attr('data-milestone-index', index);
            $(this).find('.milestone-item .milestone-number').first().text(index + 1);
            // Update checkbox name
            $(this).find('.milestone-item input[type="checkbox"][name^="milestone_invoice"]').attr('name', 'milestone_invoice[' + index + ']');
            // Update task milestone indices
            $(this).find('.fs-milestone-tasks .task-milestone-index').val(index);
        });
        
        // Renumber tasks within each milestone
        $('.fs-milestone-tasks').each(function() {
            $(this).find('.task-item').each(function(index) {
                $(this).find('.task-number').text(index + 1);
            });
        });
        
        // Renumber unassigned tasks
        $('#unassigned-tasks-container .task-item').each(function(index) {
            $(this).find('.task-number').text(index + 1);
        });
    }
    
    // Task HTML template
    function getTaskHtml(milestoneIndex) {
        return `
            <div class="fs-template-item task-item ${milestoneIndex !== '' ? 'nested-task' : ''}">
                <div class="fs-template-item-header">
                    <div class="fs-reorder-buttons">
                        <button type="button" class="fs-move-up" title="<?php esc_attr_e('Move Up', 'freelance-studio'); ?>"><span class="dashicons dashicons-arrow-up-alt2"></span></button>
                        <button type="button" class="fs-move-down" title="<?php esc_attr_e('Move Down', 'freelance-studio'); ?>"><span class="dashicons dashicons-arrow-down-alt2"></span></button>
                    </div>
                    <strong><?php esc_html_e('Task', 'freelance-studio'); ?> <span class="task-number">1</span></strong>
                    <button type="button" class="button-link remove-task"><?php esc_html_e('Remove', 'freelance-studio'); ?></button>
                </div>
                <div class="fs-template-item-body">
                    <input type="hidden" name="task_milestone_index[]" class="task-milestone-index" value="${milestoneIndex}">
                    <div class="fs-form-row">
                        <div class="fs-form-field fs-col-5">
                            <label><?php esc_html_e('Task Title', 'freelance-studio'); ?></label>
                            <input type="text" name="task_title[]" placeholder="<?php esc_attr_e('e.g., Create wireframes', 'freelance-studio'); ?>">
                        </div>
                        <div class="fs-form-field fs-col-2">
                            <label><?php esc_html_e('Priority', 'freelance-studio'); ?></label>
                            <select name="task_priority[]">
                                <option value="low"><?php esc_html_e('Low', 'freelance-studio'); ?></option>
                                <option value="medium" selected><?php esc_html_e('Medium', 'freelance-studio'); ?></option>
                                <option value="high"><?php esc_html_e('High', 'freelance-studio'); ?></option>
                                <option value="urgent"><?php esc_html_e('Urgent', 'freelance-studio'); ?></option>
                            </select>
                        </div>
                        <div class="fs-form-field fs-col-2">
                            <label><?php esc_html_e('Days from Start', 'freelance-studio'); ?></label>
                            <input type="number" name="task_days_offset[]" value="0" min="0">
                        </div>
                        <div class="fs-form-field fs-col-3">
                            <label><?php esc_html_e('Est. Hours', 'freelance-studio'); ?></label>
                            <input type="number" name="task_hours[]" step="0.5" placeholder="0">
                        </div>
                    </div>
                    <div class="fs-form-row">
                        <div class="fs-form-field fs-col-12">
                            <label><?php esc_html_e('Description', 'freelance-studio'); ?></label>
                            <input type="text" name="task_description[]" placeholder="<?php esc_attr_e('Brief description...', 'freelance-studio'); ?>">
                        </div>
                    </div>
                </div>
            </div>
        `;
    }
    
    // Add milestone
    $('#add-milestone').on('click', function() {
        var milestoneIndex = $('.fs-milestone-block').length;
        var html = `
            <div class="fs-milestone-block" data-milestone-index="${milestoneIndex}">
                <div class="fs-template-item milestone-item">
                    <div class="fs-template-item-header">
                        <div class="fs-reorder-buttons">
                            <button type="button" class="fs-move-up" title="<?php esc_attr_e('Move Up', 'freelance-studio'); ?>"><span class="dashicons dashicons-arrow-up-alt2"></span></button>
                            <button type="button" class="fs-move-down" title="<?php esc_attr_e('Move Down', 'freelance-studio'); ?>"><span class="dashicons dashicons-arrow-down-alt2"></span></button>
                        </div>
                        <strong><?php esc_html_e('Milestone', 'freelance-studio'); ?> <span class="milestone-number">${milestoneIndex + 1}</span></strong>
                        <button type="button" class="button-link remove-milestone"><?php esc_html_e('Remove', 'freelance-studio'); ?></button>
                    </div>
                    <div class="fs-template-item-body">
                        <div class="fs-form-row">
                            <div class="fs-form-field fs-col-35">
                                <label><?php esc_html_e('Milestone Name', 'freelance-studio'); ?></label>
                                <input type="text" name="milestone_name[]" placeholder="<?php esc_attr_e('e.g., Design Mockups Complete', 'freelance-studio'); ?>">
                            </div>
                            <div class="fs-form-field fs-col-2">
                                <label><?php esc_html_e('Days from Start', 'freelance-studio'); ?></label>
                                <input type="number" name="milestone_days_offset[]" value="0" min="0">
                            </div>
                            <div class="fs-form-field fs-col-2">
                                <label><?php esc_html_e('Invoice %', 'freelance-studio'); ?></label>
                                <input type="number" name="milestone_percentage[]" step="0.01" placeholder="0">
                            </div>
                            <div class="fs-form-field fs-col-3 fs-checkbox-field">
                                <label class="fs-checkbox-label">
                                    <input type="checkbox" name="milestone_invoice[${milestoneIndex}]" value="1">
                                    <?php esc_html_e('Invoice on completion', 'freelance-studio'); ?>
                                </label>
                            </div>
                        </div>
                        <div class="fs-form-row">
                            <div class="fs-form-field fs-col-12">
                                <label><?php esc_html_e('Description', 'freelance-studio'); ?></label>
                                <input type="text" name="milestone_description[]" placeholder="<?php esc_attr_e('Brief description...', 'freelance-studio'); ?>">
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="fs-milestone-tasks">
                    <button type="button" class="fs-add-task-to-milestone">
                        <span class="dashicons dashicons-plus-alt2"></span> <?php esc_html_e('Add Task', 'freelance-studio'); ?>
                    </button>
                </div>
            </div>
        `;
        
        $('#milestones-tasks-container').append(html);
        updateSummary();
    });
    
    // Add task to milestone
    $(document).on('click', '.fs-add-task-to-milestone', function() {
        var $milestoneBlock = $(this).closest('.fs-milestone-block');
        var milestoneIndex = $milestoneBlock.attr('data-milestone-index');
        var taskHtml = getTaskHtml(milestoneIndex);
        $(this).before(taskHtml);
        renumberItems();
        updateSummary();
    });
    
    // Add unassigned task
    $('#add-unassigned-task').on('click', function() {
        var taskHtml = getTaskHtml('');
        $('#unassigned-tasks-container').append(taskHtml);
        renumberItems();
        updateSummary();
    });
    
    // Move milestone up
    $(document).on('click', '.fs-milestone-block > .milestone-item .fs-move-up', function() {
        var $block = $(this).closest('.fs-milestone-block');
        var $prev = $block.prev('.fs-milestone-block');
        if ($prev.length && !$block.hasClass('moving')) {
            // Do DOM swap first
            $block.insertBefore($prev);
            
            // Apply inverse transforms so items appear in original positions
            $block.addClass('moving').css('transform', 'translateY(100%)');
            $prev.css('transform', 'translateY(-100%)');
            
            // Force reflow then animate to new positions
            $block[0].offsetHeight;
            $block.css('transform', '');
            $prev.css('transform', '');
            
            // Clean up after animation
            setTimeout(function() {
                $block.removeClass('moving');
                renumberItems();
            }, 350);
        }
    });
    
    // Move milestone down
    $(document).on('click', '.fs-milestone-block > .milestone-item .fs-move-down', function() {
        var $block = $(this).closest('.fs-milestone-block');
        var $next = $block.next('.fs-milestone-block');
        if ($next.length && !$block.hasClass('moving')) {
            // Do DOM swap first
            $block.insertAfter($next);
            
            // Apply inverse transforms so items appear in original positions
            $block.addClass('moving').css('transform', 'translateY(-100%)');
            $next.css('transform', 'translateY(100%)');
            
            // Force reflow then animate to new positions
            $block[0].offsetHeight;
            $block.css('transform', '');
            $next.css('transform', '');
            
            // Clean up after animation
            setTimeout(function() {
                $block.removeClass('moving');
                renumberItems();
            }, 350);
        }
    });
    
    // Move task up (within container)
    $(document).on('click', '.task-item .fs-move-up', function() {
        var $item = $(this).closest('.task-item');
        var $prev = $item.prev('.task-item');
        if ($prev.length && !$item.hasClass('moving')) {
            // Do DOM swap first
            $item.insertBefore($prev);
            
            // Apply inverse transforms so items appear in original positions
            $item.addClass('moving').css('transform', 'translateY(100%)');
            $prev.css('transform', 'translateY(-100%)');
            
            // Force reflow then animate to new positions
            $item[0].offsetHeight;
            $item.css('transform', '');
            $prev.css('transform', '');
            
            // Clean up after animation
            setTimeout(function() {
                $item.removeClass('moving');
                renumberItems();
            }, 350);
        }
    });
    
    // Move task down (within container)
    $(document).on('click', '.task-item .fs-move-down', function() {
        var $item = $(this).closest('.task-item');
        var $next = $item.next('.task-item');
        if ($next.length && !$item.hasClass('moving')) {
            // Do DOM swap first
            $item.insertAfter($next);
            
            // Apply inverse transforms so items appear in original positions
            $item.addClass('moving').css('transform', 'translateY(-100%)');
            $next.css('transform', 'translateY(100%)');
            
            // Force reflow then animate to new positions
            $item[0].offsetHeight;
            $item.css('transform', '');
            $next.css('transform', '');
            
            // Clean up after animation
            setTimeout(function() {
                $item.removeClass('moving');
                renumberItems();
            }, 350);
        }
    });
    
    // Remove milestone (and its tasks)
    $(document).on('click', '.remove-milestone', function() {
        if (confirm('<?php esc_html_e('Remove this milestone and all its tasks?', 'freelance-studio'); ?>')) {
            $(this).closest('.fs-milestone-block').remove();
            renumberItems();
            updateSummary();
        }
    });
    
    // Remove task
    $(document).on('click', '.remove-task', function() {
        $(this).closest('.task-item').remove();
        renumberItems();
        updateSummary();
    });
    
    // Initial setup
    renumberItems();
    updateSummary();
});
</script>
