<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 { apiGet } from "@/api/client";
import ChatPanel from "@/components/ChatPanel.vue";
import { MoreVertical, Menu, Paperclip, Trash2 } from "lucide-vue-next";

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

const summarizing = ref(false);
const sidebarOpen = ref(false);
const convSearchQuery = ref("");
const headerKebabOpen = ref(false);
const sidebarKebabOpen = ref(false);

// ── RAG scope chip ────────────────────────────────────────────────────────────
const projects = ref<{ id: number; title: string }[]>([]);
const scopeDropdownOpen = ref(false);
const scopePulse = ref(false);

const scopeLabel = computed(() => {
  const id = store.ragProjectId;
  if (id === -1) return "All notes";
  if (id === null) return "Orphan notes";
  return projects.value.find((p) => p.id === id)?.title ?? `Project ${id}`;
});

async function loadProjects() {
  try {
    const data = await apiGet<{ projects: { id: number; title: string }[] }>(
      "/api/projects?status=active"
    );
    projects.value = data.projects ?? [];
  } catch {
    projects.value = [];
  }
}

async function onScopeSelect(value: number | null) {
  scopeDropdownOpen.value = false;
  const id = store.currentConversation?.id;
  if (!id) return;
  await store.updateRagScope(id, value);
  scopePulse.value = true;
  setTimeout(() => { scopePulse.value = false; }, 600);
}

watch(
  () => store.ragProjectId,
  () => {
    scopePulse.value = true;
    setTimeout(() => { scopePulse.value = false; }, 600);
  }
);

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);

  if (diffMin < 1) return "Just now";
  if (diffMin < 60) return `${diffMin}m ago`;
  if (diffHrs < 10) return `${diffHrs}h ago`;
  if (date.getFullYear() === now.getFullYear()) {
    return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
  }
  return date.toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" });
}

interface ConvGroup { label: string; convs: typeof store.conversations }

const groupedConversations = computed((): ConvGroup[] => {
  const now = new Date();
  const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const startOfYesterday = new Date(startOfToday.getTime() - 86_400_000);
  const startOfWeek = new Date(startOfToday.getTime() - 6 * 86_400_000);
  const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);

  const buckets: Record<string, typeof store.conversations> = {};
  const order: string[] = [];

  const q = convSearchQuery.value.trim().toLowerCase();
  const filtered = q
    ? store.conversations.filter((c) => (c.title || "").toLowerCase().includes(q))
    : store.conversations;

  for (const conv of filtered) {
    const d = new Date(conv.updated_at);
    let key: string;
    if (d >= startOfToday) {
      key = "Today";
    } else if (d >= startOfYesterday) {
      key = "Yesterday";
    } else if (d >= startOfWeek) {
      key = "This week";
    } else if (d >= startOfMonth) {
      key = "This month";
    } else {
      key = d.toLocaleDateString(undefined, { month: "long", year: "numeric" });
    }
    if (!buckets[key]) { buckets[key] = []; order.push(key); }
    buckets[key].push(conv);
  }

  return order.map((label) => ({ label, convs: buckets[label] }));
});

onMounted(async () => {
  document.addEventListener("keydown", onGlobalKeydown);
  document.addEventListener("mousedown", onDocumentMousedown);
  loadProjects();
  await store.fetchConversations();
  if (convId.value) {
    if (store.currentConversation?.id !== convId.value) {
      await store.fetchConversation(convId.value);
    }
    store.reconnectIfGenerating(convId.value);
  } else {
    await startNewConversation();
  }
  nextTick(() => chatPanelRef.value?.focus());
});

watch(convId, async (newId) => {
  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;

  if (newId) {
    if (store.currentConversation?.id !== newId && !store.isStreamingConv(newId)) {
      await store.fetchConversation(newId);
    }
    store.reconnectIfGenerating(newId);
  } else {
    await startNewConversation();
  }
  nextTick(() => chatPanelRef.value?.focus());
});

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

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

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

async function newConversation() {
  await startNewConversation();
}

// ── Bulk selection ────────────────────────────────────────────────────────────
const selectMode = ref(false);
const selectedIds = ref<Set<number>>(new Set());
const bulkConfirm = ref(false);
const bulkDeleting = ref(false);

function toggleSelectMode() {
  selectMode.value = !selectMode.value;
  selectedIds.value = new Set();
  bulkConfirm.value = false;
}

