<!DOCTYPE html>
<html lang="es">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<?php
		$app_name = !empty($app_config['app_name']) ? $app_config['app_name'] : 'BellaIdea';
		$app_logo = !empty($app_config['logo_path']) ? $app_config['logo_path'] : '';
	?>
	<title>Inventario | <?php echo html_escape($app_name); ?></title>
	<style>
		:root {
			--bg: #f6f7fb;
			--card: #ffffff;
			--text: #1f2937;
			--muted: #64748b;
			--line: #e2e8f0;
			--primary: #0ea5a3;
			--ok-bg: #dcfce7;
			--ok-text: #166534;
		}
		body.theme-oscuro {
			--bg: #0f172a;
			--card: #111827;
			--text: #e5e7eb;
			--muted: #9ca3af;
			--line: #334155;
			--primary: #14b8a6;
			--ok-bg: #064e3b;
			--ok-text: #bbf7d0;
		}
		body.theme-rosado {
			--bg: #fff1f6;
			--card: #ffffff;
			--text: #4a1028;
			--muted: #8a4661;
			--line: #f8bbd0;
			--primary: #ec4899;
			--ok-bg: #fce7f3;
			--ok-text: #9d174d;
		}
		body.theme-fuccia {
			--bg: #fdf2ff;
			--card: #ffffff;
			--text: #4a044e;
			--muted: #7e22ce;
			--line: #f0abfc;
			--primary: #d946ef;
			--ok-bg: #fae8ff;
			--ok-text: #86198f;
		}
		body.theme-verde {
			--bg: #f0fdf4;
			--card: #ffffff;
			--text: #14532d;
			--muted: #166534;
			--line: #86efac;
			--primary: #22c55e;
			--ok-bg: #dcfce7;
			--ok-text: #166534;
		}
		body.theme-rojo {
			--bg: #fff1f2;
			--card: #ffffff;
			--text: #7f1d1d;
			--muted: #b91c1c;
			--line: #fca5a5;
			--primary: #ef4444;
			--ok-bg: #fee2e2;
			--ok-text: #991b1b;
		}
		body.theme-azul_claro {
			--bg: #eff6ff;
			--card: #ffffff;
			--text: #1e3a8a;
			--muted: #1d4ed8;
			--line: #93c5fd;
			--primary: #38bdf8;
			--ok-bg: #dbeafe;
			--ok-text: #1e40af;
		}
		body.theme-azul_rey {
			--bg: #eef2ff;
			--card: #ffffff;
			--text: #1e1b4b;
			--muted: #312e81;
			--line: #a5b4fc;
			--primary: #4f46e5;
			--ok-bg: #e0e7ff;
			--ok-text: #3730a3;
		}
		* { box-sizing: border-box; }
		body {
			margin: 0;
			font-family: "Segoe UI", Tahoma, Arial, sans-serif;
			background: var(--bg);
			color: var(--text);
		}
		.appbar {
			background: var(--card);
			border-bottom: 1px solid var(--line);
			padding: 10px 12px;
			position: sticky;
			top: 0;
			z-index: 20;
		}
		.appbar-inner {
			max-width: 540px;
			margin: 0 auto;
			display: flex;
			align-items: center;
			justify-content: space-between;
		}
		.company-wrap {
			display: grid;
			grid-template-columns: 52px minmax(0, 1fr);
			column-gap: 10px;
			row-gap: 2px;
			align-items: center;
		}
		.company-wrap.no-logo {
			grid-template-columns: minmax(0, 1fr);
		}
		.brand {
			display: contents;
		}
		.company-logo {
			width: 52px;
			height: 52px;
			border-radius: 8px;
			object-fit: cover;
			border: 1px solid var(--line);
			background: var(--card);
			grid-column: 1;
			grid-row: 1 / span 2;
		}
		.company-name {
			font-size: 18px;
			font-weight: 800;
			color: var(--text);
			grid-column: 2;
			grid-row: 1;
			line-height: 1.15;
			word-break: break-word;
		}
		.appbar-user {
			font-size: 12px;
			color: var(--muted);
			grid-column: 2;
			grid-row: 2;
		}
		.company-wrap.no-logo .company-name,
		.company-wrap.no-logo .appbar-user {
			grid-column: 1;
		}
		.container {
			max-width: 540px;
			margin: 0 auto;
			padding: 12px 12px 24px;
		}
		.top {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin: 6px 0 12px;
		}
		.title-wrap h1 {
			margin: 0;
			font-size: 22px;
		}
		.user {
			font-size: 12px;
			color: var(--muted);
			margin-top: 3px;
		}
		.menu-btn {
			width: 42px;
			height: 42px;
			border: 1px solid var(--line);
			border-radius: 10px;
			background: var(--card);
			padding: 9px 8px;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
		}
		.menu-btn span {
			display: block;
			height: 3px;
			border-radius: 5px;
			background: var(--text);
		}
		.card {
			background: var(--card);
			border-radius: 14px;
			padding: 12px;
			border: 1px solid var(--line);
			margin-bottom: 12px;
		}
		.subtabs {
			display: grid;
			grid-template-columns: 1fr 1fr 1fr;
			gap: 8px;
			margin-bottom: 12px;
		}
		.subtab-link {
			display: block;
			text-align: center;
			text-decoration: none;
			font-weight: 700;
			font-size: 14px;
			padding: 10px;
			border: 1px solid var(--line);
			border-radius: 10px;
			color: var(--text);
			background: var(--card);
		}
		.subtab-link.active {
			background: var(--primary);
			color: #fff;
			border-color: var(--primary);
		}
		h2 {
			margin: 0 0 10px;
			font-size: 16px;
		}
		label {
			font-size: 13px;
			font-weight: 600;
			margin: 8px 0 4px;
			display: block;
		}
		input {
			width: 100%;
			border: 1px solid var(--line);
			background: var(--card);
			color: var(--text);
			border-radius: 10px;
			padding: 10px;
			font-size: 15px;
		}
		select {
			width: 100%;
			border: 1px solid var(--line);
			background: var(--card);
			color: var(--text);
			border-radius: 10px;
			padding: 10px;
			font-size: 15px;
		}
		textarea {
			width: 100%;
			border: 1px solid var(--line);
			background: var(--card);
			color: var(--text);
			border-radius: 10px;
			padding: 10px;
			font-size: 15px;
			min-height: 88px;
			resize: vertical;
		}
		button {
			margin-top: 12px;
			width: 100%;
			border: 0;
			border-radius: 10px;
			background: var(--primary);
			color: #fff;
			padding: 11px;
			font-size: 15px;
			font-weight: 700;
		}
		.action-btn {
			display: inline-block;
			width: 100%;
			text-align: center;
			text-decoration: none;
			border: 0;
			border-radius: 10px;
			background: var(--primary);
			color: #fff;
			padding: 11px;
			font-size: 15px;
			font-weight: 700;
			margin-top: 4px;
		}
		.item-card {
			border: 1px solid var(--line);
			border-radius: 12px;
			background: var(--card);
			margin-bottom: 8px;
			overflow: hidden;
		}
		.material-group {
			margin-bottom: 10px;
		}
		.material-children {
			margin-left: 16px;
			padding-left: 10px;
			border-left: 2px dashed var(--line);
		}
		.material-group > .material-children {
			display: none;
		}
		.material-group > .parent-material-card[open] + .material-children {
			display: block;
		}
		.child-tag {
			font-size: 11px;
			color: var(--muted);
			font-weight: 700;
			text-transform: uppercase;
			margin-bottom: 3px;
		}
		.item-card summary {
			list-style: none;
			cursor: pointer;
			padding: 11px 12px;
			display: flex;
			align-items: center;
			justify-content: space-between;
			gap: 8px;
		}
		.item-card summary::-webkit-details-marker {
			display: none;
		}
		.item-title {
			font-size: 15px;
			font-weight: 700;
			color: var(--text);
		}
		.item-mini {
			font-size: 12px;
			color: var(--muted);
			margin-top: 2px;
		}
		.item-right {
			display: flex;
			align-items: center;
			gap: 8px;
			flex-shrink: 0;
		}
		.badge {
			border-radius: 999px;
			background: var(--bg);
			color: var(--text);
			font-size: 12px;
			font-weight: 700;
			padding: 4px 8px;
		}
		.chev {
			font-size: 12px;
			color: var(--muted);
			transition: transform 0.2s ease;
		}
		.item-card[open] .chev {
			transform: rotate(180deg);
		}
		.item-details {
			border-top: 1px solid var(--line);
			padding: 10px 12px;
		}
		.item-details.compact {
			padding-top: 6px;
			padding-bottom: 8px;
		}
		.category-card {
			border: 1px solid var(--line);
			border-radius: 10px;
			padding: 10px;
			margin-bottom: 8px;
		}
		.category-title {
			font-size: 15px;
			font-weight: 700;
		}
		.check-list {
			margin-top: 8px;
			border: 1px solid var(--line);
			border-radius: 10px;
			padding: 4px;
			max-height: 160px;
			overflow-y: auto;
		}
		.template-search {
			margin-top: 6px;
		}
		.template-search-wrap {
			position: relative;
		}
		.template-search-wrap input {
			padding-right: 34px;
		}
		.template-search-clear {
			position: absolute;
			right: 8px;
			top: 50%;
			transform: translateY(-50%);
			width: 22px;
			height: 22px;
			border-radius: 999px;
			border: 1px solid var(--line);
			background: var(--card);
			color: var(--muted);
			font-size: 13px;
			font-weight: 700;
			line-height: 1;
			padding: 0;
			margin: 0;
			display: none;
			cursor: pointer;
		}
		.template-search-clear.show {
			display: inline-flex;
			align-items: center;
			justify-content: center;
		}
		.template-search-info {
			font-size: 12px;
			color: var(--muted);
			padding: 6px 2px 0;
		}
		.template-empty {
			display: none;
			font-size: 12px;
			color: var(--muted);
			padding: 6px 4px 2px;
		}
		.check-item {
			display: flex;
			align-items: center;
			gap: 8px;
			padding: 2px 4px;
			min-height: 24px;
		}
		.template-group {
			padding: 2px 0 4px;
			border-bottom: 1px dashed var(--line);
		}
		.template-group:last-child {
			border-bottom: 0;
		}
		.template-parent-label {
			font-size: 11px;
			font-weight: 700;
			color: var(--muted);
			padding: 1px 4px 2px;
			text-transform: uppercase;
		}
		.check-item.child-item {
			padding-left: 12px;
		}
		.check-item input {
			width: auto;
			padding: 0;
		}
		.check-item span {
			display: block;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			font-size: 15px;
		}
		.templates-disabled {
			opacity: 0.55;
		}
		.material-detail-fields.hidden {
			display: none;
		}
		.meta {
			font-size: 13px;
			color: var(--muted);
			margin-top: 3px;
		}
		.detail-actions {
			margin-top: 10px;
			display: flex;
			justify-content: flex-end;
			gap: 8px;
			flex-wrap: wrap;
		}
		.item-details.compact .detail-actions {
			margin-top: 0;
		}
		.btn-outline {
			border: 1px solid var(--line);
			background: var(--card);
			color: var(--text);
			border-radius: 8px;
			padding: 7px 12px;
			font-size: 13px;
			font-weight: 700;
			cursor: pointer;
			width: auto;
			margin-top: 0;
		}
		.btn-primary-inline {
			width: auto;
			margin-top: 0;
			padding: 7px 12px;
			font-size: 13px;
			border-radius: 8px;
		}
		.thumb-grid {
			display: flex;
			flex-wrap: wrap;
			gap: 8px;
			margin-top: 8px;
		}
		.thumb-link {
			display: block;
			width: 64px;
			height: 64px;
			border: 1px solid var(--line);
			border-radius: 8px;
			overflow: hidden;
			background: var(--card);
		}
		.thumb-link img {
			width: 100%;
			height: 100%;
			object-fit: cover;
			display: block;
		}
		.history-title {
			margin: 0;
			font-size: 18px;
		}
		.history-note {
			margin: 8px 0 10px;
			font-size: 12px;
			color: var(--muted);
		}
		.history-list {
			border: 1px solid var(--line);
			border-radius: 10px;
			max-height: 52vh;
			overflow-y: auto;
			background: var(--card);
		}
		.history-item {
			padding: 10px;
			border-bottom: 1px solid var(--line);
		}
		.history-item:last-child {
			border-bottom: 0;
		}
		.history-item-top {
			display: flex;
			align-items: center;
			justify-content: space-between;
			gap: 8px;
		}
		.history-item-title {
			font-size: 14px;
			font-weight: 700;
		}
		.history-item-amount {
			font-size: 13px;
			font-weight: 700;
			color: var(--text);
		}
		.history-item-meta {
			margin-top: 4px;
			font-size: 12px;
			color: var(--muted);
		}
		.empty {
			font-size: 14px;
			color: var(--muted);
		}
		.ok {
			background: var(--ok-bg);
			color: var(--ok-text);
			border-radius: 10px;
			padding: 10px;
			font-size: 13px;
			margin-bottom: 10px;
		}
		.drawer-backdrop {
			position: fixed;
			inset: 0;
			background: rgba(15, 23, 42, 0.4);
			opacity: 0;
			pointer-events: none;
			transition: opacity 0.2s ease;
			z-index: 29;
		}
		.drawer {
			position: fixed;
			top: 0;
			right: 0;
			width: min(86vw, 330px);
			height: 100vh;
			height: 100dvh;
			min-height: 100dvh;
			background: var(--card);
			border-left: 1px solid var(--line);
			transform: translateX(100%);
			transition: transform 0.25s ease;
			z-index: 30;
			padding: 16px 14px calc(72px + env(safe-area-inset-bottom));
			display: flex;
			flex-direction: column;
			overflow-y: auto;
		}
		.drawer.open { transform: translateX(0); }
		.drawer-backdrop.open {
			opacity: 1;
			pointer-events: auto;
		}
		.drawer-head {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 10px;
		}
		.drawer-title {
			margin: 0;
			font-size: 18px;
		}
		.close-btn {
			border: 1px solid var(--line);
			background: var(--card);
			color: var(--text);
			border-radius: 8px;
			width: 34px;
			height: 34px;
			font-size: 18px;
			line-height: 1;
		}
		.module-link {
			display: block;
			text-decoration: none;
			font-weight: 700;
			color: var(--text);
			padding: 11px 12px;
			border-radius: 10px;
			border: 1px solid var(--line);
			margin-bottom: 8px;
		}
		.module-link.active {
			background: var(--primary);
			color: #fff;
			border-color: var(--primary);
		}
		.drawer-bottom { margin-top: auto; }
		.logout-link {
			display: block;
			margin-top: 8px;
			text-decoration: none;
			text-align: center;
			font-weight: 700;
			color: var(--text);
			padding: 10px 12px;
			border: 1px solid var(--line);
			border-radius: 10px;
		}
		.modal-backdrop {
			position: fixed;
			inset: 0;
			background: rgba(15, 23, 42, 0.45);
			opacity: 0;
			pointer-events: none;
			transition: opacity 0.2s ease;
			z-index: 39;
		}
		.modal {
			position: fixed;
			left: 50%;
			top: 50%;
			width: min(92vw, 480px);
			max-height: 88vh;
			overflow-y: auto;
			background: var(--card);
			border: 1px solid var(--line);
			border-radius: 14px;
			padding: 14px;
			transform: translate(-50%, -45%);
			opacity: 0;
			pointer-events: none;
			transition: all 0.2s ease;
			z-index: 40;
		}
		.modal.open {
			transform: translate(-50%, -50%);
			opacity: 1;
			pointer-events: auto;
		}
		.modal-backdrop.open {
			opacity: 1;
			pointer-events: auto;
		}
		.modal-head {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 8px;
		}
		.modal-head h3 {
			margin: 0;
			font-size: 18px;
		}
		.error {
			background: #fee2e2;
			color: #991b1b;
		}
	</style>
