<?php
// whatsapp.php - PHP 8.2
require_once __DIR__ . '/config.php';
$pdo = db();

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ============================================
// CONSTANTES PARA MEDIA Y OPENAI
// ============================================
if (!defined('MEDIA_BASE_URL')) {
    define('MEDIA_BASE_URL', 'https://nodo11.radiosnet.com.ar/whatsapp_ofi/');
}

if (!defined('OPENAI_API_KEY')) {
    define('OPENAI_API_KEY', 'PEGAR_EN_config.php'); // Definir en config.php
}
define('WHISPER_API_URL', 'https://api.openai.com/v1/audio/transcriptions');

// Plantillas a excluir
$PLANTILLA_PREFIJOS = [
    "Hola, buenas tardes. Hace un tiempo charlamos",
    "Hola, buen día. Hace un tiempo charlamos",
    "Hola, buen dia. Hace un tiempo charlamos",
];

// Directorio para uploads
define('UPLOAD_DIR', __DIR__ . '/uploads/');
if (!is_dir(UPLOAD_DIR)) {
    mkdir(UPLOAD_DIR, 0755, true);
}

// Tipos de archivo permitidos
$ALLOWED_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
$ALLOWED_AUDIO_TYPES = ['audio/mpeg', 'audio/mp3', 'audio/wav', 'audio/ogg', 'audio/x-m4a'];
$ALLOWED_VIDEO_TYPES = ['video/mp4', 'video/avi', 'video/mov', 'video/wmv', 'video/webm'];

/* =========================
   Helpers
========================= */
function normalizar_texto_prefijo($txt) {
    $txt = (string)$txt;
    $txt = str_replace("\r\n", "\n", $txt);
    $txt = str_replace("\r", "\n", $txt);
    return trim($txt);
}
function normalizar_mensaje($txt) {
    $txt = (string)$txt;
    $txt = str_replace("\r\n", "\n", $txt);
    $txt = str_replace("\r", "\n", $txt);
    return trim($txt);
}
function starts_with_mb($haystack, $needle) {
    $haystack = (string)$haystack;
    $needle   = (string)$needle;
    if ($needle === '') return false;
    return mb_substr($haystack, 0, mb_strlen($needle)) === $needle;
}
function esPlantillaMsg($txt, $prefijos) {
    $txtNorm = normalizar_texto_prefijo($txt);
    foreach ($prefijos as $p) {
        $pNorm = normalizar_texto_prefijo($p);
        if ($pNorm !== '' && starts_with_mb($txtNorm, $pNorm)) {
            return true;
        }
    }
    return false;
}
function validar_fecha_ymd($s) {
    if (!is_string($s) || $s === '') return false;
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $s)) return false;
    $parts = explode('-', $s);
    return checkdate((int)$parts[1], (int)$parts[2], (int)$parts[0]);
}
function fecha_hoy_ymd() { return date('Y-m-d'); }
function fecha_ayer_ymd() { return date('Y-m-d', strtotime('-1 day')); }
function fecha_anteayer_ymd() { return date('Y-m-d', strtotime('-2 day')); }

function etiqueta_fecha_chat($datetime) {
    if (!$datetime) return '';
    $ts = strtotime($datetime);
    if (!$ts) return '';
    $ymd = date('Y-m-d', $ts);

    $hoy = date('Y-m-d');
    $ayer = date('Y-m-d', strtotime('-1 day'));

    if ($ymd === $hoy) return 'Hoy';
    if ($ymd === $ayer) return 'Ayer';
    return date('d/m/Y', $ts);
}

function linkify_text($text) {
    $text = (string)$text;
    $safe = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
    $pattern = '~\b((https?://|www\.)[^\s<]+)~i';

    $safe = preg_replace_callback($pattern, function($m) {
        $urlText = $m[1];
        $trimChars = '.,;:!?)"]}';
        while (strlen($urlText) > 0 && strpos($trimChars, substr($urlText, -1)) !== false) {
            $urlText = substr($urlText, 0, -1);
        }
        if ($urlText === '') return $m[1];
        $href = $urlText;
        if (stripos($href, 'http://') !== 0 && stripos($href, 'https://') !== 0) {
            $href = 'https://' . $href;
        }
        $hrefEsc = htmlspecialchars($href, ENT_QUOTES, 'UTF-8');
        $txtEsc  = htmlspecialchars($urlText, ENT_QUOTES, 'UTF-8');
        return '<a href="'.$hrefEsc.'" target="_blank" rel="noopener noreferrer" style="color:#0aa884; text-decoration:none;">'.$txtEsc.'</a>';
    }, $safe);

    return nl2br($safe);
}

function normalizar_telefono_ultra($telefono) {
    $to = trim((string)$telefono);
    $to = str_replace('@c.us', '', $to);

    if ($to !== '' && $to[0] !== '+') {
        $digits = preg_replace('/\D+/', '', $to);
        $digits = ltrim($digits, '0');
        if ($digits === '') return '';
        if (strpos($digits, '549') === 0) {
            $to = '+' . $digits;
        } elseif (strpos($digits, '54') === 0) {
            $to = '+' . $digits;
        } elseif (strpos($digits, '341') === 0) {
            $to = '+549' . $digits;
        } else {
            $to = '+' . $digits;
        }
    }
    return $to;
}

function enviar_whatsapp_texto($telefono, $mensaje) {
    $to = normalizar_telefono_ultra($telefono);

    if ($to === '') {
        file_put_contents(__DIR__ . '/debug_send_ultramsg.log', "ERROR NORMALIZANDO TELEFONO VACIO DESDE: {$telefono}\n", FILE_APPEND);
        return ['success'=>false,'error'=>'Teléfono vacío tras normalizar','response'=>'','data'=>null];
    }

    $params = array(
        'token'    => ULTRA_TOKEN,
        'to'       => $to,
        'body'     => $mensaje,
        'priority' => 10,
    );

    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://api.ultramsg.com/" . ULTRA_INSTANCE_ID . "/messages/chat",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_SSL_VERIFYPEER => 0,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => http_build_query($params),
        CURLOPT_HTTPHEADER => array("content-type: application/x-www-form-urlencoded"),
    ));

    $response = curl_exec($curl);
    $err      = curl_error($curl);
    curl_close($curl);

    $log = "==== ".date('Y-m-d H:i:s')." ====\n";
    $log .= "RAW TEL: {$telefono}\nTO: {$to}\nBODY: {$mensaje}\nRESPONSE: {$response}\nERROR: {$err}\n\n";
    file_put_contents(__DIR__ . '/debug_send_ultramsg.log', $log, FILE_APPEND);

    if ($err) {
        return ['success'=>false,'error'=>$err,'response'=>$response,'data'=>null];
    }

    $data = json_decode($response, true);
    $success = false;

    if (is_array($data) && isset($data['sent'])) {
        $success = ($data['sent'] === 'true' || $data['sent'] === true || $data['sent'] === 1 || $data['sent'] === '1');
    } else {
        $success = true;
    }

    return [
        'success'  => $success,
        'error'    => $success ? null : ($data['message'] ?? 'Error al enviar'),
        'response' => $response,
        'data'     => $data
    ];
}

// ============================================
// NUEVO: SUBIR ARCHIVO AL SERVIDOR
// ============================================
function subir_archivo_servidor($file, $tipo) {
    global $ALLOWED_IMAGE_TYPES, $ALLOWED_AUDIO_TYPES, $ALLOWED_VIDEO_TYPES;
    
    // Validar que sea una subida de archivo válida
    if (!isset($file['error']) || $file['error'] !== UPLOAD_ERR_OK) {
        return ['ok' => 0, 'error' => 'Error en la subida del archivo'];
    }
    
    // Validar tamaño máximo (10MB)
    $maxSize = 10 * 1024 * 1024;
    if ($file['size'] > $maxSize) {
        return ['ok' => 0, 'error' => 'El archivo es demasiado grande (máx 10MB)'];
    }
    
    // Obtener el MIME type real
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimeType = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);
    
    // Validar tipo de archivo según la categoría
    $allowedTypes = [];
    if ($tipo === 'imagen') {
        $allowedTypes = $ALLOWED_IMAGE_TYPES;
        $extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        $subfolder = 'images/';
    } elseif ($tipo === 'audio') {
        $allowedTypes = $ALLOWED_AUDIO_TYPES;
        $extensions = ['mp3', 'wav', 'ogg', 'm4a', 'mp4'];
        $subfolder = 'audios/';
    } elseif ($tipo === 'video') {
        $allowedTypes = $ALLOWED_VIDEO_TYPES;
        $extensions = ['mp4', 'avi', 'mov', 'wmv', 'webm'];
        $subfolder = 'videos/';
    } else {
        return ['ok' => 0, 'error' => 'Tipo de archivo no válido'];
    }
    
    if (!in_array($mimeType, $allowedTypes)) {
        return ['ok' => 0, 'error' => 'Tipo de archivo no permitido para ' . $tipo];
    }
    
    // Crear subdirectorio si no existe
    $subdir = UPLOAD_DIR . $subfolder;
    if (!is_dir($subdir)) {
        mkdir($subdir, 0755, true);
    }
    
    // Generar nombre único
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $fileName = uniqid('wa_', true) . '.' . $extension;
    $filePath = $subdir . $fileName;
    
    // Mover el archivo
    if (!move_uploaded_file($file['tmp_name'], $filePath)) {
        return ['ok' => 0, 'error' => 'No se pudo guardar el archivo'];
    }
    
    // Generar URL pública
    $publicUrl = MEDIA_BASE_URL . 'uploads/' . $subfolder . $fileName;
    
    return [
        'ok' => 1,
        'url' => $publicUrl,
        'path' => $filePath,
        'name' => $file['name'],
        'size' => $file['size'],
        'type' => $mimeType
    ];
}

// ============================================
// NUEVO: ENVIAR IMAGEN (UltraMsg)
// ============================================
function enviar_whatsapp_imagen($telefono, $imagen_url, $caption = '') {
    $to = normalizar_telefono_ultra($telefono);
    if ($to === '') return ['success'=>false,'error'=>'Teléfono vacío','response'=>'','data'=>null];
    
    $params = array(
        'token' => ULTRA_TOKEN,
        'to'    => $to,
        'image' => $imagen_url,
        'priority' => 10,
    );
    
    if (!empty($caption)) {
        $params['caption'] = $caption;
    }
    
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://api.ultramsg.com/" . ULTRA_INSTANCE_ID . "/messages/image",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_SSL_VERIFYPEER => 0,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => http_build_query($params),
        CURLOPT_HTTPHEADER => array("content-type: application/x-www-form-urlencoded"),
    ));
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    
    $log = "==== ".date('Y-m-d H:i:s')." ====\n";
    $log .= "IMAGEN TEL: {$telefono}\nTO: {$to}\nURL: {$imagen_url}\nCAPTION: {$caption}\nRESPONSE: {$response}\nERROR: {$err}\n\n";
    file_put_contents(__DIR__ . '/debug_send_ultramsg.log', $log, FILE_APPEND);
    
    if ($err) return ['success'=>false,'error'=>$err,'response'=>$response,'data'=>null];
    
    $data = json_decode($response, true);
    $success = is_array($data) && isset($data['sent']) && ($data['sent'] === 'true' || $data['sent'] === true || $data['sent'] === 1 || $data['sent'] === '1');
    return [
        'success' => $success,
        'error'   => $success ? null : ($data['message'] ?? 'Error'),
        'response' => $response,
        'data'    => $data
    ];
}

// ============================================
// NUEVO: ENVIAR AUDIO (UltraMsg)
// ============================================
function enviar_whatsapp_audio($telefono, $audio_url) {
    $to = normalizar_telefono_ultra($telefono);
    if ($to === '') return ['success'=>false,'error'=>'Teléfono vacío','response'=>'','data'=>null];
    
    $params = array(
        'token' => ULTRA_TOKEN,
        'to'    => $to,
        'audio' => $audio_url
    );
    
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://api.ultramsg.com/" . ULTRA_INSTANCE_ID . "/messages/audio",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_SSL_VERIFYPEER => 0,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => http_build_query($params),
        CURLOPT_HTTPHEADER => array("content-type: application/x-www-form-urlencoded"),
    ));
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    
    $log = "==== ".date('Y-m-d H:i:s')." ====\n";
    $log .= "AUDIO TEL: {$telefono}\nTO: {$to}\nAUDIO_URL: {$audio_url}\nRESPONSE: {$response}\nERROR: {$err}\n\n";
    file_put_contents(__DIR__ . '/debug_send_ultramsg.log', $log, FILE_APPEND);
    
    if ($err) return ['success'=>false,'error'=>$err,'response'=>$response,'data'=>null];
    
    $data = json_decode($response, true);
    $success = is_array($data) && isset($data['sent']) && ($data['sent'] === 'true' || $data['sent'] === true || $data['sent'] === 1 || $data['sent'] === '1');
    return [
        'success' => $success,
        'error'   => $success ? null : ($data['message'] ?? 'Error'),
        'response' => $response,
        'data'    => $data
    ];
}

// ============================================
// NUEVO: ENVIAR VIDEO (UltraMsg)
// ============================================
function enviar_whatsapp_video($telefono, $video_url, $caption = '') {
    $to = normalizar_telefono_ultra($telefono);
    if ($to === '') return ['success'=>false,'error'=>'Teléfono vacío','response'=>'','data'=>null];
    
    $params = array(
        'token' => ULTRA_TOKEN,
        'to'    => $to,
        'video' => $video_url,
        'priority' => 10,
    );
    
    if (!empty($caption)) {
        $params['caption'] = $caption;
    }
    
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://api.ultramsg.com/" . ULTRA_INSTANCE_ID . "/messages/video",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 60, // Más tiempo para videos
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_SSL_VERIFYPEER => 0,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => http_build_query($params),
        CURLOPT_HTTPHEADER => array("content-type: application/x-www-form-urlencoded"),
    ));
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    
    $log = "==== ".date('Y-m-d H:i:s')." ====\n";
    $log .= "VIDEO TEL: {$telefono}\nTO: {$to}\nURL: {$video_url}\nCAPTION: {$caption}\nRESPONSE: {$response}\nERROR: {$err}\n\n";
    file_put_contents(__DIR__ . '/debug_send_ultramsg.log', $log, FILE_APPEND);
    
    if ($err) return ['success'=>false,'error'=>$err,'response'=>$response,'data'=>null];
    
    $data = json_decode($response, true);
    $success = is_array($data) && isset($data['sent']) && ($data['sent'] === 'true' || $data['sent'] === true || $data['sent'] === 1 || $data['sent'] === '1');
    return [
        'success' => $success,
        'error'   => $success ? null : ($data['message'] ?? 'Error'),
        'response' => $response,
        'data'    => $data
    ];
}

