(() => {
  "use strict";
  const workspace=window.parent !== window ? window.parent.Workspace : null;
  const projectId=workspace?.getProject()?.id || "";
  const programId=()=>window.MODULE_PROGRAM_ID;
  const backupKey=()=>"htzd-draft-recovery:"+projectId+":"+programId();
  const $=selector=>document.querySelector(selector);
  const state={timer:null,pending:Promise.resolve(),revision:0,saved:0,undo:[],last:null,restoring:false,history:false};
  const icons=()=>window.lucide?.createIcons();
  const status=text=>{$("#draft-state").textContent=text;};
  function current(){return window.CalculationEngine?.draft();}
  async function flush(){
    clearTimeout(state.timer);
    if(!workspace || !projectId || !state.revision || state.saved===state.revision || state.history)return;
    const revision=state.revision,draft=current();
    localStorage.setItem(backupKey(),JSON.stringify(draft));
    status("保存中");
    state.pending=state.pending.catch(()=>{}).then(async()=>{
      await workspace.saveDraft(programId(),draft,projectId);
      state.saved=revision;
      if(state.revision===revision)localStorage.removeItem(backupKey());
      status(state.revision===revision?"草稿已保存":"参数已修改");
    });
    try{await state.pending;}catch(error){status("保存失败");workspace.toast(error.message);throw error;}
  }
  window.CalculationWorkspace={flush};
  function modified(){
    if(state.restoring)return;
    if(state.history){state.history=false;$("#result-state").textContent="历史成果参数已修改";}
    const draft=current();
    if(JSON.stringify(draft)===JSON.stringify(state.last))return;
    if(state.last)state.undo.push(state.last);
    if(state.undo.length>50)state.undo.shift();
    state.last=draft;state.revision++;status("参数已修改");
    try{if(projectId)localStorage.setItem(backupKey(),JSON.stringify(draft));}catch(error){status("临时恢复副本写入失败");}
    clearTimeout(state.timer);state.timer=setTimeout(()=>flush().catch(()=>{}),600);
  }
  function resultTab(name){
    document.querySelectorAll("[data-result-tab]").forEach(b=>{const active=b.dataset.resultTab===name;b.classList.toggle("active",active);b.setAttribute("aria-selected",String(active));});
    document.querySelectorAll(".result-view").forEach(p=>p.hidden=p.dataset.resultView!==name);
    if(document.body.dataset.calcPane==='output'&&innerWidth>=700)requestAnimationFrame(()=>$('.result-card-wrap').scrollIntoView({block:'start'}));
  }
  function organize(result){
    const root=$(".result"),children=[...root.children];
    const panels={};
    for(const key of ["summary","tables","charts","book"]){
      const panel=document.createElement("div");panel.className="result-view";panel.dataset.resultView=key;panels[key]=panel;
    }
    for(const child of children){
      let key="summary";
      if(child.matches(".calculation-process,.calculation-formula,.source,.parameter-record"))key="book";
      else if(child.querySelector("svg.chart,svg.section-chart") || child.matches(".figure-tools"))key="charts";
      else if(child.querySelector("table") || child.matches(".table-download"))key="tables";
      panels[key].append(child);
    }
    const summary=document.createElement("div");summary.className="outcome-summary";
    const rows=result.metrics || result.result_rows || [];
    const selected=Array.isArray(rows)?rows.filter(r=>r && (r.value!==undefined || r.result!==undefined)).slice(0,8):[];
    if(selected.length && !panels.summary.querySelector('.kpi-card,.water-kpi-card,.outcome-summary')){
      selected.forEach(row=>{
        const item=document.createElement("article"),name=document.createElement("span"),value=document.createElement("strong"),unit=document.createElement("small");
        name.textContent=row.name || row.label || row.item || "成果";
        value.textContent=String(row.value ?? row.result ?? "");unit.textContent=row.unit || "";
        item.append(name,value,unit);summary.append(item);
      });
      panels.summary.prepend(summary);
    }
    if(!panels.summary.children.length){
      const p=document.createElement("p");p.className="result-empty";p.textContent="计算已完成，完整成果见结果表与计算书。";panels.summary.append(p);
    }
    for(const key of ["tables","charts","book"]){
      if(!panels[key].children.length){
        const p=document.createElement("p");p.className="result-empty";p.textContent=key==="charts"?"本项成果不包含曲线数据。":key==="tables"?"本项未返回独立成果表。":"本项未返回计算书。";panels[key].append(p);
      }
    }
    panels.book.querySelectorAll("details").forEach(d=>d.open=true);
    root.replaceChildren(...Object.values(panels));
    $("#result-state").textContent=state.history?"历史成果快照":"已计算";
    resultTab("summary");icons();
  }
  function pane(value){
    document.body.dataset.calcPane=value;
    document.querySelectorAll("button[data-calc-pane]").forEach(b=>b.classList.toggle("active",b.dataset.calcPane===value));
    if(innerWidth>=700)$(value==='input'?'.input-card':'.result-card-wrap').scrollIntoView({block:'start'});
  }
  window.addEventListener("calculation-ready",()=>{
    const header=$(".calc-header");
    new ResizeObserver(()=>document.documentElement.style.setProperty('--calc-header-height',header.getBoundingClientRect().height+'px')).observe(header);
    const engine=window.CalculationEngine;
    const entry=window.WORKSPACE_ENTRIES?.find(p=>p.member_ids.includes(programId()));
    const methodSelect=$("#calculation-mode");
    if(entry && methodSelect){
      let modes=entry.modes;
      if(!modes.length){
        const legacy=Object.entries(entry.legacy_labels || {}).filter(([id])=>workspace?.getDraft(id)||id===programId());
        if(legacy.length)modes=[{program_id:entry.program_id,name:"当前计算"},...legacy.map(([id,name])=>({program_id:id,name}))];
      }
      methodSelect.closest("label").hidden=!modes.length;
      for(const mode of modes){const option=new Option(mode.name,mode.program_id);methodSelect.add(option);}
      methodSelect.value=programId();
      methodSelect.onchange=async()=>{
        const target=methodSelect.value;methodSelect.disabled=true;
        try{await flush();if(workspace)workspace.navigate("calc/"+target);else location.href="calculation.html?program="+encodeURIComponent(target);}
        catch(error){workspace?.toast(error.message);methodSelect.value=programId();}
        finally{methodSelect.value=programId();methodSelect.disabled=false;}
      };
    }
    const recordId=new URLSearchParams(location.search).get("record");
    const record=recordId?workspace?.getRecord(recordId):null;
    let recovery=null;
    try{if(projectId)recovery=JSON.parse(localStorage.getItem(backupKey())||"null");}catch(error){workspace?.toast("临时草稿无法读取，已保留工程内的最近保存内容。");}
    const draft=recovery || workspace?.getDraft(programId());
    if(record){state.history=true;engine.restoreResult(record.params,record.result);organize(record.result);status("历史参数快照");}
    else if(draft){engine.restore(draft);status(recovery?"已恢复未完成保存的草稿":"已恢复工程草稿");}
    else status(projectId?"草稿自动保存":"未连接工程");
    state.last=current();
    if(recovery && !record){state.revision++;flush().catch(()=>{});}
    $(".input-card").addEventListener("input",e=>{if(e.target.type!=="search")modified();});
    $(".input-card").addEventListener("change",e=>{if(e.target.type!=="search")modified();});
    $("[data-fill-example]")?.addEventListener("click",()=>{modified();icons();});
    $("#save-draft").onclick=()=>{state.revision++;state.history=false;flush().catch(()=>{});};
    $("#undo-input").onclick=()=>{
      const draft=state.undo.pop();if(!draft)return;
      state.restoring=true;engine.restore(draft);state.last=current();state.restoring=false;state.revision++;state.history=false;flush().catch(()=>{});
    };
    $("#reset-input").onclick=()=>{
      const dialog=document.createElement("dialog");
      dialog.innerHTML='<h2>清空本页参数？</h2><p>已归档的计算成果会保留。</p><footer><button data-cancel>取消</button><button class="primary" data-confirm>清空参数</button></footer>';
      dialog.querySelector("[data-cancel]").onclick=()=>dialog.close();
      dialog.querySelector("[data-confirm]").onclick=()=>{
        state.undo.push(current());state.restoring=true;
        const fields=Object.fromEntries(engine.fields().map(f=>[f.key,f.type==="select"?(f.default ?? ""):""]));
        engine.restore({fields});state.last=current();state.restoring=false;state.history=false;state.revision++;flush().catch(()=>{});dialog.close();
      };dialog.addEventListener("close",()=>dialog.remove());document.body.append(dialog);dialog.showModal();
    };
    $("#context-source").textContent=$(".program-source").textContent;
    $("#toggle-context").onclick=()=>{
      const panel=$("#parameter-context");panel.hidden=!panel.hidden;$("#toggle-context").setAttribute("aria-expanded",String(!panel.hidden));
    };
    $(".form-grid").addEventListener("focusin",e=>{
      const field=engine.fields().find(f=>f.key===e.target.name);
      if(field){$("#context-title").textContent=field.label || field.key;$("#context-help").textContent=field.help || e.target.closest(".field-item")?.querySelector(".field-help")?.textContent || "";}
    });
    document.querySelectorAll("[data-result-tab]").forEach(b=>b.onclick=()=>resultTab(b.dataset.resultTab));
    document.querySelectorAll("button[data-calc-pane]").forEach(b=>b.onclick=()=>pane(b.dataset.calcPane));
    const word=$('[data-action="export"]'),excel=$('[data-action="generate-book"]');
    word.textContent="Word";word.title="导出 Word 计算书";excel.textContent="Excel";excel.title="导出 Excel 成果与图表";
    const cad=$('[data-action="export-cad-section"]');if(cad){cad.textContent="DXF";cad.title="导出 CAD 断面图";}
    const tools=$(".parameter-tools");if(tools){
      const paragraphs=tools.querySelectorAll("p");paragraphs.forEach(p=>p.hidden=true);
      const example=$("[data-fill-example]");if(example){example.textContent="示例";example.title="填入空白参数的教学示例，使用前请核定";}
    }
    const cadImport=new URLSearchParams(location.search).get("cad") || sessionStorage.getItem("htzd-workspace-cad-ready");
    if(programId()==="4-02" && cadImport && !record){
      try{
        const data=JSON.parse(sessionStorage.getItem("htzd-reviewed-cad-section")||"null");
        if(data?.profile?.length>=2){
          const next=engine.draft();next.fields.points=data.profile.map(p=>p.offset+","+p.elevation).join(";");
          next.sources.points="CAD 导入："+data.file;engine.restore(next);modified();
          sessionStorage.removeItem("htzd-workspace-cad-ready");
        }
      }catch(error){workspace?.toast("断面草稿读取失败，请重新导入。");}
    }
    icons();
  });
  window.addEventListener("calculation-invalidated",()=>{$("#result-state").textContent="待重新计算";});
  window.addEventListener("calculation-complete",async event=>{
    const {programId:id,params,result}=event.detail;
    state.history=false;organize(result);modified();
    if(workspace && projectId){
      try{await flush();await workspace.saveRecord(id,params,result,projectId);$("#result-state").textContent="已归档";}catch(error){$("#result-state").textContent="归档失败";workspace.toast(error.message);}
    }else $("#result-state").textContent="已计算 · 未归档";
    pane("output");
  });
})();
