<?php
ob_start();

$title = 'Product Backlog - ' . htmlspecialchars($project['name']);
$page_title = 'Product Backlog';
$current_page = 'backlog';
$showSidebar = true;
?>

<div class="max-w-7xl mx-auto">
    <!-- Header con información del proyecto -->
    <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <div class="flex justify-between items-start">
            <div>
                <div class="flex items-center gap-3 mb-2">
                    <a href="/projects/<?= $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($project['name']) ?></h1>
                    <span class="px-3 py-1 text-xs font-semibold rounded-full bg-gray-100 text-gray-600">
                        <?= htmlspecialchars($project['code']) ?>
                    </span>
                </div>
                <p class="text-gray-600 text-sm"><?= htmlspecialchars($project['description'] ?? '') ?></p>
            </div>
            <button onclick="openCreateItemModal()" class="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition-colors">
                <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>
                Nuevo Item
            </button>
        </div>
    </div>

    <!-- Tabs: Backlog / Sprints -->
    <div class="bg-white rounded-lg shadow-sm mb-6">
        <div class="border-b border-gray-200">
            <nav class="-mb-px flex">
                <button onclick="showTab('backlog')" id="tab-backlog" class="tab-button active border-b-2 border-primary-600 text-primary-600 py-4 px-6 font-medium">
                    Product Backlog
                    <span class="ml-2 px-2 py-1 text-xs rounded-full bg-primary-100"><?= count($items) ?></span>
                </button>
                <button onclick="showTab('sprints')" id="tab-sprints" class="tab-button border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 py-4 px-6 font-medium">
                    Sprints
                    <span class="ml-2 px-2 py-1 text-xs rounded-full bg-gray-100"><?= count($sprints) ?></span>
                </button>
            </nav>
        </div>

        <!-- Contenido Product Backlog -->
        <div id="content-backlog" class="tab-content p-6">
            <?php if (empty($items)): ?>
                <div class="text-center py-12">
                    <svg class="w-16 h-16 mx-auto text-gray-300 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"/>
                    </svg>
                    <h3 class="text-lg font-medium text-gray-900 mb-2">No hay items en el backlog</h3>
                    <p class="text-gray-500 mb-4">Comienza agregando historias de usuario o tareas</p>
                    <button onclick="openCreateItemModal()" class="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700">
                        Crear primer item
                    </button>
                </div>
            <?php else: ?>
                <div class="space-y-3">
                    <?php foreach ($items as $item): ?>
                        <div class="border border-gray-200 rounded-lg p-4 hover:border-primary-300 transition-colors cursor-pointer" onclick="viewItemDetails(<?= $item['id'] ?>)">
                            <div class="flex items-start justify-between">
                                <div class="flex-1">
                                    <div class="flex items-center gap-2 mb-2">
                                        <!-- Badge de tipo -->
                                        <?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'
                                        ];
                                        ?>
                                        <span class="px-2 py-1 text-xs font-semibold rounded <?= $type_colors[$item['type']] ?? 'bg-gray-100 text-gray-800' ?>">
                                            <?= $type_labels[$item['type']] ?? $item['type'] ?>
                                        </span>

                                        <!-- Badge de prioridad -->
                                        <?php
                                        $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 <?= $priority_colors[$item['priority']] ?>">
                                            <?= ucfirst($item['priority']) ?>
                                        </span>

                                        <!-- Badge de estado -->
                                        <?php
                                        $status_colors = [
                                            'backlog' => 'bg-gray-100 text-gray-800',
                                            'ready' => 'bg-blue-100 text-blue-800',
                                            'in_progress' => 'bg-yellow-100 text-yellow-800',
                                            'done' => 'bg-green-100 text-green-800',
                                            'cancelled' => 'bg-red-100 text-red-800'
                                        ];
                                        $status_labels = [
                                            'backlog' => 'Backlog',
                                            'ready' => 'Listo',
                                            'in_progress' => 'En Progreso',
                                            'done' => 'Hecho',
                                            'cancelled' => 'Cancelado'
                                        ];
                                        ?>
                                        <span class="px-2 py-1 text-xs font-semibold rounded <?= $status_colors[$item['status']] ?>">
                                            <?= $status_labels[$item['status']] ?>
                                        </span>

                                        <?php if ($item['story_points']): ?>
                                            <span class="px-2 py-1 text-xs font-semibold rounded bg-indigo-100 text-indigo-800">
                                                <?= $item['story_points'] ?> pts
                                            </span>
                                        <?php endif; ?>
                                    </div>

                                    <h3 class="text-lg font-semibold text-gray-800 mb-1"><?= htmlspecialchars($item['title']) ?></h3>
                                    
                                    <!-- Trazabilidad: Origen del Requerimiento -->
                                    <?php if ($item['requirement_code']): ?>
                                        <div class="mb-2 flex items-center gap-2">
                                            <div class="flex items-center gap-1 px-2 py-1 bg-blue-50 border border-blue-200 rounded text-xs">
                                                <svg class="w-3 h-3 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 9l3 3m0 0l-3 3m3-3H8m13 0a9 9 0 11-18 0 9 9 0 0118 0z"/>
                                                </svg>
                                                <span class="text-blue-700 font-medium">Desde:</span>
                                                <a href="/requirements/<?= $item['requirement_id'] ?>" class="text-blue-600 hover:text-blue-800 font-mono font-semibold">
                                                    <?= htmlspecialchars($item['requirement_code']) ?>
                                                </a>
                                                <span class="text-blue-600">-</span>
                                                <span class="text-blue-700 max-w-xs truncate"><?= htmlspecialchars($item['requirement_title']) ?></span>
                                            </div>
                                        </div>
                                    <?php else: ?>
                                        <div class="mb-2 flex items-center gap-1 px-2 py-1 bg-purple-50 border border-purple-200 rounded text-xs w-fit">
                                            <svg class="w-3 h-3 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"/>
                                            </svg>
                                            <span class="text-purple-700 font-medium">Item técnico sin requerimiento</span>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <?php if ($item['description']): ?>
                                        <p class="text-sm text-gray-600 mb-2"><?= nl2br(htmlspecialchars(substr($item['description'], 0, 150))) ?><?= strlen($item['description']) > 150 ? '...' : '' ?></p>
                                    <?php endif; ?>

                                    <div class="flex items-center gap-4 text-xs text-gray-500">
                                        <?php if ($item['assigned_to']): ?>
                                            <span>
                                                <svg class="w-4 h-4 inline-block mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/>
                                                </svg>
                                                <?= htmlspecialchars($item['assigned_first_name'] . ' ' . $item['assigned_last_name']) ?>
                                            </span>
                                        <?php endif; ?>
                                        
                                        <?php if ($item['tasks_count'] > 0): ?>
                                            <span>
                                                <svg class="w-4 h-4 inline-block mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"/>
                                                </svg>
                                                <?= $item['tasks_count'] ?> tareas
                                            </span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>

        <!-- Contenido Sprints -->
        <div id="content-sprints" class="tab-content hidden p-6">
            <div class="mb-4">
                <button onclick="openCreateSprintModal()" 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>
                    Nuevo Sprint
                </button>
            </div>

            <?php if (empty($sprints)): ?>
                <div class="text-center py-12">
                    <svg class="w-16 h-16 mx-auto text-gray-300 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
                    </svg>
                    <h3 class="text-lg font-medium text-gray-900 mb-2">No hay sprints creados</h3>
                    <p class="text-gray-500 mb-4">Organiza el trabajo en iteraciones de 2-4 semanas</p>
                    <button onclick="openCreateSprintModal()" class="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700">
                        Crear primer sprint
                    </button>
                </div>
            <?php else: ?>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <?php foreach ($sprints as $sprint): ?>
                        <div class="border border-gray-200 rounded-lg p-4 hover:border-primary-300 transition-colors">
                            <div class="flex items-start justify-between mb-3">
                                <div>
                                    <h3 class="font-semibold text-gray-800"><?= htmlspecialchars($sprint['name']) ?></h3>
                                    <p class="text-sm text-gray-500">
                                        <?= date('d/m/Y', strtotime($sprint['start_date'])) ?> - <?= date('d/m/Y', strtotime($sprint['end_date'])) ?>
                                    </p>
                                </div>
                                <?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-2 py-1 text-xs font-semibold rounded <?= $sprint_status_colors[$sprint['status']] ?>">
                                    <?= $sprint_status_labels[$sprint['status']] ?>
                                </span>
                            </div>

                            <?php if ($sprint['goal']): ?>
                                <p class="text-sm text-gray-600 mb-3"><?= htmlspecialchars($sprint['goal']) ?></p>
                            <?php endif; ?>

                            <div class="flex items-center justify-between">
                                <span class="text-sm text-gray-500">
                                    <svg class="w-4 h-4 inline-block mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"/>
                                    </svg>
                                    <?= $sprint['items_count'] ?> items
                                </span>
                                <a href="/sprints/<?= $sprint['id'] ?>" class="text-primary-600 hover:text-primary-700 text-sm font-medium">
                                    Ver detalles →
                                </a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Modal: Crear Item -->
