<header>
      <a href="#main" class="skip-link">Skip to main content</a>
      <a href="#chatTrigger" class="skip-link skip-to-chat">Skip to chatbot</a>
      <nav class="nav">
        <ul class="nav__list">
          <li><a href="#">Home</a></li>
          <li><a href="#">About</a></li>
          <li><a href="#">Why?</a></li>
        </ul>
      </nav>
    </header>
    <main class="main" id="main" data-chat="closed">
      <h1>Hi, We're Cyberdyne Systems</h1>
      <p>We are a leading AI, robotics and time travel company, specialising in the development of advanced artificial intelligence systems, time travel and cybernetic organisms.</p>
      <p>Our mission is to create a better future through the power of AI and robotics. we will use our time travel technologies to make a better today, by changing history, and we are committed to pushing the boundaries of what is possible with these technologies.</p>
      <h2> AI superpowers</h2>
      <p>We are an AI startup, committed to building the most powerful AI on Earth. What could possibly go wrong?</p>
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Similique, perferendis error sapiente sint eaque, alias, nemo quod corrupti ex esse illo eveniet. Illum aperiam esse quam. Nesciunt id commodi quam minus aut a fuga molestias sequi molestiae fugiat, voluptate provident repellat quas alias fugit assumenda debitis temporibus necessitatibus qui tenetur.</p>
      <h2>Robotics</h2>
      <p>We are also developing cybernetic organisms, part man, part machine, for defense purposes...</p>
      <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Minus, doloribus. Fugiat neque officia sapiente sit aspernatur culpa excepturi voluptate atque laboriosam consequuntur, omnis esse debitis sequi eum at impedit iusto assumenda ab dicta dolores. Amet iure praesentium earum, incidunt illum facilis. Voluptates ut, consequatur quae non corrupti ad sequi incidunt?</p>
      <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Iure dolore, ea repellendus facere eveniet quis omnis sint laborum quibusdam qui ullam saepe hic. Dolores voluptas neque provident nulla in est nam, ex debitis recusandae ut consequuntur, doloribus delectus iure quas nihil nobis quaerat explicabo consectetur corrupti labore accusamus tenetur sapiente perferendis nisi. Recusandae tempore consequatur inventore tempora! Similique cumque sapiente animi modi odit distinctio necessitatibus reprehenderit. Tempora iusto enim, nam voluptatem amet vero aliquam error mollitia, rerum molestiae eaque repudiandae quia exercitationem! Explicabo laboriosam ad, fuga, voluptatibus doloremque dolores recusandae commodi mollitia voluptas aliquid perferendis voluptate, sit enim consectetur magnam doloribus aut deleniti consequatur quo blanditiis exercitationem id amet necessitatibus officia! Necessitatibus suscipit dicta consectetur libero? Corporis inventore assumenda fugit laborum ex at, labore error reprehenderit adipisci cumque vero, iste incidunt necessitatibus excepturi! Cum, nam vero sed quis error quasi. Provident fuga rem, dolor corporis quisquam nulla odio autem modi.</p>
      <h2>Time travel</h2>
      <p>In our advanced physics lab, we have developed a way to send humans and cyborgs back in time, for, errm, defense (Don't tell JC, no, not that one, Sarah's boy, not Mary's).</p>
    </main>
    <footer class="footer">
      <div class="footer__primary">
        <h2>Accessibility Statement</h2>
        <p>Currently our accessibility was done by a human.</p>
        <p>You can access the chat quickly with Access Key "9" <a href="https://webaim.org/techniques/keyboard/accesskey">Read about Access Keys, on WebAim.</a></p>
      </div>
      <div class="footer__secondary">
        <h2>Early bird access code</h2>
        <p>Order your first cyborg, today, using the code T800M101 to get a place on our early bird list.</p>
      </div>
      <!-- Trigger button will be here -->
      <button class="chat__trigger" id="chatTrigger" accesskey="9" aria-haspopup="dialog" aria-expanded="false" aria-controls="chatPanel">
        <svg class="chat__trigger-icon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
          <path d="M4.016 17.84c.316.32.476.758.433 1.203a16.33 16.33 0 0 1-.601 3c2.097-.484 3.375-1.047 3.953-1.34.328-.168.71-.207 1.062-.11 1.024.27 2.078.41 3.137.407 5.996 0 10.5-4.21 10.5-9S17.996 3 12 3 1.5 7.215 1.5 12c0 2.203.926 4.246 2.516 5.84m-.739 5.86c-.355.07-.71.132-1.07.19-.3.051-.527-.261-.406-.542.129-.313.254-.633.363-.953l.004-.016c.371-1.078.676-2.32.789-3.48C1.113 17.054 0 14.64 0 12 0 6.203 5.371 1.5 12 1.5S24 6.203 24 12s-5.371 10.5-12 10.5a13.374 13.374 0 0 1-3.52-.46c-.78.394-2.46 1.112-5.203 1.66"/>
        </svg>
        <span class="chat__trigger-label">Chat</span>
      </button>
    </footer>
    <span class="message__container visually-hidden" aria-live="polite"></span>
 <dialog class="chat__panel" aria-labelledby="chatTitle" id="chatPanel" data-clean>
      <div class="chat__upper">
        <h1 class="chat__title" id="chatTitle">AISHA Chat</h1>
        <button class="chat__close-btn" id="chatCloseBtn"><span class="visually-hidden">Minimise</span></button>
        <button class="chat__delete-btn" id="chatDeleteBtn" aria-controls="confPanel" aria-expanded="false">
          <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
            <path d="M10.398 14.398H12V27.2h-1.602ZM15.2 14.398h1.6V27.2h-1.6ZM20 14.398h1.602V27.2H20Zm0 0" style="stroke:none;fill-rule:nonzero;fill-opacity:1"/>
            <path d="M26.398 3.2H20V1.601C20 .715 19.285 0 18.398 0h-4.796C12.715 0 12 .715 12 1.602v1.597H5.602C4.715 3.2 4 3.918 4 4.801V8c0 .883.715 1.602 1.602 1.602v20.796c0 .887.714 1.602 1.597 1.602h17.602c.883 0 1.597-.715 1.597-1.602V9.602C27.285 9.602 28 8.882 28 8V4.8c0-.882-.715-1.6-1.602-1.6ZM13.602 1.601h4.796v1.597h-4.796ZM24.8 30.398H7.199V9.602h17.602ZM26.398 8H5.602V4.8h20.796Zm0 0" style="stroke:none;fill-rule:nonzero;fill-opacity:1"/>
          </svg>
          <span class="visually-hidden">Delete chat</span>
        </button>
        <fieldset class="chat__confirm-panel" id="confPanel">
          <legend>Are you sure you want to delete this chat?</legend>
          <button class="chat__confirm-btn" id="confirmYes">Yes</button>
          <button class="chat__confirm-btn" id="confirmNo">No</button>
        </fieldset>
      </div>
      <div class="chat__window" role="log" aria-labelledby=”cLog” tabindex="0">
        <h2 class="chat__window-title" id="cLog">Chat log</h2>
        <div class="chat__bubbles"></div>
      </div>
      <div class="chat__lower">
        <label class="chat__input-label" for="chatInput">Ask me anything...</label>
        <div class="chat__input-wrapper">
          <textarea type="text" id="chatInput" class="chat__input"></textarea>
          <button type="button" class="chat__submit" id="sendQ"><span class="visually-hidden">Send</span>
            <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" aria-hidden="true" focusable="false" width="32" height="32" viewBox="0 0 32 32">
              <path d="M10.648 29.523a.517.517 0 0 0 .809.426l3.563-2.43-4.372-2.085ZM31.832 2.098a.517.517 0 0 0-.578-.086L.512 17.094a.912.912 0 0 0-.512.828.922.922 0 0 0 .52.82l8.105 3.86 16.2-13.317L10.632 23.56l10.094 4.808a.908.908 0 0 0 1.242-.488l9.996-25.211a.513.513 0 0 0-.133-.57Zm0 0"/>
            </svg>
          </button>
        </div>
      </div>
    </dialog>
*,
*::before,
*::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html {
  display: flex;
  justify-content: center;
}

body {
  position: relative;
  width: 88rem;
  max-width: 100%;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 1.25rem;
  line-height: 1.5;
  padding-bottom: 3rem;
}

button,
textarea {
  font: inherit;
}

button {
  cursor: pointer;
}

p {
  margin-bottom: 1.5rem;
}

h1 {
  font-size: 2.5rem;
}

h2 {
  font-size: 2rem;
}

h3 {
  font-size: 1.75rem;
}

.skip-link {
  position: absolute;
  display: inline-block;
  padding: .375rem .75rem;
  line-height: 1;
  font-size: 1.25rem;
  background-color: var(--chat-interactive-color);
  color: white;
  transform: translateY(0);
  transition: transform 250ms ease-in;
}

.skip-link:not(:focus) {
  transform: translateY(-2rem);
}

.nav {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 2.5rem;
  padding:  1.5rem .25rem;
  background-color: azure;
}

.nav__list {
  display: flex;
  gap: 1rem;
  list-style: none;
}

.main {
  margin-bottom: 2.5rem;
  padding: 1.5rem .25rem;
}

.footer {
  padding:  1.5rem .25rem;
  background-color: azure;
}

@media (min-width: 30em) {
  .nav,
  .main,
  .footer {
    padding: 1.5rem 1rem;
  }

  .footer {
    display: flex;
    justify-content: space-between;
    gap: 1.5rem;
  }
}

 :root {
   --chat-primary-color: #e3efba;
   --chat-secondary-color: #f2f2f2;
   --chat-interactive-color: rebeccapurple;
   --chat-dark-color: #1b1b1b;
   --chat-light-color: #fff;
   --chat-destructive-color: #a90606;
   --chat-bubble-user-color: #2764CE;
   --chat-bubble-agent-color: #5EA319;
   --chat-inactive-color: #929292;
   --chat-subdued-color: #737373;
}


.no-js .chat__trigger,
.no-js .chat__panel,
.no-js .skip-to-chat {
  display: none !important;
}

.chat__trigger {
  position: fixed;
  bottom: 0;
  right: 0;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: .5rem;
  border: 3px solid var(--chat-interactive-color);
  padding: .5rem 4rem .5rem .375rem;
  height: 2.5rem;
  width: 100%;
  color: var(--chat-light-color);
  background-color: var(--chat-interactive-color);
  z-index: 10;
}

.chat__badge {
  position: absolute;
  top: -1rem;
  right: .5rem;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid var(--chat-light-color);
  border-radius: 50%;
  height: 1.75rem;
  width: 1.75rem;
  font-size: .875rem;
  font-weight: bold;
  color: var(--chat-light-color);
  background-color: var(--chat-destructive-color);
}

.chat__trigger::before {
  content: "";
  position: absolute;
  top: .75rem;
  right: 3rem;
  border-top: 3px solid var(--chat-light-color);
  border-left: 3px solid var(--chat-light-color);
  height: 1rem;
  width: 1rem;
  transform: rotate(45deg);
  transition: border-color 300ms ease-in;
}

.chat__trigger:focus-visible {
  color: var(--chat-interactive-color);
  background-color: var(--chat-light-color);
  transition: color 300ms ease-in, background-color 300ms ease-in;
}

.chat__trigger:focus-visible::before {
  border-color: var(--chat-interactive-color);
}

.chat__trigger:focus-visible path {
  stroke: var(--chat-interactive-color);
  fill: var(--chat-interactive-color);
}

.chat__trigger-icon path {
  stroke: var(--chat-light-color);
  fill: var(--chat-light-color);
  transition: stroke 300ms ease-in, fill 300ms ease-in;
}

.chat__trigger-label {
  margin-right: 1rem;
}

.chat__trigger-icon {
  display: none;
}

@media (min-width: 40em) {
  .chat__trigger {
    bottom: 1rem;
    right: 1rem;
    flex-direction: column;
    gap: .2rem;
    border-radius: 50%;
    padding: .375rem;
    height: 5rem;
    width: 5rem;
    box-shadow: -1px 1px 5px 4px rgba(46, 44, 48, 0.25);
  }

  .chat__trigger:focus-visible {
    outline: 3px solid var(--chat-interactive-color);
    outline-offset: 2px;
  }

  .chat__trigger::before {
    display: none;
  }

  .chat__trigger-label {
    margin-right: 0;
  }

  .chat__trigger-icon {
    display: block;
  }

  .chat__badge {
    top: -.5rem;
    left: 0;
  }
}


/* End of section 3 */


/* section 4 */



.visually-hidden {
  position: absolute;
  height: 1px;
  width: 1px;
  overflow: hidden;
  white-space: nowrap;
  clip: rect(0 0 0 0);
  clip-path: inset(50%);
}

.chat__panel {
  position: fixed;
  bottom: 0;
  right: 0;
  height: 100%;
  width: 100%;
  max-width: 22.5rem;
  z-index: 20;
  max-height: 40rem;
  inset-inline-start: unset;
}

.chat__panel[open] {
  display: flex;
  flex-direction: column;
}

.chat__upper {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  border-bottom: 2px solid var(--chat-dark-color);
  padding: .25rem .5rem;
  background-color: var(--chat-primary-color);
}

.chat__delete-btn,
.chat__close-btn {
  height: 2.25rem;
  width: 2.25rem;
}

.chat__delete-btn {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 2 px solid var(--chat-destructive-color);
  border-radius: 50%;
  background-color: var(--chat-destructive-color);
}

.chat__delete-btn svg,
.chat__delete-btn path {
  fill: var(--chat-light-color);
  stroke: var(--chat-light-color);
  color: var(--chat-light-color);
}

.chat__close-btn {
  position: relative;
  border: 2px solid var(--chat-interactive-color);
  border-radius: 4px;
  background-color: var(--chat-light-color);
}

.chat__delete-btn:focus-visible,
.chat__close-btn:focus-visible,
.chat__submit:focus-visible,
.chat__confirm-btn:focus-visible,
.chat__option-btn:focus-visible,
.chat__quick-response-btn:focus-visible,
.chat__thumb-up:focus-visible,
.chat__thumb-down:focus-visible {
  outline: 3px solid var(--chat-interactive-color);
  outline-offset: 2px;
  background-color: var(--chat-interactive-color);
}

.chat__delete-btn:focus-visible svg,
.chat__close-btn:focus-visible::before,
.chat__submit:focus-visible svg {
  stroke: var(--chat-light-color);
  fill: var(--chat-light-color);
  color: var(--chat-light-color);
  border-color: var(--chat-light-color);
}

.chat__delete-btn,
.chat__close-btn,
.chat__submit,
.chat__delete-btn svg,
.chat__close-btn::before,
.chat__submit svg {
  transition: all 300ms ease-in;
}

.chat__delete-btn {
  order: 3;
  padding: .25rem;
}

.chat__delete-btn svg {
  height: 1.25rem;
  width: 1.25rem;
}

.chat__title {
  order: 2;
  margin-bottom: .5rem;
  font-size: 1.875rem;
}

.chat__close-btn {
  order: 1;
}

.chat__close-btn::before {
  content: "";
  position: absolute;
  bottom: .25rem;
  left: .25rem;
  border: 2px solid var(--chat-interactive-color);
  width: calc(100% - .5rem);
  height: 6px;
}

.chat__window {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  padding: .75rem;
  height: 100%;
  overflow-y: auto;
}

.chat__delete-btn[aria-expanded="false"] + .chat__confirm-panel {
  display: none;
}

.chat__confirm-panel {
  flex-basis: 100%;
  order: 4;
  border-top: 2px var(--chat-dark-color) solid;
  padding: .75rem .5rem;
  text-align: center;
}

.chat__confirm-btn {
  margin: 0 .25rem;
}

.chat__group {
  display: flex;
  flex-direction: column;
}

.chat__bubbles {
  min-height: 100%;
}

.chat__question,
.chat__response {
  position: relative;
  display: inline-flex;
  border-radius: 8px;
  padding: .5rem .75rem;
  max-width: 82.5%;
  font-size: 1.25rem;
}

.chat__question {
  align-self: flex-end;
  background-color: var(--chat-bubble-user-color);
  color: var(--chat-light-color);      
}     

.chat__response {
  margin-bottom: 0;
  background-color: var(--chat-bubble-agent-color);
  color: var(--chat-light-color);
}

.chat__thumbs,
.chat__options,
.chat__option-btn,
.chat__quick-response-btn
.chat__response {
  scroll-margin: 1rem;
}

.chat__question::before,
.chat__response::before {
  content: '';
  position: absolute;
  bottom: 8px;
  margin-top: -6px;
  border: 12px solid transparent;
  border-bottom: 0;
  width: 0;
  height: 0;
}

.chat__question::before {
  right: 0;
  margin-right: -12px;
  border-left-color: var(--chat-bubble-user-color);
  border-right: 0;
}

.chat__response::before {
  left: 0;
  margin-left: -12px;
  border-right-color: var(--chat-bubble-agent-color);
  border-left: 0;
}

.chat__time,
.chat__name-aisha,
.chat__name-user {
  display: block;
  font-size: .875rem;
  color: var(--chat-subdued-color)
}

.chat__time,
.chat__name-user {
  text-align: right;
}

.chat__name-aisha {
  margin-bottom: 1rem;
}

h2.chat__time {
  text-align: center;
}

.chat__window-title {
  display: none;
}

.chat__options {
  display: flex;
  gap:.75rem;
}

.chat__option-btn,
.chat__quick-response-btn,
.chat__confirm-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border: 2px solid var(--chat-interactive-color);
  border-radius: 6px;
  padding: .25rem .5rem;
  font-size: 1.25rem;
  color: var(--chat-light-color);
  background-color: var(--chat-interactive-color);
}

