<?php
ob_start();

$title = htmlspecialchars($sprint['name']) . ' - ' . htmlspecialchars($sprint['project_name']);
$page_title = 'Sprint';
$current_page = 'backlog';
$showSidebar = true;
?>

<div class="max-w-7xl mx-auto">
    <!-- Header del Sprint -->
    <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <div class="flex justify-between items-start mb-4">
            <div>
                <div class="flex items-center gap-3 mb-2">
                    <a href="/backlog/<?= $sprint['project_id'] ?>" class="text-gray-500 hover:text-gray-700">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
                        </svg>
                    </a>
                    <h1 class="text-2xl font-bold text-gray-800"><?= htmlspecialchars($sprint['name']) ?></h1>
                    <?php
                    $sprint_status_colors = [
                        'planning' => 'bg-gray-100 text-gray-800',
                        'active' => 'bg-green-100 text-green-800',
                        'completed' => 'bg-blue-100 text-blue-800',
                        'cancelled' => 'bg-red-100 text-red-800'
                    ];
                    $sprint_status_labels = [
                        'planning' => 'Planificación',
                        'active' => 'Activo',
                        'completed' => 'Completado',
                        'cancelled' => 'Cancelado'
                    ];
                    ?>
                    <span class="px-3 py-1 text-xs font-semibold rounded-full <?= $sprint_status_colors[$sprint['status']] ?>">
                        <?= $sprint_status_labels[$sprint['status']] ?>
                    </span>
                </div>
                <p class="text-sm text-gray-600">
                    Proyecto: <a href="/projects/<?= $sprint['project_id'] ?>" class="text-primary-600 hover:text-primary-700"><?= htmlspecialchars($sprint['project_code']) ?> - <?= htmlspecialchars($sprint['project_name']) ?></a>
                </p>
                <p class="text-sm text-gray-500 mt-1">
                    <?= date('d/m/Y', strtotime($sprint['start_date'])) ?> - <?= date('d/m/Y', strtotime($sprint['end_date'])) ?>
                    (<?php
                    $days_total = ceil((strtotime($sprint['end_date']) - strtotime($sprint['start_date'])) / 86400);
                    $days_remaining = ceil((strtotime($sprint['end_date']) - time()) / 86400);
                    echo $days_remaining > 0 ? "$days_remaining de $days_total días" : "Finalizado";
                    ?>)
                </p>
                <?php if ($sprint['goal']): ?>
                    <p class="text-sm text-gray-700 mt-2"><strong>Objetivo:</strong> <?= htmlspecialchars($sprint['goal']) ?></p>
                <?php endif; ?>
            </div>

            <div class="flex gap-2">
                <select id="sprintStatus" onchange="updateSprintStatus()" class="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500">
                    <option value="planning" <?= $sprint['status'] === 'planning' ? 'selected' : '' ?>>Planificación</option>
                    <option value="active" <?= $sprint['status'] === 'active' ? 'selected' : '' ?>>Activo</option>
                    <option value="completed" <?= $sprint['status'] === 'completed' ? 'selected' : '' ?>>Completado</option>
                    <option value="cancelled" <?= $sprint['status'] === 'cancelled' ? 'selected' : '' ?>>Cancelado</option>
                </select>

                <button onclick="openAddItemModal()" class="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700">
                    <svg class="w-5 h-5 inline-block mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
                    </svg>
                    Agregar Item
                </button>
            </div>
        </div>

        <!-- Estadísticas del Sprint -->
        <div class="grid grid-cols-4 gap-4">
            <?php
            $total_items = count($items);
            $done_items = count(array_filter($items, fn($i) => $i['status'] === 'done'));
            $in_progress = count(array_filter($items, fn($i) => $i['status'] === 'in_progress'));
            $total_committed = array_sum(array_column($items, 'committed_hours'));
            $total_actual = array_sum(array_column($items, 'actual_hours'));
            ?>
            <div class="bg-blue-50 rounded-lg p-4">
                <div class="text-2xl font-bold text-blue-700"><?= $total_items ?></div>
                <div class="text-sm text-blue-600">Items Totales</div>
            </div>
            <div class="bg-yellow-50 rounded-lg p-4">
                <div class="text-2xl font-bold text-yellow-700"><?= $in_progress ?></div>
                <div class="text-sm text-yellow-600">En Progreso</div>
            </div>
            <div class="bg-green-50 rounded-lg p-4">
                <div class="text-2xl font-bold text-green-700"><?= $done_items ?></div>
                <div class="text-sm text-green-600">Completados</div>
            </div>
            <div class="bg-purple-50 rounded-lg p-4">
                <div class="text-2xl font-bold text-purple-700"><?= number_format($total_committed, 1) ?>h</div>
                <div class="text-sm text-purple-600">Horas Comprometidas</div>
            </div>
        </div>
    </div>

    <!-- Burndown Chart -->
    <?php if ($sprint['status'] === 'active' || $sprint['status'] === 'completed'): ?>
    <div class="bg-white rounded-lg shadow-sm p-6">
        <div class="flex items-center justify-between mb-4">
            <h2 class="text-lg font-semibold text-gray-800">
                <i class="fas fa-chart-line mr-2 text-blue-600"></i>Burndown Chart
            </h2>
            <div class="flex items-center gap-4 text-sm">
                <div class="flex items-center">
                    <span class="w-3 h-3 bg-blue-500 rounded-full mr-2"></span>
                    <span class="text-gray-600">Línea Ideal</span>
                </div>
                <div class="flex items-center">
                    <span class="w-3 h-3 bg-green-500 rounded-full mr-2"></span>
                    <span class="text-gray-600">Progreso Real</span>
                </div>
            </div>
        </div>

        <div id="burndownMetrics" class="grid grid-cols-4 gap-4 mb-4">
            <!-- Se llenará dinámicamente -->
        </div>

        <div class="relative" style="height: 300px;">
            <canvas id="burndownChart"></canvas>
        </div>

        <div id="burndownAlert" class="mt-4"></div>
    </div>
    <?php endif; ?>

    <!-- Tablero Kanban -->
    <div class="bg-white rounded-lg shadow-sm p-6">
        <h2 class="text-lg font-semibold text-gray-800 mb-4">Tablero Sprint</h2>

        <div class="grid grid-cols-4 gap-4">
            <!-- Columna Por Hacer (Backlog del Sprint) -->
            <div class="bg-gray-50 rounded-lg p-4">
                <h3 class="font-semibold text-gray-700 mb-3 flex items-center">
                    <span class="w-3 h-3 rounded-full bg-gray-400 mr-2"></span>
                    Por Hacer
                    <span class="ml-auto bg-gray-200 text-gray-700 px-2 py-1 rounded-full text-xs">
                        <?= count(array_filter($items, fn($i) => $i['status'] === 'backlog')) ?>
                    </span>
                </h3>
                <p class="text-xs text-gray-500 mb-3">Items agregados al sprint pero aún no iniciados</p>
                <div class="space-y-3" id="column-backlog">
                    <?php foreach ($items as $item): ?>
                        <?php if ($item['status'] === 'backlog'): ?>
                            <?php include __DIR__ . '/_item_card.php'; ?>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Columna En Preparación (Ready) -->
            <div class="bg-blue-50 rounded-lg p-4">
                <h3 class="font-semibold text-gray-700 mb-3 flex items-center">
                    <span class="w-3 h-3 rounded-full bg-blue-500 mr-2"></span>
                    Preparado
                    <span class="ml-auto bg-blue-200 text-blue-700 px-2 py-1 rounded-full text-xs">
                        <?= count(array_filter($items, fn($i) => $i['status'] === 'ready')) ?>
                    </span>
                </h3>
                <p class="text-xs text-gray-500 mb-3">Refinado y listo para iniciar trabajo</p>
                <div class="space-y-3" id="column-ready">
                    <?php foreach ($items as $item): ?>
                        <?php if ($item['status'] === 'ready'): ?>
                            <?php include __DIR__ . '/_item_card.php'; ?>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Columna En Progreso -->
            <div class="bg-yellow-50 rounded-lg p-4">
                <h3 class="font-semibold text-gray-700 mb-3 flex items-center">
                    <span class="w-3 h-3 rounded-full bg-yellow-500 mr-2"></span>
                    En Progreso
                    <span class="ml-auto bg-yellow-200 text-yellow-700 px-2 py-1 rounded-full text-xs">
                        <?= count(array_filter($items, fn($i) => $i['status'] === 'in_progress')) ?>
                    </span>
                </h3>
                <p class="text-xs text-gray-500 mb-3">En desarrollo activo</p>
                <div class="space-y-3" id="column-in_progress">
                    <?php foreach ($items as $item): ?>
                        <?php if ($item['status'] === 'in_progress'): ?>
                            <?php include __DIR__ . '/_item_card.php'; ?>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Columna Hecho -->
            <div class="bg-green-50 rounded-lg p-4">
                <h3 class="font-semibold text-gray-700 mb-3 flex items-center">
                    <span class="w-3 h-3 rounded-full bg-green-500 mr-2"></span>
                    Hecho
                    <span class="ml-auto bg-green-200 text-green-700 px-2 py-1 rounded-full text-xs">
                        <?= count(array_filter($items, fn($i) => $i['status'] === 'done')) ?>
                    </span>
                </h3>
                <p class="text-xs text-gray-500 mb-3">Completado y validado</p>
                <div class="space-y-3" id="column-done">
                    <?php foreach ($items as $item): ?>
                        <?php if ($item['status'] === 'done'): ?>
                            <?php include __DIR__ . '/_item_card.php'; ?>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal: Agregar Item al Sprint -->
