<script setup lang="ts">
import { onMounted, onUnmounted, ref, computed, watch, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useChatStore } from "@/stores/chat";
import { useSettingsStore } from "@/stores/settings";
import { apiGet } from "@/api/client";
import { renderMarkdown } from "@/utils/markdown";
import ChatMessage from "@/components/ChatMessage.vue";
import ToolCallCard from "@/components/ToolCallCard.vue";
import ToolConfirmCard from "@/components/ToolConfirmCard.vue";
import type { Note } from "@/types/note";

const route = useRoute();
const router = useRouter();
const store = useChatStore();
const settingsStore = useSettingsStore();

const messageInput = ref("");
const messagesEl = ref<HTMLElement | null>(null);
const inputEl = ref<HTMLTextAreaElement | null>(null);
const sending = ref(false);
const summarizing = ref(false);
const sidebarOpen = ref(false);

// Note picker state
const attachedNote = ref<{ id: number; title: string } | null>(null);
const showNotePicker = ref(false);
const noteSearchQuery = ref("");
const noteSearchResults = ref<{ id: number; title: string }[]>([]);
const noteSearchLoading = ref(false);
let noteSearchTimer: ReturnType<typeof setTimeout> | null = null;

// Exclude tracking (session-scoped per conversation)
const excludedNoteIds = ref<Set<number>>(new Set());

// Persistent context notes — populated as assistant responds, cleared on conv change
const contextNotes = ref<{ id: number; title: string }[]>([]);

let prevConvId: number | null = null;

const convId = computed(() => {
  const id = route.params.id;
  return id ? Number(id) : null;
});

function formatConvDate(dateStr: string): string {
  const date = new Date(dateStr);
  const now = new Date();
  const diffMs = now.getTime() - date.getTime();
  const diffMin = Math.floor(diffMs / 60_000);
  const diffHrs = Math.floor(diffMs / 3_600_000);

  // Relative time for < 10 hours
  if (diffMin < 1) return "Just now";
  if (diffMin < 60) return `${diffMin}m ago`;
  if (diffHrs < 10) return `${diffHrs}h ago`;

  // Date for older
  if (date.getFullYear() === now.getFullYear()) {
    return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
  }
  return date.toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" });
}

const streamingRendered = computed(() => {
  if (!store.streamingContent) return "";
  return renderMarkdown(store.streamingContent);
});

const inputPlaceholder = computed(() => {
  if (!store.chatReady) return "Chat unavailable";
  return "Type a message... (Enter to send, Shift+Enter for new line)";
});

onMounted(async () => {
  document.addEventListener("keydown", onGlobalKeydown);
  await store.fetchConversations();
  if (convId.value && store.currentConversation?.id !== convId.value) {
    await store.fetchConversation(convId.value);
  }
  nextTick(() => inputEl.value?.focus());
});

watch(convId, async (newId) => {
  // Clean up empty previous conversation
  if (prevConvId && prevConvId !== newId) {
    const prev = store.conversations.find((c) => c.id === prevConvId);
    if (prev && prev.message_count === 0) {
      store.deleteConversation(prevConvId);
    }
  }
  prevConvId = newId ?? null;

  excludedNoteIds.value = new Set();
  contextNotes.value = [];
  attachedNote.value = null;
  store.lastContextMeta = null;
  if (newId) {
    // Skip re-fetch if this conversation is already loaded (avoids race
    // condition where a stale GET overwrites messages during streaming)
    if (store.currentConversation?.id !== newId) {
      await store.fetchConversation(newId);
    }
    scrollToBottom();
  } else {
    store.currentConversation = null;
  }
  nextTick(() => inputEl.value?.focus());
});

watch(
  () => store.streamingContent,
  () => scrollToBottom()
);

watch(
  () => store.lastContextMeta?.auto_notes,
  (newNotes) => {
    if (!newNotes) return;
    const excluded = excludedNoteIds.value;
    const existing = new Set(contextNotes.value.map((n) => n.id));
    for (const note of newNotes) {
      if (!excluded.has(note.id) && !existing.has(note.id)) {
        contextNotes.value.push(note);
        existing.add(note.id);
      }
    }
  }
);

function scrollToBottom() {
  nextTick(() => {
    if (messagesEl.value) {
      messagesEl.value.scrollTop = messagesEl.value.scrollHeight;
    }
  });
}

