]*>\s*<\/code><\/pre>/g,""),e}catch(o){ve.warn("UIRenderer","Marked解析失败:",o);}let n=t;return n=n.replace(/```([a-zA-Z0-9]*)?\n([\s\S]*?)```/g,(e,t,n)=>{if(!n.trim())return "";return `${this._escapeHtml(n)}
`}),n=n.replace(/^### (.*$)/gim,"$1
"),n=n.replace(/^## (.*$)/gim,"$1
"),n=n.replace(/^# (.*$)/gim,"$1
"),n=n.replace(/\*\*(.*?)\*\*/g,"$1"),n=n.replace(/(?$1"),n=n.replace(/`([^`]+)`/g,"$1"),n=n.replace(/^\* (.*$)/gim,"$1 "),n=n.replace(/^- (.*$)/gim,"$1 "),n=n.replace(/^\d+\. (.*$)/gim,"$1 "),n=n.replace(/(.*<\/li>(?:\s* .*<\/li>)*)/g,"$1
"),n=n.replace(/((?:- .*<\/li>\s*)+)<\/ul>/g,(e,n)=>t.split("\n").some(e=>/^\d+\.\s+/.test(e))?`
${n}
`:e),n=n.replace(/\n/g,"
"),n}normalizeMarkdown(e){if(!e)return "";let t=String(e).replace(/\r\n/g,"\n").replace(/\r/g,"\n").trim();const n=t.match(/^```[a-zA-Z0-9+_-]*\s*\n([\s\S]*?)\s*```$/);n&&(t=n[1]);const o=t.split("\n"),i=o.filter(e=>e.trim().length>0);if(i.length>0){const e=Math.min(...i.map(e=>e.match(/^ */)[0].length));e>0&&(t=o.map(t=>t.startsWith(" ".repeat(e))?t.slice(e):t).join("\n"));}return t.trim()}renderAISummaryPanel(e=null,t=false){let n="";if(e){let t="",o=[];if("object"==typeof e&&e.markdown)t=this.parseMarkdown(e.markdown),o=e.segments||[];else if("string"==typeof e){t=this.parseAISummary(e).mainSummary;}n='',o&&o.length>0&&(n+=`\n \n AI时间戳段落\n ${this.renderAISegments(o)}\n \n \n `),n+=t.trim()?`\n \n ${t}\n \n `:'暂无总结内容',n+="";}else n='\n \n 点击上方AI图标生成视频总结
\n \n ';return n}parseAISummary(e){let t="",n=[];const o=e.match(/\[总结\]([\s\S]*?)(?=\[段落\]|$)/i),i=e.match(/\[段落\]([\s\S]*)/i);if(o&&o[1]){const e=o[1].trim();t=this.parseMarkdown(e);}if(i&&i[1]){const e=i[1],t=/\[(\d{1,2}:\d{2}(?::\d{2})?)\]\s*([^\n]+?)(?:\n\s+([^\[]+?))?(?=\[|$)/g;let o;for(;null!==(o=t.exec(e));){const[e,t,i,s]=o;let r=t;const a=t.split(":");if(2===a.length)r=`[${a[0].padStart(2,"0")}:${a[1].padStart(2,"0")}]`;else if(3===a.length){r=`[${(60*parseInt(a[0])+parseInt(a[1])).toString().padStart(2,"0")}:${a[2].padStart(2,"0")}]`;}const l=i.trim(),c=s?s.trim():"";n.push({title:l,time:r,content:c});}}if(!t&&0===n.length){const o=e.split("\n");let i=[],s=false;for(const e of o){const t=e.trim();if(t.match(/^\[\d{1,2}:\d{2}(?::\d{2})?\]/)){s=true;const e=t.match(/^\[(\d{1,2}:\d{2}(?::\d{2})?)\]\s*(.*)/);if(e){const[t,o,i]=e;let s=o;const r=o.split(":");if(2===r.length)s=`[${r[0].padStart(2,"0")}:${r[1].padStart(2,"0")}]`;else if(3===r.length){s=`[${(60*parseInt(r[0])+parseInt(r[1])).toString().padStart(2,"0")}:${r[2].padStart(2,"0")}]`;}n.push({title:i.trim(),time:s,content:""});}}else s?n.length>0&&e.startsWith(" ")&&(n[n.length-1].content+=(n[n.length-1].content?" ":"")+t):i.push(e);}i.length>0&&(t=this.parseMarkdown(i.join("\n").trim()));}if(!t&&0===n.length){const o=e.split(/##\s*要点/i);if(o.length>=2){const e=o[0].replace(/##\s*总结/i,"").trim();t=this.parseMarkdown(e);const i=o[1].matchAll(/###\s*\[?([^\]\n]+)\]?[\s\S]*?-\s*时间[::]\s*\[(\d{1,2}):(\d{2})\][\s\S]*?-\s*内容[::]\s*([^\n]+)/gi);for(const t of i){const[e,o,i,s,r]=t;n.push({title:o.trim(),time:`[${i.padStart(2,"0")}:${s.padStart(2,"0")}]`,content:r.trim()});}}}return t||0!==n.length||(t=this.parseMarkdown(e)),{mainSummary:t,keyPoints:n}}renderAISummarySection(e=null,t=false){const n=document.createElement("div");return n.className="ai-summary-section",n.innerHTML=this.renderAISummaryPanel(e,t),n}updateAISummary(e,t){if(e||(e=document.getElementById("subtitle-container")),!e)return;const n=e.querySelector("#summary-panel");n&&(n.innerHTML=this.renderAISummaryPanel(t,false));}renderAISegments(e){return e.map((e,t)=>{const n=(e.timestamp||"[00:00]").replace(/[\[\]]/g,"");return `\n \n \n \n ${e.summary?`${e.title||""}\n ${e.summary}`:`${e.title||""}`}\n \n \n `}).join("")}createNotification(e){const t=document.createElement("div");return t.className="notion-toast show",t.textContent=e,document.body.appendChild(t),setTimeout(()=>{t.remove();},3e3),t}createNotionConfigModal(){const e=document.createElement("div");return e.id="notion-config-modal",e.className="config-modal",e.innerHTML='\n \n ',e}createAIConfigModal(){const e=document.createElement("div");return e.id="ai-config-modal",e.className="config-modal",e.innerHTML='\n \n ',e}renderAIConfigList(e){const t=Se.getAIConfigs(),n=Se.getSelectedAIConfigId();e.innerHTML=t.map(e=>{const t=e.apiKey&&""!==e.apiKey.trim(),o=t?"✅":"⚠️",i=t?"已配置":"未配置",s=t?"#4ade80":"#fbbf24";return `\n \n \n ${e.name}\n \n ${o} ${i}\n \n \n \n \n \n \n `}).join("");}showNotionStatus(e,t=false){const n=document.getElementById("notion-status-message");n&&(n.className="config-status "+(t?"error":"success"),n.textContent=e);}renderShortcutConfigModal(){if(ve.debug("UIRenderer","renderShortcutConfigModal 开始"),!Ce)return console.error("[UIRenderer] shortcutManager 未定义"),null;let e;try{e=Ce.getAllShortcuts(),ve.debug("UIRenderer","获取到快捷键:",e);}catch(t){return console.error("[UIRenderer] 获取快捷键失败:",t),null}return e&&"object"==typeof e?`\n \n \n \n `:(console.error("[UIRenderer] 快捷键配置无效:",e),null)}};const mt=new class{constructor(){this.stack=[],this.escHandler=null,this.init();}init(){this.escHandler=e=>{if("Escape"===e.key&&this.stack.length>0){const e=this.stack[this.stack.length-1];e&&"function"==typeof e.hide&&e.hide();}},document.addEventListener("keydown",this.escHandler);}push(e){if(!e||"function"!=typeof e.hide)return void ve.warn("ModalManager","模态框实例必须有hide方法");-1===this.stack.indexOf(e)&&this.stack.push(e);}pop(e){const t=this.stack.indexOf(e);t>-1&&this.stack.splice(t,1);}closeAll(){for(;this.stack.length>0;){const e=this.stack.pop();e&&"function"==typeof e.hide&&e.hide();}}getStackSize(){return this.stack.length}isInStack(e){return this.stack.includes(e)}destroy(){this.escHandler&&(document.removeEventListener("keydown",this.escHandler),this.escHandler=null),this.stack=[];}};const bt=new class{constructor(){this.panel=null,this.isPanelVisible=false,this.filters={showText:true,showScreenshot:true};}createPanel(){return this.panel||(this.panel=document.createElement("div"),this.panel.id="notes-panel",this.panel.className="notes-panel",document.body.appendChild(this.panel)),this.panel}showPanel(){const e=this.createPanel();this.renderPanel(),e.classList.add("show"),this.isPanelVisible=true,mt.push(this);}hidePanel(){this.panel&&this.panel.classList.remove("show"),this.isPanelVisible=false,mt.pop(this);}hide(){this.hidePanel();}togglePanel(){this.isPanelVisible?this.hidePanel():this.showPanel();}renderPanel(){const e=this.createPanel(),t=this.getFilteredGroupedNotes(),n=Ke.getAllNotes(),o=n.filter(e=>"screenshot"!==e.type&&"ai-summary"!==e.type).length,i=n.filter(e=>"ai-summary"===e.type).length,s=n.filter(e=>"screenshot"===e.type).length,r=o+i,a=`\n \n \n 我的笔记
\n \n \n \n \n \n \n \n ${0===t.length?this.renderEmptyState():t.map(e=>this.renderGroup(e)).join("")}\n \n \n `;e.innerHTML=a,this.bindPanelEvents();}getFilteredGroupedNotes(){const e=Ke.getAllNotes().filter(e=>"screenshot"===e.type?this.filters.showScreenshot:(e.type,this.filters.showText)),t={};return e.forEach(e=>{const n=e.createdAt||e.timestamp,o=Ke.formatDate(n);t[o]||(t[o]=[]),t[o].push(e);}),Object.keys(t).sort((e,n)=>{const o=t[e][0].createdAt||t[e][0].timestamp;return (t[n][0].createdAt||t[n][0].timestamp)-o}).map(e=>({date:e,notes:t[e].sort((e,t)=>{if("ai-summary"===e.type&&"ai-summary"!==t.type)return -1;if("ai-summary"!==e.type&&"ai-summary"===t.type)return 1;const n=e.createdAt||e.timestamp;return (t.createdAt||t.timestamp)-n})}))}renderEmptyState(){if(Ke.getAllNotes().length>0)return '\n \n \n 没有符合筛选条件的笔记\n 请调整上方的筛选条件\n \n ';{let t="截图";try{const e=window.shortcutManager;if(e){const n=e.getAllShortcuts();n.takeScreenshot&&(t=e.formatShortcut(n.takeScreenshot));}}catch(e){}return `\n \n \n 还没有保存任何笔记\n 选中文字后点击粉色钢笔即可保存
或使用 ${t} 保存截图\n \n `}}renderGroup(e){return `\n \n \n \n ${e.date} (${e.notes.length}条)\n \n \n \n \n \n \n \n ${e.notes.map(e=>this.renderNote(e)).join("")}\n \n \n `}renderNote(e){if("ai-summary"===e.type)return this.renderAISummaryNote(e);const t=e.content.length>200?e.content.substring(0,200)+"...":e.content,n="screenshot"===e.type&&e.imageData?`\n \n
\n \n ${this.escapeHtml(t)}\n `:`${this.escapeHtml(t)}`;let o="",i="";return "screenshot"===e.type?(o=e.timeString||Ke.formatTime(e.createdAt||e.timestamp),e.videoTitle&&"未知视频"!==e.videoTitle?i=` · ${this.escapeHtml(e.videoTitle)}`:e.videoBvid&&(i=` · ${this.escapeHtml(e.videoBvid)}`)):(o=Ke.formatTime(e.timestamp),e.videoTitle&&(i=` · ${this.escapeHtml(e.videoTitle)}`)),`\n \n ${n}\n \n \n `}renderAISummaryNote(e){const t=e.videoInfo?.title||e.videoBvid||"未知视频",n=`\n \n 📹 视频信息\n \n ${this.escapeHtml(t)}\n \n \n `,o=e.summary?`\n \n 📊 视频总结\n \n ${this.escapeHtml(e.summary).replace(/\n/g,"
")}\n \n \n `:"",i=e.segments&&e.segments.length>0?`\n \n ⏱️ 时间戳段落\n \n ${e.segments.map((t,n)=>{const o=(e.screenshots||[]).filter(e=>e.segmentIndex===n);return `\n \n \n [${t.timestamp}]\n ${this.escapeHtml(t.title)}\n \n ${this.escapeHtml(t.summary)}\n ${o.map(e=>`\n \n
\n 📸 ${e.timeString}\n \n `).join("")}\n \n `}).join("")}\n \n \n `:"";return `\n \n \n ${n}\n ${o}\n ${i}\n \n \n \n `}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}async copyToClipboard(e){try{if(navigator.clipboard&&navigator.clipboard.writeText)await navigator.clipboard.writeText(e);else {const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t);}}catch(t){console.error("复制失败:",t);}}bindPanelEvents(){const e=this.panel.querySelector(".notes-panel-close");e&&e.addEventListener("click",()=>this.hidePanel());const t=this.panel.querySelector("#filter-text-notes"),n=this.panel.querySelector("#filter-screenshot-notes");t&&t.addEventListener("change",e=>{this.filters.showText=e.target.checked,this.renderPanel();}),n&&n.addEventListener("change",e=>{this.filters.showScreenshot=e.target.checked,this.renderPanel();});const o=this.panel.querySelector(".notes-panel-body");o&&o.addEventListener("click",async e=>{const t=e.target.closest(".note-copy-btn");if(t){const e=t.getAttribute("data-note-id"),n=Ke.getAllNotes().find(t=>t.id===e);if(n){await this.copyToClipboard(n.content);const e=t.textContent;t.textContent="✓",setTimeout(()=>{t.textContent=e;},1e3);}return}const n=e.target.closest(".note-delete-btn");if(n){const e=n.getAttribute("data-note-id");return Ke.deleteNote(e),void this.renderPanel()}const o=e.target.closest(".note-group-copy-btn");if(o){const e=o.getAttribute("data-date"),t=Ke.getGroupedNotes().find(t=>t.date===e);if(t){const e=t.notes.map(e=>e.content).join("\n\n");await this.copyToClipboard(e);const n=o.textContent;o.textContent="✓",setTimeout(()=>{o.textContent=n;},1e3);}return}const i=e.target.closest(".note-group-delete-btn");if(i){const e=i.getAttribute("data-date"),t=Ke.getGroupedNotes().find(t=>t.date===e);if(t&&confirm(`确定要删除 ${e} 的 ${t.notes.length} 条笔记吗?`)){const e=t.notes.map(e=>e.id);Ke.deleteNotes(e),this.renderPanel();}return}});}addSaveButton(e){if(e.querySelector(".save-subtitle-note-btn"))return;const t=e.querySelector(".subtitle-text")?.textContent;if(!t)return;const n=document.createElement("button");n.className="save-subtitle-note-btn",n.textContent="保存",n.title="保存此字幕为笔记",n.addEventListener("click",e=>{e.stopPropagation(),Ke.saveSubtitleNote(t),n.textContent="✓",setTimeout(()=>{n.textContent="保存";},1e3);});const o=e.querySelector(".subtitle-time");o&&o.appendChild(n);}addSaveButtonsToSubtitles(e){e.querySelectorAll(".subtitle-item").forEach(e=>this.addSaveButton(e));}};const ft=new class{constructor(){this.index=new Map,this.items=[],this.minWordLength=1;}buildIndex(e){this.items=e,this.index.clear(),e.forEach((e,t)=>{this.tokenize(e.content).forEach(e=>{this.index.has(e)||this.index.set(e,[]);const n=this.index.get(e);n.includes(t)||n.push(t);});}),ve.debug("SearchIndex",`索引构建完成: ${this.index.size} 个词, ${e.length} 项数据`);}tokenize(e){if(!e)return [];const t=[],n=e.toLowerCase();for(let o=0;o0;i++){const e=this.index.get(n[i])||[];o=o.filter(t=>e.includes(t));}return o}incrementalSearch(e,t,n){if(e.startsWith(t)&&n.length>0){const t=e.toLowerCase();return n.filter(e=>{const n=this.items[e];return n&&n.content.toLowerCase().includes(t)})}return this.search(e)}clear(){this.index.clear(),this.items=[];}getStats(){return {indexSize:this.index.size,itemsCount:this.items.length,avgIndicesPerWord:this.index.size>0?(Array.from(this.index.values()).reduce((e,t)=>e+t.length,0)/this.index.size).toFixed(2):0}}};const yt=new class{constructor(){this.container=null,this.video=null,this.isFollowing=true,this.scrollTimer=null,this.followInterval=null,this.userScrollTimeout=null,this.lastScrollTime=0,this.lastHighlightedItem=null,this.config={followIntervalMs:200,userScrollDetectMs:300,scrollBehavior:"smooth",scrollPosition:"start",highlightClass:"current"},this.callbacks={onFollowStatusChange:null,onSubtitleHighlight:null};}init(e,t={}){e?(this.container=e,this.video=document.querySelector("video"),this.video?(this.config={...this.config,...t},this.setupScrollListener(),this.startAutoFollow()):console.warn("SubtitleScrollManager: 未找到视频元素")):console.warn("SubtitleScrollManager: 容器不存在");}setupScrollListener(){this.container&&this.container.addEventListener("scroll",()=>{this.handleUserScroll();},{passive:true});}handleUserScroll(){Date.now()-this.lastScrollTime<50||(this.userScrollTimeout&&clearTimeout(this.userScrollTimeout),this.isFollowing,this.userScrollTimeout=setTimeout(()=>{this.isFollowing&&(this.isFollowing=false,this.triggerFollowStatusChange(false));},this.config.userScrollDetectMs));}startAutoFollow(){this.stopAutoFollow(),this.isFollowing=true,this.triggerFollowStatusChange(true),this.updateScroll(),this.followInterval=setInterval(()=>{this.isFollowing&&this.updateScroll();},this.config.followIntervalMs);}stopAutoFollow(){this.followInterval&&(clearInterval(this.followInterval),this.followInterval=null),this.isFollowing=false,this.triggerFollowStatusChange(false);}resumeAutoFollow(){this.startAutoFollow(),this.scrollToCurrentSubtitle(true);}updateScroll(){if(!this.video||!this.container)return;const e=this.video.currentTime,t=this.container.querySelectorAll(".subtitle-item");if(0===t.length)return;let n=null;for(let o=0;o=s&&e<=r){n=i;break}if(o=s&&e=n&&t<=i){this.updateHighlight(o),this.scrollToElement(o,e);break}}}triggerFollowStatusChange(e){this.callbacks.onFollowStatusChange&&this.callbacks.onFollowStatusChange(e);}on(e,t){this.callbacks.hasOwnProperty(e)&&(this.callbacks[e]=t);}updateConfig(e){this.config={...this.config,...e};}isAutoFollowing(){return this.isFollowing}destroy(){this.stopAutoFollow(),this.userScrollTimeout&&(clearTimeout(this.userScrollTimeout),this.userScrollTimeout=null),this.lastHighlightedItem&&(this.lastHighlightedItem.classList.remove(this.config.highlightClass),this.lastHighlightedItem=null),this.container=null,this.video=null,this.callbacks={onFollowStatusChange:null,onSubtitleHighlight:null};}};const vt=new class{constructor(){this.isDragging=false,this.dragStartX=0,this.dragStartY=0,this.translateX=0,this.translateY=0,this.isResizing=false,this.resizeStartX=0,this.resizeStartY=0,this.resizeStartWidth=0,this.resizeStartHeight=0,this.searchMatches=[],this.currentMatchIndex=-1,this.searchTerm="",this.lastSearchTerm="",this.searchIndexBuilt=false,this.subtitleDataCache=null,this.currentHighlightedIndex=-1,this.debouncedSearch=null,this.throttledHighlight=null,this.aiConfigModalProxy={hide:()=>this.hideAIConfigModal()},this.notionConfigModalProxy={hide:()=>this.hideNotionConfigModal()},this.shortcutConfigModalProxy={hide:()=>this.hideShortcutConfigModal()};}initializeSearchIndex(e){e&&e.length>0&&(ft.buildIndex(e),this.searchIndexBuilt=true);}bindSubtitlePanelEvents(e){this.restoreContainerState(e),this.bindDragEvents(e),this.bindResizeEvents(e),this.observeContainerResize(e);const t=e.querySelector(".subtitle-close");t&&t.addEventListener("click",()=>{we.setPanelVisible(false),e.classList.remove("show"),yt.destroy();});const n=e.querySelectorAll(".subtitle-tab"),o=e.querySelectorAll(".subtitle-panel");n.forEach(e=>{e.addEventListener("click",()=>{const t=e.getAttribute("data-tab");n.forEach(e=>e.classList.remove("active")),e.classList.add("active"),o.forEach(e=>{if(e.id===`${t}-panel`){if(e.style.display="block","subtitles"===t){const t=e.querySelector("#subtitle-list-container");t&&!yt.container&&this.initSubtitleScroll(t);}}else e.style.display="none";});});});const i=e.querySelector(".ai-icon");i&&i.addEventListener("click",async t=>{if(t.stopPropagation(),we.ai.isSummarizing)return void Ye.warning("AI总结正在生成中,请稍候...");const n=we.getSubtitleData();if(!n||0===n.length)return void Ye.error("没有可用的字幕数据");if(!Se.getSelectedAIConfig())return void Ye.warning("请先在油猴菜单中AI配置中选择或配置一个AI服务");const o=we.getVideoKey();if(we.getAISummary(o)){if(!confirm('已存在AI总结,是否重新生成?\n\n点击"确定"重新生成\n点击"取消"查看现有总结')){const t=e?.querySelector('.subtitle-tab[data-tab="summary"]');return void(t&&t.click())}o&&sessionStorage.removeItem(`ai-summary-${o}`),we.ai.currentSummary=null;}try{await Je.summarize(n,!0);const t=e?.querySelector('.subtitle-tab[data-tab="summary"]');t&&t.click();}catch(i){Ye.handleError(i,"AI总结");}});const s=e.querySelector("#progress-switch");s&&s.addEventListener("click",()=>{s.classList.toggle("on");s.classList.contains("on")?this.addProgressBarMarkers(e):this.removeProgressBarMarkers();});const r=e.querySelector(".download-icon");r&&r.addEventListener("click",e=>{e.stopPropagation();try{Re.downloadSubtitleFile(),Ye.success("字幕文件已下载");}catch(t){Ye.handleError(t,"下载字幕");}});const a=e.querySelector(".notion-icon");a&&a.addEventListener("click",async e=>{if(e.stopPropagation(),we.ai.isSummarizing)return void Ye.warning("AI总结正在生成中,请稍后再发送到Notion");const t=we.getSubtitleData();if(t&&0!==t.length)try{const e=we.getVideoInfo(),n=we.getVideoKey(),o=n?we.getAISummary(n):null,i=Se.getNotionContentOptions().subtitles?t:null;await Ge.sendComplete(i,o,e);}catch(n){Ye.handleError(n,"Notion发送");}else Ye.error("没有字幕数据可发送");});const l=e.querySelector("#subtitle-list-container");l&&this.initSubtitleScroll(l);const c=e.querySelector("#subtitle-search-input");c&&(this.debouncedSearch||(this.debouncedSearch=Oe((e,t)=>{this.handleSearch(e,t);},300)),c.addEventListener("input",t=>{this.debouncedSearch(e,t.target.value);}),c.addEventListener("keydown",t=>{"Enter"===t.key&&(t.preventDefault(),this.navigateSearch(e,1));}));const d=e.querySelector("#search-prev"),u=e.querySelector("#search-next");d&&d.addEventListener("click",()=>{this.navigateSearch(e,-1);}),u&&u.addEventListener("click",()=>{this.navigateSearch(e,1);}),e.addEventListener("click",t=>{const n=t.target.closest(".section-item");if(n){t.stopPropagation();const e=window.getSelection();e&&e.removeAllRanges(),ve.info("EventHandlers","段落元素被点击");const o=n.getAttribute("data-time");if(ve.info("EventHandlers","时间戳字符串:",o),o){let e=0;const t=o.match(/\[?(\d{1,2}):(\d{2})(?::(\d{2}))?\]?/);if(t){const[i,s,r,a]=t;e=a?3600*parseInt(s)+60*parseInt(r)+parseInt(a):60*parseInt(s)+parseInt(r),ve.info("EventHandlers","解析后的秒数:",e);const l=document.querySelector(ie);if(l){l.currentTime=e;const t=o.replace(/[\[\]]/g,"");Ye.info(`跳转到 ${t}`),n.classList.add("clicked"),setTimeout(()=>{n.classList.remove("clicked");},300);}}}return}const o=t.target.closest(".save-subtitle-note-btn");if(o){t.stopPropagation();const e=o.getAttribute("data-content");return void(e&&(Ke.saveSubtitleNote(e),o.textContent="✓",setTimeout(()=>{o.textContent="保存";},1e3)))}const i=t.target.closest(".subtitle-item");if(i){const t=document.querySelector(ie);if(t){const n=parseFloat(i.dataset.from);e.querySelectorAll(".subtitle-item").forEach(e=>{e.classList.remove("current");}),i.classList.add("current"),t.currentTime=n;}}}),this.syncSubtitleHighlight(e);}setupDragging(e){const t=e.querySelector(".subtitle-header");t&&(t.addEventListener("mousedown",t=>{t.target.closest(".subtitle-close")||t.target.closest(".ai-icon")||t.target.closest(".download-icon")||t.target.closest(".notion-icon")||t.target.closest(".subtitle-search-container")||(this.isDragging=true,this.dragStartX=t.clientX,this.dragStartY=t.clientY,e.style.willChange="transform",t.preventDefault());}),document.addEventListener("mousemove",t=>{this.isDragging&&requestAnimationFrame(()=>{const n=t.clientX-this.dragStartX,o=t.clientY-this.dragStartY;this.translateX+=n,this.translateY+=o,this.dragStartX=t.clientX,this.dragStartY=t.clientY,e.style.transform=`translate(${this.translateX}px, ${this.translateY}px)`;});}),document.addEventListener("mouseup",()=>{this.isDragging&&(this.isDragging=false,e.style.willChange="auto",this.savePanelPosition(e));}));}setupResize(e){const t=e.querySelector(".subtitle-resize-handle");t&&(t.addEventListener("mousedown",t=>{this.isResizing=true,this.resizeStartX=t.clientX,this.resizeStartY=t.clientY,this.resizeStartWidth=e.offsetWidth,this.resizeStartHeight=e.offsetHeight,t.preventDefault(),t.stopPropagation();}),document.addEventListener("mousemove",t=>{this.isResizing&&requestAnimationFrame(()=>{const n=t.clientX-this.resizeStartX,o=t.clientY-this.resizeStartY,i=this.resizeStartWidth+n,s=this.resizeStartHeight+o,r=Math.max(300,Math.min(800,i)),a=.9*window.innerHeight,l=Math.max(400,Math.min(a,s));e.style.width=`${r}px`,e.style.maxHeight=`${l}px`;});}),document.addEventListener("mouseup",()=>{this.isResizing&&(this.isResizing=false,this.savePanelDimensions(e));}));}savePanelPosition(e){try{localStorage.setItem("subtitle_panel_position",JSON.stringify({translateX:this.translateX,translateY:this.translateY}));}catch(t){console.error("保存面板位置失败:",t);}}savePanelDimensions(e){try{localStorage.setItem("subtitle_panel_dimensions",JSON.stringify({width:e.offsetWidth,height:e.offsetHeight}));}catch(t){console.error("保存面板尺寸失败:",t);}}loadPanelDimensions(e){try{const t=localStorage.getItem("subtitle_panel_dimensions");if(t){const{width:n,height:o}=JSON.parse(t);e.style.width=`${n}px`,e.style.maxHeight=`${o}px`;}const n=localStorage.getItem("subtitle_panel_position");if(n){const{translateX:t,translateY:o}=JSON.parse(n);this.translateX=t,this.translateY=o,e.style.transform=`translate(${t}px, ${o}px)`;}}catch(t){console.error("加载面板设置失败:",t);}}syncSubtitleHighlight(e){const t=We.get(ie);if(!t)return;const n=Array.from(e.querySelectorAll(".subtitle-item"));this.subtitleDataCache=n.map(e=>({element:e,from:parseFloat(e.dataset.from),to:parseFloat(e.dataset.to)})),this.throttledHighlight||(this.throttledHighlight=function(e){let t=null;return function(...n){null===t&&(t=requestAnimationFrame(()=>{e.apply(this,n),t=null;}));}}(e=>{this.updateSubtitleHighlight(e);})),t.addEventListener("timeupdate",()=>{this.throttledHighlight(t.currentTime);});}updateSubtitleHighlight(e){if(!this.subtitleDataCache||0===this.subtitleDataCache.length)return;const t=function(e,t){if(!e||0===e.length)return -1;if(e.length<50){for(let n=0;n=e[n].from&&t<=e[n].to)return n;return -1}let n=0,o=e.length-1;for(;n<=o;){const i=Math.floor((n+o)/2),s=e[i];if(t>=s.from&&t<=s.to)return i;t=0&&this.currentHighlightedIndex=0&&this.subtitleDataCache[t].element.classList.add("current"),this.currentHighlightedIndex=t);}handleSearch(e,t){if(this.searchTerm=t.trim(),this.clearSearchHighlights(e),!this.searchTerm)return this.updateSearchCounter(0,0),void(this.lastSearchTerm="");if(!this.searchIndexBuilt){const e=we.getSubtitleData();e&&(ft.buildIndex(e),this.searchIndexBuilt=true);}this.searchMatches=[],this.highlightSearchInContainer(e),this.updateSearchCounter(this.searchMatches.length>0?1:0,this.searchMatches.length),this.searchMatches.length>0&&(this.currentMatchIndex=0,this.scrollToMatch(this.searchMatches[0])),this.lastSearchTerm=this.searchTerm;}highlightSearchInContainer(e){const t=e.querySelector(".subtitle-content");if(!t)return;const n=t.querySelector(".ai-summary-section");if(n){const e=n.querySelector(".ai-summary-content");e&&this.highlightInElement(e,this.searchTerm);}t.querySelectorAll(".subtitle-item").forEach(e=>{const t=e.querySelector(".subtitle-text");t&&this.highlightInElement(t,this.searchTerm);});}highlightInElement(e,t){const n=e.textContent,o=new RegExp(`(${this.escapeRegex(t)})`,"gi");if(n.match(o)){let t=n.replace(o,e=>`${e}`);e.innerHTML=t;e.querySelectorAll("mark[data-search-match]").forEach(e=>{this.searchMatches.push(e);});}}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}clearSearchHighlights(e){e.querySelectorAll("mark[data-search-match]").forEach(e=>{const t=e.textContent,n=document.createTextNode(t);e.parentNode.replaceChild(n,e);}),this.searchMatches=[],this.currentMatchIndex=-1;}navigateSearch(e,t){if(0===this.searchMatches.length)return;this.currentMatchIndex>=0&&this.currentMatchIndex=this.searchMatches.length?this.currentMatchIndex=0:this.currentMatchIndex<0&&(this.currentMatchIndex=this.searchMatches.length-1);const n=this.searchMatches[this.currentMatchIndex];n.classList.remove("search-highlight"),n.classList.add("search-highlight-current"),this.scrollToMatch(n),this.updateSearchCounter(this.currentMatchIndex+1,this.searchMatches.length);}scrollToMatch(e){e.classList.add("search-highlight-current"),e.scrollIntoView({behavior:"smooth",block:"center"});}updateSearchCounter(e,t){const n=document.getElementById("search-counter");n&&(n.textContent=`${e}/${t}`);const o=document.getElementById("search-controls");o&&(o.style.display=t>0?"flex":"none");const i=document.getElementById("search-prev"),s=document.getElementById("search-next");i&&(i.disabled=0===t),s&&(s.disabled=0===t);}showAIConfigModal(){const e=document.getElementById("ai-config-modal");if(!e)return;const t=document.getElementById("ai-config-list");t&>.renderAIConfigList(t),this.clearAIConfigForm();const n=e.querySelector(".ai-config-form");n&&n.classList.add("hidden"),document.getElementById("ai-auto-summary-enabled").checked=Se.getAIAutoSummaryEnabled(),e.classList.add("show"),mt.push(this.aiConfigModalProxy);}hideAIConfigModal(){const e=document.getElementById("ai-config-modal");if(!e)return;const t=document.getElementById("ai-auto-summary-enabled").checked;Se.setAIAutoSummaryEnabled(t),e.classList.remove("show"),this.clearAIConfigForm(),mt.pop(this.aiConfigModalProxy);}clearAIConfigForm(){const e=document.getElementById("ai-config-name"),t=document.getElementById("ai-config-url"),n=document.getElementById("ai-config-apikey"),o=document.getElementById("ai-config-model"),i=document.getElementById("ai-config-prompt1"),s=document.getElementById("ai-config-prompt2"),r=document.getElementById("ai-config-is-openrouter"),a=document.getElementById("ai-save-new-btn"),l=document.getElementById("ai-update-btn"),c=document.getElementById("model-select-wrapper"),d=document.getElementById("api-key-help-link");e&&(e.value=""),t&&(t.value="https://openrouter.ai/api/v1/chat/completions"),n&&(n.value=""),o&&(o.value="alibaba/tongyi-deepresearch-30b-a3b:free"),i&&(i.value=""),s&&(s.value=""),r&&(r.checked=true),a&&(a.style.display=""),l&&(l.style.display="none"),c&&(c.style.display="none"),d&&(d.innerHTML="");}showNotionConfigModal(){const e=document.getElementById("notion-config-modal");if(!e)return;const t=Se.getNotionConfig(),n=Se.getNotionContentOptions();document.getElementById("notion-api-key").value=t.apiKey,document.getElementById("notion-parent-page-id").value=t.parentPageId,document.getElementById("notion-auto-send-enabled").checked=Se.getNotionAutoSendEnabled(),document.getElementById("notion-content-video-info").checked=n.videoInfo,document.getElementById("notion-content-summary").checked=n.summary,document.getElementById("notion-content-segments").checked=n.segments,document.getElementById("notion-content-subtitles").checked=n.subtitles;const o=document.getElementById("notion-status-message");o&&(o.innerHTML=""),e.classList.add("show"),mt.push(this.notionConfigModalProxy);}hideNotionConfigModal(){const e=document.getElementById("notion-config-modal");e&&e.classList.remove("show"),mt.pop(this.notionConfigModalProxy);}showShortcutConfigModal(){try{ve.debug("EventHandlers","显示快捷键配置模态框");const e=document.getElementById("shortcut-config-modal");if(e)return e.classList.add("show"),void mt.push(this.shortcutConfigModalProxy);const t=gt.renderShortcutConfigModal();if(!t)return console.error("[EventHandlers] 无法生成快捷键配置模态框HTML"),void Ye.error("无法打开快捷键设置");const n=document.createElement("div");n.innerHTML=t;const o=n.firstElementChild;if(!o)return console.error("[EventHandlers] 无法创建模态框元素"),void Ye.error("无法创建快捷键设置界面");document.body.appendChild(o),requestAnimationFrame(()=>{o.classList.add("show"),mt.push(this.shortcutConfigModalProxy);}),this.bindShortcutConfigModalEvents(o),ve.debug("EventHandlers","快捷键配置模态框已显示");}catch(e){console.error("[EventHandlers] 显示快捷键配置模态框失败:",e),Ye.error("打开快捷键设置失败: "+e.message);}}hideShortcutConfigModal(){const e=document.getElementById("shortcut-config-modal");e&&(e.classList.remove("show"),mt.pop(this.shortcutConfigModalProxy),setTimeout(()=>{e&&e.parentNode&&e.parentNode.removeChild(e);},300));}bindShortcutConfigModalEvents(e){const t=e.querySelector(".config-modal-close");t&&t.addEventListener("click",()=>{this.hideShortcutConfigModal();}),e.addEventListener("click",t=>{t.target===e&&this.hideShortcutConfigModal();});e.querySelectorAll(".shortcut-input").forEach(e=>{e.addEventListener("click",t=>{t.preventDefault(),this.startShortcutCapture(e);});});e.querySelectorAll(".shortcut-reset-btn").forEach(t=>{t.addEventListener("click",()=>{const n=t.dataset.key,o=Ce.constructor.DEFAULT_SHORTCUTS||{};if(o[n]){Ce.updateShortcut(n,o[n]);const t=e.querySelector(`.shortcut-input[data-key="${n}"]`);t&&(t.value=Ce.formatShortcut(o[n])),Ye.success("已重置到默认值");}});});const n=e.querySelector("#reset-all-shortcuts");n&&n.addEventListener("click",()=>{confirm("确定要重置所有快捷键到默认值吗?")&&(Ce.resetToDefaults(),Ye.success("快捷键已重置到默认值"),this.hideShortcutConfigModal(),this.showShortcutConfigModal());});e.querySelectorAll(".shortcut-mode-btn").forEach(e=>{e.addEventListener("click",t=>{t.preventDefault();const n=e.dataset.key,o=e.dataset.mode,i=Ce.getAllShortcuts()[n];if(!i)return;const s=e.closest(".shortcut-item"),r=s.querySelector(".shortcut-hold-btn"),a=s.querySelector(".shortcut-double-btn");if("hold"===o){const t=e.classList.contains("active");r.classList.toggle("active"),a.classList.remove("active");const o={...i,holdMode:!t,doubleClickMode:false};Ce.updateShortcut(n,o);}else if("double"===o){const t=e.classList.contains("active");a.classList.toggle("active"),r.classList.remove("active");const o={...i,holdMode:false,doubleClickMode:!t};Ce.updateShortcut(n,o);}});});}startShortcutCapture(e){const t=e.dataset.key,n=Ce.getAllShortcuts()[t];e.classList.add("recording");const o=e.closest(".shortcut-item"),i=o?.querySelector(".shortcut-hold-btn"),s=o?.querySelector(".shortcut-double-btn"),r=i?.classList.contains("active"),a=s?.classList.contains("active");e.value=r||a?"按下任意键...":"按下快捷键...";let l=null,c="";const d=o=>{if(o.preventDefault(),o.stopPropagation(),"Escape"===o.key)return e.classList.remove("recording"),e.value=Ce.formatShortcut(n),void document.removeEventListener("keydown",d);if(r||a){const i={key:o.code||o.key,meta:false,ctrl:false,alt:false,shift:false,holdMode:r,doubleClickMode:a},s=Ce.updateShortcut(t,i);return s.success?(e.value=Ce.formatShortcut(i),Ye.success("快捷键已更新")):(Ye.error(s.error),e.value=Ce.formatShortcut(n)),e.classList.remove("recording"),void document.removeEventListener("keydown",d)}if(["Meta","Control","Alt","Shift"].includes(o.key))return void(e.value="继续按下字符键...");if(!(o.ctrlKey||o.metaKey||o.altKey||o.shiftKey)&&"takeScreenshot"===t&&"Slash"===o.code){if("Slash"===c&&l){clearTimeout(l);const n={key:"Slash",meta:false,ctrl:false,alt:false,shift:false,doubleClick:true};Ce.updateShortcut(t,n).success&&(e.value=Ce.formatShortcut(n),Ye.success("快捷键已更新")),e.classList.remove("recording"),document.removeEventListener("keydown",d);}else c="Slash",l=setTimeout(()=>{l=null,c="";},300);return}const i={key:o.code||o.key,meta:o.metaKey,ctrl:o.ctrlKey,alt:o.altKey,shift:o.shiftKey,doubleClick:false},s=Ce.checkConflict(t,i);if(s)Ye.warning(`与"${s}"冲突,请重新设置`),e.value=Ce.formatShortcut(n);else {const o=Ce.updateShortcut(t,i);o.success?(e.value=Ce.formatShortcut(i),Ye.success("快捷键已更新")):(Ye.error(o.error),e.value=Ce.formatShortcut(n));}e.classList.remove("recording"),document.removeEventListener("keydown",d);};document.addEventListener("keydown",d);}bindAIConfigModalEvents(e){e.addEventListener("click",t=>{t.target===e&&this.hideAIConfigModal();});const t=document.getElementById("ai-config-list");t&&t.addEventListener("click",n=>{const o=n.target.closest(".ai-config-item"),i=n.target.closest(".ai-edit-btn");if(i){const t=i.dataset.id,n=e.querySelector(".ai-config-form");n&&n.classList.remove("hidden"),this.loadConfigToForm(t);}else if(o&&!i){const n=o.dataset.id;Se.setSelectedAIConfigId(n),gt.renderAIConfigList(t);const i=Se.getAIConfigs().find(e=>e.id===n);Ye.success(`已选择配置: ${i.name}`);const s=e.querySelector(".ai-config-form");s&&s.classList.remove("hidden"),this.loadConfigToForm(n);}});const n=document.getElementById("ai-start-summary-btn");n&&n.addEventListener("click",async()=>{const e=we.getSubtitleData();if(!e||0===e.length)return void Ye.error("没有可用的字幕数据");if(Se.getSelectedAIConfig()){this.hideAIConfigModal();try{await Je.summarize(e,!0);const t=document.getElementById("subtitle-container"),n=t?.querySelector('.subtitle-tab[data-tab="summary"]');n&&n.click();}catch(t){Ye.handleError(t,"AI总结");}}else Ye.warning("请先选择或配置一个AI服务");}),document.getElementById("ai-new-config-btn").addEventListener("click",()=>{this.clearAIConfigForm();const t=e.querySelector(".ai-config-form");t&&(t.classList.remove("hidden"),setTimeout(()=>{t.scrollIntoView({behavior:"smooth",block:"nearest"});},100)),Ye.info("请填写新配置信息");}),document.getElementById("ai-save-new-btn").addEventListener("click",()=>{this.saveNewAIConfig();}),document.getElementById("ai-update-btn").addEventListener("click",()=>{this.updateAIConfig();}),document.getElementById("ai-cancel-btn").addEventListener("click",()=>{this.hideAIConfigModal();}),document.getElementById("ai-delete-current-btn").addEventListener("click",()=>{const e=document.getElementById("ai-delete-current-btn"),t=e?.dataset.deleteId;if(t&&Ye.confirm("确定要删除这个配置吗?")){const n=Se.deleteAIConfig(t);if(n.success){Ye.success("配置已删除");const t=document.getElementById("ai-config-list");t&>.renderAIConfigList(t);const n=document.querySelector(".ai-config-form");n&&n.classList.add("hidden"),e.style.display="none";}else Ye.error(n.error);}}),document.getElementById("fetch-models-btn").addEventListener("click",async()=>{await this.fetchModels();});}loadConfigToForm(e){const t=Se.getAIConfigs().find(t=>t.id===e);if(!t)return;const n=document.getElementById("ai-config-name"),o=document.getElementById("ai-config-url"),i=document.getElementById("ai-config-apikey"),s=document.getElementById("ai-config-model"),r=document.getElementById("ai-config-prompt1"),a=document.getElementById("ai-config-prompt2"),l=document.getElementById("ai-config-is-openrouter"),c=document.getElementById("ai-save-new-btn"),d=document.getElementById("ai-update-btn"),u=document.getElementById("model-select-wrapper");n&&(n.value=t.name),o&&(o.value=t.url),i&&(i.value=t.apiKey),s&&(s.value=t.model),r&&(r.value=t.prompt1||""),a&&(a.value=t.prompt2||""),l&&(l.checked=t.isOpenRouter||false);const p=document.getElementById("api-key-help-link");p&&z[t.id]?p.innerHTML=`📖 如何获取API Key?`:p&&(p.innerHTML=""),c&&(c.style.display="none"),d&&(d.style.display="",d.dataset.editId=e),u&&(u.style.display="none");const h=document.getElementById("ai-delete-current-btn");h&&("openrouter"===e||"openai"===e||"siliconflow"===e||"deepseek"===e||"moonshot"===e||"zhipu"===e||"yi"===e||"dashscope"===e||"gemini"===e?h.style.display="none":(h.style.display="",h.dataset.deleteId=e)),setTimeout(()=>{const e=document.querySelector(".ai-config-form");e&&e.scrollIntoView({behavior:"smooth",block:"nearest"});},100);}editAIConfig(e){this.loadConfigToForm(e);}saveNewAIConfig(){const e={name:document.getElementById("ai-config-name").value.trim(),url:document.getElementById("ai-config-url").value.trim(),apiKey:document.getElementById("ai-config-apikey").value.trim(),model:document.getElementById("ai-config-model").value.trim(),prompt1:document.getElementById("ai-config-prompt1").value,prompt2:document.getElementById("ai-config-prompt2").value,isOpenRouter:document.getElementById("ai-config-is-openrouter").checked},t=Se.addAIConfig(e);if(t.success){Ye.success(`配置"${e.name}"已添加`);const t=document.getElementById("ai-config-list");t&>.renderAIConfigList(t),this.clearAIConfigForm();}else Ye.error(t.error);}updateAIConfig(){const e=document.getElementById("ai-update-btn").dataset.editId;if(!e)return;const t={name:document.getElementById("ai-config-name").value.trim(),url:document.getElementById("ai-config-url").value.trim(),apiKey:document.getElementById("ai-config-apikey").value.trim(),model:document.getElementById("ai-config-model").value.trim(),prompt1:document.getElementById("ai-config-prompt1").value,prompt2:document.getElementById("ai-config-prompt2").value,isOpenRouter:document.getElementById("ai-config-is-openrouter").checked},n=Se.updateAIConfig(e,t);if(n.success){Ye.success(`配置"${t.name}"已更新`);const e=document.getElementById("ai-config-list");e&>.renderAIConfigList(e),this.clearAIConfigForm();}else Ye.error(n.error);}async fetchModels(){const e=document.getElementById("ai-config-apikey").value.trim(),t=document.getElementById("ai-config-url").value.trim(),n=document.getElementById("ai-config-is-openrouter").checked;if(!e)return void Ye.error("请先填写 API Key");if(!n)return void Ye.error("仅OpenRouter支持获取模型列表");const o=document.getElementById("fetch-models-btn");o.disabled=true,o.textContent="获取中...";try{const n=await Je.fetchOpenRouterModels(e,t),o=document.getElementById("model-select-wrapper"),i=document.getElementById("model-select"),s=document.getElementById("model-search-input");if(!i)return void Ye.error("模型选择器未找到");this.allModels=n,i.innerHTML="",n.forEach(e=>{const t=document.createElement("option");t.value=e.id,t.textContent=`${e.name||e.id} (${e.context_length||"N/A"} tokens)`,t.title=e.id,i.appendChild(t);}),o&&(o.style.display="block"),i.onchange=()=>{document.getElementById("ai-config-model").value=i.value;},i.ondblclick=()=>{document.getElementById("ai-config-model").value=i.value,Ye.success("已选择模型");},s&&(s.value="",s.oninput=e=>{this.filterModels(e.target.value);},s.onkeydown=e=>{"Enter"===e.key&&i.options.length>0&&(i.selectedIndex=0,document.getElementById("ai-config-model").value=i.options[0].value,Ye.success("已选择: "+i.options[0].text));}),Ye.success(`已获取 ${n.length} 个模型`);}catch(i){Ye.error(`获取模型列表失败: ${i.message}`);}finally{o.disabled=false,o.textContent="获取模型";}}filterModels(e){if(!this.allModels)return;const t=document.getElementById("model-select");if(!t)return;const n=e.toLowerCase().trim();if(!n)return t.innerHTML="",void this.allModels.forEach(e=>{const n=document.createElement("option");n.value=e.id,n.textContent=`${e.name||e.id} (${e.context_length||"N/A"} tokens)`,n.title=e.id,t.appendChild(n);});const o=this.allModels.filter(e=>{const t=(e.id||"").toLowerCase(),o=(e.name||"").toLowerCase();return t.includes(n)||o.includes(n)});t.innerHTML="",o.forEach(e=>{const n=document.createElement("option");n.value=e.id,n.textContent=`${e.name||e.id} (${e.context_length||"N/A"} tokens)`,n.title=e.id,t.appendChild(n);});const i=document.getElementById("model-search-input");i&&(i.placeholder=o.length>0?`找到 ${o.length} 个模型`:"未找到匹配的模型");}addProgressBarMarkers(e){const t=e.querySelectorAll(".section-item[data-time]"),n=document.querySelector("video"),o=document.querySelector(".bpx-player-progress-wrap");if(!n||!o)return;const i=n.duration;if(!i)return;let s=o.querySelector(".ai-points-container");s||(s=document.createElement("div"),s.className="ai-points-container",o.appendChild(s)),s.innerHTML="",t.forEach(e=>{const t=e.getAttribute("data-time");if(!t)return;const o=t.match(/\[(\d{1,2}):(\d{2})\]/);if(!o)return;const r=60*parseInt(o[1])+parseInt(o[2]),a=r/i*100,l=document.createElement("span");l.className="bpx-player-progress-point bpx-player-progress-point-aipoint",l.style.cssText=`left: ${a}%;`,l.setAttribute("data-time",r),l.addEventListener("click",()=>{n.currentTime=r;}),s.appendChild(l);}),this._addProgressBarStyles();}removeProgressBarMarkers(){const e=document.querySelector(".ai-points-container");e&&e.remove();}_addProgressBarStyles(){if(document.querySelector("#ai-progress-styles"))return;const e=document.createElement("style");e.id="ai-progress-styles",e.textContent="\n .ai-points-container {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n pointer-events: none;\n z-index: 5;\n }\n \n .bpx-player-progress-point-aipoint {\n position: absolute;\n top: 50%;\n transform: translate(-50%, -50%);\n width: 8px;\n height: 8px;\n background: #ff69b4;\n border: 2px solid rgba(255, 255, 255, 0.9);\n border-radius: 50%;\n opacity: 0.9;\n pointer-events: auto;\n cursor: pointer;\n transition: all 0.2s;\n box-shadow: 0 0 4px rgba(255, 105, 180, 0.6);\n }\n \n .bpx-player-progress-point-aipoint:hover {\n opacity: 1;\n transform: translate(-50%, -50%) scale(1.5);\n box-shadow: 0 0 8px rgba(255, 105, 180, 0.9);\n }\n ",document.head.appendChild(e);}initSubtitleScroll(e){if(!e)return void ve.warn("EventHandlers","字幕容器不存在,无法初始化滚动");const t=document.querySelector("#subtitle-follow-btn");yt.init(e,{followIntervalMs:200,userScrollDetectMs:300,scrollBehavior:"smooth",scrollPosition:"center",highlightClass:"current"}),yt.on("onFollowStatusChange",e=>{t&&(t.style.display=e?"none":"block"),ve.debug("字幕滚动",`跟随状态改变: ${e}`);}),t&&t.addEventListener("click",()=>{ve.debug("字幕滚动","点击恢复滚动"),yt.resumeAutoFollow();}),ve.info("EventHandlers","字幕滚动管理器初始化完成");}bindNotionConfigModalEvents(e){e.addEventListener("click",t=>{t.target===e&&this.hideNotionConfigModal();}),document.getElementById("notion-save-btn").addEventListener("click",()=>{const e=document.getElementById("notion-api-key").value.trim(),t=document.getElementById("notion-parent-page-id").value.trim(),n=document.getElementById("notion-auto-send-enabled").checked,o={videoInfo:document.getElementById("notion-content-video-info").checked,summary:document.getElementById("notion-content-summary").checked,segments:document.getElementById("notion-content-segments").checked,subtitles:document.getElementById("notion-content-subtitles").checked};if(!e)return void gt.showNotionStatus("请输入 API Key",true);if(!t)return void gt.showNotionStatus("请输入目标位置(Page ID 或 Database ID)",true);const i=Se.saveNotionConfig({apiKey:e,parentPageId:t});i.success?(Se.setNotionAutoSendEnabled(n),Se.saveNotionContentOptions(o),gt.showNotionStatus("配置已保存"),setTimeout(()=>{this.hideNotionConfigModal();},1500)):gt.showNotionStatus(i.error,true);}),document.getElementById("notion-cancel-btn").addEventListener("click",()=>{this.hideNotionConfigModal();});}restoreContainerState(e){const t=localStorage.getItem("subtitle-container-state");if(t)try{const n=JSON.parse(t);n.width&&(e.style.width=n.width),n.height&&(e.style.height=n.height),n.top&&(e.style.top=n.top),n.left&&(e.style.left=n.left);}catch(n){ve.warn("EventHandlers","恢复容器状态失败:",n);}}parsePositionValue(e,t){return e?e.endsWith("px")?parseInt(e):e.endsWith("%")?parseInt(e)/100*t:parseInt(e)||0:0}resetContainerPosition(e){localStorage.removeItem("subtitle-container-state"),e.style.width="500px",e.style.height="600px",e.style.top="10%",e.style.left="100%",e.style.marginLeft="10px",Ye.success("字幕面板位置已重置");}saveContainerState(e){const t={width:e.style.width||e.offsetWidth+"px",height:e.style.height||e.offsetHeight+"px",top:e.style.top||"10%",left:e.style.left||"100%"};localStorage.setItem("subtitle-container-state",JSON.stringify(t));}bindDragEvents(e){const t=e.querySelector(".subtitle-header");if(!t)return;let n=false,o=0,i=0,s=0,r=0;const a=a=>{if(a.target.closest("button")||a.target.closest("input")||a.target.closest(".subtitle-search-container")||a.target.closest(".ai-icon")||a.target.closest(".notion-icon")||a.target.closest(".subtitle-close"))return;n=true,o=a.clientX,i=a.clientY;const l=e.getBoundingClientRect(),c=document.querySelector(".bpx-player-primary-area"),d=c?.getBoundingClientRect()||{left:0,top:0};s=l.left-d.left,r=l.top-d.top,t.style.cursor="grabbing",a.preventDefault();},l=t=>{if(!n)return;const a=t.clientX-o,l=t.clientY-i,c=s+a,d=r+l;e.style.left=c+"px",e.style.top=d+"px",e.style.marginLeft="0";},c=()=>{n&&(n=false,t.style.cursor="move",this.saveContainerState(e));};t.addEventListener("mousedown",a),document.addEventListener("mousemove",l),document.addEventListener("mouseup",c),e._dragCleanup=()=>{t.removeEventListener("mousedown",a),document.removeEventListener("mousemove",l),document.removeEventListener("mouseup",c);};}bindResizeEvents(e){let t=false,n="",o=0,i=0,s=0,r=0,a=0,l=0;const c=(e,t)=>{const n=e.clientX-t.left,o=e.clientY-t.top,i=t.width,s=t.height;let r="";return o<8?r+="n":o>s-8&&(r+="s"),n<8?r+="w":n>i-8&&(r+="e"),r},d=n=>{if(t)return;const o=e.getBoundingClientRect(),i=c(n,o);e.className=e.className.replace(/\bresize-\w+\b/g,""),i&&e.classList.add(`resize-${i}`);},u=d=>{const u=e.getBoundingClientRect();n=c(d,u),n&&(d.target.closest(".subtitle-header")||(t=true,o=d.clientX,i=d.clientY,s=e.offsetWidth,r=e.offsetHeight,a=e.offsetLeft,l=e.offsetTop,d.preventDefault(),d.stopPropagation()));},p=c=>{if(!t)return;const d=c.clientX-o,u=c.clientY-i;let p=s,h=r,g=a,m=l;if(n.includes("e")&&(p=Math.max(400,Math.min(800,s+d))),n.includes("w")){const e=s-d;p=Math.max(400,Math.min(800,e)),g=a+(s-p);}if(n.includes("s")&&(h=Math.max(400,Math.min(.9*window.innerHeight,r+u))),n.includes("n")){const e=r-u;h=Math.max(400,Math.min(.9*window.innerHeight,e)),m=l+(r-h);}e.style.width=p+"px",e.style.height=h+"px",e.style.left=g+"px",e.style.top=m+"px";},h=()=>{t&&(t=false,n="",this.saveContainerState(e));};e.addEventListener("mousemove",d),e.addEventListener("mousedown",u),document.addEventListener("mousemove",p),document.addEventListener("mouseup",h),e._resizeCleanup=()=>{e.removeEventListener("mousemove",d),e.removeEventListener("mousedown",u),document.removeEventListener("mousemove",p),document.removeEventListener("mouseup",h);};}observeContainerResize(e){const t=new ResizeObserver(Oe(()=>{this.saveContainerState(e);},500));t.observe(e),e._resizeObserver=t;}};const xt=new class{constructor(){this.modal=null;}createModal(){return this.modal||(this.modal=document.createElement("div"),this.modal.id="help-modal",this.modal.className="config-modal",document.body.appendChild(this.modal)),this.modal}show(){const e=this.createModal();this.renderModal(),e.classList.add("show"),mt.push(this);}hide(){this.modal&&this.modal.classList.remove("show"),mt.pop(this);}renderModal(){this.modal.innerHTML='\n \n ',this.bindEvents();}bindEvents(){this.modal.addEventListener("click",e=>{e.target===this.modal&&this.hide();});const e=document.getElementById("help-close-btn");e&&e.addEventListener("click",()=>this.hide());}};const wt=new class{constructor(){this.modal=null;}createModal(){return this.modal||(this.modal=document.createElement("div"),this.modal.id="sponsorblock-modal",this.modal.className="config-modal",document.body.appendChild(this.modal)),this.modal}show(){const e=this.createModal();this.renderModal(),e.classList.add("show"),mt.push(this);}hide(){this.modal&&this.modal.classList.remove("show"),mt.pop(this);}renderModal(){const e=ot.getAll();this.modal.innerHTML=`\n \n `,this.bindEvents();}bindEvents(){this.modal.addEventListener("click",e=>{e.target===this.modal&&this.hide();});const e=document.getElementById("sponsorblock-save-btn");e&&e.addEventListener("click",()=>this.saveSettings());const t=document.getElementById("sponsorblock-cancel-btn");t&&t.addEventListener("click",()=>this.hide());}saveSettings(){const e={skipCategories:Array.from(this.modal.querySelectorAll('.sponsor-checkbox-item input[type="checkbox"]:checked')).map(e=>e.value),showAdBadge:this.modal.querySelector("#showAdBadge").checked,showQualityBadge:this.modal.querySelector("#showQualityBadge").checked,showProgressMarkers:this.modal.querySelector("#showProgressMarkers").checked};ot.setAll(e),this.hide(),Ye.info("设置已保存!\n\n✅ 勾选的类别 → 自动跳过\n⏸️ 未勾选的类别 → 手动提示(5秒)\n\n页面将刷新以应用新设置。"),setTimeout(()=>{location.reload();},2e3);}};const St=new class{constructor(){this.resources={eventBusSubscriptions:new Map,domListeners:new Map,mutationObservers:new Set,intervals:new Map,timeouts:new Set,rafIds:new Set,audioContexts:new Set,customCleanups:new Set},this.isDestroyed=false,this.maxIntervalDuration=3e5,this.startAutoCleanup();}trackEventBusSubscription(e,t,n="default"){this.resources.eventBusSubscriptions.has(n)||this.resources.eventBusSubscriptions.set(n,[]),this.resources.eventBusSubscriptions.get(n).push({event:e,unsubscribe:t});}trackDOMListener(e,t,n,o){const i=Symbol("listener");return this.resources.domListeners.set(i,{element:e,event:t,handler:n,options:o}),e.addEventListener(t,n,o),i}removeDOMListener(e){const t=this.resources.domListeners.get(e);t&&(t.element.removeEventListener(t.event,t.handler,t.options),this.resources.domListeners.delete(e));}trackMutationObserver(e){return this.resources.mutationObservers.add(e),e}trackInterval(e,t,n=this.maxIntervalDuration){const o=Date.now(),i=setInterval(()=>{if(Date.now()-o>n)return ve.warn("ResourceManager",`定时器${i}运行超过${n}ms,自动清理`),void this.clearTrackedInterval(i);e();},t);return this.resources.intervals.set(i,{startTime:o,maxDuration:n,delay:t}),i}clearTrackedInterval(e){clearInterval(e),this.resources.intervals.delete(e);}trackTimeout(e,t){const n=setTimeout(()=>{e(),this.resources.timeouts.delete(n);},t);return this.resources.timeouts.add(n),n}clearTrackedTimeout(e){clearTimeout(e),this.resources.timeouts.delete(e);}trackRAF(e){const t=requestAnimationFrame(e);return this.resources.rafIds.add(t),t}cancelTrackedRAF(e){cancelAnimationFrame(e),this.resources.rafIds.delete(e);}trackAudioContext(e){return this.resources.audioContexts.add(e),e}addCleanup(e){this.resources.customCleanups.add(e);}startAutoCleanup(){this.autoCleanupInterval=setInterval(()=>{this.cleanupExpiredIntervals();},3e4);}cleanupExpiredIntervals(){const e=Date.now(),t=[];this.resources.intervals.forEach((n,o)=>{e-n.startTime>n.maxDuration&&(ve.warn("ResourceManager",`清理超时interval: ${o}, 运行了${((e-n.startTime)/1e3).toFixed(1)}秒`),clearInterval(o),t.push(o));}),t.forEach(e=>this.resources.intervals.delete(e)),t.length>0&&ve.debug("ResourceManager",`已清理${t.length}个超时定时器`);}getStats(){return {intervals:this.resources.intervals.size,timeouts:this.resources.timeouts.size,rafIds:this.resources.rafIds.size,audioContexts:this.resources.audioContexts.size,domListeners:this.resources.domListeners.size,mutationObservers:this.resources.mutationObservers.size,eventBusSubscriptions:Array.from(this.resources.eventBusSubscriptions.values()).reduce((e,t)=>e+t.length,0)}}cleanupModule(e){const t=this.resources.eventBusSubscriptions.get(e);t&&(t.forEach(({unsubscribe:t})=>{try{t();}catch(n){console.error(`[ResourceManager] 清理模块 "${e}" 订阅失败:`,n);}}),this.resources.eventBusSubscriptions.delete(e));}cleanup(){this.isDestroyed?ve.warn("ResourceManager","已经销毁,跳过清理"):(ve.debug("ResourceManager","开始清理资源..."),this.resources.eventBusSubscriptions.forEach((e,t)=>{e.forEach(({event:e,unsubscribe:n})=>{try{n();}catch(o){console.error(`[ResourceManager] 清理 EventBus 订阅失败 (${t}.${e}):`,o);}});}),this.resources.eventBusSubscriptions.clear(),this.resources.domListeners.forEach(({element:e,event:t,handler:n,options:o})=>{try{e.removeEventListener(t,n,o);}catch(i){console.error("[ResourceManager] 清理 DOM 监听器失败:",i);}}),this.resources.domListeners.clear(),this.resources.mutationObservers.forEach(e=>{try{e.disconnect();}catch(t){console.error("[ResourceManager] 清理 MutationObserver 失败:",t);}}),this.resources.mutationObservers.clear(),this.resources.intervals.forEach((e,t)=>{try{clearInterval(t);}catch(n){console.error("[ResourceManager] 清理 interval 失败:",n);}}),this.resources.intervals.clear(),this.autoCleanupInterval&&(clearInterval(this.autoCleanupInterval),this.autoCleanupInterval=null),this.resources.timeouts.forEach(e=>{try{clearTimeout(e);}catch(t){console.error("[ResourceManager] 清理 timeout 失败:",t);}}),this.resources.timeouts.clear(),this.resources.rafIds.forEach(e=>{try{cancelAnimationFrame(e);}catch(t){console.error("[ResourceManager] 清理 RAF 失败:",t);}}),this.resources.rafIds.clear(),this.resources.audioContexts.forEach(e=>{try{"closed"!==e.state&&e.close();}catch(t){console.error("[ResourceManager] 关闭 AudioContext 失败:",t);}}),this.resources.audioContexts.clear(),this.resources.customCleanups.forEach(e=>{try{e();}catch(t){console.error("[ResourceManager] 执行自定义清理失败:",t);}}),this.resources.customCleanups.clear(),this.isDestroyed=true,ve.debug("ResourceManager","资源清理完成"));}getStats(){return {eventBusSubscriptions:Array.from(this.resources.eventBusSubscriptions.entries()).reduce((e,[t,n])=>(e[t]=n.length,e),{}),domListeners:this.resources.domListeners.size,mutationObservers:this.resources.mutationObservers.size,intervals:this.resources.intervals.size,timeouts:this.resources.timeouts.size,rafIds:this.resources.rafIds.size,audioContexts:this.resources.audioContexts.size,customCleanups:this.resources.customCleanups.size}}},kt=location.hostname.endsWith("bilibili.com"),It=location.hostname.includes("youtube.com")||location.hostname.includes("youtu.be");const Et=new class{constructor(){this.initialized=false,this.ball=null,this.container=null,this.videoQualityService=null,this.universalAdSkipService=null,this.isBilibili=kt,this.isYouTube=It;}setupErrorHandler(){const e=window.onerror;window.onerror=(t,n,o,i,s)=>{const r=String(t||""),a=String(n||"");return a&&(a.includes("extension://")||a.includes("content.js"))?(ve.debug("Main","忽略来自其他扩展的错误:",r),true):a.includes("nc-loader")||r.includes("addIceCandidate")?(ve.debug("Main","忽略第三方组件错误"),true):r.includes("Extension context invalidated")?(ve.debug("Main","忽略扩展上下文失效错误"),true):!!e&&e(t,n,o,i,s)},window.addEventListener("unhandledrejection",e=>{const t=e.reason,n=t?String(t.message||t):"";return n.includes("Extension context invalidated")?(e.preventDefault(),void ve.debug("Main","忽略Promise中的扩展上下文失效错误")):n.includes("addIceCandidate")||n.includes("nc-loader")?(e.preventDefault(),void ve.debug("Main","忽略Promise中的第三方组件错误")):void 0}),ve.info("Main","全局错误处理器已设置");}async init(){if(!this.initialized){if(this.setupErrorHandler(),Fe.init(),Fe.getSubtitleService(),function(){const e=document.createElement("style");e.textContent=de,document.head.appendChild(e);}(),await this.waitForPageReady(),this.isBilibili&&Se.fixExistingConfigPrompts(),Ke.init(),tt.init(),this.isBilibili){try{await rt.init();}catch(t){ve.warn("Main","SponsorBlock 初始化失败:",t.message);}this.videoQualityService=(e=rt.getAPI(),dt||(dt=new ct(e)),dt),this.videoQualityService.start();}var e;if(this.isBilibili||this.isYouTube)try{const e=this.isYouTube?{get:e=>({autoSkip:"false"!==localStorage.getItem("youtube_auto_skip"),skipCategories:JSON.parse(localStorage.getItem("youtube_skip_categories")||'["sponsor", "selfpromo"]'),showNotifications:"false"!==localStorage.getItem("youtube_show_notifications"),showProgressMarkers:"false"!==localStorage.getItem("youtube_show_markers"),detectNativeAds:"false"!==localStorage.getItem("youtube_detect_native"),skipDelay:parseInt(localStorage.getItem("youtube_skip_delay")||"0"),muteInsteadOfSkip:"true"===localStorage.getItem("youtube_mute_instead")}[e]),set:(e,t)=>{localStorage.setItem(`youtube_${e}`,JSON.stringify(t));}}:{get:e=>({autoSkip:"false"!==localStorage.getItem("bilibili_auto_skip"),skipCategories:JSON.parse(localStorage.getItem("bilibili_skip_categories")||'["sponsor", "selfpromo"]'),showNotifications:"false"!==localStorage.getItem("bilibili_show_notifications"),showProgressMarkers:"false"!==localStorage.getItem("bilibili_show_markers"),detectNativeAds:"false"!==localStorage.getItem("bilibili_detect_native"),skipDelay:parseInt(localStorage.getItem("bilibili_skip_delay")||"0"),muteInsteadOfSkip:"true"===localStorage.getItem("bilibili_mute_instead")}[e]),set:(e,t)=>{localStorage.setItem(`bilibili_${e}`,JSON.stringify(t));}};this.universalAdSkipService=new pt(e),await this.universalAdSkipService.init(),ve.info("Main","通用广告跳过服务已初始化");}catch(t){ve.warn("Main","通用广告跳过服务初始化失败:",t.message);}if(this.isYouTube)try{await ht.init(),ve.info("Main","YouTube视频标签服务已初始化");}catch(t){ve.warn("Main","YouTube视频标签服务初始化失败:",t.message);}if((this.isBilibili||this.isYouTube&&"/watch"===location.pathname)&&this.createUI(),this.bindEvents(),(this.isBilibili||this.isYouTube&&"/watch"===location.pathname)&&this.setupAutomation(),this.registerMenuCommands(),this.registerShortcuts(),this.isBilibili)Re.checkSubtitleButton(),this.observeVideoChange();else if(this.isYouTube&&"/watch"===location.pathname){const e=Fe.getSubtitleService();e&&setTimeout(async()=>{await e.checkSubtitleAvailability();},2e3),this.observeVideoChange();}this.initialized=true;}}registerShortcuts(){Ce.register("toggleSubtitlePanel",()=>{we.togglePanel();}),Ce.register("toggleNotesPanel",()=>{bt.togglePanel();}),Ce.register("takeScreenshot",async()=>{try{const e=we.getVideoInfo(),t=e?.bvid,n=Se.getNotionConfig().apiKey&&t&&we.getNotionPageId(t);if(await lt.captureAndSave(n)){Ye.success(n?"截图已保存到笔记和Notion":"截图已保存到笔记");const e=document.querySelector(".notes-panel");e&&"none"!==e.style.display&&window.notesPanel?.render();}}catch(e){console.error("[Main] 截图失败:",e),Ye.error("截图失败: "+e.message);}}),Ce.register("speedIncrease",()=>{tt.adjustBaseSpeed(.1);}),Ce.register("speedDecrease",()=>{tt.adjustBaseSpeed(-0.1);}),Ce.register("speedReset",()=>{tt.resetToNormalSpeed();}),Ce.register("speedDouble",()=>{tt.setToDoubleSpeed();}),Ce.startListening();}registerMenuCommands(){if("undefined"==typeof GM_registerMenuCommand)return;this.isBilibili&&(GM_registerMenuCommand("AI配置",()=>{vt.showAIConfigModal();}),GM_registerMenuCommand("Notion配置",()=>{vt.showNotionConfigModal();})),GM_registerMenuCommand("📝 笔记管理",()=>{bt.togglePanel();});null!==document.querySelector("video")&&GM_registerMenuCommand("📸 截图",async()=>{try{if(await lt.captureAndSave(!1)){Ye.success("截图已保存到笔记");const e=document.querySelector(".notes-panel");e&&"none"!==e.style.display&&window.notesPanel?.render();}}catch(e){Ye.error("截图失败: "+e.message);}}),GM_registerMenuCommand("⌨️ 快捷键设置",()=>{if(ve.debug("Main","快捷键设置菜单被点击"),ve.debug("Main","eventHandlers 是否存在:",!!vt),ve.debug("Main","showShortcutConfigModal 是否存在:",!!vt?.showShortcutConfigModal),!vt||!vt.showShortcutConfigModal)return console.error("[Main] eventHandlers 或其方法未正确加载"),void Ye.error("快捷键设置功能未正确加载");vt.showShortcutConfigModal();}),this.isBilibili&&(GM_registerMenuCommand("🔄 重置字幕面板位置",()=>{const e=document.getElementById("subtitle-container");e?vt.resetContainerPosition(e):Ye.warning("字幕面板未初始化,请先加载视频");}),GM_registerMenuCommand("SponsorBlock 设置",()=>{wt.show();})),GM_registerMenuCommand("使用帮助",()=>{xt.show();}),this.isYouTube&&GM_registerMenuCommand("🚫 YouTube广告设置",()=>{this.showYouTubeAdSettings();}),GM_registerMenuCommand(`🔧 调试模式 (${ve.isDebugMode()?"开启":"关闭"})`,()=>{const e=ve.toggleDebugMode();Ye.info("调试模式已"+(e?"开启":"关闭")),e&&Ye.info("调试模式已开启,控制台将输出详细日志");});}async waitForPageReady(){return this.isBilibili?new Promise(t=>{const n=setInterval(()=>{document.querySelector(se)&&(clearInterval(n),t());},e);}):new Promise(e=>{"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>e(),{once:true}):e();})}createUI(){let e;if(this.ball=document.createElement("div"),this.ball.id="subtitle-ball",this.ball.title="字幕提取器",this.isBilibili)e=document.querySelector(se),e&&("relative"!==e.style.position&&"absolute"!==e.style.position&&(e.style.position="relative"),e.appendChild(this.ball));else if(this.isYouTube&&(e=document.querySelector("#movie_player")||document.querySelector(".html5-video-player"),e)){this.ball.style.right="10px",this.ball.style.top="10px",this.ball.style.transform="none",this.ball.style.zIndex="9999",e.appendChild(this.ball);const t=()=>{document.fullscreenElement||document.webkitFullscreenElement?this.ball.style.top="60px":this.ball.style.top="10px";};document.addEventListener("fullscreenchange",t),document.addEventListener("webkitfullscreenchange",t);}this.ball&&this.ball.addEventListener("click",()=>{if(this.ball.classList.contains("active")||this.ball.classList.contains("ai-summarizing"))this.container&&(this.container.classList.toggle("show"),ye.emit(N,this.container.classList.contains("show")));else if(this.ball.classList.contains("loading"))ve.debug("App","字幕正在加载中...");else {Fe.getSubtitleService()&&(this.isYouTube?je.manualFetchSubtitle().catch(e=>{ve.error("App","YouTube字幕获取失败:",e),Ye.error("获取字幕失败: "+e.message);}):this.isBilibili&&Re.toggleSubtitle());}}),this.createEmbeddedContainer();const t=gt.createNotionConfigModal();document.body.appendChild(t),vt.bindNotionConfigModalEvents(t);const n=gt.createAIConfigModal();document.body.appendChild(n),vt.bindAIConfigModalEvents(n);}createEmbeddedContainer(){let e;this.container=document.createElement("div"),this.container.id="subtitle-container",this.isBilibili?(e=document.querySelector(se),e&&("relative"!==e.style.position&&"absolute"!==e.style.position&&(e.style.position="relative"),e.appendChild(this.container))):this.isYouTube?setTimeout(()=>{if(e=document.querySelector("#secondary-inner")||document.querySelector("#secondary")||document.querySelector("#related")||document.querySelector("#columns"),e){const t=e.firstElementChild;t?e.insertBefore(this.container,t):e.appendChild(this.container),this.container.style.position="relative",this.container.style.left="auto",this.container.style.top="auto",this.container.style.marginBottom="16px",this.container.style.width="100%",this.container.style.maxWidth="400px",this.container.style.height="500px",this.container.classList.add("show");}else document.body.appendChild(this.container);},1e3):document.body.appendChild(this.container);}bindEvents(){ye.on(q,e=>{if(ve.info("App","监听到视频切换事件:",e),this.ball&&(this.ball.classList.remove("has-data","ai-loading"),this.updateBallStatus(f)),this.container){const e=this.container.querySelector("#subtitle-list-container");e&&(e.innerHTML='字幕列表等待加载字幕...');const t=this.container.querySelector("#summary-panel");t&&(t.innerHTML='等待字幕加载完成后生成AI总结...');}setTimeout(()=>{ve.debug("App","开始重新获取字幕..."),Re.checkSubtitleButton();},2e3);}),ye.on(k,(e,t)=>{this.renderSubtitles(e),vt.initializeSearchIndex(e);}),ye.on(C,()=>{ve.debug("App","AI总结开始,小球进入AI总结状态"),we.setBallStatus(S);const e=this.container?.querySelector(".ai-icon");e&&e.classList.add("loading");}),ye.on($,e=>{this.container&>.updateAISummary(this.container,e);}),ye.on(T,(e,t)=>{ve.debug("App","AI总结完成,恢复小球正常状态"),Ye.success("AI总结完成"),this.container&>.updateAISummary(this.container,e),we.setBallStatus(v);const n=this.container?.querySelector(".ai-icon");n&&n.classList.remove("loading");}),ye.on(M,()=>{Ye.success("字幕已成功发送到 Notion");const e=this.container?.querySelector(".notion-icon");e&&e.classList.remove("loading");}),ye.on(I,e=>{Ye.handleError(e,"字幕获取");}),ye.on(A,e=>{ve.debug("App","AI总结失败,恢复小球正常状态"),Ye.handleError(e,"AI总结"),we.setBallStatus(v);const t=this.container?.querySelector(".ai-icon");t&&t.classList.remove("loading");}),ye.on(P,e=>{Ye.handleError(e,"Notion发送");}),ye.on(L,e=>{this.updateBallStatus(e);}),ye.on(N,e=>{this.container&&(e?this.container.classList.add("show"):this.container.classList.remove("show"));});}renderSubtitles(e){if(!this.container||!e)return;this.container.innerHTML=gt.renderSubtitlePanel(e);const t=we.getVideoKey(),n=t?we.getAISummary(t):null;n&>.updateAISummary(this.container,n),vt.bindSubtitlePanelEvents(this.container),ve.debug("App","字幕面板已渲染");}setupAutomation(){ye.on(k,async e=>{await De(a);const t=Se.getAIAutoSummaryEnabled(),n=Se.getNotionAutoSendEnabled(),o=Se.getSelectedAIConfig(),i=Se.getNotionConfig(),s=we.getVideoKey(),r=s?we.getAISummary(s):null;if(t&&o&&o.apiKey&&!r)try{await Je.summarize(e,!1);}catch(l){console.error("[App] 自动总结失败:",l);}else if(n&&i.apiKey)try{const t=Se.getNotionContentOptions(),n=we.getVideoInfo();await Ge.sendToNotion({videoInfo:n,aiSummary:r,subtitleData:t.subtitles?e:null,isAuto:!0}),t.subtitles&&e&&ve.debug("App","字幕已自动发送到Notion");}catch(l){console.error("[App] 自动发送到Notion失败:",l);}}),ye.on(T,async e=>{ve.debug("App","AI总结完成,已由AIService处理Notion发送");});}updateBallStatus(e){if(this.ball)switch(this.ball.classList.remove("loading","active","no-subtitle","error","ai-summarizing"),e){case v:this.ball.classList.add("active"),this.ball.style.cursor="pointer",this.ball.title="字幕提取器 - 点击查看字幕";break;case x:this.ball.classList.add("no-subtitle"),this.ball.style.cursor="default",this.ball.title="该视频无字幕";break;case w:this.ball.classList.add("error"),this.ball.style.cursor="default",this.ball.title="字幕加载失败";break;case y:this.ball.classList.add("loading"),this.ball.style.cursor="default",this.ball.title="正在加载字幕...";break;case S:this.ball.classList.add("ai-summarizing"),this.ball.style.cursor="default",this.ball.title="正在AI总结...";}}observeVideoChange(){let e=location.href,t=location.href.match(/BV[1-9A-Za-z]{10}/)?.[0],n=null,o=parseInt(new URLSearchParams(window.location.search).get("p")||"1");const i=()=>{try{const e=unsafeWindow.__INITIAL_STATE__;return e?.videoData?.cid||e?.videoData?.pages?.[0]?.cid}catch(e){return null}};n=i();const s=()=>{const s=location.href,a=s.match(/BV[1-9A-Za-z]{10}/)?.[0],l=i(),c=new URLSearchParams(window.location.search),d=parseInt(c.get("p")||"1");s===e||a===t&&l===n&&d===o||(ve.debug("App","检测到视频切换:",{from:`${t}_p${o}`,to:`${a}_p${d}`,oldCid:n,newCid:l}),e=s,t=a,n=l,o=d,we.reset(),Re.reset(),ye.emit(q,{bvid:a,cid:l,p:d,oldP:o}),setTimeout(()=>{const e=Ne();we.setVideoInfo(e),Re.checkSubtitleButton();},r));},a=history.pushState,l=history.replaceState;history.pushState=function(...e){a.apply(this,e),s();},history.replaceState=function(...e){l.apply(this,e),s();},window.addEventListener("popstate",s);const c=setInterval(s,1e3);this.urlChangeCleanup=()=>{history.pushState=a,history.replaceState=l,window.removeEventListener("popstate",s),clearInterval(c);},ve.debug("App","视频切换监听已启动(使用 History API 劫持)");}showYouTubeAdSettings(){const e=document.createElement("div");if(e.className="youtube-ad-settings-modal",e.innerHTML=`\n \n \n `,!document.querySelector("#youtube-ad-settings-styles")){const e=document.createElement("style");e.id="youtube-ad-settings-styles",e.textContent='\n .youtube-ad-settings-modal {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 999999;\n }\n .settings-modal-overlay {\n position: absolute;\n inset: 0;\n background: rgba(0, 0, 0, 0.5);\n }\n .settings-modal-content {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n background: white;\n border-radius: 8px;\n width: 500px;\n max-height: 80vh;\n overflow-y: auto;\n box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);\n }\n .settings-modal-header {\n padding: 20px;\n border-bottom: 1px solid #e0e0e0;\n display: flex;\n justify-content: space-between;\n align-items: center;\n }\n .settings-modal-header h3 {\n margin: 0;\n font-size: 18px;\n }\n .settings-close-btn {\n background: none;\n border: none;\n font-size: 24px;\n cursor: pointer;\n padding: 0;\n width: 30px;\n height: 30px;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n .settings-modal-body {\n padding: 20px;\n }\n .setting-item {\n margin-bottom: 15px;\n }\n .setting-item label {\n display: block;\n cursor: pointer;\n user-select: none;\n }\n .setting-item input[type="checkbox"] {\n margin-right: 8px;\n }\n .setting-item input[type="number"] {\n width: 60px;\n padding: 4px;\n border: 1px solid #ddd;\n border-radius: 4px;\n }\n .category-checkboxes {\n margin-top: 10px;\n display: grid;\n grid-template-columns: repeat(2, 1fr);\n gap: 8px;\n }\n .category-checkboxes label {\n display: flex;\n align-items: center;\n }\n .settings-modal-footer {\n padding: 15px 20px;\n border-top: 1px solid #e0e0e0;\n display: flex;\n justify-content: flex-end;\n gap: 10px;\n }\n .settings-modal-footer button {\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n }\n .settings-save-btn {\n background: #ff0000;\n color: white;\n border: none;\n }\n .settings-save-btn:hover {\n background: #cc0000;\n }\n .settings-cancel-btn {\n background: #f0f0f0;\n border: 1px solid #ddd;\n color: #333;\n }\n .settings-cancel-btn:hover {\n background: #e0e0e0;\n }\n ',document.head.appendChild(e);}document.body.appendChild(e);const t=JSON.parse(localStorage.getItem("youtube_skip_categories")||'["sponsor", "selfpromo"]');e.querySelectorAll(".skip-category").forEach(e=>{e.checked=t.includes(e.value);});const n=()=>e.remove();e.querySelector(".settings-modal-overlay").addEventListener("click",n),e.querySelector(".settings-close-btn").addEventListener("click",n),e.querySelector(".settings-cancel-btn").addEventListener("click",n),e.querySelector(".settings-save-btn").addEventListener("click",()=>{localStorage.setItem("youtube_auto_skip",e.querySelector("#youtube-auto-skip").checked),localStorage.setItem("youtube_detect_native",e.querySelector("#youtube-native-detect").checked),localStorage.setItem("youtube_show_notifications",e.querySelector("#youtube-show-notifications").checked),localStorage.setItem("youtube_show_markers",e.querySelector("#youtube-show-markers").checked),localStorage.setItem("youtube_mute_instead",e.querySelector("#youtube-mute-instead").checked),localStorage.setItem("youtube_skip_delay",e.querySelector("#youtube-skip-delay").value);const t=[];e.querySelectorAll(".skip-category:checked").forEach(e=>{t.push(e.value);}),localStorage.setItem("youtube_skip_categories",JSON.stringify(t)),this.universalAdSkipService&&this.universalAdSkipService.updateConfig({autoSkip:e.querySelector("#youtube-auto-skip").checked,detectNativeAds:e.querySelector("#youtube-native-detect").checked,showNotifications:e.querySelector("#youtube-show-notifications").checked,showProgressMarkers:e.querySelector("#youtube-show-markers").checked,muteInsteadOfSkip:e.querySelector("#youtube-mute-instead").checked,skipDelay:parseInt(e.querySelector("#youtube-skip-delay").value),skipCategories:t}),Ye.success("设置已保存"),n();});}cleanup(){ve.debug("App","开始清理应用资源"),this.urlChangeCleanup&&this.urlChangeCleanup(),this.videoQualityService&&this.videoQualityService.stop(),rt.playerController&&rt.playerController.destroy(),tt.destroy(),searchIndex.clear(),Me.destroy(),St.cleanup(),ve.debug("App","应用资源清理完成");}};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>Et.init()):Et.init();
})();