<div id="addItemModal" class="hidden fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
    <div class="relative top-20 mx-auto p-5 border w-full max-w-2xl shadow-lg rounded-md bg-white">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold text-gray-900">Agregar Items al Sprint</h3>
            <button onclick="closeAddItemModal()" class="text-gray-400 hover:text-gray-500">
                <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                </svg>
            </button>
        </div>

        <?php if (empty($available_items)): ?>
            <p class="text-gray-500 text-center py-8">No hay items disponibles para agregar</p>
        <?php else: ?>
            <div class="space-y-2 max-h-96 overflow-y-auto">
                <?php foreach ($available_items as $avail_item): ?>
                    <div class="border border-gray-200 rounded p-3 hover:border-primary-300 transition-colors">
                        <div class="flex items-start justify-between">
                            <div class="flex-1">
                                <h4 class="font-medium text-gray-800"><?= htmlspecialchars($avail_item['title']) ?></h4>
                                <div class="flex gap-2 mt-1">
                                    <?php
                                    $type_colors = [
                                        'user_story' => 'bg-blue-100 text-blue-800',
                                        'task' => 'bg-green-100 text-green-800',
                                        'bug' => 'bg-red-100 text-red-800',
                                        'technical' => 'bg-purple-100 text-purple-800'
                                    ];
                                    $type_labels = [
                                        'user_story' => 'Historia',
                                        'task' => 'Tarea',
                                        'bug' => 'Bug',
                                        'technical' => 'Técnico'
                                    ];
                                    $priority_colors = [
                                        'critical' => 'bg-red-100 text-red-800',
                                        'high' => 'bg-orange-100 text-orange-800',
                                        'medium' => 'bg-yellow-100 text-yellow-800',
                                        'low' => 'bg-gray-100 text-gray-800'
                                    ];
                                    ?>
                                    <span class="px-2 py-1 text-xs font-semibold rounded <?= $type_colors[$avail_item['type']] ?? 'bg-gray-100' ?>">
                                        <?= $type_labels[$avail_item['type']] ?? $avail_item['type'] ?>
                                    </span>
                                    <span class="px-2 py-1 text-xs font-semibold rounded <?= $priority_colors[$avail_item['priority']] ?>">
                                        <?= ucfirst($avail_item['priority']) ?>
                                    </span>
                                    <?php if ($avail_item['story_points']): ?>
                                        <span class="px-2 py-1 text-xs font-semibold rounded bg-indigo-100 text-indigo-800">
                                            <?= $avail_item['story_points'] ?> pts
                                        </span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <button onclick="addItemToSprint(<?= $avail_item['id'] ?>)" class="ml-4 px-3 py-1 bg-primary-600 text-white text-sm rounded hover:bg-primary-700">
                                Agregar
                            </button>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <div class="flex justify-end gap-3 pt-4 mt-4 border-t">
            <button type="button" onclick="closeAddItemModal()" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50">
                Cerrar
            </button>
        </div>
    </div>