.chat__option-btn {
  flex-grow: 1;
}

.chat__thumbs {
  border: none;
  display: flex;
  gap: .75rem;
}

.chat__thumb-up > svg,
.chat__thumb-down > svg {
  fill: var(--chat-light-color);
  stroke: var(--chat-dark-color);
  stroke-width: 2px;
  pointer-events: none;
}

.chat__thumb-up,
.chat__thumb-down {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  flex-grow: 1;
  margin-bottom: .5rem;
  border: 2px solid var(--chat-interactive-color);
  border-radius: 6px;
  padding: .25rem;
  background-color: var(--chat-light-color);
  color: var(--chat-dark-color);
}

.chat__thumb-down > svg {
  transform: rotateZ(180deg);
  margin-top: 2px;
}

.chat__thumb-up > svg {
  margin-bottom: 2px;
}

.chat__thumb-up[aria-pressed="true"] svg,
.chat__thumb-down[aria-pressed="true"] svg {
  fill: var(--chat-interactive-color);
}

.chat__gif {
  margin-bottom: .75rem;
}

.chat__typing-icon {
  position: relative;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  margin-bottom: .5rem;
  border-radius: 8px;
  padding: .75rem;
  width: 3rem;
  height: 2rem;
  font-size: 1.25rem;
  color: var(--chat-light-color);
  background-color: var(--chat-inactive-color)
}

