const AppIcon = window.PrototypeIcon;

function CompletePrototypeApp() {
  const [surface, setSurface] = React.useState("meegle");
  const [stage, setStage] = React.useState("detected");
  const [larkSection, setLarkSection] = React.useState("chat");
  const [adminRequestedSection, setAdminRequestedSection] = React.useState("overview");
  const [comments, setComments] = React.useState(window.workComments);
  const [auditEvents, setAuditEvents] = React.useState(window.baseAuditEvents);
  const [employees, setEmployees] = React.useState(window.prototypeEmployees);
  const [policies, setPolicies] = React.useState(window.prototypePolicies);
  const [connections, setConnections] = React.useState(window.prototypeConnections);
  const [knowledgeSources, setKnowledgeSources] = React.useState(window.prototypeKnowledgeSources);
  const [credentials, setCredentials] = React.useState(window.prototypeCredentials);
  const [runtimes, setRuntimes] = React.useState(window.prototypeRuntimes);
  const [teamMembers, setTeamMembers] = React.useState([]);
  const [decision, setDecision] = React.useState(null);
  const [deliverableVersion, setDeliverableVersion] = React.useState(1);
  const [acceptanceRound, setAcceptanceRound] = React.useState(1);
  const [runPaused, setRunPaused] = React.useState(false);
  const [incident, setIncident] = React.useState(null);
  const [feedback, setFeedback] = React.useState(null);
  const [improvement, setImprovement] = React.useState({ status: "none", version: "v4" });
  const [toast, setToast] = React.useState(null);
  const [modal, setModal] = React.useState(null);
  const [confirm, setConfirm] = React.useState(null);
  const toastTimer = React.useRef(null);
  const deliveryTimer = React.useRef(null);
  const currentStage = window.prototypeStages.find(item => item.id === stage) || window.prototypeStages[0];

  const notify = (title, detail = "", tone = "success") => {
    window.clearTimeout(toastTimer.current);
    setToast({ title, detail, tone });
    toastTimer.current = window.setTimeout(() => setToast(null), 3600);
  };
  const addAudit = (type, title, detail, actor = "系统", level = "neutral") => {
    setAuditEvents(current => [...current, { id: `e${Date.now()}${Math.random()}`, time: new Date().toLocaleTimeString("zh-CN", { hour12: false }), actor, type, title, detail, level }]);
  };
  const addAiComment = text => setComments(current => [...current, { id: `c${Date.now()}`, author: "AI 工作平台", avatar: "AI", time: "刚刚", text, kind: "ai" }]);

  const changeSurface = next => {
    if (next === "admin") setAdminRequestedSection("overview");
    setSurface(next);
    notify(next === "meegle" ? "已切换到 Meegle 集成场景" : next === "lark" ? "已切换到飞书集成场景" : "已切换到 HyperWork 控制台", next === "admin" ? "这里是自有产品界面，只展示治理所需的最小数据范围。" : "第三方客户端仅作交互模拟；高亮区域由 HyperWork 提供。", "info");
  };
  const goLark = section => { setLarkSection(section || "chat"); setSurface("lark"); };
  const goAdmin = section => { setAdminRequestedSection(section || "runs"); setSurface("admin"); };
  const goMeegle = () => setSurface("meegle");
  const openRunConfiguration = () => {
    setStage("plan");
    setLarkSection("chat");
    setSurface("lark");
    addAudit("DispatchProposalPresented", "发起确认卡已送达", "DP-0813-007：项目研究员 v4、报告交付、预算 ¥220、指定数据范围。", "飞书适配器");
    notify("派工提案已发送到飞书", "确认前 Run、ExternalBinding、Workspace 和 Attempt 均不存在。", "info");
  };

  const startRun = ({ name, deliverable }) => {
    setModal(null);
    setStage("context");
    setDecision(null);
    addAudit("RunCreated", "创建 RUN-TEST-0812-002", `${name}；交付物：${deliverable}`, "Rowan");
    addAudit("ContextRequested", "请求补充联调边界", "飞书私聊卡片已发送给 Story 负责人 Rowan。", "平台联调负责人");
    addAiComment("已创建 RUN-TEST-0812-002，并向负责人发送上下文补充卡片；Story 仍是业务真相。");
    notify("Run 已创建", "接下来请在飞书确认测试写回和关闭规则。");
  };
  const submitContext = value => {
    setStage("plan");
    addAudit("ContextSnapshot", "上下文快照已冻结", `负责人补充：${value}`, "Rowan");
    addAudit("PlanProposed", "项目研究员已生成计划", "研究、证据核验和正式报告三项工作，预计 18 分钟。", "项目研究员");
    addAiComment("负责人已补充限制条件。上下文快照已冻结，项目研究员计划等待确认。");
    notify("上下文已提交", "项目研究员已生成执行计划。", "success");
  };
  const confirmPlan = () => {
    setStage("running");
    setDecision(null);
    addAudit("DispatchConfirmed", "Rowan 确认 DP-0813-007", "同时预授权在指定目录创建 L1 飞书文档草稿。", "Rowan", "success");
    addAudit("RunCreated", "原子创建 Run 与 ExternalBinding", "RUN-TEST-0813-007 · Story Family generation #7 · 活跃守卫已获得。", "Run 编排器", "success");
    addAudit("ActorRunStarted", "项目研究员 v4 开始执行", "1 ActorRun · 1 PairSession · Codex Attempt #1；生产凭据不进入 Workspace。", "Run 编排器");
    addAiComment("发起提案已确认。项目研究员 v4 开始执行；飞书草稿将由 Document Gateway 创建，而不是由 Codex 直写。");
    notify("Run 已创建并开始执行", "V1 为单员工、单 ActorRun、单 PairSession。", "success");
  };
  const requestPlanChange = () => {
    setStage("plan");
    setDecision(null);
    addAudit("DispatchProposalChanged", "负责人调整派工范围", "Run 暂未创建；提案更新后仍在原卡再次确认。", "Rowan", "warning");
    notify("派工提案已更新", "仍未创建 Run 或启动 Attempt。", "info");
  };
  const advanceRun = () => {
    if (runPaused) { notify("Run 当前已暂停", "请先继续 Run，再推进执行。", "danger"); return; }
    setStage("review");
    setDecision(null);
    addAudit("ActionIntentSubmitted", "Codex 提交交付内容、证据与 ActionIntent", "执行引擎未接触飞书生产凭据。", "Codex Attempt #1");
    addAudit("DocumentGatewayReceipt", `Document Gateway 创建交付草稿 v${deliverableVersion}`, "L1 可逆写入 · 使用发起确认预授权 · 幂等回执 DOC-0813-007。", "Document Gateway", "success");
    addAudit("AcceptanceRoundCreated", `创建验收轮 ${acceptanceRound}`, `绑定不可变 DeliverableVersion v${deliverableVersion}；每轮最多一个决定。`, "交付循环");
    addAiComment(`内部调研报告 v${deliverableVersion} 已生成，正在等待第 ${acceptanceRound} 轮验收。通过即完成 Run 并授权异步回写；无需单独发布审批。`);
    notify("交付版本已进入验收", "这是第 2 个人工触点。", "success");
  };
  const resolveApproval = result => {
    if (result === "accepted") { acceptWork(); return; }
    setDecision(result);
    if (result === "approved") {
      setStage("delivering");
      addAudit("ApprovalDecision", "Rowan 批准测试写回", "允许按不可变快照范围执行；不能扩大 Story 或字段范围。", "Rowan", "success");
      addAudit("AuthorizedActionStarted", "动作网关开始执行", "使用 Meegle 测试空间应用身份。", "动作网关");
      notify("已批准，正在执行", "范围已锁定；结果会写入同一审计链。", "success");
      window.clearTimeout(deliveryTimer.current);
      deliveryTimer.current = window.setTimeout(() => {
        setStage("review");
        addAudit("ActionCompleted", "测试写回模拟成功", "评论、文档链接和待验收状态回执 3/3。", "动作网关", "success");
        addAudit("DeliveryWrittenBack", "交付摘要已回写 Meegle", "仅包含文档链接、证据摘要和待验收状态。", "Meegle 适配器", "success");
        addAiComment("交付已完成：联调报告、证据清单、测试写回回执 3/3。请负责人完成最终验收。");
        notify("交付完成，等待验收", "请回到 Meegle 查看文档和证据。", "success");
      }, 1100);
    } else if (result === "modify") {
      setStage("plan");
      addAudit("ApprovalDecision", "Rowan 要求修改", "缩小测试写回字段后重新提交审批。", "Rowan", "warning");
      addAiComment("负责人要求缩小测试写回范围。Run 已回到计划阶段。");
      notify("已要求修改", "Run 已暂停并返回计划阶段。", "info");
    } else if (result === "rejected") {
      addAudit("ApprovalDecision", "Rowan 拒绝测试写回", "本次不会修改 Meegle 内容。", "Rowan", "danger");
      addAiComment("负责人拒绝了本次测试写回；联调报告仍保留在飞书，可人工查看。");
      notify("测试写回已拒绝", "不会修改 Meegle Story。", "danger");
    } else {
      setRunPaused(true);
      addAudit("HumanTakeover", "Rowan 人工接管", "AI 停止第三方写回；控制权交还负责人。", "Rowan", "warning");
      addAiComment("负责人已人工接管。本次 AI 写回停止，联调报告和证据仍可查看。");
      notify("已人工接管", "Run 已暂停，AI 不会继续执行外部动作。", "info");
    }
  };
  const acceptWork = () => {
    setStage("completed_sync");
    addAudit("AcceptanceDecision", `第 ${acceptanceRound} 轮验收通过`, `不可变决定绑定 DeliverableVersion v${deliverableVersion}；重复回调将被幂等拒绝。`, "Rowan", "success");
    addAudit("RunCompleted", "RUN-TEST-0813-007 已完成", "完成事实来自 AcceptanceDecision，不等待 Meegle API。", "交付循环", "success");
    addAudit("WritebackTaskCreated", "创建 Meegle 异步投影任务", "WB-0813-022 · pending · projection generation #7。", "同步服务", "warning");
    addAiComment("验收已通过，Run 已完成。Meegle 当前仍显示待验收：WritebackTask 正在异步同步，这不会回退 Run 状态。");
    notify("Run 已完成，Meegle 待同步", "验收事实已落盘；第三方投影状态独立。", "success");
  };
  const requestWorkChanges = (feedback = { category: "证据", comment: "关键结论需要补充可追溯来源，并说明证据版本。" }) => {
    setStage("running");
    setDecision(null);
    setDeliverableVersion(current => current + 1);
    setAcceptanceRound(current => current + 1);
    addAudit("AcceptanceDecision", `第 ${acceptanceRound} 轮结构化退回`, `绑定 DeliverableVersion v${deliverableVersion}；类型：${feedback.category}；意见：${feedback.comment}；同 PairSession 从检查点续做。`, "Rowan", "warning");
    addAudit("AttemptStarted", "同 PairSession 创建新的 Codex Attempt", "携带结构化退回意见从 CP-014 续做，不覆盖已验收版本。", "运行时控制器");
    addAiComment(`验收未通过（${feedback.category}）：${feedback.comment} 项目研究员将在同一 PairSession 中续做，并生成新的不可变交付版本。`);
    notify(`已按“${feedback.category}”退回`, "续做会产生新 DeliverableVersion 和新验收轮。", "info");
  };

  const completeWriteback = () => {
    if (stage !== "completed_sync") return;
    setStage("accepted");
    addAudit("WritebackSucceeded", "Meegle 投影同步完成", "WB-0813-022 · generation #7 校验通过；评论、当前指针与状态回执已记录。", "Action Gateway", "success");
    addAiComment("Meegle 投影已同步完成。Run 的验收事实未变化；现在两端视图一致。");
    notify("Meegle 已同步", "WritebackTask succeeded · projection generation #7。", "success");
  };
  const toggleRun = () => {
    setRunPaused(current => {
      const next = !current;
      addAudit(next ? "RunPaused" : "RunResumed", next ? "Run 已暂停" : "Run 已继续", next ? "所有 ActorRun 已保存检查点。" : "从最近检查点恢复执行。", "Rowan", next ? "warning" : "success");
      notify(next ? "Run 已暂停" : "Run 已继续", next ? "所有执行状态已安全保存。" : "已从最近检查点恢复。", next ? "info" : "success");
      return next;
    });
  };
  const addHumanComment = text => {
    setComments(current => [...current, { id: `c${Date.now()}`, author: "Rowan", avatar: "R", time: "刚刚", text, kind: "human" }]);
    addAudit("CollaborationMessage", "负责人补充协作消息", text, "Rowan");
    notify("消息已发送", "AI 工作平台会把它加入当前 Run 的协作上下文。", "success");
  };
  const createEmployee = values => {
    const id = `employee-${Date.now()}`;
    setEmployees(current => [...current, { id, initials: values.name.slice(0, 1), name: values.name, role: values.role, tone: "blue", status: "停用", model: values.model || "GPT-5.2", skills: [values.sop === "从空白 SOP 开始" ? "待配置" : values.sop.replace(/ SOP.*/, "")], tools: values.channel?.includes("飞书") ? ["飞书消息", "飞书文档"] : ["飞书文档"], budget: values.budget || "¥50 / ActorRun", description: values.description }]);
    setModal(null);
    addAudit("AIEmployeeDraftCreated", `创建 AI 员工草稿：${values.name}`, `角色：${values.role}；知识：${values.knowledge}；策略：${values.policy}。`, "袁野");
    notify("AI 员工草稿已创建", "完成权限检查和回归验证后，才能发布为在岗员工。", "success");
  };
  const toggleEmployee = id => {
    setEmployees(current => current.map(employee => employee.id === id ? { ...employee, status: employee.status === "启用" ? "停用" : "启用" } : employee));
    notify("员工状态已更新", "变更只影响新的 Run；已在运行的 ActorRun 不受影响。", "success");
  };
  const togglePolicy = id => {
    setPolicies(current => current.map(policy => policy.id === id ? { ...policy, enabled: !policy.enabled } : policy));
    addAudit("PolicyChanged", `策略 ${id} 状态已变更`, "变更从下一个动作授权请求开始生效。", "袁野");
    notify("策略已更新", "现有批准快照不会被新的配置覆盖。", "success");
  };
  const testConnection = id => {
    setConnections(current => current.map(connection => connection.id === id ? { ...connection, status: "正常", checked: "刚刚" } : connection));
    notify("连接测试成功", "读取、写入和回调权限均符合当前配置。", "success");
  };
  const triggerIncident = () => {
    if (stage !== "running" || incident === "blocked") return;
    setIncident("blocked");
    setRunPaused(true);
    addAudit("LeaseRevoked", "可靠执行验证的 Codex Attempt #1 心跳超时", "Lease LS-9087 已撤销；已保存检查点 CP-014，fencing token 推进到 #45。", "运行时控制器", "danger");
    addAiComment("执行遇到可恢复阻塞：可靠执行验证的 Codex Attempt 失联。平台已保存 CP-014 并隔离旧 Attempt，业务工作项保持“进行中”。");
    notify("Codex Attempt 已安全隔离", "旧 Lease 已撤销，可从 CP-014 绑定新的 Attempt。", "danger");
  };
  const recoverIncident = strategy => {
    if (incident !== "blocked") return;
    setIncident("recovering");
    addAudit("CodexRebindStarted", "从 CP-014 绑定 Codex Attempt #2", "恢复 TaskFrame、Workspace 与动作回执游标；不重复已完成步骤。", "袁野", "warning");
    notify("正在安全重绑", "新的 Codex Attempt 将使用 fencing token #45。", "info");
    window.setTimeout(() => {
      setIncident("resolved");
      setRunPaused(false);
      addAudit("CodexAttemptBound", "可靠执行验证已绑定 Codex Attempt #2", "从事件 #1047 继续；Attempt #1 的迟到事件将被 fencing token 拒绝。", "运行时控制器", "success");
      addAiComment("可靠执行验证已从检查点 CP-014 恢复到新的 Codex Attempt，未重复已完成步骤或第三方写回。预计交付时间恢复为 2 分钟后。");
      notify("安全重绑完成", "ActorRun 已继续，恢复证据已写入审计链。", "success");
    }, 950);
  };
  const submitFeedback = values => {
    setFeedback({ ...values, submittedAt: "刚刚" });
    setImprovement({ status: "suggested", version: "v4" });
    setModal(null);
    addAudit("EvaluationCreated", `业务负责人提交 ${values.rating}/5 评价`, `${values.tags.join(" · ")}；已生成员工改进提案草稿。`, "Rowan", "success");
    notify("评价已提交", "平台生成了一条待管理员评审的改进提案。", "success");
  };
  const createKnowledgeSource = values => {
    setKnowledgeSources(current => [...current, { id: `knowledge-${Date.now()}`, ...values, permission: "沿用操作者权限", version: "待首次同步", sync: "刚刚", status: "正在校验" }]);
    setModal(null);
    addAudit("KnowledgeSourceAdded", `添加知识源：${values.name}`, `${values.type}；授权给 ${values.scope}。`, "袁野");
    notify("知识源已添加", "正在校验飞书权限与可引用版本。", "success");
  };
  const rotateCredential = id => {
    setCredentials(current => current.map(item => item.id === id ? { ...item, expires: "90 天后", status: "正常" } : item));
    addAudit("CredentialReferenceRotated", "服务身份引用已轮换", "密钥值未进入平台数据库或审计记录。", "袁野", "success");
    notify("凭据引用已轮换", "新引用仅影响后续授权动作。", "success");
  };
  const verifyRuntime = id => {
    setRuntimes(current => current.map(item => item.id === id ? { ...item, status: "刚刚验证" } : item));
    notify("运行环境验证通过", "镜像、网络策略、工具清单与资源上限均可用。", "success");
  };
  const publishImprovement = () => {
    setImprovement({ status: "published", version: "v5" });
    setModal(null);
    addAudit("AIEmployeeVersionPublished", "项目研究员 v5 已发布", "验收意见逐项回应检查已加入交付前门禁；只影响新 Run。", "袁野", "success");
    notify("项目研究员 v5 已发布", "已经运行的 Run 继续使用冻结的 v4。", "success");
  };
  const cancelRun = () => setConfirm({ title: "取消当前 Run？", subtitle: "这不会删除审计记录或 Meegle 工作项。", body: "ActorRun 将停止并保存最后检查点；已完成的第三方写入不会自动撤销。", confirmLabel: "取消 Run", tone: "danger", icon: "stop", onConfirm: () => { setConfirm(null); setRunPaused(false); setStage("detected"); setDecision(null); addAudit("RunCancelled", "RUN-TEST-0813-007 已取消", "Story 保留在 Meegle，可重新生成 DispatchProposal。", "袁野", "danger"); notify("Run 已取消", "Meegle Story 仍然存在，可以重新发起新的 Run。", "danger"); } });
  const resetDemo = () => setConfirm({ title: "重置完整演示？", subtitle: "回到 Meegle 工作项已识别、只有 DispatchProposal 的状态。", body: "本地原型中的恢复流程、评论、验收、同步与审计事件都会恢复为初始演示数据。", confirmLabel: "重置演示", tone: "danger", icon: "reset", onConfirm: () => { window.clearTimeout(deliveryTimer.current); setConfirm(null); setSurface("meegle"); setStage("detected"); setAdminRequestedSection("overview"); setLarkSection("chat"); setComments(window.workComments); setAuditEvents(window.baseAuditEvents); setEmployees(window.prototypeEmployees); setPolicies(window.prototypePolicies); setConnections(window.prototypeConnections); setKnowledgeSources(window.prototypeKnowledgeSources); setCredentials(window.prototypeCredentials); setRuntimes(window.prototypeRuntimes); setTeamMembers([]); setDecision(null); setDeliverableVersion(1); setAcceptanceRound(1); setRunPaused(false); setIncident(null); setFeedback(null); setImprovement({ status: "none", version: "v4" }); setModal(null); notify("演示已重置", "从 DispatchProposal 开始，Run 尚未创建。", "info"); } });

  return <div className="prototype-root" data-surface={surface}>
    <GlobalHeader surface={surface} stage={currentStage} onSurfaceChange={changeSurface} onReset={resetDemo}></GlobalHeader>
    <div className={`surface-stage ${surface === "admin" ? "owned-mode" : "external-mode"}`}>
      <ExperienceBoundaryBar surface={surface} stage={stage}></ExperienceBoundaryBar>
      {surface === "meegle" ? <MeegleWorkspace stage={stage} currentStage={currentStage} comments={comments} auditEvents={auditEvents} runPaused={runPaused} decision={decision} incident={incident} feedback={feedback} deliverableVersion={deliverableVersion} acceptanceRound={acceptanceRound} onStart={openRunConfiguration} onOpenRun={() => goAdmin("runs")} onAdvance={advanceRun} onAccept={acceptWork} onSync={completeWriteback} onFeedback={() => setModal("feedback")} onRequestChanges={requestWorkChanges} onPause={toggleRun} onTriggerIncident={triggerIncident} onComment={addHumanComment} onGoLark={goLark}></MeegleWorkspace> : null}
      {surface === "lark" ? <LarkWorkspace stage={stage} currentStage={currentStage} section={larkSection} onSectionChange={setLarkSection} decision={decision} incident={incident} deliverableVersion={deliverableVersion} acceptanceRound={acceptanceRound} onContextSubmit={submitContext} onPlanConfirm={confirmPlan} onPlanChange={requestPlanChange} onApproval={resolveApproval} onAdvance={advanceRun} onAccept={acceptWork} onRequestChanges={requestWorkChanges} onSync={completeWriteback} onOpenRecovery={() => goAdmin("runs")} onOpenMeegle={goMeegle} onDocumentComment={addHumanComment}></LarkWorkspace> : null}
      {surface === "admin" ? <V6AdminWorkspace stage={stage} currentStage={currentStage} requestedSection={adminRequestedSection} employees={employees} policies={policies} connections={connections} knowledgeSources={knowledgeSources} credentials={credentials} runtimes={runtimes} auditEvents={auditEvents} runPaused={runPaused} incident={incident} feedback={feedback} improvement={improvement} teamMembers={teamMembers} deliverableVersion={deliverableVersion} acceptanceRound={acceptanceRound} onNewEmployee={() => setModal("employee")} onToggleEmployee={toggleEmployee} onEditTeam={() => setModal("team")} onTogglePolicy={togglePolicy} onTestConnection={testConnection} onAddKnowledge={() => setModal("knowledge")} onRotateCredential={rotateCredential} onVerifyRuntime={verifyRuntime} onTriggerIncident={triggerIncident} onRecoverIncident={recoverIncident} onReviewImprovement={() => setModal("improvement")} onPauseRun={toggleRun} onCancelRun={cancelRun} onAdvance={advanceRun} onSync={completeWriteback} onExportAudit={() => notify("审计链已导出", "原型已模拟生成 RUN-TEST-0813-007-audit.json。", "success")} onNotify={notify} onGoMeegle={goMeegle} onGoLark={() => goLark("chat")}></V6AdminWorkspace> : null}
    </div>
    <Toast toast={toast} onClose={() => setToast(null)}></Toast>
    {modal === "employee" ? <NewEmployeeForm onCancel={() => setModal(null)} onCreate={createEmployee}></NewEmployeeForm> : null}
    {modal === "feedback" ? <FeedbackForm onCancel={() => setModal(null)} onSubmit={submitFeedback}></FeedbackForm> : null}
    {modal === "knowledge" ? <V9KnowledgeSourceForm employees={employees} onCancel={() => setModal(null)} onCreate={createKnowledgeSource}></V9KnowledgeSourceForm> : null}
    {modal === "improvement" ? <ImprovementReviewModal improvement={improvement} onCancel={() => setModal(null)} onPublish={publishImprovement}></ImprovementReviewModal> : null}
    <ConfirmDialog config={confirm} onClose={() => setConfirm(null)}></ConfirmDialog>
  </div>;
}

ReactDOM.createRoot(document.getElementById("root")).render(<CompletePrototypeApp></CompletePrototypeApp>);
