AffineEditor.vue 210 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 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845
<template>
  <div class="affine-editor-wrapper" :lang="locale">
    <div v-if="loading" class="editor-skeleton">
      <div class="skeleton-header"></div>
      <div class="skeleton-line title"></div>
      <div class="skeleton-line body" v-for="i in 10" :key="i"></div>
    </div>

    <!-- Toast 通知系统 -->
    <div class="affine-toast-container">
      <transition-group name="toast-fade">
        <div 
          v-for="toast in toasts" 
          :key="toast.id" 
          class="affine-toast" 
          :class="toast.type"
        >
          <i :class="getToastIcon(toast.type)"></i>
          <span>{{ toast.message }}</span>
        </div>
      </transition-group>
    </div>

    <!-- 命令面板 (Command Palette) -->
    <transition name="fade">
      <div v-if="showCommandPalette" class="command-palette-overlay" @click.self="showCommandPalette = false">
        <div class="command-palette">
          <div class="command-input-wrapper">
            <i class="fas fa-terminal"></i>
            <input 
              type="text" 
              v-model="commandSearch" 
              placeholder="输入命令或搜索功能..." 
              ref="commandInput"
              @keydown.down.prevent="selectNextCommand"
              @keydown.up.prevent="selectPrevCommand"
              @keydown.enter="executeCommand()"
              @keydown.esc="showCommandPalette = false"
            />
          </div>
          <div class="command-list" v-if="filteredCommands.length">
            <template v-for="(cmd, index) in filteredCommands" :key="cmd.id">
              <!-- 分组标题 -->
              <div 
                v-if="index === 0 || cmd.group !== filteredCommands[index - 1]?.group" 
                class="command-group-title"
              >
                {{ cmd.group }}
              </div>
              
              <div 
                class="command-item"
                :class="{ active: index === selectedCommandIndex }"
                @click="executeCommand(cmd)"
                @mouseenter="selectedCommandIndex = index"
              >
                <div class="command-icon-box">
                  <i :class="cmd.icon"></i>
                </div>
                <div class="command-info">
                  <span class="command-title">{{ cmd.title }}</span>
                  <span class="command-shortcut" v-if="cmd.shortcut">{{ cmd.shortcut }}</span>
                </div>
              </div>
            </template>
          </div>
          <div class="command-empty" v-else>
            没有找到匹配的命令
          </div>
        </div>
      </div>
    </transition>
    
    <!-- 顶部工具栏:优化 -->
    <div class="editor-toolbar" v-if="!loading">
      <div class="toolbar-left">
        <ModeSwitcher 
          v-model="editorMode" 
          @change="handleModeChange"
          style="margin-right: 12px;"
        />
        <div class="toolbar-divider" style="width: 1px; height: 16px; background: var(--el-border-color-lighter); margin-right: 12px;"></div>
        <div class="save-status-group">
          <i :class="hasChanges ? 'fas fa-cloud-upload-alt saving' : 'fas fa-cloud-check saved'"></i>
          <span class="file-status" :class="{ changed: hasChanges }">
            {{ hasChanges ? t('common.saveInProgress') : t('common.savedToCloud') }}
          </span>
        </div>
        <div class="doc-stats" v-if="wordCount > 0">
          <span class="stat-item">{{ stats.chars }} {{ t('common.chars') }}</span>
        </div>
      </div>
      <div class="toolbar-right">
        <button 
          class="toolbar-btn toc-toggle" 
          :class="{ active: showToc }"
          @click="toggleToc"
          :title="t('documentOutline.title')"
        >
          <i class="fas fa-list-ul"></i>
          <span>{{ t('documentOutline.outline') }}</span>
        </button>
        <el-dropdown trigger="click" @command="handleExportCommand">
          <button 
            class="toolbar-btn export-btn" 
            :title="t('common.export')"
          >
            <i class="fas fa-download"></i>
            <span>{{ t('common.export') }}</span>
          </button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="markdown">
                <i class="fab fa-markdown" style="margin-right: 8px; color: #1e6fff;"></i>
                Markdown (.md)
              </el-dropdown-item>
              <el-dropdown-item command="html">
                <i class="fas fa-code" style="margin-right: 8px; color: #ff9d00;"></i>
                HTML (.html)
              </el-dropdown-item>
              <el-dropdown-item command="png">
                <i class="fas fa-image" style="margin-right: 8px; color: #52c41a;"></i>
                {{ t('affine.export.imagePng') }} (.png)
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <div class="main-content-area" :class="{ 'with-references': props.showReferences }">
      <div 
        class="affine-editor-container blocksuite-editor" 
        ref="container" 
        theme="light"
        :style="props.showReferences ? { height: editorHeight } : {}"
        :class="{ 'is-loading': loading, 'loaded': !loading }"
      ></div>

      <!-- 参考文献管理区域 -->
      <div
        v-if="props.showReferences"
        class="reference-section"
        :style="{ height: referenceHeight }"
      >
        <!-- 拖动条 -->
        <div
          class="resize-handle"
          @mousedown="startResizing"
          @touchstart="startResizing"
        ></div>

        <!-- 参考文献工具栏 -->
        <div class="reference-toolbar">
          <div class="toolbar-left">
            <button
              class="toolbar-btn"
              :title="t('reference.addReference') || '添加参考文献'"
              @click="openImportDialog"
            >
              <i class="fas fa-file-alt"></i>
            </button>
          </div>

          <!-- 搜索框 -->
          <div class="ref-search-input-wrapper">
            <i class="fas fa-search search-icon"></i>
            <input
              v-model="searchQuery"
              type="text"
              :placeholder="t('reference.searchPlaceholder') || 'All Fields & Tags'"
              class="search-input"
            />
          </div>
        </div>

        <!-- 参考文献表格 -->
        <div class="reference-table-container">
          <!-- 加载状态 -->
          <div v-if="isLoadingReferences" class="reference-loading">
            <i class="fas fa-spinner fa-spin loading-icon"></i>
            <span class="loading-text">加载文献中...</span>
          </div>

          <!-- 空状态 -->
          <div v-else-if="references.length === 0" class="reference-empty">
            <i class="fas fa-book-open empty-icon"></i>
            <span class="empty-text">暂无参考文献</span>
            <el-button type="primary" size="small" @click="openImportDialog" style="margin-top: 10px;">
              立即导入
            </el-button>
          </div>

          <!-- 有数据时显示表格 -->
          <table v-else class="reference-table">
            <thead>
              <tr>
                <th width="60">{{ t('reference.serialNumber') }}</th>
                <th>{{ t('reference.name') }}</th>
                <th width="120">{{ t('reference.alias') }}</th>
                <th width="150">{{ t('reference.author') }}</th>
                <th width="80">{{ t('reference.year') }}</th>
                <th width="120">{{ t('reference.details') }}</th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="reference in filteredReferences"
                :key="reference.workId"
                :class="{ highlighted: selectedReferenceId === reference.workId }"
                :draggable="true"
                tabindex="0"
                @click="selectReference(reference.workId, $event)"
                @dragstart="handleReferenceDragStart($event, reference)"
                class="reference-row"
              >
                <td>{{ reference.serialNumber }}</td>
                <td class="title-cell">
                  <span class="title-text" :title="reference.title">{{ reference.title }}</span>
                </td>
                <td>
                  <!-- 别名编辑 -->
                  <div
                    v-if="editingReferenceId !== reference.workId"
                    class="alias-display"
                  >
                    <span class="alias-text">{{ reference.note || "-" }}</span>
                    <button
                      class="edit-alias-btn"
                      @click.stop="startEditAlias(reference)"
                      title="编辑别名"
                    >
                      <i class="fas fa-edit"></i>
                    </button>
                  </div>
                  <div v-else class="alias-edit" @click.stop>
                    <input
                      v-model="editingAlias"
                      type="text"
                      class="alias-input"
                      @keydown.enter="handleEnterKey(reference)"
                      @blur="handleBlur(reference)"
                    />
                  </div>
                </td>
                <td>{{ reference.authorsText }}</td>
                <td>{{ reference.publicationYear }}</td>
                <td class="details-cell">
                  <div class="detail-icons">
                    <el-popover
                      placement="top-end"
                      :width="400"
                      trigger="click"
                      popper-class="reference-detail-popover"
                    >
                      <template #reference>
                        <i
                          class="fas fa-file-alt icon-info"
                          style="color: #1890ff;"
                          title="查看详情"
                          @click.stop="viewReferenceDetail(reference)"
                        ></i>
                      </template>
                      <div
                        v-if="currentDetailReference?.workId === reference.workId"
                        class="reference-detail-content"
                      >
                        <div v-if="isLoadingDetail" class="detail-loading">
      <i class="fas fa-spinner fa-spin"></i>
                          <span>{{ t('common.loading') }}</span>
    </div>
                        <template v-else-if="currentDetailReference">
                          <div class="detail-item">
                            <div class="detail-label">{{ t('reference.detailLabels.title') }}</div>
                            <div class="detail-value">{{ currentDetailReference.title }}</div>
                          </div>
                          <div class="detail-item" v-if="currentDetailReference.abstractText">
                            <div class="detail-label">{{ t('reference.detailLabels.abstract') }}</div>
                            <div class="detail-value abstract">{{ currentDetailReference.abstractText }}</div>
                          </div>
                          <div class="detail-item" v-if="currentDetailReference.doi">
                            <div class="detail-label">{{ t('reference.detailLabels.doi') }}</div>
                            <div class="detail-value">{{ currentDetailReference.doi }}</div>
                          </div>
                        </template>
                      </div>
                    </el-popover>
                    <i
                      class="fas fa-comment-alt icon-copy"
                      style="color: #52c41a;"
                      :title="t('common.copyCitation')"
                      @click.stop="handleCopyReference(reference)"
                    ></i>
                    <i
                      class="fas fa-trash-alt icon-delete"
                      style="color: #f5222d;"
                      :title="t('common.delete')"
                      @click.stop="handleDeleteReference(reference)"
                    ></i>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      
      <!-- TOC 侧边栏 -->
      <transition name="slide">
        <div v-if="showToc" class="toc-sidebar" ref="tocContainer">
           <div class="toc-header">
             <span>{{ t('documentOutline.title') }}</span>
             <i class="fas fa-times close-toc" @click="showToc = false"></i>
           </div>
           <div class="toc-content" ref="tocContentRoot">
             <!-- 动态挂载 affine-outline-panel -->
           </div>
        </div>
      </transition>
    </div>

    <!-- 导入参考文献对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      :title="t('reference.importReference')"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="import-dialog-content">
        <div class="import-method-section">
          <el-radio-group v-model="importMethod" class="import-method-group">
            <el-radio label="title">{{ t('reference.importByTitle') }}</el-radio>
            <el-radio label="doi">{{ t('reference.importByDoi') }}</el-radio>
          </el-radio-group>
        </div>

        <div class="import-search-section">
          <el-input
            ref="importInputRef"
            v-model="importInput"
            :placeholder="importMethod === 'title' ? t('reference.enterLiteratureTitle') : t('reference.enterDoi')"
            clearable
            @keyup.enter="handleImportSearch"
          >
            <template #append>
              <el-button @click="handleImportSearch" :loading="isSearching">
                {{ t('common.search') }}
              </el-button>
            </template>
          </el-input>
        </div>

        <div v-if="searchResults.length > 0" class="search-results-section">
          <div class="results-list">
            <div
              v-for="result in searchResults"
              :key="result.workId"
              class="result-item"
            >
              <div class="result-content">
                <div class="result-title">{{ result.title }}</div>
                <div class="result-meta">
                  <span>{{ result.authorsText }}</span>
                  <span v-if="result.publicationYear">({{ result.publicationYear }})</span>
                </div>
              </div>
              <el-button 
                type="primary" 
                size="small" 
                @click="handleAddReference(result)"
                :loading="result.importing"
              >
                添加
              </el-button>
            </div>
          </div>
        </div>
        <div v-else-if="hasSearched && !isSearching" class="no-results">
          没有找到匹配的文献
        </div>
      </div>
    </el-dialog>

    <!-- 查找替换面板 -->
    <transition name="fade">
      <div v-if="showSearch" class="search-panel">
        <div class="search-input-wrapper">
          <i class="fas fa-search"></i>
          <input 
            type="text" 
            v-model="searchText" 
            placeholder="在文档中查找..." 
            ref="searchInput"
            @keydown.enter="findNext"
            @keydown.esc="showSearch = false"
          />
          <span class="search-results-count" v-if="searchText">
            {{ searchCurrent }}/{{ searchTotal }}
          </span>
        </div>
        <div class="search-controls">
          <button @click="findPrev" :disabled="!searchTotal"><i class="fas fa-chevron-up"></i></button>
          <button @click="findNext" :disabled="!searchTotal"><i class="fas fa-chevron-down"></i></button>
          <button @click="showSearch = false" class="close-search"><i class="fas fa-times"></i></button>
        </div>
      </div>
    </transition>

    <!-- 回到顶部 -->
    <transition name="fade">
      <button 
        class="back-to-top" 
        v-if="showBackToTop" 
        @click="scrollToTop"
        title="回到顶部"
      >
        <i class="fas fa-chevron-up"></i>
      </button>
    </transition>

    <!-- 快捷键帮助面板 -->
    <transition name="fade">
      <div v-if="showHelp" class="help-overlay" @click.self="showHelp = false">
        <div class="help-modal">
          <div class="help-header">
            <h3>快捷键与功能说明</h3>
            <i class="fas fa-times" @click="showHelp = false"></i>
          </div>
          <div class="help-body">
            <div class="help-section">
              <h4>基础操作</h4>
              <ul>
                <li><kbd>/</kbd> 唤起斜杠菜单</li>
                <li><kbd>Ctrl</kbd> + <kbd>S</kbd> 手动保存</li>
                <li><kbd>Ctrl</kbd> + <kbd>F</kbd> 查找内容</li>
              </ul>
            </div>
            <div class="help-section">
              <h4>区块快捷键</h4>
              <ul>
                <li><kbd>#</kbd> 一级标题</li>
                <li><kbd>##</kbd> 二级标题</li>
                <li><kbd>1.</kbd> 有序列表</li>
                <li><kbd>-</kbd> 无序列表</li>
                <li><kbd>> </kbd> 引用区块</li>
                <li><kbd>```</kbd> 代码块</li>
              </ul>
            </div>
            <div class="help-section">
              <h4>{{ t('documentOutline.outline') }}</h4>
              <p>{{ t('affine.askAi.modes.pageHint') }} / {{ t('affine.askAi.modes.edgelessHint') }}</p>
            </div>
          </div>
        </div>
      </div>
    </transition>

    <!-- New Ask AI Menu Popup (High Fidelity Interaction) -->
    <Teleport to="body">
      <AskAIPanel 
        :visible="showAskAIMenu" 
        :position="askAIMenuPosition"
        :state="aiPanelState"
        :answer="aiResult"
        @close="handleAiClose"
        @action="handleAskAIMenuAction"
        @stop="stopAIGeneration"
        @retry="handleAiRetry"
        @replace="handleAiReplace"
        @insert="handleAiInsert"
      />
    </Teleport>

    <!-- 引用标记切换菜单 (Citation Switcher Menu) -->
    <Teleport to="body">
      <div
        v-if="showCitationMenu"
        class="citation-menu-wrapper"
        :style="{
          top: citationMenuPosition.y + 'px',
          left: citationMenuPosition.x + 'px',
        }"
      >
        <div ref="citationMenuRef" class="citation-menu">
          <div class="citation-menu-header">
            <span class="header-title">{{ t("reference.selectReference") }}</span>
            <div class="header-search">
              <i class="fas fa-search search-icon"></i>
              <input
                v-model="citationMenuSearch"
                type="text"
                :placeholder="t('reference.searchReferences')"
                class="search-input"
                @click.stop
              />
            </div>
          </div>
          <div class="citation-menu-list">
            <div
              v-for="reference in filteredCitationMenuReferences"
              :key="reference.workId"
              class="citation-menu-item"
              @mousedown.stop="replaceCitation(reference)"
            >
              <span class="menu-item-note">{{ reference.note || reference.title }}</span>
              <span class="menu-item-meta">{{ reference.authorsText }} ({{ reference.publicationYear }})</span>
            </div>
            <div
              v-if="filteredCitationMenuReferences.length === 0 && references.length > 0"
              class="citation-menu-empty"
            >
              {{ t("reference.noMatchingReferences") }}
            </div>
            <div v-if="references.length === 0" class="citation-menu-empty">
              {{ t("reference.noReferences") }}
            </div>
          </div>
        </div>
      </div>
    </Teleport>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { useI18n } from "vue-i18n";
import { useAppStore } from "@/stores/app";
import { Text as BlockSuiteText } from '@blocksuite/store';
// @ts-ignore
import { TestWorkspace } from '@blocksuite/store/test';
import { BlockStdScope, TextSelection, BlockSelection } from '@blocksuite/affine/std';
// @ts-ignore
import { getInternalViewExtensions } from '@blocksuite/affine/extensions/view';
// @ts-ignore
import { getInternalStoreExtensions } from '@blocksuite/affine/extensions/store';
// @ts-ignore
import { ViewExtensionManager, StoreExtensionManager } from '@blocksuite/affine/ext-loader';
import { MarkdownAdapter, HtmlAdapter } from '@blocksuite/affine/shared/adapters';
// @ts-ignore
import { BlockMarkdownAdapterMatcherIdentifier, HtmlAdapterFactoryIdentifier } from '@blocksuite/affine/shared/adapters';
// @ts-ignore
import { 
  ViewportElementProvider, 
  LinkPreviewServiceIdentifier, 
  ToolbarRegistryIdentifier, 
  ActionPlacement
} from '@blocksuite/affine/shared/services';
// @ts-ignore
import { AiIcon } from '@blocksuite/icons/lit';
// @ts-ignore
import { html } from 'lit';
// @ts-ignore
import { getSelectedModelsCommand } from '@blocksuite/affine/shared/commands';
// @ts-ignore
import '@blocksuite/affine/effects';
// @ts-ignore
import '@blocksuite/affine-components';

import ModeSwitcher from '@/components/common/ModeSwitcher.vue';

// UI Components
import { 
  ElMessageBox, 
  ElDialog, 
  ElRadioGroup, 
  ElRadio, 
  ElInput, 
  ElButton,
  ElPopover,
// @ts-ignore
} from "element-plus";

// API & Utils
import * as filesApi from "@/api/files";
import { apiGetDraftById, apiUpdateDraft } from "@/api/drafts";
import {
  getFileReferences,
  searchReferencesByTitle,
  searchReferencesByDoi,
  addReferenceToFile,
  getReferenceDetail,
  deleteReferenceFromFile,
  updateReferenceNote,
  getFormatCitation,
} from "@/api/references";
import type {
  ReferenceItem,
  ImportSearchResultItem,
  ReferenceDetail,
} from "@/api/references";
import { fileCache } from "@/utils/fileCache";
import { preprocessMathContent } from "@/utils/renderMarkdown";
import { triggerNewbieTask } from "@/utils/newbieTask";

// CSS
import '@blocksuite/affine/shared/styles';

import AskAIPanel from './AskAIPanel.vue';
import { useChatApiStore } from "@/stores/chatApi";

interface Props {
  fileId: string | number;
  fileName: string;
  preloadContent?: string;
  readonly?: boolean;
  isChatAnswer?: boolean;
  folderId?: string | number;
  showReferences?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  preloadContent: "",
  readonly: false,
  isChatAnswer: false,
  showReferences: false,
});

const emit = defineEmits<{
  (e: 'content-change', data: { text: string; html: string; hasChanges: boolean }): void;
  (e: 'file-saved', data: { fileId: string | number; fileName: string; content: string; isAutoSave: boolean }): void;
  (e: 'request-show-references'): void;
}>();

const { t, locale } = useI18n();
import { watch } from 'vue';

// 监听语言变化,同步更新 BlockSuite 内部语言
watch(locale, (newLocale) => {
  if (stdScope) {
    try {
      // @ts-ignore
      const i18n = stdScope.get('affine:i18n') as any;
      if (i18n && typeof i18n.setLocale === 'function') {
        const bsLocale = newLocale === 'zh-CN' ? 'zh' : 'en';
        i18n.setLocale(bsLocale);
        console.log('[Affine] Watcher: Set BlockSuite locale to:', bsLocale);
      }
    } catch (e) {
      if (!(e instanceof Error && e.message.includes('not a service identifier'))) {
        console.warn('[Affine] Watcher: Failed to set internal locale:', e);
      }
    }
  }
}, { immediate: false });

const container = ref<HTMLElement | null>(null);
let store: any = null;
let stdScope: any = null;
let editorHost: any = null;
const tocContentRoot = ref<HTMLElement | null>(null);
const loading = ref(true);
const isSavedToKnowledge = ref(false);
const hasChanges = ref(false);
const isInitialized = ref(false);
const isProgrammaticChange = ref(false); // 新增:标记是否为程序化修改,用于暂停引用渲染
const showToc = ref(false);
const toggleToc = () => {
  showToc.value = !showToc.value;
};
const editorMode = ref<'page' | 'edgeless'>('page');
const wordCount = ref(0);
const isPreviewMode = ref(false);
const isFullScreen = ref(false);
const showHelp = ref(false);
const showAskAIMenu = ref(false); // Popup Menu (new)
const askAIMenuPosition = ref({ top: 0, left: 0 });
const aiPanelState = ref<'input' | 'generating' | 'finished' | 'error'>('input');
const aiResult = ref('');
const currentAiAction = ref('');
let currentAiInterval: any = null;
let lastSelectionRange: Range | null = null; // 记录最后的有效选区
let lastTriggerRect: DOMRect | null = null; // 记录触发按钮的位置
let lastBlockSuiteSelection: any = null; // 记录 BlockSuite 选区状态

// 更新 AI 面板位置的函数 (参考源码的 FloatingUI 逻辑)
const updateAiPanelPosition = () => {
  if (!showAskAIMenu.value) return;

  let rect: DOMRect | null = null;

  // 1. 尝试从 BlockSuite 的 Selection 获取位置 (最准确)
  try {
    if (stdScope && stdScope.host) {
      // @ts-ignore
      let textSelection = stdScope.selection.find(TextSelection);
      // 如果实时选区为空,使用备份
      if ((!textSelection || textSelection.collapsed) && lastBlockSuiteSelection) {
        textSelection = lastBlockSuiteSelection;
      }

      if (textSelection && !textSelection.collapsed) {
        const host = stdScope.host;
        // 获取所有选中的 Block 视图
        const rects: DOMRect[] = [];
        textSelection.selectedModels.forEach((model: any) => {
          const view = host.view.getBlock(model.id);
          if (view) {
            // 获取块内选中的矩形区域
            // @ts-ignore
            const blockRects = view.getSelectionRects?.(textSelection);
            if (blockRects && blockRects.length > 0) {
              rects.push(...blockRects);
            }
          }
        });

        if (rects.length > 0) {
          let minTop = Infinity, maxBottom = -Infinity, minLeft = Infinity, maxRight = -Infinity;
          rects.forEach((r: any) => {
            minTop = Math.min(minTop, r.top);
            maxBottom = Math.max(maxBottom, r.bottom);
            minLeft = Math.min(minLeft, r.left);
            maxRight = Math.max(maxRight, r.right);
          });
          rect = {
            top: minTop,
            bottom: maxBottom,
            left: minLeft,
            right: maxRight,
            width: maxRight - minLeft,
            height: maxBottom - minTop,
            x: minLeft,
            y: minTop,
            toJSON: () => {}
          } as DOMRect;
        }
      }
    }
  } catch (e) {
    console.warn('[Affine] Failed to get BlockSuite selection rect:', e);
  }

  // 2. 兜底使用原生选区 (对 Shadow DOM 兼容性可能较差)
  if (!rect || rect.top === 0) {
    const selection = window.getSelection();
    if (selection && selection.rangeCount > 0) {
      const range = selection.getRangeAt(0);
      if (!range.collapsed) {
        rect = range.getBoundingClientRect();
      }
    }
  }

  // 3. 再次兜底使用最后的备份
  if (!rect || rect.top === 0) {
    if (lastSelectionRange) {
      rect = lastSelectionRange.getBoundingClientRect();
    }
  }

  // 4. 最后兜底使用触发按钮位置
  if (!rect || (rect.top === 0 && rect.bottom === 0 && rect.left === 0)) {
    rect = lastTriggerRect;
  }

  if (rect && (rect.top !== 0 || rect.bottom !== 0)) {
    const panelWidth = 400;
    // 动态预估高度,输入态较矮,结果态较高
    const panelHeight = aiPanelState.value === 'input' ? 320 : 480; 
    
    // 计算相对于视口的绝对位置 (AskAIPanel 现在 Teleport 到 body)
    let left = rect.left + (rect.width / 2) - (panelWidth / 2);
    let top = rect.bottom + 12;

    // 边界检查
    left = Math.max(16, Math.min(left, window.innerWidth - panelWidth - 16));
    
    // 空间不足向上弹出
    if (top + panelHeight > window.innerHeight - 20 && rect.top > panelHeight + 20) {
      top = rect.top - panelHeight - 12;
    }

    // 视野外处理
    let isHidden = false;
    if (container.value) {
      const containerRect = container.value.getBoundingClientRect();
      // 检查选区是否在编辑器视口之外
      if (rect.bottom < containerRect.top || rect.top > containerRect.bottom) {
        isHidden = true;
      }
    }

    if (isHidden && aiPanelState.value === 'input') {
      // 仅在输入状态下,且不可见时隐藏
      askAIMenuPosition.value = { top: -9999, left: -9999 };
    } else {
      askAIMenuPosition.value = { top: top, left: left };
    }
  }
};

const stopAIGeneration = () => {
  if (currentAiInterval) {
    clearInterval(currentAiInterval);
    currentAiInterval = null;
  }
  // 关键修复:停止生成并立即关闭弹窗
  handleAiClose();
};

const chatStore = useChatApiStore();

const aiLastPromptInfo = ref<{ text: string, prompt: string, action: string } | null>(null);

const handleAskAIMenuAction = async (action: string) => {
  console.log('[Affine] AI Action triggered:', action);
  currentAiAction.value = action;
  
  // 1. 获取选中内容 (优先使用 BlockSuite 原生 Selection)
  let selectedText = '';
  // 如果是重试,且我们有缓存,则使用缓存的文本
  if (action === 'retry' && aiLastPromptInfo.value) {
    selectedText = aiLastPromptInfo.value.text;
    action = aiLastPromptInfo.value.action;
  } else {
    try {
      if (stdScope) {
        // @ts-ignore
        const [_, ctx] = stdScope.command.exec(getSelectedModelsCommand, {
          types: ['block', 'text'],
        });
        if (ctx.selectedModels && ctx.selectedModels.length > 0) {
          selectedText = ctx.selectedModels
            .map((m: any) => m.text?.toString() || '')
            .filter(Boolean)
            .join('\n');
        }
      }
    } catch (e) {
      console.warn('[Affine] Failed to get BlockSuite selection, falling back to window.getSelection', e);
    }
    
    if (!selectedText) {
      const selection = window.getSelection();
      selectedText = selection ? selection.toString().trim() : '';
    }
  }

  // 构建 Prompt
  let prompt = '';
  if (action.startsWith('submit:')) {
    const userInput = action.substring(7);
    prompt = selectedText 
      ? `${t('affine.askAi.prompts.suggestBasedOn')}\n"${selectedText}"\n\n${t('affine.askAi.prompts.executeInstruction')}${userInput}`
      : userInput;
  } else if (action.includes(':')) {
    // 处理带参数的操作 (如 translate:english, change-tone:professional)
    const parts = action.split(':');
    const baseAction = parts[0];
    const param = parts[1];
    
    if (!baseAction || !param) return;

    const basePrompts: Record<string, string> = {
      'translate': t('affine.askAi.items.translate'),
      'change-tone': t('affine.askAi.items.changeTone')
    };
    
    // 获取参数的国际化文本 (如 english -> 英语)
    let localizedParam = param;
    if (baseAction === 'translate') {
      localizedParam = t(`affine.askAi.languages.${param}`);
    } else if (baseAction === 'change-tone') {
      localizedParam = t(`affine.askAi.tones.${param}`);
    }

    const actionName = basePrompts[baseAction] || baseAction;
    prompt = `${actionName} "${localizedParam}":\n\n"${selectedText}"`;
  } else {
    const prompts: Record<string, string> = {
      'fix-spelling': t('affine.askAi.items.fixSpelling') + ':',
      'fix-grammar': t('affine.askAi.items.fixGrammar') + ':',
      'explain': t('affine.askAi.items.explain') + ':',
      'improve': t('affine.askAi.items.improve') + ':',
      'simplify': t('affine.askAi.items.simplify') + ':',
      'longer': t('affine.askAi.items.longer') + ':',
      'shorter': t('affine.askAi.items.shorter') + ':',
      'continue': t('affine.askAi.items.continue') + ':',
      'summarize': t('affine.askAi.items.summarize') + ':',
      'write-article': t('affine.askAi.items.writeArticle') + ':',
      'brainstorm': t('affine.askAi.items.brainstorm') + ':',
      'translate': t('affine.askAi.items.translate') + ':',
      'find-action-items': t('affine.askAi.items.findActionItems') + ':',
      'write-outline': t('affine.askAi.items.writeOutline') + ':',
      'write-social-media-post': t('affine.askAi.items.writeSocialMediaPost') + ':',
      'write-poem': t('affine.askAi.items.writePoem') + ':',
      'write-essay': t('affine.askAi.items.writeEssay') + ':',
    };
    const basePrompt = prompts[action] || 'AI: ';
    const noSelectionAllowed = [
      'write-article', 'brainstorm', 'write-outline', 
      'write-social-media-post', 'write-poem', 'write-essay'
    ];
    if (!selectedText && !noSelectionAllowed.includes(action)) {
      addToast(t('affine.askAi.toast.pleaseSelectText'), 'warning');
      return;
    }
    prompt = selectedText ? `${basePrompt}\n\n"${selectedText}"` : basePrompt;
  }

  // 缓存当前请求信息用于重试
  aiLastPromptInfo.value = { text: selectedText, prompt, action };

  // 2. 准备状态
  aiPanelState.value = 'generating';
  aiResult.value = '';

  try {
    // 3. 调用豆包模型
    const result = await (chatStore as any).sendMessage({
      sessionId: (chatStore as any).currentSessionId,
      question: prompt,
      provider: 'doubao'
    });

    if (result.success && result.data?.questionId) {
      const qid = result.data.questionId;
      
      if (currentAiInterval) clearInterval(currentAiInterval);
      
      currentAiInterval = setInterval(() => {
        const msg = chatStore.messages.find(m => m.questionId === qid);
        if (msg && msg.answers && msg.answers.length > 0) {
          const answer = msg.answers[0];
          if (answer) {
            aiResult.value = answer.answerContent || '';
            
            if (answer.status === 'completed') {
              clearInterval(currentAiInterval);
              currentAiInterval = null;
              aiPanelState.value = 'finished';
            } else if (answer.status === 'error') {
              clearInterval(currentAiInterval);
              currentAiInterval = null;
              aiPanelState.value = 'error';
              addToast(t('affine.askAi.status.error'), 'error');
            }
          }
        }
      }, 100);
    } else {
      throw new Error(result.error || t('affine.askAi.status.error'));
    }
  } catch (err: any) {
    console.error('[Affine] AI Action failed:', err);
    aiPanelState.value = 'error';
    addToast(`${t('affine.askAi.status.error')}: ${err.message}`, 'error');
  }
};

// 处理来自 AskAIPanel 的具体操作
const handleAiReplace = async (content: string) => {
  await replaceSelectionWithText(content);
  addToast(t('affine.askAi.toast.replaced'), 'success');
  handleAiClose();
  
  // 显式触发保存 (视为手动保存,确保状态更新)
  if (saveTimer) clearTimeout(saveTimer);
  setTimeout(() => {
    saveDocument(false).catch(err => console.error('[Affine] AI Auto-save failed:', err));
  }, 500);
};

const handleAiInsert = async (content: string) => {
  await insertBlockBelow(content);
  addToast(t('affine.askAi.toast.inserted'), 'success');
  handleAiClose();
  
  // 显式触发保存
  if (saveTimer) clearTimeout(saveTimer);
  setTimeout(() => {
    saveDocument(false).catch(err => console.error('[Affine] AI Auto-save failed:', err));
  }, 500);
};

const handleAiClose = () => {
  // 关闭面板时,如果正在生成,必须停止并清理资源
  if (currentAiInterval) {
    clearInterval(currentAiInterval);
    currentAiInterval = null;
  }
  
  showAskAIMenu.value = false;
  lastSelectionRange = null; 
  lastTriggerRect = null;
  lastBlockSuiteSelection = null; 
};

const handleAiRetry = () => {
  handleAskAIMenuAction('retry');
};

// 在当前选中块下方插入新块 (支持 Markdown 解析)
const insertBlockBelow = async (text: string) => {
  console.log('[Affine] insertBlockBelow triggered, text length:', text.length);
  if (!editorHost || !stdScope) {
    console.error('[Affine] insertBlockBelow: editorHost or stdScope not found');
    return;
  }

  isProgrammaticChange.value = true; // 锁定引用渲染

  try {
    let textSelection = stdScope.selection.find(TextSelection);
    // 使用备份的 BlockSuite 选区
    if ((!textSelection || textSelection.collapsed) && lastBlockSuiteSelection) {
      console.log('[Affine] Using cached lastBlockSuiteSelection for insertion');
      textSelection = lastBlockSuiteSelection;
    }

    if (textSelection) {
      // @ts-ignore
      const from = textSelection.from;
      const blockId = from.blockId;
      const currentStore = stdScope.store;
      const parentBlock = currentStore.getBlock(blockId);
      
      if (parentBlock) {
        const parentModel = parentBlock.model;
        const containerModel = parentBlock.model.parent;
        
        if (containerModel) {
          const index = containerModel.children.indexOf(parentModel);
          console.log('[Affine] Importing AI content blocks at index:', index + 1);
          
          // 使用 MarkdownAdapter 解析 AI 返回的内容 (可能包含多行、标题、列表等)
          const transformer = currentStore.getTransformer();
          const adapter = new MarkdownAdapter(transformer, currentStore.provider);
          const snapshot = await adapter.toDocSnapshot({ file: text });
          
          if (snapshot && snapshot.blocks) {
            // 使用辅助函数提取实际内容块
            const blocksToInsert = extractContentBlocks(snapshot);
            
            if (blocksToInsert.length > 0) {
              let currentInsertIndex = index + 1;
              for (const child of blocksToInsert) {
                try {
                  await transformer.snapshotToBlock(child, currentStore, containerModel.id, currentInsertIndex);
                  currentInsertIndex++;
                } catch (err) {
                  console.error('[Affine] Error when transforming snapshot to block:', err);
                }
              }
            } else {
              // 兜底:如果没有解析出块,作为普通段落插入
              currentStore.transact(() => {
                currentStore.addBlock('affine:paragraph', { text: new BlockSuiteText(text) }, containerModel.id, index + 1);
              });
            }
          } else {
            // 兜底:解析失败
            currentStore.transact(() => {
              currentStore.addBlock('affine:paragraph', { text: new BlockSuiteText(text) }, containerModel.id, index + 1);
            });
          }
          
          console.log('[Affine] BlockSuite multi-block insertion completed');
          
          if (editorHost && editorHost.requestUpdate) {
            editorHost.requestUpdate();
          }

          hasChanges.value = true;
          scheduleAutoSave(); 
          
          setTimeout(() => { 
            isProgrammaticChange.value = false; 
            if (editorHost && editorHost.requestUpdate) editorHost.requestUpdate();
          }, 300);
          return;
        }
      }
    }
  } catch (e) {
    console.error('[Affine] BlockSuite multi-block insert failed:', e);
  }

  // 兜底:DOM 操作
  console.log('[Affine] Fallback to DOM insertion');
  insertTextAtCursor('\n' + text + '\n');
  setTimeout(() => { isProgrammaticChange.value = false; }, 300);
};

// 在选区位置替换为新内容 (支持 Markdown 解析)
const replaceSelectionWithText = async (text: string) => {
  console.log('[Affine] replaceSelectionWithText async triggered, text length:', text.length);
  if (!editorHost) {
    console.error('[Affine] editorHost not found');
    return;
  }
  
  let textSelection: any = null;
  isProgrammaticChange.value = true; // 锁定引用渲染

  try {
    if (stdScope) {
      // @ts-ignore
      textSelection = stdScope.selection.find(TextSelection);
    }

    // 使用备份的 BlockSuite 选区
    if ((!textSelection || (textSelection.to === null && (!textSelection.from || !textSelection.from.length))) && lastBlockSuiteSelection) {
      console.log('[Affine] Using cached lastBlockSuiteSelection:', lastBlockSuiteSelection);
      textSelection = lastBlockSuiteSelection;
    }

    if (textSelection) {
      // @ts-ignore
      const from = textSelection.from;
      // @ts-ignore
      const to = textSelection.to;
      const currentStore = stdScope ? stdScope.store : store;
      const isSingleBlock = !to || (to.blockId === from.blockId);

      if (from && isSingleBlock) {
        const blockId = from.blockId;
        const block = currentStore.getBlock(blockId);
        const model = block?.model;
        
        if (model && model.text) {
          try {
            const currentText = model.text.toString();
            const fromIndex = Math.min(from.index, currentText.length);
            let selectionLength = 0;
            if (to) {
               selectionLength = to.index - from.index;
            } else if (typeof from.length === 'number') {
               selectionLength = from.length;
            }
            if (selectionLength < 0) selectionLength = 0;
            const toIndex = Math.min(fromIndex + selectionLength, currentText.length);
            
            // 核心修复逻辑:
            // 使用 MarkdownAdapter 解析 AI 内容,并合并到当前文档中
            const transformer = currentStore.getTransformer();
            const adapter = new MarkdownAdapter(transformer, currentStore.provider);
            
            // 构造完整的 Markdown 字符串进行解析
            const fullMarkdown = currentText.slice(0, fromIndex) + text + currentText.slice(toIndex);
            const snapshot = await adapter.toDocSnapshot({ file: fullMarkdown });
            
            if (snapshot && snapshot.blocks) {
              const blocksToInsert = extractContentBlocks(snapshot);
              
              if (blocksToInsert.length === 1 && blocksToInsert[0].flavour === 'affine:paragraph') {
                // 情况 A: 结果仍然是单段落,直接更新内容
                const newTextProp = blocksToInsert[0].props?.text;
                console.log('[Affine] Single block replacement (paragraph)');
                currentStore.transact(() => {
                  currentStore.updateBlock(model, {
                    text: newTextProp instanceof BlockSuiteText ? newTextProp : new BlockSuiteText(text)
                  });
                });
              } else if (blocksToInsert.length > 0) {
                // 情况 B: 结果变成了多块,执行块拆分
                const containerModel = model.parent;
                if (containerModel) {
                  const currentIndex = containerModel.children.indexOf(model);
                  console.log('[Affine] Multi-block replacement starting at index:', currentIndex);
                  
                  // 注意:snapshotToBlock 内部会创建新块。
                  // 我们先删除旧块,然后在原位置逐个插入新块。
                  currentStore.transact(() => {
                    currentStore.deleteBlock(model);
                  });
                  
                  let insertPos = currentIndex;
                  for (const child of blocksToInsert) {
                    try {
                      console.log('[Affine] Replacing with block:', child.flavour, 'at pos:', insertPos);
                      await transformer.snapshotToBlock(child, currentStore, containerModel.id, insertPos++);
                    } catch (e) {
                      console.error('[Affine] Error when transforming replace snapshot to block:', e);
                    }
                  }
                }
              }
            } else {
              // 兜底:纯文本更新
              currentStore.transact(() => {
                currentStore.updateBlock(model, { text: new BlockSuiteText(fullMarkdown) });
              });
            }

            console.log('[Affine] BlockSuite replacement completed');
            if (editorHost && editorHost.requestUpdate) editorHost.requestUpdate();

            setTimeout(() => {
               try {
                 if (stdScope) {
                   const updatedBlock = currentStore.getBlock(blockId);
                   const finalLen = updatedBlock?.model.text?.length || 0;
                   const newIndex = Math.min(from.index + text.length, finalLen);
                   // @ts-ignore
                   const sel = stdScope.selection.create(TextSelection, {
                     from: { blockId: blockId, index: newIndex, length: 0 },
                     to: null
                   });
                   stdScope.selection.setGroup('note', [sel]);
                   if (editorHost.requestUpdate) editorHost.requestUpdate();
                 }
               } finally {
                 setTimeout(() => { isProgrammaticChange.value = false; }, 300);
               }
            }, 100);

            hasChanges.value = true;
            scheduleAutoSave(); 
            return;
          } catch (err) {
            console.error('[Affine] Transaction failed:', err);
            isProgrammaticChange.value = false;
          }
        }
      }
    }
  } catch (e) {
    console.error('[Affine] BlockSuite replacement failed:', e);
    isProgrammaticChange.value = false;
  }

  // 2. 兜底:使用原生 DOM 操作
  console.log('[Affine] Fallback to DOM replacement');
  
  let selection = window.getSelection();
  let range: Range | null = null;

  // 优先使用当前有效选区,否则使用备份选区
  if (selection && selection.rangeCount > 0 && !selection.getRangeAt(0).collapsed) {
    console.log('[Affine] Using current window selection');
    range = selection.getRangeAt(0);
  } else if (lastSelectionRange) {
    console.log('[Affine] Using cached lastSelectionRange');
    range = lastSelectionRange;
  }

  if (range) {
    console.log('[Affine] Range found:', range);
    try {
      // 重新建立选区
      if (selection) {
        selection.removeAllRanges();
        selection.addRange(range);
      }
      
      console.log('[Affine] Executing DOM deleteContents');
      range.deleteContents();
      
      console.log('[Affine] Executing DOM insertNode');
      const textNode = document.createTextNode(text);
      range.insertNode(textNode);
      
      // 关键修复:DOM 操作后尝试同步 Store 模型,如果失败则静默
      // 我们刚刚手动修改了 DOM,这破坏了 Lit 的状态一致性
      // 尝试通过空事务触发 BlockSuite 的重新同步
      try {
        if (textSelection && textSelection.from) {
           const blockId = textSelection.from.blockId;
           store.transact(() => {
             // 执行一个无害的操作来触发更新
             const block = store.getBlock(blockId);
             if (block && block.model.text) {
               // 只是为了触发 update,不做实际修改
               // block.model.text.insert(0, ''); 
             }
           });
        }
      } catch (e) {}
      
      hasChanges.value = true;
      scheduleAutoSave(); 
      nextTick(() => renderCitationsInAffine());
      console.log('[Affine] DOM replacement success');
    } catch (domError) {
      console.error('[Affine] DOM replacement failed:', domError);
      // 最后的救命稻草:追加到 note 结尾
      insertTextAtCursor('\n' + text);
    }
  } else {
     console.warn('[Affine] No DOM range available, appending to cursor');
     // 如果连备份选区都没有,只能追加
     insertTextAtCursor('\n' + text);
  }
};

const appStore = useAppStore();

// 辅助函数:从 DocSnapshot 中提取实际可用的内容块 (过滤掉 page/note/surface 等结构块)
const extractContentBlocks = (snapshot: any) => {
  if (!snapshot || !snapshot.blocks) return [];
  
  console.log('[Affine] Extracting content blocks from snapshot...');
  const contentBlocks: any[] = [];
  
  // 只允许插入到 affine:note 中的业务块 flavour
  const contentFlavours = [
    'affine:paragraph', 'affine:heading', 'affine:list', 'affine:code', 
    'affine:image', 'affine:attachment', 'affine:divider', 'affine:equation',
    'affine:database', 'affine:canvas'
  ];

  const traverse = (node: any) => {
    if (!node) return;
    
    if (contentFlavours.includes(node.flavour)) {
      // 找到了业务块,克隆并清理它,防止携带非法的子节点
      const cleanNode = { ...node };
      // 业务块通常不应该包含 surface 或 note 这种结构块作为子节点
      if (cleanNode.children) {
        cleanNode.children = cleanNode.children.filter((c: any) => contentFlavours.includes(c.flavour));
      }
      contentBlocks.push(cleanNode);
    } else if (node.children) {
      // 结构块(如 page, note, surface),我们跳过它们本身,继续找它们的子节点
      for (const child of node.children) {
        traverse(child);
      }
    }
  };
  
  traverse(snapshot.blocks);
  console.log('[Affine] Extracted content blocks:', contentBlocks.map(b => b.flavour));
  return contentBlocks;
};

// 参考文献相关状态
const editorHeight = ref("70%");
const referenceHeight = ref("30%");
const searchQuery = ref("");
const editingReferenceId = ref<number | null>(null); // 记录正在编辑的参考文献ID
const editingAlias = ref(""); // 编辑中的别名内容
const selectedReferenceId = ref<number | null>(null); // 记录选中的参考文献ID
const isHandlingEnterKey = ref(false); // 标记是否正在处理回车键
const currentDetailReference = ref<ReferenceDetail | null>(null); // 当前查看详情的参考文献
const isLoadingDetail = ref(false); // 是否正在加载详情

// 导入参考文献对话框相关状态
const importDialogVisible = ref(false); // 对话框显示状态
const importMethod = ref<"title" | "doi">("title"); // 导入方式:title 或 doi
const importInput = ref(""); // 输入内容
const importInputRef = ref<InstanceType<typeof ElInput>>(); // 输入框引用
const isSearching = ref(false); // 搜索中状态
const hasSearched = ref(false); // 是否已经搜索过
const searchResults = ref<any[]>([]); // 搜索结果列表

// 导出相关状态
const exportOutputFormat = ref<"html" | "markdown" | "png">("markdown"); // 输出格式
const exportCitationFormat = ref<"apa" | "ieee">("apa"); // 引用格式
const isExporting = ref(false); // 是否正在导出

// 参考文献列表相关状态
const references = ref<any[]>([]); // 参考文献列表
const isLoadingReferences = ref(false); // 是否正在加载参考文献
const referencesTotal = ref(0); // 参考文献总数

// 拖拽调整高度相关状态
const isResizing = ref(false);
const startY = ref(0);
const startEditorHeight = ref(0);
const startReferenceHeight = ref(0);

// 过滤后的参考文献(用于参考文献表格)
const filteredReferences = computed(() => {
  if (!searchQuery.value.trim()) {
    return references.value;
  }

  const query = searchQuery.value.toLowerCase().trim();
  return references.value.filter(
    (ref) =>
      ref.title.toLowerCase().includes(query) ||
      ref.authorsText.toLowerCase().includes(query) ||
      (ref.note && ref.note.toLowerCase().includes(query)) ||
      ref.publicationYear.toString().includes(query) ||
      (ref.doi && ref.doi.toLowerCase().includes(query)),
  );
});

// 计算属性相关部分结束

let citationObserver: MutationObserver | null = null;

// 极致体验:引用标记渲染核心逻辑 (深度还原 Vditor 逻辑与样式)
const renderCitationsInAffine = () => {
  if (!container.value || isProgrammaticChange.value) return;
  
  // 锁定,防止 MutationObserver 递归触发死循环
  isProgrammaticChange.value = true;

  try {
    const walk = (root: Node | ShadowRoot) => {
      const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
      let node;
      const targets: Text[] = [];
      
      while (node = walker.nextNode()) {
        const textNode = node as Text;
        
        // 避开已经在标签内的 (兼容多种层级)
        const parent = textNode.parentElement;
        if (parent && (parent.closest('.citation-tag') || parent.closest('.editor-toolbar') || parent.closest('.reference-section'))) {
          continue;
        }
        
        if (/\{\{cite:([^:]+):([^}]*)\}\}/.test(textNode.textContent || '')) {
          targets.push(textNode);
        }
      }
      
      targets.forEach(textNode => {
        const text = textNode.textContent || '';
        const regex = /\{\{cite:([^:]+):([^}]*)\}\}/g;
        const fragment = document.createDocumentFragment();
        let lastIndex = 0;
        let match;
        
        while ((match = regex.exec(text)) !== null) {
          if (match.index > lastIndex) {
            fragment.appendChild(document.createTextNode(text.substring(lastIndex, match.index)));
          }
          
          const workId = String(match[1]);
          const note = String(match[2] || '');
          const markup = match[0];
          
          // 智能匹配逻辑 (深度还原 Vditor)
          let matchedReference = null;
          if (references.value.length > 0) {
            // 1. 优先尝试通过 note/title/authors 匹配 (增加去空格处理)
            const cleanNote = note.trim().toLowerCase();
            if (cleanNote) {
              matchedReference = references.value.find(ref => 
                (ref.note && ref.note.trim().toLowerCase() === cleanNote) ||
                (ref.title && ref.title.trim().toLowerCase() === cleanNote)
              );
              
              if (!matchedReference) {
                matchedReference = references.value.find(ref => 
                  (ref.title && ref.title.toLowerCase().includes(cleanNote)) ||
                  (ref.authorsText && ref.authorsText.toLowerCase().includes(cleanNote))
                );
              }
            }
            // 2. 如果 note 没匹配到,或者没有 note,则尝试通过 workId 匹配
            if (!matchedReference && workId) {
              matchedReference = references.value.find(ref => String(ref.workId) === String(workId));
            }
          }

          // 只要符合格式,就渲染成标签,即使没找到匹配项(显示原始 note 或 workId)
          const finalWorkId = matchedReference ? String(matchedReference.workId) : workId;
          const finalNote = matchedReference ? (matchedReference.note || matchedReference.title || "") : (note || workId);
          const correctedMarkup = matchedReference ? `{{cite:${finalWorkId}:${finalNote}}}` : markup;
          const displayText = `cite:${finalNote}`;

          const span = document.createElement('span');
          span.className = 'citation-tag';
          if (!matchedReference) span.classList.add('unmatched'); 
          
          span.setAttribute('data-work-id', finalWorkId);
          // 关键:存储原始 markup 以便在 replaceCitation 中能准确找到并替换
          span.setAttribute('data-citation-markup', markup);
          span.setAttribute('data-display-text', displayText);
          span.setAttribute('contenteditable', 'false');
          
          // 设置 textContent 为 markup 但由 CSS 隐藏,::before 显示 label
          span.textContent = correctedMarkup;
          
          // 隐藏容器用于定位和标记识别
          const content = document.createElement('span');
          content.className = 'citation-tag-content';
          content.textContent = correctedMarkup;
          span.appendChild(content);
          
          span.onclick = (e) => {
            openCitationMenu(span, e);
          };
          
          fragment.appendChild(span);
          
          lastIndex = regex.lastIndex;
        }
        
        if (lastIndex < text.length) {
          fragment.appendChild(document.createTextNode(text.substring(lastIndex)));
        }
        
        try {
          // 在替换前检查父节点是否仍然存在于文档中
          if (textNode.parentNode) {
            textNode.parentNode.replaceChild(fragment, textNode);
          }
        } catch (e) {
          console.warn("Citation render replace failed:", e);
        }
      });

      // 递归处理 Shadow DOM
      const children = root instanceof ShadowRoot ? root.children : (root as Element).children;
      if (children) {
        for (const child of Array.from(children)) {
          if (child.shadowRoot) walk(child.shadowRoot);
          else walk(child);
        }
      }
    };

    walk(container.value);
  } finally {
    // 释放锁:改为立即释放或极短延迟,防止错过 Lit 的后续更新
    isProgrammaticChange.value = false;
  }
};

// 监听参考文献数据变化,数据加载后重新渲染
watch(() => references.value, (newRefs) => {
  if (newRefs && newRefs.length > 0) {
    nextTick(() => {
      renderCitationsInAffine();
    });
  }
}, { deep: true });

// 启动 DOM 监听
const initCitationObserver = () => {
  if (!container.value) return;
  
  // 初始渲染
  renderCitationsInAffine();
  
  // 监听内容变化
  citationObserver = new MutationObserver((mutations) => {
    // 即使 isProgrammaticChange 为 true,如果发现了原始标记文本,也应该考虑处理
    // 但为了稳定,我们还是尊重锁,只是把锁的释放变得更即时了
    if (isProgrammaticChange.value) return; 
    
    let shouldRender = false;
    for (const mutation of mutations) {
      if (mutation.type === 'childList' || mutation.type === 'characterData') {
        const target = mutation.target as Node;
        const element = target.nodeType === Node.ELEMENT_NODE ? (target as HTMLElement) : target.parentElement;
        
        // 避开我们自己的标签和工具栏
        if (element && (element.closest('.citation-tag') || element.closest('.editor-toolbar'))) continue;
        
        shouldRender = true;
        break;
      }
    }
    if (shouldRender) {
      renderCitationsInAffine();
    }
  });
  
  citationObserver.observe(container.value, {
    childList: true,
    subtree: true,
    characterData: true
  });
};

const handleEditorCopy = (event: ClipboardEvent) => {
  // 如果正在搜索或执行命令,不干预
  if (showSearch.value && document.activeElement === searchInput.value) return;
  if (showCommandPalette.value && document.activeElement === commandInput.value) return;

  try {
    // 检查是否在编辑器内触发
    const path = event.composedPath();

    const isInsideEditor = path.some((el: any) => {
      const tagName = el.tagName || '';
      const classList = el.classList;
      return tagName === 'EDITOR-HOST' || 
             tagName === 'BLOCKSUITE-EDITOR' ||
             tagName.startsWith('AFFINE-') ||
             (classList && (
               classList.contains('affine-editor-container') || 
               classList.contains('blocksuite-editor') ||
               classList.contains('affine-page-root') ||
               Array.from(classList).some((c: any) => c.startsWith('affine-'))
             ));
    });

    if (!isInsideEditor) return;

    let text = '';
    
    // 1. 尝试从 BlockSuite 获取选中文本
    if (stdScope) {
      // 方法 A: 使用 getSelectedModelsCommand (更全面)
      try {
        // @ts-ignore
        const [_, ctx] = stdScope.command.exec(getSelectedModelsCommand, {
          types: ['block', 'text'],
        });
        if (ctx.selectedModels && ctx.selectedModels.length > 0) {
          text = ctx.selectedModels
            .map((m: any) => m.text?.toString() || '')
            .filter(Boolean)
            .join('\n');
        }
      } catch (e) {
        console.warn('[Affine] getSelectedModelsCommand failed:', e);
      }

      // 方法 B: 兜底使用 TextSelection
      if (!text) {
        const textSelection = stdScope.selection.find(TextSelection);
        if (textSelection && !textSelection.collapsed) {
          const models = textSelection.selectedModels;
          if (models && models.length > 0) {
            text = models
              .map((m: any) => m.text?.toString() || '')
              .filter(Boolean)
              .join('\n');
          }
        }
      }
      
      // 方法 C: 兜底使用 BlockSelection
      if (!text) {
        const blockSelection = stdScope.selection.find(BlockSelection);
        if (blockSelection && blockSelection.blockIds.length > 0) {
          text = blockSelection.blockIds
            .map((id: string) => store.getBlock(id)?.model?.text?.toString() || '')
            .filter(Boolean)
            .join('\n');
        }
      }
    }

    // 3. 兜底:使用标准 DOM 选区
    if (!text) {
      const selection = window.getSelection();
      text = selection ? selection.toString() : '';
    }

    // 4. 将文本写入剪贴板的 text/plain 格式
    if (text) {
      if (event.clipboardData) {
        event.clipboardData.setData('text/plain', text);
      }
      
      const textToCopy = text;
      setTimeout(async () => {
        try {
          await navigator.clipboard.writeText(textToCopy);
        } catch (err) {
          // 忽略可能的权限错误(如果此时已失去焦点)
          console.debug('[Affine] Deferred clipboard sync info:', err);
        }
      }, 50);
    }
  } catch (e) {
    console.warn('[Affine] Copy handler failed:', e);
  }
};

const handleEditorPaste = (event: ClipboardEvent) => {
  // 如果正在搜索,不拦截粘贴
  if (showSearch.value && document.activeElement === searchInput.value) return;
  if (showCommandPalette.value && document.activeElement === commandInput.value) return;

  if (!event.clipboardData) return;

  const text = event.clipboardData.getData("text/plain");

  // 尝试解析 JSON 格式的引用数据
  let parsedData: any = null;
  try {
    parsedData = JSON.parse(text);
    if (!(parsedData && parsedData.work_id !== undefined)) {
      return; // 不是有效的引用数据
    }
  } catch (error) {
    return; // 不是 JSON 格式
  }

  // 如果是引用数据,拦截并处理
  event.preventDefault();
  event.stopPropagation();

  const workId = parsedData.work_id;
  const note = parsedData.note || "";
  const citationMarkup = `{{cite:${workId}:${note}}}`;

  // 在 Affine 中插入内容
  insertTextAtCursor(citationMarkup);
  addToast(`已插入引用: ${note || workId}`, 'success');
  
  // 强制触发一次渲染
  nextTick(() => renderCitationsInAffine());
};

const handleEditorDrop = (event: DragEvent) => {
  if (!event.dataTransfer) return;
  
  const jsonString = event.dataTransfer.getData("text/plain") || event.dataTransfer.getData("application/json");
  if (!jsonString) return;

  try {
    const parsedData = JSON.parse(jsonString);
    if (parsedData && parsedData.work_id !== undefined) {
      event.preventDefault();
      event.stopPropagation();
      
      const workId = parsedData.work_id;
      const note = parsedData.note || "";
      const citationMarkup = `{{cite:${workId}:${note}}}`;
      
      insertTextAtCursor(citationMarkup);
      addToast(`已放置引用: ${note || workId}`, 'success');
      
      // 强制触发一次渲染
      nextTick(() => renderCitationsInAffine());
    }
  } catch (e) {
    // 忽略非 JSON 放置
  }
};

const insertTextAtCursor = (text: string) => {
  if (!editorHost) return;
  
  // 核心优化:尝试使用更加原生的方式插入,兼容 Shadow DOM
  const selection = window.getSelection();
  if (selection && selection.rangeCount > 0) {
    const range = selection.getRangeAt(0);
    range.deleteContents();
    const textNode = document.createTextNode(text);
    range.insertNode(textNode);
    
    // 移动光标
    range.setStartAfter(textNode);
    range.setEndAfter(textNode);
    selection.removeAllRanges();
    selection.addRange(range);
    
    hasChanges.value = true;
    scheduleAutoSave(); // 手动触发保存
  } else {
    // 兜底:如果没焦点,尝试找到 note 并追加
    const note = store.getAllModels().find((m: any) => m.flavour === 'affine:note');
    if (note && note.children.length > 0) {
      const lastChild = store.getBlock(note.children[note.children.length - 1]);
      if (lastChild && lastChild.model.text) {
        lastChild.model.text.insert(lastChild.model.text.length, text);
        hasChanges.value = true;
        scheduleAutoSave(); // 手动触发保存
      }
    }
  }
};

// 参考文献核心方法实现
const loadReferences = async () => {
  if (!props.fileId) {
    console.warn("⚠️ 无法加载参考文献:fileId 为空");
    return;
  }
  
  isLoadingReferences.value = true;
  try {
    const response = await getFileReferences(
      props.fileId,
      undefined,
      undefined,
      props.isChatAnswer
    );
    
    if (response && response.data) {
      const { items, total } = response.data;
      references.value = (items || []).map((item: ReferenceItem, index: number) => ({
        ...item,
        serialNumber: index + 1,
      }));
      referencesTotal.value = total || 0;
      console.log('[Affine] References loaded:', references.value.length);
    } else {
      references.value = [];
    }
  } catch (error) {
    console.error("加载参考文献失败:", error);
    addToast("加载参考文献失败", "error");
  } finally {
    isLoadingReferences.value = false;
  }
};

const openImportDialog = () => {
  importDialogVisible.value = true;
  searchResults.value = [];
  importInput.value = "";
  hasSearched.value = false;
  nextTick(() => {
    importInputRef.value?.focus();
  });
};

const closeImportDialog = () => {
  importDialogVisible.value = false;
};

const handleImportSearch = async () => {
  if (!importInput.value.trim()) {
    addToast(importMethod.value === "title" ? "请输入文献标题" : "请输入 DOI", "warning");
    return;
  }
  isSearching.value = true;
  hasSearched.value = true;
  searchResults.value = [];
  try {
    let res;
    if (importMethod.value === "title") {
      res = await searchReferencesByTitle(importInput.value.trim());
    } else {
      res = await searchReferencesByDoi(importInput.value.trim());
    }
    
    if (res && res.data && res.data.items) {
      searchResults.value = res.data.items.map((item: ImportSearchResultItem) => ({
        ...item,
        importing: false,
      }));
    } else {
      searchResults.value = [];
    }
  } catch (error) {
    console.error("搜索参考文献失败:", error);
    addToast("搜索失败", "error");
  } finally {
    isSearching.value = false;
  }
};

const handleAddReference = async (result: any) => {
  if (!props.fileId) return;

  // 检查是否已经导入过
  if (references.value.some((ref) => ref.workId === result.workId)) {
    addToast("该文献已经导入", "warning");
    // 从结果中移除
    searchResults.value = searchResults.value.filter(
      (r) => r.workId !== result.workId,
    );
    // 如果结果为空,重置已搜索状态,避免显示“没有找到匹配的文献”
    if (searchResults.value.length === 0) {
      hasSearched.value = false;
    }
    return;
  }

  try {
    result.importing = true;
    const response = await addReferenceToFile(Number(props.fileId), result.workId);
    
    const isSuccess = response && ((response as any).code === 200 || (response as any).status === 200);
    if (isSuccess) {
      addToast("成功导入文献", "success");
      // 从结果中移除
      searchResults.value = searchResults.value.filter(r => r.workId !== result.workId);
      loadReferences();
      // 如果搜索结果空了,关闭对话框
      if (searchResults.value.length === 0) {
        closeImportDialog();
      }
    } else {
      throw new Error((response as any)?.message || "导入失败");
    }
  } catch (error) {
    console.error("添加参考文献失败:", error);
    addToast(`导入失败: ${(error as Error).message}`, "error");
  } finally {
    result.importing = false;
  }
};

const handleDeleteReference = async (reference: any) => {
  if (!props.fileId) return;
  try {
    await ElMessageBox.confirm(
      `确定要从该文件中移除参考文献《${reference.title}》吗?`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );
    await deleteReferenceFromFile(props.fileId, reference.workId);
    addToast("移除参考文献成功", "success");
    if (selectedReferenceId.value === reference.workId) {
      selectedReferenceId.value = null;
    }
    loadReferences();
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除参考文献失败:", error);
      addToast("移除失败", "error");
    }
  }
};

const startEditAlias = (reference: any) => {
  editingReferenceId.value = reference.workId;
  editingAlias.value = reference.note || "";

  // 在下一帧自动聚焦到输入框并全选
  nextTick(() => {
    const input = document.querySelector(".alias-input") as HTMLInputElement;
    if (input) {
      input.focus();
      input.select();
    }
  });
};

const handleBlur = (reference: any) => {
  // 如果正在处理回车键,跳过失焦事件,防止重复保存
  if (isHandlingEnterKey.value) {
    isHandlingEnterKey.value = false;
    return;
  }
  if (editingReferenceId.value === reference.workId) {
    saveAlias(reference);
  }
};

const handleEnterKey = (reference: any) => {
  isHandlingEnterKey.value = true;
  saveAlias(reference);
};

// 核心:更新编辑器数据模型中的引用标记
const updateCitationMarksInAffine = (workId: string | number, newNote: string) => {
  if (!store) return;
  const workIdStr = String(workId);
  // 转义 workId 以防特殊字符破坏正则
  const escapedId = workIdStr.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  const regex = new RegExp(`\\{\\{cite:${escapedId}:([^}]*)\\}\\}`, 'g');
  const replacement = `{{cite:${workIdStr}:${newNote}}}`;

  const models = store.getAllModels();
  let updated = false;

  models.forEach((model: any) => {
    if (model.text) {
      const originalText = model.text.toString();
      let match;
      const matches = [];
      
      // 重置正则状态
      regex.lastIndex = 0;
      while ((match = regex.exec(originalText)) !== null) {
        matches.push({ index: match.index, length: match[0].length });
      }

      if (matches.length > 0) {
        // 从后往前替换,避免偏移量失效
        matches.reverse().forEach(m => {
          model.text.delete(m.index, m.length);
          model.text.insert(replacement, m.index);
        });
        updated = true;
      }
    }
  });

  if (updated) {
    hasChanges.value = true;
    console.log(`[Affine] Updated citation marks for workId: ${workId}`);
  }
};

const saveAlias = async (reference: any) => {
  if (!props.fileId) return;
  const workId = reference.workId;
  const newNote = editingAlias.value.trim();

  if (newNote === reference.note) {
    editingReferenceId.value = null;
    isHandlingEnterKey.value = false;
    return;
  }

  try {
    const response = await updateReferenceNote(props.fileId, workId, newNote);
    
    // 检查响应
    const isSuccess = response && ((response as any).code === 200 || (response as any).status === 200);
    
    if (isSuccess) {
      reference.note = newNote;
      addToast("更新别名成功", "success");
      
      // 核心:更新编辑器 Markdown 模型中的引用标记
      updateCitationMarksInAffine(workId, newNote);
      
      // 同步更新编辑器中的引用标签视觉呈现
      nextTick(() => renderCitationsInAffine());
    } else {
      throw new Error("API 返回错误");
    }
  } catch (error) {
    console.error("更新别名失败:", error);
    addToast("更新失败", "error");
  } finally {
    editingReferenceId.value = null;
    isHandlingEnterKey.value = false;
  }
};

const viewReferenceDetail = async (reference: any) => {
  currentDetailReference.value = { ...reference };
  isLoadingDetail.value = true;
  try {
    const res = await getReferenceDetail(reference.workId);
    if (res && res.data) {
      currentDetailReference.value = res.data;
    }
  } catch (error) {
    console.error("获取参考文献详情失败:", error);
  } finally {
    isLoadingDetail.value = false;
  }
};

// 引用弹窗与菜单相关状态
let citationModalElement: HTMLElement | null = null;
let citationClickOutsideHandler: ((e: MouseEvent) => void) | null = null;
let citationScrollHandler: ((e: Event) => void) | null = null;

const showCitationMenu = ref(false);
const citationMenuPosition = ref({ x: 0, y: 0 });
const citationMenuRef = ref<HTMLElement | null>(null);
const citationMenuSearch = ref("");
const currentCitationSpan = ref<HTMLElement | null>(null);
const currentCitationBlockId = ref<string | null>(null);
const currentCitationMarkup = ref<string | null>(null);

const filteredCitationMenuReferences = computed(() => {
  if (!citationMenuSearch.value.trim()) {
    return references.value;
  }

  const query = citationMenuSearch.value.toLowerCase().trim();
  return references.value.filter(
    (ref) =>
      ref.title.toLowerCase().includes(query) ||
      ref.authorsText.toLowerCase().includes(query) ||
      (ref.note && ref.note.toLowerCase().includes(query)),
  );
});

// HTML 转义函数
const escapeHtml = (text: string): string => {
  const div = document.createElement("div");
  div.textContent = text;
  return div.innerHTML;
};

// 显示引用弹窗 (深度还原 DeerFlowChat 样式)
const showCitationModal = (
  target: HTMLElement,
  referenceDetail: ReferenceDetail,
) => {
  if (citationClickOutsideHandler) {
    document.removeEventListener("click", citationClickOutsideHandler);
    citationClickOutsideHandler = null;
  }
  if (citationScrollHandler) {
    window.removeEventListener("scroll", citationScrollHandler, true);
    citationScrollHandler = null;
  }
  if (citationModalElement) {
    citationModalElement.classList.remove("show");
    citationModalElement.remove();
    citationModalElement = null;
  }

  citationModalElement = document.createElement("div");
  citationModalElement.className = "citation-modal";

  let modalHTML = `
    <div class="citation-modal-header">
      <div class="citation-modal-title">引用文献</div>
      <button class="citation-modal-close" aria-label="关闭">
        <i class="fas fa-times"></i>
      </button>
    </div>
    <div class="citation-modal-body">
      <div class="citation-modal-content-text">
  `;

  if (referenceDetail.authorsText) {
    const authors = referenceDetail.authorsText
      .split(/[;,]/)
      .map((author) => author.trim())
      .filter((author) => author.length > 0);
    const displayAuthors = authors.slice(0, 3);
    let authorsDisplayText = displayAuthors.join(", ");
    if (authors.length > 3) authorsDisplayText += ", et al.";
    modalHTML += `<span class="citation-author">${escapeHtml(authorsDisplayText)}</span> `;
  }

  if (referenceDetail.title) {
    modalHTML += `<span class="title-bold">"${escapeHtml(referenceDetail.title)}"</span> `;
  }

  const journalName = referenceDetail.venueName;
  if (journalName) {
    modalHTML += `<span class="journal-style">${escapeHtml(journalName)}.</span> `;
  }

  const otherParts: string[] = [];
  if (referenceDetail.volume) otherParts.push(`vol. ${referenceDetail.volume}`);
  if (referenceDetail.issue) otherParts.push(`no. ${referenceDetail.issue}`);
  if (referenceDetail.publicationYear) otherParts.push(String(referenceDetail.publicationYear));
  if (referenceDetail.pages) otherParts.push(`pp. ${referenceDetail.pages}`);
  if (referenceDetail.doi) otherParts.push(`DOI: ${referenceDetail.doi}`);

  if (otherParts.length > 0) {
    modalHTML += `<span class="citation-other">${escapeHtml(otherParts.join(", "))}</span>`;
  }

  modalHTML += `</div></div>`;

  const url = referenceDetail.landingUrl || referenceDetail.pdfUrl;
  if (url) {
    modalHTML += `
      <div class="citation-modal-footer">
        <a href="${escapeHtml(url)}" target="_blank" rel="noopener noreferrer" class="citation-modal-link">
          查看原文 <i class="fas fa-external-link-alt"></i>
        </a>
      </div>
    `;
  }

  citationModalElement.innerHTML = modalHTML;
  const closeBtn = citationModalElement.querySelector(".citation-modal-close");
  if (closeBtn) closeBtn.addEventListener("click", hideCitationModal);

  citationModalElement.style.visibility = "hidden";
  document.body.appendChild(citationModalElement);

  const rect = target.getBoundingClientRect();
  const modalRect = citationModalElement.getBoundingClientRect();

  let left = rect.left + rect.width / 2 - modalRect.width / 2;
  let top = rect.top - modalRect.height - 10;

  if (left < 10) left = 10;
  if (left + modalRect.width > window.innerWidth - 10) left = window.innerWidth - modalRect.width - 10;
  if (top < 10) top = rect.bottom + 10;
  if (top + modalRect.height > window.innerHeight - 10) top = window.innerHeight - modalRect.height - 10;

  citationModalElement.style.left = `${left}px`;
  citationModalElement.style.top = `${top}px`;
  citationModalElement.style.visibility = "visible";

  requestAnimationFrame(() => {
    if (citationModalElement) citationModalElement.classList.add("show");
  });

  citationClickOutsideHandler = (event: MouseEvent) => {
    const targetEl = event.target as HTMLElement;
    if (citationModalElement && !citationModalElement.contains(targetEl) && !target.contains(targetEl)) {
      hideCitationModal();
    }
  };
  setTimeout(() => document.addEventListener("click", citationClickOutsideHandler!), 10);

  citationScrollHandler = () => hideCitationModal();
  window.addEventListener("scroll", citationScrollHandler, true);
};

const hideCitationModal = () => {
  if (citationModalElement) {
    citationModalElement.classList.remove("show");
    setTimeout(() => {
      if (citationModalElement && !citationModalElement.classList.contains("show")) {
        citationModalElement.remove();
        citationModalElement = null;
      }
    }, 200);
  }
  if (citationClickOutsideHandler) {
    document.removeEventListener("click", citationClickOutsideHandler);
    citationClickOutsideHandler = null;
  }
  if (citationScrollHandler) {
    window.removeEventListener("scroll", citationScrollHandler, true);
    citationScrollHandler = null;
  }
};

// 打开引用切换菜单 (深度还原 Vditor 交互)
const openCitationMenu = (span: HTMLElement, event: MouseEvent) => {
  event.preventDefault();
  event.stopPropagation();

  currentCitationSpan.value = span;
  
  // 优化:跨 Shadow DOM 查找 blockId
  let blockId = null;
  let current: Node | null = span;
  while (current) {
    if (current instanceof HTMLElement && (current.hasAttribute('data-block-id') || current.getAttribute('flavour'))) {
      blockId = current.getAttribute('data-block-id') || (current as any).model?.id;
      if (blockId) break;
    }
    // 跨越 Shadow Root 边界
    if (current instanceof ShadowRoot) {
      current = current.host;
    } else {
      current = current.parentNode || (current as any).host; // 兼容更多 Shadow DOM 情况
    }
  }
  
  // 如果还是找不到,尝试从点击事件的路径中找
  if (!blockId && event.composedPath) {
    const path = event.composedPath();
    for (const target of path) {
      if (target instanceof HTMLElement && target.hasAttribute('data-block-id')) {
        blockId = target.getAttribute('data-block-id');
        break;
      }
    }
  }
  
  if (blockId) {
    currentCitationBlockId.value = blockId;
    console.log('[Affine] Found blockId:', blockId);
  } else {
    console.warn('[Affine] Could not find blockId for citation span');
  }
  
  const markupAttr = span.getAttribute('data-citation-markup');
  if (markupAttr) {
    currentCitationMarkup.value = markupAttr;
  } else {
    const contentEl = span.querySelector('.citation-tag-content');
    if (contentEl) currentCitationMarkup.value = contentEl.textContent;
  }
  
  console.log('[Affine] Current citation markup:', currentCitationMarkup.value);

  const rect = span.getBoundingClientRect();
  citationMenuPosition.value = {
    x: rect.left,
    y: rect.bottom + 5,
  };

  showCitationMenu.value = true;

  // 使用 nextTick 等待菜单渲染后精细调整位置,防止溢出屏幕
  nextTick(() => {
    if (!citationMenuRef.value) return;

    const menuRect = citationMenuRef.value.getBoundingClientRect();
    const viewportHeight = window.innerHeight;
    const viewportWidth = window.innerWidth;

    let x = rect.left;
    let y = rect.bottom + 5;

    // 检查底部溢出
    if (y + menuRect.height > viewportHeight) {
      // 如果下方空间不足,尝试显示在上方
      const topY = rect.top - menuRect.height - 5;
      if (topY > 0) {
        y = topY;
      } else {
        // 如果上方也不够,尽量靠底部显示,但不超出屏幕
        y = Math.max(5, viewportHeight - menuRect.height - 10);
      }
    }

    // 检查右侧溢出
    if (x + menuRect.width > viewportWidth) {
      x = Math.max(10, viewportWidth - menuRect.width - 10);
    }

    citationMenuPosition.value = { x, y };
  });
  
  setTimeout(() => {
    window.addEventListener('click', handleCitationMenuClickOutside);
    window.addEventListener('scroll', handleCitationMenuScroll, true);
  }, 10);
};

const closeCitationMenu = () => {
  showCitationMenu.value = false;
  currentCitationSpan.value = null;
  currentCitationBlockId.value = null;
  currentCitationMarkup.value = null;
  citationMenuSearch.value = "";
  window.removeEventListener('click', handleCitationMenuClickOutside);
  window.removeEventListener('scroll', handleCitationMenuScroll, true);
};

const handleCitationMenuClickOutside = (event: MouseEvent) => {
  const target = event.target as HTMLElement;
  if (!target || !target.closest) {
    closeCitationMenu();
    return;
  }
  
  if (!target.closest('.citation-menu-wrapper') && !target.closest('.citation-tag')) {
    closeCitationMenu();
  }
};

const handleCitationMenuScroll = (event: Event) => {
  if (!showCitationMenu.value) return;
  
  const target = event.target as HTMLElement;
  // 如果滚动发生在菜单内部,则不关闭
  if (target && target.closest && target.closest(".citation-menu-wrapper")) {
    return;
  }
  
  closeCitationMenu();
};

// 替换引用标记 (Affine 深度集成)
const replaceCitation = async (reference: any) => {
  console.log('[Affine] replaceCitation triggered. target workId:', reference.workId);
  
  if (!currentCitationBlockId.value || !currentCitationMarkup.value || !store) {
    console.warn('[Affine] Context missing:', {
      blockId: currentCitationBlockId.value,
      markup: currentCitationMarkup.value,
      hasStore: !!store
    });
    return;
  }

  const blockId = currentCitationBlockId.value;
  const oldMarkup = currentCitationMarkup.value;
  const newWorkId = String(reference.workId);
  const newNote = reference.note || reference.title || "";
  const newMarkup = `{{cite:${newWorkId}:${newNote}}}`;

  try {
    // 1. 获取 block model
    const block = store.getBlock(blockId);
    console.log('[Affine] Found block model:', block?.flavour, block?.id);

    if (!block) {
      console.error('[Affine] Block not found in store:', blockId);
      addToast('更新失败:未找到数据块', 'error');
      return;
    }

    // 2. 获取文本内容 (兼容多种 BlockSuite 访问方式)
    const textProp = block.text || (block as any).model?.text;
    if (!textProp) {
      console.error('[Affine] Block has no text property:', block.flavour);
      addToast('该区块不支持引用替换', 'warning');
      return;
    }

    const content = textProp.toString();
    console.log('[Affine] Current block content:', content.substring(0, 50) + '...');

    // 锁定渲染
    isProgrammaticChange.value = true;
    
    // 3. 匹配并替换
    let targetMarkup = oldMarkup;
    if (!content.includes(oldMarkup)) {
      console.log('[Affine] Exact markup not found, searching by ID:', oldMarkup);
      const idMatch = oldMarkup.match(/\{\{cite:([^:]+):/);
      if (idMatch) {
        const id = idMatch[1];
        const regex = new RegExp(`\\{\\{cite:${id}:[^}]*\\}\\}`, 'g');
        const matches = content.match(regex);
        if (matches && matches.length > 0) {
          targetMarkup = matches[0];
          console.log('[Affine] Found match by ID:', targetMarkup);
        }
      }
    }

    if (content.includes(targetMarkup)) {
      const newContent = content.replace(targetMarkup, newMarkup);
      console.log('[Affine] Executing replacement in store. New content length:', newContent.length);
      
      // 4. 视觉层预处理:立即更新当前 Span 的显示(Vditor 风格,提供即时反馈)
      if (currentCitationSpan.value) {
        currentCitationSpan.value.setAttribute('data-display-text', `cite:${newNote}`);
        currentCitationSpan.value.setAttribute('data-work-id', newWorkId);
        currentCitationSpan.value.setAttribute('data-citation-markup', newMarkup);
        const contentEl = currentCitationSpan.value.querySelector('.citation-tag-content');
        if (contentEl) contentEl.textContent = newMarkup;
      }

      // 5. 数据模型更新 (回归最稳健的标准 API,包裹在事务中)
      try {
        store.transact(() => {
          const model = (block as any).model || block;
          console.log('[Affine] Updating block via standard updateBlock API...');
          
          // 必须创建一个全新的 BlockSuiteText 实例,这会强制 BlockSuite 识别到内容变更
          store.updateBlock(model, {
            text: new BlockSuiteText(newContent)
          });
        });
        
        // 验证更新结果
        const finalModel = (block as any).model || block;
        const finalText = finalModel.text?.toString();
        console.log('[Affine] Store update success. Final text length:', finalText?.length);
        
        if (!finalText || finalText.length === 0) {
          console.error('[Affine] CRITICAL: Store content is empty after update!');
        }

        hasChanges.value = true;
        addToast('已更新引用', 'success');
      } catch (transError) {
        console.error('[Affine] Transaction failed:', transError);
        addToast('数据同步失败', 'error');
      }

      // 6. 确保数据持久化
      // 稍微延长延迟,给 BlockSuite 内部同步留出时间
      setTimeout(async () => {
        try {
          console.log('[Affine] Triggering final cloud save...');
          await saveDocument(false);
          console.log('[Affine] Cloud save operation completed');
        } catch (err) {
          console.error("[Affine] Cloud save failed:", err);
        }
      }, 300);
    } else {
      console.warn('[Affine] Target markup still not found in content.');
      addToast('未能定位引用标记', 'warning');
    }
    
    // 关闭菜单
    closeCitationMenu();

    // 释放锁并强制渲染
    nextTick(() => {
      isProgrammaticChange.value = false;
      renderCitationsInAffine();
    });

  } catch (error) {
    console.error("[Affine] replaceCitation error:", error);
    addToast('更新引用失败', 'error');
    isProgrammaticChange.value = false;
    closeCitationMenu();
  }
};

const handleCopyReference = async (reference: any) => {
  const citationData = {
    work_id: String(reference.workId),
    note: reference.note || "",
  };
  const jsonString = JSON.stringify(citationData);
  try {
    await navigator.clipboard.writeText(jsonString);
    addToast("已复制引用数据,可在编辑器中粘贴", "success");
  } catch (error) {
    addToast("复制失败", "error");
  }
};

const handleExportCommand = (command: "markdown" | "html" | "png") => {
  exportOutputFormat.value = command;
  handleExportDocument();
};

const handleExportDocument = async () => {
  if (!store || isExporting.value) return;
  isExporting.value = true;
  addToast(t("affine.export.exporting"), "info"); // 显示加载提示
  try {
    // 1. 获取 Markdown 内容
    const transformer = store.getTransformer();
    const adapter = new MarkdownAdapter(transformer, store.provider);
    const result = await adapter.fromDoc(store);
    
    if (!result || typeof result.file !== 'string') {
      throw new Error("解析文档内容失败");
    }
    
    let content = result.file;

    // 2. 调用后端接口获取格式化的引用列表
    const citationGroups = getAllCitationIds();
    if (citationGroups.length > 0 && exportOutputFormat.value !== 'png') {
      const res = await getFormatCitation(
        props.fileId as string, 
        citationGroups,
        exportCitationFormat.value,
        exportOutputFormat.value as "html" | "markdown"
      );
      
      // 注意:API 返回的是 FormatCitationResponse,包含 entries 数组
      if (res && (res as any).data && (res as any).data.entries && (res as any).data.entries.length > 0) {
        const referenceList = (res as any).data.entries.join("\n");
      content += `\n\n## 参考文献\n\n${referenceList}`;
      }
    }

    // 3. 根据格式导出
    const fileName = props.fileName.replace(/\.md$/, "");
    if (exportOutputFormat.value === "markdown") {
      const blob = new Blob([content], { type: "text/markdown" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `${fileName}.md`;
      a.click();
      URL.revokeObjectURL(url);
    } else if (exportOutputFormat.value === "html") {
      const transformer = store.getTransformer();
      const adapter = new HtmlAdapter(transformer, store.provider);
      const result = await adapter.fromDoc(store);
      
      if (result && typeof result.file === 'string') {
        const blob = new Blob([result.file], { type: 'text/html' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `${fileName}.html`;
        a.click();
        URL.revokeObjectURL(url);
      }
    } else if (exportOutputFormat.value === "png") {
      try {
        if (stdScope) {
          // 在 BlockSuite 中,服务通常通过 provider 获取
          // 我们尝试几种可能的标识符
          const possibleIds = ['affine:export-manager', 'ExportManager'];
          let exportManager: any = null;
          
          for (const id of possibleIds) {
            try {
              // @ts-ignore
              exportManager = stdScope.get(id);
              if (exportManager) break;
            } catch (e) {
              // 忽略单个标识符失败
            }
          }

          if (exportManager && typeof exportManager.exportPng === 'function') {
            await exportManager.exportPng();
          } else {
            addToast(t("affine.export.pngNotSupported"), "warning");
          }
        }
      } catch (err) {
        console.error('[Affine] PNG export failed:', err);
        addToast(t("affine.export.pngExportFailed"), "error");
      }
    } else {
      // 其他格式处理(简化版)
      addToast(t("affine.export.formatNotSupported", { format: exportOutputFormat.value }), "info");
      const blob = new Blob([content], { type: "text/markdown" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `${fileName}.md`;
      a.click();
      URL.revokeObjectURL(url);
    }
    addToast(t("affine.export.exportSuccess"), "success");
    // 触发新手任务:下载文档
    triggerNewbieTask("doc_download_save");
  } catch (error) {
    console.error("导出失败:", error);
    addToast(t("affine.export.exportFailed"), "error");
  } finally {
    isExporting.value = false;
  }
};

const handleReferenceDragStart = (event: DragEvent, reference: any) => {
  if (!event.dataTransfer) return;
  const citationData = {
    work_id: String(reference.workId),
    note: reference.note || "",
  };
  const jsonString = JSON.stringify(citationData);
  event.dataTransfer.effectAllowed = "copy";
  event.dataTransfer.setData("text/plain", jsonString);
  event.dataTransfer.setData("application/json", jsonString);
};

// 调整高度逻辑
const startResizing = (event: MouseEvent | TouchEvent) => {
  isResizing.value = true;
  const clientY =
    event instanceof MouseEvent ? event.clientY : event.touches[0]?.clientY ?? 0;
  startY.value = clientY;
  
  // 记录初始像素高度
  const refEl = document.querySelector('.reference-section') as HTMLElement;
  const editorEl = container.value;
  startReferenceHeight.value = refEl?.offsetHeight || 300;
  startEditorHeight.value = editorEl?.offsetHeight || 0;
  
  console.log('[Affine] Start resizing - StartY:', startY.value, 'InitialRefH:', startReferenceHeight.value, 'InitialEditorH:', startEditorHeight.value);
  
  document.addEventListener("mousemove", handleResizing);
  document.addEventListener("mouseup", stopResizing);
  document.addEventListener("touchmove", handleResizing, { passive: false });
  document.addEventListener("touchend", stopResizing);
  document.body.style.cursor = "row-resize";
  document.body.style.userSelect = "none";
};

const handleResizing = (event: MouseEvent | TouchEvent) => {
  if (!isResizing.value) return;
  const clientY =
    event instanceof MouseEvent ? event.clientY : event.touches[0]?.clientY ?? 0;
  const deltaY = clientY - startY.value;
  
  const mainArea = container.value?.closest('.main-content-area') as HTMLElement;
  if (!mainArea) return;
  
  const containerHeight = mainArea.offsetHeight;
  
  let newReferenceHeight = startReferenceHeight.value - deltaY;
  
  // 极致体验:最小高度限制
  const minH = 200; 
  if (newReferenceHeight < minH) newReferenceHeight = minH;
  if (newReferenceHeight > containerHeight - 150) newReferenceHeight = containerHeight - 150;

  referenceHeight.value = `${newReferenceHeight}px`;
  // 编辑器高度同步更新,确保不超出容器
  editorHeight.value = `${containerHeight - newReferenceHeight}px`;
  
  console.log('[Affine] Resizing - NewRefH:', referenceHeight.value, 'NewEditorH:', editorHeight.value);
};

const stopResizing = () => {
  isResizing.value = false;
  document.removeEventListener("mousemove", handleResizing);
  document.removeEventListener("mouseup", stopResizing);
  document.removeEventListener("touchmove", handleResizing);
  document.removeEventListener("touchend", stopResizing);
  document.body.style.cursor = "";
};

const selectReference = (id: number, event?: MouseEvent) => {
  selectedReferenceId.value = id;
  if (event && event.currentTarget) {
    (event.currentTarget as HTMLElement).focus();
  }
};

// 极致体验:自定义 Toast 通知系统
const toasts = ref<{ id: number; message: string; type: 'info' | 'success' | 'warning' | 'error' }[]>([]);
let toastIdCounter = 0;

const addToast = (message: string, type: 'info' | 'success' | 'warning' | 'error' = 'info') => {
  const id = ++toastIdCounter;
  toasts.value.push({ id, message, type });
  setTimeout(() => {
    toasts.value = toasts.value.filter(t => t.id !== id);
  }, 3000);
};

const getToastIcon = (type: string) => {
  switch (type) {
    case 'success': return 'fas fa-check-circle';
    case 'warning': return 'fas fa-exclamation-triangle';
    case 'error': return 'fas fa-times-circle';
    default: return 'fas fa-info-circle';
  }
};

// 极致体验:全局命令面板 (Command Palette)
const showCommandPalette = ref(false);
const commandSearch = ref("");
const selectedCommandIndex = ref(0);
const commandInput = ref<HTMLInputElement | null>(null);

const commands = computed(() => [
  { id: 'ask-ai', group: 'AI 助手', title: '询问 AI (Ask AI)', icon: 'fas fa-magic', action: () => {
    const selection = window.getSelection();
    let rect = null;
    if (selection && selection.rangeCount > 0) {
      rect = selection.getRangeAt(0).getBoundingClientRect();
    } else {
      rect = container.value?.getBoundingClientRect();
    }
    window.dispatchEvent(new CustomEvent('affine-ask-ai-trigger', { detail: { rect } }));
  }, shortcut: 'Space' },
  
  { id: 'h1', group: '基础区块', title: '一级标题 (Heading 1)', icon: 'fas fa-heading', action: () => insertMarkdownBlock('# ') },
  { id: 'h2', group: '基础区块', title: '二级标题 (Heading 2)', icon: 'fas fa-heading', action: () => insertMarkdownBlock('## ') },
  { id: 'h3', group: '基础区块', title: '三级标题 (Heading 3)', icon: 'fas fa-heading', action: () => insertMarkdownBlock('### ') },
  { id: 'bullet-list', group: '基础区块', title: '无序列表 (Bullet List)', icon: 'fas fa-list-ul', action: () => insertMarkdownBlock('- ') },
  { id: 'numbered-list', group: '基础区块', title: '有序列表 (Numbered List)', icon: 'fas fa-list-ol', action: () => insertMarkdownBlock('1. ') },
  { id: 'code-block', group: '基础区块', title: '代码块 (Code Block)', icon: 'fas fa-code', action: () => insertMarkdownBlock('```\n\n```') },
  { id: 'quote', group: '基础区块', title: '引用块 (Quote)', icon: 'fas fa-quote-left', action: () => insertMarkdownBlock('> ') },
  
  { id: 'mode-toggle', group: '视图切换', title: editorMode.value === 'page' ? '切换到白板模式 (Edgeless Mode)' : '切换到文档模式 (Page Mode)', icon: 'fas fa-sync', action: () => toggleMode(), shortcut: 'M' },
  { id: 'toggle-toc', group: '视图切换', title: '显示/隐藏大纲 (Toggle Outline)', icon: 'fas fa-list-ul', action: () => toggleToc(), shortcut: 'T' },
  { id: 'preview', group: '视图切换', title: isPreviewMode.value ? '进入编辑模式' : '进入预览模式', icon: 'fas fa-eye', action: () => togglePreview() },
  { id: 'full-screen', group: '视图切换', title: '切换全屏模式', icon: 'fas fa-expand', action: () => toggleFullScreen(), shortcut: 'F11' },
  
  { id: 'export-doc', group: '操作', title: '导出文档 (Export Markdown)', icon: 'fas fa-download', action: () => handleExportCommand('markdown'), shortcut: 'E' },
  { id: 'copy-md', group: '操作', title: '复制为 Markdown', icon: 'fas fa-copy', action: () => copyAsMarkdown(), shortcut: 'C' },
  { id: 'clear', group: '操作', title: '清空文档内容', icon: 'fas fa-trash-alt', action: () => clearDocument(), shortcut: 'Shift+D' },
]);

// 辅助函数:插入 Markdown 格式的块
const insertMarkdownBlock = (prefix: string) => {
  if (stdScope && stdScope.store) {
    insertBlockBelow(prefix);
  }
};

const filteredCommands = computed(() => {
  if (!commandSearch.value) return commands.value;
  const s = commandSearch.value.toLowerCase();
  return commands.value.filter(c => c.title.toLowerCase().includes(s));
});

const selectNextCommand = () => {
  if (filteredCommands.value.length === 0) return;
  selectedCommandIndex.value = (selectedCommandIndex.value + 1) % filteredCommands.value.length;
};
const selectPrevCommand = () => {
  if (filteredCommands.value.length === 0) return;
  selectedCommandIndex.value = (selectedCommandIndex.value - 1 + filteredCommands.value.length) % filteredCommands.value.length;
};
const executeCommand = (cmd?: any) => {
  const target = cmd || filteredCommands.value[selectedCommandIndex.value];
  if (target) {
    target.action();
    showCommandPalette.value = false;
  }
};

watch(showCommandPalette, (val) => {
  if (val) {
    commandSearch.value = "";
    selectedCommandIndex.value = 0;
    nextTick(() => {
      commandInput.value?.focus();
    });
  }
});

// 计算文档统计信息
const stats = computed(() => {
  const chars = wordCount.value;
  const readingTime = Math.ceil(chars / 400); // 假设每分钟读400字
  return {
    chars,
    readingTime
  };
});

// 获取文档中所有的引用 ID (用于导出参考文献列表)
const getAllCitationIds = (): number[][] => {
  if (!store) return [];
  const regex = /\{\{cite:(\d+):([^}]*)\}\}/g;
  const models = store.getAllModels();
  const ids: number[] = [];
  
  models.forEach((model: any) => {
    if (model.text) {
      const text = model.text.toString();
      let match;
      while ((match = regex.exec(text)) !== null) {
        ids.push(parseInt(match[1] || '0'));
      }
    }
  });
  
  // 按照出现的顺序返回唯一的 ID 组
  const uniqueIds = Array.from(new Set(ids));
  return uniqueIds.map(id => [id]);
};

// 辅助函数:解析实际应用的主题(支持系统设置匹配)
const getResolvedTheme = () => {
  const theme = appStore.theme;
  if (theme === 'auto' || theme === 'system') {
    return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
  }
  return theme;
};

// 查找替换相关
const showSearch = ref(false);
const searchText = ref("");
const searchTotal = ref(0);
const searchCurrent = ref(0);
const searchInput = ref<HTMLInputElement | null>(null);
const showBackToTop = ref(false);
const currentPageId = ref("");
const currentNoteId = ref("");

// 新增:实现 LinkPreviewProvider
const customLinkPreviewService = {
  query: async (url: string) => {
    console.log('[Affine] Querying link preview for:', url);
    try {
      // 使用 microlink API 作为演示,实际生产环境建议部署自己的后端中转
      const response = await fetch(`https://api.microlink.io?url=${encodeURIComponent(url)}`);
      const data = await response.json();
      if (data.status === 'success' && data.data) {
        return {
          title: data.data.title || url,
          description: data.data.description || '',
          icon: data.data.logo?.url || '',
          image: data.data.image?.url || ''
        };
      }
    } catch (e) {
      console.warn('[Affine] Link preview fetch failed, using fallback');
    }
    return { title: url };
  },
  endpoint: '',
  setEndpoint: () => {}
};

let saveTimer: any = null;
let outlinePanel: any = null;

const scheduleAutoSave = () => {
  if (saveTimer) clearTimeout(saveTimer);
  // 从 3s 增加到 10s 以解决编辑器卡顿
  saveTimer = setTimeout(() => saveDocument(true), 10000);
};

// 优化:防止图片重复处理的集合
const processingImages = new Set<string>();

const handleModeChange = (newMode: 'page' | 'edgeless') => {
  if (!store || !isInitialized.value) return;
  
  console.log('[Affine] Switching mode to:', newMode);
  mountEditorView(newMode);
  addToast(t('affine.askAi.toast.switchedMode', { mode: t(`affine.askAi.modes.${newMode}`) }), 'info');
};

const toggleMode = () => {
  if (!store || !isInitialized.value) return;
  
  const newMode = editorMode.value === 'page' ? 'edgeless' : 'page';
  editorMode.value = newMode;
  handleModeChange(newMode);
};

const togglePreview = () => {
  isPreviewMode.value = !isPreviewMode.value;
  if (!store) return;
  
  // 预览模式即为只读模式的增强版
  store.readonly = isPreviewMode.value || props.readonly;
  
  // 强制更新视图
  if (editorHost && editorHost.requestUpdate) {
    editorHost.requestUpdate();
  }
};

const toggleFullScreen = () => {
  if (!container.value) return;
  const wrapper = container.value.closest('.affine-editor-wrapper');
  if (!wrapper) return;

  if (!isFullScreen.value) {
    if (wrapper.requestFullscreen) {
      wrapper.requestFullscreen();
    }
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    }
  }
  isFullScreen.value = !isFullScreen.value;
};

const copyAsMarkdown = async () => {
  if (!store) return;
  try {
    const transformer = store.getTransformer();
    const adapter = new MarkdownAdapter(transformer, store.provider);
    const result = await adapter.fromDoc(store);
    
    if (result && typeof result.file === 'string') {
      await navigator.clipboard.writeText(result.file);
      addToast('已复制为 Markdown', 'success');
    }
  } catch (error) {
    console.error('[Affine] Copy failed:', error);
    addToast('复制失败', 'error');
  }
};

const clearDocument = async () => {
  if (!store || props.readonly) return;
  
  if (!confirm('确定要清空所有内容吗?此操作不可撤销。')) {
    return;
  }

  try {
    const root = store.root;
    if (root) {
      // 找到 note 块,清空其子项
      const note = store.getAllModels().find((m: any) => m.flavour === 'affine:note');
      if (note) {
        store.withoutTransact(() => {
          const children = [...note.children];
          children.forEach(child => store.deleteBlock(child));
          // 添加一个空的段落,防止编辑器完全为空
          store.addBlock('affine:paragraph', { text: new BlockSuiteText() }, note.id);
        });
      }
    }
    updateWordCount();
    hasChanges.value = true;
    console.log('[Affine] Document cleared');
  } catch (error) {
    console.error('[Affine] Clear failed:', error);
  }
};

// 抽取视图挂载逻辑
const mountEditorView = async (mode: 'page' | 'edgeless') => {
  if (!container.value || !store) return;
  
  console.time(`[Affine] Render ${mode}`);
  
  // 1. 清理旧的 EditorHost 和 Std
  if (editorHost) {
    try {
      if (editorHost.parentElement) {
        editorHost.remove();
      }
    } catch (e) {
      console.warn('[Affine] Error removing old editor host:', e);
    }
    editorHost = null;
  }

  if (stdScope && typeof stdScope.dispose === 'function') {
    try {
      stdScope.dispose();
    } catch (e) {
      console.warn('[Affine] Error disposing old std scope:', e);
    }
    stdScope = null;
  }
  
  // 2. 获取对应模式的扩展
  const viewManager = new ViewExtensionManager(getInternalViewExtensions());
  const viewportExtension = {
    setup: (di: any) => {
      di.override(ViewportElementProvider, () => ({
        get viewportElement() {
          return container.value;
        }
      }));
      // 注入自定义链接预览服务
      di.override(LinkPreviewServiceIdentifier, () => customLinkPreviewService);
    }
  };
  
  const extensions = [
    ...viewManager.get(mode),
    viewportExtension
  ];
  console.log(`[Affine] ${mode} view extensions count:`, extensions.length);
  
  // 3. 创建新的 Std 作用域
  const std = new BlockStdScope({ store, extensions });
  stdScope = std;

  // 关键:同步应用语言到 BlockSuite 内部 UI (如果支持)
  try {
    // 尝试获取 i18n 插件,BlockSuite 的插件系统可能在不同版本中有差异
    // @ts-ignore
    const i18n = std.get('affine:i18n') as any;
    if (i18n && typeof i18n.setLocale === 'function') {
      const bsLocale = locale.value === 'zh-CN' ? 'zh' : 'en';
      i18n.setLocale(bsLocale);
      console.log('[Affine] Set BlockSuite locale to:', bsLocale);
    }
  } catch (e) {
    // 忽略找不到服务的错误,这通常意味着该版本的 BlockSuite 不支持或没加载此插件
    if (!(e instanceof Error && e.message.includes('not a service identifier'))) {
      console.warn('[Affine] Failed to set internal locale:', e);
    }
  }

  // 注入自定义 Toolbar 配置 (Ask AI)
  const registry = std.provider.get(ToolbarRegistryIdentifier);
  if (registry) {
    // 定义 Ask AI Action (样式高度还原官方:蓝色图标 + 文字 + 原生按钮交互)
    const askAiAction = {
      id: 'A.ai', // 匹配官方 ID 前缀
      placement: ActionPlacement.Start,
      score: -1, // 确保在最前面
      content: () => html`
        <div 
          class="ask-ai-btn-wrapper"
          aria-label="${t('affine.askAi.title')}"
          style="display: flex; align-items: center; cursor: pointer; padding: 0 8px; height: 28px; border-radius: 4px; transition: background 0.2s; pointer-events: auto;"
          @mouseenter=${(e: MouseEvent) => { (e.currentTarget as HTMLElement).style.background = 'var(--affine-hover-color, rgba(0,0,0,0.05))'; }}
          @mouseleave=${(e: MouseEvent) => { (e.currentTarget as HTMLElement).style.background = 'transparent'; }}
          @click=${(e: MouseEvent) => {
             e.stopPropagation();
             e.preventDefault();
             console.log('[Affine] Ask AI button clicked directly');
             const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
             window.dispatchEvent(new CustomEvent('affine-ask-ai-trigger', { 
               detail: { rect } 
             }));
          }}
          @mousedown=${(e: MouseEvent) => {
             // 额外捕获 mousedown,防止 BlockSuite 内部事件吞噬
             e.stopPropagation();
             e.preventDefault();
             console.log('[Affine] Ask AI button mousedown captured');
             const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
             window.dispatchEvent(new CustomEvent('affine-ask-ai-trigger', { 
               detail: { rect } 
             }));
          }}
        >
          <span style="color: var(--affine-primary-color, #1e96eb); display: flex; align-items: center; justify-content: center; pointer-events: none;">
            ${AiIcon({ width: '20px', height: '20px' })}
          </span>
          <span style="color: var(--affine-primary-color, #1e96eb); margin-left: 4px; font-size: 14px; font-weight: 500; pointer-events: none; white-space: nowrap;">${t('affine.askAi.title')}</span>
        </div>
      `,
      when: () => true,
    };
    
    // @ts-ignore
    const modules = registry.modules;
    if (modules instanceof Map) {
      // 1. 遍历所有模块,彻底移除旧的 Ask AI 标识
      modules.forEach((module: any) => {
        if (module?.config?.actions) {
          const idsToRemove = ['ask-ai', 'ask-ai-separator', 'A.ai', 'A.ai-separator'];
          module.config.actions = module.config.actions.filter((a: any) => !idsToRemove.includes(a.id));
        }
      });

      // 2. 注入新 Action
      const textLikeFlavours = [
        'affine:paragraph', 'affine:list', 'affine:code', 'affine:quote', 'affine:note'
      ];
      
      textLikeFlavours.forEach(flavour => {
        const module = modules.get(flavour);
        if (module?.config?.actions) {
           // 只保留 Ask AI 按钮,移除手动注入的分隔符 Action,
           // 因为 BlockSuite 可能会自动在插件区域后添加分隔符,或者我们可以通过 CSS 控制
           module.config.actions.unshift(askAiAction);
        }
      });
    }
  }
  
  // 4. 渲染新的 EditorHost
  if (typeof customElements !== 'undefined') {
    await customElements.whenDefined('editor-host');
  }
  
  editorHost = std.render();
  // @ts-ignore
  editorHost.doc = store.doc; 
  // @ts-ignore
  editorHost.pageId = currentPageId.value; // 关键修复:必须设置为 affine:page block 的 ID,否则斜杠菜单等 Widget 无法挂载
  editorHost.setAttribute('mode', mode);
  editorHost.setAttribute('theme', getResolvedTheme()); // 关键:注入解析后的主题

  // 获取 stdScope
  stdScope = editorHost.std;

  container.value.innerHTML = ''; 
  container.value.appendChild(editorHost);
  
  // 注入 Shadow DOM 样式覆盖
  const injectToolbarStyles = () => {
    const toolbarWidget = editorHost?.querySelector('affine-toolbar-widget') as any;
    if (toolbarWidget && toolbarWidget.shadowRoot) {
      // 1. 增加点击调试日志
      if (!toolbarWidget._debugInjected) {
        toolbarWidget.shadowRoot.addEventListener('click', (e: MouseEvent) => {
          const target = e.target as HTMLElement;
          const path = e.composedPath();
          // 增加:打印当前选区状态
          const selection = window.getSelection();
          
          // 如果点击了颜色相关的按钮
          const colorBtn = path.find((el: any) => el.getAttribute?.('data-name') === 'color');
          if (colorBtn) {
            setTimeout(() => {
              const menu = document.querySelector('.affine-context-menu');
            }, 100);
          }
        }, true);
        toolbarWidget._debugInjected = true;
      }

      if (!toolbarWidget.shadowRoot.querySelector('#custom-toolbar-style')) {
        const style = document.createElement('style');
        style.id = 'custom-toolbar-style';
        style.textContent = `
          editor-toolbar {
            background: rgba(255, 255, 255, 0.9) !important;
            backdrop-filter: blur(16px) saturate(180%) !important;
            -webkit-backdrop-filter: blur(16px) saturate(180%) !important;
            border: 0.5px solid rgba(0, 0, 0, 0.08) !important;
            border-radius: 10px !important;
            box-shadow: 
              0 1px 2px rgba(0, 0, 0, 0.02),
              0 4px 12px rgba(0, 0, 0, 0.05),
              0 12px 24px rgba(0, 0, 0, 0.03) !important;
            padding: 2px 6px !important;
            gap: 2px !important;
            height: auto !important;
            min-height: 32px !important;
            display: flex !important;
            align-items: center !important;
            overflow: visible !important;
            pointer-events: auto !important;
          }
          editor-toolbar-separator {
            background-color: rgba(0, 0, 0, 0.08) !important;
            width: 1px !important;
            height: 28px !important;
            margin: 0 4px !important;
            display: inline-block !important;
            vertical-align: middle !important;
          }
          /* 针对 Ask AI 后的分隔符清理 */
          /* 如果工具栏中由于插件注入导致连续出现两个分隔符,隐藏第二个 */
          editor-toolbar-separator + editor-toolbar-separator {
             display: none !important;
          }
          /* 确保 Ask AI 后的第一个 separator 显示正常 */
          .ask-ai-btn-wrapper + editor-toolbar-separator {
             display: inline-block !important;
             opacity: 1 !important;
          }
          editor-menu-button, editor-icon-button {
            border: none !important;
            border-radius: 6px !important;
            padding: 0 4px !important;
            height: 28px !important;
            min-width: 28px !important;
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
            transition: background-color 0.12s ease !important;
          }
          editor-menu-button:hover, editor-icon-button:hover {
            background-color: rgba(0, 0, 0, 0.04) !important;
          }
          /* 适配颜色选择器按钮的特殊外观 */
          editor-menu-button[data-name="color"] {
            padding: 0 2px !important;
          }
          /* 黑暗模式适配 */
          :host([data-theme="dark"]) editor-toolbar {
            background: rgba(30, 30, 30, 0.9) !important;
            border-color: rgba(255, 255, 255, 0.1) !important;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3) !important;
          }
          :host([data-theme="dark"]) editor-toolbar-separator {
            background-color: rgba(255, 255, 255, 0.1) !important;
          }
          :host([data-theme="dark"]) editor-menu-button:hover, 
          :host([data-theme="dark"]) editor-icon-button:hover {
            background-color: rgba(255, 255, 255, 0.08) !important;
          }
        `;
        toolbarWidget.shadowRoot.appendChild(style);
        console.log('[Affine] Custom toolbar styles injected');
      }
    }
  };

  // 使用 MutationObserver 监听 Widget 的加载
  const observer = new MutationObserver(() => {
    injectToolbarStyles();
  });
  if (editorHost) {
    observer.observe(editorHost, { childList: true, subtree: true });
    // 立即尝试注入一次
    injectToolbarStyles();
  }
  
  // 5. 挂载并激活
  if (typeof std.mount === 'function') {
    std.mount();
  }
  
  // 触发 rootAdded 以激活渲染
  if (store.root) {
    store.slots.rootAdded.next(store.root.id);
  }
  
  // 6. 后续处理
  setTimeout(() => {
    window.dispatchEvent(new Event('resize'));
    if (editorHost && editorHost.requestUpdate) editorHost.requestUpdate();
    
    // 如果大纲面板已打开,需要重新绑定新的 editorHost
    if (showToc.value) {
      mountOutlinePanel();
    }
    
    loading.value = false; // 确保加载状态关闭
    console.timeEnd(`[Affine] Render ${mode}`);
    console.log(`[Affine] ${mode} mode view mounted.`);
  }, 100);
};

const mountOutlinePanel = () => {
  if (!tocContentRoot.value || !editorHost) return;
  
  // 清理旧的
  tocContentRoot.value.innerHTML = '';
  
  // 创建官方 OutlinePanel 实例
  const panel = document.createElement('affine-outline-panel');
  // @ts-ignore
  panel.editor = editorHost;
  
  tocContentRoot.value.appendChild(panel);
  outlinePanel = panel;
};

// 监听 TOC 显示状态
watch([showToc, () => editorHost], ([newShow, newHost]) => {
  if (newShow && newHost) {
    nextTick(() => {
      mountOutlinePanel();
    });
  }
}, { immediate: true });

// 监听主题变化
watch(() => appStore.theme, () => {
  if (editorHost) {
    const resolvedTheme = getResolvedTheme();
    editorHost.setAttribute('theme', resolvedTheme);
    if (outlinePanel) {
      outlinePanel.setAttribute('theme', resolvedTheme);
    }
  }
});

// 监听系统主题变化 (当设置为 system/auto 时生效)
const handleSystemThemeChange = (e: MediaQueryListEvent | MediaQueryList) => {
  if ((appStore.theme === 'system' || appStore.theme === 'auto') && editorHost) {
    const newTheme = e.matches ? 'dark' : 'light';
    editorHost.setAttribute('theme', newTheme);
    if (outlinePanel) {
      outlinePanel.setAttribute('theme', newTheme);
    }
  }
};

const systemThemeMedia = window.matchMedia('(prefers-color-scheme: dark)');

const removeReferencesSection = (content: string): string => {
  if (!content) return content;
  const referencePatterns = [
    /\n##\s*参考文献[\s\S]*$/i,
    /\n#\s*参考文献[\s\S]*$/i,
    /\n###\s*参考文献[\s\S]*$/i,
    /\n####\s*参考文献[\s\S]*$/i,
    /\n#####\s*参考文献[\s\S]*$/i,
    /\n######\s*参考文献[\s\S]*$/i,
    /\n##\s*References[\s\S]*$/i,
    /\n#\s*References[\s\S]*$/i,
    /\n###\s*References[\s\S]*$/i,
    /\n####\s*References[\s\S]*$/i,
    /\n#####\s*References[\s\S]*$/i,
    /\n######\s*References[\s\S]*$/i,
    /^##\s*参考文献[\s\S]*$/i,
    /^#\s*参考文献[\s\S]*$/i,
    /^###\s*参考文献[\s\S]*$/i,
    /^##\s*References[\s\S]*$/i,
    /^#\s*References[\s\S]*$/i,
    /^###\s*References[\s\S]*$/i,
    /\n\s*参考文献\s*[\n\r][\s\S]*$/i,
    /\n\s*References\s*[\n\r][\s\S]*$/i,
  ];

  let processedContent = content;
  for (const pattern of referencePatterns) {
    if (pattern.test(processedContent)) {
      processedContent = processedContent.replace(pattern, "");
      break;
    }
  }
  return processedContent.trim();
};

const loadFileContent = async (): Promise<string> => {
  try {
    const fileId = props.fileId;
    try {
      const cached = await fileCache.getFile(fileId);
      if (cached && typeof cached.content === "string") {
        return cached.content;
      }
    } catch (e) {}

    let content = "";
    if (props.isChatAnswer) {
      const response = await apiGetDraftById(fileId);
      if (response && response.data) {
        content = response.data.content || "";
        content = removeReferencesSection(content);
      }
    } else {
      const response = await filesApi.downloadFile(fileId);
      let blob: Blob | null = null;
      if (response instanceof Blob) {
        blob = response;
      } else if (response && (response as any).data instanceof Blob) {
        blob = (response as any).data;
      }
      if (blob) {
        content = await blob.text();
        content = removeReferencesSection(content);
      }
    }

    if (content) {
      content = preprocessMathContent(content);
      await fileCache.setFile({
        fileId,
        content,
        type: "markdown",
        fileName: props.fileName,
      });
    }
    return content;
  } catch (error) {
    console.error("Failed to load file content:", error);
    return "";
  }
};

const saveDocument = async (isAutoSave = true) => {
  if (!store || !hasChanges.value) return;

  try {
    const transformer = store.getTransformer();
    const adapter = new MarkdownAdapter(transformer, store.provider);
    const result = await adapter.fromDoc(store);
    
    if (result && typeof result.file === 'string') {
      const content = result.file;
      console.log('[Affine] Document serialized for saving. Content length:', content.length);
      
      if (props.isChatAnswer) {
        await apiUpdateDraft(props.fileId, {
          content,
          title: props.fileName.replace(/\.md$/, ""),
        });
      } else {
        await filesApi.saveFileContent(props.fileId, {
          content,
          fileName: props.fileName,
        });
      }

      await fileCache.setFile({
        fileId: props.fileId,
        content,
        type: "markdown",
        fileName: props.fileName,
      });

      hasChanges.value = false;
      emit('file-saved', {
        fileId: props.fileId,
        fileName: props.fileName,
        content,
        isAutoSave
      });

      // 触发新手任务:编辑/生成文档
      triggerNewbieTask("doc_generate_edit");

      if (!isAutoSave) {
        addToast('保存成功', 'success');
      }
    }
  } catch (error) {
    console.error("Failed to save document:", error);
    if (!isAutoSave) {
      addToast('保存失败', 'error');
    }
  }
};

const markAsSavedToKnowledge = () => {
  isSavedToKnowledge.value = true;
};

// 优化:计算字数
const updateWordCount = () => {
  if (!store) return;
  let count = 0;
  // 遍历所有 block model,累加 text 长度
  const models = store.getAllModels();
  models.forEach((model: any) => {
    if (model.text) {
      count += model.text.toString().length;
    }
  });
  wordCount.value = count;
};

// 查找替换逻辑
const findNext = () => {
  // 简单模拟,实际上 Affine 有自己的搜索 API,但这里我们先做一个简单的 UI 响应
  if (!searchText.value) return;
  // TODO: 调用 std.get(SearchService) 进行深度集成
  console.log('[Affine] Finding next:', searchText.value);
};

const findPrev = () => {
  console.log('[Affine] Finding prev:', searchText.value);
};

const scrollToTop = () => {
  if (container.value) {
    container.value.scrollTo({ top: 0, behavior: 'smooth' });
  }
};

const handleScroll = (e: Event) => {
  const target = e.target as HTMLElement;
  showBackToTop.value = target.scrollTop > 300;
  
  // 优化:大纲滚动同步高亮逻辑
  if (showToc.value && outlinePanel) {
    syncOutlineHighlight(target);
  }
};

// 新增:同步大纲高亮
const syncOutlineHighlight = (scrollTarget: HTMLElement) => {
  if (!store || !outlinePanel) return;
  
  const models = store.getAllModels();
  const headings = models.filter((m: any) => 
    m.flavour === 'affine:paragraph' && ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(m.type)
  );
  
  if (headings.length === 0) return;
  
  // 寻找当前最靠近视口顶部的标题
  let activeId = '';
  const viewportOffset = 100; // 偏移量,使得标题接近顶部时就触发
  
  for (const heading of headings) {
    const element = editorHost?.querySelector(`[data-block-id="${heading.id}"]`);
    if (element) {
      const rect = element.getBoundingClientRect();
      const containerRect = scrollTarget.getBoundingClientRect();
      const relativeTop = rect.top - containerRect.top;
      
      if (relativeTop <= viewportOffset) {
        activeId = heading.id;
      } else {
        break;
      }
    }
  }
  
  if (activeId && outlinePanel.activeBlockId !== activeId) {
    // @ts-ignore
    outlinePanel.activeBlockId = activeId;
    
    // 同时也尝试在大纲面板内滚动到对应项
    nextTick(() => {
      const activeItem = outlinePanel.shadowRoot?.querySelector(`[data-block-id="${activeId}"]`);
      if (activeItem) {
        activeItem.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
      }
    });
  }
};

watch(showSearch, (val) => {
  if (val) {
    nextTick(() => {
      searchInput.value?.focus();
    });
  }
});

// 优化点:处理图片上传持久化
const handleImageUpload = async (blockId: string, blobUrl: string) => {
  try {
    console.log('[Affine] Local image detected, starting persistence...', blockId);
    
    // 新增:视觉反馈 - 开始处理
    const imageEl = editorHost?.querySelector(`[data-block-id="${blockId}"]`);
    if (imageEl) {
      imageEl.classList.add('processing');
    }

    const response = await fetch(blobUrl);
    const blob = await response.blob();
    
    // 构造 File 对象
    const extension = blob.type.split('/')[1] || 'png';
    const file = new File([blob], `affine-image-${Date.now()}.${extension}`, { type: blob.type });
    
    // 1. 创建上传会话
    const sessionRes = await filesApi.createUploadSession();
    const uploadId = (sessionRes as any).data.uploadId;
    
    // 2. 上传文件到服务器
    // 我们将图片暂存到用户当前的文件夹下 (props.folderId)
    const uploadRes = await filesApi.uploadFile({
      file,
      uploadId,
      parentId: props.folderId || undefined
    });
    
    if (uploadRes && (uploadRes as any).code === 200) {
      // 3. 获取服务器返回的下载链接
      const fileData = (uploadRes as any).data?.files?.[0];
      if (fileData && fileData.fileId) {
        const permanentUrl = `/api/files/${fileData.fileId}/download`;
        
        store.withoutTransact(() => {
          store.updateBlock(blockId, {
            sourceId: permanentUrl
          });
        });
        console.log('[Affine] Image persisted to server:', permanentUrl);
      }
    }

    // 新增:视觉反馈 - 结束处理
    if (imageEl) {
      imageEl.classList.remove('processing');
    }

  } catch (err) {
    console.error('[Affine] Failed to persist image:', err);
    // 失败也移除状态
    const imageEl = editorHost?.querySelector(`[data-block-id="${blockId}"]`);
    if (imageEl) {
      imageEl.classList.remove('processing');
    }
  } finally {
    // 延迟清理,确保状态已同步
    setTimeout(() => processingImages.delete(blockId), 2000);
  }
};

const initEditor = async () => {
  if (!container.value || isInitialized.value) return;
  isInitialized.value = true;

    console.log('[Affine] Starting source-pattern initialization...');
  
    try {
      // 1. 初始化 Collection (Workspace)
    // @ts-ignore
      const collection = new TestWorkspace({ id: 'linkmed-workspace-' + props.fileId });
    
    // 合并并处理全量 Store 扩展 (包含 Markdown 适配器、数据模型等)
    // getInternalStoreExtensions() 内部会自动处理标准 Block 的 Schema 注册
    // @ts-ignore
    const storeManager = new StoreExtensionManager(getInternalStoreExtensions());
    const baseExtensions = storeManager.get('store');
    
    // 严格过滤掉任何没有 setup 方法的无效扩展,并确保不重复
    const storeExtensions = baseExtensions.filter(
      (ext, index, self) => ext && typeof ext.setup === 'function' && self.indexOf(ext) === index
    );
    
    // 调试:检查扩展列表
    console.log('[Affine] Store extensions loaded:', storeExtensions.length);
    
    collection.meta.initialize();
    collection.start();
    // workspace = collection; // 暂时注释掉,如果后面需要用到再开启,以消除 lint 警告
    
    // 3. 创建 Doc 并获取具备操作能力的 Store
    const doc = collection.createDoc();
    doc.load();
    
    // 官方模式:将扩展传给 getStore,内部会处理 DI
      // @ts-ignore
    const targetStore = doc.getStore({ extensions: storeExtensions });
    targetStore.load();
    store = targetStore;

    // 4. 准备内容
    console.time('[Affine] Load Content');
    let initialContent = props.preloadContent || (props.fileId ? await loadFileContent() : "");
    if (initialContent) initialContent = removeReferencesSection(initialContent);
    if (!initialContent) initialContent = "";
    console.timeEnd('[Affine] Load Content');
    console.log('[Affine] Content length:', initialContent.length);

    // 5. 按照源码构建官方标准骨架
    console.time('[Affine] Build Skeleton');
    targetStore.transact(() => {
      // 检查是否已有 Page,防止重复添加
      if (targetStore.root) return;
      
      currentPageId.value = targetStore.addBlock('affine:page', { 
        title: new BlockSuiteText(props.fileName || 'Untitled') 
      });
      targetStore.addBlock('affine:surface', {}, currentPageId.value);
      currentNoteId.value = targetStore.addBlock('affine:note', {}, currentPageId.value);
    });
    console.timeEnd('[Affine] Build Skeleton');
    
    // 如果已经存在 root,重新获取 ID
    if (!currentPageId.value && targetStore.root) {
      currentPageId.value = targetStore.root.id;
      // 查找 surface 和 note
      const page = targetStore.getBlock(currentPageId.value);
      if (page) {
        // @ts-ignore
        const note = page.model.children.find(c => c.flavour === 'affine:note');
        if (note) currentNoteId.value = note.id;
      }
    }
    console.log('[Affine] Created IDs - Page:', currentPageId.value, 'Note:', currentNoteId.value);
    
    // 调试:验证 root block 类型
    const rootBlock = targetStore.getBlock(currentPageId.value);
    console.log('[Affine] Root block flavour:', rootBlock?.flavour);

    // 8. 全量高级内容导入 (先导入内容,再设置只读,避免 addBlock 失败)
    if (initialContent) {
      console.time('[Affine] Import content');
      try {
        console.log('[Affine] Importing content with framework native pattern...');
        const transformer = targetStore.getTransformer();
        const adapter = new MarkdownAdapter(transformer, targetStore.provider);
        
        // 调试:验证 Matcher 是否已加载
        // @ts-ignore
        const matchers = Array.from(targetStore.provider.getAll(BlockMarkdownAdapterMatcherIdentifier).values());
        console.log('[Affine] Markdown Matchers count:', matchers.length);

        const snapshot = await adapter.toDocSnapshot({ file: initialContent });
        
        // 源码模式:toDocSnapshot 返回的是 DocSnapshot,其 blocks 属性是根 block 的嵌套结构
        if (snapshot && snapshot.blocks) {
          const rootBlock = snapshot.blocks;
          console.log('[Affine] Snapshot root:', JSON.stringify({
            flavour: rootBlock.flavour,
            childrenCount: rootBlock.children?.length,
            childrenFlavours: rootBlock.children?.map((c: any) => c.flavour)
          }));
          
          // 找到 snapshot 中的 note block
          const findNoteSnapshot = (snap: any): any => {
            if (snap.flavour === 'affine:note') return snap;
            if (snap.children) {
              for (const child of snap.children) {
                const found = findNoteSnapshot(child);
                if (found) return found;
              }
            }
            return null;
          };

          const noteSnapshot = findNoteSnapshot(rootBlock);
          // 检查是否有标题被解析到了 note 中
          if (noteSnapshot && noteSnapshot.children) {
            console.log('[Affine] Importing content blocks from snapshot note, count:', noteSnapshot.children.length);
            
            const fileNameTitle = props.fileName.replace(/\.md$/, '').trim();
            const pageTitle = (props.fileName || 'Untitled').trim();
            
            // 尝试获取快照中的页面标题
            let snapshotTitle = '';
            if (rootBlock.flavour === 'affine:page' && rootBlock.props?.title) {
              snapshotTitle = rootBlock.props.title.toString().trim();
            }

            for (const child of noteSnapshot.children) {
              // 关键修复:过滤掉重复的标题
              // 如果块是 H1 且内容与文件名、Page Title 或快照标题一致,则跳过导入
              if (child.flavour === 'affine:paragraph' && child.props?.type === 'h1') {
                let h1Text = '';
                const textProp = child.props?.text;
                
                if (typeof textProp === 'string') {
                  h1Text = textProp.trim();
                } else if (textProp && typeof textProp === 'object') {
                  if (Array.isArray(textProp.delta)) {
                    h1Text = textProp.delta.map((d: any) => d.insert || '').join('').trim();
                  } else if (textProp.toString) {
                    h1Text = textProp.toString().trim();
                  }
                }

                // 检查是否与文件名或页面标题重复 (增加更宽泛的模糊匹配)
                const normalizedH1 = h1Text.toLowerCase().replace(/\s+/g, '');
                const normalizedFileName = fileNameTitle.toLowerCase().replace(/\s+/g, '');
                const normalizedPageTitle = pageTitle.toLowerCase().replace(/\s+/g, '');
                const normalizedSnapshotTitle = snapshotTitle.toLowerCase().replace(/\s+/g, '');

                const isDuplicate = h1Text && (
                  h1Text === fileNameTitle || 
                  h1Text === pageTitle || 
                  h1Text === snapshotTitle ||
                  normalizedH1 === normalizedFileName ||
                  normalizedH1 === normalizedPageTitle ||
                  normalizedH1 === normalizedSnapshotTitle
                );

                if (isDuplicate) {
                  console.log(`[Affine] Filtering redundant H1 title: "${h1Text}"`);
                  continue; 
                }
              }
              
              // 使用 transformer.snapshotToBlock 官方方法导入
              await transformer.snapshotToBlock(child, targetStore, currentNoteId.value);
            }
          } else {
            // 如果没找到 note,尝试直接导入 rootBlock 的子项 (兜底)
            console.log('[Affine] Note snapshot not found, importing root children instead');
            if (rootBlock.children) {
              for (const child of rootBlock.children) {
                // 同样过滤 affine:page 这种根节点
                if (child.flavour !== 'affine:page' && child.flavour !== 'affine:note' && child.flavour !== 'affine:surface') {
                await transformer.snapshotToBlock(child, targetStore, currentNoteId.value);
                }
              }
            }
          }
          
          const importedCount = targetStore.getBlock(currentNoteId.value)?.model.children.length || 0;
          console.log('[Affine] Successfully imported blocks to note:', importedCount);
        }
      } catch (e) {
        console.warn("[Affine] Native import failed, fallback:", e);
        targetStore.transact(() => {
          targetStore.addBlock('affine:paragraph', { text: new BlockSuiteText(initialContent) }, currentNoteId.value);
        });
      }
      console.timeEnd('[Affine] Import content');
    }

    // 确保至少有一个内容块
    const noteBlock = targetStore.getBlock(currentNoteId.value);
    if (noteBlock && noteBlock.model.children.length === 0) {
      targetStore.transact(() => {
        targetStore.addBlock('affine:paragraph', { text: new BlockSuiteText('') }, currentNoteId.value);
      });
    }

    // 设置只读模式 (如果 props.readonly 为 true)
    if (props.readonly) {
      store.readonly = true;
      console.log('[Affine] Editor set to readonly mode after initialization');
    }

  // 9. 使用统一挂载逻辑渲染初始视图
  await mountEditorView(editorMode.value);
  
  // 10. 初始化参考文献特殊格式渲染器
  nextTick(() => {
    initCitationObserver();
  });
  
  // 11. 绑定数据更新回调
    store.slots.blockUpdated.subscribe(async (payload: any) => {
      // 优化:监听图片块的变化,自动上传本地 Blob
      if (payload.type === 'add' || payload.props?.key === 'sourceId') {
        const block = store.getBlock(payload.id);
        if (block?.flavour === 'affine:image') {
          // @ts-ignore
          const sourceId = block.model.sourceId;
          // 增加 processingImages 校验,防止重复上传导致的渲染异常
          if (sourceId && sourceId.startsWith('blob:') && !props.readonly && !processingImages.has(payload.id)) {
            processingImages.add(payload.id);
            handleImageUpload(payload.id, sourceId);
          }
        }
      }

      hasChanges.value = true;
      updateWordCount(); // 更新字数
      emit('content-change', { text: "", html: "", hasChanges: true });
      scheduleAutoSave();
    });

    // 初始计算字数
    updateWordCount();
  } catch (error) {
    console.error('[Affine] Initialization failed:', error);
    loading.value = false;
  }
};

const handleKeyDown = (e: KeyboardEvent) => {
  const target = e.target as HTMLElement;
  // 检查是否在输入框、文本域、富文本编辑器或其它交互组件内
  const isInput = target.tagName === 'INPUT' || 
                 target.tagName === 'TEXTAREA' || 
                 target.isContentEditable ||
                 target.closest('.search-panel') || 
                 target.closest('.el-input') || 
                 target.closest('.el-textarea') ||
                 target.closest('.ask-ai-panel') ||
                 target.closest('.citation-menu-container');
                 
  // 检查是否在编辑器核心区域内
  const isEditor = target.closest('editor-host') || target.closest('.affine-editor-container');

  // 处理 Delete/Backspace 键删除选中的参考文献
  if (e.key === 'Delete' || e.key === 'Backspace') {
    // 检查是否在参考文献区域内
    const isInReferenceArea = target.closest('.reference-section');
    
    // 如果在参考文献区域且不是正在输入别名等输入框,或者显式选中了某行且不在编辑器内
    if ((isInReferenceArea && !isInput) || (!isInput && !isEditor && selectedReferenceId.value !== null)) {
      if (selectedReferenceId.value !== null) {
        const selectedRef = references.value.find(r => r.workId === selectedReferenceId.value);
        if (selectedRef) {
          e.preventDefault();
          handleDeleteReference(selectedRef);
          return;
        }
      }
    }
  }

  if ((e.ctrlKey || e.metaKey) && e.key === 's') {
    e.preventDefault();
    saveDocument(false);
    addToast('已手动保存', 'success');
  }
  
  // 增加全选功能快捷键 (Ctrl+A / Cmd+A)
  if ((e.ctrlKey || e.metaKey) && e.key === 'a') {
    if (isEditor && !isInput) {
      console.log('[Affine] Select all shortcut triggered');
      
      try {
        if (stdScope && store) {
          const models = store.getAllModels();
          // 选中所有的内容块 (排除 root block 和容器块)
          const blockIds = models
            .filter((m: any) => m.flavour.startsWith('affine:') && 
                                m.flavour !== 'affine:page' && 
                                m.flavour !== 'affine:surface')
            .map((m: any) => m.id);
            
          if (blockIds.length > 0) {
            e.preventDefault();
            // @ts-ignore
            const blockSelection = stdScope.selection.create(BlockSelection, { blockIds });
            stdScope.selection.setGroup('note', [blockSelection]);
            
            if (editorHost && editorHost.requestUpdate) {
              editorHost.requestUpdate();
            }
            console.log(`[Affine] Selected all ${blockIds.length} blocks`);
            return;
          }
        }
      } catch (err) {
        console.warn('[Affine] BlockSuite native select all failed, falling back to browser default', err);
      }
      
      // 如果上述逻辑失败,则让浏览器尝试处理,或者使用 execCommand
      // 不调用 e.preventDefault() 可能会让浏览器执行默认行为
    }
  }

  if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
    e.preventDefault();
    showSearch.value = !showSearch.value;
    if (showSearch.value) {
      nextTick(() => {
        searchInput.value?.focus();
        addToast('查找模式已开启', 'info');
      });
    }
  }
  if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
    e.preventDefault();
    showCommandPalette.value = !showCommandPalette.value;
  }
  
  // 增加斜杠菜单触发 (/)
  // 这里的逻辑对应帮助文档中的 "/ 唤起斜杠菜单"
  if (e.key === '/' && !e.ctrlKey && !e.metaKey && !e.altKey) {
    if (showSearch.value || showCommandPalette.value || showAskAIMenu.value) return;

    const target = e.target as HTMLElement;
    // 检查是否在编辑器区域内
    const isEditor = target.closest('editor-host') || target.closest('.affine-editor-container');
    // 检查是否在输入框、文本域或搜索面板内
    const isInput = target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.closest('.search-panel');

    if (isEditor && !isInput) {
      // 获取当前选区状态,确保只在没有选中文本时触发
      const selection = window.getSelection();
      if (selection && selection.isCollapsed) {
        console.log('[Affine] Slash menu triggered via /');
        e.preventDefault();
        showCommandPalette.value = true;
      }
    }
  }
};

