WordPress Plugin

Vantage VSP makes it easy to integrate the chatbot into your WordPress site with 0 code.

1. Register on the website and subscribe to get your API key.

2. Download the plugin. Go to Settings -> Chatbot Settings and enter your API key.

DONE! You can stop there. If you want to change the name or the colors go to step 3.

3. Go into Appearance -> Customize then edit the chatbot, select the name, and the color scheme to match your site.

Backend Technologies

Vantage VSP makes it easy to integrate the chatbot into your WordPress site with 0 code.

1. Register on the website and subscribe to get your API key.

2. Download the plugin. Go to Settings -> Chatbot Settings and enter your API key. DONE! you can stop there if you want.

3. Go into Appearance -> Customize then edit the chatbot, select the name, and the color scheme to match your site.

  1. The backend will be responsible for processing the chatbot’s interactions by handling user questions and managing follow-up communications via email. Begin by setting up your Node.js environment and ensure that you have the necessary dependencies installed. You will need express and node-fetch for handling HTTP requests. Install them with:
    npm install express node-fetch
  2. Create a new router file in your routes directory (e.g., chatbot.js) where you will define the routes that handle chatbot requests. Start by importing the required modules:
    
                    const express = require('express');
                    const fetch = require('node-fetch');
                    const router = express.Router();
                  
  3. Define the /client/ask-question POST route, which will receive the user’s question from the frontend. This route should send the question to VantageVSP’s chatbot endpoint and return the chatbot’s response back to the frontend. Here’s how you define this route:
    
        router.post('/client/ask-question', async (req, res) => {
            try {
                const { chatBotQuestion } = req.body;
                
                const response = await fetch('http://localhost:3000/chatbot/ask-question', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        chatBotQuestion,
                        apiKey: process.env.PULSE_CHAT_KEY 
                    })
                });
    
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
    
                const data = await response.json();
                res.status(200).json({ message: data.message, emailNeeded: data.emailNeeded, questionId: data.questionId });
            } catch (error) {
                console.error('Error:', error);
                res.status(500).json({ error: 'Internal server error' });
            }
        });
                  

    This route handles the entire process of sending the question to the chatbot and returning the chatbot’s reply to the user. It also checks if an email is needed for follow-up and includes a unique questionId for tracking the conversation.

  4. Next, define the /client/submit-email POST route, which will be used to handle email submissions when the chatbot requests an email. This route sends the email and the corresponding question ID to the backend:
    
      router.post('/client/submit-email', async (req, res) => {
          try {
              const { questionId, email } = req.body;
              
              const response = await fetch('http://localhost:3000/chatbot/submit-email', {
                  method: 'POST',
                  headers: {
                      'Content-Type': 'application/json',
                  },
                  body: JSON.stringify({
                      questionId: questionId,
                      email: email 
                  })
              });
    
              if (!response.ok) {
                  throw new Error(`HTTP error! status: ${response.status}`);
              }
    
              const data = await response.json();
              res.status(200).json({ message: data.message });
          } catch (error) {
              console.error('Error:', error);
              res.status(500).json({ error: 'Internal server error' });
          }
      });
                  

    This route ensures that when the chatbot requires further communication via email, the user’s email address is securely stored along with the associated question ID.

  5. Once your routes are defined, ensure they are connected to your main server file (e.g., app.js or server.js). Import the router and use it in your application:
    
                  const chatbotRoutes = require('./routes/chatbot');
    
                  app.use('/chatbot', chatbotRoutes);
                  

    This step integrates the chatbot routes into your application, allowing the frontend to interact with the chatbot via the defined endpoints.

  6. Finally, make sure to handle any environment variables (like PULSE_CHAT_KEY) securely by storing them in a .env file and accessing them via process.env. Run your Node.js application to start handling chatbot interactions. The backend will now correctly process user questions, forward them to the chatbot, and manage any necessary follow-up through email.

Code Snippet


const express = require('express');
const router = express.Router();