function toggleSidebar() {
  sidebarOpen.value = !sidebarOpen.value;
}

async function selectConversation(id: number) {
  sidebarOpen.value = false;
  router.push(`/chat/${id}`);
}

async function newConversation() {
  const conv = await store.createConversation();
  await store.fetchConversation(conv.id);
  router.push(`/chat/${conv.id}`);
}

async function removeConversation(id: number) {
  await store.deleteConversation(id);
  if (convId.value === id) {
    router.push("/chat");
  }
}

async function sendMessage() {
  const content = messageInput.value.trim();
  if (!content || store.streaming) return;

  // Auto-create conversation if none selected
  if (!store.currentConversation) {
    const conv = await store.createConversation();
    await store.fetchConversation(conv.id);
    router.push(`/chat/${conv.id}`);
  }

  sending.value = true;
  const contextNoteId = attachedNote.value?.id ?? undefined;
  const contextNoteTitle = attachedNote.value?.title ?? undefined;
  attachedNote.value = null;
  messageInput.value = "";
  resetTextareaHeight();
  scrollToBottom();

  await store.sendMessage(
    content,
    contextNoteId,
    excludedNoteIds.value.size ? [...excludedNoteIds.value] : undefined,
    true, // enable thinking in the full chat view
    contextNoteTitle,
  );
  sending.value = false;

  // Refresh conversation list to show updated title/timestamps
  store.fetchConversations();
  scrollToBottom();
  nextTick(() => inputEl.value?.focus());
}

async function handleSaveAsNote(messageId: number) {
  try {
    await store.saveMessageAsNote(messageId);
    const { useToastStore } = await import("@/stores/toast");
    useToastStore().show("Saved as note");
  } catch {
    const { useToastStore } = await import("@/stores/toast");
    useToastStore().show("Failed to save as note", "error");
  }
}

async function handleSummarize() {
  if (!store.currentConversation || summarizing.value) return;
  summarizing.value = true;
  try {
    await store.summarizeAsNote(store.currentConversation.id);
    const { useToastStore } = await import("@/stores/toast");
    useToastStore().show("Conversation summarized and saved as note");
  } catch {
    const { useToastStore } = await import("@/stores/toast");
    useToastStore().show("Failed to summarize", "error");
  } finally {
    summarizing.value = false;
  }
}

function autoResize() {
  const el = inputEl.value;
  if (!el) return;
  el.style.height = "auto";
  el.style.height = Math.min(el.scrollHeight, 150) + "px";
}

function resetTextareaHeight() {
  const el = inputEl.value;
  if (!el) return;
  el.style.height = "auto";
}

function onInputKeydown(e: KeyboardEvent) {
  if (e.key === "Enter" && !e.shiftKey) {
    e.preventDefault();
    sendMessage();
  }
}

// Note picker
function toggleNotePicker() {
  showNotePicker.value = !showNotePicker.value;
  if (showNotePicker.value) {
    noteSearchQuery.value = "";
    noteSearchResults.value = [];
    nextTick(() => {
      const el = document.querySelector(".note-picker-search") as HTMLInputElement;
      el?.focus();
    });
  }
}

function onNoteSearchInput() {
  if (noteSearchTimer) clearTimeout(noteSearchTimer);
  noteSearchTimer = setTimeout(async () => {
    const q = noteSearchQuery.value.trim();
    if (!q) {
      noteSearchResults.value = [];
      return;
    }
    noteSearchLoading.value = true;
    try {
      const data = await apiGet<{ notes: Note[] }>(
        `/api/notes?q=${encodeURIComponent(q)}&all=true&limit=5`
      );
      noteSearchResults.value = data.notes.map((n) => ({ id: n.id, title: n.title }));
    } catch {
      noteSearchResults.value = [];
    } finally {
      noteSearchLoading.value = false;
    }
  }, 250);
}

function selectNote(note: { id: number; title: string }) {
  attachedNote.value = note;
  showNotePicker.value = false;
}

function removeAttachedNote() {
  attachedNote.value = null;
}

function excludeAutoNote(noteId: number) {
  excludedNoteIds.value = new Set([...excludedNoteIds.value, noteId]);
  contextNotes.value = contextNotes.value.filter((n) => n.id !== noteId);
}

