// Employee Tasks — task setup, samples, schedules, and results.
(function () {
  const { useState, useEffect } = React;
  const h = React.createElement;
  window.Screens = window.Screens || {};
  const { Card, CardHead, Badge, RiskBadge, Button, KPI, Avatar, PageHeader, Segmented, Toggle, ProgressBar, EmptyHint, FutureStep, Modal, Section, Icon } = window;
  const { RoleIcon, RoleDot, InlineIcon, StatusIcon, Chip, levelChip, caveatLine, Seg3, AUDIT_TONE } = window;

  // English short labels per office id (role.short is 繁中; mirror dashboard rosters / SHORT_EN).
	  const SHORT_EN = { clerk: "Admin Assistant", cs: "Customer Support Assistant", sales: "Sales Assistant", social: "Marketing Assistant", acct: "Accounting Assistant" };
	  const shortEn = (id) => SHORT_EN[id] || "Assistant";
	  const roleName = (role) => window.officeRoleName ? window.officeRoleName(role, role.id) : shortEn(role.id);
	  const roleMission = (role) => window.officeRoleMission ? window.officeRoleMission(role, role.id) : role.tagline;
	  const displayTime = (value) => window.officeTimeDisplay ? window.officeTimeDisplay(value) : value;
	  const taskCopy = (role, skill, field) => window.skillCopy ? window.skillCopy(role.id, skill, field) : (skill && (skill[field] || skill.name)) || "";

	  // C3: 繁中 audit actions counted for quality coverage; the heuristic is 100%-of-actions, not certified.
	  const QA_ACTIONS = ["核准", "自動執行", "修改後核准", "退回", "政策封鎖", "撤回", "聘用請求", "核准聘用", "退回聘用", "建立任務", "建立工作單", "完成工作單", "重開工作單", "指派工具", "移除工具", "上傳檔案", "歸檔檔案", "發布設定", "還原設定", "更新設定", "更新公司", "邀請用戶", "更新用戶", "更新用戶權限", "重寄邀請", "停用用戶", "恢復用戶", "移除用戶"];
	  // C3: 繁中 audit action -> English display label (i18n re-maps to 已核准/… via the shared dict).
	  const ACTION_EN = { "核准": "Approved", "自動執行": "Repeat work", "修改後核准": "Approved with edits", "退回": "Returned", "政策封鎖": "Rule blocked", "撤回": "Undone", "聘用請求": "Hire requested", "核准聘用": "Hire approved", "退回聘用": "Hire declined", "建立任務": "Task created", "建立工作單": "Task created", "完成工作單": "Task completed", "重開工作單": "Task reopened", "指派工具": "App assigned", "移除工具": "App removed", "上傳檔案": "File added", "歸檔檔案": "File saved", "發布設定": "Settings applied", "還原設定": "Settings undone", "更新設定": "Settings updated", "更新公司": "Company updated", "邀請用戶": "Team member invited", "更新用戶": "Team member updated", "更新用戶權限": "Team member access changed", "重寄邀請": "Invite resent", "停用用戶": "Team member suspended", "恢復用戶": "Team member reactivated", "移除用戶": "Team member removed" };
	  const EVAL_SEV_TONE = { Low: "blue", Medium: "amber", High: "red" };

	  function failedCaseRoleId(item, office) {
	    const roleById = (office && office.roleById) || {};
	    if (item && item.roleId && roleById[item.roleId]) return item.roleId;
	    const text = [item && item.set, item && item.input, item && item.expected, item && item.got, item && item.future].join(" ").toLowerCase();
	    if (/customer|support|refund|warranty|damaged|kb|knowledge/.test(text) && roleById.cs) return "cs";
	    if (/proposal|quote|price|delivery|sales/.test(text) && roleById.sales) return "sales";
	    if (/brand|tone|social|community|post/.test(text) && roleById.social) return "social";
	    if (/invoice|receipt|bank|finance|account/.test(text) && roleById.acct) return "acct";
	    if (roleById.clerk) return "clerk";
	    return (((office && office.roles) || []).find((r) => r.hired) || ((office && office.roles) || [])[0] || {}).id || "clerk";
	  }
	  function trainingSetupRoute(office, arg) {
	    const roleById = (office && office.roleById) || {};
	    const raw = String(arg || "");
	    if (raw.indexOf("quality/") === 0) {
	      const roleId = raw.slice("quality/".length);
	      return { tab: "quality", roleId: roleById[roleId] ? roleId : "clerk" };
	    }
	    return { tab: "setup", roleId: roleById[raw] ? raw : "clerk" };
	  }

  function RoutineModal({ role, skill, ctx, onClose }) {
    const [d, setD] = useState("Mon");
    const [t, setT] = useState("09:00");
    const DAYS = [["Mon", "週一"], ["Tue", "週二"], ["Wed", "週三"], ["Thu", "週四"], ["Fri", "週五"]];
    const DAY_EN = { Mon: "Monday", Tue: "Tuesday", Wed: "Wednesday", Thu: "Thursday", Fri: "Friday" };
    const TIMES = ["08:00", "09:00", "12:00", "17:00", "18:00"];
    return h(Modal, {
      title: "Set schedule", icon: "clock", width: 520, onClose,
	      sub: "Choose a day and time.",
      "data-training-modal": "routine", "data-training-role-id": role.id, "data-training-skill-id": skill.id,
      footer: [
        skill.routine && h(Button, { key: "off", "data-training-action": "routine-clear", "data-training-role-id": role.id, "data-training-skill-id": skill.id, onClick: () => {
          ctx.setRoutine(role.id, skill.id, undefined); onClose(); // toast comes from the mutator
        } }, "Clear schedule"),
        h(Button, { key: "c", "data-training-action": "routine-cancel", "data-training-role-id": role.id, "data-training-skill-id": skill.id, onClick: onClose }, "Close"),
        h(Button, { key: "ok", variant: "primary", "data-training-action": "routine-confirm", "data-training-role-id": role.id, "data-training-skill-id": skill.id, onClick: () => {
          ctx.setRoutine(role.id, skill.id, "Every " + DAY_EN[d] + " " + t + " · " + taskCopy(role, skill, "name")); onClose(); // toast comes from the mutator
        } }, "Save schedule"),
      ],
    },
      h("div", { className: "row gap10 wrap", style: { marginBottom: 12 } },
        h(Segmented, { options: DAYS.map((x) => ({ value: x[0], label: x[0], attrs: { "data-training-routine-day": x[0], "data-training-routine-day-active": d === x[0] ? "true" : "false" } })), value: d, onChange: setD }),
        h("select", { value: t, onChange: (e) => setT(e.target.value), "data-training-routine-time": "true",
          style: { border: "1px solid var(--border)", borderRadius: 9, padding: "7px 10px", fontFamily: "var(--mono)", fontSize: 13, background: "var(--bg-2)", color: "var(--text)" } },
          TIMES.map((x) => h("option", { key: x, value: x }, x)))),
	      h("p", { style: { fontSize: 13, lineHeight: 1.6, color: "var(--text-dim)" } },
	        "Results wait in My Desk."),
      skill.routine && h("p", { style: { fontSize: 12.5, color: "var(--text-faint)" } }, h("span", null, "Current schedule: "), h("span", null, skill.routine)));
  }

  function AutonomyModal({ role, skill, ctx, onClose }) {
    const [demoteStep, setDemoteStep] = useState(false);
    const okRate = 100 - skill.edited - skill.back;
    const criteria = [
      { label: "Used at least 30 times", ok: skill.uses >= 30 },
      { label: "Returned 5% or less", ok: skill.back <= 5 },
      { label: "Approved unchanged 90% or more", ok: okRate >= 90 },
      { label: "No high-risk issues", ok: true },
    ];
    const allOk = criteria.every((c) => c.ok);
    const failed = criteria.filter((c) => !c.ok).map((c) => c.label);
    return h(Modal, {
      title: "Repeat-work settings", icon: "shield", width: 560, onClose,
      sub: "You can turn repeat work off anytime.",
      "data-training-modal": "autonomy", "data-training-role-id": role.id, "data-training-skill-id": skill.id, "data-training-autonomy-confirming": demoteStep ? "true" : "false",
      footer: [
        h(Button, { key: "c", "data-training-action": "autonomy-cancel", "data-training-role-id": role.id, "data-training-skill-id": skill.id, onClick: onClose }, "Close"),
        skill.level === 1
          ? h(Button, { key: "up", variant: "primary", "data-training-action": "autonomy-confirm-promote", "data-training-role-id": role.id, "data-training-skill-id": skill.id, disabled: !allOk || !ctx.can("promoteL2"),
              title: !ctx.can("promoteL2") ? ctx.denyReason("promoteL2") : allOk ? "" : "Not yet eligible: " + failed.join(", "),
              onClick: () => { ctx.setSkill(role.id, skill.id, { level: 2, suggest: false });
                ctx.showToast("Low-risk repeat work allowed"); onClose(); } },
              "Allow low-risk repeat work")
          : h(Button, { key: "down", variant: "primary", "data-training-action": demoteStep ? "autonomy-confirm-revoke" : "autonomy-revoke", "data-training-role-id": role.id, "data-training-skill-id": skill.id, disabled: !ctx.can("promoteL2"),
              title: ctx.can("promoteL2") ? "" : ctx.denyReason("promoteL2"),
              onClick: () => { if (!demoteStep) { setDemoteStep(true); return; }
                ctx.setSkill(role.id, skill.id, { level: 1 });
                ctx.showToast("Approval is required again"); onClose(); } },
	              demoteStep ? "Require approval?" : "Require approval again"),
      ],
    },
      h("div", { style: { marginBottom: 10 } }, levelChip(skill.level)),
      criteria.map((c, i) => h("div", { key: i, className: "row gap8", style: { padding: "6px 0", fontSize: 13.5, borderBottom: "1px solid var(--border)" } },
        h(StatusIcon, { ok: c.ok }), c.label)),
      skill.level === 1 && h("p", { style: { fontSize: 13, lineHeight: 1.65, color: "var(--text-dim)", marginTop: 10 } },
        "Low-risk work waits 10 minutes before sending. Two returns in 7 days turn repeat work off."));
  }

	  function DemoModal({ role, skill, ctx, onClose, onRoutine }) {
	    const [phase, setPhase] = useState("idle");
	    const [step, setStep] = useState(0);
	    const [demoRun, setDemoRun] = useState(null);
	    const steps = skill.demo.steps;
    useEffect(() => {
      if (phase !== "run") return;
      const t = setTimeout(() => { if (step >= steps.length - 1) setPhase("done"); else setStep(step + 1); }, 780);
      return () => clearTimeout(t);
	    }, [phase, step]);
	    const hired = !!role.hired;
	    const canRunDemo = ctx.can("brief");
	    function startSampleRun() {
	      if (!canRunDemo) { if (ctx.showToast) ctx.showToast(ctx.denyReason("brief")); return; }
	      const result = ctx.runDemo ? ctx.runDemo(role.id, skill.id) : null;
	      if (result) setDemoRun(result);
	      setStep(0);
	      setPhase("run");
	    }
	    function openDemoApproval() {
	      if (demoRun && demoRun.approvalId && ctx.setHighlight) ctx.setHighlight(demoRun.approvalId);
	      onClose();
	      ctx.openPage("approvals");
	    }
	    function hireFromDemo() {
	      if (ctx.can("hire")) {
	        ctx.hire(role.id);
	        ctx.showToast(shortEn(role.id) + " added; the sample draft is still in My Desk");
	        onClose();
	        return;
	      }
	      if (ctx.can("requestHire")) {
	        onClose();
	        ctx.requestHire(role.id);
	        return;
	      }
	      if (ctx.showToast) ctx.showToast(ctx.denyReason("requestHire"));
	    }
	    return h(Modal, {
	      title: "Try sample", icon: "play", width: 880, onClose,
      sub: "Uses sample data only. Nothing is sent.",
      "data-training-modal": "demo", "data-training-role-id": role.id, "data-training-skill-id": skill.id,
      footer: [
        h("div", { key: "l", className: "row gap8 grow wrap" },
          levelChip(skill.level),
          skill.uses > 0 && h(Chip, { tone: "gray" }, h("span", null, "Used "), h("span", null, skill.uses + "× · returned " + skill.back + "%"))),
	        phase !== "done" && h(Button, { key: "run", variant: "primary", icon: "play", "data-training-action": "demo-run", "data-training-role-id": role.id, "data-training-skill-id": skill.id, disabled: phase === "run" || !canRunDemo, title: canRunDemo ? "" : ctx.denyReason("brief"), onClick: startSampleRun },
	          phase === "run" ? "Trying sample…" : "Try sample"),
	        phase === "done" && demoRun && h(Button, { key: "approval", iconRight: "arrowRight", "data-training-action": "demo-open-approval", "data-training-role-id": role.id, "data-training-skill-id": skill.id, onClick: openDemoApproval }, "Open in My Desk"),
	        phase === "done" && (hired
	          ? (skill.enabled
	            ? h(Button, { key: "rt", icon: "clock", "data-training-action": "set-routine", "data-training-target": "routine-open", "data-training-role-id": role.id, "data-training-skill-id": skill.id, disabled: !ctx.can("promoteL2"), title: ctx.can("promoteL2") ? "" : ctx.denyReason("promoteL2"), onClick: () => onRoutine(skill) }, "Set schedule")
	            : h(Button, { key: "en", variant: "primary", "data-training-action": "enable", "data-training-role-id": role.id, "data-training-skill-id": skill.id, disabled: !ctx.can("superviseRole"), title: ctx.can("superviseRole") ? "" : ctx.denyReason("superviseRole"), onClick: () => { ctx.setSkill(role.id, skill.id, { enabled: true }); ctx.showToast("Task enabled"); onClose(); } }, "Enable task"))
	          : h(Button, { key: "hire", variant: "primary", disabled: !ctx.can("hire") && !ctx.can("requestHire"), title: ctx.can("hire") || ctx.can("requestHire") ? "" : ctx.denyReason("requestHire"), onClick: hireFromDemo }, (ctx.can("hire") ? "Add " : "Request · ") + shortEn(role.id) + " — 14 days free")),
	        phase === "done" && h(Button, { key: "again", "data-training-action": "demo-run", "data-training-role-id": role.id, "data-training-skill-id": skill.id, disabled: !canRunDemo, title: canRunDemo ? "" : ctx.denyReason("brief"), onClick: startSampleRun }, "Try again"),
	      ],
    },
      h("div", { className: "demo-grid" },
        h("div", { className: "demo-pane" },
          h("div", { className: "demo-pane-t" }, h("span", null, "You provide → "), h("b", null, taskCopy(role, skill, "give"))),
          h("div", { className: "demo-doc in" }, h("div", { className: "demo-doc-t" }, skill.demo.inTitle),
            skill.demo.inLines.map((l, i) => h("p", { key: i }, l)))),
        h("div", { className: "demo-arrow" }, h(Icon, { name: phase === "run" ? "clock" : "arrowRight", size: 19 })),
        h("div", { className: "demo-pane" },
          h("div", { className: "demo-pane-t" }, h("span", null, "You get → "), h("b", null, taskCopy(role, skill, "result"))),
          phase === "idle" && h("div", { className: "demo-doc placeholder" },
            h("p", null, "Select “Try sample” to see a result."),
            h("p", { style: { color: "var(--text-faint)" } }, "Only sample data is used.")),
          phase === "run" && h("div", { className: "demo-doc running" },
            steps.map((s, i) => h("div", { key: i, className: "demo-step" + (i < step ? " done" : i === step ? " now" : "") },
              h("span", { className: "demo-step-i" }, i < step ? h(Icon, { name: "check", size: 11 }) : i === step ? "⋯" : "·"), s))),
          phase === "done" && h("div", { className: "demo-doc out" }, h("div", { className: "demo-doc-t" }, skill.demo.outTitle),
            skill.demo.outLines.map((l, i) => h("p", { key: i, className: "fade-line", style: { animationDelay: (i * 0.14) + "s" } }, l))))),
      caveatLine(taskCopy(role, skill, "limit")));
  }

  function SkillCard({ role, skill, ctx, onDemo, onAutonomy, onRoutine }) {
    const hired = !!role.hired;
    const okRate = 100 - skill.edited - skill.back;
    const canSet = ctx.can("superviseRole");
    return h(Card, { className: "skill-card", "data-training-skill-card": skill.id, "data-training-skill-id": skill.id, "data-training-role-id": role.id, style: { "--accent": role.color } },
      h("div", { className: "row gap8", style: { marginBottom: 8 } },
        h(window.Face, { role: role, size: 22, variant: "head" }), h("b", { style: { fontSize: 14.5 } }, taskCopy(role, skill, "name")), h("span", { className: "grow" }),
        skill.routine && h(Button, { variant: "ghost", sm: true, icon: "clock", title: skill.routine, ariaLabel: "Open schedule", "data-training-action": "routine-open-existing", "data-training-target": "routine-open-existing", "data-training-role-id": role.id, "data-training-skill-id": skill.id, "data-training-routine": skill.routine, disabled: !hired, onClick: hired ? () => onRoutine(skill) : undefined })),
      h("div", { className: "sk-io" },
        h("div", null, h("span", { className: "sk-l" }, "You provide"), taskCopy(role, skill, "give")),
        h("div", null, h("span", { className: "sk-l out" }, "You get"), taskCopy(role, skill, "result"))),
      h("div", { className: "row gap6 wrap", style: { margin: "10px 0 6px" } },
        levelChip(skill.level),
        skill.uses > 0 ? h(Chip, { tone: "gray" }, h("span", null, skill.uses + "× · returned " + skill.back + "%")) : h(Chip, { tone: "gray" }, "Not enabled"),
        skill.noSource != null && h(Chip, { tone: "amber" }, h("span", null, "Stopped: file missing "), h("span", null, skill.noSource + "×"))),
      skill.uses > 0 && h("div", { style: { marginBottom: 8 } }, h(Seg3, { ok: okRate, ed: skill.edited, bk: skill.back })),
      h("div", { className: "row gap8 wrap" },
        h(Button, { variant: "primary", sm: true, icon: "play", "data-training-action": "run-demo", "data-training-target": "demo-open", "data-training-skill-id": skill.id, "data-training-role-id": role.id, onClick: onDemo, style: { flex: 1, justifyContent: "center" } }, "Try sample"),
        hired && (skill.enabled
          ? h(Chip, { tone: "mint", style: { alignSelf: "center" } }, h(Icon, { name: "check", size: 12 }), "Enabled")
          : h(Button, { sm: true, "data-training-action": "enable", "data-training-skill-id": skill.id, "data-training-role-id": role.id, disabled: !canSet, title: canSet ? "" : ctx.denyReason("superviseRole"), onClick: () => { ctx.setSkill(role.id, skill.id, { enabled: true }); ctx.showToast("Task enabled"); } }, "Enable")),
        hired && h(Button, { variant: "ghost", sm: true, "data-training-action": "autonomy", "data-training-target": "autonomy-open", "data-training-skill-id": skill.id, "data-training-role-id": role.id, onClick: () => onAutonomy(skill) }, "Repeat settings"),
        hired && skill.enabled && !skill.routine && h(Button, { variant: "ghost", sm: true, icon: "clock", "data-training-action": "set-routine", "data-training-target": "routine-open", "data-training-skill-id": skill.id, "data-training-role-id": role.id, disabled: !ctx.can("promoteL2"), title: ctx.can("promoteL2") ? "" : ctx.denyReason("promoteL2"), onClick: () => onRoutine(skill) }, "Set schedule")),
      caveatLine(taskCopy(role, skill, "limit")));
  }

  function GuideRow({ entry, index, roleId, onRemove, canDelete, denyDelete }) {
    const [confirm, setConfirm] = useState(false);
    const skillId = entry.skillId || "";
    return h("div", { className: "guide-row", "data-training-guidance-row": "true", "data-training-role-id": roleId, "data-training-guidance-index": index, "data-training-guidance-skill-id": skillId, "data-training-guidance-confirming": confirm ? "true" : "false" },
      h("span", { className: "guide-date" }, entry.date),
      h("div", { className: "grow" }, entry.text, h("div", { className: "guide-from" }, h("span", null, "From: "), h("span", null, entry.from))),
      h(Chip, { tone: "gray" }, h("span", null, "Applied "), h("span", null, entry.hits + "×")),
      h(Button, { variant: "ghost", sm: true, "data-training-action": confirm ? "guidance-confirm-delete" : "guidance-delete", "data-training-role-id": roleId, "data-training-guidance-index": index, "data-training-guidance-skill-id": skillId, "data-training-guidance-confirming": confirm ? "true" : "false", "data-training-rbac": "rejectWithRule", disabled: !canDelete, title: canDelete ? "" : denyDelete, onClick: () => { if (confirm) onRemove(); else setConfirm(true); } }, confirm ? "Confirm delete?" : "Delete"));
  }

  function SkillTable({ role, ctx, onDemo, onAutonomy, onRoutine }) {
    const hired = !!role.hired;
    const canRoutine = ctx.can("promoteL2");
    const canSet = ctx.can("superviseRole"); // enable/disable a skill is a supervision action (owner+manager)
    return h("div", { style: { overflowX: "auto" }, className: "glass", },
      h("table", { className: "tbl" },
        h("thead", null, h("tr", null,
          h("th", null, "Task"),
          h("th", null, "Approval"),
          h("th", null, "Status"),
          h("th", { style: { textAlign: "right" } }, "Uses"),
          h("th", { style: { textAlign: "right" } }, "Edited"),
          h("th", { style: { textAlign: "right" } }, "Sent back"),
          h("th", null, "Schedule"),
          h("th", { style: { textAlign: "right" } }, ""))),
        h("tbody", null, role.skills.map((s) => h("tr", { key: s.id, "data-training-skill-row": s.id, "data-training-skill-id": s.id, "data-training-role-id": role.id },
          h("td", null, h("div", { className: "row gap6", style: { alignItems: "center" } }, h(window.Face, { role: role, size: 22, variant: "head" }), h("b", { style: { fontSize: 13 } }, h("span", null, taskCopy(role, s, "name"))))),
          h("td", null, h(Chip, { tone: s.level === 2 ? "mint" : "purple", title: s.level === 2 ? "Low-risk repeat work · 10-minute undo" : "Drafts need approval" }, s.level === 2 ? "Low-risk repeats" : "Approval needed")),
          h("td", null, hired
            ? (canSet
                ? h("div", { className: "row gap6", style: { alignItems: "center" } },
                    h(Toggle, { blue: true, on: !!s.enabled, "data-training-action": s.enabled ? "disable" : "enable", "data-training-target": "skill-enabled-toggle", "data-training-skill-id": s.id, "data-training-role-id": role.id, onChange: (v) => { ctx.setSkill(role.id, s.id, { enabled: v }); ctx.showToast(v ? "Task enabled" : "Task disabled"); } }),
                    h("span", { style: { fontSize: 12, color: "var(--text-faint)" } }, s.enabled ? "On" : "Off"))
                : h(Chip, { tone: s.enabled ? "mint" : "gray", title: ctx.denyReason("superviseRole") }, s.enabled ? "On" : "Off"))
            : h(Chip, { tone: "gray" }, "Not hired")),
          h("td", { className: "mono", style: { textAlign: "right" } }, s.uses > 0 ? "" + s.uses : "—"),
          h("td", { className: "mono", style: { textAlign: "right" } }, s.uses > 0 ? s.edited + "%" : "—"),
          h("td", { className: "mono", style: { textAlign: "right" } }, s.uses > 0 ? s.back + "%" : "—"),
          h("td", null, s.routine
            ? h(Button, { variant: "ghost", sm: true, icon: "clock", title: s.routine, ariaLabel: "Open schedule", "data-training-action": "routine-open-existing", "data-training-target": "routine-open-existing", "data-training-skill-id": s.id, "data-training-role-id": role.id, "data-training-routine": s.routine, disabled: !hired, onClick: hired ? () => onRoutine(s) : undefined }, s.routine)
            : (hired && s.enabled
                ? h(Button, { variant: "ghost", sm: true, icon: "clock", "data-training-action": "set-routine", "data-training-target": "routine-open", "data-training-skill-id": s.id, "data-training-role-id": role.id, disabled: !canRoutine, title: canRoutine ? "" : ctx.denyReason("promoteL2"), onClick: () => onRoutine(s) }, "Set schedule")
                : h("span", { style: { color: "var(--text-faint)", fontSize: 12 } }, "—"))),
          h("td", { style: { textAlign: "right" } }, h("div", { className: "row gap6 wrap", style: { justifyContent: "flex-end" } },
            h(Button, { variant: "ghost", sm: true, icon: "play", "data-training-action": "run-demo", "data-training-target": "demo-open", "data-training-skill-id": s.id, "data-training-role-id": role.id, onClick: () => onDemo(s) }, "Try sample"),
            hired && h(Button, { variant: "ghost", sm: true, "data-training-action": "autonomy", "data-training-target": "autonomy-open", "data-training-skill-id": s.id, "data-training-role-id": role.id, onClick: () => onAutonomy(s) }, "Repeat settings"))))))));
  }

  function GuidanceCard({ role, ctx }) {
    const [open, setOpen] = useState(true);
    return h(Card, { style: { marginBottom: 18, padding: 18 } },
      h("div", { className: "row gap8", style: { cursor: "pointer" }, onClick: () => setOpen((v) => !v) },
        h("b", { className: "row gap8" }, h(Icon, { name: "clipboard", size: 15 }), h("span", null, "Working rules ("), h("span", null, "" + role.guidance.length), h("span", null, ")")),
        h("span", { className: "grow" }), h("span", { style: { color: "var(--text-faint)" } }, h(Icon, { name: open ? "chevDown" : "chevRight", size: 14 }))),
      open && (role.guidance.length === 0
        ? h("p", { style: { fontSize: 13, marginTop: 10, color: "var(--text-faint)" } }, "No rules yet. Return notes are saved here.")
        : h("div", { style: { marginTop: 6 } }, role.guidance.map((g, idx) => h(GuideRow, { key: g.date + "-" + idx, entry: g, index: idx, roleId: role.id, canDelete: ctx.can("rejectWithRule"), denyDelete: ctx.denyReason("rejectWithRule"), onRemove: () => ctx.removeGuidance(role.id, idx) })))));
  }

  function KnowledgeGapCard({ role, ctx }) {
    const gapped = role.skills.filter((s) => s.gapTopics && s.gapTopics.length);
    if (!gapped.length) return null;
    const total = gapped.reduce((n, s) => n + s.gapTopics.reduce((m, g) => m + (g.count || 0), 0), 0);
    return h(Card, { style: { marginBottom: 18, padding: 18 } },
      h("b", { className: "row gap8", style: { marginBottom: 6 } }, h(Icon, { name: "folder", size: 15 }), h("span", null, "Stopped because a file was missing ("), h("span", null, "" + total), h("span", null, ")")),
      h("p", { style: { fontSize: 12.5, margin: "0 0 10px", color: "var(--text-faint)" } }, "Add a matching file so the employee can answer next time."),
      gapped.map((s) => s.gapTopics.map((g, i) => h("div", { key: s.id + "-" + i, className: "gap-row", "data-training-knowledge-gap": "true", "data-training-role-id": role.id, "data-training-skill-id": s.id, "data-training-gap-topic": g.topic || "", "data-training-gap-index": String(i) },
        h("span", { className: "grow" }, g.topic),
        h(Chip, { tone: "amber" }, h("span", null, g.count + " stopped")),
        h(Button, { sm: true, icon: "upload", disabled: !ctx.can("addUpload"), title: ctx.can("addUpload") ? "" : ctx.denyReason("addUpload"), "data-training-action": "knowledge-gap-add-file", "data-training-role-id": role.id, "data-training-skill-id": s.id, "data-training-gap-topic": g.topic || "", "data-training-gap-index": String(i),
          onClick: () => ctx.stageMissingSource({ source: "training", roleId: role.id, skillId: s.id, skill: s.name, topic: g.topic }) }, "Add a file")))));
  }

	  function WorkHistoryCard({ role, ctx }) {
	    const rows = ctx.office.auditLog.filter((e) => e.roleId === role.id).slice(0, 8);
	    const label = roleName(role);
	    return h(Card, { style: { marginBottom: 18, padding: 18 } },
	      h("b", { className: "row gap8", style: { marginBottom: 8 } }, h(Icon, { name: "clipboard", size: 15 }), h("span", null, "Recent approvals · "), h("span", null, label)),
	      rows.length === 0
	        ? h("p", { style: { fontSize: 13, color: "var(--text-faint)" } }, "No approval history yet.")
        : h("div", null, rows.map((e) => h("div", { key: e.id, className: "row gap8", style: { padding: "8px 0", borderBottom: "1px solid var(--border)" } },
          h("span", { className: "mono", style: { fontSize: 12, color: "var(--text-faint)" } }, displayTime(e.time)),
          h(Chip, { tone: AUDIT_TONE[e.action] || "gray" }, ACTION_EN[e.action] || e.action),  // C3: 繁中 logic, English display
          h("b", { style: { fontSize: 13 } }, e.title)))),
	      h("p", { style: { fontSize: 11.5, marginTop: 8, color: "var(--text-faint)" } }, "Includes returned and undone work."));
  }

  // ---- Quality & Results tab (the former evals screen, plain owner language) ----
	  function QualityTab({ ctx, onOpenSetup }) {
	    const office = ctx.office;
	    const acts = office.auditLog.filter((e) => QA_ACTIONS.indexOf(e.action) >= 0);  // C3: count 繁中 actions
	    const reviewed = acts.length;
	    const failed = acts.filter((e) => e.action === "退回" || e.action === "撤回").length;
	    const coverage = reviewed ? 100 : 100; // 100%-of-actions QA heuristic (not certified)
	    const passRate = reviewed ? Math.round(((reviewed - failed) / reviewed) * 100) : 100;
	    const flagged = acts.filter((e) => e.action === "退回" || e.action === "撤回" || e.action === "政策封鎖" || e.action === "退回聘用").slice(0, 12);
	    const failedCases = (office.failedCases || []).slice(0, 12);
	    const qaReviewed = flagged.filter((e) => e.qaReviewedAt).length + failedCases.filter((f) => f.qaReviewedAt).length;
	    const fixCount = flagged.filter((e) => e.qaFixWorkOrderId).length + failedCases.filter((f) => f.qaFixWorkOrderId).length;
	    const findingCount = flagged.length + failedCases.length;
	    return h("div", { "data-training-quality-root": "true", "data-training-quality-reviewed-count": String(qaReviewed), "data-training-quality-flagged-count": String(findingCount), "data-training-quality-audit-finding-count": String(flagged.length), "data-training-quality-eval-case-count": String(failedCases.length), "data-training-quality-fix-count": String(fixCount) },
	      h("div", { style: { display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(160px,1fr))", gap: 12, marginBottom: 18 } },
	        [["Actions reviewed", "" + reviewed, "blue"], ["Actions checked", coverage + "%", "green"], ["Accepted rate", passRate + "%", "green"], ["Issues", "" + failedCases.length, failedCases.length ? "amber" : "green"]].map((m, i) =>
	          h(Card, { key: i, style: { padding: 15 } },
	            h("div", { className: "mono", style: { fontSize: 24, fontWeight: 700, color: "var(--" + m[2] + ")" } }, m[1]),
	            h("div", { style: { fontSize: 11.5, color: "var(--text-dim)", marginTop: 5 } }, m[0])))),
	      h(Card, { style: { padding: 18, marginBottom: 18 } },
	        h("b", null, "How it's doing"),
	        h("p", { style: { fontSize: 13, color: "var(--text-dim)", lineHeight: 1.6, marginTop: 8 } },
	          "Check issues stay here until reviewed or turned into a follow-up task."),
	        h("div", { style: { marginTop: 12 } }, h(ProgressBar, { value: passRate, tone: passRate >= 90 ? "green" : "amber", height: 6 }))),
	      h(Card, { style: { padding: 18, marginBottom: 18 } },
	        h("b", null, "Decisions to review"),
	        h("p", { style: { fontSize: 12.5, color: "var(--text-faint)", marginTop: 6, lineHeight: 1.5 } },
	          h("span", null, flagged.filter((e) => e.qaReviewedAt).length + "/" + flagged.length + " reviewed"), h("span", null, " · "), h("span", null, flagged.filter((e) => e.qaFixWorkOrderId).length + " "), h("span", null, "Follow-up tasks")),
	        flagged.length === 0
	          ? h("p", { style: { fontSize: 13, color: "var(--text-faint)", marginTop: 10 } }, "No flagged decisions need follow-up.")
	          : h("div", { style: { marginTop: 10 } }, flagged.map((e) =>
	            h("div", { key: e.id, className: "quality-row row gap8 wrap" + (ctx.highlight === e.id ? " onboard-hl" : ""), "data-training-quality-finding-id": e.id, "data-training-quality-action": e.action || "", "data-training-quality-role-id": e.roleId || "", "data-training-quality-reviewed": e.qaReviewedAt ? "true" : "false", "data-training-quality-fix-workorder-id": e.qaFixWorkOrderId || "", style: { padding: "9px 0", borderBottom: "1px solid var(--border)", fontSize: 13 } },
              h(Chip, { tone: AUDIT_TONE[e.action] || (e.action === "退回" ? "red" : "gray") }, ACTION_EN[e.action] || e.action),
              h("b", { className: "grow", style: { minWidth: 180 } }, e.title),
              e.qaReviewedAt
                ? h(Chip, { tone: "green", title: "Reviewed by " + (e.qaReviewedBy || "team") + " · " + e.qaReviewedAt }, "Reviewed")
                : h(Chip, { tone: "amber" }, "Needs review"),
	              h(Button, { sm: true, variant: "ghost", "data-training-action": "quality-review", "data-training-quality-finding-id": e.id, disabled: !ctx.can("superviseRole") || !!e.qaReviewedAt,
	                title: !ctx.can("superviseRole") ? ctx.denyReason("superviseRole") : e.qaReviewedAt ? "Already reviewed" : "Mark this decision reviewed",
                onClick: () => ctx.reviewQaEvent(e.id) }, e.qaReviewedAt ? "Reviewed" : "Mark reviewed"),
	              h(Button, { sm: true, variant: e.qaFixWorkOrderId ? "ghost" : "primary", iconRight: "arrowRight", "data-training-action": e.qaFixWorkOrderId ? "quality-open-fix" : "quality-create-fix", "data-training-quality-finding-id": e.id, "data-training-quality-fix-workorder-id": e.qaFixWorkOrderId || "",
	                disabled: !ctx.can("workOrder"), title: ctx.can("workOrder") ? "" : ctx.denyReason("workOrder"),
	                onClick: () => e.qaFixWorkOrderId ? ctx.openPage("workorder", e.qaFixWorkOrderId) : ctx.createQaFixWorkOrder(e.id) }, e.qaFixWorkOrderId ? "Open task" : "Create follow-up task"),
	              e.roleId && h(Button, { sm: true, variant: "ghost", iconRight: "arrowRight", "data-training-action": "quality-open-setup", "data-training-quality-finding-id": e.id, "data-training-role-id": e.roleId, onClick: () => onOpenSetup ? onOpenSetup(e.roleId) : ctx.openPage("training-setup", e.roleId) }, "Open setup"))))),
	      h(Card, { style: { padding: 18 } },
	        h("b", null, "Check issues"),
	        h("p", { style: { fontSize: 12.5, color: "var(--text-faint)", marginTop: 6, lineHeight: 1.5 } },
	          h("span", null, failedCases.filter((f) => f.qaReviewedAt).length + "/" + failedCases.length + " reviewed"), h("span", null, " · "), h("span", null, failedCases.filter((f) => f.qaFixWorkOrderId).length + " "), h("span", null, "Follow-up tasks")),
	        failedCases.length === 0
	          ? h("p", { style: { fontSize: 13, color: "var(--text-faint)", marginTop: 10 } }, "No check issues need follow-up.")
	          : h("div", { style: { marginTop: 10 } }, failedCases.map((f) => {
	            const rid = failedCaseRoleId(f, office);
	            const sev = f.sev || "Low";
	            const title = f.id + " · " + (f.set || "Check case");
	            return h("div", { key: f.id, className: "quality-row row gap8 wrap" + (ctx.highlight === f.id ? " onboard-hl" : ""), "data-training-quality-eval-case-id": f.id, "data-training-quality-source": "failed-case", "data-training-quality-role-id": rid || "", "data-training-quality-reviewed": f.qaReviewedAt ? "true" : "false", "data-training-quality-fix-workorder-id": f.qaFixWorkOrderId || "", style: { padding: "11px 0", borderBottom: "1px solid var(--border)", fontSize: 13, alignItems: "flex-start" } },
	              h(Chip, { tone: EVAL_SEV_TONE[sev] || "amber" }, sev),
	              h("div", { className: "grow", style: { minWidth: 240 } },
	                h("b", null, title),
	                h("div", { style: { marginTop: 4, color: "var(--text-dim)", fontSize: 12.5, lineHeight: 1.45 } },
		                  h("span", null, f.input || "Untitled input"), h("span", null, " · Expected: "), h("span", null, f.expected || "—"), h("span", null, " · Actual: "), h("span", null, f.got || "—"))),
	              f.qaReviewedAt
	                ? h(Chip, { tone: "green", title: "Reviewed by " + (f.qaReviewedBy || "team") + " · " + f.qaReviewedAt }, "Reviewed")
	                : h(Chip, { tone: "amber" }, "Needs review"),
	              h(Button, { sm: true, variant: "ghost", "data-training-action": "quality-eval-review", "data-training-quality-eval-case-id": f.id, disabled: !ctx.can("superviseRole") || !!f.qaReviewedAt,
	                title: !ctx.can("superviseRole") ? ctx.denyReason("superviseRole") : f.qaReviewedAt ? "Already reviewed" : "Mark this check issue reviewed",
	                onClick: () => ctx.reviewQaEvent(f.id, "failed-case") }, f.qaReviewedAt ? "Reviewed" : "Mark reviewed"),
	              h(Button, { sm: true, variant: f.qaFixWorkOrderId ? "ghost" : "primary", iconRight: "arrowRight", "data-training-action": f.qaFixWorkOrderId ? "quality-eval-open-fix" : "quality-eval-create-fix", "data-training-quality-eval-case-id": f.id, "data-training-quality-fix-workorder-id": f.qaFixWorkOrderId || "",
	                disabled: !ctx.can("workOrder"), title: ctx.can("workOrder") ? "" : ctx.denyReason("workOrder"),
	                onClick: () => f.qaFixWorkOrderId ? ctx.openPage("workorder", f.qaFixWorkOrderId) : ctx.createQaFixWorkOrder(f.id, "failed-case") }, f.qaFixWorkOrderId ? "Open task" : "Create follow-up task"),
	              rid && h(Button, { sm: true, variant: "ghost", iconRight: "arrowRight", "data-training-action": "quality-eval-open-setup", "data-training-quality-eval-case-id": f.id, "data-training-role-id": rid, onClick: () => onOpenSetup ? onOpenSetup(rid) : ctx.openPage("training-setup", rid) }, "Open setup"));
	          }))));
	  }

	  function Training({ ctx }) {
	    const initialSetupRoute = trainingSetupRoute(ctx.office, ctx.pageArg);
	    const [tab, setTab] = useState(initialSetupRoute.tab);
	    const [roleId, setRoleId] = useState(initialSetupRoute.roleId);
	    const [demo, setDemo] = useState(null);
	    const [autonomySkill, setAutonomySkill] = useState(null);
	    const [routineSkill, setRoutineSkill] = useState(null);
	    const [skillView, setSkillView] = useState("cards");
		    useEffect(() => {
		      const next = trainingSetupRoute(ctx.office, ctx.pageArg);
		      if (next.roleId && ctx.office.roleById[next.roleId]) setRoleId(next.roleId);
		      if (next.tab) setTab(next.tab);
		    }, [ctx.pageArg]);
	    const role = ctx.office.roleById[roleId];
	    const roleLabel = role ? roleName(role) : "";
	    const roleMissionText = role ? roleMission(role) : "";
	    function selectRole(id) {
	      if (!ctx.office.roleById[id]) return;
	      setRoleId(id);
	      ctx.openPage("training-setup", id);
	    }
	    function openSetupRole(id) {
	      if (!ctx.office.roleById[id]) return;
	      setRoleId(id);
	      setTab("setup");
	      ctx.openPage("training-setup", id);
	    }
	    return h("div", null,
      h(PageHeader, { eyebrow: "Employees", title: "Employee Tasks", icon: "graduation",
        sub: "Choose a task, try a sample, or set a schedule.",
        right: tab === "setup" ? h(Button, { sm: true, variant: ctx.office.sandbox ? "primary" : "", icon: ctx.office.sandbox ? "check" : "play",
          "data-training-action": "sandbox", "data-training-target": "sandbox-toggle", "data-training-sandbox-state": ctx.office.sandbox ? "on" : "off",
          disabled: !ctx.can("setSandbox"), title: ctx.can("setSandbox") ? "Sample mode keeps every draft in My Desk" : ctx.denyReason("setSandbox"),
          onClick: () => ctx.setSandbox(!ctx.office.sandbox) }, ctx.office.sandbox ? "Sample mode on" : "Use sample mode") : null }),
      h("div", { style: { marginBottom: 18 } },
        h(Segmented, { value: tab, onChange: setTab, blue: true, options: [
          { value: "setup", label: "Tasks", attrs: { "data-training-tab": "setup", "data-training-tab-active": tab === "setup" ? "true" : "false" } },
          { value: "quality", label: "Results", attrs: { "data-training-tab": "quality", "data-training-tab-active": tab === "quality" ? "true" : "false" } },
        ] })),
	      tab === "quality" ? h(QualityTab, { ctx, onOpenSetup: openSetupRole }) : h("div", null,
	        h("div", { className: "row gap8 wrap", style: { marginBottom: 18 } },
	          ctx.office.roles.map((r) => {
	            const label = roleName(r);
	            return h("button", { key: r.id, className: "role-tab" + (r.id === roleId ? " on" : ""), "data-training-role-id": r.id, "data-training-hired-tier": r.hired ? (r.hired.tier || "standard") : "none", onClick: () => selectRole(r.id),
	              style: r.id === roleId ? { borderColor: r.color, color: r.deep, background: "#fff" } : {} },
	              h(window.Face, { role: r, size: 22, variant: "head" }), h("span", null, label),
	              r.hired ? h(Chip, { tone: "mint" }, r.hired.tier === "senior" ? "Hired · Senior" : "Hired") : h(Chip, { tone: "gray" }, "Not hired"));
	          })),
	        h(Card, { "data-training-role-summary": role.id, "data-training-hired-tier": role.hired ? (role.hired.tier || "standard") : "none", style: { marginBottom: 18, padding: 18, borderLeft: "4px solid " + role.color } },
	          h("div", { className: "row gap10 wrap" },
	            h(window.Face, { role: role, size: 32, variant: "portrait" }),
	            h("div", { className: "grow" }, h("b", { style: { fontSize: 16 } }, roleLabel),
	              h("p", { style: { margin: "2px 0 0", fontSize: 13.5, color: "var(--text-faint)" } }, h("span", null, roleMissionText), h("span", null, "  "), h("span", null, role.skills.length + " tasks."))),
	            role.hired && role.hired.tier === "standard" && h(Button, { "data-training-action": "promote-senior", "data-training-target": "promote-senior", "data-training-role-id": role.id, "data-training-tier": role.hired.tier || "standard", "data-training-rbac": "promoteL2", disabled: !ctx.can("promoteL2"), title: ctx.can("promoteL2") ? "" : ctx.denyReason("promoteL2"),
	              onClick: () => { ctx.promote(role.id); ctx.showToast(roleLabel + " promoted to Senior — Files ready"); } }, "Promote to Senior")),
          role.hired && h("div", { className: "row gap8 wrap", style: { marginTop: 12 } },
            h(Icon, { name: "users", size: 14 }),
	            role.paused ? h(Chip, { tone: "amber" }, role.policyPause ? "Paused by rule" : "Paused")
              : role.forceL1 ? h(Chip, { tone: "amber" }, "Approval needed for all work") : h(Chip, { tone: "mint" }, "Active"),
            h("span", { className: "grow" }),
            h(Button, { sm: true, disabled: !ctx.can("superviseRole"), title: ctx.can("superviseRole") ? "" : ctx.denyReason("superviseRole"),
              "data-training-action": role.paused ? "resume" : "pause", "data-training-target": "pause-toggle", "data-training-role-id": role.id, "data-training-paused": role.paused ? "true" : "false",
              onClick: () => role.paused ? ctx.resumeRole(role.id) : ctx.pauseRole(role.id) }, role.paused ? "Resume employee" : "Pause employee"),
            !role.paused && h(Button, { sm: true, disabled: !ctx.can("superviseRole"), title: ctx.can("superviseRole") ? "" : ctx.denyReason("superviseRole"),
              "data-training-action": role.forceL1 ? "release-to-human" : "to-human", "data-training-target": "human-route-toggle", "data-training-role-id": role.id, "data-training-force-l1": role.forceL1 ? "true" : "false",
              onClick: () => role.forceL1 ? ctx.releaseForce(role.id) : ctx.forceToHuman(role.id) }, role.forceL1 ? "Restore repeat settings" : "Require approval"))),
        h(GuidanceCard, { role, ctx }),
        h(KnowledgeGapCard, { role, ctx }),
        h(WorkHistoryCard, { role, ctx }),
        h("div", { className: "row gap8 wrap", style: { alignItems: "center", marginBottom: 12 } },
          h("b", { style: { fontSize: 14 } }, h("span", null, "Tasks"), h("span", { style: { color: "var(--text-faint)", fontWeight: 500 } }, " (" + role.skills.length + ")")),
          h("span", { className: "grow" }),
          h(Segmented, { value: skillView, onChange: setSkillView, blue: true, options: [
            { value: "cards", label: "Cards", attrs: { "data-training-view": "cards", "data-training-view-active": skillView === "cards" ? "true" : "false" } },
            { value: "table", label: "Table", attrs: { "data-training-view": "table", "data-training-view-active": skillView === "table" ? "true" : "false" } },
          ] })),
        skillView === "table"
          ? h(SkillTable, { role, ctx, onDemo: setDemo, onAutonomy: setAutonomySkill, onRoutine: setRoutineSkill })
          : h("div", { className: "skill-grid" }, role.skills.map((s) => h(SkillCard, { key: s.id, role, skill: s, ctx,
              onDemo: () => setDemo(s), onAutonomy: setAutonomySkill, onRoutine: setRoutineSkill }))),
        demo && h(DemoModal, { role, skill: demo, ctx, onClose: () => setDemo(null), onRoutine: setRoutineSkill }),
        autonomySkill && h(AutonomyModal, { role, skill: autonomySkill, ctx, onClose: () => setAutonomySkill(null) }),
        routineSkill && h(RoutineModal, { role, skill: routineSkill, ctx, onClose: () => setRoutineSkill(null) })));
  }

  window.Screens["training-setup"] = Training;
})();