//this is the vantage pulse client endpoint
router.post('/client/ask-question', async (req, res) => {
    try {
        const { chatBotQuestion } = req.body;
        
        const response = await fetch('http://vantagevsp.com/chatbot/ask-question', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                chatBotQuestion,
                apiKey: process.env.PULSE_CHAT_KEY 
            })
        });

        if (!response.ok) {
            throw new Error();
        }

        const data = await response.json();
        res.status(200).json({ message: data.message, emailNeeded: data.emailNeeded, questionId: data.questionId });
    } catch (error) {
        console.error('Error:', error);
        res.status(500).json({ error: 'Internal server error' });
    }
});

router.post('/client/submit-email', async (req, res) => {
    try {
        const { questionId, email } = req.body;
        
        const response = await fetch('http://vantagevsp.com/chatbot/submit-email', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                questionId: questionId,
                email: email 
            })
        });

        if (!response.ok) {
            throw new Error();
        }

        const data = await response.json();
        res.status(200).json({ message: data.message });
    } catch (error) {
        console.error('Error:', error);
        res.status(500).json({ error: 'Internal server error' });
    }
});

module.exports = router;

 

1. Setting up the .NET Environment

Make sure you have .NET SDK installed.

Create a new ASP.NET Core Web API project by running the following command in your terminal:

dotnet new webapi -n ChatbotAPI

Install the necessary packages by adding HttpClient for handling HTTP requests. This is included by default in .NET Core, but ensure you are using it properly in your service or controller.

 

2. Creating Controllers

In ASP.NET Core, you’ll define routes in a controller instead of a router file.

Start by creating a new controller in the Controllers directory, for example, ChatbotController.cs:

using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;

namespace ChatbotAPI.Controllers
{
[ApiController]
[Route(“api/[controller]”)]
public class ChatbotController : ControllerBase
{
private readonly HttpClient _httpClient;
private readonly IConfiguration _configuration;

public ChatbotController(HttpClient httpClient, IConfiguration configuration)
{
_httpClient = httpClient;
_configuration = configuration;
}

// POST api/chatbot/client/ask-question
[HttpPost(“client/ask-question”)]
public async Task AskQuestion([FromBody] ChatbotQuestionRequest request)
{
var apiKey = _configuration[“PULSE_CHAT_KEY”];
var chatbotUrl = “http://vantagevsp.com/chatbot/ask-question”; // Replace with actual URL

var payload = new
{
chatBotQuestion = request.ChatBotQuestion,
apiKey = apiKey
};

var content = new StringContent(System.Text.Json.JsonSerializer.Serialize(payload), System.Text.Encoding.UTF8, “application/json”);

var response = await _httpClient.PostAsync(chatbotUrl, content);

if (!response.IsSuccessStatusCode)
{
return StatusCode((int)response.StatusCode, “Error sending the question to the chatbot.”);
}

var data = await response.Content.ReadAsStringAsync();
var chatbotResponse = System.Text.Json.JsonSerializer.Deserialize(data);

return Ok(new { message = chatbotResponse.Message, emailNeeded = chatbotResponse.EmailNeeded, questionId = chatbotResponse.QuestionId });
}

// POST api/chatbot/client/submit-email
[HttpPost(“client/submit-email”)]
public async Task SubmitEmail([FromBody] ChatbotEmailRequest request)
{
var chatbotUrl = “http://vantagevsp.com/chatbot/submit-email”; // Replace with actual URL

var payload = new
{
questionId = request.QuestionId,
email = request.Email
};

var content = new StringContent(System.Text.Json.JsonSerializer.Serialize(payload), System.Text.Encoding.UTF8, “application/json”);

var response = await _httpClient.PostAsync(chatbotUrl, content);

if (!response.IsSuccessStatusCode)
{
return StatusCode((int)response.StatusCode, “Error submitting the email.”);
}

var data = await response.Content.ReadAsStringAsync();
var chatbotResponse = System.Text.Json.JsonSerializer.Deserialize(data);

return Ok(new { message = chatbotResponse.Message });
}
}

// DTOs for the request and response objects
public class ChatbotQuestionRequest
{
public string ChatBotQuestion { get; set; }
}

public class ChatbotEmailRequest
{
public string QuestionId { get; set; }
public string Email { get; set; }
}

public class ChatbotResponse
{
public string Message { get; set; }
public bool EmailNeeded { get; set; }
public string QuestionId { get; set; }
}
}

 

