File "app-previous.js"

Full path: /home/fsibplc/public_html/bot/bot-js/app-previous.js
File size: 54.63 B (54.63 KB bytes)
MIME-type: text/plain
Charset: utf-8

Download   Open   Edit   Advanced Editor   Back

class Chatbox {
  constructor() {
    this.args = {
      openButton: document.querySelector("#Ch12"),
      chatBox: document.querySelector(".chatbox__support"),
      questionBox : document.querySelector('#questionBox'),
      sendButton : document.querySelector('.send__button'),
      minimizeButton: document.querySelector(".minimize__button"),
      maxButton: document.querySelector(".chatbox__maxbutton"),
      minButton: document.querySelector(".chatbox__minbutton"),
      resetButton: document.querySelector(".chatbox__resetbutton"),
      overlayBot: document.querySelector(".overlayBot"),
      container: document.querySelector('.container2'),
      soundButton : document.getElementById('soundButton'),
      // <---------------------- Custom buttons -------------------->
      customButtons: document.querySelectorAll(".custom_button_welcome"),
    };
    this.botSound = document.getElementById('botSound');
    this.chatboxButton= document.getElementById('chatbox__button');
    this.questionBox = document.querySelector('#questionBox');
    this.sendButton = document.querySelector('.send__button');
    this.darkSendIcon = this.sendButton.querySelector('img[src*="dark"]');
    this.whiteSendIcon = this.sendButton.querySelector('img[src*="white"]');
    this.updateSendButtonState();
    this.setupInputListener();
    this.isSoundOn=false;
    this.buttonAnimationDelay = 100;
    this.state = false;
    this.isMaximized = false;
    this.isSendButtonDisabled=true;
    this.messages = [];
    this.user_messages_count = 0;
    this.bot_messages_count = 0;
	this.clieked_id = ''; 
	this.response = '';
    
    // Text to be typed
    this.txt = "";
    this.instructions = [];
    this.i = 0;
    this.j = 0;
    this.speed = 20;
    this.parser = new DOMParser();
    this.allButtons = new Set();
    this.loadingIndicator = document.createElement("div");
    // this.loadingIndicator.className = "loading-indicator";
    this.loadingIndicator.innerHTML = ChatBotHTMLTemplates.animationContainer;
    this.loadingIndicator.style.display = "none";
    this.args.chatBox
      .querySelector(".chatbox__messages")
      .appendChild(this.loadingIndicator);
    this.initializeChatbox();

  }
  //initail response from bot
  initializeChatbox() {
    
    const chatboxMessages = this.args.chatBox.querySelector(".chatbox__messages");
    chatboxMessages.innerHTML = `
      <div id="chat-message"></div>
    `;
    //append loading indicator inside chat-message
    chatboxMessages.appendChild(this.loadingIndicator);

    // Show loading indicator
    this.showLoadingIndicator();

    // show loading indicator for 1.5second then display welcome message
    setTimeout(() => {
      this.hideLoadingIndicator();
      if (this.isSoundOn) {
        this.botSound.play();
        
    }
      this.displayWelcomeMessage();
    }, 1500); // 1.5 seconds delay
  }
//contents of welcome message
  displayWelcomeMessage() {
    this.bot_messages_count += 1;
    const chatmessage = document.querySelector("#chat-message");
    const divId = "welcomeMessage" + this.bot_messages_count;
    const html = `
      <div class="response_message">
        <div class="chatbox__image--header">
          <div class="header-avatar-2"></div>
        </div>
        <div id="${divId}" class="messages__item messages__item--visitor" style="text-align:left !important; padding:10px; line-height:1.3"></div>
        <div id="buttonContainer-${divId}"></div>
      </div>
      <div id="timestamp-${divId}" class="message-time-bot"></div>
    `;

    chatmessage.innerHTML += html;

    const responseElement = document.getElementById(divId);
    const welcomeMessage = "Muhtaram/Muhtarama, Assalamu Alaikum. I am Smart Connect your banking assistant from FSIB. How can I help you?";
//type content then show buttons and timestamps
    this.typeContent(responseElement, welcomeMessage)
      .then(() => {
        this.renderButtonsAndTimestamp(divId);
      });

    // Add welcome buttons
    this.ButtonHtml = ChatbotButtonTemplates.mainMenuOptionHtml;
  }

