File size: 7,959 Bytes
eb81b34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71e611b
 
 
 
 
 
 
 
 
 
 
 
 
 
eb81b34
 
71e611b
eb81b34
71e611b
 
 
 
eb81b34
71e611b
 
 
 
 
 
 
 
eb81b34
71e611b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb81b34
71e611b
eb81b34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
class ChatInterface {
    constructor() {
        this.messagesContainer = document.getElementById('chatMessages');
        this.messageInput = document.getElementById('messageInput');
        this.sendButton = document.getElementById('sendButton');
        this.typingIndicator = document.getElementById('typingIndicator');
        this.quickReplies = document.getElementById('quickReplies');

        this.isTyping = false;
        this.conversationStarted = false;

        this.init();
    }

    init() {
        this.setupEventListeners();
        this.startConversation();
        this.adjustTextareaHeight();
    }

    setupEventListeners() {
        // Send button click
        this.sendButton.addEventListener('click', () => this.sendMessage());

        // Enter key to send (Shift+Enter for new line)
        this.messageInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.sendMessage();
            }
        });

        // Auto-resize textarea
        this.messageInput.addEventListener('input', () => this.adjustTextareaHeight());

        // Quick reply clicks
        this.quickReplies.addEventListener('click', (e) => {
            if (e.target.classList.contains('quick-reply')) {
                this.sendQuickReply(e.target.textContent);
            }
        });
    }

    adjustTextareaHeight() {
        this.messageInput.style.height = 'auto';
        this.messageInput.style.height = Math.min(this.messageInput.scrollHeight, 100) + 'px';
    }

    async startConversation() {
        await this.delay(2000);

        const welcomeMessage = "Hello! 👋 I'm your AI assistant calling on behalf of a client who is interested in making a reservation to visit your apartment. Could you please tell me which apartment you'd like to schedule a viewing for?";

        await this.addBotMessage(welcomeMessage);

        await this.delay(2000);

        this.showQuickReplies([
            "Apartment A - 2BR/1BA",
            "Apartment B - 3BR/2BA",
            "Apartment C - 1BR/1BA",
            "I have multiple units"
        ]);

        this.conversationStarted = true;
    }

    async sendMessage() {
        const message = this.messageInput.value.trim();
        if (!message || this.isTyping) return;

        this.addUserMessage(message);
        this.messageInput.value = '';
        this.adjustTextareaHeight();
        this.hideQuickReplies();

        // Simulate AI processing
        await this.showTyping();

        const response = await this.generateResponse(message);
        await this.addBotMessage(response.message);

        await this.delay(2000);

        if (response.quickReplies) {
            this.showQuickReplies(response.quickReplies);
        }
    }

    async sendQuickReply(reply) {
        this.addUserMessage(reply);
        this.hideQuickReplies();

        await this.showTyping();

        const response = await this.generateResponse(reply);
        await this.addBotMessage(response.message);

        await this.delay(2000);

        if (response.quickReplies) {
            this.showQuickReplies(response.quickReplies);
        }
    }

    async generateResponse(userMessage) {
        try {
            const response = await fetch('/chat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    message: userMessage,
                    conversation_history: this.getConversationHistory()
                })
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();

            return {
                message: data.message,
                quickReplies: data.quick_replies || []
            };

        } catch (error) {
            console.error('Error calling chat API:', error);

            // Fallback response if API fails
            return {
                message: "I apologize, but I'm having trouble connecting right now. Could you please try again in a moment?",
                quickReplies: ["Try again", "Contact support"]
            };
        }
    }

    getConversationHistory() {
        const messages = this.messagesContainer.querySelectorAll('.message');
        const history = [];

        messages.forEach(messageEl => {
            const isBot = messageEl.classList.contains('message-bot');
            const content = messageEl.querySelector('.message-content').textContent;

            history.push({
                role: isBot ? 'assistant' : 'user',
                content: content
            });
        });

        return history;
    }

    addUserMessage(message) {
        const messageElement = this.createMessageElement('user', message);
        this.messagesContainer.appendChild(messageElement);
        this.scrollToBottom();
    }

    async addBotMessage(message) {
        const messageElement = this.createMessageElement('bot', message);
        this.messagesContainer.appendChild(messageElement);
        this.scrollToBottom();
        this.hideTyping();
    }

    createMessageElement(sender, content) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message message-${sender}`;

        const avatar = document.createElement('div');
        avatar.className = `avatar avatar-${sender}`;
        avatar.innerHTML = sender === 'bot' ? '<i class="fas fa-robot"></i>' : '<i class="fas fa-user"></i>';

        const contentDiv = document.createElement('div');
        contentDiv.className = 'message-content';
        contentDiv.textContent = content;

        messageDiv.appendChild(avatar);
        messageDiv.appendChild(contentDiv);

        return messageDiv;
    }

    async showTyping() {
        this.isTyping = true;
        this.sendButton.disabled = true;
        this.typingIndicator.style.display = 'flex';
        this.scrollToBottom();
    }

    hideTyping() {
        this.isTyping = false;
        this.sendButton.disabled = false;
        this.typingIndicator.style.display = 'none';
    }

    showQuickReplies(replies) {
        this.quickReplies.innerHTML = '';
        replies.forEach(reply => {
            const button = document.createElement('button');
            button.className = 'quick-reply';
            button.textContent = reply;
            this.quickReplies.appendChild(button);
        });
        this.quickReplies.style.display = 'flex';
    }

    hideQuickReplies() {
        this.quickReplies.style.display = 'none';
    }

    scrollToBottom() {
        setTimeout(() => {
            this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight;
        }, 100);
    }

    delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}

// Initialize the chat interface when the page loads
document.addEventListener('DOMContentLoaded', () => {
    new ChatInterface();
});

// Add some smooth animations and interactions
document.addEventListener('DOMContentLoaded', () => {
    // Add hover effects to messages
    document.addEventListener('mouseover', (e) => {
        if (e.target.closest('.message')) {
            e.target.closest('.message').style.transform = 'translateY(-1px)';
        }
    });

    document.addEventListener('mouseout', (e) => {
        if (e.target.closest('.message')) {
            e.target.closest('.message').style.transform = 'translateY(0)';
        }
    });

    // Add some visual feedback for the send button
    const sendButton = document.getElementById('sendButton');
    sendButton.addEventListener('mousedown', () => {
        sendButton.style.transform = 'scale(0.95)';
    });

    sendButton.addEventListener('mouseup', () => {
        sendButton.style.transform = 'scale(1)';
    });
});