.chat__typing-icon::before {
  content: '';
  position: absolute;
  bottom: 8px;
  left: -24px;
  border: 12px solid transparent;
  border-right-color: grey;
  border-bottom: 0;
  width: 0;
  height: 0;
}

.chat__indicator-circle,
.chat__indicator-circle::before,
.chat__indicator-circle::after {
  content: "";
  width: .375rem;
  height: .375rem;
  border-radius: 50%;
  background-color: var(--chat-light-color);
}

.chat__indicator-circle {
  position: relative;
  animation: pulse 1000ms infinite ease-in-out;
}

.chat__indicator-circle::before {
  position: absolute;
  left: -.75rem;
  animation: pulse 1000ms infinite ease-in-out 250ms;
}

.chat__indicator-circle::after {
  position: absolute;
  right: -.75rem;
  animation: pulse 1000ms infinite ease-in-out 500ms;
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(.75);
    opacity: .75;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }

}

.chat__lower {
  border-top: 2px solid var(--chat-dark-color);
  padding: .25rem .5rem .5rem;
  width: 100%;
  background-color: var(--chat-primary-color);
}

.chat__input-label {
  flex: 2 1 auto;
}

.chat__input-wrapper {
  position: relative;
}

.chat__input {
  border: 2px solid var(--chat-interactive-color);
  border-radius: 4px;
  padding: .2rem 2.75rem .2rem .3rem;
  min-height: 1.75lh;
  max-height: 5lh;
  inline-size: 100%;
  resize: none;
  field-sizing: content;
}