Explanation:

 

  1. AskQuestion Endpoint:
    • This endpoint handles the user’s question and sends it to the chatbot endpoint at vantagevsp.com/chatbot/ask-question.
    • The chatbot’s response is deserialized and returned as a JSON response.
    • We use HttpClient to make a POST request to the chatbot.
  2. SubmitEmail Endpoint:
    • This handles the email submission when required by the chatbot.
    • Similar to the previous method, it sends the question ID and email to the chatbot backend.

3. Injecting HttpClient and IConfiguration

In Startup.cs (or Program.cs if using .NET 6 and beyond), configure HttpClient and load environment variables like PULSE_CHAT_KEY:

public class Startup {

public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)

{
Configuration = configuration;
}

public void ConfigureServices(IServiceCollection services) {
services.AddControllers();
services.AddHttpClient(); // Register HttpClient
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {

if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}

app.UseRouting();
app.UseEndpoints(endpoints => {
  endpoints.MapControllers();
});
}
}

4. Environment Variables

Store your PULSE_CHAT_KEY securely in appsettings.json or as environment variables:
{

“PULSE_CHAT_KEY”: “your-api-key”

}

Or, set it in your environment:  export PULSE_CHAT_KEY=your-api-key

5. Running the Application

  1. To run the .NET application:

dotnet run

  1. Your endpoints will now be available at /api/chatbot/client/ask-question and /api/chatbot/client/submit-email.

Frontend Technologies

Step 1: Add the chat interface to your HTML by including the following code:

<!-- Chat Icon Button -->
<div id="chat-icon" style="position: fixed; bottom: 20px; right: 20px; z-index: 1000;">
    <button id="chat-fab" style="background-color: #007bff; color: white; border: none; border-radius: 50%; width: 60px; height: 60px; display: flex; justify-content: center; align-items: center;">
        <i class="bi bi-chat-dots" style="font-size: 2rem;"></i>
    </button>
</div>

<!-- Chat Window -->
<div id="chat-window" style="position: fixed; bottom: 80px; right: 20px; width: 320px; max-height: 450px; background-color: #ffffff; border-radius: 15px; box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1); display: none; flex-direction: column; overflow: hidden; z-index: 1000;">
    <div id="chat-header" style="background-color: #f0f0f0; padding: 15px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #ddd;">
        <p>Pulse Chat</p>
        <button id="chat-close" style="background: none; border: none; font-size: 1.2rem; cursor: pointer;">✖️</button>
    </div>
    <div id="chat-messages" style="padding: 10px 15px; overflow-y: auto; flex-grow: 1; background-color: #fafafa;"></div>
    <div id="chat-input-section" style="display: flex; padding: 10px; background-color: #f8f8f8;">
        <input id="chat-input" type="text" placeholder="Type your message..." style="flex-grow: 1; padding: 10px; border-radius: 20px; border: 1px solid #ccc; margin-right: 10px;">
        <button id="chat-send" style="background-color: #007bff; color: white; border: none; border-radius: 20px; padding: 10px 15px; cursor: pointer;">Send</button>
    </div>
    <div id="email-input-section" style="display: none; padding: 10px; background-color: #f8f8f8;">
        <input id="email-input" type="email" placeholder="Enter your email" style="flex-grow: 1; padding: 10px; border-radius: 20px; border: 1px solid #ccc; margin-right: 10px;">
        <button id="email-send" style="background-color: #007bff; color: white; border: none; border-radius: 20px; padding: 10px 15px; cursor: pointer;">Send</button>
    </div>
</div>

Step 2: Add the JavaScript functionality to handle the chat interaction:

