<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted, nextTick, watchEffect } from "vue";
import { useRouter } from "vue-router";
import { apiGet, apiPatch, transcribeAudio } from "@/api/client";
import { fmtCompact } from "@/utils/dateFormat";
import { renderMarkdown } from "@/utils/markdown";
import { useChatStore } from "@/stores/chat";
import { useSettingsStore } from "@/stores/settings";
import { useVoiceRecorder } from "@/composables/useVoiceRecorder";
import GraphView from "@/views/GraphView.vue";

const router = useRouter();
const chatStore = useChatStore();
const settingsStore = useSettingsStore();

// ─── Types ────────────────────────────────────────────────────────────────────

interface KnowledgeItem {
  id: number;
  note_type: "note" | "person" | "place" | "list";
  title: string;
  snippet: string;
  tags: string[];
  project_id: number | null;
  metadata: Record<string, string>;
  created_at: string;
  updated_at: string;
  // type-specific
  relationship?: string;
  email?: string;
  phone?: string;
  address?: string;
  hours?: string;
  item_count?: number;
  checked_count?: number;
  list_items?: { text: string; checked: boolean }[];
  body?: string;
}

interface UpcomingEvent {
  id: number;
  title: string;
  start_dt: string;
  all_day: boolean;
}

// ─── Filter state ─────────────────────────────────────────────────────────────

const activeType = ref<"" | "note" | "person" | "place" | "list">("");
const activeTag = ref("");
const sortMode = ref<"modified" | "created" | "alpha" | "type">("modified");
const searchQuery = ref("");
let searchDebounce: ReturnType<typeof setTimeout> | null = null;

// ─── Items ────────────────────────────────────────────────────────────────────

const items = ref<KnowledgeItem[]>([]);
const total = ref(0);
const page = ref(1);
const perPage = 24;
const loading = ref(false);
const allTags = ref<string[]>([]);

async function fetchItems(reset = false) {
  if (reset) page.value = 1;
  loading.value = true;
  try {
    const params = new URLSearchParams();
    if (activeType.value) params.set("type", activeType.value);
    if (activeTag.value) params.set("tags", activeTag.value);
    params.set("sort", sortMode.value);
    params.set("page", String(page.value));
    params.set("per_page", String(perPage));
    if (searchQuery.value.trim()) params.set("q", searchQuery.value.trim());
    const data = await apiGet<{ items: KnowledgeItem[]; total: number }>(`/api/knowledge?${params}`);
    if (reset || page.value === 1) {
      items.value = data.items;
    } else {
      items.value = [...items.value, ...data.items];
    }
    total.value = data.total;
  } catch {
    /* silent */
  } finally {
    loading.value = false;
  }
}

async function fetchTags() {
  try {
    const data = await apiGet<{ tags: string[] }>("/api/knowledge/tags");
    allTags.value = data.tags;
  } catch { /* silent */ }
}

function onSearchInput() {
  if (searchDebounce) clearTimeout(searchDebounce);
  searchDebounce = setTimeout(() => fetchItems(true), 380);
}

watch([activeType, activeTag, sortMode], () => fetchItems(true));

// ─── Today bar ────────────────────────────────────────────────────────────────

const upcomingEvents = ref<UpcomingEvent[]>([]);
const overdueCount = ref(0);

async function fetchTodayBar() {
  try {
    const now = new Date();
    const end = new Date(now.getTime() + 7 * 86_400_000);
    const [evData, taskData] = await Promise.all([
      apiGet<{ events: UpcomingEvent[] }>(
        `/api/events?from=${now.toISOString().slice(0, 10)}&to=${end.toISOString().slice(0, 10)}`
      ).catch(() => ({ events: [] as UpcomingEvent[] })),
      apiGet<{ total: number }>(
        `/api/tasks?status=todo&status=in_progress&overdue=true&limit=1`
      ).catch(() => ({ total: 0 })),
    ]);
    upcomingEvents.value = (evData.events ?? []).slice(0, 3);
    overdueCount.value = taskData.total ?? 0;
  } catch { /* silent */ }
}

const formatEventDate = fmtCompact

// ─── Graph panel ──────────────────────────────────────────────────────────────

const _GRAPH_OPEN_KEY = 'fa_knowledge_graph_open'
const _GRAPH_EXP_KEY  = 'fa_knowledge_graph_expanded'