</head>
<?php
	$theme_current = $this->session->userdata('theme') ? $this->session->userdata('theme') : 'claro';
	$theme_custom_vars = $this->session->userdata('theme_custom_vars');
	$is_custom_theme = (strpos((string) $theme_current, 'custom_') === 0) && is_array($theme_custom_vars);
	$theme_render = $theme_current;
	if (!$is_custom_theme && strpos((string) $theme_current, 'custom_') === 0) {
		$theme_render = 'claro';
	}
	$body_class = $is_custom_theme ? 'theme-custom' : 'theme-'.html_escape($theme_render);
	$theme_presets = array(
		'claro' => array('bg'=>'#f6f7fb','card'=>'#ffffff','text'=>'#1f2937','muted'=>'#64748b','line'=>'#e2e8f0','primary'=>'#0ea5a3','ok_bg'=>'#dcfce7','ok_text'=>'#166534'),
		'oscuro' => array('bg'=>'#0f172a','card'=>'#111827','text'=>'#e5e7eb','muted'=>'#9ca3af','line'=>'#334155','primary'=>'#14b8a6','ok_bg'=>'#064e3b','ok_text'=>'#bbf7d0'),
		'rosado' => array('bg'=>'#fff1f6','card'=>'#ffffff','text'=>'#4a1028','muted'=>'#8a4661','line'=>'#f8bbd0','primary'=>'#ec4899','ok_bg'=>'#fce7f3','ok_text'=>'#9d174d'),
		'fuccia' => array('bg'=>'#fdf2ff','card'=>'#ffffff','text'=>'#4a044e','muted'=>'#7e22ce','line'=>'#f0abfc','primary'=>'#d946ef','ok_bg'=>'#fae8ff','ok_text'=>'#86198f'),
		'verde' => array('bg'=>'#f0fdf4','card'=>'#ffffff','text'=>'#14532d','muted'=>'#166534','line'=>'#86efac','primary'=>'#22c55e','ok_bg'=>'#dcfce7','ok_text'=>'#166534'),
		'rojo' => array('bg'=>'#fff1f2','card'=>'#ffffff','text'=>'#7f1d1d','muted'=>'#b91c1c','line'=>'#fca5a5','primary'=>'#ef4444','ok_bg'=>'#fee2e2','ok_text'=>'#991b1b'),
		'azul_claro' => array('bg'=>'#eff6ff','card'=>'#ffffff','text'=>'#1e3a8a','muted'=>'#1d4ed8','line'=>'#93c5fd','primary'=>'#38bdf8','ok_bg'=>'#dbeafe','ok_text'=>'#1e40af'),
		'azul_rey' => array('bg'=>'#eef2ff','card'=>'#ffffff','text'=>'#1e1b4b','muted'=>'#312e81','line'=>'#a5b4fc','primary'=>'#4f46e5','ok_bg'=>'#e0e7ff','ok_text'=>'#3730a3')
	);
	$vars = $is_custom_theme ? $theme_custom_vars : (isset($theme_presets[$theme_render]) ? $theme_presets[$theme_render] : $theme_presets['claro']);
	$inline_style = '--bg:'.$vars['bg'].';--card:'.$vars['card'].';--text:'.$vars['text'].';--muted:'.$vars['muted'].';--line:'.$vars['line'].';--primary:'.$vars['primary'].';--ok-bg:'.$vars['ok_bg'].';--ok-text:'.$vars['ok_text'].';';