// Keyboard shortcuts
function onGlobalKeydown(e: KeyboardEvent) {
  if (e.key !== "Escape") return;
  // Close note picker first
  if (showNotePicker.value) {
    showNotePicker.value = false;
    return;
  }
  // Close mobile sidebar overlay
  if (sidebarOpen.value) {
    sidebarOpen.value = false;
    return;
  }
  // If textarea is focused and has content, clear it (don't navigate away)
  if (document.activeElement === inputEl.value && messageInput.value.trim()) {
    messageInput.value = "";
    resetTextareaHeight();
    return;
  }
  // Navigate home
  router.push("/");
}

onUnmounted(() => {
  document.removeEventListener("keydown", onGlobalKeydown);
});
</script>

<template>
  <main class="chat-page">
    <div
      v-if="sidebarOpen"
      class="sidebar-overlay"
      @click="sidebarOpen = false"
    ></div>
    <aside class="chat-sidebar" :class="{ open: sidebarOpen }">
      <button class="btn-new-conv" @click="newConversation">
        + New Chat
      </button>
      <div class="conv-list">
        <div
          v-for="conv in store.conversations"
          :key="conv.id"
          class="conv-item"
          :class="{ active: convId === conv.id }"
          @click="selectConversation(conv.id)"
        >
          <div class="conv-info">
            <span class="conv-title">{{ conv.title || "Untitled" }}</span>
            <span class="conv-date">{{ formatConvDate(conv.updated_at) }}</span>
          </div>
          <button
            class="btn-delete-conv"
            @click.stop="removeConversation(conv.id)"
            title="Delete conversation"
          >
            &times;
          </button>
        </div>
        <p v-if="!store.conversations.length" class="empty-msg">
          No conversations yet
        </p>
      </div>
    </aside>

    <section class="chat-main">
      <template v-if="store.currentConversation">
        <div class="chat-header">
          <button class="btn-sidebar-toggle hide-desktop" @click="toggleSidebar">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <line x1="3" y1="6" x2="21" y2="6"/>
              <line x1="3" y1="12" x2="21" y2="12"/>
              <line x1="3" y1="18" x2="21" y2="18"/>
            </svg>
          </button>
          <h2>{{ store.currentConversation.title || "New Chat" }}</h2>
          <button
            v-if="store.currentConversation.messages.length"
            class="btn-summarize"
            @click="handleSummarize"
            :disabled="summarizing || store.streaming"
          >
            {{ summarizing ? "Summarizing..." : "Summarize as Note" }}
          </button>
        </div>

        <div class="chat-body">
          <div ref="messagesEl" class="messages-container">
            <div class="messages-inner">
              <ChatMessage
                v-for="msg in store.currentConversation.messages"
                :key="msg.id"
                :message="msg"
                @save-as-note="handleSaveAsNote"
              />

              <!-- Streaming message (assistant typing) -->
              <div v-if="store.streaming" class="chat-message role-assistant">
                <div class="message-bubble streaming-bubble">
                  <div class="message-header">
                    <span class="role-label">{{ settingsStore.assistantName }}</span>
                  </div>
                  <div v-if="store.streamingToolCalls.length" class="streaming-tool-calls">
                    <ToolCallCard
                      v-for="(tc, i) in store.streamingToolCalls"
                      :key="i"
                      :tool-call="tc"
                    />
                  </div>
                  <ToolConfirmCard
                    v-if="store.streamingPendingTool"
                    :pending-tool="store.streamingPendingTool"
                    @accept="store.confirmTool(true)"
                    @decline="store.confirmTool(false)"
                  />
                  <div v-if="store.streamingStatus" class="streaming-status-line">
                    <span class="streaming-status-dot"></span>
                    {{ store.streamingStatus }}
                  </div>
                  <div class="message-content prose" v-html="streamingRendered"></div>
                  <span v-if="!store.streamingStatus" class="typing-indicator"></span>
                </div>
              </div>

              <p
                v-if="!store.currentConversation.messages.length && !store.streaming"
                class="empty-msg"
              >
                Send a message to start the conversation.
              </p>
            </div>
          </div>

          <!-- Persistent context sidebar -->
          <aside v-if="contextNotes.length || attachedNote" class="context-sidebar">
            <div class="context-sidebar-header">In Context</div>

            <!-- Manually attached note — pinned until sent -->
            <div v-if="attachedNote" class="context-note context-note-pinned">
              <span class="context-note-icon" title="Attached for this message">📌</span>
              <router-link :to="`/notes/${attachedNote.id}`" class="context-note-name">
                {{ attachedNote.title }}
              </router-link>
              <button class="context-note-remove" @click="removeAttachedNote" title="Remove">&times;</button>
            </div>

            <!-- Auto-found notes — persist across turns -->
            <div v-for="note in contextNotes" :key="note.id" class="context-note">
              <router-link :to="`/notes/${note.id}`" class="context-note-name">
                {{ note.title }}
              </router-link>
              <button class="context-note-remove" @click="excludeAutoNote(note.id)" title="Remove from context">&times;</button>
            </div>
          </aside>
        </div>

        <div class="input-wrapper">
          <div class="input-area">
            <!-- Note picker button -->
            <div class="note-picker-wrapper">
              <button
                class="btn-attach"
                @click="toggleNotePicker"
                :disabled="store.streaming || !store.chatReady"
                title="Attach a note"
              >
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <path d="M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"/>
                </svg>
              </button>

              <!-- Note picker dropdown -->
              <div v-if="showNotePicker" class="note-picker-dropdown">
                <input
                  class="note-picker-search"
                  v-model="noteSearchQuery"
                  @input="onNoteSearchInput"
                  placeholder="Search notes..."
                />
                <div class="note-picker-results">
                  <div
                    v-for="note in noteSearchResults"
                    :key="note.id"
                    class="note-picker-item"
                    @click="selectNote(note)"
                  >
                    {{ note.title || "Untitled" }}
                  </div>
                  <div v-if="noteSearchLoading" class="note-picker-empty">Searching...</div>
                  <div v-else-if="noteSearchQuery && !noteSearchResults.length" class="note-picker-empty">
                    No notes found
                  </div>
                </div>
              </div>
            </div>

            <textarea
              ref="inputEl"
              v-model="messageInput"
              @keydown="onInputKeydown"
              @input="autoResize"
              :placeholder="inputPlaceholder"
              :disabled="store.streaming || !store.chatReady"
              rows="1"
            ></textarea>
            <button
              v-if="store.streaming"
              class="btn-stop"
              @click="store.cancelGeneration()"
              title="Stop generation"
            >
              <svg width="14" height="14" viewBox="0 0 14 14" fill="currentColor">
                <rect width="14" height="14" rx="2" />
              </svg>
            </button>
            <button
              v-else
              class="btn-send"
              @click="sendMessage"
              :disabled="!messageInput.trim() || !store.chatReady"
            >
              &uarr;
            </button>
          </div>
        </div>
      </template>

      <div v-else class="no-conversation">
        <button class="btn-sidebar-toggle no-conv-toggle hide-desktop" @click="toggleSidebar">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <line x1="3" y1="6" x2="21" y2="6"/>
            <line x1="3" y1="12" x2="21" y2="12"/>
            <line x1="3" y1="18" x2="21" y2="18"/>
          </svg>
        </button>
        <p>Select a conversation or start a new chat.</p>
        <button class="btn-new-conv" @click="newConversation">
          + New Chat
        </button>
      </div>
    </section>
  </main>
