<template>
  <div class="w-full md:min-w-[350px] max-w-[750px] flex flex-col">
    <div ref="chatWindow" class="w-full overflow-auto h-32 mb-5 bg-gray-300/80 rounded-lg border-2 border-solid border-cyan-200" v-show="gameStore.isChatOpen">
      <div v-for="message in chats" class="flex-col py-2 items-center p-3">
        <span class="text-ellipsis overflow-hidden whitespace-nowrap text-sm">{{ message.character.name }}</span>
        <p class="text-gray-50 m-0">{{ message.message }}</p>
      </div>
    </div>
    <div class="w-full flex">
      <input
        class="w-full h-12 rounded-lg text-lg px-4 py-0 bg-gray-300/80 border-2 border-solid border-cyan-200 text-gray-50 bg-[url('/assets/icons/submit-icon.svg')] bg-no-repeat bg-[right_25px_center] bg-[length:30px] focus:outline-none focus:ring-0 focus:border-cyan-800"
        placeholder="Type something..."
        v-model="message"
        @keypress="handleKeyPress"
        @submit="handleSubmit"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref, nextTick } from 'vue'
import { useGameStore } from '@/stores/game'
import { useNotificationStore } from '@/stores/notifications'
import type { Character } from '@/types'

const gameStore = useGameStore()
const notifications = useNotificationStore()

const message = ref('')
const chats = ref([] as ChatMessage[])
const chatWindow = ref<HTMLElement | null>(null)

const sendMessage = () => {
  if (!message.value.trim()) return
  gameStore.connection?.emit('chat:send_message', { message: message.value }, (response: boolean) => {
    if (!response) {
      notifications.addNotification({ message: 'Failed to send message' })
      return
    }
    message.value = ''
  })
  message.value = ''
}

const handleSubmit = (event: Event) => {
  event.preventDefault()
  sendMessage()
}

const handleKeyPress = (event: KeyboardEvent) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    sendMessage()
  }
}

const scrollToBottom = () => {
  nextTick(() => {
    if (chatWindow.value) {
      chatWindow.value.scrollTop = chatWindow.value.scrollHeight
    }
  })
}

type ChatMessage = {
  character: Character
  message: string
}

onMounted(() => {
  gameStore.connection?.on('chat:message', (data: ChatMessage) => {
    chats.value.push(data)
    scrollToBottom()
  })
  scrollToBottom()
})

onBeforeUnmount(() => {
  gameStore.connection?.off('chat:message')
})
</script>
