page.tsx 109 KB
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 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471
"use client";

import { useState, useEffect, useMemo, useRef } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import {
  FileText, Upload, Trash2, Search, BookOpen, MessageSquare,
  ChevronRight, Activity, Download, Loader2, CheckCircle2,
  Clock, HardDrive, Filter, MoreVertical, LayoutGrid, List as ListIcon,
  ShieldCheck, Zap, Globe, Settings, LogOut, ChevronDown, Check,
  X, AlertCircle, Eye, LogOut as Eject, Folder, Square, RefreshCw,
  FileImage, FileSpreadsheet, FileArchive, FileCode,
  ChevronLeft, ChevronsLeft, ChevronsRight
} from "lucide-react";
import { cn } from "@/lib/utils";
import { MessageBubble, type ReasoningStep } from "@/components/MessageBubble";
import FrontmatterCard from "@/components/FrontmatterCard";
import { parseFrontmatter } from "@/lib/frontmatter";
import * as XLSX from "xlsx";
import type { SheetData } from "x-data-spreadsheet";
import "x-data-spreadsheet/dist/xspreadsheet.css";

interface UploadQueueItem {
  file: File;
  name: string;
  status: 'pending' | 'uploading' | 'success' | 'error';
  errorMsg?: string;
}

interface FileItem {
  id: string;
  name: string;
  time: string;
  full_time?: string;
  format: string;
  size: string;
  size_raw?: number;
  word_count?: number;
  status: "Indexed" | "Pending" | "Ingesting" | "Uploading" | "Failed";
  meta?: {
    ingest_duration?: string;
    total_tokens?: number | { total_tokens: number; input_tokens: number; output_tokens: number };
    input_tokens?: number;
    output_tokens?: number;
    cached_input_tokens?: number;
    vlm_total_tokens?: number;
    overall_total_tokens?: number;
    ingest_mode?: string;
    ingest_time?: string;
  };
}

interface TreeFolder {
  name: string;
  type: "folder";
  children: Record<string, TreeFolder | TreeFile>;
}

interface TreeFile {
  name: string;
  type: "file";
  path: string;
}

type PreviewStatus = "idle" | "loading" | "ready" | "missing" | "error";

const canDirectIframePreview = (name: string) => {
  const lowerName = name.toLowerCase();
  return lowerName.endsWith(".pdf");
};

const needsControlledPreview = (name: string) => {
  const lowerName = name.toLowerCase();
  return lowerName.endsWith(".ppt") || lowerName.endsWith(".pptx");
};

const needsSpreadsheetPreview = (name: string) => {
  const lowerName = name.toLowerCase();
  return lowerName.endsWith(".xlsx") || lowerName.endsWith(".xls");
};

const SPREADSHEET_MAX_ROWS = 5000;
const SPREADSHEET_MAX_CELLS = 200000;
const SPREADSHEET_MAX_FILE_BYTES = 50 * 1024 * 1024;

const colWidthFromExcel = (col?: { wch?: number; wpx?: number }) => {
  if (!col) return undefined;
  if (typeof col.wpx === "number") return col.wpx;
  if (typeof col.wch === "number") return Math.round(col.wch * 7 + 5);
  return undefined;
};

const FONT_UNIT_PX = 7;
const CELL_PADDING_PX = 16;
const MIN_COL_WIDTH = 50;
const MAX_AUTO_COL_WIDTH = 320;
const DEFAULT_ROW_HEIGHT = 25;
const ROW_LINE_HEIGHT = 20;

const isWideChar = (code: number) => (
  (code >= 0x1100 && code <= 0x115f)
  || (code >= 0x2e80 && code <= 0xa4cf && code !== 0x303f)
  || (code >= 0xac00 && code <= 0xd7a3)
  || (code >= 0xf900 && code <= 0xfaff)
  || (code >= 0xff00 && code <= 0xff60)
  || (code >= 0xffe0 && code <= 0xffe6)
);

const textDisplayUnits = (text: string) => {
  let units = 0;
  for (const ch of text) {
    units += isWideChar(ch.codePointAt(0) || 0) ? 2 : 1;
  }
  return units;
};

const workbookToSpreadsheetData = (
  workbook: import("xlsx").WorkBook
): { sheets: SheetData[]; truncated: boolean } => {
  let truncated = false;

  const sheets: SheetData[] = workbook.SheetNames.map((name) => {
    const worksheet = workbook.Sheets[name];
    const ref = worksheet["!ref"];
    const rows: Record<number, { cells: Record<number, { text: string; style?: number }>; height?: number }> & { len?: number } = {};
    const cols: Record<number, { width: number }> & { len?: number } = {};
    const colMaxUnits: Record<number, number> = {};

    if (ref) {
      const range = XLSX.utils.decode_range(ref);
      let maxRow = range.e.r;
      const totalCols = range.e.c - range.s.c + 1;
      const rowLimit = Math.max(
        0,
        Math.min(maxRow - range.s.r, SPREADSHEET_MAX_ROWS - 1, Math.floor(SPREADSHEET_MAX_CELLS / Math.max(totalCols, 1)) - 1)
      );
      if (range.e.r - range.s.r > rowLimit) {
        truncated = true;
        maxRow = range.s.r + rowLimit;
      }

      for (let r = range.s.r; r <= maxRow; r++) {
        const cells: Record<number, { text: string; style?: number }> = {};
        let hasValue = false;
        for (let c = range.s.c; c <= range.e.c; c++) {
          const cellAddr = XLSX.utils.encode_cell({ r, c });
          const cell = worksheet[cellAddr];
          if (cell && cell.v !== undefined && cell.v !== null) {
            const text = String(cell.v);
            cells[c - range.s.c] = { text };
            hasValue = true;
            const col = c - range.s.c;
            const lineUnits = Math.max(...text.split("\n").map(textDisplayUnits));
            colMaxUnits[col] = Math.max(colMaxUnits[col] || 0, lineUnits);
          }
        }
        if (hasValue) {
          rows[r - range.s.r] = { cells };
        }
      }
      rows.len = maxRow - range.s.r + 1;
      cols.len = totalCols;
    }

    const excelCols = (worksheet["!cols"] || []) as Array<{ wch?: number; wpx?: number } | undefined>;
    for (let c = 0; c < (cols.len || 0); c++) {
      const autoWidth = Math.min(
        MAX_AUTO_COL_WIDTH,
        Math.max(MIN_COL_WIDTH, (colMaxUnits[c] || 0) * FONT_UNIT_PX + CELL_PADDING_PX)
      );
      const storedWidth = colWidthFromExcel(excelCols[c]);
      const width = Math.max(autoWidth, storedWidth || 0);
      if (width) {
        cols[c] = { width };
      }
    }

    const wrapStyleIndex = 0;
    Object.keys(rows).forEach((rowKey) => {
      if (rowKey === "len") return;
      const row = rows[Number(rowKey)];
      let neededHeight = DEFAULT_ROW_HEIGHT;
      Object.keys(row.cells).forEach((colKey) => {
        const c = Number(colKey);
        const cellData = row.cells[c];
        const colWidth = cols[c]?.width || MIN_COL_WIDTH;
        const capacityUnits = Math.max(1, Math.floor((colWidth - CELL_PADDING_PX) / FONT_UNIT_PX));
        const segments = cellData.text.split("\n");
        const totalLines = segments.reduce(
          (sum, seg) => sum + Math.max(1, Math.ceil(textDisplayUnits(seg) / capacityUnits)),
          0
        );
        if (totalLines > 1) {
          cellData.style = wrapStyleIndex;
          neededHeight = Math.max(neededHeight, totalLines * ROW_LINE_HEIGHT + 8);
        }
      });
      if (neededHeight > DEFAULT_ROW_HEIGHT) {
        row.height = neededHeight;
      }
    });

    const merges = ((worksheet["!merges"] || []) as Array<{ s: { r: number; c: number }; e: { r: number; c: number } }>)
      .filter((m) => ref && m.e.r < (XLSX.utils.decode_range(ref).s.r + (rows.len || 0)))
      .map((m) => {
        const base = ref ? XLSX.utils.decode_range(ref) : { s: { r: 0, c: 0 } };
        return `${XLSX.utils.encode_cell({ r: m.s.r - base.s.r, c: m.s.c - base.s.c })}:${XLSX.utils.encode_cell({ r: m.e.r - base.s.r, c: m.e.c - base.s.c })}`;
      });

    return {
      name,
      rows,
      cols,
      merges,
      styles: [{ textwrap: true, valign: "top" }],
    } as SheetData;
  });

  return { sheets, truncated };
};

const buildTree = (links: string[]) => {
  const root: TreeFolder = { name: "root", type: "folder", children: {} };

  links.forEach(link => {
    const cleanLink = link.replace(/^ware\/wiki\//, '');
    const parts = cleanLink.split('/');
    let current = root;

    for (let i = 0; i < parts.length; i++) {
      const part = parts[i];
      if (i === parts.length - 1) {
        current.children[part] = { name: part, type: "file", path: cleanLink };
      } else {
        if (!current.children[part]) {
          current.children[part] = { name: part, type: "folder", children: {} };
        }
        current = current.children[part] as TreeFolder;
      }
    }
  });

  return root;
};

const PAGE_SIZE_OPTIONS = [10, 20, 50, 100];

// 生成分页页码列表,用 "ellipsis" 表示省略号
const getPaginationRange = (currentPage: number, totalPages: number): (number | "ellipsis")[] => {
  if (totalPages <= 7) {
    return Array.from({ length: totalPages }, (_, i) => i + 1);
  }

  const pages = new Set<number>([1, totalPages, currentPage, currentPage - 1, currentPage + 1]);
  const sorted = Array.from(pages).filter(p => p >= 1 && p <= totalPages).sort((a, b) => a - b);

  const result: (number | "ellipsis")[] = [];
  sorted.forEach((page, idx) => {
    if (idx > 0 && page - sorted[idx - 1] > 1) {
      result.push("ellipsis");
    }
    result.push(page);
  });
  return result;
};

const TreeNode = ({ node, level = 0, onSelect, selectedPath }: { node: TreeFolder | TreeFile, level?: number, onSelect: (path: string) => void, selectedPath: string | null }) => {
  const [isOpen, setIsOpen] = useState(true);

  if (node.type === "file") {
    return (
      <div
        className={cn(
          "flex items-center gap-2 py-1.5 px-2 rounded-lg cursor-pointer transition-colors text-sm",
          selectedPath === node.path ? "bg-blue-100 text-blue-700 font-medium" : "hover:bg-slate-100 text-slate-600"
        )}
        style={{ paddingLeft: `${level * 12 + 8}px` }}
        onClick={() => onSelect(node.path)}
      >
        <FileText className="w-4 h-4 shrink-0" />
        <span className="truncate">{node.name}</span>
      </div>
    );
  }

  const children = Object.values(node.children).sort((a, b) => {
    if (a.type === b.type) return a.name.localeCompare(b.name);
    return a.type === "folder" ? -1 : 1;
  });

  return (
    <div>
      <div
        className="flex items-center gap-2 py-1.5 px-2 rounded-lg cursor-pointer hover:bg-slate-100 text-slate-700 transition-colors text-sm font-medium"
        style={{ paddingLeft: `${level * 12 + 8}px` }}
        onClick={() => setIsOpen(!isOpen)}
      >
        <Folder className="w-4 h-4 shrink-0 text-blue-500" />
        <span className="truncate">{node.name}</span>
      </div>
      {isOpen && (
        <div className="flex flex-col gap-0.5 mt-0.5">
          {children.map(child => (
            <TreeNode key={child.name} node={child} level={level + 1} onSelect={onSelect} selectedPath={selectedPath} />
          ))}
        </div>
      )}
    </div>
  );
};

const SpreadsheetPreview = ({ sheets }: { sheets: SheetData[] }) => {
  const containerRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    const container = containerRef.current;
    if (!container) return undefined;
    container.innerHTML = "";
    let cancelled = false;
    import("x-data-spreadsheet/dist/xspreadsheet.js")
      .then(() => {
        if (cancelled || !window.x_spreadsheet) return;
        const instance = window.x_spreadsheet(container, {
          mode: "read",
          showToolbar: false,
          showContextmenu: false,
          showBottomBar: true,
          view: {
            height: () => container.clientHeight,
            width: () => container.clientWidth,
          },
        });
        instance.loadData(sheets);
      })
      .catch((e) => {
        console.error("加载 x-data-spreadsheet 失败", e);
      });
    return () => {
      cancelled = true;
      container.innerHTML = "";
    };
  }, [sheets]);

  return (
    <div
      ref={containerRef}
      className="wiki-spreadsheet-readonly w-full h-full overflow-hidden"
      onWheel={(e) => e.stopPropagation()}
    />
  );
};