const graphOpen     = ref(localStorage.getItem(_GRAPH_OPEN_KEY) === 'true')
const graphExpanded = ref(localStorage.getItem(_GRAPH_EXP_KEY)  === 'true')

function toggleGraph() {
  graphOpen.value = !graphOpen.value
  localStorage.setItem(_GRAPH_OPEN_KEY, String(graphOpen.value))
}

function toggleGraphExpand() {
  graphExpanded.value = !graphExpanded.value
  localStorage.setItem(_GRAPH_EXP_KEY, String(graphExpanded.value))
}

// ─── Mini-chat widget ─────────────────────────────────────────────────────────

const chatInput = ref("");
const chatOpen = ref(false);
const chatCollapsed = ref(false);
const chatConvId = ref<number | null>(null);
const chatSending = ref(false);
const chatMessages = computed(() => {
  if (!chatConvId.value) return [];
  const conv = chatStore.currentConversation;
  if (!conv || conv.id !== chatConvId.value) return [];
  return conv.messages ?? [];
});
const chatScrollEl = ref<HTMLElement | null>(null);
const chatInputEl = ref<HTMLTextAreaElement | null>(null);

const voiceEnabled = computed(() => settingsStore.voiceSttReady);
const transcribingVoice = ref(false);
const recorder = useVoiceRecorder();

async function sendChatMessage() {
  const text = chatInput.value.trim();
  if (!text || chatSending.value || chatStore.streaming) return;

  chatOpen.value = true;

  // Create a conversation on first message
  if (!chatConvId.value) {
    try {
      const conv = await chatStore.createConversation("Quick chat");
      chatConvId.value = conv.id;
      await chatStore.fetchConversation(conv.id);
    } catch { return; }
  } else if (chatStore.currentConversation?.id !== chatConvId.value) {
    await chatStore.fetchConversation(chatConvId.value);
  }

  chatInput.value = "";
  chatSending.value = true;
  try {
    await chatStore.sendMessage(text);
    await nextTick();
    scrollChatToBottom();
  } catch { /* silent */ } finally {
    chatSending.value = false;
  }
}

function scrollChatToBottom() {
  nextTick(() => {
    if (chatScrollEl.value) {
      chatScrollEl.value.scrollTop = chatScrollEl.value.scrollHeight;
    }
  });
}

// ─── Auto-refresh cards when chat creates/edits notes or tasks ───────────────

const processedToolCalls = ref(0);

watch(
  () => chatStore.streamingToolCalls,
  (calls) => {
    for (let i = processedToolCalls.value; i < calls.length; i++) {
      const tc = calls[i];
      if (
        ['create_note', 'update_note', 'create_task', 'update_task'].includes(tc.function) &&
        tc.status === 'success'
      ) {
        fetchItems(true);
        fetchTags();
        break;
      }
    }
    processedToolCalls.value = calls.length;
  },
  { deep: true }
);

watch(() => chatStore.streaming, (streaming) => {
  if (!streaming) {
    scrollChatToBottom();
    processedToolCalls.value = 0;
  }
});

async function closeChat() {
  chatOpen.value = false;
  chatConvId.value = null;
  chatInput.value = "";
}

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

async function startPtt() {
  if (!voiceEnabled.value || recorder.recording.value) return;
  await recorder.startRecording();
}

async function stopPtt() {
  if (!recorder.recording.value) return;
  transcribingVoice.value = true;
  try {
    const blob = await recorder.stopRecording();
    const { transcript } = await transcribeAudio(blob);
    if (transcript.trim()) {
      chatInput.value = transcript.trim();
      await sendChatMessage();
    }
  } catch { /* silent */ } finally {
    transcribingVoice.value = false;
  }
}

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

// ─── List item toggle ─────────────────────────────────────────────────────────

async function toggleListItem(item: KnowledgeItem, index: number) {
  if (!item.list_items || item.body === undefined) return;

  // Optimistic update
  const newChecked = !item.list_items[index].checked;
  item.list_items[index].checked = newChecked;
  item.checked_count = item.list_items.filter(i => i.checked).length;

  // Rebuild the body by replacing the targeted checkbox line
  let listIdx = 0;
  const newBody = (item.body).split('\n').map(line => {
    const stripped = line.trimStart();
    if (stripped.startsWith('- [ ] ') || stripped.startsWith('- [x] ') || stripped.startsWith('- [X] ')) {
      if (listIdx === index) {
        const indent = line.length - stripped.length;
        const newLine = (' '.repeat(indent)) + (newChecked ? '- [x] ' : '- [ ] ') + item.list_items![index].text;
        listIdx++;
        return newLine;
      }
      listIdx++;
    }
    return line;
  }).join('\n');

  item.body = newBody;
  try {
    await apiPatch(`/api/notes/${item.id}`, { body: newBody });
  } catch {
    fetchItems(true); // revert on error
  }
}

