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 += `${c.trim()} `; });
tableHtml += ' ';
} else {
tableHtml += '';
cells.forEach(c => { tableHtml += `${c.trim()} `; });
tableHtml += ' ';
}
} else {
if (inTable) {
inTable = false;
tableHtml += '
';
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 */}
setIsOpen(true)}
className="fixed bottom-6 right-6 z-[100] p-4 bg-gradient-to-r from-indigo-600 via-indigo-700 to-purple-700 hover:scale-105 active:scale-95 text-white rounded-3xl shadow-2xl transition-all duration-200 flex items-center gap-3 border-2 border-white/30 group cursor-pointer"
title="Abrir Shift Copilot AI"
>
{/* CHAT LATERAL FLUIDO */}
{isOpen && (
setIsOpen(false)}>
e.stopPropagation()}
>
{/* Cabecera */}
Shift Copilot AI
{keySourceUsed === 'dedicada' ? 'Clave Dedicada' : 'Cuota Maestra Shift'}
{companyName || 'Empresa'} • Aislamiento Activo
setIsOpen(false)} className="p-2.5 text-slate-400 hover:text-white rounded-full bg-white/10 transition-colors">
{/* 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"
>
))}
)}
)}
{/* Caja de Entrada */}
)}
);
};