<!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>Clientes | <?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;
		}
		.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);
		}
		.container {
			max-width: 540px;
			margin: 0 auto;
			padding: 12px 12px 24px;
		}
		.top h1 {
			margin: 6px 0 12px;
			font-size: 22px;
		}
		.card {
			background: var(--card);
			border-radius: 14px;
			padding: 12px;
			border: 1px solid var(--line);
			margin-bottom: 12px;
		}
		h2 {
			margin: 0 0 10px;
			font-size: 16px;
		}
		label {
			font-size: 13px;
			font-weight: 600;
			margin: 8px 0 4px;
			display: block;
		}
		input, textarea {
			width: 100%;
			border: 1px solid var(--line);
			background: var(--card);
			color: var(--text);
			border-radius: 10px;
			padding: 10px;
			font-size: 15px;
		}
		textarea {
			min-height: 80px;
			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: block;
			text-align: center;
			text-decoration: none;
			border-radius: 10px;
			background: var(--primary);
			color: #fff;
			padding: 11px;
			font-size: 18px;
			font-weight: 700;
		}
		.ok {
			background: var(--ok-bg);
			color: var(--ok-text);
			border-radius: 10px;
			padding: 10px;
			font-size: 13px;
			margin-bottom: 10px;
		}
		.error {
			background: #fee2e2;
			color: #991b1b;
		}
		.client-card {
			border: 1px solid var(--line);
			border-radius: 12px;
			margin-bottom: 8px;
			overflow: hidden;
		}
		.client-card summary {
			list-style: none;
			cursor: pointer;
			padding: 11px 12px;
			display: grid;
			grid-template-columns: minmax(0, 1fr) auto;
			align-items: center;
			gap: 10px;
		}
		.client-card summary::-webkit-details-marker {
			display: none;
		}
		.client-name {
			font-size: 16px;
			font-weight: 700;
		}
		.summary-phone {
			font-size: 15px;
			font-weight: 700;
			color: var(--text);
			text-align: right;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			max-width: 180px;
		}
		.client-details {
			border-top: 1px solid var(--line);
			padding: 10px 12px;
		}
		.meta {
			font-size: 13px;
			color: var(--muted);
			margin-top: 3px;
			word-break: break-word;
		}
		.copy-value {
			border: 0;
			background: transparent;
			padding: 0;
			margin: 0;
			color: inherit;
			font-size: inherit;
			font-family: inherit;
			cursor: pointer;
			text-decoration: underline;
			text-decoration-style: dotted;
		}
		.summary-phone.copy-value {
			text-decoration: none;
		}
		.copy-tip {
			font-size: 12px;
			color: var(--muted);
			margin-top: 8px;
		}
		.detail-actions {
			margin-top: 10px;
			display: flex;
			justify-content: flex-end;
		}
		.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;
		}
		.copy-toast {
			position: fixed;
			left: 50%;
			bottom: 18px;
			transform: translateX(-50%);
			background: var(--text);
			color: var(--card);
			padding: 8px 12px;
			border-radius: 10px;
			font-size: 12px;
			opacity: 0;
			pointer-events: none;
			transition: opacity 0.2s ease;
			z-index: 60;
		}
		.copy-toast.show {
			opacity: 1;
		}
		.search-input {
			width: 100%;
			border: 1px solid var(--line);
			background: var(--card);
			color: var(--text);
			border-radius: 10px;
			padding: 10px;
			font-size: 15px;
			margin-bottom: 10px;
		}
		.search-empty {
			display: none;
			border: 1px dashed var(--line);
			border-radius: 10px;
			padding: 10px;
			font-size: 13px;
			color: var(--muted);
		}
		.empty {
			font-size: 14px;
			color: var(--muted);
		}
		.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, 520px);
			max-height: 90vh;
			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;
		}
	</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'].';';
	$flash_ok = $this->session->flashdata('ok');
	$flash_error = $this->session->flashdata('error');
