<script setup lang="ts">
// AI 채팅 패널 — Claude API 와 대화. 대화/이력은 DB(ai.store)에 보관.
// 우측 슬라이드 패널. 채팅 뷰 ↔ 지난 대화(기록) 목록 뷰 전환.
import { nextTick, ref, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useAiStore } from '@/stores/ai.store'
import { useDialog } from '@/composables/useDialog'
import { relativeTimeKo } from '@/shared/utils/format'
import { renderMarkdown } from '@/shared/utils/markdown'

interface Props {
  open: boolean
}
const props = defineProps<Props>()

interface Emits {
  (e: 'close'): void
}
const emit = defineEmits<Emits>()

const aiStore = useAiStore()
const dialog = useDialog()
const { conversations, listLoading, messages, loading, error } =
  storeToRefs(aiStore)

// 입력값과 뷰 전환만 컴포넌트 로컬
const input = ref('')
const showHistory = ref(false)
const bodyEl = ref<HTMLElement | null>(null)

function scrollToBottom() {
  void nextTick(() => {
    if (bodyEl.value && !showHistory.value) {
      bodyEl.value.scrollTop = bodyEl.value.scrollHeight
    }
  })
}
watch(() => [messages.value.length, loading.value], scrollToBottom)
watch(
  () => props.open,
  (open) => {
    if (open && !showHistory.value) scrollToBottom()
  },
)

async function send() {
  const text = input.value
  if (!text.trim() || loading.value) return
  input.value = ''
  const ok = await aiStore.send(text)
  if (!ok) input.value = text // 실패 시 입력 복원
}

function newChat() {
  aiStore.newConversation()
  showHistory.value = false
  input.value = ''
}

async function toggleHistory() {
  showHistory.value = !showHistory.value
  if (showHistory.value) await aiStore.loadConversations()
}

async function openConv(id: string) {
  await aiStore.openConversation(id)
  showHistory.value = false
}

async function removeConv(id: string) {
  const ok = await dialog.confirm('이 대화를 삭제할까요?', {
    variant: 'danger',
    confirmText: '삭제',
  })
  if (!ok) return
  await aiStore.removeConversation(id)
}
</script>