<div id="createItemModal" 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">Nuevo Backlog Item</h3>
            <button onclick="closeCreateItemModal()" 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>

        <form id="createItemForm" class="space-y-4">
            <input type="hidden" name="project_id" value="<?= $project['id'] ?>">

            <div class="grid grid-cols-2 gap-4">
                <div class="col-span-2">
                    <label class="block text-sm font-medium text-gray-700 mb-1">Título *</label>
                    <input type="text" name="title" required class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Tipo *</label>
                    <select name="type" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500">
                        <option value="user_story">Historia de Usuario</option>
                        <option value="task">Tarea</option>
                        <option value="bug">Bug</option>
                        <option value="technical">Técnico</option>
                    </select>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Prioridad *</label>
                    <select name="priority" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500">
                        <option value="low">Baja</option>
                        <option value="medium" selected>Media</option>
                        <option value="high">Alta</option>
                        <option value="critical">Crítica</option>
                    </select>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Story Points</label>
                    <input type="number" name="story_points" min="1" max="100" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500">
                </div>

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

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

                <div class="col-span-2">
                    <label class="block text-sm font-medium text-gray-700 mb-1">Historia de Usuario (Como... Quiero... Para...)</label>
                    <textarea name="user_story" rows="3" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500" placeholder="Como [rol], quiero [funcionalidad], para [beneficio]"></textarea>
                </div>

                <div class="col-span-2">
                    <label class="block text-sm font-medium text-gray-700 mb-1">Criterios de Aceptación</label>
                    <textarea name="acceptance_criteria" rows="3" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500" placeholder="- Dado que... Cuando... Entonces..."></textarea>
                </div>
            </div>

            <div class="flex justify-end gap-3 pt-4">
                <button type="button" onclick="closeCreateItemModal()" 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-primary-600 text-white rounded-lg hover:bg-primary-700">
                    Crear Item
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Modal: Crear Sprint -->
<div id="createSprintModal" 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-xl shadow-lg rounded-md bg-white">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold text-gray-900">Nuevo Sprint</h3>
            <button onclick="closeCreateSprintModal()" 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>

        <form id="createSprintForm" class="space-y-4">
            <input type="hidden" name="project_id" value="<?= $project['id'] ?>">

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Nombre del Sprint *</label>
                <input type="text" name="name" required placeholder="Sprint 1" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500">
            </div>

            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Fecha Inicio *</label>
                    <input type="date" name="start_date" required class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Fecha Fin *</label>
                    <input type="date" name="end_date" required class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500">
                </div>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Objetivo del Sprint</label>
                <textarea name="goal" rows="3" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500" placeholder="¿Qué se espera lograr en este sprint?"></textarea>
            </div>

            <div class="flex justify-end gap-3 pt-4">
                <button type="button" onclick="closeCreateSprintModal()" 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-primary-600 text-white rounded-lg hover:bg-primary-700">
                    Crear Sprint
                </button>
            </div>
        </form>
    </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-3xl 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 -->
        </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" 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 if (empty($teamMembers)): ?>
                                <option value="" disabled>⚠️ No hay miembros en el equipo del proyecto</option>
                            <?php else: ?>
                                <?php foreach ($teamMembers as $member): ?>
                                <option value="<?= $member['id'] ?>">
                                    <?= htmlspecialchars($member['name']) ?>
                                    <?= $member['is_leader'] ? ' (Líder)' : '' ?>
                                </option>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </select>
                        <?php if (empty($teamMembers)): ?>
                        <p class="mt-1 text-xs text-amber-600">
                            <i class="fas fa-exclamation-triangle"></i>
                            Este proyecto no tiene un equipo asignado o el equipo no tiene miembros.
                        </p>
                        <?php endif; ?>
                    </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>