</template>

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

.chat-sidebar {
  width: 260px;
  min-width: 200px;
  border-right: 1px solid var(--color-border);
  display: flex;
  flex-direction: column;
  background: var(--color-bg-secondary);
}

.btn-new-conv {
  margin: 0.75rem;
  padding: 0.5rem;
  background: var(--color-primary);
  color: #fff;
  border: none;
  border-radius: var(--radius-sm);
  cursor: pointer;
  font-size: 0.9rem;
}
.btn-new-conv:hover {
  opacity: 0.9;
}

.conv-list {
  flex: 1;
  overflow-y: auto;
  padding: 0 0.5rem;
}

.conv-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.5rem 0.75rem;
  border-radius: var(--radius-sm);
  cursor: pointer;
  margin-bottom: 0.25rem;
}
.conv-item:hover {
  background: var(--color-bg-card);
}
.conv-item.active {
  background: var(--color-primary);
  color: #fff;
}
.conv-info {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
}
.conv-title {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 0.9rem;
}
.conv-date {
  font-size: 0.75rem;
  color: var(--color-text-muted);
  margin-top: 1px;
}
.conv-item.active .conv-date {
  color: rgba(255, 255, 255, 0.7);
}
.btn-delete-conv {
  background: none;
  border: none;
  color: var(--color-text-muted);
  cursor: pointer;
  font-size: 1.2rem;
  padding: 0 0.25rem;
  line-height: 1;
}
.conv-item.active .btn-delete-conv {
  color: rgba(255, 255, 255, 0.7);
}
.btn-delete-conv:hover {
  color: var(--color-danger, #e74c3c);
}

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

.chat-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.75rem 1rem;
  border-bottom: 1px solid var(--color-border);
}
.chat-header h2 {
  margin: 0;
  font-size: 1.1rem;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
  min-width: 0;
}

