<script setup lang="ts">
// 회의실 채팅 — 데이터 채널 메시지 목록 + 입력. 새 메시지 도착 시 맨 아래로 스크롤.
import { nextTick, ref, watch } from 'vue'
import MeetingIcon from './MeetingIcon.vue'
import UserAvatar from '@/components/UserAvatar.vue'
import { MAX_CHAT_LENGTH } from '@/composables/useLiveKitRoom'
import type { ChatMessage } from '@/types/meeting'

interface Props {
  messages: ChatMessage[]
}
const props = defineProps<Props>()
const emit = defineEmits<{ (e: 'send', text: string): void }>()

const text = ref('')
const listRef = ref<HTMLElement | null>(null)
const inputRef = ref<HTMLTextAreaElement | null>(null)

// 입력 높이 자동 확장 — 최대 약 7.5rem까지는 스크롤바 없이 늘어나고, 초과 시에만 스크롤.
const MAX_INPUT_HEIGHT = 120
function autoGrow() {
  const el = inputRef.value
  if (!el) return
  el.style.height = 'auto'
  const full = el.scrollHeight
  el.style.height = `${Math.min(full, MAX_INPUT_HEIGHT)}px`
  el.style.overflowY = full > MAX_INPUT_HEIGHT ? 'auto' : 'hidden'
}

// 시각(HH:MM) 표시
function fmtTime(ts: number): string {
  const d = new Date(ts)
  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}

function submit() {
  const body = text.value.trim()
  if (!body) return
  emit('send', body)
  text.value = ''
  void nextTick(autoGrow) // 전송 후 높이 초기화
}

// 메시지 증가 시 맨 아래로
watch(
  () => props.messages.length,
  async () => {
    await nextTick()
    const el = listRef.value
    if (el) el.scrollTop = el.scrollHeight
  },
)
</script>

<template>
  <div class="chat">
    <div
      ref="listRef"
      class="chat-list"
    >
      <div
        v-if="messages.length === 0"
        class="chat-empty"
      >
        아직 메시지가 없습니다. 첫 메시지를 보내보세요.
      </div>
      <div
        v-for="m in messages"
        :key="m.id"
        class="chat-msg"
        :class="{ self: m.self }"
      >
        <span
          v-if="!m.self"
          class="chat-av"
        ><UserAvatar
          :url="m.senderAvatarUrl"
          :name="m.senderName"
        /></span>
        <div class="chat-col">
          <div class="chat-meta">
            <span
              v-if="!m.self"
              class="chat-name"
            >{{ m.senderName }}</span>
            <span class="chat-time">{{ fmtTime(m.ts) }}</span>
          </div>
          <div class="chat-bubble">
            {{ m.text }}
          </div>
        </div>
      </div>
    </div>
    <div class="chat-input">
      <textarea
        ref="inputRef"
        v-model="text"
        rows="1"
        :maxlength="MAX_CHAT_LENGTH"
        placeholder="메시지 보내기… (Shift+Enter 줄바꿈)"
        aria-label="채팅 메시지"
        @input="autoGrow"
        @keydown.enter.exact.prevent="submit"
      />
      <button
        type="button"
        class="chat-send"
        :disabled="!text.trim()"
        title="보내기"
        @click="submit"
      >
        <MeetingIcon name="send" />
      </button>
    </div>
  </div>
</template>

<style scoped>
.chat {
  display: flex;
  flex-direction: column;
  min-height: 0;
  flex: 1;
}
.chat-list {
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 0.875rem;
  padding: 1rem 0.875rem;
  scrollbar-width: thin;
  scrollbar-color: var(--d-border) transparent;
}
.chat-list::-webkit-scrollbar {
  width: 0.4375rem;
}
.chat-list::-webkit-scrollbar-thumb {
  background: var(--d-border);
  border-radius: 0.25rem;
}
.chat-empty {
  margin: auto;
  text-align: center;
  font-size: 0.8125rem;
  color: var(--d-text-3);
}
.chat-msg {
  display: flex;
  gap: 0.5625rem;
  align-items: flex-start;
}
.chat-msg.self {
  flex-direction: row-reverse;
}
.chat-av {
  width: 1.875rem;
  height: 1.875rem;
  flex-shrink: 0;
}
.chat-col {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  max-width: 80%;
  min-width: 0;
}
.chat-msg.self .chat-col {
  align-items: flex-end;
}
.chat-meta {
  display: flex;
  align-items: baseline;
  gap: 0.4375rem;
}
.chat-name {
  font-size: 0.75rem;
  font-weight: 600;
  color: var(--d-text-2);
}
.chat-time {
  font-size: 0.65625rem;
  color: var(--d-text-3);
}
.chat-bubble {
  font-size: 0.8125rem;
  line-height: 1.5;
  color: var(--d-text);
  background: var(--d-panel-2);
  border: 1px solid var(--d-border);
  padding: 0.5rem 0.75rem;
  border-radius: 0.75rem;
  border-top-left-radius: 0.25rem;
  word-break: break-word;
  white-space: pre-wrap;
}
.chat-msg.self .chat-bubble {
  background: var(--accent);
  border-color: var(--accent);
  color: #fff;
  border-top-left-radius: 0.75rem;
  border-top-right-radius: 0.25rem;
}
.chat-input {
  display: flex;
  align-items: flex-end;
  gap: 0.5rem;
  padding: 0.75rem;
  border-top: 1px solid var(--d-border);
}
.chat-input textarea {
  flex: 1;
  min-width: 0;
  min-height: 2.5rem;
  max-height: 7.5rem;
  padding: 0.5625rem 0.8125rem;
  border: 1px solid var(--d-border);
  border-radius: 0.625rem;
  background: var(--d-panel-2);
  color: var(--d-text);
  font-family: inherit;
  font-size: 0.8125rem;
  line-height: 1.4;
  outline: none;
  resize: none;
  overflow-y: hidden;
}
.chat-input textarea:focus {
  border-color: var(--accent);
}
.chat-input textarea::placeholder {
  color: var(--d-text-3);
}
.chat-send {
  width: 2.5rem;
  height: 2.5rem;
  flex-shrink: 0;
  border: none;
  border-radius: 0.625rem;
  background: var(--accent);
  color: #fff;
  cursor: pointer;
  display: grid;
  place-items: center;
}
.chat-send svg {
  width: 1.125rem;
  height: 1.125rem;
}
.chat-send:hover:not(:disabled) {
  background: var(--accent-hover);
}
.chat-send:disabled {
  opacity: 0.45;
  cursor: not-allowed;
}
</style>
