const PIcon = window.PrototypeIcon;

function PrototypeButton({ children, tone = "secondary", icon, size = "md", className = "", disabled = false, onClick, type = "button", ariaLabel }) {
  return <button type={type} aria-label={ariaLabel} disabled={disabled} className={`p-button ${tone} ${size} ${className}`} onClick={onClick}>{icon ? <PIcon name={icon} size={size === "sm" ? 14 : 16}></PIcon> : null}<span>{children}</span></button>;
}

function IconButton({ label, icon, active = false, badge, onClick }) {
  return <button aria-label={label} title={label} className={`icon-button ${active ? "active" : ""}`} onClick={onClick}><PIcon name={icon}></PIcon>{badge ? <span className="icon-badge">{badge}</span> : null}</button>;
}

function Avatar({ initials, tone = "blue", size = "md" }) {
  return <span className={`avatar ${tone} ${size}`}>{initials}</span>;
}

function StatusPill({ children, tone = "neutral", dot = true }) {
  return <span className={`status-pill ${tone}`}>{dot ? <i></i> : null}{children}</span>;
}

function Toast({ toast, onClose }) {
  if (!toast) return null;
  return <div className={`toast ${toast.tone || "success"}`} role="status"><span className="toast-icon"><PIcon name={toast.tone === "danger" ? "warning" : "check"}></PIcon></span><div><strong>{toast.title}</strong>{toast.detail ? <p>{toast.detail}</p> : null}</div><button aria-label="关闭提示" onClick={onClose}><PIcon name="x" size={15}></PIcon></button></div>;
}

function Modal({ title, subtitle, width = "medium", children, footer, onClose }) {
  return <div className="modal-layer" role="presentation" onMouseDown={event => { if (event.target === event.currentTarget) onClose(); }}><section className={`modal-card ${width}`} role="dialog" aria-modal="true" aria-label={title}><header><div><h2>{title}</h2>{subtitle ? <p>{subtitle}</p> : null}</div><IconButton label="关闭" icon="x" onClick={onClose}></IconButton></header><div className="modal-body">{children}</div>{footer ? <footer>{footer}</footer> : null}</section></div>;
}

function ConfirmDialog({ config, onClose }) {
  if (!config) return null;
  return <Modal title={config.title} subtitle={config.subtitle} width="small" onClose={onClose} footer={<><PrototypeButton onClick={onClose}>取消</PrototypeButton><PrototypeButton tone={config.tone || "danger"} onClick={config.onConfirm}>{config.confirmLabel || "确认"}</PrototypeButton></>}><div className={`confirm-illustration ${config.tone || "danger"}`}><PIcon name={config.icon || "warning"} size={24}></PIcon></div><p className="confirm-copy">{config.body}</p></Modal>;
}

function SurfaceSwitcher({ surface, onChange }) {
  const scenarioActive = surface === "meegle" || surface === "lark";
  return <div className="experience-switcher" aria-label="原型模式切换"><div className={`scenario-cluster ${scenarioActive ? "active" : ""}`}><span className="mode-label"><strong>集成场景</strong><small>第三方客户端模拟</small></span><div className="external-choice"><button aria-label="Meegle 模拟" className={surface === "meegle" ? "active" : ""} onClick={() => onChange("meegle")}><PIcon name="meegle"></PIcon><span>Meegle</span></button><button aria-label="飞书模拟" className={surface === "lark" ? "active" : ""} onClick={() => onChange("lark")}><PIcon name="lark"></PIcon><span>飞书</span></button></div></div><button aria-label="HyperWork 控制台" className={`console-choice ${surface === "admin" ? "active" : ""}`} onClick={() => onChange("admin")}><PIcon name="admin"></PIcon><span><strong>HyperWork 控制台</strong><small>自有产品界面</small></span></button></div>;
}