  convertMillisecToHrMinSec(milisectime) {
    return ChatbotUtils.convertMillisecToHrMinSec(milisectime);
  }
  display() {
    const {
      openButton,
      chatBox,
      sendButton,
      minimizeButton,
      maxButton,
      minButton,
      resetButton,
      customButtons,
      soundButton
    } = this.args;

    openButton.addEventListener("click", () => this.toggleState());
    sendButton.addEventListener("click", () => {
      this.onSendButton(chatBox);
      this.scrollToBottom();
    });
    minimizeButton.addEventListener("click", () => {
      this.toggleState();
      document.getElementById('overlay').style.display = 'none'; //hide overlay during minimization
    });
    maxButton.addEventListener("click", () => {
      this.maximizeChatbox();
      this.scrollToBottom();
    });
    minButton.addEventListener("click", () => {
      this.minimizeChatbox();
      this.scrollToBottom();
    });
    //conditionally play sound
    soundButton.addEventListener('click', () => {
      this.isSoundOn = !this.isSoundOn;
      soundButton.innerText = this.isSoundOn ? '🔊' : '🔈';  

  });
    if (resetButton) {
      resetButton.addEventListener("click", () => {
        this.resetChatbox();
        this.scrollToBottom();
      });
    }
    //attach event listener to every custom button 
    customButtons.forEach((button) => {
      button.addEventListener("click", () => {
        this.onCustomSendButton(chatBox, button.id);
        this.scrollToBottom();
      });
    });

    const node = document.querySelector('input[id="questionBox"]');
    node.addEventListener("keyup", ({ key }) => {
      if (key === "Enter") {
        this.onSendButton(chatBox);
        this.attachButtonEventListeners(this.args.chatBox);
        this.scrollToBottom();
      }
    });
    this.sendButton.addEventListener('click', () => {
      if (!this.sendButton.disabled) {
        this.onSendButton(this.args.chatBox);
        this.attachButtonEventListeners(this.args.chatBox);
        this.scrollToBottom();
        this.updateSendButtonState(); 
      }
    });

    this.updateIcons();
  }
  toggleState() {
    this.state = !this.state;
    if (this.state) {
        this.args.chatBox.classList.add("chatbox--active");
        this.args.overlayBot.style.display="block";
        this.args.container.style.display="block";
        this.chatboxButton.style.animation="none";
        
    } else {
        this.args.chatBox.classList.remove("chatbox--active");
        this.args.container.style.display="none"
        this.args.overlayBot.style.display="none";
        this.chatboxButton.style.animation="pulse2 2s infinite";


    }
  }
  maximizeChatbox() {
    this.isMaximized = true;
    this.args.chatBox.style.height = "90vh"; // Set the height to full screen
    this.args.chatBox.style.width = "90vw"; // Set the width to full screen
    this.updateIcons();
  }
  minimizeChatbox() {
    this.isMaximized = false;
    this.args.chatBox.style.height = "510px"; // Set the height to default
    this.args.chatBox.style.width = "490px"; // Set the width to default, normal size
    this.updateIcons();
  }
  updateIcons() {
    if (this.isMaximized) {
      this.args.maxButton.style.display = "none";
      this.args.minButton.style.display = "inline-block";
    } else {
      this.args.maxButton.style.display = "inline-block";
      this.args.minButton.style.display = "none";
    }
  }
  resetChatbox() {
    // Clear the messages array
    this.messages = [];

    // Reset user and bot message counts
    this.user_messages_count = 0;
    this.bot_messages_count = 0;

    // Re-initialize the chatbox
    this.initializeChatbox();
  }
  onCustomSendButton(chatbox, buttonId) {
	this.clieked_id = buttonId; 
    const buttonText = document.querySelector("#" + buttonId).innerText;
    // alert("inside onCustomSendButton.  button id = " + buttonId +" and button text = " + buttonText);
    if (buttonText === "") {
      return;
    }
    //------------------ Printing User Question -------------------
    this.user_messages_count += 1;
    this.updateChatUserText(chatbox, buttonText);
    this.messages.push({ name: "User", message: buttonText });

    //------------------ Custom Response generation -------------------
    if (buttonId == "depositSchemeBtn") {
      this.answerText =
        "Muhtaram/Muhtarama, FSIB Savings Account provides you for more saving with attractive profit rate." +
        "what do you want to know from the following?  ";
      this.ButtonHtml = ChatbotButtonTemplates.depositSchemeOptionHtml;
      this.normalHTML = ``;
    } else if (buttonId === "backMainMenuBtn") {
      this.answerText =
        "Sure, I'm happy to help you with something else. What would you like to know about?";
      this.ButtonHtml = ChatbotButtonTemplates.mainMenuOptionHtml;
      this.normalHTML = "";
    } 
    else if (buttonId === "initialMessage") {
      this.answerText =
      "Muhtaram/Muhtarama, Assalamu Alaikum. I am Smart Connect your banking assistant from FSIB. How can I help you?";
      this.ButtonHtml = ChatbotButtonTemplates.mainMenuOptionHtml;
      this.normalHTML = "";
    } 
    else if (buttonId === "openAccount") {
      this.answerText = "Choose one of the following";
      this.ButtonHtml = ChatbotButtonTemplates.openAccountOptionHtml;
      this.normalHTML = "";
    } else if (buttonId == "mudarabaSavingsAccountBtn") {
      this.answerText = "Click any of the following to see details";
      this.ButtonHtml = ChatbotButtonTemplates.depositSchemeOptionHtml;
      this.normalHTML = ``;
    } else if (buttonId == "applyNowBtn") {
      this.answerText = `Choose one of the following`;
      this.ButtonHtml = ChatbotButtonTemplates.applyNowOptionHtml;
    } else if (buttonId == "contactUsBtn") {
      this.answerText = `Thanks for your interest. You can contact with us using the following options 
`;
      this.ButtonHtml = ChatbotButtonTemplates.contactUsBtnOptionHtml;
    }
	
	else if (buttonId == "askQuestionsBtn") {
		this.answerText = `Dear customer, I'll be more than happy to answer all of  your questions 😊  `;
		this.normalHTML = `
              <p style="margin-top:10px;">I'll ask you a couple of questions and pass your message to our team, so they can process your request as soon as possible. </p>
		      <p> Let's begin 👉 </p>
		      <p> First of all, Are you our current customer?  </p> `;
        this.ButtonHtml = ChatbotButtonTemplates.askQuestionsOptionHtml;
    } 
	else if (buttonId == "customerYes") {
		//this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
		this.ButtonHtml = `<p> </p> `;
		this.answerText = ``;
	    this.normalHTML = `<p> Please tell us your name using following formate.  </p> 
                           <p style="font-coor: gray; font-size: 11px;"> Name# your name  </p>  `;
    } 
	else if (buttonId == "customerNo") {
		//this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
		this.answerText = ``;
		this.ButtonHtml = `<p> </p> `;
        this.normalHTML = `<p> Please tell us your name using following formate.  </p> 
                           <p style="font-coor: gray; font-size: 11px;"> Email# your email  </p> `;
	  
    }

	else if (buttonId == "locationsBtn") {
      this.answerText = `See all our locations`;
      this.ButtonHtml = ChatbotButtonTemplates.locationsOptionHtml;
    } else if (buttonId == "mudrabaSavings") {
      this.answerText = `Click any of the following to see details  `;
      this.ButtonHtml = ChatbotButtonTemplates.mudrabaSavingsOptionHtml;
    } else if (buttonId == "wadiahAccount") {
      this.answerText = `Wadiah account details `;
      this.ButtonHtml = ChatbotButtonTemplates.alWadiahOptionHtml;
    } else if (buttonId == "foreignCurrency") {
      this.answerText = `Foreign Currency details `;
      this.ButtonHtml = ChatbotButtonTemplates.foreignCurrencyOptionHtml;
    } else if (buttonId == "mudrabaTermDeposit") {
      this.answerText = `Mudaraba Term Deposit details `;
      this.ButtonHtml = ChatbotButtonTemplates.mudrabaTermDepositOptionHtml;
    } else if (buttonId == "mudrabaSchemeAccount") {
      this.answerText = `Mudaraba Scheme Account details `;
      this.ButtonHtml = ChatbotButtonTemplates.mudrabaSchemeAccountOptionHtml;
      this.normalHTML = ``;
    } else if (buttonId == "mudrabaSavingsDeposit") {
      this.answerText = `FSIB Savings Account provides you for more saving with attractive profit rate. `;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.mudrabaSavingsDepositContent;
    } else if (buttonId == "mudrabaSavingsOnkur") {
      this.answerText = `Introduce the child into the world of banking!`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.mudrabaSavingsOnkurContent;
    } else if (buttonId == "mudrabaSavingsProjonmo") {
      this.answerText = `Familiarize the new generation by practicing the habit of saving`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.mudrabaSavingsProjonmoContent;
    } else if (buttonId == "mudrabaSavingsPrapti") {
      this.answerText = `FSIB Mudarabah Salary Saving Account (Prapti) is for those whose monthly salary is BDT 5000 or above. It’s an account styled to provide you the best profit rate at a low balance requirement—making it the classic choice for you. `;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.mudrabaSavingsPraptiContent;
    } else if (buttonId == "mudrabaSavingsProbin") {
      this.answerText = `Considering the contribution of Senior Citizen in high esteem, FSIB offers a unique moderate saving account for their convenience. `;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.mudrabaSavingsProbinContent;
    } else if (buttonId == "mudrabaSavingsMehonoti") {
      this.answerText = `Specialized account for people with lower income bracket of the country.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.mudrabaSavingsMehonotiContent;
    } else if (buttonId == "mudrabaSavingsSND") {
      this.answerText = `A Specialized account that gives you more transactions limit than regular.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.mudrabaSavingsSNDContent;
    } else if (buttonId == "mudrabaSavingsSmartAccount") {
      this.answerText = `Mudarabah “FSIB Smart Account” for those who are interested to get unlimited transaction facility and high profit rate like as Mudarabah Term Deposit Account in one account. It’s a unique savings account and provides the best profit rate at slab wise.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.mudrabaSavingsSmartAccountContent;
    } else if (buttonId == "wadiahCurentDepositBtn") {
      this.answerText = `Desiring for unlimited transaction facility for conducting day to day higher business transactions? We offer the best for you.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.wadiahCurentDepositBtnContent;
    } else if (buttonId == "shommanBtn") {
      this.answerText = `Al-Wadeeah Premium Account gives you free intercity transaction with unlimited transaction facility.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.shommanBtnContent;
    } else if (buttonId == "morjadaBtn") {
      this.answerText = `It’s a unique account which allows you for having unlimited transaction facility with a wide list of specialized advantages. It certainly adds more for you.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.morjadaBtnContent;
    } else if (buttonId == "foreignCurrencyPFC") {
      this.answerText = `Private Foreign Currency (PFC) Accounts for Bangladeshi and foreign nationals, offering flexible features for managing foreign currencies.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.foreignCurrencyPFCContent;
    } else if (buttonId == "foreignCurrencyRFCD") {
      this.answerText = `Resident Foreign Currency Deposit (RFCD) Account for Bangladeshi residents to manage foreign exchange brought from abroad.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.foreignCurrencyRFCDContent;
    } else if (buttonId == "foreignCurrencyNFCD") {
      this.answerText = `Non-Resident Foreign Currency Deposit (NFCD) Account for non-residents and foreign entities.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.foreignCurrencyNFCDContent;
    } else if (buttonId == "foreignCurrencyERQ") {
      this.answerText = `Export Retention Quota (ERQ) Account:`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.foreignCurrencyERQContent;
    } else if (buttonId == "foreignCurrencyNITA") {
      this.answerText = `Non-Resident Investor's Taka Account (NITA)`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.foreignCurrencyNITAContent;
    } else if (buttonId == "foreignCurrencyOther") {
      this.answerText = `Details `;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.foreignCurrencyOtherContent;
    } else if (buttonId == "mudarabaTermDepositMTD") {
      this.answerText = `Mudarabah Term Deposit`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.mudarabaTermDepositMTDContent;
    } else if (buttonId == "mudarabaTermDepositMMPS") {
      this.answerText = `Don’t wait long for getting your profit. By depositing in MMPS, get your profit on monthly basis.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.mudarabaTermDepositMMPSContent;
    } else if (buttonId == "mudarabaTermDepositFM") {
      this.answerText = `FSIB Murobbi`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.mudarabaTermDepositFMContent;
    } else if (buttonId == "mudarabaTermDepositM") {
      this.answerText = `FSIB Mahiyasi`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.mudarabaTermDepositMContent;
    } else if (buttonId == "mudarabaTermDepositFS") {
      this.answerText = `FSIB Sanchay`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.mudarabaTermDepositFSContent;
    } else if (buttonId == "mudarabaTermDepositMDDS") {
      this.answerText = `Will not be happy to get double? FSIB allows your deposit to be doubled within shortest possible time.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.mudarabaTermDepositMDDSContent;
    } else if (buttonId == "mudarabaTermDepositU") {
      this.answerText = `Mudarabah Special Gift Monthly Profit Scheme “Utshob- 24”`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.mudarabaTermDepositUContent;
    } else if (buttonId == "mudarabaTermDepositMSDDS") {
      this.answerText = `Mudarabah Smart Deposit Double Scheme `;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.mudarabaTermDepositMSDDSContent;
    } else if (buttonId == "mudarabaTermDepositFC") {
      this.answerText = `Mudarabah Term Deposit Account “FSIB Century” is an attractive Term deposit account which is open to individuals & organizations.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.mudarabaTermDepositFCContent;
    } else if (buttonId == "mudarabaTermDepositMTDA") {
      this.answerText = `Mudarabah Term Deposit Account “Double Century” is an attractive Scheme account which is open to individuals & organizations.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.mudarabaTermDepositMTDAContent;
    } else if (buttonId == "mudarabaSchemAccountNiramoy") {
      this.answerText = `FSIB Health Care Deposit Scheme helps you meet the medical crises at the right moment.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.mudarabaSchemAccountNiramoyContent;
    } else if (buttonId == "mudarabaSchemAccountAgroshor") {
      this.answerText = `Be a Millionaire by starting as installment of only BDT 2,125 in convenient tenure.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML =
        ChatBotHTMLTemplates.mudarabaSchemAccountAgroshorContent;
    } else if (buttonId == "mudarabaSchemAccountDurbar") {
      this.answerText = `Mudarabah Monthly Deposit Scheme “Durbar” offers flexible installment options. `;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.mudarabaSchemAccountDurbarContent;
    } else if (buttonId == "mudarabaSchemAccountEhsan") {
      this.answerText = `An attractive deposit scheme offering high profit rates for fixed deposits with installments.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.mudarabaSchemAccountEhsanContent;
    } else if (buttonId == "mudarabaSchemAccountBondhon") {
      this.answerText = `Facing a shortage of money for marriage? FSIB Bondhon helps you solve it with flexible installments.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.mudarabaSchemAccountBondhonContent;
    } else if (buttonId == "mudarabaSchemAccountGhoroni") {
      this.answerText = `Griheni Deposit Scheme encourages women empowerment by offering flexible savings options.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.mudarabaSchemAccountGhoroniContent;
    } else if (buttonId == "mudarabaSchemAccountHaj") {
      this.answerText = `Special Deposit Scheme to simplify performing Haj.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.mudarabaSchemAccountHajContent;
    } else if (buttonId == "mudarabaSchemAccountMushafir") {
      this.answerText = `“Traveling-Unlimited” `;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML =
        ChatBotHTMLTemplates.mudarabaSchemAccountMushafirContent;
    } else if (buttonId == "mudarabaSchemAccountSanchaye") {
      this.answerText = `By opening Mudarabah Pension Scheme “Sanchaye Shukh” an account holder will get monthly pension as social safety.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML =
        ChatBotHTMLTemplates.mudarabaSchemAccountSanchayeContent;
    } else if (buttonId == "mudarabaSchemAccountMerchant") {
      this.answerText = `This is an attractive monthly deposit scheme for different organizations.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML =
        ChatBotHTMLTemplates.mudarabaSchemAccountMerchantContent;
    } else if (buttonId == "mudarabaSchemAccountFSIBCare") {
      this.answerText = `Mudarabah Monthly Deposit Scheme “FSIB Care” gives More attractive provisional profit rate than others.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML =
        ChatBotHTMLTemplates.mudarabaSchemAccountFSIBCareContent;
    } else if (buttonId == "investmentBtn") {
      this.answerText = `We offer four modes of investment options. Choose one of the following to see details`;
      this.ButtonHtml = ChatbotButtonTemplates.investmentOptionHtml;
      this.normalHTML = ``;
    } else if (buttonId == "investmentTrading") {
      this.answerText = `We offer four modes of investment options. Choose one of the following to see details`;
      this.ButtonHtml = ChatbotButtonTemplates.investmentTradingOptionHtml;
      this.normalHTML = ``;
    } else if (buttonId == "investmentTradingMurabaha") {
      this.answerText = `Bai-Murabaha literally means "a sale at a mutually agreed-upon profit." Thus, it is a contract between a buyer and a seller in which the seller sells particular commodities legal by Islamic Shariah and the law of the land to the buyer at a cost plus agreed-upon profit payable in cash on any fixed future date in lump sum or installments`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ``;
    } else if (buttonId == "investmentTradingMujjal") {
      this.answerText = `Bai-Muajjal literally translates to "credit sale." It is a contract between a buyer and a seller in which the seller sells certain goods (permissible under Shariah and national law) to the buyer at an agreed-upon fixed price payable in lump sum at a certain fixed future date or in fixed installments over a certain length of time. The seller may also sell the goods he purchased according to the Buyer's order and specifications.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ``;
    } else if (buttonId == "investmentTradingSalam") {
      this.answerText = `Bai-Salam refers to a contract in which an advance payment is made for goods to be delivered later on. This is about export financing. Bai-Salam refers to a deal in which the buyer makes an advance payment but delivery is delayed until a later date. Typically, the seller is an individual or corporation, whereas the buyer is a bank. This sale is for products only, not gold, silver, or currencies.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ``;
    } else if (buttonId == "investmentTradingIstishna") {
      this.answerText = `Bai-Istishna is a contractual agreement for manufacturing goods and commodities that allows for cash payment in advance as well as future delivery or payment. Istishna can be used to provide finance for the manufacturing or construction of buildings, plants, projects, bridges, roads, and highways.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ``;
    } else if (buttonId == "investmentPartnership") {
      this.answerText = `Choose one of the following to see details`;
      this.ButtonHtml = ChatbotButtonTemplates.investmentPartnershipOptionHtml;
      this.normalHTML = ``;
    } else if (buttonId == "investmentPartnershipMudarabah") {
      this.answerText = `The term 'Mudaraba' is derived from an Arabic word that signifies 'travel'. Thus, the term 'Mudaraba' denotes 'Travel' for conducting business. A form of partnership where one party provides the funds while the other provides expertise and management. The provider of capital is called "Shahib al-maal", while the provider of skill and labour is called "Mudarib". Any profits accrued are shared between the two parties on a pre-agreed basis, while loss is borne only by the provider of the capital.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ``;
    } else if (buttonId == "investmentPartnershipMusharakah") {
      this.answerText = `The name Musharaka is derived from the Arabic word 'Shirkat' or 'Sharikat' (Shirk). Shirkat, Sharikat, or Shirk are Arabic terms that refer to partnership or sharing. Musharakah means a relationship established under a contract by the mutual consent of the parties for sharing of profits and losses in the joint business. Every partner has to provide more or less equity funds in this partnership business. Both the Bank and the investment client reserve the right to share in the management of the business. But the Bank may opt to permit the investment client to operate the whole business. In practice, the investment client normally conducts the business. The profit is divided between the bank and the investment client at a predetermined ratio. Loss, if any, is to be borne by the bank and the investment client according to capital ratio.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ``;
    } else if (buttonId == "investmentLeasing") {
      this.answerText = `Choose one of the following to see details`;
      this.ButtonHtml = ChatbotButtonTemplates.investmentLeasingOptionHtml;
      this.normalHTML = ``;
    } else if (buttonId == "investmentLeasingHPSM") {
      this.answerText = `Shirkat means partnership. Shirkatul Melk means share in ownership. When two or more persons supply equity, purchase an asset, own the same jointly, and share the benefit as per agreement and bear the loss in proportion to their respective equity, the contract is called Shirkatul Melk contract. Hire Purchase (participatory ownership) mode both the Bank and the client supply equity in equal or unequal proportion for purchase of an asset like land, building, machinery, transport, etc. Purchase the asset with that equity money, own the same jointly; share the benefit as per agreement and bear the loss in proportion to their respective equity. The share, part or portion of the asset owned by the Bank is hired out to the client partner for a fixed rent per unit of time for a fixed period. Lastly the Bank sells and transfers the ownership of its share/ part/ portion to the client against payment of price fixed for that part either gradually part by part or in lump sum within the hired period after the expiry of the hire agreement.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ``;
    } else if (buttonId == "investmentOthers") {
      this.answerText = `Choose one of the following to see details`;
      this.ButtonHtml = ChatbotButtonTemplates.investmentOthersOptionHtml;
      this.normalHTML = ``;
    } else if (buttonId == "investmentOtherOptionQuad") {
      this.answerText = `Quard means investment without profit. It is a mode to provide financial assistance/ investment with the stipulation to return the principal amount in the future without any increase thereon. Here bank just takes the service charge in return.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ``;
    } else if (buttonId == "investmentOtherOptionQuadEHasana") {
      this.answerText = `This is an investment extended on a goodwill basis, and the debtor (client) is only required to repay the amount borrowed. However, the debtor may, at his or her discretion, pay an extra amount beyond the principle amount of the investment (without promising it) as a token of appreciation to the creditor (bank). In the case that the debtor does not pay an extra amount to the creditor, this transaction is a true profit-free investment.`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ``;
    } else if (buttonId == "cardBtn") {
      this.answerText = `Now you can access to your money 24/7 more easily and conveniently through our widespread network of ATMs in Bangladesh. Therefore, your life becomes hassle-free and safe`;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.cardBtnContent;
    } else if (buttonId == "agentBankingBtn") {
      this.answerText = `“First Security Islami Bank PLC. got permission from Bangladesh Bank to commence Agent Banking Services on September 01, 2015. The Agent Banking outlet is running under the ABS system integrated with CBS. The brand name is “FSIB Agent Banking”. It is a mini banking system looking exactly like a model branch where the following services such as Account Opening, Cash Deposit/withdrawal, BEFTN, BACH & RTGS etc. in limited scale ( as per Bangladesh Bank guidelines) are provided. Choose one of the options to see details  `;
      this.ButtonHtml = ChatbotButtonTemplates.agentBankingOptionHtml;
      this.normalHTML = `<a href="https://fsibplc.com/File/Forms/Application%20for%20Agent%20Outlet.pdf" 
   target="_blank" 
   style="text-decoration: none; color: #007BFF; font-size: 15px; font-weight: bold;  transition: background-color 0.3s, color 0.3s;">
   Fill up the form for agent banking
</a>
`;
    } else if (buttonId == "agentBankingAgent") {
      this.answerText = ` `;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.agentBankingAgentContent;
    } else if (buttonId == "agentBankingMasterAgent") {
      this.answerText = ``;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.agentBankingMasterAgentContent;
    } else if (buttonId == "agentBankingUnitAgent") {
      this.answerText = ``;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.agentBankingUnitAgentContent;
    } else if (buttonId == "agentBankingNonEligible") {
      this.answerText = ` `;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.agentBankingNonEligibleContent;
    } else if (buttonId == "agentBankingEligible") {
      this.answerText = ``;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.agentBankingEligibleContent;
    } else if (buttonId == "agentBankingPermissible") {
      this.answerText = ``;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.agentBankingPermissibleContent;
    } else if (buttonId == "agentBankingProhibited") {
      this.answerText = ` `;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
      this.normalHTML = ChatBotHTMLTemplates.agentBankingProhibitedContent;
    } else if (buttonId == "servicesBtn") {
      this.answerText = `Choose one of the following to know more about all of our services`;
      this.ButtonHtml = ChatbotButtonTemplates.servicesOptionHtml;
    } else if (buttonId == "serviceIBFT") {
      this.answerText = `Choose one of the following to see details`;
      // this.ButtonHtml =ChatbotButtonTemplates.serviceIBFTOptionHtml;
      this.ButtonHtml = `<div class="button_group"><a href="https://fsibplc.com/ibft.php" target="_blank" class="custom_button" style="text-decoration:none;font-size:16px"> See more ↗</a> </div>`;
      this.normalHTML = ``;
    } else if (buttonId == "serviceIBFTRTGS") {
      this.answerText = `Choose one of the following to see details`;
      this.ButtonHtml = ChatbotButtonTemplates.serviceIBFTOptionHtml;
      this.normalHTML = ``;
    } else if (buttonId == "digitalBankingBtn") {
      this.answerText = `See all of our digital banking services`;
      this.ButtonHtml = ChatbotButtonTemplates.digitalBankingOptionHtml;
    } else if (buttonId == "callCenter") {
      this.answerText = ``;
      this.normalHTML = ChatBotHTMLTemplates.callCeneterContent;
      this.ButtonHtml = ChatbotButtonTemplates.onlyBackButtonOptionHtml;
    } else if (buttonId == "address") {
      this.answerText = `Rangs RD Center, Block: SE (F), Plot:03, Gulshan Ave, Dhaka 1212 `;
      this.normalHTML = ``;
      this.ButtonHtml = ChatbotButtonTemplates.addressOptionHtml;
    }
    // this.messages.push({ name: "Bot", message: this.answerText });
    // this.bot_messages_count += 1;
    // this.updateChatResponseText(chatbox, this.answerText);
	
	
    this.showLoadingIndicator();
     

    // Simulate a delay to make the typing indicator visible (you can adjust the delay as needed)
    setTimeout(() => {
      this.hideLoadingIndicator(); // Hide typing indicator
      this.messages.push({ name: "Bot", message: this.answerText });
      this.bot_messages_count += 1;
      this.updateChatResponseText(chatbox, this.answerText);
    }, 1500); // 1 second delay
  }
  
