script.js 35.6 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
"use strict";
let mapping = {};
const dbStorage = {
  dbName: "vvSearchCache",
  dbVersion: 1,
  async init() {
    if (this._dbPromise) return this._dbPromise;
    this._dbPromise = new Promise((resolve, reject) => {
      const request = indexedDB.open(this.dbName, this.dbVersion);
      request.onerror = (event) => {
        reject(event.target.error);
      };
      request.onsuccess = (event) => {
        this.db = event.target.result;
        resolve(this.db);
      };
      request.onupgradeneeded = (event) => {
        const db = event.target.result;
        if (!db.objectStoreNames.contains("indices"))
          db.createObjectStore("indices", { keyPath: "key" });
        if (!db.objectStoreNames.contains("mappings"))
          db.createObjectStore("mappings", { keyPath: "key" });
        if (!db.objectStoreNames.contains("databases"))
          db.createObjectStore("databases", { keyPath: "key" });
      };
    });
    return this._dbPromise;
  },
  async getItem(storeName, key) {
    try {
      await this.init();
      return new Promise((resolve, reject) => {
        const transaction = this.db.transaction(storeName, "readonly");
        const store = transaction.objectStore(storeName);
        const request = store.get(key);
        request.onsuccess = () => {
          resolve(request.result ? request.result.value : null);
        };
        request.onerror = (event) => {
          reject(event.target.error);
        };
      });
    } catch (error) {
      return null;
    }
  },
  async setItem(storeName, key, value) {
    try {
      await this.init();
      return new Promise((resolve, reject) => {
        const transaction = this.db.transaction(storeName, "readwrite");
        const store = transaction.objectStore(storeName);
        const request = store.put({ key, value });
        request.onsuccess = () => {
          resolve();
        };
        request.onerror = (event) => {
          reject(event.target.error);
        };
      });
    } catch (error) {
      throw error;
    }
  },
  async removeItem(storeName, key) {
    try {
      await this.init();
      return new Promise((resolve, reject) => {
        const transaction = this.db.transaction(storeName, "readwrite");
        const store = transaction.objectStore(storeName);
        const request = store.delete(key);
        request.onsuccess = () => {
          resolve();
        };
        request.onerror = (event) => {
          reject(event.target.error);
        };
      });
    } catch (error) {
      throw error;
    }
  },
  async getAllKeys(storeName) {
    try {
      await this.init();
      return new Promise((resolve, reject) => {
        const transaction = this.db.transaction(storeName, "readonly");
        const store = transaction.objectStore(storeName);
        const request = store.getAllKeys();
        request.onsuccess = () => {
          resolve(request.result);
        };
        request.onerror = (event) => {
          reject(event.target.error);
        };
      });
    } catch (error) {
      return [];
    }
  },
};
const RequestController = {
  queue: new Map(),
  maxConcurrent: 4,

  async enqueue(key, requestFn) {
    if (this.queue.has(key)) {
      return this.queue.get(key);
    }
    while (this.queue.size >= this.maxConcurrent) {
      await new Promise((resolve) => setTimeout(resolve, 50));
    }

    const promise = requestFn().finally(() => {
      this.queue.delete(key);
    });

    this.queue.set(key, promise);
    return promise;
  },
};
const indexCache = {
  data: new Map(),
  preloadQueue: new Set(),
  preloadPromises: new Map(),

  async get(groupIndex, baseDir) {
    const cacheKey = `${baseDir}/${groupIndex}`;

    if (this.data.has(cacheKey)) {
      return this.data.get(cacheKey);
    }

    if (this.preloadPromises.has(cacheKey)) {
      return this.preloadPromises.get(cacheKey);
    }

    return RequestController.enqueue(cacheKey, async () => {
      try {
        if (this.data.has(cacheKey)) {
          return this.data.get(cacheKey);
        }

        const cachedData = await dbStorage.getItem("indices", cacheKey);
        if (cachedData) {
          const arrayBuffer = this._base64ToArrayBuffer(cachedData);
          this.data.set(cacheKey, arrayBuffer);
          return arrayBuffer;
        }

        const indexData = await this._fetchIndex(groupIndex, baseDir);
        this.data.set(cacheKey, indexData);

        this._saveToCache(cacheKey, indexData).catch(() => {});

        return indexData;
      } catch (error) {
        console.error(`Failed to load index ${cacheKey}:`, error);
        throw error;
      }
    });
  },

  async _saveToCache(cacheKey, data) {
    const base64Data = this._arrayBufferToBase64(data);
    await dbStorage.setItem("indices", cacheKey, base64Data);
  },

  async preload(groupIndex, baseDir) {
    const cacheKey = `${baseDir}/${groupIndex}`;
    if (this.data.has(cacheKey) || this.preloadQueue.has(cacheKey)) {
      return;
    }

    this.preloadQueue.add(cacheKey);
    const promise = this.get(groupIndex, baseDir)
      .catch(() => {})
      .finally(() => {
        this.preloadQueue.delete(cacheKey);
        this.preloadPromises.delete(cacheKey);
      });

    this.preloadPromises.set(cacheKey, promise);
  },

  async _fetchIndex(groupIndex, baseDir) {
    const cacheKey = `${baseDir}/${groupIndex}`;

    const indexUrl = `${baseDir}/${groupIndex}.index`;

    try {
      const indexResponse = await fetch(indexUrl, {
        method: "GET",
        mode: "cors",
        credentials: "omit",
        cache: "no-cache",
        headers: {
          Accept: "application/octet-stream",
        },
        referrerPolicy: "no-referrer",
      });

      if (!indexResponse.ok) {
        throw new Error(
          `Failed to fetch index: ${indexResponse.status} ${indexResponse.statusText}`,
        );
      }

      const headers = Object.fromEntries(indexResponse.headers.entries());
      const contentType = headers["content-type"];

      const compressedData = await indexResponse.arrayBuffer();

      if (compressedData.byteLength === 0) {
        throw new Error("Received empty response");
      }

      const header = new Uint8Array(compressedData.slice(0, 2));

      let decompressedData;

      if (header[0] === 0x1f && header[1] === 0x8b) {
        try {
          const ds = new DecompressionStream("gzip");
          const decompressedStream = new Response(
            compressedData,
          ).body.pipeThrough(ds);
          decompressedData = await new Response(
            decompressedStream,
          ).arrayBuffer();
        } catch (error) {
          console.error("Decompression failed:", error);
          throw error;
        }
      } else {
        decompressedData = compressedData;
      }

      if (decompressedData.byteLength < 16) {
        throw new Error("Data too small");
      }

      const view = new DataView(decompressedData);
      const gridW = view.getUint32(0, true);
      const gridH = view.getUint32(4, true);
      const folderCount = view.getUint32(8, true);

      if (gridW === 0 || gridH === 0 || folderCount === 0) {
        throw new Error("Invalid index format");
      }

      return decompressedData;
    } catch (error) {
      console.error(`Failed to fetch or process index ${indexUrl}:`, error);
      throw error;
    }
  },

  _arrayBufferToBase64(buffer) {
    const binary = [];
    const bytes = new Uint8Array(buffer);
    for (let i = 0; i < bytes.byteLength; i++)
      binary.push(String.fromCharCode(bytes[i]));
    return btoa(binary.join(""));
  },

  _base64ToArrayBuffer(base64) {
    const binaryString = atob(base64);
    const len = binaryString.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) bytes[i] = binaryString.charCodeAt(i);
    return bytes.buffer;
  },

  _cleanupLocalStorage() {
    try {
      const cacheKeys = [];
      for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i);
        if (key.startsWith("indexCache_")) cacheKeys.push(key);
      }
      if (cacheKeys.length > 20)
        for (let i = 0; i < 5; i++) localStorage.removeItem(cacheKeys[i]);
    } catch (e) {}
  },
};
const watermarkImage = new Image();
watermarkImage.src = "watermark.png";
let watermarkLoaded = false;
watermarkImage.onload = () => {
  watermarkLoaded = true;
};
async function extractFrame(folderId, frameNum, baseDir = "") {
  const groupIndex = Math.floor((folderId - 1) / 10);
  const requestKey = `${baseDir}/${groupIndex}/${folderId}/${frameNum}`;

  return RequestController.enqueue(requestKey, async () => {
    try {
      if (!baseDir) {
        throw new Error("Base directory is required");
      }

      const indexData = await indexCache.get(groupIndex, baseDir);

      const dataView = new DataView(indexData);
      let offset = 0;

      const gridW = dataView.getUint32(offset, true);
      offset += 4;
      const gridH = dataView.getUint32(offset, true);
      offset += 4;
      const folderCount = dataView.getUint32(offset, true);
      offset += 4;
      offset += folderCount * 4;
      const fileCount = dataView.getUint32(offset, true);
      offset += 4;

      let left = 0;
      let right = fileCount - 1;
      let startOffset = null;
      let endOffset = null;

      while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        const recordOffset = offset + mid * 16;
        const currFolder = dataView.getUint32(recordOffset, true);
        const currFrame = dataView.getUint32(recordOffset + 4, true);
        const currFileOffset = Number(
          dataView.getBigUint64(recordOffset + 8, true),
        );

        if (currFolder === folderId && currFrame === frameNum) {
          startOffset = currFileOffset;
          if (mid < fileCount - 1) {
            endOffset = Number(dataView.getBigUint64(recordOffset + 24, true));
          }
          break;
        } else if (
          currFolder < folderId ||
          (currFolder === folderId && currFrame < frameNum)
        ) {
          left = mid + 1;
        } else {
          right = mid - 1;
        }
      }

      if (startOffset === null) {
        throw new Error(`Frame ${frameNum} not found in folder ${folderId}`);
      }

      const imageUrl = `${baseDir}/${groupIndex}.webp`;

      const response = await fetch(imageUrl, {
        method: "GET",
        headers: {
          Range: `bytes=${startOffset}-${endOffset ? endOffset - 1 : ""}`,
        },
        mode: "cors",
        credentials: "omit",
        referrerPolicy: "no-referrer",
      });

      if (response.status === 416 || !response.ok) {
        const fullResponse = await fetch(imageUrl, {
          method: "GET",
          mode: "cors",
          credentials: "omit",
          referrerPolicy: "no-referrer",
        });

        if (!fullResponse.ok) {
          throw new Error(
            `HTTP error: ${fullResponse.status} ${fullResponse.statusText}`,
          );
        }

        return new Blob([await fullResponse.blob()], { type: "image/webp" });
      }

      const data = await response.blob();
      if (!data || data.size === 0) {
        throw new Error("Empty response");
      }

      return new Blob([data], { type: "image/webp" });
    } catch (error) {
      console.error(
        `Error extracting frame ${frameNum} from folder ${folderId}:`,
        error,
      );
      throw new Error(`Failed to load preview image: ${error.message}`);
    }
  });
}
async function loadMapping() {
  try {
    const cachedMapping = await dbStorage.getItem("mappings", "mapping");
    if (cachedMapping) return cachedMapping;
    try {
      const localMapping = localStorage.getItem("mapping");
      if (localMapping) {
        const mappingData = JSON.parse(localMapping);
        try {
          await dbStorage.setItem("mappings", "mapping", mappingData);
          localStorage.removeItem("mapping");
        } catch (e) {}
        return mappingData;
      }
    } catch (e) {}
    const response = await fetch("./mapping.json", {
      referrerPolicy: "no-referrer",
      mode: "cors",
      credentials: "omit",
    });
    if (!response.ok) throw new Error("Failed to load mapping.json");
    const mappingData = await response.json();
    try {
      await dbStorage.setItem("mappings", "mapping", mappingData);
    } catch (e) {
      try {
        localStorage.setItem("mapping", JSON.stringify(mappingData));
      } catch (e) {}
    }
    return mappingData;
  } catch (error) {
    return {};
  }
}
const AppState = {
  isSearching: false,
  randomStringDisplayed: false,
  searchResults: [],
  currentPage: 1,
  itemsPerPage: 20,
  hasMoreResults: true,
  cachedResults: [],
  displayedCount: 0,
  showWatermark: true,
  dbLoaded: false,
  dbLoading: false,
};
const CONFIG = {
  randomStrings: [
    "\u63a2\u7d22VV\u7684\u5f00\u6e90\u4e16\u754c",
    "\u4e3a\u4e1c\u5927\u52a9\u529b",
    "\u641c\u7d22\u4f60\u60f3\u8981\u7684\u5185\u5bb9",
  ],
  apiBaseUrl: "https://vvapi.cicada000.work",
  semanticApiUrl: "https://vvapi.cicada000.work",
  imageBaseUrl: "https://vv.noxylva.org",
  watermarkPath: "watermark.png",
  indexPreloadCount: 26
};
class UIController {
  static updateSearchFormPosition(isSearching) {
    const searchForm = document.getElementById("searchForm");
    const randomStringDisplay = document.getElementById("randomStringDisplay");
    if (isSearching) {
      searchForm.classList.add("searching");
      if (!AppState.randomStringDisplayed) this.showRandomString();
    } else {
      searchForm.classList.remove("searching");
      this.clearRandomString();
    }
  }
  static showRandomString() {
    if (!AppState.randomStringDisplayed) {
      const randomStringDisplay = document.getElementById(
        "randomStringDisplay",
      );
      const randomIndex = Math.floor(
        Math.random() * CONFIG.randomStrings.length,
      );
      randomStringDisplay.textContent = CONFIG.randomStrings[randomIndex];
      AppState.randomStringDisplayed = true;
      randomStringDisplay.classList.remove("fade-out");
      randomStringDisplay.classList.add("fade-in");
    }
  }
  static clearRandomString() {
    const randomStringDisplay = document.getElementById("randomStringDisplay");
    randomStringDisplay.classList.remove("fade-in");
    randomStringDisplay.classList.add("fade-out");
    setTimeout(() => {
      randomStringDisplay.textContent = "";
      AppState.randomStringDisplayed = false;
    }, 300);
  }
}
class SearchController {
  static validateSearchInput(query) {
    return query && query.trim().length > 0;
  }

