File size: 11,809 Bytes
949043b
2575c7e
f305300
 
 
 
 
 
 
949043b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f305300
 
 
949043b
 
 
 
 
 
 
 
 
 
 
 
f305300
 
949043b
f305300
949043b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f305300
 
949043b
f305300
949043b
f305300
 
 
949043b
f305300
949043b
f305300
 
949043b
f305300
 
949043b
f305300
 
949043b
 
 
 
f305300
 
949043b
f305300
949043b
f305300
949043b
f305300
 
 
949043b
 
 
f305300
949043b
 
 
 
 
 
 
 
 
 
 
 
f305300
 
 
 
 
949043b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f305300
 
 
949043b
 
 
 
 
 
 
 
 
 
 
 
f305300
 
949043b
 
 
 
 
 
 
 
f305300
949043b
 
 
 
 
 
 
 
 
f305300
 
 
949043b
 
f305300
 
949043b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f305300
 
949043b
f305300
 
 
 
 
 
 
 
949043b
f305300
 
949043b
 
 
 
 
 
 
f305300
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
import React, { useEffect, useMemo, useState } from 'react';

interface Message {
  id: string;
  role: 'user' | 'assistant' | 'error';
  content: string;
  avatar: string;
}

interface ApiMessage {
  role: 'user' | 'assistant';
  content: string;
}

interface Props {
  chatId: string | null;
  uid: string;
  onRefreshChats: () => Promise<void>;
  onEnsureChat: () => Promise<string>;
  onError: (error: string | null) => void;
}

interface ExamplePrompt {
  label: string;
  prompt: string;
}

const EXAMPLE_PROMPTS: ExamplePrompt[] = [
  {
    label: 'Definir audiencia 🎯',
    prompt: 'Ayúdame a definir una audiencia concreta para este correo: dolor principal, deseo y nivel de conciencia.',
  },
  {
    label: 'Propuesta de valor 💎',
    prompt: 'Convierte mi producto en una promesa clara de transformación sin listar características aburridas.',
  },
  {
    label: 'CTA que convierte 🚀',
    prompt: 'Dame 3 opciones de CTA claras para este email, con baja fricción y orientadas a una sola acción.',
  },
  {
    label: 'Asunto + gancho ✉️',
    prompt: 'Propón 5 asuntos y 3 ganchos de apertura para aumentar aperturas y clics de este correo.',
  },
];

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

const escapeHtml = (text: string) =>
  text
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;');

const inlineMarkdown = (text: string) => {
  let html = escapeHtml(text);
  html = html.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
  html = html.replace(/\*(.+?)\*/g, '<em>$1</em>');
  return html;
};

const markdownToHtml = (raw: string) => {
  const lines = raw.split('\n');
  const output: string[] = [];
  let inUl = false;
  let inOl = false;

  const closeLists = () => {
    if (inUl) {
      output.push('</ul>');
      inUl = false;
    }
    if (inOl) {
      output.push('</ol>');
      inOl = false;
    }
  };

  lines.forEach((line) => {
    const trimmed = line.trim();

    if (!trimmed) {
      closeLists();
      output.push('<br />');
      return;
    }

    if (trimmed.startsWith('### ')) {
      closeLists();
      output.push(`<h3>${inlineMarkdown(trimmed.slice(4))}</h3>`);
      return;
    }

    if (trimmed.startsWith('## ')) {
      closeLists();
      output.push(`<h2>${inlineMarkdown(trimmed.slice(3))}</h2>`);
      return;
    }

    if (trimmed.startsWith('# ')) {
      closeLists();
      output.push(`<h1>${inlineMarkdown(trimmed.slice(2))}</h1>`);
      return;
    }

    const ordered = trimmed.match(/^(\d+)\.\s+(.*)$/);
    if (ordered) {
      if (inUl) {
        output.push('</ul>');
        inUl = false;
      }
      if (!inOl) {
        output.push('<ol>');
        inOl = true;
      }
      output.push(`<li>${inlineMarkdown(ordered[2])}</li>`);
      return;
    }

    const bullet = trimmed.match(/^[-*]\s+(.*)$/);
    if (bullet) {
      if (inOl) {
        output.push('</ol>');
        inOl = false;
      }
      if (!inUl) {
        output.push('<ul>');
        inUl = true;
      }
      output.push(`<li>${inlineMarkdown(bullet[1])}</li>`);
      return;
    }

    closeLists();
    output.push(`<p>${inlineMarkdown(trimmed)}</p>`);
  });

  closeLists();
  return output.join('');
};