function GlobalHeader({ surface, stage, onSurfaceChange, onReset }) {
  return <header className="global-header"><div className="global-brand"><span className="global-mark">HW</span><div><strong>HyperWork</strong><small>Four-system journey · V6</small></div></div><SurfaceSwitcher surface={surface} onChange={onSurfaceChange}></SurfaceSwitcher><div className="global-state"><span className="live-dot"></span><div><strong>{surface === "admin" ? "控制平面" : "Story 24233867"}</strong><small>{surface === "admin" ? "自有产品界面" : `${stage.label} · 第三方客户端`}</small></div><PrototypeButton size="sm" icon="reset" ariaLabel="重置演示" onClick={onReset}>重置演示</PrototypeButton></div></header>;
}

function ExperienceBoundaryBar({ surface }) {
  const external = surface !== "admin";
  const product = surface === "meegle" ? "Meegle" : "飞书";
  return <div className={`experience-boundary ${external ? "external" : "owned"}`} data-screen-label={external ? `${product} 第三方客户端模拟说明` : "HyperWork 自有控制台说明"}><div className="boundary-identity"><span className="boundary-mark"><PIcon name={external ? surface : "admin"}></PIcon></span><div><strong>{external ? `${product} 客户端模拟` : "HyperWork 自有产品 · Control Plane"}</strong><small>{external ? "仅用于内部定义集成交互，不代表我们开发第三方客户端" : "配置、执行治理、恢复、审计与持续改进发生在这里"}</small></div></div><div className="boundary-scope"><span>{external ? "本场景中的 HyperWork 能力" : "默认数据边界"}</span>{surface === "meegle" ? <><em>AI 执行扩展</em><em>评论与状态回写</em><em>验收入口</em></> : surface === "lark" ? <><em>机器人与卡片</em><em>审批和纠偏</em><em>文档交付</em></> : <><em>元数据默认可见</em><em>Run 快照按权限展开</em><em>原文留在第三方</em></>}</div></div>;
}

function StageRail({ currentId, compact = false }) {
  const currentIndex = window.prototypeStages.findIndex(stage => stage.id === currentId);
  return <ol className={`stage-rail ${compact ? "compact" : ""}`}>{window.prototypeStages.map((stage, index) => <li key={stage.id} className={`${index < currentIndex ? "done" : ""} ${index === currentIndex ? "current" : ""}`}><span>{index < currentIndex || currentId === "accepted" ? <PIcon name="check" size={13}></PIcon> : index + 1}</span><div><strong>{stage.short}</strong>{compact ? null : <small>{index < currentIndex ? "已记录" : index === currentIndex ? "当前阶段" : "待开始"}</small>}</div></li>)}</ol>;
}

function ProgressBar({ value, tone = "blue" }) {
  return <div className={`progress-track ${tone}`}><span style={{ width: `${value}%` }}></span></div>;
}

function SectionTitle({ eyebrow, title, detail, action }) {
  return <div className="section-title"><div>{eyebrow ? <span className="eyebrow">{eyebrow}</span> : null}<h2>{title}</h2>{detail ? <p>{detail}</p> : null}</div>{action || null}</div>;
}

function StartRunForm({ onCancel, onConfirm }) {
  const [name, setName] = React.useState("Story 24233867 · 四系统端到端联调");
  const [deliverable, setDeliverable] = React.useState("飞书联调报告 + 事件证据 + Meegle 测试回写摘要");
  const [acknowledged, setAcknowledged] = React.useState(true);
  const [error, setError] = React.useState("");
  const submit = () => {
    if (!name.trim() || !deliverable.trim()) { setError("请填写本次 Run 的名称和交付物。"); return; }
    if (!acknowledged) { setError("请确认高风险动作会进入人工审批。"); return; }
    onConfirm({ name, deliverable });
  };
  return <Modal title="在飞书配置 AI Run" subtitle="绑定 Meegle Story 24233867；不会创建第二个业务任务。" onClose={onCancel} footer={<><PrototypeButton onClick={onCancel}>取消</PrototypeButton><PrototypeButton tone="primary" icon="play" onClick={submit}>创建测试 Run</PrototypeButton></>}><div className="form-grid"><label className="field full"><span>Run 名称 <b>*</b></span><input value={name} onChange={event => setName(event.target.value)}></input></label><label className="field full"><span>预期交付物 <b>*</b></span><textarea rows="2" value={deliverable} onChange={event => setDeliverable(event.target.value)}></textarea></label><div className="form-summary full"><div><span className="summary-label">执行小队</span><strong>平台联调小队</strong><small>联调负责人 + Meegle 适配、飞书协作、可靠执行</small></div><div><span className="summary-label">预计用时</span><strong>约 8 分钟</strong><small>本页全部为测试数据</small></div></div><label className="check-field full"><input type="checkbox" checked={acknowledged} onChange={event => setAcknowledged(event.target.checked)}></input><span><strong>采用默认策略</strong><small>只允许测试空间内低风险动作；文档发布、状态关闭与权限扩大需要负责人在飞书批准。</small></span></label>{error ? <p className="form-error full"><PIcon name="warning" size={14}></PIcon>{error}</p> : null}</div></Modal>;
}

