<?php
if (session_id() == '') {
    session_start();
}
require_once('Connections/kosmos.php'); 
mysqli_select_db($kosmos, $database_kosmos);

$up_id = null;
$token = null;

// 1. Prioridad: Capturar token por URL (index.php?token=...)
if (isset($_GET['token']) && !empty($_GET['token'])) {
    $token = trim($_GET['token']);
    
    // Guardar en Cookie por 365 días (Sintaxis compatible con PHP 5.6 para setcookie)
    setcookie('kosmos_token', $token, time() + (86400 * 365), '/', '', false, true);
} 
// 2. Fallback: Buscar en la Cookie guardada previamente
elseif (isset($_COOKIE['kosmos_token']) && !empty($_COOKIE['kosmos_token'])) {
    $token = trim($_COOKIE['kosmos_token']);
}

// 3. DETERMINAR SI ES INVITADO O NO:
// Si hay un token (por GET o por Cookie), consideramos que NO es invitado.
// (Puedes combinarlo con tu validación de sesión si la tienes, por ejemplo: isset($_SESSION['user_id']) || !empty($token))
$is_logged = (!empty($token)); 
$is_guest = !$is_logged;

// 3. Validar el token de ACCESO contra la Base de Datos
if ($token) {
    $stmt_token = $kosmos->prepare("
        SELECT up.up_id, u.usu_id 
        FROM usuarios u
        INNER JOIN usuarios_perfil up ON up.usu_id = u.usu_id
        WHERE u.usu_token = ?
        LIMIT 1
    ");
    if ($stmt_token) {
        $stmt_token->bind_param("s", $token);
        $stmt_token->execute();
        $res_token = $stmt_token->get_result();

        if ($row_t = $res_token->fetch_assoc()) {
            $up_id = $row_t['up_id'];
            $_SESSION['up_id'] = $up_id;
            $_SESSION['usu_id'] = $row_t['usu_id']; // ID para vincular token de Firebase después
        }
    }
}

// 4. Fallback final: Sesión activa
if (!$up_id && isset($_SESSION['up_id'])) {
    $up_id = $_SESSION['up_id'];
}

// Inicialización de variables para evitar errores si no hay sesión
$nombre_usuario = 'Invitado';
$nombre_copropiedad = 'Plataformas KOSMOS';
$contactos_permitidos = array();
$mis_grupos = array();

// Si la sesión o token se validó correctamente, consultamos la información del usuario
if ($up_id) {
    $stmt = $kosmos->prepare("
        SELECT 
            CONCAT(e.nombres, ' ', e.apellidos) AS nom_empresa_completo,
            CONCAT(u.nombres, ' ', u.apellidos) AS nom_usuario_completo,
            u.foto_perfil AS mi_foto,
            up.cli_pertenece,
            e.logo,
            e.logop
        FROM usuarios_perfil up
        INNER JOIN usuarios u ON up.usu_id = u.usu_id
        LEFT JOIN usuarios_perfil up_emp ON up.cli_pertenece = up_emp.usu_id
        LEFT JOIN usuarios e ON up_emp.usu_id = e.usu_id
        WHERE up.up_id = ?
    ");
    if ($stmt) {
        $stmt->bind_param("i", $up_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $row_empresa = $result->fetch_assoc();

        // Ajuste PHP 5.6: Reemplazo del operador ?? por operador ternario con isset()
        $nombre_usuario = isset($row_empresa['nom_usuario_completo']) && !empty($row_empresa['nom_usuario_completo']) ? $row_empresa['nom_usuario_completo'] : 'Invitado';
        $nombre_copropiedad = isset($row_empresa['nom_empresa_completo']) && !empty($row_empresa['nom_empresa_completo']) ? $row_empresa['nom_empresa_completo'] : 'Plataformas KOSMOS';
    }

// 1. Capturamos el filtro. intval() lo convierte en número, bloqueando cualquier inyección SQL.
$filtro_perfil = isset($_GET['filtro_perfil']) ? intval($_GET['filtro_perfil']) : 0;

// 2. Construimos la consulta base (tu consulta original intacta)
$sql = "
    SELECT DISTINCT 
        CASE 
            WHEN cc.propietario_up_id = ? THEN cc.contacto_up_id 
            ELSE cc.propietario_up_id 
        END AS contacto_up_id,
        CONCAT(u.nombres, ' ', u.apellidos) AS nombre_contacto,
        u.foto_perfil AS foto_contacto,
        up.per_id,
        (
            SELECT COUNT(*) FROM mensajes_chat m 
            WHERE m.destinatario_up_id = ? 
              AND m.remitente_up_id = up.up_id 
              AND m.leido = 0
        ) AS mensajes_no_leidos,
        (
            SELECT COALESCE(SUM(file_size), 0) FROM mensajes_chat m2 
            WHERE m2.remitente_up_id = ? 
              AND m2.destinatario_up_id = up.up_id
        ) AS bytes_enviados,
        (
            SELECT COALESCE(SUM(file_size), 0) FROM mensajes_chat m3 
            WHERE m3.destinatario_up_id = ? 
              AND m3.remitente_up_id = up.up_id
        ) AS bytes_recibidos,
        (
            SELECT MAX(fecha_envio) FROM mensajes_chat m4 
            WHERE (m4.remitente_up_id = ? AND m4.destinatario_up_id = up.up_id)
               OR (m4.destinatario_up_id = ? AND m4.remitente_up_id = up.up_id)
        ) AS ultimo_mensaje_fecha
    FROM chat_contactos cc
    INNER JOIN usuarios_perfil up ON (
        (cc.propietario_up_id = ? AND cc.contacto_up_id = up.up_id) OR 
        (cc.contacto_up_id = ? AND cc.propietario_up_id = up.up_id)
    )
    INNER JOIN usuarios u ON up.usu_id = u.usu_id
    WHERE (cc.propietario_up_id = ? OR cc.contacto_up_id = ?) 
      AND up.up_id != ? 
      AND cc.estado = 'activo'
";

// 3. SOLO si existe un filtro, le pegamos la condición al SQL
if ($filtro_perfil > 0) {
    $sql .= " AND up.per_id = " . $filtro_perfil;
}

// 4. Pegamos el ordenamiento al final
$sql .= " ORDER BY ultimo_mensaje_fecha IS NULL, ultimo_mensaje_fecha DESC, nombre_contacto ASC";

// 5. Preparamos y bindeamos (SIEMPRE las mismas 11 variables)
$stmt_c = $kosmos->prepare($sql);
$stmt_c->bind_param("iiiiiiiiiii", 
    $up_id, $up_id, $up_id, $up_id, $up_id, 
    $up_id, $up_id, $up_id, $up_id, $up_id, $up_id
);


        $stmt_c->execute();
        $res_c = $stmt_c->get_result();
		
		
        while ($row_c = $res_c->fetch_assoc()) {
            $contactos_permitidos[] = $row_c;
        }

// Consultar grupos del usuario
    $stmt_g = $kosmos->prepare("
        SELECT 
            g.grupo_id, 
            g.nombre_grupo, 
            g.foto_grupo,
            (
                -- Suma de bytes que el usuario actual ha enviado a este grupo
                SELECT COALESCE(SUM(file_size), 0) 
                FROM mensajes_grupo mg_env 
                WHERE mg_env.grupo_id = g.grupo_id 
                  AND mg_env.remitente_up_id = ?
            ) AS bytes_enviados,
            (
                -- Suma de bytes que OTROS han enviado a este grupo
                SELECT COALESCE(SUM(file_size), 0) 
                FROM mensajes_grupo mg_rec 
                WHERE mg_rec.grupo_id = g.grupo_id 
                  AND mg_rec.remitente_up_id != ?
            ) AS bytes_recibidos
        FROM grupos g
        INNER JOIN grupo_miembros gm ON g.grupo_id = gm.grupo_id
        WHERE gm.up_id = ?
    ");
    
    if ($stmt_g) {
        // Ahora pasamos 3 parámetros en lugar de 1, todos corresponden al $up_id del usuario
        $stmt_g->bind_param("iii", $up_id, $up_id, $up_id);
        $stmt_g->execute();
        $res_g = $stmt_g->get_result();
        while ($row_g = $res_g->fetch_assoc()) {
            $mis_grupos[] = $row_g;
        }
    }
}

// PEGAR AQUÍ ARRIBA DEL TODO PARA QUE NUNCA FALLE
if (!function_exists('formatearBytes')) {
    function formatearBytes($bytes) {
        $bytes = floatval($bytes); // Forzamos a que sea un número seguro
        if ($bytes <= 0) return '0 B';
        $unidades = array('B', 'KB', 'MB', 'GB', 'TB');
        $pow = floor(log($bytes) / log(1024));
        $pow = min($pow, count($unidades) - 1);
        $bytes /= pow(1024, $pow);
        return round($bytes, 1) . ' ' . $unidades[$pow]; 
    }
}
?>
<!DOCTYPE html>
<html lang="es" id="html-root">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>KOSMOS Chat <?php //echo isset($nombre_copropiedad) ? '- ' . htmlspecialchars($nombre_copropiedad) : ''; ?></title>
  
  <!-- Manifest y PWA Meta Tags -->
  <link rel="manifest" href="manifest.json">
  
  <!-- Compatibilidad con iOS (Safari) -->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <meta name="apple-mobile-web-app-title" content="KOSMOS Chat">
  <link rel="apple-touch-icon" href="logos/logo_384k.png">
  <link rel="icon" type="image/png" href="imagenes/mifaviconkosmoschat.png" />
  <script src="https://cdn.tailwindcss.com"></script>
  <script>
    tailwind.config = { darkMode: 'class' };
  </script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
  
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr/dist/l10n/es.js"></script>

  <!-- 1. AUTO-LOGUEO CON LOCALSTORAGE (SE EJECUTA ANTES DE MOSTRAR ACCESO NO AUTORIZADO) -->
  <script>
  // Crear el canal de alta prioridad para Android (Heads-Up Notification)
if (window.Capacitor && window.Capacitor.isNativePlatform()) {
    const PushNotifications = window.Capacitor.Plugins.PushNotifications;

    PushNotifications.createChannel({
        id: 'kosmos_chat_channel',
        name: 'Alertas de Chat',
        description: 'Notificaciones flotantes de mensajes entrantes',
        importance: 5, // 5 = Alta / Máxima importancia (despliega banner flotante)
        visibility: 1, // 1 = Visible en pantalla de bloqueo
        sound: 'default',
        vibration: true
    }).then(() => {
        console.log('Canal de notificaciones de alta prioridad creado');
    });
}
  
  
  
  (function() {
      const urlParams = new URLSearchParams(window.location.search);
      const tokenUrl = urlParams.get('token');

      if (tokenUrl) {
          // Si entra con ?token=..., se almacena en el teléfono
          localStorage.setItem('kosmos_token', tokenUrl);
      } else {
          // Si abre la app limpia
          const savedToken = localStorage.getItem('kosmos_token');
          <?php if (!$up_id): ?>
              if (savedToken) {
                  // Redirección inmediata pasando el token del almacenamiento local
                  window.location.href = "index.php?token=" + encodeURIComponent(savedToken);
              }
          <?php endif; ?>
      }

      if ('serviceWorker' in navigator) {
          window.addEventListener('load', () => {
              navigator.serviceWorker.register('sw.js')
                  .then((reg) => { console.log('Service Worker registrado:', reg.scope); })
                  .catch((err) => { console.log('Error en Service Worker:', err); });
          });
      }
  })();
  
  
  function hacerScrollAbajo() {
  const cajaChat = document.getElementById('chat-box');
  if (!cajaChat) return;

  // 1. Intento inmediato
  cajaChat.scrollTop = cajaChat.scrollHeight;

  // 2. Intentos escalonados para dar tiempo al WebView de Android de dibujar todo
  setTimeout(() => { cajaChat.scrollTop = cajaChat.scrollHeight; }, 150);
  setTimeout(() => { cajaChat.scrollTop = cajaChat.scrollHeight; }, 400);
  setTimeout(() => { cajaChat.scrollTop = cajaChat.scrollHeight; }, 800);
}
  </script>

  <!-- 2. REGISTRO DE NOTIFICACIONES PUSH CON CAPACITOR -->
  <?php if ($up_id && isset($_SESSION['usu_id'])): ?>
  <script>
  document.addEventListener('DOMContentLoaded', async () => {
      if (window.Capacitor && window.Capacitor.isNativePlatform()) {
          const PushNotifications = window.Capacitor.Plugins.PushNotifications;
          const Badge = window.Capacitor.Plugins.Badge;

          if (PushNotifications) {
              try {
                  let permStatus = await PushNotifications.checkPermissions();

                  if (permStatus.receive === 'prompt') {
                      permStatus = await PushNotifications.requestPermissions();
                  }

                  if (permStatus.receive === 'granted') {
                      await PushNotifications.register();

                      PushNotifications.addListener('registration', (token) => {
                          console.log('Token FCM obtenido:', token.value);
                          enviarTokenAlServidor(token.value);
                      });

                      PushNotifications.addListener('pushNotificationActionPerformed', () => {
                          /*if (Badge) { Badge.set({ count: 0 }); }*/
                      });
                  }
              } catch (error) {
                  console.error('Error al inicializar PushNotifications:', error);
              }
          }
      }
  });

  function enviarTokenAlServidor(fcmToken) {
      fetch('guardar_push.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ push_token: fcmToken })
      })
      .then(res => res.json())
      .then(data => console.log('Respuesta servidor token push:', data))
      .catch(err => console.error('Error guardando token push:', err));
  }
  </script>
  <?php endif; ?>
</head>
<body class="bg-slate-200 dark:bg-slate-950 h-dvh w-screen flex justify-center items-center font-sans overflow-hidden text-slate-800 dark:text-slate-100 transition-colors duration-300">

  <audio id="chat-sound" src="https://assets.mixkit.co/active_storage/sfx/2354/2354-preview.mp3" preload="auto"></audio>

  <!-- Contenedor Principal (Siempre se renderiza) -->
  <div class="w-full max-w-7xl h-full md:h-[90vh] bg-white dark:bg-slate-900 rounded-none md:rounded-lg shadow-2xl flex overflow-hidden border border-slate-200 dark:border-slate-800 relative transition-all duration-300">
    
    <!-- ========================================== -->
    <!-- 1. SIDEBAR (COLUMNA IZQUIERDA)             -->
    <!-- ========================================== -->
    <div id="sidebar" class="w-full md:w-1/3 bg-white dark:bg-slate-900 border-r border-slate-200 dark:border-slate-800 flex flex-col h-full overflow-hidden shrink-0">
      
      <!-- Header Sidebar -->
      <div class="bg-gradient-to-r from-gray-500 to-gray-400 dark:from-slate-800 dark:to-slate-800 text-white p-3.5 font-semibold flex justify-between items-center shadow-sm shrink-0 border-b border-slate-200 dark:border-slate-700/60">
        
        <?php 
          // Blindaje contra variables no definidas para PHP 5.6
          $mi_foto = isset($row_empresa['mi_foto']) ? $row_empresa['mi_foto'] : '';
          $nom_usuario = (isset($nombre_usuario) && $nombre_usuario) ? $nombre_usuario : (isset($row_empresa['nom_usuario_completo']) ? $row_empresa['nom_usuario_completo'] : 'Invitado');
// Imprimimos un script que JavaScript podrá leer sin problemas de sintaxis
echo "<script>
    window.KOSMOS_USER_NAME = " . json_encode($nom_usuario) . ";
    window.KOSMOS_IS_GUEST = " . json_encode((bool)$is_guest) . ";
</script>";
          $cargo_bien = !empty($row_empresa);
          $dotColor = $cargo_bien ? 'bg-emerald-500' : 'bg-amber-500'; // Amber para el invitado
          $dotTitle = $cargo_bien ? 'Conectado / Sesión Activa' : 'Modo Invitado';
        ?>

        <!-- Avatar y Título -->
        <div class="flex items-center gap-2.5 cursor-pointer group min-w-0" onClick="openProfileModal()" title="Cambiar foto de perfil">
          <div class="relative flex-shrink-0">
            <?php if (!empty($mi_foto)): ?>
              <img src="<?php echo htmlspecialchars($mi_foto); ?>" class="w-9 h-9 rounded-full object-cover border-2 border-white/40 shadow-sm group-hover:scale-105 transition-transform">
            <?php else: ?>
              <div class="w-9 h-9 bg-sky-700 rounded-full flex items-center justify-center font-bold text-xs text-white border-2 border-white/40 shadow-sm group-hover:scale-105 transition-transform">
                <?php 
                  $n_arr = explode(' ', trim($nom_usuario));
                  echo strtoupper(mb_substr($n_arr[0], 0, 1) . (isset($n_arr[1]) ? mb_substr($n_arr[1], 0, 1) : ''));
                ?>
              </div>
            <?php endif; ?>
            <span class="absolute -bottom-0.5 -right-0.5 w-3.5 h-3.5 <?php echo $dotColor; ?> border-2 border-sky-600 rounded-full" title="<?php echo $dotTitle; ?>"></span>
          </div>
          <!-- Título y Nombre -->
          <div class="flex flex-col overflow-hidden">
            <span class="text-sky-400 dark:text-sky-400 font-bold text-sm truncate leading-tight"><?php echo htmlspecialchars($nom_usuario); ?></span>
            <span class="text-sky-100 dark:text-white text-xs truncate">KOSMOS Chats</span>
          </div>
        </div>
        
        <!-- Lado Derecho: Botón de Tema y Logo -->
        <div class="flex items-center gap-2.5 flex-shrink-0">
          <button id="theme-toggle" class="p-1.5 rounded-lg bg-white/20 dark:bg-slate-700/60 hover:bg-white/30 dark:hover:bg-slate-700 transition-colors text-white" title="Cambiar tema">
            <svg id="theme-toggle-light-icon" class="w-4 h-4 hidden" fill="currentColor" viewBox="0 0 20 20">
              <path d="M10 2a1 1 0 011 1v1a1 1 0 11-2 0V3a1 1 0 011-1zm4 8a4 4 0 11-8 0 4 4 0 018 0zm-.464 4.95l.707.707a1 1 0 001.414-1.414l-.707-.707a1 1 0 00-1.414 1.414zm2.12-10.607a1 1 0 010 1.414l-.706.707a1 1 0 11-1.414-1.414l.707-.707a1 1 0 011.414 0zM17 11a1 1 0 100-2h-1a1 1 0 100 2h1zm-7 4a1 1 0 011 1v1a1 1 0 11-2 0v-1a1 1 0 011-1zM5.05 6.464A1 1 0 106.465 5.05l-.708-.707a1 1 0 00-1.414 1.414l.707.707zm1.414 8.486l-.707.707a1 1 0 01-1.414-1.414l.707-.707a1 1 0 011.414 1.414zM4 11a1 1 0 100-2H3a1 1 0 100 2h1z" />
            </svg>
            <svg id="theme-toggle-dark-icon" class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
              <path d="M17.293 13.293A8 8 0 016.707 2.707a8.001 8.001 0 1010.586 10.586z" />
            </svg>
          </button>
          <div class="pl-4 border-l border-sky-400/40 dark:border-slate-700">
            <img src="logos/logo_384k.png" alt="Logo Kosmos" class="w-12 h-12 object-contain drop-shadow-sm">
          </div>
        </div>
      </div>
      
<!-- Buscador y Filtros -->
      <div class="p-3 bg-slate-100 dark:bg-slate-900 shrink-0 flex items-center gap-3 border-b border-slate-200 dark:border-slate-800">
        
        <!-- Input acortado (flex-1) -->
        <input type="text" placeholder="Buscar o empezar un chat" class="flex-1 min-w-0 text-sm p-2 rounded-lg bg-white dark:bg-slate-800 text-slate-800 dark:text-slate-200 border border-slate-300 dark:border-slate-700 placeholder-slate-400 focus:outline-none focus:border-sky-500 transition-colors">
        
        <!-- Iconos de Filtro más grandes (Estilo PlayStation) -->
        <div class="flex items-center gap-2 shrink-0">
        
<a href="index.php">
  <svg class="w-5 h-5 cursor-pointer text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200 hover:scale-110 hover:brightness-110 transition-all drop-shadow-sm" 
       fill="none" stroke="currentColor" viewBox="0 0 24 24" title="Todos">
    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 20l-3 1v-8.5L3 5h18l-3.8 4.8M17 17l4 4m0-4l-4 4" />
  </svg>
</a>
          
          <!-- Clientes (3): Triángulo Verde -->
          <a href="index.php?filtro_perfil=3">
          <svg class="w-5 h-5 cursor-pointer text-emerald-500 hover:scale-110 hover:brightness-110 transition-all drop-shadow-sm" 
               fill="none" stroke="currentColor" viewBox="0 0 24 24" title="Filtrar Clientes">
            <polygon points="12 3 22 20 2 20" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
          </a>

          <!-- Proveedores (4): Cuadrado Amarillo Quemado -->
          <a href="index.php?filtro_perfil=4">
          <svg class="w-5 h-5 cursor-pointer text-amber-500 hover:scale-110 hover:brightness-110 transition-all drop-shadow-sm" 
               fill="none" stroke="currentColor" viewBox="0 0 24 24" title="Filtrar Proveedores">
            <rect x="4" y="4" width="16" height="16" rx="3" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
		  </a>
          <!-- Colaboradores (5): Círculo Rojo -->
          <a href="index.php?filtro_perfil=5">
          <svg class="w-5 h-5 cursor-pointer text-rose-500 hover:scale-110 hover:brightness-110 transition-all drop-shadow-sm" 
               fill="none" stroke="currentColor" viewBox="0 0 24 24" title="Filtrar Colaboradores">
            <circle cx="12" cy="12" r="8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
          </a>
          <!-- Por definir (6): Rombo Azul -->
          <a href="index.php?filtro_perfil=6">
          <svg class="w-5 h-5 cursor-pointer text-sky-500 hover:scale-110 hover:brightness-110 transition-all drop-shadow-sm" 
               fill="none" stroke="currentColor" viewBox="0 0 24 24" title="Filtrar Otros">
            <polygon points="12 3 21 12 12 21 3 12" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
          </a>
        </div>
      </div>

      <!-- ÁREA DE SCROLL -->
      <div class="flex-1 overflow-y-auto">
        
        <!-- SIEMPRE MOSTRAMOS AL BOT -->
<!-- SIEMPRE MOSTRAMOS AL BOT -->
        <div onClick="openChat('Asistente Virtual', 'bot', 'imagenes/bot.png')" class="flex items-center p-3 bg-sky-50/50 dark:bg-slate-800/80 border-b border-slate-200 dark:border-slate-800 cursor-pointer hover:bg-sky-100/50 dark:hover:bg-slate-800 transition-colors">
          <div class="mr-3 flex-shrink-0">
            <img src="imagenes/bot.png" alt="Bot" class="w-12 h-12 rounded-full object-cover shadow-sm border border-slate-200 dark:border-slate-700">
          </div>
          <div class="overflow-hidden flex-1">
            <h4 class="font-semibold text-slate-800 dark:text-slate-200 text-sm">Asistente Virtual Plataformas KOSMOS</h4>
            <p class="text-xs text-slate-500 dark:text-slate-400 truncate"><?php echo htmlspecialchars(isset($nombre_copropiedad) ? $nombre_copropiedad : 'Empresa'); ?></p>
          </div>
          
          <div class="ml-2 flex-shrink-0">
            <button type="button" onClick="event.stopPropagation(); openChat('Asistente Virtual', 'bot', 'imagenes/bot.png'); openCanvasPanel('Asistente Virtual', 'imagenes/bot.png', 'bot', 'contacto');" class="w-7 h-7 bg-white hover:bg-sky-100 dark:bg-slate-800 dark:hover:bg-sky-900/60 text-sky-500 hover:text-sky-600 dark:text-sky-400 rounded flex items-center justify-center border border-sky-200 dark:border-slate-700 transition-colors shadow-sm shrink-0" title="Ver Tareas Pendientes">
              <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01"></path></svg>
            </button>
          </div>
        </div>
        
        <?php 
        // Si tiene up_id mostramos el resto de opciones de la empresa
        if ($up_id): 
        ?>
<!-- BOTÓN DE NUEVA DIFUSIÓN -->
          <div onClick="openBroadcastChat()" class="flex items-center p-3 border-b border-slate-200 dark:border-slate-800 cursor-pointer hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors">
            <div class="mr-3 flex-shrink-0">
              <img src="imagenes/difusion.png" alt="Difusión" class="w-12 h-12 rounded-full object-cover shadow-sm border border-slate-200 dark:border-slate-700">
            </div>
            <div class="overflow-hidden">
              <h4 class="font-semibold text-slate-800 dark:text-slate-200 text-sm">Nueva Difusión</h4>
              <p class="text-xs text-slate-500 dark:text-slate-400 truncate">Envía a múltiples contactos</p>
            </div>
          </div>

<!-- ========================================== -->
          <!-- CONTACTO FIJO: MIS RECORDATORIOS (TÚ)      -->
          <!-- ========================================== -->
          <?php 
            // Capturamos el ID del usuario en sesión
            $mi_id = isset($_SESSION['up_id']) ? $_SESSION['up_id'] : 0;
            $mi_foto = isset($_SESSION['foto_usuario']) ? $_SESSION['foto_usuario'] : '';
            $mi_nombre = 'Tú (Mis Recordatorios)';
          ?>
          
          <!-- MAGIA AQUÍ: Forzamos a que JavaScript conozca tu ID de forma segura -->
          <script>
            window.KOSMOS_USER_ID = "<?php echo $mi_id; ?>";
          </script>

          <div onClick="openChat('<?php echo $mi_nombre; ?>', <?php echo $mi_id; ?>, '<?php echo $mi_foto; ?>')" class="flex items-center justify-between p-3 border-b border-sky-100 dark:border-sky-900/40 cursor-pointer hover:bg-sky-50 dark:hover:bg-sky-900/20 bg-sky-50/40 dark:bg-slate-800/50 transition-colors">
            
            <div class="flex items-center overflow-hidden">
            <div class="mr-3 flex-shrink-0">
              <img src="imagenes/recordatorio.png" alt="Difusión" class="w-12 h-12 rounded-full object-cover shadow-sm border border-slate-200 dark:border-slate-700">
            </div>
              
              <div class="overflow-hidden">
                <h4 class="font-semibold text-slate-800 dark:text-slate-200 text-sm"><?php echo $mi_nombre; ?></h4>
                <p class="text-xs text-sky-600 dark:text-sky-400 truncate">Guarda notas y programa avisos</p>
              </div>
            </div>

            <!-- Botón Cuadrado de Tareas (Atajo) CORREGIDO -->
            <button type="button" onClick="event.stopPropagation(); openChat('<?php echo htmlspecialchars($mi_nombre, ENT_QUOTES, 'UTF-8'); ?>', <?php echo $mi_id; ?>, '<?php echo htmlspecialchars($mi_foto, ENT_QUOTES, 'UTF-8'); ?>'); openCanvasPanel('<?php echo htmlspecialchars($mi_nombre, ENT_QUOTES, 'UTF-8'); ?>', '<?php echo htmlspecialchars($mi_foto, ENT_QUOTES, 'UTF-8'); ?>', <?php echo $mi_id; ?>, 'contacto');" class="w-7 h-7 bg-white hover:bg-sky-100 dark:bg-slate-800 dark:hover:bg-sky-900/60 text-sky-500 hover:text-sky-600 dark:text-sky-400 rounded flex items-center justify-center border border-sky-200 dark:border-slate-700 transition-colors shadow-sm shrink-0" title="Programar Recordatorio">
              <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01"></path></svg>
            </button>
            
          </div>
          <!-- ========================================== -->

          <?php 
          // Prevenimos error en foreach si los arrays no existen
          $contactos_permitidos = isset($contactos_permitidos) && is_array($contactos_permitidos) ? $contactos_permitidos : [];
          foreach ($contactos_permitidos as $contacto): 
          ?>
<div onClick="openChat('<?php echo htmlspecialchars($contacto['nombre_contacto'], ENT_QUOTES, 'UTF-8'); ?>', <?php echo $contacto['contacto_up_id']; ?>, '<?php echo htmlspecialchars(isset($contacto['foto_contacto']) ? $contacto['foto_contacto'] : '', ENT_QUOTES, 'UTF-8'); ?>')" class="flex items-center justify-between p-3 border-b border-slate-200 dark:border-slate-800 cursor-pointer hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors">
            <div class="flex items-center overflow-hidden">
              <div class="mr-3 flex-shrink-0">
                <?php if (!empty($contacto['foto_contacto'])): ?>
                  <img src="<?php echo htmlspecialchars($contacto['foto_contacto']); ?>" alt="Foto" class="w-12 h-12 rounded-full object-cover shadow-sm border border-slate-200 dark:border-slate-700">
                <?php else: ?>
                  <div class="w-12 h-12 bg-emerald-600 rounded-full flex items-center justify-center text-white font-bold shadow-sm">
                    <?php
                      $nombres_arr = explode(' ', trim($contacto['nombre_contacto']));
                      $iniciales = mb_substr($nombres_arr[0], 0, 1) . (isset($nombres_arr[1]) ? mb_substr($nombres_arr[1], 0, 1) : '');
                      echo strtoupper($iniciales);
                    ?>
                  </div>
                <?php endif; ?>
              </div>
    
    <div class="overflow-hidden">
      <h4 class="font-semibold text-slate-800 dark:text-slate-200 text-sm"><?php echo htmlspecialchars($contacto['nombre_contacto']); ?></h4>
      
      <!-- INDICADORES DE CONSUMO DE DATOS -->
      <div class="flex items-center gap-2.5 mt-0.5 text-[10px] font-medium text-slate-500 dark:text-slate-400 truncate">
        
        <!-- Datos Recibidos (Flecha abajo Verde) -->
        <div class="flex items-center gap-0.5" title="Datos recibidos">
          <svg class="w-3.5 h-3.5 text-emerald-500 dark:text-emerald-400 drop-shadow-sm" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 13l-3 3m0 0l-3-3m3 3V8m0 13a9 9 0 110-18 9 9 0 010 18z" />
          </svg>
          <span><?php echo formatearBytes($contacto['bytes_recibidos']); ?></span>
        </div>
        
        <!-- Datos Enviados (Flecha arriba Azul) -->
        <div class="flex items-center gap-0.5" title="Datos enviados">
          <svg class="w-3.5 h-3.5 text-sky-500 dark:text-sky-400 drop-shadow-sm" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 11l3-3m0 0l3 3m-3-3v8m0 5a9 9 0 110-18 9 9 0 010 18z" />
          </svg>
          <span><?php echo formatearBytes($contacto['bytes_enviados']); ?></span>
        </div>

        <!-- CLASIFICACIÓN DE CONTACTOS (Estilo PlayStation modificado) -->
        <div class="flex items-center gap-1.5 pl-2 ml-1 border-l border-slate-300 dark:border-slate-600 shrink-0 contenedor-perfiles-<?php echo $contacto['contacto_up_id']; ?>">
          
          <!-- Clientes (3): Triángulo Verde -->
          <svg onClick="cambiarPerfil(event, <?php echo $contacto['contacto_up_id']; ?>, 3, this)" 
               class="w-3.5 h-3.5 cursor-pointer transition-colors <?php echo (isset($contacto['per_id']) && $contacto['per_id'] == 3) ? 'text-emerald-500 dark:text-emerald-400' : 'text-slate-300 dark:text-slate-600 hover:text-emerald-500 dark:hover:text-emerald-400'; ?>" 
               fill="none" stroke="currentColor" viewBox="0 0 24 24" title="Cliente">
            <polygon points="12 3 22 20 2 20" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>

          <!-- Proveedores (4): Cuadrado Amarillo Quemado -->
          <svg onClick="cambiarPerfil(event, <?php echo $contacto['contacto_up_id']; ?>, 4, this)" 
               class="w-3.5 h-3.5 cursor-pointer transition-colors <?php echo (isset($contacto['per_id']) && $contacto['per_id'] == 4) ? 'text-amber-500 dark:text-amber-400' : 'text-slate-300 dark:text-slate-600 hover:text-amber-500 dark:hover:text-amber-400'; ?>" 
               fill="none" stroke="currentColor" viewBox="0 0 24 24" title="Proveedor">
            <rect x="4" y="4" width="16" height="16" rx="3" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>

          <!-- Colaboradores (5): Círculo Rojo -->
          <svg onClick="cambiarPerfil(event, <?php echo $contacto['contacto_up_id']; ?>, 5, this)" 
               class="w-3.5 h-3.5 cursor-pointer transition-colors <?php echo (isset($contacto['per_id']) && $contacto['per_id'] == 5) ? 'text-rose-500 dark:text-rose-400' : 'text-slate-300 dark:text-slate-600 hover:text-rose-500 dark:hover:text-rose-400'; ?>" 
               fill="none" stroke="currentColor" viewBox="0 0 24 24" title="Colaborador">
            <circle cx="12" cy="12" r="8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>

          <!-- Por definir (6): Rombo Azul -->
          <svg onClick="cambiarPerfil(event, <?php echo $contacto['contacto_up_id']; ?>, 6, this)" 
               class="w-3.5 h-3.5 cursor-pointer transition-colors <?php echo (isset($contacto['per_id']) && $contacto['per_id'] == 6) ? 'text-blue-500 dark:text-blue-400' : 'text-slate-300 dark:text-slate-600 hover:text-blue-500 dark:hover:text-blue-400'; ?>" 
               fill="none" stroke="currentColor" viewBox="0 0 24 24" title="Por definir">
            <polygon points="12 3 21 12 12 21 3 12" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>

        </div>

      </div>
      </div>
  </div>
  
  <!-- CONTENEDOR DERECHO: Badge + Botón Tareas -->
  <div class="flex flex-col items-end justify-center gap-1.5 ml-2 shrink-0">
    <span id="badge-contact-<?php echo $contacto['contacto_up_id']; ?>" class="bg-emerald-500 text-white text-xs font-bold px-2 py-0.5 rounded-full shadow-sm <?php echo ($contacto['mensajes_no_leidos'] > 0) ? '' : 'hidden'; ?>">
      <?php echo $contacto['mensajes_no_leidos']; ?>
    </span>
    <!-- Botón Cuadrado de Tareas (Atajo) -->
   <button type="button" onClick="event.stopPropagation(); openChat('<?php echo htmlspecialchars($contacto['nombre_contacto'], ENT_QUOTES, 'UTF-8'); ?>', <?php echo $contacto['contacto_up_id']; ?>, '<?php echo htmlspecialchars(isset($contacto['foto_contacto']) ? $contacto['foto_contacto'] : '', ENT_QUOTES, 'UTF-8'); ?>'); openCanvasPanel('<?php echo htmlspecialchars($contacto['nombre_contacto'], ENT_QUOTES, 'UTF-8'); ?>', '<?php echo htmlspecialchars(isset($contacto['foto_contacto']) ? $contacto['foto_contacto'] : '', ENT_QUOTES, 'UTF-8'); ?>', <?php echo $contacto['contacto_up_id']; ?>, 'contacto');" class="w-7 h-7 bg-slate-100 hover:bg-sky-100 dark:bg-slate-800 dark:hover:bg-sky-900/40 text-slate-500 hover:text-sky-600 dark:text-slate-400 dark:hover:text-sky-400 rounded flex items-center justify-center border border-slate-200 dark:border-slate-700 transition-colors shadow-sm" title="Gestión de Acuerdos">
  <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01"></path></svg>
</button>
    
    
  </div>
</div>
<?php endforeach; ?>

          <?php 
          $mis_grupos = isset($mis_grupos) && is_array($mis_grupos) ? $mis_grupos : [];
foreach ($mis_grupos as $grupo): ?>
          <div onClick="openGroupChat('<?php echo htmlspecialchars($grupo['nombre_grupo'], ENT_QUOTES, 'UTF-8'); ?>', <?php echo $grupo['grupo_id']; ?>, '<?php echo htmlspecialchars(isset($grupo['foto_grupo']) ? $grupo['foto_grupo'] : '', ENT_QUOTES, 'UTF-8'); ?>')" class="flex items-center justify-between p-3 border-b border-slate-200 dark:border-slate-800 cursor-pointer hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors">
            <div class="flex items-center overflow-hidden">
              <div class="mr-3 flex-shrink-0">
                <?php if (!empty($grupo['foto_grupo'])): ?>
                  <img src="<?php echo htmlspecialchars($grupo['foto_grupo']); ?>" alt="Grupo" class="w-12 h-12 rounded-full object-cover shadow-sm border border-slate-200 dark:border-slate-700">
                <?php else: ?>
                  <div class="w-12 h-12 bg-indigo-600 rounded-full flex items-center justify-center text-white font-bold shadow-sm">
                    👥
                  </div>
                <?php endif; ?>
              </div>
              
              <div class="overflow-hidden">
                <h4 class="font-semibold text-slate-800 dark:text-slate-200 text-sm"><?php echo htmlspecialchars($grupo['nombre_grupo']); ?></h4>
                
                <!-- INDICADORES DE CONSUMO DE DATOS GRUPALES -->
                <div class="flex items-center gap-2.5 mt-0.5 text-[10px] font-medium text-slate-500 dark:text-slate-400 truncate">
                  
                  <!-- Datos Recibidos (Flecha abajo Verde) -->
                  <div class="flex items-center gap-0.5" title="Datos recibidos">
                    <svg class="w-3.5 h-3.5 text-emerald-500 dark:text-emerald-400 drop-shadow-sm" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 13l-3 3m0 0l-3-3m3 3V8m0 13a9 9 0 110-18 9 9 0 010 18z" />
                    </svg>
                    <span><?php echo formatearBytes(isset($grupo['bytes_recibidos']) ? $grupo['bytes_recibidos'] : 0); ?></span>
                  </div>
                  
                  <!-- Datos Enviados (Flecha arriba Azul) -->
                  <div class="flex items-center gap-0.5" title="Datos enviados">
                    <svg class="w-3.5 h-3.5 text-sky-500 dark:text-sky-400 drop-shadow-sm" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 11l3-3m0 0l3 3m-3-3v8m0 5a9 9 0 110-18 9 9 0 010 18z" />
                    </svg>
                    <span><?php echo formatearBytes(isset($grupo['bytes_enviados']) ? $grupo['bytes_enviados'] : 0); ?></span>
                  </div>

                </div>
              </div>
            </div>
            
            <!-- CONTENEDOR DERECHO: Badge + Botón Tareas -->
            <div class="flex flex-col items-end justify-center gap-1.5 ml-2 shrink-0">
              <span id="badge-grupo-<?php echo $grupo['grupo_id']; ?>" class="bg-indigo-500 text-white text-xs font-bold px-2 py-0.5 rounded-full shadow-sm hidden">
                0
              </span>
              <!-- Botón Cuadrado de Tareas (Atajo) -->
<button type="button" onClick="event.stopPropagation(); openGroupChat('<?php echo htmlspecialchars($grupo['nombre_grupo'], ENT_QUOTES, 'UTF-8'); ?>', <?php echo $grupo['grupo_id']; ?>, '<?php echo htmlspecialchars(isset($grupo['foto_grupo']) ? $grupo['foto_grupo'] : '', ENT_QUOTES, 'UTF-8'); ?>'); openCanvasPanel('<?php echo htmlspecialchars($grupo['nombre_grupo'], ENT_QUOTES, 'UTF-8'); ?>', '<?php echo htmlspecialchars(isset($grupo['foto_grupo']) ? $grupo['foto_grupo'] : '', ENT_QUOTES, 'UTF-8'); ?>', <?php echo $grupo['grupo_id']; ?>, 'grupo');" class="w-7 h-7 bg-slate-100 hover:bg-sky-100 dark:bg-slate-800 dark:hover:bg-sky-900/40 text-slate-500 hover:text-sky-600 dark:text-slate-400 dark:hover:text-sky-400 rounded flex items-center justify-center border border-slate-200 dark:border-slate-700 transition-colors shadow-sm" title="Gestión de Acuerdos del Grupo">
  <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01"></path></svg>
</button>
            </div>
          </div>
          <?php endforeach; ?>
          
        <?php endif; // Fin del bloque de menús para usuarios registrados ?>

      </div> <!-- FINAL DEL ÁREA DE SCROLL -->
      
      <!-- FOOTER DEL SIDEBAR -->
      <div class="bg-gradient-to-r from-gray-400 to-gray-400 dark:from-slate-800 dark:to-slate-800 text-white py-2 px-3 font-normal items-center shadow-sm shrink-0 border-t border-slate-200 dark:border-slate-700/60">
        <p class="text-[9.5px] text-slate-200 dark:text-slate-500 select-none text-center">
          &copy; <?php echo date('Y'); ?> Derechos reservados Plataformas KOSMOS by Jacques Salinas Joris
        </p>
      </div>

    </div> <!-- FIN DEL SIDEBAR -->

    <!-- ========================================== -->
    <!-- 2. ÁREA PRINCIPAL DEL CHAT (COLUMNA DERECHA) -->
    <!-- ========================================== -->
    <div id="main-chat" class="w-full flex-1 flex flex-col h-full bg-[#e8f1f8] dark:bg-[#0b141a] hidden md:flex overflow-hidden transition-all duration-300">
      
      <!-- Header Chat -->
      <div class="bg-gradient-to-r from-gray-500 to-gray-400 dark:from-slate-800 dark:to-slate-800 text-white p-3 flex items-center justify-between shadow-md shrink-0 z-10 border-b dark:border-slate-700/60">
        <div class="flex items-center min-w-0 pr-2">
          <button id="back-btn" class="mr-2 md:hidden p-1.5 hover:bg-white/20 dark:hover:bg-slate-700 rounded-full transition-colors" title="Volver a chats">
            <svg class="w-6 h-6 text-white dark:text-slate-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
            </svg>
          </button>
         <div id="chat-header-avatar" class="flex-shrink-0 mr-3">
          <div class="w-10 h-10 bg-sky-700/80 dark:bg-sky-700 rounded-full flex items-center justify-center font-bold text-sm text-white shadow-sm border border-sky-300/40">AI</div>
        </div>
          <div class="truncate">
            <h3 id="chat-title" class="font-semibold text-sm leading-tight text-white dark:text-slate-100 truncate"><?php echo htmlspecialchars(isset($nombre_copropiedad) ? $nombre_copropiedad : 'Empresa'); ?></h3>
            <p class="text-xs text-sky-100 dark:text-sky-400 truncate"><?php echo htmlspecialchars(isset($nombre_copropiedad) ? $nombre_copropiedad : 'Empresa'); ?></p>
          </div>
        </div>
        <!-- LADO DERECHO DEL HEADER: Botón Canvas + Logo -->
        <div class="flex items-center">
          <!-- Botón Cuadrado Superior en el Chat -->
          <button id="toggle-canvas-btn" onClick="toggleCanvasPanel()" class="relative flex items-center justify-center w-9 h-9 mr-3 bg-white/10 hover:bg-white/20 dark:bg-slate-700/50 dark:hover:bg-slate-700 rounded-lg transition-colors border border-white/20 dark:border-slate-600/50 shadow-sm" title="Panel de Gestión">
            <svg class="w-5 h-5 text-white dark:text-slate-200" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01"></path></svg>
            <span class="absolute -top-1 -right-1 w-2.5 h-2.5 bg-red-500 border border-white dark:border-slate-800 rounded-full animate-pulse hidden" id="canvas-alert-dot"></span>
          </button>
          
          <div class="flex-shrink-0 pl-3 border-l border-sky-400/40 dark:border-slate-700/80">
            <img src="logos/logo_384k.png" alt="Logo Kosmos" class="w-11 h-11 object-contain drop-shadow-sm">
          </div>
        </div>
      </div>
      
      <!-- Historial de Mensajes -->
      <div id="chat-box" class="flex-1 p-4 overflow-y-auto space-y-3"></div>
      
      <!-- Input Bar (TU CÓDIGO ACTUAL, COMPLETO) -->
      <div class="bg-slate-100 dark:bg-slate-900 p-3 flex items-center gap-2 border-t border-slate-200 dark:border-slate-800 shrink-0 z-10 relative">
        
        <!-- VISTA PREVIA DE ADJUNTO -->
        <div id="attachment-preview" class="hidden absolute bottom-full left-0 w-full p-2 bg-transparent z-20 pointer-events-none">
          <div class="bg-white dark:bg-slate-800 p-2.5 rounded-xl shadow-lg border border-slate-200 dark:border-slate-700 flex justify-between items-center max-w-sm ml-2 pointer-events-auto">
            <div class="flex items-center gap-2 overflow-hidden">
              <span id="attachment-icon" class="text-2xl drop-shadow-sm">📎</span>
              <div class="flex flex-col">
                <span id="attachment-text" class="text-sm text-slate-800 dark:text-slate-100 font-bold truncate">Subiendo...</span>
                <span id="attachment-subtext" class="text-[10px] text-slate-500 dark:text-slate-400">Espera un momento ⏳</span>
              </div>
            </div>
            <button id="attachment-cancel" type="button" onClick="cancelarAdjunto()" class="text-slate-400 hover:text-red-500 p-1.5 transition-colors hidden ml-3" title="Cancelar adjunto">
              <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
            </button>
          </div>
        </div>
        
        <!-- Menú de adjuntos -->
        <div id="attach-menu" class="absolute bottom-14 left-3 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-lg shadow-xl hidden flex-col py-2 z-50 w-48">
          <button onClick="triggerInput('camera-input')" class="flex items-center gap-3 px-4 py-2.5 text-sm text-slate-700 dark:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-700 transition-colors text-left w-full">
            <span class="text-lg">📷</span> Tomar Foto
          </button>
          <button onClick="triggerInput('gallery-input')" class="flex items-center gap-3 px-4 py-2.5 text-sm text-slate-700 dark:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-700 transition-colors text-left w-full">
            <span class="text-lg">🖼️</span> Galería
          </button>
          <button onClick="triggerInput('video-input')" class="flex items-center gap-3 px-4 py-2.5 text-sm text-slate-700 dark:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-700 transition-colors text-left w-full border-t border-slate-100 dark:border-slate-700">
            <span class="text-lg">🎥</span> Subir Video
          </button>
          <button onClick="triggerInput('pdf-input')" class="flex items-center gap-3 px-4 py-2.5 text-sm text-slate-700 dark:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-700 transition-colors text-left w-full border-t border-slate-100 dark:border-slate-700">
            <span class="text-lg">📄</span> Documento PDF
          </button>
        </div>

        <input type="file" id="camera-input" accept="image/*" capture="environment" class="hidden">
        <input type="file" id="gallery-input" accept="image/*" class="hidden">
        <input type="file" id="video-input" accept="video/mp4,video/webm,video/ogg,video/quicktime" class="hidden">
        <input type="file" id="pdf-input" accept="application/pdf" class="hidden">

       <!-- CONTENEDOR DE ICONOS COMPACTO -->
        <div class="flex items-center gap-0.5 shrink-0">
          
          <button id="attach-btn" type="button" class="p-1.5 text-slate-500 hover:text-sky-500 transition-colors shrink-0" title="Adjuntar archivo">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" />
            </svg>
          </button>

          <button id="schedule-btn" type="button" onClick="openScheduleModal()" class="p-1.5 text-slate-500 hover:text-indigo-500 transition-colors relative shrink-0" title="Programar mensaje">
            <svg id="schedule-icon" class="w-5 h-5 transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <span id="schedule-badge" class="absolute top-1 right-1 w-2 h-2 bg-indigo-500 rounded-full hidden border border-white dark:border-slate-900"></span>
          </button>

          <button id="mic-btn" type="button" class="p-1.5 text-slate-500 transition-colors relative shrink-0" title="Grabar nota de voz">
            <svg id="mic-icon" class="w-5 h-5 transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z" />
            </svg>
            <span id="mic-timer" class="absolute -top-10 left-1/2 -translate-x-1/2 bg-red-500 text-white text-xs font-bold px-2 py-1 rounded-full shadow-md hidden pointer-events-none whitespace-nowrap">00:00</span>
          </button>

        </div>
        <!-- FIN ICONOS -->

        <textarea 
          id="user-input" 
          rows="1" 
          autocomplete="new-password" 
          autocorrect="off" 
          autocapitalize="off" 
          spellcheck="false" 
          data-lpignore="true"
          placeholder="Escribe un mensaje aquí..." 
          class="flex-1 p-2 text-sm bg-white dark:bg-slate-800 text-slate-800 dark:text-slate-100 placeholder-slate-400 rounded-lg border border-slate-300 dark:border-slate-700 focus:outline-none focus:border-sky-500 resize-none max-h-[230px] overflow-y-auto leading-relaxed"
        ></textarea>
        
<button id="send-btn" type="button" class="bg-sky-500 dark:bg-sky-600 hover:bg-sky-600 dark:hover:bg-sky-500 text-white p-2.5 rounded-lg transition-colors flex items-center justify-center shadow-sm">
  <svg class="w-5 h-5" viewBox="0 0 20 20" fill="currentColor">
    <!-- El g/grupo centra la rotación perfectamente y ejecuta los keyframes -->
    <g transform="rotate(90 10 10)">
      <path d="M10.894 2.553a1 1 0 00-1.788 0l-7 14a1 1 0 001.169 1.409l5-1.429A1 1 0 009 15.571V11a1 1 0 112 0v4.571a1 1 0 00.725.962l5 1.428a1 1 0 001.17-1.408l-7-14z"/>
      
      <!-- Animación interna integrada con el nuevo centro (10, 10) -->
      <animateTransform 
        attributeName="transform" 
        type="rotate" 
        values="90 10 10; 75 10 10; 120 10 10; 90 10 10; 90 10 10" 
        keyTimes="0; 0.2; 0.5; 0.7; 1" 
        dur="3s" 
        repeatCount="indefinite" 
      />
    </g>
  </svg>
</button>
      </div>
      
      <!-- Franja de Derechos Reservados Chat Principal -->
      <div class="pb-2 text-center shrink-0">
        <p class="text-[10px] text-slate-400 dark:text-slate-500 select-none">
          &copy; <?php echo date('Y'); ?> Derechos reservados Plataformas KOSMOS by Jacques Salinas Joris
        </p>
      </div>
    </div>
    <!-- FIN MAIN CHAT -->

<!-- ========================================== -->
    <!-- 3. PANEL DE GESTIÓN (CANVAS)               -->
    <!-- ========================================== -->
    <div id="agreements-canvas" class="w-full md:w-[350px] lg:w-[400px] bg-slate-50 dark:bg-slate-900 border-l border-slate-200 dark:border-slate-800 flex-col h-full hidden absolute md:relative right-0 z-50 md:z-0 shadow-2xl md:shadow-none transition-transform duration-300 transform translate-x-full shrink-0">
      
      <!-- Header Canvas -->
      <div class="bg-gradient-to-r from-gray-500 to-gray-400 dark:from-slate-800 dark:to-slate-800 text-white p-3 flex items-center justify-between shadow-md shrink-0 z-10 border-b dark:border-slate-700/60">
        
        <!-- Lado Izquierdo: Botón de cierre (<) + Avatar + Títulos -->
        <div class="flex items-center min-w-0 pr-2">
          
          <!-- Botón de Retroceso / Cierre (<) -->
          <button onClick="closeCanvasPanel()" class="mr-2 p-1.5 hover:bg-white/20 dark:hover:bg-slate-700 rounded-full transition-colors" title="Cerrar espacio de trabajo">
            <svg class="w-6 h-6 text-white dark:text-slate-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
            </svg>
          </button>
          
          <!-- Avatar Dinámico del Contacto -->
          <div id="canvas-avatar-container" class="hidden flex-shrink-0 mr-3 w-10 h-10 rounded-full overflow-hidden border border-sky-300/40 shadow-sm">
            <img id="canvas-contact-photo" src="" class="w-full h-full object-cover">
          </div>

          <!-- Títulos -->
          <div class="truncate">
            <h3 id="canvas-contact-name" class="font-semibold text-sm leading-tight text-white dark:text-slate-100 truncate">Gestión de Acuerdos</h3>
            <p class="text-xs text-sky-100 dark:text-sky-400 truncate">Espacio de Trabajo</p>
          </div>
        </div>

        <!-- Lado Derecho: Logo de KOSMOS -->
        <div class="flex-shrink-0 pl-4 border-l border-sky-400/40 dark:border-slate-700 ml-2">
          <img src="logos/logo_384k.png" alt="Logo Kosmos" class="w-12 h-12 object-contain drop-shadow-sm">
        </div>
      </div>

      <!-- ESPACIO DE TRABAJO TIPO CARPETAS (FOLDER TABS) -->
      <div class="flex flex-col flex-1 p-3 overflow-hidden">
        
        <!-- Pestañas Superiores (Tabs Carrusel) -->
        <div class="flex items-end px-1 relative z-10 w-full">
  
          <!-- Botón Izquierda (Oculto por defecto) -->
          <button id="scroll-left-btn" onClick="scrollTabs(-1)" class="hidden relative px-2 py-2 text-slate-500 bg-slate-200 hover:bg-slate-300 dark:bg-slate-700 dark:hover:bg-slate-600 rounded-tl-lg shadow-inner z-30 transition-all border-r border-slate-300 dark:border-slate-600 h-[36px] flex items-center justify-center">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M15 19l-7-7 7-7" /></svg>
          </button>

          <!-- Contenedor Scrollable -->
          <div id="tabs-scroll-container" class="flex space-x-1 overflow-x-auto scroll-smooth flex-1 no-scrollbar h-[36px]">
            <!-- Tab: Chats -->
            <button id="tab-btn-chats" onClick="switchFolderTab('chats')" class="tab-btn relative px-3 py-1.5 text-xs md:text-sm font-bold text-sky-600 dark:text-sky-400 bg-white dark:bg-slate-800 rounded-t-lg border-t-2 border-sky-500 shadow-[0_-2px_4px_rgba(0,0,0,0.05)] z-20 transition-all duration-200 whitespace-nowrap flex items-center gap-1.5 shrink-0">
              <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"/></svg> Chats
            </button>
            <!-- Tab: Acuerdos -->
            <button id="tab-btn-acuerdos" onClick="switchFolderTab('acuerdos')" class="tab-btn relative px-3 py-1.5 text-xs md:text-sm font-medium text-slate-500 dark:text-slate-400 bg-slate-200 hover:bg-slate-300 dark:bg-slate-700 dark:hover:bg-slate-600 rounded-t-lg shadow-inner z-0 transition-all duration-200 whitespace-nowrap flex items-center gap-1.5 shrink-0">
              <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg> Acuerdos
            </button>
            <!-- Tab: Tareas -->
            <button id="tab-btn-tareas" onClick="switchFolderTab('tareas')" class="tab-btn relative px-3 py-1.5 text-xs md:text-sm font-medium text-slate-500 dark:text-slate-400 bg-slate-200 hover:bg-slate-300 dark:bg-slate-700 dark:hover:bg-slate-600 rounded-t-lg shadow-inner z-0 transition-all duration-200 whitespace-nowrap flex items-center gap-1.5 shrink-0">
              <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"/></svg> Tareas
            </button>
            <!-- Tab: Archivos -->
            <button id="tab-btn-archivos" onClick="switchFolderTab('archivos')" class="tab-btn relative px-3 py-1.5 text-xs md:text-sm font-medium text-slate-500 dark:text-slate-400 bg-slate-200 hover:bg-slate-300 dark:bg-slate-700 dark:hover:bg-slate-600 rounded-t-lg shadow-inner z-0 transition-all duration-200 whitespace-nowrap flex items-center gap-1.5 shrink-0">
              <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"/></svg> Archivos
            </button>
            <!-- Tab: Cotizaciones -->
            <button id="tab-btn-cotizaciones" onClick="switchFolderTab('cotizaciones')" class="tab-btn relative px-3 py-1.5 text-xs md:text-sm font-medium text-slate-500 dark:text-slate-400 bg-slate-200 hover:bg-slate-300 dark:bg-slate-700 dark:hover:bg-slate-600 rounded-t-lg shadow-inner z-0 transition-all duration-200 whitespace-nowrap flex items-center gap-1.5 shrink-0">
              <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg> Cotizaciones
            </button>
            <!-- Tab: Notas -->
            <button id="tab-btn-notas" onClick="switchFolderTab('notas')" class="tab-btn relative px-3 py-1.5 text-xs md:text-sm font-medium text-slate-500 dark:text-slate-400 bg-slate-200 hover:bg-slate-300 dark:bg-slate-700 dark:hover:bg-slate-600 rounded-t-lg shadow-inner z-0 transition-all duration-200 whitespace-nowrap flex items-center gap-1.5 shrink-0">
              <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg> Notas
            </button>
            <!-- Tab: Enlaces -->
            <button id="tab-btn-enlaces" onClick="switchFolderTab('enlaces')" class="tab-btn relative px-3 py-1.5 text-xs md:text-sm font-medium text-slate-500 dark:text-slate-400 bg-slate-200 hover:bg-slate-300 dark:bg-slate-700 dark:hover:bg-slate-600 rounded-t-lg shadow-inner z-0 transition-all duration-200 whitespace-nowrap flex items-center gap-1.5 shrink-0">
              <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"/></svg> Enlaces
            </button>
          </div>

          <!-- Botón Derecha -->
          <button id="scroll-right-btn" onClick="scrollTabs(1)" class="relative px-2 py-2 text-slate-500 bg-slate-200 hover:bg-slate-300 dark:bg-slate-700 dark:hover:bg-slate-600 rounded-tr-lg shadow-inner z-30 transition-all border-l border-slate-300 dark:border-slate-600 h-[36px] flex items-center justify-center">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" /></svg>
          </button>
          
        </div>

        <!-- CSS para ocultar la barra de scroll en navegadores Webkit -->
        <style>
          .no-scrollbar::-webkit-scrollbar {
            display: none;
          }
          .no-scrollbar {
            -ms-overflow-style: none;  /* IE and Edge */
            scrollbar-width: none;  /* Firefox */
          }
        </style>

        <!-- Cuerpo Principal de la Carpeta -->
        <div class="bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-b-xl rounded-tr-xl shadow-sm flex-1 overflow-y-auto flex flex-col relative z-20 -mt-[1px] p-4" onscroll="handleCanvasScroll(this)">
          
          <!-- CONTENEDORES PARA CADA PESTAÑA LISTOS PARA RECIBIR DATOS -->
          <div id="content-chats" class="tab-content flex flex-col gap-3"></div>
          <div id="content-acuerdos" class="tab-content hidden flex flex-col gap-3"></div>
          <div id="content-tareas" class="tab-content hidden flex flex-col gap-3"></div>
          <div id="content-archivos" class="tab-content hidden flex flex-col gap-3"></div>
          <div id="content-cotizaciones" class="tab-content hidden flex flex-col gap-3"></div>
          <div id="content-notas" class="tab-content hidden flex flex-col gap-3"></div>
          <div id="content-enlaces" class="tab-content hidden flex flex-col gap-3"></div>

        </div>
      </div>
              
      <!-- FOOTER DEL CANVAS -->
      <div class="bg-gradient-to-r from-gray-400 to-gray-400 dark:from-slate-800 dark:to-slate-800 text-white py-2 px-3 font-normal items-center shadow-sm shrink-0 border-t border-slate-200 dark:border-slate-700/60">
        <p class="text-[9.5px] text-slate-200 dark:text-slate-500 select-none text-center">
          &copy; <?php echo date('Y'); ?> Derechos reservados Plataformas KOSMOS by Jacques Salinas Joris
        </p>
      </div>
      
      <!-- Script para la lógica de las carpetas y visualización móvil -->
      <script>
        // --- LÓGICA DE PAGINACIÓN HORIZONTAL ---
        const tabContainer = document.getElementById('tabs-scroll-container');
        const leftBtn = document.getElementById('scroll-left-btn');
        const rightBtn = document.getElementById('scroll-right-btn');

        function scrollTabs(direction) {
          const scrollAmount = tabContainer.clientWidth * 0.8; 
          tabContainer.scrollBy({ left: scrollAmount * direction, behavior: 'smooth' });
        }

        function updateScrollButtons() {
          if (tabContainer.scrollLeft > 0) leftBtn.classList.remove('hidden');
          else leftBtn.classList.add('hidden');

          if (Math.ceil(tabContainer.scrollLeft + tabContainer.clientWidth) >= tabContainer.scrollWidth - 2) {
            rightBtn.classList.add('hidden');
          } else {
            rightBtn.classList.remove('hidden');
          }
        }

        if (tabContainer) {
            tabContainer.addEventListener('scroll', updateScrollButtons);
            window.addEventListener('resize', updateScrollButtons);
            setTimeout(updateScrollButtons, 300);
        }

        // --- LÓGICA DE PESTAÑAS (SWITCH TAB) CONECTADA A LA BASE DE DATOS ---
 // Variables globales para el Canvas
let canvasMostrarTodos = false;
let canvasOffset = 0;
const canvasLimite = 15;
let canvasCargando = false;
let canvasHayMas = true;
let canvasCarpetaActual = '';

function switchFolderTab(tabName) {
  const tabs = document.querySelectorAll('.tab-btn');
  const contents = document.querySelectorAll('.tab-content');

  // Lógica de Doble Clic (Toggle)
  if (canvasCarpetaActual === tabName && tabName !== 'chats') {
    canvasMostrarTodos = !canvasMostrarTodos; // Alternar entre pendientes/todos
  } else {
    canvasMostrarTodos = false; // Por defecto siempre pendientes
    canvasCarpetaActual = tabName;
  }

  // Resetear estilos de todos los botones
  tabs.forEach(btn => {
    btn.className = "tab-btn relative px-3 py-1.5 text-xs md:text-sm font-medium text-slate-500 dark:text-slate-400 bg-slate-200 hover:bg-slate-300 dark:bg-slate-700 dark:hover:bg-slate-600 rounded-t-lg shadow-inner z-0 transition-all duration-200 whitespace-nowrap flex items-center gap-1.5 shrink-0";
    // Resetear el SVG a su color apagado
    const icon = btn.querySelector('svg');
    if(icon) icon.className = "w-4 h-4 text-slate-500 dark:text-slate-400";
  });
  
  contents.forEach(content => content.classList.add('hidden'));

  const activeBtn = document.getElementById('tab-btn-' + tabName);
  const activeContent = document.getElementById('content-' + tabName);
  
  if (activeBtn) {
    activeBtn.className = "tab-btn relative px-3 py-1.5 text-xs md:text-sm font-bold bg-white dark:bg-slate-800 rounded-t-lg border-t-2 border-sky-500 shadow-[0_-2px_4px_rgba(0,0,0,0.05)] z-20 transition-all duration-200 whitespace-nowrap flex items-center gap-1.5 shrink-0";
    
    // Si estamos mostrando TODOS, iluminamos el ícono y el texto en Verde (o Ámbar). Si no, normal (Sky)
    const icon = activeBtn.querySelector('svg');
    if (canvasMostrarTodos) {
      activeBtn.classList.add('text-emerald-600', 'dark:text-emerald-400');
      if(icon) icon.className = "w-4 h-4 text-emerald-500 drop-shadow-[0_0_5px_rgba(16,185,129,0.8)]";
    } else {
      activeBtn.classList.add('text-sky-600', 'dark:text-sky-400');
      if(icon) icon.className = "w-4 h-4 text-sky-500";
    }

    activeBtn.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
  }

  if (activeContent) {
    activeContent.classList.remove('hidden');
    if (tabName !== 'chats') {
        // Al cambiar de tab (o alternar), forzamos un RESET de la lista (offset 0)
        cargarMensajesCanvas(tabName, 'content-' + tabName, true);
    }
  }
}
      </script>
    </div>
    <!-- FIN CANVAS -->

  </div>

  <!-- SCRIPT QUE SE EJECUTA SÓLO SI EL USUARIO NO ESTÁ REGISTRADO -->
  <?php if (!$up_id): ?>
  <script>
    document.addEventListener('DOMContentLoaded', function() {
      // 1. Dispara el chat con el bot en cuanto carga la pantalla
      openChat('Asistente Virtual', 'bot');
      
      // 2. Un pequeño truco opcional para móviles: Ocultar el botón "Volver" del header
      // Así evitamos que el invitado pueda ir al sidebar vacío.
      var backBtn = document.getElementById('back-btn');
      if (backBtn) {
        backBtn.style.display = 'none';
      }
    });
  </script>
  <?php endif; ?>

  <!-- MODAL DE IMAGEN AMPLIADA -->
  <div id="image-modal" class="fixed inset-0 z-50 bg-black/95 hidden overflow-auto flex items-center justify-center p-2">
    <button onClick="closeImageModal()" class="fixed top-4 right-4 z-50 bg-slate-800/90 text-white w-12 h-12 rounded-full flex items-center justify-center text-3xl font-bold hover:bg-slate-700 transition-colors cursor-pointer shadow-xl">&times;</button>
    <a id="download-modal-btn" href="" download="imagen_chat.jpg" class="fixed bottom-6 right-6 z-50 bg-sky-600/90 text-white w-14 h-14 rounded-full flex items-center justify-center hover:bg-sky-500 transition-colors cursor-pointer shadow-xl" title="Descargar imagen">
      <svg class="w-7 h-7" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
      </svg>
    </a>
    <div class="min-w-full min-h-full flex items-center justify-center p-4">
      <img id="modal-img" src="" style="touch-action: none; transform-origin: center center;" class="max-w-full max-h-[90vh] w-auto h-auto object-contain rounded-lg shadow-2xl transition-transform duration-75 select-none">
    </div>
  </div>

  <script>
  
  function iniciarChat(mensaje) {
    // 1. Apuntamos al textarea correcto usando tu ID 'user-input'
    const inputCaja = document.getElementById('user-input'); 
    
    // 2. Apuntamos a tu botón de enviar
    const botonEnviar = document.getElementById('send-btn'); 

    if (inputCaja && botonEnviar) {
        // Escribe "Hola" en la caja
        inputCaja.value = mensaje; 
        
        // Simula el clic en el botón de enviar
        botonEnviar.click(); 
        
        // Desactiva el botón "Empecemos" para que no se envíe dos veces
        event.target.disabled = true;
        event.target.classList.add('opacity-50', 'cursor-not-allowed');
    }
}
  
  
  
    // ESTADOS GLOBALES
    let chatType = 'bot';     
    let currentId = null;     
    let activeCategory = '';
    const processedMessageIds = new Set();
    const currentUserId = <?php echo json_encode($up_id); ?>;
    const misGruposData = <?php echo json_encode($mis_grupos); ?>;
	const misContactosData = <?php echo json_encode($contactos_permitidos); ?>;
    let firstGroupPollDone = false;
	//nuevas
let offsetMensajes = 0;
const limiteMensajes = 10;
let cargandoHistorial = false;
let hayMasMensajes = true;

    // VARIABLES DE GRABACIÓN DE AUDIO
    let mediaRecorder = null;
    let audioChunks = [];
    let isRecording = false;
    let recordInterval = null;
    let recordSeconds = 0;

    // DOM Elements
    const sidebar = document.getElementById('sidebar');
    const mainChat = document.getElementById('main-chat');
    const backBtn = document.getElementById('back-btn');
    const chatBox = document.getElementById('chat-box');
    const userInput = document.getElementById('user-input');
    const sendBtn = document.getElementById('send-btn');
    const htmlRoot = document.getElementById('html-root');
    const themeToggleBtn = document.getElementById('theme-toggle');
    const darkIcon = document.getElementById('theme-toggle-dark-icon');
    const lightIcon = document.getElementById('theme-toggle-light-icon');

/*    document.addEventListener("DOMContentLoaded", () => {
      if ("Notification" in window && Notification.permission !== "granted") {
        Notification.requestPermission();
      }
      openChat('Asistente Virtual', 'bot');
    });*/

	document.addEventListener("DOMContentLoaded", () => {
  if ("Notification" in window && Notification.permission !== "granted") {
    Notification.requestPermission();
  }
  
  // En pantallas de escritorio (PC) abre el bot por defecto
  if (window.innerWidth >= 768) {
    openChat('Asistente Virtual', 'bot');
  } 
  // En celulares, garantiza que el Sidebar (Contactos) sea visible al entrar
  else {
    sidebar.classList.remove('hidden');
    mainChat.classList.add('hidden');
    mainChat.classList.remove('flex');
    chatType = 'bot';
    currentId = null;
  }
});


// Inicialización del tema al cargar la página
if (localStorage.getItem('theme') === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
  htmlRoot.classList.add('dark');
  lightIcon.classList.remove('hidden'); // Muestra el Sol
  darkIcon.classList.add('hidden');     // Oculta la Luna
} else {
  htmlRoot.classList.remove('dark');
  darkIcon.classList.remove('hidden');  // ✅ CORREGIDO: Muestra la Luna
  lightIcon.classList.add('hidden');    // ✅ CORREGIDO: Oculta el Sol
}

    themeToggleBtn.addEventListener('click', () => {
      if (htmlRoot.classList.contains('dark')) {
        htmlRoot.classList.remove('dark');
        localStorage.setItem('theme', 'light');
        darkIcon.classList.remove('hidden');
        lightIcon.classList.add('hidden');
      } else {
        htmlRoot.classList.add('dark');
        localStorage.setItem('theme', 'dark');
        lightIcon.classList.remove('hidden');
        darkIcon.classList.add('hidden');
      }
    });

async function openChat(contactName, target = 'bot', fotoUrl = '') {
        if (target === 'bot') {
            chatType = 'bot';
            currentId = 'bot';
        } else {
            chatType = 'user';
            currentId = target;
        }
        
        document.getElementById('chat-title').innerText = contactName;

        // --- ACTUALIZAR AVATAR EN EL HEADER DEL CHAT ---
    const headerAvatarEl = document.getElementById('chat-header-avatar');
    if (headerAvatarEl) {
	// Verificamos si el chat abierto es el tuyo (Mis Recordatorios)
        const myId = window.KOSMOS_USER_ID || document.body.getAttribute('data-my-id') || null;
        
        if (myId !== null && String(target) === String(myId)) {
             headerAvatarEl.innerHTML = `<div class="mr-3 flex-shrink-0">
            <img src="imagenes/recordatorio.png" alt="Difusión" class="w-12 h-12 rounded-full object-cover shadow-sm border border-slate-200 dark:border-slate-700">
          </div>`;
        } else if (target === 'bot') {
            headerAvatarEl.innerHTML = `<div class="mr-3 flex-shrink-0">
            <img src="imagenes/bot.png" alt="Difusión" class="w-12 h-12 rounded-full object-cover shadow-sm border border-slate-200 dark:border-slate-700">
          </div>`;
        } else if (fotoUrl && fotoUrl.trim() !== '') {
            // AQUÍ ESTÁ LA MAGIA: Agregamos onclick="openImageModal(...)" y cursor-pointer
            headerAvatarEl.innerHTML = `<img src="${fotoUrl}" onclick="openImageModal('${fotoUrl}')" class="w-10 h-10 rounded-full object-cover shadow-sm border border-sky-300/40 cursor-pointer hover:opacity-80 transition-opacity" title="Ver foto de perfil">`;
        } else {
            const nombresArr = contactName.split(' ');
            const iniciales = (nombresArr[0]?.[0] || '') + (nombresArr[1]?.[0] || '');
            headerAvatarEl.innerHTML = `<div class="w-10 h-10 bg-emerald-600 rounded-full flex items-center justify-center font-bold text-sm text-white shadow-sm">${iniciales.toUpperCase()}</div>`;
        }
    }

// ====================================================
    // NUEVO: SINCRONIZAR EL PANEL DE TAREAS Y EL BOTÓN SUPERIOR
    // ====================================================
    // 1. Calculamos el ID numérico (si es bot, le pasamos 0 para evitar errores)
    let idCanvas = (target === 'bot') ? 0 : target;
    
    // 2. Si el panel ya está abierto, lo actualizamos en segundo plano
    const canvas = document.getElementById('agreements-canvas');
    if (canvas && !canvas.classList.contains('hidden')) {
        openCanvasPanel(contactName, fotoUrl, idCanvas, 'contacto');
    }

    // 3. ACTUALIZAMOS EL BOTÓN SUPERIOR DEL CHAT
    const btnTareas = document.getElementById('toggle-canvas-btn');
    if (btnTareas) {
        // Escapamos comillas simples en el nombre por seguridad (ej. O'Connor)
        const safeName = contactName.replace(/'/g, "\\'");
        // Inyectamos la función completa al botón
        btnTareas.setAttribute('onclick', `openCanvasPanel('${safeName}', '${fotoUrl}', ${idCanvas}, 'contacto')`);
    }
    // ====================================================etch o cargas los mensajes) ...
    // ----------------------------------------------
        // ----------------------------------------------

        chatBox.innerHTML = '';

        if (chatType === 'bot') {
            chatBox.innerHTML = `
<div class="flex justify-start w-full mb-3">
                <div class="bg-white dark:bg-[#202c33] text-slate-800 dark:text-slate-200 p-3 rounded-2xl rounded-bl-none border-r-4 border-r-sky-500 dark:border-r-sky-400 max-w-xs md:max-w-md shadow-sm border border-slate-100 dark:border-slate-700/40 text-sm">
                  
                  <!-- MANITO ANIMADA -->
                  ¡Hola 
                  <svg class="w-6 h-6 inline-block align-bottom mx-1 overflow-visible" viewBox="0 0 24 24" fill="#FBBF24" xmlns="http://www.w3.org/2000/svg">
                    <g>
                      <path d="M13.5 24q-2.725 0-5.062-1.375T4.6 19.1l-4.1-4.15q-.3-.3-.413-.675T0 13.525q0-.375.125-.75t.375-.675q.55-.55 1.35-.575t1.4.525L6 14.8V4.5q0-.625.438-1.062T7.5 3q.625 0 1.063.438T9 4.5v6h1V3.5q0-.625.438-1.062T11.5 2q.625 0 1.063.438T13 3.5v7h1V2.5q0-.625.438-1.062T15.5 1q.625 0 1.063.438T17 2.5v8h1V5.5q0-.625.438-1.062T19.5 4q.625 0 1.063.438T21 5.5v10.35q0 3.4-2.363 5.775T13.5 24Z"/>
                      <animateTransform attributeName="transform" type="rotate" values="0 12 22; -15 12 22; 20 12 22; -10 12 22; 15 12 22; 0 12 22; 0 12 22" keyTimes="0; 0.15; 0.3; 0.45; 0.6; 0.75; 1" dur="2.5s" repeatCount="indefinite" />
                    </g>
                  </svg>
                  
                  <strong><?php echo htmlspecialchars((isset($nombre_usuario) && $nombre_usuario) ? $nombre_usuario : 'Invitado'); ?></strong>!<br>
                  
                  Bienvenido al asistente de <strong><?php echo htmlspecialchars(isset($nombre_copropiedad) ? $nombre_copropiedad : 'Plataformas KOSMOS'); ?></strong>.<br><br>
                  
                  <!-- NUEVO BOTÓN DE ACCIÓN INTERACTIVO -->
                  <div class="flex items-center gap-3 mt-1">
<button type="button" onclick="iniciarChat('Hola')" class="bg-sky-500 hover:bg-sky-600 dark:bg-sky-600 dark:hover:bg-sky-500 text-white font-medium py-1.5 pl-5 pr-4 rounded-full shadow-md transition-transform transform hover:scale-105 flex items-center justify-center text-sm outline-none">
                      Empecemos 
                      
                      <!-- COHETE VECTORIZADO CON AJUSTE DE POSICIÓN (Arriba y a la derecha) -->
                      <svg class="w-5 h-5 ml-2.5 -translate-y-0.5 inline-block" viewBox="0 0 64 64" xmlns="http://www.w3.org/2000/svg">
                        <g transform="rotate(45 32 32)">
                          <path d="M24 54 Q32 70 32 70 Q32 70 40 54 Q32 60 24 54 Z" fill="#FACC15" />
                          <path d="M20 36 L6 50 L6 60 L20 50 Z" fill="#EF4444" />
                          <path d="M44 36 L58 50 L58 60 L44 50 Z" fill="#EF4444" />
                          <path d="M20 24 L44 24 L44 44 C44 52 38 56 32 56 C26 56 20 52 20 44 Z" fill="#CBD5E1" />
                          <path d="M29 50 L35 50 L33 62 L31 62 Z" fill="#DC2626" />
                          <path d="M32 4 C40 10 44 20 44 24 L20 24 C20 20 24 10 32 4 Z" fill="#EF4444" />
                          <circle cx="32" cy="34" r="7" fill="#94A3B8" />
                          <circle cx="32" cy="34" r="3.5" fill="#1E293B" />
                        </g>
                      </svg>
                    </button>
                    
                    <!-- CARITA DEL BOT PARPADEANDO AL LADO DEL BOTÓN -->
                    <svg class="w-10 h-10 inline-block align-middle" viewBox="0 0 72 72" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M12 36C12 19.4315 25.4315 6 42 6H48C64.5685 6 78 19.4315 78 36V40C78 48.8366 70.8366 56 62 56H28C19.1634 56 12 48.8366 12 40V36Z" fill="#94A3B8" transform="scale(0.8) translate(4, 4)"/>
                      <rect x="16" y="17" width="40" height="26" rx="9" fill="#0F172A" />
                      <path d="M30 35C30 37.5 33 39 36 39C39 39 42 37.5 42 35" stroke="#38BDF8" stroke-width="2.5" stroke-linecap="round"/>
                      <g>
                        <circle cx="27" cy="27" r="4.5" fill="#38BDF8">
                          <animate attributeName="cy" values="27; 27; 26; 27; 27" keyTimes="0; 0.85; 0.9; 0.95; 1" dur="4s" repeatCount="indefinite"/>
                          <animate attributeName="r" values="4.5; 4.5; 0.5; 4.5; 4.5" keyTimes="0; 0.85; 0.9; 0.95; 1" dur="4s" repeatCount="indefinite"/>
                        </circle>
                        <circle cx="45" cy="27" r="4.5" fill="#38BDF8">
                          <animate attributeName="cy" values="27; 27; 26; 27; 27" keyTimes="0; 0.85; 0.9; 0.95; 1" dur="4s" repeatCount="indefinite"/>
                          <animate attributeName="r" values="4.5; 4.5; 0.5; 4.5; 4.5" keyTimes="0; 0.85; 0.9; 0.95; 1" dur="4s" repeatCount="indefinite"/>
                        </circle>
                      </g>
                    </svg>
                  </div>

                  <span class="block text-[10px] text-slate-400 dark:text-slate-400 text-right mt-2">${new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</span>
                </div>
              </div>
            `;
        } else {
            const badgeEl = document.getElementById(`badge-contact-${currentId}`);
            if (badgeEl) {
              badgeEl.innerText = '0';
              badgeEl.classList.add('hidden');
            }
            actualizarBadgeNativo(); 

            try {
              // Reseteamos el paginador al entrar a un nuevo chat
              offsetMensajes = 0;
              hayMasMensajes = true;
              const response = await fetch(`cargar_historial.php?contacto=${currentId}&offset=${offsetMensajes}`);
              const data = await response.json();

              if (data.status === 'success' && data.messages.length > 0) {
                data.messages.forEach(msg => {
                  const soyYo = parseInt(msg.remitente_up_id) !== parseInt(currentId);
				  appendMessageDb(msg.mensaje, soyYo, msg.fecha_envio, false, msg.leido == 1, (msg.msj_id || msg.id), (msg.carpeta || ''), (msg.carpeta_estado || 0));
                  processedMessageIds.add(msg.msj_id);
                });
                
                setTimeout(() => {
                  hacerScrollAbajo();
                }, 100);

                await fetch('marcar_leidos.php', {
                  method: 'POST',
                  headers: { 'Content-Type': 'application/json' },
                  body: JSON.stringify({ remitente: currentId })
                });
              } else {
                chatBox.innerHTML = `
                  <div class="flex justify-center my-4">
                    <span class="text-xs bg-slate-200 dark:bg-slate-800 text-slate-500 dark:text-slate-400 px-3 py-1 rounded-full shadow-sm">
                      💬 Inicia la conversación con ${contactName}
                    </span>
                  </div>
                `;
              }
            } catch (error) {
              console.error("Error al cargar historial", error);
            }
        }

        if (window.innerWidth < 768) {
            sidebar.classList.add('hidden');
            mainChat.classList.remove('hidden');
            mainChat.classList.add('flex');
        }
        hacerScrollAbajo();
    }

function openGroupChat(groupName, grupoId, fotoUrl = '') {
      chatType = 'group';
      currentId = grupoId;
      document.getElementById('chat-title').innerText = groupName;
      
      // --- AVATAR EN HEADER CON GESTIÓN DE FOTO DE GRUPO ---
      const headerAvatarEl = document.getElementById('chat-header-avatar');
      if (headerAvatarEl) {
          if (fotoUrl && fotoUrl.trim() !== '') {
              // CAMBIO: Ahora abre el modal para cambiar foto en lugar de solo ampliarla
              headerAvatarEl.innerHTML = `
                <img src="${fotoUrl}" 
                     onclick="openGroupProfileModal(${grupoId}, '${fotoUrl}')" 
                     class="w-10 h-10 rounded-full object-cover shadow-sm border border-indigo-300/40 cursor-pointer hover:opacity-80 transition-opacity" 
                     title="Cambiar foto del grupo">`;
          } else {
              // Si no tiene foto, abre el mismo modal pero desde el ícono
              headerAvatarEl.innerHTML = `
                <div onclick="openGroupProfileModal(${grupoId}, '${fotoUrl}')" 
                     class="w-10 h-10 bg-indigo-600 hover:bg-indigo-500 transition-colors rounded-full flex items-center justify-center font-bold text-lg text-white shadow-sm border border-indigo-300/40 cursor-pointer" 
                     title="Subir foto del grupo">👥</div>`;
          }
      }
      
      const badgeEl = document.getElementById(`badge-grupo-${grupoId}`);
      if (badgeEl) {
        badgeEl.innerText = '0';
        badgeEl.classList.add('hidden');
      }
      actualizarBadgeNativo();

      cargarHistorialGrupo(grupoId);

      if (window.innerWidth < 768) {
        sidebar.classList.add('hidden');
        mainChat.classList.remove('hidden');
        mainChat.classList.add('flex');
      }
    }
	
	
// --- LÓGICA DE DIFUSIÓN ---
    function openBroadcastChat() {
        chatType = 'broadcast';
        currentId = null;
        
        document.getElementById('chat-title').innerText = 'Nueva Difusión';
        
        const headerAvatarEl = document.getElementById('chat-header-avatar');
        if (headerAvatarEl) {
           // headerAvatarEl.innerHTML = `<div class="w-10 h-10 bg-purple-600 rounded-full flex items-center justify-center text-white text-lg shadow-sm">📢</div>`;
		   headerAvatarEl.innerHTML = `<img src="imagenes/difusion.png" class="w-10 h-10 rounded-full object-cover shadow-sm border border-purple-300/40" title="Difusión">`;
        }

        let htmlContactos = `
            <div class="p-2 flex flex-col">
                <div class="bg-white dark:bg-slate-800 p-4 rounded-lg shadow-sm border border-slate-200 dark:border-slate-700 mb-3 flex justify-between items-center">
                    <div>
                        <h3 class="font-bold text-slate-800 dark:text-slate-200">Destinatarios</h3>
                        <p class="text-xs text-slate-500 dark:text-slate-400">Selecciona a quiénes enviar el mensaje</p>
                    </div>
<button onclick="toggleSelectAllBroadcast(this)" class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm font-semibold transition-colors bg-slate-100 text-slate-800 border border-slate-300 hover:bg-slate-200 dark:bg-blue-900/30 dark:text-blue-500 dark:border-blue-800/50 dark:hover:bg-blue-800/50">
    <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
        <path stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
    </svg>
    <span>Todos</span>
</button>
                </div>
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-2 pb-4">
        `;

        misContactosData.forEach(contacto => {
            const fotoUrl = contacto.foto_contacto || '';
            const nombre = contacto.nombre_contacto || 'Invitado';
            const iniciales = nombre.split(' ').map(n => n[0]).join('').substring(0, 2).toUpperCase();

            let avatarHtml = fotoUrl 
                ? `<img src="${fotoUrl}" class="w-8 h-8 rounded-full object-cover">`
                : `<div class="w-8 h-8 bg-emerald-600 rounded-full flex items-center justify-center text-white font-bold text-xs">${iniciales}</div>`;

            htmlContactos += `
                <label class="flex items-center p-3 bg-white dark:bg-slate-800 rounded-lg border border-slate-200 dark:border-slate-700 cursor-pointer hover:bg-slate-50 dark:hover:bg-slate-750">
                    <input type="checkbox" value="${contacto.contacto_up_id}" class="broadcast-checkbox w-5 h-5 text-purple-600 rounded border-slate-300 mr-3">
                    <div class="mr-3 flex-shrink-0">${avatarHtml}</div>
                    <div class="flex-1 truncate">
                        <h4 class="font-semibold text-slate-800 dark:text-slate-200 text-sm truncate">${nombre}</h4>
                    </div>
                </label>
            `;
        });

        htmlContactos += `</div></div>`;
        chatBox.innerHTML = htmlContactos;

        if (window.innerWidth < 768) {
            sidebar.classList.add('hidden');
            mainChat.classList.remove('hidden');
            mainChat.classList.add('flex');
        }
    }

    let selectAllBroadcast = false;
function toggleSelectAllBroadcast(btn) {
    selectAllBroadcast = !selectAllBroadcast;
    document.querySelectorAll('.broadcast-checkbox').forEach(cb => cb.checked = selectAllBroadcast);
    
    // Definimos los colores: gris oscuro para fondo blanco, azul para modo oscuro
    const colorClasses = "text-slate-800 dark:text-blue-500";
    
    if (selectAllBroadcast) {
        btn.innerHTML = `
            <svg class="w-4 h-4 ${colorClasses}" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path stroke-linecap="round" stroke-linejoin="round" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
            </svg>
            <span class="${colorClasses}">Ninguno</span>
        `;
    } else {
        btn.innerHTML = `
            <svg class="w-4 h-4 ${colorClasses}" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
            </svg>
            <span class="${colorClasses}">Todos</span>
        `;
    }
}
//=============================================================================

// --- LÓGICA DE VISTA PREVIA DE ADJUNTOS ---
    let adjuntoPendiente = '';

    function mostrarPreviewSubiendo(icono) {
      document.getElementById('attachment-preview').classList.remove('hidden');
      document.getElementById('attachment-icon').innerText = icono;
      document.getElementById('attachment-text').innerText = 'Subiendo archivo...';
      document.getElementById('attachment-subtext').innerText = 'Espera un momento ⏳';
      document.getElementById('attachment-cancel').classList.add('hidden');
      document.getElementById('send-btn').disabled = true; // Evita enviar mientras sube
    }

    function mostrarPreviewListo(icono, etiqueta, nombre) {
      adjuntoPendiente = etiqueta;
      document.getElementById('attachment-text').innerText = nombre;
      document.getElementById('attachment-subtext').innerText = 'Listo para enviar. Añade un texto si deseas.';
      document.getElementById('attachment-cancel').classList.remove('hidden');
      document.getElementById('send-btn').disabled = false;
    }

    function cancelarAdjunto() {
      adjuntoPendiente = '';
      document.getElementById('attachment-preview').classList.add('hidden');
      document.getElementById('camera-input').value = '';
      document.getElementById('gallery-input').value = '';
      document.getElementById('video-input').value = '';
      document.getElementById('pdf-input').value = '';
    }

//=============================================================================
	
    async function cargarHistorialGrupo(grupoId) {
      try {
        //const response = await fetch(`cargar_historial_grupo.php?grupo_id=${grupoId}&t=${Date.now()}`);
        // Reseteamos el paginador al entrar a un nuevo grupo
offsetMensajes = 0;
hayMasMensajes = true;
const response = await fetch(`cargar_historial_grupo.php?grupo_id=${grupoId}&offset=${offsetMensajes}&t=${Date.now()}`);
		const data = await response.json();
        chatBox.innerHTML = ''; 

        if (data.status === 'success' && data.messages.length > 0) {
          data.messages.forEach(msg => {
            const msgId = `g_${grupoId}_${msg.msj_id || msg.id || msg.id_mensaje || msg.fecha_envio}`;
            processedMessageIds.add(msgId); 
            
            const soyYo = parseInt(msg.remitente_up_id) === parseInt(currentUserId);
            const textoContenido = soyYo ? msg.mensaje : `<strong class="text-sky-600 dark:text-sky-400 text-xs block mb-0.5">${msg.nombre_remitente || 'Usuario'}</strong>${msg.mensaje}`;
			appendMessageDb(textoContenido, soyYo, msg.fecha_envio, false, msg.leido == 1, (msg.msj_id || msg.id), (msg.carpeta || ''), (msg.carpeta_estado || 0));
          });
		  
		  // 👇 AGREGA ESTAS 3 LÍNEAS AQUÍ 👇
  setTimeout(() => {
    hacerScrollAbajo();
  }, 100);
        } else {
          chatBox.innerHTML = `
            <div class="flex justify-center my-4">
              <span class="text-xs bg-slate-200 dark:bg-slate-800 text-slate-500 dark:text-slate-400 px-3 py-1 rounded-full shadow-sm">
                💬 Grupo sin mensajes aún. ¡Escribe el primero!
              </span>
            </div>
          `;
        }
      } catch (error) {
        console.error("Error al cargar historial del grupo", error);
      }
    }

    function playNotificationSound() {
      const sound = document.getElementById('chat-sound');
      if (sound) {
        sound.currentTime = 0;
        sound.play().catch(e => console.log("Audio bloqueado por navegador"));
      }
    }

    function showSystemNotification(text) {
      let cleanText = text.replace(/\[img\].*?\[\imagen\]/gi, '📷 Imagen adjunta');
      cleanText = cleanText.replace(/\[pdf\].*?\[\/pdf\]/gi, '📄 Documento PDF');
      cleanText = cleanText.replace(/\[audio\].*?\[\/audio\]/gi, '🎤 Nota de voz');
      cleanText = cleanText.replace(/<[^>]*>?/gm, '');

      if (document.hidden && "Notification" in window && Notification.permission === "granted") {
        new Notification("KOSMOSChat", {
          body: cleanText,
          icon: "logos/logo_384k.png"
        });
      }
    }
	
async function abrirPdfKOSMOS(urlPdf) {
  const urlCompleta = new URL(urlPdf, window.location.href).href;

  // 1. SI ES PC: Abre en otra pestaña normalmente
  if (!window.Capacitor || !window.Capacitor.isNativePlatform()) {
    window.open(urlCompleta, '_blank');
    return; 
  }

  // 2. SI ES CELULAR: Modal optimizado
  const modal = document.getElementById('pdf-modal');
  const container = document.getElementById('pdf-pages-container');
  const downloadBtn = document.getElementById('download-pdf-btn');

  // CONECTAMOS EL BOTÓN A LA NUEVA MAGIA DE DESCARGA
  if (downloadBtn) {
    downloadBtn.onclick = (e) => {
      e.preventDefault();
      descargarArchivoKOSMOS(urlPdf); // Llama a la descarga en segundo plano
    };
  }

  try {
    if (typeof pdfjsLib !== 'undefined') {
      pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
    } else {
      throw new Error("La librería PDF.js no cargó");
    }

    if (modal) modal.classList.remove('hidden');
    if (container) container.innerHTML = '<div class="text-white mt-10 font-bold animate-pulse text-center">Cargando documento...<br><span class="text-xs font-normal">Por favor espera</span></div>';
    
    const loadingTask = pdfjsLib.getDocument(urlCompleta);
    const pdf = await loadingTask.promise;
    
    if (container) container.innerHTML = ''; 
    
    const page = await pdf.getPage(1);
    
    const viewport = page.getViewport({ scale: 1.0 });
    const outputScale = window.devicePixelRatio || 1; 
    
    const canvas = document.createElement('canvas');
    canvas.width = Math.floor(viewport.width * outputScale);
    canvas.height = Math.floor(viewport.height * outputScale);
    
    canvas.style.width = '100%';
    canvas.style.height = 'auto';
    canvas.className = 'mb-4 rounded shadow-lg bg-white';
    
    if (container) {
        container.appendChild(canvas);
        
        if (pdf.numPages > 1) {
            const aviso = document.createElement('div');
            aviso.className = 'text-center text-slate-300 text-xs mt-2 mb-6 px-4';
            aviso.innerHTML = `Vista previa (Página 1 de ${pdf.numPages}).<br>Usa el botón flotante azul para descargar el archivo completo.`;
            container.appendChild(aviso);
        }
    }

    const renderContext = {
      canvasContext: canvas.getContext('2d'),
      transform: [outputScale, 0, 0, outputScale, 0, 0],
      viewport: viewport
    };
    
    await page.render(renderContext).promise;
    
  } catch (error) {
    console.error("Error al renderizar PDF en el celular:", error);
    // Si falla la imagen, no dejamos la pantalla negra, mostramos un aviso:
    if (container) {
        container.innerHTML = '<div class="text-white mt-10 text-center text-sm font-bold">No se pudo cargar la vista previa. 📄<br><span class="font-normal text-xs text-slate-300">Usa el botón azul debajo para descargarlo.</span></div>';
    }
  }
}

// Asegúrate de conservar intacta esta función para poder cerrarlo:
function closePdfModal() {
  const modal = document.getElementById('pdf-modal');
  const container = document.getElementById('pdf-pages-container');
  if (modal) modal.classList.add('hidden');
  if (container) container.innerHTML = ''; // Limpia el canvas de la memoria
}

function formatearMensaje(texto) {
      if (!texto) return '';
	  const imgRegex = /\[img\](.*?)\[\/img\]/gi;
      if (imgRegex.test(texto)) {
        texto = texto.replace(imgRegex, `<img src="$1" onclick="openImageModal('$1')" class="w-full max-w-[230px] sm:max-w-[250px] h-auto rounded-lg mt-1 mb-2 border border-slate-200 dark:border-slate-700 cursor-pointer object-cover hover:opacity-90 transition-opacity" alt="Imagen">`);
      }
      
const pdfRegex = /\[pdf\](.*?)\[\/pdf\]/gi;
if (pdfRegex.test(texto)) {
  texto = texto.replace(pdfRegex, `
    <div class="flex items-center justify-between gap-3 p-3 mt-1 mb-2 bg-white/60 dark:bg-slate-800/80 border border-slate-200 dark:border-slate-700/60 rounded-xl w-full max-w-[260px] shadow-sm">
      <div class="flex items-center gap-3 min-w-0">
        <!-- Ícono de PDF -->
        <div class="flex-shrink-0 w-10 h-10 bg-red-100 dark:bg-red-500/20 text-red-500 rounded-lg flex items-center justify-center text-2xl shadow-sm">
          📄
        </div>
        <div class="flex-1 min-w-0">
          <div class="text-sm font-bold text-slate-800 dark:text-slate-200 truncate">Documento PDF</div>
          <div class="text-[10px] text-slate-500 dark:text-slate-400 truncate">Toca el ícono para bajar</div>
        </div>
      </div>
      
      <!-- Botón de Descarga Directa (Llama a nuestra magia nativa) -->
      <button type="button" onclick="descargarArchivoKOSMOS('$1')" class="p-2 bg-sky-50 dark:bg-sky-900/30 text-sky-600 dark:text-sky-400 hover:bg-sky-500 hover:text-white dark:hover:bg-sky-500 rounded-full transition-colors flex-shrink-0 shadow-sm" title="Descargar Documento">
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
        </svg>
      </button>
    </div>
  `);
}
	  


	  
const videoRegex = /\[video\](.*?)\[\/video\]/gi;
if (videoRegex.test(texto)) {
  texto = texto.replace(videoRegex, `
    <div class="mt-1 mb-2 max-w-[250px] sm:max-w-[300px] rounded-lg overflow-hidden border border-slate-200 dark:border-slate-800 shadow-sm bg-black relative flex items-center justify-center">
      <video src="$1#t=0.1" controls preload="metadata" controlsList="nodownload" class="w-full h-auto max-h-[300px] object-contain rounded-lg"></video>
      
      <!-- Botón de descarga apuntando a la nueva función -->
      <button type="button" onclick="descargarArchivoKOSMOS('$1')" class="absolute top-2 right-2 bg-black/60 p-1.5 rounded-full text-white hover:bg-sky-500 transition-colors z-10 opacity-80" title="Descargar Video">
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
        </svg>
      </button>
    </div>
  `);
}

      const audioRegex = /\[audio\](.*?)\[\/audio\]/gi;
      if (audioRegex.test(texto)) {
        const audioId = 'aud_' + Math.random().toString(36).substr(2, 9);
        texto = texto.replace(audioRegex, `
          <div class="flex items-center gap-2 p-2 bg-slate-100 dark:bg-slate-800/80 rounded-xl border border-slate-200 dark:border-slate-700/60 max-w-[280px] sm:max-w-[320px] mt-1 shadow-sm">
            <div class="relative flex-shrink-0">
              <div class="w-10 h-10 bg-emerald-500 text-white rounded-full flex items-center justify-center font-bold text-sm shadow-sm">
                🎙️
              </div>
            </div>

            <button type="button" onclick="togglePlayAudio('${audioId}')" id="btn-${audioId}" class="w-9 h-9 bg-emerald-600 hover:bg-emerald-500 text-white rounded-full flex items-center justify-center flex-shrink-0 transition-transform active:scale-95 shadow-sm">
              <svg id="icon-play-${audioId}" class="w-5 h-5 ml-0.5" fill="currentColor" viewBox="0 0 20 20">
                <path d="M6.3 2.841A1.5 1.5 0 004 4.11V15.89a1.5 1.5 0 002.3 1.269l9.333-5.89a1.5 1.5 0 000-2.538L6.3 2.841z"/>
              </svg>
              <svg id="icon-pause-${audioId}" class="w-5 h-5 hidden" fill="currentColor" viewBox="0 0 20 20">
                <path d="M5.75 4.5a.75.75 0 00-.75.75v9.5c0 .414.336.75.75.75h1.5a.75.75 0 00.75-.75v-9.5a.75.75 0 00-.75-.75h-1.5zm7 0a.75.75 0 00-.75.75v9.5c0 .414.336.75.75.75h1.5a.75.75 0 00.75-.75v-9.5a.75.75 0 00-.75-.75h-1.5z"/>
              </svg>
            </button>

            <div class="flex-1 min-w-0 flex flex-col justify-center">
              <input type="range" id="seek-${audioId}" value="0" min="0" max="100" oninput="seekAudio('${audioId}', this.value)" class="w-full h-1.5 bg-slate-300 dark:bg-slate-600 rounded-lg appearance-none cursor-pointer accent-emerald-500">
              
              <div class="flex justify-between items-center text-[10px] text-slate-500 dark:text-slate-400 mt-1 font-mono">
                <span id="time-${audioId}">0:00</span>
                
                <button type="button" onclick="changeSpeed('${audioId}')" id="speed-${audioId}" class="text-[9px] bg-slate-200 dark:bg-slate-700 hover:bg-emerald-500 hover:text-white px-1.5 py-0.5 rounded font-bold transition-colors">
                  1x
                </button>
              </div>
            </div>

            <button type="button" onclick="descargarAudioUniversal('$1')" class="p-1.5 text-slate-400 hover:text-emerald-500 dark:hover:text-emerald-400 transition-colors flex-shrink-0" title="Descargar nota de voz">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
              </svg>
            </button>

            <audio id="${audioId}" src="$1" preload="metadata" onloadedmetadata="initAudioPlayer('${audioId}')" ondurationchange="initAudioPlayer('${audioId}')" ontimeupdate="updateAudioProgress('${audioId}')" onended="resetAudioPlayer('${audioId}')"></audio>
          </div>
        `);
      }

      return texto;
    }

function appendMessage(text, isUser = false) {
    // =========================================================
    // BLOQUEO DE GLOBO VERDE (Doble burbuja)
    // =========================================================
    // Leemos la variable directamente sin el "window."
    let chatActivoId = null;
    if (typeof currentId !== 'undefined' && currentId !== null) {
        chatActivoId = currentId;
    } else if (typeof id_destino !== 'undefined' && id_destino !== null) {
        chatActivoId = id_destino;
    }

    const myId = window.KOSMOS_USER_ID || document.body.getAttribute('data-my-id') || null;
    
    // Si el chat abierto tiene el mismo ID que tu sesión, abortamos el globo verde.
    if (chatActivoId !== null && myId !== null && String(chatActivoId) === String(myId)) {
        return; 
    }
    // =========================================================

    const wrapper = document.createElement('div');
    wrapper.className = `flex w-full mb-3 burbuja-temporal ${isUser ? 'justify-end' : 'justify-start'}`;
    
    // ... (Tu código sigue igual de aquí hacia abajo) ...
    
    const time = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    const bgUser = 'bg-[#dbfee2] dark:bg-[#005c4b]';
    const bgBot = 'bg-white dark:bg-[#202c33]';
    const bg = isUser ? bgUser : bgBot;
    
    const corner = isUser ? 'rounded-2xl rounded-br-none' : 'rounded-2xl rounded-bl-none';
const borderStyle = isUser 
        ? 'border-r-4 border-r-emerald-500 dark:border-r-emerald-400' 
        : 'border-l-4 border-l-sky-500 dark:border-l-sky-400';

    let indicador = '';
    if (isUser) {
        // En el temporal ponemos la bolita en gris (Enviado)
        indicador = `<span class="w-2 h-2 rounded-full bg-slate-400 inline-block shadow-sm" title="Enviando..."></span>`;
    }

    // =========================================================
    // ICONOS EXACTAMENTE IGUALES AL ORIGINAL
    // =========================================================
    const iconosData = [
      { id: 'chats', title: 'Chats', d: 'M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z' },
      { id: 'acuerdos', title: 'Acuerdos', d: 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z' },
      { id: 'tareas', title: 'Tareas', d: 'M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2' },
      { id: 'archivos', title: 'Archivos', d: 'M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13' },
      { id: 'cotizaciones', title: 'Cotizaciones', d: 'M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z' },
      { id: 'notas', title: 'Notas', d: 'M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z' },
      { id: 'enlaces', title: 'Enlaces', d: 'M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1' }
    ];

    // Mantenemos tu estructura, pero le ponemos opacidad para indicar que "está cargando" y quitamos el click
    let svgsHtml = iconosData.map(icon => {
      return `
        <svg class="w-3.5 h-3.5 transition-colors text-slate-400 dark:text-slate-400/80 opacity-60" 
             fill="none" stroke="currentColor" viewBox="0 0 24 24" title="${icon.title}">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="${icon.d}"/>
        </svg>
      `;
    }).join('');

    const botonEstadoHtml = `
      <div class="pl-1.5 ml-1 border-l border-slate-300 dark:border-slate-600 flex items-center">
        <svg class="w-4 h-4 transition-colors text-slate-300 dark:text-slate-500 opacity-60" 
             fill="none" stroke="currentColor" viewBox="0 0 24 24" title="Guardando...">
			 <circle cx="12" cy="12" r="11" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 13l3 3L17 8" />
        </svg>
      </div>
    `;

    // MAGIA AQUÍ: Bloqueamos los clics temporalmente con 'pointer-events-none'
    const actionIconsHtml = `<div class="flex items-center gap-1.5 shrink-0 pointer-events-none">${svgsHtml} ${botonEstadoHtml}</div>`;

    let footerContent = '';
    if (isUser) {
      footerContent = `
        <div class="flex items-center justify-between gap-2 mt-1.5 pt-1.5 border-t border-slate-200/50 dark:border-slate-700/40 text-[10px]">
          <div>${actionIconsHtml}</div>
          <div class="flex items-center justify-end gap-1 text-slate-400 dark:text-slate-300/70 shrink-0">
            <span>${time}</span>
            ${indicador}
          </div>
        </div>
      `;
    } else {
      footerContent = `
        <div class="flex items-center justify-between gap-2 mt-1.5 pt-1.5 border-t border-slate-200/50 dark:border-slate-700/40 text-[10px]">
          <div class="flex items-center gap-1 text-slate-400 dark:text-slate-300/70 shrink-0">
            <span>${time}</span>
          </div>
          <div>${actionIconsHtml}</div>
        </div>
      `;
    }

    wrapper.innerHTML = `
      <div class="${bg} text-slate-800 dark:text-slate-100 p-3 ${corner} ${borderStyle} max-w-[90%] md:max-w-md shadow-sm border border-slate-100 dark:border-slate-700/30 text-sm break-words">
        ${formatearMensaje(text)}
        ${footerContent}
      </div>
    `;
    
    const chatBox = document.getElementById('chat-box');
    if (chatBox) {
        chatBox.appendChild(wrapper);
        chatBox.scrollTop = chatBox.scrollHeight;
    }
}

// Pequeña función auxiliar para mostrar el aviso de forma elegante sin usar el feo "alert" del navegador
function toastMsg(mensaje) {
    // Si ya usas alguna librería de notificaciones (como SweetAlert o Toastr), puedes cambiar esto.
    // Por ahora usaremos un alert nativo si no tienes una definida.
    if (typeof Swal !== 'undefined') {
        Swal.fire({ toast: true, position: 'top-end', icon: 'info', title: mensaje, showConfirmButton: false, timer: 3000 });
    } else {
        alert(mensaje);
    }
}

// NOTA: Se añadió carpetaEstado = 0 al final =================================================

  function appendMessageDb(text, isUser = false, fechaHora = '', alInicio = false, leido = false, msgId = null, carpetaActual = '', carpetaEstado = 0) {
    const wrapper = document.createElement('div');
    wrapper.className = `flex w-full mb-3 ${isUser ? 'justify-end' : 'justify-start'}`;
    
    let textoFechaHora = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    
    if (fechaHora) {
      const fechaIso = fechaHora.includes(' ') ? fechaHora.replace(' ', 'T') : fechaHora;
      const fechaObj = new Date(fechaIso);
      if (!isNaN(fechaObj)) {
        const hoy = new Date();
        const esHoy = fechaObj.toDateString() === hoy.toDateString();
        const hora = fechaObj.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
        if (esHoy) textoFechaHora = hora; 
        else {
          const dia = String(fechaObj.getDate()).padStart(2, '0');
          const mes = String(fechaObj.getMonth() + 1).padStart(2, '0');
          const anio = String(fechaObj.getFullYear()).slice(-2);
          textoFechaHora = `${dia}/${mes}/${anio} ${hora}`;
        }
      }
    }

    const bgUser = 'bg-[#dbfee2] dark:bg-[#005c4b]';
    const bgBot = 'bg-white dark:bg-[#202c33]';
    const bg = isUser ? bgUser : bgBot;
    
    const corner = isUser ? 'rounded-2xl rounded-br-none' : 'rounded-2xl rounded-bl-none';
    const borderStyle = isUser ? 'border-l-4 border-l-emerald-500 dark:border-l-emerald-400' : 'border-r-4 border-r-sky-500 dark:border-r-sky-400';

    let indicador = '';
    if (isUser) {
        const colorBolita = leido ? 'bg-emerald-500' : 'bg-slate-400';
        const tituloBolita = leido ? 'Leído' : 'Enviado';
        indicador = `<span class="w-2 h-2 rounded-full ${colorBolita} inline-block shadow-sm" title="${tituloBolita}"></span>`;
    }

    // --- ICONOS DE CARPETAS ---
    const iconosData = [
      { id: 'chats', title: 'Chats', d: 'M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z' },
      { id: 'acuerdos', title: 'Acuerdos', d: 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z' },
      { id: 'tareas', title: 'Tareas', d: 'M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2' },
      { id: 'archivos', title: 'Archivos', d: 'M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13' },
      { id: 'cotizaciones', title: 'Cotizaciones', d: 'M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z' },
      { id: 'notas', title: 'Notas', d: 'M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z' },
      { id: 'enlaces', title: 'Enlaces', d: 'M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1' }
    ];

    let svgsHtml = iconosData.map(icon => {
      const colorClass = (carpetaActual !== '' && carpetaActual === icon.id) ? 'text-sky-500' : 'text-slate-400 dark:text-slate-400/80 hover:text-sky-500';
      return `
        <svg class="w-3.5 h-3.5 transition-colors cursor-pointer icon-msg-${msgId} ${colorClass}" 
             fill="none" stroke="currentColor" viewBox="0 0 24 24" title="${icon.title}" 
             onClick="cambiarCarpetaMensaje(this, '${msgId}', '${icon.id}')">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="${icon.d}"/>
        </svg>
      `;
    }).join('');

    // --- NUEVO BOTÓN DE ESTADO (CUMPLIDO / PENDIENTE) ---
    const isCumplido = parseInt(carpetaEstado) === 1;
    const colorEstado = isCumplido ? 'text-emerald-500' : 'text-slate-300 dark:text-slate-500 hover:text-emerald-400';
    
    const botonEstadoHtml = `
      <div class="pl-1.5 ml-1 border-l border-slate-300 dark:border-slate-600 flex items-center">
        <svg class="w-4 h-4 transition-colors cursor-pointer estado-msg-${msgId} ${colorEstado}" 
             data-estado="${isCumplido ? '1' : '0'}"
             fill="none" stroke="currentColor" viewBox="0 0 24 24" title="${isCumplido ? 'Cumplido' : 'Marcar cumplido'}"
             onClick="toggleEstadoMensaje(this, '${msgId}')">
			<circle cx="12" cy="12" r="11" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 13l3 3L17 8"/>
        </svg>
      </div>
    `;

    const actionIconsHtml = `<div class="flex items-center gap-1.5 shrink-0">${svgsHtml} ${botonEstadoHtml}</div>`;
    // ----------------------------------------

   let footerContent = '';
    if (isUser) {
      footerContent = `
        <div class="flex items-center justify-between gap-2 mt-1.5 pt-1.5 border-t border-slate-200/50 dark:border-slate-700/40 text-[10px]">
          <div>${actionIconsHtml}</div>
          <div class="flex items-center justify-end gap-1 text-slate-400 dark:text-slate-300/70 shrink-0">
            <span>${textoFechaHora}</span>
            ${indicador}
          </div>
        </div>
      `;
    } else {
      footerContent = `
        <div class="flex items-center justify-between gap-2 mt-1.5 pt-1.5 border-t border-slate-200/50 dark:border-slate-700/40 text-[10px]">
          <div class="flex items-center gap-1 text-slate-400 dark:text-slate-300/70 shrink-0">
            <span>${textoFechaHora}</span>
          </div>
          <div>${actionIconsHtml}</div>
        </div>
      `;
    }

    wrapper.innerHTML = `
      <div class="${bg} text-slate-800 dark:text-slate-100 p-3 ${corner} ${borderStyle} max-w-[90%] md:max-w-md shadow-sm border border-slate-100 dark:border-slate-700/30 text-sm break-words">
        ${formatearMensaje(text)}
        ${footerContent}
      </div>
    `;
    
    if (alInicio) {
      chatBox.prepend(wrapper); 
    } else {
      chatBox.appendChild(wrapper);
      hacerScrollAbajo();
    }
  }
  //========================================================
  
async function cargarMensajesCanvas(carpeta, idContenedorCanvas, reset = false) {
    if (!currentId) return;
    const contenedor = document.getElementById(idContenedorCanvas);
    if (!contenedor) return;

    if (reset) {
        canvasOffset = 0;
        canvasHayMas = true;
        contenedor.innerHTML = `
            <div class="flex justify-center items-center p-6 text-sky-500">
                <svg class="animate-spin h-6 w-6 mr-2" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                </svg>
                <span class="text-sm font-medium">Buscando...</span>
            </div>
        `;
    }

    if (canvasCargando || !canvasHayMas) return;
    canvasCargando = true;

    try {
        const statusModo = canvasMostrarTodos ? 1 : 0;
        
        // Ruteo inteligente de la petición
        let urlFetch = '';
        if (currentId === 'bot') {
            urlFetch = `obtener_mensajes_bot.php?carpeta=${carpeta}&todos=${statusModo}&offset=${canvasOffset}`;
        } else {
            urlFetch = `obtener_mensajes_canvas.php?contacto=${currentId}&carpeta=${carpeta}&todos=${statusModo}&offset=${canvasOffset}`;
        }

        const response = await fetch(urlFetch);
        const data = await response.json();

        if (data.status === 'success' && data.messages.length > 0) {
            let html = '';
            
            data.messages.forEach(msg => {
                let esMio = false;
                let badgeTxt = '';
                let badgeStyle = '';

                // Renderizado para el bot (nombres) vs Renderizado normal
                if (currentId === 'bot') {
                    esMio = (msg.direccion === 'MIO-USU');
                    const nombreCorto = msg.contacto_nombre ? msg.contacto_nombre.split(' ')[0] : 'Desconocido';
                    badgeTxt = esMio ? `Para: ${nombreCorto}` : `De: ${nombreCorto}`;
                    badgeStyle = esMio 
                        ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/50 dark:text-emerald-300' 
                        : 'bg-slate-200 text-slate-700 dark:bg-slate-700 dark:text-slate-300';
                } else {
                    esMio = (parseInt(msg.remitente_up_id) !== parseInt(currentId));
                    badgeTxt = esMio ? 'Mío' : 'Contacto';
                    badgeStyle = esMio ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/50 dark:text-emerald-300' : 'bg-sky-100 text-sky-700 dark:bg-sky-900/50 dark:text-sky-300';
                }
                
                const estaCumplido = parseInt(msg.estado) === 1;
                const msgIdVal = msg.msj_id || msg.id || msg.id_mensaje;

                const bgClass = esMio ? 'bg-[#f0fdf4] dark:bg-[#003b30]' : 'bg-white dark:bg-slate-800';
                const borderClass = esMio ? 'border-l-4 border-l-emerald-500 dark:border-l-emerald-400' : 'border-l-4 border-l-sky-500 dark:border-l-sky-400';
                
                const fecha = new Date(msg.fecha_envio).toLocaleDateString('es-ES', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' });

                html += `
                    <div class="p-3 mb-3 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700/60 ${bgClass} ${borderClass} transition-all hover:shadow-md">
                        <div class="flex justify-between items-center mb-1.5">
                            <span class="text-[9px] font-bold px-2 py-0.5 rounded-md ${badgeStyle}">${badgeTxt}</span>
                            <div class="flex items-center">
                                <span class="text-[10px] text-slate-400 dark:text-slate-500">${fecha}</span>
                                <div class="pl-1.5 ml-2 border-l border-slate-300 dark:border-slate-600 flex items-center">
                                    <svg class="w-4 h-4 transition-colors cursor-pointer estado-msg-${msgIdVal} ${estaCumplido ? 'text-emerald-500' : 'text-slate-300 dark:text-slate-500 hover:text-emerald-400'}" 
                                         data-estado="${estaCumplido ? '1' : '0'}"
                                         fill="none" stroke="currentColor" viewBox="0 0 24 24" title="${estaCumplido ? 'Cumplido' : 'Marcar cumplido'}"
                                         onClick="toggleEstadoMensaje(this, '${msgIdVal}')">
                                      <circle cx="12" cy="12" r="11" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 13l3 3L17 8" />
                                    </svg>
                                </div>
                            </div>
                        </div>
                        <p id="texto-msg-canvas-${msgIdVal}" class="text-sm text-slate-700 dark:text-slate-200 transition-all duration-300 ${estaCumplido ? 'opacity-50' : ''}">
                            ${formatearMensaje(msg.mensaje)}
                        </p>
                    </div>
                `;
            });
            
            if (reset) {
                contenedor.innerHTML = html;
            } else {
                contenedor.insertAdjacentHTML('beforeend', html);
            }
            
            if (typeof canvasLimite !== 'undefined') {
                canvasOffset += canvasLimite;
            } else {
                canvasOffset += 10;
            }

        } else {
            canvasHayMas = false;
            if (reset) {
                const modoTxt = canvasMostrarTodos ? 'guardados' : 'pendientes';
                contenedor.innerHTML = `
                    <div class="text-center p-8">
                        <div class="text-slate-300 dark:text-slate-600 mb-2 text-4xl">📂</div>
                        <p class="text-slate-400 dark:text-slate-500 text-sm">No tienes mensajes ${modoTxt} en <b>${carpeta}</b>.</p>
                    </div>
                `;
            } else {
                contenedor.insertAdjacentHTML('beforeend', `<div class="text-center text-xs text-slate-400 p-2 py-4">No hay más mensajes.</div>`);
            }
        }
    } catch (error) {
        console.error(`Error cargando canvas ${carpeta}:`, error);
        if (reset) contenedor.innerHTML = '<div class="text-center p-4 text-red-500 text-sm">Ocurrió un error de conexión.</div>';
    } finally {
        canvasCargando = false;
    }
}

// Función que detecta cuando el usuario baja en el panel lateral
function handleCanvasScroll(elemento) {
    // Si estamos en la pestaña "chats", esto no aplica
    if (canvasCarpetaActual === 'chats' || canvasCarpetaActual === '') return;

    // Detectar si llegamos cerca del fondo (con un margen de 50px)
    if (elemento.scrollTop + elemento.clientHeight >= elemento.scrollHeight - 50) {
        if (!canvasCargando && canvasHayMas) {
            cargarMensajesCanvas(canvasCarpetaActual, 'content-' + canvasCarpetaActual, false);
        }
    }
}
  
  //========================================================
  
// Función 1: Actualiza la carpeta (Iconos SVG)
async function cambiarCarpetaMensaje(elementoClickeado, msgId, nuevaCarpeta) {
    if(!msgId || msgId === 'null') return;

    const iconosDelMensaje = document.querySelectorAll(`.icon-msg-${msgId}`);
    iconosDelMensaje.forEach(icon => {
        icon.classList.remove('text-sky-500');
        icon.classList.add('text-slate-400', 'dark:text-slate-400/80');
    });
    elementoClickeado.classList.remove('text-slate-400', 'dark:text-slate-400/80');
    elementoClickeado.classList.add('text-sky-500');

    try {
        const formData = new FormData();
        formData.append('msj_id', msgId);
        formData.append('accion', 'carpeta');
        formData.append('valor', nuevaCarpeta);
        //formData.append('usuario_id', typeof miUsuarioId !== 'undefined' ? miUsuarioId : currentId); // Asegúrate de enviar el ID tuyo

        await fetch('actualizar_carpeta.php', { method: 'POST', body: formData });
    } catch (error) {
        console.error("Error AJAX Carpeta:", error);
    }
}

// Función 2: Alterna el estado Cumplido/Pendiente (Icono Check)
async function toggleEstadoMensaje(elementoClickeado, msgId) {
    if(!msgId || msgId === 'null') return;

    const estadoActual = elementoClickeado.getAttribute('data-estado');
    const nuevoEstado = estadoActual === '1' ? '0' : '1';

    // 1. Actualizar TODOS los íconos sincronizados (Chat + Canvas)
    const iconos = document.querySelectorAll(`.estado-msg-${msgId}`);
    iconos.forEach(icono => {
        if (nuevoEstado === '1') {
            icono.classList.remove('text-slate-300', 'dark:text-slate-500', 'hover:text-emerald-400');
            icono.classList.add('text-emerald-500');
            icono.setAttribute('title', 'Cumplido');
        } else {
            icono.classList.remove('text-emerald-500');
            icono.classList.add('text-slate-300', 'dark:text-slate-500', 'hover:text-emerald-400');
            icono.setAttribute('title', 'Marcar cumplido');
        }
        icono.setAttribute('data-estado', nuevoEstado);
    });

    // 2. Tachar o destachar el texto dentro del panel derecho (Canvas)
    const textoCanvas = document.getElementById(`texto-msg-canvas-${msgId}`);
    if (textoCanvas) {
        if (nuevoEstado === '1') {
            textoCanvas.classList.add('opacity-50');
        } else {
            textoCanvas.classList.remove('opacity-50');
        }
    }

    // 3. Guardar en Base de Datos
    try {
        const formData = new FormData();
        formData.append('msj_id', msgId);
        formData.append('accion', 'estado');
        formData.append('valor', nuevoEstado);

        await fetch('actualizar_carpeta.php', { method: 'POST', body: formData });
    } catch (error) {
        console.error("Error AJAX Estado:", error);
    }
}
  
  
  //========================================================
  
  
  
  //=========================================================

//    function sendMessage() {
//      const message = userInput.value.trim();
//      if (!message) return;
//
//      appendMessage(message, true);
//      userInput.value = '';
//	  userInput.style.height = 'auto'; // <--- AGREGA ESTA LÍNEA AQUÍ
//      sendPayload(activeCategory, message);
//    }


//function sendMessage() {
//      const message = userInput.value.trim();
//      if (!message) return;
//
//      if (chatType === 'broadcast') {
//          const seleccionados = document.querySelectorAll('.broadcast-checkbox:checked');
//          if (seleccionados.length === 0) {
//              alert("⚠️ Por favor, selecciona al menos un destinatario para la difusión.");
//              return;
//          }
//      }
//
//      appendMessage(message, true);
//      userInput.value = '';
//      userInput.style.height = 'auto'; 
//      sendPayload(activeCategory, message);
//    }
	
//====================================================

function sendMessage() {
    const message = userInput.value.trim();
    
    if (!message && !adjuntoPendiente) return;

    if (chatType === 'broadcast') {
        const seleccionados = document.querySelectorAll('.broadcast-checkbox:checked');
        if (seleccionados.length === 0) {
            alert("⚠️ Por favor, selecciona al menos un destinatario para la difusión.");
            return;
        }
    }

    let finalMessage = '';
    if (adjuntoPendiente) {
        finalMessage = adjuntoPendiente;
        if (message) finalMessage += "\n\n" + message;
    } else {
        finalMessage = message;
    }

    // 1. Leemos los atributos del DOM
    let pesoGuardado = document.body.getAttribute('data-peso-archivo');
    let pesoBytes = pesoGuardado ? parseInt(pesoGuardado) : 0;
    let fechaProgramadaActiva = document.body.getAttribute('data-fecha-programada');

    // 2. DISPARAMOS ALERTA O PINTAMOS EL GLOBO
    if (fechaProgramadaActiva) {
        alert(`⏰ Mensaje programado para: ${fechaProgramadaActiva.replace('T', ' ')}`);
    } else {
        appendMessage(finalMessage, true);
    }
    
    userInput.value = '';
    userInput.style.height = 'auto'; 
    cancelarAdjunto(); 
	
	// 👇 ESTA ES LA LÍNEA CLAVE QUE FALTABA PARA LIMPIAR EL PESO ENVIADO
    document.body.removeAttribute('data-peso-archivo');
    
    // 3. Enviamos el payload (¡Sin apagar el reloj todavía!)
    sendPayload(activeCategory, finalMessage, pesoBytes);
}
	
	
//======================================================================

// Recibe el peso como tercer parámetro
async function sendPayload(category, message, pesoBytes = 0) {
    try {
        // Captura inmediata de la fecha antes de cualquier otra acción
        let fechaProgGuardada = document.body.getAttribute('data-fecha-programada') || '';
        
        let endpoint = 'integracion.php';
        let guestSessionId = localStorage.getItem('bot_guest_id');
        if (!guestSessionId) {
            guestSessionId = 'inv_' + Math.random().toString(36).substring(2, 12);
            localStorage.setItem('bot_guest_id', guestSessionId);
        }

        // Payload base para el BOT
        let payload = { 
            action: category, 
            message: message,
            is_guest: window.KOSMOS_IS_GUEST,
            user_name: window.KOSMOS_USER_NAME,
            session_id: guestSessionId,
            peso_bytes: pesoBytes,
            fecha_programada: fechaProgGuardada 
        };

        // Redefinimos payload y endpoint dependiendo del TIPO DE CHAT
        if (chatType === 'user') {
            endpoint = 'enviar_mensaje.php';
            payload = { destinatario: currentId, message: message, peso_bytes: pesoBytes, fecha_programada: fechaProgGuardada };
            
        } else if (chatType === 'group') {
            endpoint = 'enviar_mensaje_grupo.php'; 
            payload = { grupo_id: currentId, message: message, peso_bytes: pesoBytes, fecha_programada: fechaProgGuardada };
            
        } else if (chatType === 'broadcast') {
            const checkboxes = document.querySelectorAll('.broadcast-checkbox:checked');
            const destinatarios = Array.from(checkboxes).map(cb => cb.value);
            if (destinatarios.length === 0) return; 

            endpoint = 'procesar_difusion.php';
            payload = { destinatarios: destinatarios, message: message, peso_bytes: pesoBytes, fecha_programada: fechaProgGuardada};
        }

        // 👉 CHIVATO 1: EL PAQUETE QUE SALE HACIA EL SERVIDOR
        console.log("=== 🚀 ENVIANDO DATOS A PHP ===");
        console.log("Archivo destino:", endpoint);
        console.log("Datos del Payload:", payload);
        console.log("===============================");

        const response = await fetch(endpoint, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        });

        // Leemos primero como texto para capturar cualquier error crudo de PHP antes de parsearlo a JSON
        const textResponse = await response.text();
        
        // 👉 CHIVATO 2: LO QUE RESPONDIÓ EL SERVIDOR
        console.log("=== 📩 RESPUESTA CRUDA DE PHP ===", textResponse);

        // Convertimos el texto a JSON
        const data = JSON.parse(textResponse);

        // 👇 MAGIA AQUÍ: Si el servidor dice que es un mensaje programado, apagamos el reloj
        if (data.status === 'scheduled') {
            console.log("✅ Confirmado por servidor. Apagando reloj.");
            // Verificamos que la función exista para evitar otro crash
            if (typeof clearSchedule === 'function') {
                clearSchedule();
            }
        }

        // Si es un mensaje normal y trae respuesta para el bot...
        if (data.status === 'success') {
            
            // Reemplazo Invisible
            const burbujasTemp = document.querySelectorAll('.burbuja-temporal');
            if (burbujasTemp.length > 0 && data.msg_id) {
                const ultimaBurbuja = burbujasTemp[burbujasTemp.length - 1];
                ultimaBurbuja.remove();
                
                // Dibujamos la oficial (que sí tiene el ID y los iconos clickeables)
                appendMessageDb(message, true, '', false, false, data.msg_id, '', 0);
            }

            if (data.reply) {
                appendMessage(data.reply, false);
            }
        }
        
    } catch (error) {
        console.error("❌ Error CRÍTICO en el envío:", error);
    }
}
	
//======================================================================

    async function verificarMensajesNuevos() {
	// === NUEVO: MAGIA DE LAS BOLITAS EN TIEMPO REAL ===
      if (chatType === 'user' && currentId) {
        try {
          const resLeidos = await fetch(`verificar_leidos.php?contacto=${currentId}&t=${Date.now()}`);
          const dataLeidos = await resLeidos.json();
          
          if (dataLeidos.status === 'success' && dataLeidos.todo_leido) {
            // Buscamos todas las bolitas grises en el chat y las pasamos a verde
            document.querySelectorAll('.bg-slate-400[title="Enviado"]').forEach(bolita => {
              bolita.classList.remove('bg-slate-400');
              bolita.classList.add('bg-emerald-500');
              bolita.title = "Leído";
            });
          }
        } catch (e) {
          console.error("Error verificando leídos:", e);
        }
      }
      // =================================================
      try {
        const response = await fetch(`obtener_mensajes.php?t=${Date.now()}`);
        const data = await response.json();

        if (data.status === 'success' && data.messages.length > 0) {
          data.messages.forEach(msg => {
            const msgId = `u_${msg.msj_id || msg.id || msg.id_mensaje || msg.fecha_envio}`;
            if (processedMessageIds.has(msgId)) return;
            processedMessageIds.add(msgId);

            if (chatType === 'user' && parseInt(msg.remitente_up_id) === parseInt(currentId)) {
              //appendMessageDb(msg.mensaje, false, msg.fecha_envio, false, msg.leido == 1);
			  appendMessageDb(msg.mensaje, false, msg.fecha_envio, false, msg.leido == 1, (msg.msj_id || msg.id || msg.id_mensaje), (msg.carpeta || ''), (msg.carpeta_estado || 0));
              fetch('marcar_leidos.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ remitente: currentId })
              });
            } else {
              playNotificationSound();
              showSystemNotification(`Nuevo mensaje de ${msg.nombre_remitente || 'Usuario'}: ${msg.mensaje}`);

              const badgeEl = document.getElementById(`badge-contact-${msg.remitente_up_id}`);
              if (badgeEl) {
                let actual = parseInt(badgeEl.innerText) || 0;
                badgeEl.innerText = actual + 1;
                badgeEl.classList.remove('hidden');
              }
            }
          });
        }
      } catch (error) {
        console.error("Error al verificar mensajes directos", error);
      }

      if (Array.isArray(misGruposData)) {
        for (const grupo of misGruposData) {
          try {
            const resGrupo = await fetch(`cargar_historial_grupo.php?grupo_id=${grupo.grupo_id}&t=${Date.now()}`);
            const dataGrupo = await resGrupo.json();

            if (dataGrupo.status === 'success' && dataGrupo.messages.length > 0) {
              dataGrupo.messages.forEach(msg => {
                const msgId = `g_${grupo.grupo_id}_${msg.msj_id || msg.id || msg.id_mensaje || msg.fecha_envio}`;
                if (processedMessageIds.has(msgId)) return;
                processedMessageIds.add(msgId);

                if (firstGroupPollDone) {
                  const soyYo = parseInt(msg.remitente_up_id) === parseInt(currentUserId);
                  if (!soyYo) {
                    if (chatType === 'group' && parseInt(currentId) === parseInt(grupo.grupo_id)) {
                      const textoContenido = `<strong class="text-sky-600 dark:text-sky-400 text-xs block mb-0.5">${msg.nombre_remitente || 'Usuario'}</strong>${msg.mensaje}`;
                      appendMessageDb(textoContenido, false, msg.fecha_envio, false, msg.leido == 1, (msg.msj_id || msg.id), (msg.carpeta || ''), (msg.carpeta_estado || 0));
                    } else {
                      playNotificationSound();
                      showSystemNotification(`Mensaje en ${grupo.nombre_grupo}: ${msg.mensaje}`);
                      
                      const badgeEl = document.getElementById(`badge-grupo-${grupo.grupo_id}`);
                      if (badgeEl) {
                        let actual = parseInt(badgeEl.innerText) || 0;
                        badgeEl.innerText = actual + 1;
                        badgeEl.classList.remove('hidden');
                      }
                    }
                  }
                }
              });
            }
          } catch (e) {
            console.error(`Error al verificar grupo ${grupo.grupo_id}`, e);
          }
        }
      }
      firstGroupPollDone = true;
    }

    // MANEJO DEL MENÚ Y ADJUNTOS
    const attachBtn = document.getElementById('attach-btn');
    const attachMenu = document.getElementById('attach-menu');
    const cameraInput = document.getElementById('camera-input');
    const galleryInput = document.getElementById('gallery-input');
    const pdfInput = document.getElementById('pdf-input');

    attachBtn.addEventListener('click', (e) => {
      e.stopPropagation();
      if (chatType === 'bot') {
        alert("El asistente virtual solo admite texto por ahora.");
        return;
      }
      attachMenu.classList.toggle('hidden');
      attachMenu.classList.toggle('flex');
    });

    document.addEventListener('click', () => {
      if (attachMenu) {
        attachMenu.classList.add('hidden');
        attachMenu.classList.remove('flex');
      }
    });

    function triggerInput(inputId) {
      if (attachMenu) {
        attachMenu.classList.add('hidden');
        attachMenu.classList.remove('flex');
      }
      document.getElementById(inputId).click();
    }

   function handleImageSelection(e) {
      const file = e.target.files[0];
      if (!file) return;

      if (!file.type.startsWith('image/')) {
        alert("Por favor, selecciona solo imágenes.");
        return;
      }

      // NUEVO: Muestra la vista previa bonita arriba del texto
      mostrarPreviewSubiendo('🖼️');

      const imgURL = URL.createObjectURL(file);
      const img = new Image();
      
      img.onload = function() {
        URL.revokeObjectURL(imgURL);

        const canvas = document.createElement('canvas');
        const MAX_WIDTH = 800; 
        const MAX_HEIGHT = 800;
        let width = img.width;
        let height = img.height;

        if (width > height) {
          if (width > MAX_WIDTH) {
            height *= MAX_WIDTH / width;
            width = MAX_WIDTH;
          }
        } else {
          if (height > MAX_HEIGHT) {
            width *= MAX_HEIGHT / height;
            height = MAX_HEIGHT;
          }
        }

        canvas.width = width;
        canvas.height = height;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0, width, height);

        canvas.toBlob(async (blob) => {
          const formData = new FormData();
          formData.append('imagen', blob, 'chat_img.jpg');

          try {
            const response = await fetch('subir_imagen.php', { method: 'POST', body: formData });
            const textResponse = await response.text(); 
            
            try {
              const data = JSON.parse(textResponse);

              if (data.status === 'success') {
			  	// NUEVO: Guardamos el peso en la memoria global (window)
    			document.body.setAttribute('data-peso-archivo', data.peso_bytes); 
    			console.log("1. Peso tatuado en el HTML:", document.body.getAttribute('data-peso-archivo'));
                // NUEVO: La imagen se subió, pero NO se envía al chat todavía. Se queda en memoria.
                const mensajeImagen = `[img]${data.ruta}[/img]`;
                mostrarPreviewListo('🖼️', mensajeImagen, 'Imagen lista');
              } else {
                alert("Error: " + data.message);
                cancelarAdjunto();
              }
            } catch (parseError) {
              console.error("Respuesta cruda:", textResponse);
              cancelarAdjunto();
            }
          } catch (error) {
            console.error("Error de conexión:", error);
            cancelarAdjunto();
          }
        }, 'image/jpeg', 0.7); 
      };

      img.src = imgURL;
    }

    cameraInput.addEventListener('change', handleImageSelection);
    galleryInput.addEventListener('change', handleImageSelection);

  pdfInput.addEventListener('change', async (e) => {
      const file = e.target.files[0];
      if (!file) return;

      if (file.type !== 'application/pdf') {
        alert("Por favor, selecciona un archivo PDF válido.");
        return;
      }
      
      if (file.size > 5242880) {
        alert("El PDF supera el límite de 5MB.");
        return;
      }

      // NUEVO: Vista previa subiendo
      mostrarPreviewSubiendo('📄');

      const formData = new FormData();
      formData.append('documento', file);

      try {
        const response = await fetch('subir_pdf.php', { method: 'POST', body: formData });
        const textResponse = await response.text();
        
        try {
          const data = JSON.parse(textResponse);
          if (data.status === 'success') {
		  document.body.setAttribute('data-peso-archivo', data.peso_bytes);
            // NUEVO: Archivo listo en memoria
            const mensajePdf = `[pdf]${data.ruta}[/pdf]`;
            mostrarPreviewListo('📄', mensajePdf, file.name); // Muestra el nombre real del archivo
          } else {
            alert(data.message);
            cancelarAdjunto();
          }
        } catch (e) {
          console.error("Respuesta cruda:", textResponse);
          cancelarAdjunto();
        }
      } catch (error) {
        console.error("Error de red:", error);
        cancelarAdjunto();
      }
    });
	
	
	
	const videoInput = document.getElementById('video-input');
    
   videoInput.addEventListener('change', async (e) => {
      const file = e.target.files[0];
      if (!file) return;

      if (!file.type.startsWith('video/')) {
        alert("Por favor, selecciona un archivo de video válido.");
        videoInput.value = '';
        return;
      }
      
      const MAX_SIZE = 16 * 1024 * 1024;
      if (file.size > MAX_SIZE) {
        alert("El video es demasiado pesado. El límite máximo permitido es 16 MB.");
        videoInput.value = '';
        return;
      }

      // NUEVO: Vista previa subiendo
      mostrarPreviewSubiendo('🎥');

      const formData = new FormData();
      formData.append('video', file);

      try {
        const response = await fetch('subir_video.php', { method: 'POST', body: formData });
        const textResponse = await response.text();
        
        try {
          const data = JSON.parse(textResponse);
          if (data.status === 'success') {
		    document.body.setAttribute('data-peso-archivo', data.peso_bytes);
            // NUEVO: Video en memoria
            const mensajeVideo = `[video]${data.ruta}[/video]`;
            mostrarPreviewListo('🎥', mensajeVideo, 'Video listo');
          } else {
            alert(data.message);
            cancelarAdjunto();
          }
        } catch (e) {
          console.error("Respuesta cruda:", textResponse);
          alert("Error en el servidor al subir el video.");
          cancelarAdjunto();
        }
      } catch (error) {
        console.error("Error de red:", error);
        cancelarAdjunto();
      }
      
      videoInput.value = ''; 
    });
	
	

    // MANEJO DE GRABACIÓN DE AUDIO
    const micBtn = document.getElementById('mic-btn');
    const micIcon = document.getElementById('mic-icon');
    const micTimer = document.getElementById('mic-timer');

    if (micBtn) {
      micBtn.addEventListener('click', async (e) => {
        e.preventDefault();
        e.stopPropagation();

        if (chatType === 'bot') {
          alert("El asistente virtual solo admite texto por ahora.");
          return;
        }

        if (!isRecording) {
          if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
            alert("Tu navegador o la conexión actual (se requiere HTTPS) bloquea el micrófono.");
            return;
          }

          try {
            const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
            audioChunks = [];
            
            mediaRecorder = new MediaRecorder(stream);
            
            mediaRecorder.ondataavailable = event => {
              if (event.data.size > 0) audioChunks.push(event.data);
            };

            mediaRecorder.onstop = async () => {
              const audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
              audioChunks = []; 
              stream.getTracks().forEach(track => track.stop());
              await uploadAudio(audioBlob);
            };

            mediaRecorder.start();
            isRecording = true;
            
            micIcon.classList.add('text-red-500', 'animate-pulse');
            micTimer.classList.remove('hidden');
            recordSeconds = 0;
            micTimer.innerText = '00:00';
            
            recordInterval = setInterval(() => {
              recordSeconds++;
              const mins = String(Math.floor(recordSeconds / 60)).padStart(2, '0');
              const secs = String(recordSeconds % 60).padStart(2, '0');
              micTimer.innerText = `${mins}:${secs}`;
            }, 1000);

          } catch (err) {
            console.error("Error micrófono:", err);
            if (err.name === 'NotAllowedError' || err.name === 'PermissionDeniedError') {
              alert("Permiso de micrófono denegado en el navegador.");
            } else {
              alert("No se pudo iniciar el micrófono: " + err.message);
            }
          }
        } else {
          if (mediaRecorder && mediaRecorder.state !== "inactive") {
            mediaRecorder.stop();
          }
          isRecording = false;
          clearInterval(recordInterval);
          
          micIcon.classList.remove('text-red-500', 'animate-pulse');
          micTimer.classList.add('hidden');
        }
      });
    }

    async function uploadAudio(blob) {
      const tempId = 'carga-' + Date.now();
      appendMessage(`<span id="${tempId}">⏳ <em>Subiendo nota de voz...</em></span>`, true);

      const formData = new FormData();
      formData.append('audio', blob, 'nota_voz.webm');

      try {
        const response = await fetch('subir_audio.php', { method: 'POST', body: formData });
        const textResponse = await response.text();
        
        try {
          const data = JSON.parse(textResponse);
          if (data.status === 'success') {
            const mensajeAudio = `[audio]${data.ruta}[/audio]`;
            sendPayload('', mensajeAudio, data.peso_bytes);
            
            const tempElement = document.getElementById(tempId);
            if (tempElement) {
              const horaActual = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
              tempElement.parentNode.innerHTML = formatearMensaje(mensajeAudio) + `<span class="block text-[10px] text-slate-400 dark:text-slate-300/70 text-right mt-1">${horaActual}</span>`;
            }
          } else {
            alert("Error: " + data.message);
          }
        } catch (e) {
          console.error("Respuesta cruda del servidor:", textResponse);
        }
      } catch (error) {
        console.error("Error de red al subir audio:", error);
      }
    }

   // MODAL IMAGEN CON ZOOM MULTITÁCTIL (WEB + APK CAPACITOR)
let imgScale = 1;
let imgStartDist = 0;
let imgStartScale = 1;
let imgPosX = 0;
let imgPosY = 0;
let imgStartX = 0;
let imgStartY = 0;
let imgIsDragging = false;

function openImageModal(src) {
  const modal = document.getElementById('image-modal');
  const modalImg = document.getElementById('modal-img');
  const downloadBtn = document.getElementById('download-modal-btn');
  
  if (!modal || !modalImg) return;

  modalImg.src = src;
  
if (downloadBtn) {
    downloadBtn.onclick = (e) => {
      e.preventDefault(); // Evita fallos
      descargarArchivoKOSMOS(src); // Llama a la nueva función
    };
  }
  
  resetImageZoom();

  modal.classList.remove('hidden');
  document.body.style.overflow = 'hidden'; 
}

function closeImageModal() {
  const modal = document.getElementById('image-modal');
  const modalImg = document.getElementById('modal-img');
  
  if (!modal) return;
  modal.classList.add('hidden');
  if (modalImg) modalImg.src = ''; 
  document.body.style.overflow = 'auto';
  
  resetImageZoom();
}

function resetImageZoom() {
  imgScale = 1;
  imgPosX = 0;
  imgPosY = 0;
  applyImageTransform();
}

function applyImageTransform() {
  const modalImg = document.getElementById('modal-img');
  if (modalImg) {
    modalImg.style.transform = `translate(${imgPosX}px, ${imgPosY}px) scale(${imgScale})`;
  }
}

// Cierre al hacer clic fuera
document.getElementById('image-modal')?.addEventListener('click', (e) => {
  if (e.target.id === 'image-modal') closeImageModal();
});

// EVENTOS TÁCTILES PARA WEBVIEW DE ANDROID
const modalImgElem = document.getElementById('modal-img');
if (modalImgElem) {
  // Asegurar que WebView no capture el evento como scroll
  modalImgElem.style.touchAction = 'none';

  modalImgElem.addEventListener('touchstart', (e) => {
    if (e.touches.length === 2) {
      e.preventDefault();
      imgStartDist = Math.hypot(
        e.touches[0].clientX - e.touches[1].clientX,
        e.touches[0].clientY - e.touches[1].clientY
      );
      imgStartScale = imgScale;
    } else if (e.touches.length === 1 && imgScale > 1) {
      imgIsDragging = true;
      imgStartX = e.touches[0].clientX - imgPosX;
      imgStartY = e.touches[0].clientY - imgPosY;
    }
  }, { passive: false });

  modalImgElem.addEventListener('touchmove', (e) => {
    if (e.touches.length === 2 && imgStartDist > 0) {
      e.preventDefault();
      const currentDist = Math.hypot(
        e.touches[0].clientX - e.touches[1].clientX,
        e.touches[0].clientY - e.touches[1].clientY
      );
      imgScale = Math.min(Math.max(1, (currentDist / imgStartDist) * imgStartScale), 4);
      applyImageTransform();
    } else if (e.touches.length === 1 && imgIsDragging && imgScale > 1) {
      e.preventDefault();
      imgPosX = e.touches[0].clientX - imgStartX;
      imgPosY = e.touches[0].clientY - imgStartY;
      applyImageTransform();
    }
  }, { passive: false });

  modalImgElem.addEventListener('touchend', (e) => {
    if (e.touches.length < 2) imgStartDist = 0;
    if (e.touches.length === 0) imgIsDragging = false;

    if (imgScale <= 1) {
      resetImageZoom();
    }
  }, { passive: true });
}

    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape') closeImageModal();
    });

    // TECLADO Y POLLING
    sendBtn.addEventListener('click', sendMessage);
    userInput.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') sendMessage();
    });

    userInput.addEventListener('focus', () => {
      setTimeout(() => { hacerScrollAbajo(); }, 300);
    });
    
    backBtn.addEventListener('click', () => {
      if (window.innerWidth < 768) {
        mainChat.classList.add('hidden');
        mainChat.classList.remove('flex');
        sidebar.classList.remove('hidden');
        chatType = 'bot';
        currentId = null; 
      }
    });

    setInterval(verificarMensajesNuevos, 4000);
	
	// Auto-ajustar altura del textarea al escribir