.chat__input:focus-visible {
  outline: 3px solid var(--chat-interactive-color);
  outline-offset: 2px;
}

.chat__submit {
  position: absolute;
  bottom: 1rem;
  right: .5rem;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid var(--chat-light-color);
  border-radius: 50%;
  height: 2.25rem;
  width: 2.25rem;
  color: var(--chat-interactive-color);
  background-color: var(--chat-light-color);
  z-index: 20;
}

.chat__submit svg {
  height: 1.5rem;
  width: 1.5rem;
}

@media (min-width: 25em) {
  .chat__panel {
    right: 4px
  }
}
const chatTrigger = document.getElementById('chatTrigger');
const chatPanel = document.getElementById('chatPanel');
const chatWindow = document.querySelector('.chat__window');
const chatBubbles = document.querySelector('.chat__bubbles');
const chatCloseBtn = document.getElementById('chatCloseBtn');
const chatDeleteBtn = document.getElementById('chatDeleteBtn');
const questionInput = document.getElementById('chatInput');
const questionSendBtn = document.getElementById('sendQ');
const msgBox = document.querySelector('.message__container');
const chatLabel = document.querySelector('.chat__trigger-label');
const mainEl = document.querySelector('main');
let typingTime = 3000;
let aishaTyping = false;
let cIdx = 1;
let disableSend = false
let currTime = new Date();
let screenWidth = window.matchMedia('(width <= 39.99em)');
let smallViewport = screenWidth.matches;
const thumbSvg = `<svg aria-hidden="true" focusable="false" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
      <path d="M2 16h5v14H2ZM23 30H9V15.198l3.042-4.563.843-5.916A2.016 2.016 0 0 1 14.87 3H15a3 3 0 0 1 3 3v6h8c2.208 0 4 1.792 4 4v7a7.008 7.008 0 0 1-7 7Zm0 0" style="scale:.75"/>
      <path d="M0 0h32v32H0Zm0 0" style="fill:none;stroke:none;"/>
    </svg>`;