</div>

<!-- Modal: Ver Detalles del Item -->
<div id="itemDetailsModal" class="hidden fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
    <div class="relative top-10 mx-auto p-6 border w-full max-w-4xl shadow-lg rounded-md bg-white">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-xl font-semibold text-gray-900" id="modalItemTitle">Detalles del Item</h3>
            <button onclick="closeItemDetailsModal()" class="text-gray-400 hover:text-gray-500">
                <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                </svg>
            </button>
        </div>

        <div id="itemDetailsContent" class="space-y-4">
            <!-- Se llenará dinámicamente con JavaScript -->
        </div>

        <!-- Sección de Tareas -->
        <div class="mt-6 border-t pt-4">
            <div class="flex justify-between items-center mb-4">
                <h4 class="text-lg font-semibold text-gray-900">
                    <i class="fas fa-tasks mr-2 text-blue-600"></i>Tareas
                </h4>
                <button onclick="showCreateTaskModal()" class="px-3 py-1 bg-green-600 text-white text-sm rounded-md hover:bg-green-700">
                    <i class="fas fa-plus mr-1"></i>Nueva Tarea
                </button>
            </div>
            <div id="tasksList" class="space-y-2">
                <!-- Se llenará dinámicamente -->
            </div>
        </div>

        <div class="flex justify-end gap-3 pt-4 mt-4 border-t">
            <button type="button" onclick="closeItemDetailsModal()" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50">
                Cerrar
            </button>
        </div>
    </div>