// ============================================
// NUEVO: TRANSCRIBIR AUDIO (Whisper API)
// ============================================
function transcribir_audio_whisper($audio_url) {
    if (!defined('OPENAI_API_KEY') || trim(OPENAI_API_KEY) === '') {
        return ['ok'=>0, 'error'=>'Falta OPENAI_API_KEY'];
    }

    // Descargar temporalmente
    $temp_file = tempnam(sys_get_temp_dir(), 'audio_') . '.mp3';
    $fp = fopen($temp_file, 'w+');

    $ch = curl_init($audio_url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $success = curl_exec($ch);
    curl_close($ch);
    fclose($fp);

    if (!$success || filesize($temp_file) < 100) {
        @unlink($temp_file);
        return ['ok'=>0, 'error'=>'No se pudo descargar el audio'];
    }

    // Whisper API
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => WHISPER_API_URL,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 60,
        CURLOPT_CONNECTTIMEOUT => 30,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => [
            'file' => new CURLFile($temp_file, 'audio/mpeg', 'audio.mp3'),
            'model' => 'whisper-1',
            'response_format' => 'json',
            'language' => 'es'
        ],
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer " . OPENAI_API_KEY
        ],
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_SSL_VERIFYPEER => 0,
    ]);

    $resp = curl_exec($ch);
    $err = curl_error($ch);
    $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    @unlink($temp_file);

    if ($err) return ['ok'=>0, 'error'=>$err, 'http'=>$code, 'raw'=>$resp];

    $data = json_decode($resp, true);
    if (!is_array($data)) return ['ok'=>0, 'error'=>'Respuesta Whisper inválida', 'http'=>$code, 'raw'=>$resp];

    if ($code < 200 || $code >= 300) {
        $msg = isset($data['error']['message']) ? $data['error']['message'] : 'Error Whisper';
        return ['ok'=>0, 'error'=>$msg, 'http'=>$code, 'raw'=>$resp];
    }

    $texto = isset($data['text']) ? trim($data['text']) : '';
    if (empty($texto)) return ['ok'=>0, 'error'=>'Transcripción vacía', 'http'=>$code, 'raw'=>$resp];

    return ['ok'=>1, 'texto'=>$texto, 'raw'=>$resp, 'http'=>$code];
}

// ============================================
// AJAX: SUBIR ARCHIVO
// ============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_subir_archivo']) && $_POST['ajax_subir_archivo'] == '1') {
    header('Content-Type: application/json; charset=utf-8');
    
    $tipo = isset($_POST['tipo']) ? trim($_POST['tipo']) : '';
    if (!in_array($tipo, ['imagen', 'audio', 'video'])) {
        echo json_encode(['ok'=>0, 'message'=>'Tipo de archivo no válido']);
        exit;
    }
    
    if (!isset($_FILES['archivo']) || $_FILES['archivo']['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['ok'=>0, 'message'=>'No se subió ningún archivo o hay un error']);
        exit;
    }
    
    $resultado = subir_archivo_servidor($_FILES['archivo'], $tipo);
    if ($resultado['ok'] !== 1) {
        echo json_encode(['ok'=>0, 'message'=> $resultado['error'] ?? 'Error al subir']);
        exit;
    }
    
    echo json_encode(['ok'=>1, 'url'=> $resultado['url'], 'nombre'=> $resultado['name']]);
    exit;
}

// ============================================
// AJAX: TRANSCRIBIR AUDIO
// ============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_transcribir_audio']) && $_POST['ajax_transcribir_audio'] == '1') {
    header('Content-Type: application/json; charset=utf-8');
    $audio_url = isset($_POST['audio_url']) ? trim($_POST['audio_url']) : '';
    if ($audio_url === '') {
        echo json_encode(['ok'=>0, 'message'=>'Falta URL de audio']);
        exit;
    }
    $resultado = transcribir_audio_whisper($audio_url);
    if (!$resultado['ok']) {
        echo json_encode(['ok'=>0, 'message'=> $resultado['error'] ?? 'Error en transcripción']);
        exit;
    }
    echo json_encode(['ok'=>1, 'texto'=> $resultado['texto']]);
    exit;
}

// ============================================
// AJAX: ENVIAR IMAGEN
// ============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_send_imagen']) && $_POST['ajax_send_imagen'] == '1') {
    header('Content-Type: application/json; charset=utf-8');
    $contacto_id = isset($_POST['contacto_id']) ? (int)$_POST['contacto_id'] : 0;
    $imagen_url  = isset($_POST['imagen_url']) ? trim($_POST['imagen_url']) : '';
    $caption     = isset($_POST['caption']) ? trim($_POST['caption']) : '';
    
    if ($contacto_id <= 0 || $imagen_url === '') {
        echo json_encode(['ok'=>0, 'message'=>'Falta contacto o URL de imagen']);
        exit;
    }
    
    $stmt = $pdo->prepare("SELECT telefono FROM contactos WHERE id = ? LIMIT 1");
    $stmt->execute([$contacto_id]);
    $tel = $stmt->fetchColumn();
    
    if (!$tel) {
        echo json_encode(['ok'=>0, 'message'=>'No se encontró teléfono']);
        exit;
    }
    
    $resultado = enviar_whatsapp_imagen($tel, $imagen_url, $caption);
    
    if (!$resultado['success']) {
        echo json_encode(['ok'=>0, 'message'=> ($resultado['error'] ?: 'Error')]);
        exit;
    }
    
    echo json_encode(['ok'=>1, 'message'=>'Imagen enviada']);
    exit;
}

// ============================================
// AJAX: ENVIAR AUDIO
// ============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_send_audio']) && $_POST['ajax_send_audio'] == '1') {
    header('Content-Type: application/json; charset=utf-8');
    $contacto_id = isset($_POST['contacto_id']) ? (int)$_POST['contacto_id'] : 0;
    $audio_url   = isset($_POST['audio_url']) ? trim($_POST['audio_url']) : '';
    
    if ($contacto_id <= 0 || $audio_url === '') {
        echo json_encode(['ok'=>0, 'message'=>'Falta contacto o URL de audio']);
        exit;
    }
    
    $stmt = $pdo->prepare("SELECT telefono FROM contactos WHERE id = ? LIMIT 1");
    $stmt->execute([$contacto_id]);
    $tel = $stmt->fetchColumn();
    
    if (!$tel) {
        echo json_encode(['ok'=>0, 'message'=>'No se encontró teléfono']);
        exit;
    }
    
    $resultado = enviar_whatsapp_audio($tel, $audio_url);
    
    if (!$resultado['success']) {
        echo json_encode(['ok'=>0, 'message'=> ($resultado['error'] ?: 'Error')]);
        exit;
    }
    
    echo json_encode(['ok'=>1, 'message'=>'Audio enviado']);
    exit;
}

// ============================================
// AJAX: ENVIAR VIDEO
// ============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_send_video']) && $_POST['ajax_send_video'] == '1') {
    header('Content-Type: application/json; charset=utf-8');
    $contacto_id = isset($_POST['contacto_id']) ? (int)$_POST['contacto_id'] : 0;
    $video_url   = isset($_POST['video_url']) ? trim($_POST['video_url']) : '';
    $caption     = isset($_POST['caption']) ? trim($_POST['caption']) : '';
    
    if ($contacto_id <= 0 || $video_url === '') {
        echo json_encode(['ok'=>0, 'message'=>'Falta contacto o URL de video']);
        exit;
    }
    
    $stmt = $pdo->prepare("SELECT telefono FROM contactos WHERE id = ? LIMIT 1");
    $stmt->execute([$contacto_id]);
    $tel = $stmt->fetchColumn();
    
    if (!$tel) {
        echo json_encode(['ok'=>0, 'message'=>'No se encontró teléfono']);
        exit;
    }
    
    $resultado = enviar_whatsapp_video($tel, $video_url, $caption);
    
    if (!$resultado['success']) {
        echo json_encode(['ok'=>0, 'message'=> ($resultado['error'] ?: 'Error')]);
        exit;
    }
    
    echo json_encode(['ok'=>1, 'message'=>'Video enviado']);
    exit;
}

// ============================================
// FUNCIONES EXISTENTES (sin cambios)
// ============================================
function cargarPreguntas($pdo) {
    $stmt = $pdo->query("SELECT id, categoria, titulo, texto FROM preguntas WHERE activo=1 ORDER BY categoria ASC, id DESC");
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $out = ['STOCK'=>[],'RADIOSNET'=>[],'SITIOS'=>[],'JINGLES'=>[],'OTROS'=>[]];
    foreach ($rows as $r) {
        if (!isset($out[$r['categoria']])) $out[$r['categoria']] = [];
        $out[$r['categoria']][] = $r;
    }
    return $out;
}
$PREGUNTAS = cargarPreguntas($pdo);

function buscar_contacto_id_por_telefono($pdo, $telefonoRaw) {
    $digits = preg_replace('/\D+/', '', (string)$telefonoRaw);
    if ($digits === '') return 0;
    $d1 = $digits;
    $d2 = (strpos($digits, '549') === 0) ? substr($digits, 3) : $digits;
    $d3 = (strpos($digits, '54') === 0) ? substr($digits, 2) : $digits;
    $likes = array_unique(['%'.$d1.'%', '%'.$d2.'%', '%'.$d3.'%']);
    $sql = "SELECT id FROM contactos WHERE telefono LIKE ? OR telefono LIKE ? OR telefono LIKE ? ORDER BY id DESC LIMIT 1";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$likes[0], $likes[1], $likes[2]]);
    $id = (int)$stmt->fetchColumn();
    return $id > 0 ? $id : 0;
}

function ultimo_mensaje_enviado_contacto($pdo, $contactoId) {
    $stmtUlt = $pdo->prepare("SELECT mensaje FROM charlas WHERE contacto_id = ? AND direccion = 'enviado' AND tipo = 'texto' ORDER BY fecha DESC LIMIT 1");
    $stmtUlt->execute([(int)$contactoId]);
    $ult = $stmtUlt->fetchColumn();
    return ($ult === false) ? null : (string)$ult;
}

function obtener_bandera($telefono) {
    $digits = preg_replace('/\D+/', '', (string)$telefono);
    if (strpos($digits, '54') === 0 || strpos($digits, '549') === 0) return 'AR';
    if (strpos($digits, '51') === 0) return 'PE';
    if (strpos($digits, '52') === 0) return 'MX';
    if (strpos($digits, '56') === 0) return 'CL';
    if (strpos($digits, '57') === 0) return 'CO';
    if (strpos($digits, '55') === 0) return 'BR';
    if (strpos($digits, '1') === 0)  return 'US';
    return 'INT';
}

function es_post_repetido($key, $ttlSeg = 20) {
    $now = time();
    if (!isset($_SESSION['wa_last_posts']) || !is_array($_SESSION['wa_last_posts'])) {
        $_SESSION['wa_last_posts'] = [];
    }
    foreach ($_SESSION['wa_last_posts'] as $k => $info) {
        if (!is_array($info) || !isset($info['t'])) { unset($_SESSION['wa_last_posts'][$k]); continue; }
        if ($now - (int)$info['t'] > $ttlSeg) unset($_SESSION['wa_last_posts'][$k]);
    }
    if (isset($_SESSION['wa_last_posts'][$key])) return true;
    $_SESSION['wa_last_posts'][$key] = ['t' => $now];
    return false;
}

// ============================================
// PARÁMETROS DE BÚSQUEDA Y PAGINACIÓN
// ============================================
$contactoIdSel = isset($_GET['contacto_id']) ? (int)$_GET['contacto_id'] : 0;
$busqueda      = isset($_GET['q']) ? trim($_GET['q']) : '';
$hasta         = isset($_GET['desde']) ? trim($_GET['desde']) : '';
if ($hasta !== '' && !validar_fecha_ymd($hasta)) $hasta = '';
$hastaDT = ($hasta !== '') ? ($hasta . ' 23:59:59') : '';

$soloNoLeidos  = isset($_GET['no_leidos']) && $_GET['no_leidos'] == '1';
$soloPocas     = isset($_GET['pocas']) && $_GET['pocas'] == '1';
$soloUno       = isset($_GET['uno']) && $_GET['uno'] == '1';

if ($soloNoLeidos) { $soloPocas = false; $soloUno = false; }
elseif ($soloPocas) { $soloNoLeidos = false; $soloUno = false; }
elseif ($soloUno) { $soloNoLeidos = false; $soloPocas = false; }

$refChat = isset($_GET['ref_chat']) && $_GET['ref_chat'] == '1';

$porPagina     = 100;
$paginaActual  = isset($_GET['p']) ? (int)$_GET['p'] : 1;
if ($paginaActual < 1) $paginaActual = 1;
$offset = ($paginaActual - 1) * $porPagina;

$where  = "WHERE 1=1";
$params = [];

$hayFiltrosActivos = ($soloNoLeidos || $soloPocas || $soloUno || ($hasta !== '') || ($busqueda !== ''));
$keepId = ($hayFiltrosActivos && $contactoIdSel > 0) ? $contactoIdSel : 0;

if ($busqueda !== '') {
    $where .= " AND (c.nombre LIKE :busq OR c.telefono LIKE :busq)";
    $params[':busq'] = '%' . $busqueda . '%';
}

if ($hastaDT !== '') {
    $condFecha = "(SELECT chf.fecha FROM charlas chf WHERE chf.contacto_id = c.id ORDER BY chf.fecha DESC LIMIT 1) <= :hasta_dt";
    if ($keepId > 0) {
        $condFecha = "($condFecha OR c.id = :keep_id)";
        $params[':keep_id'] = $keepId;
    }
    $where .= " AND $condFecha";
    $params[':hasta_dt'] = $hastaDT;
}

if ($soloNoLeidos) {
    $condNo = "((SELECT ch2.direccion FROM charlas ch2 WHERE ch2.contacto_id = c.id ORDER BY ch2.fecha DESC LIMIT 1) = 'recibido')";
    if ($keepId > 0) {
        if (!isset($params[':keep_id'])) $params[':keep_id'] = $keepId;
        $condNo = "($condNo OR c.id = :keep_id)";
    }
    $where .= " AND $condNo";
}

if ($soloPocas) {
    $umbral = 6;
    $condParts = [];
    $i = 1;
    foreach ($PLANTILLA_PREFIJOS as $pref) {
        $ph = ':plantilla_pref' . $i;
        $condParts[] = "chp.mensaje LIKE $ph";
        $params[$ph] = normalizar_texto_prefijo($pref) . '%';
        $i++;
    }

    $condPocas = "( (SELECT COUNT(*) FROM charlas chx WHERE chx.contacto_id = c.id) < :umbral )";
    $params[':umbral'] = $umbral;

    if ($condParts) {
        $condPocas .= " AND NOT EXISTS (SELECT 1 FROM charlas chp WHERE chp.contacto_id = c.id AND chp.direccion = 'enviado' AND chp.tipo = 'texto' AND (" . implode(' OR ', $condParts) . "))";
    }

    $condPocas = "($condPocas)";
    if ($keepId > 0) {
        if (!isset($params[':keep_id'])) $params[':keep_id'] = $keepId;
        $condPocas = "($condPocas OR c.id = :keep_id)";
    }
    $where .= " AND $condPocas";
}