<script>
document.addEventListener('DOMContentLoaded', function () {
    const chatFab = document.getElementById('chat-fab');
    const chatWindow = document.getElementById('chat-window');
    const chatClose = document.getElementById('chat-close');
    const chatInput = document.getElementById('chat-input');
    const chatSend = document.getElementById('chat-send');
    const chatMessages = document.getElementById('chat-messages');
    const emailInputSection = document.getElementById('email-input-section');
    const emailInput = document.getElementById('email-input');
    const emailSend = document.getElementById('email-send');
    let isEmailRequired = false;
    let lastQuestionId = null;

    // Toggle chat window visibility
    chatFab.addEventListener('click', () => {
        chatWindow.style.display = chatWindow.style.display === 'none' ? 'block' : 'none';
    });

    chatClose.addEventListener('click', () => {
        chatWindow.style.display = 'none';
    });

    // Handle message send
    chatSend.addEventListener('click', () => {
        const userMessage = chatInput.value.trim();
        if (userMessage !== '') {
            addMessage(userMessage, true);
            chatInput.value = '';

            if (isEmailRequired) {
                // Submit email when email is required
                submitEmail(userMessage);
                isEmailRequired = false;
            } else {
                sendQuestionToChatbot(userMessage);
            }
        }
    });

    // Add message to the chat window
    function addMessage(text, isUser) {
        const messageElement = document.createElement('div');
        messageElement.textContent = text;
        messageElement.style.backgroundColor = isUser ? '#007bff' : '#e6e6e6';
        messageElement.style.color = isUser ? 'white' : '#333';
        messageElement.style.padding = '8px 12px';
        messageElement.style.borderRadius = isUser ? '15px 15px 0 15px' : '15px 15px 15px 0';
        messageElement.style.marginBottom = '8px';
        messageElement.style.alignSelf = isUser ? 'flex-end' : 'flex-start';
        chatMessages.appendChild(messageElement);
    }

    // Send question to chatbot API
    function sendQuestionToChatbot(question) {
        fetch('/chatbot/client/ask-question', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ chatBotQuestion: question }),
        })
        .then(response => response.json())
        .then(data => {
            addMessage(data.message, false);
            if (data.emailNeeded) {
                emailInputSection.style.display = 'flex';
                lastQuestionId = data.questionId;
                isEmailRequired = true;
            }
        })
        .catch(error => {
            addMessage('Error: Could not reach chatbot. Try again later.', false);
        });
    }

    // Submit email for follow-up
    function submitEmail(email) {
        fetch('/chatbot/client/submit-email', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ questionId: lastQuestionId, email: email }),
        })
        .then(response => response.json())
        .then(data => {
            addMessage(data.message, false);
            emailInputSection.style.display = 'none';
        })
        .catch(error => {
            addMessage('Error: Could not submit email. Try again later.', false);
        });
    }
});
</script>

Step 3: Add optional CSS to style the chat interface:

<style>
    #chat-messages {
        max-height: 250px;
        overflow-y: auto;
    }
    #chat-fab:hover {
        transform: scale(1.1);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
    }
</style>

Step 4: Load Bootstrap Icons for the chat icon:

<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
  1. The ChatComponent is a reusable Vue component that enables a chat interface in your application. The component allows users to send messages to a chatbot and, if necessary, provide their email address for follow-up.
  2. To use the ChatComponent, first install the necessary dependencies. If you want to use Bootstrap Icons for the chat icon, install them with:
    npm install bootstrap-icons
  3. Once the dependencies are installed, import the ChatComponent into your App.vue or any other parent component where you want the chat icon to appear:
    import ChatComponent from './components/ChatComponent.vue';
  4. Add the <ChatComponent /> tag within your template to display the chat icon on your page. For example, in App.vue:
    
                      <template>
                        <div id="app">
                          <ChatComponent />
                          <!-- Other components or content -->
                        </div>
                      </template>
                    
  5. The component sends user messages to your backend via the /chatbot/client/ask-question route. This route expects a POST request with the user’s question:
    
                    {
                      "chatBotQuestion": "User's question"
                    }
                  

    From this backend endpoint, you will make a request to VantageVSP’s chatbot endpoint which will return a response from our chatbot (Find more details about this once you choose the backend framework you are using). If the chatbot requires an email for follow-up, the backend will prompt the user to provide one.

  6. If the chatbot requests an email, the /chatbot/client/submit-email route is used to send the email address along with the question ID. The backend should then store this information for further communication:
    
                    {
                      "questionId": "unique-question-id",
                      "email": "user@example.com"
                    }
                  
  7. Finally, run your application to see the chat icon on your page. You can now interact with the chatbot, and the component will handle sending messages and collecting emails as necessary.
  8. You can customize the appearance and functionality of the ChatComponent by modifying the styles and methods within the component file to better fit your application’s design and requirements.

