const $=(s,r=document)=>r.querySelector(s), $$=(s,r=document)=>[...r.querySelectorAll(s)];
const ANSWERS_KEY="vdr-public-answers-v2", HF_DATASET_BASE="https://huggingface.co/datasets/hh721/vdr_temp/resolve/main";
const state={dataset:null,flat:[],current:0,answers:{},timer:{running:false,base:0,started:null,ticker:null}};
const currentItem=()=>state.flat[state.current], keyFor=i=>i.sample_id;
function emptyAnswer(i){return{question:i.sample_id,video_id:i.video_id,question_id:i.question_id,answer_text:"",state_claim:"",evidence_units:[{start_sec:"",end_sec:"",description:"",modality:""}],web_evidence:[{url:"",quote:"",support_claim:""}],time_spent_seconds:0,used_google_ai_overview:"",completed:false,updated_at:null};}
function formatTime(s){s=Math.max(0,Math.floor(Number(s)||0));return`${String(Math.floor(s/60)).padStart(2,"0")}:${String(s%60).padStart(2,"0")}`;}
function parseTime(v){const s=String(v).trim();if(/^\d+(\.\d+)?$/.test(s))return Number(s);const m=/^(\d+):([0-5]?\d(?:\.\d+)?)$/.exec(s);return m?Number(m[1])*60+Number(m[2]):NaN;}
function toast(m){const e=$("#toast");e.textContent=m;e.classList.add("show");clearTimeout(e._timer);e._timer=setTimeout(()=>e.classList.remove("show"),2200);}
function timerSeconds(){return Math.max(0,Math.floor(state.timer.base+(state.timer.running?(Date.now()-state.timer.started)/1000:0)));}
function renderTimer(){const s=timerSeconds();$("#timerDisplay").textContent=formatTime(s);$("#timeSpent").value=s;$("#toggleTimer").textContent=state.timer.running?"暂停计时":"继续计时";}
function startTimer(base=0){clearInterval(state.timer.ticker);Object.assign(state.timer,{base:Number(base)||0,started:Date.now(),running:true});state.timer.ticker=setInterval(renderTimer,1000);renderTimer();}
function pauseTimer(notify=true){if(state.timer.running){state.timer.base=timerSeconds();state.timer.running=false;state.timer.started=null;}clearInterval(state.timer.ticker);state.timer.ticker=null;renderTimer();if(notify)toast("计时已暂停");}
function resumeTimer(){if(state.timer.running)return;state.timer.started=Date.now();state.timer.running=true;state.timer.ticker=setInterval(renderTimer,1000);renderTimer();toast("计时已继续");}
async function init(){const d=await fetch("./dataset.json").then(r=>{if(!r.ok)throw Error("题目数据载入失败");return r.json();});let a={};try{a=JSON.parse(localStorage.getItem(ANSWERS_KEY)||localStorage.getItem("vdr-public-answers-v1")||"{}");}catch{}state.dataset=d;state.answers=a;state.flat=d.videos.flatMap(v=>v.questions.map(q=>({...q,video_id:v.video_id,video_available:v.video_available})));$("#datasetCount").textContent=`${d.total_videos} 个视频 · ${d.total_questions} 道题`;bindEvents();renderNav();loadQuestion(0);}
function bindEvents(){
$("#searchInput").oninput=renderNav;$("#addEvidence").onclick=()=>addEvidence({});$("#addWebEvidence").onclick=()=>addWebEvidence({});
$("#answerForm").oninput=()=>{$("#saveStatus").textContent="有未保存修改";scheduleSnapshot();};
$("#answerForm").onsubmit=async e=>{e.preventDefault();if(await saveCurrent(true))loadQuestion(Math.min(state.current+1,state.flat.length-1));};
$("#saveButton").onclick=()=>saveCurrent(false);$("#prevQuestion").onclick=()=>loadQuestion(Math.max(0,state.current-1));$("#nextQuestion").onclick=()=>loadQuestion(Math.min(state.flat.length-1,state.current+1));
$("#videoPlayer").ontimeupdate=()=>{$("#currentTime").textContent=formatTime($("#videoPlayer").currentTime);};$("#copyTime").onclick=async()=>{await navigator.clipboard.writeText(formatTime($("#videoPlayer").currentTime));toast("已复制当前时间");};
$("#captureStart").onclick=()=>captureVideoTime("start_sec");$("#captureEnd").onclick=()=>captureVideoTime("end_sec");$("#toggleTimer").onclick=()=>state.timer.running?pauseTimer():resumeTimer();$("#resetTimer").onclick=()=>{startTimer(0);toast("本题计时已重置");};
$("#exportCurrent").onclick=()=>{persist();exportJson([state.answers[keyFor(currentItem())]],`${currentItem().sample_id}.json`);};$("#exportAll").onclick=()=>{persist();saveAll();exportJson(Object.values(state.answers),"vdr_answers.json");};window.onbeforeunload=()=>{persist();localStorage.setItem(ANSWERS_KEY,JSON.stringify(state.answers));};
}
function renderNav(){if(!state.dataset)return;const term=$("#searchInput").value.trim().toLowerCase(),nav=$("#questionNav");nav.innerHTML="";for(const v of state.dataset.videos){const visible=v.questions.filter(q=>!term||v.video_id.toLowerCase().includes(term)||q.sample_id.toLowerCase().includes(term)||q.task_question.toLowerCase().includes(term)||(q.task_question_zh||"").toLowerCase().includes(term));if(!visible.length)continue;const g=document.createElement("div");g.className="video-group";if(visible.some(q=>state.flat[state.current]?.sample_id===q.sample_id)||term)g.classList.add("open");const done=v.questions.filter(q=>state.answers[q.sample_id]?.completed).length,t=document.createElement("button");t.className=`video-toggle ${done===v.questions.length?"complete":""}`;t.innerHTML=` ${v.video_id}${done}/${v.questions.length}`;t.onclick=()=>g.classList.toggle("open");g.append(t);const links=document.createElement("div");links.className="question-links";for(const q of visible){const b=document.createElement("button");b.className=`question-link ${q.sample_id===state.flat[state.current]?.sample_id?"active":""} ${state.answers[q.sample_id]?.completed?"done":""}`;b.innerHTML=`${q.question_id}`;b.title=q.task_question_zh||q.task_question;b.onclick=()=>loadQuestion(state.flat.findIndex(x=>x.sample_id===q.sample_id));links.append(b);}g.append(links);nav.append(g);}$("#progressCount").textContent=`已完成 ${Object.values(state.answers).filter(a=>a.completed).length}/${state.flat.length}`;}
function loadQuestion(index){persist();pauseTimer(false);state.current=index;const i=currentItem();if(!i)return;const a=state.answers[keyFor(i)]||emptyAnswer(i);state.answers[keyFor(i)]=a;$("#questionMeta").textContent=`${i.video_id} / ${i.question_id} · ${i.sample_id}`;$("#questionText").textContent=i.task_question_zh||i.task_question;$("#questionOriginal").textContent=`英文原题:${i.task_question}`;$("#videoPlayer").src=`${HF_DATASET_BASE}/videos/${encodeURIComponent(i.video_id)}.mp4`;$("#videoPlayer").load();$("#answerText").value=a.answer_text||"";$("#stateClaim").value=a.state_claim||"";$$('input[name="googleAi"]').forEach(x=>x.checked=x.value===a.used_google_ai_overview);$("#evidenceList").innerHTML="";(a.evidence_units?.length?a.evidence_units:[{}]).forEach(addEvidence);$("#webEvidenceList").innerHTML="";(a.web_evidence?.length?a.web_evidence:[{}]).forEach(addWebEvidence);const req=[];if(i.required_modalities?.audio_required)req.push('需要音频证据');if(i.required_modalities?.image_search_required)req.push('需要图片搜索');if(!req.length)req.push('无额外模态要求');$("#requirements").innerHTML=req.join("");startTimer(a.time_spent_seconds||0);$("#validationSummary").hidden=true;$("#saveStatus").textContent=a.updated_at?`已保存 ${new Date(a.updated_at).toLocaleTimeString()}`:"尚未保存";renderNav();window.scrollTo({top:0,behavior:"smooth"});}
function addEvidence(d={}){const n=$("#evidenceTemplate").content.firstElementChild.cloneNode(true);$("[data-field=start_sec]",n).value=d.start_sec===""||d.start_sec==null?"":formatTime(d.start_sec);$("[data-field=end_sec]",n).value=d.end_sec===""||d.end_sec==null?"":formatTime(d.end_sec);$("[data-field=description]",n).value=d.description||"";$("[data-field=modality]",n).value=d.modality||"";$(".remove-button",n).onclick=()=>{if($$(".evidence-card",$("#evidenceList")).length>1)n.remove();renumber();};$("#evidenceList").append(n);renumber();}
function addWebEvidence(d={}){const n=$("#webEvidenceTemplate").content.firstElementChild.cloneNode(true);for(const k of["url","quote","support_claim"])$(`[data-field=${k}]`,n).value=d[k]||"";$(".remove-button",n).onclick=()=>{if($$(".evidence-card",$("#webEvidenceList")).length>1)n.remove();renumber();};$("#webEvidenceList").append(n);renumber();}
function renumber(){$$("#evidenceList .item-index").forEach((x,i)=>x.textContent=i+1);$$("#webEvidenceList .item-index").forEach((x,i)=>x.textContent=i+1);}
function captureVideoTime(f){const target=$$("#evidenceList .evidence-card").at(-1)?.querySelector(`[data-field=${f}]`);if(target){target.value=formatTime($("#videoPlayer").currentTime);target.dispatchEvent(new Event("input",{bubbles:true}));toast(f==="start_sec"?"已填入开始时间":"已填入结束时间");}}
function collectForm(completed=true){const i=currentItem();return{question:i.sample_id,video_id:i.video_id,question_id:i.question_id,answer_text:$("#answerText").value.trim(),state_claim:$("#stateClaim").value.trim(),evidence_units:$$("#evidenceList .evidence-card").map(c=>({start_sec:parseTime($("[data-field=start_sec]",c).value),end_sec:parseTime($("[data-field=end_sec]",c).value),description:$("[data-field=description]",c).value.trim(),modality:$("[data-field=modality]",c).value})),web_evidence:$$("#webEvidenceList .evidence-card").map(c=>({url:$("[data-field=url]",c).value.trim(),quote:$("[data-field=quote]",c).value.trim(),support_claim:$("[data-field=support_claim]",c).value.trim()})),time_spent_seconds:timerSeconds(),used_google_ai_overview:$("input[name=googleAi]:checked")?.value||"",completed,updated_at:new Date().toISOString()};}
function validate(a){const e=[];if(!a.answer_text)e.push("填写最终答案");if(!a.state_claim)e.push("填写视频事实主张");a.evidence_units.forEach((x,i)=>{if(!Number.isFinite(x.start_sec)||!Number.isFinite(x.end_sec)||x.end_sec{if(!x.url||!x.quote||!x.support_claim)e.push(`补全网页证据 ${i+1}`);});if(!a.used_google_ai_overview)e.push("选择是否使用 Google AI Overview");return e;}
async function saveCurrent(advance=false){pauseTimer(false);const a=collectForm(true),errors=validate(a);if(errors.length){const b=$("#validationSummary");b.hidden=false;b.textContent=`请先完成:${errors.join("、")}`;b.scrollIntoView({behavior:"smooth",block:"center"});return false;}state.answers[keyFor(currentItem())]=a;await saveAll();toast(advance?"已保存,进入下一题":"本题已保存,计时已停止");return true;}
async function saveAll(){localStorage.setItem(ANSWERS_KEY,JSON.stringify(state.answers));$("#saveStatus").textContent=`已保存到本浏览器 ${new Date().toLocaleTimeString()}`;renderNav();}
function persist(){if(!state.flat.length||!currentItem())return;const old=state.answers[keyFor(currentItem())];if(!old)return;const d=collectForm(false);d.completed=old.completed||false;state.answers[keyFor(currentItem())]={...old,...d};}
let snapshotTimer;function scheduleSnapshot(){clearTimeout(snapshotTimer);snapshotTimer=setTimeout(()=>{persist();localStorage.setItem(ANSWERS_KEY,JSON.stringify(state.answers));},500);}
function exportJson(data,name){const blob=new Blob([JSON.stringify(data,null,2)+"\n"],{type:"application/json"}),a=document.createElement("a");a.href=URL.createObjectURL(blob);a.download=name;a.click();URL.revokeObjectURL(a.href);}
init().catch(e=>{$("#questionText").textContent=`载入失败:${e.message}`;console.error(e);});