</div>

<!-- Modal: Crear/Editar Tarea -->
<div id="taskModal" class="hidden fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
    <div class="relative top-10 mx-auto p-6 border w-full max-w-2xl shadow-lg rounded-md bg-white">
        <form id="taskForm" onsubmit="saveTask(event)">
            <input type="hidden" name="csrf_token" value="<?= csrf_token() ?>">
            <input type="hidden" name="sprint_id" value="<?= $sprint['id'] ?>">
            <input type="hidden" id="task_backlog_item_id" name="backlog_item_id">
            <input type="hidden" id="task_id" name="task_id">
            <input type="hidden" id="task_action" name="action" value="create">

            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-semibold text-gray-900" id="taskModalTitle">Nueva Tarea</h3>
                <button type="button" onclick="closeTaskModal()" class="text-gray-400 hover:text-gray-500">
                    <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                    </svg>
                </button>
            </div>

            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Título *</label>
                    <input type="text" name="title" id="task_title" required
                           class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Descripción</label>
                    <textarea name="description" id="task_description" rows="3"
                              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"></textarea>
                </div>

                <div class="grid grid-cols-3 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Estado</label>
                        <select name="status" id="task_status"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                            <option value="todo">Por Hacer</option>
                            <option value="in_progress">En Progreso</option>
                            <option value="done">Hecho</option>
                        </select>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Horas Estimadas</label>
                        <input type="number" name="estimated_hours" id="task_estimated_hours" step="0.5" min="0"
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Asignar a</label>
                        <select name="assigned_to" id="task_assigned_to"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                            <option value="">Sin asignar</option>
                            <?php foreach ($teamMembers as $member): ?>
                            <option value="<?= $member['id'] ?>"><?= htmlspecialchars($member['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
            </div>

            <div class="flex justify-end gap-3 pt-4 mt-4 border-t">
                <button type="button" onclick="closeTaskModal()" 
                        class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50">
                    Cancelar
                </button>
                <button type="submit" 
                        class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700">
                    <i class="fas fa-save mr-2"></i>Guardar Tarea
                </button>
            </div>
        </form>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
const sprintId = <?= $sprint['id'] ?>;
const sprintStatus = '<?= $sprint['status'] ?>';
let currentBacklogItemId = null;
let burndownChart = null;

// Cargar burndown chart si el sprint está activo o completado
if (sprintStatus === 'active' || sprintStatus === 'completed') {
    loadBurndownChart();
}

async function loadBurndownChart() {
    try {
        const response = await fetch(`/sprints/burndown?sprint_id=${sprintId}`);
        const result = await response.json();
        
        if (result.success) {
            renderBurndownMetrics(result.metrics);
            renderBurndownChart(result.chartData, result.metrics);
        }
    } catch (error) {
        console.error('Error loading burndown chart:', error);
    }
}

function renderBurndownMetrics(metrics) {
    const metricsHtml = `
        <div class="bg-blue-50 rounded-lg p-3">
            <div class="text-xl font-bold text-blue-700">${metrics.total_points}</div>
            <div class="text-xs text-blue-600">Story Points Totales</div>
        </div>
        <div class="bg-green-50 rounded-lg p-3">
            <div class="text-xl font-bold text-green-700">${metrics.completed_points}</div>
            <div class="text-xs text-green-600">Completados</div>
        </div>
        <div class="bg-orange-50 rounded-lg p-3">
            <div class="text-xl font-bold text-orange-700">${metrics.remaining_points}</div>
            <div class="text-xs text-orange-600">Restantes</div>
        </div>
        <div class="bg-purple-50 rounded-lg p-3">
            <div class="text-xl font-bold text-purple-700">${metrics.velocity}</div>
            <div class="text-xs text-purple-600">Velocidad (pts/día)</div>
        </div>
    `;
    
    document.getElementById('burndownMetrics').innerHTML = metricsHtml;
    
    // Mostrar alerta si no está en track
    const alertDiv = document.getElementById('burndownAlert');
    if (!metrics.on_track && sprintStatus === 'active') {
        alertDiv.innerHTML = `
            <div class="bg-yellow-50 border-l-4 border-yellow-400 p-4">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <i class="fas fa-exclamation-triangle text-yellow-400"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm text-yellow-700">
                            <strong>⚠️ Sprint en riesgo:</strong> Al ritmo actual se completarán ${metrics.predicted_completion.toFixed(1)} de ${metrics.total_points} story points.
                            Considera priorizar items críticos o reducir el alcance.
                        </p>
                    </div>
                </div>
            </div>
        `;
    } else if (metrics.on_track && sprintStatus === 'active') {
        alertDiv.innerHTML = `
            <div class="bg-green-50 border-l-4 border-green-400 p-4">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <i class="fas fa-check-circle text-green-400"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm text-green-700">
                            <strong>✓ Sprint en buen camino:</strong> El equipo está avanzando según lo esperado.
                        </p>
                    </div>
                </div>
            </div>
        `;
    }
}

function renderBurndownChart(chartData, metrics) {
    const ctx = document.getElementById('burndownChart').getContext('2d');
    
    // Destruir chart anterior si existe
    if (burndownChart) {
        burndownChart.destroy();
    }
    
    const labels = chartData.ideal.map(d => {
        const date = new Date(d.date);
        return date.toLocaleDateString('es-ES', { day: 'numeric', month: 'short' });
    });
    
    burndownChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [
                {
                    label: 'Línea Ideal',
                    data: chartData.ideal.map(d => d.remaining),
                    borderColor: 'rgb(59, 130, 246)',
                    backgroundColor: 'rgba(59, 130, 246, 0.1)',
                    borderWidth: 2,
                    borderDash: [5, 5],
                    tension: 0.1,
                    pointRadius: 3
                },
                {
                    label: 'Progreso Real',
                    data: chartData.actual.map(d => d.remaining),
                    borderColor: 'rgb(34, 197, 94)',
                    backgroundColor: 'rgba(34, 197, 94, 0.1)',
                    borderWidth: 3,
                    tension: 0.3,
                    pointRadius: 4,
                    pointBackgroundColor: 'rgb(34, 197, 94)',
                    fill: true
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: true,
                    position: 'top'
                },
                tooltip: {
                    mode: 'index',
                    intersect: false,
                    callbacks: {
                        label: function(context) {
                            return context.dataset.label + ': ' + context.parsed.y.toFixed(1) + ' pts';
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: 'Story Points Restantes'
                    },
                    ticks: {
                        stepSize: Math.ceil(metrics.total_points / 10)
                    }
                },
                x: {
                    title: {
                        display: true,
                        text: 'Día del Sprint'
                    }
                }
            },
            interaction: {
                mode: 'nearest',
                axis: 'x',
                intersect: false
            }
        }
    });
}