const withUidPath = (path: string, uid: string) =>
  `${path}${path.includes('?') ? '&' : '?'}uid=${encodeURIComponent(uid)}`;

function toUiMessage(msg: ApiMessage, idx: number): Message {
  return {
    id: `${msg.role}-${idx}-${Date.now()}`,
    role: msg.role,
    content: msg.content,
    avatar: msg.role === 'user' ? '👤' : '🤖',
  };
}

function ChatWindow({ chatId, uid, onRefreshChats, onEnsureChat, onError }: Props) {
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  const [feedbackByMessage, setFeedbackByMessage] = useState<Record<string, 'up' | 'down'>>({});
  const [chatError, setChatError] = useState<string | null>(null);

  const loadMessages = async (targetChatId: string) => {
    const response = await fetch(withUidPath(`/api/chats/${targetChatId}/messages`, uid));
    if (!response.ok) {
      throw new Error('No se pudo cargar el historial');
    }

    const data: ApiMessage[] = await response.json();
    setMessages(data.map((msg, idx) => toUiMessage(msg, idx)));
  };

  useEffect(() => {
    if (!chatId || loading) return;

    loadMessages(chatId).catch((error) => {
      const message = error instanceof Error ? error.message : 'No se pudo cargar el historial';
      setChatError(message);
      onError(message);
    });
  }, [chatId, loading, onError]);

  const animateAssistantText = async (messageId: string, fullText: string) => {
    let partial = '';
    for (const char of fullText) {
      partial += char;
      setMessages((prev) =>
        prev.map((msg) =>
          msg.id === messageId
            ? {
                ...msg,
                content: partial,
              }
            : msg,
        ),
      );
      await sleep(8);
    }
  };

  const sendToCurrentChat = async (content: string, isExample = false) => {
    const activeChatId = await onEnsureChat();

    const userMessage: Message = {
      id: `${Date.now()}-user`,
      role: 'user',
      content,
      avatar: '👤',
    };

    setMessages((prev) => [...prev, userMessage]);
    setLoading(true);
    setChatError(null);

    try {
      const response = await fetch(withUidPath(`/api/chats/${activeChatId}/messages`, uid), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ content, is_example: isExample }),
      });

      if (!response.ok) {
        const payload = await response.json().catch(() => ({}));
        throw new Error(payload.detail || 'Error enviando mensaje');
      }

      const data = await response.json();
      const assistantId = `${Date.now()}-assistant`;
      const assistantMessage: Message = {
        id: assistantId,
        role: 'assistant',
        content: '',
        avatar: '🤖',
      };

      setMessages((prev) => [...prev, assistantMessage]);
      await animateAssistantText(assistantId, data.response ?? '');
      await onRefreshChats();
    } catch (error) {
      const msg = error instanceof Error ? error.message : 'Error enviando mensaje';
      setChatError(msg);
      onError(msg);
      setMessages((prev) => [
        ...prev,
        {
          id: `${Date.now()}-error`,
          role: 'error',
          content: msg,
          avatar: '⚠️',
        },
      ]);
    } finally {
      setLoading(false);
    }
  };

  const hasInput = input.trim().length > 0;

  const handleSendMessage = async () => {
    if (!input.trim() || loading) return;
    const content = input;
    setInput('');
    await sendToCurrentChat(content, false);
  };

  const dismissChatError = () => {
    setChatError(null);
    onError(null);
  };

  const assistantHtmlById = useMemo(() => {
    const map = new Map<string, string>();
    messages.forEach((message) => {
      if (message.role === 'assistant') {
        map.set(message.id, markdownToHtml(message.content));
      }
    });
    return map;
  }, [messages]);

  const handleCopy = async (messageId: string, text: string) => {
    try {
      await navigator.clipboard.writeText(text);
      setFeedbackByMessage((prev) => ({ ...prev, [messageId]: prev[messageId] || 'up' }));
    } catch (error) {
      console.error('No se pudo copiar:', error);
    }
  };

  const handleFeedback = (messageId: string, type: 'up' | 'down') => {
    setFeedbackByMessage((prev) => {
      const current = prev[messageId];
      if (current === type) {
        const next = { ...prev };
        delete next[messageId];
        return next;
      }
      return { ...prev, [messageId]: type };
    });
  };

  return (
    <div className="chat-window">
      <div className="messages">
        {chatError && (
          <div className="chat-error-banner" role="alert">
            <strong>Error:</strong> {chatError}
            <button
              className="chat-error-close"
              onClick={dismissChatError}
              aria-label="Cerrar error del chat"
            >
              ×
            </button>
          </div>
        )}
        {messages.length === 0 && (
          <div className="initial-menu">
            <img
              className="brand-remote-logo"
              src="https://huggingface.co/spaces/JeCabrera/chatbot_mail/resolve/main/robocopy_logo.png"
              alt="RoboCopy"
            />
            <h1 className="robocopy-title">Email Story Creator</h1>
            <span className="brand-author subtitle">By Jesús Cabrera</span>
            <p>✉️ Experto en emails narrativos que conectan historias con ventas de forma natural</p>
            <div className="example-buttons">
              {EXAMPLE_PROMPTS.map((example) => (
                <button
                  key={example.label}
                  className="example-btn"
                  onClick={() => sendToCurrentChat(example.prompt, true)}
                >
                  {example.label}
                </button>
              ))}
            </div>
          </div>
        )}

        {messages.map((msg) => (
          <div key={msg.id} className={`message ${msg.role}`}>
            <span className="avatar">{msg.avatar}</span>
            <div className="content">
              {msg.role === 'assistant' ? (
                <>
                  <div
                    className="assistant-markdown"
                    dangerouslySetInnerHTML={{ __html: assistantHtmlById.get(msg.id) || '' }}
                  />
                  <div className="assistant-actions">
                    <button
                      className="action-btn"
                      onClick={() => handleCopy(msg.id, msg.content)}
                      aria-label="Copiar respuesta"
                      title="Copiar"
                    >

                    </button>
                    <button
                      className={`action-btn ${feedbackByMessage[msg.id] === 'up' ? 'active' : ''}`}
                      onClick={() => handleFeedback(msg.id, 'up')}
                      aria-label="Respuesta útil"
                      title="Bien"
                    >
                      👍
                    </button>
                    <button
                      className={`action-btn ${feedbackByMessage[msg.id] === 'down' ? 'active' : ''}`}
                      onClick={() => handleFeedback(msg.id, 'down')}
                      aria-label="Respuesta no útil"
                      title="Mal"
                    >
                      👎
                    </button>
                  </div>
                </>
              ) : (
                <div className={msg.role === 'error' ? 'error-plain' : 'user-plain'}>{msg.content}</div>
              )}
            </div>
          </div>
        ))}

        {loading && <div className="message loading">🤖 Escribiendo...</div>}
      </div>

      <div className="input-area">
        <input
          type="text"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={(e) => e.key === 'Enter' && handleSendMessage()}
          placeholder="Escribe aquí tus instrucciones"
        />
        {hasInput && <span className="input-ready" aria-hidden="true"></span>}
        <button
          className={`send-btn ${hasInput ? 'active' : ''}`}
          onClick={handleSendMessage}
          aria-label="Enviar mensaje"
        >

        </button>
      </div>
    </div>
  );
}

export default ChatWindow;