userInput.addEventListener('input', function() {
  this.style.height = 'auto'; // Resetea la altura para recalcular
  this.style.height = this.scrollHeight + 'px'; // Ajusta al contenido
});
    
    // REPRODUCTOR PERSONALIZADO ESTILO WHATSAPP
    function formatAudioTime(seconds) {
      if (!seconds || isNaN(seconds) || seconds === Infinity || seconds === -Infinity) {
        return "0:00";
      }
      const mins = Math.floor(seconds / 60);
      const secs = Math.floor(seconds % 60);
      return `${mins}:${secs < 10 ? '0' : ''}${secs}`;
    }

    function togglePlayAudio(id) {
      const audio = document.getElementById(id);
      const iconPlay = document.getElementById(`icon-play-${id}`);
      const iconPause = document.getElementById(`icon-pause-${id}`);

      if (!audio) return;

      if (audio.paused) {
        document.querySelectorAll('audio').forEach(a => {
          if (a.id !== id && !a.paused) {
            a.pause();
            const otherId = a.id;
            const p = document.getElementById(`icon-play-${otherId}`);
            const pa = document.getElementById(`icon-pause-${otherId}`);
            if (p) p.classList.remove('hidden');
            if (pa) pa.classList.add('hidden');
          }
        });

        audio.play().then(() => {
          if (audio.duration && !isNaN(audio.duration) && audio.duration !== Infinity) {
            const timeLabel = document.getElementById(`time-${id}`);
            if (timeLabel && audio.currentTime === 0) {
              timeLabel.innerText = formatAudioTime(audio.duration);
            }
          }
        }).catch(err => console.error("Error al reproducir audio:", err));

        iconPlay.classList.add('hidden');
        iconPause.classList.remove('hidden');
      } else {
        audio.pause();
        iconPlay.classList.remove('hidden');
        iconPause.classList.add('hidden');
      }
    }

    function initAudioPlayer(id) {
      const audio = document.getElementById(id);
      const timeLabel = document.getElementById(`time-${id}`);
      if (audio && timeLabel) {
        if (audio.duration && !isNaN(audio.duration) && audio.duration !== Infinity) {
          timeLabel.innerText = formatAudioTime(audio.duration);
        } else {
          timeLabel.innerText = "0:00";
        }
      }
    }

    function updateAudioProgress(id) {
      const audio = document.getElementById(id);
      const seek = document.getElementById(`seek-${id}`);
      const timeLabel = document.getElementById(`time-${id}`);

      if (audio && seek && timeLabel) {
        const duracionValida = audio.duration && !isNaN(audio.duration) && audio.duration !== Infinity;
        
        if (duracionValida) {
          const value = (audio.currentTime / audio.duration) * 100;
          seek.value = value || 0;
          timeLabel.innerText = formatAudioTime(audio.currentTime);
        } else {
          timeLabel.innerText = formatAudioTime(audio.currentTime);
        }
      }
    }

    function seekAudio(id, percent) {
      const audio = document.getElementById(id);
      if (audio && audio.duration && !isNaN(audio.duration) && audio.duration !== Infinity) {
        audio.currentTime = (percent / 100) * audio.duration;
      }
    }

    function resetAudioPlayer(id) {
      const iconPlay = document.getElementById(`icon-play-${id}`);
      const iconPause = document.getElementById(`icon-pause-${id}`);
      const seek = document.getElementById(`seek-${id}`);
      const timeLabel = document.getElementById(`time-${id}`);
      const audio = document.getElementById(id);
      
      if (iconPlay) iconPlay.classList.remove('hidden');
      if (iconPause) iconPause.classList.add('hidden');
      if (seek) seek.value = 0;
      if (timeLabel && audio && audio.duration && !isNaN(audio.duration) && audio.duration !== Infinity) {
        timeLabel.innerText = formatAudioTime(audio.duration);
      } else if (timeLabel) {
        timeLabel.innerText = "0:00";
      }
    }

    function changeSpeed(id) {
      const audio = document.getElementById(id);
      const speedBtn = document.getElementById(`speed-${id}`);
      if (!audio || !speedBtn) return;

      if (audio.playbackRate === 1.0) {
        audio.playbackRate = 1.5;
        speedBtn.innerText = '1.5x';
      } else if (audio.playbackRate === 1.5) {
        audio.playbackRate = 2.0;
        speedBtn.innerText = '2x';
      } else {
        audio.playbackRate = 1.0;
        speedBtn.innerText = '1x';
      }
    }