if ($soloUno) {
    $condUno = "((SELECT COUNT(*) FROM charlas chx WHERE chx.contacto_id = c.id) = 1)";
    if ($keepId > 0) {
        if (!isset($params[':keep_id'])) $params[':keep_id'] = $keepId;
        $condUno = "($condUno OR c.id = :keep_id)";
    }
    $where .= " AND $condUno";
}

$sqlCount = "SELECT COUNT(*) FROM contactos c $where";
$stmtCount = $pdo->prepare($sqlCount);
foreach ($params as $k => $v) {
    $stmtCount->bindValue($k, $v, is_int($v) ? PDO::PARAM_INT : PDO::PARAM_STR);
}
$stmtCount->execute();
$totalContactos = (int)$stmtCount->fetchColumn();

$totalPaginas = ($totalContactos > 0) ? (int)ceil($totalContactos / $porPagina) : 1;
if ($paginaActual > $totalPaginas) $paginaActual = $totalPaginas;
$offset = ($paginaActual - 1) * $porPagina;

// ============================================
// ENVÍO DE MENSAJE (POST) - EXISTENTE
// ============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['mensaje'])) {
    $contactoId      = isset($_POST['contacto_id']) ? (int)$_POST['contacto_id'] : 0;
    $mensajeRaw      = (string)$_POST['mensaje'];
    $mensaje         = normalizar_mensaje($mensajeRaw);
    $telefonoDirecto = isset($_POST['telefono_directo']) ? trim((string)$_POST['telefono_directo']) : '';
    
    $busqPost      = isset($_POST['q']) ? trim((string)$_POST['q']) : '';
    $noLeidosPost  = isset($_POST['no_leidos']) && $_POST['no_leidos'] == '1';
    $pagPost       = isset($_POST['p']) ? (int)$_POST['p'] : 1;
    $pocasPost     = isset($_POST['pocas']) && $_POST['pocas'] == '1';
    $unoPost       = isset($_POST['uno']) && $_POST['uno'] == '1';
    $hastaPost     = isset($_POST['desde']) ? trim((string)$_POST['desde']) : '';
    if ($hastaPost !== '' && !validar_fecha_ymd($hastaPost)) $hastaPost = '';
    $isAjaxSend    = isset($_POST['ajax_send']) && $_POST['ajax_send'] == '1';

    $redirectParams = [];
    if ($contactoId > 0) $redirectParams['contacto_id'] = $contactoId;
    if ($busqPost !== '') $redirectParams['q'] = $busqPost;
    if ($noLeidosPost) $redirectParams['no_leidos'] = 1;
    if ($pocasPost) $redirectParams['pocas'] = 1;
    if ($unoPost) $redirectParams['uno'] = 1;
    if ($pagPost > 1) $redirectParams['p'] = $pagPost;
    if ($hastaPost !== '') $redirectParams['desde'] = $hastaPost;
    if ($contactoId > 0 && $telefonoDirecto === '') $redirectParams['ref_chat'] = 1;

    $redirectUrl = 'whatsapp.php';
    if (!empty($redirectParams)) $redirectUrl .= '?' . http_build_query($redirectParams);

    $resultOk = true;
    $resultMsg = 'OK';

    if ($mensaje !== '') {
        $hashKey = md5(($contactoId > 0 ? "cid:$contactoId" : "tel:".normalizar_telefono_ultra($telefonoDirecto)) . "|msg:" . $mensaje);
        if (es_post_repetido($hashKey, 20)) {
            file_put_contents(__DIR__ . '/debug_send_ultramsg.log', "POST REPETIDO BLOQUEADO: {$hashKey}\n", FILE_APPEND);
            if ($isAjaxSend) {
                header('Content-Type: application/json; charset=utf-8');
                echo json_encode(['ok'=>1,'blocked'=>1,'message'=>'Repetido bloqueado']);
                exit;
            }
            header("Location: $redirectUrl"); exit;
        }

        if ($contactoId > 0 && $telefonoDirecto === '') {
            $stmt = $pdo->prepare("SELECT telefono FROM contactos WHERE id = ?");
            $stmt->execute([$contactoId]);
            $telefono = $stmt->fetchColumn();

            if ($telefono) {
                $ultimo = ultimo_mensaje_enviado_contacto($pdo, $contactoId);
                if ($ultimo !== null && normalizar_mensaje($ultimo) === $mensaje) {
                    file_put_contents(__DIR__ . '/debug_send_ultramsg.log', "DUPLICADO BLOQUEADO CONTACTO {$contactoId} ({$telefono}): {$mensaje}\n\n", FILE_APPEND);
                    if ($isAjaxSend) {
                        header('Content-Type: application/json; charset=utf-8');
                        echo json_encode(['ok'=>1,'blocked'=>1,'message'=>'Duplicado bloqueado']);
                        exit;
                    }
                    header("Location: $redirectUrl"); exit;
                }

                $resultado = enviar_whatsapp_texto($telefono, $mensaje);
                file_put_contents(__DIR__ . '/debug_send_ultramsg.log', "RESULTADO ENVÍO CONTACTO {$contactoId} ({$telefono}): " . json_encode($resultado) . "\n\n", FILE_APPEND);

                if (!$resultado['success']) {
                    $resultOk = false;
                    $resultMsg = $resultado['error'] ?: 'Error enviando';
                }
            } else {
                $resultOk = false;
                $resultMsg = 'No se encontró teléfono del contacto';
            }
        } elseif ($telefonoDirecto !== '') {
            $cid = buscar_contacto_id_por_telefono($pdo, $telefonoDirecto);
            if ($cid > 0) {
                $ultimo = ultimo_mensaje_enviado_contacto($pdo, $cid);
                if ($ultimo !== null && normalizar_mensaje($ultimo) === $mensaje) {
                    file_put_contents(__DIR__ . '/debug_send_ultramsg.log', "DUPLICADO BLOQUEADO CINE cid={$cid} tel={$telefonoDirecto}: {$mensaje}\n\n", FILE_APPEND);
                    if ($isAjaxSend) {
                        header('Content-Type: application/json; charset=utf-8');
                        echo json_encode(['ok'=>1,'blocked'=>1,'message'=>'Duplicado bloqueado']);
                        exit;
                    }
                    header("Location: $redirectUrl"); exit;
                }
            }

            $resultado = enviar_whatsapp_texto($telefonoDirecto, $mensaje);
            file_put_contents(__DIR__ . '/debug_send_ultramsg.log', "RESULTADO ENVÍO DIRECTO ({$telefonoDirecto}): " . json_encode($resultado) . "\n\n", FILE_APPEND);

            if (!$resultado['success']) {
                $resultOk = false;
                $resultMsg = $resultado['error'] ?: 'Error enviando';
            }
        }
    }

    if ($isAjaxSend) {
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode([
            'ok' => $resultOk ? 1 : 0,
            'message' => $resultMsg,
            'contacto_id' => $contactoId
        ]);
        exit;
    }

    header("Location: $redirectUrl");
    exit;
}

// ============================================
// OBTENER CONTACTOS
// ============================================
$sqlContactos = "
    SELECT 
        c.id, c.telefono, c.nombre,
        (SELECT mensaje   FROM charlas ch  WHERE ch.contacto_id = c.id ORDER BY ch.fecha DESC LIMIT 1) AS ultimo_mensaje,
        (SELECT fecha     FROM charlas ch  WHERE ch.contacto_id = c.id ORDER BY ch.fecha DESC LIMIT 1) AS ultima_fecha,
        (SELECT direccion FROM charlas ch  WHERE ch.contacto_id = c.id ORDER BY ch.fecha DESC LIMIT 1) AS ultima_direccion,
        (SELECT COUNT(*)  FROM charlas ch3 WHERE ch3.contacto_id = c.id) AS total_msgs,
        (SELECT mensaje   FROM charlas ch4 WHERE ch4.contacto_id = c.id ORDER BY ch4.fecha ASC LIMIT 1) AS primer_mensaje,
        (
            SELECT COUNT(*)
            FROM charlas chr
            WHERE chr.contacto_id = c.id
              AND chr.direccion = 'recibido'
              AND chr.fecha > COALESCE(
                    (SELECT MAX(chs.fecha) FROM charlas chs WHERE chs.contacto_id = c.id AND chs.direccion = 'enviado'),
                    '1970-01-01 00:00:00'
                )
        ) AS pendientes
    FROM contactos c
    $where
    ORDER BY ultima_fecha DESC, c.fecha_alta DESC
    LIMIT :offset, :limite
";

$stmt = $pdo->prepare($sqlContactos);
foreach ($params as $k => $v) {
    $stmt->bindValue($k, $v, is_int($v) ? PDO::PARAM_INT : PDO::PARAM_STR);
}
$stmt->bindValue(':offset', (int)$offset, PDO::PARAM_INT);
$stmt->bindValue(':limite', (int)$porPagina, PDO::PARAM_INT);
$stmt->execute();
$contactos = $stmt->fetchAll(PDO::FETCH_ASSOC);