<template>
  <Teleport to="body">
    <div
      v-if="open"
      class="ac-backdrop"
      @click="emit('close')"
    />
    <aside
      class="ac-panel"
      :class="{ open }"
      aria-label="AI 채팅"
    >
      <!-- 헤더 -->
      <header class="ac-head">
        <div class="ac-title">
          <span class="ac-logo">AI</span>
          <div class="ac-name">
            {{ showHistory ? '지난 대화' : 'Relay 어시스턴트' }}
          </div>
        </div>
        <div class="ac-headbtns">
          <button
            class="ac-iconbtn"
            type="button"
            :title="showHistory ? '대화로 돌아가기' : '지난 대화'"
            :aria-label="showHistory ? '대화로 돌아가기' : '지난 대화'"
            :class="{ on: showHistory }"
            @click="toggleHistory"
          >
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
            >
              <path d="M3 12a9 9 0 1 0 9-9 9.74 9.74 0 0 0-6.74 2.74L3 8" /><path d="M3 3v5h5" /><path d="M12 7v5l3 2" />
            </svg>
          </button>
          <button
            class="ac-iconbtn"
            type="button"
            title="새 대화"
            aria-label="새 대화"
            :disabled="loading"
            @click="newChat"
          >
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
            >
              <path d="M12 5v14M5 12h14" />
            </svg>
          </button>
          <button
            class="ac-iconbtn"
            type="button"
            title="닫기"
            aria-label="닫기"
            @click="emit('close')"
          >
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
            >
              <path d="M18 6 6 18M6 6l12 12" />
            </svg>
          </button>
        </div>
      </header>

      <!-- 기록(지난 대화) 뷰 -->
      <div
        v-if="showHistory"
        class="ac-body ac-history"
      >
        <div
          v-if="listLoading && conversations.length === 0"
          class="ac-hist-empty"
        >
          불러오는 중…
        </div>
        <div
          v-else-if="conversations.length === 0"
          class="ac-hist-empty"
        >
          지난 대화가 없습니다.
        </div>
        <template v-else>
          <div
            v-for="c in conversations"
            :key="c.id"
            class="ac-hist-item"
            @click="openConv(c.id)"
          >
            <div class="ac-hist-main">
              <div class="ac-hist-title">
                {{ c.title }}
              </div>
              <div class="ac-hist-time">
                {{ relativeTimeKo(c.updatedAt) }}
              </div>
            </div>
            <button
              class="ac-hist-del"
              type="button"
              title="삭제"
              aria-label="대화 삭제"
              @click.stop="removeConv(c.id)"
            >
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              >
                <path d="M3 6h18M8 6V4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2m2 0v14a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V6" />
              </svg>
            </button>
          </div>
        </template>
      </div>

      <!-- 채팅 뷰 -->
      <div
        v-else
        ref="bodyEl"
        class="ac-body"
      >
        <div
          v-if="messages.length === 0"
          class="ac-welcome"
        >
          <div class="ac-welcome-logo">
            AI
          </div>
          <div class="ac-welcome-title">
            무엇을 도와드릴까요?
          </div>
          <div class="ac-welcome-sub">
            업무나 일정에 대해 자유롭게 질문해 보세요.
          </div>
        </div>

        <div
          v-for="(m, i) in messages"
          :key="i"
          class="ac-msg"
          :class="m.role"
        >
          <span
            v-if="m.role === 'assistant'"
            class="ac-ava"
          >AI</span>
          <!-- AI 응답은 마크다운 렌더(renderMarkdown 가 escapeHtml 후 신뢰 태그만 조립 → XSS 안전) -->
          <!-- eslint-disable vue/no-v-html -->
          <div
            v-if="m.role === 'assistant'"
            class="ac-bubble ac-md"
            v-html="renderMarkdown(m.content)"
          />
          <!-- eslint-enable vue/no-v-html -->
          <div
            v-else
            class="ac-bubble"
          >
            {{ m.content }}
          </div>
        </div>

        <div
          v-if="loading"
          class="ac-msg assistant"
        >
          <span class="ac-ava">AI</span>
          <div class="ac-bubble ac-typing">
            <span /><span /><span />
          </div>
        </div>

        <div
          v-if="error"
          class="ac-error"
        >
          {{ error }}
        </div>
      </div>

      <!-- 입력 (채팅 뷰에서만) -->
      <footer
        v-if="!showHistory"
        class="ac-foot"
      >
        <div class="ac-inputrow">
          <textarea
            v-model="input"
            class="ac-input"
            rows="1"
            placeholder="메시지를 입력하세요…"
            :disabled="loading"
            @keydown.enter.exact.prevent="send"
          />
          <button
            class="ac-send"
            type="button"
            title="전송"
            aria-label="전송"
            :disabled="loading || !input.trim()"
            @click="send"
          >
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
            >
              <path d="m22 2-7 20-4-9-9-4Z" /><path d="M22 2 11 13" />
            </svg>
          </button>
        </div>
        <div class="ac-hint">
          Enter 전송 · Shift+Enter 줄바꿈
        </div>
      </footer>
    </aside>
  </Teleport>
</template>

<style scoped>
.ac-backdrop {
  position: fixed;
  inset: 0;
  background: rgba(17, 18, 22, 0.32);
  z-index: 60;
}
.ac-panel {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  width: 26rem;
  max-width: 96vw;
  background: #fff;
  border-left: 1px solid var(--border);
  box-shadow: -0.5rem 0 1.5rem rgba(17, 18, 22, 0.12);
  display: flex;
  flex-direction: column;
  transform: translateX(100%);
  transition: transform 0.22s ease;
  z-index: 61;
}
.ac-panel.open {
  transform: translateX(0);
}