  // onSendButton(chatbox) {
  //   // var textField = chatbox.querySelector('input');
  //   const questionField = document.querySelector('input[id="questionBox"]');
  //   let question = questionField.value;
  //   if (question === "") {
  //     return;
  //   }

  //   this.user_messages_count += 1;
  //   this.updateChatUserText(chatbox, question);
  //   this.messages.push({ name: "User", message: question });
  //   questionField.value = "";

  //   let headers = new Headers();
  //   headers.append("Content-Type", "application/json"); //headers.append('GET', 'POST', 'OPTIONS'); //headers.append('Access-Control-Allow-Origin', '*');
  //   //let predict_url = "http://127.0.0.1:5000/predict"; //let predict_url ='http://10.20.42.26:5000/predict'; //let predict_url ='https://bot.fsiblbd.com/predict';
  //   let predict_url =''
     
  //   if(this.clieked_id =='customerYes' || this.clieked_id == 'customerNo'){	
  //       predict_url = "bot_function.php";

	// 	var req_start_time = new Date().getTime(); // console.log("req_start_time == "+ req_start_time);
	// 	console.log("Req start time == " + this.convertMillisecToHrMinSec(req_start_time)); 
		 
	// 	//let dateInWords = new Date(start_time); console.log("/n dateInWords =="+ dateInWords);
	// 	//this.showTypingIndicator();
	// 	fetch(predict_url, {
	// 	  method: "POST",
	// 	  body: JSON.stringify({ message: question, currentCustomer:this.clieked_id}),
	// 	  mode: "cors",
	// 	  headers: headers,
	// 	})
	// 	  .then((r) => r.json())
	// 	  .then((r) => {
			 