.btn-summarize {
  padding: 0.3rem 0.75rem;
  background: var(--color-bg-secondary);
  color: var(--color-text);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-sm);
  cursor: pointer;
  font-size: 0.85rem;
  white-space: nowrap;
}
.btn-summarize:hover:not(:disabled) {
  background: var(--color-primary);
  color: #fff;
  border-color: var(--color-primary);
}
.btn-summarize:disabled {
  opacity: 0.6;
  cursor: default;
}

.chat-body {
  flex: 1;
  display: flex;
  min-height: 0;
  overflow: hidden;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 1rem 1.5rem;
  display: flex;
  flex-direction: column;
  max-width: 960px;
  margin: 0 auto;
  width: 100%;
}

.context-sidebar {
  width: 220px;
  min-width: 180px;
  border-left: 1px solid var(--color-border);
  background: var(--color-bg-secondary);
  display: flex;
  flex-direction: column;
  padding: 0.75rem;
  gap: 0.35rem;
  overflow-y: auto;
}
.context-sidebar-header {
  font-size: 0.7rem;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  color: var(--color-text-muted);
  margin-bottom: 0.25rem;
}
.context-note {
  display: flex;
  align-items: center;
  gap: 0.3rem;
  padding: 0.3rem 0.4rem;
  border-radius: var(--radius-sm);
  background: var(--color-bg-card);
  border: 1px solid var(--color-border);
  font-size: 0.82rem;
}
.context-note-pinned {
  border-color: var(--color-primary);
}
.context-note-icon {
  font-size: 0.75rem;
  flex-shrink: 0;
}
.context-note-name {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: var(--color-text);
  text-decoration: none;
}
.context-note-name:hover {
  color: var(--color-primary);
}
.context-note-remove {
  background: none;
  border: none;
  cursor: pointer;
  color: var(--color-text-muted);
  font-size: 1rem;
  line-height: 1;
  padding: 0 0.1rem;
  flex-shrink: 0;
}
.context-note-remove:hover {
  color: var(--color-danger, #e74c3c);
}
.messages-inner {
  margin-top: auto;
}

/* Streaming bubble — matches ChatMessage assistant style */
.chat-message {
  display: flex;
  margin-bottom: 0.75rem;
}
.role-assistant {
  justify-content: flex-start;
}
.streaming-bubble {
  max-width: 80%;
  padding: 0.75rem 1rem;
  border-radius: 16px;
  border-bottom-left-radius: 4px;
  background: var(--color-bg-card);
  border: 1px solid var(--color-border);
}
.streaming-bubble .message-header {
  display: flex;
  align-items: center;
  margin-bottom: 0.25rem;
}
.streaming-bubble .role-label {
  font-size: 0.75rem;
  font-weight: 600;
  color: var(--color-text-muted);
  text-transform: uppercase;
  letter-spacing: 0.03em;
}
.streaming-bubble .message-content {
  font-size: 0.95rem;
  line-height: 1.55;
  word-break: break-word;
}

.streaming-tool-calls {
  display: flex;
  flex-wrap: wrap;
  gap: 0.3rem;
  margin-bottom: 0.4rem;
}
.streaming-status-line {
  display: flex;
  align-items: center;
  gap: 0.4rem;
  font-size: 0.8rem;
  color: var(--color-text-muted);
  font-style: italic;
  margin-bottom: 0.3rem;
}
.streaming-status-dot {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: var(--color-primary);
  animation: blink 1s infinite;
  flex-shrink: 0;
}
.typing-indicator {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: var(--color-primary);
  animation: blink 1s infinite;
  margin-left: 4px;
  vertical-align: middle;
}
@keyframes blink {
  0%, 100% { opacity: 0.3; }
  50% { opacity: 1; }
}

/* Input wrapper */
.input-wrapper {
  max-width: 960px;
  margin: 0 auto 2rem;
  padding: 0 1rem;
  width: 100%;
  box-sizing: border-box;
}

/* Floating input bar */
.input-area {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 0.5rem 0.5rem 0.75rem;
  background: var(--color-input-bar-bg);
  border-radius: 20px;
  box-shadow: 0 2px 12px var(--color-shadow);
}

/* Note picker */
.note-picker-wrapper {
  position: relative;
}
.btn-attach {
  background: none;
  border: none;
  cursor: pointer;
  color: var(--color-input-bar-text);
  opacity: 0.6;
  padding: 0.25rem;
  display: flex;
  align-items: center;
  justify-content: center;
}
.btn-attach:hover {
  opacity: 1;
}
.btn-attach:disabled {
  opacity: 0.3;
  cursor: default;
}
.note-picker-dropdown {
  position: absolute;
  bottom: calc(100% + 8px);
  left: 0;
  width: 280px;
  background: var(--color-bg-card);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-md);
  box-shadow: 0 4px 16px var(--color-shadow);
  z-index: 10;
  overflow: hidden;
}
.note-picker-search {
  width: 100%;
  padding: 0.5rem 0.75rem;
  border: none;
  border-bottom: 1px solid var(--color-border);
  background: transparent;
  color: var(--color-text);
  font-size: 0.9rem;
  outline: none;
  font-family: inherit;
  box-sizing: border-box;
}
.note-picker-results {
  max-height: 200px;
  overflow-y: auto;
}
.note-picker-item {
  padding: 0.5rem 0.75rem;
  cursor: pointer;
  font-size: 0.9rem;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.note-picker-item:hover {
  background: var(--color-bg-secondary);
}
.note-picker-empty {
  padding: 0.5rem 0.75rem;
  color: var(--color-text-muted);
  font-size: 0.85rem;
}
.input-area textarea {
  flex: 1;
  resize: none;
  padding: 0.4rem 0.5rem;
  border: none;
  border-radius: 12px;
  font-family: inherit;
  font-size: 0.95rem;
  background: transparent;
  color: var(--color-input-bar-text);
  outline: none;
  max-height: 150px;
  overflow-y: auto;
}
.input-area textarea::placeholder {
  color: var(--color-input-bar-placeholder);
}
.input-area textarea:disabled {
  opacity: 0.5;
}
.btn-send {
  width: 34px;
  min-width: 34px;
  height: 34px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--color-primary);
  color: #fff;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  font-size: 1.1rem;
  flex-shrink: 0;
}
.btn-send:disabled {
  opacity: 0.35;
  cursor: default;
}
.btn-stop {
  width: 34px;
  min-width: 34px;
  height: 34px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--color-danger, #e74c3c);
  color: #fff;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  flex-shrink: 0;
}
.btn-stop:hover {
  opacity: 0.85;
}

