<script setup lang="ts">
import { ChevronRight, Database, FileText, FolderOpen, FolderPlus, Loader, Upload, X } from 'lucide-vue-next'
import FolderTree from '@/components/FolderTree.vue'
import { useKnowledgeView } from '@/pages/knowledge/composables/useKnowledgeView'

const {
  folders, documents, currentFolderId, uploadError, uploadSuccess, highlightedDocumentId, uploadInput,
  showNewFolderDialog, newFolderName, showRenameDialog, renameFolderName, showDeleteDialog, deletingFolder,
  showDocumentDialog, activeDocument, activeDocumentContent, isLoadingDocumentContent, isLoadingDocuments,
  isRoot, visibleFolders, breadcrumbs, currentFolder, enterFolder, goToFolder, triggerUpload, handleUpload,
  handleDeleteDocument, openNewFolderDialog, createFolder, openRenameDialog, renameFolder, openDeleteDialog,
  deleteFolder, openDocument, closeDocumentDialog, getFileTypeColor, formatFileSize, formatDate, getStatusLabel,
} = useKnowledgeView()
</script>

<template>
  <div class="knowledge-hud-panel">
    <input ref="uploadInput" type="file" class="hidden-upload" accept=".pdf,.md,.txt,.doc,.docx,.csv,.xlsx" @change="handleUpload" />

    <div class="hud-toolbar">
      <div class="hud-toolbar-left">
        <div class="hud-badge"><Database :size="14" /><span>ARCHIVE CORE</span></div>
        <div class="hud-breadcrumbs">
          <button
            v-for="(crumb, index) in breadcrumbs"
            :key="`${crumb.id ?? 'root'}-${index}`"
            class="hud-crumb"
            :class="{ active: crumb.id === currentFolderId || (crumb.id === null && isRoot) }"
            @click="goToFolder(crumb.id)"
          >
            <span>{{ crumb.name }}</span>
            <ChevronRight v-if="index < breadcrumbs.length - 1" :size="12" />
          </button>
        </div>
      </div>
      <div class="hud-toolbar-actions">
        <button class="hud-btn" @click="openNewFolderDialog(currentFolderId)"><FolderPlus :size="14" /><span>NEW FOLDER</span></button>
        <button class="hud-btn primary" :disabled="isRoot" @click="triggerUpload"><Upload :size="14" /><span>UPLOAD FILE</span></button>
      </div>
    </div>

    <div v-if="uploadError" class="hud-alert error">{{ uploadError }}</div>
    <div v-if="uploadSuccess" class="hud-alert success">{{ uploadSuccess }}</div>

    <div class="explorer-shell">
      <aside class="folder-sidebar">
        <div class="pane-head">
          <div class="pane-title">DIRECTORIES</div>
          <button class="sidebar-action" @click="openNewFolderDialog(null)">ROOT NODE</button>
        </div>

        <div v-if="folders.length" class="folder-list tree-host">
          <FolderTree
            :folders="folders"
            :selected-id="currentFolderId"
            :on-select="enterFolder"
            :on-create="openNewFolderDialog"
            :on-rename="openRenameDialog"
            :on-delete="openDeleteDialog"
          />
        </div>

        <div v-else class="pane-empty">
          <FolderOpen :size="22" />
          <span>NO DIRECTORIES</span>
        </div>
      </aside>

      <section class="content-pane">
        <div class="pane-head content-head">
          <div>
            <div class="pane-title">CONTENTS</div>
            <div class="content-subtitle">{{ currentFolder?.name || 'ROOT DIRECTORY' }}</div>
          </div>
          <div class="content-meta">
            <span>{{ visibleFolders.length }} folders</span>
            <span>{{ documents.length }} files</span>
          </div>
        </div>

        <div class="content-table">
          <div class="content-table-head">
            <span>NAME</span>
            <span>TYPE</span>
            <span>DATE</span>
            <span>SIZE</span>
            <span>STATUS</span>
            <span>ACTIONS</span>
          </div>

          <div v-if="isLoadingDocuments" class="pane-empty loading-state">
            <Loader :size="16" class="spin" />
            <span>LOADING DIRECTORY...</span>
          </div>

          <div v-else-if="visibleFolders.length === 0 && documents.length === 0" class="pane-empty">
            <FolderOpen :size="24" />
            <span>DIRECTORY EMPTY</span>
          </div>

          <div v-else class="content-table-body">
            <button v-for="folder in visibleFolders" :key="folder.id" class="content-row folder-row" @click="enterFolder(folder)">
              <span class="cell name-cell">
                <span class="glyph folder"><FolderOpen :size="14" /></span>
                <span class="entry-name">{{ folder.name }}</span>
              </span>
              <span class="cell">FOLDER</span>
              <span class="cell">--</span>
              <span class="cell">--</span>
              <span class="cell"><span class="status-chip ready">READY</span></span>
              <span class="cell row-actions">
                <button class="inline-btn" @click.stop="openRenameDialog(folder)">RENAME</button>
                <button class="inline-btn danger" @click.stop="openDeleteDialog(folder)">DELETE</button>
              </span>
            </button>

            <button
              v-for="doc in documents"
              :key="doc.id"
              class="content-row"
              :class="{ highlight: highlightedDocumentId === doc.id }"
              @click="openDocument(doc)"
            >
              <span class="cell name-cell">
                <span class="glyph" :style="{ color: getFileTypeColor(doc.file_type) }"><FileText :size="14" /></span>
                <span class="entry-name">{{ doc.title }}</span>
              </span>
              <span class="cell">{{ doc.file_type.toUpperCase() }}</span>
              <span class="cell">{{ formatDate(doc.created_at) }}</span>
              <span class="cell">{{ formatFileSize(doc.file_size) }}</span>
              <span class="cell">
                <span class="status-chip" :class="(doc.ingestion_status ?? (doc.is_indexed ? 'ready' : 'uploaded')).toLowerCase()">
                  {{ getStatusLabel(doc.ingestion_status, doc.is_indexed) }}
                </span>
              </span>
              <span class="cell row-actions">
                <button class="inline-btn danger" @click.stop="handleDeleteDocument(doc.id)">DELETE</button>
              </span>
            </button>
          </div>
        </div>
      </section>
    </div>

    <div v-if="showNewFolderDialog" class="dialog-overlay" @click.self="showNewFolderDialog = false">
      <div class="dialog-card">
        <div class="dialog-head"><span>CREATE DIRECTORY</span><button class="dialog-close" @click="showNewFolderDialog = false"><X :size="14" /></button></div>
        <input v-model="newFolderName" class="dialog-input" placeholder="DIRECTORY NAME" @keyup.enter="createFolder" />
        <div class="dialog-actions"><button class="hud-btn" @click="showNewFolderDialog = false">CANCEL</button><button class="hud-btn primary" @click="createFolder">CREATE</button></div>
      </div>
    </div>

    <div v-if="showRenameDialog" class="dialog-overlay" @click.self="showRenameDialog = false">
      <div class="dialog-card">
        <div class="dialog-head"><span>RENAME DIRECTORY</span><button class="dialog-close" @click="showRenameDialog = false"><X :size="14" /></button></div>
        <input v-model="renameFolderName" class="dialog-input" placeholder="DIRECTORY NAME" @keyup.enter="renameFolder" />
        <div class="dialog-actions"><button class="hud-btn" @click="showRenameDialog = false">CANCEL</button><button class="hud-btn primary" @click="renameFolder">SAVE</button></div>
      </div>
    </div>

    <div v-if="showDeleteDialog && deletingFolder" class="dialog-overlay" @click.self="showDeleteDialog = false">
      <div class="dialog-card">
        <div class="dialog-head"><span>DELETE DIRECTORY</span><button class="dialog-close" @click="showDeleteDialog = false"><X :size="14" /></button></div>
        <div class="dialog-copy">DELETE <strong>{{ deletingFolder.name }}</strong> AND ITS CONTENTS?</div>
        <div class="dialog-actions"><button class="hud-btn" @click="showDeleteDialog = false">CANCEL</button><button class="hud-btn danger" @click="deleteFolder">DELETE</button></div>
      </div>
    </div>

    <div v-if="showDocumentDialog && activeDocument" class="dialog-overlay hud-preview" @click.self="closeDocumentDialog()">
      <div class="dialog-card document-card">
        <div class="dialog-head"><span>{{ activeDocument.title }}</span><button class="dialog-close" @click="closeDocumentDialog()"><X :size="14" /></button></div>
        <div class="document-meta">
          <span>{{ activeDocument.file_type.toUpperCase() }}</span>
          <span>{{ formatFileSize(activeDocument.file_size) }}</span>
          <span>{{ formatDate(activeDocument.created_at) }}</span>
        </div>
        <div v-if="isLoadingDocumentContent" class="pane-empty loading-state"><Loader :size="16" class="spin" /><span>LOADING DOCUMENT...</span></div>
        <pre v-else class="document-content">{{ activeDocumentContent || 'NO PREVIEW AVAILABLE.' }}</pre>
      </div>
    </div>
  </div>
