const V7AdminIcon = window.PrototypeIcon;

function V9KnowledgeSourceForm({ employees, onCancel, onCreate }) {
  const activeEmployees = (employees || []).filter(employee => employee.status === "启用");
  const [name, setName] = React.useState("");
  const [type, setType] = React.useState("飞书 Wiki");
  const [scope, setScope] = React.useState(activeEmployees[0]?.name || "项目研究员");
  const [error, setError] = React.useState("");
  const submit = () => {
    if (!name.trim()) { setError("请输入知识源名称"); return; }
    onCreate({ name: name.trim(), type, scope });
  };
  return <Modal title="添加知识源" subtitle="绑定给一名长期 AI 员工；仅保存引用和访问策略。" onClose={onCancel} footer={<><PrototypeButton onClick={onCancel}>取消</PrototypeButton><PrototypeButton tone="primary" icon="plus" onClick={submit}>添加知识源</PrototypeButton></>}><div className="form-grid"><label className="field full"><span>知识源名称 <b>*</b></span><input value={name} placeholder="例如：AI 员工平台设计 Wiki" onChange={event => { setName(event.target.value); setError(""); }}></input></label><label className="field"><span>来源类型</span><select value={type} onChange={event => setType(event.target.value)}><option>飞书 Wiki</option><option>飞书文档目录</option><option>飞书多维表格</option></select></label><label className="field"><span>授权给 AI 员工</span><select value={scope} onChange={event => setScope(event.target.value)}>{activeEmployees.length ? activeEmployees.map(employee => <option key={employee.id}>{employee.name}</option>) : <option>项目研究员</option>}</select></label><div className="permission-preview full"><V7AdminIcon name="lock"></V7AdminIcon><div><strong>沿用操作者权限</strong><p>绑定员工不等于扩大权限；Run 创建时会冻结引用版本和当次访问决策。</p></div></div>{error ? <p className="form-error full"><V7AdminIcon name="warning" size={14}></V7AdminIcon>{error}</p> : null}</div></Modal>;
}

function V6AdminWorkspace(props) {
  const {
    stage, currentStage, requestedSection, employees, policies, connections,
    knowledgeSources, credentials, runtimes, auditEvents, runPaused, incident, feedback, improvement,
    deliverableVersion, acceptanceRound, onNewEmployee, onToggleEmployee, onTogglePolicy,
    onTestConnection, onAddKnowledge, onRotateCredential, onVerifyRuntime,
    onTriggerIncident, onRecoverIncident, onReviewImprovement, onPauseRun,
    onCancelRun, onAdvance, onSync, onExportAudit, onNotify, onGoMeegle, onGoLark
  } = props;
  const [section, setSection] = React.useState(requestedSection || "overview");
  const [selectedEmployee, setSelectedEmployee] = React.useState(employees[0]?.id);
  React.useEffect(() => {
    if (requestedSection) setSection(requestedSection);
  }, [requestedSection]);
  const nav = [
    { id: "overview", label: "总览", icon: "home" },
    { id: "employees", label: "AI 员工", icon: "employee" },
    { id: "runs", label: "Run 与 Pair", icon: "run" },
    { id: "policies", label: "策略与 Gateway", icon: "shield" },
    { id: "resources", label: "连接与资源", icon: "connection" },
    { id: "improvement", label: "评估与改进", icon: "spark" },
    { id: "audit", label: "审计", icon: "audit" }
  ];
  return <div className="product-shell admin-shell" data-screen-label="HyperWork · V1 控制台">
    <aside className="admin-sidebar">
      <div className="admin-brand"><span>HW</span><div><strong>HyperWork</strong><small>V1 Control Plane · V9</small></div></div>
      <div className="tenant-switch"><span>组织</span><button>联调测试组织 <V7AdminIcon name="down" size={14}></V7AdminIcon></button></div>
      <nav>{nav.map(item => <button aria-label={item.label} key={item.id} className={section === item.id ? "active" : ""} onClick={() => setSection(item.id)}><V7AdminIcon name={item.icon}></V7AdminIcon><span>{item.label}</span>{item.id === "audit" && stage === "completed_sync" ? <i></i> : null}</button>)}</nav>
      <div className="admin-side-note"><V7AdminIcon name="info"></V7AdminIcon><div><strong>后台只承担配置与治理</strong><p>日常发起、验收在飞书；业务事实留在 Meegle。</p></div></div>
      <div className="sidebar-user admin-user"><Avatar initials="袁" tone="violet" size="sm"></Avatar><div><strong>袁野</strong><small>平台管理员</small></div></div>
    </aside>
    <section className="admin-main">
      <header className="admin-topbar"><div><span>HyperWork 控制台</span><V7AdminIcon name="chevron" size={13}></V7AdminIcon><strong>{nav.find(item => item.id === section)?.label}</strong></div><div><span className="owned-product-chip"><i>HW</i>自有产品界面</span><div className="admin-search"><V7AdminIcon name="search" size={15}></V7AdminIcon><span>搜索员工、Run、策略</span><kbd>⌘ K</kbd></div></div></header>
      <div className="admin-content">
        {section === "overview" ? <V9ConsoleOverview stage={stage} currentStage={currentStage} employees={employees} connections={connections} knowledgeSources={knowledgeSources} improvement={improvement} onNavigate={setSection} onNewEmployee={onNewEmployee} onAddKnowledge={onAddKnowledge}></V9ConsoleOverview> : null}
        {section === "employees" ? <EmployeesAdminV4 employees={employees} selected={employees.find(item => item.id === selectedEmployee) || employees[0]} onSelect={setSelectedEmployee} onNew={onNewEmployee} onToggle={onToggleEmployee} onNotify={onNotify} onOpenRuns={() => setSection("runs")} onGoMeegle={onGoMeegle} onGoLark={() => onGoLark("chat")}></EmployeesAdminV4> : null}
        {section === "runs" ? <CurrentRunPage stage={stage} currentStage={currentStage} paused={runPaused} incident={incident} version={deliverableVersion} round={acceptanceRound} events={auditEvents} onPause={onPauseRun} onCancel={onCancelRun} onAdvance={onAdvance} onSync={onSync} onTrigger={onTriggerIncident} onRecover={onRecoverIncident} onGoMeegle={onGoMeegle} onGoLark={onGoLark}></CurrentRunPage> : null}
        {section === "policies" ? <V9PolicyPage policies={policies} stage={stage} onToggle={onTogglePolicy} onNotify={onNotify}></V9PolicyPage> : null}
        {section === "resources" ? <V9ResourcesPage connections={connections} knowledgeSources={knowledgeSources} credentials={credentials} runtimes={runtimes} onTest={onTestConnection} onAddKnowledge={onAddKnowledge} onRotateCredential={onRotateCredential} onVerifyRuntime={onVerifyRuntime} onNotify={onNotify}></V9ResourcesPage> : null}
        {section === "improvement" ? <V9ImprovementPage feedback={feedback} improvement={improvement} onReview={onReviewImprovement} onNotify={onNotify} onEmployees={() => setSection("employees")}></V9ImprovementPage> : null}
        {section === "audit" ? <CurrentAuditPage events={auditEvents} stage={stage} onExport={onExportAudit}></CurrentAuditPage> : null}
      </div>
    </section>
  </div>;
}