async function descargarAudioUniversal(urlAudio) {
  try {
    // 1. Si es la app de Android, pasamos el audio al navegador nativo para que lo descargue
    if (window.Capacitor && window.Capacitor.isNativePlatform() && window.Capacitor.Plugins.Browser) {
        await window.Capacitor.Plugins.Browser.open({ url: urlAudio });
        return; // Salimos para no ejecutar el código web
    }

    // 2. Comportamiento normal para la Web
    const response = await fetch(urlAudio);
    const blob = await response.blob();
    
    const blobUrl = URL.createObjectURL(blob);
    const tempAnchor = document.createElement('a');
    tempAnchor.href = blobUrl;
    
    const fechaNombre = new Date().toISOString().slice(0,10);
    tempAnchor.download = `nota_de_voz_${fechaNombre}.mp3`;
    
    document.body.appendChild(tempAnchor);
    tempAnchor.click();
    document.body.removeChild(tempAnchor);
    
    setTimeout(() => URL.revokeObjectURL(blobUrl), 1000);
  } catch (error) {
    console.error("Error al descargar archivo de audio:", error);
    window.open(urlAudio, '_blank'); // Respaldo por si algo falla
  }
}


async function descargarVideoKOSMOS(urlVideo) {
  try {
    if (window.Capacitor && window.Capacitor.isNativePlatform() && window.Capacitor.Plugins.Browser) {
        await window.Capacitor.Plugins.Browser.open({ url: urlVideo });
    } else {
        const a = document.createElement('a');
        a.href = urlVideo;
        a.download = '';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    }
  } catch (error) {
    console.error('Error al descargar video:', error);
    window.open(urlVideo, '_blank');
  }
}