// ─── Navigation helpers ───────────────────────────────────────────────────────

function openItem(item: KnowledgeItem) {
  router.push(`/notes/${item.id}`);
}

function formatDate(iso: string): string {
  const d = new Date(iso);
  const now = new Date();
  const diff = now.getTime() - d.getTime();
  const days = Math.floor(diff / 86_400_000);
  if (days === 0) return "Today";
  if (days === 1) return "Yesterday";
  if (days < 7) return `${days}d ago`;
  if (d.getFullYear() === now.getFullYear()) return d.toLocaleDateString(undefined, { month: "short", day: "numeric" });
  return d.toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" });
}

// ─── Infinite scroll ──────────────────────────────────────────────────────────

const sentinelEl = ref<HTMLElement | null>(null);
let scrollObserver: IntersectionObserver | null = null;

function setupScrollObserver() {
  if (scrollObserver) scrollObserver.disconnect();
  if (!sentinelEl.value) return;
  scrollObserver = new IntersectionObserver(
    (entries) => {
      if (entries[0].isIntersecting && !loading.value && items.value.length < total.value) {
        page.value++;
        fetchItems();
      }
    },
    { rootMargin: "200px" }
  );
  scrollObserver.observe(sentinelEl.value);
}

// ─── Lifecycle ────────────────────────────────────────────────────────────────

onMounted(() => {
  fetchItems(true);
  fetchTags();
  fetchTodayBar();
  nextTick(() => {
    chatInputEl.value?.focus();
    setupScrollObserver();
  });
});

onUnmounted(() => {
  if (searchDebounce) clearTimeout(searchDebounce);
  scrollObserver?.disconnect();
});

watchEffect(() => {
  if (sentinelEl.value) setupScrollObserver();
});
</script>