if ($keepId > 0) {
    $enLista = false;
    foreach ($contactos as $cc) {
        if ((int)$cc['id'] === $keepId) { $enLista = true; break; }
    }
    if (!$enLista) {
        $stmtK = $pdo->prepare("
            SELECT 
                c.id, c.telefono, c.nombre,
                (SELECT mensaje   FROM charlas ch  WHERE ch.contacto_id = c.id ORDER BY ch.fecha DESC LIMIT 1) AS ultimo_mensaje,
                (SELECT fecha     FROM charlas ch  WHERE ch.contacto_id = c.id ORDER BY ch.fecha DESC LIMIT 1) AS ultima_fecha,
                (SELECT direccion FROM charlas ch  WHERE ch.contacto_id = c.id ORDER BY ch.fecha DESC LIMIT 1) AS ultima_direccion,
                (SELECT COUNT(*)  FROM charlas ch3 WHERE ch3.contacto_id = c.id) AS total_msgs,
                (SELECT mensaje   FROM charlas ch4 WHERE ch4.contacto_id = c.id ORDER BY ch4.fecha ASC LIMIT 1) AS primer_mensaje,
                (
                    SELECT COUNT(*)
                    FROM charlas chr
                    WHERE chr.contacto_id = c.id
                      AND chr.direccion = 'recibido'
                      AND chr.fecha > COALESCE(
                            (SELECT MAX(chs.fecha) FROM charlas chs WHERE chs.contacto_id = c.id AND chs.direccion = 'enviado'),
                            '1970-01-01 00:00:00'
                        )
                ) AS pendientes
            FROM contactos c WHERE c.id = ? LIMIT 1
        ");
        $stmtK->execute([$keepId]);
        $rowK = $stmtK->fetch(PDO::FETCH_ASSOC);
        if ($rowK) array_unshift($contactos, $rowK);
    }
}

$contactoSel = null;
$mensajes    = [];

if ($contactoIdSel > 0) {
    $stmt = $pdo->prepare("SELECT * FROM contactos WHERE id = ?");
    $stmt->execute([$contactoIdSel]);
    $contactoSel = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($contactoSel) {
        if ($hastaDT !== '') {
            $stmt = $pdo->prepare("SELECT * FROM charlas WHERE contacto_id = ? AND fecha <= ? ORDER BY fecha ASC");
            $stmt->execute([$contactoIdSel, $hastaDT]);
        } else {
            $stmt = $pdo->prepare("SELECT * FROM charlas WHERE contacto_id = ? ORDER BY fecha ASC");
            $stmt->execute([$contactoIdSel]);
        }
        $mensajes = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

// ============================================
// RENDER FUNCTIONS
// ============================================
function renderListaContactos($contactos, $contactoIdSel, $busqueda, $paginaActual, $soloNoLeidos, $totalPaginas, $soloPocas, $soloUno, $PLANTILLA_PREFIJOS, $hasta) {
    ob_start(); ?>
    <?php foreach ($contactos as $c): ?>
        <?php
        $activo  = ((int)$c['id'] === (int)$contactoIdSel) ? 'activo' : '';
        $nombre  = $c['nombre'] ?: $c['telefono'];
        $telMini = $c['telefono'] ?? '';

        $primer      = $c['primer_mensaje'] ?? '';
        $esPlantilla = esPlantillaMsg($primer, $PLANTILLA_PREFIJOS);

        $ultDir = $c['ultima_direccion'] ?? '';
        $pend   = isset($c['pendientes']) ? (int)$c['pendientes'] : 0;

        $tienePendiente = ($ultDir === 'recibido');
        $showBadge = ($tienePendiente && $pend > 0);

        $totalMsgs = isset($c['total_msgs']) ? (int)$c['total_msgs'] : 0;

        $bgClass = '';
        if ($totalMsgs === 1) {
            $bgClass = 'wa-bg-uno';
        } elseif (!$esPlantilla && $totalMsgs > 0 && $totalMsgs < 6) {
            $bgClass = 'wa-bg-pocas';
        } elseif ($tienePendiente) {
            $bgClass = 'wa-bg-cliente';
        }

        $queryParams = ['contacto_id' => (int)$c['id']];
        if ($busqueda !== '') $queryParams['q'] = $busqueda;
        if ($paginaActual > 1) $queryParams['p'] = $paginaActual;
        if ($soloNoLeidos) $queryParams['no_leidos'] = 1;
        if ($soloPocas)    $queryParams['pocas'] = 1;
        if ($soloUno)      $queryParams['uno'] = 1;
        if ($hasta !== '') $queryParams['desde'] = $hasta;

        $urlContacto = 'whatsapp.php?' . http_build_query($queryParams);

        $ultFechaTxt = '';
        if (!empty($c['ultima_fecha'])) $ultFechaTxt = date('d/m H:i', strtotime($c['ultima_fecha']));

        $inicialNombre = mb_strtoupper(mb_substr($nombre, 0, 1));
        $pais = obtener_bandera($telMini);
        ?>
        <a href="<?= htmlspecialchars($urlContacto) ?>" class="wa-contact-link" data-id="<?= (int)$c['id'] ?>" onclick="guardarScrollLista()">
            <div class="wa-contacto <?= $activo ?> <?= $bgClass ?> <?= $esPlantilla ? 'wa-contacto-plantilla' : '' ?>">
                <div class="wa-contact-row">
                    <div class="wa-avatar"><?= $inicialNombre ?></div>
                    <div class="wa-contact-info">
                        <div class="wa-contact-top">
                            <span class="wa-contact-name">
                                <?php if ($tienePendiente): ?><span class="wa-dot-pendiente"></span><?php endif; ?>
                                <span class="wa-pais"><?= htmlspecialchars($pais) ?></span>
                                <?= htmlspecialchars($nombre) ?>
                            </span>
                            <span class="wa-contact-time"><?= htmlspecialchars($ultFechaTxt) ?></span>
                        </div>
                        <div class="wa-contact-phone"><?= htmlspecialchars($telMini) ?></div>
                        <div class="wa-contact-bottom">
                            <span class="wa-contact-last">
                                <?php if ($esPlantilla): ?><span class="wa-badge-plantilla">TPL</span><?php endif; ?>
                                <?= htmlspecialchars(mb_substr($c['ultimo_mensaje'] ?? '', 0, 46)) ?>
                            </span>

                            <?php if ($showBadge): ?>
                                <span class="wa-count-badge"><?= (int)$pend ?></span>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </a>
    <?php endforeach; ?>

    <?php if ($totalPaginas > 1): ?>
        <div class="wa-pager">
            <?php
            $baseParams = [];
            if ($busqueda !== '') $baseParams['q'] = $busqueda;
            if ($contactoIdSel) $baseParams['contacto_id'] = (int)$contactoIdSel;
            if ($soloNoLeidos) $baseParams['no_leidos'] = 1;
            if ($soloPocas) $baseParams['pocas'] = 1;
            if ($soloUno) $baseParams['uno'] = 1;
            if ($hasta !== '') $baseParams['desde'] = $hasta;
            ?>
            <div>
                <?php if ($paginaActual > 1): ?>
                    <?php $prevParams = $baseParams; $prevParams['p'] = $paginaActual - 1; ?>
                    <a href="<?= htmlspecialchars('whatsapp.php?' . http_build_query($prevParams)) ?>">« Ant</a>
                <?php endif; ?>
            </div>
            <div class="wa-pager-info"><?= (int)$paginaActual ?>/<?= (int)$totalPaginas ?></div>
            <div>
                <?php if ($paginaActual < $totalPaginas): ?>
                    <?php $nextParams = $baseParams; $nextParams['p'] = $paginaActual + 1; ?>
                    <a href="<?= htmlspecialchars('whatsapp.php?' . http_build_query($nextParams)) ?>">Sig »</a>
                <?php endif; ?>
            </div>
        </div>
    <?php endif; ?>
    <?php
    return ob_get_clean();
}

function renderMensajesInner($contactoSel, $mensajes, $hasta) {
    ob_start();
    if ($contactoSel): ?>
        <?php if ($hasta !== ''): ?>
            <div class="wa-chat-hint">Hasta <?= htmlspecialchars($hasta) ?></div>
        <?php endif; ?>

        <?php $prevYmd = ''; ?>

        <?php foreach ($mensajes as $m): ?>
            <?php
            $clase = ($m['direccion'] === 'enviado') ? 'enviado' : 'recibido';

            $ts = strtotime($m['fecha']);
            $ymd = $ts ? date('Y-m-d', $ts) : '';
            $hora = $ts ? date('H:i', $ts) : '';
            $etFecha = $ts ? etiqueta_fecha_chat($m['fecha']) : '';

            if ($ymd !== '' && $ymd !== $prevYmd):
                $prevYmd = $ymd;
            ?>
                <div class="wa-day-sep"><span><?= htmlspecialchars($etFecha) ?></span></div>
            <?php endif; ?>

            <?php $fechaPie = ($etFecha !== '' && $hora !== '') ? ($etFecha . ' ' . $hora) : $hora; ?>

            <div class="wa-msg <?= $clase ?>">
                <?php if ($m['tipo'] === 'texto'): ?>
                    <div class="wa-msg-text"><?= linkify_text($m['mensaje'] ?? '') ?></div>
                <?php else: ?>
                    <div class="wa-media">
                        <?php if (in_array($m['tipo'], ['imagen', 'image']) && $m['media_path']): ?>
                            <?php
                            $mediaPath = $m['media_path'];
                            if (!filter_var($mediaPath, FILTER_VALIDATE_URL)) {
                                $mediaPath = MEDIA_BASE_URL . ltrim($mediaPath, '/');
                            }
                            $mediaEsc = htmlspecialchars($mediaPath, ENT_QUOTES, 'UTF-8');
                            ?>
                            <img src="<?= $mediaEsc ?>" alt="Imagen" onclick="abrirImgModal('<?= $mediaEsc ?>')" style="max-width: 320px; border-radius: 10px; cursor:pointer;">
                            <?php if (!empty($m['mensaje'])): ?>
                                <div class="wa-msg-text"><?= linkify_text($m['mensaje'] ?? '') ?></div>
                            <?php endif; ?>
                        <?php elseif (in_array($m['tipo'], ['audio', 'voice', 'ptt']) && $m['media_path']): ?>
                            <?php
                            $mediaPath = $m['media_path'];
                            if (!filter_var($mediaPath, FILTER_VALIDATE_URL)) {
                                $mediaPath = MEDIA_BASE_URL . ltrim($mediaPath, '/');
                            }
                            $mediaEsc = htmlspecialchars($mediaPath, ENT_QUOTES, 'UTF-8');
                            $audioId = uniqid('audio_');
                            ?>
                            <div class="wa-audio-wrapper">
                                <audio controls id="<?= $audioId ?>">
                                    <source src="<?= $mediaEsc ?>" type="audio/mpeg">
                                </audio>
                                <div style="margin-top:8px;">
                                    <button class="wa-transcribe-btn" onclick="transcribirAudio(this, '<?= $mediaEsc ?>', '<?= $audioId ?>')">
                                        🔊 Transcribir audio
                                    </button>
                                    <div id="transcription-<?= $audioId ?>" class="wa-transcription-result" style="display:none;"></div>
                                </div>
                            </div>
                        <?php elseif (in_array($m['tipo'], ['video']) && $m['media_path']): ?>
                            <?php
                            $mediaPath = $m['media_path'];
                            if (!filter_var($mediaPath, FILTER_VALIDATE_URL)) {
                                $mediaPath = MEDIA_BASE_URL . ltrim($mediaPath, '/');
                            }
                            $mediaEsc = htmlspecialchars($mediaPath, ENT_QUOTES, 'UTF-8');
                            ?>
                            <video controls style="max-width: 320px; border-radius: 10px;">
                                <source src="<?= $mediaEsc ?>" type="video/mp4">
                                Tu navegador no soporta video HTML5.
                            </video>
                            <?php if (!empty($m['mensaje'])): ?>
                                <div class="wa-msg-text"><?= linkify_text($m['mensaje'] ?? '') ?></div>
                            <?php endif; ?>
                        <?php else: ?>
                            <?php if (!empty($m['media_path'])): ?>
                                <?php
                                $mediaPath = $m['media_path'];
                                if (!filter_var($mediaPath, FILTER_VALIDATE_URL)) {
                                    $mediaPath = MEDIA_BASE_URL . ltrim($mediaPath, '/');
                                }
                                ?>
                                <a href="<?= htmlspecialchars($mediaPath, ENT_QUOTES, 'UTF-8') ?>" target="_blank">Ver archivo</a>
                            <?php endif; ?>
                            <?php if (!empty($m['mensaje'])): ?>
                                <div class="wa-msg-text"><?= linkify_text($m['mensaje'] ?? '') ?></div>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
                <div class="wa-fecha"><?= htmlspecialchars($fechaPie) ?></div>
            </div>
        <?php endforeach; ?>
    <?php else: ?>
        <div class="wa-empty">
            <div class="wa-empty-icon">
                <svg width="72" height="72" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                    <path d="M21 11.5a8.38 8.38 0 0 1-1.8 5.2 8.5 8.5 0 0 1-7.2 3.3 8.38 8.38 0 0 1-5.2-1.8L3 21l1.5-3.8A8.38 8.38 0 0 1 2.7 12 8.5 8.5 0 0 1 12 3.5a8.5 8.5 0 0 1 9 8z"/>
                </svg>
            </div>
            <div class="wa-empty-title">WhatsApp</div>
            <div class="wa-empty-sub">Selecciona un chat para comenzar</div>
        </div>
    <?php endif;
    return ob_get_clean();
}

// ============================================
// AJAX ENDPOINTS
// ============================================
if (isset($_GET['ajax']) && $_GET['ajax'] === 'lista') {
    echo renderListaContactos($contactos, $contactoIdSel, $busqueda, $paginaActual, $soloNoLeidos, $totalPaginas, $soloPocas, $soloUno, $PLANTILLA_PREFIJOS, $hasta);
    exit;
}
if (isset($_GET['ajax']) && $_GET['ajax'] === 'mensajes') {
    echo renderMensajesInner($contactoSel, $mensajes, $hasta);
    exit;
}

?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>WhatsApp</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }

        :root{
            --wa-bg: #f0f2f5;
            --wa-panel: #ffffff;
            --wa-panel-2: #ffffff;
            --wa-border: #d1d7db;
            --wa-green: #00a884;
            --wa-green-dark: #008069;
            --wa-text: #111b21;
            --wa-text-secondary: #667781;
            --wa-hover: #f5f6f6;
            --wa-active: #eef2f3;
            --wa-input-bg: #ffffff;
            --wa-sent: #d9fdd3;
            --wa-recv: #ffffff;
            --wa-shadow: 0 1px 2px rgba(0,0,0,0.08);
        }

        body{
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: var(--wa-bg);
            color: var(--wa-text);
            font-size: 14px;
            overflow: hidden;
        }

        .wa-container{
            display:flex;
            width: 100vw;
            height: 100vh;
            background: var(--wa-bg);
        }

        .wa-sidebar{
            width: 420px;
            min-width: 340px;
            display:flex;
            flex-direction:column;
            border-right: 1px solid var(--wa-border);
            background: var(--wa-panel);
        }

        .wa-sidebar-header{
            padding: 12px 16px;
            border-bottom: 1px solid var(--wa-border);
            background: var(--wa-panel);
        }

        .wa-sidebar-top{
            display:flex;
            justify-content:space-between;
            align-items:center;
            margin-bottom: 10px;
        }

        .wa-sidebar-title{
            font-size: 18px;
            font-weight: 600;
            color: var(--wa-text);
        }

        .wa-header-actions{ display:flex; gap:8px; align-items:center; }

        .wa-btn-icon{
            width: 36px;
            height: 36px;
            border:none;
            background: transparent;
            color: var(--wa-text-secondary);
            border-radius: 50%;
            cursor:pointer;
            display:flex;
            align-items:center;
            justify-content:center;
            transition: all .15s;
        }
        .wa-btn-icon:hover{ background: var(--wa-hover); color: var(--wa-text); }

        .wa-btn-new{
            background: var(--wa-green);
            color:#fff;
            padding: 8px 14px;
            border:none;
            border-radius: 8px;
            font-size: 13px;
            font-weight: 600;
            cursor:pointer;
            transition: all .15s;
        }
        .wa-btn-new:hover{ background: var(--wa-green-dark); }

        .wa-search-box{ position:relative; margin-bottom: 10px; }
        .wa-search-box input{
            width:100%;
            padding: 10px 12px 10px 40px;
            background: #f0f2f5;
            border: 1px solid transparent;
            border-radius: 10px;
            color: var(--wa-text);
            outline:none;
        }
        .wa-search-box input:focus{
            border-color: rgba(0,168,132,0.35);
            background:#fff;
        }
        .wa-search-box input::placeholder{ color: var(--wa-text-secondary); }
        .wa-search-box svg{
            position:absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--wa-text-secondary);
        }

        .wa-filters{ display:flex; gap:6px; flex-wrap:wrap; margin-bottom: 10px; }
        .wa-filter-btn{
            padding: 6px 12px;
            background: #f0f2f5;
            border: 1px solid transparent;
            border-radius: 999px;
            color: var(--wa-text-secondary);
            font-size: 12px;
            font-weight: 600;
            cursor:pointer;
            text-decoration:none;
            transition: all .15s;
        }
        .wa-filter-btn:hover{ background: var(--wa-hover); color: var(--wa-text); }
        .wa-filter-btn.active{
            background: rgba(0,168,132,0.12);
            border-color: rgba(0,168,132,0.25);
            color: var(--wa-green-dark);
        }

        .wa-date-row{ display:flex; gap:6px; align-items:center; }
        .wa-date-btn{
            padding: 6px 10px;
            background: transparent;
            border: 1px solid var(--wa-border);
            border-radius: 8px;
            color: var(--wa-text-secondary);
            font-size: 11px;
            cursor:pointer;
            text-decoration:none;
            transition: all .15s;
        }
        .wa-date-btn:hover{ background: var(--wa-hover); color: var(--wa-text); }
        .wa-date-input{
            flex:1;
            max-width: 160px;
            padding: 6px 10px;
            background: #f0f2f5;
            border: 1px solid transparent;
            border-radius: 8px;
            color: var(--wa-text);
            font-size: 12px;
            outline:none;
        }
        .wa-date-input:focus{ background:#fff; border-color: rgba(0,168,132,0.25); }
        .wa-date-clear{
            padding: 6px 10px;
            background: #d9534f;
            border:none;
            border-radius: 8px;
            color:#fff;
            font-size: 11px;
            cursor:pointer;
            text-decoration:none;
        }

        .wa-contact-list{ flex:1; overflow-y:auto; background: var(--wa-panel); }
        .wa-contact-link{ text-decoration:none; color:inherit; display:block; }
        .wa-contacto{
            padding: 10px 14px;
            border-bottom: 1px solid rgba(0,0,0,0.06);
            cursor:pointer;
            transition: background .15s;
        }
        .wa-contacto:hover{ background: var(--wa-hover); }
        .wa-contacto.activo{ background: var(--wa-active); }

        .wa-contact-row{ display:flex; gap:12px; align-items:center; }
        .wa-avatar{
            width: 46px;
            height: 46px;
            border-radius: 50%;
            background: linear-gradient(135deg, #00a884 0%, #25d366 100%);
            display:flex;
            align-items:center;
            justify-content:center;
            color:#fff;
            font-weight:700;
            font-size: 16px;
            flex-shrink:0;
        }

        .wa-contact-info{ flex:1; min-width:0; }
        .wa-contact-top{ display:flex; justify-content:space-between; align-items:center; margin-bottom: 2px; }
        .wa-contact-name{
            font-weight: 600;
            font-size: 14px;
            color: var(--wa-text);
            white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
            display:flex; align-items:center; gap:6px;
        }
        .wa-pais{
            font-size: 11px;
            font-weight: 700;
            color: var(--wa-text-secondary);
            padding: 2px 6px;
            border-radius: 999px;
            background: #f0f2f5;
            border: 1px solid rgba(0,0,0,0.06);
        }
        .wa-contact-time{ font-size: 11px; color: var(--wa-text-secondary); flex-shrink:0; }
        .wa-contact-phone{ font-size: 11px; color: var(--wa-text-secondary); margin: 1px 0 2px; }
        .wa-contact-bottom{ display:flex; justify-content:space-between; align-items:center; gap:10px; }
        .wa-contact-last{
            font-size: 13px;
            color: var(--wa-text-secondary);
            white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
            flex:1;
        }

        .wa-dot-pendiente{
            width: 8px;
            height: 8px;
            background: var(--wa-green);
            border-radius: 50%;
            flex-shrink:0;
        }

        .wa-count-badge{
            background: var(--wa-green);
            color:#fff;
            font-size: 11px;
            font-weight: 800;
            padding: 2px 8px;
            border-radius: 999px;
            flex-shrink:0;
        }

        .wa-badge-plantilla{
            background: rgba(0,0,0,0.06);
            color: var(--wa-text-secondary);
            font-size: 9px;
            padding: 2px 6px;
            border-radius: 6px;
            margin-right: 6px;
            font-weight: 800;
        }

        .wa-bg-uno{ border-left: 3px solid #f1c40f; }
        .wa-bg-pocas{ border-left: 3px solid #9b59b6; }
        .wa-bg-cliente{ border-left: 3px solid #0aa884; }
        .wa-contacto-plantilla{ opacity: .78; }

        .wa-pager{
            display:flex;
            justify-content:space-between;
            align-items:center;
            padding: 10px 14px;
            border-top: 1px solid var(--wa-border);
            background: var(--wa-panel);
        }
        .wa-pager a{ color: var(--wa-green-dark); text-decoration:none; font-weight:700; }
        .wa-pager-info{ color: var(--wa-text-secondary); font-weight:700; }

        .wa-chat{ flex:1; display:flex; flex-direction:column; background: var(--wa-bg); }
        .wa-chat-header{
            padding: 12px 16px;
            background: var(--wa-panel);
            border-bottom: 1px solid var(--wa-border);
            display:flex;
            justify-content:space-between;
            align-items:center;
            box-shadow: var(--wa-shadow);
            z-index: 2;
        }

        .wa-chat-header-info{ display:flex; align-items:center; gap:12px; }
        .wa-chat-name{ font-weight:800; font-size: 14px; color: var(--wa-text); }
        .wa-chat-phone{ font-size: 12px; color: var(--wa-text-secondary); }

        .wa-messages{
            flex:1;
            overflow-y:auto;
            padding: 18px 52px;
            background:
                radial-gradient(circle at 20px 20px, rgba(0,0,0,0.02) 2px, transparent 2px) 0 0/40px 40px,
                var(--wa-bg);
        }

        .wa-chat-hint{
            text-align:center;
            padding: 8px 12px;
            background: rgba(0,0,0,0.04);
            border: 1px solid rgba(0,0,0,0.06);
            border-radius: 999px;
            font-size: 12px;
            color: var(--wa-text-secondary);
            margin-bottom: 14px;
            align-self:center;
        }

        .wa-day-sep{ display:flex; justify-content:center; margin: 10px 0 12px; }
        .wa-day-sep span{
            font-size: 12px;
            color: var(--wa-text-secondary);
            background: rgba(0,0,0,0.04);
            border: 1px solid rgba(0,0,0,0.06);
            padding: 6px 12px;
            border-radius: 999px;
            font-weight: 700;
        }

        .wa-msg{
            max-width: 68%;
            margin-bottom: 6px;
            padding: 8px 12px;
            border-radius: 10px;
            position:relative;
            box-shadow: var(--wa-shadow);
            border: 1px solid rgba(0,0,0,0.04);
        }
        .wa-msg.enviado{
            background: var(--wa-sent);
            margin-left:auto;
            border-bottom-right-radius: 6px;
        }
        .wa-msg.recibido{
            background: var(--wa-recv);
            border-bottom-left-radius: 6px;
        }
        .wa-msg-text{ font-size: 14px; line-height: 1.35; word-wrap: break-word; }
        .wa-fecha{
            font-size: 10px;
            color: var(--wa-text-secondary);
            text-align:right;
            margin-top: 4px;
            font-weight: 600;
        }
        
        /* Estilos para audio y transcripción */
        .wa-audio-wrapper {
            margin: 8px 0;
        }
        
        .wa-audio-wrapper audio {
            max-width: 300px;
            height: 40px;
            border-radius: 20px;
            background: #f0f2f5;
        }
        
        .wa-transcribe-btn {
            background: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 6px 12px;
            font-size: 12px;
            cursor: pointer;
            margin-top: 5px;
            transition: background 0.2s;
        }
        
        .wa-transcribe-btn:hover {
            background: #0056b3;
        }
        
        .wa-transcribe-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        
        .wa-transcription-result {
            margin-top: 8px;
            padding: 8px;
            background: #f8f9fa;
            border-radius: 6px;
            border-left: 3px solid #007bff;
            font-size: 13px;
            line-height: 1.4;
        }

        .wa-empty{
            display:flex;
            flex-direction:column;
            align-items:center;
            justify-content:center;
            height:100%;
            color: var(--wa-text-secondary);
            gap: 6px;
        }
        .wa-empty-icon{ color: rgba(0,0,0,0.2); }
        .wa-empty-title{ font-size: 24px; font-weight: 800; color: var(--wa-text); }
        .wa-empty-sub{ font-size: 13px; }

        /* Chat footer */
        .wa-chat-footer{
            padding: 10px 12px;
            background: var(--wa-panel);
            border-top: 1px solid var(--wa-border);
            box-shadow: var(--wa-shadow);
        }

        .wa-input-row{ display:flex; gap:10px; align-items:flex-end; }
        .wa-input-wrap{
            flex:1;
            display:flex;
            align-items:flex-end;
            background: #f0f2f5;
            border: 1px solid transparent;
            border-radius: 10px;
            padding: 0 12px;
        }
        .wa-input-wrap:focus-within{
            background:#fff;
            border-color: rgba(0,168,132,0.25);
        }
        .wa-input-wrap textarea{
            flex:1;
            background:transparent;
            border:none;
            color: var(--wa-text);
            font-size: 14px;
            padding: 12px 0;
            resize:none;
            outline:none;
            max-height: 140px;
            font-family: inherit;
        }
        .wa-input-wrap textarea::placeholder{ color: var(--wa-text-secondary); }

        .wa-btn-pregrab{
            background:transparent;
            border:none;
            color: var(--wa-text-secondary);
            padding: 10px 6px;
            cursor:pointer;
        }
        .wa-btn-pregrab:hover{ color: var(--wa-text); }

        /* Botón para adjuntar archivos */
        .wa-btn-attach{
            background:transparent;
            border:none;
            color: var(--wa-text-secondary);
            padding: 10px 6px;
            cursor:pointer;
            position:relative;
        }
        .wa-btn-attach:hover{ color: var(--wa-text); }

        .wa-btn-send{
            width: 44px;
            height: 44px;
            background: var(--wa-green);
            border:none;
            border-radius: 50%;
            color:#fff;
            cursor:pointer;
            display:flex;
            align-items:center;
            justify-content:center;
            transition: all .15s;
            flex-shrink:0;
        }
        .wa-btn-send:hover{ background: var(--wa-green-dark); transform: scale(1.03); }
        .wa-btn-send:disabled{ opacity:.55; cursor:not-allowed; transform:none; }

        /* Toast */
        .wa-toast{
            position: fixed;
            bottom: 18px;
            right: 18px;
            background: var(--wa-panel);
            border: 1px solid var(--wa-border);
            border-radius: 10px;
            padding: 12px 14px;
            box-shadow: 0 8px 24px rgba(0,0,0,0.12);
            display:none;
            z-index: 1000;
            min-width: 220px;
        }
        .wa-toast-title{ font-weight: 800; margin-bottom: 3px; color: var(--wa-text); }
        .wa-toast-sub{ font-size: 12px; color: var(--wa-text-secondary); }

        /* Modal imagen */
        .wa-img-overlay{
            position: fixed;
            inset: 0;
            background: rgba(0,0,0,0.85);
            z-index: 2000;
            display:none;
            align-items:center;
            justify-content:center;
        }
        .wa-img-overlay img{ max-width: 92%; max-height: 92%; border-radius: 12px; }
        .wa-img-close{
            position:absolute;
            top: 16px;
            right: 16px;
            background: rgba(255,255,255,0.12);
            border: 1px solid rgba(255,255,255,0.22);
            color:#fff;
            width: 44px;
            height: 44px;
            border-radius: 50%;
            font-size: 26px;
            cursor:pointer;
        }

        /* Modal cine (Nuevo mensaje) */
        .wa-cine-overlay{
            position: fixed;
            inset: 0;
            background: rgba(0,0,0,0.45);
            z-index: 1500;
            display:none;
            align-items:center;
            justify-content:center;
        }
        .wa-cine-inner{
            width: 92%;
            max-width: 760px;
            background: var(--wa-panel);
            border: 1px solid var(--wa-border);
            border-radius: 14px;
            box-shadow: 0 18px 60px rgba(0,0,0,0.22);
            padding: 16px;
            display:flex;
            flex-direction:column;
            gap: 10px;
        }
        .wa-cine-head{
            display:flex;
            align-items:center;
            justify-content:space-between;
            gap: 10px;
        }
        .wa-cine-title{
            font-size: 16px;
            font-weight: 900;
            color: var(--wa-text);
        }
        .wa-cine-close{
            width: 36px;
            height: 36px;
            border-radius: 50%;
            border:none;
            background: transparent;
            cursor:pointer;
            color: var(--wa-text-secondary);
        }
        .wa-cine-close:hover{ background: var(--wa-hover); color: var(--wa-text); }

        .wa-cine-input{
            width: 100%;
            padding: 10px 12px;
            background: #f0f2f5;
            border: 1px solid transparent;
            border-radius: 10px;
            color: var(--wa-text);
            font-size: 14px;
            outline:none;
        }
        .wa-cine-input:focus{ background:#fff; border-color: rgba(0,168,132,0.25); }

        .wa-cine-textarea{
            width: 100%;
            min-height: 180px;
            background: #f0f2f5;
            border: 1px solid transparent;
            border-radius: 10px;
            color: var(--wa-text);
            font-size: 14px;
            padding: 12px;
            resize: none;
            outline:none;
        }
        .wa-cine-textarea:focus{ background:#fff; border-color: rgba(0,168,132,0.25); }

        .wa-cine-buttons{
            display:flex;
            justify-content:flex-end;
            gap: 10px;
            margin-top: 2px;
        }
        .wa-cine-btn{
            padding: 10px 14px;
            border-radius: 10px;
            border: 1px solid var(--wa-border);
            background: #fff;
            color: var(--wa-text);
            cursor:pointer;
            font-weight: 800;
            font-size: 13px;
        }
        .wa-cine-btn:hover{ background: var(--wa-hover); }

        .wa-cine-send{
            background: var(--wa-green);
            border-color: var(--wa-green);
            color:#fff;
        }
        .wa-cine-send:hover{ background: var(--wa-green-dark); border-color: var(--wa-green-dark); }

        /* Modal pregrabados */
        .wa-pregrab-overlay{
            position: fixed;
            inset: 0;
            background: rgba(0,0,0,0.45);
            z-index: 1600;
            display:none;
            align-items:center;
            justify-content:center;
        }
        .wa-pregrab-modal{
            width: 94%;
            max-width: 640px;
            max-height: 86vh;
            background: var(--wa-panel);
            border: 1px solid var(--wa-border);
            border-radius: 14px;
            display:flex;
            flex-direction:column;
            overflow:hidden;
            box-shadow: 0 18px 60px rgba(0,0,0,0.22);
        }
        .wa-pregrab-header{
            padding: 14px 16px;
            border-bottom: 1px solid var(--wa-border);
            display:flex;
            justify-content:space-between;
            align-items:center;
        }
        .wa-pregrab-title{ font-size: 14px; font-weight: 900; color: var(--wa-text); }
        .wa-pregrab-close{
            background: transparent;
            border: none;
            color: var(--wa-text-secondary);
            font-size: 24px;
            cursor: pointer;
            width: 36px;
            height: 36px;
            border-radius: 50%;
        }
        .wa-pregrab-close:hover{ background: var(--wa-hover); color: var(--wa-text); }

        .wa-pregrab-body{ padding: 14px 16px; overflow-y:auto; }

        .wa-pregrab-tabs{
            display:flex;
            gap: 8px;
            margin-bottom: 12px;
            flex-wrap: wrap;
        }
        .wa-pregrab-tab{
            padding: 6px 12px;
            background: #f0f2f5;
            border: 1px solid transparent;
            border-radius: 999px;
            color: var(--wa-text-secondary);
            font-size: 12px;
            font-weight: 800;
            cursor:pointer;
        }
        .wa-pregrab-tab.active{
            background: rgba(0,168,132,0.12);
            border-color: rgba(0,168,132,0.25);
            color: var(--wa-green-dark);
        }

        .wa-pregrab-card{
            padding: 12px;
            background: #f0f2f5;
            border: 1px solid rgba(0,0,0,0.04);
            border-radius: 12px;
            margin-bottom: 8px;
            cursor:pointer;
            transition: all .15s;
        }
        .wa-pregrab-card:hover{ background: var(--wa-hover); }
        .wa-pregrab-card-title{ font-weight: 900; margin-bottom: 4px; color: var(--wa-text); }
        .wa-pregrab-card-text{ font-size: 13px; color: var(--wa-text-secondary); white-space: pre-wrap; }

        /* Modal para adjuntar archivos */
        .wa-attach-modal{
            position: fixed;
            inset: 0;
            background: rgba(0,0,0,0.45);
            z-index: 1700;
            display:none;
            align-items:center;
            justify-content:center;
        }
        .wa-attach-inner{
            width: 92%;
            max-width: 500px;
            background: var(--wa-panel);
            border: 1px solid var(--wa-border);
            border-radius: 14px;
            box-shadow: 0 18px 60px rgba(0,0,0,0.22);
            padding: 20px;
            display:flex;
            flex-direction:column;
            gap: 15px;
        }
        .wa-attach-title{
            font-size: 18px;
            font-weight: 900;
            color: var(--wa-text);
            display:flex;
            align-items:center;
            gap: 10px;
        }
        .wa-attach-close{
            position: absolute;
            top: 16px;
            right: 16px;
            width: 36px;
            height: 36px;
            border-radius: 50%;
            border:none;
            background: transparent;
            cursor:pointer;
            color: var(--wa-text-secondary);
            font-size: 24px;
        }
        
        .wa-attach-tabs{
            display:flex;
            border-bottom: 1px solid var(--wa-border);
            margin-bottom: 15px;
        }
        .wa-attach-tab{
            flex:1;
            padding: 12px;
            background: transparent;
            border:none;
            border-bottom: 3px solid transparent;
            color: var(--wa-text-secondary);
            font-weight: 700;
            cursor:pointer;
            transition: all .2s;
        }
        .wa-attach-tab:hover{
            background: var(--wa-hover);
        }
        .wa-attach-tab.active{
            color: var(--wa-green-dark);
            border-bottom-color: var(--wa-green-dark);
        }
        
        .wa-attach-section{
            display:none;
        }
        .wa-attach-section.active{
            display:block;
        }
        
        .wa-attach-input{
            width: 100%;
            padding: 12px 14px;
            background: #f0f2f5;
            border: 1px solid transparent;
            border-radius: 10px;
            color: var(--wa-text);
            font-size: 14px;
            outline:none;
            margin-bottom: 10px;
        }
        .wa-attach-input:focus{ background:#fff; border-color: rgba(0,168,132,0.25); }
        
        .wa-file-input-container{
            position:relative;
            margin-bottom: 15px;
        }
        .wa-file-input-label{
            display:block;
            width:100%;
            padding: 40px 20px;
            background: #f0f2f5;
            border: 2px dashed var(--wa-border);
            border-radius: 12px;
            text-align:center;
            color: var(--wa-text-secondary);
            cursor:pointer;
            transition: all .2s;
        }
        .wa-file-input-label:hover{
            background: var(--wa-hover);
            border-color: var(--wa-green);
        }
        .wa-file-input-label svg{
            display:block;
            margin: 0 auto 10px;
            color: var(--wa-text-secondary);
        }
        .wa-file-input{
            position:absolute;
            width:100%;
            height:100%;
            top:0;
            left:0;
            opacity:0;
            cursor:pointer;
        }
        .wa-file-name{
            margin-top: 10px;
            font-size: 12px;
            color: var(--wa-text);
            text-align:center;
        }
        
        .wa-attach-buttons{
            display:flex;
            justify-content:flex-end;
            gap: 10px;
            margin-top: 10px;
        }
        .wa-attach-btn{
            padding: 10px 18px;
            border-radius: 10px;
            border: 1px solid var(--wa-border);
            background: #fff;
            color: var(--wa-text);
            cursor:pointer;
            font-weight: 800;
            font-size: 13px;
        }
        .wa-attach-btn:hover{ background: var(--wa-hover); }
        .wa-attach-send{
            background: var(--wa-green);
            border-color: var(--wa-green);
            color:#fff;
        }
        .wa-attach-send:hover{ background: var(--wa-green-dark); border-color: var(--wa-green-dark); }
        
        .wa-attach-progress{
            width:100%;
            height:6px;
            background:#f0f2f5;
            border-radius:3px;
            overflow:hidden;
            margin:10px 0;
            display:none;
        }
        .wa-attach-progress-bar{
            height:100%;
            background:var(--wa-green);
            width:0%;
            transition:width .3s;
        }

        /* Modal para texto adicional (caption) */
        .wa-caption-modal{
            position: fixed;
            inset: 0;
            background: rgba(0,0,0,0.45);
            z-index: 1800;
            display:none;
            align-items:center;
            justify-content:center;
        }
        .wa-caption-inner{
            width: 92%;
            max-width: 500px;
            background: var(--wa-panel);
            border: 1px solid var(--wa-border);
            border-radius: 14px;
            box-shadow: 0 18px 60px rgba(0,0,0,0.22);
            padding: 20px;
            display:flex;
            flex-direction:column;
            gap: 15px;
        }
        .wa-caption-title{
            font-size: 18px;
            font-weight: 900;
            color: var(--wa-text);
        }
        .wa-caption-close{
            position: absolute;
            top: 16px;
            right: 16px;
            width: 36px;
            height: 36px;
            border-radius: 50%;
            border:none;
            background: transparent;
            cursor:pointer;
            color: var(--wa-text-secondary);
            font-size: 24px;
        }
        .wa-caption-textarea{
            width:100%;
            min-height: 100px;
            padding: 12px;
            background: #f0f2f5;
            border: 1px solid transparent;
            border-radius: 10px;
            color: var(--wa-text);
            font-size: 14px;
            resize: vertical;
            outline:none;
        }
        .wa-caption-textarea:focus{
            background:#fff;
            border-color: rgba(0,168,132,0.25);
        }
        .wa-caption-buttons{
            display:flex;
            justify-content:flex-end;
            gap: 10px;
            margin-top: 10px;
        }
        .wa-caption-btn{
            padding: 10px 18px;
            border-radius: 10px;
            border: 1px solid var(--wa-border);
            background: #fff;
            color: var(--wa-text);
            cursor:pointer;
            font-weight: 800;
            font-size: 13px;
        }
        .wa-caption-btn:hover{ background: var(--wa-hover); }
        .wa-caption-send{
            background: var(--wa-green);
            border-color: var(--wa-green);
            color:#fff;
        }
        .wa-caption-send:hover{ background: var(--wa-green-dark); border-color: var(--wa-green-dark); }

        /* Scrollbar */
        ::-webkit-scrollbar { width: 8px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: rgba(0,0,0,0.18); border-radius: 6px; }
        ::-webkit-scrollbar-thumb:hover { background: rgba(0,0,0,0.25); }
    </style>
</head>

<body>
<div class="wa-container">
    <!-- Sidebar -->
    <div class="wa-sidebar">
        <div class="wa-sidebar-header">
            <div class="wa-sidebar-top">
                <span class="wa-sidebar-title">Chats</span>
                <div class="wa-header-actions">
                    <button type="button" class="wa-btn-icon" title="Actualizar" onclick="actualizarListaContactos(true)">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M17.65 6.35A7.95 7.95 0 0012 4V1L7 6l5 5V7a5 5 0 11-5 5H5a7 7 0 107.75-6.95 7.9 7.9 0 014.9 1.3z"/>
                        </svg>
                    </button>
                    <button type="button" class="wa-btn-new" onclick="abrirCine()">Nuevo</button>
                </div>
            </div>

            <form method="get" id="filtrosForm">
                <?php if ($contactoIdSel): ?><input type="hidden" name="contacto_id" value="<?= (int)$contactoIdSel ?>"><?php endif; ?>
                <?php if ($paginaActual > 1): ?><input type="hidden" name="p" value="<?= (int)$paginaActual ?>"><?php endif; ?>
                <?php if ($soloNoLeidos): ?><input type="hidden" name="no_leidos" value="1"><?php endif; ?>
                <?php if ($soloPocas): ?><input type="hidden" name="pocas" value="1"><?php endif; ?>
                <?php if ($soloUno): ?><input type="hidden" name="uno" value="1"><?php endif; ?>

                <div class="wa-search-box">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="11" cy="11" r="8"></circle>
                        <path d="m21 21-4.35-4.35"></path>
                    </svg>
                    <input type="text" name="q" placeholder="Buscar..." value="<?= htmlspecialchars($busqueda) ?>" onchange="this.form.submit()">
                </div>

                <?php
                    $base = [];
                    if ($busqueda !== '') $base['q'] = $busqueda;
                    if ($contactoIdSel) $base['contacto_id'] = $contactoIdSel;
                    if ($hasta !== '') $base['desde'] = $hasta;

                    $urlTodos = 'whatsapp.php' . (!empty($base) ? ('?' . http_build_query($base)) : '');
                    $pNo = $base; $pNo['no_leidos'] = 1; $urlNo = 'whatsapp.php?' . http_build_query($pNo);
                    $pPocas = $base; $pPocas['pocas'] = 1; $urlPocas = 'whatsapp.php?' . http_build_query($pPocas);
                    $pUno = $base; $pUno['uno'] = 1; $urlUno = 'whatsapp.php?' . http_build_query($pUno);
                ?>

                <div class="wa-filters">
                    <a href="<?= htmlspecialchars($urlTodos) ?>" class="wa-filter-btn <?= (!$soloNoLeidos && !$soloPocas && !$soloUno) ? 'active' : '' ?>">Todos</a>
                    <a href="<?= htmlspecialchars($urlNo) ?>" class="wa-filter-btn <?= $soloNoLeidos ? 'active' : '' ?>">No respondidos</a>
                    <a href="<?= htmlspecialchars($urlPocas) ?>" class="wa-filter-btn <?= $soloPocas ? 'active' : '' ?>">&lt; 6</a>
                    <a href="<?= htmlspecialchars($urlUno) ?>" class="wa-filter-btn <?= $soloUno ? 'active' : '' ?>">= 1</a>
                </div>

                <?php
                    $baseFecha = [];
                    if ($busqueda !== '') $baseFecha['q'] = $busqueda;
                    if ($contactoIdSel) $baseFecha['contacto_id'] = $contactoIdSel;
                    if ($soloNoLeidos) $baseFecha['no_leidos'] = 1;
                    if ($soloPocas) $baseFecha['pocas'] = 1;
                    if ($soloUno) $baseFecha['uno'] = 1;

                    $bHoy = $baseFecha; $bHoy['desde'] = fecha_hoy_ymd(); $urlHoy = 'whatsapp.php?' . http_build_query($bHoy);
                    $bAyer = $baseFecha; $bAyer['desde'] = fecha_ayer_ymd(); $urlAyer = 'whatsapp.php?' . http_build_query($bAyer);
                    $bAnte = $baseFecha; $bAnte['desde'] = fecha_anteayer_ymd(); $urlAnte = 'whatsapp.php?' . http_build_query($bAnte);
                    $bSin = $baseFecha; unset($bSin['desde']); $urlSinFecha = 'whatsapp.php' . (!empty($bSin) ? ('?' . http_build_query($bSin)) : '');
                ?>

                <div class="wa-date-row">
                    <a class="wa-date-btn" href="<?= htmlspecialchars($urlHoy) ?>">Hoy</a>
                    <a class="wa-date-btn" href="<?= htmlspecialchars($urlAyer) ?>">Ayer</a>
                    <a class="wa-date-btn" href="<?= htmlspecialchars($urlAnte) ?>">Ante</a>
                    <input type="date" name="desde" class="wa-date-input" value="<?= htmlspecialchars($hasta) ?>" onchange="this.form.submit()">
                    <?php if ($hasta !== ''): ?>
                        <a class="wa-date-clear" href="<?= htmlspecialchars($urlSinFecha) ?>">Quitar</a>
                    <?php endif; ?>
                </div>
            </form>
        </div>

        <div class="wa-contact-list" id="listaContactos">
            <?= renderListaContactos($contactos, $contactoIdSel, $busqueda, $paginaActual, $soloNoLeidos, $totalPaginas, $soloPocas, $soloUno, $PLANTILLA_PREFIJOS, $hasta) ?>
        </div>
    </div>

    <!-- Chat -->
    <div class="wa-chat">
        <div class="wa-chat-header">
            <?php if ($contactoSel): ?>
                <div class="wa-chat-header-info">
                    <div class="wa-avatar"><?= mb_strtoupper(mb_substr($contactoSel['nombre'] ?: $contactoSel['telefono'], 0, 1)) ?></div>
                    <div>
                        <div class="wa-chat-name"><?= htmlspecialchars($contactoSel['nombre'] ?: $contactoSel['telefono']) ?></div>
                        <div class="wa-chat-phone"><?= htmlspecialchars($contactoSel['telefono']) ?></div>
                    </div>
                </div>
                <button type="button" class="wa-btn-icon" onclick="actualizarMensajesChat()" title="Actualizar chat">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M17.65 6.35A7.95 7.95 0 0012 4V1L7 6l5 5V7a5 5 0 11-5 5H5a7 7 0 107.75-6.95 7.9 7.9 0 014.9 1.3z"/>
                    </svg>
                </button>
            <?php else: ?>
                <span style="color: var(--wa-text-secondary); font-weight:700;">Selecciona un chat</span>
            <?php endif; ?>
        </div>

        <div class="wa-messages" id="mensajesWrap">
            <div id="mensajesDiv">
                <?= renderMensajesInner($contactoSel, $mensajes, $hasta) ?>
            </div>
        </div>

        <div class="wa-chat-footer">
            <?php if ($contactoSel): ?>
                <form method="post" id="formEnvio">
                    <input type="hidden" name="contacto_id" value="<?= (int)$contactoSel['id'] ?>">
                    <?php if ($busqueda !== ''): ?><input type="hidden" name="q" value="<?= htmlspecialchars($busqueda) ?>"><?php endif; ?>
                    <?php if ($hasta !== ''): ?><input type="hidden" name="desde" value="<?= htmlspecialchars($hasta) ?>"><?php endif; ?>
                    <input type="hidden" name="no_leidos" value="<?= $soloNoLeidos ? '1' : '0' ?>">
                    <input type="hidden" name="pocas" value="<?= $soloPocas ? '1' : '0' ?>">
                    <input type="hidden" name="uno" value="<?= $soloUno ? '1' : '0' ?>">
                    <input type="hidden" name="p" value="<?= (int)$paginaActual ?>">

                    <div class="wa-input-row">
                        <div class="wa-input-wrap">
                            <textarea name="mensaje" id="mensajeTextarea" rows="1" placeholder="Escribe un mensaje..." required></textarea>
                            <!-- Botón para adjuntar archivos -->
                            <button type="button" class="wa-btn-attach" onclick="abrirModalAdjuntar()" title="Adjuntar archivo">
                                <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                                    <path d="M14.5 6.5V17a3.5 3.5 0 11-7 0V5a2 2 0 114 0v10.5a1 1 0 01-2 0V6.5"/>
                                    <path d="M18 6.5V17a5 5 0 01-10 0V5a3 3 0 116 0v11.5a1.5 1.5 0 01-3 0V6.5"/>
                                </svg>
                            </button>
                            <!-- Botón para pregrabados -->
                            <button type="button" class="wa-btn-pregrab" onclick="abrirPregrabados('chat')" title="Pregrabados">
                                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                                    <polyline points="14 2 14 8 20 8"/>
                                </svg>
                            </button>
                        </div>
                        <button type="submit" class="wa-btn-send" id="btnEnviar" title="Enviar">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                                <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
                            </svg>
                        </button>
                    </div>
                </form>
            <?php else: ?>
                <div style="text-align: center; color: var(--wa-text-secondary); font-weight:700;">Selecciona un chat para escribir</div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Toast -->
<div class="wa-toast" id="waToast">
    <div class="wa-toast-title" id="waToastTitle">Info</div>
    <div class="wa-toast-sub" id="waToastSub"></div>
</div>

<!-- Modal imagen -->
<div class="wa-img-overlay" id="imgOverlay" onclick="cerrarImgModal()">
    <button class="wa-img-close" onclick="cerrarImgModal()">×</button>
    <img id="imgModalSrc" src="">
</div>

<!-- Modal cine (Nuevo mensaje) -->
<div class="wa-cine-overlay" id="cineOverlay">
    <div class="wa-cine-inner">
        <div class="wa-cine-head">
            <div class="wa-cine-title">Nuevo mensaje</div>
            <button class="wa-cine-close" onclick="cerrarCine()" title="Cerrar">×</button>
        </div>

        <input type="text" id="cineTelefono" class="wa-cine-input" placeholder="Número (ej: 341xxxxxx)">
        <textarea id="cineTextarea" class="wa-cine-textarea" placeholder="Escribe tu mensaje..."></textarea>

        <div class="wa-cine-buttons">
            <button type="button" class="wa-cine-btn" onclick="abrirPregrabados('cine')">Pregrabados</button>
            <button type="button" class="wa-cine-btn" onclick="cerrarCine()">Cancelar</button>
            <button type="button" class="wa-cine-btn wa-cine-send" onclick="enviarDesdeCine()">Enviar</button>
        </div>
    </div>
</div>

<!-- Modal pregrabados -->
<div class="wa-pregrab-overlay" id="pregrabOverlay" onclick="if(event.target===this)cerrarPregrabados()">
    <div class="wa-pregrab-modal">
        <div class="wa-pregrab-header">
            <span class="wa-pregrab-title">Mensajes pregrabados</span>
            <button class="wa-pregrab-close" onclick="cerrarPregrabados()">×</button>
        </div>
        <div class="wa-pregrab-body">
            <div class="wa-pregrab-tabs">
                <button class="wa-pregrab-tab active" data-cat="STOCK" onclick="seleccionarCategoriaPregrab('STOCK')">Stock</button>
                <button class="wa-pregrab-tab" data-cat="RADIOSNET" onclick="seleccionarCategoriaPregrab('RADIOSNET')">RadiosNet</button>
                <button class="wa-pregrab-tab" data-cat="SITIOS" onclick="seleccionarCategoriaPregrab('SITIOS')">Sitios</button>
                <button class="wa-pregrab-tab" data-cat="JINGLES" onclick="seleccionarCategoriaPregrab('JINGLES')">Jingles</button>
                <button class="wa-pregrab-tab" data-cat="OTROS" onclick="seleccionarCategoriaPregrab('OTROS')">Otros</button>
            </div>

            <?php
            $catLabels = ['STOCK'=>'Stock','RADIOSNET'=>'RadiosNet','SITIOS'=>'Sitios','JINGLES'=>'Jingles','OTROS'=>'Otros'];
            foreach ($catLabels as $catKey => $catName):
                $list = $PREGUNTAS[$catKey] ?? [];
            ?>
                <div class="wa-pregrab-section" data-cat="<?= htmlspecialchars($catKey) ?>" style="<?= ($catKey!=='STOCK' ? 'display:none' : '') ?>">
                    <?php if (!$list): ?>
                        <p style="color: var(--wa-text-secondary); font-weight:700;">No hay mensajes en esta categoría.</p>
                    <?php else: ?>
                        <?php foreach ($list as $p): ?>
                            <div class="wa-pregrab-card" onclick="usarPregrabadoDesdeCard(this)">
                                <div class="wa-pregrab-card-title"><?= htmlspecialchars($p['titulo']) ?></div>
                                <div class="wa-pregrab-card-text"><?= htmlspecialchars($p['texto']) ?></div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<!-- Modal para adjuntar archivos -->
<div class="wa-attach-modal" id="attachModal">
    <div class="wa-attach-inner">
        <div style="position:relative;">
            <div class="wa-attach-title">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M14.5 6.5V17a3.5 3.5 0 11-7 0V5a2 2 0 114 0v10.5a1 1 0 01-2 0V6.5"/>
                    <path d="M18 6.5V17a5 5 0 01-10 0V5a3 3 0 116 0v11.5a1.5 1.5 0 01-3 0V6.5"/>
                </svg>
                Adjuntar archivo
            </div>
            <button class="wa-attach-close" onclick="cerrarModalAdjuntar()">×</button>
        </div>
        
        <div class="wa-attach-tabs">
            <button class="wa-attach-tab active" onclick="seleccionarTabAdjuntar('imagen')">Imagen</button>
            <button class="wa-attach-tab" onclick="seleccionarTabAdjuntar('audio')">Audio</button>
            <button class="wa-attach-tab" onclick="seleccionarTabAdjuntar('video')">Video</button>
            <button class="wa-attach-tab" onclick="seleccionarTabAdjuntar('url')">URL</button>
        </div>
        
        <!-- Sección Imagen -->
        <div class="wa-attach-section active" id="section-imagen">
            <div class="wa-file-input-container">
                <label class="wa-file-input-label" for="fileInputImagen">
                    <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                        <rect x="3" y="3" width="18" height="18" rx="2" ry="2"/>
                        <circle cx="8.5" cy="8.5" r="1.5"/>
                        <polyline points="21 15 16 10 5 21"/>
                    </svg>
                    <div>Haz clic para seleccionar una imagen</div>
                    <div style="font-size:12px; margin-top:5px;">Formatos: JPG, PNG, GIF, WebP (máx. 10MB)</div>
                </label>
                <input type="file" id="fileInputImagen" class="wa-file-input" accept="image/*" onchange="mostrarNombreArchivo(this, 'imagen')">
                <div id="fileNameImagen" class="wa-file-name"></div>
            </div>
            <div class="wa-attach-progress" id="progressImagen">
                <div class="wa-attach-progress-bar" id="progressBarImagen"></div>
            </div>
            <div class="wa-attach-buttons">
                <button type="button" class="wa-attach-btn" onclick="cerrarModalAdjuntar()">Cancelar</button>
                <button type="button" class="wa-attach-btn wa-attach-send" onclick="subirArchivo('imagen')">Subir y enviar</button>
            </div>
        </div>
        
        <!-- Sección Audio -->
        <div class="wa-attach-section" id="section-audio">
            <div class="wa-file-input-container">
                <label class="wa-file-input-label" for="fileInputAudio">
                    <svg width="48" height="48" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M12 1a3 3 0 00-3 3v8a3 3 0 006 0V4a3 3 0 00-3-3z"/>
                        <path d="M19 10v2a7 7 0 01-14 0v-2"/>
                        <line x1="12" y1="19" x2="12" y2="23"/>
                        <line x1="8" y1="23" x2="16" y2="23"/>
                    </svg>
                    <div>Haz clic para seleccionar un audio</div>
                    <div style="font-size:12px; margin-top:5px;">Formatos: MP3, WAV, OGG, M4A (máx. 10MB)</div>
                </label>
                <input type="file" id="fileInputAudio" class="wa-file-input" accept="audio/*" onchange="mostrarNombreArchivo(this, 'audio')">
                <div id="fileNameAudio" class="wa-file-name"></div>
            </div>
            <div class="wa-attach-progress" id="progressAudio">
                <div class="wa-attach-progress-bar" id="progressBarAudio"></div>
            </div>
            <div class="wa-attach-buttons">
                <button type="button" class="wa-attach-btn" onclick="cerrarModalAdjuntar()">Cancelar</button>
                <button type="button" class="wa-attach-btn wa-attach-send" onclick="subirArchivo('audio')">Subir y enviar</button>
            </div>
        </div>
        
        <!-- Sección Video -->
        <div class="wa-attach-section" id="section-video">
            <div class="wa-file-input-container">
                <label class="wa-file-input-label" for="fileInputVideo">
                    <svg width="48" height="48" viewBox="0 0 24 24" fill="currentColor">
                        <polygon points="23 7 16 12 23 17 23 7"/>
                        <rect x="1" y="5" width="15" height="14" rx="2" ry="2"/>
                    </svg>
                    <div>Haz clic para seleccionar un video</div>
                    <div style="font-size:12px; margin-top:5px;">Formatos: MP4, AVI, MOV, WMV (máx. 10MB)</div>
                </label>
                <input type="file" id="fileInputVideo" class="wa-file-input" accept="video/*" onchange="mostrarNombreArchivo(this, 'video')">
                <div id="fileNameVideo" class="wa-file-name"></div>
            </div>
            <div class="wa-attach-progress" id="progressVideo">
                <div class="wa-attach-progress-bar" id="progressBarVideo"></div>
            </div>
            <div class="wa-attach-buttons">
                <button type="button" class="wa-attach-btn" onclick="cerrarModalAdjuntar()">Cancelar</button>
                <button type="button" class="wa-attach-btn wa-attach-send" onclick="subirArchivo('video')">Subir y enviar</button>
            </div>
        </div>
        
        <!-- Sección URL -->
        <div class="wa-attach-section" id="section-url">
            <input type="text" id="urlInput" class="wa-attach-input" placeholder="https://ejemplo.com/imagen.jpg">
            <div style="font-size:12px; color:#666; margin-bottom:15px;">
                Ingresa la URL pública del archivo (imagen, audio o video)
            </div>
            <div class="wa-attach-buttons">
                <button type="button" class="wa-attach-btn" onclick="cerrarModalAdjuntar()">Cancelar</button>
                <button type="button" class="wa-attach-btn wa-attach-send" onclick="enviarDesdeURL()">Enviar desde URL</button>
            </div>
        </div>
    </div>
</div>

<!-- Modal para texto adicional (caption) -->
<div class="wa-caption-modal" id="captionModal">
    <div class="wa-caption-inner">
        <div class="wa-caption-title">Agregar texto adicional</div>
        <button class="wa-caption-close" onclick="cerrarModalCaption()">×</button>
        
        <textarea id="captionTextarea" class="wa-caption-textarea" placeholder="Texto opcional que aparecerá con el archivo..."></textarea>
        
        <div class="wa-caption-buttons">
            <button type="button" class="wa-caption-btn" onclick="cerrarModalCaption()">Sin texto</button>
            <button type="button" class="wa-caption-btn wa-caption-send" onclick="enviarConCaption()">Enviar con texto</button>
        </div>
    </div>
</div>

<!-- Form oculto para cine -->
<form method="post" id="formEnvioCine" style="display:none;">
    <input type="hidden" name="mensaje" id="cineMensajeHidden">
    <input type="hidden" name="telefono_directo" id="cineTelefonoHidden">
    <?php if ($busqueda !== ''): ?><input type="hidden" name="q" value="<?= htmlspecialchars($busqueda) ?>"><?php endif; ?>
    <?php if ($hasta !== ''): ?><input type="hidden" name="desde" value="<?= htmlspecialchars($hasta) ?>"><?php endif; ?>
    <input type="hidden" name="no_leidos" value="<?= $soloNoLeidos ? '1' : '0' ?>">
    <input type="hidden" name="pocas" value="<?= $soloPocas ? '1' : '0' ?>">
    <input type="hidden" name="uno" value="<?= $soloUno ? '1' : '0' ?>">
    <input type="hidden" name="p" value="<?= (int)$paginaActual ?>">
</form>

<!-- Input oculto para formulario de subida -->
<input type="file" id="hiddenFileInput" style="display:none;">

<script>
// Estado actual
const STATE = {
    contactId: <?= (int)$contactoIdSel ?>,
    busqueda: <?= json_encode($busqueda) ?>,
    noLeidos: '<?= $soloNoLeidos ? '1' : '0' ?>',
    pocas: '<?= $soloPocas ? '1' : '0' ?>',
    uno: '<?= $soloUno ? '1' : '0' ?>',
    desde: <?= json_encode($hasta) ?>,
    pagina: <?= (int)$paginaActual ?>,
    refChat: '<?= $refChat ? '1' : '0' ?>'
};

const hayFiltroActivo = STATE.noLeidos === '1' || STATE.pocas === '1' || STATE.uno === '1';

// Variables para el flujo de envío de archivos
let archivoParaEnviar = null;
let tipoArchivoParaEnviar = '';
let urlArchivoParaEnviar = '';

// Target de pregrabados: 'chat' o 'cine'
let PREGRAB_TARGET = 'chat';

function guardarScrollLista() {
    const cont = document.getElementById('listaContactos');
    if (cont) sessionStorage.setItem('wa_scroll_pos', cont.scrollTop);
}
function restaurarScrollLista() {
    const cont = document.getElementById('listaContactos');
    const savedPos = sessionStorage.getItem('wa_scroll_pos');
    if (cont && savedPos !== null) cont.scrollTop = parseInt(savedPos, 10);
}

document.addEventListener('DOMContentLoaded', function() {
    restaurarScrollLista();

    const mensajesWrap = document.getElementById('mensajesWrap');
    if (mensajesWrap) mensajesWrap.scrollTop = mensajesWrap.scrollHeight;

    const textarea = document.getElementById('mensajeTextarea');
    if (textarea) {
        textarea.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = Math.min(this.scrollHeight, 140) + 'px';
        });
        textarea.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                document.getElementById('formEnvio').requestSubmit();
            }
        });
    }

    const formEnvio = document.getElementById('formEnvio');
    const btnEnviar = document.getElementById('btnEnviar');
    if (formEnvio && btnEnviar) {
        formEnvio.addEventListener('submit', function(ev) {
            ev.preventDefault();

            if (btnEnviar.dataset.locked === '1') return false;
            btnEnviar.dataset.locked = '1';
            btnEnviar.disabled = true;

            const fd = new FormData(formEnvio);
            fd.append('ajax_send', '1');

            fetch('whatsapp.php', { method: 'POST', body: fd, cache: 'no-store' })
                .then(r => r.json())
                .then(data => {
                    const ta = document.getElementById('mensajeTextarea');
                    if (ta) { ta.value = ''; ta.style.height = 'auto'; }

                    setTimeout(function() {
                        actualizarMensajesChat();
                        if (!hayFiltroActivo) actualizarListaContactos(false);
                    }, 900);

                    if (!data || data.ok !== 1) toast('Error', (data && data.message) ? data.message : 'No se pudo enviar');
                    else toast('Enviado', 'Mensaje enviado');
                })
                .catch(() => toast('Error', 'Error de red'))
                .finally(() => {
                    setTimeout(() => { btnEnviar.disabled = false; btnEnviar.dataset.locked = '0'; }, 850);
                });

            return false;
        });
    }

    const cineTextarea = document.getElementById('cineTextarea');
    if (cineTextarea) {
        cineTextarea.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                enviarDesdeCine();
            }
        });
    }

    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            cerrarImgModal();
            cerrarCine();
            cerrarPregrabados();
            cerrarModalAdjuntar();
            cerrarModalCaption();
        }
    });

    if (STATE.refChat === '1' && STATE.contactId > 0) {
        setTimeout(function() {
            actualizarMensajesChat();
            try {
                const u = new URL(window.location.href);
                if (u.searchParams.has('ref_chat')) {
                    u.searchParams.delete('ref_chat');
                    window.history.replaceState({}, document.title, u.toString());
                }
            } catch(e) {}
        }, 900);
    }

    // Auto-refresh SOLO si NO hay filtro activo
    if (!hayFiltroActivo) {
        setInterval(function() { actualizarListaContactos(false); }, 15000);
    }
});

