<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<style>
	.management-grid {
		display: grid;
		grid-template-columns: repeat(2, minmax(0, 1fr));
		gap: 16px;
		margin-bottom: 16px;
	}
	.management-card {
		display: grid;
		gap: 14px;
		padding: 18px;
		border-radius: 22px;
		background: var(--panel);
		box-shadow: var(--shadow);
	}
	.management-card-head {
		display: flex;
		align-items: center;
		justify-content: space-between;
		gap: 12px;
	}
	.management-card-head h3 {
		margin: 0;
		font-size: 1.02rem;
	}
	.management-card-head p {
		margin: 4px 0 0;
		color: var(--muted);
		font-size: 0.9rem;
	}
	.management-list {
		display: grid;
		gap: 10px;
	}
	.management-row {
		display: grid;
		grid-template-columns: minmax(0, 1fr) auto;
		gap: 12px;
		align-items: center;
		padding: 14px;
		border-radius: 18px;
		background: var(--card);
		box-shadow: inset 0 0 0 1px rgba(20, 41, 64, 0.08);
	}
	.management-row strong,
	.management-row span {
		display: block;
	}
	.management-row strong {
		color: var(--ink);
	}
	.management-row span {
		margin-top: 4px;
		color: var(--muted);
		font-size: 0.9rem;
	}
	.management-empty {
		padding: 18px;
		border-radius: 18px;
		background: var(--card);
		color: var(--muted);
		text-align: center;
		box-shadow: inset 0 0 0 1px rgba(20, 41, 64, 0.08);
	}
	.filter-bar {
		display: grid;
		grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
		gap: 12px;
		margin-bottom: 18px;
	}
	.filter-bar input, .filter-bar select {
		padding: 10px 12px;
		border-radius: 12px;
		border: 0;
		box-shadow: inset 0 0 0 1px var(--border);
		font-family: inherit;
	}
	.quick-task-actions {
		display: flex;
		flex-wrap: wrap;
		gap: 10px;
		align-items: center;
		margin-bottom: 12px;
	}
	.employee-task-board {
		display: grid;
		gap: 16px;
	}
	.employee-task-card {
		background: var(--panel);
		border-radius: 22px;
		box-shadow: var(--shadow);
		overflow: hidden;
	}
	.employee-task-head {
		display: flex;
		align-items: center;
		justify-content: space-between;
		gap: 12px;
		padding: 16px 18px;
		background: linear-gradient(180deg, rgba(95, 143, 168, 0.12), rgba(95, 143, 168, 0.04));
		border-bottom: 1px solid var(--border);
	}
	.employee-task-head h3 {
		margin: 0;
		font-size: 1.02rem;
	}
	.employee-task-head p {
		margin: 4px 0 0;
		color: var(--muted);
		font-size: 0.9rem;
	}
	.employee-task-count {
		padding: 8px 12px;
		border-radius: 999px;
		background: var(--card);
		color: var(--ink);
		font-size: 0.85rem;
		box-shadow: inset 0 0 0 1px var(--border);
	}
	table {
		width: 100%;
		border-collapse: collapse;
		background: var(--panel);
		border-radius: 18px;
		overflow: hidden;
		box-shadow: var(--shadow);
	}
	.table-actions form { margin: 0; }
	th, td {
		padding: 12px 14px;
		text-align: left;
		border-bottom: 1px solid var(--border);
	}
	th {
		background: var(--card);
		font-size: 0.9rem;
		text-transform: uppercase;
		letter-spacing: 0.04em;
		color: var(--muted);
	}
	tr:last-child td { border-bottom: 0; }
	.panel-message {
		margin-bottom: 12px;
	}
	.panel-message.success {
		background: #e9f7ef;
		color: #1f5c3a;
	}
	.panel-message.error {
		background: #fdecea;
		color: #7a2d2d;
	}
	.task-row.is-updating {
		opacity: 0.55;
		transition: opacity 0.18s ease;
	}
	.modal-backdrop {
		position: fixed;
		inset: 0;
		background: rgba(15, 23, 42, 0.44);
		display: none;
		align-items: center;
		justify-content: center;
		padding: 24px;
		z-index: 999;
	}
	.modal-backdrop.is-open {
		display: flex;
	}
	.modal-card {
		width: min(920px, 100%);
		max-height: calc(100vh - 48px);
		overflow: auto;
		background: var(--panel);
		border-radius: 24px;
		box-shadow: 0 24px 60px rgba(15, 23, 42, 0.24);
	}
	.modal-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		gap: 12px;
		padding: 18px 20px;
		border-bottom: 1px solid var(--border);
		position: sticky;
		top: 0;
		background: var(--panel);
		z-index: 2;
	}
	.modal-header h3 {
		margin: 0;
		font-size: 1.1rem;
	}
	.modal-close {
		width: 42px;
		height: 42px;
		border: 0;
		border-radius: 999px;
		background: var(--card);
		color: var(--ink);
		font-size: 1.2rem;
		cursor: pointer;
		box-shadow: inset 0 0 0 1px var(--border);
	}
	.modal-body {
		padding: 20px;
	}
	.quick-task-card {
		display: grid;
		gap: 18px;
	}
	.quick-task-form-grid {
		display: grid;
		gap: 14px;
	}
	.task-modal-card {
		display: grid;
		gap: 18px;
	}
	.task-modal-head {
		display: flex;
		align-items: flex-start;
		justify-content: space-between;
		gap: 16px;
	}
	.task-modal-head h3 {
		margin: 0;
		font-size: 1.25rem;
	}
	.task-modal-meta {
		display: flex;
		flex-wrap: wrap;
		gap: 10px;
		margin-top: 10px;
		color: var(--muted);
		font-size: 0.92rem;
	}
	.task-modal-grid {
		display: grid;
		grid-template-columns: repeat(2, minmax(0, 1fr));
		gap: 16px;
	}
	.task-modal-section {
		background: var(--card);
		border-radius: 18px;
		padding: 16px;
		box-shadow: inset 0 0 0 1px var(--border);
	}
	.task-modal-section h4 {
		margin: 0 0 12px;
	}
	.task-modal-form-grid {
		display: grid;
		grid-template-columns: repeat(2, minmax(0, 1fr));
		gap: 12px;
		margin-bottom: 12px;
	}
	.task-field {
		display: grid;
		gap: 6px;
		color: var(--muted);
		font-size: 0.92rem;
	}
	.task-field input,
	.task-field textarea,
	.task-field select {
		width: 100%;
		border: 0;
		border-radius: 14px;
		padding: 14px 16px;
		background: #ffffff;
		color: var(--field-ink);
		box-shadow: inset 0 0 0 1px rgba(20, 41, 64, 0.12);
		font-family: inherit;
		font-size: 0.98rem;
		transition: box-shadow 0.18s ease, transform 0.18s ease;
	}
	.task-field input:focus,
	.task-field textarea:focus,
	.task-field select:focus {
		outline: none;
		box-shadow: inset 0 0 0 2px rgba(95, 143, 168, 0.42);
		transform: translateY(-1px);
	}
	.quick-task-modal-actions {
		display: flex;
		justify-content: flex-end;
		gap: 10px;
		padding-top: 6px;
	}
	.task-modal-list {
		display: grid;
		gap: 10px;
	}
	.task-modal-row, .task-modal-note {
		background: #fff;
		border-radius: 14px;
		padding: 12px;
		box-shadow: inset 0 0 0 1px var(--border);
	}
	.task-modal-row {
		display: flex;
		align-items: center;
		justify-content: space-between;
		gap: 12px;
	}
	@media (max-width: 760px) {
		.management-grid {
			grid-template-columns: 1fr;
		}
		.quick-task-actions {
			display: grid;
			grid-template-columns: 1fr;
		}
		.modal-backdrop {
			padding: 12px;
		}
		.quick-task-modal-actions {
			grid-template-columns: 1fr;
			display: grid;
		}
		.quick-task-modal-actions .btn {
			width: 100%;
		}
		.task-modal-head,
		.task-modal-grid {
			grid-template-columns: 1fr;
			display: grid;
		}
		.task-modal-form-grid {
			grid-template-columns: 1fr;
		}
	}