.no-conversation {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 1rem;
  color: var(--color-text-muted);
}

.empty-msg {
  color: var(--color-text-muted);
  font-size: 0.9rem;
  text-align: center;
  padding: 1rem;
}

.btn-sidebar-toggle {
  background: none;
  border: none;
  cursor: pointer;
  color: var(--color-text);
  padding: 0.25rem;
  display: flex;
  align-items: center;
  justify-content: center;
}
.no-conv-toggle {
  position: absolute;
  top: 0.75rem;
  left: 0.75rem;
}
.no-conversation {
  position: relative;
}

.sidebar-overlay {
  display: none;
}

@media (max-width: 768px) {
  .chat-sidebar {
    position: fixed;
    top: 49px;
    left: 0;
    bottom: 0;
    z-index: 100;
    transform: translateX(-100%);
    transition: transform 0.25s ease;
    width: 260px;
  }
  .chat-sidebar.open {
    transform: translateX(0);
  }
  .sidebar-overlay {
    display: block;
    position: fixed;
    inset: 0;
    top: 49px;
    background: var(--color-overlay);
    z-index: 99;
  }
  .context-sidebar {
    display: none;
  }
  .messages-container {
    padding: 0.75rem;
  }
  .input-wrapper {
    padding: 0 0.5rem;
    margin-bottom: 0.5rem;
  }
}
</style>