function toggleSelectConv(id: number) {
  if (selectedIds.value.has(id)) {
    selectedIds.value.delete(id);
  } else {
    selectedIds.value.add(id);
  }
  selectedIds.value = new Set(selectedIds.value);
}

function selectAll() {
  selectedIds.value = new Set(store.conversations.map((c) => c.id));
}

function clearSelection() {
  selectedIds.value = new Set();
  bulkConfirm.value = false;
}

async function bulkDelete() {
  if (!bulkConfirm.value) { bulkConfirm.value = true; return; }
  bulkDeleting.value = true;
  try {
    const ids = [...selectedIds.value];
    await store.bulkDeleteConversations(ids);
    if (ids.includes(convId.value ?? -1)) router.push("/chat");
    selectedIds.value = new Set();
    bulkConfirm.value = false;
    selectMode.value = false;
  } finally {
    bulkDeleting.value = false;
  }
}

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

// ── Summarize ─────────────────────────────────────────────────────────────────
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;
  }
}

const chatPanelRef = ref<InstanceType<typeof ChatPanel> | null>(null);

const contextCount = computed(() => chatPanelRef.value?.contextCount ?? 0);
const contextSidebarOpen = computed(() => chatPanelRef.value?.sidebarOpen ?? false);
function toggleContextSidebar() {
  chatPanelRef.value?.toggleContextSidebar();
}

// ── Kebab dismissal ───────────────────────────────────────────────────────────
function onDocumentMousedown(e: MouseEvent) {
  const target = e.target as HTMLElement | null;
  if (headerKebabOpen.value && !target?.closest(".header-kebab-wrapper")) {
    headerKebabOpen.value = false;
  }
  if (sidebarKebabOpen.value && !target?.closest(".sidebar-kebab-wrapper")) {
    sidebarKebabOpen.value = false;
  }
  if (scopeDropdownOpen.value && !target?.closest(".scope-chip-wrapper")) {
    scopeDropdownOpen.value = false;
  }
}

// ── Keyboard ──────────────────────────────────────────────────────────────────
function onGlobalKeydown(e: KeyboardEvent) {
  if (e.key !== "Escape") return;
  if (headerKebabOpen.value || sidebarKebabOpen.value || scopeDropdownOpen.value) {
    headerKebabOpen.value = false;
    sidebarKebabOpen.value = false;
    scopeDropdownOpen.value = false;
    return;
  }
  if (sidebarOpen.value) {
    sidebarOpen.value = false;
    return;
  }
  router.push("/");
}

onUnmounted(() => {
  document.removeEventListener("keydown", onGlobalKeydown);
  document.removeEventListener("mousedown", onDocumentMousedown);
  if (prevConvId) {
    const conv = store.conversations.find((c) => c.id === prevConvId);
    if (conv && conv.message_count === 0) {
      store.deleteConversation(prevConvId);
    }
  }
});
</script>