</style>

<?php
	$filters = isset($filters) && is_array($filters) ? $filters : array();
	$current_status = isset($filters['status']) ? (string) $filters['status'] : 'all';
	$templates = isset($templates) && is_array($templates) ? $templates : array();
	$rules = isset($rules) && is_array($rules) ? $rules : array();
	$assignment_groups = array();
	foreach ((array) $assignments as $assignment) {
		$employee_key = isset($assignment['employee_id']) ? (int) $assignment['employee_id'] : 0;
		if (!isset($assignment_groups[$employee_key])) {
			$assignment_groups[$employee_key] = array(
				'employee_id' => $employee_key,
				'employee_name' => isset($assignment['employee_name']) ? (string) $assignment['employee_name'] : 'Empleado',
				'group_name' => isset($assignment['group_name']) ? (string) $assignment['group_name'] : '',
				'rows' => array(),
			);
		}
		$assignment_groups[$employee_key]['rows'][] = $assignment;
	}
	uasort($assignment_groups, function ($left, $right) {
		$left_name = isset($left['employee_name']) ? (string) $left['employee_name'] : '';
		$right_name = isset($right['employee_name']) ? (string) $right['employee_name'] : '';
		return strcasecmp($left_name, $right_name);
	});
?>

<div class="quick-task-actions">
	<button class="btn" type="button" id="quick-task-open">Agregar tarea rapida</button>
	<?php if (!empty($can_view_task_templates)) { ?>
		<a class="btn btn-outline" href="<?php echo site_url('tareas/plantillas'); ?>">Plantillas</a>
	<?php } ?>
	<?php if (!empty($can_view_task_rules)) { ?>
		<a class="btn" href="<?php echo site_url('tareas/configuradas'); ?>">Tareas</a>
	<?php } ?>
	<?php if (!empty($can_export_tasks)) { ?>
		<a class="btn" href="<?php echo site_url('tareas/exportar').'?'.http_build_query($filters); ?>">Exportar CSV</a>
	<?php } ?>
</div>