// Actualizar estado del sprint
async function updateSprintStatus() {
    const status = document.getElementById('sprintStatus').value;
    
    try {
        const response = await fetch(`/sprints/${sprintId}/update`, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ action: 'update_status', status })
        });
        
        const result = await response.json();
        if (result.success) {
            window.location.reload();
        } else {
            alert('Error: ' + result.message);
        }
    } catch (error) {
        alert('Error al actualizar estado del sprint');
    }
}

// Modal agregar item
function openAddItemModal() {
    document.getElementById('addItemModal').classList.remove('hidden');
}
function closeAddItemModal() {
    document.getElementById('addItemModal').classList.add('hidden');
}

// Agregar item al sprint
async function addItemToSprint(itemId) {
    try {
        const response = await fetch(`/sprints/${sprintId}/update`, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ 
                action: 'add_item', 
                backlog_item_id: itemId 
            })
        });
        
        const result = await response.json();
        if (result.success) {
            window.location.reload();
        } else {
            alert('Error: ' + result.message);
        }
    } catch (error) {
        alert('Error al agregar item');
    }
}

// Remover item del sprint
async function removeItemFromSprint(itemId, itemTitle) {
    if (!confirm(`¿Remover "${itemTitle}" del sprint?`)) return;
    
    try {
        const response = await fetch(`/sprints/${sprintId}/update`, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ 
                action: 'remove_item', 
                backlog_item_id: itemId 
            })
        });
        
        const result = await response.json();
        if (result.success) {
            window.location.reload();
        } else {
            alert('Error: ' + result.message);
        }
    } catch (error) {
        alert('Error al remover item');
    }
}