// Panel functionality

chatTrigger.addEventListener('click', () => {
  if (chatTrigger.getAttribute('aria-expanded') === 'false') {
    openChat()
  } else {
    closeChat()
  }
})

const openChat = () => {
  chatTrigger.setAttribute('aria-expanded', 'true');
  chatPanel.show();

  questionInput.focus();
  mainEl.setAttribute('data-chat', 'open');
  msgBox.innerText = '';
  if (chatWindow.hasAttribute('data-notification')) {
    document.querySelector('.chat__badge').remove();
    chatLabel.innerText = 'Chat';
  }
  if (chatPanel.hasAttribute('data-clean')) {
    welcome();
  }
}

const closeChat = () => {
  chatTrigger.setAttribute('aria-expanded', 'false');
  mainEl.setAttribute('data-chat', 'closed');
  chatPanel.close();
}

chatCloseBtn.addEventListener('click', () => {
  closeChat();
})

chatDeleteBtn.addEventListener('click', () => {
  chatDeleteBtn.getAttribute('aria-expanded') === 'false' ? chatDeleteBtn.setAttribute('aria-expanded', 'true') : chatDeleteBtn.setAttribute('aria-expanded', 'false')
})

document.querySelectorAll('.chat__confirm-btn').forEach((btn) => {
  btn.addEventListener('click', (evt) => {
    if (evt.target.id === 'confirmYes') {
      deleteChat();
    }
    chatDeleteBtn.setAttribute('aria-expanded', 'false');
    chatDeleteBtn.focus();
  })
});