<?php if (FALSE) { ?>
<section class="management-grid">
	<div class="management-card">
		<div class="management-card-head">
			<div>
				<h3>Plantillas</h3>
				<p>Edita la base de subtareas antes de asignarlas.</p>
			</div>
			<a class="btn btn-outline" href="<?php echo site_url('tareas/plantillas/nueva'); ?>">Nueva</a>
		</div>
		<?php if (empty($templates)) { ?>
			<div class="management-empty">Todavia no hay plantillas creadas.</div>
		<?php } else { ?>
			<div class="management-list">
				<?php foreach (array_slice($templates, 0, 4) as $template) { ?>
					<div class="management-row">
						<div>
							<strong><?php echo htmlspecialchars(!empty($template['name']) ? (string) $template['name'] : 'Plantilla', ENT_QUOTES, 'UTF-8'); ?></strong>
							<span><?php echo !empty($template['description']) ? htmlspecialchars((string) $template['description'], ENT_QUOTES, 'UTF-8') : 'Sin descripcion'; ?></span>
						</div>
						<a class="btn btn-outline" href="<?php echo site_url('tareas/plantillas/'.(int) $template['id']); ?>">Editar</a>
					</div>
				<?php } ?>
			</div>
		<?php } ?>
	</div>

	<div class="management-card">
		<div class="management-card-head">
			<div>
				<h3>Tareas configuradas</h3>
				<p>Edita reglas, destino y recurrencia sin salir del modulo.</p>
			</div>
			<a class="btn" href="<?php echo site_url('tareas/nueva'); ?>">Nueva</a>
		</div>
		<?php if (empty($rules)) { ?>
			<div class="management-empty">Todavia no hay tareas configuradas.</div>
		<?php } else { ?>
			<div class="management-list">
				<?php foreach (array_slice($rules, 0, 4) as $rule) { ?>
					<div class="management-row">
						<div>
							<strong><?php echo htmlspecialchars(!empty($rule['display_name']) ? (string) $rule['display_name'] : (!empty($rule['title']) ? (string) $rule['title'] : 'Tarea'), ENT_QUOTES, 'UTF-8'); ?></strong>
							<span><?php echo htmlspecialchars((string) $rule['target_label'].' · '.(string) $rule['recurrence_label'].' · Proxima: '.(string) $rule['next_due_date_label'], ENT_QUOTES, 'UTF-8'); ?></span>
						</div>
						<a class="btn btn-outline" href="<?php echo site_url('tareas/reglas/'.(int) $rule['id']); ?>">Editar</a>
					</div>
				<?php } ?>
			</div>
		<?php } ?>
	</div>
</section>
<?php } ?>

<form method="get" class="filter-bar">
	<input type="text" name="q" placeholder="Buscar..." value="<?php echo htmlspecialchars(isset($filters['q']) ? $filters['q'] : '', ENT_QUOTES, 'UTF-8'); ?>" />
	<select name="status">
		<?php
			$statuses = array(
				'all' => 'Todas',
				'pending' => 'Pendientes',
				'in_progress' => 'En progreso',
				'overdue' => 'Vencidas',
				'completed' => 'Completadas',
			);
		?>
		<?php foreach ($statuses as $value => $label) { ?>
			<option value="<?php echo $value; ?>" <?php echo $current_status === $value ? 'selected' : ''; ?>><?php echo $label; ?></option>
		<?php } ?>
	</select>
	<select name="employee_id">
		<option value="0">Todos los empleados</option>
		<?php foreach ((array) $employees as $employee) { ?>
			<option value="<?php echo (int)$employee['person_id']; ?>" <?php echo !empty($filters['employee_id']) && (int)$filters['employee_id'] === (int)$employee['person_id'] ? 'selected' : ''; ?>>
				<?php echo htmlspecialchars($employee['full_name'], ENT_QUOTES, 'UTF-8'); ?>
			</option>
		<?php } ?>
	</select>
	<select name="group_id">
		<option value="0">Todos los grupos</option>
		<?php foreach ((array) $groups as $group) { ?>
			<option value="<?php echo (int)$group['id']; ?>" <?php echo !empty($filters['group_id']) && (int)$filters['group_id'] === (int)$group['id'] ? 'selected' : ''; ?>>
				<?php echo htmlspecialchars($group['name'], ENT_QUOTES, 'UTF-8'); ?>
			</option>
		<?php } ?>
	</select>
	<button class="btn" type="submit">Filtrar</button>
	<a class="btn btn-outline" href="<?php echo site_url('tareas'); ?>">Limpiar</a>
</form>

<div id="tasks-feedback" class="panel panel-message" hidden></div>

<?php if (!empty($flash_message)) { ?>
	<div class="panel panel-message success">
		<?php echo htmlspecialchars($flash_message, ENT_QUOTES, 'UTF-8'); ?>
	</div>
<?php } ?>
<?php if (!empty($flash_error)) { ?>
	<div class="panel panel-message error">
		<?php echo htmlspecialchars($flash_error, ENT_QUOTES, 'UTF-8'); ?>
	</div>
<?php } ?>

