<script setup lang="ts">
import { MessageCircle, Trash2, Send, Sparkles, CornerDownLeft, Paperclip, Smile } from 'lucide-vue-next'
import EmojiPicker from '@/components/chat/EmojiPicker.vue'
import FileMessage from '@/components/chat/FileMessage.vue'
import TelemetrySparkline from '@/components/chat/TelemetrySparkline.vue'
import OrchestrationPanel from '@/components/chat/OrchestrationPanel.vue'
import { useChatView } from '@/pages/chat/composables/useChatView'

const {
  store,
  inputMessage,
  isSending,
  chatContainer,
  inputRef,
  isTyping,
  fileInputRef,
  showEmojiPicker,
  chatModels,
  selectedModelName,
  selectedModel,
  isLoadingModels,
  conversationsError,
  orchestrationPanelVisible,
  orchestrationStatus,
  orchestrationInsight,
  activeAgent,
  visitedAgents,
  orchestrationEventFeed,
  systemTelemetry,
  sessionTelemetry,
  sendMessage,
  selectConversation,
  newConversation,
  deleteConversation,
  formatTime,
  formatConvDate,
  autoResize,
  handleFileSelect,
  insertEmoji,
  openFilePicker,
} = useChatView()

function extractThinkParts(content: string) {
  const thinkPattern = /<think>([\s\S]*?)<\/think>/gi
  const thinkBlocks = Array.from(content.matchAll(thinkPattern))
    .map((match) => match[1]?.trim())
    .filter((block): block is string => Boolean(block))

  const visibleContent = content.replace(thinkPattern, '').trim()

  return {
    hasThink: thinkBlocks.length > 0,
    thinkBlocks,
    visibleContent,
  }
}

function escapeHtml(content: string) {
  return content
    .replaceAll('&', '&amp;')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;')
    .replaceAll('"', '&quot;')
    .replaceAll("'", '&#39;')
}