<template>
  <main class="chat-page">
    <div
      v-if="sidebarOpen"
      class="sidebar-overlay"
      @click="sidebarOpen = false"
    ></div>
    <aside class="chat-sidebar" :class="{ open: sidebarOpen }">
      <div class="sidebar-top-bar">
        <button class="btn-new-conv btn-new-conv--full" @click="newConversation">+ New Chat</button>
        <div class="sidebar-search-row">
          <input
            v-model="convSearchQuery"
            class="conv-search-input"
            type="search"
            placeholder="Search conversations…"
            aria-label="Search conversations"
          />
          <div class="sidebar-kebab-wrapper">
            <button
              class="btn-kebab"
              :class="{ active: sidebarKebabOpen }"
              @click="sidebarKebabOpen = !sidebarKebabOpen"
              aria-label="List actions"
              title="List actions"
            >
              <MoreVertical :size="16" />
            </button>
            <div v-if="sidebarKebabOpen" class="kebab-menu">
              <button
                class="kebab-item"
                @click="sidebarKebabOpen = false; toggleSelectMode()"
              >{{ selectMode ? "Exit select mode" : "Select conversations" }}</button>
            </div>
          </div>
        </div>
      </div>

      <div v-if="selectMode" class="bulk-bar">
        <span class="bulk-count">{{ selectedIds.size }} selected</span>
        <button class="bulk-link" @click="selectAll">All</button>
        <button class="bulk-link" @click="clearSelection">None</button>
        <button
          v-if="selectedIds.size"
          class="bulk-delete-btn"
          :class="{ confirm: bulkConfirm }"
          :disabled="bulkDeleting"
          @click="bulkDelete"
        >
          <Trash2 :size="16" />
          {{ bulkDeleting ? '...' : bulkConfirm ? `Delete ${selectedIds.size}?` : `Delete (${selectedIds.size})` }}
        </button>
      </div>

      <div class="conv-list">
        <template v-for="group in groupedConversations" :key="group.label">
          <div class="conv-group-label">{{ group.label }}</div>
          <div
            v-for="conv in group.convs"
            :key="conv.id"
            class="conv-item"
            :class="{ active: convId === conv.id, selected: selectedIds.has(conv.id) }"
            @click="selectMode ? toggleSelectConv(conv.id) : selectConversation(conv.id)"
          >
            <input
              v-if="selectMode"
              type="checkbox"
              class="conv-checkbox"
              :checked="selectedIds.has(conv.id)"
              @click.stop="toggleSelectConv(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
              v-if="!selectMode"
              class="btn-delete-conv"
              @click.stop="removeConversation(conv.id)"
              title="Delete conversation"
            >
              &times;
            </button>
          </div>
        </template>
        <p v-if="!store.conversations.length" class="empty-msg">
          No conversations yet
        </p>
        <p
          v-else-if="convSearchQuery && !groupedConversations.length"
          class="empty-msg"
        >No matches for “{{ convSearchQuery }}”</p>
      </div>
    </aside>

    <section class="chat-main">
      <template v-if="store.currentConversation">
        <div class="chat-header">
          <button class="btn-sidebar-toggle hide-desktop" aria-label="Toggle sidebar" @click="toggleSidebar">
            <Menu :size="24" />
          </button>
          <h2>{{ store.currentConversation.title || "New Chat" }}</h2>

          <div class="scope-chip-wrapper">
            <button
              class="scope-chip"
              :class="{ pulse: scopePulse }"
              @click="scopeDropdownOpen = !scopeDropdownOpen"
              title="Change RAG scope"
            >
              <span class="scope-dot">⊙</span> {{ scopeLabel }}
            </button>
            <div v-if="scopeDropdownOpen" class="scope-dropdown">
              <button
                class="scope-option"
                :class="{ active: store.ragProjectId === null }"
                @click="onScopeSelect(null)"
              >Orphan notes only</button>
              <button
                v-for="p in projects"
                :key="p.id"
                class="scope-option"
                :class="{ active: store.ragProjectId === p.id }"
                @click="onScopeSelect(p.id)"
              >{{ p.title }}</button>
              <button
                class="scope-option"
                :class="{ active: store.ragProjectId === -1 }"
                @click="onScopeSelect(-1)"
              >All notes</button>
            </div>
          </div>

          <button
            v-if="contextCount > 0"
            class="btn-context-toggle"
            :class="{ active: contextSidebarOpen }"
            @click="toggleContextSidebar"
            :title="contextSidebarOpen ? 'Hide context panel' : 'Show context panel'"
          >
            <Paperclip class="context-icon" :size="16" />
            <span class="context-label">Context</span>
            <span class="context-count-badge">{{ contextCount }}</span>
          </button>

          <div class="header-kebab-wrapper">
            <button
              class="btn-kebab"
              :class="{ active: headerKebabOpen }"
              @click="headerKebabOpen = !headerKebabOpen"
              aria-label="Conversation actions"
              title="Conversation actions"
            >
              <MoreVertical :size="16" />
            </button>
            <div v-if="headerKebabOpen" class="kebab-menu kebab-menu--right">
              <button
                class="kebab-item"
                :disabled="!store.currentConversation.messages.length || summarizing || store.streaming"
                @click="headerKebabOpen = false; handleSummarize()"
              >{{ summarizing ? "Summarizing…" : "Summarize as Note" }}</button>
            </div>
          </div>
        </div>

        <ChatPanel
          ref="chatPanelRef"
          variant="full"
          :auto-focus="true"
          class="chat-panel-fill"
        />
      </template>

      <div v-else class="no-conversation">
        <button class="btn-sidebar-toggle no-conv-toggle hide-desktop" @click="toggleSidebar">
          <Menu :size="24" />
        </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: var(--sidebar-width);
  min-width: 200px;
  display: flex;
  flex-direction: column;
  background: var(--color-bg-secondary);
}