let currentBacklogItemId = null;

// Tabs
function showTab(tab) {
    document.querySelectorAll('.tab-button').forEach(btn => {
        btn.classList.remove('active', 'border-primary-600', 'text-primary-600');
        btn.classList.add('border-transparent', 'text-gray-500');
    });
    document.querySelectorAll('.tab-content').forEach(content => content.classList.add('hidden'));
    
    document.getElementById('tab-' + tab).classList.add('active', 'border-primary-600', 'text-primary-600');
    document.getElementById('tab-' + tab).classList.remove('border-transparent', 'text-gray-500');
    document.getElementById('content-' + tab).classList.remove('hidden');
}

// Modals
function openCreateItemModal() {
    document.getElementById('createItemModal').classList.remove('hidden');
}
function closeCreateItemModal() {
    document.getElementById('createItemModal').classList.add('hidden');
    document.getElementById('createItemForm').reset();
}

function openCreateSprintModal() {
    document.getElementById('createSprintModal').classList.remove('hidden');
}
function closeCreateSprintModal() {
    document.getElementById('createSprintModal').classList.add('hidden');
    document.getElementById('createSprintForm').reset();
}

// Crear Item
document.getElementById('createItemForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    const data = Object.fromEntries(formData.entries());
    
    try {
        const response = await fetch('/backlog/items/create', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        if (result.success) {
            window.location.reload();
        } else {
            alert('Error: ' + result.message);
        }
    } catch (error) {
        alert('Error al crear item');
    }
});