async function descargarArchivoKOSMOS(urlMedia) {
  try {
    const baseUrl = window.location.href.substring(0, window.location.href.lastIndexOf('/') + 1);
    const urlAbsoluta = urlMedia.startsWith('http') ? urlMedia : baseUrl + urlMedia;
    
    const urlDescarga = 'descargar_archivo.php?url=' + encodeURIComponent(urlAbsoluta);

    if (window.Capacitor && window.Capacitor.isNativePlatform()) {
        // En lugar del iframe, le decimos al WebView que procese la URL directamente.
        // Al detectar las cabeceras de descarga de PHP, no abrirá reproductores,
        // interceptará el archivo con el DownloadListener de Java.
        window.location.href = urlDescarga;
    } else {
        // Web / PC
        const a = document.createElement('a');
        a.href = urlDescarga;
        a.download = '';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    }
  } catch (error) {
    console.error('Error al descargar:', error);
  }
}
	
	//borrar badge
	
async function actualizarBadgeNativo() {
  if (window.Capacitor && window.Capacitor.isNativePlatform()) {
    const Badge = window.Capacitor.Plugins.Badge;
    
    if (Badge) {
      let totalSinLeer = 0;
      
      // 1. Sumar los mensajes no leídos de los contactos directos
      document.querySelectorAll('[id^="badge-contact-"]:not(.hidden)').forEach(el => {
        totalSinLeer += parseInt(el.innerText) || 0;
      });
      
      // 2. Sumar los mensajes no leídos de los grupos
      document.querySelectorAll('[id^="badge-grupo-"]:not(.hidden)').forEach(el => {
        totalSinLeer += parseInt(el.innerText) || 0;
      });

      try {
        if (totalSinLeer > 0) {
          // Si aún hay mensajes, actualiza el número en el ícono
          await Badge.set({ count: totalSinLeer });
        } else {
          // SOLO si el total es 0, limpiamos el ícono y la barra del celular
          await Badge.clear();
          const PushNotifications = window.Capacitor.Plugins.PushNotifications;
          if (PushNotifications) {
            await PushNotifications.removeAllDeliveredNotifications();
          }
        }
      } catch (error) { 
        console.log("Error actualizando badge:", error); 
      }
    }
  }
}