<template>
  <div class="knowledge-root" :class="{ 'graph-open': graphOpen, 'graph-expanded': graphExpanded && graphOpen }">

    <!-- Today bar -->
    <div class="today-bar">
      <div class="today-events">
        <span v-if="upcomingEvents.length === 0" class="today-empty">No upcoming events</span>
        <router-link
          v-for="ev in upcomingEvents"
          :key="ev.id"
          :to="`/calendar`"
          class="today-event-chip"
        >
          <span class="chip-dot"></span>
          {{ ev.title }}
          <span class="chip-date">{{ formatEventDate(ev.start_dt, ev.all_day) }}</span>
        </router-link>
      </div>
      <div class="today-actions">
        <router-link v-if="overdueCount > 0" to="/tasks" class="overdue-badge">
          {{ overdueCount }} overdue
        </router-link>
        <router-link to="/briefing" class="today-link">Briefing</router-link>
        <router-link to="/chat" class="today-link">Chat</router-link>
      </div>
    </div>

    <!-- Main layout -->
    <div class="knowledge-layout">

      <!-- Filter panel -->
      <aside class="filter-panel">
        <div class="filter-section">
          <div class="filter-label">Type</div>
          <button
            v-for="t in ([['', 'All'], ['note', 'Notes'], ['person', 'People'], ['place', 'Places'], ['list', 'Lists']] as [string, string][])"
            :key="t[0]"
            class="filter-btn"
            :class="{ active: activeType === t[0] }"
            @click="activeType = (t[0] as '' | 'note' | 'person' | 'place' | 'list')"
          >{{ t[1] }}</button>
        </div>

        <div v-if="allTags.length > 0" class="filter-section">
          <div class="filter-label">Tags</div>
          <button
            class="filter-btn filter-tag"
            :class="{ active: activeTag === '' }"
            @click="activeTag = ''"
          >All tags</button>
          <button
            v-for="tag in allTags"
            :key="tag"
            class="filter-btn filter-tag"
            :class="{ active: activeTag === tag }"
            @click="activeTag = activeTag === tag ? '' : tag"
          >{{ tag }}</button>
        </div>
      </aside>

      <!-- Content area -->
      <div class="knowledge-content">

        <!-- Toolbar -->
        <div class="knowledge-toolbar">
          <div class="search-wrap">
            <svg class="search-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
            <input
              v-model="searchQuery"
              @input="onSearchInput"
              type="text"
              class="search-input"
              placeholder="Search knowledge…"
            />
          </div>
          <select v-model="sortMode" class="sort-select">
            <option value="modified">Recently modified</option>
            <option value="created">Recently created</option>
            <option value="alpha">Alphabetical</option>
            <option value="type">By type</option>
          </select>
          <button class="btn-graph" :class="{ active: graphOpen }" @click="toggleGraph" title="Toggle graph view">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/>
              <path d="m8.59 13.51 6.83 3.98M15.41 6.51l-6.82 3.98"/>
            </svg>
            Graph
          </button>
        </div>

        <!-- Loading / empty -->
        <div v-if="loading && items.length === 0" class="knowledge-empty">Loading…</div>
        <div v-else-if="!loading && items.length === 0" class="knowledge-empty">
          <p>Nothing here yet.</p>
          <p v-if="activeType || activeTag || searchQuery" class="empty-hint">Try clearing the filters.</p>
          <p v-else class="empty-hint">Start by creating a note, saving a person or place, or making a list.</p>
        </div>

        <!-- Card grid -->
        <div v-else class="card-grid">
          <div
            v-for="item in items"
            :key="item.id"
            class="k-card"
            :class="`k-card--${item.note_type}`"
            @click="openItem(item)"
          >
            <!-- Type badge -->
            <span class="type-badge" :class="`badge--${item.note_type}`">
              <span v-if="item.note_type === 'note'">Note</span>
              <span v-else-if="item.note_type === 'person'">Person</span>
              <span v-else-if="item.note_type === 'place'">Place</span>
              <span v-else>List</span>
            </span>

            <div class="k-card-body">
              <div class="k-card-title">{{ item.title }}</div>

              <!-- Person specifics -->
              <div v-if="item.note_type === 'person'" class="k-card-meta">
                <span v-if="item.relationship" class="meta-chip">{{ item.relationship }}</span>
                <span v-if="item.phone" class="meta-muted">{{ item.phone }}</span>
              </div>

              <!-- Place specifics -->
              <div v-else-if="item.note_type === 'place'" class="k-card-meta">
                <span v-if="item.address" class="meta-muted">{{ item.address }}</span>
                <span v-if="item.hours" class="meta-muted">{{ item.hours }}</span>
              </div>

              <!-- List specifics -->
              <div v-else-if="item.note_type === 'list'" class="k-card-list" @click.stop>
                <label
                  v-for="(li, idx) in (item.list_items ?? []).slice(0, 6)"
                  :key="idx"
                  class="list-item-row"
                >
                  <input
                    type="checkbox"
                    :checked="li.checked"
                    @change="toggleListItem(item, idx)"
                  />
                  <span :class="{ 'list-item-done': li.checked }">{{ li.text }}</span>
                </label>
                <div v-if="(item.list_items?.length ?? 0) > 6" class="list-item-more">
                  +{{ (item.list_items?.length ?? 0) - 6 }} more
                </div>
                <span class="list-progress" style="margin-top: 6px;">
                  <span class="list-progress-bar" :style="{ width: item.item_count ? `${Math.round(((item.checked_count ?? 0) / item.item_count) * 100)}%` : '0%' }"></span>
                </span>
              </div>

              <!-- Note snippet -->
              <p v-else-if="item.snippet" class="k-card-snippet">{{ item.snippet }}</p>
            </div>

            <div class="k-card-footer">
              <div class="k-card-tags">
                <span v-for="tag in item.tags.slice(0, 3)" :key="tag" class="tag-pill">{{ tag }}</span>
              </div>
              <span class="k-card-date">{{ formatDate(item.updated_at) }}</span>
            </div>
          </div>
        </div>

        <!-- Infinite scroll sentinel -->
        <div ref="sentinelEl" class="scroll-sentinel">
          <span v-if="loading && items.length > 0" class="sentinel-loading">Loading…</span>
        </div>
      </div>

      <!-- Graph panel -->
      <aside v-if="graphOpen" class="graph-panel" :class="{ expanded: graphExpanded }">
        <div class="graph-panel-header">
          <span>Graph</span>
          <div style="display:flex;gap:4px;align-items:center">
            <button
              class="btn-icon-sm"
              @click="toggleGraphExpand"
              :title="graphExpanded ? 'Narrow panel' : 'Expand panel'"
            >
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <polyline v-if="graphExpanded" points="15 18 9 12 15 6"/>
                <polyline v-else points="9 18 15 12 9 6"/>
              </svg>
            </button>
            <button class="btn-icon-sm" @click="toggleGraph" title="Close graph">✕</button>
          </div>
        </div>
        <div class="graph-embed">
          <GraphView :embedded="true" />
        </div>
      </aside>

    </div><!-- end knowledge-layout -->

    <!-- Floating mini-chat -->
    <div class="minichat" :class="{ 'minichat--open': chatOpen }">
      <!-- Message history (shown when chatOpen and not collapsed) -->
      <div v-if="chatOpen && !chatCollapsed" class="minichat-messages" ref="chatScrollEl">
        <template v-if="chatMessages.length === 0 && !chatStore.streaming">
          <div class="minichat-welcome">Ask me anything about your notes, tasks, or ideas.</div>
        </template>
        <div
          v-for="msg in chatMessages"
          :key="msg.id"
          class="minichat-msg"
          :class="msg.role === 'user' ? 'msg--user' : 'msg--assistant'"
        >
          <div class="msg-content" v-html="msg.role === 'assistant' ? renderMarkdown(msg.content) : msg.content"></div>
        </div>
        <div v-if="chatStore.streaming" class="minichat-msg msg--assistant">
          <div class="msg-content streaming-indicator">
            <span class="dot"></span><span class="dot"></span><span class="dot"></span>
          </div>
        </div>
      </div>

      <!-- Input bar — matches shared chat-input-bar pattern -->
      <div class="minichat-input-row">
        <div class="chat-input-bar">
          <textarea
            ref="chatInputEl"
            v-model="chatInput"
            @keydown="onChatKeydown"
            @input="chatAutoResize"
            placeholder="Ask anything…"
            :disabled="chatStore.streaming"
            rows="1"
          ></textarea>
          <button
            v-if="voiceEnabled && recorder.isSupported"
            class="btn-attach btn-mic-ptt"
            :class="{ 'mic-recording': recorder.recording.value, 'mic-transcribing': transcribingVoice }"
            @mousedown.prevent="startPtt"
            @mouseup.prevent="stopPtt"
            @touchstart.prevent="startPtt"
            @touchend.prevent="stopPtt"
            :disabled="transcribingVoice"
            title="Hold to speak"
            aria-label="Push to talk"
          >
            <svg v-if="!transcribingVoice" width="17" height="17" viewBox="0 0 24 24" fill="currentColor">
              <path d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm-1-9c0-.55.45-1 1-1s1 .45 1 1v6c0 .55-.45 1-1 1s-1-.45-1-1V5zm6 6c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z"/>
            </svg>
            <svg v-else width="17" height="17" viewBox="0 0 24 24" fill="currentColor">
              <circle cx="12" cy="12" r="8" opacity="0.35"/><circle cx="12" cy="12" r="4"/>
            </svg>
          </button>
          <button
            class="btn-send"
            :disabled="!chatInput.trim() || chatSending || chatStore.streaming"
            @click="sendChatMessage"
            title="Send"
          >&uarr;</button>
        </div>
        <button
          v-if="chatOpen"
          class="btn-close-chat"
          @click="chatCollapsed = !chatCollapsed"
          :title="chatCollapsed ? 'Expand chat' : 'Collapse chat'"
        >
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
            <polyline v-if="chatCollapsed" points="18 15 12 9 6 15"/>
            <polyline v-else points="6 9 12 15 18 9"/>
          </svg>
        </button>
        <button
          v-if="chatOpen"
          class="btn-close-chat"
          @click="closeChat"
          title="Close chat"
        >✕</button>
      </div>
    </div>

  </div>