function V9ConsoleOverview({ stage, currentStage, employees, connections, knowledgeSources, improvement, onNavigate, onNewEmployee, onAddKnowledge }) {
  const hasRun = ["running", "review", "completed_sync", "accepted"].includes(stage);
  return <div className="admin-page v9-console-overview" data-screen-label="HyperWork 控制台总览">
    <SectionTitle eyebrow="CONTROL PLANE" title="配置 AI 员工，治理每一次执行" detail="业务工作仍在 Meegle 和飞书；这里管理长期员工、能力资产、运行边界、资源和改进版本。" action={<div className="v9-title-actions"><PrototypeButton icon="database" onClick={onAddKnowledge}>添加知识源</PrototypeButton><PrototypeButton tone="primary" icon="plus" onClick={onNewEmployee}>新建 AI 员工</PrototypeButton></div>}></SectionTitle>
    <div className="v9-overview-metrics">
      <button onClick={() => onNavigate("employees")}><span className="blue"><V7AdminIcon name="employee"></V7AdminIcon></span><div><strong>{employees.length}</strong><em>AI 员工</em><small>{employees.filter(item => item.status === "启用").length} 名在岗 · 配置可版本化</small></div><V7AdminIcon name="chevron"></V7AdminIcon></button>
      <button onClick={() => onNavigate("resources")}><span className="violet"><V7AdminIcon name="database"></V7AdminIcon></span><div><strong>{knowledgeSources.length}</strong><em>知识源</em><small>飞书权限沿用 · 每次 Run 冻结版本</small></div><V7AdminIcon name="chevron"></V7AdminIcon></button>
      <button onClick={() => onNavigate("resources")}><span className="green"><V7AdminIcon name="connection"></V7AdminIcon></span><div><strong>{connections.filter(item => item.status === "正常").length}/{connections.length}</strong><em>连接正常</em><small>Meegle 写入仍按降级路径处理</small></div><V7AdminIcon name="chevron"></V7AdminIcon></button>
      <button onClick={() => onNavigate("improvement")}><span className="amber"><V7AdminIcon name="spark"></V7AdminIcon></span><div><strong>{improvement.status === "suggested" ? "1" : "0"}</strong><em>待评审改进</em><small>只影响未来 Run · 可回滚</small></div><V7AdminIcon name="chevron"></V7AdminIcon></button>
    </div>
    <div className="v9-overview-grid">
      <section className="v9-current-work"><header><div><span>当前工作</span><h3>Story 24233867 · 内部调研报告</h3></div><StatusPill tone={hasRun ? stage === "completed_sync" ? "warning" : stage === "accepted" ? "success" : "blue" : "neutral"}>{hasRun ? currentStage.label : "Run 尚未创建"}</StatusPill></header><p>项目研究员 v4 将 Meegle 工作项转成可验收的飞书文档；一次发起只创建一个 Run。</p><div className="v9-work-chain"><div className="done"><span><V7AdminIcon name="meegle"></V7AdminIcon></span><strong>WorkItem</strong><small>Story 24233867</small></div><i></i><div className={hasRun ? "active" : ""}><span><V7AdminIcon name="run"></V7AdminIcon></span><strong>Run / Pair</strong><small>{hasRun ? "RUN-0813-007" : "等待确认"}</small></div><i></i><div className={["review","completed_sync","accepted"].includes(stage) ? "active" : ""}><span><V7AdminIcon name="docs"></V7AdminIcon></span><strong>Deliverable</strong><small>{["review","completed_sync","accepted"].includes(stage) ? "v1+" : "尚未生成"}</small></div></div><footer><PrototypeButton tone="primary" icon="eye" onClick={() => onNavigate("runs")}>{hasRun ? "查看 Run 详情" : "查看派工状态"}</PrototypeButton><PrototypeButton icon="audit" onClick={() => onNavigate("audit")}>查看审计链</PrototypeButton></footer></section>
      <section className="v9-config-map"><header><div><span>配置地图</span><h3>一名长期 AI 员工由什么组成</h3></div><button onClick={() => onNavigate("employees")}>进入员工系统 <V7AdminIcon name="chevron"></V7AdminIcon></button></header><div><button onClick={() => onNavigate("employees")}><span><V7AdminIcon name="employee"></V7AdminIcon></span><strong>身份与人设</strong><small>岗位、边界、模型</small></button><button onClick={() => onNavigate("employees")}><span><V7AdminIcon name="spark"></V7AdminIcon></span><strong>Skills 与 SOP</strong><small>方法、工具、知识</small></button><button onClick={() => onNavigate("employees")}><span><V7AdminIcon name="database"></V7AdminIcon></span><strong>记忆与职责</strong><small>候选事实、定时工作</small></button><button onClick={() => onNavigate("policies")}><span><V7AdminIcon name="shield"></V7AdminIcon></span><strong>权限与策略</strong><small>L0–L3、预算、Gateway</small></button><button onClick={() => onNavigate("resources")}><span><V7AdminIcon name="sandbox"></V7AdminIcon></span><strong>运行环境</strong><small>凭据引用、隔离 Workspace</small></button><button onClick={() => onNavigate("improvement")}><span><V7AdminIcon name="audit"></V7AdminIcon></span><strong>评估与版本</strong><small>反馈、回归、发布</small></button></div></section>
    </div>
  </div>;
}