// Detectar scroll hacia arriba para cargar historial antiguo
chatBox.addEventListener('scroll', async () => {
  // Si tocó el techo (scrollTop === 0) y hay mensajes por cargar
  if (chatBox.scrollTop === 0 && hayMasMensajes && !cargandoHistorial) {
    cargandoHistorial = true;
    offsetMensajes += limiteMensajes; // Sumamos 10 al offset

    // Guardamos la altura actual del contenedor para que la pantalla no salte
    const alturaAnterior = chatBox.scrollHeight;

    try {
      let endpoint = chatType === 'group' 
        ? `cargar_historial_grupo.php?grupo_id=${currentId}&offset=${offsetMensajes}&t=${Date.now()}`
        : `cargar_historial.php?contacto=${currentId}&offset=${offsetMensajes}`;

      const response = await fetch(endpoint);
      const data = await response.json();

      if (data.status === 'success' && data.messages.length > 0) {
        
        // Invertimos el array para que, al usar prepend (poner arriba), queden cronológicos
        data.messages.reverse().forEach(msg => {
          let msgId = '';
          let soyYo = false;
          let textoContenido = msg.mensaje;

          if (chatType === 'group') {
            msgId = `g_${currentId}_${msg.msj_grupo_id || msg.fecha_envio}`;
            soyYo = parseInt(msg.remitente_up_id) === parseInt(currentUserId);
            if (!soyYo) {
              textoContenido = `<strong class="text-sky-600 dark:text-sky-400 text-xs block mb-0.5">${msg.nombre_remitente || 'Usuario'}</strong>${msg.mensaje}`;
            }
          } else {
            msgId = msg.msj_id || msg.fecha_envio;
            soyYo = parseInt(msg.remitente_up_id) !== parseInt(currentId);
          }

          processedMessageIds.add(msgId);
          
          // Enviamos 'true' al final para indicar que se debe insertar ARRIBA
          appendMessageDb(textoContenido, soyYo, msg.fecha_envio, true, msg.leido == 1, (msg.msj_id || msg.id), (msg.carpeta || ''), (msg.carpeta_estado || 0)); 
        });

        // Calculamos la nueva altura y ajustamos el scroll para que el usuario no pierda su lugar
        chatBox.scrollTop = chatBox.scrollHeight - alturaAnterior;
        
      } else {
        hayMasMensajes = false; // Ya no hay más historial en la BD
      }
    } catch (error) {
      console.error("Error al cargar historial antiguo", error);
    } finally {
      cargandoHistorial = false;
    }
  }
});