Code Snippet


<template>
  <div class="chat-container">
    <button class="chat-icon" @click="toggleChatWindow">
      <i style="font-size:2rem;" class="bi bi-chat-dots"></i>
    </button>

    <transition name="fade">
      <div v-if="isChatOpen" class="chat-window">
        <div class="chat-header">
          <p>Pulse Chat</p>
          <button class="close-btn" @click="toggleChatWindow">✖️</button>
        </div>

        <div class="chat-messages">
          <div
            v-for="(msg, index) in messages"
            :key="index"
            :class="{'user-message': msg.isUser, 'agent-message': !msg.isUser}"
          >
            {{ msg.text }}
          </div>
        </div>

        <div class="chat-input">
          <input
            v-model="newMessage"
            @keyup.enter="sendMessage"
            type="text"
            placeholder="Type your message..."
          />
          <button @click="sendMessage">Send</button>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
import { ref } from 'vue';

export default {
  name: 'ChatComponent',
  setup() {

    const isChatOpen = ref(false);
    const messages = ref([]);
    const newMessage = ref('');
    const organizationId = 8;

    const toggleChatWindow = () => {
      isChatOpen.value = !isChatOpen.value;
    };

    const sendMessage = async () => {
      if (newMessage.value.trim() !== '') {
        const userMessage = newMessage.value;
        messages.value.push({ text: userMessage, isUser: true });
        newMessage.value = '';

        try {
          const response = await fetch('/chatbot/client/ask-question', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              chatBotQuestion: userMessage,
            }),
          });

          if (!response.ok) {
            throw new Error('Failed to get response from the chatbot');
          }

          const data = await response.json();
          messages.value.push({ text: data.message, isUser: false });
          if(data.emailNeeded){
            messages.value.push({text: 'What is an email we can reach you at with a response to your question?', isUser: false})
          }
        } catch (error) {
          console.error('Error:', error);
          messages.value.push({
            text: 'Sorry, something went wrong. Please try again later.',
            isUser: false,
          });
        }
      }
    };

    return {
      isChatOpen,
      messages,
      newMessage,
      toggleChatWindow,
      sendMessage,
    };
  },
};
</script>

<style scoped>
.chat-container {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
}

.chat-icon {
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  width: 60px;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s, box-shadow 0.2s;
}

.chat-icon:hover {
  transform: scale(1.1);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}

.chat-window {
  position: absolute;
  bottom: 80px;
  right: 0;
  width: 320px;
  max-height: 450px;
  background-color: #ffffff;
  border-radius: 15px;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  opacity: 1;
  animation: slide-up 0.3s ease-out;
}

.chat-header {
  background-color: #f0f0f0;
  color: #333333;
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ddd;
}

.chat-messages {
  padding: 10px 15px;
  overflow-y: auto;
  flex-grow: 1;
  background-color: #fafafa;
  font-size: 0.9rem;
}

.user-message {
  background-color: #007bff;
  color: white;
  padding: 8px 12px;
  border-radius: 15px 15px 0 15px;
  margin-bottom: 8px;
  align-self: flex-end;
  max-width: 75%;
  word-wrap: break-word;
}

.agent-message {
  background-color: #e6e6e6;
  color: #333333;
  padding: 8px 12px;
  border-radius: 15px 15px 15px 0;
  margin-bottom: 8px;
  align-self: flex-start;
  max-width: 75%;
  word-wrap: break-word;
}

.chat-input {
  display: flex;
  padding: 10px;
  border-top: 1px solid #ddd;
  background-color: #f8f8f8;
}

.chat-input input {
  flex-grow: 1;
  padding: 10px;
  border-radius: 20px;
  border: 1px solid #ccc;
  margin-right: 10px;
  font-size: 0.9rem;
}