<?php if (empty($assignments)) { ?>
	<div id="tasks-empty-state" class="panel">No hay tareas que coincidan con los filtros.</div>
<?php } else { ?>
	<div id="tasks-empty-state" class="panel" style="display:none;">No hay tareas que coincidan con los filtros.</div>
	<div id="tasks-table" class="employee-task-board">
		<?php foreach ($assignment_groups as $employee_group) { ?>
			<section class="employee-task-card" data-employee-section="<?php echo (int) $employee_group['employee_id']; ?>">
				<div class="employee-task-head">
					<div>
						<h3><?php echo htmlspecialchars($employee_group['employee_name'], ENT_QUOTES, 'UTF-8'); ?></h3>
						<p>
							<?php
								$group_names = array();
								foreach ((array) $employee_group['rows'] as $row) {
									if (!empty($row['group_name']) && !in_array($row['group_name'], $group_names, TRUE)) {
										$group_names[] = $row['group_name'];
									}
								}
								echo !empty($group_names)
									? htmlspecialchars(implode(' · ', $group_names), ENT_QUOTES, 'UTF-8')
									: 'Sin grupo asignado';
							?>
						</p>
					</div>
					<span class="employee-task-count" data-role="employee-task-count"><?php echo count($employee_group['rows']); ?> tareas</span>
				</div>
				<table>
					<thead>
						<tr>
							<th>Tarea</th>
							<th>Estado</th>
							<th>Asignada</th>
							<th>Vence</th>
							<th>Grupo</th>
							<th>Detalle</th>
							<th>Verificado</th>
							<th></th>
						</tr>
					</thead>
					<tbody>
					<?php foreach ($employee_group['rows'] as $assignment) { ?>
						<?php
							$status = isset($assignment['status']) ? (string)$assignment['status'] : 'pending';
							$status_label = isset($assignment['status_label']) ? (string)$assignment['status_label'] : 'Pendiente';
							$status_class = isset($assignment['status_class']) ? (string)$assignment['status_class'] : 'warning';
							$action_type = isset($assignment['action_type']) ? (string)$assignment['action_type'] : ($status === 'completed' ? 'reactivate' : 'complete');
							$action_label = isset($assignment['action_label']) ? (string)$assignment['action_label'] : ($status === 'completed' ? 'Reactivar' : 'Completar');
						?>
						<tr class="task-row" data-assignment-id="<?php echo (int)$assignment['id']; ?>" data-status="<?php echo htmlspecialchars($status, ENT_QUOTES, 'UTF-8'); ?>" data-employee-id="<?php echo (int) $assignment['employee_id']; ?>">
							<td data-role="task-title"><?php echo htmlspecialchars((string) $assignment['title'], ENT_QUOTES, 'UTF-8'); ?></td>
							<td><span class="badge <?php echo $status_class; ?>" data-role="task-status"><?php echo $status_label; ?></span></td>
							<td><?php echo htmlspecialchars(isset($assignment['assigned_date_label']) ? $assignment['assigned_date_label'] : (!empty($assignment['assigned_date']) ? date('d/m/Y', strtotime($assignment['assigned_date'])) : '-'), ENT_QUOTES, 'UTF-8'); ?></td>
							<td data-role="task-due-date"><?php echo htmlspecialchars(isset($assignment['due_date_label']) ? $assignment['due_date_label'] : (!empty($assignment['due_date']) ? date('d/m/Y', strtotime($assignment['due_date'])) : '-'), ENT_QUOTES, 'UTF-8'); ?></td>
							<td><?php echo htmlspecialchars((string) $assignment['group_name'], ENT_QUOTES, 'UTF-8'); ?></td>
							<td>
								<span class="note" data-role="task-detail"><?php echo htmlspecialchars(isset($assignment['detail_label']) ? $assignment['detail_label'] : 'Sin detalle', ENT_QUOTES, 'UTF-8'); ?></span>
							</td>
							<td>
								<div class="muted" data-role="task-verification">
									<?php if (!empty($assignment['verified_by_label'])) { ?>
										<?php echo htmlspecialchars((string) $assignment['verified_by_label'], ENT_QUOTES, 'UTF-8'); ?>
										<?php if (!empty($assignment['verified_at_label'])) { ?>
											<br><?php echo htmlspecialchars((string) $assignment['verified_at_label'], ENT_QUOTES, 'UTF-8'); ?>
										<?php } ?>
									<?php } else { ?>
										-
									<?php } ?>
								</div>
							</td>
							<td class="table-actions" data-role="task-actions">
								<div style="display:flex; gap:8px; flex-wrap:wrap;">
									<button class="btn btn-outline js-task-view" type="button" data-url="<?php echo site_url('tareas/'.(int)$assignment['id']); ?>">Ver</button>
									<?php if ($action_type !== '' && $action_label !== '') { ?>
										<form method="post" action="<?php echo site_url('tareas'); ?>" class="js-task-action-form" style="display:inline-block;">
											<input type="hidden" name="assignment_id" value="<?php echo (int)$assignment['id']; ?>" />
											<input type="hidden" name="action_type" value="<?php echo htmlspecialchars($action_type, ENT_QUOTES, 'UTF-8'); ?>" data-role="action-type" />
											<button class="btn<?php echo in_array($action_type, array('reactivate', 'verify'), TRUE) ? ' btn-outline' : ''; ?>" type="button" data-role="submit-button"><?php echo htmlspecialchars($action_label, ENT_QUOTES, 'UTF-8'); ?></button>
										</form>
									<?php } ?>
									<?php if (!empty($assignment['secondary_action_type']) && !empty($assignment['secondary_action_label'])) { ?>
										<form method="post" action="<?php echo site_url('tareas'); ?>" class="js-task-action-form" style="display:inline-block;">
											<input type="hidden" name="assignment_id" value="<?php echo (int)$assignment['id']; ?>" />
											<input type="hidden" name="action_type" value="<?php echo htmlspecialchars((string) $assignment['secondary_action_type'], ENT_QUOTES, 'UTF-8'); ?>" data-role="action-type" />
											<button class="btn btn-outline" type="button" data-role="submit-button"><?php echo htmlspecialchars((string) $assignment['secondary_action_label'], ENT_QUOTES, 'UTF-8'); ?></button>
										</form>
									<?php } ?>
								</div>
							</td>
						</tr>
					<?php } ?>
				</table>
			</section>
		<?php } ?>
	</div>
<?php } ?>