function toast(title, sub) {
    const t = document.getElementById('waToast');
    const tt = document.getElementById('waToastTitle');
    const ts = document.getElementById('waToastSub');
    if (!t) return;
    tt.textContent = title || 'Info';
    ts.textContent = sub || '';
    t.style.display = 'block';
    clearTimeout(window.__toastTO);
    window.__toastTO = setTimeout(() => { t.style.display = 'none'; }, 2400);
}

function buildQuery() {
    let params = [];
    if (STATE.busqueda) params.push('q=' + encodeURIComponent(STATE.busqueda));
    if (STATE.noLeidos === '1') params.push('no_leidos=1');
    if (STATE.pocas === '1') params.push('pocas=1');
    if (STATE.uno === '1') params.push('uno=1');
    if (STATE.desde) params.push('desde=' + encodeURIComponent(STATE.desde));
    if (STATE.pagina > 1) params.push('p=' + STATE.pagina);
    if (STATE.contactId > 0) params.push('contacto_id=' + STATE.contactId);
    return params.length ? '&' + params.join('&') : '';
}

function actualizarListaContactos(forceTop) {
    const cont = document.getElementById('listaContactos');
    if (!cont) return;

    const prevScroll = cont.scrollTop;
    const url = 'whatsapp.php?ajax=lista' + buildQuery();

    fetch(url, { cache: 'no-store' })
        .then(r => r.text())
        .then(html => {
            cont.innerHTML = html;
            if (!forceTop) cont.scrollTop = prevScroll;
        })
        .catch(() => {});
}