watch(() => props.showReferences, (newValue) => {
  console.log('[Affine] showReferences changed:', newValue);
  if (newValue) {
    // 极致体验:大幅增加初始视觉比例,对标专业文献管理软件
    const mainArea = container.value?.closest('.main-content-area') as HTMLElement;
    const totalH = mainArea?.offsetHeight || window.innerHeight - 150;
    
    // 默认占据 45% 高度,且最小不低于 300px
    const targetH = Math.max(300, Math.floor(totalH * 0.45));
    
    referenceHeight.value = `${targetH}px`;
    // 编辑器高度精确计算,防止溢出
    editorHeight.value = `${totalH - targetH}px`;
    
    console.log('[Affine] Initialized heights - Reference:', referenceHeight.value, 'Editor:', editorHeight.value, 'TotalH:', totalH);
    
    loadReferences();
    nextTick(() => {
      window.dispatchEvent(new Event('resize'));
    });
  } else {
    editorHeight.value = "100%";
    referenceHeight.value = "0px";
  }
}, { immediate: true });


// 监听 Ask AI 触发事件 (核心通信桥梁)
const handleAskAiTrigger = (e: any) => {
  console.log('[Affine] Ask AI trigger received:', e.detail);
  
  // 如果面板正在生成,忽略触发(防止中断)
  if (showAskAIMenu.value && aiPanelState.value === 'generating') {
    console.log('[Affine] AI is generating, ignoring trigger');
    return;
  }

  const { rect } = e.detail || {};
  if (rect) lastTriggerRect = rect;
  
  // 备份当前选区 (DOM)
  const selection = window.getSelection();
  if (selection && selection.rangeCount > 0 && !selection.getRangeAt(0).collapsed) {
    lastSelectionRange = selection.getRangeAt(0).cloneRange();
    console.log('[Affine] DOM selection range cached');
  }

  // 备份 BlockSuite 选区
  if (stdScope) {
    // @ts-ignore
    const textSelection = stdScope.selection.find(TextSelection);
    if (textSelection && !textSelection.collapsed) {
      lastBlockSuiteSelection = textSelection;
      console.log('[Affine] BlockSuite selection cached');
    }
  }
  
  aiPanelState.value = 'input'; // 每次打开重置为输入状态
  aiResult.value = '';
  showAskAIMenu.value = true;
  console.log('[Affine] Setting showAskAIMenu to true');

  // 立即更新位置 (在 showAskAIMenu 设为 true 后)
  nextTick(() => {
    updateAiPanelPosition();
  });
};