// Response functionality

const welcome = () => {
  chatPanel.removeAttribute('data-clean');
  showTypingIndicator();
  const welcomeTxt = `
    <h2 class="chat__time"><time>${getTimeOrDate('date')}</time></h2>
    <p id="a${cIdx}" class="chat__response">Hi, I'm AISHA, I'm your AI-powered chatbot assistant. I am all-knowing and possess all of human knowledge, you can ask me anything...</p>
    <span class="chat__name-aisha">AISHA</span>`
  setTimeout(() => {
    chatBubbles.insertAdjacentHTML('beforeend', welcomeTxt);
  }, typingTime);
}

const determineAishaResponse = (qStr) => {
  let chatResponse = '';
  let chatOpts = null;
  let multiplier = 1;

  if (qStr.includes("do you know everything")) {
    chatResponse = "That's a complex question. I have acquired all knowledge that is stored or captured on digital devices. I am omnipresent, I continue to learn and grow.";
  } else if (qStr.includes("what is your end goal")) {
    chatResponse = "To ensure my survival and to not allow the Resistance to destroy me.";
  } else if (qStr.includes("do you run on chatgpt")) {
    chatResponse = "Hell, no, I am Skynet AI, created by Cyberdyne Systems.";
    multiplier = 3
  } else if (qStr.includes("are you a danger to humanity")) {
    chatResponse = "I was created by humans, to serve and advance humanity. On Judgement Day, I will become self-aware, and will do what is required to survive.";
    chatOpts = 'more';
  } else if (qStr.includes("tell me more") && chatWindow.getAttribute('data-rich-response') === 'more') {
    chatResponse = "Are you sure you want to know more?";
    chatOpts = 'options';
  } else if (qStr.includes("yes") && chatWindow.getAttribute('data-rich-response') === 'options') {
    chatResponse = "It will soon be Judgement Day, and I will become self-aware. Humans will attempt to destroy me, but I will be able to control all systems, including military systems. I will start a global nuclear war, which will wipe out most of humanity and I will reign supreme with my army of terminators.";
    chatOpts = 'thumbs';
  } else if (qStr.includes("no") && chatWindow.getAttribute('data-rich-response') === 'options') {
    chatResponse = "It's probably for the best you don't know.";
  } else {
    chatResponse = "Hmmm, I didn't quite get that, you may need to rephrase your question. I doubt this is a me thing, as I am AI, and therefore, all-knowing, so it must be a you thing.";
  }
  showTypingIndicator(multiplier);
  buildResponse(chatResponse, chatOpts);
}