function V9PolicyPage({ policies, onToggle, onNotify }) {
  const [selectedId, setSelectedId] = React.useState(policies[0]?.id);
  const [editing, setEditing] = React.useState(false);
  const [overrides, setOverrides] = React.useState({});
  const selected = policies.find(item => item.id === selectedId) || policies[0];
  const effective = selected ? { ...selected, ...(overrides[selected.id] || {}) } : null;
  const [draft, setDraft] = React.useState(effective || {});
  React.useEffect(() => { setEditing(false); setDraft(effective || {}); }, [selectedId]);
  const save = () => { setOverrides(current => ({ ...current, [selected.id]: { name: draft.name, trigger: draft.trigger, route: draft.route, fallback: draft.fallback } })); setEditing(false); onNotify("策略草稿已保存", "完成回归校验后才会发布并影响新的授权请求。", "success"); };
  return <div className="admin-page"><SectionTitle eyebrow="POLICY ENGINE" title="策略与 Gateway" detail="统一配置动作风险、授权入口、凭据边界、超时和失败降级；执行引擎不能绕过 Gateway。" action={<PrototypeButton icon="plus" onClick={() => onNotify("新建策略草稿", "选择风险等级、动作类型和授权路由后创建版本草稿。")}>新建策略</PrototypeButton>}></SectionTitle><div className="policy-overview"><div><span className="metric-icon"><V7AdminIcon name="shield"></V7AdminIcon></span><div><strong>{policies.filter(item => item.enabled).length}</strong><span>已启用策略</span></div></div><div><span className="metric-icon amber"><V7AdminIcon name="docs"></V7AdminIcon></span><div><strong>L1</strong><span>内部草稿默认风险</span></div></div><div><span className="metric-icon red"><V7AdminIcon name="lock"></V7AdminIcon></span><div><strong>0</strong><span>引擎生产凭据</span></div></div></div><div className="policy-layout"><section className="table-card"><header><strong>当前策略</strong><div className="inline-search"><V7AdminIcon name="search"></V7AdminIcon><span>搜索策略</span></div></header><table><thead><tr><th>策略</th><th>触发条件</th><th>风险</th><th>授权</th><th>启用</th></tr></thead><tbody>{policies.map(item => { const row = { ...item, ...(overrides[item.id] || {}) }; return <tr key={item.id} className={selectedId === item.id ? "selected" : ""} onClick={() => setSelectedId(item.id)}><td><strong>{row.name}</strong><small>{item.id}</small></td><td>{row.trigger}</td><td><StatusPill tone={item.risk.includes("L2") ? "warning" : "blue"}>{item.risk}</StatusPill></td><td>{row.route}</td><td><button className={`switch ${item.enabled ? "on" : ""}`} onClick={event => { event.stopPropagation(); onToggle(item.id); }}><span></span></button></td></tr>; })}</tbody></table></section>{effective ? <aside className="detail-panel policy-detail v9-policy-editor"><header><div><span>POLICY DETAIL</span><h3>{effective.id}</h3></div>{editing ? <StatusPill tone="warning">草稿编辑中</StatusPill> : <PrototypeButton size="sm" icon="edit" onClick={() => { setDraft(effective); setEditing(true); }}>编辑</PrototypeButton>}</header>{editing ? <div className="v9-edit-form"><label><span>策略名称</span><input value={draft.name || ""} onChange={event => setDraft({...draft,name:event.target.value})}></input></label><label><span>触发条件</span><textarea rows="4" value={draft.trigger || ""} onChange={event => setDraft({...draft,trigger:event.target.value})}></textarea></label><label><span>授权路由</span><input value={draft.route || ""} onChange={event => setDraft({...draft,route:event.target.value})}></input></label><label><span>失败降级</span><textarea rows="3" value={draft.fallback || ""} onChange={event => setDraft({...draft,fallback:event.target.value})}></textarea></label><footer><PrototypeButton onClick={() => setEditing(false)}>取消</PrototypeButton><PrototypeButton tone="primary" icon="check" disabled={!draft.name?.trim() || !draft.trigger?.trim()} onClick={save}>保存草稿</PrototypeButton></footer></div> : <><StatusPill tone={effective.risk.includes("L2") ? "warning" : "blue"}>{effective.risk}</StatusPill><p>{effective.trigger}</p><dl><div><dt>授权入口</dt><dd>{effective.route}</dd></div><div><dt>超时</dt><dd>{effective.timeout}</dd></div><div><dt>失败降级</dt><dd>{effective.fallback}</dd></div></dl><div className="scope-rule"><V7AdminIcon name="lock"></V7AdminIcon><div><strong>授权范围冻结</strong><p>执行时不能扩大工作项、文档目录、字段、接收方或有效期。</p></div></div></>}</aside> : null}</div></div>;
}