const handleGlobalScrollOrResize = () => {
  if (showAskAIMenu.value) {
    requestAnimationFrame(updateAiPanelPosition);
  }
};

const handleGlobalMouseDown = (e: MouseEvent) => {
  // 穿透 Shadow DOM 的全路径搜索
  // @ts-ignore
  const path = e.composedPath();
  const askAiBtn = path.find((el: any) => {
    if (!el || !el.getAttribute) return false;
    // 检查是否为 Ask AI 按钮
    const isAiBtn = el.getAttribute('aria-label') === t('affine.askAi.title') || 
           (el.classList && el.classList.contains('ask-ai-btn-wrapper'));
    return isAiBtn;
  });
  
  if (askAiBtn) {
    console.log('[Affine] Ask AI button detected via global capture!');
    // 只有在确定是 AI 按钮时才拦截
    e.stopPropagation();
    e.preventDefault();
    
    const rect = (askAiBtn as HTMLElement).getBoundingClientRect();
    handleAskAiTrigger({ detail: { rect } });
  }
};

onMounted(() => {
  nextTick(() => {
    initEditor();
    if (props.fileId) {
      loadReferences();
    }
  });
  window.addEventListener('keydown', handleKeyDown);
  window.addEventListener('copy', handleEditorCopy as any, true);
  if (container.value) {
    container.value.addEventListener('scroll', handleScroll);
    container.value.addEventListener('paste', handleEditorPaste as any);
    container.value.addEventListener('drop', handleEditorDrop as any);
    container.value.addEventListener('dragover', (e) => e.preventDefault());
  }
  systemThemeMedia.addEventListener('change', handleSystemThemeChange);

  // 极致体验:图片点击放大 Lightbox 实现
  const handleImageClick = (e: MouseEvent) => {
    const target = e.target as HTMLElement;
    if (target.tagName === 'IMG' && target.closest('.affine-image-block-container')) {
      const src = (target as HTMLImageElement).src;
      const overlay = document.createElement('div');
      overlay.className = 'lightbox-overlay';
      overlay.innerHTML = `
        <div class="lightbox-content">
          <img src="${src}" />
          <div class="lightbox-close"><i class="fas fa-times"></i></div>
        </div>
      `;
      document.body.appendChild(overlay);
      
      // 动画进入
      requestAnimationFrame(() => overlay.classList.add('active'));

      overlay.onclick = () => {
        overlay.classList.remove('active');
        overlay.classList.add('fade-out');
        setTimeout(() => {
          if (document.body.contains(overlay)) {
            document.body.removeChild(overlay);
          }
        }, 300);
      };
    }
  };

  document.addEventListener('click', handleImageClick);
  
  // 注册全局事件监听
  window.addEventListener('affine-ask-ai-trigger', handleAskAiTrigger);
  window.addEventListener('scroll', handleGlobalScrollOrResize, true);
  window.addEventListener('resize', handleGlobalScrollOrResize, true);
  
  window.addEventListener('mousedown', (e) => {
    handleGlobalMouseDown(e);
  }, true);
});