.sidebar-top-bar {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  padding: 0.75rem;
}

.btn-new-conv {
  padding: 0.5rem;
  background: var(--color-primary);
  color: #fff;
  border: none;
  border-radius: var(--radius-sm);
  cursor: pointer;
  font-size: 0.9rem;
  transition: box-shadow 0.15s, opacity 0.15s;
}
.btn-new-conv--full { width: 100%; }
.btn-new-conv:hover {
  opacity: 0.9;
  box-shadow: 0 0 14px rgba(91, 74, 138, 0.35);
}

.sidebar-search-row {
  display: flex;
  align-items: center;
  gap: 0.35rem;
}
.conv-search-input {
  flex: 1;
  min-width: 0;
  padding: 0.4rem 0.6rem;
  border: 1px solid var(--color-border);
  border-radius: var(--radius-sm);
  background: var(--color-bg);
  color: var(--color-text);
  font-size: 0.85rem;
  outline: none;
  font-family: inherit;
}
.conv-search-input:focus { border-color: var(--color-primary); }
.conv-search-input::placeholder { color: var(--color-text-muted); }

.bulk-bar {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.3rem 0.75rem;
  background: color-mix(in srgb, var(--color-primary) 6%, var(--color-bg-secondary));
  border-bottom: 1px solid var(--color-border);
  flex-shrink: 0;
  flex-wrap: wrap;
}

.bulk-count { font-size: 0.75rem; color: var(--color-text-muted); flex-shrink: 0; }
.bulk-link {
  background: none; border: none; color: var(--color-text-secondary);
  font-size: 0.75rem; cursor: pointer; padding: 0; text-decoration: underline;
}
.bulk-link:hover { color: var(--color-text); }

/* Destructive action — Oxblood per Hybrid rule, paired with Trash2 icon */
.bulk-delete-btn {
  display: inline-flex;
  align-items: center;
  gap: 0.3rem;
  margin-left: auto;
  background: none;
  border: 1px solid var(--color-action-destructive);
  color: var(--color-action-destructive);
  border-radius: var(--radius-sm);
  font-size: 0.75rem;
  font-weight: 500;
  padding: 0.2rem 0.55rem;
  cursor: pointer;
}
.bulk-delete-btn:hover:not(:disabled) { background: var(--color-action-destructive); color: #fff; }
.bulk-delete-btn:disabled { opacity: 0.5; cursor: default; }
.bulk-delete-btn.confirm { background: var(--color-action-destructive-hover); color: #fff; border-color: var(--color-action-destructive-hover); }

.conv-checkbox {
  flex-shrink: 0;
  accent-color: var(--color-primary);
  cursor: pointer;
  width: 0.9rem;
  height: 0.9rem;
}
.conv-item.selected {
  background: color-mix(in srgb, var(--color-primary) 8%, var(--color-bg-secondary));
}

.conv-list {
  flex: 1;
  overflow-y: auto;
  padding: 0 0.5rem 0.5rem;
}
.conv-group-label {
  font-size: 0.68rem;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.06em;
  color: var(--color-text-muted);
  padding: 0.6rem 0.75rem 0.2rem;
  position: sticky;
  top: 0;
  background: var(--color-surface);
  z-index: 1;
}
.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;
  border-left: 3px solid transparent;
  transition: background 0.15s, border-color 0.15s;
}
.conv-item:hover { background: rgba(91, 74, 138,0.05); border-left-color: var(--color-primary); }
.conv-item.active {
  background: color-mix(in srgb, var(--color-primary) 15%, transparent);
  color: var(--color-primary);
  border-left-color: var(--color-primary);
}
.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; }
.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;
}
.btn-delete-conv:hover { color: var(--color-action-destructive); }

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

/* ChatPanel fills the remaining space in chat-main. Layout (grid vs
 * flex) is owned by ChatPanel's own .chat-full root — don't force a
 * display here or it overrides the grid. */
.chat-panel-fill {
  flex: 1;
  min-height: 0;
}

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

/* Kebab button + dropdown menu — shared by header and sidebar */
.btn-kebab {
  background: none;
  border: none;
  cursor: pointer;
  color: var(--color-text-muted);
  padding: 0.25rem;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: var(--radius-sm);
  flex-shrink: 0;
}
.btn-kebab:hover { color: var(--color-text); background: var(--color-bg-secondary); }
.btn-kebab.active { color: var(--color-primary); }