// Cambiar estado del item (drag & drop simulado con click)
async function changeItemStatus(itemId, newStatus) {
    try {
        const response = await fetch(`/backlog/items/${itemId}/update`, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ 
                action: 'update_status', 
                status: newStatus 
            })
        });
        
        const result = await response.json();
        if (result.success) {
            window.location.reload();
        } else {
            alert('Error: ' + result.message);
        }
    } catch (error) {
        alert('Error al cambiar estado');
    }
}

// Modal de detalles del item
const allItems = <?= json_encode($items) ?>;

function viewItemDetails(itemId) {
    const item = allItems.find(i => i.id == itemId);
    if (!item) return;
    
    currentBacklogItemId = itemId; // Guardar para crear tareas
    
    const typeLabels = {
        'user_story': 'Historia de Usuario',
        'task': 'Tarea',
        'bug': 'Bug',
        'technical': 'Técnico'
    };
    
    const statusLabels = {
        'backlog': 'Por Hacer',
        'ready': 'Preparado',
        'in_progress': 'En Progreso',
        'done': 'Hecho',
        'cancelled': 'Cancelado'
    };
    
    const priorityLabels = {
        'low': 'Baja',
        'medium': 'Media',
        'high': 'Alta',
        'critical': 'Crítica'
    };
    
    document.getElementById('modalItemTitle').textContent = item.title;
    
    const content = `
        <div class="grid grid-cols-2 gap-4 mb-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Tipo</label>
                <span class="text-sm text-gray-900">${typeLabels[item.type] || item.type}</span>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Prioridad</label>
                <span class="text-sm text-gray-900">${priorityLabels[item.priority]}</span>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Estado Actual</label>
                <span class="text-sm text-gray-900">${statusLabels[item.status]}</span>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Story Points</label>
                <span class="text-sm text-gray-900">${item.story_points || 'No estimado'}</span>
            </div>
        </div>
        
        ${item.requirement_code ? `
        <div class="mb-4 bg-blue-50 border-l-4 border-blue-400 p-3 rounded">
            <label class="block text-xs font-medium text-blue-900 mb-1">🔗 Origen</label>
            <a href="/requirements/view/${item.requirement_id}" class="text-sm text-blue-700 hover:text-blue-900 font-medium">
                ${item.requirement_code} - ${item.requirement_title || 'Ver requerimiento'}
            </a>
        </div>
        ` : ''}
        
        ${item.description ? `
        <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 mb-1">Descripción</label>
            <p class="text-sm text-gray-900 whitespace-pre-wrap">${item.description}</p>
        </div>
        ` : ''}
        
        ${item.user_story ? `
        <div class="mb-4 bg-blue-50 p-4 rounded">
            <label class="block text-sm font-medium text-blue-900 mb-2">📖 Historia de Usuario</label>
            <p class="text-sm text-blue-800 whitespace-pre-wrap">${item.user_story}</p>
        </div>
        ` : ''}
        
        ${item.acceptance_criteria ? `
        <div class="mb-4 bg-green-50 p-4 rounded">
            <label class="block text-sm font-medium text-green-900 mb-2">✓ Criterios de Aceptación</label>
            <p class="text-sm text-green-800 whitespace-pre-wrap">${item.acceptance_criteria}</p>
        </div>
        ` : ''}
        
        <div class="grid grid-cols-2 gap-4 mb-4 text-sm">
            ${item.committed_hours ? `
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Horas Comprometidas</label>
                <span class="text-sm text-gray-900">${item.committed_hours}h</span>
            </div>
            ` : ''}
            ${item.tasks_count > 0 ? `
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Tareas</label>
                <span class="text-sm text-gray-900">${item.tasks_count} tareas creadas</span>
            </div>
            ` : ''}
            ${item.assigned_to ? `
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Asignado a</label>
                <span class="text-sm text-gray-900">${item.assigned_first_name} ${item.assigned_last_name}</span>
            </div>
            ` : ''}
        </div>
        
        <div class="bg-yellow-50 border-l-4 border-yellow-400 p-3 text-sm">
            <p class="font-medium text-yellow-900">💡 Story Points vs Horas</p>
            <p class="text-yellow-700 mt-1">
                <strong>Story Points:</strong> Estimación relativa de complejidad (1, 2, 3, 5, 8, 13...). Útil para planificar sprints.<br>
                <strong>Horas:</strong> Estimación absoluta de tiempo. Se define al agregar al sprint.
            </p>
        </div>
    `;
    
    document.getElementById('itemDetailsContent').innerHTML = content;
    
    // Cargar tareas
    loadTasks(itemId);
    
    document.getElementById('itemDetailsModal').classList.remove('hidden');
}