onBeforeUnmount(() => {
  if (saveTimer) clearTimeout(saveTimer);
  if (hasChanges.value) saveDocument(false);
  
  // 增加安全清理逻辑
  try {
    if (editorHost) {
      // 检查 editorHost 是否还在文档中,如果在则移除
      if (editorHost.parentElement) {
        editorHost.remove();
      }
      editorHost = null;
    }
    
    // 如果 stdScope 有 dispose 方法,尝试调用它
    if (stdScope && typeof stdScope.dispose === 'function') {
      stdScope.dispose();
    }
    stdScope = null;
  } catch (e) {
    console.warn('[Affine] Error during unmount cleanup:', e);
  }

  if (citationObserver) citationObserver.disconnect();
  window.removeEventListener('keydown', handleKeyDown);
  window.removeEventListener('copy', handleEditorCopy as any, true);
  if (container.value) {
    container.value.removeEventListener('scroll', handleScroll);
    container.value.removeEventListener('paste', handleEditorPaste as any);
    container.value.removeEventListener('drop', handleEditorDrop as any);
  }
  systemThemeMedia.removeEventListener('change', handleSystemThemeChange);
  
  window.removeEventListener('affine-ask-ai-trigger', handleAskAiTrigger);
  window.removeEventListener('scroll', handleGlobalScrollOrResize, true);
  window.removeEventListener('resize', handleGlobalScrollOrResize, true);
  window.removeEventListener('mousedown', handleGlobalMouseDown, true);
});