/* 헤더 */
.ac-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 0.75rem;
  padding: 0.875rem 1rem;
  border-bottom: 1px solid var(--border);
  flex-shrink: 0;
}
.ac-title {
  display: flex;
  align-items: center;
  gap: 0.625rem;
  min-width: 0;
}
.ac-logo {
  width: 2rem;
  height: 2rem;
  border-radius: 0.5rem;
  background: var(--accent);
  color: #fff;
  display: grid;
  place-items: center;
  font-size: 0.75rem;
  font-weight: 800;
  flex-shrink: 0;
}
.ac-name {
  font-size: 0.9375rem;
  font-weight: 700;
  color: var(--text);
}
.ac-headbtns {
  display: flex;
  gap: 0.25rem;
  flex-shrink: 0;
}
.ac-iconbtn {
  width: 2rem;
  height: 2rem;
  border: none;
  background: transparent;
  border-radius: 0.5rem;
  color: var(--text-3);
  display: grid;
  place-items: center;
  cursor: pointer;
}
.ac-iconbtn:hover {
  background: #f1f2f4;
  color: var(--text);
}
.ac-iconbtn.on {
  background: var(--accent-weak);
  color: var(--accent);
}
.ac-iconbtn:disabled {
  opacity: 0.5;
  cursor: default;
}
.ac-iconbtn svg {
  width: 1.0625rem;
  height: 1.0625rem;
}

/* 대화 영역 */
.ac-body {
  flex: 1;
  overflow-y: auto;
  padding: 1.125rem 1rem;
  display: flex;
  flex-direction: column;
  gap: 0.875rem;
}
.ac-welcome {
  margin: auto;
  text-align: center;
  padding: 1.5rem 0;
}
.ac-welcome-logo {
  width: 2.75rem;
  height: 2.75rem;
  border-radius: 0.75rem;
  background: var(--accent-weak);
  color: var(--accent);
  display: grid;
  place-items: center;
  font-weight: 800;
  margin: 0 auto 0.875rem;
}
.ac-welcome-title {
  font-size: 1rem;
  font-weight: 700;
  color: var(--text);
}
.ac-welcome-sub {
  font-size: 0.8125rem;
  color: var(--text-3);
  margin-top: 0.375rem;
  line-height: 1.5;
}

.ac-msg {
  display: flex;
  gap: 0.5rem;
  max-width: 100%;
}
.ac-msg.user {
  justify-content: flex-end;
}
.ac-ava {
  width: 1.625rem;
  height: 1.625rem;
  border-radius: 0.5rem;
  background: var(--accent-weak);
  color: var(--accent);
  display: grid;
  place-items: center;
  font-size: 0.625rem;
  font-weight: 800;
  flex-shrink: 0;
  margin-top: 0.125rem;
}
.ac-bubble {
  font-size: 0.875rem;
  line-height: 1.6;
  color: var(--text);
  white-space: pre-wrap;
  word-break: break-word;
  padding: 0.5625rem 0.75rem;
  border-radius: 0.75rem;
  max-width: 19rem;
}
.ac-msg.assistant .ac-bubble {
  background: #f4f5f7;
  border-top-left-radius: 0.25rem;
}

/* 마크다운 렌더 영역 — v-html 내부라 :deep() 로 타겟 */
.ac-bubble.ac-md {
  white-space: normal;
}
.ac-md :deep(p) {
  margin: 0 0 0.5em;
}
.ac-md :deep(p:last-child) {
  margin-bottom: 0;
}
.ac-md :deep(ul),
.ac-md :deep(ol) {
  margin: 0.25em 0 0.5em;
  padding-left: 1.25em;
}
.ac-md :deep(li) {
  margin: 0.15em 0;
}
.ac-md :deep(strong) {
  font-weight: 700;
}
.ac-md :deep(code) {
  background: rgba(0, 0, 0, 0.06);
  padding: 0.05em 0.3em;
  border-radius: 0.25rem;
  font-size: 0.85em;
  font-family: ui-monospace, 'SFMono-Regular', monospace;
}
.ac-md :deep(pre.md-pre) {
  background: #1f2430;
  color: #e6e8ec;
  padding: 0.6rem 0.75rem;
  border-radius: 0.5rem;
  overflow-x: auto;
  margin: 0.4em 0;
}
.ac-md :deep(pre.md-pre code) {
  background: none;
  padding: 0;
  color: inherit;
  font-size: 0.8125rem;
}
.ac-md :deep(.md-h) {
  font-weight: 700;
  margin: 0.4em 0 0.25em;
}
.ac-md :deep(.md-h1) {
  font-size: 1.05em;
}
.ac-md :deep(hr) {
  border: none;
  border-top: 1px solid var(--border-strong);
  margin: 0.6em 0;
}
.ac-md :deep(a) {
  color: var(--accent);
  text-decoration: underline;
}
.ac-msg.user .ac-bubble {
  background: var(--accent);
  color: #fff;
  border-top-right-radius: 0.25rem;
}