// Abrir el modal con animación
function abrirModalToken() {
    const modal = document.getElementById('modalToken');
    modal.classList.remove('hidden');
    // Pequeño delay para que la transición de opacidad y escala funcione
    setTimeout(() => {
        modal.classList.remove('opacity-0');
        modal.querySelector('div').classList.remove('scale-95');
    }, 10);
    
    // Enfocar el input automáticamente
    document.getElementById('inputCajaToken').focus();
}

// Cerrar el modal con animación
function cerrarModalToken() {
    const modal = document.getElementById('modalToken');
    modal.classList.add('opacity-0');
    modal.querySelector('div').classList.add('scale-95');
    setTimeout(() => {
        modal.classList.add('hidden');
        // Limpiar la caja de texto al cerrar
        document.getElementById('inputCajaToken').value = ''; 
    }, 300);
}

// Capturar el token y enviarlo al chat
// Capturar el token y redirigir la página
function enviarTokenDesdeModal() {
    const inputToken = document.getElementById('inputCajaToken');
    const valorToken = inputToken.value.trim();
    
    if (valorToken !== "") {
        // En lugar de enviar un mensaje al chat, recargamos la página apuntando al index con el parámetro
        // Usamos encodeURIComponent por seguridad, por si el token tiene caracteres especiales
        window.location.href = "index.php?token=" + encodeURIComponent(valorToken); 
        
    } else {
        // Un pequeño feedback visual si intentan enviarlo vacío
        inputToken.classList.add('border-red-500');
        setTimeout(() => inputToken.classList.remove('border-red-500'), 1500);
    }
}


	
  </script>
  