function ContextForm({ onSubmit }) {
  const [value, setValue] = React.useState("");
  const [error, setError] = React.useState("");
  const submit = () => {
    if (value.trim().length < 8) { setError("请至少补充一条明确限制条件。"); return; }
    onSubmit(value.trim());
  };
  return <div className="context-form"><label><span>补充说明</span><textarea rows="4" value={value} placeholder="例如：只允许测试空间；评论可自动写回；关闭 Story 必须人工批准。" onChange={event => { setValue(event.target.value); setError(""); }}></textarea></label>{error ? <p className="form-error"><PIcon name="warning" size={14}></PIcon>{error}</p> : null}<div className="card-actions"><PrototypeButton tone="primary" icon="send" onClick={submit}>提交并继续</PrototypeButton><PrototypeButton onClick={() => setValue("仅允许操作测试空间 hyperwork-ai-test-0812；进展评论可自动写回；关闭 Story 与文档权限变更必须人工批准。")}>填入示例</PrototypeButton></div></div>;
}

function NewEmployeeForm({ onCancel, onCreate }) {
  const [step, setStep] = React.useState(1);
  const [name, setName] = React.useState("");
  const [role, setRole] = React.useState("Specialist");
  const [description, setDescription] = React.useState("");
  const [persona, setPersona] = React.useState("");
  const [model, setModel] = React.useState("GPT-5.2");
  const [knowledge, setKnowledge] = React.useState("AI 员工平台设计 Wiki");
  const [sop, setSop] = React.useState("从空白 SOP 开始");
  const [channel, setChannel] = React.useState("飞书私聊服务");
  const [policy, setPolicy] = React.useState("知识工作标准策略");
  const [owner, setOwner] = React.useState("AI 平台团队");
  const [budget, setBudget] = React.useState("¥50 / ActorRun");
  const [error, setError] = React.useState("");
  const next = () => {
    if (step === 1 && (name.trim().length < 2 || description.trim().length < 8)) { setError("请填写员工名称和清晰的职责说明。"); return; }
    if (step === 2 && persona.trim().length < 12) { setError("请定义这名员工的岗位人设与职责边界。"); return; }
    setError("");
    setStep(current => Math.min(3, current + 1));
  };
  const submit = () => onCreate({ name: name.trim(), role, description: description.trim(), persona, model, knowledge, sop, channel, policy, owner, budget });
  const applyTemplate = () => {
    setDescription("负责验证第三方工作项绑定、受控写回与证据留存；不维护业务项目状态机，也不持有真实凭据值。");
    setPersona("你是平台连接器专员。先确认外部对象、授权主体和最小字段范围，再执行读取或写回；所有写动作必须生成幂等键和证据，超出测试范围时立即升级人工处理。");
    setKnowledge("AI 员工平台设计 Wiki");
    setSop("第三方连接器验证 SOP v2");
  };
  const footer = <><PrototypeButton onClick={step === 1 ? onCancel : () => { setError(""); setStep(current => current - 1); }}>{step === 1 ? "取消" : "上一步"}</PrototypeButton>{step < 3 ? <PrototypeButton tone="primary" icon="arrow" onClick={next}>下一步</PrototypeButton> : <PrototypeButton tone="primary" icon="check" onClick={submit}>创建员工草稿</PrototypeButton>}</>;
  return <Modal title={`新建 AI 员工 · ${step}/3`} subtitle="创建长期岗位主体；员工发布后，每次工作仍会生成独立 Run。" width="large" onClose={onCancel} footer={footer}><div className="employee-onboarding-v4"><div className="employee-onboarding-steps-v4"><span className={step >= 1 ? "active" : ""}><i>1</i><strong>身份与岗位</strong><small>这名员工是谁</small></span><em></em><span className={step >= 2 ? "active" : ""}><i>2</i><strong>能力与人设</strong><small>如何完成专业工作</small></span><em></em><span className={step >= 3 ? "active" : ""}><i>3</i><strong>治理与服务</strong><small>在哪里、按什么规则工作</small></span></div>
    {step === 1 ? <div className="form-grid employee-onboarding-pane-v4"><div className="onboarding-template-v4 full"><PIcon name="spark"></PIcon><div><strong>从岗位模板开始</strong><p>先填入“平台连接器专员”示例，再按组织实际职责调整。</p></div><PrototypeButton size="sm" onClick={applyTemplate}>使用模板</PrototypeButton></div><label className="field"><span>员工名称 <b>*</b></span><input autoFocus value={name} placeholder="例如：平台连接器专员" onChange={event => { setName(event.target.value); setError(""); }}></input></label><label className="field"><span>角色类型</span><select value={role} onChange={event => setRole(event.target.value)}><option>Specialist</option><option>Lead AI</option></select></label><label className="field full"><span>职责说明 <b>*</b></span><textarea rows="4" value={description} placeholder="说明它负责什么，以及明确不负责什么。" onChange={event => { setDescription(event.target.value); setError(""); }}></textarea></label><label className="field"><span>所属团队</span><select value={owner} onChange={event => setOwner(event.target.value)}><option>AI 平台团队</option><option>业务自动化团队</option><option>安全与合规团队</option></select></label><label className="field"><span>员工负责人</span><select><option>袁野</option><option>Rowan</option></select></label></div> : null}
    {step === 2 ? <div className="form-grid employee-onboarding-pane-v4"><label className="field full"><span>岗位 Prompt <b>*</b></span><textarea rows="7" value={persona} placeholder="定义工作方法、表达风格、升级条件和明确边界。" onChange={event => { setPersona(event.target.value); setError(""); }}></textarea></label><label className="field"><span>默认模型</span><select value={model} onChange={event => setModel(event.target.value)}><option>GPT-5.2</option><option>GPT-5.2-mini</option></select></label><label className="field"><span>初始 SOP</span><select value={sop} onChange={event => setSop(event.target.value)}><option>从空白 SOP 开始</option><option>第三方连接器验证 SOP v2</option><option>可靠执行恢复 SOP v1</option></select></label><label className="field full"><span>初始知识作用域</span><select value={knowledge} onChange={event => setKnowledge(event.target.value)}><option>AI 员工平台设计 Wiki</option><option>完整流程设计目录</option><option>不绑定知识源</option></select></label><div className="permission-preview full"><PIcon name="lock"></PIcon><div><strong>能力绑定不直接授予数据权限</strong><p>知识读取继续遵循飞书原始权限，工具和模型变更会进入员工版本。</p></div></div></div> : null}
    {step === 3 ? <div className="employee-onboarding-pane-v4"><div className="onboarding-review-v4"><section><header><Avatar initials={(name.trim() || "AI").slice(0,1)} tone="violet"></Avatar><div><span>{role}</span><strong>{name.trim() || "未命名员工"}</strong><small>{owner}</small></div><StatusPill tone="warning">草稿</StatusPill></header><p>{description || "尚未填写职责说明"}</p><dl><div><dt>默认模型</dt><dd>{model}</dd></div><div><dt>知识作用域</dt><dd>{knowledge}</dd></div><div><dt>初始 SOP</dt><dd>{sop}</dd></div></dl></section><div className="form-grid"><label className="field"><span>默认服务渠道</span><select value={channel} onChange={event => setChannel(event.target.value)}><option>飞书私聊服务</option><option>飞书群聊 · 仅被 @ 响应</option><option>暂不挂载渠道</option></select></label><label className="field"><span>审批与风险策略</span><select value={policy} onChange={event => setPolicy(event.target.value)}><option>知识工作标准策略</option><option>只读研究策略</option><option>严格人工批准策略</option></select></label><label className="field full"><span>单次预算</span><input value={budget} onChange={event => setBudget(event.target.value)}></input></label></div></div><div className="onboarding-publish-note-v4"><PIcon name="info"></PIcon><p><strong>创建后仍然是草稿</strong><span>完成能力校验、权限检查和一组回归任务后，才能发布为在岗员工。</span></p></div></div> : null}
    {error ? <p className="form-error"><PIcon name="warning" size={14}></PIcon>{error}</p> : null}
  </div></Modal>;
}

