All files / src/apps/user/pages/knowledge/source DocumentsSection.tsx

44.37% Statements 71/160
61.43% Branches 94/153
30.61% Functions 15/49
45.03% Lines 68/151

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673                                                      2x             2x       32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x     32x   32x   2x       62x 62x 30x 30x   62x         32x 32x     32x   32x 1x 1x 1x 1x         1x   1x 1x       32x                               32x                                     32x 1x 1x     32x                         32x                   32x                               32x                         32x 32x 32x     32x   16x       32x                                           1x                                                                                               32x                                                 2x                           1x                                                                                             48x                                                                                                                           16x 16x   16x 16x 16x 16x 16x                                                                                                       1x                                                                                                                                                                                                                                                                                                                                                                                                  
import { type KnowledgeDocument } from "@/objects/Knowledge";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { useApiHandler } from "@/services/useApiHandler";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { AlertCircle, Check, ChevronRight, Download, ExternalLink, Eye, File as FileIcon, FileStack, Folder, FolderInput, FolderOpen, FolderPlus, Home, Link as LinkIcon, Loader2, RefreshCw, Trash2, Upload, X } from "lucide-react";
import React, { useRef, useState } from "react";
import { formatBytes } from "../util";
import { documentsKey } from "../figures";
import { SectionCard, Skeleton } from "@/components/detail";
import { errorDetail } from "@/util/apiError";
import { parseServerDate } from "@/util/time";
import DocumentPreviewModal from "./DocumentPreviewModal";
import IndexStatusBadge from "./IndexStatusBadge";
import ImportFromUrlForm from "./ImportFromUrlForm";
import {
  buildBreadcrumbs,
  docFolderPath,
  getFilesAtPath,
  getSubfolders,
  hostOf,
  isImporting,
  isSearchable,
} from "./documents";
 
// ─── Documents section ────────────────────────────────────────────────────────
 
const ACCEPTED_TYPES =
  ".pdf,.txt,.md,.csv,.json,.xml,.docx,.doc,.xlsx,.xls,.pptx,.ppt,.html,.htm,.rst,.yaml,.yml";
 
/**
 * A file source's documents. `readOnly` (a built-in source — the CHAIN-R
 * guide) keeps browsing, preview and download and drops every control the
 * API would refuse: upload, new folder, re-index, move and delete.
 */
