<script setup lang="ts">
import { computed, ref } from 'vue'
import { BookOpen, Search, ArrowLeft, Clock, FileText, Filter } from '@lucide/vue'
import { RouterLink } from 'vue-router'
import { useDocQuery, useDocsQuery } from '../api/knowledge'
import { renderMarkdown } from '../utils/markdown'
import AsyncStatePanel from '../components/mission-control/AsyncStatePanel.vue'

// State
const docsQuery = useDocsQuery()
const docs = computed(() => docsQuery.data.value ?? [])
const loading = computed(() => docsQuery.isPending.value)

const searchQuery = ref('')
const categoryFilter = ref('')

const selectedDocPath = ref('')
const docQuery = useDocQuery(selectedDocPath)
const selectedDoc = computed(() =>
  selectedDocPath.value ? docQuery.data.value ?? null : null,
)
const selectedDocInfo = computed(() =>
  docs.value.find(doc => doc.path === selectedDocPath.value) ?? null,
)
const contentLoading = computed(() => docQuery.isFetching.value)
const listProblem = computed(() => docsQuery.error.value)
const contentProblem = computed(() => docQuery.error.value)

const categories = ['phases', 'skills', 'workspace', 'nexus', 'nexus-phases']

// Filtered + sorted docs (newest first)
const filteredDocs = computed(() => {
  let items = [...docs.value]
  if (categoryFilter.value) {
    items = items.filter(d => d.category === categoryFilter.value)
  }
  if (searchQuery.value.trim()) {
    const q = searchQuery.value.trim().toLowerCase()
    items = items.filter(d => d.name.toLowerCase().includes(q) || d.path.toLowerCase().includes(q))
  }
  return items.sort((a, b) => new Date(b.modifiedAt).getTime() - new Date(a.modifiedAt).getTime())
})

function selectDoc(_name: string, path: string) {
  selectedDocPath.value = path
}

function goBack() {
  selectedDocPath.value = ''
}

function retryList() {
  void docsQuery.refetch()
}

function retryContent() {
  void docQuery.refetch()
}

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString('de-DE', {
    year: 'numeric', month: 'short', day: 'numeric',
    hour: '2-digit', minute: '2-digit',
  })
}

function formatSize(bytes: number | string): string {
  const numericBytes = Number(bytes)
  if (!Number.isFinite(numericBytes)) return String(bytes)
  if (numericBytes < 1024) return `${numericBytes} B`
  if (numericBytes < 1024 * 1024) return `${(numericBytes / 1024).toFixed(1)} KB`
  return `${(numericBytes / (1024 * 1024)).toFixed(1)} MB`
}

</script>