// Crear Sprint
document.getElementById('createSprintForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    const data = Object.fromEntries(formData.entries());
    
    try {
        const response = await fetch('/backlog/sprints/create', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        if (result.success) {
            window.location.href = '/sprints/' + result.sprint_id;
        } else {
            alert('Error: ' + result.message);
        }
    } catch (error) {
        alert('Error al crear sprint');
    }
});

function editItem(id) {
    // TODO: Implementar modal de edición
    console.log('Edit item:', id);
}

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

function viewItemDetails(itemId) {
    const item = allItems.find(i => i.id == itemId);
    if (!item) return;
    
    const typeLabels = {
        'user_story': 'Historia de Usuario',
        'task': 'Tarea',
        'bug': 'Bug',
        'technical': 'Técnico'
    };
    
    const statusLabels = {
        'backlog': 'Backlog',
        '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.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>
            ` : ''}
            ${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</span>
            </div>
            ` : ''}
        </div>
        
        <div class="bg-blue-50 border-l-4 border-blue-400 p-3 text-sm">
            <p class="font-medium text-blue-900">ℹ️ Información</p>
            <p class="text-blue-700 mt-1">
                El progreso del proyecto se calcula automáticamente basado en los items marcados como "Hecho".
            </p>
        </div>
    `;
    
    document.getElementById('itemDetailsContent').innerHTML = content;
    
    // Cargar tareas
    currentBacklogItemId = itemId;
    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;
    document.getElementById('taskModal').classList.remove('hidden');
}

function editTask(taskId) {
    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');
    
    // Log para debugging
    console.log('=== SAVE TASK ===');
    console.log('Action:', action);
    for (let pair of formData.entries()) {
        console.log(pair[0] + ':', pair[1]);
    }
    
    try {
        const url = action === 'create' ? '/tasks/create' : '/tasks/update';
        console.log('URL:', url);
        
        const response = await fetch(url, {
            method: 'POST',
            body: formData,
            credentials: 'same-origin'
        });
        
        console.log('Response status:', response.status);
        console.log('Response ok:', response.ok);
        
        const text = await response.text();
        console.log('Response text:', text);
        
        let result;
        try {
            result = JSON.parse(text);
        } catch (e) {
            console.error('Error parsing JSON:', e);
            throw new Error('Respuesta no válida del servidor: ' + text.substring(0, 100));
        }
        
        console.log('Parsed result:', result);
        
        if (result.success) {
            closeTaskModal();
            loadTasks(currentBacklogItemId);
        } else {
            alert('Error: ' + result.message);
        }
    } catch (error) {
        console.error('Error completo:', error);
        alert('Error al guardar tarea: ' + error.message);
    }
}

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);
            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);
            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';
?>