.chat-input button {
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 20px;
  padding: 10px 15px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.chat-input button:hover {
  background-color: #0056b3;
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

@keyframes slide-up {
  from {
    transform: translateY(100%);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}
</style>
  1. The ChatComponent is a reusable React component that enables a chat interface in your application. The component allows users to send messages to a chatbot and, if necessary, provide their email address for follow-up.
  2. To use the ChatComponent, first install the necessary dependencies. If you want to use Bootstrap Icons for the chat icon, install them with:
    npm install bootstrap-icons
  3. Once the dependencies are installed, import the ChatComponent into your App.js or any other parent component where you want the chat icon to appear:
    import ChatComponent from './components/ChatComponent';
  4. Add the <ChatComponent /> tag within your JSX to display the chat icon on your page. For example, in App.js:
    
                        function App() {
                          return (
                            <div className="App">
                              <ChatComponent />
                              <!-- Other components or content -->
                            </div>
                          );
                        }
                      
  5. The component sends user messages to your backend via the /chatbot/client/ask-question route. This route expects a POST request with the user’s question:
    
                      {
                        "chatBotQuestion": "User's question"
                      }
                    

    From this backend endpoint, you will make a request to VantageVSP’s chatbot endpoint which will return a response from our chatbot. If the chatbot requires an email for follow-up, the backend will prompt the user to provide one.

  6. If the chatbot requests an email, the /chatbot/client/submit-email route is used to send the email address along with the question ID. The backend should then store this information for further communication:
    
                      {
                        "questionId": "unique-question-id",
                        "email": "user@example.com"
                      }
                    
  7. Finally, run your application to see the chat icon on your page. You can now interact with the chatbot, and the component will handle sending messages and collecting emails as necessary.
  8. You can customize the appearance and functionality of the ChatComponent by modifying the styles and methods within the component file to better fit your application’s design and requirements.

Code Snippet



import React, { useState } from 'react';

const ChatComponent = () => {
  const [isChatOpen, setIsChatOpen] = useState(false);
  const [messages, setMessages] = useState([]);
  const [newMessage, setNewMessage] = useState('');
  const [isCollectingEmail, setIsCollectingEmail] = useState(false);
  const [lastQuestionId, setLastQuestionId] = useState(null);

  const toggleChatWindow = () => {
    setIsChatOpen(!isChatOpen);
  };

  const sendMessage = async () => {
    if (newMessage.trim() !== '') {
      const userMessage = newMessage;
      setMessages([...messages, { text: userMessage, isUser: true }]);
      setNewMessage('');

      if (isCollectingEmail) {
        await submitEmail(userMessage);
        setIsCollectingEmail(false);
      } else {
        await sendQuestionToChatbot(userMessage);
      }
    }
  };

  const sendQuestionToChatbot = async (userMessage) => {
    try {
      const response = await fetch('/chatbot/client/ask-question', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ chatBotQuestion: userMessage }),
      });

      if (!response.ok) {
        throw new Error('Failed to get a response from the chatbot');
      }

      const data = await response.json();
      setMessages([...messages, { text: data.message, isUser: false }]);

      if (data.emailNeeded) {
        setMessages((prevMessages) => [
          ...prevMessages,
          { text: 'What is an email we can reach you at with a response to your question?', isUser: false }
        ]);
        setLastQuestionId(data.questionId);
        setIsCollectingEmail(true);
      }
    } catch (error) {
      console.error('Error:', error);
      setMessages([...messages, { text: 'Sorry, something went wrong. Please try again later.', isUser: false }]);
    }
  };

  const submitEmail = async (email) => {
    try {
      const emailResponse = await fetch('/chatbot/client/submit-email', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          questionId: lastQuestionId,
          email: email,
        }),
      });

      if (!emailResponse.ok) {
        throw new Error('Failed to submit email');
      }

      const data = await emailResponse.json();
      setMessages([...messages, { text: data.message, isUser: false }]);
      setLastQuestionId(null);
    } catch (error) {
      console.error('Error:', error);
      setMessages([...messages, { text: 'Sorry, something went wrong. Please try again later.', isUser: false }]);
      setLastQuestionId(null);
    }
  };

  return (
    <div style={styles.chatContainer}>
      <button style={styles.chatIcon} onClick={toggleChatWindow}>
        <i style={{ fontSize: '2rem' }} className="bi bi-chat-dots"></i>
      </button>

      {isChatOpen && (
        <div style={styles.chatWindow}>
          <div style={styles.chatHeader}>
            <p>Pulse Chat</p>
            <button style={styles.closeBtn} onClick={toggleChatWindow}>✖️</button>
          </div>

          <div style={styles.chatMessages}>
            {messages.map((msg, index) => (
              <div
                key={index}
                style={msg.isUser ? styles.userMessage : styles.agentMessage}
              >
                {msg.text}
              </div>
            ))}
          </div>

          <div style={styles.chatInput}>
            <input
              value={newMessage}
              onChange={(e) => setNewMessage(e.target.value)}
              onKeyUp={(e) => e.key === 'Enter' && sendMessage()}
              type="text"
              placeholder="Type your message..."
              style={styles.inputField}
            />
            <button style={styles.sendButton} onClick={sendMessage}>Send</button>
          </div>
        </div>
      )}
    </div>
  );
};