function renderInlineMarkdown(content: string) {
  return content
    .replace(/`([^`]+)`/g, '<code>$1</code>')
    .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
    .replace(/\*([^*]+)\*/g, '<em>$1</em>')
}

function isMarkdownTable(lines: string[]) {
  return lines.length >= 2
    && lines[0].includes('|')
    && lines[1].includes('|')
    && lines[1].split('|').filter(Boolean).every((cell) => /^\s*:?-{3,}:?\s*$/.test(cell))
}

function splitTableRow(line: string) {
  return line
    .trim()
    .replace(/^\|/, '')
    .replace(/\|$/, '')
    .split('|')
    .map((cell) => cell.trim())
}

function renderMarkdown(content: string) {
  const normalizedContent = content
    .replace(/\\r\\n/g, '\n')
    .replace(/\\n/g, '\n')
    .replace(/\r\n/g, '\n')

  const normalized = escapeHtml(normalizedContent)
  const blocks = normalized.split(/\n\n+/)

  return blocks.map((block) => {
    const trimmed = block.trim()
    if (!trimmed) return ''

    if (/^```[\s\S]*```$/.test(trimmed)) {
      const code = trimmed.replace(/^```\w*\n?/, '').replace(/```$/, '').trimEnd()
      return `<pre class="md-pre"><code>${code}</code></pre>`
    }

    const lines = trimmed.split('\n')

    if (isMarkdownTable(lines)) {
      const [headerLine, , ...bodyLines] = lines
      const headers = splitTableRow(headerLine)
      const thead = `<thead><tr>${headers.map((cell) => `<th>${renderInlineMarkdown(cell)}</th>`).join('')}</tr></thead>`
      const tbody = bodyLines.length
        ? `<tbody>${bodyLines.map((line) => `<tr>${splitTableRow(line).map((cell) => `<td>${renderInlineMarkdown(cell)}</td>`).join('')}</tr>`).join('')}</tbody>`
        : ''
      return `<div class="md-table-wrap"><table class="md-table">${thead}${tbody}</table></div>`
    }

    if (lines.every((line) => /^\s*[-*]\s+/.test(line))) {
      const items = lines
        .map((line) => line.replace(/^\s*[-*]\s+/, '').trim())
        .map((line) => `<li>${renderInlineMarkdown(line)}</li>`)
        .join('')
      return `<ul class="md-list">${items}</ul>`
    }

    if (lines.every((line) => /^\s*\d+\.\s+/.test(line))) {
      const items = lines
        .map((line) => line.replace(/^\s*\d+\.\s+/, '').trim())
        .map((line) => `<li>${renderInlineMarkdown(line)}</li>`)
        .join('')
      return `<ol class="md-list">${items}</ol>`
    }

    if (/^#{1,3}\s+/.test(trimmed)) {
      const level = Math.min((trimmed.match(/^#+/)?.[0].length || 1) + 1, 6)
      const text = trimmed.replace(/^#{1,3}\s+/, '')
      return `<h${level} class="md-heading">${renderInlineMarkdown(text)}</h${level}>`
    }

    return `<p>${renderInlineMarkdown(trimmed).replace(/\n/g, '<br>')}</p>`
  }).join('')
}
</script>

<template>
  <div class="chat-view">
    <!-- Conversation list sidebar -->
    <aside class="conv-sidebar">
      <div class="sidebar-runtime-panel" :class="`is-${orchestrationStatus}`">
        <div class="section-label">// RUNTIME STATUS</div>
        <div class="runtime-grid">
          <div class="runtime-card cpu-card">
            <div class="runtime-topline">
              <span class="runtime-label">CPU</span>
              <span class="runtime-value">{{ systemTelemetry.cpu.online && systemTelemetry.cpu.current !== null ? `${systemTelemetry.cpu.current}%` : 'OFFLINE' }}</span>
            </div>
            <TelemetrySparkline :points="systemTelemetry.cpu.series" stroke="#22d3ee" fill="rgba(34, 211, 238, 0.16)" />
          </div>
          <div class="runtime-card mem-card">
            <div class="runtime-topline">
              <span class="runtime-label">MEM</span>
              <span class="runtime-value">{{ systemTelemetry.memory.online && systemTelemetry.memory.current !== null ? `${systemTelemetry.memory.current}%` : 'OFFLINE' }}</span>
            </div>
            <TelemetrySparkline :points="systemTelemetry.memory.series" stroke="#a78bfa" fill="rgba(167, 139, 250, 0.14)" />
          </div>
          <div class="runtime-card disk-card">
            <div class="runtime-topline">
              <span class="runtime-label">DISK</span>
              <span class="runtime-value">{{ systemTelemetry.disk.online && systemTelemetry.disk.current !== null ? `${systemTelemetry.disk.current}%` : 'OFFLINE' }}</span>
            </div>
            <TelemetrySparkline :points="systemTelemetry.disk.series" stroke="#4ade80" fill="rgba(74, 222, 128, 0.14)" />
          </div>
        </div>
        <div class="runtime-activity-card">
          <div class="runtime-activity-head">
            <span class="runtime-activity-title">SESSION ACTIVITY</span>
            <span class="runtime-badge">{{ orchestrationStatus === 'active' ? 'LIVE' : 'IDLE' }}</span>
          </div>
          <TelemetrySparkline :points="sessionTelemetry.activitySeries" stroke="#f59e0b" fill="rgba(245, 158, 11, 0.16)" />
          <div class="runtime-stats">
            <div class="runtime-stat">
              <span class="runtime-stat-key">EVENTS</span>
              <span class="runtime-stat-value">{{ sessionTelemetry.eventsCount }}</span>
            </div>
            <div class="runtime-stat">
              <span class="runtime-stat-key">AGENTS</span>
              <span class="runtime-stat-value">{{ sessionTelemetry.agentCount }}</span>
            </div>
            <div class="runtime-stat">
              <span class="runtime-stat-key">TOOLS</span>
              <span class="runtime-stat-value">{{ sessionTelemetry.toolCount }}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="conv-sidebar-header">
        <div class="section-label">// SESSIONS</div>
      </div>

      <div class="conv-list">
        <div
          v-for="conv in store.conversations"
          :key="conv.id"
          class="conv-item"
          :class="{ active: conv.id === store.currentConversationId }"
          @click="selectConversation(conv.id)"
        >
          <div class="conv-item-icon">
            <MessageCircle :size="12" />
          </div>
          <div class="conv-item-body">
            <div class="conv-title">{{ conv.title || 'New Conversation' }}</div>
            <div class="conv-date">{{ formatConvDate(conv.updated_at || conv.created_at) }}</div>
          </div>
          <button class="conv-delete" @click="deleteConversation(conv.id, $event)">
            <Trash2 :size="12" />
          </button>
          <div class="conv-active-line"></div>
        </div>

        <div v-if="conversationsError" class="conv-empty">
          <div class="empty-icon"><MessageCircle :size="24" /></div>
          <div class="empty-text">{{ conversationsError }}</div>
          <div class="empty-hint">请刷新页面或重新登录后重试</div>
        </div>

        <div v-else-if="store.conversations.length === 0" class="conv-empty">
          <div class="empty-icon"><MessageCircle :size="24" /></div>
          <div class="empty-text">No sessions yet</div>
          <div class="empty-hint">Send a message to create one</div>
        </div>
      </div>

      <div class="conv-sidebar-footer">
        <button class="new-chat-btn muted" @click="newConversation">
          <span class="btn-line"></span>
          <MessageCircle :size="14" />
          <span>NEW SESSION</span>
        </button>
      </div>
    </aside>

    <!-- Chat area -->
    <section class="chat-area">
      <div class="chat-shell">
        <div class="chat-main">
          <!-- Top bar -->
          <div class="chat-topbar">
            <div class="chat-status">
              <div class="status-indicator" :class="{ active: !isSending }"></div>
              <span class="status-text">{{ isTyping ? 'PROCESSING...' : 'READY' }}</span>
            </div>
            <div class="chat-model-panel">
              <label class="chat-model-label" for="chat-model-select">
                <Sparkles :size="12" />
                <span>CHAT MODEL</span>
              </label>
              <select
                id="chat-model-select"
                v-model="selectedModelName"
                class="chat-model-select"
                :disabled="isSending || isLoadingModels || chatModels.length === 0"
              >
                <option v-if="chatModels.length === 0" value="">
                  {{ isLoadingModels ? 'Loading models...' : 'No chat models' }}
                </option>
                <option v-for="model in chatModels" :key="model.name" :value="model.name">
                  {{ model.name }} · {{ model.provider }}
                </option>
              </select>
              <div v-if="selectedModel" class="chat-model">
                <Sparkles :size="12" />
                <span>{{ selectedModel.model }}</span>
              </div>
            </div>
          </div>

          <!-- Messages -->
          <div ref="chatContainer" class="messages-area">
            <!-- Welcome screen -->
            <div v-if="store.messages.length === 0" class="welcome-screen">
              <div class="welcome-icon">
                <div class="welcome-ring r1"></div>
                <div class="welcome-ring r2"></div>
                <div class="welcome-ring r3"></div>
                <div class="welcome-core">
                  <Sparkles :size="28" />
                </div>
              </div>
              <div class="welcome-title">JARVIS</div>
              <div class="welcome-sub">Strategic Thinking Partner</div>
              <div class="welcome-hint">把目标给我，我先帮您收束重点，再往下推进。</div>
            </div>

            <!-- Message bubbles -->
            <div
              v-for="(msg, i) in store.messages"
              :key="msg.id"
              class="message-row"
              :class="msg.role"
              :style="{ animationDelay: `${i * 30}ms` }"
            >
              <div class="msg-avatar">
                <span v-if="msg.role === 'user'">{{ '>' }}</span>
                <span v-else class="ai-icon">J</span>
              </div>
              <div class="msg-content">
                <div class="msg-meta">
                  <span class="msg-role">{{ msg.role === 'user' ? 'YOU' : 'JARVIS' }}</span>
                  <span v-if="msg.role === 'assistant' && msg.model" class="msg-model">{{ msg.model }}</span>
                  <span class="msg-time">{{ formatTime(msg.created_at) }}</span>
                </div>
                <template v-if="msg.role === 'assistant' && extractThinkParts(msg.content).hasThink">
                  <details class="think-panel">
                    <summary class="think-summary">
                      <span class="think-chip">
                        <span class="think-chip-dot"></span>
                        <span>THINK</span>
                      </span>
                    </summary>
                    <div class="think-content">
                      <div
                        v-for="(block, index) in extractThinkParts(msg.content).thinkBlocks"
                        :key="index"
                        class="think-block"
                        v-html="renderMarkdown(block)"
                      ></div>
                    </div>
                  </details>
                  <div
                    v-if="extractThinkParts(msg.content).visibleContent"
                    class="msg-bubble markdown-body"
                    v-html="renderMarkdown(extractThinkParts(msg.content).visibleContent)"
                  ></div>
                </template>
                <div v-else class="msg-bubble markdown-body" v-html="renderMarkdown(msg.content)"></div>
                <div v-if="msg.role === 'user' && msg.attachments?.length" class="msg-attachments">
                  <FileMessage
                    v-for="att in msg.attachments"
                    :key="att.id"
                    :filename="att.name"
                    :file-type="att.type"
                    :file-size="att.size"
                  />
                </div>
              </div>
            </div>

            <div v-if="isTyping" class="message-row assistant thinking-row">
              <div class="msg-avatar">
                <span class="ai-icon">J</span>
              </div>
              <div class="msg-content">
                <div class="msg-meta">
                  <span class="msg-role">JARVIS</span>
                  <span class="msg-model">thinking</span>
                </div>
                <div class="msg-bubble thinking-bubble">
                  <div class="thinking-hud">
                    <div class="thinking-core">
                      <span class="thinking-ring ring-1"></span>
                      <span class="thinking-ring ring-2"></span>
                      <span class="thinking-ring ring-3"></span>
                      <span class="thinking-dot"></span>
                    </div>
                    <div class="thinking-copy">
                      <div class="thinking-title">JARVIS THINKING</div>
                      <div class="thinking-subtitle">正在分析请求并准备响应</div>
                    </div>
                    <div class="typing-inline" aria-hidden="true">
                      <span class="dot"></span>
                      <span class="dot"></span>
                      <span class="dot"></span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

          </div>

          <!-- Input area -->
          <div class="input-area">
            <div class="input-frame">
              <div class="input-corners tl"></div>
              <div class="input-corners tr"></div>
              <div class="input-corners bl"></div>
              <div class="input-corners br"></div>
              <textarea
                ref="inputRef"
                v-model="inputMessage"
                placeholder="输入指令，按 Enter 发送..."
                :disabled="isSending"
                rows="1"
                @keydown.enter.exact.prevent="sendMessage"
                @input="autoResize"
              ></textarea>
              <input
                ref="fileInputRef"
                type="file"
                multiple
                accept=".jpg,.jpeg,.png,.gif,.webp,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt"
                style="display: none"
                @change="handleFileSelect"
              />
              <button class="attach-btn" @click="openFilePicker" title="上传文件">
                <Paperclip :size="15" />
              </button>
              <div class="emoji-wrapper">
                <button
                  class="emoji-btn"
                  :class="{ active: showEmojiPicker }"
                  @click="showEmojiPicker = !showEmojiPicker"
                  title="表情包"
                >
                  <Smile :size="15" />
                </button>
                <EmojiPicker
                  :visible="showEmojiPicker"
                  @select="insertEmoji"
                  @close="showEmojiPicker = false"
                />
              </div>
              <button
                class="send-btn"
                :class="{ active: inputMessage.trim() }"
                :disabled="!inputMessage.trim() || isSending"
                @click="sendMessage"
              >
                <Send :size="15" />
                <CornerDownLeft :size="12" class="enter-hint" />
              </button>
            </div>
            <div class="input-hints">
              <span class="hint-item">ENTER 发送</span>
              <span class="hint-sep">|</span>
              <span class="hint-item">SHIFT+ENTER 换行</span>
            </div>
          </div>
        </div>

        <OrchestrationPanel
          :visible="orchestrationPanelVisible"
          :status="orchestrationStatus"
          :insight="orchestrationInsight"
          :active-agent="activeAgent"
          :visited-agents="visitedAgents"
          :events="orchestrationEventFeed"
          :system-telemetry="systemTelemetry"
          :session-telemetry="sessionTelemetry"
        />
      </div>
    </section>
  </div>
</template>

<style scoped>
.chat-view {
  display: flex;
  height: 100%;
  overflow: hidden;
}

.sidebar-runtime-panel {
  padding: 12px 14px;
  border-bottom: 1px solid var(--border-dim);
  display: flex;
  flex-direction: column;
  gap: 10px;
  background: linear-gradient(180deg, rgba(7, 12, 24, 0.92), rgba(7, 11, 20, 0.82));
}

.runtime-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 8px;
}

.runtime-card,
.runtime-activity-card {
  border: 1px solid rgba(34, 211, 238, 0.12);
  border-radius: 12px;
  background: rgba(10, 16, 30, 0.74);
  box-shadow: inset 0 1px 0 rgba(255,255,255,0.03);
  padding: 10px;
}

.runtime-topline,
.runtime-activity-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  margin-bottom: 8px;
}

.runtime-label,
.runtime-activity-title,
.runtime-stat-key {
  font-family: var(--font-mono);
  font-size: 9px;
  letter-spacing: 0.12em;
  color: var(--text-dim);
}

.runtime-value,
.runtime-stat-value {
  font-family: var(--font-display);
  font-size: 10px;
  letter-spacing: 0.08em;
  color: var(--text-primary);
}

.runtime-badge {
  padding: 3px 7px;
  border-radius: 999px;
  border: 1px solid rgba(245, 158, 11, 0.2);
  background: rgba(245, 158, 11, 0.1);
  color: var(--accent-amber);
  font-family: var(--font-mono);
  font-size: 8px;
  letter-spacing: 0.14em;
}

.runtime-stats {
  margin-top: 8px;
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 6px;
}

.runtime-stat {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.cpu-card { border-color: rgba(34, 211, 238, 0.22); }
.mem-card { border-color: rgba(167, 139, 250, 0.22); }
.disk-card { border-color: rgba(74, 222, 128, 0.22); }

/* ── Conversation Sidebar ── */
.conv-sidebar {
  width: 260px;
  min-width: 260px;
  background: var(--bg-panel);
  border-right: 1px solid var(--border-dim);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.conv-sidebar-header {
  padding: 12px 14px 10px;
  border-bottom: 1px solid var(--border-dim);
}

.section-label {
  font-family: var(--font-mono);
  font-size: 9px;
  letter-spacing: 0.15em;
  color: var(--text-dim);
}

.sidebar-runtime-panel .section-label {
  margin-bottom: 10px;
}

.conv-sidebar-header .section-label {
  margin-bottom: 0;
}

.conv-sidebar-footer {
  padding: 12px 14px 14px;
  border-top: 1px solid var(--border-dim);
}

.new-chat-btn.muted {
  background: rgba(0, 245, 212, 0.08);
}

.new-chat-btn.muted:hover {
  background: rgba(0, 245, 212, 0.14);
}

.new-chat-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
  padding: 8px 12px;
  background: var(--accent-cyan-dim);
  border: 1px solid var(--border-mid);
  border-radius: var(--radius-md);
  color: var(--accent-cyan);
  font-size: 10px;
  letter-spacing: 0.1em;
  font-weight: 600;
  transition: all var(--transition-fast);
  position: relative;
  overflow: hidden;
}

.new-chat-btn::before {
  content: '';
  position: absolute;
  inset: 0;
  background: linear-gradient(90deg, transparent, rgba(0,245,212,0.1), transparent);
  transform: translateX(-100%);
  transition: transform 0.4s;
}

.new-chat-btn:hover::before { transform: translateX(100%); }

.new-chat-btn:hover {
  background: rgba(0, 245, 212, 0.18);
  box-shadow: var(--glow-cyan);
}

.btn-line {
  width: 1px;
  height: 12px;
  background: var(--accent-cyan);
  opacity: 0.6;
}

.conv-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.conv-item {
  position: relative;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 10px;
  border-radius: var(--radius-md);
  cursor: pointer;
  margin-bottom: 2px;
  border: 1px solid transparent;
  transition: all var(--transition-fast);
  overflow: hidden;
}

.conv-item:hover {
  background: rgba(0, 245, 212, 0.04);
  border-color: var(--border-dim);
}

.conv-item.active {
  background: var(--accent-cyan-dim);
  border-color: var(--border-mid);
}

.conv-active-line {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 2px;
  background: var(--accent-cyan);
  opacity: 0;
  transition: opacity var(--transition-fast);
  box-shadow: 0 0 6px var(--accent-cyan);
}

.conv-item.active .conv-active-line { opacity: 1; }

.conv-item-icon {
  color: var(--text-dim);
  flex-shrink: 0;
}

.conv-item.active .conv-item-icon { color: var(--accent-cyan); }

.conv-item-body { flex: 1; min-width: 0; }

.conv-title {
  font-size: 11px;
  color: var(--text-secondary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 2px;
}

.conv-item.active .conv-title { color: var(--accent-cyan); }

.conv-date {
  font-size: 9px;
  color: var(--text-dim);
  font-family: var(--font-mono);
}

.conv-delete {
  background: none;
  border: none;
  color: var(--text-dim);
  cursor: pointer;
  padding: 3px;
  opacity: 0;
  transition: all var(--transition-fast);
  border-radius: 3px;
}

.conv-item:hover .conv-delete { opacity: 1; }
.conv-delete:hover { color: var(--accent-red); background: rgba(255,71,87,0.1); }

.conv-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 16px;
  gap: 8px;
}

.empty-icon { color: var(--text-dim); }
.empty-text { font-size: 12px; color: var(--text-dim); }
.empty-hint { font-size: 10px; color: var(--text-muted); }

/* ── Chat Area ── */
.chat-area {
  flex: 1;
  overflow: hidden;
  position: relative;
}

.chat-shell {
  display: flex;
  height: 100%;
  overflow: hidden;
}

.chat-main {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-topbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 24px;
  border-bottom: 1px solid var(--border-dim);
  background: rgba(5, 8, 16, 0.6);
  backdrop-filter: blur(8px);
}

.chat-status {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-indicator {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: var(--text-dim);
}

.status-indicator.active {
  background: var(--accent-green);
  box-shadow: 0 0 8px var(--accent-green);
  animation: pulse-glow 1.5s ease-in-out infinite;
}

.status-text {
  font-family: var(--font-mono);
  font-size: 10px;
  letter-spacing: 0.15em;
  color: var(--text-dim);
}

.chat-model-panel {
  display: flex;
  align-items: center;
  gap: 10px;
}

.chat-model-label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-family: var(--font-mono);
  font-size: 10px;
  letter-spacing: 0.12em;
  color: var(--text-dim);
}

.chat-model-select {
  min-width: 220px;
  padding: 7px 12px;
  border: 1px solid rgba(34, 211, 238, 0.2);
  border-radius: 10px;
  background: rgba(10, 16, 28, 0.92);
  color: var(--text-main);
  font-family: var(--font-mono);
  font-size: 12px;
  outline: none;
}

.chat-model-select:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.chat-model {
  display: flex;
  align-items: center;
  gap: 6px;
  font-family: var(--font-display);
  font-size: 9px;
  letter-spacing: 0.1em;
  color: var(--accent-amber);
  padding: 3px 10px;
  border: 1px solid rgba(249, 168, 37, 0.2);
  border-radius: 20px;
  background: var(--accent-amber-dim);
}

/* ── Messages ── */
.messages-area {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

/* Welcome screen */
.welcome-screen {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
  padding-bottom: 80px;
}

.welcome-icon {
  position: relative;
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--accent-cyan);
  margin-bottom: 8px;
}

.welcome-ring {
  position: absolute;
  border-radius: 50%;
  border: 1px solid var(--accent-cyan);
  animation: spin linear infinite;
}

.r1 { width: 80px; height: 80px; opacity: 0.3; animation-duration: 8s; border-style: dashed; }
.r2 { width: 60px; height: 60px; opacity: 0.5; animation-duration: 5s; animation-direction: reverse; }
.r3 { width: 40px; height: 40px; opacity: 0.7; animation-duration: 3s; }

.welcome-core {
  position: relative;
  z-index: 1;
  filter: drop-shadow(0 0 12px var(--accent-cyan));
  animation: pulse-glow 2s ease-in-out infinite;
}

.welcome-title {
  font-family: var(--font-display);
  font-size: 32px;
  font-weight: 800;
  letter-spacing: 0.2em;
  color: var(--accent-cyan);
  text-shadow: var(--glow-cyan);
}

.welcome-sub {
  font-family: var(--font-mono);
  font-size: 10px;
  letter-spacing: 0.3em;
  color: var(--text-dim);
  text-transform: uppercase;
}

.welcome-hint {
  font-size: 13px;
  color: var(--text-dim);
  margin-top: 20px;
}

/* Message rows */
.message-row {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 8px 0;
  animation: fade-in-up 0.3s ease both;
}

.message-row.user {
  flex-direction: row-reverse;
}

.message-row.assistant {
  justify-content: flex-start;
}

.msg-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: var(--font-display);
  font-size: 12px;
  font-weight: 700;
  flex-shrink: 0;
  margin-top: 4px;
}

.user .msg-avatar {
  background: rgba(0, 245, 212, 0.1);
  border: 1px solid var(--border-mid);
  color: var(--accent-cyan);
}

.assistant .msg-avatar {
  background: linear-gradient(135deg, var(--accent-cyan-dim), var(--accent-purple-dim));
  border: 1px solid var(--border-bright);
  color: var(--accent-cyan);
  box-shadow: 0 0 10px var(--accent-cyan-glow);
}

.msg-content {
  display: flex;
  flex-direction: column;
  min-width: 0;
  max-width: min(75%, 820px);
}

.user .msg-content {
  align-items: flex-end;
}

.assistant .msg-content {
  align-items: flex-start;
}

.msg-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 4px;
  flex-wrap: wrap;
}

.user .msg-meta {
  justify-content: flex-end;
}

.msg-role {
  font-family: var(--font-display);
  font-size: 9px;
  letter-spacing: 0.15em;
  color: var(--text-dim);
}

.msg-model {
  font-family: var(--font-mono);
  font-size: 10px;
  color: var(--accent-cyan);
  letter-spacing: 0.08em;
}

.msg-time {
  font-family: var(--font-mono);
  font-size: 9px;
  color: var(--text-muted);
}

.msg-bubble {
  display: inline-block;
  max-width: 100%;
  padding: 10px 16px;
  border-radius: var(--radius-md);
  font-size: 13px;
  line-height: 1.65;
  word-break: break-word;
  white-space: pre-wrap;
}

.user .msg-bubble {
  background: var(--accent-cyan-dim);
  border: 1px solid rgba(0, 245, 212, 0.2);
  border-radius: var(--radius-md) var(--radius-md) 4px var(--radius-md);
  color: var(--text-primary);
}

.assistant .msg-bubble {
  background: rgba(13, 21, 37, 0.8);
  border: 1px solid var(--border-dim);
  border-radius: var(--radius-md) var(--radius-md) var(--radius-md) 4px;
  color: var(--text-secondary);
  backdrop-filter: blur(4px);
}

.think-panel {
  margin-bottom: 8px;
}

.think-summary {
  cursor: pointer;
  list-style: none;
  user-select: none;
}

.think-summary::-webkit-details-marker {
  display: none;
}

.think-chip {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 5px 10px;
  border-radius: 999px;
  border: 1px solid rgba(167, 139, 250, 0.22);
  background: linear-gradient(135deg, rgba(40, 24, 68, 0.72), rgba(18, 24, 48, 0.72));
  color: #c4b5fd;
  font-family: var(--font-mono);
  font-size: 9px;
  letter-spacing: 0.16em;
  box-shadow: inset 0 1px 0 rgba(255,255,255,0.03), 0 0 12px rgba(167, 139, 250, 0.08);
}

.think-chip-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: currentColor;
  box-shadow: 0 0 8px currentColor;
}

.think-content {
  margin-top: 8px;
  padding: 10px 12px;
  border: 1px solid rgba(167, 139, 250, 0.14);
  border-radius: 12px;
  background: rgba(18, 20, 34, 0.55);
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.think-block {
  font-size: 12px;
  line-height: 1.6;
  color: var(--text-dim);
}

.markdown-body :deep(p),
.think-block :deep(p) {
  margin: 0;
}

.markdown-body :deep(p + p),
.think-block :deep(p + p) {
  margin-top: 10px;
}

.markdown-body :deep(.md-heading),
.think-block :deep(.md-heading) {
  margin: 0 0 8px;
  font-size: 13px;
  line-height: 1.5;
  color: var(--text-primary);
}

.markdown-body :deep(.md-list),
.think-block :deep(.md-list) {
  margin: 0;
  padding-left: 18px;
}

.markdown-body :deep(.md-list li),
.think-block :deep(.md-list li) {
  margin: 4px 0;
}

.markdown-body :deep(code),
.think-block :deep(code) {
  padding: 1px 5px;
  border-radius: 6px;
  background: rgba(148, 163, 184, 0.14);
  font-family: var(--font-mono);
  font-size: 12px;
}

.markdown-body :deep(.md-pre),
.think-block :deep(.md-pre) {
  margin: 0;
  padding: 10px 12px;
  border-radius: 10px;
  background: rgba(5, 10, 20, 0.78);
  border: 1px solid rgba(148, 163, 184, 0.12);
  overflow-x: auto;
}

.markdown-body :deep(.md-pre code),
.think-block :deep(.md-pre code) {
  padding: 0;
  background: transparent;
}

.markdown-body :deep(.md-table-wrap),
.think-block :deep(.md-table-wrap) {
  width: 100%;
  overflow-x: auto;
  margin: 2px 0;
  border-radius: 10px;
  border: 1px solid rgba(34, 211, 238, 0.16);
  background: rgba(5, 10, 20, 0.46);
}

.markdown-body :deep(.md-table),
.think-block :deep(.md-table) {
  width: 100%;
  min-width: 320px;
  border-collapse: collapse;
  font-size: 12px;
}

.markdown-body :deep(.md-table th),
.markdown-body :deep(.md-table td),
.think-block :deep(.md-table th),
.think-block :deep(.md-table td) {
  padding: 8px 10px;
  border: 1px solid rgba(148, 163, 184, 0.16);
  text-align: left;
  vertical-align: top;
}

.markdown-body :deep(.md-table th),
.think-block :deep(.md-table th) {
  background: rgba(34, 211, 238, 0.1);
  color: var(--text-primary);
  font-family: var(--font-mono);
  font-size: 10px;
  letter-spacing: 0.12em;
}

.markdown-body :deep(.md-table tbody tr:nth-child(even)),
.think-block :deep(.md-table tbody tr:nth-child(even)) {
  background: rgba(148, 163, 184, 0.04);
}

.think-panel[open] .think-chip {
  border-color: rgba(167, 139, 250, 0.3);
  color: #ddd6fe;
}

.think-panel[open] .think-chip-dot {
  animation: pulse-glow 1.4s ease-in-out infinite;
}

/* Typing indicator */
.thinking-row {
  padding-top: 2px;
}

.thinking-bubble {
  min-width: 280px;
  padding: 12px 14px;
  background: linear-gradient(135deg, rgba(12, 20, 36, 0.92), rgba(16, 18, 34, 0.84));
  border-color: rgba(34, 211, 238, 0.18);
}

.thinking-hud {
  display: flex;
  align-items: center;
  gap: 14px;
}

.thinking-core {
  position: relative;
  width: 28px;
  height: 28px;
  flex-shrink: 0;
}

.thinking-ring,
.thinking-dot {
  position: absolute;
  inset: 0;
  border-radius: 50%;
}

.thinking-ring {
  border: 1px solid rgba(34, 211, 238, 0.45);
}

.ring-1 {
  animation: spin 2.6s linear infinite;
}

.ring-2 {
  inset: 4px;
  border-color: rgba(167, 139, 250, 0.38);
  animation: spin 1.8s linear infinite reverse;
}

.ring-3 {
  inset: 8px;
  border-color: rgba(245, 158, 11, 0.36);
  animation: pulse-glow 1.4s ease-in-out infinite;
}

.thinking-dot {
  inset: 11px;
  background: var(--accent-cyan);
  box-shadow: 0 0 10px rgba(34, 211, 238, 0.7);
}

.thinking-copy {
  min-width: 0;
  flex: 1;
}

.thinking-title {
  font-family: var(--font-display);
  font-size: 10px;
  letter-spacing: 0.14em;
  color: var(--accent-cyan);
}

.thinking-subtitle {
  margin-top: 3px;
  font-size: 12px;
  color: var(--text-dim);
}

.typing .dot,
.typing-inline .dot {
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background: var(--accent-cyan);
  margin: 0 2px;
  animation: typing-bounce 1.2s ease-in-out infinite;
}

.typing-inline {
  flex-shrink: 0;
  white-space: nowrap;
}

.typing .dot:nth-child(2),
.typing-inline .dot:nth-child(2) { animation-delay: 0.2s; }
.typing .dot:nth-child(3),
.typing-inline .dot:nth-child(3) { animation-delay: 0.4s; }

@keyframes typing-bounce {
  0%, 60%, 100% { transform: translateY(0); opacity: 0.4; }
  30% { transform: translateY(-4px); opacity: 1; }
}

/* ── Input Area ── */
.input-area {
  padding: 16px 24px 20px;
  border-top: 1px solid var(--border-dim);
  background: rgba(5, 8, 16, 0.8);
  backdrop-filter: blur(12px);
}

.input-frame {
  position: relative;
  background: var(--bg-card);
  border: 1px solid var(--border-mid);
  border-radius: var(--radius-lg);
  padding: 12px 16px;
  display: flex;
  align-items: flex-end;
  gap: 12px;
  transition: all var(--transition-mid);
}

.input-frame:focus-within {
  border-color: var(--accent-cyan);
  box-shadow: 0 0 0 1px rgba(0,245,212,0.1), var(--glow-cyan);
}

/* Corner accents */
.input-corners {
  position: absolute;
  width: 8px;
  height: 8px;
  pointer-events: none;
}
.input-corners::before,
.input-corners::after {
  content: '';
  position: absolute;
  background: var(--accent-cyan);
}
.input-corners::before { width: 100%; height: 1px; }
.input-corners::after { width: 1px; height: 100%; }
.tl { top: -1px; left: -1px; }
.tr { top: -1px; right: -1px; transform: scaleX(-1); }
.bl { bottom: -1px; left: -1px; transform: scaleY(-1); }
.br { bottom: -1px; right: -1px; transform: scale(-1); }

.input-frame textarea {
  flex: 1;
  background: transparent;
  border: none;
  outline: none;
  color: var(--text-primary);
  font-family: var(--font-mono);
  font-size: 13px;
  line-height: 1.6;
  resize: none;
  max-height: 120px;
  padding: 8px 0;
  vertical-align: middle;
  overflow: hidden;
}

.input-frame textarea::placeholder { color: var(--text-dim); }

.send-btn {
  width: 36px;
  height: 36px;
  border-radius: var(--radius-md);
  background: var(--text-muted);
  border: 1px solid transparent;
  color: var(--text-dim);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  position: relative;
  transition: all var(--transition-fast);
}

.send-btn.active {
  background: var(--accent-cyan-dim);
  border-color: var(--border-mid);
  color: var(--accent-cyan);
}

.send-btn.active:hover {
  background: rgba(0, 245, 212, 0.2);
  box-shadow: var(--glow-cyan);
  transform: scale(1.05);
}

.enter-hint { display: none; }

.input-hints {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
  padding-left: 4px;
}

.hint-item {
  font-family: var(--font-mono);
  font-size: 9px;
  letter-spacing: 0.1em;
  color: var(--text-muted);
}

.hint-sep {
  color: var(--text-muted);
  font-size: 9px;
}

/* File attachment button */
.attach-btn {
  width: 36px;
  height: 36px;
  border-radius: var(--radius-md);
  background: transparent;
  border: 1px solid transparent;
  color: var(--text-dim);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all var(--transition-fast);
}
.attach-btn:hover {
  background: var(--accent-cyan-dim);
  border-color: var(--border-mid);
  color: var(--accent-cyan);
}

/* Emoji button */
.emoji-wrapper {
  position: relative;
}
.emoji-btn {
  width: 36px;
  height: 36px;
  border-radius: var(--radius-md);
  background: transparent;
  border: 1px solid transparent;
  color: var(--text-dim);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all var(--transition-fast);
}
.emoji-btn:hover,
.emoji-btn.active {
  background: var(--accent-cyan-dim);
  border-color: var(--border-mid);
  color: var(--accent-cyan);
}

/* Message attachments */
.msg-attachments {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
}
</style>