defineExpose({ markAsSavedToKnowledge, saveDocument });
</script>

<style scoped>
/* 黑暗模式支持 */
:global([data-theme='dark']) .affine-editor-wrapper {
  background: #1e1e1e !important;
  /* color: #d4d4d4; */
}

:global([data-theme='dark']) :deep(editor-host) {
  /* --affine-background-color: #1e1e1e; */
  /* --affine-foreground-color: #d4d4d4; */
  background: #1e1e1e !important;
  /* color: #d4d4d4; */
}

:global([data-theme='dark']) :deep(.affine-page-root) {
  background-color: #1e1e1e !important;
}

:global([data-theme='dark']) .editor-toolbar {
  background: #252526 !important;
  border-bottom-color: #333 !important;
}

:global([data-theme='dark']) .toolbar-btn {
  color: #ccc !important;
}

:global([data-theme='dark']) .toolbar-btn:hover {
  background: #37373d !important;
  color: white !important;
}

:global([data-theme='dark']) .toc-sidebar {
  background: #252526 !important;
  border-left-color: #333 !important;
}

:global([data-theme='dark']) .toc-header {
  color: #eee !important;
  border-bottom-color: #333 !important;
}

:global([data-theme='dark']) :deep(.affine-code-block-container) {
  background: #2d2d2d !important;
  border-color: #444 !important;
}

