const { useState, useRef, useEffect } = React;

// Parseador de Markdown a HTML elegante
function formatMarkdown(text) {
    if (!text) return '';
    let html = text
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;");

    // Títulos y encabezados
    html = html.replace(/^### (.*$)/gim, '<h4 class="font-black text-sm text-indigo-950 mt-3 mb-1 uppercase tracking-wider">$1</h4>');
    html = html.replace(/^## (.*$)/gim, '<h3 class="font-black text-base text-indigo-950 mt-4 mb-2 uppercase tracking-wide">$1</h3>');
    html = html.replace(/^# (.*$)/gim, '<h2 class="font-black text-lg text-indigo-950 mt-4 mb-2">$1</h2>');

    // Negritas
    html = html.replace(/\*\*(.*?)\*\*/g, '<strong class="font-black text-slate-900">$1</strong>');
    
    // Cursiva
    html = html.replace(/\*(.*?)\*/g, '<em class="italic text-slate-600">$1</em>');

    // Viñetas con estilo
    html = html.replace(/^\s*[\-\*•]\s+(.*$)/gim, '<div class="flex items-start gap-2 my-1 text-slate-700"><span class="w-1.5 h-1.5 rounded-full bg-indigo-600 mt-1.5 flex-shrink-0"></span><span>$1</span></div>');

    // Saltos de línea
    html = html.replace(/\n\n/g, '<div class="h-2"></div>');

    return html;
}

window.AdminAICopilot = function({ companyName, currentTab = 'logs' }) {
    const [isOpen, setIsOpen] = useState(false);
    const [messages, setMessages] = useState([
        { 
            sender: 'ai', 
            text: `¡Hola! Soy **Shift Copilot AI**, tu analista de operaciones y recursos humanos para **${companyName || 'tu empresa'}**.\n\nHe sincronizado la base de datos de tu personal, horarios, contratos y bitácoras de asistencia. Selecciona un análisis rápido o hazme cualquier consulta operativa:` 
        }
    ]);
    const [inputPrompt, setInputPrompt] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const chatEndRef = useRef(null);

    useEffect(() => {
        if (isOpen && chatEndRef.current) {
            chatEndRef.current.scrollIntoView({ behavior: 'smooth' });
        }
    }, [messages, isOpen, isLoading]);

    // Lista vertical de 3 Prompts Sugeridos Inteligentes
    const smartPrompts = [
        {
            icon: "🍔",
            title: "Auditoría de Almuerzos (> 60 min)",
            desc: "Identifica qué colaboradores han excedido el tiempo de almuerzo en los últimos 5 días y totaliza el exceso.",
            query: "¿Quiénes han tenido pausas de almuerzo superiores a 60 minutos en los últimos 5 días? Detalla el nombre del colaborador, fecha y minutos de exceso de forma organizada."
        },
        {
            icon: "⏰",
            title: "Puntualidad y Tardanzas del Mes",
            desc: "Analiza el historial de llegadas tardías y ausencias de todo el personal en el mes actual.",
            query: "Realiza una auditoría completa de llegadas tardías y ausencias de todo el personal en lo que va del mes. Lista los colaboradores con incidencias y la cantidad de minutos acumulados."
        },
        {
            icon: "📄",
            title: "Auditoría de Expedientes e INSS",
            desc: "Revisa los contratos emitidos y detecta quiénes están pendientes de número de seguro social.",
            query: "¿Cuáles son los últimos contratos individuales emitidos y qué colaboradores activos aún no tienen registrado su número de seguro social (INSS)?"
        }
    ];

    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) {
                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. Revisa si configuraste tu Gemini API Key en Ajustes." }]);
            }
        } catch (err) {
            setMessages(prev => [...prev, { sender: 'ai', text: "Error de comunicación con el motor de IA: " + err.message }]);
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <React.Fragment>
            {/* BOTÓN FLOTANTE SHIFT AI */}
            <button 
                onClick={() => 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-300 flex items-center gap-3 border-2 border-white/30 group cursor-pointer"
                title="Abrir Shift Copilot AI"
            >
                <div className="w-8 h-8 rounded-2xl bg-white/20 flex items-center justify-center">
                    <svg className="w-5 h-5 text-white animate-pulse" fill="none" stroke="currentColor" strokeWidth="2.5" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z" />
                    </svg>
                </div>
                <div className="text-left hidden sm:block pr-1">
                    <p className="font-black text-[11px] uppercase tracking-wider leading-none">Shift AI</p>
                    <p className="text-[9px] text-indigo-200 font-bold uppercase tracking-widest mt-0.5">Copilot</p>
                </div>
            </button>

            {/* DRAWER / CHAT LATERAL */}
            {isOpen && (
                <div className="fixed inset-0 bg-slate-950/60 z-[140] flex justify-end backdrop-blur-xs fade-in" onClick={() => setIsOpen(false)}>
                    <div 
                        className="bg-white w-full max-w-xl h-full shadow-2xl flex flex-col justify-between border-l border-slate-200" 
                        onClick={e => e.stopPropagation()}
                    >
                        {/* Cabecera Elegante */}
                        <div className="p-6 border-b border-slate-100 flex items-center justify-between bg-gradient-to-r from-slate-900 via-indigo-950 to-slate-900 text-white shadow-sm">
                            <div className="flex items-center gap-3.5">
                                <div className="w-11 h-11 rounded-2xl bg-indigo-600 flex items-center justify-center text-white shadow-lg border border-indigo-400/30">
                                    <svg className="w-6 h-6" fill="none" stroke="currentColor" strokeWidth="2.5" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z" />
                                    </svg>
                                </div>
                                <div>
                                    <h3 className="font-black text-base text-white tracking-tight flex items-center gap-2">
                                        Shift Copilot AI
                                        <span className="px-2 py-0.5 bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 rounded-full text-[8px] font-black uppercase">Gemini 2.5</span>
                                    </h3>
                                    <p className="text-[10px] text-indigo-200 font-bold uppercase tracking-widest mt-0.5">
                                        {companyName || 'Empresa'} • Aislamiento Activo
                                    </p>
                                </div>
                            </div>
                            <button onClick={() => setIsOpen(false)} className="p-2.5 text-slate-400 hover:text-white rounded-full bg-white/10 transition-colors">
                                <svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"></path></svg>
                            </button>
                        </div>

                        {/* Área de Mensajes */}
                        <div className="flex-1 overflow-y-auto p-6 space-y-5 bg-slate-50">
                            {messages.map((m, idx) => (
                                <div key={idx} className={`flex ${m.sender === 'user' ? 'justify-end' : 'justify-start'}`}>
                                    <div className={`max-w-[88%] p-5 rounded-3xl text-xs leading-relaxed shadow-sm ${
                                        m.sender === 'user' 
                                            ? 'bg-indigo-600 text-white font-medium rounded-tr-none shadow-indigo-100' 
                                            : 'bg-white text-slate-800 border border-slate-200/80 rounded-tl-none font-sans space-y-1'
                                    }`}>
                                        {m.sender === 'ai' ? (
                                            <div dangerouslySetInnerHTML={{ __html: formatMarkdown(m.text) }} />
                                        ) : (
                                            <span>{m.text}</span>
                                        )}
                                    </div>
                                </div>
                            ))}

                            {isLoading && (
                                <div className="flex justify-start">
                                    <div className="bg-white p-4 rounded-3xl rounded-tl-none border border-slate-200/80 shadow-sm flex items-center gap-2.5">
                                        <div className="w-2.5 h-2.5 rounded-full bg-indigo-600 animate-bounce"></div>
                                        <div className="w-2.5 h-2.5 rounded-full bg-purple-600 animate-bounce [animation-delay:0.2s]"></div>
                                        <div className="w-2.5 h-2.5 rounded-full bg-emerald-600 animate-bounce [animation-delay:0.4s]"></div>
                                        <span className="text-[10px] font-black uppercase tracking-wider text-slate-500 ml-1">
                                            Consultando y analizando datos de {companyName || 'tu empresa'}...
                                        </span>
                                    </div>
                                </div>
                            )}

                            {/* Tarjetas de Prompts Verticales */}
                            {messages.length <= 2 && !isLoading && (
                                <div className="pt-2 space-y-2.5">
                                    <p className="text-[10px] font-black uppercase tracking-widest text-slate-400 px-1">
                                        Análisis Rápidos Sugeridos:
                                    </p>
                                    <div className="space-y-2">
                                        {smartPrompts.map((sp, i) => (
                                            <div 
                                                key={i}
                                                onClick={() => 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"
                                            >
                                                <div className="flex items-center gap-3">
                                                    <span className="text-xl">{sp.icon}</span>
                                                    <div className="flex-1 overflow-hidden">
                                                        <h4 className="font-black text-slate-900 text-xs group-hover:text-indigo-600 transition-colors">{sp.title}</h4>
                                                        <p className="text-[11px] text-slate-500 font-medium leading-snug mt-0.5">{sp.desc}</p>
                                                    </div>
                                                    <svg className="w-4 h-4 text-slate-400 group-hover:text-indigo-600 transition-colors flex-shrink-0" fill="none" stroke="currentColor" strokeWidth="2.5" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" /></svg>
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            )}

                            <div ref={chatEndRef}></div>
                        </div>

                        {/* Caja de Entrada */}
                        <form onSubmit={(e) => { e.preventDefault(); handleSendPrompt(); }} className="p-4 border-t border-slate-100 bg-white flex gap-2">
                            <input 
                                type="text"
                                value={inputPrompt}
                                onChange={e => 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}
                            />
                            <button 
                                type="submit"
                                disabled={isLoading || !inputPrompt.trim()}
                                className="px-5 bg-indigo-600 hover:bg-indigo-700 disabled:opacity-40 text-white rounded-2xl shadow-md active:scale-95 transition-all flex items-center justify-center cursor-pointer"
                            >
                                <svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth="2.5" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M14 5l7 7m0 0l-7 7m7-7H3" /></svg>
                            </button>
                        </form>
                    </div>
                </div>
            )}
        </React.Fragment>
    );
};