<div id="task-modal" class="modal-backdrop" aria-hidden="true">
	<div class="modal-card" role="dialog" aria-modal="true" aria-labelledby="task-modal-title">
		<div class="modal-header">
			<h3 id="task-modal-title">Detalle de tarea</h3>
			<button class="modal-close" type="button" data-role="close-modal" aria-label="Cerrar">x</button>
		</div>
		<div id="task-modal-body" class="modal-body">
			<div class="empty">Cargando...</div>
		</div>
	</div>
</div>

<div id="quick-task-modal" class="modal-backdrop" aria-hidden="true">
	<div class="modal-card" role="dialog" aria-modal="true" aria-labelledby="quick-task-title">
		<div class="modal-header">
			<h3 id="quick-task-title">Agregar tarea rapida</h3>
			<button class="modal-close" type="button" data-role="close-quick-task" aria-label="Cerrar">x</button>
		</div>
		<div class="modal-body">
			<div class="quick-task-card">
				<form id="quick-task-form" class="quick-task-form-grid">
					<div class="task-field">
						<label for="quick-task-name">Nombre de la tarea</label>
						<input id="quick-task-name" name="title" type="text" maxlength="255" placeholder="Ej. Organizar vitrinas de entrada" />
					</div>
					<div class="task-field">
						<label for="quick-task-employee">Empleado</label>
						<select id="quick-task-employee" name="employee_id">
							<option value="">Selecciona un empleado</option>
							<?php foreach ((array) $all_employees as $employee_option) { ?>
								<?php $employee_option_id = isset($employee_option['person_id']) ? (int) $employee_option['person_id'] : 0; ?>
								<?php if ($employee_option_id <= 0) { continue; } ?>
								<option value="<?php echo $employee_option_id; ?>">
									<?php echo htmlspecialchars(!empty($employee_option['full_name']) ? (string) $employee_option['full_name'] : 'Empleado', ENT_QUOTES, 'UTF-8'); ?>
								</option>
							<?php } ?>
						</select>
					</div>
					<div class="quick-task-modal-actions">
						<button class="btn btn-outline" type="button" id="quick-task-cancel">Cancelar</button>
						<button class="btn" type="submit" id="quick-task-save">Aceptar</button>
					</div>
				</form>
			</div>
		</div>
	</div>
</div>