.header-kebab-wrapper,
.sidebar-kebab-wrapper {
  position: relative;
}

/* RAG scope chip (header) */
.scope-chip-wrapper { position: relative; flex-shrink: 0; }
.scope-chip {
  display: flex;
  align-items: center;
  gap: 0.3rem;
  background: none;
  border: 1px solid var(--color-border);
  border-radius: 20px;
  padding: 0.2rem 0.65rem;
  font-size: 0.75rem;
  color: var(--color-text-muted);
  cursor: pointer;
  transition: border-color 0.15s, color 0.15s;
}
.scope-chip:hover { border-color: var(--color-primary); color: var(--color-primary); }
.scope-chip.pulse { animation: pulse-chip 0.6s ease; }
@keyframes pulse-chip {
  0%, 100% { border-color: var(--color-border); }
  50% {
    border-color: var(--color-primary);
    color: var(--color-primary);
    box-shadow: 0 0 6px rgba(91, 74, 138, 0.4);
  }
}
.scope-dot { font-size: 0.6rem; }
.scope-dropdown {
  position: absolute;
  top: calc(100% + 4px);
  right: 0;
  min-width: 200px;
  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: 20;
  overflow: hidden;
}
.scope-option {
  display: block;
  width: 100%;
  padding: 0.45rem 0.75rem;
  text-align: left;
  background: none;
  border: none;
  font-size: 0.85rem;
  color: var(--color-text);
  cursor: pointer;
}
.scope-option:hover { background: var(--color-bg-secondary); }
.scope-option.active { color: var(--color-primary); font-weight: 500; }

/* Context toggle button (header) */
.btn-context-toggle {
  display: flex;
  align-items: center;
  gap: 0.3rem;
  background: none;
  border: 1px solid var(--color-border);
  border-radius: 20px;
  padding: 0.2rem 0.55rem;
  font-size: 0.75rem;
  color: var(--color-text-muted);
  cursor: pointer;
  flex-shrink: 0;
  transition: border-color 0.15s, color 0.15s, background 0.15s;
  font-family: inherit;
}
.btn-context-toggle:hover { border-color: var(--color-primary); color: var(--color-primary); }
.btn-context-toggle.active {
  background: color-mix(in srgb, var(--color-primary) 10%, transparent);
  border-color: var(--color-primary);
  color: var(--color-primary);
}
.context-icon { font-size: 0.85rem; line-height: 1; }
.context-count-badge {
  font-size: 0.65rem;
  font-weight: 500;
  background: var(--color-bg);
  padding: 0.05rem 0.35rem;
  border-radius: 8px;
  color: var(--color-text);
}

.kebab-menu {
  position: absolute;
  top: calc(100% + 4px);
  left: 0;
  min-width: 180px;
  background: var(--color-bg-card);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-md);
  box-shadow: 0 4px 20px var(--color-shadow);
  padding: 0.25rem;
  z-index: 20;
}
.kebab-menu--right { left: auto; right: 0; }
.kebab-item {
  display: block;
  width: 100%;
  text-align: left;
  background: none;
  border: none;
  color: var(--color-text);
  font-size: 0.85rem;
  padding: 0.45rem 0.65rem;
  border-radius: var(--radius-sm);
  cursor: pointer;
}
.kebab-item:hover:not(:disabled) { background: var(--color-bg-secondary); color: var(--color-primary); }
.kebab-item:disabled { opacity: 0.4; cursor: default; }

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

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

.btn-sidebar-toggle {
  background: none; border: none; cursor: pointer;
  color: var(--color-text-muted); padding: 0.2rem;
  display: flex; align-items: center;
}
.btn-sidebar-toggle:hover { color: var(--color-text); }

.sidebar-overlay {
  position: fixed; inset: 0; background: var(--color-overlay); z-index: 99;
}

@media (min-width: 768px) {
  .hide-desktop { display: none; }
  .chat-sidebar { position: relative; transform: none !important; }
}

@media (max-width: 767px) {
  .chat-sidebar {
    position: fixed; left: 0; top: 0; bottom: 0;
    z-index: 100; transform: translateX(-100%);
    transition: transform 0.25s ease;
    box-shadow: 4px 0 16px rgba(0,0,0,0.2);
  }
  .chat-sidebar.open { transform: translateX(0); }
}
</style>