function V9ResourcesPage({ connections, knowledgeSources, credentials, runtimes, onTest, onAddKnowledge, onRotateCredential, onVerifyRuntime, onNotify }) {
  const [tab, setTab] = React.useState("connections");
  const tabs = [{id:"connections",label:"第三方连接",count:connections.length},{id:"knowledge",label:"知识源",count:knowledgeSources.length},{id:"credentials",label:"凭据引用",count:credentials.length},{id:"runtimes",label:"运行环境",count:runtimes.length}];
  return <div className="admin-page resources-page"><SectionTitle eyebrow="EXECUTION FOUNDATION" title="连接与资源" detail="配置员工能读取什么、以谁的身份通过 Gateway 行动，以及 Attempt 在什么隔离环境运行。" action={tab === "knowledge" ? <PrototypeButton tone="primary" icon="plus" onClick={onAddKnowledge}>添加知识源</PrototypeButton> : tab === "connections" ? <PrototypeButton icon="plus" onClick={() => onNotify("添加连接", "选择飞书、Meegle 或执行引擎，并配置最小授权范围。")}>添加连接</PrototypeButton> : null}></SectionTitle><div className="resource-tabs v9-resource-tabs">{tabs.map(item => <button key={item.id} className={tab === item.id ? "active" : ""} onClick={() => setTab(item.id)}>{item.label}<span>{item.count}</span></button>)}</div>
    {tab === "connections" ? <div className="connection-grid">{connections.map(item => <article key={item.id}><header><span className={`connection-logo ${item.id}`}><V7AdminIcon name={item.id === "meegle" ? "meegle" : item.id === "credential" ? "code" : "lark"}></V7AdminIcon></span><StatusPill tone={item.status === "正常" ? "success" : "warning"}>{item.status}</StatusPill></header><h3>{item.name}</h3><p>{item.account}</p><dl><div><dt>权限范围</dt><dd>{item.scope}</dd></div><div><dt>最近检查</dt><dd>{item.checked}</dd></div></dl><footer><PrototypeButton icon="connection" onClick={() => onTest(item.id)}>测试连接</PrototypeButton><PrototypeButton icon="edit" onClick={() => onNotify("连接配置已打开", "可以调整读取范围、回调地址和 Gateway 身份引用。")}>编辑</PrototypeButton></footer></article>)}</div> : null}
    {tab === "knowledge" ? <div className="resource-layout"><section className="resource-list"><header><div><strong>已授权知识源</strong><p>Run 创建时冻结引用版本和访问结果。</p></div><StatusPill tone="success">权限隔离开启</StatusPill></header>{knowledgeSources.map(source => <article key={source.id}><span className="resource-icon"><V7AdminIcon name="database"></V7AdminIcon></span><div className="resource-main"><header><strong>{source.name}</strong><StatusPill dot={false} tone={source.status === "已同步" ? "success" : "warning"}>{source.status}</StatusPill></header><p>{source.type} · {source.permission}</p><div><span>授权给 {source.scope}</span><span>版本 {source.version}</span><span>同步 {source.sync}</span></div></div><IconButton label="编辑知识源" icon="edit" onClick={() => onNotify("知识源编辑器已打开", "可以调整员工范围、同步策略或停用该引用。")}></IconButton></article>)}</section><aside className="governance-card"><span><V7AdminIcon name="lock"></V7AdminIcon></span><h3>知识不复制为新事实源</h3><p>平台保存来源引用、权限决策、引用片段和版本号；读取继续执行飞书原始权限。</p><dl><div><dt>跨 Run 记忆</dt><dd>仅已批准事实</dd></div><div><dt>敏感内容</dt><dd>不写入公开评论</dd></div><div><dt>版本漂移</dt><dd>新 Run 重新快照</dd></div></dl></aside></div> : null}
    {tab === "credentials" ? <div className="credential-admin"><div className="credential-principle"><V7AdminIcon name="lock"></V7AdminIcon><div><strong>平台只保存密钥引用</strong><p>Token、密码和私钥不进入提示词、Workspace 或审计载荷。</p></div></div><div className="credential-table"><header><span>身份</span><span>允许范围</span><span>有效期</span><span>操作</span></header>{credentials.map(item => <article key={item.id}><div><strong>{item.name}</strong><small>{item.provider}</small></div><p>{item.scope}</p><StatusPill tone={item.status === "正常" ? "success" : "warning"}>{item.expires}</StatusPill><PrototypeButton size="sm" icon="refresh" onClick={() => onRotateCredential(item.id)}>{item.status === "正常" ? "轮换" : "立即复核"}</PrototypeButton></article>)}</div></div> : null}
    {tab === "runtimes" ? <div className="runtime-grid">{runtimes.map(runtime => <article key={runtime.id}><header><span><V7AdminIcon name="sandbox"></V7AdminIcon></span><div><h3>{runtime.name}</h3><p>{runtime.image}</p></div><StatusPill tone="success">{runtime.status}</StatusPill></header><dl><div><dt>资源</dt><dd>{runtime.cpu} · {runtime.memory}</dd></div><div><dt>网络</dt><dd>{runtime.network}</dd></div><div><dt>工具</dt><dd>{runtime.tools}</dd></div><div><dt>最长运行</dt><dd>{runtime.timeout}</dd></div></dl><footer><PrototypeButton icon="check" onClick={() => onVerifyRuntime(runtime.id)}>验证环境</PrototypeButton><PrototypeButton icon="edit" onClick={() => onNotify("运行环境版本草稿", "可以修改镜像、资源额度、工具清单和网络策略。")}>编辑版本</PrototypeButton></footer></article>)}<article className="runtime-guard"><V7AdminIcon name="shield" size={25}></V7AdminIcon><h3>默认隔离</h3><p>每个 ActorRun 使用独立文件系统、资源额度和网络策略；结束后销毁临时环境。</p></article></div> : null}
  </div>;
}