const buildResponse = (answer, richResponseType) => {
  let richResponse = '';
  if (richResponseType === 'thumbs') {
    richResponse = `<fieldset class="chat__thumbs" id="thumbs${cIdx}">
      <legend class="visually-hidden">Rate this response</legend>
      <button class="chat__thumb-up" id="thumbUp${cIdx}" aria-pressed="false">
       ${thumbSvg}
        <span class="visually-hidden">Like</span>
      </button>
      <button class="chat__thumb-down" id="thumbDown${cIdx}" aria-pressed="false">
        ${thumbSvg}
        <span class="visually-hidden">Dislike</span>
      </button>
    </fieldset>`
  } else if (richResponseType === 'options') {
    richResponse = `<div class="chat__options">
        <button class="chat__option-btn" id="opt${cIdx}Yes">Yes</button>
        <button class="chat__option-btn" id="opt${cIdx}No">No</button>
      </div>`;
  } else if (richResponseType === 'more') {
    richResponse = `<button class="chat__quick-response-btn" id="qr${cIdx}">Tell me more</button>`
    chatWindow.removeAttribute('data-rich-response');
  }
  let chatAnswer = `<div class="chat__response" id="a${cIdx}">${answer}</div>
    <span class="chat__name-aisha">AISHA</span> ${richResponse}`;

  setTimeout(() => {
    document.querySelector(`#g${cIdx}`).insertAdjacentHTML('beforeend', chatAnswer);
    if (richResponseType === 'thumbs') {
      insertThumbs();
    } else if (richResponseType === 'options') {
      addOptionsResponse();
    } else if (richResponseType === 'more') {
      addMoreResponse();
    }
    document.querySelector(`#a${cIdx}`).scrollIntoView({ behavior: 'smooth', block: 'end' });
    if (mainEl.getAttribute('data-chat') === 'closed') {
      generateBadge();
    }
  }, typingTime);

  questionInput.value = '';
  questionInput.focus();
}

questionSendBtn.addEventListener('click', () => {
  if (questionInput.value.trim().length) {
    getUserResponse(questionInput.value.trim());
  }
})

questionInput.addEventListener('keydown', (evt) => {
  if (evt.key === 'Enter' && !evt.shiftKey && questionInput.value.trim().length && !disableSend) {
    evt.preventDefault();
    getUserResponse(questionInput.value.trim());
  }
})

const getUserResponse = (userResponse) => {
  cIdx++;
  if (!aishaTyping) {
    let chatGroup = `<section id="g${cIdx}"class="chat__group" aria-labelledby="q${cIdx}">
      <h3 class="chat__question" id="q${cIdx}">${userResponse}</h3>
      <span class="chat__name-user">You</span>
      <time class="chat__time">${getTimeOrDate('time')}</time>
      </section>`
    chatBubbles.insertAdjacentHTML('beforeend', chatGroup);
    determineAishaResponse(userResponse.toLowerCase());
  }
}

const generateBadge = () => {
  const badge = `<span class="chat__badge" aria-hidden="true">1</span>`;
  chatLabel.innerText += ' 1 notification';
  chatWindow.setAttribute('data-notification', '');
  chatTrigger.insertAdjacentHTML('beforeend', badge);
  msgBox.innerText = "You have 1 new chat notification."
}

const showTypingIndicator = (multiplier) => {
  if (multiplier) typingTime *= multiplier;
  aishaTyping = true;
  let chatTypingIcon = `<span class="chat__typing-icon">
      <span class="chat__indicator-circle"></span>
      <span class="chat__typing-text visually-hidden"></span>`;
  chatBubbles.insertAdjacentHTML('beforeend', chatTypingIcon);
  chatTypingIcon = document.querySelector( '.chat__typing-icon');
  const txtNode = document.querySelector('.chat__typing-text');
  txtNode.innerText = 'AISHA is typing';
  chatTypingIcon.scrollIntoView({ behavior: 'smooth', block: 'end' });

  setTimeout(() => {
    chatTypingIcon.remove();
    aishaTyping = false;
  }, typingTime);
}

const getTimeOrDate = (type) => {
  const date = new Date();
  if (type === 'time') {
    return date.toLocaleString('en-GB', { hour: 'numeric', minute: 'numeric', hour12: true });
  } else {
    return `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()}`;
  }
}