	// 		//let response_time = new Date().getTime(); // console.log("request_time=="+request_time);
	// 		//console.log("/n response_time = " + this.convertMillisecToHrMinSec(response_time));
	// 		//let dateInWords2 = new Date(response_time);   console.log("/n dateInWords =="+ dateInWords2);

	// 		//let total_duration = response_time - req_start_time;
	// 		//console.log(  "/n total_duration = " +this.convertMillisecToHrMinSec(total_duration));

	// 		//console.log(" bot response = " + r.answer);
	// 		this.messages.push({ name: "Bot", message: r.answer });
	// 		this.bot_messages_count += 1;
	// 		this.updateChatResponseText(chatbox, r.answer);
  //   this.setupInputListener();

	// 	  })
	// 	  .catch((error) => {
	// 		console.error("Error:", error);
	// 		this.updateChatResponseText(chatbox, "");
  //   this.setupInputListener();

			
	// 	  }); 
	// }else
	// 	{ 
  //     	console.log(this.clieked_id + " in else " );
	//     //this.normalHTML = "<p> </p> "
	// 	this.response = "This part is still under development. Please have patience. We will get back to you soon.";
	// 	this.messages.push({ name: "Bot", message: this.response });
	// 	this.bot_messages_count += 1;
	// 	this.updateChatResponseText(chatbox, this.response);
  //   // this.attachButtonEventListeners(this.args.chatBox);
  //   // this.ButtonHtml = null;
	// }		
  // }
  
//   onSendButton(chatbox) {
//     // Get the question from the input field
//     const questionField = document.querySelector('input[id="questionBox"]');
//     let question = questionField.value.trim();
//     console.log(question);
//     // If the input is empty, do nothing
//     if (question === "") {
//       return;
//     }

//     // Update the message counter and display the user's message
//     this.user_messages_count += 1;
//     this.updateChatUserText(chatbox, question);
//     this.messages.push({ name: "User", message: question });
//     questionField.value = ""; // Clear the input field

//     // Set the request headers
//     let headers = new Headers();
//     headers.append("Content-Type", "application/json");

//     // Define the Rasa API URL (adjust to match your server setup)
//     let predict_url = "http://127.0.0.1:5005/webhooks/rest/webhook"; // example API URL for Rasa

//     // Track the start time for the request
//     var req_start_time = new Date().getTime();
//     console.log("Req start time == " + this.convertMillisecToHrMinSec(req_start_time));

//     // Show loading indicator while waiting for response
//     this.showLoadingIndicator();
//     console.log(JSON.stringify({"sender": "anik", "message": question}))

//     let requestBody = {"sender": "user1", "message": "/fsib_card_features"};

//     // Send the POST request to the Rasa server
//     fetch(predict_url, {
//       method: "POST",
//       body: requestBody,  // send message and sender info
//       mode: "cors",
//       headers: headers,
//     })
//       .then((response) => {console.log(response); return response.json();})
//       .then((r) => {
//         // Hide loading indicator when response is received
//         this.hideLoadingIndicator();

//         // Track the response time
//         let response_time = new Date().getTime();
//         console.log("/n response_time = " + this.convertMillisecToHrMinSec(response_time));

//         let total_duration = response_time - req_start_time;
//         console.log("/n total_duration = " + this.convertMillisecToHrMinSec(total_duration));

//         // Process the bot's response
//         if (r && r.length > 0) {
//           const botMessage = r[0].text;  // Extract the bot's response from the API
//           console.log("Bot response = " + botMessage);
//           this.messages.push({ name: "Bot", message: botMessage });
//           this.bot_messages_count += 1;
//           this.updateChatResponseText(chatbox, botMessage);
//         } else {
//           // If no response, show a default message
//           this.updateChatResponseText(chatbox, "Sorry, I couldn't understand that.");
//         }
//       })
//       .catch((error) => {
//         // Hide the loading indicator and handle errors
//         this.hideLoadingIndicator();
//         console.error("Error:", error);
//         this.updateChatResponseText(chatbox, "There was an error processing your request. Please try again later.");
//       });
// }





//anik modification


onSendButton(chatbox) {
  // Get the question from the input field
  const questionField = document.querySelector('input[id="questionBox"]');
  let question = questionField.value.trim();
  console.log(question);
  // If the input is empty, do nothing
  if (question === "") {
    return;
  }

  // Update the message counter and display the user's message
  this.user_messages_count += 1;
  this.updateChatUserText(chatbox, question);
  this.messages.push({ name: "User", message: question });
  questionField.value = ""; // Clear the input field

  // Set the request headers
  let headers = new Headers();
  headers.append("Content-Type", "application/json");

  // Define the Rasa API URL (adjust to match your server setup)
  let predict_url = "http://127.0.0.1:5005/webhooks/rest/webhook"; // example API URL for Rasa

  // Track the start time for the request
  var req_start_time = new Date().getTime();
  console.log("Req start time == " + this.convertMillisecToHrMinSec(req_start_time));

  // Show loading indicator while waiting for response
  this.showLoadingIndicator();
  console.log(JSON.stringify({ sender: "anik", message: question }));

  // Correctly stringify the request body
  let requestBody = JSON.stringify({ sender: "user1", message: question });

  // Send the POST request to the Rasa server
  fetch(predict_url, {
    method: "POST",
    body: requestBody,  // send message and sender info
    mode: "cors",
    headers: headers,
  })
    .then((response) => {
      console.log(response?.payload);
      return response.json();
    })
    .then((r) => {
      // Hide loading indicator when response is received
      this.hideLoadingIndicator();

      // Track the response time
      let response_time = new Date().getTime();
      console.log("\n response_time = " + this.convertMillisecToHrMinSec(response_time));

      let total_duration = response_time - req_start_time;
      console.log("\n total_duration = " + this.convertMillisecToHrMinSec(total_duration));

      // Process the bot's response
      if (r && r.length > 0) {
        const botMessage = r[0].text;  // Extract the bot's response from the API
        const buttons=r[0].buttons
        console.log(r[0].buttons);
        console.log("Bot response = " + botMessage);
        this.messages.push({ name: "Bot", message: botMessage });
        this.bot_messages_count += 1;
        this.updateChatResponseText(chatbox, botMessage);
      } else {
        // If no response, show a default message
        this.updateChatResponseText(chatbox, "Sorry, I couldn't understand that.");
      }
    })
    .catch((error) => {
      // Hide the loading indicator and handle errors
      this.hideLoadingIndicator();
      console.error("Error:", error);
      this.updateChatResponseText(chatbox, "There was an error processing your request. Please try again later.");
    });
}














  
  /* -------------------------------------------Old function before adding QuestionButton---------------------------------------------- 
  onSendButton(chatbox) {
    // var textField = chatbox.querySelector('input');
    questionField.value = "";
    this.updateSendButtonState();
    const questionField = document.querySelector('input[id="questionBox"]');
    let question = questionField.value.trim();
    if (question === "") {
      return;
    }

    this.user_messages_count += 1;
    this.updateChatUserText(chatbox, question);
    this.messages.push({ name: "User", message: question });
    questionField.value = "";

    let headers = new Headers();
    headers.append("Content-Type", "application/json"); //headers.append('GET', 'POST', 'OPTIONS'); //headers.append('Access-Control-Allow-Origin', '*');
    let predict_url = "http://127.0.0.1:5000/predict"; //let predict_url ='http://10.20.42.26:5000/predict'; //let predict_url ='https://bot.fsiblbd.com/predict';

    var req_start_time = new Date().getTime(); //console.log("req_start_time=="+ req_start_time);
    console.log(
      "Req start time == " + this.convertMillisecToHrMinSec(req_start_time)
    );
    //let dateInWords = new Date(start_time); console.log("/n dateInWords =="+ dateInWords);
    this.showLoadingIndicator();
    fetch(predict_url, {
      method: "POST",
      body: JSON.stringify({ message: question }),
      mode: "cors",
      headers: headers,
    })
      .then((r) => r.json())
      .then((r) => {
        this.hideLoadingIndicator();
        let response_time = new Date().getTime(); // console.log("request_time=="+request_time);
        console.log(
          "/n response_time = " + this.convertMillisecToHrMinSec(response_time)
        );
        //let dateInWords2 = new Date(response_time);   console.log("/n dateInWords =="+ dateInWords2);

        let total_duration = response_time - req_start_time;
        console.log(
          "/n total_duration = " +
            this.convertMillisecToHrMinSec(total_duration)
        );

        console.log(" bot response = " + r.answer);
        this.messages.push({ name: "Bot", message: r.answer });
        this.bot_messages_count += 1;
        this.updateChatResponseText(chatbox, r.answer);
      })
      .catch((error) => {
        this.hideLoadingIndicator();
        console.error("Error:", error);
        this.updateChatResponseText(chatbox, "");
      });
  } */
  
  
  //text and timestamp from user
  updateChatUserText(chatbox, userMessage) {
    var divId = "userMessage" + this.user_messages_count;
    var timestamp = this.getCurrentTimestamp();
    const chatmessage = document.querySelector("#chat-message");

    var html =
      '<img class="" src="./bot-images/user-icon-dark.png" alt="image"  style=" width: 30px; height: 28px; float: right; margin-right: -20px; margin-top: 12px; margin-bottom:1rem">' +
      '<div id= "' +
      divId +
      '" class="messages__item messages__item--operator"> </div>' +
      '<div class="message-time-user">' +
      timestamp +
      "</div>";
    chatmessage.innerHTML += html;

    var i = 0;
    var timer = setInterval(function () {
      //document.getElementsByClassName("messages__item--operator").innerHTML += userMessage.charAt(i);
      document.getElementById(divId).innerHTML += userMessage.charAt(i);
      i++;
      if (i > userMessage.length - 1) {
        clearInterval(timer);
      }
    }, 30);
  }
  //sending response
  updateChatResponseText(chatbox, botResponse) {
    if (this.isSoundOn) {  this.botSound.play(); }
	
    const chatmessage = document.querySelector("#chat-message");
    var divId = "responseMessage" + this.bot_messages_count;
    const html = `
      <div class="response_message">
        <div class="chatbox__image--header">
          <div class="header-avatar-2"></div>
        </div>
        <div id="${divId}" class="messages__item messages__item--visitor" style="text-align:left !important; padding:10px; line-height:1.3"></div>
        <div id="buttonContainer-${divId}"></div>
      </div>
      <div id="timestamp-${divId}" class="message-time-bot"></div>
    `;

    chatmessage.innerHTML += html;

    const responseElement = document.getElementById(divId);
    this.typeContent(responseElement, botResponse)
      .then(() => {
        if (this.normalHTML) {
          this.txt = this.normalHTML;
          this.instructions = [];
          this.i = 0;
          this.j = 0;
          this.recreateNode(this.txt, responseElement);
          return new Promise((resolve) =>
            this.typeWriter(responseElement, resolve)
          );
        }
      })
      .then(() => {
        // Render buttons and timestamp after all typing is complete
        this.renderButtonsAndTimestamp(divId);
      });
  }
  
  
  //
  //
  typeContent(element, content) {
    return new Promise((resolve) => {
      this.typeText(element, content, resolve);
    });
  }
  
  
  //
  //
  attachButtonEventListeners(container) {
    const buttons = container.querySelectorAll(".custom_button");
    buttons.forEach((button) => {
      // Only add event listener if it hasn't been added before
      if (!this.allButtons.has(button)) {
        button.addEventListener("click", () => {
          this.onCustomSendButton(this.args.chatBox, button.id);
          this.scrollToBottom();
        });
        // Add button to the set of all buttons
        this.allButtons.add(button);
      }
    });
  }
  