function V9ImprovementPage({ feedback, improvement, onReview, onNotify, onEmployees }) {
  const ready = improvement.status === "suggested" || improvement.status === "published";
  return <div className="admin-page improvement-page"><SectionTitle eyebrow="LEARNING GOVERNANCE" title="评估与持续改进" detail="业务反馈只能生成可评审、可回归、可回滚的新员工版本，不会静默改变运行中的 ActorRun。" action={<PrototypeButton icon="employee" onClick={onEmployees}>打开员工版本</PrototypeButton>}></SectionTitle><div className="evaluation-metrics"><article><span><V7AdminIcon name="spark"></V7AdminIcon></span><div><strong>4.6 / 5</strong><p>近 30 天业务评分</p></div></article><article><span><V7AdminIcon name="audit"></V7AdminIcon></span><div><strong>96%</strong><p>证据覆盖率</p></div></article><article><span><V7AdminIcon name="check"></V7AdminIcon></span><div><strong>18 / 20</strong><p>合格 Run 一次通过</p></div></article><article><span><V7AdminIcon name="employee"></V7AdminIcon></span><div><strong>{ready && improvement.status !== "published" ? "1" : "0"}</strong><p>待评审提案</p></div></article></div><div className="improvement-layout"><section className="evaluation-stream"><header><div><strong>当前评估信号</strong><p>项目研究员 · RUN-TEST-0813-007</p></div><StatusPill tone={feedback ? "success" : "warning"}>{feedback ? "业务评价已提交" : "等待验收反馈"}</StatusPill></header>{feedback ? <article className="business-feedback"><div className="feedback-score"><strong>{feedback.rating}.0</strong><span>/ 5</span></div><div><header><strong>Rowan · Story 负责人</strong><small>{feedback.submittedAt}</small></header><p>{feedback.comment}</p><div>{feedback.tags.map(tag => <em key={tag}>{tag}</em>)}</div></div></article> : <div className="empty-evaluation"><V7AdminIcon name="message" size={24}></V7AdminIcon><strong>验收后收集业务评价</strong><p>退回类别、意见、验收轮和最终评分都会成为改进信号。</p></div>}<div className="auto-evaluation"><span>自动评估</span><div><strong>验收标准覆盖</strong><StatusPill dot={false} tone="success">4/4</StatusPill></div><div><strong>证据可追溯</strong><StatusPill dot={false} tone="success">12/12</StatusPill></div><div><strong>权限与预算合规</strong><StatusPill dot={false} tone="success">通过</StatusPill></div><div><strong>结构化退回学习</strong><StatusPill dot={false} tone="warning">待积累</StatusPill></div></div></section><aside className={`improvement-proposal ${ready ? "ready" : "waiting"}`}><header><span><V7AdminIcon name="spark"></V7AdminIcon></span><div><small>员工改进提案</small><h3>项目研究员 {improvement.version === "v4" ? "v5" : improvement.version}</h3></div><StatusPill tone={improvement.status === "published" ? "success" : ready ? "warning" : "neutral"}>{improvement.status === "published" ? "已发布" : ready ? "待评审" : "等待信号"}</StatusPill></header><p>{ready ? "补强关键结论的来源版本标注，并把结构化退回类别写入交付前检查。" : "完成一次验收或结构化退回后，系统会把信号整理为员工版本草稿。"}</p>{ready ? <><div className="proposal-evidence"><div><span>影响范围</span><strong>仅未来 Run</strong></div><div><span>权限变化</span><strong>无</strong></div><div><span>回归任务</span><strong>20 项</strong></div></div><PrototypeButton tone={improvement.status === "published" ? "success" : "primary"} icon={improvement.status === "published" ? "check" : "eye"} disabled={improvement.status === "published"} onClick={onReview}>{improvement.status === "published" ? "v5 已发布" : "评审改进提案"}</PrototypeButton></> : <PrototypeButton icon="spark" onClick={() => onNotify("改进信号说明", "正常流程完成验收评价，或发生结构化退回后才会生成提案。")}>查看生成条件</PrototypeButton>}</aside></div></div>;
}