function TeamEditor({ employees, onCancel, onSave }) {
  const [members, setMembers] = React.useState(["research", "data", "writer"]);
  const toggle = id => setMembers(current => current.includes(id) ? current.filter(item => item !== id) : current.length < 3 ? [...current, id] : current);
  return <Modal title="编辑平台联调小队" subtitle="一个负责人 AI + 最多三位专业 AI。" onClose={onCancel} footer={<><PrototypeButton onClick={onCancel}>取消</PrototypeButton><PrototypeButton tone="primary" onClick={() => onSave(members)}>保存小队</PrototypeButton></>}><div className="team-editor"><div className="lead-lock"><Avatar initials="联" tone="violet"></Avatar><div><span>负责人 AI</span><strong>平台联调负责人</strong><small>对最终结果负责，不能从小队移除</small></div><PIcon name="lock"></PIcon></div><span className="field-label">专业 AI · {members.length}/3</span><div className="member-options">{employees.filter(employee => employee.role === "Specialist").map(employee => <button key={employee.id} disabled={!members.includes(employee.id) && members.length >= 3} className={members.includes(employee.id) ? "selected" : ""} onClick={() => toggle(employee.id)}><Avatar initials={employee.initials} tone={employee.tone} size="sm"></Avatar><div><strong>{employee.name}</strong><small>{employee.skills.slice(0, 2).join(" · ")}</small></div><span>{members.includes(employee.id) ? <PIcon name="check"></PIcon> : <PIcon name="plus"></PIcon>}</span></button>)}</div></div></Modal>;
}