<template>
  <div class="docs-page nexus-page">
  <div class="page-heading">
    <div>
      <span class="eyebrow">KNOWLEDGE</span>
      <h1>Docs</h1>
      <p>Browse documentation, agent skills, and workspace references.</p>
    </div>
  </div>

  <div class="docs-toolbar">
    <div class="docs-search-bar">
      <Search :size="16" />
      <input
        v-model="searchQuery"
        aria-label="Search documents"
        placeholder="Search documents..."
      />
    </div>
    <div class="docs-filter-group">
      <Filter :size="14" />
      <select v-model="categoryFilter" aria-label="Filter documents by category">
        <option value="">All categories</option>
        <option v-for="cat in categories" :key="cat" :value="cat">{{ cat }}</option>
      </select>
    </div>
  </div>

  <div class="memory-layout">
    <!-- Left column: document list -->
    <aside class="memory-sidebar">
      <AsyncStatePanel
        v-if="loading && !docs.length"
        state="loading"
        title="Dokumente werden geladen"
        compact
      />
      <AsyncStatePanel
        v-else-if="listProblem && !docs.length"
        state="error"
        title="Dokumente nicht verfügbar"
        :problem="listProblem"
        compact
        @action="retryList"
      />
      <template v-else-if="filteredDocs.length">
        <AsyncStatePanel
          v-if="listProblem"
          state="stale"
          title="Dokumentliste möglicherweise veraltet"
          :problem="listProblem"
          action-label="Aktualisieren"
          compact
          @action="retryList"
        />
        <div class="memory-list-header">{{ filteredDocs.length }} documents</div>
        <button
          v-for="doc in filteredDocs"
          :key="doc.name + doc.path"
          type="button"
          :class="['memory-file-item', { active: selectedDocPath === doc.path }]"
          :aria-current="selectedDocPath === doc.path ? 'true' : undefined"
          @click="selectDoc(doc.name, doc.path)"
        >
          <div class="memory-file-icon">
            <FileText :size="14" />
          </div>
          <div class="memory-file-info">
            <strong>{{ doc.name }}</strong>
            <div class="doc-tags">
              <span :class="['doc-category-badge', `cat-${doc.category}`]">{{ doc.category }}</span>
              <span class="doc-type-tag">{{ doc.type }}</span>
            </div>
            <span class="memory-file-meta">
              <Clock :size="10" /> {{ formatDate(doc.modifiedAt) }}
              · {{ formatSize(doc.size) }}
            </span>
          </div>
        </button>
      </template>
      <AsyncStatePanel
        v-else
        state="empty"
        title="Keine passenden Dokumente"
        message="Passe Suche oder Kategorie an."
        compact
      />
    </aside>

    <!-- Right column: content -->
    <main class="memory-content">
      <AsyncStatePanel
        v-if="contentLoading && !selectedDoc"
        state="loading"
        title="Dokument wird geladen"
      />
      <AsyncStatePanel
        v-else-if="contentProblem && !selectedDoc"
        state="error"
        title="Dokument nicht verfügbar"
        :problem="contentProblem"
        @action="retryContent"
      />
      <template v-else-if="selectedDoc">
        <AsyncStatePanel
          v-if="contentProblem"
          state="stale"
          title="Angezeigtes Dokument ist möglicherweise veraltet"
          :problem="contentProblem"
          action-label="Aktualisieren"
          compact
          @action="retryContent"
        />
        <header class="memory-content-header">
          <button type="button" class="memory-back-btn" @click="goBack">
            <ArrowLeft :size="14" />
            Back
          </button>
          <div>
            <strong>{{ selectedDoc.name }}</strong>
            <div v-if="selectedDocInfo" class="doc-tags">
              <span :class="['doc-category-badge', `cat-${selectedDocInfo.category}`]">{{ selectedDocInfo.category }}</span>
              <span class="doc-type-tag">{{ selectedDocInfo.type }}</span>
            </div>
            <span class="memory-content-meta">
              <Clock :size="10" /> {{ formatDate(selectedDoc.modifiedAt) }}
              · {{ formatSize(selectedDoc.size) }}
            </span>
            <span class="source-context">
              Agent
              <RouterLink :to="{ name: 'AgentDetail', params: { id: selectedDoc.sourceAgentId } }">
                {{ selectedDoc.sourceAgentId }}
              </RouterLink>
              · <code>{{ selectedDoc.workspacePath }}</code>
            </span>
          </div>
        </header>
        <article
          class="memory-rendered"
          v-html="renderMarkdown(selectedDoc.content)"
        ></article>
      </template>
      <template v-else>
        <div class="memory-empty-state">
          <BookOpen :size="28" />
          <h3>Select a document</h3>
          <p>Choose a document from the list or use the search/filter to find what you need.</p>
        </div>
      </template>
    </main>
  </div>
  </div>
</template>