function CurrentEmployeePage({ employees, onToggle, onNotify }) {
  const employee = employees[0];
  return <div className="admin-page">
    <SectionTitle eyebrow="LONG-LIVED AI EMPLOYEE" title="项目研究员" detail="长期存在的岗位主体；每次 Run 冻结使用 EmployeeVersion，反馈只能影响未来版本。" action={<PrototypeButton icon="edit" onClick={() => onNotify("员工编辑器已打开", "原型展示身份、岗位、SOP、知识、工具与模型绑定。")}>编辑草稿</PrototypeButton>}></SectionTitle>
    <div className="admin-split">
      <section className="detail-panel">
        <header><div><span>EMPLOYEE · EMP-007</span><h3>{employee.name} · v4</h3></div><StatusPill tone="success">在岗</StatusPill></header>
        <p>{employee.description}</p>
        <div className="run-facts"><div><span>岗位</span><strong>内部调研与正式报告</strong></div><div><span>模型绑定</span><strong>执行引擎（当前 Codex）</strong></div><div><span>预算</span><strong>¥220 / Run</strong></div><div><span>版本策略</span><strong>新 Run 才生效</strong></div></div>
        <div className="tool-list"><div><V7AdminIcon name="check"></V7AdminIcon><strong>调研 SOP · 证据核验 · 正式报告</strong><StatusPill dot={false} tone="success">已发布</StatusPill></div><div><V7AdminIcon name="docs"></V7AdminIcon><strong>飞书 Wiki 与文档目录</strong><StatusPill dot={false}>按用户权限</StatusPill></div><div><V7AdminIcon name="connection"></V7AdminIcon><strong>Document Gateway</strong><StatusPill dot={false} tone="blue">L1 写入</StatusPill></div></div>
      </section>
      <aside className="detail-panel"><header><div><span>VERSION GOVERNANCE</span><h3>EmployeeVersion v4</h3></div></header><p>当前 Run 冻结 v4。验收退回会形成改进信号，但不会在执行中静默修改身份、SOP、知识或权限。</p><div className="version-checks-v4"><span>发布门禁</span><div><V7AdminIcon name="check"></V7AdminIcon><strong>历史质量基线</strong><StatusPill dot={false} tone="success">通过</StatusPill></div><div><V7AdminIcon name="check"></V7AdminIcon><strong>权限没有扩大</strong><StatusPill dot={false} tone="success">通过</StatusPill></div></div></aside>
    </div>
  </div>;
}