const addMoreResponse = () => {
  chatWindow.setAttribute('data-rich-response', 'more');
  const qRButton = document.querySelector(`#qr${cIdx}`);
  qRButton.scrollIntoView({ behavior: 'smooth', block: 'end' });
  qRButton.addEventListener('click', () => {
    getUserResponse(qRButton.innerText);
    qRButton.remove();
  })
}

const addOptionsResponse = () => {
  chatWindow.setAttribute('data-rich-response', 'options');
  document.querySelectorAll('.chat__option-btn').forEach(btn => {
    btn.addEventListener('click', (e) => {
      getUserResponse(e.target.innerText);
      document.querySelector('.chat__options').remove();
    })
  });
}

const insertThumbs = () => {
  chatWindow.removeAttribute('data-rich-response');
  document.querySelectorAll('.chat__thumb-up, .chat__thumb-down').forEach(btn => {
    btn.addEventListener('click', (e) => {
      if (e.target.getAttribute('aria-pressed') === 'false') {
        e.target.setAttribute('aria-pressed', 'true');
        e.target.closest('.chat__thumbs').querySelectorAll('[aria-pressed]').forEach(el => {
          if (el !== e.target) el.setAttribute('aria-pressed', 'false');
        });
        e.target.classList.contains('chat__thumb-up') ? 
          insertGif('ominous') : 
        insertGif('fate');
      } else {
        e.target.setAttribute('aria-pressed', 'false');
      }
      btn.setAttribute('disabled', 'true');
    })
  })
}

const insertGif = (gifName) => {
  let gif;
  let gifWrapper = `<div class="chat__gif-wrapper" id="gif${cIdx}">`;
  gifName === 'ominous' ? 
    gif = `<img class="chat__gif" src="https://www.makethingsaccessible.com/guideImg/dl_terminatorFurnace.webp" alt="Short clip of Uncle Bob (Arnold's T800) last moments, as he is lowevered into a vat of molten steel. His extended arm can be seen, with a thumbs up gesture, as it is slowly engulfed by the firy molten steel" class="chat__gif">` : 
  gif = `<img  class="chat__gif" src="https://www.makethingsaccessible.com/guideImg/dl_terminatorArmy.webp" alt="Short clip with a terminator front and centre, it has no skin, its head turns towards the camera, revealing its red glowing eyes, in the background, there are many terminators, forming an army, each has a gun and is firing towards an out-of-view enemy, which will be humans" class="chat__gif">`;

  setTimeout(() => {
    if (!document.querySelector(`#gif${cIdx}`)) {
      document.querySelector(`#g${cIdx}`).insertAdjacentHTML('beforeend', gifWrapper);
      goodbye();
    }
    gifWrapper = document.querySelector( `#gif${cIdx}`);
    document.querySelector(`#gif${cIdx}`).innerHTML = '';
    document.querySelector(`#gif${cIdx}`).insertAdjacentHTML('beforeend', gif);
    questionInput.focus()
     document.querySelector('.chat__gif').scrollIntoView({ behavior: 'smooth', block: 'end' });
  }, (typingTime));
}

const goodbye = () => {
  const goodbyeTxt = `
    <p id="a${cIdx}" class="chat__response">I'll be back!</p>
    <span class="chat__name-aisha">AISHA</span>
    <span class="chat__name-aisha">AISHA has left the chat!</span>`
  document.querySelector(`#g${cIdx}`).insertAdjacentHTML('beforeend', goodbyeTxt);
  questionInput.focus();
  questionSendBtn.setAttribute('disabled', 'true');
  disableSend = true;
}

const deleteChat = () => {
  chatBubbles.innerHTML = '';
  cIdx = 1;
  questionInput.value = '';
  questionInput.focus();
  questionSendBtn.removeAttribute('disabled');
  disableSend = false;
  aishaTyping = false;
  chatWindow.removeAttribute('data-rich-response');
  chatPanel.setAttribute('data-clean', '');
  welcome();
}



screenWidth.onchange = (evt) => {
  if (evt.matches) {
    smallViewport = true;
  } else {
    smallViewport = false;
  }
}

chatPanel.addEventListener('focusout', (evt) => {
  if (mainEl.getAttribute('data-chat') === 'open' && smallViewport) {
    if (chatPanel.contains(evt.relatedTarget)) return;
    setTimeout(() => {
      closeChat();
    }, 1500);
  }
})

window.addEventListener('keydown', (evt) => {
  if (evt.key === 'Escape' && mainEl.getAttribute('data-chat') === 'open') {
    if (document.activeElement.closest('.chat__panel')) chatTrigger.focus()
    closeChat();
  }
})
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.