<style scoped>
.docs-toolbar {
  display: flex;
  gap: 10px;
  margin-bottom: 16px;
  flex-wrap: wrap;
}
.docs-search-bar {
  flex: 1;
  min-width: 200px;
  display: flex;
  align-items: center;
  gap: 9px;
  padding: 10px 14px;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: var(--panel);
  color: var(--tx-3);
}
.docs-search-bar input {
  flex: 1;
  border: none;
  outline: none;
  background: transparent;
  color: var(--tx);
  font: inherit;
  font-size: 13px;
}
.docs-filter-group {
  display: flex;
  align-items: center;
  gap: 7px;
  padding: 10px 14px;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: var(--panel);
  color: var(--tx-3);
}
.docs-filter-group select {
  border: none;
  outline: none;
  background: transparent;
  color: var(--tx);
  font: inherit;
  font-size: 12px;
  cursor: pointer;
}
.memory-layout {
  display: grid;
  grid-template-columns: 320px 1fr;
  gap: 12px;
  min-height: 480px;
}
.memory-sidebar {
  border: 1px solid var(--line);
  border-radius: 9px;
  background: var(--panel);
  padding: 8px;
  max-height: 640px;
  overflow-y: auto;
}
.memory-list-header {
  font-size: 9px;
  font-weight: 700;
  color: var(--tx-3);
  text-transform: uppercase;
  letter-spacing: 0.14em;
  padding: 10px 8px 6px;
}
.memory-file-item {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  width: 100%;
  padding: 10px;
  border: none;
  border-radius: 7px;
  background: transparent;
  color: var(--tx);
  text-align: left;
  cursor: pointer;
  font: inherit;
}
.memory-file-item:hover,
.memory-file-item.active {
  background: var(--accent-soft);
}
.memory-file-icon {
  flex-shrink: 0;
  width: 28px;
  height: 28px;
  display: grid;
  place-items: center;
  border-radius: 6px;
  color: var(--tx-2);
  background: color-mix(in srgb, var(--a-mid) 10%, transparent);
}
.memory-file-info strong {
  display: block;
  font-size: 11px;
  margin-bottom: 3px;
  word-break: break-word;
}
.doc-tags {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
  margin-bottom: 3px;
}
.doc-category-badge {
  font-size: 8px;
  padding: 1px 6px;
  border-radius: 6px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.04em;
}
.doc-category-badge.cat-phases {
  background: color-mix(in srgb, var(--a-mid) 12%, transparent);
  color: var(--tx-2);
}
.doc-category-badge.cat-skills {
  background: color-mix(in srgb, var(--st-work) 10%, transparent);
  color: var(--st-work);
}
.doc-category-badge.cat-workspace {
  background: color-mix(in srgb, var(--st-review) 10%, transparent);
  color: var(--st-review);
}
.doc-category-badge.cat-nexus {
  background: color-mix(in srgb, var(--a-blue) 10%, transparent);
  color: var(--a-blue);
}
.doc-category-badge.cat-nexus-phases {
  background: color-mix(in srgb, var(--st-block) 10%, transparent);
  color: var(--st-block);
}
.doc-type-tag {
  font-size: 8px;
  padding: 1px 5px;
  border: 1px solid var(--line-2);
  border-radius: 4px;
  color: var(--tx-3);
}
.memory-file-meta {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 9px;
  color: var(--tx-3);
}
.memory-content {
  border: 1px solid var(--line);
  border-radius: 9px;
  background: var(--panel);
  padding: 24px;
  min-height: 480px;
  overflow-y: auto;
}
.memory-content-header {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 20px;
  padding-bottom: 14px;
  border-bottom: 1px solid var(--line);
}
.memory-content-header > div strong {
  display: block;
  font-size: 13px;
  margin-bottom: 4px;
}
.memory-content-meta {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 9px;
  color: var(--tx-3);
  margin-top: 4px;
}
.source-context {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-top: 5px;
  color: var(--tx-3);
  font-family: var(--font-mono-v2);
  font-size: 10px;
}
.source-context a {
  color: var(--a-blue);
}
.source-context code {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.memory-back-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 5px 10px;
  border: 1px solid var(--line);
  border-radius: 6px;
  background: transparent;
  color: var(--tx-3);
  font-size: 10px;
  cursor: pointer;
  flex-shrink: 0;
}
.memory-back-btn:hover {
  color: var(--tx);
  background: var(--accent-soft);
}
.memory-status {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 32px;
  color: var(--tx-3);
  font-size: 11px;
}
.memory-status.error {
  color: var(--st-block);
}
.memory-empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  min-height: 360px;
  color: var(--tx-3);
}
.memory-empty-state h3 {
  margin: 12px 0 6px;
  font-size: 14px;
  color: var(--tx-2);
}
.memory-empty-state p {
  margin: 0;
  font-size: 10px;
  color: var(--tx-3);
}
.memory-rendered {
  font-size: 12px;
  line-height: 1.7;
  color: var(--tx);
}
.memory-rendered :deep(h1),
.memory-rendered :deep(h2),
.memory-rendered :deep(h3) {
  color: var(--tx);
  margin: 1.2em 0 0.5em;
}
.memory-rendered :deep(h1) { font-size: 1.3rem; }
.memory-rendered :deep(h2) { font-size: 1.1rem; }
.memory-rendered :deep(h3) { font-size: 1rem; }
.memory-rendered :deep(p) { margin: 0.6em 0; }
.memory-rendered :deep(code) {
  padding: 2px 5px;
  background: color-mix(in srgb, var(--a-mid) 8%, transparent);
  border-radius: 4px;
  font-size: 11px;
}
.memory-rendered :deep(pre) {
  padding: 12px;
  border-radius: 8px;
  background: var(--space-1);
  border: 1px solid var(--nx-line);
  overflow-x: auto;
}
.memory-rendered :deep(pre code) {
  background: none;
  padding: 0;
}
.memory-rendered :deep(a) {
  color: var(--tx-2);
  text-decoration: none;
}
.memory-rendered :deep(a:hover) {
  text-decoration: underline;
}
.memory-rendered :deep(ul) {
  padding-left: 20px;
}
.memory-rendered :deep(li) {
  margin: 0.3em 0;
}
.memory-rendered :deep(hr) {
  border: none;
  border-top: 1px solid var(--nx-line);
  margin: 1.2em 0;
}
.memory-rendered :deep(strong) {
  color: var(--tx);
}
.spin {
  animation: spin 1s linear infinite;
}
@keyframes spin {
  to { transform: rotate(360deg); }
}

@media (max-width: 900px) {
  .memory-layout {
    grid-template-columns: 1fr;
  }
  .memory-sidebar {
    max-height: 280px;
  }
}
</style>