  static async performSearch(query, minRatio, minSimilarity) {
    const isSemanticSearch = document
      .getElementById("semanticToggle")
      .classList.contains("active");
    if (!isSemanticSearch) {
      if (window.subtitleDB && window.subtitleDB.isLoaded) {
        try {
          const localResults = await window.subtitleDB.search(
            query,
            minRatio,
            minSimilarity,
          );

          if (localResults && Array.isArray(localResults)) {
            return {
              status: "success",
              data: localResults,
              count: localResults.length,
            };
          } else if (
            localResults &&
            localResults.status === "success" &&
            Array.isArray(localResults.data)
          ) {
            return localResults;
          }
        } catch (error) {
          console.log("本地搜索失败,使用vvapi", error);
        }
      }

      const vvapiUrl = `${CONFIG.apiBaseUrl}/search?query=${encodeURIComponent(query)}&min_ratio=${minRatio}&min_similarity=${minSimilarity}`;

      try {
        console.log("使用普通搜索:", vvapiUrl);
        const response = await fetch(vvapiUrl);
        if (!response.ok)
          throw new Error(
            `API 请求失败: ${response.status} ${response.statusText}`,
          );

        const text = await response.text();
        const lines = text.trim().split("\n");
        const results = [];

        for (const line of lines) {
          try {
            if (line.trim()) {
              const item = JSON.parse(line);
              results.push(item);
            }
          } catch (e) {}
        }

        return {
          status: "success",
          data: results,
          count: results.length,
        };
      } catch (error) {
        throw error;
      }
    }

    const emuUrl = `${CONFIG.semanticApiUrl}/search?query=${encodeURIComponent(query)}&min_ratio=${minRatio}&min_similarity=${minSimilarity}&rag=true`;

    try {
      console.log("使用语义搜索:", emuUrl);
      const response = await fetch(emuUrl);
      if (!response.ok)
        throw new Error(
          `API 请求失败: ${response.status} ${response.statusText}`,
        );

      const text = await response.text();
      const lines = text.trim().split("\n");
      const results = [];

      for (const line of lines) {
        try {
          if (line.trim()) {
            const item = JSON.parse(line);
            
            if (item.filename && !item.filename.endsWith('.json')) {
              item.filename = item.filename + '.json';
            }
            
            results.push(item);
          }
        } catch (e) {}
      }

      return {
        status: "success",
        data: results,
        count: results.length,
      };
    } catch (error) {
      throw error;
    }
  }
}
async function handleSearch(event) {
  event.preventDefault();
  const query = document.getElementById("query").value.trim();
  if (!query) return;
  const minRatio = parseInt(document.getElementById("minRatio").value) || 50;
  const minSimilarity =
    parseFloat(document.getElementById("minSimilarity").value) || 0;
  const searchForm = document.getElementById("searchForm");
  searchForm.classList.add("searching");
  startNaturalLoadingBar();

  try {
    const results = await SearchController.performSearch(
      query,
      minRatio,
      minSimilarity,
    );

    if (results && results.status === "success") {
      AppState.cachedResults = results.data;
      AppState.hasMoreResults = results.data.length > AppState.itemsPerPage;
      AppState.displayedCount = 0;

      displayResults(results);
      completeLoadingBar();
    } else {
      throw new Error("Invalid search results format");
    }
  } catch (error) {
    console.error("Search error:", error);
    document.getElementById("errorDisplay").textContent =
      `搜索失败: ${error.message}`;
    document.getElementById("errorDisplay").style.display = "block";
    completeLoadingBar();
  } finally {
    enableKeywordTags();
    searchForm.classList.remove("searching");
  }
}
async function initializeApp() {
  try {
    await dbStorage.init().catch((error) => {});
    mapping = await loadMapping();
    initializeScrollListener();

    for (let i = 0; i <= CONFIG.indexPreloadCount; i++) {
      indexCache.preload(i, CONFIG.imageBaseUrl).catch((error) => {});
    }

    if (
      window.subtitleDB &&
      !window.subtitleDB.isLoaded &&
      !window.subtitleDB.isLoading
    ) {
      window.subtitleDB
        .load()
        .then(() => {
          AppState.dbLoaded = true;
        })
        .catch((error) => {
          setTimeout(() => {
            window.subtitleDB.load().catch((err) => {});
          }, 3000);
        });
    }

    document
      .getElementById("searchForm")
      .addEventListener("submit", async (e) => {
        e.preventDefault();
        if (AppState.isSearching) return;
        AppState.isSearching = true;
        try {
          await handleSearch(e);
        } finally {
          AppState.isSearching = false;
        }
      });

    document.getElementById("query").addEventListener("keydown", (e) => {
      if (e.key === "Enter") {
        e.preventDefault();
        if (AppState.isSearching) return;
        document
          .getElementById("searchForm")
          .dispatchEvent(new Event("submit"));
      }
    });

    document
      .getElementById("refreshDiv")
      .addEventListener("click", function () {
        location.reload();
      });

    document
      .getElementById("semanticToggle")
      .addEventListener("click", function () {
        this.classList.toggle("active");
      });
  } catch (error) {}
}
document.addEventListener("DOMContentLoaded", () => {
  const loadingBar = document.getElementById("loadingBar");
  if (loadingBar) {
    loadingBar.style.width = "0%";
    loadingBar.style.display = "none";
  }
  initializeApp();
  const toggleButton = document.getElementById("toggleAdvancedOptions");
  const advancedOptions = document.getElementById("advancedOptions");
  toggleButton.addEventListener("click", () => {
    const isExpanded = advancedOptions.classList.contains("show");
    if (!isExpanded) {
      advancedOptions.style.transition = "none";
      advancedOptions.classList.add("show");
      const height = advancedOptions.scrollHeight;
      advancedOptions.classList.remove("show");
      void advancedOptions.offsetHeight;
      advancedOptions.style.transition = "";
      advancedOptions.style.maxHeight = height + "px";
      advancedOptions.classList.add("show");
    } else {
      advancedOptions.style.maxHeight = "0";
      advancedOptions.classList.remove("show");
    }
    toggleButton.classList.toggle("active");
    toggleButton.setAttribute("aria-expanded", !isExpanded);
  });
  
  const semanticToggle = document.getElementById("semanticToggle");
  const semanticTooltip = document.getElementById("semanticTooltip");
  
  semanticToggle.addEventListener("mouseenter", () => {
    semanticTooltip.classList.add("visible");
  });
  
  semanticToggle.addEventListener("mouseleave", () => {
    semanticTooltip.classList.remove("visible");
  });
  
  const watermarkToggle = document.getElementById("watermarkToggle");
  watermarkToggle.addEventListener("change", () => {
    AppState.showWatermark = watermarkToggle.checked;
    if (window.canvasRenderQueue)
      window.canvasRenderQueue.forEach((canvas) => {
        const ctx = canvas.getContext("2d");
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(canvas.originalCanvas, 0, 0);
        if (AppState.showWatermark && watermarkLoaded) {
          const watermarkScale = (canvas.width * 0.25) / watermarkImage.width;
          const watermarkWidth = watermarkImage.width * watermarkScale;
          const watermarkHeight = watermarkImage.height * watermarkScale;
          ctx.drawImage(
            watermarkImage,
            canvas.width - watermarkWidth - 5,
            canvas.height - watermarkHeight - 5,
            watermarkWidth,
            watermarkHeight,
          );
        }
      });
  });
});
function displayResults(data, append = false) {
  const resultsDiv = document.getElementById("results");
  const keywordsContainer = document.getElementById("keywordsContainer");

  document.getElementById("errorDisplay").style.display = "none";

  if (!append) {
    resultsDiv.innerHTML = "";
    AppState.displayedCount = 0;
    keywordsContainer.innerHTML = "";
    keywordsContainer.classList.remove("show");
  }

  if (!append && data.data.length > 0 && data.data[0].type === "keywords") {
    const keywords = data.data[0].keywords;
    if (keywords && keywords.length > 0) {
      keywordsContainer.innerHTML = `
        <div class="keywords-tags">
          ${keywords.map(keyword => `<span class="keyword-tag">${keyword}</span>`).join("")}
        </div>
      `;
      keywordsContainer.classList.add("show");
      
      keywordsContainer.querySelectorAll('.keyword-tag').forEach(tag => {
        tag.addEventListener('click', () => {
          if (AppState.isSearching) return;
          
          const keyword = tag.textContent;
          document.getElementById('query').value = keyword;
          
          keywordsContainer.querySelectorAll('.keyword-tag').forEach(t => {
            t.classList.add('disabled');
          });
          
          document.getElementById('searchForm').dispatchEvent(new Event('submit'));
        });
      });
    }
    
    data.data = data.data.slice(1);
  }

  if (data.data && data.data.length === 1 && data.data[0].count === 0) {
    const noResultData = data.data[0];
    console.log("No results case:", {
      message: noResultData.message,
      suggestions: noResultData.suggestions,
    });

    if (!append) {
      const message =
        noResultData.message ||
        `未找到与 "${document.getElementById("query").value.trim()}" 匹配的结果`;
      const suggestions = noResultData.suggestions || [
        "检查输入是否正确",
        `尝试降低最小匹配率(当前:${document.getElementById("minRatio").value}%)`,
        `尝试降低最小相似度(当前:${document.getElementById("minSimilarity").value})`,
        "尝试使用更简短的关键词",
      ];

      resultsDiv.innerHTML = `
                <div class="error-message">
                    <h3>${message}</h3>
                    <p>建议:</p>
                    <ul>
                        ${suggestions.map((suggestion) => `<li>${suggestion}</li>`).join("")}
                    </ul>
                </div>`;
    }
    AppState.hasMoreResults = false;
    return;
  }

  const fragment = document.createDocumentFragment();
  const startIndex = AppState.displayedCount;
  const endIndex = Math.min(
    startIndex + AppState.itemsPerPage,
    data.data.length,
  );
  const newResults = data.data.slice(startIndex, endIndex);

  AppState.hasMoreResults = endIndex < data.data.length;

  const cards = newResults
    .map((result) => {
      if (!result || typeof result !== "object") return null;
      const card = document.createElement("div");
      card.className = "result-card";
      card.addEventListener("click", () => handleCardClick(result));
      card.style.cursor = "pointer";

      const episodeMatch = result.filename
        ? result.filename.match(/\[P(\d+)\]/)
        : null;
      const timeMatch = result.timestamp
        ? result.timestamp.match(/^(\d+)m(\d+)s$/)
        : null;
      const cleanFilename = result.filename
        ? result.filename
            .replace(/\[P(\d+)\].*?\s+/, "P$1 ")
            .replace(/\.json$/, "")
            .trim()
        : "";

      const cardContent = `
            <div class="result-content">
                <h3>${episodeMatch ? `<span class="tag">${episodeMatch[1]}</span>${cleanFilename.replace(/P\d+/, "").trim()}` : cleanFilename}</h3>
                <p class="result-text">${result.text || ""}</p>
                ${
                  result.timestamp
                    ? `
                <p class="result-meta">
                    ${result.timestamp} \u00b7
                    \u5339\u914d\u5ea6 ${result.match_ratio ? parseFloat(result.match_ratio).toFixed(1) : 0}% \u00b7
                    \u76f8\u4f3c\u5ea6 ${result.similarity ? (result.similarity * 100).toFixed(1) : 0}%
                </p>`
                    : ""
                }
            </div>
        `;

      card.innerHTML = cardContent;
      return card;
    })
    .filter(Boolean);

  cards.forEach((card) => fragment.appendChild(card));
  resultsDiv.appendChild(fragment);

  requestAnimationFrame(() => {
    cards.forEach((card, index) => {
      const result = newResults[index];
      loadPreviewImage(card, result);
    });
  });

  AppState.displayedCount = endIndex;

  if (AppState.hasMoreResults) {
    let trigger = document.getElementById("scroll-trigger");
    if (!trigger) {
      trigger = document.createElement("div");
      trigger.id = "scroll-trigger";
      trigger.style.cssText = "height: 20px; margin: 20px 0;";

      if (window.currentObserver) {
        window.currentObserver.observe(trigger);
      }
    }
    resultsDiv.appendChild(trigger);
  }
}
async function loadPreviewImage(card, result) {
  const episodeMatch = result.filename?.match(/\[P(\d+)\]/);
  const timeMatch = result.timestamp?.match(/^(\d+)m(\d+)s$/);

  if (!episodeMatch || !timeMatch) return;

  const episodeNum = parseInt(episodeMatch[1], 10);
  const minutes = parseInt(timeMatch[1]);
  const seconds = parseInt(timeMatch[2]);
  const totalSeconds = minutes * 60 + seconds;

  const imgContainer = document.createElement("div");
  imgContainer.className = "preview-frame-container";

  const placeholder = document.createElement("div");
  placeholder.className = "preview-frame-placeholder";
  imgContainer.appendChild(placeholder);
  card.insertBefore(imgContainer, card.firstChild);

  try {
    const imageBlob = await extractFrame(
      episodeNum,
      totalSeconds,
      CONFIG.imageBaseUrl,
    );
    const imageUrl = URL.createObjectURL(imageBlob);
    const img = new Image();
    img.src = imageUrl;
    img.className = "preview-frame";
    img.decoding = "async";

    img.onerror = () => {
      console.error("Failed to load preview image");
      imgContainer.remove();
      URL.revokeObjectURL(imageUrl);
    };

    img.onload = () => {
      const originalCanvas = document.createElement("canvas");
      originalCanvas.width = img.width;
      originalCanvas.height = img.height;

      try {
        const originalCtx = originalCanvas.getContext("2d");
        if (!originalCtx) {
          throw new Error("Failed to get canvas context");
        }

        originalCtx.drawImage(img, 0, 0);

        const displayCanvas = document.createElement("canvas");
        displayCanvas.width = img.width;
        displayCanvas.height = img.height;
        displayCanvas.className = "preview-frame";
        displayCanvas.originalCanvas = originalCanvas;

        const renderCanvas = () => {
          const ctx = displayCanvas.getContext("2d");
          if (!ctx) {
            throw new Error("Failed to get display canvas context");
          }

          ctx.clearRect(0, 0, displayCanvas.width, displayCanvas.height);
          ctx.drawImage(originalCanvas, 0, 0);

          if (watermarkLoaded && AppState.showWatermark) {
            const watermarkScale =
              (displayCanvas.width * 0.25) / watermarkImage.width;
            const watermarkWidth = watermarkImage.width * watermarkScale;
            const watermarkHeight = watermarkImage.height * watermarkScale;
            ctx.drawImage(
              watermarkImage,
              displayCanvas.width - watermarkWidth - 5,
              displayCanvas.height - watermarkHeight - 5,
              watermarkWidth,
              watermarkHeight,
            );
          }
        };

        renderCanvas();

        if (!window.canvasRenderQueue) {
          window.canvasRenderQueue = new Set();
        }
        window.canvasRenderQueue.add(displayCanvas);

        displayCanvas.addEventListener("click", (e) => {
          e.stopPropagation();
          displayCanvas.toBlob((blob) => {
            if (!blob) {
              console.error("Failed to create image blob");
              return;
            }
            const url = URL.createObjectURL(blob);
            const a = document.createElement("a");
            a.href = url;
            a.download = `VV_${result.filename.replace(/[^\w\s-]/g, "")}_${result.timestamp}.png`;
            a.click();
            URL.revokeObjectURL(url);
          }, "image/png");
        });
        
        // 添加复制按钮
        const copyButton = document.createElement("button");
        copyButton.className = "copy-button";
        copyButton.title = "复制图片";
        copyButton.innerHTML = `<img src="copy.svg" alt="复制" class="copy-icon">`;
        
        copyButton.addEventListener("click", (e) => {
          e.stopPropagation();
          displayCanvas.toBlob(async (blob) => {
            if (!blob) {
              console.error("Failed to create image blob");
              return;
            }
            try {
              // 尝试使用Clipboard API复制图片
              await navigator.clipboard.write([
                new ClipboardItem({
                  [blob.type]: blob
                })
              ]);
              
              // 显示成功提示
              const toast = document.createElement("div");
              toast.className = "copy-toast";
              toast.textContent = "已复制到剪贴板";
              document.body.appendChild(toast);
              
              // 2秒后移除提示
              setTimeout(() => {
                toast.classList.add("fade-out");
                setTimeout(() => toast.remove(), 300);
              }, 2000);
              
            } catch (err) {
              console.error("复制失败:", err);
              alert("复制失败,请使用更新的浏览器或手动保存图片");
            }
          }, "image/png");
        });
        
        imgContainer.appendChild(copyButton);
        imgContainer.appendChild(displayCanvas);
        setTimeout(() => {
          displayCanvas.classList.add("loaded");
          placeholder.style.opacity = "0";
          setTimeout(() => placeholder.remove(), 300);
        }, 50);
      } catch (error) {
        console.error("Canvas error:", error);
        imgContainer.remove();
      }

      URL.revokeObjectURL(imageUrl);
    };
  } catch (error) {
    console.error("加载预览图失败:", error);
    imgContainer.remove();
  }
}
function getEpisodeUrl(filename) {
  for (let key in mapping) if (mapping[key] === filename) return key;
  return null;
}
function startNaturalLoadingBar() {
  const loadingBar = document.getElementById("loadingBar");
  loadingBar.style.transition = "";
  loadingBar.style.width = "0%";
  loadingBar.style.display = "block";
  if (loadingBar.interval) clearInterval(loadingBar.interval);
  let progress = 0;
  const targetProgress = 95;
  let speed = 0.5;
  loadingBar.interval = setInterval(() => {
    if (progress < 30) speed = 0.8;
    else if (progress < 60) speed = 0.4;
    else if (progress < 80) speed = 0.2;
    else speed = 0.1;
    progress += speed;
    if (progress >= targetProgress) {
      clearInterval(loadingBar.interval);
      progress = targetProgress;
    }
    loadingBar.style.width = `${progress}%`;
  }, 50);
}
function completeLoadingBar() {
  const loadingBar = document.getElementById("loadingBar");
  clearInterval(loadingBar.interval);
  loadingBar.style.transition = "width 0.3s ease-out";
  loadingBar.style.width = "100%";
}
function initializeScrollListener() {
  if (window.currentObserver) window.currentObserver.disconnect();

  const observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (
          entry.isIntersecting &&
          AppState.hasMoreResults &&
          !AppState.isSearching
        ) {
          if (AppState.cachedResults.length > AppState.displayedCount) {
            displayResults(
              {
                status: "success",
                data: AppState.cachedResults,
                count: AppState.cachedResults.length,
              },
              true,
            );
          }
        }
      });
    },
    { root: null, rootMargin: "200px", threshold: 0.1 },
  );

  window.currentObserver = observer;

  const oldTrigger = document.getElementById("scroll-trigger");
  if (oldTrigger) oldTrigger.remove();

  const trigger = document.createElement("div");
  trigger.id = "scroll-trigger";
  trigger.style.cssText = "height: 20px; margin: 20px 0;";
  document.getElementById("results").appendChild(trigger);

  observer.observe(trigger);
}
function handleCardClick(result) {
  const episodeMatch = result.filename.match(/\[P(\d+)\]/);
  const timeMatch = result.timestamp.match(/^(\d+)m(\d+)s$/);
  if (episodeMatch && timeMatch) {
    const episodeNum = parseInt(episodeMatch[1], 10);
    const minutes = parseInt(timeMatch[1]);
    const seconds = parseInt(timeMatch[2]);
    const totalSeconds = minutes * 60 + seconds;
    for (const [url, filename] of Object.entries(mapping))
      if (filename === result.filename) {
        const videoUrl = `https://www.bilibili.com${url}?t=${totalSeconds}`;
        window.open(videoUrl, "_blank");
        break;
      }
  }
}
function enableKeywordTags() {
  const keywordsContainer = document.getElementById("keywordsContainer");
  keywordsContainer.querySelectorAll('.keyword-tag').forEach(tag => {
    tag.classList.remove('disabled');
  });
}