?>
<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">
			<h1>Clientes</h1>
		</div>

		<div class="card">
			<?php if (!empty($flash_ok)): ?>
				<div class="ok"><?php echo $flash_ok; ?></div>
			<?php endif; ?>
			<?php if (!empty($flash_error)): ?>
				<div class="ok error"><?php echo $flash_error; ?></div>
			<?php endif; ?>
			<a href="#" id="openClientModal" class="action-btn">Agregar cliente</a>
		</div>

		<div class="card">
			<h2>Listado de clientes</h2>
			<?php if (empty($clientes)): ?>
				<div class="empty">Aun no hay clientes registrados.</div>
			<?php else: ?>
				<input id="clientSearch" class="search-input" type="text" placeholder="Buscar por nombre, telefono, cedula, correo o instagram...">
				<div id="searchEmpty" class="search-empty">No hay clientes que coincidan con la busqueda.</div>
				<?php foreach ($clientes as $c): ?>
					<?php
						$search_blob = trim(
							(string) $c->nombre.' '.
							(string) $c->telefono.' '.
							(string) $c->cedula.' '.
							(string) $c->correo.' '.
							(string) $c->instagram.' '.
							(string) $c->direccion.' '.
							(string) $c->nota
						);
					?>
					<details class="client-card" data-search="<?php echo html_escape($search_blob); ?>">
						<summary>
							<div class="client-name"><?php echo html_escape($c->nombre); ?></div>
							<?php if (!empty($c->telefono)): ?>
								<button type="button" class="copy-value summary-phone" data-copy="<?php echo html_escape($c->telefono); ?>"><?php echo html_escape($c->telefono); ?></button>
							<?php else: ?>
								<div class="summary-phone">-</div>
							<?php endif; ?>
						</summary>
						<div class="client-details">
							<?php if (!empty($c->cedula)): ?><div class="meta">Cedula: <?php echo html_escape($c->cedula); ?></div><?php endif; ?>
							<?php if (!empty($c->telefono)): ?>
								<div class="meta">Telefono: <button type="button" class="copy-value" data-copy="<?php echo html_escape($c->telefono); ?>"><?php echo html_escape($c->telefono); ?></button></div>
							<?php endif; ?>
							<?php if (!empty($c->correo)): ?>
								<div class="meta">Correo: <button type="button" class="copy-value" data-copy="<?php echo html_escape($c->correo); ?>"><?php echo html_escape($c->correo); ?></button></div>
							<?php endif; ?>
							<?php if (!empty($c->instagram)): ?>
								<div class="meta">Instagram: <button type="button" class="copy-value" data-copy="<?php echo html_escape($c->instagram); ?>"><?php echo html_escape($c->instagram); ?></button></div>
							<?php endif; ?>
							<?php if (!empty($c->direccion)): ?><div class="meta">Direccion: <?php echo html_escape($c->direccion); ?></div><?php endif; ?>
							<?php if (!empty($c->nota)): ?><div class="meta">Nota: <?php echo html_escape($c->nota); ?></div><?php endif; ?>
							<div class="copy-tip">Toca telefono, correo o instagram para copiar.</div>
							<div class="detail-actions">
								<button type="button"
									class="btn-outline edit-client-btn"
									data-id="<?php echo (int) $c->id; ?>"
									data-nombre="<?php echo html_escape($c->nombre); ?>"
									data-cedula="<?php echo html_escape($c->cedula); ?>"
									data-telefono="<?php echo html_escape($c->telefono); ?>"
									data-correo="<?php echo html_escape($c->correo); ?>"
									data-instagram="<?php echo html_escape($c->instagram); ?>"
									data-direccion="<?php echo html_escape($c->direccion); ?>"
									data-nota="<?php echo html_escape($c->nota); ?>">Editar</button>
							</div>
						</div>
					</details>
				<?php endforeach; ?>
			<?php endif; ?>
		</div>
	</div>

	<div id="copyToast" class="copy-toast">Copiado</div>

	<div id="clientBackdrop" class="modal-backdrop"></div>
	<div id="clientModal" class="modal">
		<div class="drawer-head">
			<h3 class="drawer-title" id="clientModalTitle">Agregar cliente</h3>
			<button id="closeClientModal" class="close-btn" type="button" aria-label="Cerrar modal">x</button>
		</div>
		<?php echo form_open('clientes/guardar', array('id' => 'clientForm')); ?>
			<input type="hidden" id="cliente_id" name="cliente_id">
			<label for="nombre">Nombre</label>
			<input id="nombre" name="nombre" type="text" required>

			<label for="cedula">Cedula</label>
			<input id="cedula" name="cedula" type="text">

			<label for="telefono">Telefono</label>
			<input id="telefono" name="telefono" type="text">

			<label for="correo">Correo</label>
			<input id="correo" name="correo" type="email">

			<label for="instagram">Instagram</label>
			<input id="instagram" name="instagram" type="text">

			<label for="direccion">Direccion</label>
			<input id="direccion" name="direccion" type="text">

			<label for="nota">Nota</label>
			<textarea id="nota" name="nota"></textarea>

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

	<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 active" href="<?php echo site_url('clientes'); ?>">Clientes</a>
		<a class="module-link" 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 openClientModalBtn = document.getElementById('openClientModal');
			var closeClientModalBtn = document.getElementById('closeClientModal');
			var clientModal = document.getElementById('clientModal');
			var clientBackdrop = document.getElementById('clientBackdrop');
			var clientForm = document.getElementById('clientForm');
			var clientModalTitle = document.getElementById('clientModalTitle');
			var clientSubmitBtn = document.getElementById('clientSubmitBtn');
			var editClientBtns = document.querySelectorAll('.edit-client-btn');
			var clientSearch = document.getElementById('clientSearch');
			var searchEmpty = document.getElementById('searchEmpty');
			var clientCards = document.querySelectorAll('.client-card');
			var copyToast = document.getElementById('copyToast');
			var copyTimer = null;

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

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

			function openClientModal() {
				clientModal.classList.add('open');
				clientBackdrop.classList.add('open');
			}

			function closeClientModal() {
				clientModal.classList.remove('open');
				clientBackdrop.classList.remove('open');
			}

			function fillClientForm(data, isEdit) {
				document.getElementById('cliente_id').value = data.cliente_id || '';
				document.getElementById('nombre').value = data.nombre || '';
				document.getElementById('cedula').value = data.cedula || '';
				document.getElementById('telefono').value = data.telefono || '';
				document.getElementById('correo').value = data.correo || '';
				document.getElementById('instagram').value = data.instagram || '';
				document.getElementById('direccion').value = data.direccion || '';
				document.getElementById('nota').value = data.nota || '';

				clientForm.action = isEdit ? '<?php echo site_url('clientes/editar'); ?>' : '<?php echo site_url('clientes/guardar'); ?>';
				clientModalTitle.textContent = isEdit ? 'Editar cliente' : 'Agregar cliente';
				clientSubmitBtn.textContent = isEdit ? 'Guardar cambios' : 'Guardar cliente';
			}

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

			openClientModalBtn.addEventListener('click', function (e) {
				e.preventDefault();
				fillClientForm({}, false);
				openClientModal();
			});
			closeClientModalBtn.addEventListener('click', closeClientModal);
			clientBackdrop.addEventListener('click', closeClientModal);

			editClientBtns.forEach(function (btn) {
				btn.addEventListener('click', function (e) {
					e.preventDefault();
					e.stopPropagation();
					fillClientForm({
						cliente_id: btn.getAttribute('data-id'),
						nombre: btn.getAttribute('data-nombre'),
						cedula: btn.getAttribute('data-cedula'),
						telefono: btn.getAttribute('data-telefono'),
						correo: btn.getAttribute('data-correo'),
						instagram: btn.getAttribute('data-instagram'),
						direccion: btn.getAttribute('data-direccion'),
						nota: btn.getAttribute('data-nota')
					}, true);
					openClientModal();
				});
			});

			var hasError = <?php echo !empty($flash_error) ? 'true' : 'false'; ?>;
			if (hasError) {
				fillClientForm({}, false);
				openClientModal();
			}

			function showCopied() {
				if (!copyToast) { return; }
				copyToast.classList.add('show');
				if (copyTimer) {
					clearTimeout(copyTimer);
				}
				copyTimer = setTimeout(function () {
					copyToast.classList.remove('show');
				}, 1300);
			}

			function fallbackCopy(text) {
				var temp = document.createElement('textarea');
				temp.value = text;
				temp.setAttribute('readonly', '');
				temp.style.position = 'absolute';
				temp.style.left = '-9999px';
				document.body.appendChild(temp);
				temp.select();
				try {
					document.execCommand('copy');
					showCopied();
				} catch (e) {}
				document.body.removeChild(temp);
			}

			document.addEventListener('click', function (e) {
				var target = e.target;
				if (!target || !target.classList || !target.classList.contains('copy-value')) {
					return;
				}
				e.preventDefault();
				e.stopPropagation();
				var text = target.getAttribute('data-copy') || '';
				if (!text) { return; }

				if (navigator.clipboard && navigator.clipboard.writeText) {
					navigator.clipboard.writeText(text).then(showCopied).catch(function () {
						fallbackCopy(text);
					});
				} else {
					fallbackCopy(text);
				}
			});

			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 rankCard(card, term) {
				var text = normalizeText(card.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 runSearch(term) {
				if (!clientCards || !clientCards.length) { return; }
				var any = false;
				for (var i = 0; i < clientCards.length; i++) {
					var card = clientCards[i];
					var score = rankCard(card, term);
					var show = score < 99;
					card.style.display = show ? '' : 'none';
					if (show) { any = true; }
				}
				if (searchEmpty) {
					searchEmpty.style.display = any ? 'none' : 'block';
				}
			}

			if (clientSearch) {
				clientSearch.addEventListener('input', function () {
					runSearch(clientSearch.value);
				});
				runSearch('');
			}
		})();
	</script>
</body>
</html>