</template>

<style scoped>
.knowledge-hud-panel{height:100%;display:flex;flex-direction:column;gap:14px;padding:14px 16px 16px;color:var(--text-primary);position:relative}
.knowledge-hud-panel::before,.knowledge-hud-panel::after{content:'';position:absolute;inset:0;pointer-events:none}
.knowledge-hud-panel::before{background:repeating-linear-gradient(180deg,rgba(125,211,252,.01) 0,rgba(125,211,252,.01) 1px,transparent 1px,transparent 10px);opacity:.12}
.knowledge-hud-panel::after{background:radial-gradient(circle at 14% 18%,rgba(34,211,238,.05),transparent 24%),radial-gradient(circle at 82% 14%,rgba(245,158,11,.04),transparent 22%);opacity:.72}
.hidden-upload{display:none}
.hud-toolbar,.explorer-shell,.dialog-card{position:relative;z-index:1;border:1px solid rgba(110,231,255,.18);background:linear-gradient(180deg,rgba(8,15,28,.78),rgba(5,10,18,.64));box-shadow:inset 0 1px 0 rgba(255,255,255,.04),0 18px 48px rgba(2,6,14,.26);backdrop-filter:blur(14px) saturate(115%)}
.hud-toolbar{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:12px 14px;overflow:hidden}
.hud-toolbar-left,.hud-toolbar-actions,.hud-badge,.hud-breadcrumbs,.hud-crumb,.pane-head,.dialog-head,.dialog-actions,.document-meta{display:flex;align-items:center}
.hud-toolbar-left{gap:14px;min-width:0}
.hud-toolbar-actions{gap:10px}
.hud-badge,.pane-title,.content-meta,.sidebar-action,.content-table-head,.status-chip,.inline-btn,.document-meta,.hud-crumb{font-family:'Share Tech Mono','Orbitron',monospace}
.content-subtitle,.dialog-head,.entry-name,.folder-list :deep(.folder-name){font-family:'Orbitron','Share Tech Mono',monospace}
.hud-badge{gap:8px;padding:6px 10px;border:1px solid rgba(34,211,238,.18);background:rgba(12,26,40,.54);color:#d8fbff;font-size:10px;letter-spacing:.16em}
.hud-breadcrumbs{gap:6px;min-width:0;flex-wrap:wrap}
.hud-crumb{gap:6px;border:none;background:transparent;color:var(--text-dim);font-size:10px;cursor:pointer;letter-spacing:.1em}
.hud-crumb.active{color:#d8fbff}
.hud-btn,.sidebar-action,.inline-btn{display:inline-flex;align-items:center;justify-content:center;cursor:pointer;transition:border-color var(--transition-fast),background var(--transition-fast),transform var(--transition-fast)}
.hud-btn{gap:8px;padding:8px 12px;border:1px solid rgba(148,163,184,.18);background:rgba(9,16,30,.42);color:var(--text-primary);font-family:'Share Tech Mono','Orbitron',monospace;letter-spacing:.12em}
.hud-btn.primary{border-color:rgba(34,211,238,.18);color:#d8fbff}
.hud-btn.danger,.inline-btn.danger{border-color:rgba(255,71,87,.24);color:#fda4af}
.hud-btn:hover:not(:disabled),.sidebar-action:hover,.inline-btn:hover{transform:translateY(-1px);border-color:rgba(34,211,238,.24);background:rgba(14,24,40,.58)}
.hud-btn:disabled{opacity:.45;cursor:not-allowed}
.hud-alert{position:relative;z-index:1;padding:9px 12px;font-size:12px;font-family:'Share Tech Mono','Orbitron',monospace;letter-spacing:.08em}
.hud-alert.error{background:rgba(127,29,29,.28);color:#fecaca}
.hud-alert.success{background:rgba(20,83,45,.28);color:#bbf7d0}
.explorer-shell{display:grid;grid-template-columns:280px 1fr;gap:0;flex:1;min-height:0;overflow:hidden}
.folder-sidebar{border-right:1px solid rgba(110,231,255,.1);background:linear-gradient(180deg,rgba(8,14,24,.62),rgba(6,10,16,.4));display:flex;flex-direction:column;min-height:0}
.content-pane{display:flex;flex-direction:column;min-height:0;background:linear-gradient(180deg,rgba(8,16,28,.28),rgba(5,10,18,.14))}
.pane-head{justify-content:space-between;gap:12px;padding:14px 16px 10px}
.pane-title{font-size:10px;letter-spacing:.18em;text-transform:uppercase;color:rgba(186,230,253,.78)}
.content-subtitle{margin-top:6px;color:#d8fbff;font-size:14px;letter-spacing:.12em;text-transform:uppercase}
.content-meta{display:inline-flex;gap:10px;color:var(--text-dim);font-size:10px;letter-spacing:.08em}
.sidebar-action{padding:0;border:none;background:transparent;color:#93f7ff;font-size:10px;letter-spacing:.14em}
.folder-list{padding:0 12px 14px;overflow:auto}
.tree-host :deep(.folder-tree){font-size:12px}
.tree-host :deep(.folder-row){padding:8px 10px;gap:8px;border-radius:0}
.tree-host :deep(.folder-row:hover){background:rgba(34,211,238,.06)}
.tree-host :deep(.folder-row.selected){background:rgba(34,211,238,.08);border:1px solid rgba(34,211,238,.28);box-shadow:inset 3px 0 0 #22d3ee}
.tree-host :deep(.folder-icon){color:#fbbf24}
.tree-host :deep(.folder-name){font-family:'Orbitron','Share Tech Mono',monospace;letter-spacing:.06em}
.tree-host :deep(.folder-actions button){font-family:'Share Tech Mono','Orbitron',monospace}
.tree-host :deep(.folder-children){padding-left:18px}
.glyph,.tree-host :deep(.folder-icon){flex-shrink:0}
.glyph{width:34px;height:34px;display:inline-flex;align-items:center;justify-content:center;background:rgba(10,22,36,.68);border:1px solid rgba(34,211,238,.16);color:#93f7ff}
.entry-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;letter-spacing:.06em}
.content-table{flex:1;min-height:0;display:flex;flex-direction:column;padding:0 16px 16px}
.content-table-head,.content-row{display:grid;grid-template-columns:minmax(220px,2fr) 90px 110px 90px 110px 110px;gap:12px;align-items:center}
.content-table-head{padding:10px 14px;border-bottom:1px solid rgba(148,163,184,.12);color:rgba(186,230,253,.78);font-size:10px;letter-spacing:.14em;text-transform:uppercase}
.content-table-body{flex:1;overflow:auto}
.content-row{width:100%;padding:12px 14px;border:none;border-bottom:1px solid rgba(148,163,184,.08);background:rgba(8,14,26,.08);color:var(--text-secondary);text-align:left;cursor:pointer;transition:background var(--transition-fast),box-shadow var(--transition-fast)}
.content-row:hover,.content-row.highlight{background:rgba(34,211,238,.06);box-shadow:inset 3px 0 0 #22d3ee,0 0 0 1px rgba(34,211,238,.08)}
.cell{min-width:0;font-size:12px}
.name-cell{display:flex;align-items:center;gap:10px}
.glyph.folder{color:#fbbf24}
.status-chip{display:inline-flex;padding:4px 8px;border:1px solid rgba(148,163,184,.12);background:rgba(8,14,26,.24);font-size:9px;letter-spacing:.12em}
.status-chip.ready{color:#86efac}.status-chip.failed{color:#fda4af}.status-chip.warning,.status-chip.uploaded,.status-chip.parsing,.status-chip.indexing{color:#fde68a}
.row-actions{display:inline-flex;gap:10px}
.inline-btn{padding:0;border:none;background:transparent;color:#93f7ff;font-size:10px;letter-spacing:.14em}
.pane-empty{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;color:var(--text-dim);text-align:center;font-family:'Share Tech Mono','Orbitron',monospace;letter-spacing:.14em}
.loading-state{min-height:180px}
.dialog-overlay{position:absolute;inset:0;z-index:8;display:flex;align-items:center;justify-content:center;background:rgba(2,6,14,.34);backdrop-filter:blur(10px)}
.dialog-overlay.hud-preview{background:radial-gradient(circle at center,rgba(34,211,238,.08),transparent 24%),rgba(2,6,14,.48)}
.dialog-card{width:min(520px,calc(100vw - 48px));padding:16px;overflow:hidden}
.document-card{width:min(900px,calc(100vw - 72px))}
.dialog-head{justify-content:space-between;gap:12px;margin-bottom:14px;letter-spacing:.14em;color:#d8fbff;text-transform:uppercase}
.dialog-close{border:none;background:transparent;color:var(--text-dim);cursor:pointer}
.dialog-input,.document-content{width:100%;border:1px solid rgba(148,163,184,.16);background:rgba(7,13,24,.34);color:var(--text-primary);backdrop-filter:blur(12px)}
.dialog-input{padding:12px 14px;margin-bottom:14px;font-family:'Share Tech Mono','Orbitron',monospace;letter-spacing:.1em}
.dialog-copy{margin-bottom:16px;color:var(--text-secondary);font-family:'Share Tech Mono','Orbitron',monospace;letter-spacing:.08em}
.dialog-actions{gap:14px;justify-content:flex-end;padding-top:4px}
.dialog-actions .hud-btn{min-width:124px;padding:10px 16px}
.document-meta{justify-content:flex-start;gap:12px;margin-bottom:12px;color:var(--text-dim);font-size:10px;letter-spacing:.12em}
.document-content{min-height:360px;max-height:min(60vh,680px);overflow:auto;padding:14px;white-space:pre-wrap;line-height:1.6;font-family:'Share Tech Mono','Orbitron',monospace}
.spin{animation:spin 1s linear infinite}
@media (max-width:900px){.explorer-shell{grid-template-columns:1fr}.folder-sidebar{max-height:220px;border-right:none;border-bottom:1px solid rgba(34,211,238,.12)}.content-table-head,.content-row{grid-template-columns:minmax(180px,2fr) 80px 90px 90px}.content-table-head span:nth-child(5),.content-table-head span:nth-child(6),.content-row .cell:nth-child(5),.content-row .cell:nth-child(6){display:none}}
</style>
