<script setup>
import { defineProps, onMounted, nextTick, ref, watch } from "vue";

const scrollRef = ref(null);

const props = defineProps({
  chatList: Array,
});

watch(
  () => props.chatList,
  () => {
    scrollToBottom();
  },
  { deep: true }
);

const scrollToBottom = async () => {
  await nextTick();
  if (scrollRef.value) scrollRef.value.scrollTop = scrollRef.value.scrollHeight;
};

defineExpose({
  scrollToBottom,
});
</script>

<template>
  <div id="scrollRef" ref="scrollRef" class="chat-area">
    <div v-for="item in chatList" :key="item.id" :class="`chat-${item.type}`">
      <div v-if="item.text" class="chat-item">
        {{ item.text }}
      </div>
      <div v-if="!item.text" class="loader">
        <div></div>
        <div></div>
        <div></div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.chat-area {
  position: relative;
  position: fixed;
  width: 100vw;
  max-height: 50vh;
  /* bottom: calc(80px + env(safe-area-inset-bottom)); */
  bottom: calc(65px + env(safe-area-inset-bottom));
  padding: 10px;
  overflow-y: auto;
  box-sizing: border-box;
  mask-image: linear-gradient(to top, black 70%, transparent);
  -mask-image: linear-gradient(to top, black 70%, transparent);
}
.chat-area .chat-gpt {
  display: flex;
  justify-content: start;
}
.chat-area .chat-user {
  display: flex;
  justify-content: end;
}
.chat-item {
  color: white;
  padding: 10px;
  font-size: 14px;
  margin-bottom: 10px;
  display: flex;
  flex-direction: column;
  word-break: break-all;
  position: relative;
  background: rgba(25, 137, 250, 0.8);
  max-width: 45%;
}
.chat-area .chat-gpt .chat-item {
  border-radius: 0 4px 4px 4px;
  background-color: white;
  color: #333;
}
.chat-area .chat-user .chat-item {
  border-radius: 4px 0 4px 4px;
}

.loader {
  display: inline-block;
  position: relative;
  height: 40px;
}

.loader div {
  display: inline-block;
  position: absolute;
  left: 8px;
  width: 12px;
  height: 12px;
  background: white;
  border-radius: 50%;
  animation: loading 1s cubic-bezier(0, 0.5, 0.5, 1) infinite;
}

.loader div:nth-child(1) {
  left: 8px;
  animation-delay: -0.24s;
}
.loader div:nth-child(2) {
  left: 32px;
  animation-delay: -0.12s;
}
.loader div:nth-child(3) {
  left: 56px;
  animation-delay: 0;
}

@keyframes loading {
  0%,
  80%,
  100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}
</style>