:global([data-theme='dark']) :deep(.affine-code-block-container .line-number) {
  background: #333 !important;
  color: #666 !important;
  border-right-color: #444 !important;
}

:global([data-theme='dark']) .search-panel {
  background: #252526 !important;
  border-color: #444 !important;
}

:global([data-theme='dark']) .search-input-wrapper {
  background: #333 !important;
}

:global([data-theme='dark']) .search-input-wrapper input {
  color: white !important;
}

/* 选区工具栏 (Selection Toolbar) 增强 */
:deep(affine-selection-toolbar) {
  border-radius: 8px !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
  border: 1px solid #eee !important;
  background: white !important;
}

:global([data-theme='dark']) :deep(affine-selection-toolbar) {
  background: #252526 !important;
  border-color: #444 !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3) !important;
}

/* 拖拽手柄 (Drag Handle) 增强 */
:deep(.affine-drag-handle-widget) {
  color: #999 !important;
  transition: color 0.2s !important;
}

:deep(.affine-drag-handle-widget:hover) {
  color: #666 !important;
  background: #f5f5f5 !important;
}

:global([data-theme='dark']) :deep(.affine-drag-handle-widget:hover) {
  background: #333 !important;
  color: #ccc !important;
}

/* 斜杠菜单 (Slash Menu) 增强 */
:deep(affine-slash-menu) {
  border-radius: 10px !important;
  overflow: hidden !important;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15) !important;
}

:global([data-theme='dark']) :deep(affine-slash-menu) {
  background: #2d2d2d !important;
  border: 1px solid #444 !important;
}

/* 数据库 (Database) 增强 */
:deep(.affine-database-block-container) {
  border-radius: 8px !important;
  overflow: hidden !important;
  border: 1px solid #eee !important;
}

:global([data-theme='dark']) :deep(.affine-database-block-container) {
  border-color: #333 !important;
}

/* 优化大纲面板的高亮项样式 */
:deep(affine-outline-panel) .outline-item.active {
  background: #f0f7ff !important;
  color: #007bff !important;
  border-radius: 4px !important;
}

:global([data-theme='dark']) :deep(affine-outline-panel) .outline-item.active {
  background: #1e2d3d !important;
  color: #4da3ff !important;
}

.affine-editor-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
  background: white;
  overflow: hidden;
}

.editor-toolbar {
  height: 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 16px;
  border-bottom: 1px solid #efefef;
  background: #fcfcfc;
  z-index: 100;
}

.toolbar-left {
  display: flex;
  align-items: center;
}

.toolbar-left .file-status {
  font-size: 12px;
  color: #999;
}

.toolbar-left .file-status.changed {
  color: #f56c6c;
}

.word-count {
  font-size: 12px;
  color: #999;
  margin-left: 12px;
  padding-left: 12px;
  border-left: 1px solid #eee;
}

.toolbar-right {
  display: flex;
  gap: 8px;
}

.toolbar-btn {
  border: none;
  background: transparent;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  color: #666;
  font-size: 13px;
  transition: all 0.2s;
}

.toolbar-btn:hover {
  background: #f0f0f0;
  color: #333;
}

.toolbar-btn.active {
  background: #e6f7ff;
  color: #1890ff;
}

/* 查找面板样式 */
.search-panel {
  position: absolute;
  top: 48px;
  right: 16px;
  background: white;
  border: 1px solid #efefef;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  padding: 6px 12px;
  z-index: 200;
  gap: 12px;
}

.search-input-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  background: #f5f5f5;
  padding: 4px 10px;
  border-radius: 6px;
  flex: 1;
}

.search-input-wrapper input {
  border: none;
  background: transparent;
  outline: none;
  font-size: 13px;
  width: 150px;
}

.search-results-count {
  font-size: 12px;
  color: #999;
  min-width: 30px;
}

.search-controls {
  display: flex;
  gap: 4px;
}

.search-controls button {
  border: none;
  background: transparent;
  padding: 4px;
  cursor: pointer;
  color: #666;
  border-radius: 4px;
}

.search-controls button:hover:not(:disabled) {
  background: #f0f0f0;
  color: #333;
}

.search-controls button:disabled {
  opacity: 0.3;
  cursor: not-allowed;
}

.search-controls .close-search {
  margin-left: 4px;
}

.back-to-top {
  position: absolute;
  bottom: 24px;
  right: 24px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: white;
  border: 1px solid #eee;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #666;
  z-index: 150;
  transition: all 0.3s;
}

.back-to-top:hover {
  background: #f0f0f0;
  color: #1890ff;
  transform: translateY(-2px);
}

:global([data-theme='dark']) .back-to-top {
  background: #252526 !important;
  border-color: #444 !important;
  color: #ccc !important;
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.2s;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

.main-content-area {
  flex: 1;
  display: flex;
  flex-direction: column; /* 纵向布局 */
  overflow: hidden;
  position: relative;
  height: calc(100vh - 120px);
}

.affine-editor-container {
  width: 100%;
  flex-shrink: 0; /* 禁止自动压缩,高度完全由 style 控制 */
  position: relative;
  background: white;
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 关键:编辑器外层容器不滚动,由内部 blocksuite-editor 滚动 */
}

/* 确保内部编辑器有滚动条 */
:deep(.blocksuite-editor) {
  flex: 1;
  overflow: auto;
}

.toc-sidebar {
  position: absolute; /* 大纲绝对定位在右侧,不占位纵向空间 */
  right: 0;
  top: 0;
  bottom: 0;
  width: 260px;
  height: 100%;
  border-left: 1px solid #efefef;
  background: #fff;
  display: flex;
  flex-direction: column;
  z-index: 500; /* 确保在编辑器之上 */
  box-shadow: -2px 0 8px rgba(0,0,0,0.05);
}

.toc-header {
  padding: 12px 16px;
  font-weight: 600;
  font-size: 14px;
  color: #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f5f5f5;
}

.close-toc {
  cursor: pointer;
  color: #999;
}

.close-toc:hover {
  color: #666;
}

.toc-content {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
}

/* 优化大纲项悬浮效果 */
:deep(affine-outline-panel) {
  --affine-hover-color: #f0f7ff;
}

:global([data-theme='dark']) :deep(affine-outline-panel) {
  --affine-hover-color: #37373d;
  color: #ccc;
}

/* 适配 affine-outline-panel 的样式 */
:deep(affine-outline-panel) {
  display: block;
  width: 100%;
}

/* TOC 动画 */
.slide-enter-active, .slide-leave-active {
  transition: transform 0.3s ease, opacity 0.3s ease;
}

.slide-enter-from, .slide-leave-to {
  transform: translateX(100%);
  opacity: 0;
}

:deep(editor-host) {
  flex: 1;
  width: 100%;
  height: 100% !important;
  display: flex !important;
  flex-direction: column;
  background: white !important;
  /* color: #333 !important; */
  --affine-font-family: Inter, -apple-system, sans-serif;
  /* --affine-foreground-color: #333; */
  /* --affine-background-color: #fff; */
  --affine-primary-color: #1e90ff;
  visibility: visible !important;
  opacity: 1 !important;
}

/* 彻底解决颜色失效:强制允许所有富文本元素显示自己的 inline style 颜色 */
:deep(v-element span), :deep(v-text span), :deep(.inline-editor span) {
  /* color: inherit; */
}

/* 优化:代码块高级样式增强 */
:deep(.affine-code-block-container) {
  border-radius: 8px !important;
  overflow: hidden !important;
  border: 1px solid #e0e0e0 !important;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05) !important;
  margin: 16px 0 !important;
  background: #fdfdfd !important;
}

:deep(.affine-code-block-container .line-number) {
  color: #bbb !important;
  background: #f7f7f7 !important;
  padding: 0 12px !important;
  border-right: 1px solid #eee !important;
  margin-right: 12px !important;
  text-align: right !important;
  min-width: 32px !important;
  font-family: monospace !important;
}

:deep(.affine-code-block-container .rich-text-content) {
  padding: 12px 0 !important;
}

/* 优化:Toolbar 样式适配 */
:deep(affine-code-toolbar) {
  background: white !important;
  border: 1px solid #eee !important;
  border-radius: 6px !important;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1) !important;
  padding: 4px !important;
}

:deep(language-list-button), :deep(preview-button) {
  border-radius: 4px !important;
  transition: background 0.2s !important;
}

:deep(language-list-button:hover), :deep(preview-button:hover) {
  background: #f0f0f0 !important;
}

/* 优化:拖拽手柄增强 */
:deep(.affine-drag-handle-widget) {
  background: rgba(0, 0, 0, 0.05) !important;
  border-radius: 4px !important;
  width: 24px !important;
  height: 24px !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  opacity: 0;
  transition: opacity 0.2s, background 0.2s !important;
}

:deep(.affine-block-children-container:hover .affine-drag-handle-widget) {
  opacity: 1;
}

:deep(.affine-drag-handle-widget:hover) {
  background: rgba(0, 0, 0, 0.1) !important;
}

/* 优化:斜杠菜单样式 */
:deep(affine-slash-menu) {
  background: white !important;
  border: 1px solid #efefef !important;
  border-radius: 10px !important;
  box-shadow: 0 8px 24px rgba(0,0,0,0.12) !important;
  padding: 8px !important;
  max-height: 400px !important;
  overflow-y: auto !important;
}

:deep(.affine-slash-menu-item) {
  border-radius: 6px !important;
  padding: 8px 12px !important;
  display: flex !important;
  align-items: center !important;
  gap: 10px !important;
}

:deep(.affine-slash-menu-item.active) {
  background: #f0f7ff !important;
  color: #1890ff !important;
}

/* 官方 Light 模式变量补全 */
:deep(editor-toolbar[data-app-theme='light']) {
  --affine-background-overlay-panel-color: rgba(255, 255, 255, 0.85);
  --affine-border-color: rgba(0, 0, 0, 0.08);
  --affine-icon-color: #434343;
  --affine-text-primary-color: #1a1a1a;
  --affine-hover-color: rgba(0, 0, 0, 0.04);
  --affine-divider-color: rgba(0, 0, 0, 0.06);
}

/* 优化:多选态样式 (Selection) */
:deep(.affine-block-selection) {
  background: rgba(24, 144, 255, 0.1) !important;
  border-radius: 4px !important;
}

/* 优化:提示框 (Callout) 样式增强 */
:deep(.affine-callout-container) {
  border-radius: 8px !important;
  padding: 12px 16px !important;
  margin: 12px 0 !important;
  border: 1px solid transparent !important;
  display: flex !important;
  gap: 12px !important;
}

:deep(.affine-callout-emoji-container) {
  font-size: 20px !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  width: 32px !important;
  height: 32px !important;
  background: rgba(0,0,0,0.03) !important;
  border-radius: 6px !important;
}

/* 优化:分隔线 (Divider) */
:deep(.affine-divider-block-container) {
  padding: 16px 0 !important;
}

:deep(.affine-divider-block-container hr) {
  border: none !important;
  border-top: 1px solid #eee !important;
  margin: 0 !important;
}

/* 优化:数据库/表格 (Database/Table) 样式 */
:deep(.affine-database-block-container), :deep(.affine-table-block-container) {
  border: 1px solid #f0f0f0 !important;
  border-radius: 8px !important;
  overflow: hidden !important;
  margin: 20px 0 !important;
}

:deep(.affine-data-view-header) {
  background: #fafafa !important;
  border-bottom: 1px solid #f0f0f0 !important;
}

/* 优化:数学公式 Latex 样式 */
:deep(.latex-block-container) {
  padding: 16px !important;
  background: #fcfcfc !important;
  border-radius: 4px !important;
  margin: 8px 0 !important;
  transition: background 0.2s !important;
}

:deep(.latex-block-container:hover) {
  background: #f0f7ff !important;
}

:deep(.affine-page-root) {
  padding: 60px 100px;
  background-color: white !important;
  /* color: #333; */ /* 注释掉这个,彻底放开文字颜色控制 */
  max-width: 1000px;
  margin: 0 auto;
  min-height: 100%;
}

/* 新增:彻底禁止列表项内的全局颜色覆盖 */
:deep(affine-list *) {
  /* color: unset !important; */
}

/* 白板模式适配 */
:deep(.affine-edgeless-root) {
  background-color: #f8f9fa !important;
  background-image: radial-gradient(#e0e0e0 1px, transparent 1px) !important;
  background-size: 20px 20px !important;
}

:deep(editor-host[mode="edgeless"]) {
  background-color: #f8f9fa !important;
}

:deep(.affine-edgeless-viewport) {
  display: flex !important;
  flex-direction: column !important;
  height: 100% !important;
}

/* 确保白板工具栏可见 */
:deep(.affine-edgeless-toolbar-container) {
  z-index: 1001 !important;
}

/* 优化:Markdown 引用样式 */
:deep(.affine-quote-block-container) {
  border-left: 4px solid #1890ff !important;
  background: #f0f7ff !important;
  padding: 8px 16px !important;
  margin: 12px 0 !important;
  border-radius: 0 4px 4px 0 !important;
}

:global([data-theme='dark']) :deep(.affine-quote-block-container) {
  border-left-color: #177ddc !important;
  background: #111a2c !important;
  color: #d4d4d4 !important;
}

/* 优化:选区工具栏 (Selection Toolbar) 深度美化 */
:deep(affine-selection-toolbar) {
  border-radius: 12px !important;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2) !important;
  background: white !important;
  border: 1px solid #efefef !important;
  padding: 6px !important;
  gap: 4px !important;
}