?>
<body class="<?php echo $body_class; ?>" style="<?php echo html_escape($inline_style); ?>">
	<header class="appbar">
		<div class="appbar-inner">
			<div class="company-wrap <?php echo empty($app_logo) ? 'no-logo' : ''; ?>">
				<div class="brand">
					<?php if (!empty($app_logo)): ?>
						<img class="company-logo" src="<?php echo base_url($app_logo); ?>" alt="Logo">
					<?php endif; ?>
					<div class="company-name"><?php echo html_escape($app_name); ?></div>
				</div>
				<div class="appbar-user">Hola, <?php echo html_escape($this->session->userdata('username')); ?></div>
			</div>
			<button id="openMenu" class="menu-btn" type="button" aria-label="Abrir modulos">
				<span></span>
				<span></span>
				<span></span>
			</button>
		</div>
	</header>

	<div class="container">
		<div class="top">
			<div class="title-wrap">
				<h1>Inventario</h1>
			</div>
		</div>

		<div class="card">
			<div class="subtabs">
				<a class="subtab-link <?php echo ($tab === 'materiales') ? 'active' : ''; ?>" href="<?php echo site_url('inventario/materiales'); ?>">Materiales</a>
				<a class="subtab-link <?php echo ($tab === 'productos') ? 'active' : ''; ?>" href="<?php echo site_url('inventario/productos'); ?>">Productos</a>
				<a class="subtab-link <?php echo ($tab === 'categorias') ? 'active' : ''; ?>" href="<?php echo site_url('inventario/categorias'); ?>">Templates</a>
			</div>

			<?php $error_msg = $this->session->flashdata('error'); ?>
			<?php if ($this->session->flashdata('ok')): ?>
				<div class="ok"><?php echo $this->session->flashdata('ok'); ?></div>
			<?php endif; ?>
			<?php if (!empty($error_msg)): ?>
				<div class="ok error"><?php echo $error_msg; ?></div>
			<?php endif; ?>
			<?php if ($tab === 'materiales'): ?>
				<a href="#" id="openMaterialModal" class="action-btn">Agregar material</a>
			<?php elseif ($tab === 'productos'): ?>
				<div class="meta">Aqui se muestran los productos creados desde Pedidos.</div>
			<?php else: ?>
				<a href="#" id="openCategoryModal" class="action-btn">Agregar template</a>
			<?php endif; ?>
		</div>

		<div class="card">
			<?php if ($tab === 'categorias'): ?>
				<h2>Listado de templates</h2>
				<?php if (empty($template_groups)): ?>
					<div class="empty">Aun no hay templates registrados.</div>
				<?php else: ?>
					<?php foreach ($template_groups as $group): ?>
						<?php $tpl = $group['parent']; ?>
						<div class="material-group">
							<details class="item-card parent-material-card">
								<summary>
									<div>
										<div class="item-title"><?php echo html_escape($tpl->nombre); ?></div>
									</div>
									<div class="item-right">
										<span class="badge">Hijos: <?php echo count($group['children']); ?></span>
										<span class="chev">&#9662;</span>
									</div>
								</summary>
							</details>

							<?php if (!empty($group['children'])): ?>
								<div class="material-children">
									<?php foreach ($group['children'] as $child): ?>
										<details class="item-card">
											<summary>
												<div>
													<div class="child-tag">Hijo</div>
													<div class="item-title"><?php echo html_escape($child->nombre); ?></div>
												</div>
												<div class="item-right">
													<span class="chev">&#9662;</span>
												</div>
											</summary>
											<div class="item-details compact">
												<div class="meta">Materiales: <?php echo !empty($child->materiales_template) ? html_escape($child->materiales_template) : 'Sin materiales'; ?></div>
											</div>
										</details>
									<?php endforeach; ?>
								</div>
							<?php endif; ?>
						</div>
					<?php endforeach; ?>
				<?php endif; ?>
			<?php else: ?>
				<h2>Listado de <?php echo ($tab === 'materiales') ? 'materiales' : 'productos'; ?></h2>
				<?php if ($tab === 'materiales'): ?>
					<?php if (empty($material_groups)): ?>
						<div class="empty">Aun no hay materiales registrados.</div>
					<?php else: ?>
						<?php foreach ($material_groups as $group): ?>
							<?php $item = $group['parent']; ?>
							<?php
								$children_stock_sum = 0;
								if (!empty($group['children'])) {
									foreach ($group['children'] as $child_sum) {
										$children_stock_sum += (int) $child_sum->stock_actual;
									}
								}
							?>
							<div class="material-group">
								<details class="item-card parent-material-card">
									<summary>
										<div>
											<div class="item-title"><?php echo html_escape($item->nombre); ?></div>
											<?php if (!empty($item->parent_id)): ?>
												<div class="item-mini">Costo: <?php echo number_format((float) $item->costo, 2, '.', ','); ?></div>
											<?php else: ?>
												<div class="item-mini">Material padre</div>
											<?php endif; ?>
										</div>
										<div class="item-right">
											<?php if (!empty($item->parent_id)): ?>
												<span class="badge">Stock: <?php echo (int) $item->stock_actual; ?> <?php echo html_escape($item->unidad); ?></span>
											<?php else: ?>
												<span class="badge">Stock: <?php echo (int) $children_stock_sum; ?></span>
											<?php endif; ?>
											<span class="chev">&#9662;</span>
										</div>
									</summary>
									<div class="item-details<?php echo empty($item->parent_id) ? ' compact' : ''; ?>">
										<?php if (!empty($item->parent_id)): ?>
											<div class="meta">Unidad: <?php echo html_escape($item->unidad); ?></div>
											<div class="meta">Stock actual: <?php echo (int) $item->stock_actual; ?></div>
											<div class="meta">Stock minimo: <?php echo (int) $item->stock_minimo; ?></div>
											<div class="meta">Provedor: <?php echo html_escape($item->proveedor); ?></div>
											<?php if (!empty($item->nota)): ?>
												<div class="meta">Nota: <?php echo html_escape($item->nota); ?></div>
											<?php endif; ?>
										<?php endif; ?>
										<div class="detail-actions">
											<button type="button"
												class="btn-outline history-material-btn"
												data-id="<?php echo (int) $item->id; ?>"
												data-nombre="<?php echo html_escape($item->nombre); ?>">Historial</button>
											<button type="button"
												class="btn-outline edit-material-btn"
												data-id="<?php echo (int) $item->id; ?>"
												data-nombre="<?php echo html_escape($item->nombre); ?>"
												data-parent_id="<?php echo (int) $item->parent_id; ?>"
												data-unidad="<?php echo html_escape($item->unidad); ?>"
												data-stock_minimo="<?php echo (int) $item->stock_minimo; ?>"
												data-costo="<?php echo number_format((float) $item->costo, 2, '.', ''); ?>"
												data-proveedor="<?php echo html_escape($item->proveedor); ?>"
												data-nota="<?php echo html_escape($item->nota); ?>">Editar</button>
										</div>
									</div>
								</details>

								<?php if (!empty($group['children'])): ?>
									<div class="material-children">
										<?php foreach ($group['children'] as $child): ?>
											<details class="item-card">
												<summary>
													<div>
														<div class="child-tag">Hijo</div>
														<div class="item-title"><?php echo html_escape($child->nombre); ?></div>
														<div class="item-mini">Costo: <?php echo number_format((float) $child->costo, 2, '.', ','); ?></div>
													</div>
													<div class="item-right">
														<span class="badge">Stock: <?php echo (int) $child->stock_actual; ?> <?php echo html_escape($child->unidad); ?></span>
														<span class="chev">&#9662;</span>
													</div>
												</summary>
												<div class="item-details">
													<div class="meta">Unidad: <?php echo html_escape($child->unidad); ?></div>
													<div class="meta">Stock actual: <?php echo (int) $child->stock_actual; ?></div>
													<div class="meta">Stock minimo: <?php echo (int) $child->stock_minimo; ?></div>
													<div class="meta">Provedor: <?php echo html_escape($child->proveedor); ?></div>
													<?php if (!empty($child->nota)): ?>
														<div class="meta">Nota: <?php echo html_escape($child->nota); ?></div>
													<?php endif; ?>
													<div class="detail-actions">
														<button type="button"
															class="btn-outline history-material-btn"
															data-id="<?php echo (int) $child->id; ?>"
															data-nombre="<?php echo html_escape($child->nombre); ?>">Historial</button>
														<button type="button"
															class="btn-outline edit-material-btn"
															data-id="<?php echo (int) $child->id; ?>"
															data-nombre="<?php echo html_escape($child->nombre); ?>"
															data-parent_id="<?php echo (int) $child->parent_id; ?>"
															data-unidad="<?php echo html_escape($child->unidad); ?>"
															data-stock_minimo="<?php echo (int) $child->stock_minimo; ?>"
															data-costo="<?php echo number_format((float) $child->costo, 2, '.', ''); ?>"
															data-proveedor="<?php echo html_escape($child->proveedor); ?>"
															data-nota="<?php echo html_escape($child->nota); ?>">Editar</button>
													</div>
												</div>
											</details>
										<?php endforeach; ?>
									</div>
								<?php endif; ?>
							</div>
						<?php endforeach; ?>
					<?php endif; ?>
				<?php else: ?>
					<?php if (empty($items)): ?>
						<div class="empty">Aun no hay productos registrados.</div>
					<?php else: ?>
						<?php foreach ($items as $item): ?>
							<details class="item-card">
								<summary>
									<div>
										<div class="item-title"><?php echo html_escape($item->nombre); ?></div>
										<div class="item-mini">Cantidad: <?php echo (int) $item->cantidad; ?></div>
									</div>
									<div class="item-right">
										<span class="badge">Precio: <?php echo number_format((float) $item->precio, 2, '.', ','); ?></span>
										<span class="chev">&#9662;</span>
									</div>
								</summary>
								<div class="item-details">
									<div class="meta">Cantidad: <?php echo (int) $item->cantidad; ?></div>
									<div class="meta">Precio: <?php echo number_format((float) $item->precio, 2, '.', ','); ?></div>
									<div class="detail-actions">
										<button type="button"
											class="btn-outline sell-product-btn"
											data-id="<?php echo (int) $item->id; ?>"
											data-nombre="<?php echo html_escape($item->nombre); ?>"
											data-precio="<?php echo number_format((float) $item->precio, 2, '.', ''); ?>">Vender</button>
									</div>
									<?php if (isset($item->pedido_id) && !empty($item->pedido_id)): ?>
										<div class="meta">Origen: Pedido #<?php echo (int) $item->pedido_id; ?></div>
										<?php
											$pid = (int) $item->pedido_id;
											$fotos_producto = isset($fotos_por_pedido[$pid]) ? $fotos_por_pedido[$pid] : array();
										?>
										<?php if (!empty($fotos_producto)): ?>
											<div class="thumb-grid">
												<?php foreach ($fotos_producto as $fp): ?>
													<a class="thumb-link" href="<?php echo base_url($fp); ?>" target="_blank" rel="noopener">
														<img src="<?php echo base_url($fp); ?>" alt="Foto del producto">
													</a>
												<?php endforeach; ?>
											</div>
										<?php endif; ?>
									<?php endif; ?>
								</div>
							</details>
						<?php endforeach; ?>
					<?php endif; ?>
				<?php endif; ?>
			<?php endif; ?>
		</div>
	</div>

	<?php if ($tab === 'productos'): ?>
		<div id="sellProductBackdrop" class="modal-backdrop"></div>
		<div id="sellProductModal" class="modal">
			<div class="modal-head">
				<h3>Vender producto</h3>
				<button id="closeSellProductModal" class="close-btn" type="button" aria-label="Cerrar modal">x</button>
			</div>
			<?php echo form_open('inventario/vender-producto', array('id' => 'sellProductForm')); ?>
				<input type="hidden" id="sell_producto_id" name="producto_id">

				<label for="sell_producto_nombre">Producto</label>
				<input id="sell_producto_nombre" type="text" readonly>

				<label for="sell_precio_venta">Precio de venta</label>
				<input id="sell_precio_venta" name="precio_venta" type="number" min="0" step="0.01" required>

				<div class="detail-actions" style="margin-top:12px;">
					<button type="button" id="cancelSellProductBtn" class="btn-outline">Cancelar</button>
					<button type="submit" class="btn-primary-inline">Confirmar</button>
				</div>
			<?php echo form_close(); ?>
		</div>
	<?php endif; ?>

	<?php if ($tab === 'materiales'): ?>
		<div id="materialBackdrop" class="modal-backdrop"></div>
		<div id="materialModal" class="modal">
			<div class="modal-head">
				<h3>Agregar material</h3>
				<button id="closeMaterialModal" class="close-btn" type="button" aria-label="Cerrar modal">x</button>
			</div>
			<?php echo form_open($accion_guardar); ?>
				<label for="m_nombre">Nombre</label>
				<input id="m_nombre" name="nombre" type="text" required>

				<label for="m_parent_id">Material padre</label>
				<select id="m_parent_id" name="parent_id">
					<option value="0">Sin material padre</option>
					<?php if (!empty($materiales_padre)): ?>
						<?php foreach ($materiales_padre as $pm): ?>
							<option value="<?php echo (int) $pm->id; ?>"><?php echo html_escape($pm->nombre); ?></option>
						<?php endforeach; ?>
					<?php endif; ?>
				</select>

				<div id="m_detail_fields" class="material-detail-fields">
					<label for="m_unidad">Unidad</label>
					<input id="m_unidad" name="unidad" type="text" placeholder="Ej. ml, gr, unidad">

					<label for="m_stock_minimo">Stock minimo</label>
					<input id="m_stock_minimo" name="stock_minimo" type="number" min="0">

					<label for="m_costo">Costo</label>
					<input id="m_costo" name="costo" type="number" min="0" step="0.01">

					<label for="m_proveedor">Provedor</label>
					<input id="m_proveedor" name="proveedor" type="text">

					<label for="m_nota">Nota</label>
					<textarea id="m_nota" name="nota" placeholder="Detalle opcional"></textarea>
				</div>

				<button type="submit">Guardar material</button>
			<?php echo form_close(); ?>
		</div>

		<div id="editMaterialBackdrop" class="modal-backdrop"></div>
		<div id="editMaterialModal" class="modal">
			<div class="modal-head">
				<h3>Editar material</h3>
				<button id="closeEditMaterialModal" class="close-btn" type="button" aria-label="Cerrar modal">x</button>
			</div>
			<?php echo form_open('inventario/editar-material', array('id' => 'editMaterialForm')); ?>
				<input type="hidden" id="e_material_id" name="material_id">

				<label for="e_nombre">Nombre</label>
				<input id="e_nombre" name="nombre" type="text" required>

				<label for="e_parent_id">Material padre</label>
				<select id="e_parent_id" name="parent_id">
					<option value="0">Sin material padre</option>
					<?php if (!empty($materiales_padre)): ?>
						<?php foreach ($materiales_padre as $pm): ?>
							<option value="<?php echo (int) $pm->id; ?>"><?php echo html_escape($pm->nombre); ?></option>
						<?php endforeach; ?>
					<?php endif; ?>
				</select>

				<div id="e_detail_fields" class="material-detail-fields">
					<label for="e_unidad">Unidad</label>
					<input id="e_unidad" name="unidad" type="text">

					<label for="e_stock_minimo">Stock minimo</label>
					<input id="e_stock_minimo" name="stock_minimo" type="number" min="0">

					<label for="e_costo">Costo</label>
					<input id="e_costo" name="costo" type="number" min="0" step="0.01">

					<label for="e_proveedor">Provedor</label>
					<input id="e_proveedor" name="proveedor" type="text">

					<label for="e_nota">Nota</label>
					<textarea id="e_nota" name="nota" placeholder="Detalle opcional"></textarea>
				</div>

				<button type="submit">Guardar cambios</button>
			<?php echo form_close(); ?>
		</div>

		<div id="historyBackdrop" class="modal-backdrop"></div>
		<div id="historyModal" class="modal">
			<div class="modal-head">
				<h3 id="historyTitle" class="history-title">Historial de stock</h3>
				<button id="closeHistoryModal" class="close-btn" type="button" aria-label="Cerrar modal">x</button>
			</div>
			<div id="historyNote" class="history-note"></div>
			<div id="historyList" class="history-list">
				<div class="history-item">
					<div class="history-item-meta">Selecciona un material para ver movimientos.</div>
				</div>
			</div>
		</div>
	<?php endif; ?>

	<?php if ($tab === 'categorias'): ?>
		<div id="categoryBackdrop" class="modal-backdrop"></div>
		<div id="categoryModal" class="modal">
			<div class="modal-head">
				<h3>Agregar template</h3>
				<button id="closeCategoryModal" class="close-btn" type="button" aria-label="Cerrar modal">x</button>
			</div>
			<?php echo form_open('inventario/guardar-categoria'); ?>
				<label for="c_nombre">Nombre del template</label>
				<input id="c_nombre" name="nombre" type="text" required>

				<label for="c_parent">Template padre</label>
				<select id="c_parent" name="parent_id">
					<option value="0">Sin template padre (template padre)</option>
					<?php if (!empty($categorias)): ?>
						<?php foreach ($categorias as $cat): ?>
							<option value="<?php echo (int) $cat->id; ?>"><?php echo html_escape($cat->nombre); ?></option>
						<?php endforeach; ?>
					<?php endif; ?>
				</select>

				<label>Materiales predeterminados (solo cuando tenga template padre)</label>
				<div class="template-search-wrap">
					<input id="templateMaterialSearch" class="template-search" type="text" placeholder="Buscar material...">
					<button id="templateSearchClear" type="button" class="template-search-clear" aria-label="Limpiar busqueda">x</button>
				</div>
				<div id="templateSearchInfo" class="template-search-info"></div>
				<div id="templateMaterialsWrap" class="check-list">
					<?php if (empty($materiales_disponibles)): ?>
						<div class="empty">No hay materiales disponibles.</div>
					<?php else: ?>
						<?php
							$tpl_parents = array();
							$tpl_children_by_parent = array();
							$tpl_orphans = array();
							foreach ($materiales_disponibles as $mat) {
								if (!empty($mat->parent_id)) {
									$pid = (int) $mat->parent_id;
									if (!isset($tpl_children_by_parent[$pid])) {
										$tpl_children_by_parent[$pid] = array();
									}
									$tpl_children_by_parent[$pid][] = $mat;
								} else {
									$tpl_parents[(int) $mat->id] = $mat;
								}
							}
							foreach ($tpl_children_by_parent as $pid => $list) {
								if (!isset($tpl_parents[$pid])) {
									foreach ($list as $o) {
										$tpl_orphans[] = $o;
									}
								}
							}
						?>
						<?php foreach ($tpl_parents as $p): ?>
							<div class="template-group" data-template-group>
								<div class="template-parent-label"><?php echo html_escape($p->nombre); ?></div>
								<?php if (!empty($tpl_children_by_parent[(int) $p->id])): ?>
									<?php foreach ($tpl_children_by_parent[(int) $p->id] as $child): ?>
										<label class="check-item child-item" data-search="<?php echo html_escape($child->nombre.' '.$child->unidad.' '.$child->proveedor.' '.$p->nombre); ?>">
											<input type="checkbox" class="tpl-material" name="material_ids[]" value="<?php echo (int) $child->id; ?>">
											<span><?php echo html_escape($child->nombre); ?> (<?php echo html_escape($child->unidad); ?>)</span>
										</label>
									<?php endforeach; ?>
								<?php else: ?>
									<div class="meta">Sin materiales hijos.</div>
								<?php endif; ?>
							</div>
						<?php endforeach; ?>
						<?php if (!empty($tpl_orphans)): ?>
							<div class="template-group" data-template-group>
								<div class="template-parent-label">Sin grupo</div>
								<?php foreach ($tpl_orphans as $orphan): ?>
									<label class="check-item child-item" data-search="<?php echo html_escape($orphan->nombre.' '.$orphan->unidad.' '.$orphan->proveedor); ?>">
										<input type="checkbox" class="tpl-material" name="material_ids[]" value="<?php echo (int) $orphan->id; ?>">
										<span><?php echo html_escape($orphan->nombre); ?> (<?php echo html_escape($orphan->unidad); ?>)</span>
									</label>
								<?php endforeach; ?>
							</div>
						<?php endif; ?>
					<?php endif; ?>
				</div>
				<div id="templateMaterialEmpty" class="template-empty">No hay materiales que coincidan con la busqueda.</div>

				<button type="submit">Guardar template</button>
			<?php echo form_close(); ?>
		</div>
	<?php endif; ?>

	<div id="drawerBackdrop" class="drawer-backdrop"></div>
	<aside id="drawer" class="drawer">
		<div class="drawer-head">
			<h3 class="drawer-title">Modulos</h3>
			<button id="closeMenu" class="close-btn" type="button" aria-label="Cerrar menu">x</button>
		</div>
		<a class="module-link" href="<?php echo site_url('dashboard'); ?>">Dashboard</a>
		<a class="module-link" href="<?php echo site_url('clientes'); ?>">Clientes</a>
		<a class="module-link active" href="<?php echo site_url('inventario'); ?>">Inventario</a>
		<a class="module-link" href="<?php echo site_url('compras'); ?>">Compras</a>
		<a class="module-link" href="<?php echo site_url('pedidos'); ?>">Pedidos</a>
		<a class="module-link" href="<?php echo site_url('reportes'); ?>">Reportes</a>
		<div class="drawer-bottom">
			<a class="module-link" href="<?php echo site_url('configuracion'); ?>">Configuracion</a>
			<a class="logout-link" href="<?php echo site_url('logout'); ?>">Salir</a>
		</div>
	</aside>

	<script>
		(function () {
			var openBtn = document.getElementById('openMenu');
			var closeBtn = document.getElementById('closeMenu');
			var drawer = document.getElementById('drawer');
			var backdrop = document.getElementById('drawerBackdrop');
			var openMaterialBtn = document.getElementById('openMaterialModal');
			var closeMaterialBtn = document.getElementById('closeMaterialModal');
			var materialModal = document.getElementById('materialModal');
			var materialBackdrop = document.getElementById('materialBackdrop');
			var addParentSelect = document.getElementById('m_parent_id');
			var addDetailWrap = document.getElementById('m_detail_fields');
			var addDetailInputs = addDetailWrap ? addDetailWrap.querySelectorAll('input, textarea') : [];
			var editMaterialBtns = document.querySelectorAll('.edit-material-btn');
			var closeEditMaterialBtn = document.getElementById('closeEditMaterialModal');
			var editMaterialModal = document.getElementById('editMaterialModal');
			var editMaterialBackdrop = document.getElementById('editMaterialBackdrop');
			var editMaterialId = document.getElementById('e_material_id');
			var editParentSelect = document.getElementById('e_parent_id');
			var editNombre = document.getElementById('e_nombre');
			var editUnidad = document.getElementById('e_unidad');
			var editStockMinimo = document.getElementById('e_stock_minimo');
			var editCosto = document.getElementById('e_costo');
			var editProveedor = document.getElementById('e_proveedor');
			var editNota = document.getElementById('e_nota');
			var editDetailWrap = document.getElementById('e_detail_fields');
			var editDetailInputs = editDetailWrap ? editDetailWrap.querySelectorAll('input, textarea') : [];
			var historyMaterialBtns = document.querySelectorAll('.history-material-btn');
			var closeHistoryModalBtn = document.getElementById('closeHistoryModal');
			var historyModal = document.getElementById('historyModal');
			var historyBackdrop = document.getElementById('historyBackdrop');
			var historyTitle = document.getElementById('historyTitle');
			var historyNote = document.getElementById('historyNote');
			var historyList = document.getElementById('historyList');
			var historyUrlBase = '<?php echo site_url('inventario/historial-material'); ?>';
			var sellProductBtns = document.querySelectorAll('.sell-product-btn');
			var sellProductModal = document.getElementById('sellProductModal');
			var sellProductBackdrop = document.getElementById('sellProductBackdrop');
			var closeSellProductModalBtn = document.getElementById('closeSellProductModal');
			var cancelSellProductBtn = document.getElementById('cancelSellProductBtn');
			var sellProductoId = document.getElementById('sell_producto_id');
			var sellProductoNombre = document.getElementById('sell_producto_nombre');
			var sellPrecioVenta = document.getElementById('sell_precio_venta');
			var openCategoryBtn = document.getElementById('openCategoryModal');
			var closeCategoryBtn = document.getElementById('closeCategoryModal');
			var categoryModal = document.getElementById('categoryModal');
			var categoryBackdrop = document.getElementById('categoryBackdrop');
			var parentSelect = document.getElementById('c_parent');
			var templateMaterialsWrap = document.getElementById('templateMaterialsWrap');
			var templateSearchInput = document.getElementById('templateMaterialSearch');
			var templateSearchClearBtn = document.getElementById('templateSearchClear');
			var templateSearchInfo = document.getElementById('templateSearchInfo');
			var templateEmpty = document.getElementById('templateMaterialEmpty');
			var templateMaterialChecks = document.querySelectorAll('.tpl-material');
			var templateMaterialItems = document.querySelectorAll('.check-item[data-search]');
			var templateGroups = document.querySelectorAll('[data-template-group]');
			var templateSearchTimer = null;

			function openMenu() {
				drawer.classList.add('open');
				backdrop.classList.add('open');
			}

			function closeMenu() {
				drawer.classList.remove('open');
				backdrop.classList.remove('open');
			}

			openBtn.addEventListener('click', openMenu);
			closeBtn.addEventListener('click', closeMenu);
			backdrop.addEventListener('click', closeMenu);

			function openMaterialModal() {
				if (!materialModal || !materialBackdrop) { return; }
				materialModal.classList.add('open');
				materialBackdrop.classList.add('open');
			}

			function closeMaterialModal() {
				if (!materialModal || !materialBackdrop) { return; }
				materialModal.classList.remove('open');
				materialBackdrop.classList.remove('open');
			}

			function openEditMaterialModal() {
				if (!editMaterialModal || !editMaterialBackdrop) { return; }
				editMaterialModal.classList.add('open');
				editMaterialBackdrop.classList.add('open');
			}

			function closeEditMaterialModal() {
				if (!editMaterialModal || !editMaterialBackdrop) { return; }
				editMaterialModal.classList.remove('open');
				editMaterialBackdrop.classList.remove('open');
			}

			function openHistoryModal() {
				if (!historyModal || !historyBackdrop) { return; }
				historyModal.classList.add('open');
				historyBackdrop.classList.add('open');
			}

			function closeHistoryModal() {
				if (!historyModal || !historyBackdrop) { return; }
				historyModal.classList.remove('open');
				historyBackdrop.classList.remove('open');
			}

			function openSellProductModal() {
				if (!sellProductModal || !sellProductBackdrop) { return; }
				sellProductModal.classList.add('open');
				sellProductBackdrop.classList.add('open');
			}

			function closeSellProductModal() {
				if (!sellProductModal || !sellProductBackdrop) { return; }
				sellProductModal.classList.remove('open');
				sellProductBackdrop.classList.remove('open');
			}

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

			function formatMoney(value) {
				var n = parseFloat(value || 0);
				if (isNaN(n)) { n = 0; }
				return n.toFixed(2);
			}

			function renderHistoryRows(payload) {
				if (!historyList) { return; }
				var rows = (payload && payload.movimientos) ? payload.movimientos : [];
				if (!rows.length) {
					historyList.innerHTML = '<div class="history-item"><div class="history-item-meta">Sin movimientos de stock para este material.</div></div>';
					return;
				}

				var html = '';
				for (var i = 0; i < rows.length; i++) {
					var row = rows[i];
					html += '<div class="history-item">'
						+ '<div class="history-item-top">'
						+ '<div class="history-item-title">' + escapeHtml(row.material || '') + '</div>'
						+ '<div class="history-item-amount">+' + parseInt(row.cantidad || 0, 10) + ' ' + escapeHtml(row.unidad || '') + '</div>'
						+ '</div>'
						+ '<div class="history-item-meta">Fecha: ' + escapeHtml(row.fecha || '') + '</div>'
						+ '<div class="history-item-meta">Proveedor: ' + escapeHtml(row.proveedor || 'Sin proveedor') + '</div>'
						+ '<div class="history-item-meta">Costo unitario: ' + formatMoney(row.costo_unitario) + ' | Monto: ' + formatMoney(row.monto) + '</div>'
						+ '<div class="history-item-meta">Referencia: ' + escapeHtml(row.referencia || '-') + '</div>'
						+ '</div>';
				}
				historyList.innerHTML = html;
			}

			function syncMaterialDetailFields(parentSelectEl, wrapEl, inputs) {
				if (!parentSelectEl || !wrapEl) { return; }
				var hasParent = parseInt(parentSelectEl.value || '0', 10) > 0;
				wrapEl.classList.toggle('hidden', !hasParent);
				if (inputs && inputs.length) {
					for (var i = 0; i < inputs.length; i++) {
						inputs[i].disabled = !hasParent;
					}
				}
			}

			function openCategoryModal() {
				if (!categoryModal || !categoryBackdrop) { return; }
				categoryModal.classList.add('open');
				categoryBackdrop.classList.add('open');
			}

			function closeCategoryModal() {
				if (!categoryModal || !categoryBackdrop) { return; }
				categoryModal.classList.remove('open');
				categoryBackdrop.classList.remove('open');
			}

			function syncTemplateByParent() {
				if (!parentSelect || !templateMaterialChecks) { return; }
				var hasParent = parseInt(parentSelect.value || '0', 10) > 0;
				for (var i = 0; i < templateMaterialChecks.length; i++) {
					var check = templateMaterialChecks[i];
					check.disabled = !hasParent;
					if (!hasParent) {
						check.checked = false;
					}
				}
				if (templateMaterialsWrap) {
					templateMaterialsWrap.classList.toggle('templates-disabled', !hasParent);
				}
				if (templateSearchInput) {
					templateSearchInput.disabled = !hasParent;
				}
				if (templateSearchInfo) {
					templateSearchInfo.textContent = hasParent
						? ''
						: 'Selecciona un template padre para habilitar la busqueda y seleccion de materiales.';
				}
				if (!hasParent && templateSearchInput) {
					templateSearchInput.value = '';
				}
				if (!hasParent && templateEmpty) {
					templateEmpty.style.display = 'none';
				}
			}

			function normalizeText(str) {
				var text = String(str || '').toLowerCase();
				try {
					if (typeof text.normalize === 'function') {
						text = text.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
					}
				} catch (err) {}
				return text.trim();
			}

			function levenshtein(a, b) {
				if (a === b) { return 0; }
				var al = a.length;
				var bl = b.length;
				if (al === 0) { return bl; }
				if (bl === 0) { return al; }
				var m = [];
				for (var i = 0; i <= bl; i++) { m[i] = [i]; }
				for (var j = 0; j <= al; j++) { m[0][j] = j; }
				for (var r = 1; r <= bl; r++) {
					for (var c = 1; c <= al; c++) {
						var cost = a.charAt(c - 1) === b.charAt(r - 1) ? 0 : 1;
						m[r][c] = Math.min(
							m[r - 1][c] + 1,
							m[r][c - 1] + 1,
							m[r - 1][c - 1] + cost
						);
					}
				}
				return m[bl][al];
			}

			function rankTemplateItem(item, term) {
				var text = normalizeText(item.getAttribute('data-search') || '');
				if (!term) { return 0; }
				var tokens = normalizeText(term).split(/\s+/).filter(Boolean);
				if (!tokens.length) { return 0; }
				var words = text.split(/\s+/).filter(Boolean);

				var allPrefix = tokens.every(function (tk) {
					return words.some(function (w) { return w.indexOf(tk) === 0; });
				});
				if (allPrefix) { return 0; }

				var allContains = tokens.every(function (tk) {
					return text.indexOf(tk) > -1;
				});
				if (allContains) { return 1; }

				var fuzzy = tokens.every(function (tk) {
					return words.some(function (w) {
						if (Math.abs(w.length - tk.length) > 2) { return false; }
						return levenshtein(w, tk) <= 2;
					});
				});
				if (fuzzy) { return 2; }

				return 99;
			}

			function runTemplateSearch(term) {
				if (!templateMaterialItems || !templateMaterialItems.length) { return; }
				var hasParent = parentSelect && parseInt(parentSelect.value || '0', 10) > 0;
				var any = false;
				var visibleCount = 0;
				var cleanTerm = normalizeText(term || '');
				for (var i = 0; i < templateMaterialItems.length; i++) {
					var row = templateMaterialItems[i];
					var visible = hasParent && rankTemplateItem(row, cleanTerm) < 99;
					row.style.display = visible ? '' : 'none';
					if (visible) {
						any = true;
						visibleCount++;
					}
				}
				if (templateGroups && templateGroups.length) {
					for (var g = 0; g < templateGroups.length; g++) {
						var group = templateGroups[g];
						var groupRows = group.querySelectorAll('.check-item[data-search]');
						var groupAny = false;
						for (var r = 0; r < groupRows.length; r++) {
							if (groupRows[r].style.display !== 'none') {
								groupAny = true;
								break;
							}
						}
						group.style.display = groupAny ? '' : 'none';
					}
				}
				if (templateEmpty) {
					templateEmpty.style.display = (hasParent && !any) ? 'block' : 'none';
				}
				if (templateSearchClearBtn) {
					templateSearchClearBtn.classList.toggle('show', hasParent && cleanTerm.length > 0);
				}
				if (templateSearchInfo && hasParent) {
					if (!cleanTerm) {
						templateSearchInfo.textContent = 'Escribe para filtrar materiales por nombre, unidad o proveedor.';
					} else {
						templateSearchInfo.textContent = visibleCount + ' material(es) encontrado(s).';
					}
				}
			}

			if (openMaterialBtn) {
				openMaterialBtn.addEventListener('click', function (e) {
					e.preventDefault();
					syncMaterialDetailFields(addParentSelect, addDetailWrap, addDetailInputs);
					openMaterialModal();
				});
			}
			if (closeMaterialBtn) {
				closeMaterialBtn.addEventListener('click', closeMaterialModal);
			}
			if (materialBackdrop) {
				materialBackdrop.addEventListener('click', closeMaterialModal);
			}
			if (closeEditMaterialBtn) {
				closeEditMaterialBtn.addEventListener('click', closeEditMaterialModal);
			}
			if (editMaterialBackdrop) {
				editMaterialBackdrop.addEventListener('click', closeEditMaterialModal);
			}
			if (editMaterialBtns && editMaterialBtns.length) {
				editMaterialBtns.forEach(function (btn) {
					btn.addEventListener('click', function (e) {
						e.preventDefault();
						e.stopPropagation();
						if (!editMaterialId) { return; }

						var id = parseInt(btn.getAttribute('data-id') || '0', 10);
						editMaterialId.value = id > 0 ? String(id) : '';
						if (editParentSelect) {
							editParentSelect.value = btn.getAttribute('data-parent_id') || '0';
							if (String(editParentSelect.value) === String(id)) {
								editParentSelect.value = '0';
							}
							for (var i = 0; i < editParentSelect.options.length; i++) {
								var opt = editParentSelect.options[i];
								opt.disabled = (String(opt.value) === String(id));
							}
							syncMaterialDetailFields(editParentSelect, editDetailWrap, editDetailInputs);
						}
						if (editNombre) { editNombre.value = btn.getAttribute('data-nombre') || ''; }
						if (editUnidad) { editUnidad.value = btn.getAttribute('data-unidad') || ''; }
						if (editStockMinimo) { editStockMinimo.value = btn.getAttribute('data-stock_minimo') || '0'; }
						if (editCosto) { editCosto.value = btn.getAttribute('data-costo') || '0.00'; }
						if (editProveedor) { editProveedor.value = btn.getAttribute('data-proveedor') || ''; }
						if (editNota) { editNota.value = btn.getAttribute('data-nota') || ''; }

						openEditMaterialModal();
					});
				});
			}
			if (closeHistoryModalBtn) {
				closeHistoryModalBtn.addEventListener('click', closeHistoryModal);
			}
			if (historyBackdrop) {
				historyBackdrop.addEventListener('click', closeHistoryModal);
			}
			if (historyMaterialBtns && historyMaterialBtns.length) {
				historyMaterialBtns.forEach(function (btn) {
					btn.addEventListener('click', function (e) {
						e.preventDefault();
						e.stopPropagation();
						var materialId = parseInt(btn.getAttribute('data-id') || '0', 10);
						var materialNombre = btn.getAttribute('data-nombre') || 'Material';
						if (historyTitle) {
							historyTitle.textContent = 'Historial de stock: ' + materialNombre;
						}
						if (historyNote) {
							historyNote.textContent = 'Cargando movimientos...';
						}
						if (historyList) {
							historyList.innerHTML = '<div class="history-item"><div class="history-item-meta">Cargando...</div></div>';
						}
						openHistoryModal();

						if (materialId <= 0) {
							if (historyNote) { historyNote.textContent = 'Material invalido.'; }
							if (historyList) {
								historyList.innerHTML = '<div class="history-item"><div class="history-item-meta">No se pudo cargar el historial.</div></div>';
							}
							return;
						}

						fetch(historyUrlBase + '/' + materialId, { credentials: 'same-origin' })
							.then(function (res) { return res.json(); })
							.then(function (data) {
								if (!data || !data.ok) {
									if (historyNote) {
										historyNote.textContent = (data && data.message) ? data.message : 'No se pudo cargar el historial.';
									}
									if (historyList) {
										historyList.innerHTML = '<div class="history-item"><div class="history-item-meta">Sin datos disponibles.</div></div>';
									}
									return;
								}
								if (historyTitle) {
									historyTitle.textContent = 'Historial de stock: ' + (data.material || materialNombre);
								}
								if (historyNote) {
									historyNote.textContent = data.incluye_hijos
										? 'Incluye movimientos de este material padre y sus hijos.'
										: 'Movimientos directos de este material.';
								}
								renderHistoryRows(data);
							})
							.catch(function () {
								if (historyNote) {
									historyNote.textContent = 'Error cargando historial.';
								}
								if (historyList) {
									historyList.innerHTML = '<div class="history-item"><div class="history-item-meta">No se pudo conectar para traer el historial.</div></div>';
								}
							});
					});
				});
			}
			if (closeSellProductModalBtn) {
				closeSellProductModalBtn.addEventListener('click', closeSellProductModal);
			}
			if (cancelSellProductBtn) {
				cancelSellProductBtn.addEventListener('click', closeSellProductModal);
			}
			if (sellProductBackdrop) {
				sellProductBackdrop.addEventListener('click', closeSellProductModal);
			}
			if (sellProductBtns && sellProductBtns.length) {
				sellProductBtns.forEach(function (btn) {
					btn.addEventListener('click', function (e) {
						e.preventDefault();
						e.stopPropagation();
						if (sellProductoId) { sellProductoId.value = btn.getAttribute('data-id') || ''; }
						if (sellProductoNombre) { sellProductoNombre.value = btn.getAttribute('data-nombre') || ''; }
						if (sellPrecioVenta) { sellPrecioVenta.value = btn.getAttribute('data-precio') || '0.00'; }
						openSellProductModal();
					});
				});
			}
			if (openCategoryBtn) {
				openCategoryBtn.addEventListener('click', function (e) {
					e.preventDefault();
					syncTemplateByParent();
					openCategoryModal();
				});
			}
			if (closeCategoryBtn) {
				closeCategoryBtn.addEventListener('click', closeCategoryModal);
			}
			if (categoryBackdrop) {
				categoryBackdrop.addEventListener('click', closeCategoryModal);
			}
			if (parentSelect) {
				parentSelect.addEventListener('change', syncTemplateByParent);
				parentSelect.addEventListener('change', function () {
					runTemplateSearch(templateSearchInput ? templateSearchInput.value : '');
				});
				syncTemplateByParent();
			}
			if (templateSearchInput) {
				templateSearchInput.addEventListener('input', function () {
					if (templateSearchTimer) {
						clearTimeout(templateSearchTimer);
					}
					templateSearchTimer = setTimeout(function () {
						runTemplateSearch(templateSearchInput.value);
					}, 120);
				});
				runTemplateSearch('');
			}
			if (templateSearchClearBtn && templateSearchInput) {
				templateSearchClearBtn.addEventListener('click', function () {
					templateSearchInput.value = '';
					runTemplateSearch('');
					templateSearchInput.focus();
				});
			}
			if (addParentSelect) {
				addParentSelect.addEventListener('change', function () {
					syncMaterialDetailFields(addParentSelect, addDetailWrap, addDetailInputs);
				});
				syncMaterialDetailFields(addParentSelect, addDetailWrap, addDetailInputs);
			}
			if (editParentSelect) {
				editParentSelect.addEventListener('change', function () {
					syncMaterialDetailFields(editParentSelect, editDetailWrap, editDetailInputs);
				});
			}

			var materialHasError = <?php echo ($tab === 'materiales' && !empty($error_msg)) ? 'true' : 'false'; ?>;
			if (materialHasError) {
				syncMaterialDetailFields(addParentSelect, addDetailWrap, addDetailInputs);
				openMaterialModal();
			}
			var categoryHasError = <?php echo ($tab === 'categorias' && !empty($error_msg)) ? 'true' : 'false'; ?>;
			if (categoryHasError) {
				syncTemplateByParent();
				openCategoryModal();
			}
		})();
	</script>
</body>
</html>