function actualizarMensajesChat() {
    const wrap = document.getElementById('mensajesWrap');
    const div = document.getElementById('mensajesDiv');
    if (!div || !wrap || STATE.contactId <= 0) return;

    const url = 'whatsapp.php?ajax=mensajes' + buildQuery();
    fetch(url, { cache: 'no-store' })
        .then(r => r.text())
        .then(html => {
            div.innerHTML = html;
            wrap.scrollTop = wrap.scrollHeight;
        })
        .catch(() => {});
}

// NUEVO: Función para transcribir audio
async function transcribirAudio(btn, audioUrl, audioId) {
    const resultDiv = document.getElementById('transcription-' + audioId);
    if (!btn || !resultDiv) return;

    btn.disabled = true;
    btn.textContent = 'Transcribiendo...';
    resultDiv.style.display = 'none';

    const fd = new FormData();
    fd.append('ajax_transcribir_audio', '1');
    fd.append('audio_url', audioUrl);

    try {
        const r = await fetch('whatsapp.php', {method: 'POST', body: fd, cache: 'no-store'});
        const data = await r.json();

        if (data.ok === 1 && data.texto) {
            resultDiv.innerHTML = '<strong>Transcripción:</strong><br>' + data.texto.replace(/\n/g, '<br>');
            resultDiv.style.display = 'block';
            btn.textContent = '✓ Transcribir audio';
        } else {
            resultDiv.innerHTML = '<strong>Error:</strong> ' + (data.message || 'No se pudo transcribir');
            resultDiv.style.display = 'block';
            btn.textContent = 'Transcribir audio';
            btn.disabled = false;
        }
    } catch(e) {
        console.error(e);
        resultDiv.innerHTML = '<strong>Error de red:</strong> No se pudo conectar';
        resultDiv.style.display = 'block';
        btn.textContent = 'Transcribir audio';
        btn.disabled = false;
    }
}