/* 타이핑 인디케이터 */
.ac-typing {
  display: inline-flex;
  gap: 0.25rem;
  align-items: center;
}
.ac-typing span {
  width: 0.375rem;
  height: 0.375rem;
  border-radius: 50%;
  background: var(--text-3);
  animation: ac-blink 1.2s infinite ease-in-out both;
}
.ac-typing span:nth-child(2) {
  animation-delay: 0.18s;
}
.ac-typing span:nth-child(3) {
  animation-delay: 0.36s;
}
@keyframes ac-blink {
  0%,
  80%,
  100% {
    opacity: 0.25;
  }
  40% {
    opacity: 1;
  }
}

.ac-error {
  font-size: 0.8125rem;
  color: var(--red);
  background: var(--red-weak);
  border: 1px solid var(--red-border);
  border-radius: 0.5rem;
  padding: 0.5rem 0.75rem;
}

/* 기록(지난 대화) 목록 */
.ac-history {
  gap: 0;
  padding: 0.5rem 0.5rem;
}
.ac-hist-empty {
  margin: auto;
  text-align: center;
  font-size: 0.8125rem;
  color: var(--text-3);
  padding: 2rem 0;
}
.ac-hist-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.625rem 0.625rem;
  border-radius: 0.5rem;
  cursor: pointer;
}
.ac-hist-item:hover {
  background: #f4f5f7;
}
.ac-hist-main {
  flex: 1;
  min-width: 0;
}
.ac-hist-title {
  font-size: 0.875rem;
  color: var(--text);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.ac-hist-time {
  font-size: 0.6875rem;
  color: var(--text-3);
  margin-top: 0.1875rem;
}
.ac-hist-del {
  width: 1.75rem;
  height: 1.75rem;
  border: none;
  background: transparent;
  border-radius: 0.4375rem;
  color: var(--text-3);
  display: grid;
  place-items: center;
  cursor: pointer;
  flex-shrink: 0;
  opacity: 0;
}
.ac-hist-item:hover .ac-hist-del {
  opacity: 1;
}
.ac-hist-del:hover {
  background: var(--red-weak);
  color: var(--red);
}
.ac-hist-del svg {
  width: 0.9375rem;
  height: 0.9375rem;
}

/* 입력 */
.ac-foot {
  border-top: 1px solid var(--border);
  padding: 0.75rem 1rem 0.875rem;
  flex-shrink: 0;
}
.ac-inputrow {
  display: flex;
  align-items: flex-end;
  gap: 0.5rem;
  border: 1px solid var(--border-strong);
  border-radius: 0.625rem;
  padding: 0.375rem 0.375rem 0.375rem 0.75rem;
  background: #fff;
}
.ac-inputrow:focus-within {
  border-color: var(--accent);
  box-shadow: 0 0 0 3px var(--accent-weak);
}
.ac-input {
  flex: 1;
  border: none;
  outline: none;
  resize: none;
  font-family: inherit;
  font-size: 0.875rem;
  line-height: 1.5;
  color: var(--text);
  background: transparent;
  max-height: 7rem;
  padding: 0.25rem 0;
}
.ac-input::placeholder {
  color: var(--text-3);
}
.ac-send {
  width: 2rem;
  height: 2rem;
  border: none;
  border-radius: 0.5rem;
  background: var(--accent);
  color: #fff;
  display: grid;
  place-items: center;
  cursor: pointer;
  flex-shrink: 0;
}
.ac-send:hover:not(:disabled) {
  background: var(--accent-hover);
}
.ac-send:disabled {
  opacity: 0.45;
  cursor: default;
}
.ac-send svg {
  width: 1rem;
  height: 1rem;
}
.ac-hint {
  font-size: 0.6875rem;
  color: var(--text-3);
  margin-top: 0.4375rem;
  text-align: center;
}
</style>