function FeedbackForm({ onCancel, onSubmit }) {
  const [rating, setRating] = React.useState(0);
  const [tags, setTags] = React.useState(["证据充分"]);
  const [comment, setComment] = React.useState("");
  const [error, setError] = React.useState("");
  const options = ["结果准确", "证据充分", "格式可用", "需要改进"];
  const toggleTag = tag => setTags(current => current.includes(tag) ? current.filter(item => item !== tag) : [...current, tag]);
  const submit = () => {
    if (!rating) { setError("请先选择 1–5 分的整体评价。"); return; }
    onSubmit({ rating, tags, comment: comment.trim() || "四系统边界清晰，证据可以追溯到真实测试对象。" });
  };
  return <Modal title="评价本次 AI 交付" subtitle="反馈用于评估本次 Run，并生成可审核的员工改进建议。" width="medium" onClose={onCancel} footer={<><PrototypeButton onClick={onCancel}>稍后评价</PrototypeButton><PrototypeButton tone="primary" icon="check" onClick={submit}>提交评价</PrototypeButton></>}><div className="feedback-form"><div className="feedback-group"><span>整体质量 <b>*</b></span><div className="rating-row">{[1,2,3,4,5].map(value => <button key={value} className={rating >= value ? "active" : ""} aria-label={`${value}分`} onClick={() => { setRating(value); setError(""); }}><PIcon name="spark" size={17}></PIcon><span>{value}</span></button>)}</div></div><div className="feedback-group"><span>快速标签</span><div className="tag-selector">{options.map(tag => <button key={tag} aria-label={tag} className={tags.includes(tag) ? "active" : ""} onClick={() => toggleTag(tag)}>{tags.includes(tag) ? <PIcon name="check" size={13}></PIcon> : null}{tag}</button>)}</div></div><label className="field"><span>补充说明</span><textarea rows="4" value={comment} placeholder="例如：结论准确，但客户版本还需要更明确的本地语言免责声明。" onChange={event => setComment(event.target.value)}></textarea></label>{error ? <p className="form-error"><PIcon name="warning" size={14}></PIcon>{error}</p> : null}<div className="feedback-note"><PIcon name="shield"></PIcon><p>评价不会直接修改员工配置；平台会先生成改进提案，由管理员评审和发布。</p></div></div></Modal>;
}