// ============================================
// FUNCIONES PARA ADJUNTAR ARCHIVOS
// ============================================

function abrirModalAdjuntar() {
    document.getElementById('attachModal').style.display = 'flex';
    seleccionarTabAdjuntar('imagen');
    resetearFormularioAdjuntar();
}

function cerrarModalAdjuntar() {
    document.getElementById('attachModal').style.display = 'none';
    resetearFormularioAdjuntar();
}

function seleccionarTabAdjuntar(tab) {
    // Actualizar pestañas
    document.querySelectorAll('.wa-attach-tab').forEach(t => {
        t.classList.remove('active');
    });
    document.querySelector(`.wa-attach-tab[onclick*="${tab}"]`).classList.add('active');
    
    // Mostrar sección correspondiente
    document.querySelectorAll('.wa-attach-section').forEach(s => {
        s.classList.remove('active');
    });
    document.getElementById(`section-${tab}`).classList.add('active');
    
    // Resetear formulario
    resetearFormularioAdjuntar();
}

function resetearFormularioAdjuntar() {
    // Limpiar nombres de archivo
    document.getElementById('fileNameImagen').textContent = '';
    document.getElementById('fileNameAudio').textContent = '';
    document.getElementById('fileNameVideo').textContent = '';
    document.getElementById('urlInput').value = '';
    
    // Limpiar inputs de archivo
    document.getElementById('fileInputImagen').value = '';
    document.getElementById('fileInputAudio').value = '';
    document.getElementById('fileInputVideo').value = '';
    
    // Ocultar barras de progreso
    document.querySelectorAll('.wa-attach-progress').forEach(p => {
        p.style.display = 'none';
    });
    document.querySelectorAll('.wa-attach-progress-bar').forEach(b => {
        b.style.width = '0%';
    });
}