  //typing normal text
  typeText(element, text, callback) {
    let i = 0;
    const timer = setInterval(() => {
      if (i < text.length) {
        element.innerHTML += text.charAt(i);
        i++;
      } else {
        clearInterval(timer);
        callback();
      }
      this.scrollToBottom();
    }, this.speed);
  }
  
  
  showLoadingIndicator() {
    this.loadingIndicator.style.display = "flex";
    this.scrollToBottom();
  }
  
  
  hideLoadingIndicator() {
    this.loadingIndicator.style.display = "none";
    this.scrollToBottom();
  }
  
  
  //function for auto scroll to bottom
  scrollToBottom() {
    const chatMessages = document.querySelector(".chatbox__messages");
    chatMessages.scrollTop = chatMessages.scrollHeight;
  }
  
  
  //render buttons from html
  renderButtonHtml() {
    const chatmessage = document.querySelector("#chat-message");
    const timestamp = this.getCurrentTimestamp();

    if (this.ButtonHtml) {
      chatmessage.innerHTML += `${this.ButtonHtml}<div class="message-time-bot">${timestamp}</div>`;
      // Attach event listeners to all buttons in the chat message
      this.attachButtonEventListeners(chatmessage);
      this.ButtonHtml = null;
    } else {
      chatmessage.innerHTML += `<div class="message-time-bot">${timestamp}</div>`;
    }
    this.scrollToBottom();
  }
  getCurrentTimestamp() {
    return ChatbotUtils.getCurrentTimestamp();
  }
  
  
  //type normal html content
  typeWriter(container, callback) {
    if (this.j < this.instructions.length) {
      if (typeof this.instructions[this.j][1] === "string") {
        if (this.i < this.instructions[this.j][1].length) {
          this.instructions[this.j][0].innerHTML += this.instructions[
            this.j
          ][1].charAt(this.i);
          this.i++;
          setTimeout(() => this.typeWriter(container, callback), this.speed);
        } else {
          this.j++;
          this.i = 0;
          setTimeout(() => this.typeWriter(container, callback), this.speed);
        }
      } else if (typeof this.instructions[this.j][1] === "object") {
        this.instructions[this.j][0].appendChild(this.instructions[this.j][1]);
        this.j++;
        this.i = 0;
        this.typeWriter(container, callback);
      }
      this.scrollToBottom();
    } else {
      // Typing is complete
      this.normalHTML = null;
      if (callback) callback();
    }
  }
  
  
  renderButtonsAndTimestamp(divId) {
    const buttonContainer = document.querySelector("#buttonContainer-" + divId);
    const timestampElement = document.getElementById(`timestamp-${divId}`);

    if (this.ButtonHtml) {
      buttonContainer.innerHTML = this.ButtonHtml;

      // Animate the appearance of each button
      const buttons = buttonContainer.querySelectorAll(".custom_button");
      buttons.forEach((button, index) => {
        // Initially hide the button
        button.style.opacity = "0";
        button.style.transform = "translateY(20px)";
        button.style.transition =
          "opacity 0.3s ease-out, transform 0.3s ease-out";

        // Animate the button after a delay
        setTimeout(() => {
          button.style.opacity = "1";
          button.style.transform = "translateY(0)";
        }, index * this.buttonAnimationDelay);
      });

      // Attach event listeners to all buttons in the entire chat box
      this.attachButtonEventListeners(this.args.chatBox);
      this.ButtonHtml = null;
    }

    const timestamp = this.getCurrentTimestamp();
    timestampElement.textContent = timestamp;

    this.scrollToBottom();
  }
  
  
  //a function required for typing html
  recreateNode(list, container) {
    const doc = this.parser.parseFromString(list, "text/html");
    doc.body.childNodes.forEach((a) => {
      if (a.nodeName === "#text") {
        this.instructions.push([container, a.nodeValue]);
      } else {
        const b = a.cloneNode(true);
        const c = a.cloneNode(false);
        this.instructions.push([container, c]);
        this.recreateNode(b.innerHTML, c);
      }
    });
  }


  setupInputListener() {
    this.questionBox.addEventListener('input', () => {
      this.updateSendButtonState();
    });
  }
  
  
  //changing send button based on input field
  updateSendButtonState() {
    const hasText = this.questionBox.value.trim() !== '';
    this.sendButton.disabled = !hasText;
    this.whiteSendIcon.style.display = hasText ? 'inline' : 'none';
    this.darkSendIcon.style.display = hasText ? 'none' : 'inline';
  }
}


document.addEventListener("DOMContentLoaded", () => {
  const chatbox = new Chatbox();
  chatbox.display();
});