<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue'

interface Msg {
  role: 'user' | 'assistant'
  content: string
  issue?: { number: number; url: string; title: string }
}

const open = ref(false)
const messages = ref<Msg[]>([])
const input = ref('')
const busy = ref(false)
const error = ref<string | null>(null)
const scrollEl = ref<HTMLElement | null>(null)

const canSend = computed(() => !busy.value && input.value.trim().length > 0)

watch(messages, async () => {
  await nextTick()
  scrollEl.value?.scrollTo({ top: scrollEl.value.scrollHeight, behavior: 'smooth' })
}, { deep: true })

async function send() {
  if (!canSend.value) return
  const text = input.value.trim()
  input.value = ''
  error.value = null
  messages.value.push({ role: 'user', content: text })
  busy.value = true
  try {
    const payload = {
      messages: messages.value.map((m) => ({ role: m.role, content: m.content })),
    }
    const res = await fetch('/api/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    })
    if (!res.ok) {
      const body = await res.text()
      throw new Error(body || `HTTP ${res.status}`)
    }
    const data = (await res.json()) as {
      reply: string
      created_issue: { number: number; url: string; title: string } | null
    }
    messages.value.push({
      role: 'assistant',
      content: data.reply,
      issue: data.created_issue ?? undefined,
    })
  } catch (e) {
    const msg = (e as Error).message
    error.value = msg
    messages.value.push({ role: 'assistant', content: `（出错了：${msg}）` })
  } finally {
    busy.value = false
  }
}

function onKeydown(e: KeyboardEvent) {
  if (e.key === 'Enter' && !e.shiftKey) {
    e.preventDefault()
    send()
  }
}

function reset() {
  messages.value = []
  error.value = null
}
</script>

<template>
  <button v-if="!open" class="fab" @click="open = true" aria-label="打开聊天">
    <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">
      <path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8z" />
    </svg>
    <span>反馈 / 提问</span>
  </button>

  <div v-else class="panel">
    <header>
      <div class="title">
        <span class="dot" />
        <strong>cube · chat</strong>
      </div>
      <div class="actions">
        <button class="icon" @click="reset" title="清空对话">↺</button>
        <button class="icon" @click="open = false" title="收起">✕</button>
      </div>
    </header>

    <div class="thread" ref="scrollEl">
      <div v-if="messages.length === 0" class="hint">
        <p>问 cube 平台的事，或反馈 bug / 想法 — 我会帮你提到 <code>fam/cube</code> issue。</p>
      </div>

      <div v-for="(m, i) in messages" :key="i" :class="['bubble', m.role]">
        <div class="content">{{ m.content }}</div>
        <a v-if="m.issue" :href="m.issue.url" target="_blank" rel="noopener" class="issue-link">
          已建 issue #{{ m.issue.number }} →
        </a>
      </div>

      <div v-if="busy" class="bubble assistant typing">
        <span /><span /><span />
      </div>
    </div>

    <footer>
      <textarea
        v-model="input"
        :disabled="busy"
        @keydown="onKeydown"
        rows="2"
        placeholder="说点什么...（Enter 发送，Shift+Enter 换行）"
      />
      <button class="send" :disabled="!canSend" @click="send">发送</button>
    </footer>
  </div>
</template>

<style scoped>
.fab {
  position: fixed;
  right: 20px;
  bottom: 20px;
  z-index: 1000;
  background: linear-gradient(135deg, #7c3aed, #06b6d4);
  color: white;
  border: none;
  padding: 12px 18px;
  border-radius: 999px;
  font-size: 0.95rem;
  font-weight: 600;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 8px 24px rgba(124, 58, 237, 0.35);
  transition: transform 0.15s, box-shadow 0.15s;
}
.fab:hover { transform: translateY(-2px); box-shadow: 0 12px 28px rgba(124, 58, 237, 0.45); }

.panel {
  position: fixed;
  right: 20px;
  bottom: 20px;
  z-index: 1000;
  width: min(380px, calc(100vw - 32px));
  height: min(560px, calc(100vh - 40px));
  background: var(--bg-soft, rgba(20, 20, 30, 0.95));
  backdrop-filter: blur(12px);
  border: 1px solid var(--border, rgba(255, 255, 255, 0.15));
  border-radius: 14px;
  box-shadow: 0 16px 48px rgba(0, 0, 0, 0.55);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  color: var(--fg, rgba(255, 255, 255, 0.92));
}

header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 14px;
  border-bottom: 1px solid var(--border, rgba(255, 255, 255, 0.15));
}
.title { display: flex; align-items: center; gap: 8px; }
.dot {
  width: 9px;
  height: 9px;
  border-radius: 50%;
  background: #4ade80;
  box-shadow: 0 0 8px rgba(74, 222, 128, 0.7);
}
.actions { display: flex; gap: 4px; }
.icon {
  width: 28px;
  height: 28px;
  background: transparent;
  border: 1px solid var(--border, rgba(255, 255, 255, 0.15));
  color: inherit;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.9rem;
}
.icon:hover { background: rgba(255, 255, 255, 0.06); }

.thread {
  flex: 1;
  overflow-y: auto;
  padding: 14px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.hint { color: var(--fg-dim, rgba(255, 255, 255, 0.6)); font-size: 0.9rem; }
.hint code {
  background: rgba(255, 255, 255, 0.08);
  padding: 1px 5px;
  border-radius: 4px;
  font-size: 0.85em;
}

.bubble {
  max-width: 85%;
  padding: 10px 13px;
  border-radius: 12px;
  line-height: 1.4;
  font-size: 0.92rem;
  white-space: pre-wrap;
  word-wrap: break-word;
}
.bubble.user {
  align-self: flex-end;
  background: linear-gradient(135deg, #7c3aed, #4f46e5);
  color: white;
}
.bubble.assistant {
  align-self: flex-start;
  background: rgba(255, 255, 255, 0.08);
  border: 1px solid var(--border, rgba(255, 255, 255, 0.15));
}
.issue-link {
  display: inline-block;
  margin-top: 8px;
  color: #4ea7f7;
  font-size: 0.85rem;
  text-decoration: none;
  border-top: 1px dashed rgba(255, 255, 255, 0.15);
  padding-top: 8px;
}
.issue-link:hover { color: #80c2ff; }

.bubble.typing {
  display: inline-flex;
  gap: 4px;
  padding: 12px 14px;
}
.bubble.typing span {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.45);
  animation: bounce 1.2s ease-in-out infinite;
}
.bubble.typing span:nth-child(2) { animation-delay: 0.15s; }
.bubble.typing span:nth-child(3) { animation-delay: 0.3s; }
@keyframes bounce {
  0%, 60%, 100% { transform: translateY(0); opacity: 0.45; }
  30%           { transform: translateY(-5px); opacity: 1; }
}

footer {
  padding: 10px 12px 12px;
  border-top: 1px solid var(--border, rgba(255, 255, 255, 0.15));
  display: flex;
  gap: 8px;
  align-items: flex-end;
}
textarea {
  flex: 1;
  resize: none;
  background: rgba(255, 255, 255, 0.06);
  border: 1px solid var(--border, rgba(255, 255, 255, 0.15));
  border-radius: 8px;
  padding: 8px 10px;
  font-family: inherit;
  font-size: 0.92rem;
  color: inherit;
  line-height: 1.4;
}
textarea:focus { outline: 2px solid #7c3aed; outline-offset: -1px; }
.send {
  background: linear-gradient(135deg, #7c3aed, #06b6d4);
  color: white;
  border: none;
  padding: 10px 16px;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
}
.send:disabled { background: rgba(255, 255, 255, 0.1); color: rgba(255, 255, 255, 0.4); cursor: not-allowed; }

@media (max-width: 420px) {
  .panel { right: 12px; bottom: 12px; width: calc(100vw - 24px); height: calc(100vh - 24px); }
}
</style>