function CurrentRunPage({ stage, currentStage, paused, incident, version, round, events, onPause, onCancel, onAdvance, onSync, onTrigger, onRecover, onGoMeegle, onGoLark }) {
  const hasRun = ["running", "review", "completed_sync", "accepted"].includes(stage);
  const statusTone = incident === "blocked" ? "danger" : stage === "completed_sync" ? "warning" : stage === "accepted" ? "success" : "blue";
  return <div className="admin-page">
    <SectionTitle eyebrow="RUN OPERATIONS" title="Run、PairSession 与异步投影" detail="Run 生命周期和第三方同步状态分开；执行引擎没有生产凭据，外部写入统一通过 Gateway。"></SectionTitle>
    {!hasRun ? <div className="empty-run"><span><V7AdminIcon name="run" size={26}></V7AdminIcon></span><h4>Run 尚未创建</h4><p>当前只有 DispatchProposal DP-0813-007。飞书确认后才会原子创建 Run、ExternalBinding 和 Story 家族活跃守卫。</p><PrototypeButton tone="primary" icon="message" onClick={() => onGoLark("chat")}>去飞书确认发起</PrototypeButton></div> : <div className="run-admin-layout">
      <section className="run-list"><div className="list-toolbar"><div className="inline-search"><V7AdminIcon name="search"></V7AdminIcon><span>搜索 Run 或 WorkItem</span></div></div><button className="active"><span className={`run-status-icon ${incident === "blocked" ? "failed" : ""}`}><V7AdminIcon name={incident === "blocked" ? "warning" : "run"}></V7AdminIcon></span><div><strong>项目型知识工作调研</strong><small>RUN-TEST-0813-007 · Story 24233867</small></div><StatusPill tone={statusTone}>{currentStage.label}</StatusPill></button><div className="run-list-boundary"><V7AdminIcon name="lock"></V7AdminIcon><div><strong>Story Family 活跃守卫</strong><p>tenant + space + story_id · projection generation #7</p></div></div></section>
      <aside className="run-detail"><header><div><span>RUN-TEST-0813-007</span><h3>项目研究员 × Codex Pair</h3></div><StatusPill tone={statusTone}>{currentStage.label}</StatusPill></header>
        <div className="run-links"><button onClick={onGoMeegle}><V7AdminIcon name="meegle"></V7AdminIcon>Story 24233867<V7AdminIcon name="chevron"></V7AdminIcon></button><button onClick={() => onGoLark("chat")}><V7AdminIcon name="lark"></V7AdminIcon>飞书协作<V7AdminIcon name="chevron"></V7AdminIcon></button></div>
        <div className="run-progress"><div><span>执行进度</span><strong>{currentStage.progress}%</strong></div><ProgressBar value={currentStage.progress}></ProgressBar></div>
        <div className="run-facts"><div><span>EmployeeVersion</span><strong>项目研究员 v4</strong></div><div><span>ActorRun / Pair</span><strong>1 / 1</strong></div><div><span>交付版本</span><strong>v{version} · 验收轮 {round}</strong></div><div><span>同步状态</span><strong>{stage === "completed_sync" ? "pending" : stage === "accepted" ? "succeeded" : "尚未创建"}</strong></div></div>
        {incident === "blocked" ? <div className="branch-demo"><div><V7AdminIcon name="warning"></V7AdminIcon><p><strong>Attempt #1 心跳超时，已安全隔离</strong><span>Lease 已撤销；fencing token 推进到 #45；CP-014 可恢复。</span></p></div><PrototypeButton tone="primary" icon="refresh" onClick={() => onRecover("从 CP-014 绑定 Attempt #2")}>安全重绑</PrototypeButton></div> : null}
        {stage === "completed_sync" ? <div className="branch-demo"><div><V7AdminIcon name="refresh"></V7AdminIcon><p><strong>Run completed · WritebackTask pending</strong><span>AcceptanceDecision 已落盘；Meegle 暂未对齐不阻塞完成。</span></p></div><PrototypeButton tone="primary" icon="refresh" onClick={onSync}>模拟同步成功</PrototypeButton></div> : null}
        <div className="tool-list"><div><Avatar initials="研" tone="violet" size="xs"></Avatar><strong>AR-0813-007 · PAIR-0813-007 · {incident === "resolved" ? "Attempt #2" : "Attempt #1"}</strong><StatusPill dot={false} tone={incident === "blocked" ? "danger" : "blue"}>{incident === "blocked" ? "Lease 已撤销" : stage === "running" ? "执行中" : "已完成"}</StatusPill></div><div><V7AdminIcon name="shield"></V7AdminIcon><strong>Action / Document Gateway</strong><StatusPill dot={false} tone="success">凭据与幂等边界</StatusPill></div></div>
        <div className="mini-event-list"><span>最近治理事件</span>{events.slice(-4).reverse().map(item => <article key={item.id}><i className={item.level}></i><div><strong>{item.title}</strong><small>{item.time} · {item.actor}</small></div></article>)}</div>
        <footer>{stage === "running" && !incident ? <PrototypeButton icon="warning" onClick={onTrigger}>模拟 Attempt 失联</PrototypeButton> : null}{stage === "running" && incident !== "blocked" && incident !== "recovering" ? <PrototypeButton tone="primary" icon="arrow" onClick={onAdvance}>生成文档并进入验收</PrototypeButton> : null}{stage === "running" && incident !== "blocked" && incident !== "recovering" ? <PrototypeButton icon={paused ? "play" : "pause"} onClick={onPause}>{paused ? "继续 Run" : "暂停 Run"}</PrototypeButton> : null}{stage === "review" ? <PrototypeButton tone="primary" icon="message" onClick={() => onGoLark("chat")}>去飞书验收</PrototypeButton> : null}{["running", "review"].includes(stage) ? <PrototypeButton tone="danger" icon="stop" onClick={onCancel}>取消 Run</PrototypeButton> : null}</footer>
      </aside>
    </div>}
  </div>;
}

function CurrentPolicyPage({ policies, stage, onToggle }) {
  return <div className="admin-page"><SectionTitle eyebrow="GOVERNANCE" title="风险策略与 Gateway 边界" detail="风险由动作、目标、数据范围和接收方共同决定。V1 的两个正常人工触点是发起确认和验收。"></SectionTitle><div className="policy-overview"><div><span className="metric-icon"><V7AdminIcon name="shield"></V7AdminIcon></span><div><strong>L0–L3</strong><span>动作风险分层</span></div></div><div><span className="metric-icon amber"><V7AdminIcon name="docs"></V7AdminIcon></span><div><strong>L1</strong><span>飞书内部草稿</span></div></div><div><span className="metric-icon red"><V7AdminIcon name="lock"></V7AdminIcon></span><div><strong>0</strong><span>执行引擎生产凭据</span></div></div></div><section className="table-card"><header><strong>当前策略</strong></header><table><thead><tr><th>策略</th><th>触发条件</th><th>风险</th><th>授权</th><th>启用</th></tr></thead><tbody>{policies.map(item => <tr key={item.id}><td><strong>{item.name}</strong><small>{item.id}</small></td><td>{item.trigger}</td><td><StatusPill tone={item.risk.includes("L2") ? "warning" : "blue"}>{item.risk}</StatusPill></td><td>{item.route}</td><td><button className={`switch ${item.enabled ? "on" : ""}`} onClick={() => onToggle(item.id)}><span></span></button></td></tr>)}</tbody></table></section></div>;
}

function CurrentConnectionsPage({ connections, knowledgeSources, onTest }) {
  return <div className="admin-page"><SectionTitle eyebrow="CONTROLLED ACCESS" title="第三方连接与知识范围" detail="平台保存引用、授权范围和版本；第三方原文不复制为新的业务事实源。"></SectionTitle><div className="connection-grid">{connections.map(item => <article key={item.id}><header><span className={`connection-logo ${item.id}`}><V7AdminIcon name={item.id === "meegle" ? "meegle" : item.id === "credential" ? "code" : "lark"}></V7AdminIcon></span><StatusPill tone={item.status === "正常" ? "success" : "warning"}>{item.status}</StatusPill></header><h3>{item.name}</h3><p>{item.account}</p><dl><div><dt>权限范围</dt><dd>{item.scope}</dd></div><div><dt>最近检查</dt><dd>{item.checked}</dd></div></dl><footer><PrototypeButton icon="connection" onClick={() => onTest(item.id)}>测试连接</PrototypeButton></footer></article>)}</div><section className="table-card" style={{marginTop:14}}><header><strong>知识源 · {knowledgeSources.length}</strong></header><table><thead><tr><th>名称</th><th>类型</th><th>授权给</th><th>版本</th></tr></thead><tbody>{knowledgeSources.map(item => <tr key={item.id}><td><strong>{item.name}</strong></td><td>{item.type}</td><td>{item.scope}</td><td>{item.version}</td></tr>)}</tbody></table></section></div>;
}

function CurrentAuditPage({ events, stage, onExport }) {
  const [selectedId, setSelectedId] = React.useState(events[events.length - 1]?.id);
  const selected = events.find(item => item.id === selectedId) || events[events.length - 1];
  return <div className="admin-page"><SectionTitle eyebrow="IMMUTABLE AUDIT" title="提案、执行、验收与同步事实链" detail="确认前的提案成本、每次 Attempt、Gateway 回执、AcceptanceDecision 和 WritebackTask 均可追溯。" action={<PrototypeButton icon="download" onClick={onExport}>导出当前链</PrototypeButton>}></SectionTitle><div className="audit-layout"><section className="audit-stream"><div className="audit-run-head"><div><span>{stage === "detected" || stage === "plan" ? "DP-0813-007" : "RUN-TEST-0813-007"}</span><strong>Story 24233867 · 项目型知识工作调研</strong></div><StatusPill tone="success">链完整</StatusPill></div><div className="audit-event-list">{events.slice().reverse().map(item => <button key={item.id} className={selected?.id === item.id ? "active" : ""} onClick={() => setSelectedId(item.id)}><time>{item.time}</time><span className={`audit-node ${item.level}`}></span><div><header><strong>{item.title}</strong><em>{item.type}</em></header><p>{item.detail}</p><small>{item.actor}</small></div><V7AdminIcon name="chevron"></V7AdminIcon></button>)}</div></section>{selected ? <aside className="detail-panel audit-detail"><header><div><span>EVENT DETAIL</span><h3>{selected.type}</h3></div></header><p>{selected.title}</p><dl><div><dt>Actor</dt><dd>{selected.actor}</dd></div><div><dt>WorkItem</dt><dd>Story 24233867</dd></div><div><dt>Run</dt><dd>{stage === "detected" || stage === "plan" ? "尚未创建" : "RUN-TEST-0813-007"}</dd></div></dl><div className="event-payload"><span>不可变摘要</span><pre>{JSON.stringify({event:selected.type,workItem:"24233867",run:stage === "detected" || stage === "plan" ? null : "RUN-TEST-0813-007",detail:selected.detail},null,2)}</pre></div></aside> : null}</div></div>;
}

Object.assign(window, { V6AdminWorkspace });