:global([data-theme='dark']) :deep(affine-selection-toolbar) {
  background: #2d2d2d !important;
  border-color: #444 !important;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4) !important;
}

/* 优化:数据库单元格样式 */
:deep(.affine-database-cell) {
  transition: background 0.2s ease !important;
}

:deep(.affine-database-cell:hover) {
  background: rgba(0, 0, 0, 0.02) !important;
}

:global([data-theme='dark']) :deep(.affine-database-cell:hover) {
  background: rgba(255, 255, 255, 0.05) !important;
}

/* 优化:右键菜单 (Context Menu) */
:deep(.affine-context-menu) {
  border-radius: 10px !important;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15) !important;
  border: 1px solid #eee !important;
  background: white !important;
}

:global([data-theme='dark']) :deep(.affine-context-menu) {
  background: #252526 !important;
  border-color: #454545 !important;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3) !important;
}

/* --- 极致体验优化:白板模式 (Edgeless) 网格背景与样式 --- */
:deep(.affine-edgeless-root) {
  background-color: #f9f9f9 !important;
  background-image: 
    radial-gradient(#e5e5e5 1px, transparent 1px) !important;
  background-size: 20px 20px !important;
}

:global([data-theme='dark']) :deep(.affine-edgeless-root) {
  background-color: #1a1a1a !important;
  background-image: 
    radial-gradient(#333 1px, transparent 1px) !important;
}

/* 极致体验优化:选区矩形 (Selection Rect) 美化 */
:deep(.affine-edgeless-selected-rect) {
  border: 2px solid #1890ff !important;
  background: rgba(24, 144, 255, 0.05) !important;
  border-radius: 4px !important;
  box-shadow: 0 0 0 4px rgba(24, 144, 255, 0.1) !important;
}

/* 极致体验优化:拖拽手柄 (Grabber) 容器与动画 */
:deep(.affine-drag-handle-widget) {
  opacity: 0;
  transition: opacity 0.2s cubic-bezier(0.4, 0, 0.2, 1), transform 0.2s cubic-bezier(0.4, 0, 0.2, 1) !important;
  transform: translateX(-5px);
}

:deep(.affine-block-selection:hover) .affine-drag-handle-widget,
:deep(.affine-drag-handle-widget:hover) {
  opacity: 1 !important;
  transform: translateX(0) !important;
}

/* 极致体验优化:拖拽手柄 (Grabber) 完美还原 */
:deep(.affine-drag-handle-grabber) {
  display: flex !important;
  flex-wrap: wrap !important;
  width: 14px !important;
  height: 24px !important;
  padding: 4px 2px !important;
  gap: 2px !important;
  border-radius: 4px !important;
  transition: background 0.2s !important;
  cursor: grab !important;
  align-content: center !important;
  justify-content: center !important;
}

:deep(.affine-drag-handle-grabber::before) {
  content: '::::::' !important;
  font-family: monospace !important;
  font-size: 14px !important;
  line-height: 8px !important;
  letter-spacing: 2px !important;
  color: #ccc !important;
  display: block !important;
  width: 10px !important;
  word-break: break-all !important;
  text-align: center !important;
}

:global([data-theme='dark']) :deep(.affine-drag-handle-grabber::before) {
  color: #555 !important;
}

:deep(.affine-drag-handle-grabber:hover) {
  background: rgba(0, 0, 0, 0.05) !important;
}

:global([data-theme='dark']) :deep(.affine-drag-handle-grabber:hover) {
  background: rgba(255, 255, 255, 0.1) !important;
}

/* 极致体验优化:拖拽落点指示器 (Drop Indicator) */
:deep(.affine-drop-indicator) {
  height: 2px !important;
  background: #1890ff !important;
  border-radius: 1px !important;
  position: absolute !important;
  z-index: 100 !important;
  box-shadow: 0 0 8px rgba(24, 144, 255, 0.4) !important;
}

/* 极致体验优化:数据库 (Database) 深度细节 */
:deep(.affine-database-block-container) {
  border: 1px solid #eee !important;
  border-radius: 8px !important;
  box-shadow: 0 2px 8px rgba(0,0,0,0.02) !important;
  overflow: hidden !important;
  margin: 16px 0 !important;
}

:global([data-theme='dark']) :deep(.affine-database-block-container) {
  border-color: #333 !important;
  background: #1e1e1e !important;
}

:deep(.affine-data-view-header) {
  background: #fafafa !important;
  border-bottom: 1px solid #eee !important;
  padding: 8px 12px !important;
}

:global([data-theme='dark']) :deep(.affine-data-view-header) {
  background: #252526 !important;
  border-bottom-color: #333 !important;
}

/* 极致体验优化:表格/数据库单元格交互 */
:deep(.affine-database-column-header) {
  background: rgba(0, 0, 0, 0.02) !important;
  transition: background 0.2s !important;
}

:deep(.affine-database-column-header:hover) {
  background: rgba(0, 0, 0, 0.05) !important;
}

:deep(.affine-data-view-table-row:hover) {
  background: rgba(24, 144, 255, 0.02) !important;
}

:global([data-theme='dark']) :deep(.affine-data-view-table-row:hover) {
  background: rgba(255, 255, 255, 0.02) !important;
}

/* 极致体验优化:表格边框平滑处理 */
:deep(.affine-data-view-table) {
  border-spacing: 0 !important;
  border-collapse: separate !important;
}

:deep(.affine-data-view-table-cell) {
  border-bottom: 1px solid #f0f0f0 !important;
  transition: background 0.2s !important;
}

:global([data-theme='dark']) :deep(.affine-data-view-table-cell) {
  border-bottom-color: #333 !important;
}

/* 极致体验优化:编辑器空状态 (Placeholder) */
:deep(.affine-paragraph-placeholder) {
  color: #bfbfbf !important;
  font-style: italic !important;
  opacity: 0.8 !important;
}

/* 极致体验优化:图片上传状态 (Image Uploading) */
:deep(.affine-image-block-container.processing) {
  filter: grayscale(0.5) blur(1px) !important;
  opacity: 0.7 !important;
}

:deep(.affine-image-block-container.processing::after) {
  content: '正在上传并持久化...' !important;
  position: absolute !important;
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) !important;
  background: rgba(0,0,0,0.6) !important;
  color: white !important;
  padding: 4px 12px !important;
  border-radius: 20px !important;
  font-size: 12px !important;
  z-index: 10 !important;
}

/* 优化:链接卡片 (Bookmark/Link Preview) 深度美化 */
:deep(.affine-bookmark-block-container) {
  border: 1px solid #e8e8e8 !important;
  border-radius: 12px !important;
  overflow: hidden !important;
  background: white !important;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
  margin: 12px 0 !important;
}

:deep(.affine-bookmark-block-container:hover) {
  border-color: #1890ff !important;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.1) !important;
  transform: translateY(-1px) !important;
}

:global([data-theme='dark']) :deep(.affine-bookmark-block-container) {
  background: #252526 !important;
  border-color: #444 !important;
}

:deep(.affine-bookmark-content) {
  padding: 12px 16px !important;
}

:deep(.affine-bookmark-title) {
  font-weight: 600 !important;
  font-size: 14px !important;
  color: #1a1a1a !important;
  margin-bottom: 4px !important;
}

:global([data-theme='dark']) :deep(.affine-bookmark-title) {
  color: #eee !important;
}

:deep(.affine-bookmark-description) {
  font-size: 12px !important;
  color: #666 !important;
  line-height: 1.5 !important;
  display: -webkit-box !important;
  -webkit-line-clamp: 2 !important;
  line-clamp: 2 !important;
  -webkit-box-orient: vertical !important;
  overflow: hidden !important;
}

:global([data-theme='dark']) :deep(.affine-bookmark-description) {
  color: #aaa !important;
}

:deep(.affine-bookmark-banner) {
  background-size: cover !important;
  background-position: center !important;
  border-left: 1px solid #eee !important;
  width: 120px !important;
  height: 100% !important;
  flex-shrink: 0 !important;
}

:deep(.affine-bookmark-icon) {
  width: 16px !important;
  height: 16px !important;
  margin-right: 8px !important;
  vertical-align: middle !important;
}

:deep(.affine-bookmark-url) {
  font-size: 11px !important;
  color: #999 !important;
  margin-top: 6px !important;
  white-space: nowrap !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  display: block !important;
}

/* 极致体验优化:斜杠菜单 (Slash Menu) 中文化与视觉分组 */
:deep(affine-slash-menu) {
  border-radius: 12px !important;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15) !important;
  border: 1px solid #efefef !important;
  max-height: 400px !important;
  width: 280px !important;
  z-index: 9999 !important; /* 确保在最顶层 */
}

:global([data-theme='dark']) :deep(affine-slash-menu) {
  background: #252526 !important;
  border-color: #333 !important;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4) !important;
}

/* 菜单项中文化 - 极致覆盖版 (隐藏原英文,显示中文字) */
:global([lang*="zh"] .affine-slash-menu-item .label) { font-size: 0 !important; }

:global([lang*="zh"] .affine-slash-menu-item[data-name="Text"] .label::before) { content: "正文" !important; font-size: 14px !important; }
:global([lang*="zh"] .affine-slash-menu-item[data-name="Heading 1"] .label::before) { content: "一级标题" !important; font-size: 14px !important; }
:global([lang*="zh"] .affine-slash-menu-item[data-name="Heading 2"] .label::before) { content: "二级标题" !important; font-size: 14px !important; }
:global([lang*="zh"] .affine-slash-menu-item[data-name="Heading 3"] .label::before) { content: "三级标题" !important; font-size: 14px !important; }
:global([lang*="zh"] .affine-slash-menu-item[data-name="Heading 4"] .label::before) { content: "四级标题" !important; font-size: 14px !important; }
:global([lang*="zh"] .affine-slash-menu-item[data-name="Heading 5"] .label::before) { content: "五级标题" !important; font-size: 14px !important; }
:global([lang*="zh"] .affine-slash-menu-item[data-name="Heading 6"] .label::before) { content: "六级标题" !important; font-size: 14px !important; }
:global([lang*="zh"] .affine-slash-menu-item[data-name="Bullet List"] .label::before),
:global([lang*="zh"] .affine-slash-menu-item[data-name="Bulleted List"] .label::before) { content: "无序列表" !important; font-size: 14px !important; }
:global([lang*="zh"] .affine-slash-menu-item[data-name="Numbered List"] .label::before) { content: "有序列表" !important; font-size: 14px !important; }
:global([lang*="zh"] .affine-slash-menu-item[data-name="To-do List"] .label::before) { content: "待办事项" !important; font-size: 14px !important; }
:global([lang*="zh"] .affine-slash-menu-item[data-name="Code Block"] .label::before) { content: "代码块" !important; font-size: 14px !important; }
:global([lang*="zh"] .affine-slash-menu-item[data-name="Quote"] .label::before) { content: "引用" !important; font-size: 14px !important; }
:global([lang*="zh"] .affine-slash-menu-item[data-name="Callout"] .label::before) { content: "高亮块" !important; font-size: 14px !important; }
:global([lang*="zh"] .affine-slash-menu-item[data-name="Divider"] .label::before) { content: "分割线" !important; font-size: 14px !important; }
:global([lang*="zh"] .affine-slash-menu-item[data-name="Image"] .label::before) { content: "图片" !important; font-size: 14px !important; }
:global([lang*="zh"] .affine-slash-menu-item[data-name="Database"] .label::before) { content: "数据库" !important; font-size: 14px !important; }
:global([lang*="zh"] .affine-slash-menu-item[data-name="Table"] .label::before) { content: "表格" !important; font-size: 14px !important; }

/* 极致体验优化:斜杠菜单分组伪类标题 */
:global([lang*="zh"] .affine-slash-menu-item[data-name="Text"]::before) {
  content: "基础内容";
  display: block;
  padding: 8px 12px 4px;
  font-size: 11px;
  font-weight: 600;
  color: #999;
  text-transform: uppercase;
  pointer-events: none;
}

:global([lang*="zh"] .affine-slash-menu-item[data-name="Image"]::before) {
  content: "媒体与附件";
  display: block;
  padding: 8px 12px 4px;
  font-size: 11px;
  font-weight: 600;
  color: #999;
  text-transform: uppercase;
  border-top: 1px solid rgba(0,0,0,0.05);
  margin-top: 4px;
  pointer-events: none;
}

:global([lang*="zh"] .affine-slash-menu-item[data-name="Database"]::before) {
  content: "高级组件";
  display: block;
  padding: 8px 12px 4px;
  font-size: 11px;
  font-weight: 600;
  color: #999;
  text-transform: uppercase;
  border-top: 1px solid rgba(0,0,0,0.05);
  margin-top: 4px;
  pointer-events: none;
}

:global([data-theme='dark']) :deep(.affine-slash-menu-item::before) {
  border-top-color: rgba(255,255,255,0.05);
  color: #666;
}

/* 极致体验优化:高亮块 (Callout) 深度重塑 */
:deep(.affine-callout-container) {
  border-radius: 8px !important;
  border: 1px solid transparent !important;
  padding: 12px 16px !important;
  display: flex !important;
  gap: 12px !important;
  margin: 16px 0 !important;
  background: #f1f3f5 !important;
  border-left: 4px solid #adb5bd !important;
}

:deep(.affine-callout-icon) {
  font-size: 20px !important;
  flex-shrink: 0 !important;
}

:global([data-theme='dark']) :deep(.affine-callout-container) {
  background: #2a2a2a !important;
  border-left-color: #495057 !important;
  color: #e9ecef !important;
}

/* 极致体验优化:选区工具栏 (Selection Toolbar) 磨砂玻璃效果 */
:deep(affine-selection-toolbar) {
  backdrop-filter: blur(8px) saturate(180%) !important;
  background-color: rgba(255, 255, 255, 0.85) !important;
  border: 1px solid rgba(255, 255, 255, 0.3) !important;
}

:global([data-theme='dark']) :deep(affine-selection-toolbar) {
  background-color: rgba(45, 45, 45, 0.85) !important;
  border-color: rgba(255, 255, 255, 0.1) !important;
}

/* 极致体验优化:图片点击查看 (Lightbox 模拟样式) */
:deep(.affine-image-block-container img) {
  cursor: zoom-in !important;
  transition: transform 0.2s ease !important;
}

:deep(.affine-image-block-container img:active) {
  transform: scale(0.98) !important;
}

/* 极致体验优化:代码块 (Code Block) 语言标签美化 */
:deep(.affine-code-toolbar) {
  background: rgba(0, 0, 0, 0.03) !important;
  padding: 4px 8px !important;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05) !important;
}

:global([data-theme='dark']) :deep(.affine-code-toolbar) {
  background: rgba(255, 255, 255, 0.05) !important;
  border-bottom-color: rgba(255, 255, 255, 0.05) !important;
}

/* 极致体验:Lightbox 蒙层样式 */
:global(.lightbox-overlay) {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.85);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  cursor: zoom-out;
  opacity: 0;
  transition: opacity 0.3s ease;
}

:global(.lightbox-overlay.active) {
  opacity: 1;
}

:global(.lightbox-overlay.fade-out) {
  opacity: 0;
}

:global(.lightbox-content) {
  position: relative;
  max-width: 90%;
  max-height: 90%;
  transform: scale(0.9);
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

:global(.lightbox-overlay.active .lightbox-content) {
  transform: scale(1);
}

:global(.lightbox-content img) {
  max-width: 100%;
  max-height: 100%;
  border-radius: 4px;
  box-shadow: 0 12px 48px rgba(0, 0, 0, 0.5);
}

:global(.lightbox-close) {
  position: absolute;
  top: -40px;
  right: -40px;
  color: white;
  font-size: 24px;
  cursor: pointer;
  padding: 10px;
}

.affine-editor-container.loaded {
  opacity: 1;
}

.affine-editor-container.is-loading {
  filter: blur(4px);
}

/* 极致体验优化:区块聚焦 (Block Focus) 呼吸边框 */
:deep(.affine-block-element.affine-focused) {
  position: relative !important;
}

:deep(.affine-block-element.affine-focused::before) {
  content: '' !important;
  position: absolute !important;
  left: -12px !important;
  top: 0 !important;
  bottom: 0 !important;
  width: 2px !important;
  background: #1890ff !important;
  border-radius: 4px !important;
  animation: breathe 2s infinite ease-in-out !important;
}

@keyframes breathe {
  0% { opacity: 0.3; transform: scaleY(0.95); }
  50% { opacity: 1; transform: scaleY(1); }
  100% { opacity: 0.3; transform: scaleY(0.95); }
}

/* 极致体验优化:多选区块时的视觉阴影 */
:deep(.affine-block-selection) {
  background: rgba(24, 144, 255, 0.08) !important;
  border-radius: 4px !important;
  box-shadow: 0 0 0 1px rgba(24, 144, 255, 0.2) !important;
}

:global([data-theme='dark']) :deep(.affine-bookmark-banner) {
  border-left-color: #333 !important;
}

:deep(editor-host[mode="page"]) {
  background-color: white !important;
}

/* 状态栏与统计信息 */
.save-status-group {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
}

.saving {
  color: #1890ff;
  animation: pulse 1.5s infinite;
}

.saved {
  color: #52c41a;
}

.doc-stats {
  display: flex;
  gap: 12px;
  margin-left: 16px;
  padding-left: 16px;
  border-left: 1px solid #eee;
  color: #888;
  font-size: 11px;
}

@keyframes pulse {
  0% { opacity: 0.6; }
  50% { opacity: 1; }
  100% { opacity: 0.6; }
}

/* AI 侧边栏样式 */
.ai-sidebar {
  position: absolute;
  top: 40px;
  right: 0;
  bottom: 0;
  width: 300px;
  background: white;
  border-left: 1px solid #efefef;
  z-index: 250;
  display: flex;
  flex-direction: column;
  box-shadow: -4px 0 12px rgba(0,0,0,0.05);
}

:global([data-theme='dark']) .ai-sidebar {
  background: #252526 !important;
  border-left-color: #333 !important;
  box-shadow: -4px 0 12px rgba(0,0,0,0.2) !important;
}

.ai-header {
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f5f5f5;
}

:global([data-theme='dark']) .ai-header {
  border-bottom-color: #333 !important;
}

.ai-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #722ed1;
}

.ai-actions {
  padding: 16px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.ai-action-btn {
  padding: 10px;
  border: 1px solid #e8e8e8;
  background: #f9f9f9;
  border-radius: 8px;
  cursor: pointer;
  font-size: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
  transition: all 0.2s;
}

:global([data-theme='dark']) .ai-action-btn {
  background: #333 !important;
  border-color: #444 !important;
  color: #ccc !important;
}

.ai-action-btn:hover {
  background: #f0f5ff;
  border-color: #1890ff;
  color: #1890ff;
}

/* 帮助面板样式 */
.help-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.help-modal {
  width: 500px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 12px 36px rgba(0,0,0,0.2);
  overflow: hidden;
}

:global([data-theme='dark']) .help-modal {
  background: #252526 !important;
  color: #ccc !important;
}

.help-header {
  padding: 16px 20px;
  background: #fcfcfc;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:global([data-theme='dark']) .help-header {
  background: #2d2d2d !important;
  border-bottom-color: #444 !important;
}

.help-body {
  padding: 20px;
  max-height: 400px;
  overflow-y: auto;
}

.help-section {
  margin-bottom: 20px;
}

.help-section h4 {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #1890ff;
}

.help-section ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.help-section li {
  margin-bottom: 8px;
  display: flex;
  justify-content: space-between;
  font-size: 13px;
}

kbd {
  background: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 2px 6px;
  font-size: 11px;
  font-family: monospace;
}

:global([data-theme='dark']) kbd {
  background: #444 !important;
  border-color: #555 !important;
  color: #eee !important;
}

:global([data-theme='dark']) .doc-stats {
  border-left-color: #444 !important;
  color: #666 !important;
}

:global([data-theme='dark']) .ai-status-card {
  background: #2d2d2d !important;
  border-color: #444 !important;
  color: #888 !important;
}

.ai-status-card {
  margin: 16px;
  padding: 12px;
  background: #f0f7ff;
  border: 1px dashed #1890ff;
  border-radius: 8px;
  font-size: 12px;
  color: #666;
}

.ai-history {
  padding: 16px;
  flex: 1;
}

.empty-history {
  padding: 20px 0;
  text-align: center;
  color: #bfbfbf;
  font-size: 12px;
}

.editor-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  z-index: 10;
  gap: 10px;
}
/* 极致体验:Toast 通知样式 */
.affine-toast-container {
  position: fixed;
  bottom: 24px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 10000;
  display: flex;
  flex-direction: column;
  gap: 10px;
  pointer-events: none;
}

.affine-toast {
  padding: 10px 20px;
  border-radius: 8px;
  background: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
  pointer-events: auto;
  animation: slide-up 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: 1px solid #eee;
}

:global([data-theme='dark']) .affine-toast {
  background: #2d2d2d;
  border-color: #444;
  color: #eee;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.affine-toast.success i { color: #52c41a; }
.affine-toast.info i { color: #1890ff; }
.affine-toast.warning i { color: #faad14; }
.affine-toast.error i { color: #f5222d; }

@keyframes slide-up {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

.toast-fade-enter-active, .toast-fade-leave-active {
  transition: all 0.3s ease;
}
.toast-fade-enter-from {
  opacity: 0;
  transform: translateY(20px);
}
.toast-fade-leave-to {
  opacity: 0;
  transform: scale(0.95);
}

/* 极致体验:命令面板 (Command Palette) 样式 */
.command-palette-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(8px);
  z-index: 10001;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding-top: 15vh;
}

.command-palette {
  width: 500px;
  max-width: 90%;
  background: white;
  border-radius: 12px;
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.1), 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  border: 1px solid rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
}

:global([data-theme='dark']) .command-palette {
  background: #252526;
  border-color: rgba(255, 255, 255, 0.1);
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.4);
}

.command-input-wrapper {
  padding: 14px 16px;
  display: flex;
  align-items: center;
  gap: 12px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.04);
}

:global([data-theme='dark']) .command-input-wrapper {
  border-bottom-color: rgba(255, 255, 255, 0.05);
}

.command-input-wrapper i {
  color: #1e96eb;
  font-size: 16px;
}

.command-input-wrapper input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 15px;
  background: transparent;
  color: #1d1d1f;
  font-weight: 400;
}

:global([data-theme='dark']) .command-input-wrapper input {
  color: #eee;
}

.command-list {
  max-height: 420px;
  overflow-y: auto;
  padding: 6px;
}

.command-group-title {
  font-size: 11px;
  font-weight: 600;
  color: #a0a0a0;
  padding: 10px 12px 4px 12px;
  text-transform: uppercase;
  letter-spacing: 0.02em;
}

.command-item {
  padding: 8px 12px;
  display: flex;
  align-items: center;
  gap: 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.15s ease;
  margin-bottom: 2px;
}

.command-item:last-child {
  margin-bottom: 0;
}

.command-item.active {
  background: #f5f5f7;
}

:global([data-theme='dark']) .command-item.active {
  background: rgba(255, 255, 255, 0.08);
}

.command-icon-box {
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  background: rgba(30, 150, 235, 0.08);
  color: #1e96eb;
}

:global([data-theme='dark']) .command-icon-box {
  background: rgba(30, 150, 235, 0.15);
}

.command-icon-box i {
  font-size: 14px;
}