<!-- Modal para Ingresar Token (Oculto por defecto) -->
<div id="modalToken" class="fixed inset-0 z-50 hidden bg-slate-900/60 backdrop-blur-sm flex items-center justify-center p-4 opacity-0 transition-opacity duration-300">
    <!-- Contenedor del Modal -->
    <div class="bg-white dark:bg-[#202c33] rounded-2xl shadow-2xl w-full max-w-sm p-6 transform scale-95 transition-transform duration-300 border border-slate-100 dark:border-slate-700/50">
        
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-bold text-slate-800 dark:text-slate-100 flex items-center gap-2">
                <svg class="w-5 h-5 text-emerald-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z'></path></svg>
                Tu Token de Acceso
            </h3>
            <button onClick="cerrarModalToken()" class="text-slate-400 hover:text-slate-600 dark:hover:text-slate-300 outline-none">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
            </button>
        </div>
        
        <input type="text" id="inputCajaToken" placeholder="Ej: KOSMOS-1234" autocomplete="off" class="w-full p-3 rounded-xl border border-slate-300 dark:border-slate-600 bg-slate-50 dark:bg-slate-800 text-slate-800 dark:text-slate-100 mb-5 focus:outline-none focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 transition-all">
        
        <button onClick="enviarTokenDesdeModal()" class="w-full bg-emerald-500 hover:bg-emerald-600 text-white font-medium py-2.5 px-4 rounded-xl shadow-md transition-colors outline-none">
            Validar y Continuar
        </button>
    </div>
</div>



<!-- MODAL DE VISOR DE PDF -->
<div id="pdf-modal" class="fixed inset-0 z-50 bg-black/95 hidden flex flex-col p-2">
  <!-- Cabecera -->
  <div class="flex justify-between items-center p-2 text-white shrink-0">
    <span id="pdf-modal-title" class="text-sm font-bold truncate flex-1">Documento PDF</span>
    <button onClick="closePdfModal()" class="bg-slate-800 text-white w-10 h-10 rounded-full flex items-center justify-center text-2xl font-bold hover:bg-slate-700 transition-colors ml-4 shadow-lg">&times;</button>
  </div>
  
  <!-- Contenedor dinámico HD -->
  <div id="pdf-pages-container" class="flex-1 w-full overflow-y-auto flex flex-col items-center p-2 pb-24">
  </div>

  <!-- Botón de Descarga -->
  <a id="download-pdf-btn" href="" download="documento.pdf" class="fixed bottom-6 right-6 z-50 bg-sky-600/90 text-white w-14 h-14 rounded-full flex items-center justify-center hover:bg-sky-500 transition-colors cursor-pointer shadow-xl" title="Descargar PDF">
    <svg class="w-7 h-7" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
    </svg>
  </a>
</div>


<!-- MODAL DE CAMBIO DE FOTO -->
<div id="profile-modal" class="fixed inset-0 z-50 bg-black/70 hidden flex items-center justify-center p-4">
  <div class="bg-white dark:bg-slate-900 rounded-xl shadow-2xl max-w-sm w-full p-6 border border-slate-200 dark:border-slate-800 text-center relative">
    <button onClick="closeProfileModal()" class="absolute top-4 right-4 text-slate-400 hover:text-slate-600 dark:hover:text-slate-200 text-2xl font-bold">&times;</button>
    
    <!-- Aquí agregamos el ID al título para cambiarlo dinámicamente -->
    <h3 id="modal-title-text" class="text-base font-bold text-slate-800 dark:text-slate-100 mb-4">Tu Foto de Perfil</h3>
    
    <div class="mb-5 flex justify-center">
      <div class="w-28 h-28 rounded-full overflow-hidden bg-slate-100 dark:bg-slate-800 border-4 border-sky-500/30 shadow-md flex items-center justify-center">
        <img id="profile-preview" src="<?php echo htmlspecialchars(isset($row_empresa['mi_foto']) ?$row_empresa['mi_foto'] : ''); ?>" class="w-full h-full object-cover <?php echo empty($row_empresa['mi_foto']) ? 'hidden' : ''; ?>">
        <span id="profile-placeholder" class="text-4xl font-bold text-slate-400 <?php echo !empty($row_empresa['mi_foto']) ? 'hidden' : ''; ?>">👤</span>
      </div>
    </div>

    <form id="profile-form" class="space-y-3">
      <input type="file" name="foto_perfil" id="profile-input" accept="image/*" class="hidden" onChange="previewProfileImage(event)">
      
      <button type="button" onClick="document.getElementById('profile-input').click()" class="w-full bg-slate-100 dark:bg-slate-800 hover:bg-slate-200 dark:hover:bg-slate-700 text-slate-700 dark:text-slate-200 text-sm font-semibold py-2.5 rounded-lg transition-colors border border-slate-300 dark:border-slate-700">
        📁 Seleccionar Imagen
      </button>
      
      <button type="submit" id="save-profile-btn" class="w-full bg-sky-600 hover:bg-sky-500 text-white text-sm font-bold py-2.5 rounded-lg transition-colors shadow-sm">
        Guardar Foto
      </button>
    </form>
  </div>
</div>



<!-- MODAL DE PROGRAMACIÓN -->
<div id="schedule-modal" class="fixed inset-0 z-[100] hidden bg-slate-900/60 backdrop-blur-sm flex items-center justify-center transition-opacity duration-300">
  <!-- Contenedor Principal -->
  <div class="bg-white dark:bg-slate-800 w-11/12 max-w-sm rounded-2xl shadow-2xl transform transition-all border border-slate-200 dark:border-slate-700">
    
    <!-- CABECERA -->
    <div class="p-5 border-b border-slate-200 dark:border-slate-700 flex justify-between items-center bg-slate-50 dark:bg-slate-800/80 rounded-t-2xl">
      <div class="flex items-center gap-3">
        <!-- Ícono decorativo (AHORA EN AZUL) -->
        <div class="w-10 h-10 rounded-full bg-blue-100 dark:bg-blue-900/50 flex items-center justify-center text-blue-600 dark:text-blue-400 shadow-inner">
          <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
          </svg>
        </div>
        <div>
          <h3 class="font-bold text-slate-800 dark:text-slate-200 text-base">Programar Envío</h3>
          <p class="text-xs text-slate-500 dark:text-slate-400">Elige fecha y hora</p>
        </div>
      </div>
      <!-- Botón Cerrar (X) -->
      <button onClick="closeScheduleModal()" class="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200 transition-colors bg-slate-100 hover:bg-slate-200 dark:bg-slate-700 dark:hover:bg-slate-600 rounded-full p-1.5">
        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
      </button>
    </div>

    <!-- CUERPO DEL MODAL -->
    <div class="p-5">
      <label class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
        Fecha y hora de entrega
      </label>
      <!-- INPUT DE FECHA -->