const styles = {
  chatContainer: {
    position: 'fixed',
    bottom: '20px',
    right: '20px',
    zIndex: 1000,
  },
  chatIcon: {
    backgroundColor: '#007bff',
    color: 'white',
    border: 'none',
    borderRadius: '50%',
    cursor: 'pointer',
    width: '60px',
    height: '60px',
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    boxShadow: '0 2px 10px rgba(0, 0, 0, 0.1)',
    transition: 'transform 0.2s, box-shadow 0.2s',
  },
  chatWindow: {
    position: 'absolute',
    bottom: '80px',
    right: '0',
    width: '320px',
    maxHeight: '450px',
    backgroundColor: '#ffffff',
    borderRadius: '15px',
    boxShadow: '0 10px 20px rgba(0, 0, 0, 0.1)',
    display: 'flex',
    flexDirection: 'column',
    overflow: 'hidden',
    opacity: 1,
    animation: 'slide-up 0.3s ease-out',
  },
  chatHeader: {
    backgroundColor: '#f0f0f0',
    color: '#333333',
    padding: '15px',
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    borderBottom: '1px solid #ddd',
  },
  chatMessages: {
    padding: '10px 15px',
    overflowY: 'auto',
    flexGrow: 1,
    backgroundColor: '#fafafa',
    fontSize: '0.9rem',
  },
  userMessage: {
    backgroundColor: '#007bff',
    color: 'white',
    padding: '8px 12px',
    borderRadius: '15px 15px 0 15px',
    marginBottom: '8px',
    alignSelf: 'flex-end',
    maxWidth: '75%',
    wordWrap: 'break-word',
  },
  agentMessage: {
    backgroundColor: '#e6e6e6',
    color: '#333333',
    padding: '8px 12px',
    borderRadius: '15px 15px 15px 0',
    marginBottom: '8px',
    alignSelf: 'flex-start',
    maxWidth: '75%',
    wordWrap: 'break-word',
  },
  chatInput: {
    display: 'flex',
    padding: '10px',
    borderTop: '1px solid #ddd',
    backgroundColor: '#f8f8f8',
  },
  inputField: {
    flexGrow: 1,
    padding: '10px',
    borderRadius: '20px',
    border: '1px solid #ccc',
    marginRight: '10px',
    fontSize: '0.9rem',
  },
  sendButton: {
    backgroundColor: '#007bff',
    color: 'white',
    border: 'none',
    borderRadius: '20px',
    padding: '10px 15px',
    cursor: 'pointer',
    transition: 'background-color 0.2s',
  },
  closeBtn: {
    backgroundColor: 'transparent',
    border: 'none',
    fontSize: '1.2rem',
    cursor: 'pointer',
  },
  '@keyframes slide-up': {
    from: {
      transform: 'translateY(100%)',
      opacity: 0,
    },
    to: {
      transform: 'translateY(0)',
      opacity: 1,
    },
  },
};

export default ChatComponent;