<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<?php $template = is_array($template) ? $template : array(); ?>
<style>
.template-form {
	display: grid;
	gap: 20px;
}

.template-intro {
	display: grid;
	gap: 6px;
}

.template-intro p {
	margin: 0;
	color: var(--muted);
}

.field {
	display: grid;
	gap: 6px;
}

.field label {
	font-weight: 700;
	color: var(--ink);
}

.field input,
.field textarea {
	width: 100%;
	border: 0;
	border-radius: 14px;
	padding: 12px 14px;
	background: var(--field-bg);
	color: var(--field-ink);
	box-shadow: inset 0 0 0 1px rgba(20, 41, 64, 0.12);
	font-family: inherit;
}

.field textarea {
	min-height: 110px;
	resize: vertical;
}

.template-block {
	display: grid;
	gap: 14px;
	padding: 18px;
	border-radius: 20px;
	background: var(--card);
	box-shadow: inset 0 0 0 1px rgba(20, 41, 64, 0.06);
}

.template-block-title {
	display: grid;
	gap: 4px;
}

.template-block-title strong {
	font-size: 1rem;
	color: var(--ink);
}

.template-block-title span {
	color: var(--muted);
	font-size: 0.92rem;
}

.template-toggle {
	display: inline-flex;
	align-items: center;
	gap: 10px;
	font-weight: 700;
	color: var(--ink);
	padding: 14px 16px;
	border-radius: 18px;
	background: var(--card);
	box-shadow: inset 0 0 0 1px rgba(20, 41, 64, 0.06);
}

.template-empty {
	padding: 14px 16px;
	border-radius: 16px;
	background: rgba(255, 255, 255, 0.8);
	box-shadow: inset 0 0 0 1px rgba(20, 41, 64, 0.08);
	color: var(--muted);
	font-size: 0.92rem;
	text-align: center;
}

.template-helper {
	font-size: 0.9rem;
	color: var(--muted);
	line-height: 1.5;
}
</style>
<section class="panel">
<?php $return_route = !empty($return_route) ? (string) $return_route : 'tareas/plantillas'; ?>
<form method="post" action="" autocomplete="off" id="task-template-form" class="template-form">
	<div class="actions" style="justify-content:flex-start; margin-top:0; margin-bottom:4px;">
		<a class="btn btn-outline" href="<?php echo site_url($return_route); ?>">Regresar</a>
	</div>

		<div class="template-intro">
			<h2 style="margin:0;"><?php echo !empty($template['id']) ? 'Editar plantilla' : 'Nueva plantilla'; ?></h2>
			<p>Configura la tarea base y las subtareas que luego podras usar al crear reglas desde supervisor.</p>
		</div>

		<?php if (validation_errors()) { ?>
			<div style="padding:12px 14px; border-radius:16px; background:#fdecec; color:#8a1f1f; font-weight:700;">
				<?php echo validation_errors('', ' '); ?>
			</div>
		<?php } ?>

		<div class="template-block">
			<div class="field" style="margin-top:0;">
				<label for="name">Nombre</label>
				<input id="name" type="text" name="name" value="<?php echo htmlspecialchars(set_value('name', isset($template['name']) ? $template['name'] : ''), ENT_QUOTES, 'UTF-8'); ?>" />
			</div>

			<div class="field" style="margin-top:0;">
				<label for="description">Descripcion</label>
				<textarea id="description" name="description" placeholder="Describe brevemente esta tarea"><?php echo htmlspecialchars(set_value('description', isset($template['description']) ? $template['description'] : ''), ENT_QUOTES, 'UTF-8'); ?></textarea>
			</div>
		</div>

		<div class="template-block">
			<div class="template-block-title">
				<strong>Subtareas</strong>
				<span>Construye la checklist que luego se asignara a cada empleado o grupo.</span>
			</div>
			<div style="display:grid; gap:10px;">
				<div id="task-template-items-editor" style="display:grid; gap:10px;"></div>
				<div id="task-template-empty" class="template-empty">Todavia no has agregado subtareas.</div>
				<div class="actions" style="justify-content:flex-start; margin-top:0;">
					<button class="btn btn-outline" type="button" id="add-child-item">Agregar subtarea</button>
				</div>
				<div class="template-helper">
					El nombre de arriba es la tarea principal. Aqui solo agregas las subtareas que quieres asignar.
				</div>
			</div>
			<textarea id="items_text" name="items_text" style="display:none;"><?php echo htmlspecialchars(set_value('items_text', $items_text), ENT_QUOTES, 'UTF-8'); ?></textarea>
		</div>

		<label class="template-toggle">
			<input type="checkbox" name="is_active" value="1" <?php echo set_checkbox('is_active', '1', !isset($template['is_active']) || !empty($template['is_active'])); ?> />
			<span>Plantilla activa</span>
		</label>

		<div class="actions" style="justify-content:flex-end;">
			<button class="btn" type="submit">Guardar</button>
		</div>
	</form>