function KnowledgeSourceForm({ onCancel, onCreate }) {
  const [name, setName] = React.useState("");
  const [type, setType] = React.useState("飞书 Wiki");
  const [scope, setScope] = React.useState("平台联调小队");
  const [error, setError] = React.useState("");
  const submit = () => {
    if (name.trim().length < 3) { setError("请填写可识别的知识源名称。"); return; }
    onCreate({ name: name.trim(), type, scope });
  };
  return <Modal title="添加知识源" subtitle="仅保存引用和访问策略；读取时继续遵循飞书权限。" 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>授权给</span><select value={scope} onChange={event => setScope(event.target.value)}><option>平台联调小队</option><option>平台联调负责人</option><option>可靠执行</option></select></label><div className="permission-preview full"><PIcon name="lock"></PIcon><div><strong>沿用操作者权限</strong><p>AI 员工不会获得操作者本来无法访问的内容；版本和引用会进入 Run 快照。</p></div></div>{error ? <p className="form-error full"><PIcon name="warning" size={14}></PIcon>{error}</p> : null}</div></Modal>;
}

function ImprovementReviewModal({ improvement, onCancel, onPublish }) {
  return <Modal title="评审员工改进提案" subtitle="策略负责人 v4 → v5 · 仅影响未来创建的 Run" width="large" onClose={onCancel} footer={<><PrototypeButton onClick={onCancel}>保留草稿</PrototypeButton><PrototypeButton tone="primary" icon="check" onClick={onPublish}>通过并发布 v5</PrototypeButton></>}><div className="improvement-review"><div className="review-score"><span><PIcon name="spark"></PIcon></span><div><strong>依据 1 次业务反馈和 6 项自动评估生成</strong><p>建议置信度 87% · 未发现权限或风险策略扩大</p></div><StatusPill tone="success">回归通过</StatusPill></div><div className="version-diff"><header><span>配置差异</span><small>- v4</small><small>+ v5</small></header><div><span>交付前检查</span><del>核对证据完整性</del><ins>核对证据完整性，并检查本地语言免责声明</ins></div><div><span>验收失败处理</span><del>返回负责人重新规划</del><ins>提取验收意见，限定受影响的专业 ActorRun 重跑</ins></div></div><div className="regression-list"><span>发布前验证</span>{["历史任务质量基线", "高风险审批策略不扩大", "Wiki 权限隔离", "预算上限保持不变"].map(item => <div key={item}><PIcon name="check"></PIcon><strong>{item}</strong><StatusPill dot={false} tone="success">通过</StatusPill></div>)}</div><div className="feedback-note"><PIcon name="info"></PIcon><p>已运行中的 ActorRun 继续使用 v4，避免执行中配置漂移。</p></div></div></Modal>;
}

Object.assign(window, {
  PrototypeButton, IconButton, Avatar, StatusPill, Toast, Modal, ConfirmDialog,
  SurfaceSwitcher, GlobalHeader, ExperienceBoundaryBar, StageRail, ProgressBar, SectionTitle,
  StartRunForm, ContextForm, NewEmployeeForm, TeamEditor,
  FeedbackForm, KnowledgeSourceForm, ImprovementReviewModal
});
