File size: 12,598 Bytes
2accaeb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Sidebar } from './components/Sidebar';
import { ChatView } from './components/ChatView';
import type { ChatSession, ChatMessage, UploadedFile } from './types';
import { geminiService } from './services/geminiService';
import { NEW_CHAT_ID, REEL_BOT_SYSTEM_INSTRUCTION } from './constants';
import type { Chat } from '@google/genai';
import { MenuIcon } from './components/icons';

const App: React.FC = () => {
  const [chats, setChats] = useState<Map<string, ChatSession>>(new Map());
  const [activeChatId, setActiveChatId] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);

  const transientGeminiChatsRef = useRef<Map<string, Chat>>(new Map());
  const isCancelledRef = useRef(false);

  useEffect(() => {
    const storedChats = localStorage.getItem('reelCreatorChats');
    if (storedChats) {
      try {
        const parsedChatsArray: [string, ChatSession][] = JSON.parse(storedChats);
        parsedChatsArray.forEach(([, chat]) => {
          if (!chat.messages) {
            chat.messages = [];
          }
          chat.messages.forEach(msg => {
            if (msg.file && !msg.file.dataUrl && !msg.file.type.startsWith('image/')) {
              // Potentially handle old document structures
            }
          });
        });
        setChats(new Map(parsedChatsArray));
        if (parsedChatsArray.length > 0) {
           // setActiveChatId(parsedChatsArray[0][0]); // Keep previous logic or decide default
        } else {
           setActiveChatId(NEW_CHAT_ID);
        }
      } catch (e) {
        console.error("Failed to parse chats from localStorage", e);
        localStorage.removeItem('reelCreatorChats'); 
        setActiveChatId(NEW_CHAT_ID);
      }
    } else {
        setActiveChatId(NEW_CHAT_ID);
    }
  }, []);

  useEffect(() => {
    if (chats.size > 0 || localStorage.getItem('reelCreatorChats')) { 
        const storableChatsArray = Array.from(chats.entries()).map(([id, session]) => {
            const storableMessages = session.messages.map(msg => {
                if (msg.file) {
                    const { /* rawFile, */ ...fileToStore } = msg.file; // rawFile removed from example
                    return { ...msg, file: fileToStore };
                }
                return msg;
            });
            return [id, { ...session, messages: storableMessages }];
        });
        localStorage.setItem('reelCreatorChats', JSON.stringify(storableChatsArray));
    }
  }, [chats]);
  
  const getOrCreateGeminiChatInstance = useCallback(async (chatId: string): Promise<Chat> => {
    if (transientGeminiChatsRef.current.has(chatId)) {
      return transientGeminiChatsRef.current.get(chatId)!;
    }
    const chatSession = chats.get(chatId);
    const history = chatSession 
      ? chatSession.messages
          .filter(m => !m.error) 
          .map(m => {
            let messageText = m.text;
            if (m.file) {
                // Keeping simplified logic for history
                 messageText = `${m.text} (User had attached ${m.file.type.startsWith('image/') ? 'image' : 'document'}: ${m.file.name})`;
            }
             return { 
              role: m.sender === 'user' ? 'user' : 'model', 
              parts: [{text: messageText}]
            }
          }) 
      : [];
    
    const newInstance = await geminiService.createChatSessionWithHistory(REEL_BOT_SYSTEM_INSTRUCTION, history);
    transientGeminiChatsRef.current.set(chatId, newInstance);
    return newInstance;
  }, [chats]);

  const handleStopGeneration = useCallback(() => {
    isCancelledRef.current = true;
  }, []);

  const handleSendMessage = useCallback(async (userInput: string, file?: UploadedFile, isSuggestion: boolean = false) => {
    if (!userInput.trim() && !file) return;
    
    isCancelledRef.current = false; 
    setIsLoading(true);
    setError(null);

    let currentChatId = activeChatId;
    let currentChatSession: ChatSession | undefined;

    const userMessage: ChatMessage = {
      id: Date.now().toString(),
      text: userInput,
      sender: 'user',
      timestamp: Date.now(),
      file: file ? { name: file.name, type: file.type, size: file.size, dataUrl: file.dataUrl } : undefined,
    };

    if (currentChatId === NEW_CHAT_ID || !currentChatId || !chats.has(currentChatId)) {
      const newChatId = Date.now().toString();
      let chatName = "Nuevo Chat";
      const trimmedInput = userInput.trim();

      if (trimmedInput) {
        const words = trimmedInput.split(' ');
        chatName = words.slice(0, 5).join(' ');
        if (chatName.length > 30) {
          chatName = chatName.substring(0, 27) + "...";
        }
      } else if (file) {
        chatName = `Chat con ${file.name}`;
        if (chatName.length > 30) {
          chatName = chatName.substring(0, 27) + "...";
        }
      } else {
        chatName = `Nuevo Chat ${new Date().toLocaleTimeString()}`;
      }
      
      currentChatSession = {
        id: newChatId,
        name: chatName,
        messages: [userMessage],
        createdAt: Date.now(),
      };
      setChats(prev => new Map(prev).set(newChatId, currentChatSession!));
      setActiveChatId(newChatId);
      currentChatId = newChatId;
    } else {
      currentChatSession = chats.get(currentChatId);
      if (currentChatSession) {
        const updatedMessages = [...currentChatSession.messages, userMessage];
        setChats(prev => new Map(prev).set(currentChatId!, { ...currentChatSession!, messages: updatedMessages }));
      }
    }
    
    if (!currentChatSession || !currentChatId) {
        setError("Failed to create or find chat session.");
        setIsLoading(false);
        return;
    }

    const modelMessageId = Date.now().toString() + '_model';
    const initialModelMessage: ChatMessage = {
      id: modelMessageId,
      text: '',
      sender: 'model',
      timestamp: Date.now(),
      isStreaming: true,
    };

    setChats(prev => {
        const updatedChats = new Map(prev);
        const chat = updatedChats.get(currentChatId!);
        if (chat) {
            const updatedMessages = [...chat.messages, initialModelMessage];
            updatedChats.set(currentChatId!, { ...chat, messages: updatedMessages });
        }
        return updatedChats;
    });
    
    let accumulatedText = "";
    let groundingChunks: ChatMessage['groundingChunks'] = [];
    try {
      const geminiChat = await getOrCreateGeminiChatInstance(currentChatId);
      const imageFileToSend = (file?.type.startsWith('image/') && file.dataUrl) ? file : undefined;

      const stream = await geminiService.sendMessageStream(geminiChat, userInput, imageFileToSend);
      for await (const chunk of stream) {
        if (isCancelledRef.current) {
          console.log("Generation stopped by user.");
          break; 
        }
        accumulatedText += chunk.text;
        if (chunk.groundingChunks && chunk.groundingChunks.length > 0) {
          groundingChunks = [...(groundingChunks || []), ...chunk.groundingChunks];
        }
        
        setChats(prev => {
            const updatedChats = new Map(prev);
            const chat = updatedChats.get(currentChatId!);
            if (chat) {
                const msgIndex = chat.messages.findIndex(m => m.id === modelMessageId);
                if (msgIndex !== -1) {
                    const newMessages = [...chat.messages];
                    newMessages[msgIndex] = {
                        ...newMessages[msgIndex],
                        text: accumulatedText,
                        groundingChunks: groundingChunks.length > 0 ? groundingChunks : undefined,
                        isStreaming: true 
                    };
                    updatedChats.set(currentChatId!, { ...chat, messages: newMessages });
                }
            }
            return updatedChats;
        });
      }
      
       setChats(prev => {
            const updatedChats = new Map(prev);
            const chat = updatedChats.get(currentChatId!);
            if (chat) {
                const msgIndex = chat.messages.findIndex(m => m.id === modelMessageId);
                if (msgIndex !== -1) {
                    const newMessages = [...chat.messages];
                    newMessages[msgIndex] = {
                        ...newMessages[msgIndex],
                        text: accumulatedText, 
                        isStreaming: false, 
                        groundingChunks: groundingChunks.length > 0 ? groundingChunks : undefined
                    };
                    updatedChats.set(currentChatId!, { ...chat, messages: newMessages });
                }
            }
            return updatedChats;
        });

    } catch (e: any) {
      console.error("Error sending message to Gemini:", e);
      const errorMessage = e.message || "An error occurred with the AI service.";
      setError(errorMessage); 
      setChats(prev => {
            const updatedChats = new Map(prev);
            const chat = updatedChats.get(currentChatId!);
            if (chat) {
                const msgIndex = chat.messages.findIndex(m => m.id === modelMessageId);
                if (msgIndex !== -1) {
                    const newMessages = [...chat.messages];
                    newMessages[msgIndex] = {
                        ...newMessages[msgIndex],
                        text: accumulatedText || `Error: ${errorMessage}`,
                        isStreaming: false,
                        error: errorMessage
                    };
                    updatedChats.set(currentChatId!, { ...chat, messages: newMessages });
                } else { 
                    const errorMsgEntry: ChatMessage = {
                         id: modelMessageId, 
                         text: `Error: ${errorMessage}`,
                         sender: 'model',
                         timestamp: Date.now(),
                         isStreaming: false,
                         error: errorMessage
                    };
                    const newMessages = [...chat.messages, errorMsgEntry];
                    updatedChats.set(currentChatId!, { ...chat, messages: newMessages });
                }
            }
            return updatedChats;
        });
    } finally {
      setIsLoading(false);
    }
  }, [activeChatId, chats, getOrCreateGeminiChatInstance]);

  const handleSelectChat = useCallback((chatId: string | null) => {
    setActiveChatId(chatId);
    setIsSidebarOpen(false); // Close sidebar on chat selection (mobile)
    if (chatId && chatId !== NEW_CHAT_ID && chats.has(chatId)) {
        getOrCreateGeminiChatInstance(chatId);
    }
  }, [chats, getOrCreateGeminiChatInstance]);

  const handleCreateNewChat = useCallback(() => {
    setActiveChatId(NEW_CHAT_ID);
    setIsSidebarOpen(false); // Close sidebar on new chat (mobile)
  }, []);
  
  const activeChatSession = activeChatId === NEW_CHAT_ID || !activeChatId ? null : chats.get(activeChatId) || null;

  return (
    <div className="flex h-screen bg-slate-900 text-slate-100 overflow-hidden md:overflow-auto">
      <Sidebar
        chats={Array.from(chats.values())}
        activeChatId={activeChatId}
        onSelectChat={handleSelectChat}
        onCreateNewChat={handleCreateNewChat}
        isOpen={isSidebarOpen}
        onClose={() => setIsSidebarOpen(false)}
      />

      {isSidebarOpen && (
        <div
          onClick={() => setIsSidebarOpen(false)}
          className="fixed inset-0 z-30 bg-black/60 md:hidden"
          aria-hidden="true"
        />
      )}

      <div className="flex-1 flex flex-col h-full">
        <div className="p-3 border-b border-slate-700 md:hidden flex items-center justify-start bg-slate-900 sticky top-0 z-20">
          <button
            onClick={() => setIsSidebarOpen(true)}
            className="text-slate-300 hover:text-slate-100 p-2 rounded-md focus:outline-none focus:ring-2 focus:ring-cyan-500"
            aria-label="Open menu"
          >
            <MenuIcon className="w-6 h-6" />
          </button>
          {/* Title text and spacer div removed here */}
        </div>

        <ChatView
          activeChatSession={activeChatSession}
          onSendMessage={handleSendMessage}
          isLoading={isLoading}
          error={error}
          onStopGeneration={handleStopGeneration} 
        />
      </div>
    </div>
  );
};

export default App;