function closeItemDetailsModal() {
    document.getElementById('itemDetailsModal').classList.add('hidden');
    currentBacklogItemId = null;
}

// === FUNCIONES DE TAREAS ===

async function loadTasks(backlogItemId) {
    try {
        const response = await fetch(`/tasks/list?backlog_item_id=${backlogItemId}`);
        const result = await response.json();
        
        if (result.success) {
            renderTasks(result.tasks);
        }
    } catch (error) {
        console.error('Error loading tasks:', error);
    }
}

function renderTasks(tasks) {
    const tasksList = document.getElementById('tasksList');
    
    if (!tasks || tasks.length === 0) {
        tasksList.innerHTML = '<p class="text-sm text-gray-500 text-center py-4">No hay tareas creadas aún</p>';
        return;
    }
    
    const statusLabels = {
        'todo': { text: 'Por Hacer', class: 'bg-gray-100 text-gray-800' },
        'in_progress': { text: 'En Progreso', class: 'bg-yellow-100 text-yellow-800' },
        'done': { text: 'Hecho', class: 'bg-green-100 text-green-800' }
    };
    
    tasksList.innerHTML = tasks.map(task => `
        <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100">
            <div class="flex-1">
                <div class="flex items-center gap-2 mb-1">
                    <span class="px-2 py-0.5 text-xs font-semibold rounded-full ${statusLabels[task.status].class}">
                        ${statusLabels[task.status].text}
                    </span>
                    <h5 class="font-medium text-gray-900">${task.title}</h5>
                </div>
                ${task.description ? `<p class="text-xs text-gray-600 ml-0">${task.description}</p>` : ''}
                <div class="flex items-center gap-3 mt-1 text-xs text-gray-500">
                    ${task.estimated_hours ? `<span><i class="far fa-clock mr-1"></i>${task.estimated_hours}h est.</span>` : ''}
                    ${task.actual_hours ? `<span><i class="fas fa-clock mr-1"></i>${task.actual_hours}h real</span>` : ''}
                    ${task.assigned_to ? `<span><i class="fas fa-user mr-1"></i>${task.assigned_first_name} ${task.assigned_last_name}</span>` : ''}
                </div>
            </div>
            <div class="flex items-center gap-2">
                ${task.status !== 'done' ? `
                    <button onclick="toggleTaskStatus(${task.id}, '${task.status}')" 
                            class="p-2 text-green-600 hover:bg-green-50 rounded" 
                            title="${task.status === 'todo' ? 'Marcar en progreso' : 'Marcar como hecho'}">
                        <i class="fas fa-check"></i>
                    </button>
                ` : ''}
                <button onclick="editTask(${task.id})" 
                        class="p-2 text-blue-600 hover:bg-blue-50 rounded" 
                        title="Editar">
                    <i class="fas fa-edit"></i>
                </button>
                <button onclick="deleteTask(${task.id}, '${task.title}')" 
                        class="p-2 text-red-600 hover:bg-red-50 rounded" 
                        title="Eliminar">
                    <i class="fas fa-trash"></i>
                </button>
            </div>
        </div>
    `).join('');
}