function mostrarNombreArchivo(input, tipo) {
    const fileNameDiv = document.getElementById(`fileName${tipo.charAt(0).toUpperCase() + tipo.slice(1)}`);
    if (input.files.length > 0) {
        const file = input.files[0];
        fileNameDiv.textContent = `Archivo seleccionado: ${file.name} (${formatBytes(file.size)})`;
    } else {
        fileNameDiv.textContent = '';
    }
}

function formatBytes(bytes, decimals = 2) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

async function subirArchivo(tipo) {
    let fileInput;
    let progressBar;
    let progressContainer;
    
    if (tipo === 'imagen') {
        fileInput = document.getElementById('fileInputImagen');
        progressBar = document.getElementById('progressBarImagen');
        progressContainer = document.getElementById('progressImagen');
    } else if (tipo === 'audio') {
        fileInput = document.getElementById('fileInputAudio');
        progressBar = document.getElementById('progressBarAudio');
        progressContainer = document.getElementById('progressAudio');
    } else if (tipo === 'video') {
        fileInput = document.getElementById('fileInputVideo');
        progressBar = document.getElementById('progressBarVideo');
        progressContainer = document.getElementById('progressVideo');
    } else {
        toast('Error', 'Tipo de archivo no válido');
        return;
    }
    
    if (!fileInput.files || fileInput.files.length === 0) {
        toast('Atención', 'Selecciona un archivo primero');
        return;
    }
    
    const file = fileInput.files[0];
    
    // Validar tamaño (10MB)
    if (file.size > 10 * 1024 * 1024) {
        toast('Error', 'El archivo es demasiado grande (máximo 10MB)');
        return;
    }
    
    // Mostrar progreso
    progressContainer.style.display = 'block';
    progressBar.style.width = '0%';
    
    const formData = new FormData();
    formData.append('ajax_subir_archivo', '1');
    formData.append('tipo', tipo);
    formData.append('archivo', file);
    
    try {
        const xhr = new XMLHttpRequest();
        
        xhr.upload.addEventListener('progress', function(e) {
            if (e.lengthComputable) {
                const percentComplete = (e.loaded / e.total) * 100;
                progressBar.style.width = percentComplete + '%';
            }
        });
        
        xhr.onreadystatechange = function() {
            if (xhr.readyState === XMLHttpRequest.DONE) {
                progressBar.style.width = '100%';
                
                setTimeout(() => {
                    const response = JSON.parse(xhr.responseText);
                    
                    if (response.ok === 1) {
                        // Guardar datos para envío
                        archivoParaEnviar = file;
                        tipoArchivoParaEnviar = tipo;
                        urlArchivoParaEnviar = response.url;
                        
                        // Cerrar modal de adjuntar
                        cerrarModalAdjuntar();
                        
                        // Preguntar si quiere agregar texto (caption)
                        if (tipo === 'imagen' || tipo === 'video') {
                            abrirModalCaption(tipo);
                        } else {
                            // Para audio, enviar directamente
                            enviarArchivoSubido('');
                        }
                    } else {
                        toast('Error', response.message || 'Error al subir el archivo');
                    }
                }, 300);
            }
        };
        
        xhr.open('POST', 'whatsapp.php', true);
        xhr.send(formData);
        
    } catch (error) {
        console.error('Error al subir archivo:', error);
        toast('Error', 'Error al subir el archivo');
    }
}

function abrirModalCaption(tipo) {
    document.getElementById('captionModal').style.display = 'flex';
    document.getElementById('captionTextarea').value = '';
    document.getElementById('captionTextarea').focus();
    document.getElementById('captionTextarea').placeholder = `Texto opcional para ${tipo === 'imagen' ? 'la imagen' : 'el video'}...`;
}

function cerrarModalCaption() {
    document.getElementById('captionModal').style.display = 'none';
    // Enviar sin texto
    enviarArchivoSubido('');
}

function enviarConCaption() {
    const caption = document.getElementById('captionTextarea').value.trim();
    cerrarModalCaption();
    enviarArchivoSubido(caption);
}

async function enviarArchivoSubido(caption = '') {
    if (!urlArchivoParaEnviar || !tipoArchivoParaEnviar) {
        toast('Error', 'No hay archivo para enviar');
        return;
    }
    
    const endpoint = tipoArchivoParaEnviar === 'imagen' ? 'ajax_send_imagen' : 
                    tipoArchivoParaEnviar === 'audio' ? 'ajax_send_audio' : 
                    'ajax_send_video';
    
    const fd = new FormData();
    fd.append(endpoint, '1');
    fd.append('contacto_id', STATE.contactId);
    
    if (tipoArchivoParaEnviar === 'imagen') {
        fd.append('imagen_url', urlArchivoParaEnviar);
        if (caption) fd.append('caption', caption);
    } else if (tipoArchivoParaEnviar === 'audio') {
        fd.append('audio_url', urlArchivoParaEnviar);
    } else if (tipoArchivoParaEnviar === 'video') {
        fd.append('video_url', urlArchivoParaEnviar);
        if (caption) fd.append('caption', caption);
    }
    
    try {
        const r = await fetch('whatsapp.php', {method: 'POST', body: fd, cache: 'no-store'});
        const data = await r.json();
        
        if (data.ok === 1) {
            const tipoNombre = tipoArchivoParaEnviar === 'imagen' ? 'Imagen' : 
                              tipoArchivoParaEnviar === 'audio' ? 'Audio' : 'Video';
            toast(`${tipoNombre} enviado`, `El ${tipoNombre.toLowerCase()} se envió correctamente`);
            
            // Resetear variables
            archivoParaEnviar = null;
            tipoArchivoParaEnviar = '';
            urlArchivoParaEnviar = '';
            
            // Actualizar chat
            setTimeout(() => {
                actualizarMensajesChat();
                if (!hayFiltroActivo) actualizarListaContactos(false);
            }, 1000);
        } else {
            toast('Error', data.message || `No se pudo enviar el ${tipoArchivoParaEnviar}`);
        }
    } catch(e) {
        console.error(e);
        toast('Error de red', 'No se pudo conectar');
    }
}

function enviarDesdeURL() {
    const url = document.getElementById('urlInput').value.trim();
    if (!url) {
        toast('Atención', 'Ingresa una URL');
        return;
    }
    
    // Determinar tipo por extensión
    let tipo = 'imagen';
    const urlLower = url.toLowerCase();
    
    if (urlLower.match(/\.(mp3|wav|ogg|m4a|mp4)$/)) {
        tipo = 'audio';
    } else if (urlLower.match(/\.(mp4|avi|mov|wmv|webm|mkv)$/)) {
        tipo = 'video';
    }
    
    cerrarModalAdjuntar();
    
    // Preguntar si es imagen o video
    if (tipo === 'imagen' || tipo === 'video') {
        archivoParaEnviar = null;
        tipoArchivoParaEnviar = tipo;
        urlArchivoParaEnviar = url;
        abrirModalCaption(tipo);
    } else {
        // Para audio, enviar directamente
        enviarArchivoDesdeURLDirecto(url, tipo);
    }
}

async function enviarArchivoDesdeURLDirecto(url, tipo) {
    const endpoint = tipo === 'imagen' ? 'ajax_send_imagen' : 
                    tipo === 'audio' ? 'ajax_send_audio' : 
                    'ajax_send_video';
    
    const fd = new FormData();
    fd.append(endpoint, '1');
    fd.append('contacto_id', STATE.contactId);
    
    if (tipo === 'imagen') {
        fd.append('imagen_url', url);
    } else if (tipo === 'audio') {
        fd.append('audio_url', url);
    } else if (tipo === 'video') {
        fd.append('video_url', url);
    }
    
    try {
        const r = await fetch('whatsapp.php', {method: 'POST', body: fd, cache: 'no-store'});
        const data = await r.json();
        
        if (data.ok === 1) {
            const tipoNombre = tipo === 'imagen' ? 'Imagen' : 
                              tipo === 'audio' ? 'Audio' : 'Video';
            toast(`${tipoNombre} enviado`, `El ${tipoNombre.toLowerCase()} se envió correctamente`);
            
            setTimeout(() => {
                actualizarMensajesChat();
                if (!hayFiltroActivo) actualizarListaContactos(false);
            }, 1000);
        } else {
            toast('Error', data.message || `No se pudo enviar el ${tipo}`);
        }
    } catch(e) {
        console.error(e);
        toast('Error de red', 'No se pudo conectar');
    }
}

// ============================================
// FUNCIONES EXISTENTES
// ============================================

function abrirCine() {
    document.getElementById('cineOverlay').style.display = 'flex';
    document.getElementById('cineTelefono').value = '';
    document.getElementById('cineTextarea').value = '';
    document.getElementById('cineTelefono').focus();
}

function cerrarCine() {
    document.getElementById('cineOverlay').style.display = 'none';
}

function enviarDesdeCine() {
    const tel = document.getElementById('cineTelefono').value.trim();
    const txt = document.getElementById('cineTextarea').value.trim();
    if (!tel || !txt) { toast('Atención', 'Completá número y mensaje'); return; }

    const fd = new FormData(document.getElementById('formEnvioCine'));
    fd.set('mensaje', txt);
    fd.set('telefono_directo', tel);
    fd.append('ajax_send', '1');

    cerrarCine();

    fetch('whatsapp.php', { method: 'POST', body: fd, cache: 'no-store' })
        .then(r => r.json())
        .then(data => {
            if (!data || data.ok !== 1) toast('Error', (data && data.message) ? data.message : 'No se pudo enviar');
            else toast('Enviado', 'Mensaje enviado');

            if (!hayFiltroActivo) setTimeout(() => actualizarListaContactos(false), 900);
        })
        .catch(() => toast('Error', 'Error de red'));
}

function abrirImgModal(src) {
    document.getElementById('imgModalSrc').src = src;
    document.getElementById('imgOverlay').style.display = 'flex';
}
function cerrarImgModal() {
    document.getElementById('imgOverlay').style.display = 'none';
    document.getElementById('imgModalSrc').src = '';
}

function abrirPregrabados(target) {
    PREGRAB_TARGET = target || 'chat';
    document.getElementById('pregrabOverlay').style.display = 'flex';
    seleccionarCategoriaPregrab('STOCK');
}

function cerrarPregrabados() {
    document.getElementById('pregrabOverlay').style.display = 'none';
}

function seleccionarCategoriaPregrab(cat) {
    document.querySelectorAll('.wa-pregrab-tab').forEach(t => {
        t.classList.toggle('active', t.dataset.cat === cat);
    });
    document.querySelectorAll('.wa-pregrab-section').forEach(s => {
        s.style.display = (s.dataset.cat === cat) ? 'block' : 'none';
    });
}

function appendToTextarea(textarea, text) {
    if (!textarea) return;
    const cur = textarea.value || '';
    const add = (cur.trim() === '') ? text : (cur.replace(/\s*$/, '') + "\n\n" + text);
    textarea.value = add;

    textarea.focus();
    // auto-resize si es el textarea del chat
    if (textarea.id === 'mensajeTextarea') {
        textarea.style.height = 'auto';
        textarea.style.height = Math.min(textarea.scrollHeight, 140) + 'px';
    }
}

function usarPregrabadoDesdeCard(card) {
    const textEl = card.querySelector('.wa-pregrab-card-text');
    if (!textEl) return;
    const texto = (textEl.textContent || '').trim();
    cerrarPregrabados();

    if (!texto) return;

    if (PREGRAB_TARGET === 'cine') {
        appendToTextarea(document.getElementById('cineTextarea'), texto);
    } else {
        appendToTextarea(document.getElementById('mensajeTextarea'), texto);
    }
}
</script>
</body>
</html>