</template>

<style scoped>
/* ── Root layout ─────────────────────────────────────────── */
.knowledge-root {
  display: flex;
  flex-direction: column;
  height: calc(100vh - var(--header-height, 56px));
  overflow: hidden;
}

/* ── Today bar ───────────────────────────────────────────── */
.today-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 8px 20px;
  background: var(--color-bg-secondary);
  border-bottom: 1px solid var(--color-border, rgba(255,255,255,0.06));
  flex-shrink: 0;
  font-size: 0.82rem;
  flex-wrap: wrap;
}
.today-events {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}
.today-empty {
  color: var(--color-muted);
}
.today-event-chip {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  padding: 3px 10px;
  border-radius: 20px;
  background: rgba(99, 102, 241, 0.1);
  border: 1px solid rgba(99, 102, 241, 0.2);
  color: var(--color-text);
  text-decoration: none;
  transition: background 0.15s;
}
.today-event-chip:hover { background: rgba(99, 102, 241, 0.18); }
.chip-dot {
  width: 6px; height: 6px;
  border-radius: 50%;
  background: #6366f1;
  flex-shrink: 0;
}
.chip-date { color: var(--color-muted); font-size: 0.78rem; }
.today-actions { display: flex; align-items: center; gap: 10px; }
.overdue-badge {
  padding: 2px 9px;
  border-radius: 12px;
  background: rgba(239,68,68,0.12);
  border: 1px solid rgba(239,68,68,0.25);
  color: #f87171;
  text-decoration: none;
  font-size: 0.78rem;
}
.today-link {
  color: var(--color-primary, #6366f1);
  text-decoration: none;
  font-weight: 500;
  opacity: 0.85;
  transition: opacity 0.15s;
}
.today-link:hover { opacity: 1; }

/* ── Main layout ─────────────────────────────────────────── */
.knowledge-layout {
  display: flex;
  flex: 1;
  overflow: hidden;
  min-height: 0;
}

/* ── Filter panel ────────────────────────────────────────── */
.filter-panel {
  width: var(--sidebar-width);
  flex-shrink: 0;
  padding: 16px 12px;
  border-right: 1px solid var(--color-border, rgba(255,255,255,0.06));
  overflow-y: auto;
  background: var(--color-bg-secondary);
}
.filter-section { margin-bottom: 20px; }
.filter-label {
  font-size: 0.7rem;
  text-transform: uppercase;
  letter-spacing: 0.08em;
  color: var(--color-muted);
  margin-bottom: 6px;
  padding: 0 4px;
}
.filter-btn {
  display: block;
  width: 100%;
  text-align: left;
  padding: 5px 8px;
  border-radius: 7px;
  border: none;
  background: transparent;
  color: var(--color-text);
  cursor: pointer;
  font-size: 0.85rem;
  margin-bottom: 2px;
  transition: background 0.12s, color 0.12s;
  opacity: 0.75;
}
.filter-btn:hover { background: rgba(255,255,255,0.05); opacity: 1; }
.filter-btn.active {
  background: rgba(99, 102, 241, 0.15);
  color: var(--color-primary, #818cf8);
  opacity: 1;
}
.filter-tag { font-size: 0.78rem; }

/* ── Content area ────────────────────────────────────────── */
.knowledge-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-width: 0;
}

/* ── Toolbar ─────────────────────────────────────────────── */
.knowledge-toolbar {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px 20px;
  flex-shrink: 0;
  border-bottom: 1px solid var(--color-border, rgba(255,255,255,0.06));
}
.search-wrap {
  flex: 1;
  position: relative;
}
.search-icon {
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: var(--color-muted);
  pointer-events: none;
}
.search-input {
  width: 100%;
  padding: 7px 12px 7px 32px;
  border-radius: 8px;
  border: 1px solid var(--color-border, rgba(255,255,255,0.1));
  background: var(--color-bg-tertiary, rgba(255,255,255,0.04));
  color: var(--color-text);
  font-size: 0.88rem;
  outline: none;
  transition: border-color 0.15s;
}
.search-input:focus { border-color: var(--color-primary, #6366f1); }
.sort-select {
  padding: 7px 10px;
  border-radius: 8px;
  border: 1px solid var(--color-border, rgba(255,255,255,0.1));
  background: var(--color-bg-tertiary, rgba(255,255,255,0.04));
  color: var(--color-text);
  font-size: 0.85rem;
  cursor: pointer;
  outline: none;
}
.btn-graph {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 6px 12px;
  border-radius: 8px;
  border: 1px solid var(--color-border, rgba(255,255,255,0.1));
  background: transparent;
  color: var(--color-muted);
  cursor: pointer;
  font-size: 0.85rem;
  transition: all 0.15s;
  white-space: nowrap;
}
.btn-graph:hover { color: var(--color-text); border-color: rgba(255,255,255,0.2); }
.btn-graph.active {
  background: rgba(99, 102, 241, 0.15);
  border-color: rgba(99, 102, 241, 0.35);
  color: var(--color-primary, #818cf8);
}

/* ── Card grid ───────────────────────────────────────────── */
.card-grid {
  flex: 1;
  overflow-y: auto;
  padding: 16px 20px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 12px;
  align-content: start;
}

.k-card {
  position: relative;
  background: var(--color-surface, rgba(255,255,255,0.03));
  border: 1px solid var(--color-border, rgba(255,255,255,0.07));
  border-radius: var(--radius-lg, 14px);
  padding: 14px;
  cursor: pointer;
  transition: border-color 0.15s, transform 0.12s, box-shadow 0.15s;
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-height: 100px;
}
.k-card:hover {
  border-color: rgba(255,255,255,0.14);
  transform: translateY(-1px);
  box-shadow: 0 4px 16px rgba(0,0,0,0.2);
}

/* Type accent strip */
.k-card--person { border-left: 3px solid #10b981; }
.k-card--place  { border-left: 3px solid #f59e0b; }
.k-card--list   { border-left: 3px solid #38bdf8; }
.k-card--note   { border-left: 3px solid #6366f1; }

/* Type badge */
.type-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  font-size: 0.68rem;
  padding: 2px 7px;
  border-radius: 10px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.04em;
}
.badge--note   { background: rgba(99,102,241,0.15); color: #818cf8; }
.badge--person { background: rgba(16,185,129,0.15); color: #34d399; }
.badge--place  { background: rgba(245,158,11,0.15); color: #fbbf24; }
.badge--list   { background: rgba(56,189,248,0.15); color: #7dd3fc; }

.k-card-body { flex: 1; padding-right: 40px; }
.k-card-title {
  font-weight: 600;
  font-size: 0.92rem;
  margin-bottom: 5px;
  line-height: 1.3;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
.k-card-snippet {
  font-size: 0.8rem;
  color: var(--color-muted);
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.45;
  margin: 0;
}
.k-card-meta {
  display: flex;
  flex-direction: column;
  gap: 3px;
  font-size: 0.8rem;
}
.meta-chip {
  display: inline-block;
  padding: 1px 8px;
  border-radius: 10px;
  background: rgba(255,255,255,0.06);
  font-size: 0.75rem;
  width: fit-content;
}
.meta-muted { color: var(--color-muted); }

/* List card items */
.k-card-list {
  display: flex;
  flex-direction: column;
  gap: 4px;
  margin-top: 2px;
}
.list-item-row {
  display: flex;
  align-items: baseline;
  gap: 6px;
  font-size: 0.82rem;
  color: var(--color-text);
  cursor: pointer;
  line-height: 1.4;
}
.list-item-row input[type="checkbox"] {
  flex-shrink: 0;
  accent-color: var(--color-primary);
  cursor: pointer;
}
.list-item-done {
  text-decoration: line-through;
  color: var(--color-text-muted);
}
.list-item-more {
  font-size: 0.75rem;
  color: var(--color-text-muted);
  margin-top: 2px;
}

/* List progress bar */
.list-progress {
  display: block;
  height: 4px;
  border-radius: 2px;
  background: rgba(255,255,255,0.08);
  overflow: hidden;
  margin-bottom: 4px;
}
.list-progress-bar {
  display: block;
  height: 100%;
  background: #38bdf8;
  border-radius: 2px;
  transition: width 0.3s;
}

.k-card-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 6px;
}
.k-card-tags { display: flex; gap: 4px; flex-wrap: wrap; }
.tag-pill {
  font-size: 0.68rem;
  padding: 1px 6px;
  border-radius: 8px;
  background: rgba(255,255,255,0.05);
  color: var(--color-muted);
}
.k-card-date { font-size: 0.72rem; color: var(--color-muted); white-space: nowrap; }

/* ── Empty / loading ─────────────────────────────────────── */
.knowledge-empty {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: var(--color-muted);
  text-align: center;
  gap: 6px;
}
.empty-hint { font-size: 0.85rem; opacity: 0.7; }

/* ── Infinite scroll sentinel ────────────────────────────── */
.scroll-sentinel {
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}
.sentinel-loading {
  font-size: 0.8rem;
  color: var(--color-muted);
}

/* ── Graph panel ─────────────────────────────────────────── */
.graph-panel {
  width: 500px;
  flex-shrink: 0;
  border-left: 1px solid var(--color-border, rgba(255,255,255,0.06));
  display: flex;
  flex-direction: column;
  background: var(--color-bg-secondary);
  transition: width 0.2s ease;
}
.graph-panel.expanded {
  width: min(960px, 60vw);
}
.graph-panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 14px;
  font-size: 0.85rem;
  font-weight: 600;
  border-bottom: 1px solid var(--color-border, rgba(255,255,255,0.06));
  flex-shrink: 0;
}
.btn-icon-sm {
  background: none;
  border: none;
  color: var(--color-muted);
  cursor: pointer;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 0.85rem;
  transition: color 0.15s;
}
.btn-icon-sm:hover { color: var(--color-text); }
.graph-embed {
  flex: 1;
  overflow: hidden;
  position: relative;
}
/* Override GraphView's 100vh height so it fills the panel instead */
.graph-embed :deep(.graph-page) {
  height: 100%;
}

/* ── Mini-chat ───────────────────────────────────────────── */
.minichat {
  position: absolute;
  bottom: 0;
  left: var(--sidebar-width); /* align with content area past filter panel */
  right: 0;
  max-width: var(--page-max-width);
  margin-inline: auto;
  z-index: 20;
  display: flex;
  flex-direction: column;
  background: var(--color-bg-secondary);
  border-radius: 16px 16px 0 0;
  box-shadow: 0 -8px 32px rgba(0,0,0,0.35), 0 -1px 0 rgba(255,255,255,0.05);
  transition: box-shadow 0.2s;
}
.knowledge-root.graph-open .minichat {
  right: 500px;
  transition: right 0.2s ease;
}
.knowledge-root.graph-open.graph-expanded .minichat {
  right: min(960px, 60vw);
}
.minichat-messages {
  max-height: 360px;
  overflow-y: auto;
  padding: 12px 16px;
  display: flex;
  flex-direction: column;
  gap: 8px;
  background: transparent;
  border-bottom: 1px solid rgba(255,255,255,0.05);
  border-radius: 16px 16px 0 0;
}
.minichat-welcome {
  color: var(--color-muted);
  font-size: 0.85rem;
  text-align: center;
  padding: 20px;
}
.minichat-msg { max-width: 85%; }
.msg--user {
  align-self: flex-end;
  background: rgba(99,102,241,0.12);
  border: 1px solid rgba(99,102,241,0.2);
  border-radius: 12px 12px 2px 12px;
  padding: 8px 12px;
  font-size: 0.88rem;
}
.msg--assistant {
  align-self: flex-start;
  border-left: 2px solid var(--color-primary, #6366f1);
  padding: 8px 12px;
  font-size: 0.88rem;
  background: rgba(255,255,255,0.02);
  border-radius: 0 12px 12px 2px;
}
.msg-content { line-height: 1.5; white-space: pre-wrap; }
.streaming-indicator {
  display: flex;
  gap: 4px;
  align-items: center;
  padding: 4px 0;
}
.dot {
  width: 6px; height: 6px;
  border-radius: 50%;
  background: var(--color-primary, #6366f1);
  animation: dot-pulse 1.2s ease-in-out infinite;
}
.dot:nth-child(2) { animation-delay: 0.2s; }
.dot:nth-child(3) { animation-delay: 0.4s; }
@keyframes dot-pulse {
  0%, 80%, 100% { opacity: 0.3; transform: scale(0.8); }
  40% { opacity: 1; transform: scale(1); }
}

.minichat-input-row {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 14px;
}
/* Reuse the shared chat-input-bar pattern */
.chat-input-bar {
  flex: 1;
  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);
}
.chat-input-bar 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: 120px;
  overflow-y: auto;
}
.chat-input-bar textarea::placeholder { color: var(--color-input-bar-placeholder); }
.chat-input-bar textarea:disabled { opacity: 0.5; }
.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; }
.btn-mic-ptt { transition: color 0.15s, opacity 0.15s; }
.btn-mic-ptt.mic-recording { color: #ef4444 !important; opacity: 1 !important; }
.btn-mic-ptt.mic-transcribing { color: var(--color-primary); opacity: 1 !important; }
.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-close-chat {
  flex-shrink: 0;
  background: none;
  border: 1px solid var(--color-border, rgba(255,255,255,0.1));
  border-radius: 8px;
  color: var(--color-muted);
  cursor: pointer;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.8rem;
  transition: color 0.15s;
}
.btn-close-chat:hover { color: var(--color-text); }
</style>
