const { useState, useRef, useEffect } = React; function formatMarkdown(text) { if (!text) return ''; let html = text .replace(/&/g, "&") .replace(//g, ">"); // Limpieza y estilizado de líneas divisorias '---' html = html.replace(/^---$/gim, '
'); // Encabezados con estilos ejecutivos html = html.replace(/^### (.*$)/gim, '

$1

'); html = html.replace(/^## (.*$)/gim, '

$1

'); html = html.replace(/^# (.*$)/gim, '

$1

'); // Negritas y Cursivas html = html.replace(/\*\*(.*?)\*\*/g, '$1'); html = html.replace(/\*(.*?)\*/g, '$1'); // Formato de encabezados formales (Para:, De:, Fecha:, Asunto:) html = html.replace(/\b(Para|De|Fecha|Asunto):\s*(.*$)/gim, '
$1$2
'); // Tablas Markdown pulidas if (html.includes('|')) { const lines = html.split('\n'); let inTable = false; let tableHtml = '
'; let newLines = []; lines.forEach(line => { const trimmed = line.trim(); if (trimmed.startsWith('|') && trimmed.endsWith('|')) { const cells = trimmed.split('|').filter((_, i, arr) => i > 0 && i < arr.length - 1); if (trimmed.includes('---')) return; // Saltar separador if (!inTable) { inTable = true; tableHtml += ''; cells.forEach(c => { tableHtml += ``; }); tableHtml += ''; } else { tableHtml += ''; cells.forEach(c => { tableHtml += ``; }); tableHtml += ''; } } else { if (inTable) { inTable = false; tableHtml += '
${c.trim()}
${c.trim()}
'; newLines.push(tableHtml); tableHtml = '
'; } newLines.push(line); } }); if (inTable) { tableHtml += '
'; newLines.push(tableHtml); } html = newLines.join('\n'); } // Viñetas suaves html = html.replace(/^\s*[\-\*•]\s+(.*$)/gim, '
$1
'); // Saltos de párrafo limpios html = html.replace(/\n\n/g, '
'); return html; } window.AdminAICopilot = function({ companyName, currentTab = 'logs' }) { const [isOpen, setIsOpen] = useState(false); const [keySourceUsed, setKeySourceUsed] = useState('maestra'); const [dynamicPrompts, setDynamicPrompts] = useState([]); const [loadingPrompts, setLoadingPrompts] = useState(false); const [messages, setMessages] = useState([ { sender: 'ai', text: `¡Hola! Soy **Shift Copilot AI**, tu asesor ejecutivo de operaciones y recursos humanos para **${companyName || 'tu empresa'}**.\n\nHe sincronizado tus registros de asistencia, horarios y contratos. Selecciona una de las alertas sugeridas para tu negocio o escribe tu consulta:` } ]); const [inputPrompt, setInputPrompt] = useState(''); const [isLoading, setIsLoading] = useState(false); const chatEndRef = useRef(null); // Precargar prompts dinámicos const loadSmartPrompts = async () => { if (dynamicPrompts.length > 0) return; setLoadingPrompts(true); try { const res = await window.apiCall('get_ai_smart_prompts', {}); if (res && res.success && res.prompts) { setDynamicPrompts(res.prompts); } } catch (e) {} finally { setLoadingPrompts(false); } }; useEffect(() => { if (isOpen) { loadSmartPrompts(); } }, [isOpen]); useEffect(() => { if (isOpen && chatEndRef.current) { chatEndRef.current.scrollIntoView({ behavior: 'smooth' }); } }, [messages, isOpen, isLoading]); const handleSendPrompt = async (promptToSend = null) => { const textQuery = promptToSend || inputPrompt; if (!textQuery.trim() || isLoading) return; const userMsg = { sender: 'user', text: textQuery }; setMessages(prev => [...prev, userMsg]); setInputPrompt(''); setIsLoading(true); try { const res = await window.apiCall('ask_ai_copilot', { prompt: textQuery, currentTab: currentTab }); if (res && res.success && res.response) { if (res.key_source) setKeySourceUsed(res.key_source); setMessages(prev => [...prev, { sender: 'ai', text: res.response }]); } else { setMessages(prev => [...prev, { sender: 'ai', text: res?.error || "No se pudo procesar la consulta en este momento." }]); } } catch (err) { setMessages(prev => [...prev, { sender: 'ai', text: "Error de comunicación con el motor de IA: " + err.message }]); } finally { setIsLoading(false); } }; return ( {/* BOTÓN FLOTANTE */} {/* CHAT LATERAL FLUIDO */} {isOpen && (
setIsOpen(false)}>
e.stopPropagation()} > {/* Cabecera */}

Shift Copilot AI {keySourceUsed === 'dedicada' ? 'Clave Dedicada' : 'Cuota Maestra Shift'}

{companyName || 'Empresa'} • Aislamiento Activo

{/* Conversación */}
{messages.map((m, idx) => (
{m.sender === 'ai' ? (
) : ( {m.text} )}
))} {isLoading && (
Analizando expedientes y asistencias de {companyName || 'tu empresa'}...
)} {/* Prompts Sugeridos Interactivos */} {messages.length <= 2 && !isLoading && (

Análisis y Acciones Sugeridas para tu Negocio:

{loadingPrompts ? (
Escaneando registros operativos...
) : (
{dynamicPrompts.map((sp, i) => (
handleSendPrompt(sp.query)} className="p-4 bg-white hover:bg-indigo-50/70 border border-slate-200/90 hover:border-indigo-300 rounded-2xl cursor-pointer transition-all duration-200 shadow-sm group" >

{sp.title}

{sp.desc}

))}
)}
)}
{/* Caja de Entrada */}
{ e.preventDefault(); handleSendPrompt(); }} className="p-4 border-t border-slate-100 bg-white flex gap-2"> setInputPrompt(e.target.value)} placeholder="Escribe tu consulta operativa sobre personal, tardanzas o contratos..." className="flex-1 p-4 bg-slate-50 border rounded-2xl text-xs font-bold outline-none focus:border-indigo-600 transition-colors" disabled={isLoading} />
)} ); };