<!-- INPUT DE FECHA ACTUALIZADO -->
<input type="text" id="schedule-input" placeholder="Selecciona la fecha y hora..."
       class="w-full bg-slate-50 dark:bg-slate-900 border border-slate-300 dark:border-slate-600 text-slate-800 dark:text-slate-200 text-sm rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-blue-500 block p-3.5 transition-colors shadow-sm cursor-pointer outline-none">
      <p class="text-[10px] text-slate-400 dark:text-slate-500 mt-2 text-center">
        * Se ajustará automáticamente al cuarto de hora más cercano.
      </p>
    </div>

    <!-- PIE / BOTONES -->
    <div class="p-4 border-t border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800/80 rounded-b-2xl flex justify-between gap-3">
      
      <!-- Botón Borrar (Rojo) -->
      <button onClick="clearSchedule()" class="px-4 py-2 text-sm font-semibold text-red-600 bg-red-50 hover:bg-red-100 dark:bg-red-900/20 dark:text-red-400 dark:hover:bg-red-900/40 rounded-lg transition-colors border border-red-200 dark:border-red-800/50">
        Borrar
      </button>
      
      <div class="flex gap-2 w-full justify-end">
        <!-- Botón Cancelar -->
        <button onClick="closeScheduleModal()" class="px-4 py-2 text-sm font-semibold text-slate-700 bg-white border border-slate-300 hover:bg-slate-100 dark:bg-slate-700 dark:text-slate-200 dark:border-slate-600 dark:hover:bg-slate-600 rounded-lg transition-colors">
          Cancelar
        </button>
        <!-- Botón Confirmar (AHORA EN AZUL) -->
        <button onClick="confirmSchedule()" class="px-5 py-2 text-sm font-bold text-white bg-blue-600 hover:bg-blue-700 shadow-md shadow-blue-500/30 rounded-lg transition-all hover:scale-105 active:scale-95">
          Confirmar
        </button>
      </div>
    </div>

  </div>
</div>


<script>
const miFotoPerfilURL = "<?php echo addslashes(isset($row_empresa['mi_foto']) ?$row_empresa['mi_foto'] : ''); ?>";

function openProfileModal() {
  const form = document.getElementById('profile-form');
  delete form.dataset.targetGroup; // Limpiamos cualquier rastro de grupo anterior
  document.getElementById('modal-title-text').innerText = 'Tu Foto de Perfil';
  
  const preview = document.getElementById('profile-preview');
  const placeholder = document.getElementById('profile-placeholder');
  
  // Mostrar la foto del usuario o el ícono por defecto
  if (miFotoPerfilURL && miFotoPerfilURL.trim() !== '') {
      preview.src = miFotoPerfilURL;
      preview.classList.remove('hidden');
      placeholder.classList.add('hidden');
  } else {
      preview.src = '';
      preview.classList.add('hidden');
      placeholder.classList.remove('hidden');
      placeholder.innerText = '👤';
  }
  
  document.getElementById('profile-input').value = ''; // Limpiar el input
  document.getElementById('profile-modal').classList.remove('hidden');
}

function openGroupProfileModal(grupoId, fotoGrupoUrl = '') {
  const form = document.getElementById('profile-form');
  form.dataset.targetGroup = grupoId; // Le inyectamos el ID del grupo
  document.getElementById('modal-title-text').innerText = 'Foto del Grupo';
  
  const preview = document.getElementById('profile-preview');
  const placeholder = document.getElementById('profile-placeholder');
  
  // Mostrar la foto del grupo o el ícono por defecto
  if (fotoGrupoUrl && fotoGrupoUrl.trim() !== '') {
      preview.src = fotoGrupoUrl;
      preview.classList.remove('hidden');
      placeholder.classList.add('hidden');
  } else {
      preview.src = '';
      preview.classList.add('hidden');
      placeholder.classList.remove('hidden');
      placeholder.innerText = '👥';
  }

  document.getElementById('profile-input').value = ''; // Limpiar el input
  document.getElementById('profile-modal').classList.remove('hidden');
}

function closeProfileModal() {
  document.getElementById('profile-modal').classList.add('hidden');
}

function previewProfileImage(event) {
  const file = event.target.files[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = function(e) {
      const preview = document.getElementById('profile-preview');
      const placeholder = document.getElementById('profile-placeholder');
      preview.src = e.target.result;
      preview.classList.remove('hidden');
      placeholder.classList.add('hidden');
    }
    reader.readAsDataURL(file);
  }
}



document.getElementById('profile-form').addEventListener('submit', function(e) {
  e.preventDefault(); 
  
  const fileInput = document.getElementById('profile-input');
  const file = fileInput.files[0];
  if (!file) {
    alert("Por favor, selecciona una imagen primero.");
    return;
  }

  const btnGuardar = document.getElementById('save-profile-btn');
  const textoOriginal = btnGuardar.innerText;
  btnGuardar.innerText = 'Comprimiendo y subiendo... ⏳';
  btnGuardar.disabled = true;

  const img = new Image();
  img.src = URL.createObjectURL(file);
  
  img.onload = function() {
    URL.revokeObjectURL(img.src);

    const canvas = document.createElement('canvas');
    const MAX_SIZE = 400; 
    let width = img.width;
    let height = img.height;

    if (width > height) {
      if (width > MAX_SIZE) {
        height *= MAX_SIZE / width;
        width = MAX_SIZE;
      }
    } else {
      if (height > MAX_SIZE) {
        width *= MAX_SIZE / height;
        height = MAX_SIZE;
      }
    }

    canvas.width = width;
    canvas.height = height;
    const ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0, width, height);

    canvas.toBlob(async (blob) => {
      const formData = new FormData();
      
      // Verificamos si estamos subiendo foto de grupo o de usuario
      const formEl = document.getElementById('profile-form');
      const targetGroup = formEl.dataset.targetGroup;
      
      let endpoint = 'subir_foto_perfil.php';
      
      if (targetGroup) {
          // Es un grupo
          endpoint = 'subir_foto_grupo.php';
          formData.append('foto_perfil', blob, 'grupo_optimizado.jpg');
          formData.append('grupo_id', targetGroup);
      } else {
          // Es tu usuario personal
          formData.append('foto_perfil', blob, 'perfil_optimizado.jpg');
      }

      try {
        const response = await fetch(endpoint, {
          method: 'POST',
          body: formData
        });
        
        const data = await response.json();
        
        if (data.status === 'success') {
          window.location.reload(); 
        } else {
          alert("Error del servidor: " + data.message);
          btnGuardar.innerText = textoOriginal;
          btnGuardar.disabled = false;
        }
      } catch (error) {
        console.error("Error al subir:", error);
        alert("Fallo la conexión al subir la foto.");
        btnGuardar.innerText = textoOriginal;
        btnGuardar.disabled = false;
      }
    }, 'image/jpeg', 0.8);
  };
});

</script>

<script>
    // 1. Las funciones de validación y renderizado del Link Preview
    function extractURL(text) {
        const urlRegex = /(https?:\/\/[^\s]+)/g;
        const match = text.match(urlRegex);
        return match ? match[0] : null;
    }

// ====== CÓDIGO JAVASCRIPT CORREGIDO PARA EL INDEX.PHP ======

async function renderLinkPreview(messageText, messageContainerId) {
    const url = extractURL(messageText);
    if (!url) return;

    try {
        const response = await fetch(`link-preview.php?url=${encodeURIComponent(url)}`);
        const data = await response.json();

        // 1. NUEVA VALIDACIÓN: Solo aborta si hay un error crítico. 
        // Ya no aborta si falta el título o la imagen.
        if (data.error) return;

        const domain = new URL(url).hostname.replace('www.', '');
        
        // 2. PLAN B DE TÍTULO: Si la página bloqueó todo y no hay título, usamos el dominio
        const cardTitle = data.title && data.title.trim() !== '' ? data.title : domain;

        const previewHTML = `
            <a href="${data.url}" target="_blank" rel="noopener noreferrer" 
               class="block max-w-sm mt-2 border border-sky-400/30 dark:border-slate-600 rounded-xl overflow-hidden bg-sky-50/50 dark:bg-slate-800/80 hover:bg-sky-100 dark:hover:bg-slate-700 transition-colors duration-200 cursor-pointer text-left shadow-sm">
                
                ${data.image ? `
                    <div class="w-full h-28 bg-white border-b border-sky-400/20 dark:border-slate-700/50 flex items-center justify-center p-2">
                        <img src="${data.image}" class="w-full h-full object-contain" alt="Preview" onerror="this.style.display='none'">
                    </div>
                ` : ''}
                
                <div class="p-3">
                    <h4 class="font-semibold text-sm text-slate-800 dark:text-slate-100 truncate">
                        ${cardTitle}
                    </h4>
                    ${data.description ? `<p class="text-[11px] text-slate-600 dark:text-slate-400 mt-1 line-clamp-2 leading-tight">${data.description}</p>` : ''}
                    <span class="text-[10px] text-sky-600 dark:text-sky-400 mt-2 block tracking-wider font-medium">
                        ${domain}
                    </span>
                </div>
            </a>
        `;

        const container = document.getElementById(messageContainerId);
        if (container) {
            container.insertAdjacentHTML('beforeend', previewHTML);
            const chatBox = document.getElementById('chat-box');
            chatBox.scrollTop = chatBox.scrollHeight;
        }

    } catch (error) {
        console.error('Error cargando preview:', error);
    }
}

    // 2. Lógica para enviar el mensaje e inyectarlo en tu #chat-box
    function enviarMensaje() {
        const input = document.getElementById('user-input');
        const chatBox = document.getElementById('chat-box');
        const texto = input.value.trim();

        if (texto === '') return;

        // Generamos un ID único temporal para el mensaje (ej: msg-1696001234)
        const uniqueId = 'msg-' + Date.now();

        // Estructura del globo de chat del usuario (adaptado a tu Tailwind)
        const bubbleHTML = `
            <div class="flex justify-end">
                <div id="${uniqueId}" class="bg-sky-500 dark:bg-sky-600 text-white p-3 rounded-2xl rounded-tr-sm max-w-[85%] shadow-sm text-sm leading-relaxed">
                    <p class="whitespace-pre-wrap">${texto}</p>
                </div>
            </div>
        `;

        // 1. Añadimos el mensaje al DOM
        chatBox.insertAdjacentHTML('beforeend', bubbleHTML);
        
        // 2. Limpiamos el input y bajamos el scroll
        input.value = '';
        input.style.height = 'auto'; // Resetear alto si es dinámico
        chatBox.scrollTop = chatBox.scrollHeight;

        // 3. ¡LA MAGIA! Evaluamos inmediatamente si el texto tiene un enlace
        renderLinkPreview(texto, uniqueId);

        // Aquí iría tu petición fetch/AJAX real hacia tu base de datos para guardar el mensaje...
    }

    // 3. Capturamos los eventos de tu interfaz
    
    // Clic en el botón enviar
    document.getElementById('send-btn').addEventListener('click', enviarMensaje);

    // Presionar Enter en el textarea (sin usar Shift)
    document.getElementById('user-input').addEventListener('keydown', function(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault(); // Evita que haga un salto de línea
            enviarMensaje();
        }
    });
</script>
<!-- SCRIPT CONTROLADOR DEL CANVAS -->
<script>
 // function toggleCanvasPanel() {
//    const canvas = document.getElementById('agreements-canvas');
//    if (canvas.classList.contains('hidden')) {
//      const currentName = document.getElementById('chat-title').innerText;
//      
//      // Capturamos la foto activa en el header del chat principal
//      let photoUrl = '';
//      const headerImg = document.querySelector('#chat-header-avatar img');
//      if (headerImg) {
//        photoUrl = headerImg.src;
//      }
//
//      openCanvasPanel(currentName, photoUrl);
//    } else {
//      closeCanvasPanel();
//    }
//  }

//==================================================

function toggleCanvasPanel() {
  const canvas = document.getElementById('agreements-canvas');
  
  if (canvas.classList.contains('hidden')) {
    // 1. Capturamos Nombre y Foto (Esto ya lo tenías y funciona bien)
    const currentName = document.getElementById('chat-title').innerText;
    
    let photoUrl = '';
    const headerImg = document.querySelector('#chat-header-avatar img');
    if (headerImg) {
      photoUrl = headerImg.src;
    }

    // ====================================================
    // SOLUCIÓN: Caza del ID Activo sin romper nada
    // ====================================================
    let activeId = 0;
    let activeTipo = 'contacto'; // Por defecto asumimos contacto
    
    // Intentamos capturar el ID de las variables que tu sistema ya usa para enviar mensajes:
    if (typeof window.id_destino !== 'undefined' && window.id_destino) {
        activeId = window.id_destino;
    } else if (typeof window.currentChatId !== 'undefined' && window.currentChatId) {
        activeId = window.currentChatId;
    } else if (typeof window.chatId !== 'undefined' && window.chatId) {
        activeId = window.chatId;
    } else {
        // Fallback: Busca un campo oculto por si alguna vez lo agregas al HTML
        const inputHidden = document.querySelector('input[name="id_destino"], input[name="chat_id"]');
        if (inputHidden && inputHidden.value) activeId = inputHidden.value;
    }

    if (activeId === 0) {
        console.warn("KOSMOS: No se detectó el ID del chat. Los mensajes programados no cargarán. Verifica el nombre de tu variable de ID.");
    }

    // Llamamos a openCanvas enviando TODOS los datos
    openCanvasPanel(currentName, photoUrl, activeId, activeTipo);
    
  } else {
    closeCanvasPanel();
  }
}

//==================================================

function openCanvasPanel(contactName, photoUrl = '', id_destino = 0, tipo_destino = '') {
    const canvas = document.getElementById('agreements-canvas');
    const nameLabel = document.getElementById('canvas-contact-name');
    const avatarContainer = document.getElementById('canvas-avatar-container');
    const avatarImg = document.getElementById('canvas-contact-photo');
    
    // Actualiza el nombre
    if (nameLabel && contactName) {
      nameLabel.innerText = contactName;
    }

    // Actualiza la foto dinámicamente
    if (avatarContainer && avatarImg) {
      if (photoUrl && photoUrl.trim() !== '') {
        avatarImg.src = photoUrl;
        avatarContainer.classList.remove('hidden');
      } else {
        avatarContainer.classList.add('hidden');
      }
    }

    const contentChats = document.getElementById('content-chats');
    
    // --- SOLUCIÓN: Si es el bot, evitamos consultar ajax_get_programados.php ---
    if (id_destino === 'bot') {
        if (contentChats) {
            contentChats.innerHTML = '<div class="text-center p-4 text-slate-400 text-xs mt-4">El Asistente Virtual no tiene mensajes programados.</div>';
        }
    } 
// --- Carga de mensajes programados (Para Contactos, Grupos y el Asistente) ---
    if (contentChats && id_destino !== 0 && id_destino !== null && tipo_destino !== '') {
        contentChats.innerHTML = '<div class="text-center p-4 text-slate-500 text-xs mt-4 flex flex-col items-center"><svg class="animate-spin h-5 w-5 text-sky-500 mb-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg> Cargando mensajes...</div>';

        // RUTEO INTELIGENTE: Si el destino es 'bot', llama al archivo nuevo. Si no, llama al normal.
        let urlFetchProg = (id_destino === 'bot') ? 'ajax_get_programados_bot.php' : 'ajax_get_programados.php';

        fetch(urlFetchProg, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                id_destino: id_destino,
                tipo_destino: tipo_destino
            })
        })
        .then(response => response.text())
        .then(html => {
            contentChats.innerHTML = html;
        })
        .catch(error => {
            console.error('Error al cargar mensajes programados:', error);
            contentChats.innerHTML = '<div class="text-center p-4 text-red-500 text-xs mt-4">Error al cargar los mensajes.</div>';
        });
    }

    // Animación de entrada
    canvas.classList.remove('hidden');
    setTimeout(() => {
      canvas.classList.add('flex');
      canvas.classList.remove('translate-x-full');
    }, 10);
}

  function closeCanvasPanel() {
    const canvas = document.getElementById('agreements-canvas');
    canvas.classList.add('translate-x-full');
    setTimeout(() => {
      canvas.classList.add('hidden');
      canvas.classList.remove('flex');
    }, 300);
  }
</script>

<!-- SCRIPT DE PROGRAMACIÓN DE MENSAJES -->
<!-- SCRIPT DE PROGRAMACIÓN DE MENSAJES -->
<script>
// Variable para almacenar la instancia del calendario
  let flatpickrInstance = null;

  function openScheduleModal() {
    const modal = document.getElementById('schedule-modal');
    modal.classList.remove('hidden');
    
    const input = document.getElementById('schedule-input');

    // Inicializar Flatpickr solo si no existe
    if (!flatpickrInstance) {
      flatpickrInstance = flatpickr(input, {
        enableTime: true,
        dateFormat: "Y-m-d\\TH:i", // Formato exacto que necesita tu base de datos
        minDate: "today", // Bloquea días anteriores
        minuteIncrement: 15, // Obliga a seleccionar :00, :15, :30, :45
        locale: "es", // Idioma español
        time_24hr: false, // Reloj de 12 horas (AM/PM)
      });
    }

    // Calcular la hora mínima (aproximada a los próximos 15 min de hoy)
    const now = new Date();
    const m = now.getMinutes();
    const rounded = Math.ceil(m / 15) * 15;
    now.setMinutes(rounded);
    
    flatpickrInstance.set('minTime', now);

    // Si ya había seleccionado algo antes, lo mostramos
    if (typeof fechaEnvioProgramada !== 'undefined' && fechaEnvioProgramada) {
      flatpickrInstance.setDate(fechaEnvioProgramada);
    }
  }

  function closeScheduleModal() {
    document.getElementById('schedule-modal').classList.add('hidden');
  }

  function confirmSchedule() {
    const input = document.getElementById('schedule-input').value;
    const icon = document.getElementById('schedule-icon');
    const badge = document.getElementById('schedule-badge');

    if (input) {
      document.body.setAttribute('data-fecha-programada', input);
      console.log("🕒 Fecha guardada en el DOM:", input);
      
      icon.classList.remove('text-slate-500');
      icon.classList.add('text-blue-500');
      badge.classList.remove('hidden');
    } else {
      clearSchedule();
    }
    
    closeScheduleModal();
  }

  function clearSchedule() {
    document.body.removeAttribute('data-fecha-programada');
    
    if (flatpickrInstance) {
      flatpickrInstance.clear();
    }
    
    const icon = document.getElementById('schedule-icon');
    const badge = document.getElementById('schedule-badge');

    icon.classList.remove('text-blue-500');
    icon.classList.add('text-slate-500');
    badge.classList.add('hidden');
    
    closeScheduleModal();
  }
  
    
  function borrarMensajeProgramado(id_mensaje, tipo_destino, archivo_url) {
  // 1. Confirmar con el usuario
  if (!confirm("¿Estás seguro de que deseas eliminar este mensaje programado?")) {
    return;
  }

  // 2. Dar feedback visual (poner la tarjeta opaca mientras procesa)
  const cardId = 'msg-prog-' + id_mensaje;
  const cardElement = document.getElementById(cardId);
  if (cardElement) {
    cardElement.style.opacity = '0.5';
    cardElement.style.pointerEvents = 'none'; // Evitar doble clic
  }

  // 3. Petición AJAX al servidor
  fetch('ajax_borrar_programado.php', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      id_mensaje: id_mensaje,
      tipo_destino: tipo_destino,
      archivo: archivo_url
    })
  })
  .then(response => response.json())
  .then(data => {
    if (data.status === 'success') {
      // 4. Si se borró con éxito, desaparecer la tarjeta
      if (cardElement) {
        cardElement.style.transition = 'all 0.3s ease';
        cardElement.style.transform = 'scale(0.9)';
        cardElement.style.opacity = '0';
        setTimeout(() => cardElement.remove(), 300);
      }
    } else {
      alert("Error: " + data.message);
      // Restaurar la tarjeta si falló
      if (cardElement) {
        cardElement.style.opacity = '1';
        cardElement.style.pointerEvents = 'auto';
      }
    }
  })
  .catch(error => {
    console.error('Error:', error);
    alert("Ocurrió un error de conexión.");
    if (cardElement) {
      cardElement.style.opacity = '1';
      cardElement.style.pointerEvents = 'auto';
    }
  });
}

async function cambiarPerfil(event, contactoId, nuevoPerId, elementoSvg) {
    event.stopPropagation(); // Evita abrir el chat

    try {
        const response = await fetch('actualizar_perfil_contacto.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `contacto_id=${contactoId}&per_id=${nuevoPerId}`
        });

        const data = await response.json();

        if (data.status === 'success') {
            const contenedor = elementoSvg.closest(`.contenedor-perfiles-${contactoId}`);
            if (!contenedor) return;

            // 1. Apagar TODOS los iconos en ese contenedor
            const todosLosIconos = contenedor.querySelectorAll('svg');
            todosLosIconos.forEach(svg => {
                // Quitar colores encendidos y de hover
                svg.classList.remove(
                    'text-emerald-500', 'dark:text-emerald-400',
                    'text-amber-500', 'dark:text-amber-400',
                    'text-rose-500', 'dark:text-rose-400',
                    'text-blue-500', 'dark:text-blue-400'
                );
                // Restaurar el estado base (gris con hover encendido)
                svg.classList.add('text-slate-300', 'dark:text-slate-600');
                
                // Es importante recuperar el hover original según el icono
                if (svg.querySelector('polygon[points="12 3 22 20 2 20"]')) { // Cliente
                    svg.classList.add('hover:text-emerald-500', 'dark:hover:text-emerald-400');
                } else if (svg.querySelector('rect')) { // Proveedor
                    svg.classList.add('hover:text-amber-500', 'dark:hover:text-amber-400');
                } else if (svg.querySelector('circle')) { // Colaborador
                    svg.classList.add('hover:text-rose-500', 'dark:hover:text-rose-400');
                } else if (svg.querySelector('polygon[points="12 3 21 12 12 21 3 12"]')) { // Por definir
                    svg.classList.add('hover:text-blue-500', 'dark:hover:text-blue-400');
                }
            });

            // 2. Encender SOLO el icono clickeado
            // Le quitamos las clases de "apagado" y los hovers
            elementoSvg.classList.remove(
                'text-slate-300', 'dark:text-slate-600',
                'hover:text-emerald-500', 'dark:hover:text-emerald-400',
                'hover:text-amber-500', 'dark:hover:text-amber-400',
                'hover:text-rose-500', 'dark:hover:text-rose-400',
                'hover:text-blue-500', 'dark:hover:text-blue-400'
            );

            // Le ponemos la clase "encendida" fija que le corresponde
            if (nuevoPerId === 3) elementoSvg.classList.add('text-emerald-500', 'dark:text-emerald-400');
            if (nuevoPerId === 4) elementoSvg.classList.add('text-amber-500', 'dark:text-amber-400');
            if (nuevoPerId === 5) elementoSvg.classList.add('text-rose-500', 'dark:text-rose-400');
            if (nuevoPerId === 6) elementoSvg.classList.add('text-blue-500', 'dark:text-blue-400');

        } else {
            console.error('Error al actualizar el perfil:', data.message);
        }
    } catch (error) {
        console.error('Error de red al actualizar perfil:', error);
    }
}
 
</script>
</body>
</html>