</section>
<script>
document.addEventListener('DOMContentLoaded', function () {
	var form = document.getElementById('task-template-form');
	var editor = document.getElementById('task-template-items-editor');
	var hiddenTextarea = document.getElementById('items_text');
	var addChildButton = document.getElementById('add-child-item');
	var emptyState = document.getElementById('task-template-empty');

	var syncEmptyState = function () {
		if (!emptyState || !editor) {
			return;
		}
		emptyState.style.display = editor.children.length ? 'none' : '';
	};

	var createRow = function (value) {
		var wrapper = document.createElement('div');
		wrapper.className = 'task-template-row';
		wrapper.style.display = 'grid';
		wrapper.style.gridTemplateColumns = 'auto 1fr auto';
		wrapper.style.gap = '10px';
		wrapper.style.alignItems = 'center';
		wrapper.style.padding = '12px 14px';
		wrapper.style.borderRadius = '18px';
		wrapper.style.background = 'var(--card)';

		var badge = document.createElement('span');
		badge.textContent = 'Sub';
		badge.style.fontWeight = '800';
		badge.style.color = 'var(--ink)';

		var input = document.createElement('input');
		input.type = 'text';
		input.value = value || '';
		input.placeholder = 'Nombre de la subtarea';
		input.style.width = '100%';
		input.style.border = '0';
		input.style.borderRadius = '14px';
		input.style.padding = '12px 14px';
		input.style.background = '#ffffff';
		input.style.color = 'var(--field-ink)';
		input.style.boxShadow = 'inset 0 0 0 1px rgba(20, 41, 64, 0.12)';
		input.style.fontFamily = 'inherit';

		var remove = document.createElement('button');
		remove.type = 'button';
		remove.className = 'btn btn-outline';
		remove.textContent = 'Quitar';
		remove.addEventListener('click', function () {
			wrapper.remove();
			syncEmptyState();
		});

		wrapper.appendChild(badge);
		wrapper.appendChild(input);
		wrapper.appendChild(remove);
		return wrapper;
	};

	var seedFromTextarea = function () {
		var text = hiddenTextarea ? hiddenTextarea.value.replace(/\r\n/g, '\n') : '';
		if (!text.trim()) {
			return;
		}
		text.split('\n').forEach(function (line) {
			var raw = line.trim();
			if (!raw) {
				return;
			}
			editor.appendChild(createRow(raw.replace(/^\-\s*/, '')));
		});
	};

	var serializeToTextarea = function () {
		var lines = [];
		Array.prototype.slice.call(editor.querySelectorAll('.task-template-row')).forEach(function (row) {
			var input = row.querySelector('input');
			var value = input ? input.value.trim() : '';
			if (!value) {
				return;
			}
			lines.push(value);
		});
		hiddenTextarea.value = lines.join('\n');
	};

	if (addChildButton) {
		addChildButton.addEventListener('click', function () {
			editor.appendChild(createRow(''));
			syncEmptyState();
		});
	}

	if (form) {
		form.addEventListener('submit', function () {
			serializeToTextarea();
		});
	}

	seedFromTextarea();
	syncEmptyState();
});
</script>