const DocumentsSection: React.FC<{
  knowledgeId: string;
  readOnly?: boolean;
}> = ({ knowledgeId, readOnly = false }) => {
  const { getApiHandler } = useApiHandler();
  const queryClient = useQueryClient();
  const uploadInputRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);
  const [uploadError, setUploadError] = useState<string | null>(null);
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [downloadingId, setDownloadingId] = useState<string | null>(null);
  const [previewDocId, setPreviewDocId] = useState<string | null>(null);
  const [currentPath, setCurrentPath] = useState("");
  const [creatingFolder, setCreatingFolder] = useState(false);
  const [movingDocId, setMovingDocId] = useState<string | null>(null);
  const [moveTargetPath, setMoveTargetPath] = useState("");
  const [moveCustomPath, setMoveCustomPath] = useState("");
  const [moving, setMoving] = useState(false);
  const [newFolderName, setNewFolderName] = useState("");
  const [reindexingId, setReindexingId] = useState<string | null>(null);
  const [reindexError, setReindexError] = useState<string | null>(null);
  const [reindexingAll, setReindexingAll] = useState(false);
  const [addingLinks, setAddingLinks] = useState(false);
 
  // Under the source's own key, so invalidating the source refreshes them.
  const docsKey = documentsKey(knowledgeId);
 
  const docsQuery = useQuery({
    queryKey: docsKey,
    queryFn: () => getApiHandler().knowledge_router.listDocuments(knowledgeId),
    // Keep polling while any document is still being indexed so the status
    // badges settle without a manual refresh.
    refetchInterval: (query) => {
      const docs = query.state.data;
      const busy = docs?.some((d) => {
        const st = d.document_metadata?.index_status;
        return st === "importing" || st === "pending" || st === "indexing";
      });
      return busy ? 4000 : false;
    },
  });
  // Typed here: TypeScript 5.0 reads useQuery's data as `any`
  // (hooks/useAccessCatalogue.ts).
  const documents: KnowledgeDocument[] | null | undefined = docsQuery.data;
  const isLoading = docsQuery.isLoading;
 
  const unindexedCount =
    documents?.filter((d) => !isSearchable(d) && !isImporting(d)).length ?? 0;
 
  const handleReindex = async (docId: string) => {
    setReindexingId(docId);
    setReindexError(null);
    try {
      await getApiHandler().knowledge_router.reindexDocument(
        knowledgeId,
        docId,
      );
    } catch (e) {
      setReindexError(errorDetail(e, "Reindex failed. Please try again."));
    } finally {
      await queryClient.invalidateQueries({ queryKey: docsKey });
      setReindexingId(null);
    }
  };
 
  const handleReindexAll = async (onlyFailed: boolean) => {
    setReindexingAll(true);
    setReindexError(null);
    try {
      await getApiHandler().knowledge_router.reindexKnowledge(
        knowledgeId,
        onlyFailed,
      );
    } catch (e) {
      setReindexError(errorDetail(e, "Reindex failed. Please try again."));
    } finally {
      await queryClient.invalidateQueries({ queryKey: docsKey });
      setReindexingAll(false);
    }
  };
 
  const handleUpload = async (files: FileList | null) => {
    if (!files || files.length === 0) return;
    setUploading(true);
    setUploadError(null);
    try {
      await getApiHandler().knowledge_router.uploadDocuments(
        knowledgeId,
        Array.from(files),
        currentPath || undefined,
      );
      await queryClient.invalidateQueries({ queryKey: docsKey });
    } catch {
      setUploadError("Upload failed. Please try again.");
    } finally {
      setUploading(false);
      if (uploadInputRef.current) uploadInputRef.current.value = "";
    }
  };
 
  const handleImported = async (done: boolean) => {
    Eif (done) setAddingLinks(false);
    await queryClient.invalidateQueries({ queryKey: docsKey });
  };
 
  const handleDownload = async (docId: string, filename: string) => {
    setDownloadingId(docId);
    try {
      await getApiHandler().knowledge_router.downloadDocument(
        knowledgeId,
        docId,
        filename,
      );
    } finally {
      setDownloadingId(null);
    }
  };
 
  const handleDelete = async (docId: string) => {
    setDeletingId(docId);
    try {
      await getApiHandler().knowledge_router.deleteDocument(knowledgeId, docId);
      await queryClient.invalidateQueries({ queryKey: docsKey });
    } finally {
      setDeletingId(null);
    }
  };
 
  const handleMove = async (docId: string) => {
    const targetPath = moveCustomPath.trim() || moveTargetPath;
    setMoving(true);
    try {
      await getApiHandler().knowledge_router.moveDocument(
        knowledgeId,
        docId,
        targetPath,
      );
      await queryClient.invalidateQueries({ queryKey: docsKey });
      setMovingDocId(null);
    } finally {
      setMoving(false);
    }
  };
 
  const handleConfirmFolder = () => {
    // eslint-disable-next-line no-useless-escape
    const name = newFolderName.trim().replace(/[^\w.\-]/g, "_");
    if (!name) {
      setCreatingFolder(false);
      setNewFolderName("");
      return;
    }
    setCurrentPath(currentPath ? `${currentPath}/${name}` : name);
    setCreatingFolder(false);
    setNewFolderName("");
  };
 
  const subfolders = documents ? getSubfolders(documents, currentPath) : [];
  const filesHere = documents ? getFilesAtPath(documents, currentPath) : [];
  const breadcrumbs = buildBreadcrumbs(currentPath);
 
  // All distinct folder paths across the knowledge base, for the move picker
  const allFolderPaths = documents
    ? [
        ...new Set(documents.map((d) => docFolderPath(d)).filter(Boolean)),
      ].sort()
    : [];
 
  const headerActions = readOnly ? undefined : (
    <div className="flex items-center gap-2">
      <input
        ref={uploadInputRef}
        type="file"
        multiple
        accept={ACCEPTED_TYPES}
        className="hidden"
        onChange={(e) => void handleUpload(e.target.files)}
      />
      <button
        onClick={() => {
          setCreatingFolder(true);
          setNewFolderName("");
        }}
        className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium border border-gray-200 dark:border-gray-600 text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
        title="New folder"
      >
        <FolderPlus className="size-3" />
        New Folder
      </button>
      <button
        onClick={() => setAddingLinks((v) => !v)}
        className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium border border-gray-200 dark:border-gray-600 text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
        title="Import documents from their links"
      >
        <LinkIcon className="size-3" />
        Add from URL
      </button>
      {documents && documents.length > 0 && (
        <button
          onClick={() => void handleReindexAll(unindexedCount > 0)}
          disabled={reindexingAll || uploading}
          className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium border border-gray-200 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700/50 disabled:opacity-50 transition-colors"
          title={
            unindexedCount > 0
              ? `Reindex the ${unindexedCount} document${unindexedCount === 1 ? "" : "s"} that are not searchable`
              : "Rebuild the search index for every document"
          }
        >
          {reindexingAll ? (
            <Loader2 className="size-3.5 animate-spin" />
          ) : (
            <RefreshCw className="size-3.5" />
          )}
          {unindexedCount > 0
            ? `Reindex ${unindexedCount} unindexed`
            : "Reindex all"}
        </button>
      )}
      <button
        onClick={() => uploadInputRef.current?.click()}
        disabled={uploading}
        className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium bg-gray-900 dark:bg-white text-white dark:text-gray-900 hover:opacity-80 disabled:opacity-50 transition-opacity"
      >
        {uploading ? (
          <>
            <span className="size-3 border-2 border-white/30 dark:border-gray-900/30 border-t-white dark:border-t-gray-900 rounded-full animate-spin" />
            Uploading…
          </>
        ) : (
          <>
            <Upload className="size-3" />
            Upload
          </>
        )}
      </button>
    </div>
  );
 
  return (
    <SectionCard icon={FileStack} title="Documents" action={headerActions}>
      {/* Breadcrumb navigation */}
      <div className="flex items-center gap-1 mb-3 text-xs text-gray-500 dark:text-gray-400 flex-wrap">
        <button
          onClick={() => setCurrentPath("")}
          className="flex items-center gap-1 hover:text-gray-800 dark:hover:text-gray-200 transition-colors"
        >
          <Home className="size-3" />
          Root
        </button>
        {breadcrumbs.map((crumb) => (
          <React.Fragment key={crumb.path}>
            <ChevronRight className="size-3 text-gray-300 dark:text-gray-600 shrink-0" />
            <button
              onClick={() => setCurrentPath(crumb.path)}
              className="hover:text-gray-800 dark:hover:text-gray-200 transition-colors truncate max-w-[120px]"
            >
              {crumb.label}
            </button>
          </React.Fragment>
        ))}
      </div>
 
      {[uploadError, reindexError].filter(Boolean).map((message) => (
        <div
          key={message}
          role="alert"
          className="mb-3 flex items-center gap-2 px-3 py-2 rounded-lg bg-red-50 dark:bg-red-950/40 border border-red-200 dark:border-red-800 text-red-700 dark:text-red-300 text-xs"
        >
          <AlertCircle className="size-3.5 shrink-0" />
          {message}
        </div>
      ))}
 
      {addingLinks && !readOnly && (
        <ImportFromUrlForm
          knowledgeId={knowledgeId}
          folderPath={currentPath}
          onImported={(done) => void handleImported(done)}
          onCancel={() => setAddingLinks(false)}
        />
      )}
 
      {/* New folder inline input */}
      {creatingFolder && (
        <div className="mb-3 flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-50 dark:bg-gray-700/50 border border-gray-200 dark:border-gray-600">
          <Folder className="size-4 text-gray-400 dark:text-gray-500 shrink-0" />
          <input
            autoFocus
            type="text"
            placeholder="Folder name…"
            value={newFolderName}
            onChange={(e) => setNewFolderName(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter") handleConfirmFolder();
              if (e.key === "Escape") {
                setCreatingFolder(false);
                setNewFolderName("");
              }
            }}
            className="flex-1 bg-transparent text-sm text-gray-800 dark:text-gray-200 placeholder-gray-400 dark:placeholder-gray-500 outline-none"
          />
          <button
            onClick={handleConfirmFolder}
            className="p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
            title="Confirm"
          >
            <Check className="size-3.5 text-emerald-500" />
          </button>
          <button
            onClick={() => {
              setCreatingFolder(false);
              setNewFolderName("");
            }}
            className="p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
            title="Cancel"
          >
            <X className="size-3.5 text-gray-400 dark:text-gray-500" />
          </button>
        </div>
      )}
 
      {isLoading ? (
        <div className="space-y-2">
          {Array.from({ length: 3 }).map((_, i) => (
            <div key={i} className="flex items-center gap-3">
              <Skeleton className="size-8 rounded-lg" />
              <div className="flex-1 space-y-1">
                <Skeleton className="h-3 w-40" />
                <Skeleton className="h-2.5 w-20" />
              </div>
            </div>
          ))}
        </div>
      ) : subfolders.length === 0 && filesHere.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-8 text-center">
          <div className="p-3 rounded-full bg-gray-100 dark:bg-gray-700 mb-3">
            <FileStack className="size-5 text-gray-400 dark:text-gray-500" />
          </div>
          <p className="text-sm text-gray-500 dark:text-gray-400 font-medium">
            {currentPath ? "This folder is empty" : "No documents yet"}
          </p>
          <p className="text-xs text-gray-400 dark:text-gray-500 mt-0.5">
            {readOnly
              ? "Maintained by CHAIN-R."
              : currentPath
                ? "Upload files or create a sub-folder here."
                : "Upload files to start building your knowledge base."}
          </p>
        </div>
      ) : (
        <div className="divide-y divide-gray-50 dark:divide-gray-700/50">
          {/* Folders */}
          {subfolders.map((folder) => {
            const folderPath = currentPath
              ? `${currentPath}/${folder}`
              : folder;
            const count =
              documents?.filter(
                (d) =>
                  docFolderPath(d).startsWith(`${folderPath}/`) ||
                  docFolderPath(d) === folderPath,
              ).length ?? 0;
            return (
              <button
                key={folderPath}
                onClick={() => setCurrentPath(folderPath)}
                className="w-full flex items-center gap-3 py-2.5 group text-left hover:bg-gray-50 dark:hover:bg-gray-700/30 rounded-lg px-1 -mx-1 transition-colors"
              >
                <div className="p-1.5 rounded-lg bg-amber-50 dark:bg-amber-950/40 shrink-0">
                  <FolderOpen className="size-4 text-amber-500 dark:text-amber-400" />
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-sm text-gray-800 dark:text-gray-200 font-medium truncate">
                    {folder}
                  </p>
                  <p className="text-xs text-gray-400 dark:text-gray-500">
                    {count} {count === 1 ? "file" : "files"}
                  </p>
                </div>
                <ChevronRight className="size-4 text-gray-300 dark:text-gray-600 group-hover:text-gray-400 dark:group-hover:text-gray-500 transition-colors shrink-0" />
              </button>
            );
          })}
 
          {/* Files */}
          {filesHere.map((doc) => {
            const meta = doc.document_metadata ?? {};
            const name = meta.title || meta.original_filename || doc.source_id;
            const size =
              meta.size_bytes != null ? formatBytes(meta.size_bytes) : null;
            const isDeleting = deletingId === doc.id;
            const isDownloading = downloadingId === doc.id;
            const isReindexing = reindexingId === doc.id;
            return (
              <div
                key={doc.id}
                className="flex items-center gap-3 py-2.5 group"
              >
                <div className="p-1.5 rounded-lg bg-gray-100 dark:bg-gray-700 shrink-0">
                  <FileIcon className="size-4 text-gray-400 dark:text-gray-500" />
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-sm text-gray-800 dark:text-gray-200 truncate font-medium">
                    {name}
                  </p>
                  <p className="text-xs text-gray-400 dark:text-gray-500 flex items-center gap-1.5 flex-wrap">
                    <IndexStatusBadge doc={doc} />
                    {meta.source_url && (
                      <a
                        href={meta.source_url}
                        target="_blank"
                        rel="noopener noreferrer"
                        title={meta.source_url}
                        className="inline-flex items-center gap-0.5 hover:text-gray-700 dark:hover:text-gray-300"
                      >
                        <ExternalLink className="size-3" />
                        {meta.publisher || hostOf(meta.source_url)}
                      </a>
                    )}
                    <span>
                      {size ?? ""}
                      {size && doc.created_at ? " · " : ""}
                      {doc.created_at
                        ? parseServerDate(doc.created_at).toLocaleDateString(
                            undefined,
                            {
                              day: "numeric",
                              month: "short",
                              year: "numeric",
                            },
                          )
                        : ""}
                    </span>
                  </p>
                  {meta.index_status === "failed" && meta.index_error && (
                    <p
                      className="text-xs text-red-600 dark:text-red-400 truncate"
                      title={meta.index_error}
                    >
                      {meta.index_error}
                    </p>
                  )}
                </div>
                {!readOnly && (
                  <button
                    onClick={() => void handleReindex(doc.id)}
                    disabled={
                      isDeleting ||
                      isDownloading ||
                      isReindexing ||
                      isImporting(doc)
                    }
                    className={`p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-700 transition-all disabled:opacity-50 ${
                      isSearchable(doc)
                        ? "opacity-0 group-hover:opacity-100"
                        : "opacity-100"
                    }`}
                    title={
                      isImporting(doc)
                        ? "Still importing from its link"
                        : isSearchable(doc)
                          ? "Reindex document"
                          : "Not searchable yet — reindex now"
                    }
                  >
                    <RefreshCw
                      className={`size-3.5 ${
                        isReindexing ? "animate-spin" : ""
                      } ${
                        isSearchable(doc)
                          ? "text-gray-400 dark:text-gray-500"
                          : "text-amber-500"
                      }`}
                    />
                  </button>
                )}
                <button
                  onClick={() => setPreviewDocId(doc.id)}
                  disabled={isDeleting || isDownloading}
                  className="opacity-0 group-hover:opacity-100 p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-700 transition-all disabled:opacity-50"
                  title="Preview"
                >
                  <Eye className="size-3.5 text-gray-400 dark:text-gray-500" />
                </button>
 
                {/* Move to folder */}
                {!readOnly && (
                  <Popover
                    open={movingDocId === doc.id}
                    onOpenChange={(open) => {
                      if (open) {
                        setMovingDocId(doc.id);
                        setMoveTargetPath(docFolderPath(doc));
                        setMoveCustomPath("");
                      } else {
                        setMovingDocId(null);
                      }
                    }}
                  >
                    <PopoverTrigger asChild>
                      <button
                        disabled={isDeleting || isDownloading}
                        className="opacity-0 group-hover:opacity-100 p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-700 transition-all disabled:opacity-50"
                        title="Move to folder"
                      >
                        <FolderInput className="size-3.5 text-gray-400 dark:text-gray-500" />
                      </button>
                    </PopoverTrigger>
                    <PopoverContent align="end" className="w-64 p-3 space-y-3">
                      <p className="text-xs font-semibold text-gray-700 dark:text-gray-300">
                        Move to folder
                      </p>
 
                      {/* Folder list */}
                      <div className="max-h-40 overflow-y-auto space-y-0.5">
                        {/* Root option */}
                        <button
                          onClick={() => {
                            setMoveTargetPath("");
                            setMoveCustomPath("");
                          }}
                          className={`w-full flex items-center gap-2 px-2 py-1.5 rounded text-xs text-left transition-colors ${
                            moveTargetPath === "" && !moveCustomPath
                              ? "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 font-medium"
                              : "text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700/50"
                          }`}
                        >
                          <Home className="size-3 shrink-0" />
                          Root
                        </button>
                        {allFolderPaths.map((fp) => (
                          <button
                            key={fp}
                            onClick={() => {
                              setMoveTargetPath(fp);
                              setMoveCustomPath("");
                            }}
                            className={`w-full flex items-center gap-2 px-2 py-1.5 rounded text-xs text-left transition-colors ${
                              moveTargetPath === fp && !moveCustomPath
                                ? "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 font-medium"
                                : "text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700/50"
                            }`}
                          >
                            <Folder className="size-3 shrink-0 text-amber-500" />
                            <span className="truncate">{fp}</span>
                          </button>
                        ))}
                      </div>
 
                      {/* Custom path input */}
                      <div className="space-y-1">
                        <p className="text-[10px] text-gray-400 dark:text-gray-500 uppercase tracking-wide">
                          Custom path
                        </p>
                        <input
                          type="text"
                          placeholder="e.g. reports/2026"
                          value={moveCustomPath}
                          onChange={(e) => setMoveCustomPath(e.target.value)}
                          onKeyDown={(e) => {
                            if (e.key === "Enter") void handleMove(doc.id);
                          }}
                          className="w-full px-2 py-1.5 rounded border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-800 text-xs text-gray-800 dark:text-gray-200 placeholder-gray-400 dark:placeholder-gray-500 outline-none focus:ring-1 focus:ring-gray-300 dark:focus:ring-gray-600"
                        />
                      </div>
 
                      <button
                        onClick={() => void handleMove(doc.id)}
                        disabled={moving}
                        className="w-full flex items-center justify-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium bg-gray-900 dark:bg-white text-white dark:text-gray-900 hover:opacity-80 disabled:opacity-50 transition-opacity"
                      >
                        {moving ? (
                          <span className="size-3 border-2 border-white/30 dark:border-gray-900/30 border-t-white dark:border-t-gray-900 rounded-full animate-spin" />
                        ) : (
                          <FolderInput className="size-3" />
                        )}
                        Move here
                      </button>
                    </PopoverContent>
                  </Popover>
                )}
 
                <button
                  onClick={() => void handleDownload(doc.id, name)}
                  disabled={isDownloading || isDeleting}
                  className="opacity-0 group-hover:opacity-100 p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-700 transition-all disabled:opacity-50"
                  title="Download"
                >
                  {isDownloading ? (
                    <Loader2 className="size-3.5 text-gray-400 dark:text-gray-500 animate-spin" />
                  ) : (
                    <Download className="size-3.5 text-gray-400 dark:text-gray-500" />
                  )}
                </button>
                {!readOnly && (
                  <button
                    onClick={() => void handleDelete(doc.id)}
                    disabled={isDeleting || isDownloading}
                    className="flex opacity-0 group-hover:opacity-100 p-1 rounded hover:bg-red-50 dark:hover:bg-red-950/40 transition-all disabled:opacity-50"
                    title="Delete document"
                  >
                    {isDeleting ? (
                      <span className="size-3.5 block border-2 border-red-300 border-t-red-500 rounded-full animate-spin" />
                    ) : (
                      <Trash2 className="size-3.5 text-red-400 dark:text-red-500" />
                    )}
                  </button>
                )}
              </div>
            );
          })}
        </div>
      )}
 
      {/* Preview modal */}
      {previewDocId &&
        documents &&
        (() => {
          const doc = documents.find((d) => d.id === previewDocId);
          if (!doc) return null;
          return (
            <DocumentPreviewModal
              knowledgeId={knowledgeId}
              doc={doc}
              onClose={() => setPreviewDocId(null)}
              onDownload={() => {
                const name =
                  doc.document_metadata?.original_filename ?? doc.source_id;
                void handleDownload(doc.id, name);
              }}
            />
          );
        })()}
    </SectionCard>
  );
};
 
export default DocumentsSection;