<?php if(
  strpos(Route::currentRouteName(), 'SysWebPAterrizajePlantillaxClienteEditarV2') !== false &&
  strpos(Route::currentRouteName(), 'SysWebSWebSeccionesxClientesEditarV2') !== false &&
  strpos(Route::currentRouteName(), 'SysWebSWebPaginasxTemaEditarV2') !== false &&
  strpos(Route::currentRouteName(), 'SysWebSWebPostxPlantillaEditarV2') !== false &&
  strpos(Route::currentRouteName(), 'SysWebVEmergentesVentanasEmergentesEditarV2') !== false &&
  strpos(Route::currentRouteName(), 'SysWebEmailMarketingPlantillaCorreoSecuenciaxClienteEditar') !== false &&
  strpos(Route::currentRouteName(), 'SysWebEmailMarketingPlantillaCorreoCampanhaxClienteEditar') !== false 
): ?>
<!-- Google Code for Remarketing Tag -->
<!--------------------------------------------------
Remarketing tags may not be associated with personally identifiable information or placed on pages related to sensitive categories. See more information and instructions on how to setup the tag on: http://google.com/ads/remarketingsetup
--------------------------------------------------->
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = 926937248;
var google_custom_params = window.google_tag_params;
var google_remarketing_only = true;
/* ]]> */
</script>
<script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt="" src="//googleads.g.doubleclick.net/pagead/viewthroughconversion/926937248/?guid=ON&amp;script=0"/>
</div>
</noscript>
<?php endif; ?>
<!--Start of Tawk.to Script-->
<script type="text/javascript">
 // IA Widget ID: 1iqr8m1bj