function showCreateTaskModal() {
    document.getElementById('taskModalTitle').textContent = 'Nueva Tarea';
    document.getElementById('task_action').value = 'create';
    document.getElementById('task_id').value = '';
    document.getElementById('task_backlog_item_id').value = currentBacklogItemId;
    document.getElementById('taskForm').reset();
    document.getElementById('task_backlog_item_id').value = currentBacklogItemId; // Restaurar después del reset
    document.getElementById('taskModal').classList.remove('hidden');
}

function editTask(taskId) {
    // Buscar la tarea en la lista cargada
    fetch(`/tasks/list?backlog_item_id=${currentBacklogItemId}`)
        .then(res => res.json())
        .then(result => {
            const task = result.tasks.find(t => t.id == taskId);
            if (!task) return;
            
            document.getElementById('taskModalTitle').textContent = 'Editar Tarea';
            document.getElementById('task_action').value = 'update_full';
            document.getElementById('task_id').value = task.id;
            document.getElementById('task_backlog_item_id').value = currentBacklogItemId;
            document.getElementById('task_title').value = task.title;
            document.getElementById('task_description').value = task.description || '';
            document.getElementById('task_status').value = task.status;
            document.getElementById('task_estimated_hours').value = task.estimated_hours || '';
            document.getElementById('task_assigned_to').value = task.assigned_to || '';
            
            document.getElementById('taskModal').classList.remove('hidden');
        });
}

function closeTaskModal() {
    document.getElementById('taskModal').classList.add('hidden');
}

async function saveTask(event) {
    event.preventDefault();
    
    const formData = new FormData(event.target);
    const action = formData.get('action');
    
    try {
        const url = action === 'create' ? '/tasks/create' : '/tasks/update';
        
        const response = await fetch(url, {
            method: 'POST',
            body: formData
        });
        
        if (response.redirected) {
            window.location.href = response.url;
        } else {
            const result = await response.json();
            if (result.success) {
                closeTaskModal();
                loadTasks(currentBacklogItemId);
            } else {
                alert('Error: ' + result.message);
            }
        }
    } catch (error) {
        alert('Error al guardar tarea');
    }
}

async function toggleTaskStatus(taskId, currentStatus) {
    const newStatus = currentStatus === 'todo' ? 'in_progress' : 'done';
    
    try {
        const formData = new FormData();
        formData.append('csrf_token', '<?= csrf_token() ?>');
        formData.append('task_id', taskId);
        formData.append('action', 'update_status');
        formData.append('status', newStatus);
        
        const response = await fetch('/tasks/update', {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        if (result.success) {
            loadTasks(currentBacklogItemId);
            // Recargar página para actualizar horas totales
            setTimeout(() => window.location.reload(), 500);
        } else {
            alert('Error: ' + result.message);
        }
    } catch (error) {
        alert('Error al actualizar estado');
    }
}

async function deleteTask(taskId, taskTitle) {
    if (!confirm(`¿Eliminar la tarea "${taskTitle}"?`)) return;
    
    try {
        const formData = new FormData();
        formData.append('csrf_token', '<?= csrf_token() ?>');
        formData.append('task_id', taskId);
        
        const response = await fetch('/tasks/delete', {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        if (result.success) {
            loadTasks(currentBacklogItemId);
            // Recargar página para actualizar horas totales
            setTimeout(() => window.location.reload(), 500);
        } else {
            alert('Error: ' + result.message);
        }
    } catch (error) {
        alert('Error al eliminar tarea');
    }
}
</script>

<?php
$content = ob_get_clean();
include __DIR__ . '/../layouts/app.php';
?>
