<template>
  <div class="chat-log" ref="chatLog">
    <div
      v-for="(msg, index) in messages"
      :key="index"
      :class="['bubble', msg.role]"
      v-show="msg.content"
    >
      <span>{{ msg.content }}</span>
      <em class="timestamp">{{ msg.createdAt }}</em>
    </div>
  </div>

  <Spinner v-if="isLoading" :overlay="false" />
  <div v-if="isLoading" class="thinking-text">Pensando...</div>
</template>

<script setup>
import {nextTick, ref, watch} from 'vue'
import Spinner from './Spinner.vue'

const props = defineProps({
  messages: {
    type: Array,
    required: true
  },
  isLoading: {
    type: Boolean,
    default: false
  }
})

const chatLog = ref(null)

// Scroll al final cuando se agregan mensajes
watch(() => props.messages.length, async () => {
  await nextTick()
  if (chatLog.value) {
    chatLog.value.scrollTop = chatLog.value.scrollHeight
  }
})

const formatDate = (date) => {
  return dateUtils.formatDate(date)
}
</script>

<style scoped>
.chat-log {
  flex: 1 1 auto;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 1.25rem 1.5rem;
  box-sizing: border-box;
  background-color: #1a1c22;
  border-radius: 16px;
  scrollbar-width: thin;
  scrollbar-color: #5a90ff33 transparent;
}

.chat-log::-webkit-scrollbar {
  width: 6px;
}

.chat-log::-webkit-scrollbar-thumb {
  background-color: #5a90ff55;
  border-radius: 3px;
}

.bubble {
  max-width: 75%;
  padding: 14px 18px;
  border-radius: 20px;
  line-height: 1.5;
  font-size: 1rem;
  word-wrap: break-word;
  user-select: text;
  transition: background-color 0.3s ease, color 0.3s ease;
  opacity: 0;
  transform: translateY(10px);
  animation: slideFadeIn 0.3s forwards;
}

@keyframes slideFadeIn {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.USER {
  background-color: #3451d1;
  align-self: flex-end;
  color: #ffffff;
  border-radius: 20px 20px 4px 20px;
}

.ASSISTANT {
  background-color: #2a2d35;
  align-self: flex-start;
  color: #a4c8ff;
  font-style: italic;
  border-radius: 20px 20px 20px 4px;
}

.timestamp {
  display: block;
  text-align: right;
  font-size: 0.75rem;
  color: #999;
  margin-top: 6px;
  font-style: normal;
  opacity: 0.7;
  user-select: none;
}

.thinking-text {
  text-align: center;
  color: #5a90ff;
  font-style: italic;
  margin-top: 0.5rem;
  font-weight: 600;
  user-select: none;
}
</style>
