File size: 8,908 Bytes
85f4d1b
39ff7ae
85f4d1b
 
 
 
 
39ff7ae
85f4d1b
 
 
 
39ff7ae
85f4d1b
 
 
39ff7ae
85f4d1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39ff7ae
85f4d1b
 
 
 
 
39ff7ae
85f4d1b
 
39ff7ae
85f4d1b
 
39ff7ae
85f4d1b
 
 
 
39ff7ae
85f4d1b
 
39ff7ae
85f4d1b
 
 
39ff7ae
85f4d1b
 
39ff7ae
85f4d1b
39ff7ae
85f4d1b
39ff7ae
85f4d1b
 
 
39ff7ae
85f4d1b
 
 
39ff7ae
85f4d1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39ff7ae
85f4d1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39ff7ae
85f4d1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c840d73
 
85f4d1b
 
 
 
 
 
 
 
 
 
 
 
39ff7ae
85f4d1b
 
 
39ff7ae
85f4d1b
39ff7ae
85f4d1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
document.addEventListener("DOMContentLoaded", () => {
    // === 1. CATCHING DOM ELEMENTS ===
    const sendButton = document.getElementById("send-button");
    const chatInput = document.getElementById("chat-input");
    const historyList = document.getElementById("history-list");
    const chatLog = document.getElementById("chat-log-area");
    const newChatButton = document.querySelector(".new-chat-btn");
    const clearAllButton = document.querySelector(".clear-all"); 

    const emptyChatPlaceholder = `
        <div class="empty-chat-placeholder">
            <i class="fa-solid fa-robot"></i>
            <h2>Hello! I am your Enviro-Edu Assistant. How may I assist you today?</h2>
        </div>
    `;

    // === 2. APPLICATION MAIN DATA (STATE) ===
    let conversations = {};
    let currentConversationId = null;
    let currentUserId = getOrCreateUserId();

    // === 3. EVENT LISTENERS ===
    newChatButton.addEventListener("click", (e) => {
        e.preventDefault();
        startNewChat();
    });
    sendButton.addEventListener("click", sendMessage);
    chatInput.addEventListener("keydown", (event) => {
        if (event.key === "Enter" && !event.shiftKey) {
            event.preventDefault();
            sendMessage();
        }
    });
    historyList.addEventListener("click", (e) => {
        const clickedLi = e.target.closest("li");
        if (clickedLi) {
            const id = clickedLi.dataset.id;
            switchConversation(id);
        }
    });
    
    // <-- NEW LISTENER FOR “CLEAR ALL” ---
    clearAllButton.addEventListener("click", (e) => {
        e.preventDefault();
        clearAllConversations();
    });

    // === 4. MAIN FUNCTIONS ===

    /**
     * NEW FEATURE: Delete all conversations
     */
    async function clearAllConversations() {
        if (!confirm("Are you sure you want to delete all conversations? This action cannot be undone.")) {
            return;
        }

        try {
            const response = await fetch("http://localhost:5000/api/conversations", {
                method: "DELETE",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ userId: currentUserId }) // Send userID to be deleted
            });

            if (!response.ok) {
                throw new Error("Failed to delete history on the server.");
            }
            
            // If the server is successful, clear the frontend state
            conversations = {};
            startNewChat(); // This will clear the UI (render history & chat log).
            
            console.log("All conversations have been successfully deleted.");

        } catch (error) {
            console.error("Error clearing conversations:", error);
            alert("An error occurred while deleting history.");
        }
    }
    
    // ... (The functions getOrCreateUserId, startNewChat, sendMessage, etc. remain exactly the same) ...
    
    function getOrCreateUserId() {
        let userId = localStorage.getItem('anonymousUserId');
        if (!userId) {
            userId = 'anon-' + Date.now() + '-' + Math.floor(Math.random() * 1000);
            localStorage.setItem('anonymousUserId', userId);
        }
        return userId;
    }

    function startNewChat() {
        currentConversationId = null;
        chatInput.value = "";
        renderChatLog();
        renderHistory();
    }

    async function sendMessage() {
        const messageText = chatInput.value.trim();
        if (messageText === "") return;

        let conversationIdToSend = currentConversationId; 
        let tempId = null;
        let activeConversation;

        if (currentConversationId === null) {
            const title = messageText.length > 28 ? messageText.substring(0, 28) + "..." : messageText;
            tempId = "temp-" + Date.now();
            activeConversation = {
                id: tempId,
                title: title,
                messages: []
            };
            conversations[tempId] = activeConversation;
            currentConversationId = tempId;
        } else {
            activeConversation = conversations[currentConversationId];
        }

        activeConversation.messages.push({ role: "user", content: messageText });
        renderChatLog();
        renderHistory();
        chatInput.value = "";
        
        const loadingDiv = addMessageToLog("assistant", "...");
        chatLog.scrollTop = chatLog.scrollHeight;
        
        try {
            const response = await fetch("http://localhost:5000/api/chat", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                    message: messageText,
                    userId: currentUserId,
                    conversationId: conversationIdToSend
                })
            });

            if (!response.ok) throw new Error("Network response was not ok.");
            const data = await response.json();
            if (data.error) throw new Error(data.error);

            const botText = data.answer;
            const realConversationId = data.conversationId;

            activeConversation.messages.push({ role: "assistant", content: botText });
            const p = loadingDiv.querySelector(".message-content p");
            p.textContent = botText;

            if (currentConversationId === tempId) {
                activeConversation.id = realConversationId;
                conversations[realConversationId] = activeConversation;
                delete conversations[tempId];
                currentConversationId = realConversationId;
                renderHistory();
            }
            
        } catch (error) {
            console.error("Error sending message:", error);
            const p = loadingDiv.querySelector(".message-content p");
            p.textContent = "Sorry, an error occurred. Please try again.";
        }
        
        chatLog.scrollTop = chatLog.scrollHeight;
    }

    function switchConversation(id) {
        if (currentConversationId === id) return; 
        currentConversationId = id;
        renderChatLog();
        renderHistory();
    }
    
    function renderHistory() {
        historyList.innerHTML = "";
        
        const sortedConversations = Object.values(conversations).sort((a, b) => {
             const lastMsgA = a.messages[a.messages.length - 1]?.timestamp || a.id;
             const lastMsgB = b.messages[b.messages.length - 1]?.timestamp || b.id;
             return new Date(lastMsgB) - new Date(lastMsgA);
        });

        sortedConversations.forEach(convo => {
            const li = document.createElement("li");
            li.dataset.id = convo.id;
            li.innerHTML = `<i class="fa-regular fa-comment-dots"></i> ${convo.title}`;
            if (convo.id === currentConversationId) {
                li.classList.add("active");
            }
            historyList.appendChild(li);
        });
    }

    function renderChatLog() {
        if (currentConversationId === null) {
            chatLog.innerHTML = emptyChatPlaceholder;
            return;
        }

        const activeConversation = conversations[currentConversationId];
        if (!activeConversation) {
            startNewChat();
            return;
        }

        chatLog.innerHTML = "";
        activeConversation.messages.forEach(message => {
            addMessageToLog(message.role, message.content); 
        });
        chatLog.scrollTop = chatLog.scrollHeight;
    }
    
    function addMessageToLog(role, text) {
        const messageDiv = document.createElement("div");
        messageDiv.classList.add("chat-message", role);

        let avatar = role === "user" ? "User" : '<i class="fa-solid fa-robot"></i>';
        let name = role === "user" ? "" : "<strong>Enviro Bot</strong>";

        messageDiv.innerHTML = `
            <div class="avatar">${avatar}</div>
            <div class="message-content">
                ${name}
                <p>${text}</p>
            </div>
        `;
        chatLog.appendChild(messageDiv);
        return messageDiv;
    }

    // --- Application Initialization ---
    async function initializeApp() {
        if (!currentUserId) return;
        try {
            const response = await fetch(`http://localhost:5000/api/conversations?userId=${currentUserId}`);
            if (!response.ok) {
                throw new Error("Failed to load history");
            }
            const data = await response.json(); 
            conversations = {};
            data.forEach(convo => {
                conversations[convo.id] = convo;
            });
            renderHistory();
            startNewChat();
        } catch (error) {
            console.error("Error initializing app:", error);
            startNewChat();
        }
    }

    initializeApp();
});