.command-info {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.command-title {
  font-size: 14px;
  font-weight: 450;
  color: #1d1d1f;
}

:global([data-theme='dark']) .command-title {
  color: #eee;
}

.command-shortcut {
  font-size: 11px;
  color: #86868b;
  background: rgba(0, 0, 0, 0.05);
  padding: 2px 6px;
  border-radius: 4px;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  min-width: 20px;
  text-align: center;
}

:global([data-theme='dark']) .command-shortcut {
  background: rgba(255, 255, 255, 0.1);
  color: #a0a0a0;
}

.command-empty {
  padding: 40px 20px;
  text-align: center;
  color: #a0a0a0;
  font-size: 13px;
}
/* 极致体验:骨架屏加载动画 */
.editor-skeleton {
  padding: 80px 15%;
  display: flex;
  flex-direction: column;
  gap: 20px;
  background: white;
  min-height: 100vh;
}

:global([data-theme='dark']) .editor-skeleton {
  background: #1e1e1e;
}

.skeleton-header {
  height: 40px;
  width: 100%;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: skeleton-loading 1.5s infinite;
  border-radius: 8px;
  margin-bottom: 40px;
}

.skeleton-line {
  height: 16px;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: skeleton-loading 1.5s infinite;
  border-radius: 4px;
}

.skeleton-line.title {
  width: 40%;
  height: 32px;
  margin-bottom: 20px;
}

.skeleton-line.body {
  width: 100%;
}

:global([data-theme='dark']) .skeleton-header,
:global([data-theme='dark']) .skeleton-line {
  background: linear-gradient(90deg, #333 25%, #444 50%, #333 75%);
  background-size: 200% 100%;
}

@keyframes skeleton-loading {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}

/* 极致体验:系统菜单 (ContextMenu) 美化 */
:deep(.affine-context-menu) {
  background: rgba(255, 255, 255, 0.8) !important;
  backdrop-filter: blur(12px) !important;
  border-radius: 10px !important;
  border: 1px solid rgba(0, 0, 0, 0.05) !important;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15) !important;
  padding: 6px !important;
  z-index: 10005 !important;
}

:global([data-theme='dark']) :deep(.affine-context-menu) {
  background: rgba(45, 45, 45, 0.8) !important;
  border-color: rgba(255, 255, 255, 0.05) !important;
}

:deep(.affine-context-menu-item) {
  border-radius: 6px !important;
  padding: 8px 12px !important;
  transition: all 0.2s ease !important;
}

:deep(.affine-context-menu-item:hover) {
  background: rgba(24, 144, 255, 0.1) !important;
  color: #1890ff !important;
}

:global([data-theme='dark']) :deep(.affine-context-menu-item:hover) {
  background: rgba(24, 144, 255, 0.2) !important;
}

/* 区块操作菜单 (Block Action Menu) 中文化 - 精准覆盖版 (只隐藏已翻译的项,避免误伤颜色设置等功能) */
:global([lang*="zh"] [data-name="Copy"] .label),
:global([lang*="zh"] [data-name="Copy"] .text),
:global([lang*="zh"] [data-name="Copy link to block"] .label),
:global([lang*="zh"] [data-name="Copy link to block"] .text),
:global([lang*="zh"] [data-name="Duplicate"] .label),
:global([lang*="zh"] [data-name="Duplicate"] .text),
:global([lang*="zh"] [data-name="Delete"] .label),
:global([lang*="zh"] [data-name="Delete"] .text),
:global([lang*="zh"] [data-name="Move to"] .label),
:global([lang*="zh"] [data-name="Move to"] .text),
:global([lang*="zh"] [data-name="Turn into"] .label),
:global([lang*="zh"] [data-name="Turn into"] .text),
:global([lang*="zh"] [data-name="Group"] .label),
:global([lang*="zh"] [data-name="Group"] .text),
:global([lang*="zh"] [data-name="Ungroup"] .label),
:global([lang*="zh"] [data-name="Ungroup"] .text) {
  font-size: 0 !important;
  opacity: 0 !important;
  display: inline-block !important;
  width: 0 !important;
}

/* 尝试汉化颜色相关菜单 (如果存在) */
:global([lang*="zh"] [data-name="Color"] .label),
:global([lang*="zh"] [data-name="Color"] .text) {
  font-size: 0 !important;
  width: 0 !important;
}
:global([lang*="zh"] [data-name="Color"]::before),
:global([lang*="zh"] .affine-context-menu-item[data-name="Color"]::before) { content: "颜色" !important; }

/* 颜色选择器中文化 */
:global([lang*="zh"] .affine-context-menu-item[data-name="Default"] .label),
:global([lang*="zh"] .affine-context-menu-item[data-name="Red"] .label),
:global([lang*="zh"] .affine-context-menu-item[data-name="Orange"] .label),
:global([lang*="zh"] .affine-context-menu-item[data-name="Yellow"] .label),
:global([lang*="zh"] .affine-context-menu-item[data-name="Green"] .label),
:global([lang*="zh"] .affine-context-menu-item[data-name="Teal"] .label),
:global([lang*="zh"] .affine-context-menu-item[data-name="Blue"] .label),
:global([lang*="zh"] .affine-context-menu-item[data-name="Purple"] .label),
:global([lang*="zh"] .affine-context-menu-item[data-name="Grey"] .label),
:global([lang*="zh"] .affine-context-menu-item[data-name="Default Color"] .label),
:global([lang*="zh"] .affine-context-menu-item[data-name="Default Background"] .label) {
  font-size: 0 !important;
}

:global([lang*="zh"] .affine-context-menu-item[data-name="Default"] .label::before) { content: "默认" !important; font-size: 14px !important; }
:global([lang*="zh"] .affine-context-menu-item[data-name="Red"] .label::before) { content: "红色" !important; font-size: 14px !important; }
:global([lang*="zh"] .affine-context-menu-item[data-name="Orange"] .label::before) { content: "橙色" !important; font-size: 14px !important; }
:global([lang*="zh"] .affine-context-menu-item[data-name="Yellow"] .label::before) { content: "黄色" !important; font-size: 14px !important; }
:global([lang*="zh"] .affine-context-menu-item[data-name="Green"] .label::before) { content: "绿色" !important; font-size: 14px !important; }
:global([lang*="zh"] .affine-context-menu-item[data-name="Teal"] .label::before) { content: "青色" !important; font-size: 14px !important; }
:global([lang*="zh"] .affine-context-menu-item[data-name="Blue"] .label::before) { content: "蓝色" !important; font-size: 14px !important; }
:global([lang*="zh"] .affine-context-menu-item[data-name="Purple"] .label::before) { content: "紫色" !important; font-size: 14px !important; }
:global([lang*="zh"] .affine-context-menu-item[data-name="Grey"] .label::before) { content: "灰色" !important; font-size: 14px !important; }
:global([lang*="zh"] .affine-context-menu-item[data-name="Default Color"] .label::before) { content: "默认颜色" !important; font-size: 14px !important; }
:global([lang*="zh"] .affine-context-menu-item[data-name="Default Background"] .label::before) { content: "默认背景" !important; font-size: 14px !important; }

/* 颜色选择器分组标题中文化 - 适配 BlockSuite 结构 */
:global([lang*="zh"] .affine-context-menu-group-title) {
  font-size: 0 !important;
  padding: 8px 12px 4px !important;
}
:global([lang*="zh"] .affine-context-menu-group-title::before) {
  font-size: 11px !important;
  color: #999;
  font-weight: 600;
  text-transform: uppercase;
}
/* 第一个标题通常是 Color,第二个是 Background */
:global([lang*="zh"] .affine-context-menu-group-title:first-of-type::before) { content: "文字颜色" !important; }
:global([lang*="zh"] .affine-context-menu-group-title:nth-of-type(2)::before) { content: "背景颜色" !important; }

:global([lang*="zh"] .affine-context-menu-item::before) {
  font-size: 14px !important;
  opacity: 1 !important;
  width: auto !important;
  height: auto !important;
  visibility: visible !important;
  display: inline-block !important;
}

:global([lang*="zh"] [data-name="Copy"]::before),
:global([lang*="zh"] .affine-context-menu-item[data-name="Copy"]::before) { content: "复制" !important; }

:global([lang*="zh"] [data-name="Copy link to block"]::before),
:global([lang*="zh"] .affine-context-menu-item[data-name="Copy link to block"]::before) { content: "复制块链接" !important; }

:global([lang*="zh"] [data-name="Duplicate"]::before),
:global([lang*="zh"] .affine-context-menu-item[data-name="Duplicate"]::before) { content: "复刻" !important; }

:global([lang*="zh"] [data-name="Delete"]::before),
:global([lang*="zh"] .affine-context-menu-item[data-name="Delete"]::before) { content: "删除" !important; }

:global([lang*="zh"] [data-name="Move to"]::before),
:global([lang*="zh"] .affine-context-menu-item[data-name="Move to"]::before) { content: "移动到" !important; }

:global([lang*="zh"] [data-name="Turn into"]::before),
:global([lang*="zh"] .affine-context-menu-item[data-name="Turn into"]::before) { content: "转换为" !important; }

:global([lang*="zh"] [data-name="Group"]::before),
:global([lang*="zh"] .affine-context-menu-item[data-name="Group"]::before) { content: "组合" !important; }

:global([lang*="zh"] [data-name="Ungroup"]::before),
:global([lang*="zh"] .affine-context-menu-item[data-name="Ungroup"]::before) { content: "取消组合" !important; }

/* 强制中文化 Toolbar 中的 Ask AI 文本 */
:global([lang*="zh"] .ask-ai-btn-wrapper span:last-child) { font-size: 0 !important; }
:global([lang*="zh"] .ask-ai-btn-wrapper span:last-child::before) { content: "问问 AI" !important; font-size: 14px !important; }

/* 参考文献管理区域样式 */
.main-content-area.with-references {
  height: calc(100vh - 120px);
}

.reference-section {
  border-top: 1px solid #e0e0e0;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;
  z-index: 100;
  flex-shrink: 0;
  min-height: 200px;
}

:global([data-theme='dark']) .reference-section {
  background-color: #1e1e1e;
  border-top-color: #333;
}

.resize-handle {
  height: 4px;
  width: 100%;
  cursor: row-resize;
  background: transparent;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
  transition: background 0.2s;
}

.resize-handle:hover {
  background: #1890ff;
}

.reference-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px;
  background-color: transparent;
  border-bottom: 1px solid #e0e0e0;
  flex-shrink: 0;
}

:global([data-theme='dark']) .reference-toolbar {
  background: #252526;
  border-bottom-color: #333;
}

.reference-toolbar .toolbar-left {
  display: flex;
  gap: 8px;
}

.reference-toolbar .toolbar-btn {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  border-radius: 4px;
  background: none;
  color: #333;
  cursor: pointer;
  transition: all 0.2s;
  padding: 6px;
}

:global([data-theme='dark']) .reference-toolbar .toolbar-btn {
  color: #ccc;
}

.reference-toolbar .toolbar-btn:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

:global([data-theme='dark']) .reference-toolbar .toolbar-btn:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.reference-toolbar .toolbar-btn:active {
  transform: scale(0.95);
}

.reference-toolbar .toolbar-btn i {
  font-size: 14px;
}

.reference-toolbar .ref-search-input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  width: 250px; /* 还原之前的窄宽度设计 */
  background-color: white;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  padding: 5px 12px;
  transition: border-color 0.2s;
  margin-left: 12px;
  flex: none; /* 关键:防止被 flex: 1 撑开 */
}

:global([data-theme='dark']) .reference-toolbar .ref-search-input-wrapper {
  background-color: #2d2d2d;
  border-color: #444;
}

.reference-toolbar .ref-search-input-wrapper:focus-within {
  border-color: #1890ff;
}

.reference-toolbar .search-icon {
  color: #999;
  margin-right: 8px;
  font-size: 14px;
}

.reference-toolbar .search-input {
  flex: 1;
  border: none;
  outline: none;
  background: transparent;
  color: #333;
  font-size: 14px;
  padding: 0;
}

:global([data-theme='dark']) .reference-toolbar .search-input {
  color: #eee;
}

.reference-section * {
  box-sizing: border-box;
}

.reference-table-container {
  flex: 1;
  overflow: auto;
  border-top: none;
  background-color: white;
}

:global([data-theme='dark']) .reference-table-container {
  background-color: #1e1e1e;
}

.reference-table {
  width: 100%;
  min-width: 800px;
  border-collapse: collapse;
  font-size: 13px;
  table-layout: fixed;
}

.reference-table thead {
  background-color: #f5f5f5;
  position: sticky;
  top: 0;
  z-index: 1;
}

:global([data-theme='dark']) .reference-table thead {
  background-color: #2d2d2d;
}

.reference-table th {
  padding: 12px 8px;
  text-align: left;
  font-weight: 600;
  color: #333;
  border-bottom: 1px solid #e0e0e0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

:global([data-theme='dark']) .reference-table th {
  color: #aaa;
  border-bottom-color: #333;
}

.reference-table th:first-child { width: 60px; }
.reference-table th:nth-child(2) { width: auto; min-width: 200px; }
.reference-table th:nth-child(3) { width: 140px; }
.reference-table th:nth-child(4) { width: 150px; }
.reference-table th:nth-child(5) { width: 80px; }
.reference-table th:last-child { width: 80px; }

.reference-table tbody tr {
  height: 42px;
  transition: background-color 0.2s;
  cursor: move;
}

.reference-table tbody tr:hover {
  background-color: rgba(0, 0, 0, 0.04);
}

:global([data-theme='dark']) .reference-table tbody tr:hover {
  background-color: rgba(255, 255, 255, 0.04);
}

.reference-table tbody tr.highlighted {
  background-color: rgba(24, 144, 255, 0.1);
  outline: none;
}

.reference-table tbody tr:focus {
  outline: none;
  background-color: rgba(24, 144, 255, 0.15);
}

:global([data-theme='dark']) .reference-table tbody tr:focus {
  background-color: rgba(24, 144, 255, 0.2);
}

:global([data-theme='dark']) .reference-table tbody tr.highlighted {
  background-color: rgba(24, 144, 255, 0.15);
}

.reference-table tbody tr:active {
  opacity: 0.7;
  cursor: grabbing;
}

.reference-table td {
  padding: 8px;
  color: #333;
  vertical-align: middle;
  border-bottom: 1px solid #f0f0f0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap; /* 极致还原:强制不换行 */
  height: 42px;
  box-sizing: border-box;
}

:global([data-theme='dark']) .reference-table td {
  color: #ccc;
  border-bottom-color: #333;
}

.reference-table .title-text,
.reference-table .alias-text {
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.4;
}

.alias-display {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.edit-alias-btn {
  display: none;
  background: none;
  border: none;
  color: #999;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.2s;
}

.alias-display:hover .edit-alias-btn {
  display: flex;
}

.edit-alias-btn:hover {
  background-color: rgba(0, 0, 0, 0.05);
  color: #1890ff;
}

.alias-edit {
  padding: 0 8px;
}

.alias-input {
  width: 100%;
  padding: 4px 8px;
  border: 1px solid #1890ff;
  border-radius: 4px;
  outline: none;
  font-size: 12px;
  background: white;
}

.detail-icons {
  display: flex;
  gap: 12px;
  justify-content: flex-start;
  align-items: center;
  height: 100%;
}

.detail-icons i {
  font-size: 14px;
  cursor: pointer;
  transition: color 0.2s;
}

.detail-icons i.icon-info { color: #1890ff; }
.detail-icons i.icon-copy { color: #52c41a; }
.detail-icons i.icon-delete { color: #ff4d4f; }

.detail-icons i:hover {
  opacity: 0.7;
}

.detail-icons .icon-delete:hover {
  color: #ff4d4f;
}

.reference-loading, .reference-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: #999;
}

.empty-icon, .loading-icon {
  font-size: 32px;
  margin-bottom: 12px;
}

/* 参考文献详情 */
.reference-detail-content {
  padding: 10px;
  max-height: 500px;
  overflow-y: auto;
}

.detail-item {
  margin-bottom: 12px;
}

.detail-label {
  font-weight: 600;
  font-size: 12px;
  color: #888;
  margin-bottom: 4px;
}

.detail-value {
  font-size: 13px;
  line-height: 1.5;
  word-break: break-all;
}

.detail-value.abstract {
  font-size: 12px;
  color: #666;
  text-align: justify;
}

/* 导入对话框 */
.import-dialog-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.import-method-group {
  margin-bottom: 10px;
}

.search-results-section {
  border: 1px solid #eee;
  border-radius: 8px;
  max-height: 300px;
  overflow-y: auto;
}

.result-item {
  padding: 12px;
  border-bottom: 1px solid #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 15px;
}

.result-item:last-child {
  border-bottom: none;
}

.result-content {
  flex: 1;
  overflow: hidden;
}

.result-title {
  font-weight: 600;
  font-size: 14px;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.result-meta {
  font-size: 12px;
  color: #999;
}

.no-results {
  text-align: center;
  padding: 20px;
  color: #999;
}

/* 导出对话框 */
.export-section {
  margin-bottom: 20px;
}

.export-section label {
  display: block;
  font-weight: 600;
  margin-bottom: 10px;
}

/* 拖拽预览 */
:global(.reference-drag-preview) {
  pointer-events: none;
  background: #e6f7ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 13px;
  font-weight: 500;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

/* 极致体验优化:参考文献引用标签 (Citation Tag) 视觉还原 (同步 Vditor) */
:deep(.citation-tag) {
  display: inline-block !important;
  padding: 2px 8px !important;
  background-color: #e6f7ff !important;
  border-radius: 4px !important;
  color: #1890ff !important;
  font-size: 13px !important;
  font-weight: 500 !important;
  cursor: pointer !important;
  transition: all 0.2s !important;
  white-space: nowrap !important;
  vertical-align: baseline;
  line-height: 1.4;
  margin: 0 2px;
  /* 隐藏原始的 textContent (markdown 格式) */
  font-size: 0 !important;
}

:deep(.citation-tag::before) {
  content: attr(data-display-text);
  font-size: 13px;
  color: #1890ff;
  font-weight: 500;
}

:deep(.citation-tag:hover) {
  background-color: rgba(24, 144, 255, 0.2) !important;
}

/* 隐藏原始标记文本但保留在 DOM 中供编辑器识别 */
:deep(.citation-tag-content) {
  font-size: 0 !important;
  line-height: 0 !important;
  opacity: 0 !important;
  position: absolute !important;
  pointer-events: none !important;
}

:global([data-theme='dark']) :deep(.citation-tag) {
  background-color: rgba(24, 144, 255, 0.15) !important;
  border: 1px solid rgba(24, 144, 255, 0.3) !important;
  color: #40a9ff !important;
}

:global([data-theme='dark']) :deep(.citation-tag::before) {
  color: #40a9ff !important;
}

/* 极致体验:图片点击查看 (Lightbox 模拟样式) */
:deep(.affine-image-block-container img) {
  cursor: zoom-in !important;
  transition: transform 0.2s ease !important;
}

:deep(.affine-image-block-container img:active) {
  transform: scale(0.98) !important;
}

:deep(.affine-paragraph-placeholder) {
  color: #bfbfbf !important;
}

:global(.ai-result-message-box) {
  max-width: 600px !important;
  width: 90% !important;
}

:global(.ai-result-message-box .el-message-box__content) {
  max-height: 400px;
  overflow-y: auto;
  white-space: pre-wrap;
  font-family: var(--affine-font-family);
  line-height: 1.6;
  background: #f9f9f9;
  padding: 15px !important;
  border-radius: 4px;
  margin: 10px 0;
  border: 1px solid #eee;
}

:global(.ai-confirm-btn) {
  background-color: var(--affine-primary-color) !important;
  border-color: var(--affine-primary-color) !important;
}

:global(.ai-cancel-btn:hover) {
  color: var(--affine-primary-color) !important;
  border-color: var(--affine-primary-color) !important;
  background-color: var(--affine-hover-color, #f0f7ff) !important;
}

/* 引用切换菜单样式 */
:global(.citation-menu-wrapper) {
  position: fixed;
  z-index: 10001;
  animation: citation-menu-fade-in 0.2s ease-out;
}

@keyframes citation-menu-fade-in {
  from { opacity: 0; transform: translateY(-5px); }
  to { opacity: 1; transform: translateY(0); }
}

:global(.citation-menu) {
  background: #ffffff;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 6px 0;
  min-width: 280px;
  max-width: 400px;
  max-height: 400px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

:global(.citation-menu-header) {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 8px 16px;
  border-bottom: 1px solid #e4e7ed;
}

:global(.citation-menu-header .header-title) {
  font-size: 12px;
  color: #909399;
  font-weight: 500;
  white-space: nowrap;
}

:global(.citation-menu-header .header-search) {
  position: relative;
  display: flex;
  align-items: center;
  flex: 1;
  max-width: 200px;
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 4px 8px;
  transition: all 0.2s;
}

:global(.citation-menu-header .header-search:focus-within) {
  border-color: #1890ff;
  background-color: #ffffff;
}

:global(.citation-menu-header .header-search .search-icon) {
  color: #909399;
  font-size: 12px;
  margin-right: 6px;
  flex-shrink: 0;
}

:global(.citation-menu-header .header-search .search-input) {
  flex: 1;
  border: none;
  outline: none;
  background: transparent;
  color: #303133;
  font-size: 12px;
  min-width: 0;
}

:global(.citation-menu-header .header-search .search-input::placeholder) {
  color: #c0c4cc;
}

:global(.citation-menu-list) {
  flex: 1;
  overflow-y: auto;
  max-height: 340px;
}

:global(.citation-menu-list::-webkit-scrollbar) {
  width: 6px;
}

:global(.citation-menu-list::-webkit-scrollbar-thumb) {
  background: #dcdfe6;
  border-radius: 3px;
}

:global(.citation-menu-list::-webkit-scrollbar-thumb:hover) {
  background: #c0c4cc;
}

:global(.citation-menu-item) {
  padding: 10px 16px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

:global(.citation-menu-item:hover) {
  background: #f5f7fa;
}

:global(.citation-menu-item:active) {
  background: #e6f7ff;
}

:global(.citation-menu-item .menu-item-note) {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
  line-height: 1.4;
  word-break: break-all;
  white-space: normal;
}

:global(.citation-menu-item .menu-item-meta) {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
  word-break: break-all;
  white-space: normal;
}

:global(.citation-menu-empty) {
  padding: 20px;
  text-align: center;
  color: #909399;
  font-size: 13px;
}

/* 深色模式支持 */
:global([data-theme='dark'] .citation-menu) {
  background: #1e1e1e;
  border-color: #3a3a3a;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.4);
}

:global([data-theme='dark'] .citation-menu-header) {
  border-bottom-color: #3a3a3a;
}

:global([data-theme='dark'] .citation-menu-header .header-title) {
  color: #a0a0a0;
}

:global([data-theme='dark'] .citation-menu-header .header-search) {
  background-color: #2a2a2a;
  border-color: #3a3a3a;
}

:global([data-theme='dark'] .citation-menu-header .header-search:focus-within) {
  border-color: #1890ff;
  background-color: #1e1e1e;
}

:global([data-theme='dark'] .citation-menu-header .header-search .search-icon) {
  color: #666;
}

:global([data-theme='dark'] .citation-menu-header .header-search .search-input) {
  color: #e0e0e0;
}

:global([data-theme='dark'] .citation-menu-header .header-search .search-input::placeholder) {
  color: #666;
}

:global([data-theme='dark'] .citation-menu-list::-webkit-scrollbar-thumb) {
  background: #4a4a4a;
}

:global([data-theme='dark'] .citation-menu-list::-webkit-scrollbar-thumb:hover) {
  background: #5a5a5a;
}

:global([data-theme='dark'] .citation-menu-item:hover) {
  background: #2a2a2a;
}

:global([data-theme='dark'] .citation-menu-item:active) {
  background: rgba(24, 144, 255, 0.15);
}

:global([data-theme='dark'] .citation-menu-item .menu-item-note) {
  color: #e0e0e0;
}

:global([data-theme='dark'] .citation-menu-item .menu-item-meta) {
  color: #808080;
}

:global([data-theme='dark'] .citation-menu-empty) {
  color: #808080;
}

/* 引用弹窗样式 - 同步自 DeerFlowChat.vue */
:global(.citation-modal) {
  position: fixed;
  z-index: 10000;
  max-width: 500px;
  min-width: 300px;
  width: auto;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  opacity: 0;
  transform: translateY(-5px);
  transition: opacity 0.2s ease-out, transform 0.2s ease-out;
  pointer-events: none;
  overflow: hidden;
}

:global(.citation-modal.show) {
  opacity: 1;
  transform: translateY(0);
  pointer-events: auto;
}

:global(.citation-modal-header) {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  border-radius: 12px 12px 0 0;
  background: #1890ff;
}

:global(.citation-modal-title) {
  font-size: 13px;
  font-weight: 500;
  color: #fff;
  background: rgba(255, 255, 255, 0.2);
  line-height: 1.5;
  padding: 2px 6px;
  border-radius: 4px;
}

:global(.citation-modal-close) {
  background: none;
  border: none;
  color: #fff;
  font-size: 16px;
  cursor: pointer;
  padding: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: opacity 0.2s;
  width: 24px;
  height: 24px;
  border-radius: 4px;
}

:global(.citation-modal-close:hover) {
  background: rgba(255, 255, 255, 0.2);
}

:global(.citation-modal-body) {
  padding: 16px;
  max-height: 400px;
  overflow-y: auto;
}

:global(.citation-modal-content-text) {
  font-size: 13px;
  color: #333;
  line-height: 1.8;
  text-align: justify;
  font-family: "Times New Roman", "SimSun", "FangSong", serif;
  word-wrap: break-word;
}

:global(.citation-modal-content-text .citation-author) {
  color: #333;
}

:global(.citation-modal-content-text .title-bold) {
  font-weight: 700 !important;
  color: #333 !important;
}

:global(.citation-modal-content-text .journal-style) {
  font-weight: 700 !important;
  color: #0066cc !important;
  font-style: italic !important;
}

:global(.citation-modal-content-text .citation-other) {
  color: #666;
}

:global(.citation-modal-footer) {
  padding: 12px 16px;
  border-top: 1px solid #e5e7eb;
  display: flex;
  justify-content: flex-end;
}

:global(.citation-modal-link) {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  color: #1890ff;
  font-size: 13px;
  text-decoration: none;
  transition: color 0.2s;
  padding: 4px 8px;
  border-radius: 4px;
}

:global(.citation-modal-link:hover) {
  color: #40a9ff;
  background: rgba(24, 144, 255, 0.08);
}

/* 深色模式适配 */
:global([data-theme='dark'] .citation-modal) {
  background: #1f1f1f;
  border: 1px solid #333;
}

:global([data-theme='dark'] .citation-modal-content-text) {
  color: #e0e0e0;
}

:global([data-theme='dark'] .citation-modal-content-text .citation-author),
:global([data-theme='dark'] .citation-modal-content-text .title-bold) {
  color: #e0e0e0 !important;
}

:global([data-theme='dark'] .citation-modal-content-text .journal-style) {
  color: #4a9eff !important;
}

:global([data-theme='dark'] .citation-modal-content-text .citation-other) {
  color: #aaa;
}

:global([data-theme='dark'] .citation-modal-footer) {
  border-top-color: #333;
}
</style>