<script>
(function () {
	const feedback = document.getElementById('tasks-feedback');
	const table = document.getElementById('tasks-table');
	const emptyState = document.getElementById('tasks-empty-state');
	const currentStatus = <?php echo json_encode($current_status); ?>;
	const currentQuery = <?php echo json_encode(isset($filters['q']) ? (string) $filters['q'] : ''); ?>;
	const currentEmployeeId = <?php echo json_encode((int) (isset($filters['employee_id']) ? $filters['employee_id'] : 0)); ?>;
	const currentGroupId = <?php echo json_encode((int) (isset($filters['group_id']) ? $filters['group_id'] : 0)); ?>;
	const taskModal = document.getElementById('task-modal');
	const taskModalBody = document.getElementById('task-modal-body');
	const taskModalTitle = document.getElementById('task-modal-title');
	const quickTaskModal = document.getElementById('quick-task-modal');
	const quickTaskOpen = document.getElementById('quick-task-open');
	const quickTaskForm = document.getElementById('quick-task-form');
	const quickTaskName = document.getElementById('quick-task-name');
	const quickTaskEmployee = document.getElementById('quick-task-employee');
	const quickTaskSave = document.getElementById('quick-task-save');
	const quickTaskCancel = document.getElementById('quick-task-cancel');

	function escapeHtml(value) {
		return String(value || '')
			.replace(/&/g, '&amp;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;')
			.replace(/"/g, '&quot;')
			.replace(/'/g, '&#039;');
	}

	function openModal() {
		if (!taskModal) {
			return;
		}
		taskModal.classList.add('is-open');
		taskModal.setAttribute('aria-hidden', 'false');
		document.body.style.overflow = 'hidden';
	}

	function closeModal() {
		if (!taskModal) {
			return;
		}
		taskModal.classList.remove('is-open');
		taskModal.setAttribute('aria-hidden', 'true');
		document.body.style.overflow = '';
	}

	function openQuickTaskModal() {
		if (!quickTaskModal) {
			return;
		}
		quickTaskModal.classList.add('is-open');
		quickTaskModal.setAttribute('aria-hidden', 'false');
		document.body.style.overflow = 'hidden';
		if (quickTaskName) {
			quickTaskName.focus();
		}
	}

	function closeQuickTaskModal() {
		if (!quickTaskModal) {
			return;
		}
		quickTaskModal.classList.remove('is-open');
		quickTaskModal.setAttribute('aria-hidden', 'true');
		document.body.style.overflow = '';
		if (quickTaskForm) {
			quickTaskForm.reset();
		}
	}

	function showFeedback(message, isError) {
		if (!feedback) {
			return;
		}

		if (!message) {
			feedback.hidden = true;
			feedback.textContent = '';
			feedback.classList.remove('success', 'error');
			return;
		}

		feedback.textContent = message;
		feedback.hidden = false;
		feedback.classList.remove('success', 'error');
		feedback.classList.add(isError ? 'error' : 'success');
	}

	function setFormBusy(form, isBusy) {
		const button = form.querySelector('[data-role="submit-button"]');
		if (button) {
			button.disabled = isBusy;
		}

		const row = form.closest('[data-assignment-id]');
		if (row) {
			row.classList.toggle('is-updating', isBusy);
		}
	}

	function syncEmptyState() {
		if (!table || !emptyState) {
			return;
		}

		table.querySelectorAll('[data-employee-section]').forEach(function (section) {
			const rows = section.querySelectorAll('tr[data-assignment-id]');
			if (!rows.length) {
				section.remove();
				return;
			}

			const count = section.querySelector('[data-role="employee-task-count"]');
			if (count) {
				count.textContent = rows.length + (rows.length === 1 ? ' tarea' : ' tareas');
			}
		});

		const hasRows = !!table.querySelector('tr[data-assignment-id]');
		table.style.display = hasRows ? '' : 'none';
		emptyState.style.display = hasRows ? 'none' : '';
	}
	function renderTaskActionButtons(assignment) {
		var html = '<div style="display:flex; gap:8px; flex-wrap:wrap;">';
		html += '<button class="btn btn-outline js-task-view" type="button" data-url="<?php echo site_url('tareas'); ?>/' + parseInt(assignment.id, 10) + '">Ver</button>';

		if (assignment.action_type && assignment.action_label) {
			var actionButtonClass = ['reactivate','verify'].indexOf(assignment.action_type) !== -1 ? 'btn btn-outline' : 'btn';
			html += '<form method="post" action="<?php echo site_url('tareas'); ?>" class="js-task-action-form" style="display:inline-block;">' +
				'<input type="hidden" name="assignment_id" value="' + parseInt(assignment.id, 10) + '" />' +
				'<input type="hidden" name="action_type" value="' + escapeHtml(assignment.action_type) + '" data-role="action-type" />' +
				'<button class="' + actionButtonClass + '" type="button" data-role="submit-button">' + escapeHtml(assignment.action_label) + '</button>' +
			'</form>';
		}

		if (assignment.secondary_action_type && assignment.secondary_action_label) {
			html += '<form method="post" action="<?php echo site_url('tareas'); ?>" class="js-task-action-form" style="display:inline-block;">' +
				'<input type="hidden" name="assignment_id" value="' + parseInt(assignment.id, 10) + '" />' +
				'<input type="hidden" name="action_type" value="' + escapeHtml(assignment.secondary_action_type) + '" data-role="action-type" />' +
				'<button class="btn btn-outline" type="button" data-role="submit-button">' + escapeHtml(assignment.secondary_action_label) + '</button>' +
			'</form>';
		}

		html += '</div>';
		return html;
	}

	function updateAssignmentRow(assignment) {
		if (!assignment || !assignment.id) {
			return;
		}

		const row = document.querySelector('[data-assignment-id="' + assignment.id + '"]');
		if (!row) {
			return;
		}

		if (currentStatus !== 'all' && assignment.status !== currentStatus) {
			row.remove();
			syncEmptyState();
			return;
		}

		row.dataset.status = assignment.status || 'pending';
		const titleCell = row.querySelector('[data-role="task-title"]');
		if (titleCell) {
			titleCell.textContent = assignment.title || '';
		}

		const dueDateCell = row.querySelector('[data-role="task-due-date"]');
		if (dueDateCell) {
			dueDateCell.textContent = assignment.due_date_label || '-';
		}

		const detailCell = row.querySelector('[data-role="task-detail"]');
		if (detailCell) {
			detailCell.textContent = assignment.detail_label || 'Sin detalle';
		}

		const verificationCell = row.querySelector('[data-role="task-verification"]');
		if (verificationCell) {
			verificationCell.innerHTML = assignment.verified_by_label
				? escapeHtml(assignment.verified_by_label) + (assignment.verified_at_label ? '<br>' + escapeHtml(assignment.verified_at_label) : '')
				: '-';
		}

		const statusBadge = row.querySelector('[data-role="task-status"]');
		if (statusBadge) {
			statusBadge.textContent = assignment.status_label || 'Pendiente';
			statusBadge.classList.remove('success', 'warning', 'danger');
			statusBadge.classList.add(assignment.status_class || 'warning');
		}

		const actionsCell = row.querySelector('[data-role="task-actions"]');
		if (actionsCell) {
			actionsCell.innerHTML = renderTaskActionButtons(assignment);
			actionsCell.querySelectorAll('.js-task-view').forEach(wireTaskViewButton);
			actionsCell.querySelectorAll('.js-task-action-form').forEach(wireTaskActionForm);
		}
	}

	function assignmentMatchesCurrentFilters(assignment) {
		if (!assignment) {
			return false;
		}
		if (currentStatus !== 'all' && (assignment.status || 'pending') !== currentStatus) {
			return false;
		}
		if (currentEmployeeId > 0 && parseInt(assignment.employee_id || 0, 10) !== currentEmployeeId) {
			return false;
		}
		if (currentGroupId > 0 && !assignment.group_name) {
			return false;
		}
		if (currentQuery) {
			var haystack = ((assignment.title || '') + ' ' + (assignment.employee_name || '') + ' ' + (assignment.group_name || '')).toLowerCase();
			if (haystack.indexOf(String(currentQuery).toLowerCase()) === -1) {
				return false;
			}
		}
		return true;
	}

	async function openTaskModal(button) {
		const url = button.getAttribute('data-url');
		if (!url || !taskModalBody) {
			return;
		}

		taskModalTitle.textContent = 'Detalle de tarea';
		taskModalBody.innerHTML = '<div class="empty">Cargando...</div>';
		openModal();

		try {
			const response = await fetch(url, {
				headers: {
					'X-Requested-With': 'XMLHttpRequest',
					'Accept': 'application/json'
				},
				credentials: 'same-origin'
			});
			const payload = await response.json().catch(function () {
				return null;
			});

			if (!response.ok || !payload || !payload.success) {
				window.location.href = url;
				return;
			}

			taskModalTitle.textContent = payload.title || 'Detalle de tarea';
			taskModalBody.innerHTML = payload.html || '<div class="empty">No encontramos el detalle.</div>';
			wireModalInteractions();
		} catch (error) {
			window.location.href = url;
		}
	}

	function wireTaskViewButton(button) {
		if (!button || button.dataset.wired === '1') {
			return;
		}
		button.dataset.wired = '1';
		button.addEventListener('click', function (event) {
			event.preventDefault();
			openTaskModal(button);
		});
	}

    function wireTaskActionForm(form) {
        if (!form || form.dataset.wired === '1') {
            return;
        }
        form.dataset.wired = '1';
        var submitButton = form.querySelector('[data-role="submit-button"]');
        if (submitButton) {
            submitButton.addEventListener('click', async function (event) {
                event.preventDefault();
                showFeedback('', false);
                setFormBusy(form, true);

                try {
                    const payload = await submitForm(form);
                    (payload.assignments || []).forEach(updateAssignmentRow);
                    showFeedback(payload.message || 'Tarea actualizada.', false);
                    syncEmptyState();
                } catch (error) {
                    showFeedback(error.message || 'No pudimos actualizar la tarea.', true);
                } finally {
                    setFormBusy(form, false);
                }
            });
        }
        form.addEventListener('submit', function (event) {
            event.preventDefault();
        });
    }

	function buildTaskRowHtml(assignment) {
		return '' +
			'<tr class="task-row" data-assignment-id="' + parseInt(assignment.id, 10) + '" data-status="' + escapeHtml(assignment.status || 'pending') + '" data-employee-id="' + parseInt(assignment.employee_id || 0, 10) + '">' +
				'<td data-role="task-title">' + escapeHtml(assignment.title || '') + '</td>' +
				'<td><span class="badge ' + escapeHtml(assignment.status_class || 'warning') + '" data-role="task-status">' + escapeHtml(assignment.status_label || 'Pendiente') + '</span></td>' +
				'<td>' + escapeHtml(assignment.assigned_date_label || '-') + '</td>' +
				'<td data-role="task-due-date">' + escapeHtml(assignment.due_date_label || '-') + '</td>' +
				'<td>' + escapeHtml(assignment.group_name || '') + '</td>' +
				'<td><span class="note" data-role="task-detail">' + escapeHtml(assignment.detail_label || 'Sin detalle') + '</span></td>' +
				'<td><div class="muted" data-role="task-verification">' + (assignment.verified_by_label ? escapeHtml(assignment.verified_by_label) + (assignment.verified_at_label ? '<br>' + escapeHtml(assignment.verified_at_label) : '') : '-') + '</div></td>' +
				'<td class="table-actions" data-role="task-actions">' + renderTaskActionButtons(assignment) + '</td>' +
			'</tr>';
	}

	function ensureEmployeeSection(assignment) {
		if (!table || !assignment) {
			return null;
		}
		var section = table.querySelector('[data-employee-section="' + parseInt(assignment.employee_id || 0, 10) + '"]');
		if (section) {
			return section;
		}

		var html = '' +
			'<section class="employee-task-card" data-employee-section="' + parseInt(assignment.employee_id || 0, 10) + '">' +
				'<div class="employee-task-head">' +
					'<div>' +
						'<h3>' + escapeHtml(assignment.employee_name || 'Empleado') + '</h3>' +
						'<p>' + escapeHtml(assignment.group_name || 'Sin grupo asignado') + '</p>' +
					'</div>' +
					'<span class="employee-task-count" data-role="employee-task-count">0 tareas</span>' +
				'</div>' +
				'<table>' +
					'<thead>' +
						'<tr>' +
							'<th>Tarea</th>' +
							'<th>Estado</th>' +
							'<th>Asignada</th>' +
							'<th>Vence</th>' +
							'<th>Grupo</th>' +
							'<th>Detalle</th>' +
							'<th>Verificado</th>' +
							'<th></th>' +
						'</tr>' +
					'</thead>' +
					'<tbody></tbody>' +
				'</table>' +
			'</section>';
		table.insertAdjacentHTML('beforeend', html);
		return table.querySelector('[data-employee-section="' + parseInt(assignment.employee_id || 0, 10) + '"]');
	}
    function prependAssignmentRow(assignment) {
        if (!assignmentMatchesCurrentFilters(assignment) || !table) {
            showFeedback('Tarea creada correctamente.', false);
            return;
        }

        var section = ensureEmployeeSection(assignment);
        if (!section) {
            return;
        }
        var tbody = section.querySelector('tbody');
        if (!tbody) {
            return;
        }

        tbody.insertAdjacentHTML('afterbegin', buildTaskRowHtml(assignment));
        var row = tbody.querySelector('[data-assignment-id="' + parseInt(assignment.id, 10) + '"]');
        if (row) {
            var viewButton = row.querySelector('.js-task-view');
            var actionForms = row.querySelectorAll('.js-task-action-form');
            if (viewButton) {
                wireTaskViewButton(viewButton);
            }
            actionForms.forEach(wireTaskActionForm);
        }
        syncEmptyState();
    }

	async function submitForm(form) {
		const formData = new FormData(form);
		const response = await fetch(form.action, {
			method: 'POST',
			headers: {
				'X-Requested-With': 'XMLHttpRequest',
				'Accept': 'application/json'
			},
			body: formData,
			credentials: 'same-origin'
		});
		const payload = await response.json().catch(function () {
			return {
				success: false,
				message: 'No pudimos actualizar la tarea.'
			};
		});

		if (!response.ok || !payload.success) {
			throw new Error(payload.message || 'No pudimos actualizar la tarea.');
		}

		return payload;
	}

	function wireModalInteractions() {
		if (!taskModalBody) {
			return;
		}

		const toggleButton = taskModalBody.querySelector('.js-modal-edit-toggle');
		const cancelButton = taskModalBody.querySelector('.js-modal-edit-cancel');
		const editForm = taskModalBody.querySelector('.js-modal-edit-form');

		if (toggleButton && editForm) {
			toggleButton.addEventListener('click', function () {
				editForm.style.display = editForm.style.display === 'none' ? '' : 'none';
			});
		}

		if (cancelButton && editForm) {
			cancelButton.addEventListener('click', function () {
				editForm.style.display = 'none';
			});
		}

		if (editForm) {
			editForm.addEventListener('submit', async function (event) {
				event.preventDefault();
				const submitButton = editForm.querySelector('button[type="submit"]');
				if (submitButton) {
					submitButton.disabled = true;
				}

				try {
					const response = await fetch(editForm.action, {
						method: 'POST',
						headers: {
							'X-Requested-With': 'XMLHttpRequest',
							'Accept': 'application/json'
						},
						body: new FormData(editForm),
						credentials: 'same-origin'
					});
					const payload = await response.json().catch(function () {
						return null;
					});

					if (payload && payload.html) {
						taskModalTitle.textContent = payload.title || 'Detalle de tarea';
						taskModalBody.innerHTML = payload.html;
						wireModalInteractions();
					}

					if (!response.ok || !payload || !payload.html || !payload.success) {
						throw new Error(payload && payload.message ? payload.message : 'No pudimos guardar la tarea.');
					}

					if (payload.assignment) {
						updateAssignmentRow(payload.assignment);
					}
					showFeedback(payload.message || 'Tarea actualizada.', false);
				} catch (error) {
					showFeedback(error.message || 'No pudimos guardar la tarea.', true);
				} finally {
					if (submitButton) {
						submitButton.disabled = false;
					}
				}
			});
		}
	}

	document.querySelectorAll('.js-task-view').forEach(wireTaskViewButton);
	document.querySelectorAll('.js-task-action-form').forEach(wireTaskActionForm);

	if (quickTaskOpen) {
		quickTaskOpen.addEventListener('click', function () {
			openQuickTaskModal();
		});
	}

	if (quickTaskCancel) {
		quickTaskCancel.addEventListener('click', function () {
			closeQuickTaskModal();
		});
	}

	if (quickTaskForm) {
		quickTaskForm.addEventListener('submit', async function (event) {
			event.preventDefault();
			showFeedback('', false);
			if (quickTaskSave) {
				quickTaskSave.disabled = true;
			}

			try {
				const response = await fetch('<?php echo site_url('tareas/rapida'); ?>', {
					method: 'POST',
					headers: {
						'X-Requested-With': 'XMLHttpRequest',
						'Accept': 'application/json'
					},
					body: new FormData(quickTaskForm),
					credentials: 'same-origin'
				});
				const payload = await response.json().catch(function () {
					return null;
				});
				if (!response.ok || !payload || !payload.success || !payload.assignment) {
					throw new Error(payload && payload.message ? payload.message : 'No pudimos crear la tarea rapida.');
				}

				prependAssignmentRow(payload.assignment);
				showFeedback(payload.message || 'Tarea creada correctamente.', false);
				closeQuickTaskModal();
			} catch (error) {
				showFeedback(error.message || 'No pudimos crear la tarea rapida.', true);
			} finally {
				if (quickTaskSave) {
					quickTaskSave.disabled = false;
				}
			}
		});
	}

	if (taskModal) {
		taskModal.addEventListener('click', function (event) {
			if (event.target === taskModal || event.target.getAttribute('data-role') === 'close-modal') {
				closeModal();
			}
		});
	}

	if (quickTaskModal) {
		quickTaskModal.addEventListener('click', function (event) {
			if (event.target === quickTaskModal || event.target.getAttribute('data-role') === 'close-quick-task') {
				closeQuickTaskModal();
			}
		});
	}

	document.addEventListener('keydown', function (event) {
		if (event.key !== 'Escape') {
			return;
		}
		if (taskModal && taskModal.classList.contains('is-open')) {
			closeModal();
		}
		if (quickTaskModal && quickTaskModal.classList.contains('is-open')) {
			closeQuickTaskModal();
		}
	});
})();
</script>