export default function EnterpriseWiki() {
  const [files, setFiles] = useState<FileItem[]>([]);
  const [uploadingFiles, setUploadingFiles] = useState<FileItem[]>([]);
  const [isInitialLoading, setIsInitialLoading] = useState(true);
  const [selectedFileId, setSelectedFileId] = useState<string | null>(null);
  const [wikiContent, setWikiContent] = useState<string>("");
  const [previewContent, setPreviewContent] = useState<string>("");
  const [previewStatus, setPreviewStatus] = useState<PreviewStatus>("idle");
  const [isPreviewLoading, setIsPreviewLoading] = useState(false);
  const [spreadsheetSheets, setSpreadsheetSheets] = useState<SheetData[] | null>(null);
  const [spreadsheetTruncated, setSpreadsheetTruncated] = useState(false);
  const latestPreviewRequestIdRef = useRef<string | null>(null);
  const [viewMode, setViewMode] = useState<"raw" | "wiki_tree">("raw");
  const [selectedWikiPath, setSelectedWikiPath] = useState<string | null>(null);
  const [query, setQuery] = useState("");
  const [chatHistory, setChatHistory] = useState<{
    role: "user" | "ai";
    content: string;
    reasoning?: ReasoningStep[];
    startTime?: number;
    endTime?: number;
    isStreaming?: boolean;
    serverDurationMs?: number;
  }[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isDeleting, setIsDeleting] = useState<string | null>(null);
  const [isChatOpen, setIsChatOpen] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isLintModalOpen, setIsLintModalOpen] = useState(false);
  const [isUploadModalOpen, setIsUploadModalOpen] = useState(false);
  const [uploadQueue, setUploadQueue] = useState<UploadQueueItem[]>([]);
  const [lintHistory, setLintHistory] = useState<{
    role: "user" | "ai";
    content: string;
    reasoning?: ReasoningStep[];
    startTime?: number;
    endTime?: number;
  }[]>([]);
  const [isLinting, setIsLinting] = useState(false);
  const [wikiLinks, setWikiLinks] = useState<string[]>([]);
  const [isZipDownloading, setIsZipDownloading] = useState(false);
  const [abortController, setAbortController] = useState<AbortController | null>(null);
  const [sessionId] = useState(() => "session-" + Date.now() + "-" + Math.random().toString(36).substring(2, 9));

  const chatEndRef = useRef<HTMLDivElement>(null);
  const lintEndRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    chatEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [chatHistory]);

  useEffect(() => {
    lintEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [lintHistory]);

  useEffect(() => {
    if (!isModalOpen) return undefined;

    const previousBodyOverflow = document.body.style.overflow;
    const previousBodyOverscrollBehavior = document.body.style.overscrollBehavior;
    document.body.style.overflow = "hidden";
    document.body.style.overscrollBehavior = "contain";

    return () => {
      document.body.style.overflow = previousBodyOverflow;
      document.body.style.overscrollBehavior = previousBodyOverscrollBehavior;
    };
  }, [isModalOpen]);

  const [searchQuery, setSearchQuery] = useState("");
  const [searchInput, setSearchInput] = useState("");
  const [sortBy, setSortBy] = useState<"name" | "time" | "size" | "status" | "format" | "id" | "word_count" | "token">("time");
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");
  const [statusFilter, setStatusFilter] = useState<"All" | FileItem["status"]>("All");
  const [formatFilter, setFormatFilter] = useState("All");
  const [formatOptions, setFormatOptions] = useState<string[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [totalCount, setTotalCount] = useState(0);
  const [refreshTrigger, setRefreshTrigger] = useState(0);

  // Selection state
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());

  const API_BASE = process.env.NEXT_PUBLIC_API_URL || "/api";

  const fetchFiles = async (page = currentPage, size = pageSize, search = searchQuery, isInitial = false) => {
    if (isInitial) setIsInitialLoading(true);
    try {
      const params = new URLSearchParams({
        page: String(page),
        page_size: String(size),
        search,
        sort_by: sortBy,
        sort_order: sortOrder,
        status: statusFilter,
        format: formatFilter,
      });
      const res = await fetch(`${API_BASE}/files?${params.toString()}`);
      const data = await res.json();
      setFiles(data.files || []);
      setTotalCount(data.total || 0);
      const responseFormats = data.filter_options?.formats;
      if (Array.isArray(responseFormats)) {
        setFormatOptions(responseFormats.filter((format): format is string => typeof format === "string" && format.length > 0));
      } else {
        const fallbackFormats = ((data.files || []) as FileItem[])
          .map((file) => file.format)
          .filter((format) => format.length > 0);
        setFormatOptions(Array.from(new Set<string>(fallbackFormats)).sort());
      }
    } catch (e) {
      console.error("Failed to fetch files", e);
    } finally {
      if (isInitial) setIsInitialLoading(false);
    }
  };

  useEffect(() => {
    Promise.resolve().then(() => {
      void fetchFiles(currentPage, pageSize, searchQuery, true);
    });
  }, [currentPage, pageSize, searchQuery, sortBy, sortOrder, statusFilter, formatFilter, refreshTrigger]);

  const filteredFiles = useMemo(() => {
    return [...uploadingFiles, ...files.filter(f => !uploadingFiles.some(u => u.name === f.name))];
  }, [files, uploadingFiles]);

  const handleUploadSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      const selectedFiles = Array.from(e.target.files);
      const duplicatesInQueue: string[] = [];
      const duplicatesInSelection: string[] = [];
      const validFiles: UploadQueueItem[] = [];

      const existingNames = new Set(uploadQueue.map(item => item.name));
      const seenInSelection = new Set<string>();

      for (const file of selectedFiles) {
        if (existingNames.has(file.name)) {
          duplicatesInQueue.push(file.name);
        } else if (seenInSelection.has(file.name)) {
          duplicatesInSelection.push(file.name);
        } else {
          seenInSelection.add(file.name);
          validFiles.push({
            file,
            name: file.name,
            status: 'pending'
          });
        }
      }

      if (validFiles.length > 0) {
        setUploadQueue(prev => [...prev, ...validFiles]);
      }

      const tips: string[] = [];
      if (duplicatesInQueue.length > 0) {
        tips.push(`以下文件已在上传列表中,已自动过滤:\n${duplicatesInQueue.join(', ')}`);
      }
      if (duplicatesInSelection.length > 0) {
        tips.push(`选择的文件中存在同名文件,已自动去重:\n${duplicatesInSelection.join(', ')}`);
      }

      if (tips.length > 0) {
        alert(tips.join('\n\n'));
      }
    }
    e.target.value = '';
  };

  const handleUploadConfirm = async () => {
    const pendingFiles = uploadQueue.filter(q => q.status === 'pending');
    if (pendingFiles.length === 0) return;

    // 先把当前待上传的文件状态更新为 uploading
    setUploadQueue(prev => prev.map(q => q.status === 'pending' ? { ...q, status: 'uploading' } : q));

    try {
      const initRes = await fetch(`${API_BASE}/upload/init`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          files: pendingFiles.map(q => ({ name: q.name }))
        })
      });

      if (!initRes.ok) {
        const errorData = await initRes.json().catch(() => ({ detail: "初始化上传失败" }));
        const errorMsg = errorData.detail || "初始化上传失败";
        setUploadQueue(prev => prev.map(q => pendingFiles.some(pf => pf.name === q.name) ? { ...q, status: 'error', errorMsg } : q));
        return;
      }

      const { mapping, errors } = await initRes.json();

      // 先把后端返回错误的文件标记为 error
      if (errors && Object.keys(errors).length > 0) {
        setUploadQueue(prev => prev.map(q => {
          if (errors[q.name]) {
            return { ...q, status: 'error', errorMsg: errors[q.name] };
          }
          return q;
        }));
      }

      for (const q of pendingFiles) {
        const fileId = mapping[q.name];
        if (!fileId) {
          // 如果后端没有返回它的 ID,且之前也没有标记为 error,说明可能存在未知的初始化缺失
          if (!errors || !errors[q.name]) {
            setUploadQueue(prev => prev.map(item => item.name === q.name ? { ...item, status: 'error', errorMsg: "初始化失败" } : item));
          }
          continue;
        }

        const formData = new FormData();
        formData.append("file", q.file);

        try {
          const res = await fetch(`${API_BASE}/upload/${fileId}`, {
            method: "POST",
            body: formData,
          });

          if (res.ok) {
            setUploadQueue(prev => prev.map(item => item.name === q.name ? { ...item, status: 'success' } : item));
          } else {
            const errDetail = await res.json().catch(() => ({ detail: "文件保存失败" }));
            setUploadQueue(prev => prev.map(item => item.name === q.name ? { ...item, status: 'error', errorMsg: errDetail.detail || "保存失败" } : item));
          }
        } catch {
          setUploadQueue(prev => prev.map(item => item.name === q.name ? { ...item, status: 'error', errorMsg: "上传出错" } : item));
        }
      }
    } catch {
      setUploadQueue(prev => prev.map(q => pendingFiles.some(pf => pf.name === q.name) ? { ...q, status: 'error', errorMsg: "网络请求异常" } : q));
    } finally {
      fetchFiles();
    }
  };

  const handleDelete = async (id: string) => {
    const targetFile = files.find(f => f.id === id);
    if (targetFile && targetFile.status !== "Pending" && targetFile.status !== "Failed") {
      alert("只有待处理或失败的文件才能删除!");
      return;
    }
    if (!confirm(`确定彻底删除 ${targetFile?.name} 吗?`)) return;

    setIsDeleting(id);
    // 如果删除的是当前选中的文件,先清除选中状态以卸载预览组件 (释放 iframe 句柄)
    const isSelected = selectedFileId === id;
    if (isSelected) {
      // 尝试彻底销毁 iframe 的连接
      const iframe = document.querySelector('iframe');
      if (iframe) iframe.src = "about:blank";

      setSelectedFileId(null);
      setWikiContent("");
      // 延长等待时间到 1s,给浏览器更多时间释放句柄
      await new Promise(resolve => setTimeout(resolve, 1000));
    }

    try {
      const response = await fetch(`${API_BASE}/files/${encodeURIComponent(id)}`, {
        method: "DELETE",
        mode: "cors"
      });
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({ detail: "未知错误" }));
        throw new Error(errorData.detail || `服务器返回状态码: ${response.status}`);
      }
      fetchFiles();
    } catch (error) {
      console.error("Delete failed:", error);
      const msg = error instanceof Error ? error.message : "请检查网络或后端服务状态";
      alert(`删除失败: ${msg}`);
    } finally {
      setIsDeleting(null);
    }
  };

  const handleDownload = (id: string, name: string) => {
    const downloadUrl = `${API_BASE}/files/download/${encodeURIComponent(id)}`;
    const a = document.createElement("a");
    a.href = downloadUrl;
    a.download = name;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  };

  const handleDownloadWikiZip = async () => {
    if (wikiLinks.length === 0 || isZipDownloading) return;
    setIsZipDownloading(true);
    try {
      // 后端 download_batch 以 WIKI_DIR 为根拼接路径,须先剥掉 ware/wiki/ 前缀(与 buildTree 一致),
      // 否则 join 出 .../ware/wiki/ware/wiki/... 找不到文件,导致 zip 为空。
      const paths = wikiLinks.map((l) => l.replace(/^ware\/wiki\//, ""));
      const res = await fetch(`${API_BASE}/wiki/download_batch`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ paths }),
      });
      if (!res.ok) {
        alert("打包下载失败");
        return;
      }
      const blob = await res.blob();
      const srcName = files.find(f => f.id === selectedFileId)?.name || "wiki";
      const zipName = `${srcName.replace(/\.[^.]+$/, "")}_wiki.zip`;
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = zipName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    } catch {
      alert("打包下载失败");
    } finally {
      setIsZipDownloading(false);
    }
  };

  const handleEgress = async (id: string) => {
    const targetFile = files.find(f => f.id === id);
    if (!confirm(`确定将 ${targetFile?.name} 从 Wiki 知识库中摄出吗?这会删除所有生成的 Wiki 页面。`)) return;

    try {
      const res = await fetch(`${API_BASE}/wiki/egress/${encodeURIComponent(id)}`, { method: "DELETE" });
      if (!res.ok) {
        const error = await res.json();
        alert(error.detail || "摄出失败");
      } else {
        fetchFiles();
        if (selectedFileId === id) {
          setWikiContent("");
          setViewMode("wiki_tree");
        }
      }
    } catch {
      alert("摄出请求发生错误");
    }
  };

  const handleIngest = async (id: string) => {
    setFiles(prev => prev.map(f => f.id === id ? { ...f, status: "Ingesting" } : f));
    try {
      const res = await fetch(`${API_BASE}/wiki/ingest/${encodeURIComponent(id)}`, { method: "POST" });
      if (!res.ok) {
        const error = await res.json();
        alert(error.detail || "摄入失败");
      }
      await fetchFiles();
    } catch {
      alert("摄入过程发生错误");
      await fetchFiles();
    }
  };

  const handleBatchIngest = async () => {
    const toIngest = Array.from(selectedIds).filter(id => {
      const file = files.find(f => f.id === id);
      return file && (file.status === "Pending" || file.status === "Failed");
    });

    if (toIngest.length === 0) {
      alert("请先选择待处理或失败的文件");
      return;
    }

    setFiles(prev => prev.map(f => toIngest.includes(f.id) ? { ...f, status: "Ingesting" } : f));
    setSelectedIds(new Set());

    try {
      await fetch(`${API_BASE}/wiki/batch_ingest`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ids: toIngest }),
      });
      fetchFiles();
    } catch {
      alert("批量处理发生错误");
      fetchFiles();
    }
  };

  const handleBatchEgress = async () => {
    const ids = Array.from(selectedIds);
    const toEgress = ids.filter(id => {
      const file = files.find(f => f.id === id);
      return file && file.status === "Indexed";
    });

    if (toEgress.length === 0) {
      alert("请先选择已索引的文件");
      return;
    }

    const skippedCount = ids.length - toEgress.length;
    const confirmMsg = skippedCount > 0
      ? `选中的项目中,有 ${skippedCount} 个文件不是“已索引”状态,无法摄出。\n确定摄出其余 ${toEgress.length} 个文件吗?`
      : `确定摄出选中的 ${toEgress.length} 个文件吗?`;
    if (!confirm(confirmMsg)) return;

    try {
      const res = await fetch(`${API_BASE}/wiki/batch_egress`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ids: toEgress }),
      });
      if (!res.ok) {
        const error = await res.json().catch(() => ({ detail: "批量摄出失败" }));
        alert(error.detail || "批量摄出失败");
        return;
      }
      setSelectedIds(new Set());
      await fetchFiles();
      if (selectedFileId && toEgress.includes(selectedFileId)) {
        setWikiContent("");
        setViewMode("wiki_tree");
      }
    } catch {
      alert("批量摄出请求发生错误");
      await fetchFiles();
    }
  };

  const handleBatchCancelIngest = async () => {
    const toCancel = Array.from(selectedIds).filter(id => {
      const file = files.find(f => f.id === id);
      return file && file.status === "Ingesting";
    });

    if (toCancel.length === 0) {
      alert("请先选择正在摄入的文件");
      return;
    }

    if (!confirm(`确定终止选中的 ${toCancel.length} 个摄入任务吗?终止后状态会回到“待处理”。`)) return;

    setFiles(prev => prev.map(f => toCancel.includes(f.id) ? { ...f, status: "Pending" } : f));
    try {
      const res = await fetch(`${API_BASE}/wiki/ingest/cancel`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ids: toCancel }),
      });
      if (!res.ok) {
        const error = await res.json().catch(() => ({ detail: "批量终止失败" }));
        alert(error.detail || "批量终止失败");
      }
      setSelectedIds(new Set());
      await fetchFiles();
    } catch {
      alert("批量终止请求发生错误");
      await fetchFiles();
    }
  };

  const fetchPreview = async (id: string) => {
    latestPreviewRequestIdRef.current = id;
    const targetFile = files.find(f => f.id === id);
    if (targetFile && canDirectIframePreview(targetFile.name)) {
      setPreviewStatus("ready");
      setPreviewContent("");
      setIsPreviewLoading(false);
      return;
    }

    setSpreadsheetSheets(null);
    setSpreadsheetTruncated(false);

    if (targetFile && needsSpreadsheetPreview(targetFile.name)) {
      setIsPreviewLoading(true);
      setPreviewStatus("loading");
      setPreviewContent("");
      try {
        const res = await fetch(`${API_BASE}/files/view/${encodeURIComponent(id)}`);
        if (latestPreviewRequestIdRef.current !== id) return;
        if (!res.ok) {
          setPreviewStatus("error");
          setPreviewContent("预览加载失败");
          return;
        }
        const contentLength = Number(res.headers.get("content-length") || 0);
        if (contentLength > SPREADSHEET_MAX_FILE_BYTES) {
          setPreviewStatus("error");
          setPreviewContent("文件过大,不支持在线预览,请下载查看完整内容。");
          return;
        }
        const buffer = await res.arrayBuffer();
        if (latestPreviewRequestIdRef.current !== id) return;
        const workbook = XLSX.read(buffer, { type: "array" });
        const { sheets, truncated } = workbookToSpreadsheetData(workbook);
        if (latestPreviewRequestIdRef.current !== id) return;
        setSpreadsheetSheets(sheets);
        setSpreadsheetTruncated(truncated);
        setPreviewStatus("ready");
      } catch (e) {
        console.error("Excel 预览解析失败", e);
        if (latestPreviewRequestIdRef.current !== id) return;
        setPreviewStatus("error");
        setPreviewContent("该文件解析失败,可能已加密或已损坏,请下载后用本地工具打开。");
      } finally {
        if (latestPreviewRequestIdRef.current === id) setIsPreviewLoading(false);
      }
      return;
    }

    setIsPreviewLoading(true);
    setPreviewStatus("loading");
    setPreviewContent("正在加载预览...");
    try {
      const res = await fetch(`${API_BASE}/files/view/${encodeURIComponent(id)}`);
      if (res.ok) {
        const contentType = res.headers.get("content-type") || "";
        if (contentType.includes("application/json")) {
          const data = await res.json();
          if (data.type === "text_preview") {
            setPreviewContent(data.content);
          } else {
            setPreviewContent(data.content || "无法解析文档内容");
          }
        } else {
          setPreviewContent("");
        }
        setPreviewStatus("ready");
      } else if (res.status === 202) {
        const data = await res.json().catch(() => null);
        setPreviewStatus("missing");
        setPreviewContent(data?.detail?.message || "预览 PDF 尚未生成,请稍后刷新或先发起摄入。");
      } else {
        setPreviewStatus("error");
        setPreviewContent("预览加载失败");
      }
    } catch {
      setPreviewStatus("error");
      setPreviewContent("预览请求发生错误");
    } finally {
      setIsPreviewLoading(false);
    }
  };

  const onSelectFile = async (id: string) => {
    setSelectedFileId(id);
    setPreviewStatus("idle");
    setPreviewContent("");
    setIsPreviewLoading(false);
    // 强制跳转到原始文档预览模式
    setViewMode("raw");
    setIsModalOpen(true);
    setWikiLinks([]);
    setSelectedWikiPath(null);
    const file = files.find(f => f.id === id);
    if (file?.status === "Indexed") {
      try {
        const res = await fetch(`${API_BASE}/files/${encodeURIComponent(id)}/wiki_links`);
        if (res.ok) {
          const data = await res.json();
          setWikiLinks(data.links || []);
        }
      } catch {
        console.error("Failed to fetch wiki links");
      }
    } else {
      setWikiContent("");
    }
    fetchPreview(id);
  };

  const handleLint = async () => {
    setIsLintModalOpen(true);
    setLintHistory([{ role: "user", content: "请对 Wiki 知识库进行全面的健康检查。" }]);
    setIsLinting(true);
    try {
      const response = await fetch(`${API_BASE}/wiki/lint`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ query: "对知识库进行全面的 Lint 检查" }),
      });

      if (!response.body) throw new Error("ReadableStream not supported");

      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let aiResponse = "";
      let buffer = "";
      const messageMap: Record<string, string> = {};

      while (true) {
        const { value, done } = await reader.read();
        if (done) break;

        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split("\n");
        buffer = lines.pop() || "";

        for (const line of lines) {
          const trimmedLine = line.trim();
          if (!trimmedLine || !trimmedLine.startsWith("data: ")) continue;

          const dataStr = trimmedLine.slice(6).trim();
          if (dataStr === "[DONE]") break;

          try {
            const data = JSON.parse(dataStr);
            const m_id = data.id || `msg-${Date.now()}`;

            if (["thought", "call", "response"].includes(data.type)) {
              setLintHistory(prev => {
                const newHistory = [...prev];
                let lastIdx = newHistory.length - 1;
                if (lastIdx < 0 || newHistory[lastIdx].role !== "ai") {
                  newHistory.push({ role: "ai", content: "", reasoning: [], startTime: Date.now() });
                  lastIdx = newHistory.length - 1;
                }
                const last = newHistory[lastIdx];
                const reasoning = [...(last.reasoning || [])];
                const stepId = data.id || `${data.type}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;

                const existingIndex = reasoning.findIndex(r => r.id === stepId);
                if (existingIndex !== -1) {
                  reasoning[existingIndex] = {
                    ...reasoning[existingIndex],
                    type: (data.type && data.type !== 'thought') ? data.type : reasoning[existingIndex].type,
                    content: data.content,
                    name: data.name || reasoning[existingIndex].name
                  };
                } else {
                  reasoning.push({
                    id: stepId,
                    type: data.type,
                    content: data.content,
                    name: data.name
                  });
                }
                newHistory[lastIdx] = { ...last, reasoning };
                return newHistory;
              });
            } else if (data.type === "bot" || data.type === "stream") {
              const content = data.content;
              if (content === undefined || content === null) continue;

              if (data.type === "bot") {
                messageMap[m_id] = content;
                aiResponse = Object.values(messageMap).join("");
              } else {
                aiResponse += content;
              }

              setLintHistory(prev => {
                const newHistory = [...prev];
                const lastIdx = newHistory.length - 1;
                if (lastIdx < 0 || newHistory[lastIdx].role !== "ai") {
                  newHistory.push({ role: "ai", content: aiResponse, reasoning: [], startTime: Date.now() });
                } else {
                  newHistory[lastIdx] = { 
                    ...newHistory[lastIdx], 
                    content: aiResponse,
                    startTime: newHistory[lastIdx].startTime || Date.now()
                  };
                }
                return newHistory;
              });
            }
          } catch (error) {
            console.error("Parse error", error, dataStr);
          }
        }
      }
    } catch (error) {
      setLintHistory(prev => [...prev, { role: "ai", content: "健康检查发生错误,请稍后再试。" }]);
    } finally {
      setIsLinting(false);
      setLintHistory(prev => {
        if (prev.length === 0) return prev;
        const newHistory = [...prev];
        const lastIdx = newHistory.length - 1;
        if (newHistory[lastIdx].role === "ai") {
          newHistory[lastIdx] = {
            ...newHistory[lastIdx],
            endTime: Date.now()
          };
        }
        return newHistory;
      });
    }
  };

  const handleQuery = async () => {
    if (!query.trim()) return;
    const userMessage = query;
    setQuery("");

    const historyToSend = chatHistory
      .filter(msg => msg.content && msg.content.trim())
      .slice(-16)
      .map(msg => ({
        role: msg.role === "ai" ? "assistant" : "user",
        content: msg.content
      }));

    setChatHistory(prev => [...prev, { role: "user", content: userMessage }]);
    setIsLoading(true);
    setIsChatOpen(true);

    const controller = new AbortController();
    setAbortController(controller);

    try {
      const response = await fetch(`${API_BASE}/wiki/query`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ 
          query: userMessage,
          history: historyToSend,
          sessionId: sessionId
        }),
        signal: controller.signal,
      });

      if (!response.body) throw new Error("ReadableStream not supported");

      // 检查 HTTP 状态码,若后端返回错误直接提示
      if (!response.ok) {
        const errData = await response.json().catch(() => ({ detail: `服务器错误 ${response.status}` }));
        throw new Error(errData.detail || `服务器错误 ${response.status}`);
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let aiResponse = "";
      let buffer = "";
      const messageMap: Record<string, string> = {};
      // 超时保护:90 秒内没有任何 SSE 数据则自动断开
      const TIMEOUT_MS = 90_000;
      let lastEventTime = Date.now();
      let streamFinished = false;
      let streamError: Error | null = null;

      while (!streamFinished) {
        // 检查超时
        if (Date.now() - lastEventTime > TIMEOUT_MS) {
          reader.cancel();
          throw new Error("等待响应超时(90秒),请检查后端服务是否正常运行。");
        }
        const { value, done } = await reader.read();
        if (done) break;
        lastEventTime = Date.now(); // 收到数据,刷新计时

        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split("\n");
        buffer = lines.pop() || "";

        for (const line of lines) {
          const trimmedLine = line.trim();
          if (!trimmedLine || !trimmedLine.startsWith("data: ")) continue;

          const dataStr = trimmedLine.slice(6).trim();
          if (dataStr === "[DONE]") {
            streamFinished = true;
            setIsLoading(false);
            setAbortController(null);
            break;
          }
          if (dataStr === "[INIT]") continue;

          try {
            const data = JSON.parse(dataStr);
            const m_id = data.id || `msg-${Date.now()}`;

            if (data.type === "heartbeat") {
              continue;
            }

            if (data.type === "done") {
              streamFinished = true;
              setIsLoading(false);
              setAbortController(null);
              setChatHistory(prev => {
                if (prev.length === 0) return prev;
                const newHistory = [...prev];
                for (let i = newHistory.length - 1; i >= 0; i--) {
                  if (newHistory[i].role === "ai") {
                    newHistory[i] = {
                      ...newHistory[i],
                      isStreaming: false,
                      endTime: newHistory[i].endTime || Date.now(),
                      // 服务器权威耗时:用于显示真实的「思考过程秒数」
                      serverDurationMs: data.data?.duration_ms ?? newHistory[i].serverDurationMs
                    };
                    break;
                  }
                }
                return newHistory;
              });
              break;
            }

            if (data.type === "error") {
              streamError = new Error(data.content || "Wiki 查询失败");
              streamFinished = true;
              setIsLoading(false);
              setAbortController(null);
              break;
            }

            if (data.type === "sources") {
              const sources = data.content;
              setChatHistory(prev => {
                if (prev.length === 0) return prev;
                const newHistory = [...prev];
                const lastIdx = newHistory.length - 1;
                const last = newHistory[lastIdx];

                if (last.role === "ai") {
                  const reasoning = [...(last.reasoning || [])];
                  const stepId = data.id || `source-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;

                  const existingIndex = reasoning.findIndex(r => r.id === stepId);
                  if (existingIndex !== -1) {
                    reasoning[existingIndex] = { ...reasoning[existingIndex], data: sources };
                  } else {
                    reasoning.push({
                      id: stepId,
                      type: 'sources',
                      content: '引用来源数据',
                      data: sources,
                      time: new Date(data.ts || Date.now()).toLocaleTimeString('zh-CN', { hour12: false })
                    });
                  }
                  newHistory[lastIdx] = { ...last, reasoning, isStreaming: true, endTime: undefined };
                }
                return newHistory;
              });
            } else if (["thought", "call", "response"].includes(data.type)) {
              setChatHistory(prev => {
                const newHistory = [...prev];
                let lastIdx = newHistory.length - 1;

                if (lastIdx < 0 || newHistory[lastIdx].role !== "ai") {
                  newHistory.push({ role: "ai", content: "", reasoning: [], startTime: Date.now(), isStreaming: true });
                  lastIdx = newHistory.length - 1;
                }

                const last = newHistory[lastIdx];
                const reasoning = [...(last.reasoning || [])];
                const stepId = data.id || `${data.type}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;

                const existingIndex = reasoning.findIndex(r => r.id === stepId);
                if (existingIndex !== -1) {
                  reasoning[existingIndex] = {
                    ...reasoning[existingIndex],
                    type: (data.type && data.type !== 'thought') ? data.type : reasoning[existingIndex].type,
                    content: data.content,
                    name: data.name || reasoning[existingIndex].name
                  };
                } else {
                  reasoning.push({
                    id: stepId,
                    type: data.type,
                    content: data.content,
                    name: data.name,
                    time: new Date(data.ts || Date.now()).toLocaleTimeString('zh-CN', { hour12: false })
                  });
                }

                newHistory[lastIdx] = { ...last, reasoning, isStreaming: true, endTime: undefined };
                return newHistory;
              });
            } else if (data.type === "bot" || data.type === "stream") {
              const content = data.content;
              if (content === undefined || content === null) continue;

              if (data.type === "bot") {
                // 如果是 bot 类型,通常是完整消息或消息片段的替换
                messageMap[m_id] = content;
                // 重新组合所有非推理消息
                aiResponse = Object.values(messageMap).join("");
              } else {
                // 如果是 stream 类型,则是追加增量
                aiResponse += content;
              }

              setChatHistory(prev => {
                const newHistory = [...prev];
                const lastIdx = newHistory.length - 1;

                if (lastIdx < 0 || newHistory[lastIdx].role !== "ai") {
                  newHistory.push({ role: "ai", content: aiResponse, reasoning: [], startTime: Date.now(), isStreaming: true });
                } else {
                  newHistory[lastIdx] = { 
                    ...newHistory[lastIdx], 
                    content: aiResponse,
                    startTime: newHistory[lastIdx].startTime || Date.now(),
                    isStreaming: true,
                    endTime: undefined
                  };
                }
                return newHistory;
              });
            }
          } catch (e) {
            console.error("Parse error", e, dataStr);
          }
        }

        if (streamError) {
          throw streamError;
        }
      }
    } catch (e) {
      if (e instanceof Error && e.name === 'AbortError') {
        setChatHistory(prev => [...prev, { role: "ai", content: "已手动终止回答。" }]);
      } else {
        setChatHistory(prev => [...prev, { role: "ai", content: "咨询 AI 助手时发生错误,请稍后再试。" }]);
      }
    } finally {
      setIsLoading(false);
      setAbortController(null);
      setChatHistory(prev => {
        if (prev.length === 0) return prev;
        const newHistory = [...prev];
        const lastIdx = newHistory.length - 1;
        const finishedAt = Date.now();
        for (let i = 0; i < newHistory.length; i++) {
          if (newHistory[i].role === "ai" && newHistory[i].isStreaming) {
            newHistory[i] = {
              ...newHistory[i],
              isStreaming: false,
              endTime: newHistory[i].endTime || finishedAt
            };
          }
        }
        if (newHistory[lastIdx].role === "ai" && !newHistory[lastIdx].endTime) {
          newHistory[lastIdx] = {
            ...newHistory[lastIdx],
            isStreaming: false,
            endTime: finishedAt
          };
        }
        return newHistory;
      });
    }
  };

  const handleStopChat = () => {
    if (abortController) {
      abortController.abort();
      setAbortController(null);
      setIsLoading(false);
    }
  };

  const toggleSelect = (name: string, e: React.MouseEvent) => {
    e.stopPropagation();
    const newSet = new Set(selectedIds);
    if (newSet.has(name)) newSet.delete(name);
    else newSet.add(name);
    setSelectedIds(newSet);
  };

  const toggleSelectAll = () => {
    if (selectedIds.size === filteredFiles.length) {
      setSelectedIds(new Set());
    } else {
      setSelectedIds(new Set(filteredFiles.map(f => f.id)));
    }
  };

  const selectedFileObj = useMemo(() => files.find(f => f.id === selectedFileId), [files, selectedFileId]);

  const renderTokenCount = (total_tokens: number | { total_tokens: number; input_tokens: number; output_tokens: number } | undefined) => {
    if (typeof total_tokens === 'object' && total_tokens !== null) {
      return (total_tokens.total_tokens || 0).toString();
    }
    return (total_tokens || 0).toString();
  };

  const renderTokenTitle = (file: FileItem) => {
    if (file.status !== "Indexed" || !file.meta) return undefined;
    const llmTotal =
      typeof file.meta.total_tokens === "object" && file.meta.total_tokens !== null
        ? file.meta.total_tokens.total_tokens || 0
        : file.meta.total_tokens || 0;
    const input =
      file.meta.input_tokens ??
      (typeof file.meta.total_tokens === "object" && file.meta.total_tokens !== null ? file.meta.total_tokens.input_tokens : 0) ??
      0;
    const output =
      file.meta.output_tokens ??
      (typeof file.meta.total_tokens === "object" && file.meta.total_tokens !== null ? file.meta.total_tokens.output_tokens : 0) ??
      0;
    const vlm = file.meta.vlm_total_tokens ?? 0;
    const cached = file.meta.cached_input_tokens ?? 0;
    const overall = file.meta.overall_total_tokens ?? (llmTotal + vlm);
    const hitRate = input > 0 ? ((cached / input) * 100).toFixed(1) : "0.0";
    const mode = file.meta.ingest_mode ? `\n路线: ${file.meta.ingest_mode}` : "";
    return `总消耗: ${overall}(LLM ${llmTotal} = 输入 ${input} + 输出 ${output};VLM ${vlm})\n缓存命中: ${cached} (${hitRate}%)${mode}`;
  };

  const handleSort = (field: typeof sortBy, defaultOrder: "asc" | "desc") => {
    setCurrentPage(1);
    if (sortBy === field) {
      setSortOrder(sortOrder === "asc" ? "desc" : "asc");
    } else {
      setSortBy(field);
      setSortOrder(defaultOrder);
    }
  };

  const renderSortLabel = (label: string, field: typeof sortBy) => (
    <span className="inline-flex items-center gap-1 whitespace-nowrap">
      <span>{label}</span>
      <span className="inline-block w-3 text-center text-[11px] leading-none">
        {sortBy === field ? (sortOrder === "asc" ? "↑" : "↓") : ""}
      </span>
    </span>
  );

  const getFileIcon = (format: string) => {
    const f = format.toLowerCase();
    if (f === "pdf") return <FileImage className="w-4 h-4 text-rose-500" />;
    if (f === "xlsx" || f === "xls" || f === "csv") return <FileSpreadsheet className="w-4 h-4 text-emerald-500" />;
    if (f === "docx" || f === "doc") return <FileText className="w-4 h-4 text-blue-500" />;
    if (f === "pptx" || f === "ppt") return <FileArchive className="w-4 h-4 text-orange-500" />;
    if (f === "json" || f === "ts" || f === "tsx" || f === "js" || f === "py") return <FileCode className="w-4 h-4 text-slate-500" />;
    return <FileText className="w-4 h-4 text-slate-500" />;
  };

  return (
    <>
      {/* Main Content Area: File Management Table */}
      <header className="px-10 py-8 border-b border-slate-100 bg-white shrink-0">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-4xl font-bold text-slate-800 tracking-tight">Wiki 知识库</h1>
            <p className="text-base text-slate-400 mt-2">管理您的企业文档与 AI 生成的 Wiki 知识</p>
          </div>

          <div className="flex items-center gap-4">
            <div className="flex items-center gap-4 w-fit">
              <div className="relative group w-80">
                <button
                  onClick={() => {
                    setCurrentPage(1);
                    setSearchQuery(searchInput);
                    setRefreshTrigger(prev => prev + 1);
                  }}
                  title="查询"
                  className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-blue-500 transition-colors z-10"
                >
                  <Search className="w-5 h-5" />
                </button>
                <input
                  type="text"
                  value={searchInput}
                  onChange={(e) => setSearchInput(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === "Enter") {
                      setCurrentPage(1);
                      setSearchQuery(searchInput);
                      setRefreshTrigger(prev => prev + 1);
                    }
                  }}
                  placeholder="搜索文件名..."
                  className="w-full pl-11 pr-10 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all"
                />
                {searchInput && (
                  <button
                    onClick={() => {
                      setSearchInput("");
                      setSearchQuery("");
                      setCurrentPage(1);
                      setRefreshTrigger(prev => prev + 1);
                    }}
                    title="清除"
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 transition-colors"
                  >
                    <X className="w-4 h-4" />
                  </button>
                )}
              </div>
              <button
                onClick={() => {
                  setCurrentPage(1);
                  setSearchQuery(searchInput);
                  setRefreshTrigger(prev => prev + 1);
                }}
                className="flex items-center gap-2 px-5 py-2.5 bg-blue-50 text-blue-600 rounded-xl cursor-pointer hover:bg-blue-100 transition font-bold text-sm h-[42px]"
              >
                查询
              </button>
            </div>

            <button
              onClick={handleLint}
              className="flex items-center gap-2 px-5 py-2.5 bg-emerald-50 text-emerald-600 rounded-xl cursor-pointer hover:bg-emerald-100 transition font-bold text-sm h-[42px]"
            >
              <ShieldCheck className="w-4 h-4" />
              健康检查
            </button>

            <button
              onClick={() => { setUploadQueue([]); setIsUploadModalOpen(true); }}
              className="flex items-center gap-2 px-5 py-2.5 bg-blue-600 text-white rounded-xl cursor-pointer hover:bg-blue-700 transition shadow-lg shadow-blue-500/20 font-bold text-sm h-[42px]"
            >
              <Upload className="w-4 h-4" />
              上传文件
            </button>
          </div>
        </div>
      </header>

      {/* Toolbar */}
      <div className="px-8 py-4 bg-white border-b border-slate-100 flex items-center justify-between shrink-0">
        <div className="flex items-center gap-4">
          <div className="flex items-center gap-2">
            <button
              onClick={toggleSelectAll}
              className="w-5 h-5 border border-slate-300 rounded bg-white flex items-center justify-center hover:border-blue-500 transition"
            >
              {selectedIds.size > 0 && (
                selectedIds.size === filteredFiles.length ? <Check className="w-3 h-3 text-blue-600" /> : <div className="w-2 h-[2px] bg-blue-600" />
              )}
            </button>
            <span className="text-sm font-medium text-slate-600">
              {selectedIds.size > 0 ? `已选择 ${selectedIds.size} 项` : "全选"}
            </span>
          </div>

          {selectedIds.size > 0 && (
            <div className="flex gap-2 animate-in fade-in slide-in-from-left-2 duration-200">
              <button
                onClick={handleBatchIngest}
                className="text-xs font-bold bg-blue-50 text-blue-600 px-4 py-2 rounded-lg flex items-center gap-2 hover:bg-blue-100 transition"
              >
                <Zap className="w-3.5 h-3.5" /> 批量摄入
              </button>
              <button
                onClick={handleBatchEgress}
                className="text-xs font-bold bg-amber-50 text-amber-600 px-4 py-2 rounded-lg flex items-center gap-2 hover:bg-amber-100 transition"
              >
                <Eject className="w-3.5 h-3.5 rotate-180" /> 批量摄出
              </button>
              <button
                onClick={handleBatchCancelIngest}
                className="text-xs font-bold bg-rose-50 text-rose-600 px-4 py-2 rounded-lg flex items-center gap-2 hover:bg-rose-100 transition"
              >
                <Square className="w-3.5 h-3.5 fill-current" /> 批量终止
              </button>
              <button
                onClick={async () => {
                  const ids = Array.from(selectedIds);
                  const toDelete = ids.filter(id => {
                    const f = files.find(file => file.id === id);
                    return f && (f.status === "Pending" || f.status === "Failed");
                  });

                  if (toDelete.length === 0) {
                    alert("选中的项目中没有处于“待处理”或“失败”状态的文件,无法删除。请先对已索引的文件执行“摄出”操作。");
                    return;
                  }

                  const restrictedCount = ids.length - toDelete.length;
                  const confirmMsg = restrictedCount > 0
                    ? `选中的项目中,有 ${restrictedCount} 个文件已摄入,无法删除。\n确定删除其余 ${toDelete.length} 个“待处理”的文件吗?`
                    : `确定删除选中的 ${toDelete.length} 个文件吗?`;

                  if (confirm(confirmMsg)) {
                    setIsDeleting("batch");
                    // 如果批量删除中包含当前选中的文件,先清除选中状态以卸载预览组件 (释放 iframe 句柄)
                    const isSelectedIncluded = selectedFileId && toDelete.includes(selectedFileId);
                    if (isSelectedIncluded) {
                      const iframe = document.querySelector('iframe');
                      if (iframe) iframe.src = "about:blank";

                      setSelectedFileId(null);
                      setWikiContent("");
                      await new Promise(resolve => setTimeout(resolve, 1000));
                    }

                    try {
                      const response = await fetch(`${API_BASE}/files/batch_delete`, {
                        method: "POST",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify({ ids: toDelete })
                      });
                      if (!response.ok) {
                        const errorData = await response.json().catch(() => ({ detail: "未知错误" }));
                        throw new Error(errorData.detail || `服务器返回状态码: ${response.status}`);
                      }
                    } catch (e) {
                      console.error("Batch delete failed", e);
                      const msg = e instanceof Error ? e.message : "请检查网络或后端服务状态";
                      alert(`批量删除失败: ${msg}`);
                    }
                    setSelectedIds(new Set());
                    fetchFiles();
                    setIsDeleting(null);
                  }
                }}
                className="text-xs font-bold bg-red-50 text-red-600 px-4 py-2 rounded-lg flex items-center gap-2 hover:bg-red-100 transition"
              >
                <Trash2 className="w-3.5 h-3.5" /> 批量删除
              </button>
            </div>
          )}
        </div>
      </div>

      {/* Table View */}
      <div className="flex-1 overflow-auto scrollbar-thin p-8 flex flex-col">
        <div className="min-w-full inline-block align-middle flex-1">
          <div className="border border-slate-100 rounded-2xl overflow-hidden shadow-sm">
            <table className="min-w-full table-fixed divide-y divide-slate-100">
              <thead className="sticky top-0 z-20 bg-slate-50/95 backdrop-blur">
                <tr>
                  <th scope="col" className="w-16 px-6 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider"></th>
                  <th
                    scope="col"
                    className="w-[31%] px-6 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider cursor-pointer hover:text-blue-600 transition"
                    onClick={() => handleSort("name", "asc")}
                  >
                    {renderSortLabel("文件名", "name")}
                  </th>
                  <th
                    scope="col"
                    className="w-[150px] px-6 py-3 text-left text-xs font-bold text-slate-400 uppercase tracking-wider cursor-pointer hover:text-blue-600 transition"
                    onClick={() => handleSort("status", "asc")}
                  >
                    <div className="flex items-center gap-2 whitespace-nowrap">
                      {renderSortLabel("状态", "status")}
                      <select
                        value={statusFilter}
                        onClick={(e) => e.stopPropagation()}
                        onChange={(e) => {
                          setStatusFilter(e.target.value as typeof statusFilter);
                          setCurrentPage(1);
                        }}
                        className="h-7 rounded-md border border-slate-200 bg-white px-2 text-[11px] font-semibold normal-case tracking-normal text-slate-600 outline-none transition hover:border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20"
                      >
                        <option value="All">全部</option>
                        <option value="Indexed">已索引</option>
                        <option value="Pending">待处理</option>
                        <option value="Ingesting">摄入中</option>
                        <option value="Uploading">上传中</option>
                        <option value="Failed">失败</option>
                      </select>
                    </div>
                  </th>
                  <th
                    scope="col"
                    className="w-[170px] px-6 py-3 text-left text-xs font-bold text-slate-400 uppercase tracking-wider cursor-pointer hover:text-blue-600 transition"
                    onClick={() => handleSort("format", "asc")}
                  >
                    <div className="flex items-center gap-2 whitespace-nowrap">
                      {renderSortLabel("文件类型", "format")}
                      <select
                        value={formatFilter}
                        onClick={(e) => e.stopPropagation()}
                        onChange={(e) => {
                          setFormatFilter(e.target.value);
                          setCurrentPage(1);
                        }}
                        className="h-7 rounded-md border border-slate-200 bg-white px-2 text-[11px] font-semibold normal-case tracking-normal text-slate-600 outline-none transition hover:border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20"
                      >
                        <option value="All">全部</option>
                        {formatOptions.map(format => (
                          <option key={format} value={format}>{format}</option>
                        ))}
                      </select>
                    </div>
                  </th>
                  <th
                    scope="col"
                    className="w-[110px] px-6 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider cursor-pointer hover:text-blue-600 transition"
                    onClick={() => handleSort("size", "desc")}
                  >
                    {renderSortLabel("大小", "size")}
                  </th>
                  <th
                    scope="col"
                    className="w-[135px] px-6 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider cursor-pointer hover:text-blue-600 transition"
                    onClick={() => handleSort("time", "desc")}
                  >
                    {renderSortLabel("上传时间", "time")}
                  </th>
                  <th
                    scope="col"
                    className="w-[110px] px-6 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider cursor-pointer select-none hover:text-slate-600"
                    onClick={() => handleSort("word_count", "desc")}
                  >
                    {renderSortLabel("字数", "word_count")}
                  </th>
                  <th
                    scope="col"
                    className="w-[130px] px-6 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider cursor-pointer select-none hover:text-slate-600"
                    onClick={() => handleSort("token", "desc")}
                  >
                    {renderSortLabel("Token 消耗", "token")}
                  </th>
                  <th scope="col" className="w-[125px] px-6 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider">处理时长</th>
                  <th scope="col" className="w-[115px] px-6 py-4 text-right text-xs font-bold text-slate-400 uppercase tracking-wider">操作</th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-slate-50">
                {isInitialLoading ? (
                  [1, 2, 3, 4, 5].map(i => (
                    <tr key={i} className="animate-pulse">
                      <td className="px-6 py-4"><div className="w-5 h-5 bg-slate-100 rounded" /></td>
                      <td className="px-6 py-4"><div className="h-4 bg-slate-100 rounded w-3/4" /></td>
                      <td className="px-6 py-4"><div className="h-4 bg-slate-50 rounded w-16" /></td>
                      <td className="px-6 py-4"><div className="h-4 bg-slate-50 rounded w-14" /></td>
                      <td className="px-6 py-4"><div className="h-4 bg-slate-50 rounded w-12" /></td>
                      <td className="px-6 py-4"><div className="h-4 bg-slate-50 rounded w-24" /></td>
                      <td className="px-6 py-4"><div className="h-4 bg-slate-50 rounded w-16" /></td>
                      <td className="px-6 py-4"><div className="h-4 bg-slate-50 rounded w-16" /></td>
                      <td className="px-6 py-4"><div className="h-4 bg-slate-100 rounded ml-auto w-20" /></td>
                    </tr>
                  ))
                ) : (
                  filteredFiles.map((file) => (
                    <tr
                      key={file.id}
                      className={cn(
                        "group hover:bg-slate-50/80 transition-colors cursor-pointer",
                        selectedFileId === file.id && "bg-blue-50/30"
                      )}
                      // eslint-disable-next-line react-hooks/refs -- ref access happens after the row click starts preview loading.
                      onClick={() => onSelectFile(file.id)}
                    >
                      <td className="px-6 py-4 whitespace-nowrap" onClick={(e) => e.stopPropagation()}>
                        <button
                          onClick={(e) => toggleSelect(file.id, e)}
                          className={cn(
                            "w-5 h-5 border rounded flex items-center justify-center transition-all",
                            selectedIds.has(file.id) ? "bg-blue-600 border-blue-600 text-white" : "bg-white border-slate-200 group-hover:border-slate-300"
                          )}
                        >
                          {selectedIds.has(file.id) && <Check className="w-3 h-3" />}
                        </button>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="flex min-w-0 items-center gap-3">
                          <div className="p-2 bg-slate-100 rounded-lg text-slate-500 group-hover:text-blue-600 transition-colors">
                            {getFileIcon(file.format)}
                          </div>
                          <span className="min-w-0 flex-1 truncate text-sm font-semibold text-slate-700" title={file.name}>
                            {file.name}
                          </span>
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        {isDeleting === file.id ? (
                          <span className="inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-[10px] font-bold bg-red-50 text-red-600 border border-red-100">
                            <Loader2 className="w-3 h-3 animate-spin" /> 删除中
                          </span>
                        ) : (
                          <>
                            {file.status === "Indexed" ? (
                              <span className="inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-[10px] font-bold bg-emerald-50 text-emerald-600 border border-emerald-100">
                                <CheckCircle2 className="w-3 h-3" /> 已索引
                              </span>
                            ) : file.status === "Ingesting" ? (
                              <span className="inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-[10px] font-bold bg-blue-50 text-blue-600 border border-blue-100 animate-pulse">
                                <Loader2 className="w-3 h-3 animate-spin" /> 摄入中
                              </span>
                            ) : file.status === "Uploading" ? (
                              <span className="inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-[10px] font-bold bg-purple-50 text-purple-600 border border-purple-100 animate-pulse">
                                <Upload className="w-3 h-3 animate-bounce" /> 上传中
                              </span>
                            ) : file.status === "Failed" ? (
                              <span className="inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-[10px] font-bold bg-red-50 text-red-600 border border-red-100">
                                <AlertCircle className="w-3 h-3" /> 摄入失败
                              </span>
                            ) : (
                              <span className="inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-[10px] font-bold bg-amber-50 text-amber-600 border border-amber-100">
                                <Clock className="w-3 h-3" /> 待处理
                              </span>
                            )}
                          </>
                        )}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <span className="inline-flex items-center rounded-md bg-slate-50 px-2 py-1 text-xs font-bold text-slate-600 border border-slate-100">
                          {file.format}
                        </span>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-xs text-slate-500 font-medium">
                        {file.size}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-xs text-slate-500 font-medium">
                        {file.time}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-xs text-slate-500 font-medium">
                        {file.word_count ? file.word_count.toLocaleString() : "--"}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <span className="text-xs font-bold text-slate-700" title={renderTokenTitle(file)}>
                          {file.status === "Indexed" && file.meta
                            ? renderTokenCount(file.meta.overall_total_tokens ?? file.meta.total_tokens)
                            : "--"}
                        </span>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <span className="text-xs font-bold text-slate-700">
                          {file.status === "Indexed" && file.meta ? `${file.meta.ingest_duration}s` : "--"}
                        </span>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-right" onClick={(e) => e.stopPropagation()}>
                        <div className="flex items-center justify-end gap-2 relative z-10">
                          {(file.status === "Pending" || file.status === "Failed") && !file.id.startsWith('-') && (
                            <>
                              <button onClick={(e) => { e.stopPropagation(); handleIngest(file.id); }} title="开始摄入" className="p-2 bg-blue-50 hover:bg-blue-100 text-blue-600 rounded-lg cursor-pointer transition-colors">
                                <Zap className="w-4 h-4" />
                              </button>
                              <button onClick={(e) => { e.stopPropagation(); handleDelete(file.id); }} title="删除" className="p-2 bg-slate-50 hover:bg-red-50 text-slate-500 hover:text-red-500 rounded-lg cursor-pointer transition-colors">
                                <Trash2 className="w-4 h-4" />
                              </button>
                            </>
                          )}
                          {file.status === "Ingesting" && (
                            <button disabled title="处理中..." className="p-2 bg-slate-50 text-slate-400 rounded-lg cursor-not-allowed">
                              <Loader2 className="w-4 h-4 animate-spin" />
                            </button>
                          )}
                          {file.status === "Indexed" && (
                            <>
                              <button onClick={(e) => { e.stopPropagation(); handleEgress(file.id); }} title="撤回" className="p-2 bg-amber-50 hover:bg-amber-100 text-amber-600 rounded-lg cursor-pointer transition-colors">
                                <Eject className="w-4 h-4 rotate-180" />
                              </button>
                            </>
                          )}
                          {!file.id.startsWith('-') && (
                            <button onClick={(e) => { e.stopPropagation(); handleDownload(file.id, file.name); }} title="下载原文件" className="p-2 hover:bg-slate-100 text-slate-400 hover:text-slate-600 rounded-lg cursor-pointer transition-colors">
                              <Download className="w-4 h-4" />
                            </button>
                          )}
                        </div>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
            {!isInitialLoading && filteredFiles.length === 0 && (
              <div className="py-20 text-center bg-white">
                <Filter className="w-12 h-12 mx-auto mb-4 text-slate-200" />
                <h3 className="text-lg font-bold text-slate-800">未找到匹配的文件</h3>
                <p className="text-sm text-slate-400 mt-1">请尝试更换关键词或检查筛选条件</p>
              </div>
            )}
          </div>
        </div>

        {/* Pagination */}
        <div className="mt-6 flex items-center justify-end shrink-0 pb-6 pr-24">
          <div className="flex items-center gap-4">
            <div className="text-sm text-slate-500 whitespace-nowrap">
              共 <span className="text-slate-800">{totalCount}</span> 个文件
            </div>

            <div className="w-px h-5 bg-slate-200" />

            <div className="flex items-center gap-2 whitespace-nowrap">
              <span className="text-sm text-slate-400">每页</span>
              <div className="relative flex items-center">
                <select
                  value={pageSize}
                  onChange={(e) => {
                    const size = Number(e.target.value);
                    setPageSize(size);
                    setCurrentPage(1);
                  }}
                  className="appearance-none h-8 rounded-lg bg-slate-50 pl-2.5 pr-7 text-sm text-slate-700 outline-none cursor-pointer transition hover:bg-slate-100 focus:ring-2 focus:ring-blue-500/20"
                >
                  {PAGE_SIZE_OPTIONS.map(size => (
                    <option key={size} value={size}>{size}</option>
                  ))}
                </select>
                <ChevronDown className="w-3.5 h-3.5 text-slate-400 absolute right-2 pointer-events-none" />
              </div>
              <span className="text-sm text-slate-400">条</span>
            </div>

            <div className="w-px h-5 bg-slate-200" />

            <div className="flex items-center gap-0.5">
              <button
                onClick={() => setCurrentPage(1)}
                disabled={currentPage === 1}
                title="第一页"
                className="w-8 h-8 flex items-center justify-center rounded-lg text-slate-500 hover:bg-slate-100 hover:text-slate-700 disabled:opacity-30 disabled:hover:bg-transparent disabled:cursor-not-allowed cursor-pointer transition-colors"
              >
                <ChevronsLeft className="w-4 h-4" />
              </button>
              <button
                onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                disabled={currentPage === 1}
                title="上一页"
                className="w-8 h-8 flex items-center justify-center rounded-lg text-slate-500 hover:bg-slate-100 hover:text-slate-700 disabled:opacity-30 disabled:hover:bg-transparent disabled:cursor-not-allowed cursor-pointer transition-colors"
              >
                <ChevronLeft className="w-4 h-4" />
              </button>

              {getPaginationRange(currentPage, Math.max(1, Math.ceil(totalCount / pageSize))).map((page, idx) => (
                page === "ellipsis" ? (
                  <span key={`ellipsis-${idx}`} className="w-8 h-8 flex items-center justify-center text-sm text-slate-300 select-none">···</span>
                ) : (
                  <button
                    key={page}
                    onClick={() => setCurrentPage(page)}
                    className={cn(
                      "w-8 h-8 flex items-center justify-center rounded-lg text-sm font-bold transition-all cursor-pointer",
                      page === currentPage
                        ? "bg-blue-600 text-white shadow-md shadow-blue-600/30"
                        : "text-slate-500 hover:bg-slate-100 hover:text-slate-800"
                    )}
                  >
                    {page}
                  </button>
                )
              ))}

              <button
                onClick={() => setCurrentPage(p => (p * pageSize >= totalCount ? p : p + 1))}
                disabled={currentPage * pageSize >= totalCount}
                title="下一页"
                className="w-8 h-8 flex items-center justify-center rounded-lg text-slate-500 hover:bg-slate-100 hover:text-slate-700 disabled:opacity-30 disabled:hover:bg-transparent disabled:cursor-not-allowed cursor-pointer transition-colors"
              >
                <ChevronRight className="w-4 h-4" />
              </button>
              <button
                onClick={() => setCurrentPage(Math.max(1, Math.ceil(totalCount / pageSize)))}
                disabled={currentPage * pageSize >= totalCount}
                title="最后一页"
                className="w-8 h-8 flex items-center justify-center rounded-lg text-slate-500 hover:bg-slate-100 hover:text-slate-700 disabled:opacity-30 disabled:hover:bg-transparent disabled:cursor-not-allowed cursor-pointer transition-colors"
              >
                <ChevronsRight className="w-4 h-4" />
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* 3. Preview Modal */}
      {isModalOpen && (
        <div
          className="fixed inset-0 z-[60] flex items-center justify-center p-6 bg-slate-900/60 backdrop-blur-sm animate-in fade-in duration-300 overflow-hidden overscroll-contain"
          onWheel={(e) => e.stopPropagation()}
        >
          <div className="bg-white w-full max-w-[75vw] h-[94vh] rounded-[2rem] shadow-2xl flex flex-col overflow-hidden animate-in zoom-in-95 duration-300">
            <header className="px-8 py-6 border-b border-slate-100 flex items-center justify-between shrink-0">
              <div className="flex items-center gap-4">
                <div className="p-3 bg-blue-50 rounded-2xl text-blue-600">
                  <BookOpen className="w-6 h-6" />
                </div>
                <div>
                  <h2 className="text-xl font-bold text-slate-800 truncate max-w-md">
                    {selectedFileObj?.name}
                  </h2>
                  <div className="flex items-center gap-3 mt-1">
                    <span className="text-xs font-medium text-slate-400">大小: {selectedFileObj?.size}</span>
                    <span className="text-xs font-medium text-slate-400">•</span>
                    <span className="text-xs font-medium text-slate-400">更新: {selectedFileObj?.time}</span>
                    {selectedFileObj?.status === "Indexed" && (
                      <>
                        <span className="text-xs font-medium text-slate-400">•</span>
                        <span className="text-xs font-bold text-emerald-600 bg-emerald-50 px-2 py-0.5 rounded-full">已索引</span>
                      </>
                    )}
                  </div>
                </div>
              </div>

              <div className="flex items-center gap-3">
                {selectedFileId && selectedFileObj?.status === "Indexed" && (
                  <div className="flex bg-slate-100 p-1.5 rounded-2xl">
                    <button
                      onClick={() => setViewMode("raw")}
                      className={cn(
                        "px-6 py-2 text-sm font-bold rounded-xl transition-all",
                        viewMode === "raw" ? "bg-white text-blue-600 shadow-md" : "text-slate-500 hover:text-slate-800"
                      )}
                    >
                      原始文件预览
                    </button>
                    <button
                      onClick={() => { setViewMode("wiki_tree"); }}
                      className={cn(
                        "px-6 py-2 text-sm font-bold rounded-xl transition-all",
                        viewMode === "wiki_tree" ? "bg-white text-blue-600 shadow-md" : "text-slate-500 hover:text-slate-800"
                      )}
                    >
                      Wiki仓库相关文件
                    </button>
                  </div>
                )}
                <button
                  onClick={() => setIsModalOpen(false)}
                  className="p-3 hover:bg-slate-100 rounded-2xl transition-colors text-slate-400 hover:text-slate-800"
                >
                  <X className="w-6 h-6" />
                </button>
              </div>
            </header>

            <div className="flex-1 overflow-hidden bg-slate-50/30 flex">
              {viewMode === "raw" ? (
                <div className="flex w-full h-full">
                  <div className="flex-1 w-full h-full p-8">
                    {selectedFileObj && canDirectIframePreview(selectedFileObj.name) ? (
                      <iframe
                        key={selectedFileId}
                        src={`${API_BASE}/files/view/${encodeURIComponent(selectedFileId || '')}`}
                        className="w-full h-full rounded-3xl border border-slate-200 bg-white shadow-xl"
                      />
                    ) : selectedFileObj && needsControlledPreview(selectedFileObj.name) ? (
                      previewStatus === "ready" ? (
                        <iframe
                          key={selectedFileId}
                          src={`${API_BASE}/files/view/${encodeURIComponent(selectedFileId || '')}`}
                          className="w-full h-full rounded-3xl border border-slate-200 bg-white shadow-xl"
                        />
                      ) : (
                        <div className="w-full h-full bg-white rounded-3xl border border-slate-200 p-12 shadow-xl flex items-center justify-center">
                          <div className="max-w-md text-center">
                            {isPreviewLoading || previewStatus === "loading" ? (
                              <>
                                <Loader2 className="w-10 h-10 animate-spin text-blue-600 mx-auto mb-4" />
                                <h3 className="text-base font-bold text-slate-800">正在加载预览...</h3>
                              </>
                            ) : previewStatus === "missing" ? (
                              <>
                                <AlertCircle className="w-10 h-10 text-amber-500 mx-auto mb-4" />
                                <h3 className="text-base font-bold text-slate-800">预览 PDF 尚未生成</h3>
                                <p className="text-sm text-slate-500 mt-2">{previewContent || "请稍后刷新,或先发起摄入生成预览资源。"}</p>
                              </>
                            ) : (
                              <>
                                <AlertCircle className="w-10 h-10 text-red-500 mx-auto mb-4" />
                                <h3 className="text-base font-bold text-slate-800">预览加载失败</h3>
                                <p className="text-sm text-slate-500 mt-2">{previewContent || "预览请求发生错误"}</p>
                              </>
                            )}
                            <button
                              onClick={() => selectedFileId && fetchPreview(selectedFileId)}
                              className="mt-5 inline-flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-sm font-bold text-white hover:bg-blue-700"
                            >
                              <RefreshCw className="w-4 h-4" /> 刷新预览
                            </button>
                          </div>
                        </div>
                      )
                    ) : selectedFileObj && needsSpreadsheetPreview(selectedFileObj.name) ? (
                      previewStatus === "ready" && spreadsheetSheets ? (
                        <div className="w-full h-full bg-white rounded-3xl border border-slate-200 shadow-xl flex flex-col overflow-hidden">
                          {spreadsheetTruncated && (
                            <div className="px-4 py-2 text-xs text-amber-700 bg-amber-50 border-b border-amber-200 shrink-0">
                              表格过大,仅显示前 {SPREADSHEET_MAX_ROWS} 行,请下载查看完整内容。
                            </div>
                          )}
                          <div className="flex-1 min-h-0">
                            <SpreadsheetPreview key={selectedFileId} sheets={spreadsheetSheets} />
                          </div>
                        </div>
                      ) : (
                        <div className="w-full h-full bg-white rounded-3xl border border-slate-200 p-12 shadow-xl flex items-center justify-center">
                          <div className="max-w-md text-center">
                            {previewStatus === "error" ? (
                              <>
                                <AlertCircle className="w-10 h-10 text-red-500 mx-auto mb-4" />
                                <h3 className="text-base font-bold text-slate-800">预览加载失败</h3>
                                <p className="text-sm text-slate-500 mt-2">{previewContent || "该文件解析失败,可能已加密或已损坏,请下载后用本地工具打开。"}</p>
                              </>
                            ) : (
                              <>
                                <Loader2 className="w-10 h-10 animate-spin text-blue-600 mx-auto mb-4" />
                                <h3 className="text-base font-bold text-slate-800">正在加载预览...</h3>
                              </>
                            )}
                            <div className="mt-5 flex items-center justify-center gap-3">
                              <button
                                onClick={() => selectedFileId && fetchPreview(selectedFileId)}
                                className="inline-flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-sm font-bold text-white hover:bg-blue-700"
                              >
                                <RefreshCw className="w-4 h-4" /> 刷新预览
                              </button>
                              {selectedFileId && (
                                <a
                                  href={`${API_BASE}/files/download/${encodeURIComponent(selectedFileId)}`}
                                  className="inline-flex items-center gap-2 rounded-lg border border-slate-300 px-4 py-2 text-sm font-bold text-slate-700 hover:bg-slate-50"
                                >
                                  <Download className="w-4 h-4" /> 下载文件
                                </a>
                              )}
                            </div>
                          </div>
                        </div>
                      )
                    ) : (
                      <div className="w-full h-full bg-white rounded-3xl border border-slate-200 p-12 overflow-auto shadow-xl relative custom-scrollbar">
                        {isPreviewLoading && (
                          <div className="absolute inset-0 bg-white/50 backdrop-blur-sm flex items-center justify-center z-10">
                            <Loader2 className="w-10 h-10 animate-spin text-blue-600" />
                          </div>
                        )}
                        {selectedFileObj?.name.toLowerCase().endsWith(".md") ? (
                          (() => {
                            const { data, body } = parseFrontmatter(previewContent);
                            return (
                              <div className="max-w-4xl mx-auto">
                                {data && <FrontmatterCard data={data} />}
                                <article className="prose prose-slate prose-blue max-w-none prose-headings:font-bold prose-a:text-blue-600 prose-table:text-sm">
                                  <ReactMarkdown remarkPlugins={[remarkGfm]}>
                                    {body}
                                  </ReactMarkdown>
                                </article>
                              </div>
                            );
                          })()
                        ) : (
                          <pre className="text-sm text-slate-700 font-mono whitespace-pre-wrap leading-relaxed">{previewContent}</pre>
                        )}
                      </div>
                    )}
                  </div>
                </div>
              ) : (
                <div className="flex w-full h-full">
                  <div className="w-80 border-r border-slate-200 bg-slate-50 flex flex-col shrink-0 overflow-y-auto custom-scrollbar">
                    <div className="p-4 border-b border-slate-200 flex items-center justify-between gap-2">
                      <h3 className="text-xs font-bold text-slate-500 uppercase tracking-wider flex items-center gap-2">
                        <BookOpen className="w-4 h-4" />
                        相关文件树 ({wikiLinks.length})
                      </h3>
                      <button
                        onClick={handleDownloadWikiZip}
                        disabled={wikiLinks.length === 0 || isZipDownloading}
                        title="打包下载全部相关文件 (ZIP)"
                        className="p-1.5 rounded-lg text-slate-400 hover:text-blue-600 hover:bg-blue-50 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
                      >
                        {isZipDownloading ? (
                          <Loader2 className="w-4 h-4 animate-spin" />
                        ) : (
                          <Download className="w-4 h-4" />
                        )}
                      </button>
                    </div>
                    <div className="p-4 flex-1 flex flex-col gap-1 overflow-x-hidden">
                      {wikiLinks.length > 0 ? (
                        <TreeNode
                          node={buildTree(wikiLinks)}
                          onSelect={async (path) => {
                            setSelectedWikiPath(path);
                            setWikiContent("正在加载文件内容...");
                            try {
                              const res = await fetch(`${API_BASE}/wiki/file?path=${encodeURIComponent(path)}`);
                              if (res.ok) {
                                const data = await res.json();
                                setWikiContent(data.content);
                              } else {
                                setWikiContent("文件加载失败");
                              }
                            } catch (e) {
                              setWikiContent("文件加载失败");
                            }
                          }}
                          selectedPath={selectedWikiPath}
                        />
                      ) : (
                        <div className="text-xs text-slate-400 p-4 text-center">
                          暂无相关文件
                        </div>
                      )}
                    </div>
                  </div>
                  <div className="flex-1 w-full h-full overflow-y-auto p-12 custom-scrollbar bg-white">
                    {selectedWikiPath ? (
                      <div className="max-w-5xl mx-auto">
                        {(() => {
                          const { data, body } = parseFrontmatter(wikiContent);
                          return (
                            <>
                              {data && <FrontmatterCard data={data} />}
                              <article className="prose prose-slate prose-blue max-w-none prose-headings:font-bold prose-a:text-blue-600 prose-table:text-sm">
                                <ReactMarkdown remarkPlugins={[remarkGfm]}>
                                  {body}
                                </ReactMarkdown>
                              </article>
                            </>
                          );
                        })()}
                      </div>
                    ) : (
                      <div className="flex items-center justify-center h-full text-slate-400">
                        <div className="text-center">
                          <FileText className="w-12 h-12 mx-auto mb-4 opacity-50" />
                          <p>请在左侧选择要预览的 Wiki 文件</p>
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* 4. AI Copilot (Modern Chat Interface) */}
      <button
        onClick={() => setIsChatOpen(!isChatOpen)}
        className={cn(
          "fixed bottom-8 right-8 w-16 h-16 rounded-2xl shadow-2xl flex items-center justify-center transition-all duration-300 z-50 group",
          isChatOpen ? "bg-slate-900 text-white rotate-90" : "bg-blue-600 text-white hover:scale-110 active:scale-95"
        )}
      >
        {isChatOpen ? <X className="w-6 h-6" /> : <MessageSquare className="w-6 h-6" />}
        <span className="absolute right-20 bg-slate-800 text-white text-[10px] px-3 py-1.5 rounded-lg opacity-0 group-hover:opacity-100 transition whitespace-nowrap pointer-events-none">
          咨询 Wiki AI 助手
        </span>
      </button>

      {isChatOpen && (
        <div className="fixed bottom-28 right-8 w-[800px] bg-white rounded-3xl shadow-[0_20px_50px_rgba(0,0,0,0.15)] border border-slate-200 flex flex-col h-[800px] z-50 animate-in fade-in slide-in-from-bottom-10 duration-300 overflow-hidden">
          <div className="p-6 border-b border-slate-100 flex items-center justify-between bg-gradient-to-r from-blue-600 to-indigo-700 text-white">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center backdrop-blur-md">
                <MessageSquare className="w-5 h-5" />
              </div>
              <div>
                <h3 className="font-bold text-sm">Wiki Copilot</h3>
                <div className="flex items-center gap-1.5">
                  <div className="w-1.5 h-1.5 bg-emerald-400 rounded-full animate-pulse" />
                  <span className="text-[10px] text-blue-100 font-medium uppercase tracking-wider">在线支持</span>
                </div>
              </div>
            </div>
            <button
              onClick={async () => {
                if (confirm("确定要清空当前对话历史吗?")) {
                  try {
                    await fetch(`${API_BASE}/wiki/clear_history`, { method: "POST" });
                  } catch (e) {
                    console.error("Failed to clear backend memory", e);
                  }
                  setChatHistory([]);
                  setQuery("");
                }
              }}
              className="p-2 hover:bg-white/10 rounded-lg transition-colors text-blue-100 hover:text-white"
              title="清空会话"
            >
              <Trash2 className="w-4 h-4" />
            </button>
          </div>

          <div className="flex-1 overflow-y-auto p-6 scrollbar-thin bg-slate-50/50 flex flex-col">
            {chatHistory.map((msg, idx) => (
              <MessageBubble
                key={idx}
                role={msg.role}
                content={msg.content}
                reasoning={msg.reasoning}
                isStreaming={msg.isStreaming ?? (isLoading && idx === chatHistory.length - 1 && !msg.endTime)}
                startTime={msg.startTime}
                endTime={msg.endTime}
                serverDurationMs={msg.serverDurationMs}
              />
            ))}
            {isLoading && chatHistory[chatHistory.length - 1]?.role !== "ai" && (
              <div className="flex gap-3">
                <div className="w-9 h-9 bg-blue-600 rounded-xl flex items-center justify-center text-white shrink-0 shadow-md font-bold text-xs">AI</div>
                <div className="bg-white p-4 rounded-2xl rounded-tl-none shadow-sm border border-slate-100 flex items-center gap-2">
                  <Loader2 className="w-4 h-4 animate-spin text-blue-600" />
                  <span className="text-xs text-slate-500">正在查阅知识库...</span>
                </div>
              </div>
            )}
            <div ref={chatEndRef} />
          </div>

          <div className="p-6 border-t border-slate-100 bg-white">
            <div className="relative">
              <input
                type="text"
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && handleQuery()}
                placeholder="输入问题,AI 将实时查询 Wiki..."
                className="w-full text-sm bg-slate-50 border border-slate-200 rounded-2xl px-4 py-4 pr-14 focus:ring-4 focus:ring-blue-500/10 focus:border-blue-500 outline-none transition-all"
              />
              {isLoading ? (
                <button
                  onClick={handleStopChat}
                  className="absolute right-2 top-1/2 -translate-y-1/2 w-10 h-10 bg-red-500 text-white rounded-xl flex items-center justify-center hover:bg-red-600 shadow-md transition-all active:scale-95"
                  title="终止生成"
                >
                  <Square className="w-4 h-4 fill-current" />
                </button>
              ) : (
                <button
                  onClick={handleQuery}
                  disabled={isLoading || !query.trim()}
                  className="absolute right-2 top-1/2 -translate-y-1/2 w-10 h-10 bg-blue-600 text-white rounded-xl flex items-center justify-center hover:bg-blue-700 shadow-md transition-all active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <ChevronRight className="w-5 h-5" />
                </button>
              )}
            </div>
          </div>
        </div>
      )}

      {/* 5. Lint Modal */}
      {isLintModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 backdrop-blur-sm p-8 animate-in fade-in duration-200">
          <div className="bg-slate-50 w-full max-w-4xl h-[80vh] rounded-3xl shadow-2xl flex flex-col overflow-hidden border border-slate-200/50">
            <div className="h-16 px-6 bg-white border-b border-slate-100 flex items-center justify-between shrink-0">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-emerald-100 rounded-xl flex items-center justify-center">
                  <ShieldCheck className="w-5 h-5 text-emerald-600" />
                </div>
                <div>
                  <h3 className="font-bold text-sm text-slate-800">Wiki 健康检查 (Lint)</h3>
                  <div className="flex items-center gap-1.5">
                    {isLinting ? (
                      <>
                        <div className="w-1.5 h-1.5 bg-emerald-400 rounded-full animate-pulse" />
                        <span className="text-[10px] text-slate-500 font-medium tracking-wider">正在扫描知识库...</span>
                      </>
                    ) : (
                      <>
                        <CheckCircle2 className="w-3 h-3 text-emerald-500" />
                        <span className="text-[10px] text-slate-500 font-medium tracking-wider">扫描完成</span>
                      </>
                    )}
                  </div>
                </div>
              </div>
              <button
                onClick={() => setIsLintModalOpen(false)}
                className="p-2 hover:bg-slate-100 rounded-lg transition-colors text-slate-400 hover:text-slate-800"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="flex-1 overflow-y-auto p-6 scrollbar-thin bg-white/50 flex flex-col">
              {lintHistory.map((msg, idx) => (
                <MessageBubble
                  key={idx}
                  role={msg.role}
                  content={msg.content}
                  reasoning={msg.reasoning}
                  isStreaming={isLinting && idx === lintHistory.length - 1}
                  startTime={msg.startTime}
                  endTime={msg.endTime}
                />
              ))}
              <div ref={lintEndRef} />
            </div>
          </div>
        </div>
      )}

      <style jsx global>{`
        .custom-scrollbar::-webkit-scrollbar {
          width: 6px;
        }
        .custom-scrollbar::-webkit-scrollbar-track {
          background: transparent;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb {
          background: #E2E8F0;
          border-radius: 10px;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover {
          background: #CBD5E1;
        }
        .scrollbar-thin::-webkit-scrollbar {
          width: 4px;
        }
        .scrollbar-thin::-webkit-scrollbar-track {
          background: transparent;
        }
        .scrollbar-thin::-webkit-scrollbar-thumb {
          background: #F1F5F9;
          border-radius: 10px;
        }
      `}</style>

      {/* Upload Modal */}
      {isUploadModalOpen && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center p-8 bg-slate-900/60 backdrop-blur-sm animate-in fade-in duration-300">
          <div className="bg-white w-full max-w-2xl rounded-3xl shadow-2xl flex flex-col overflow-hidden animate-in zoom-in-95 duration-300">
            <header className="px-8 py-6 border-b border-slate-100 flex items-center justify-between bg-slate-50/50">
              <div className="flex items-center gap-3">
                <div className="p-2.5 bg-blue-100 text-blue-600 rounded-xl">
                  <Upload className="w-5 h-5" />
                </div>
                <div>
                  <h2 className="text-xl font-bold text-slate-800">上传新文件</h2>
                  <p className="text-xs text-slate-500 mt-0.5">支持 PDF, Word, Excel, PPT, Markdown</p>
                </div>
              </div>
              <button onClick={() => setIsUploadModalOpen(false)} className="p-2 hover:bg-slate-200 rounded-xl transition-colors text-slate-400 hover:text-slate-800">
                <X className="w-5 h-5" />
              </button>
            </header>

            <div className="p-8 flex flex-col gap-6 bg-white min-h-[300px] max-h-[60vh] overflow-auto">
              {uploadQueue.length === 0 ? (
                <div className="flex-1 flex flex-col items-center justify-center border-2 border-dashed border-slate-200 rounded-2xl bg-slate-50 hover:bg-blue-50/50 hover:border-blue-300 transition-colors p-10 relative group">
                  <input type="file" multiple className="absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10" onChange={handleUploadSelect} />
                  <div className="w-16 h-16 bg-white shadow-sm rounded-full flex items-center justify-center mb-4 group-hover:scale-110 transition-transform">
                    <Upload className="w-8 h-8 text-blue-500" />
                  </div>
                  <h3 className="text-lg font-bold text-slate-700">点击或拖拽文件到此处</h3>
                  <p className="text-sm text-slate-400 mt-2 text-center max-w-xs">
                    上传的文件将进入“原始文件大厅”,稍后您可以发起批量摄入。
                  </p>
                </div>
              ) : (
                <div className="flex flex-col gap-3">
                  <div className="flex items-center justify-between mb-2">
                    <h3 className="text-sm font-bold text-slate-700">待上传列表 ({uploadQueue.length})</h3>
                    {!uploadQueue.some(q => q.status === 'uploading') && (
                      <label className="text-xs font-bold text-blue-600 bg-blue-50 px-3 py-1.5 rounded-lg cursor-pointer hover:bg-blue-100 transition-colors">
                        + 继续添加
                        <input type="file" multiple className="hidden" onChange={handleUploadSelect} />
                      </label>
                    )}
                  </div>
                  {uploadQueue.map((item, idx) => (
                    <div key={idx} className="flex items-center gap-4 p-4 bg-slate-50 border border-slate-100 rounded-xl">
                      <div className="p-2 bg-white rounded-lg shadow-sm border border-slate-100">
                        {getFileIcon(item.name.split('.').pop() || "")}
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center justify-between mb-1">
                          <span className="text-sm font-semibold text-slate-700 truncate">{item.name}</span>
                          <span className="text-xs font-medium text-slate-500">{(item.file.size / 1024 / 1024).toFixed(2)} MB</span>
                        </div>
                        {item.status === 'uploading' ? (
                          <div className="flex items-center gap-1.5 mt-1 text-xs font-bold text-blue-600">
                            <Loader2 className="w-3.5 h-3.5 animate-spin" /> 保存中...
                          </div>
                        ) : item.status === 'success' ? (
                          <div className="mt-1">
                            <div className="flex items-center gap-1.5 text-xs font-bold text-emerald-600">
                              <CheckCircle2 className="w-3.5 h-3.5" /> 已保存到文件库
                            </div>
                          </div>
                        ) : item.status === 'error' ? (
                          <div className="flex items-center gap-1.5 mt-1 text-xs font-bold text-red-600" title={item.errorMsg}>
                            <AlertCircle className="w-3.5 h-3.5" /> {item.errorMsg || "上传失败"}
                          </div>
                        ) : (
                          <div className="flex items-center gap-1.5 mt-1 text-xs font-bold text-slate-400">
                            等待上传...
                          </div>
                        )}
                      </div>
                      {item.status !== 'uploading' && (
                        <button onClick={() => setUploadQueue(prev => prev.filter((_, i) => i !== idx))} className="p-2 hover:bg-slate-200 rounded-lg text-slate-400 hover:text-slate-700 transition-colors" title="移除该项">
                          <X className="w-4 h-4" />
                        </button>
                      )}
                    </div>
                  ))}
                </div>
              )}
            </div>

            {uploadQueue.length > 0 && (
              <footer className="px-8 py-4 border-t border-slate-100 bg-slate-50 flex items-center justify-end gap-3">
                <button
                  onClick={() => { setUploadQueue([]); setIsUploadModalOpen(false); }}
                  disabled={uploadQueue.some(q => q.status === 'uploading')}
                  className="px-6 py-2.5 rounded-xl font-bold text-sm text-slate-600 hover:bg-slate-200 transition-colors disabled:opacity-50"
                >
                  取消
                </button>
                {uploadQueue.every(q => q.status === 'success' || q.status === 'error') ? (
                  <button
                    onClick={() => { setUploadQueue([]); setIsUploadModalOpen(false); fetchFiles(1, pageSize, searchQuery, false); }}
                    className="flex items-center gap-2 px-6 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl font-bold text-sm transition-colors shadow-lg shadow-emerald-500/30"
                  >
                    <CheckCircle2 className="w-4 h-4" /> 确认
                  </button>
                ) : (
                  <button
                    onClick={handleUploadConfirm}
                    disabled={uploadQueue.some(q => q.status === 'uploading')}
                    className="flex items-center gap-2 px-6 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-xl font-bold text-sm transition-colors shadow-lg shadow-blue-500/30 disabled:opacity-50"
                  >
                    {uploadQueue.some(q => q.status === 'uploading') ? (
                      <><Loader2 className="w-4 h-4 animate-spin" /> 上传中...</>
                    ) : (
                      <><Upload className="w-4 h-4" /> 确认上传</>
                    )}
                  </button>
                )}
              </footer>
            )}
          </div>
        </div>
      )}
    </>
  );
}