</script>
<script type="text/javascript">
	<?php
		$showLogMessage = false;
		// Obtener información del usuario y plan
		$user = 0;
		$plan = '';
		$idPlan = 0;
		$estado = 0;
		$planPausado = 0;
		$periodoGracia = '';

		// Validacion de widget de chat
		// SC -- Tawk.to
		$iaWidgetID = '1jng7qe02';
		$humanWidgetID = '1glpqplss';
		$propertyID = '63b31de947425128790b4014';
		$apiKey = 'cc45efe127fa80ee212b39c0e92962151b2e037a';
		// SC --

		// ATENCION: Poner en true si se quiere dejar solo a la IA
		$esHoraEspecial = false; // Variable de control para cambiar el chat a IA cuando se requiera

		// Definiendo rutas excluidas para validar
		$rutasExcluidas = ['SysWebAcceso', 'SysWebRecuperarContrasenha', 'SysWebReestablecerContrasenha'];

		// Rutas previas excluidas
		$rutasPreviasExclusion = ['SysWebAcceso', 'SysWebClientes'];

		// Se determian cuales son dias feriados
		$diasAsueto = [
			'01-01', // Anio Nuevo
			'04-02', // Semana Santa
			'04-03', // Semana Santa
			'04-04', // Semana Santa
			'05-01', // Dia del Trabajador
			'05-10', // Dia de la Madre
			'06-17', // Dia del Padre
			'08-03', // Divino Salvador del Mundo
			'08-05', // Divino Salvador del Mundo
			'08-06', // Divino Salvador del Mundo
			'09-13', // Dia del Programador
			'09-15', // Dia de Independencia
			'11-02', // Dia de los difuntos
			'12-25', // Navidad
			'12-31', // Fin de Anio
			// Agrega otros días aquí si es necesario
		];

		// Obtener la URL anterior
		$urlPrevia = URL::previous();

		// Extraer la parte relativa de la URL (después de 'public/')
		$basePath = trim(str_replace(url('/'), '', $urlPrevia), '/');

		// Intentar resolver el nombre de la ruta a partir de la URL relativa
		try {
			$route = app('router')->getRoutes()->match(app('request')->create("/$basePath"));
			$rutaPrevia = $route->getName();
		}
		catch (\Exception $e) {
			$rutaPrevia = null; // No se encontró una ruta coincidente
		}
		// ---
		// Rutas excluidas
		$esRutaPreviaExcluida = in_array($rutaPrevia, $rutasPreviasExclusion);
		if(!Auth::guest()){
			$user = Auth::user();

			// error_log("USUARIO: ".json_encode($user));
			if($user->tipo !== 'A'){
				$userId = $user->id;
				$esEmpleado = in_array($user->tipo, ['EC', 'NUV2']);

				if ($esEmpleado) {
					$clienteId = Empleado::where('users_id', $userId)->pluck('clientes_id');
					$cliente = Cliente::find($clienteId);
				}
				else {
					$cliente = Cliente::where('users_id', $userId)->first();
				}

				// Plan
				$idPlan = !empty($cliente->planes_sc_id) ? $cliente->planes_sc_id : 0;

				$plan = 'Sin plan'; // Valor predeterminado
				$planSC = PlanSC::find($idPlan);

				if ($planSC) {
					$plan = $planSC->nombre;
				}

				// Estado
				if ($esEmpleado) {
					$estado = User::join('clientes', 'users.id', '=', 'clientes.users_id')
						->where('clientes.id', $cliente->id)
						->pluck('users.estado');
				}
				else {
					$estado = User::where('id', $userId)->pluck('estado');
				}

				$estado = ($estado == 1) ? "Activo" : "Inactivo";

				// Plan pausado
				$planPausado = $cliente->planPausa;
				$enPausa = ($cliente->planPausa == 1) ? "Sí" : "No";

				// Periodo de gracia
				$periodoGracia = $esEmpleado
					? $cliente->permiso_acceso
					: User::where('id', $userId)->pluck('permiso_acceso');

				$periodoGracia = !empty($periodoGracia) ? $periodoGracia : "Vacío";
			}
		}

		// Definiendo rutas excluidas
		$rutaActual = Route::currentRouteName();
		$esRutaExcluida = in_array($rutaActual, $rutasExcluidas);

		// Se almacena en una variable global el codigo para el widget que se debe cargar, por defecto IA
		$TWidgetID = $iaWidgetID;

		// Se recupera la fecha actual basado en una zona horaria en especifico
		$fechaActual = new DateTime('now', new DateTimeZone('America/El_Salvador'));

		// Se establece horario de inicio y fin chat de soporte
		$horaInicioManiana = new DateTime('today 8:30', new DateTimeZone('America/El_Salvador'));
		$horaFinManiana = new DateTime('today 12:00', new DateTimeZone('America/El_Salvador'));
		$horaInicioTarde = new DateTime('today 13:00', new DateTimeZone('America/El_Salvador'));
		$horaFinTarde = new DateTime('today 17:30', new DateTimeZone('America/El_Salvador'));

		// Se obtiene el numero entero correspondiente a dia, hora y minuto de la fecha actual
		$diaSemana = (int) $fechaActual->format('N');
		$horaActual = (int) $fechaActual->format('G');
		$minutos = (int) $fechaActual->format('i');
		$segundos = (int) $fechaActual->format('s');
		$horaDecimal = $horaActual + ($minutos / 60);

		// Se recupera solo el mes y el dia de la fecha actual para validar si es un dia feriado
		// faf: fecha actual formateada
		$faf = $fechaActual->format('m-d'); // Formato MM-DD

		// Se define si el dia es habil o dia se semana
		$esDiaHabil = $diaSemana >= 1 && $diaSemana <= 5;
		$esFinSemana = $diaSemana == 6 || $diaSemana == 7;
		$esSabado = $diaSemana == 6;
		$esDomingo = $diaSemana == 7;

		// Verifica si el día actual es festivo
		$esDiaAsueto = in_array($faf, $diasAsueto);

		// Se define horario de soporte en vivo
		$esHorarioHabil = $horaDecimal >= 8.5 && $horaDecimal < 17.5;

		// Se define el horario de chat para IA y Humano
		$esHorarioChatConIA = $horaDecimal >= 0 && $horaDecimal < 8.5 || $horaDecimal >= 12 && $horaDecimal < 13 || $horaDecimal >= 17.5;
		$esHorarioChatConHumano = $horaDecimal >= 8.5 && $horaDecimal < 12 || $horaDecimal >= 13 && $horaDecimal < 17.5;

		// Se define horarios de soporte
		$esHorarioMatutino = $horaDecimal >= 8.5 && $horaDecimal < 12;
		$esHorarioVespertino = $horaDecimal >= 13 && $horaDecimal < 17.5;

		$esHorarioChatEnVivo = $esHorarioMatutino || $esHorarioVespertino;
		$esHoraAlmuerzo = $horaDecimal >= 12 && $horaDecimal < 13;

		// Por defecto el cambio se hace al inicio de la maniana
		$horaCambioChat = $horaDecimal < 8.5 ? $horaInicioManiana : $horaFinTarde;

		// Se determina los segundos para hacer el cambio de chat
		$segundosParaCambio = 0;
		$cambioAutomatico = false;
		$tipoWidgetCambio = 'ia';

		// 7.95 ~ 7:57 am | 8.45 ~ 08:27 am | 11.95 ~ 11:57 am | 12.95 ~ 12:57 pm | 17.45 ~ 05:27 pm
		if($esDiaHabil){
			$showLogMessage && error_log("01 | Es dia habil [Lunes, Viernes]");
			$cambioAutomatico = true;
			if($horaDecimal > 7.5 && $horaDecimal <= 8.5){
				$horaCambioChat = $horaInicioManiana;
				$tipoWidgetCambio = 'humano';
				$showLogMessage && error_log("02 | Cambio de ]7.5, 8.5]");
			}
			else if($horaDecimal > 11.5 && $horaDecimal <= 12){
				$horaCambioChat = $horaFinManiana;
				$showLogMessage && error_log("03 | Cambio de ]11.5, 12]");
			}
			else if($horaDecimal > 12.5 && $horaDecimal <= 13){
				$horaCambioChat = $horaInicioTarde;
				$tipoWidgetCambio = 'humano';
				$showLogMessage && error_log("04 | Cambio ]12.5 , 13]");
			}
			else if($horaDecimal > 17 && $horaDecimal <= 17.5) {
				$horaCambioChat = $horaFinTarde;
				$showLogMessage && error_log("05 | Cambio ]17, 17.5]");
			}
			else {
				$cambioAutomatico = false;
				$showLogMessage && error_log("06 | No se hace cambio...");
			}
		}
		else if($esSabado){
			$showLogMessage && error_log("07 | Es sábado");
			$cambioAutomatico = true;
			if($horaDecimal > 7.5 && $horaDecimal <= 8.0){
				$horaCambioChat = $horaInicioManiana;
				$tipoWidgetCambio = 'humano';
				$showLogMessage && error_log("08 | Cambio de ]7.5, 8.5]");
			}
			else if($horaDecimal > 11.5 && $horaDecimal <= 12){
				$horaCambioChat = $horaFinManiana;
				$showLogMessage && error_log("09 | Cambio de ]11.5, 12]");
			}
			else {
				$cambioAutomatico = false;
				$showLogMessage && error_log("10 | No se hace cambio...");
			}
		}

		if($cambioAutomatico){
			$segundosParaCambio = $horaCambioChat->getTimestamp() - $fechaActual->getTimestamp();
			$showLogMessage && error_log("11 | Se establece segundos para cambio...");
		}

		// Se define si el chat de soporte sera solo con IA para casos especiales
		$esSoporteSoloIA = $esDiaAsueto || $esHoraEspecial || $esRutaExcluida;

		// Obteniendo la version de la plataforma
		$permiteChatConHumano = true;

		// Validando si el usuario tiene soporte en vivo con un humano

		if($permiteChatConHumano){
			$showLogMessage && error_log("16 | El plan permite chat con humano...");
			if($esDiaHabil){
				$showLogMessage && error_log("17 | Es dia habil...");
				if($esHorarioChatConHumano){
					$showLogMessage && error_log("18 | Es horario de chat con humano...");
					$TWidgetID =  $humanWidgetID;
				}
			}
			else if($esSabado){
				$showLogMessage && error_log("19 | Es sabado...");
				if($esHorarioMatutino){
					$showLogMessage && error_log("20 | Es horario de chat con humano...");
					$TWidgetID =  $humanWidgetID;
				}
			}
			else {
				$TWidgetID = $iaWidgetID;
				$showLogMessage && error_log("21 | No es dia habil, ni sabado...");
			}
		}
		else {
			$TWidgetID = $iaWidgetID;
			$showLogMessage && error_log("22 | No se permite chat con humano...");
		}

		// En caso que sea dia de asueto, una hora especial o una ruta excluida se establece en soporte con IA
		if( $esSoporteSoloIA ){
			$showLogMessage && error_log("23 | El soporte es solo con IA...");

			$cambioAutomatico = true;
			$tipoWidgetCambio = 'ia';
			$horaCambioChat = new DateTime('today 0:00', new DateTimeZone('America/El_Salvador'));
			$permiteChatConHumano = false;
			// Se definie que el soporte sea solo con IA
			$TWidgetID = $iaWidgetID;
		}

		// Se crea una variable para almacenar el tipo de chat actual
		$soporteActual = $TWidgetID === $humanWidgetID ? 'humano' : 'ia';

		// Si el usuario no está autenticado que no haga cambio automatico
		if(Auth::guest() || $esRutaExcluida){
			$cambioAutomatico = false;

			$showLogMessage && error_log("24 | Es un usuario invitado o es una ruta excluida...");
			$showLogMessage && error_log("25 | No se hara cambio automatico...");
		}

		// TEST ===============================

		// $fechaActual = new DateTime('2025-05-03 8:25:00', new DateTimeZone('America/El_Salvador')); // TEST
		// $horaCambioChat = new DateTime('2025-05-03 08:30', new DateTimeZone('America/El_Salvador')); // TEST

		// $segundosParaCambio = $horaCambioChat->getTimestamp() - $fechaActual->getTimestamp();
		// $tipoWidgetCambio = 'humano';
		// $cambioAutomatico = true;
		// $TWidgetID = ($tipoWidgetCambio === 'humano')? $iaWidgetID : $humanWidgetID; // id actual

		// $soporteActual = $TWidgetID === $humanWidgetID ? 'humano' : 'ia';
		// // $TWidgetID = $humanWidgetID;

		// $horaInicioManiana = new DateTime('today 8:30', new DateTimeZone('America/El_Salvador'));
		// $horaFinManiana = new DateTime('today 12:00', new DateTimeZone('America/El_Salvador'));
		// $horaInicioTarde = new DateTime('today 13:00', new DateTimeZone('America/El_Salvador'));
		// $horaFinTarde = new DateTime('today 17:30', new DateTimeZone('America/El_Salvador'));

		$fechaA = $fechaActual->format('d-m-Y H:i:s');
		$fechaC = $horaCambioChat->format('d-m-Y H:i:s');

		// END TEST ===============================

		// Variables para el estado del chat en vivo
		$chatActivo = false;
		$mensajeChat = '';
		$mensajeChatMovil = '';
		$tiempoRestante = '';
		$claseChatEstado = 'inactivo';
		$mostrarEstadoChat = false;
		$enlacePeriodoGracia = '';

		// Mostrar el estado del chat si el usuario tiene acceso
		if ($user && $user->tipo !== 'A') {
			$mostrarEstadoChat = true;
			
			// Determinar si el chat está activo y qué mensaje mostrar
			if ($esDiaHabil) {
				if ($esHorarioMatutino || $esHorarioVespertino) {
					$mostrarEstadoChat = false;
				}
				else if ($esHoraAlmuerzo) {
					// Calcular tiempo restante para que vuelva el chat
					$minutosRestantes = 60 - $minutos;
					$tiempoRestante = $minutosRestantes <= 0 ? '1 min' : $minutosRestantes . ' min';
					$mensajeChat = "Receso - Chat humano disponible en {$tiempoRestante}";
					$mensajeChatMovil = '!';
				}
				else if ($horaDecimal < 8.5 && $horaDecimal >= 4) {
					// Solo mostrar mensaje si estamos entre 4:00 AM y 8:00 AM
					$horasRestantes = floor(8.5 - $horaDecimal);
					$minutosRestantes = floor((8.5 - $horaDecimal - $horasRestantes) * 60);
					$tiempoRestante = "{$horasRestantes}h {$minutosRestantes}m";
					$mensajeChat = "Chat humano disponible en {$tiempoRestante}";
					$mensajeChatMovil = '!';
				}
				else if ($horaDecimal < 4) {
					// Si es antes de las 4:00 AM, no mostrar el mensaje
					$mostrarEstadoChat = false;
				}
				else {
					// Después del horario laboral
					$mensajeChat = 'Chat humano inactivo por horario';
					$mensajeChatMovil = '!';
				}
			}
			else if ($esSabado && $esHorarioMatutino) {
				$mostrarEstadoChat = false;
			}
			else {
				$mensajeChat = 'Chat humano inactivo por horario';
				$mensajeChatMovil = '!';
			}
			
			// Si es día de asueto, no mostrar chat
			if ($esDiaAsueto) {
				$mostrarEstadoChat = false;
			}
		}
		else if ($user&& $user->tipo !== 'A' && !empty($periodoGracia) && $periodoGracia !== 'Vacío') {
			// Usuario en período de gracia por falta de pago
			$mostrarEstadoChat = true;
			$mensajeChat = 'Chat humano no disponible por falta de pago';
			$mensajeChatMovil = '!';
			$enlacePeriodoGracia = 'https://sumeclientes.com/bienvenido-de-regreso-en-transicion#activo';
		}
		// Este es el widget que se carga por defecto
		$TWVinculo = 'https://embed.tawk.to/'. $propertyID .'/' . $TWidgetID;
	?>
	var chatEstadoInfo = {
        activo: <?php echo ($chatActivo ? 'true' : 'false'); ?>,
        mensaje: "<?php echo addslashes($mensajeChat); ?>",
        clase: "<?php echo $claseChatEstado; ?>",
        mostrar: <?php echo ($mostrarEstadoChat ? 'true' : 'false'); ?>,
		mensajeMovil: "<?php echo addslashes($mensajeChatMovil); ?>"
    };
	// Cargar Script
	var tiempoInicioCambio = null;
	let timeoutId = null;
	const tiempoEsperaCierre = 10 * 60 * 1000; // Tiempo para cerrar el chat
	const tiempoEsperaWidget = 2.5 * 60 * 1000; // Tiempo para reiniciar el widget despues del cambio

	window.Tawk_API = window.Tawk_API || {}, Tawk_LoadStart = new Date(), intervalCambiarWidget = null, intervalWidgetCargado = null, widgetCargado = false;
	var enlacePeriodoGraciaGlobal = (chatEstadoInfo.enlacePeriodoGracia && chatEstadoInfo.enlacePeriodoGracia.length) ? chatEstadoInfo.enlacePeriodoGracia : '';
	function actualizarEstadoChat() {
		var $chatSpan = $("#chatEstadoSpan");
		console.log("Actualizando estado del chat...");
		if ($chatSpan.length === 0) return;
		var esMovil = $(window).width() <= 1024;
		if (enlacePeriodoGraciaGlobal) {
			$chatSpan.attr("href", enlacePeriodoGraciaGlobal);
			$chatSpan.attr("target", "_blank");
			$chatSpan.attr("rel", "noopener");
		}
		// Verificar si se debe mostrar el span
		if (chatEstadoInfo.mostrar) {
			// Actualizar el contenido
			var mensaje = '<span class="texto-escritorio">' + chatEstadoInfo.mensaje + '</span>' +
						'<span class="texto-movil">'+ chatEstadoInfo.mensajeMovil + '</span>';
			$chatSpan.html(mensaje).css("display", "inline-block");
			// Actualizar clases
			if (chatEstadoInfo.activo) {
				$chatSpan.addClass("activo").removeClass("inactivo");
			}
			else {
				$chatSpan.addClass("inactivo").removeClass("activo");
			}
		}
		else {
			// Ocultar el span si no debe mostrarse
			$chatSpan.css("display", "none");
		}
		// Destruir el popover existente (si existe)
		if ($chatSpan.data("plugin_webuiPopover")) {
			$chatSpan.webuiPopover("destroy");
		}
		// Solo inicializar el popover en dispositivos móviles
		if (esMovil) {
			var contenido = "<p class='text-theme'>" + chatEstadoInfo.mensaje + "</p>";
			if (enlacePeriodoGraciaGlobal) {
				contenido += "<p><a href='" + enlacePeriodoGraciaGlobal + "' target='_blank' rel='noopener' class='btn btn-warning btn-sm'>Más información</a></p>";
			}
			else {
				contenido += "<p><a href='https://sumeclientes.com/soporte/' target='_blank' rel='noopener' class='btn btn-warning btn-sm'>Crear ticket</a></p>";
			}
			// Configuración del popover
			var configuracionPopover = {
				width: "auto",
				height: "auto",
				animation: "pop",
				title: "Soporte humano no disponible",
				content: contenido,
				closeable: true,
				cache: true,
				style: "ayuda popover-warning",
			};
			$chatSpan.webuiPopover(configuracionPopover);
		}
	}

	$( document ).ready(function() {
		actualizarEstadoChat();
		// console.log( "Página lista..." );
		// Verificar si hay una marca de tiempo almacenada
		const tiempoEsperaWR = localStorage.getItem("tiempoEsperaWR"); // Tiempo Espera Widget Restante

		<?php if(Session::has('ingresoAdminGeneral')): ?>
			// console.log("No se mostrará widget de chat de soporte...");
			return;
		<?php endif; ?>

		// SE INICIA EL WIDGET PARA EL CHAT DE SOPORTE

		// Codigo base
		// var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
		// (function(){
		// 	var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
		// 	s1.async=true;
		// 	s1.src="<?php echo $TWVinculo; ?>";
		// 	s1.charset="UTF-8";
		// 	s1.setAttribute("crossorigin","*");
		// 	s0.parentNode.insertBefore(s1,s0);
		// })();
		// Fin codigo base

		// console.log(new Date().toLocaleString(), " | Iniciando widget del chat...");

		if(tiempoEsperaWR){
			const tiempoActual = Date.now();
			const tiempoRestante = tiempoEsperaWR - tiempoActual;
			// console.log(new Date().toLocaleString(), " | Tiempo restante: ", (tiempoRestante / 1000));
			if(tiempoRestante > 0){
				setTimeout(() => {
					localStorage.removeItem("tiempoEsperaWR");
					cargarWidgetChat("<?php echo $propertyID; ?>", "<?php echo $TWidgetID; ?>");
				}, tiempoRestante);
			}
			else {
				localStorage.removeItem("tiempoEsperaWR");
				cargarWidgetChat("<?php echo $propertyID; ?>", "<?php echo $TWidgetID; ?>");
			}
		}
		else {
			cargarWidgetChat("<?php echo $propertyID; ?>", "<?php echo $TWidgetID; ?>");
		}

		<?php if(!Auth::guest()): ?>
			// Quitando sesion de visitante
			// localStorage.removeItem('anonVisitorId');
			// console.log(new Date().toLocaleString(), " | Iniciando datos del visitante...");

			// Preparando objeto de datos de vistante autenticado
			window.Tawk_API.visitor = {
				name  : "<?php echo $cliente->empresa; ?>",
				email : "<?php echo Auth::user()->email; ?>",
				hash  : "<?php echo hash_hmac('sha256', Auth::user()->email, $apiKey); ?>"
			};
		<?php else: ?>

			// let anonVisitorId = localStorage.anonVisitorId ?? getAnonVisitorId();

			// Preparando objeto de datos de vistante no autenticado
			// window.Tawk_API.visitor = {
			// 	name: 'Visitante',
			// 	email: anonVisitorId + '@sumeclientes.com'
			// };

		<?php endif; ?>

	});

	// Función para iniciar o reiniciar el temporizador
	function iniciarTemporizador() {

		// console.log(new Date().toLocaleString(), " | Se ha iniciado la cuenta para cerrar el chat...");
		// Limpiar el temporizador existente (si lo hay)
		if (timeoutId) {
			// console.log(new Date().toLocaleString(), " | Timer reiniciado...");
			clearTimeout(timeoutId);
		}

		// Iniciar un nuevo temporizador
		timeoutId = setTimeout(() => {
			// console.log(new Date().toLocaleString(), " | Se ha cerrado el chat de soporte por inactividad...");
			// console.log("Han pasado ", (tiempoEsperaCierre / 1000 / 60)," minutos sin respuesta del visitante. Cerrando el chat...");

			window.Tawk_API.endChat(); // Cerrar el chat
		}, tiempoEsperaCierre);
    }

	// Función para detener el temporizador
	function detenerTemporizador() {
		// console.log("Temporizador detenido...");
		if (timeoutId) {
			clearTimeout(timeoutId);
			timeoutId = null;
			// console.log("Temporizador detenido.");
		}
	}

	function getAnonVisitorId() {
		const storageKey = 'anonVisitorId';
		const expirationTime = 1 * 60 * 1000; // 60 minutos en milisegundos

		// Obtener los datos almacenados en localStorage
		let storedData = localStorage.getItem(storageKey);

		if (storedData) {
			try {
				// Parsear los datos almacenados (ID y marca de tiempo)
				const { id, timestamp } = JSON.parse(storedData);

				// Verificar si el ID ha expirado (han pasado más de 60 minutos)
				if (Date.now() - timestamp > expirationTime) {
					// console.log("El ID anónimo ha expirado. Generando uno nuevo...");
					storedData = null; // Forzar la creación de un nuevo ID
				}
			} catch (error) {
				console.error("Error al parsear los datos almacenados:", error);
				storedData = null; // Si hay un error, forzar la creación de un nuevo ID
			}
		}

		// Si no hay un ID válido o ha expirado, crear uno nuevo
		if (!storedData) {
			const newId = 'visitor' + "<?php echo $fechaActual->format('\FdmY\HHis'); ?>" + "NA" + Math.floor(Math.random() * 1000000);
			const newData = {
				id: newId,
				timestamp: Date.now() // Guardar la marca de tiempo actual
			};

			// Almacenar el nuevo ID y la marca de tiempo en localStorage
			localStorage.setItem(storageKey, JSON.stringify(newData));
			return newId;
		}

		// Si el ID es válido y no ha expirado, devolverlo
		const { id } = JSON.parse(storedData);
		return id;
	}

	function cargarWidgetChat(propertyID, widgetID) {
		// console.log(new Date().toLocaleString(), " | Cargando widget...");
		const script = document.createElement("script");
		script.async = true;
		script.src = `https://embed.tawk.to/${propertyID}/${widgetID}`;
		script.charset = "UTF-8";
		script.setAttribute("crossorigin", "*");
		document.head.appendChild(script);


		window.Tawk_API.onLoad = function(){
			widgetCargado = true;
			// console.log(new Date().toLocaleString(), " | Minimizando chat cargado...");
			window.Tawk_API.minize();

			var loadTime = new Date() - Tawk_LoadStart; // Diferencia en milisegundos
			// console.log("El widget de Tawk.to tardó " + (loadTime / 1000) + "s en cargarse.");

			<?php if(!Auth::guest()): ?>

				// Creando sesion de usuario en TawkTo  // [REVISAR] | Actualmente no funciona porque debe ir fuera del onLoad de Tawk_API
				window.Tawk_API.login({
					hash : "<?php echo hash_hmac('sha256', Auth::user()->email, $apiKey); ?>",
					userId : "<?php echo Auth::user()->email; ?>",
					name : "<?php echo $cliente->empresa; ?>",
					email : "<?php echo Auth::user()->email; ?>"
					}, function(error) {
					if(error){
						console.log("Ocurrio un erro al iniciar sesion...");
					}
				});

				// Agegando atributos
				window.Tawk_API.setAttributes(
					{
						"Plan": "<?php echo $plan; ?>",
						"Estado": "<?php echo $estado; ?>",
						"Enpausa": "<?php echo $planPausado ? 'Sí': 'No'; ?>",
						"Periododegracia": "<?php echo $periodoGracia; ?>",
						"hash": "<?php echo hash_hmac('sha256', Auth::user()->email, $apiKey); ?>"
					},
					function(error){
						if(error){
							// console.log("Ocurrio un error al agregar atributos");
						}
					}
				);

				// Agregando etiquetas
				window.Tawk_API.addTags(
					[
						"<?php echo Auth::user()->email; ?>",
						"<?php echo $plan; ?>",
						"<?php echo $estado; ?>",
						"Permiso de acceso: <?php echo $periodoGracia; ?>"
					],
					function(error){
						if(error){
							// console.log("Ocurrio un error al agregar las etiquetas");
						}
					}
				);
			<?php endif; ?>

			// Minimizar el chat
			$(window).click(function() {
				window.Tawk_API.minimize();
			});

		} // Fin Tawk_API.onLoad

		window.Tawk_API.onChatStarted = function(){
			// console.log("onChatStarted : ", "Yes");

			// Iniciar el temporizador al comenzar el chat
			if(!timeoutId){
				// console.log("No existe timer");
				iniciarTemporizador();
			}
			else {
				// console.log("Existe timer...");
			}
		};

		window.Tawk_API.onChatMessageVisitor = function(message){
			// console.log("onChatMessageVisitor : ", message);
			// Reiniciar el temporizador cuando el visitante responde
			iniciarTemporizador();
		};

		window.Tawk_API.onChatMessageAgent = function(message){
			// console.log("onChatMessageAgent : ", message);
			iniciarTemporizador();
		};

		window.Tawk_API.onChatEnded = function(){
			// console.log("onChatEnded : Yes");
			if(localStorage.removeItem('anonVisitorId')){
				localStorage.removeItem('anonVisitorId');
			}

			// Detener el temporizador cuando el chat termine
			if (timeoutId) {
				detenerTemporizador();
			}
		};

		window.Tawk_API.onChatHidden = function(){
			//
		};

		window.Tawk_API.onChatMaximized = function(){
			//MODIFICACION DE CUERPO DE CHAT
			<?php if(!Auth::guest()): ?>
				var timeChat = 0;
				var tiempoChat = setInterval(function(){
						timeChat++;
							if(timeChat > 20){
								clearInterval(tiempoChat);
							}
							else{
								if(!window.Tawk_API.isChatMinimized()){
									$('.widget-visible').find("iframe:nth-child(2)").css({"bottom": "", "left":""});
									$('.widget-visible').find("iframe:nth-child(2)").css({"bottom": "5px", "left":"5px"});
									$('.widget-visible').find("iframe:nth-child(2)").css("clip-path", "unset");
									$('.widget-visible').find("iframe:nth-child(2)").css("z-index", "1030 !important");
									clearInterval(tiempoChat);
								}
							}
						}, 100);
			<?php endif; ?>
		};

		if(!localStorage.getItem("tiempoEsperaWR")){
			// console.log((new Date()).toLocaleString(), " | No existe tiempo restante...");
			hacerCambioWidget();
		}

		<?php if(!Auth::guest()): ?>
			var time = 0;
			var tiempo = setInterval(function(){
						time++;
						if(time > 20){
							clearInterval(tiempo);
						}
						else{
							$('.widget-visible').find("iframe:nth-child(2)").css("clip-path", "circle(0)");
							if($('.widget-visible').find("iframe:first").length > 0){
								$('.widget-visible').find("iframe:first").css({"transform": "", "min-height":"", "top":"", "right":"","left":""});
								$('.widget-visible').find("iframe:first").css({"transform": "scale(0.6)", "min-height":"60px", "top":"-9px", "right":"160px"});
								$('.widget-visible').css("clip-path", "unset");
								//----------------------------------------------------------
								$('.widget-visible').find("iframe:nth-child(2)").css("clip-path", "unset");
								$('.widget-visible').find("iframe:nth-child(2)").css({"bottom": "", "left":""});
								$('.widget-visible').find("iframe:nth-child(2)").css({"bottom": "5px", "left":"5px"});
								clearInterval(tiempo);
							}
						}
					},
			500);
		<?php endif; ?>
	}

	function hacerCambioWidget(){
		// console.log((new Date()).toLocaleString(), " | Ejecutando funcion para hacer cambio de widget...");
		const intentosVerificacion = 25;
		let intentosRealizados = 0;

		// Verificando si es cambio automatico
		intervalWidgetCargado = setInterval(function(){
			// console.log(intentosRealizados, " | Verificacion del widget cargado...");

			if(!widgetCargado && intentosRealizados >= intentosVerificacion){
				// intentosRealizados = 0;
				clearInterval(intervalWidgetCargado);

				// console.log("El widget del chat no cargo, recargue la página...");

			}

			if(widgetCargado){
				// console.log("Widget Cargado...");
				// Borrando el intervalo de verificacion del widget cargado
				clearInterval(intervalWidgetCargado);

				// VERIFICAR CAMBIO AUTOMATICO
				<?php if($cambioAutomatico): ?>

					// Se marca la hora actual y los segundos que faltan para el cambio
					let segundosParaCambio = <?php echo $segundosParaCambio * 1000; ?>;

					segundosParaCambio = segundosParaCambio >= 0 ? segundosParaCambio : 0;

					tiempoInicioCambio = new Date();

					const tipoWidgetCambio = "<?php echo $tipoWidgetCambio; ?>";
					const propertyID = "<?php echo $propertyID; ?>";
					const iaWidgetID = "<?php echo $iaWidgetID; ?>";
					const humanWidgetID = "<?php echo $humanWidgetID; ?>";
					const widgetID = tipoWidgetCambio === "humano" ? humanWidgetID : iaWidgetID;
					const soporteActual = "<?php echo $soporteActual; ?>";

					// Esperar para realizar el cambio
					// console.log((new Date()).toLocaleString(), " | Esperando cambio de chat...");
					setTimeout(() => {
							// console.log("La activación del cambio se tardo ", (new Date() - tiempoInicioCambio) / 1000, " segundos");

							if(soporteActual !== tipoWidgetCambio){

								const tiempoReinicioWidget = Date.now() + tiempoEsperaWidget;
								localStorage.setItem("tiempoEsperaWR", tiempoReinicioWidget);

								// console.log((new Date()).toLocaleString(), " | Haciendo cambio de chat...");

								var iniTime = new Date();
								window.Tawk_API.minimize();

								// Verificar si hay un chat en curso
								if(window.Tawk_API.isChatOngoing()) {
									// console.log((new Date()).toLocaleString(), " | Hay un chat en curso. Finalizando el chat actual..."); // TEST
									// window.Tawk_API.minimize();
									window.Tawk_API.endChat();
								}
								// console.log((new Date()).toLocaleString(), " | Ocultando widget...");
								window.Tawk_API.hideWidget();
								// window.Tawk_API.logout();
								// console.log((new Date()).toLocaleString(), " | Cortando comunicación widget...");
								window.Tawk_API.shutdown();

								setTimeout(() => {
									window.Tawk_API.switchWidget({
									propertyId: propertyID,
									widgetId: widgetID // widgetID
								},
								function (error) {
									if (error) {
										console.error("Error al cambiar el widget:", error);
									}
									else {
										// console.log((new Date()).toLocaleString(), " | Cambio de widget realizado...");
										// console.log("Widget cambiado correctamente a " + "<?php echo $tipoWidgetCambio; ?>");
										// console.log("El cambio se tardo:  ", (new Date() - iniTime) / 1000, " segundos");
									}
								});
								localStorage.removeItem("tiempoEsperaWR");
								}, tiempoEsperaWidget); // Este tiempo no debe romperse
							}
					}, segundosParaCambio);
				<?php endif; ?>
			}
			intentosRealizados += 1;

		}, 1000);
	}

</script>
<!--End of Tawk.to Script-->
